A descriptor generator for SODA that builds a
``ProductDescriptor`` for PubDIDs that have been built by
``getStandardsPubDID``
(i.e., the path part of the IVOID is a tilde, with the
products table accref as the query part).
In case you want to add a bit of extra logic in these descriptor
generators, define a function ``addExtras(descriptor)`` in a setup element
and add attributes as necessary.
None
None
desc = ProductDescriptor.fromAccref(
pubDID,
getAccrefFromStandardPubDID(pubDID),
accrefPrefix)
desc.contentQualifier = contentQualifier
if "addExtras" in globals():
addExtras(desc)
return desc
The tivial formatter for SODA processed data -- it just
returns descriptor.data, which will only work it it works as a
nevow resource.
If you do not give any dataFormatter yourself in a SODA core,
this is what will be used.
return descriptor.data
A data function for SODA that returns a product instance.
You can restrict the mime type of the product requested so the
following filters have a good idea what to expect.
frozenset()
from gavo.protocols import products
if requireMimes and descriptor.mime not in requireMimes:
raise base.ValidationError("Document type not supported: %s"%
descriptor.mime, colName="PUBDID", hint="Only source documents"
" of the types %s are supported here."%str(requireMimes))
descriptor.data = products.getProductForRAccref(descriptor.accref)
A data function for SODA returning the product row
corresponding to a PubDID within an SSA table.
The descriptors generated have an ssaRow attribute containing
the original row in the SSA table.
ssap.SSADescriptor
True
"#spectrum"
ssaTD = base.resolveCrossId(ssaTD, rscdef.TableDef)
with base.getTableConn() as conn:
# accept naked accrefs for local data, too
if not pubDID.startswith("ivo://"):
pubDID = getStandardPubDID(pubDID)
if useAccref:
cond, pars = "accref=%(accref)s", {
"accref": rscdef.getAccrefFromStandardPubDID(pubDID)}
else:
cond, pars = "ssa_pubdid=%(pubdid)s", {"pubdid": pubDID}
ssaTable = rsc.TableForDef(ssaTD, connection=conn
).getTableForQuery(
ssaTD,
cond,
pars)
if not ssaTable.rows:
return DatalinkFault.NotFoundFault(pubDID,
"No spectrum with this pubDID known here")
desc = ssap.SSADescriptor.fromSSAResult(ssaTable)
# SSADescriptors.fromSSAResult clears the pubDID attribute
# as a service for SSA-embedded SODA blocks. So, we retrofit
# pubDID here.
desc.pubDID = pubDID
desc.contentQualifier = contentQualifier
return desc
A data function for SODA returning a spectral data model
compliant table that later data functions can then work on.
As usual for generators, it uses the implicit PUBDID argument.
from gavo import rscdef
builder = base.resolveCrossId(builder, rscdef.DataDescriptor)
from gavo.protocols import sdm
descriptor.data = sdm.makeSDMDataForSSARow(descriptor.ssaRow, builder)
A stream inserting a data function and its metadata generator to
do select flux calibrations in SDM data. This expects
sdm_generate (or at least parameters.data as an SDM data instance)
as the generating function within the SODA core.
Clients can select "RELATIVE" as FLUXCALIB, which does a
normalization to max(flux)=1 here. Everything else is rejected
right now.
This probably is more an example of how to write such a thing
then genuinely useful.
supportedCalibs = set(["RELATIVE"])
foundCalibs = descriptor.ssaRow["ssa_fluxcalib"]
# this is tricky: When we have a set of matches, we may be
# returning calibrations we cannot serve (since we can only
# change to RELATIVE for now). There's nothing I can really
# do about this.
if "ssa_fluxcalib" in descriptor.limits \
and descriptor.limits["ssa_fluxcalib"].values:
supportedCalibs.update(descriptor.limits["ssa_fluxcalib"].values)
else:
if isinstance(foundCalibs, str):
supportedCalibs.add(foundCalibs)
yield MS(InputKey, name="FLUXCALIB", type="text",
multiplicity="forced-single",
ucd="phot.calib",
utype="ssa:Char.FluxAxis.Calibration",
description="Recalibrate the spectrum. Right now, the only"
" recalibration supported is max(flux)=1 ('RELATIVE').",
values=MS(Values, options=[
MS(Option, content_=val) for val in supportedCalibs]))
if not args.get("FLUXCALIB"):
return
from gavo.protocols import sdm
# table is changed in place
sdm.mangle_fluxcalib(descriptor.data.getPrimaryTable(),
args["FLUXCALIB"])
A stream inserting a data function and its metaMaker to
do cutouts in SDM data. This expects sdm_generate (or at least
parameters.data as an SDM data instance) as the generating function
within the SODA core.
The cutout limits are always given in meters, regardless of
the spectrum's actual units (as in SSAP's BAND parameter).
yield MS(InputKey, type="double precision[2]", xtype="interval",
name="BAND", multiplicity="forced-single",
unit="m", ucd="em.wl",
description="Spectral cutout interval",
values=MS(Values,
min=descriptor.limits["ssa_specstart"].min,
max=descriptor.limits["ssa_specend"].max))
if args.get("BAND") is None:
return
from gavo.protocols import sdm
# table is modified in place
sdm.mangle_cutout(
descriptor.data.getPrimaryTable(),
args["BAND"][0], args["BAND"][1])
A formatter for SDM data, together with its input key
for FORMAT.
formatsAvailable = {
"application/x-votable+xml": "VOTable, binary encoding",
"application/x-votable+xml;serialization=tabledata":
"VOTable, tabledata encoding",
"text/plain": "Tab separated values",
"text/csv": "Comma separated values",
"application/fits": "FITS binary table",
"application/x-votable+xml;serialization=TABLEDATA;version=1.6":
"VOTable 1.6 beta"}
yield MS(InputKey, name="FORMAT", type="text",
ucd="meta.code.mime",
utype="ssa:Access.Format",
multiplicity="forced-single",
description="MIME type of the output format",
values = MS(Values,
options = [MS(Option, title=value, content_=key)
for key, value in formatsAvailable.items()]))
from gavo.protocols import sdm
if not descriptor.data.getPrimaryTable().rows:
raise soda.EmptyData()
return sdm.formatSDMData(descriptor.data, args["FORMAT"])
A data function for SODA returning the a fits descriptor.
This has, in addition to the standard stuff, a hdr attribute containing
the primary header as pyfits structure.
The functionality of this is in its setup, getFITSDescriptor.
The intention is that customized DGs (e.g., fixing the header)
can use this as an original.
None
FITSProductDescriptor
True
"#image"
desc = getFITSDescriptor(pubDID, accrefPrefix, cls=descClass, qnd=qnd)
desc.contentQualifier = contentQualifier
return desc
A metaMaker that generates the SODA POLYGON, CIRCLE, and
POS parameters for a rectangular image with WCS in ICRS.
Needs a FITSDescriptor.
yield MS(InputKey, name="POS", type="text",
ucd="phys.angArea;obs",
description="SIAv2-compatible cutout specification",
multiplicity="forced-single")
A data function to interpret SODA POS.
This merely translates the POS parameter to the equivalent
POLYGON, CIRCLE, or RA/DC parameters. It thus must run before
these other data functions. Just run it after the initial data
function and be done with it.
from gavo.protocols import siap
if not args["POS"]:
return
geom = siap.parseSIAP2Geometry(args["POS"])
args["POS"] = None
if isinstance(geom, pgsphere.SCircle):
if args.get("CIRCLE"):
raise ValidationError(
"Cannot give POS and CIRCLE in one request.",
"POS")
args["CIRCLE"] = geom
elif isinstance(geom, pgsphere.SPoly):
if args.get("POLYGON"):
raise ValidationError(
"Cannot give POS and POLYGON in one request.",
"POS")
args["POLYGON"] = geom
elif isinstance(geom, pgsphere.SBox):
if args.get("RA") or args.get("DEC"):
raise ValidationError(
"Cannot give POS and RA/DEC in one request.",
"POS")
args["RA"] = (geom.corner1.x/DEG, geom.corner2.x/DEG)
args["DEC"] = (geom.corner1.y/DEG, geom.corner2.y/DEG)
else: # parseSIAP2Geometry failure
raise ValidationError("Unexpected geometry result", "POS")
A metaMaker that generates parameters allowing cutouts along
the various WCS axes in physical coordinates.
This uses astropy.wcs for the spatial coordinates and tries to figure out
what these are with some heuristics. For the remaining coordinates,
it can set up separate, manual transformations. However, since in general,
they will correspond to standard SODA parameters (like BAND; there are
other streams of that in this RD), you have to explicitly request that by
mentioning the fits axis index in axisMetaOverrides, minimally like this::
<bind key="axisMetaOverrides">{3: {}}</bind>
This will generate a parameter from the FITS metadata of axis 3.
You can override param attributes in the dictionary that is the
value of the axis key.
The metaMaker leaves an axisNames mapping in the descriptor.
This is important for the fits_doWCSCutout, and replacement metaMakers
must do the same.
The meta maker also creates a skyWCS attribute in the descriptor
if successful, containing the spatial transformation only. All
other transformations, if present, are in miscWCS, by a dict mapping
axis labels to the fitstools.WCS1Trans instances.
None
{}
soda.ensureSkyWCS(descriptor)
for ik in soda.iterSpatialAxisKeys(descriptor, axisMetaOverrides):
yield ik
for ik in soda.iterOtherAxisKeys(descriptor, axisMetaOverrides):
yield ik
An initial data function to construct a pyfits hduList and
make that into a descriptor's data attribute.
This wants a descriptor as returned by fits_genDesc.
There's a hack here: this sets a dataIsPristine boolean on
descriptor that's made false when one of the fits manipulators
change something. If that's true by the time the formatter
sees it, it will just push out the entire file. So, if you
use this and insert your own data functions, make sure you
set dataIsPristine accordingly.
True
from gavo.utils import pyfits
descriptor.dataIsPristine = True
descriptor.data = pyfits.open(os.path.join(
base.getConfig("inputsDir"), descriptor.accessPath),
do_not_scale_image_data=True)
descriptor.toClose = [descriptor.data]
if crop and descriptor.imageExtind==0:
descriptor.data = pyfits.HDUList([descriptor.data[0]])
A fairly generic FITS cutout function.
It expects some special attributes in the descriptor to allow it
to decode the arguments. These must be left behind by the
metaMaker(s) creating the parameters.
This is axisNames, a dictionary mapping parameter names to
the FITS axis numbers or the special names WCSLAT or WCSLONG.
It also expects a skyWCS attribute, a wcs.WCS instance for spatial
cutouts.
Finally, descriptor must have a list attribute slices, containing
zero or more tuples of (fits axis, lowerPixel, upperPixel); this
allows things like BAND to add their slices obtained
from parameters in standard units.
The .data attribute must be a pyfits hduList, as generated by the
fits_makeHDUList data function.
soda.doAxisCutout(descriptor, args)
Formats pyfits HDUs into a FITS file.
This all works in memory, so for large FITS files you'd want something
more streamlined.
if descriptor.dataIsPristine:
return File(os.path.join(
base.getConfig("inputsDir"), descriptor.accessPath),
"application/fits")
from gavo.formats import fitstable
resultName = fitstable.writeFITSTableFile(descriptor.data)
return TemporaryFile(resultName, "application/fits")
This stream should be included in FITS-handling SODA services;
it adds parameter and code to just retrieve the FITS header to the
core.
For this to work as expected, it must be immediately before the
formatter.
yield MS(InputKey, name="KIND", type="text",
multiplicity="forced-single", description="Set to HEADER"
" to retrieve just the primary header, leave empty for data.",
values = MS(Values,
options = [MS(Option, content_="HEADER",
title="Retrieve header only"),
MS(Option, content_="DATA",
title="Retrieve the full data, including header (default)")]))
from gavo.utils import fitstools
if args["KIND"]=="HEADER":
descriptor.data = ("application/fits-header",
fitstools.serializeHeader(
descriptor.data[
descriptor.imageExtind].header))
raise DeliverNow()
This stream should be included in FITS-handling SODA services;
it add parameters and code to perform cut-outs along pixel coordinates.
ucdMap = {
1: "pos.cartesian.x;instr.pixel",
2: "pos.cartesian.y;instr.pixel",
3: "pos.cartesian.z;instr.pixel"}
for axisInd in range(descriptor.hdr["NAXIS"]):
fitsInd = axisInd+1
minVal, maxVal = 1, descriptor.hdr["NAXIS%s"%fitsInd]
if maxVal==minVal:
continue
yield MS(InputKey, name="PIXEL_%s"%fitsInd,
type="integer[2]", unit="", xtype="interval",
description="Pixel coordinate along axis %s"%fitsInd,
ucd=ucdMap.get(fitsInd), multiplicity="forced-single",
values=MS(Values, min=minVal, max=maxVal))
from gavo.utils import fitstools
slices = []
for fitsInd in range(1, descriptor.hdr["NAXIS"]+1):
imMin, imMax = 1, descriptor.hdr["NAXIS"+str(fitsInd)]
parName = "PIXEL_%s"%fitsInd
if args.get(parName) is None:
continue
axMin, axMax = args[parName]
descriptor.changingAxis(fitsInd, parName)
slices.append([fitsInd, axMin, axMax])
if slices:
descriptor.dataIsPristine = False
descriptor.data[descriptor.imageExtind
] = fitstools.cutoutFITS(descriptor.data[descriptor.imageExtind],
*slices)
Yields standard BAND params.
DaCHS should in general be smart enough to convert between common
spectral units (like MHz, or keV, or whatever) and the meter
that SODA BAND expects. If your files do to give VOUnits-parseable
units on the spectral axis' CUNIT header, use the wavelengthOverride
param.
This adds specToMeter, meterToSpec, and spectralAxis attributes to the
descriptor for later use by fits_makeBANDSlice.
3
None
from gavo.utils import fitstools
if not fitsAxis:
return
if wavelengthOverride:
wavelengthUnit = wavelengthOverride
else:
wavelengthUnit = descriptor.hdr["CUNIT%d"%fitsAxis]
descriptor.specToMeter = base.getSpecConverter(
wavelengthUnit, "m")
descriptor.meterToSpec = base.getSpecConverter(
"m", wavelengthUnit)
descriptor.specAxis = fitstools.WCSAxis.fromHeader(
descriptor.hdr, fitsAxis, forceSeparable=True)
descriptor.specAxisIndex = fitsAxis
limits = [descriptor.specToMeter(v)
for v in descriptor.specAxis.getLimits()]
yield MS(InputKey, name="BAND", unit="m",
type="double precision[2]", xtype="interval",
ucd="em.wl", description="Vacuum wavelength limits",
multiplicity="forced-single",
values=MS(Values, min=min(limits), max=max(limits)))
Computes a cutout for the parameters added by makeBANDMeta.
This *must* sit in front of doWCSCutout.
This also reuses internal state added by makeBANDMeta,
so this really only makes sense together with it.
if args.get("BAND") is None:
return
transform = descriptor.specAxis
limits = [transform.physToPix(
descriptor.meterToSpec(v)) for v in args["BAND"]]
descriptor.changingAxis(descriptor.specAxisIndex, "BAND")
descriptor.slices.append(
(descriptor.specAxisIndex,
utils.floorInt(min(limits)),
utils.ceilInt(max(limits))))
Adds metadata and data function for one axis containing wavelengths.
(this could be extended to cover frequency and energy axes, I guess)
To use this, give the fits axis containing the spectral coordinate
in the spectralAxis attribute; if needed, you can override the
unit in wavelengthUnit (if the unit in the header is somehow
bad or missing; don't use quotes here).
This *must* be included physically before fits_doWCSCutout.
Otherwise, no cutout will be performed.
\spectralAxis
'\wavelengthOverride'
Yields a non-SODA VELOCITY param for velocity cutouts in m/s.
This tries to get the unit in the FITS file from CUNITn. If that
is missing, unparsable or plain wrong, you can set the unit in
velocityOverride.
3
None
if not fitsAxis:
return
if velocityOverride:
velocityUnit = velocityOverride
else:
velocityUnit = descriptor.hdr["CUNIT%d"%fitsAxis]
descriptor.velFactor = base.computeConversionFactor(
velocityUnit, "m/s")
descriptor.velAxis = fitstools.WCSAxis.fromHeader(
descriptor.hdr, fitsAxis, forceSeparable=True)
descriptor.velAxisIndex = fitsAxis
limits = [v*descriptor.velFactor
for v in descriptor.velAxis.getLimits()]
yield MS(InputKey, name="VELOCITY", unit="m/s",
type="double precision[2]", xtype="interval",
description="Limits on the velocity axis",
multiplicity="forced-single",
values=MS(Values, min=min(limits), max=max(limits)))
Computes a cutout for the parameters added by makeVELOCITYMeta.
This *must* sit in front of doWCSCutout.
This also reuses internal state added by makeVELOCITYMeta,
so this really only makes sense together with it.
if args.get("VELOCITY") is None:
return
transform = descriptor.velAxis
limits = [transform.physToPix(v/descriptor.velFactor)
for v in args["VELOCITY"]]
descriptor.changingAxis(descriptor.velAxisIndex, "VELOCITY")
descriptor.slices.append(
(descriptor.velAxisIndex,
utils.floorInt(min(limits)),
utils.ceilInt(max(limits))))
Yields a SIAv2-style POS param for cutouts.
yield MS(InputKey, name="POS", type="text", ucd="phys.angArea;obs",
description="Region to (approximately) cut out, as Circle,"
" Region, or Polygon", multiplicity="forced-single")
Yields a SODA POLYGON parameter. This needs a descriptor
made by fits_genDesc.
soda.ensureSkyWCS(descriptor)
yield MS(InputKey, name="POLYGON", type="double precision(*)",
xtype="polygon",
ucd="phys.argArea;obs", unit="deg",
description="A polygon (as a flattened array of ra, dec pairs)"
" that should be covered by the cutout.",
multiplicity="forced-single",
values=MS(Values,
max=coords.getSpolyFromWCSFields(descriptor.skyWCS).asSODA()))
Interprets POLYGON parameters. It just adds slices to the
descriptor. The actual cutout is done by fits_doWCSCutout, and
thus this procDef must be physically before it.
if args.get("POLYGON"):
soda.addPolygonSlices(descriptor, args["POLYGON"], "POLYGON")
Yields a SODA CIRCLE parameter. This needs a descriptor
made by fits_genDesc.
soda.ensureSkyWCS(descriptor)
yield MS(InputKey, name="CIRCLE", type="double precision(3)",
ucd="phys.argArea;obs", unit="deg",
xtype="circle",
description="A circle (as a flattened array of ra, dec, radius)"
" that should be covered by the cutout.",
multiplicity="forced-single",
values=MS(Values,
max=coords.getCoveringCircle(
descriptor.skyWCS,
descriptor.spatialAxes).asSODA()))
Interprets CIRCLE parameters. It just adds slices to the
descriptor. The actual cutout is done by fits_doWCSCutout, and
thus this procDef must be physically before it.
if args.get("CIRCLE"):
soda.addPolygonSlices(descriptor, args["CIRCLE"].asPoly(), "CIRCLE")
Yields standard SCALE meta for FITS files. Scale factors
need to be integral here.
""
if thirdaxes.strip("0"):
# there is a third axis, which our scale code cannot deal with
return
yield MS(InputKey, name="SCALE", type="integer",
description="Factor to scale the image down before transporting"
" (this does not currently take into account cutout parameters).",
values=MS(Values, min=2, max=32))
Sets the scaled fits as the current data attribute. This
can only deal with integral scales and will not honor cutout ranges
(for now).
Pulls in all "standard" SODA functions for FITSes, including
cutouts and header retrieval.
You can give an stcs attribute (for fits_makeWCSParams); for this
doesn't make sense because STCS cannot express the SODA parameter
structure.
For spectral cubes, you can give a
spectralAxis attribute here containing the
fits axis index (1..n) of the spectral axis. If you don't, no BAND
cutout will be generated. If you do, you may want to fix
wavelengthOverride (default is to take what the FITS says).
For velocity cubes, there is, analogously, velocityAxis and
and velocityOverride. This will generate a (non-SODA) VELOCITY
parameter (using m/s).
For axisMetaOverrides, see `//soda#fits_makeWCSParams`_ (except it's
an attribute here rather than a proc param).
To work, this needs a descriptor generator; you probably want
//soda#fits_genDesc here.
'\stcs'
\axisMetaOverrides
"\spectralAxis\velocityAxis"
\spectralAxis
\wavelengthOverride
\velocityAxis
\velocityOverride