2010-10-07T13:00:00 Table structures and definitions used in building Simple Spectral Access (SSAP) services. virtual-observatories Position ICRS [ssa_location] Size "ssa_aperture" "ssa_aperture" SpectralInterval "ssa_specstart" "ssa_specend" Spectral "ssa_specmid" Size "ssa_specext" Fixed parameters of all SSA tables Spectrum-1.0 ICRS \timeSI \spectralSI \spectralUCD \magicEmpty{\spectralUnit} \fluxSI \magicEmpty{\fluxUCD} \magicEmpty{\fluxUnit} The parameters table for an SSA (HCD) result. The definition of the homogeneous in HCD is that all these parameters are constant for all datasets within a table ("collection"). These params are supposed to be filled using mixin parameters (or stream parameters, but the available parameters are documented in the hcd mixin). Some params are hardcoded to NULL right now; they can easily be added to hcd's parameters if someone needs them. ssa_model and ssa_dstype cannot be changed right now. Changing them would probably not make much sense since they reflect what's in this RD. Spectrum \publisher \creator \collection \instrument \datasource \creationType \reference \statFluxError \sysFluxError \fluxCalibration \statSpectError \sysSpectError \spectralCalibration \spectralResolution \statSpaceError The fields that a mixc table needs on top of what hcd has; for simplicity, this is everything that hcd has as a parameter. defaults = {"type": "real", "unit": "__NULL__", "ucd": "__NULL__"} for evType, name, pars in context.getById("hcd_outpars").iterEvents(): if evType=="start" and name=="param": if (pars["name"].endswith("SI") # those remain params or pars["name"] in ["ssa_csysName", "ssa_model"]): continue if (pars["name"] in ["ssa_spaceRes", "ssa_spaceCalib", "ssa_spaceError"]): # would anyone *ever* miss those? continue if pars["name"].endswith("unit") or pars["name"].endswith("ucd"): # these must be parameters since they end up in the table # metadata continue rec = {} rec.update(defaults) rec.update(pars) rec["verbLevel"] = '15' yield rec A stream for form-based service's VOTables to include simple RA and Dec rather than normal ssa_location. SSA services get that from the core and don't need this. A measure of how closely the record matches your query. Higher numbers mean better matches. A sample of SSA fields for referencing and such.
Sets metadata for an SSA data collection, including its products definition. Since this is only useful with the deprecated hcd and mixc mixins, this should no longer be used. The values are left in vars, so you need to do manual copying, e.g., using idmaps="*", or, if you need to be more specific, idmaps="ssa_*". None None datetime.datetime.utcnow() None None None None None None None None None None None None None None None None copiedKWs = ['dstitle', 'creatorDID', 'pubDID', 'cdate', 'pdate', 'bandpass', 'cversion', 'targname', 'targclass', 'redshift', 'snr', 'aperture', 'timeExt', 'specstart', 'specend', 'length'] vars["ssa_dateObs"] = toMJD(dateObs) userPars = locals() for kw in copiedKWs: vars["ssa_"+kw] = userPars[kw] alpha = parseFloat(alpha) delta = parseFloat(delta) specstart = parseFloat(specstart) specend = parseFloat(specend) if specstart is not None and specend is not None: vars["ssa_specext"] = specend-specstart vars["ssa_specmid"] = (specend-specstart)/2 vars["ssa_region"] = vars["ssa_location"] = None if alpha is not None and delta is not None: vars["ssa_location"] = pgsphere.SPoint.fromDegrees(alpha, delta) if aperture: vars["ssa_region"] = pgsphere.SCircle.fromDALI( [alpha, delta, aperture]).asPoly(6) Sets metadata for an SSA data set from mixed sources. This will only work sensibly in cooperation with setMeta Since //ssap#mixc is deprecated, there is no reason to use this in new RDs. As with setMeta, the values are left in vars; if you did as recommended with setMeta, you'll have this covered as well. "spectrum" "Take from RD" "Take from RD" None "Take from RD" None None "Take from RD" None None None None None None None None inVars = locals() for parName, metaName in [ ("publisher", "publisher"), ("reference", "source"), ("instrument", "instrument")]: if inVars[parName]=="Take from RD": vars["ssa_"+parName] = base.getMetaText( rd, metaName, acceptSequence=False) else: vars["ssa_"+parName] = inVars[parName] for copiedName in ["dstype", "collection", "datasource", "creationType", "fluxCalib", "specCalib", "specres", "binSize"]: vars["ssa_"+copiedName.lower()] = inVars[copiedName] if vars["ssa_specres"] is None: vars["ssa_specres"] = vars["ssa_binsize"] __EMPTY__ __EMPTY__ __NULL__ __NULL__ __NULL__ em.wl phot.flux.density;em.wl UNKNOWN TT "mySchema.myTableName" ]]> __NULL__ \metaString{publisherID}{\metaString{publisher}} __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ __NULL__ NaN (votable:Coords) { time: { frame: { timescale: \timescale refPosition: \refposition time0: 2400000.5 } location: @ssa_dateObs } } # these secret attributes are used by the sdm-instance substrate.from_mixin_spectral_unit = mixinPars["spectralUnit"] substrate.from_mixin_spectral_ucd = mixinPars["spectralUCD"] substrate.from_mixin_flux_unit = mixinPars["fluxUnit"] substrate.from_mixin_flux_ucd = mixinPars["fluxUCD"] "schema.table" ]]> (votable:Coords) { time: { frame: { timescale: \timescale refPosition: \refposition time0: 2400000.5 } location: @ssa_dateObs } } # these secret attributes are used by the sdm-instance substrate.from_mixin_spectral_unit = mixinPars["spectralUnit"] substrate.from_mixin_spectral_ucd = mixinPars["spectralUCD"] substrate.from_mixin_flux_unit = mixinPars["fluxUnit"] substrate.from_mixin_flux_ucd = mixinPars["fluxUCD"] ). The mixin will automatically create an index over whatever you give for ssa_pubDID (if you give something). ]]> False __EMPTY__ UNKNOWN TT not given __EMPTY__ __EMPTY__ VIEWPAR_DEFAULTS = { # maps view column names to defaults for the mixin "accref": "accref", "owner": "owner", "embargo": "embargo", "mime": "mime", "accsize": "accsize", "ssa_aperture": "NULL", "ssa_bandpass": "NULL", "ssa_collection": "NULL", "ssa_creationtype": "\\sqlquote{\\metaString{ssap.creationType}{unknown}}", "ssa_csysName": "'ICRS'", "ssa_datasource": "\\sqlquote{\\metaString{ssap.dataSource}{unknown}}", "ssa_dateObs": "NULL", "ssa_dstitle": "NULL", "ssa_dstype": "'spectrum'", "ssa_fluxcalib": "", "ssa_fluxucd": "'phot.flux.density;em.wl'", "ssa_instrument": "\\sqlquote{\\metaString{instrument}{unknown}}", "ssa_length": "NULL", "ssa_location": "NULL", "ssa_model": "'Spectrum-1.0'", "ssa_pdate": "\\sqlquote{\\today}", "ssa_publisher": "\\sqlquote{\\metaString{publisher}{unknown}}", "ssa_pubDID": "\\sql_standardPubDID", "ssa_reference": "\\sqlquote{\\metaString{source}{unknown}}", "ssa_specres": "NULL", "ssa_spectralucd": "'em.wl;obs.atmos'", "ssa_spectralunit": "", "ssa_specmid": "(ssa_specend+ssa_specstart)/2", "ssa_specext": "(ssa_specend-ssa_specstart)", } DESCRIPTION_OVERRIDES = { "ssa_binSize": "Size of the typical spectral bin in meters" " of wavelength.", "ssa_cdate": "Dataset creation date as a datetime", "ssa_pdate": "Date of (last) publication as a datetime", "ssa_dataObs": "MJD of the midpoint of the exposure", "ssa_fluxSI": "It's safe to ignore this.", "ssa_timeSI": "It's safe to ignore this.", "ssa_spectralSI": "It's safe to ignore this.", "ssa_fluxunit": "Unit of the flux column in the dataset. This" " is also the unit for the ssa_flux*Error columns (and thus" " better had not change between rows).", "ssa_spectralunit": "Unit of the flux column in the dataset" " (e.g., 'Angstrom'). This is also the unit for the" " ssa_spectral*Error columns (and thus better had not" " change between rows).", "ssa_location": "You probably don't want to manually" " handle this. Use `the //ssap#plainlocation mixin`_" " on your metadata table instead and write ssa_location here.", "ssa_region": "You probably don't want to manually" " handle this. Use `the /ssap#simpleCoverage mixin`_" " on your metadata table instead.", "ssa_targetpos": "Position of the intended target of the" " observation. You don't usually need to give this." " if you do, you probably want to write" " pgsphere.SPoint.fromDegrees(targ_ra, targ_dec)", } from gavo.protocols import ssap for c in ssap.iterViewColumns(context): yield {"name": c.name, "description": DESCRIPTION_OVERRIDES.get(c.name, c.description), "default": VIEWPAR_DEFAULTS.get(c.name, "NULL")} \default valueExpression = adql.getRawGrammar()[0]["valueExpression"] def getCopiedColumns(copiedColumnsSpec, baseTable): """returns a sequence for columns in baseTable matching copiedColumnsSpec. copiedColumnsSpec has comma-separated shell patterns as in rowmaker/@idmaps. Refactoring this and rscdef.rmkdef.RowmakerDef._resolveIdmaps is probably not worth it. """ baseNames = [c.key for c in baseTable] matchingNames = [] for pat in [s.strip() for s in copiedColumnsSpec.split(",")]: matchingNames.extend(fnmatch.filter(baseNames, pat)) # if a column has matched multiple times, it will # be returned multiple times; since later occurrences # overwrite earlier ones in tables, that shouldn't hurt. return [baseTable.getColumnByName(n) for n in matchingNames] # Change product table column utypes; this is always universally # necessary because these columns typically come from sourcetable # and there from //products#tablecols. And where's not necessary # it certainly doesn't hurt either. UTYPE_OVERRIDES = { "accref": ("ssa:Access.Reference", "meta.ref.url;meta.dataset"), "mime": ("ssa:Access.Format", "meta.code.mime"), "accsize": ("ssa:Access.Size", "")} def applyOverrides(col): if col.name in UTYPE_OVERRIDES: utype, ucd = UTYPE_OVERRIDES[col.name] return col.change(utype=utype, ucd=ucd) return col def nullToEmpty(val): return "" if val.lower()=="null" else val def makeOptionsForConstant(sqlLit, col): """sets col's values to sqlLit's string value if it is a string literal. This is mainly cosmetics for VOSI tablesets, where we don't want *calib columns to oddly stick out with a lot of irrelevant options. """ # better say nothing than bleed out non-expanded # macros if '\\\\' in sqlLit: return if col.type=="text" and utils.isSQLTextLiteral(sqlLit): if col.values is None: col.values = base.makeStruct(rscdef.Values, parent_=col) col.values.options = makeOptionsFromDist({ sqlLit.strip()[1:-1].replace("''", "'"): 1}) col.values.actual = True from gavo.protocols import ssap substrate.viewPieces = collections.OrderedDict() for c in ssap.iterViewColumns(context): substrate.feedObject("column", applyOverrides(c)) val = mixinPars[c.name] if '\\\\' not in val: # this is *not* a security feature (if you can run this # mixin, you can run SQL through the viewStatement anyway). # This is just so you get get perhaps more useful error messages # in some cases. try: _ = valueExpression.parseString(val, parseAll=True) except base.ParseException: raise base.StructureError("Mixin par %s=%s does not match SQL" " valueExpression."%(c.name, val), hint="ssap#view parameters are in general put literally" " into a view declaration and hence must be valid SQL." " What you put in here is not recognised by DaCHS'" " ADQL parser. If you are sure postgres will swallow" " it, prefix it with backslash-+ to make DaCHS accept it, too.") substrate.viewPieces[c.name] = "(%s)::%s AS %s"%( val, base.sqltypeToPG(c.type), c.name) makeOptionsForConstant(val, c) # ssa_region is a local addition (yet) and can't be taken # from ssap#instance. if mixinPars["ssa_region"]!="not given": substrate.feedObject("column", MS(rscdef.Column, name="ssa_region", type="spoly", tablehead="Coverage", description="Rough coverage based on location and aperture", verbLevel=30)) substrate.viewPieces["ssa_region"] = ( "(%s)::spoly AS ssa_region"%mixinPars["ssa_region"]) # Copy over columns from the source table (these will overwrite # stuff from ssap#instance) sourceTable = base.resolveId( context, mixinPars["sourcetable"], forceType=rscdef.TableDef) for c in getCopiedColumns(mixinPars["copiedcolumns"], sourceTable): substrate.feedObject("column", applyOverrides(c)) substrate.viewPieces[c.name] = "(%s)::%s AS %s"%( c.name, base.sqltypeToPG(c.type), c.name) # the source table almost always needs an index we can use # for our pubdids, so just create it. if mixinPars["ssa_pubDID"]: sourceTable.feedObject("index", base.makeStruct(rscdef.DBIndex, columns=["ssa_pubDID"], content_="(%s)"%mixinPars["ssa_pubDID"], name="obscore_%s_did_index"%substrate.id)) # these secret attributes are used by the sdm-instance substrate.from_mixin_spectral_unit = nullToEmpty( mixinPars["ssa_spectralunit"]).strip("'") substrate.from_mixin_spectral_ucd = nullToEmpty( mixinPars["ssa_spectralucd"]).strip("'") substrate.from_mixin_flux_unit = nullToEmpty( mixinPars["ssa_fluxunit"]).strip("'") substrate.from_mixin_flux_ucd = nullToEmpty( mixinPars["ssa_fluxucd"]).strip("'") # Now override view definitions for columns the substrate # got from the source table. sourceTable = base.resolveId( context, mixinPars["sourcetable"]) for col in substrate.columns: if col.name in sourceTable: substrate.viewPieces[col.name] = "%s::%s"%( col.name, base.sqltypeToPG(col.type)) if base.parseBooleanLiteral(mixinPars["materialize"]): materialization = "MATERIALIZED" else: materialization = "" substrate.viewStatement = substrate.viewStatement.replace( "__VIEW_DEF_LINES__", ",\n".join(substrate.viewPieces.values()) ).replace( "__SOURCETABLE_NAME__", sourceTable.getQName() ).replace( "__MATERIALIZATION__", materialization ).replace( "__COL_NAMES__", ", ".join(c.name for c in substrate)) True (votable:Coords) { time: { frame: { timescale: \timescale refPosition: \refposition time0: 2400000.5 } location: @ssa_dateObs } } CREATE __MATERIALIZATION__ VIEW \\curtable AS ( SELECT __COL_NAMES__ FROM ( SELECT __VIEW_DEF_LINES__ \customcode FROM __SOURCETABLE_NAME__ \whereclause) AS internal_ssa_view) A procDef for condDescs that may match against table params *or* table columns, depending on where consCol is found. from gavo import rscdef key = inputKeys[0].name val = inPars.get(key, None) if val is None or val.lower()=="any": return parsed = parClass.fromLiteral(val, key) valueSource = core.queriedTable.getByName(consCol) if isinstance(valueSource, rscdef.Param): if (valueSource.value is not None and not parsed.covers(valueSource.value)): yield '1!=1' else: yield parsed.getSQL(consCol, outPars) This stream defines the condDescs for an SSA service based on one of the mixins defined here. "ssa_location" key = inputKeys[0].name lit = inPars.get(key, None) if lit is None: return try: ranges = pql.PQLFloatPar.fromLiteral(lit, key) if ranges is None: # null string return yield ranges.getSQLForInterval( "ssa_specstart", "ssa_specend", outPars) except base.LiteralParseError: # As float ranges, things didn't work out. Try band names ("V") # and bail out if unsuccessful. yield pql.PQLPar.fromLiteral(lit, key).getSQL( "ssa_bandpass", outPars) "ssa_dateObs" "mjd" frozenset([ "application/x-votable+xml"]) frozenset([ "application/fits", "text/csv", "text/plain", "image/fits"]) "mime" val = inPars.get("FORMAT", None) if val is None: return if val=="" or val=="ALL": # no constraint return sel = pql.PQLStringPar.fromLiteral( val.lower(), "FORMAT").getValuesAsSet() if "all" in sel: return # No constraints if "compliant" in sel: yield "%s IN %%(%s)s"%(consCol, base.getSQLKey(consCol, compliantFormats, outPars)) sel.remove("compliant") if "native" in sel: yield "%s IN %%(%s)s"%(consCol, base.getSQLKey(consCol, nativeFormats, outPars)) sel.remove("native") if "graphic" in sel: yield "%s LIKE 'image/%%'"%(consCol) sel.remove("graphic") if "votable" in sel: yield "%s = 'application/x-votable+xml'"%consCol sel.remove("votable") if "fits" in sel: yield "%s = 'application/fits'"%consCol sel.remove("fits") if "xml" in sel: yield "1=0" # whatever would *that* be? sel.remove("xml") if sel: yield "%s IN %%(%s)s"%(consCol, base.getSQLKey(consCol, sel, outPars)) keyName, matchCol, procDef APERTURE, ssa_aperture, //pql#floatParameter SNR, ssa_snr, //pql#floatParameter REDSHIFT, ssa_redshift, //pql#floatParameter TARGETNAME, ssa_targname, //pql#irStringParameter TARGETCLASS, ssa_targclass, //pql#stringParameter MTIME, ssa_pdate, //pql#dateParameter "\matchCol" keyName, matchCol, parClass FLUXCALIB, ssa_fluxcalib, pql.PQLCaselessPar SPATRES, ssa_spaceRes, pql.PQLFloatPar WAVECALIB, ssa_speccalib, pql.PQLCaselessPar COLLECTION, ssa_collection, pql.PQLPar "\matchCol" \parClass from gavo import rscdef keyName, matchCol PUBDID, ssa_pubDID CREATORDID, ssa_creatorDID yield "\matchCol=%%(%s)s"%base.getSQLKey("\keyName", inPars["\keyName"], outPars) keyName, parClass, addDesc WILDTARGET, PQLNocaseShellPatternPar, (case insensitive) WILDTARGETCASE, PQLShellPatternPar, (case sensitive) parsed = pql.\parClass.fromLiteral( inPars.get("\keyName"), "\keyName") if parsed is not None: yield parsed.getSQL("\keyName", outPars) queryData True if False: yield from gavo.protocols import sdm srcTable = context.getById("instance") for name in "\fieldnames".split(): utype = sdm.getSDM1UtypeForSSA( srcTable.getElementForName(name).utype) yield {"dest": name, "utype": utype} //ssap#sdm-instance The mixin thus defines a gazillion of params. This will almost always be filled using `//ssap#feedSSAToSDM`_ as explained in `SDM compliant tables`_ ]]> The independent variable of this spectrum (see its ucd to figure out whether it's a wavelength, frequency, or energy) The dependent variable of this spectrum (see the ucd for its physical meaning) __EMPTY__ __EMPTY__ __EMPTY__ __EMPTY__ from gavo import base from gavo import rscdef from gavo.protocols import sdm # copy over columns and params from the instance table as # params for us. ssapInstance = context.resolveId(mixinPars["ssaTable"]) for col in ssapInstance.columns: atts = col.getAttributes() atts["utype"] = sdm.getSDM1UtypeForSSA(atts["utype"]) atts["required"] = False substrate.feedObject("param", base.makeStruct(rscdef.Param, parent_=substrate, **atts)) for param in ssapInstance.params: newUtype = sdm.getSDM1UtypeForSSA(param.utype) substrate.feedObject("param", param.change(utype=newUtype)) specUnit = getattr( ssapInstance, "from_mixin_spectral_unit", "\spectralUnitOverride") if specUnit is None: raise base.StructureError("Cannot deduce spectral ucd/unit from" " ssa table; use spectralUCDOverride and spectralUnitOverride") specCol = substrate.getColumnByName("spectral") specCol.feed("ucd", r"\spectralUCDOverride" or ssapInstance.from_mixin_spectral_ucd) specCol.feed("unit", r"\spectralUnitOverride" or ssapInstance.from_mixin_spectral_unit) fluxUnit = getattr(ssapInstance, "from_mixin_flux_unit", "\fluxUnitOverride") if fluxUnit is None: raise base.StructureError("Cannot deduce flux ucd/unit from" " ssa table; use fluxUCDOverride and fluxUnitOverride") if specUnit is None: raise base.StructureError("Cannot deduce flux ucd/unit from" " ssa table; use fluxUCDOverride and fluxUnitOverride") fluxCol = substrate.getColumnByName("flux") fluxCol.feed("ucd", r"\fluxUCDOverride" or ssapInstance.from_mixin_flux_ucd) fluxCol.feed("unit", r"\fluxUnitOverride" or ssapInstance.from_mixin_flux_unit) # set the SDM container meta if not already present if substrate.getMeta("utype", default=None) is None: substrate.setMeta("utype", "spec:Spectrum") A mixin furnishes a table with an ssa_region column giving a polygonal coverage. For SSA itself, that's unnecessary, but it's highly recommended if you have data with positional and aperture data and will publish it via obscore, too (which in turn is highly recommended). The column will be filled with a hexagon approximating the aperture. This is done by //ssap#fill-plainlocation (or, historically, by //ssap#setMeta), so usually you're all set with this mixin. We also create an index for the ssa_region field. To make it visible in obscore, you must bind the ``ssa_region`` parameter of `the //ssap#view mixin`_ to ``ssa_region`` (so the column is in the SSAP table, and the ``coverage`` mixin par of `the //obscore#publishSSAPMIXC mixin`_ to ``ssa_region`` (so the value ends up in obscore's ``s_region``). A mixin that adds ssa_location column to a table. You probably want this in the source tables for //ssap#view tables. This will also index the column. At least if you later want to publish the data through obscore, you will also want `the //ssap#simpleCoverage mixin`_ if you mix this in. Use the `//ssap#fill-plainlocation`_ apply to feed these. This mixin fills the columns added by the plainlocation mixin with values generated from ra, dec, and aperture. None vars["ssa_location"] = vars["ssa_region"] = None if ra is None or dec is None: return vars["ssa_location"] = pgsphere.SPoint.fromDegrees(ra, dec) if aperture is not None: vars["ssa_region"] = pgsphere.SCircle.fromDALI( [ra, dec, aperture/2]).asPoly(6) feedSSAToSDM takes the current rowIterator's sourceToken and feeds it to the params of the current target. sourceTokens must be an SSA rowdict (as provided by the sdmCore). Further, it takes the params from the sourceTable argument and feeds them to the params, too. All this probably only makes sense in parmakers when making tables mixing in //ssap#sdm-instance in data children of sdmCores. srcMeta = vars["parser_"].sourceToken for param in targetTable.tableDef.params: newVal = srcMeta.get(param.name) if newVal is not None: targetTable.setParam(param.name, newVal) Include this stream in an ssa-like table feeding obscore. It will add an index useful for querying against obscore t_min and t_max. This uses the dateObs and timeExt attributes which are preset for what the columns are called in SSA tables. dateObs must be a column reference because we declare the index to be on it. timeExt can be an expression, too, and no index will be declared on it. (\dateObs-\timeExt/43200.) (\dateObs+\timeExt/43200.)