Debian Codegraph @

gavo/resources/inputs/__system__/soda.rd

raw
1 <!-- a collection of various helpers for building datalink services.
2
3 This is a temporary location for procDefs and friends complying to
4 "DALI-style" (interval) params
5 -->
6
7 <resource resdir="__system" schema="dc">
8
9
10 <!-- ********************* generic SODA procs -->
11
12 <procDef type="descriptorGenerator" id="fromStandardPubDID">
13 <doc>A descriptor generator for SODA that builds a
14 ``ProductDescriptor`` for PubDIDs that have been built by
15 ``getStandardsPubDID``
16 (i.e., the path part of the IVOID is a tilde, with the
17 products table accref as the query part).
18
19 In case you want to add a bit of extra logic in these descriptor
20 generators, define a function ``addExtras(descriptor)`` in a setup element
21 and add attributes as necessary.
22 </doc>
23 <setup>
24 <par key="accrefPrefix" description="A prefix for the accrefs
25 the parent SODA service works on. Calls on all other accrefs
26 will be rejected with a 403 forbidden. You should always
27 include a restriction like this when you make assumptions
28 about the FITSes (e.g., what axes are available).">None</par>
29 <par key="contentQualifier" description="An identifier for the
30 sort of data #this is. Choose from
31 http://www.ivoa.net/rdf/product-type if you want to give
32 clients a hint what other client might be suitable to work with that
33 link (version 2.8+).">None</par>
34 </setup>
35 <code>
36 desc = ProductDescriptor.fromAccref(
37 pubDID,
38 getAccrefFromStandardPubDID(pubDID),
39 accrefPrefix)
40 desc.contentQualifier = contentQualifier
41
42 if "addExtras" in globals():
43 addExtras(desc)
44
45 return desc
46 </code>
47 </procDef>
48
49 <procDef type="dataFormatter" id="trivialFormatter">
50 <doc>The tivial formatter for SODA processed data -- it just
51 returns descriptor.data, which will only work it it works as a
52 nevow resource.
53
54 If you do not give any dataFormatter yourself in a SODA core,
55 this is what will be used.
56 </doc>
57 <code>
58 return descriptor.data
59 </code>
60 </procDef>
61
62
63 <!-- ********************* SODA interface to generic products -->
64
65 <procDef type="dataFunction" id="generateProduct">
66 <doc>A data function for SODA that returns a product instance.
67 You can restrict the mime type of the product requested so the
68 following filters have a good idea what to expect.
69 </doc>
70 <setup>
71 <par key="requireMimes" description="A set or sequence of mime type
72 strings; when given, the data generator will bail out with
73 ValidationError if the product mime is not among the mimes
74 given.">frozenset()</par>
75 <code>
76 from gavo.protocols import products
77 </code>
78 </setup>
79 <code>
80 if requireMimes and descriptor.mime not in requireMimes:
81 raise base.ValidationError("Document type not supported: %s"%
82 descriptor.mime, colName="PUBDID", hint="Only source documents"
83 " of the types %s are supported here."%str(requireMimes))
84
85 descriptor.data = products.getProductForRAccref(descriptor.accref)
86 </code>
87 </procDef>
88
89
90 <!-- ********************* SODA interface to SDM spectra -->
91
92 <procDef type="descriptorGenerator" id="sdm_genDesc">
93 <doc>A data function for SODA returning the product row
94 corresponding to a PubDID within an SSA table.
95
96 The descriptors generated have an ssaRow attribute containing
97 the original row in the SSA table.
98 </doc>
99 <setup imports="gavo.rscdef, gavo.rsc, gavo.svcs, gavo.protocols.ssap">
100 <par key="ssaTD" description="Full reference (like path/rdname#id)
101 to the SSA table the spectrum's PubDID can be found in."/>
102 <par key="descriptorClass" description="The SSA descriptor
103 class to use. You'll need to override this if the dc.products
104 path doesn't actually lead to the file (see
105 `custom generators &lt;#custom-product-descriptor-generators&gt;`_).
106 This class must have an fromSSAResult constructor."
107 late="True">ssap.SSADescriptor</par>
108 <par key="useAccref" description="By default, this genDesc will
109 parse the pubDID passed in and match with the accref, which in
110 DaCHS typically is indexed. This don't work if you have exotic
111 pubDID schemes; in that case, set this to False">True</par>
112 <par key="contentQualifier" description="The sort of data that #this
113 is; you might want to override this if you are abusing this
114 for time series or so (version 2.8+).">"#spectrum"</par>
115 <code>
116 ssaTD = base.resolveCrossId(ssaTD, rscdef.TableDef)
117 </code>
118 </setup>
119
120 <code>
121 with base.getTableConn() as conn:
122 # accept naked accrefs for local data, too
123 if not pubDID.startswith("ivo://"):
124 pubDID = getStandardPubDID(pubDID)
125
126 if useAccref:
127 cond, pars = "accref=%(accref)s", {
128 "accref": rscdef.getAccrefFromStandardPubDID(pubDID)}
129 else:
130 cond, pars = "ssa_pubdid=%(pubdid)s", {"pubdid": pubDID}
131
132 ssaTable = rsc.TableForDef(ssaTD, connection=conn
133 ).getTableForQuery(
134 ssaTD,
135 cond,
136 pars)
137
138 if not ssaTable.rows:
139 return DatalinkFault.NotFoundFault(pubDID,
140 "No spectrum with this pubDID known here")
141
142 desc = ssap.SSADescriptor.fromSSAResult(ssaTable)
143 # SSADescriptors.fromSSAResult clears the pubDID attribute
144 # as a service for SSA-embedded SODA blocks. So, we retrofit
145 # pubDID here.
146 desc.pubDID = pubDID
147 desc.contentQualifier = contentQualifier
148 return desc
149
150 </code>
151 </procDef>
152
153 <procDef type="dataFunction" id="sdm_genData">
154 <doc>A data function for SODA returning a spectral data model
155 compliant table that later data functions can then work on.
156 As usual for generators, it uses the implicit PUBDID argument.
157 </doc>
158 <setup>
159 <par key="builder" description="Full reference (like path/rdname#id)
160 to a data element building the SDM instance table as its
161 primary table."/>
162 <code>
163 from gavo import rscdef
164 builder = base.resolveCrossId(builder, rscdef.DataDescriptor)
165 </code>
166 </setup>
167
168 <code>
169 from gavo.protocols import sdm
170 descriptor.data = sdm.makeSDMDataForSSARow(descriptor.ssaRow, builder)
171 </code>
172 </procDef>
173
174 <STREAM id="sdm_plainfluxcalib">
175 <doc>A stream inserting a data function and its metadata generator to
176 do select flux calibrations in SDM data. This expects
177 sdm_generate (or at least parameters.data as an SDM data instance)
178 as the generating function within the SODA core.
179
180 Clients can select "RELATIVE" as FLUXCALIB, which does a
181 normalization to max(flux)=1 here. Everything else is rejected
182 right now.
183
184 This probably is more an example of how to write such a thing
185 then genuinely useful.
186 </doc>
187 <metaMaker>
188 <code>
189 supportedCalibs = set(["RELATIVE"])
190 foundCalibs = descriptor.ssaRow["ssa_fluxcalib"]
191 # this is tricky: When we have a set of matches, we may be
192 # returning calibrations we cannot serve (since we can only
193 # change to RELATIVE for now). There's nothing I can really
194 # do about this.
195 if "ssa_fluxcalib" in descriptor.limits \
196 and descriptor.limits["ssa_fluxcalib"].values:
197 supportedCalibs.update(descriptor.limits["ssa_fluxcalib"].values)
198 else:
199 if isinstance(foundCalibs, str):
200 supportedCalibs.add(foundCalibs)
201
202 yield MS(InputKey, name="FLUXCALIB", type="text",
203 multiplicity="forced-single",
204 ucd="phot.calib",
205 utype="ssa:Char.FluxAxis.Calibration",
206 description="Recalibrate the spectrum. Right now, the only"
207 " recalibration supported is max(flux)=1 ('RELATIVE').",
208 values=MS(Values, options=[
209 MS(Option, content_=val) for val in supportedCalibs]))
210 </code>
211 </metaMaker>
212
213 <dataFunction>
214 <code>
215 if not args.get("FLUXCALIB"):
216 return
217
218 from gavo.protocols import sdm
219 # table is changed in place
220 sdm.mangle_fluxcalib(descriptor.data.getPrimaryTable(),
221 args["FLUXCALIB"])
222 </code>
223 </dataFunction>
224 </STREAM>
225
226 <STREAM id="sdm_cutout">
227 <doc>A stream inserting a data function and its metaMaker to
228 do cutouts in SDM data. This expects sdm_generate (or at least
229 parameters.data as an SDM data instance) as the generating function
230 within the SODA core.
231
232 The cutout limits are always given in meters, regardless of
233 the spectrum's actual units (as in SSAP's BAND parameter).
234 </doc>
235
236 <metaMaker>
237 <code>
238 yield MS(InputKey, type="double precision[2]", xtype="interval",
239 name="BAND", multiplicity="forced-single",
240 unit="m", ucd="em.wl",
241 description="Spectral cutout interval",
242 values=MS(Values,
243 min=descriptor.limits["ssa_specstart"].min,
244 max=descriptor.limits["ssa_specend"].max))
245 </code>
246 </metaMaker>
247
248 <dataFunction>
249 <code>
250 if args.get("BAND") is None:
251 return
252
253 from gavo.protocols import sdm
254 # table is modified in place
255 sdm.mangle_cutout(
256 descriptor.data.getPrimaryTable(),
257 args["BAND"][0], args["BAND"][1])
258 </code>
259 </dataFunction>
260 </STREAM>
261
262 <STREAM id="sdm_format">
263 <doc>A formatter for SDM data, together with its input key
264 for FORMAT.
265 </doc>
266
267 <metaMaker>
268 <code>
269 formatsAvailable = {
270 "application/x-votable+xml": "VOTable, binary encoding",
271 "application/x-votable+xml;serialization=tabledata":
272 "VOTable, tabledata encoding",
273 "text/plain": "Tab separated values",
274 "text/csv": "Comma separated values",
275 "application/fits": "FITS binary table",
276 "application/x-votable+xml;serialization=TABLEDATA;version=1.6":
277 "VOTable 1.6 beta"}
278
279 yield MS(InputKey, name="FORMAT", type="text",
280 ucd="meta.code.mime",
281 utype="ssa:Access.Format",
282 multiplicity="forced-single",
283 description="MIME type of the output format",
284 values = MS(Values,
285 options = [MS(Option, title=value, content_=key)
286 for key, value in formatsAvailable.items()]))
287 </code>
288 </metaMaker>
289
290 <dataFormatter>
291 <code>
292 from gavo.protocols import sdm
293 if not descriptor.data.getPrimaryTable().rows:
294 raise soda.EmptyData()
295 return sdm.formatSDMData(descriptor.data, args["FORMAT"])
296 </code>
297 </dataFormatter>
298 </STREAM>
299
300
301 <!-- ********************* SODA interface for generic FITS
302 manipulations -->
303 <procDef type="descriptorGenerator" id="fits_genDesc">
304 <doc>A data function for SODA returning the a fits descriptor.
305
306 This has, in addition to the standard stuff, a hdr attribute containing
307 the primary header as pyfits structure.
308
309 The functionality of this is in its setup, getFITSDescriptor.
310 The intention is that customized DGs (e.g., fixing the header)
311 can use this as an original.
312 </doc>
313 <setup>
314 <par key="accrefPrefix" description="A prefix for the accrefs
315 the parent SODA service works on. Calls on all other accrefs
316 will be rejected with a 403 forbidden. You should always
317 include a restriction like this when you make assumptions
318 about the FITSes (e.g., what axes are available).">None</par>
319 <par key="descClass" description="The descriptor class to
320 use. The default is fine for vanilla FITS files, but when
321 you deliver datalinks through the product table, you'll have
322 to use DLFITSDescriptor here. Also, you can define a descriptor
323 yourself in the setup (inherit from FITSDescriptor)."
324 >FITSProductDescriptor</par>
325 <par key="qnd" description="Pass 0 or False here to not
326 use DaCHS fast header reader here. This is necessary
327 to properly handle compressed FITS images -- but it entails
328 the risk that astropy magic will mogrify the header, and
329 it may be dramatically slower in some circumstances.">True</par>
330 <par key="contentQualifier" description="An identifier for the
331 sort of data #this is. Choose from
332 http://www.ivoa.net/rdf/product-type in case the default does
333 not quite work for you (version 2.8+).">"#image"</par>
334 </setup>
335 <code>
336 desc = getFITSDescriptor(pubDID, accrefPrefix, cls=descClass, qnd=qnd)
337 desc.contentQualifier = contentQualifier
338 return desc
339 </code>
340 </procDef>
341
342
343 <procDef type="metaMaker" id="fits_makeSODAPOS">
344 <doc>A metaMaker that generates the SODA POLYGON, CIRCLE, and
345 POS parameters for a rectangular image with WCS in ICRS.
346 Needs a FITSDescriptor.
347 </doc>
348 <code>
349 yield MS(InputKey, name="POS", type="text",
350 ucd="phys.angArea;obs",
351 description="SIAv2-compatible cutout specification",
352 multiplicity="forced-single")
353 </code>
354 </procDef>
355
356 <procDef type="dataFunction" id="fits_translateSODAPOS">
357 <doc>A data function to interpret SODA POS.
358
359 This merely translates the POS parameter to the equivalent
360 POLYGON, CIRCLE, or RA/DC parameters. It thus must run before
361 these other data functions. Just run it after the initial data
362 function and be done with it.
363 </doc>
364 <setup>
365 <code>
366 from gavo.protocols import siap
367 </code>
368 </setup>
369 <code>
370 if not args["POS"]:
371 return
372 geom = siap.parseSIAP2Geometry(args["POS"])
373 args["POS"] = None
374
375 if isinstance(geom, pgsphere.SCircle):
376 if args.get("CIRCLE"):
377 raise ValidationError(
378 "Cannot give POS and CIRCLE in one request.",
379 "POS")
380 args["CIRCLE"] = geom
381
382 elif isinstance(geom, pgsphere.SPoly):
383 if args.get("POLYGON"):
384 raise ValidationError(
385 "Cannot give POS and POLYGON in one request.",
386 "POS")
387 args["POLYGON"] = geom
388
389 elif isinstance(geom, pgsphere.SBox):
390 if args.get("RA") or args.get("DEC"):
391 raise ValidationError(
392 "Cannot give POS and RA/DEC in one request.",
393 "POS")
394 args["RA"] = (geom.corner1.x/DEG, geom.corner2.x/DEG)
395 args["DEC"] = (geom.corner1.y/DEG, geom.corner2.y/DEG)
396
397 else: # parseSIAP2Geometry failure
398 raise ValidationError("Unexpected geometry result", "POS")
399 </code>
400 </procDef>
401
402 <procDef type="metaMaker" id="fits_makeWCSParams">
403 <doc>A metaMaker that generates parameters allowing cutouts along
404 the various WCS axes in physical coordinates.
405
406 This uses astropy.wcs for the spatial coordinates and tries to figure out
407 what these are with some heuristics. For the remaining coordinates,
408 it can set up separate, manual transformations. However, since in general,
409 they will correspond to standard SODA parameters (like BAND; there are
410 other streams of that in this RD), you have to explicitly request that by
411 mentioning the fits axis index in axisMetaOverrides, minimally like this::
412
413 &lt;bind key="axisMetaOverrides">{3: {}}&lt;/bind>
414
415 This will generate a parameter from the FITS metadata of axis 3.
416 You can override param attributes in the dictionary that is the
417 value of the axis key.
418
419 The metaMaker leaves an axisNames mapping in the descriptor.
420 This is important for the fits_doWCSCutout, and replacement metaMakers
421 must do the same.
422
423 The meta maker also creates a skyWCS attribute in the descriptor
424 if successful, containing the spatial transformation only. All
425 other transformations, if present, are in miscWCS, by a dict mapping
426 axis labels to the fitstools.WCS1Trans instances.
427 </doc>
428 <setup>
429 <par key="stcs" description="A QSTC expression describing the
430 STC structure of the parameters. This is currently ignored
431 and will almost certainly look totally different when STC2
432 finally comes around. Meanwhile, don't bother.">None</par>
433 <par key="axisMetaOverrides" description="A python dictionary
434 mapping fits axis indices (1-based) to dictionaries of
435 inputKey constructor arguments; for spatial axes, use the
436 axis name instead of the axis index.">{}</par>
437 <code><![CDATA[
438 if stcs is None:
439 parSTC = None
440 else:
441 parSTC = stc.parseQSTCS(stcs)
442 ]]></code>
443 </setup>
444
445 <code>
446 soda.ensureSkyWCS(descriptor)
447
448 for ik in soda.iterSpatialAxisKeys(descriptor, axisMetaOverrides):
449 yield ik
450
451 for ik in soda.iterOtherAxisKeys(descriptor, axisMetaOverrides):
452 yield ik
453 </code>
454 </procDef>
455
456 <procDef type="dataFunction" id="fits_makeHDUList">
457 <doc>
458 An initial data function to construct a pyfits hduList and
459 make that into a descriptor's data attribute.
460
461 This wants a descriptor as returned by fits_genDesc.
462
463 There's a hack here: this sets a dataIsPristine boolean on
464 descriptor that's made false when one of the fits manipulators
465 change something. If that's true by the time the formatter
466 sees it, it will just push out the entire file. So, if you
467 use this and insert your own data functions, make sure you
468 set dataIsPristine accordingly.
469 </doc>
470 <setup>
471 <par key="crop" description="Cut away everything but the
472 primary HDU? (This is unconditionally suppressed for
473 compressed FITSes and when operations are on a non-primary
474 extension).">True</par>
475 </setup>
476 <code>
477 from gavo.utils import pyfits
478
479 descriptor.dataIsPristine = True
480 descriptor.data = pyfits.open(os.path.join(
481 base.getConfig("inputsDir"), descriptor.accessPath),
482 do_not_scale_image_data=True)
483 descriptor.toClose = [descriptor.data]
484
485 if crop and descriptor.imageExtind==0:
486 descriptor.data = pyfits.HDUList([descriptor.data[0]])
487 </code>
488 </procDef>
489
490 <procDef type="dataFunction" id="fits_doWCSCutout">
491 <doc>
492 A fairly generic FITS cutout function.
493
494 It expects some special attributes in the descriptor to allow it
495 to decode the arguments. These must be left behind by the
496 metaMaker(s) creating the parameters.
497
498 This is axisNames, a dictionary mapping parameter names to
499 the FITS axis numbers or the special names WCSLAT or WCSLONG.
500 It also expects a skyWCS attribute, a wcs.WCS instance for spatial
501 cutouts.
502
503 Finally, descriptor must have a list attribute slices, containing
504 zero or more tuples of (fits axis, lowerPixel, upperPixel); this
505 allows things like BAND to add their slices obtained
506 from parameters in standard units.
507
508 The .data attribute must be a pyfits hduList, as generated by the
509 fits_makeHDUList data function.
510 </doc>
511 <code>
512 soda.doAxisCutout(descriptor, args)
513 </code>
514 </procDef>
515
516 <procDef type="dataFormatter" id="fits_formatHDUs">
517 <doc>
518 Formats pyfits HDUs into a FITS file.
519
520 This all works in memory, so for large FITS files you'd want something
521 more streamlined.
522 </doc>
523 <code>
524 if descriptor.dataIsPristine:
525 return File(os.path.join(
526 base.getConfig("inputsDir"), descriptor.accessPath),
527 "application/fits")
528
529 from gavo.formats import fitstable
530 resultName = fitstable.writeFITSTableFile(descriptor.data)
531
532 return TemporaryFile(resultName, "application/fits")
533 </code>
534 </procDef>
535
536 <STREAM id="fits_genKindPar">
537 <doc>This stream should be included in FITS-handling SODA services;
538 it adds parameter and code to just retrieve the FITS header to the
539 core.
540
541 For this to work as expected, it must be immediately before the
542 formatter.</doc>
543 <metaMaker name="genKindPar">
544 <code>
545 yield MS(InputKey, name="KIND", type="text",
546 multiplicity="forced-single", description="Set to HEADER"
547 " to retrieve just the primary header, leave empty for data.",
548 values = MS(Values,
549 options = [MS(Option, content_="HEADER",
550 title="Retrieve header only"),
551 MS(Option, content_="DATA",
552 title="Retrieve the full data, including header (default)")]))
553 </code>
554 </metaMaker>
555
556 <dataFunction>
557 <setup>
558 <code>
559 from gavo.utils import fitstools
560 </code>
561 </setup>
562 <code>
563 if args["KIND"]=="HEADER":
564 descriptor.data = ("application/fits-header",
565 fitstools.serializeHeader(
566 descriptor.data[
567 descriptor.imageExtind].header))
568 raise DeliverNow()
569 </code>
570 </dataFunction>
571 </STREAM>
572
573 <STREAM id="fits_genPixelPar">
574 <doc>This stream should be included in FITS-handling SODA services;
575 it add parameters and code to perform cut-outs along pixel coordinates.
576 </doc>
577 <metaMaker name="genPixelPars">
578 <code>
579 ucdMap = {
580 1: "pos.cartesian.x;instr.pixel",
581 2: "pos.cartesian.y;instr.pixel",
582 3: "pos.cartesian.z;instr.pixel"}
583
584 for axisInd in range(descriptor.hdr["NAXIS"]):
585 fitsInd = axisInd+1
586 minVal, maxVal = 1, descriptor.hdr["NAXIS%s"%fitsInd]
587 if maxVal==minVal:
588 continue
589
590 yield MS(InputKey, name="PIXEL_%s"%fitsInd,
591 type="integer[2]", unit="", xtype="interval",
592 description="Pixel coordinate along axis %s"%fitsInd,
593 ucd=ucdMap.get(fitsInd), multiplicity="forced-single",
594 values=MS(Values, min=minVal, max=maxVal))
595 </code>
596 </metaMaker>
597
598 <dataFunction name="cutoutPixelPars">
599 <code>
600 from gavo.utils import fitstools
601 slices = []
602 for fitsInd in range(1, descriptor.hdr["NAXIS"]+1):
603 imMin, imMax = 1, descriptor.hdr["NAXIS"+str(fitsInd)]
604 parName = "PIXEL_%s"%fitsInd
605 if args.get(parName) is None:
606 continue
607 axMin, axMax = args[parName]
608 descriptor.changingAxis(fitsInd, parName)
609 slices.append([fitsInd, axMin, axMax])
610
611 if slices:
612 descriptor.dataIsPristine = False
613 descriptor.data[descriptor.imageExtind
614 ] = fitstools.cutoutFITS(descriptor.data[descriptor.imageExtind],
615 *slices)
616 </code>
617 </dataFunction>
618 </STREAM>
619
620 <procDef type="metaMaker" id="fits_makeBANDMeta">
621 <doc>
622 Yields standard BAND params.
623
624 DaCHS should in general be smart enough to convert between common
625 spectral units (like MHz, or keV, or whatever) and the meter
626 that SODA BAND expects. If your files do to give VOUnits-parseable
627 units on the spectral axis' CUNIT header, use the wavelengthOverride
628 param.
629
630 This adds specToMeter, meterToSpec, and spectralAxis attributes to the
631 descriptor for later use by fits_makeBANDSlice.
632 </doc>
633 <setup>
634 <par key="fitsAxis" description="FITS axis index (1-based) of
635 the spectral axis">3</par>
636 <par key="wavelengthOverride" description="Override for the FITS
637 unit given for the wavelength (for when it is botched or
638 missing; leave at None for taking it from the header); this is
639 a python literal.">None</par>
640 <code>
641 from gavo.utils import fitstools
642 </code>
643 </setup>
644 <code>
645 if not fitsAxis:
646 return
647 if wavelengthOverride:
648 wavelengthUnit = wavelengthOverride
649 else:
650 wavelengthUnit = descriptor.hdr["CUNIT%d"%fitsAxis]
651
652 descriptor.specToMeter = base.getSpecConverter(
653 wavelengthUnit, "m")
654 descriptor.meterToSpec = base.getSpecConverter(
655 "m", wavelengthUnit)
656 descriptor.specAxis = fitstools.WCSAxis.fromHeader(
657 descriptor.hdr, fitsAxis, forceSeparable=True)
658 descriptor.specAxisIndex = fitsAxis
659
660 limits = [descriptor.specToMeter(v)
661 for v in descriptor.specAxis.getLimits()]
662 yield MS(InputKey, name="BAND", unit="m",
663 type="double precision[2]", xtype="interval",
664 ucd="em.wl", description="Vacuum wavelength limits",
665 multiplicity="forced-single",
666 values=MS(Values, min=min(limits), max=max(limits)))
667 </code>
668 </procDef>
669
670 <procDef type="dataFunction" id="fits_makeBANDSlice">
671 <doc>
672 Computes a cutout for the parameters added by makeBANDMeta.
673
674 This *must* sit in front of doWCSCutout.
675
676 This also reuses internal state added by makeBANDMeta,
677 so this really only makes sense together with it.
678 </doc>
679 <code>
680 if args.get("BAND") is None:
681 return
682 transform = descriptor.specAxis
683 limits = [transform.physToPix(
684 descriptor.meterToSpec(v)) for v in args["BAND"]]
685
686 descriptor.changingAxis(descriptor.specAxisIndex, "BAND")
687 descriptor.slices.append(
688 (descriptor.specAxisIndex,
689 utils.floorInt(min(limits)),
690 utils.ceilInt(max(limits))))
691 </code>
692 </procDef>
693
694 <STREAM id="fits_standardBANDCutout">
695 <doc>
696 Adds metadata and data function for one axis containing wavelengths.
697
698 (this could be extended to cover frequency and energy axes, I guess)
699
700 To use this, give the fits axis containing the spectral coordinate
701 in the spectralAxis attribute; if needed, you can override the
702 unit in wavelengthUnit (if the unit in the header is somehow
703 bad or missing; don't use quotes here).
704
705 This *must* be included physically before fits_doWCSCutout.
706 Otherwise, no cutout will be performed.
707 </doc>
708
709 <DEFAULTS spectralAxis="0" wavelengthOverride=""/>
710
711 <metaMaker procDef="//soda#fits_makeBANDMeta">
712 <bind key="fitsAxis">\spectralAxis</bind>
713 <bind key="wavelengthOverride">'\wavelengthOverride'</bind>
714 </metaMaker>
715 <dataFunction procDef="//soda#fits_makeBANDSlice"/>
716 </STREAM>
717
718
719 <procDef type="metaMaker" id="fits_makeVELOCITYMeta">
720 <doc>
721 Yields a non-SODA VELOCITY param for velocity cutouts in m/s.
722
723 This tries to get the unit in the FITS file from CUNITn. If that
724 is missing, unparsable or plain wrong, you can set the unit in
725 velocityOverride.
726 </doc>
727 <setup imports="gavo.utils.fitstools">
728 <par key="fitsAxis" description="FITS axis index (1-based) of
729 the velocity axis">3</par>
730 <par key="velocityOverride" description="Override for the FITS
731 unit given for the velocity axis (default: take from the
732 FITS file).">None</par>
733 </setup>
734 <code>
735 if not fitsAxis:
736 return
737 if velocityOverride:
738 velocityUnit = velocityOverride
739 else:
740 velocityUnit = descriptor.hdr["CUNIT%d"%fitsAxis]
741
742 descriptor.velFactor = base.computeConversionFactor(
743 velocityUnit, "m/s")
744 descriptor.velAxis = fitstools.WCSAxis.fromHeader(
745 descriptor.hdr, fitsAxis, forceSeparable=True)
746 descriptor.velAxisIndex = fitsAxis
747
748 limits = [v*descriptor.velFactor
749 for v in descriptor.velAxis.getLimits()]
750 yield MS(InputKey, name="VELOCITY", unit="m/s",
751 type="double precision[2]", xtype="interval",
752 description="Limits on the velocity axis",
753 multiplicity="forced-single",
754 values=MS(Values, min=min(limits), max=max(limits)))
755 </code>
756 </procDef>
757
758 <procDef type="dataFunction" id="fits_makeVELOCITYSlice">
759 <doc>
760 Computes a cutout for the parameters added by makeVELOCITYMeta.
761
762 This *must* sit in front of doWCSCutout.
763
764 This also reuses internal state added by makeVELOCITYMeta,
765 so this really only makes sense together with it.
766 </doc>
767 <code>
768 if args.get("VELOCITY") is None:
769 return
770 transform = descriptor.velAxis
771 limits = [transform.physToPix(v/descriptor.velFactor)
772 for v in args["VELOCITY"]]
773
774 descriptor.changingAxis(descriptor.velAxisIndex, "VELOCITY")
775 descriptor.slices.append(
776 (descriptor.velAxisIndex,
777 utils.floorInt(min(limits)),
778 utils.ceilInt(max(limits))))
779 </code>
780 </procDef>
781
782
783 <procDef type="metaMaker" id="fits_makePOSMeta">
784 <doc>
785 Yields a SIAv2-style POS param for cutouts.
786 </doc>
787 <code>
788 yield MS(InputKey, name="POS", type="text", ucd="phys.angArea;obs",
789 description="Region to (approximately) cut out, as Circle,"
790 " Region, or Polygon", multiplicity="forced-single")
791 </code>
792 </procDef>
793
794 <procDef type="metaMaker" id="fits_makePOLYGONMeta">
795 <doc>
796 Yields a SODA POLYGON parameter. This needs a descriptor
797 made by fits_genDesc.
798 </doc>
799 <code>
800 soda.ensureSkyWCS(descriptor)
801 yield MS(InputKey, name="POLYGON", type="double precision(*)",
802 xtype="polygon",
803 ucd="phys.argArea;obs", unit="deg",
804 description="A polygon (as a flattened array of ra, dec pairs)"
805 " that should be covered by the cutout.",
806 multiplicity="forced-single",
807 values=MS(Values,
808 max=coords.getSpolyFromWCSFields(descriptor.skyWCS).asSODA()))
809 </code>
810 </procDef>
811
812 <procDef type="dataFunction" id="fits_makePOLYGONSlice">
813 <doc>
814 Interprets POLYGON parameters. It just adds slices to the
815 descriptor. The actual cutout is done by fits_doWCSCutout, and
816 thus this procDef must be physically before it.
817 </doc>
818 <code>
819 if args.get("POLYGON"):
820 soda.addPolygonSlices(descriptor, args["POLYGON"], "POLYGON")
821 </code>
822 </procDef>
823
824 <procDef type="metaMaker" id="fits_makeCIRCLEMeta">
825 <doc>
826 Yields a SODA CIRCLE parameter. This needs a descriptor
827 made by fits_genDesc.
828 </doc>
829 <code>
830 soda.ensureSkyWCS(descriptor)
831 yield MS(InputKey, name="CIRCLE", type="double precision(3)",
832 ucd="phys.argArea;obs", unit="deg",
833 xtype="circle",
834 description="A circle (as a flattened array of ra, dec, radius)"
835 " that should be covered by the cutout.",
836 multiplicity="forced-single",
837 values=MS(Values,
838 max=coords.getCoveringCircle(
839 descriptor.skyWCS,
840 descriptor.spatialAxes).asSODA()))
841 </code>
842 </procDef>
843
844 <procDef type="dataFunction" id="fits_makeCIRCLESlice">
845 <doc>
846 Interprets CIRCLE parameters. It just adds slices to the
847 descriptor. The actual cutout is done by fits_doWCSCutout, and
848 thus this procDef must be physically before it.
849 </doc>
850 <code>
851 if args.get("CIRCLE"):
852 soda.addPolygonSlices(descriptor, args["CIRCLE"].asPoly(), "CIRCLE")
853 </code>
854 </procDef>
855
856 <STREAM id="fits_Geometries">
857 <metaMaker procDef="//soda#fits_makePOSMeta" name="polygonMeta"/>
858 <dataFunction procDef="//soda#fits_translateSODAPOS"
859 name="translatePOS"/>
860 <metaMaker procDef="//soda#fits_makePOLYGONMeta" name="polygonMeta"/>
861 <dataFunction procDef="//soda#fits_makePOLYGONSlice"
862 name="polygonSlice"/>
863 <metaMaker procDef="//soda#fits_makeCIRCLEMeta" name="circleMeta"/>
864 <dataFunction procDef="//soda#fits_makeCIRCLESlice"
865 name="circleSlice"/>
866 </STREAM>
867
868 <procDef type="metaMaker" id="fits_makeSCALEMeta">
869 <doc>
870 Yields standard SCALE meta for FITS files. Scale factors
871 need to be integral here.
872 </doc>
873 <setup>
874 <par name="thirdaxes" description="Skip this metadatum
875 if this string contains anything but 0s (this
876 is mainly for DaCHS internals).">""</par>
877 </setup>
878 <code>
879 if thirdaxes.strip("0"):
880 # there is a third axis, which our scale code cannot deal with
881 return
882
883 yield MS(InputKey, name="SCALE", type="integer",
884 description="Factor to scale the image down before transporting"
885 " (this does not currently take into account cutout parameters).",
886 values=MS(Values, min=2, max=32))
887 </code>
888 </procDef>
889
890 <procDef type="dataFunction" id="fits_doSCALE">
891 <doc>
892 Sets the scaled fits as the current data attribute. This
893 can only deal with integral scales and will not honor cutout ranges
894 (for now).
895 </doc>
896 <setup imports="gavo.utils.fitstools"/>
897 <code><![CDATA[
898 if args.get("SCALE") is None:
899 return
900 if not 1<args["SCALE"]<33:
901 raise base.ValidationError("SCALE must be between 2 and 32.",
902 "SCALE")
903
904 # TODO: make this stream out the scaled bytes
905 descriptor.data = ("application/fits", b"".join(
906 chunk for chunk in fitstools.iterScaledBytes(
907 os.path.join(base.getConfig("inputsDir"), descriptor.accref),
908 args["SCALE"])))
909 raise DeliverNow()
910 ]]></code>
911 </procDef>
912
913 <STREAM id="fits_standardDLFuncs">
914 <doc>
915 Pulls in all "standard" SODA functions for FITSes, including
916 cutouts and header retrieval.
917
918 You can give an stcs attribute (for fits_makeWCSParams); for this
919 doesn't make sense because STCS cannot express the SODA parameter
920 structure.
921
922 For spectral cubes, you can give a
923 spectralAxis attribute here containing the
924 fits axis index (1..n) of the spectral axis. If you don't, no BAND
925 cutout will be generated. If you do, you may want to fix
926 wavelengthOverride (default is to take what the FITS says).
927
928 For velocity cubes, there is, analogously, velocityAxis and
929 and velocityOverride. This will generate a (non-SODA) VELOCITY
930 parameter (using m/s).
931
932 For axisMetaOverrides, see `//soda#fits_makeWCSParams`_ (except it's
933 an attribute here rather than a proc param).
934
935 To work, this needs a descriptor generator; you probably want
936 //soda#fits_genDesc here.
937 </doc>
938 <DEFAULTS stcs="" spectralAxis="0" wavelengthOverride="None"
939 velocityAxis="0" velocityOverride="None"
940 axisMetaOverrides="{}"/>
941 <metaMaker procDef="//soda#fits_makeWCSParams" name="getWCSParams">
942 <bind key="stcs">'\stcs'</bind>
943 <bind key="axisMetaOverrides">\axisMetaOverrides</bind>
944 </metaMaker>
945 <dataFunction procDef="//soda#fits_makeHDUList" name="makeHDUList"/>
946 <metaMaker procDef="//soda#fits_makeSCALEMeta">
947 <bind name="thirdaxes">"\spectralAxis\velocityAxis"</bind>
948 </metaMaker>
949 <dataFunction procDef="//soda#fits_doSCALE"/>
950
951 <metaMaker procDef="//soda#fits_makeBANDMeta">
952 <bind key="fitsAxis">\spectralAxis</bind>
953 <bind key="wavelengthOverride">\wavelengthOverride</bind>
954 </metaMaker>
955 <dataFunction procDef="//soda#fits_makeBANDSlice"/>
956
957 <metaMaker procDef="//soda#fits_makeVELOCITYMeta">
958 <bind key="fitsAxis">\velocityAxis</bind>
959 <bind key="velocityOverride">\velocityOverride</bind>
960 </metaMaker>
961 <dataFunction procDef="//soda#fits_makeVELOCITYSlice"/>
962
963 <FEED source="//soda#fits_Geometries"/>
964 <dataFunction procDef="//soda#fits_doWCSCutout" name="doWCSCutout"/>
965 <FEED source="//soda#fits_genPixelPar"/>
966 <FEED source="//soda#fits_genKindPar"/>
967 <dataFormatter procDef="//soda#fits_formatHDUs" name="formatHDUs"/>
968 </STREAM>
969
970
971 </resource>