Debian Codegraph @

gavo/protocols/sdm.py

raw
1 """
2 Code dealing with spectra (the actual data), in particular in the spectral
3 data model (sdm).
4
5 This assumes Spectral Data Model Version 1, but doesn't use very much of it.
6 """
7
8 #c Copyright 2008-2025, the GAVO project <[email protected]>
9 #c
10 #c This program is free software, covered by the GNU GPL. See the
11 #c COPYING file in the source distribution.
12
13
14 import datetime
15 import io
16 import os
17
18 from gavo import base
19 from gavo import formats
20 from gavo import rsc
21 from gavo import svcs
22 from gavo import utils
23 from gavo.formats import fitstable
24 from gavo.protocols import products
25
26
27 # MIME types we can generate *from* SDM-compliant data; the values are
28 # either keys for formats.formatData, or None if we have special
29 # handling below.
30 GETDATA_FORMATS = {
31 base.votableType: "votable",
32 "application/x-votable+xml;serialization=tabledata": "votabletd",
33 "text/plain": "tsv",
34 "text/csv": "csv",
35 "application/fits": None,
36 "application/x-votable+xml;serialization=TABLEDATA;version=1.6": "vodml"}
37
38
39 _SDM1_IRREGULARS = {
40 "dataset.datamodel": "Spectrum.DataModel",
41 "dataset.type": "Spectrum.Type",
42 "dataset.length": "Spectrum.Length",
43 "dataset.timesi": "Spectrum.TimeSI",
44 "dataset.spectralsi": "Spectrum.SpectralSI",
45 "dataset.fluxsi": "Spectrum.FluxSI",
46 "access.format": None,
47 "access.reference": None,
48 "access.size": None,
49 "astrocoords.position2d.value2":
50 "Spectrum.Char.SpatialAxis.Coverage.Location.Value",
51 "target.pos.spoint": "Spectrum.Target.pos",
52 }
53
54 def getSDM1UtypeForSSA(utype):
55 """returns a utype from the spectrum data model for a utype of the ssa
56 data model.
57
58 For most utypes, this just removes a prefix and adds spec:Spectrum. Heaven
59 knows why these are two different data models anyway. There are some
60 (apparently random) differences, though.
61
62 For convenience, utype=None is allowed and returned as such.
63 """
64 if utype is None:
65 return None
66 localName = utype.split(":")[-1]
67 specLocal = _SDM1_IRREGULARS.get(localName.lower(), "Spectrum."+localName)
68 if specLocal:
69 return "spec:"+specLocal
70 else:
71 return None
72
73
74 _SDM_TO_SED_UTYPES = {
75 "spec:Spectrum.Data.SpectralAxis.Value":
76 "sed:Segment.Points.SpectralCoord.Value",
77 "spec:Data.SpectralAxis.Value":
78 "sed:Segment.Points.SpectralCoord.Value",
79 "spec:Spectrum.Data.FluxAxis.Value": "sed:Segment.Points.Flux.Value",
80 "spec:Data.FluxAxis.Value": "sed:Segment.Points.Flux.Value",
81 }
82
83
84 ################### Making SDM compliant tables (from SSA rows and
85 ################### data descriptors making spectral data)
86
87 def makeSDMDataForSSARow(ssaRow, spectrumData,
88 sdmVersion=base.getConfig("ivoa", "sdmVersion")):
89 """returns a rsc.Data instance containing an SDM compliant spectrum
90 for the spectrum described by ssaRow.
91
92 spectrumData is a data element making a primary table containing
93 the spectrum data from an SSA row (typically, this is going to be
94 the tablesource property of an SSA service).
95
96 You'll usually use this via //soda#sdm_genData
97 """
98 with base.getTableConn() as conn:
99 resData = rsc.makeData(spectrumData, forceSource=ssaRow,
100 connection=conn)
101 resData.setMeta("utype", "spec:Spectrum")
102
103 for resTable in resData.tables.values():
104
105 # fudge accref into a full URL
106 if resTable.getParam("accref"):
107 resTable.setParam("accref",
108 products.makeProductLink(resTable.getParam("accref")))
109 resData.DACHS_SDM_VERSION = sdmVersion
110
111 # fudge spoint params into 2-arrays
112 for param in resTable.iterParams():
113 # Bad, bad: In-place changes; change this to creating new params
114 # one of these days.
115 if param.type=="spoint":
116 val = param.value
117 param.type = "double precision(2)"
118 param.xtype = None
119 param.unit = "deg"
120 if val:
121 param.set([val.x/utils.DEG, val.y/utils.DEG])
122
123 # we want to include service metadata for data origin, but getting to
124 # the service object from in here is really hard (since services may
125 # share cores). So... let's steal. Nothing much breaks if this doesn't
126 # work out.
127 try:
128 resData.contributingMetaCarriers.append(utils.stealVar("service"))
129 except ValueError:
130 # no service local in stack
131 pass
132
133 return resData
134
135
136 def makeSDMDataForPUBDID(pubDID, ssaTD, spectrumData,
137 sdmVersion=base.getConfig("ivoa", "sdmVersion")):
138 """returns a rsc.Data instance containing an SDM compliant spectrum
139 for pubDID from ssaTable.
140
141 ssaTD is the definition of a table containing the SSA metadata,
142 spectrumData is a data element making a primary table containing
143 the spectrum data from an SSA row (typically, this is going to be
144 the tablesource property of an SSA service).
145 """
146 matchingRows = ssaTD.doSimpleQuery(fragments="ssa_pubdid=%(pubDID)s",
147 params={"pubDID": pubDID})
148 if not matchingRows:
149 raise svcs.UnknownURI("No spectrum with pubdid %s known here"%
150 pubDID)
151 return makeSDMDataForSSARow(
152 matchingRows[0],
153 spectrumData,
154 sdmVersion=sdmVersion)
155
156
157 ################## Special FITS hacks for SDM serialization
158
159 def _add_target_pos_cards(header, par):
160 """_SDM_HEADER_MAPPING for target.pos.
161 """
162 header.set("RA_TARG", par.value.x/utils.DEG)
163 header.set("DEC_TARG", par.value.y/utils.DEG)
164
165
166 def _add_location_cards(header, par):
167 """_SDM_HEADER_MAPPING for target.pos.
168 """
169 header.set("RA", par.value[0])
170 header.set("DEC", par.value[1])
171
172
173 def getColIndForUtype(header, colUtype):
174 """returns the fits field index that has colUtype as its utype within
175 header.
176
177 If no such field exists, this raises a KeyError
178 """
179 nCols = header.get("TFIELDS", 0)
180 for colInd in range(1, nCols+1):
181 key = "TUTYP%d"%colInd
182 if header.get(key, None)==colUtype:
183 return colInd
184 else:
185 raise KeyError(colUtype)
186
187
188 def _make_limits_func(colUtype, keyBase):
189 """returns a _SDM_HEADER_MAPPING for declaring TDMIN/MAXn and friends.
190
191 colUtype determines the n here.
192 """
193 def func(header, par):
194 try:
195 key = keyBase+str(getColIndForUtype(header, colUtype))
196 header.set(key, par.value, comment="[%s]"%par.unit)
197 except KeyError:
198 # no field for utype
199 pass
200
201 return func
202
203
204 # A mapping from utypes to the corresponding FITS keywords
205 # There are some more complex cases, for which a function is a value
206 # here; the function is called with the FITS header and the parameter
207 # in question.
208 _SDM_HEADER_MAPPING = {
209 "datamodel": "VOCLASS",
210 "length": "DATALEN",
211 "type": "VOSEGT",
212 "coordsys.id": "VOCSID",
213 "coordsys.spaceframe.name": "RADECSYS",
214 "coordsys.spaceframe.equinox": "EQUINOX",
215 "coordsys.spaceframe.ucd": "SKY_UCD",
216 "coordsys.spaceframe.refpos": "SKY_REF",
217 "coordsys.timeframe.name": "TIMESYS",
218 "coordsys.timeframe.ucd": None,
219 "coordsys.timeframe.zero": "MJDREF",
220 "coordsys.timeframe.refpos": None,
221 "coordsys.spectralframe.refpos": "SPECSYS",
222 "coordsys.spectralframe.redshift": "REST_Z",
223 "coordsys.spectralframe.name": "SPECNAME",
224 "coordsys.redshiftframe.name": "ZNAME",
225 "coordsys.redshiftframe.refpos": "SPECSYSZ",
226 "curation.publisher": "VOPUB",
227 "curation.reference": "VOREF",
228 "curation.publisherid": "VOPUBID",
229 "curation.version": "VOVER",
230 "curation.contactname": "CONTACT",
231 "curation.contactemail": "EMAIL",
232 "curation.rights": "VORIGHTS",
233 "curation.date": "VODATE",
234 "curation.publisherdid": "DS_IDPUB",
235 "target.name": "OBJECT",
236 "target.description": "OBJDESC",
237 "target.class": "SRCCLASS",
238 "target.spectralclass": "SPECTYPE",
239 "target.redshift": "REDSHIFT",
240 "target.varampl": "TARGVAR",
241 "dataid.title": "TITLE",
242 "dataid.creator": "AUTHOR",
243 "dataid.datasetid": "DS_IDENT",
244 "dataid.creatordid": "CR_IDENT",
245 "dataid.date": "DATE",
246 "dataid.version": "VERSION",
247 "dataid.instrument": "INSTRUME",
248 "dataid.creationtype": "CRETYPE",
249 "dataid.logo": "VOLOGO",
250 # collection will need work when we properly implement it
251 "dataid.collection": "COLLECT1",
252 "dataid.contributor": "CONTRIB1",
253 "dataid.datasource": "DSSOURCE",
254 "dataid.bandpass": "SPECBAND",
255 "derived.snr": "DER_SNR",
256 "derived.redshift.value": "DER_Z",
257 "derived.redshift.staterror": "DER_ZERR",
258 "derived.redshift.confidence": "DER_ZCNF",
259 "derived.varampl": "DER_VAR",
260 "timesi": "TIMESDIM",
261 "spectralsi": "SPECSDIM",
262 "fluxsi": "FLUXSDIM",
263 "char.fluxaxis.name": None,
264 "char.fluxaxis.unit": None,
265 "char.fluxaxis.ucd": None,
266 "char.spectralaxis.name": None,
267 "char.spectralaxis.unit": None,
268 "char.spectralaxis.ucd": None,
269 "char.timeaxis.name": None,
270 "char.timeaxis.ucd": None,
271 "char.spatialaxis.name": None,
272 "char.spatialaxis.unit": None,
273 "char.fluxaxis.accuracy.staterror": "STAT_ERR",
274 "char.fluxaxis.accuracy.syserror": "SYS_ERR",
275 "char.timeaxis.accuracy.staterror": "TIME_ERR",
276 "char.timeaxis.accuracy.syserror": "TIME_SYE",
277 "char.timeaxis.resolution": "TIME_RES",
278 "char.fluxaxis.calibration": "FLUX_CAL",
279 "char.spectralaxis.calibration": "SPEC_CAL",
280 "char.spectralaxis.coverage.location.value": "SPEC_VAL",
281 "char.spectralaxis.coverage.bounds.extent": "SPEC_BW",
282 "char.spectralaxis.coverage.bounds.start":
283 _make_limits_func("spec:spectrum.data.spectralaxis.value", "TDMIN"),
284 "char.spectralaxis.coverage.bounds.stop":
285 _make_limits_func("spec:spectrum.data.spectralaxis.value", "TDMAX"),
286 "char.spectralaxis.samplingprecision.": None,
287 "samplingprecisionrefval.fillfactor": "SPEC_FIL",
288 "char.spectralaxis.samplingprecision.SampleExtent": "SPEC BIN",
289 "char.spectralaxis.accuracy.binsize": "SPEC_BIN",
290 "char.spectralaxis.accuracy.staterror": "SPEC_ERR",
291 "char.spectralaxis.accuracy.syserror": "SPEC_SYE",
292 "char.spectralaxis.resolution": "SPEC_RES",
293 "char.spectralaxis.respower": "SPEC_RP",
294 "char.spectralaxis.coverage.support.extent": "SPECWID",
295 "char.timeaxis.unit": "TIMEUNIT",
296 "char.timeaxis.accuracy.binsize": "TIMEDEL",
297 "char.timeaxis.calibration": "TIME_CAL",
298 "char.timeaxis.coverage.location.value": "TMID",
299 "char.timeaxis.coverage.bounds.extent": "TELAPSE",
300 "char.timeaxis.coverage.bounds.start": "TSTART",
301 "char.timeaxis.coverage.bounds.stop": "TSTOP",
302 "char.timeaxis.coverage.support.extent": "EXPOSURE",
303 "char.timeaxis.samplingprecision.samplingprecisionrefval.fillfactor": "DTCOR",
304 "char.timeaxis.samplingprecision.sampleextent": "TIMEDEL",
305 "char.spatialaxis.ucd": "SKY_UCD",
306 "char.spatialaxis.accuracy.staterr": "SKY_ERR",
307 "char.spatialaxis.accuracy.syserror": "SKY_SYE",
308 "char.spatialaxis.calibration": "SKY_CAL",
309 "char.spatialaxis.resolution": "SKY_RES",
310 "char.spatialaxis.coverage.bounds.extent": "APERTURE",
311 "char.spatialaxis.coverage.support.area": "REGION",
312 "char.spatialaxis.coverage.support.extent": "AREA",
313 "char.spatialaxis.samplingprecision.samplingprecisionrefval.fillfactor":
314 "SKY_FILL",
315
316 # special handling through functions
317 "target.pos": _add_target_pos_cards,
318 "char.spatialaxis.coverage.location.value": _add_location_cards,
319 }
320
321 def makeBasicSDMHeader(sdmData, header):
322 """updates the fits header header with the params from sdmData.
323 """
324 for par in sdmData.getPrimaryTable().iterParams():
325 if par.value is None or par.utype is None:
326 continue
327
328 mapKey = par.utype.lower().split(":")[-1]
329 if mapKey.startswith("spectrum."): # WTF?
330 mapKey = mapKey[9:]
331
332 destKey = _SDM_HEADER_MAPPING.get(mapKey, None)
333 if destKey is None:
334 pass
335 elif callable(destKey):
336 destKey(header, par)
337 else:
338 comment = ""
339 if par.unit:
340 comment = str("[%s]"%par.unit)
341
342 # TODO: use our serialising infrastructure here
343 value = par.value
344 if isinstance(value, bytes):
345 value = value.decode("ascii")
346 elif isinstance(value, datetime.datetime):
347 value = value.isoformat()
348
349 header.set(destKey, value, comment)
350
351
352 def makeSDMFITS(sdmData):
353 """returns sdmData in an SDM-compliant FITS.
354
355 This only works for SDM version 1. Behaviour with version 2 SDM
356 data is undefined.
357 """
358 sdmData.getPrimaryTable().IgnoreTableParams = None
359 hdus = fitstable.makeFITSTable(sdmData)
360 sdmHdr = hdus[1].header
361 makeBasicSDMHeader(sdmData, sdmHdr)
362 srcName = fitstable.writeFITSTableFile(hdus)
363 with open(srcName, "rb") as f:
364 data = f.read()
365 os.unlink(srcName)
366 return data
367
368
369 ################## Serializing SDM compliant tables
370
371 def formatSDMData(sdmData, format, queryMeta=svcs.emptyQueryMeta):
372 """returns a pair of mime-type and payload for a rendering of the SDM
373 Data instance sdmData in format.
374
375 (you'll usually use this via //soda#sdm_format)
376 """
377 destMime = str(format or base.votableType)
378 if queryMeta["tdEnc"] and destMime==base.votableType:
379 destMime = "application/x-votable+xml;serialization=tabledata"
380 formatId = GETDATA_FORMATS.get(destMime, None)
381
382 if formatId is None:
383 # special or unknown format
384 if destMime=="application/fits":
385 return destMime, makeSDMFITS(sdmData)
386 else:
387 raise base.ValidationError("Cannot format table to %s"%destMime,
388 "FORMAT")
389
390 # target version is usually set by makeSDMDataForSSARow; but if
391 # people made sdmData in some other way, fall back to default.
392 sdmVersion = getattr(sdmData, "DACHS_SDM_VERSION",
393 base.getConfig("ivoa", "sdmVersion"))
394 if sdmVersion=="1":
395 sdmData.addMeta("_votableRootAttributes",
396 'xmlns:spec="http://www.ivoa.net/xml/SpectrumModel/v1.01"')
397
398 # I'm not altogehter sure whether it's wise to kick out
399 # empty tables; but TOPCAT does ugly modal dialogs when they
400 # are there, so let's take them out.
401 for name in list(sdmData.tables):
402 if len(sdmData.tables[name].rows)==0:
403 del sdmData.tables[name]
404
405 resF = io.BytesIO()
406 formats.formatData(formatId, sdmData, resF, acquireSamples=False)
407 return destMime, resF.getvalue()
408
409
410 ################## Manipulation of SDM compliant tables
411 # The idea here is that you can push in a table, the function does some
412 # magic, and it returns that table. The getData implementation (see ssap.py)
413 # and some SODA data functions (//soda)
414 # use these functions to provide some spectrum transformations. We
415 # may want to provide some plugin system so people can add their own
416 # transformations, but let's first see someone request that.
417
418 def getFluxColumn(sdmTable):
419 """returns the column containing the flux in sdmTable.
420 """
421 return sdmTable.tableDef.getByUtypes("spec:Spectrum.Data.FluxAxis.Value")
422
423
424 def getSpectralColumn(sdmTable):
425 """returns the column containing the spectral coordinate in sdmTable.
426 """
427 return sdmTable.tableDef.getByUtypes(
428 "spec:Spectrum.Data.SpectralAxis.Value")
429
430
431 def mangle_cutout(sdmTable, low, high):
432 """returns only those rows from sdmTable for which the spectral coordinate
433 is between low and high.
434
435 Both low and high must be given. If you actually want half-open intervals,
436 do it in interface code (low=-1 and high=1e308 should do fine).
437 """
438 spectralColumn = getSpectralColumn(sdmTable)
439
440 # we may swap limits later; let's memorise whether we have an empty
441 # interval.
442 returnEmpty = low>high
443
444 spectralUnit = spectralColumn.unit
445 # convert low and high from meters to the unit on the
446 # spectrum's spectral axis
447 converter = base.getSpecConverter("m", spectralUnit)
448 low, high = converter(low), converter(high)
449 # swap limits in case of (freq, energy) -> wavelength
450 low, high = min(low, high), max(low, high)
451
452 # Whoa! we should have an API that allows replacing table rows safely
453 # (this stuff will blow up when we have indices):
454 spectralName = spectralColumn.name
455 if returnEmpty:
456 sdmTable.rows=[]
457 else:
458 sdmTable.rows=[
459 row for row in sdmTable.rows if low<=row[spectralName]<=high]
460
461 specVals = [r[spectralName] for r in sdmTable.rows]
462 if specVals:
463 invConverter = base.getSpecConverter(spectralUnit, "m")
464 lim1, lim2 = invConverter(min(specVals)), invConverter(max(specVals))
465 specstart, specend = min(lim1, lim2), max(lim1, lim2)
466 sdmTable.setParam("ssa_specext", specend-specstart)
467 sdmTable.setParam("ssa_specstart", specstart)
468 sdmTable.setParam("ssa_specend", specend)
469 sdmTable.setParam("ssa_specmid", (specstart+specend)/2)
470
471 return sdmTable
472
473
474 def mangle_fluxcalib(sdmTable, newCalib):
475 """returns sdmTable with a new calibration.
476
477 Currently, we can only normalize the spectrum to the maximum value.
478 """
479 newCalib = newCalib.lower()
480 if newCalib==sdmTable.getParam("ssa_fluxcalib").lower():
481 return sdmTable
482 fluxName = getFluxColumn(sdmTable).name
483
484 try:
485 # TODO: parameterize this
486 errorName = sdmTable.tableDef.getColumnByUCD(
487 "stat.error;phot.flux;em.opt").name
488 except base.StructureError:
489 # no (known) error column
490 errorName = None
491
492 if newCalib=="relative":
493 # whoa! we're changing this in place; I guess that should be
494 # legalized for tables in general.
495 normalizer = float(max(row[fluxName] for row in sdmTable.rows))
496 for row in sdmTable.rows:
497 row[fluxName] = row[fluxName]/normalizer
498
499 if errorName:
500 for row in sdmTable.rows:
501 row[errorName] = row[errorName]/normalizer
502
503 sdmTable.setParam("ssa_fluxcalib", "RELATIVE")
504 sdmTable.tableDef = sdmTable.tableDef.copy(sdmTable.tableDef.parent)
505 sdmTable.tableDef.getColumnByName("flux").unit = ""
506 return sdmTable
507
508 raise base.ValidationError("Do not know how to turn a %s spectrum"
509 " into a %s one."%(sdmTable.getParam("ssa_fluxcalib"), newCalib),
510 "FLUXCALIB")