Debian Codegraph @

gavo/helpers/fitstricks.py

raw
1 """
2 Helpers for manipulating FITS files.
3
4 In contrast to fitstools, this is not for online processing or import of
5 files, but just for the manipulation before processing.
6
7 Rough guideline: if it's about writing fixed fits files, it probably belongs
8 here, otherwise it goes to fitstools.
9
10 Realistically, this module has been hemorraghing functions to
11 fitstools and probably should be removed completely.
12
13 One important function it has grown is FITS header templates. These
14 can be used by processors. If these use custom templates, they should
15 register them (or regret it later). See registerTemplate's docstring.
16 """
17
18 #c Copyright 2008-2025, the GAVO project <[email protected]>
19 #c
20 #c This program is free software, covered by the GNU GPL. See the
21 #c COPYING file in the source distribution.
22
23
24 import datetime
25 import re
26
27 from gavo import base
28 from gavo.utils import pyfits
29
30 DEFAULT_IGNORED_HEADERS = ["simple", "bitpix", "naxis", "imageh",
31 "imagew", "naxis1", "naxis2", "datamin", "datamax", "date"]
32
33
34 def addHistoryCard(header, entry, recognizer):
35 """adds a history card to header, overwriting a previous version if
36 it's present.
37
38 This will reject entries longer than 72 characters, as these would
39 create cruft on overwriting. Since we always prepend today's date to entry,
40 the net payload size is 61 characters.
41
42 regcognizer is a string that is searched within the history string. If
43 it is found, entry is put into the card. If none such card is found,
44 a new history card is written.
45
46 This is mainly for processors; in particular during development,
47 but quite likely also when reprocessing, you don't want extra
48 history entries each time the processor runs (yeah, there are
49 situations when you *would* want to know about reprocessing, but
50 weight these against the horrible cruft, I know what I want.
51 """
52 entry = "%s %s"%(datetime.date.today().isoformat(), entry)
53 if len(entry)>72:
54 raise ValueError("History entries must not exceed 61 characters.")
55
56 histCards = header["history"]
57 for index, card in enumerate(histCards):
58 if recognizer in card:
59 header["history"][index] = entry
60 break
61 else:
62 header.add_history(entry)
63
64
65 def copyFields(header, cardList,
66 ignoredHeaders=frozenset(DEFAULT_IGNORED_HEADERS)):
67 """copies over all cards from cardList into header, excluding headers
68 named in ignoredHeaders.
69
70 ignoredHeaders must be all lowercase.
71 """
72 for card in cardList:
73 if card.keyword=="COMMENT":
74 header.add_comment(card.value)
75 elif card.keyword=="HISTORY":
76 header.add_history(card.value)
77 elif card.keyword=="":
78 header.append(pyfits.Card("", card.value), end=True)
79 elif card.keyword.lower() in ignoredHeaders:
80 pass
81 else:
82 header.set(card.keyword, card.value, card.comment)
83
84
85 def getHeaderAsDict(hdr):
86 """returns the "normal" key-value pairs from hdr in a dictionary.
87
88 Comment, history and blank cards are excluded; the comments from the
89 cards are lost, too.
90 """
91 ignored = frozenset(["", "HISTORY", "COMMENT"])
92 return dict((k,v) for k,v in hdr.items()
93 if k not in ignored)
94
95
96 def _makeHeaderSequence(keyTpl, commentTpl):
97 try:
98 return [
99 (keyTpl%ind, commentTpl%numeral)
100 for ind, numeral in [
101 (1, "1st"),
102 (2, "2nd"),
103 (3, "3rd"),]]
104 except TypeError:
105 raise base.ReportableError("Invalid header sequence templates: %r %r"%(
106 keyTpl, commentTpl))
107
108
109 # FITS header template for a minimal pixel array
110 MINIMAL_IMAGE_TEMPLATE = [
111 pyfits.Card("SIMPLE", True),
112 pyfits.Card("EXTEND", True),
113 ("BITPIX", "Array data type"),
114 pyfits.Card("NAXIS", 2),
115 ("NAXIS1", "Number of elements along 1st axis"),
116 ("NAXIS2", "Number of elements along 2nd axis"),
117 ("BZERO", "Zero point of pixel scaling function"),
118 ("BSCALE", "Slope of pixel scaling function"),]
119
120
121 WCS_TEMPLATE = [
122 pyfits.Card(value="-------------------- Spatial WCS"),
123 ('EQUINOX', "Equinox of RA and Dec"),
124 ('RADESYS', "Reference System used for RA and Dec"),
125 ('WCSAXES', "Number of FITS axes covered by WCS"),
126 ('CTYPE1', "Projection on axis 1"),
127 ('CTYPE2', "Projection on axis 2"),
128 ('LONPOLE', "See sect 2.4 of WCS paper II"),
129 ('LATPOLE', "See sect 2.4 of WCS paper II"),
130 ('CRVAL1', "Longitude of reference point"),
131 ('CRVAL2', "Latitude of reference point"),
132 ('CRPIX1', "X reference pixel"),
133 ('CRPIX2', "Y reference pixel"),
134 ('CUNIT1', "X pixel scale units"),
135 ('CUNIT2', "Y pixel scale units"),
136 ('CD1_1', "(1,1) Full transformation matrix"),
137 ('CD1_2', "(1,2) Full transformation matrix"),
138 ('CD2_1', "(2,1) Full transformation matrix"),
139 ('CD2_2', "(2,2) Full transformation matrix"),
140 ('PC1_1', "(1,1) Transformation matrix"),
141 ('PC1_2', "(1,2) Transformation matrix"),
142 ('PC2_1', "(2,1) Transformation matrix"),
143 ('PC2_2', "(2,2) Transformation matrix"),
144 ('A_ORDER', "Correction polynomial order, axis 1"),
145 ('A_0_0', "Axis 1 correction polynomial, coefficient"),
146 ('A_0_1', "Axis 1 correction polynomial, coefficient"),
147 ('A_0_2', "Axis 1 correction polynomial, coefficient"),
148 ('A_0_3', "Axis 1 correction polynomial, coefficient"),
149 ('A_1_0', "Axis 1 correction polynomial, coefficient"),
150 ('A_1_1', "Axis 1 correction polynomial, coefficient"),
151 ('A_1_2', "Axis 1 correction polynomial, coefficient"),
152 ('A_2_0', "Axis 1 correction polynomial, coefficient"),
153 ('A_2_1', "Axis 1 correction polynomial, coefficient"),
154 ('A_3_0', "Axis 1 correction polynomial, coefficient"),
155 ('B_ORDER', "Correction polynomial order, axis 2"),
156 ('B_0_0', "Axis 2 correction polynomial, coefficient"),
157 ('B_0_1', "Axis 2 correction polynomial, coefficient"),
158 ('B_0_2', "Axis 2 correction polynomial, coefficient"),
159 ('B_0_3', "Axis 2 correction polynomial, coefficient"),
160 ('B_1_0', "Axis 2 correction polynomial, coefficient"),
161 ('B_1_1', "Axis 2 correction polynomial, coefficient"),
162 ('B_1_2', "Axis 2 correction polynomial, coefficient"),
163 ('B_2_0', "Axis 2 correction polynomial, coefficient"),
164 ('B_2_1', "Axis 2 correction polynomial, coefficient"),
165 ('B_3_0', "Axis 2 correction polynomial, coefficient"),
166 ('AP_ORDER', "Inverse polynomial order, axis 1"),
167 ('AP_0_0', "Axis 1 inverse polynomial, coefficient"),
168 ('AP_0_1', "Axis 1 inverse polynomial, coefficient"),
169 ('AP_0_2', "Axis 1 inverse polynomial, coefficient"),
170 ('AP_1_0', "Axis 1 inverse polynomial, coefficient"),
171 ('AP_1_1', "Axis 1 inverse polynomial, coefficient"),
172 ('AP_2_0', "Axis 1 inverse polynomial, coefficient"),
173 ('BP_ORDER', "Inverse polynomial order, axis 2"),
174 ('BP_0_0', "Axis 2 inverse polynomial, coefficient"),
175 ('BP_0_1', "Axis 2 inverse polynomial, coefficient"),
176 ('BP_0_2', "Axis 2 inverse polynomial, coefficient"),
177 ('BP_1_0', "Axis 2 inverse polynomial, coefficient"),
178 ('BP_1_1', "Axis 2 inverse polynomial, coefficient"),
179 ('BP_2_0', "Axis 2 inverse polynomial, coefficient"),]
180
181
182 # Internal representation of Tuvikene et al FITS headers for plates
183 # See https://www.plate-archive.org/applause/wiki/fits-header-format-dr2/
184 WFPDB_TEMPLATE = MINIMAL_IMAGE_TEMPLATE+[
185 pyfits.Card(value="-------------------- Original data of observation"),
186 ("DATEORIG", "Original recorded date of the observation"),
187 ("TMS-ORIG", "Start of the observation (logs)"),
188 ("TME-ORIG", "End of the observation (logs)"),
189 ("TIMEFLAG", "Quality flag of the recorded observation time"),
190 ("RA-ORIG", "RA of plate center as given in source"),
191 ("DEC-ORIG", "Dec of plate center as given in source"),
192 ("EQ-ORIG", "Equinox of RA-ORIG and DEC-ORIG"),
193 ("COORFLAG", "Quality flag of the recorded coordinates"),
194 ("OBJECT", "Observed object or field"),
195 ("OBJTYPE", "Object type as in WFPDB"),
196 ("EXPTIME", " [s] Exposure time of the first exposure"),
197 ("NUMEXP", "Number of exposures"),
198 ]+_makeHeaderSequence(
199 "DATEOR%d", "Original recorded date of the %s exposure"
200 )+_makeHeaderSequence(
201 "TMS-OR%d", "Start of %s exposure (logs)"
202 )+_makeHeaderSequence(
203 "TME-OR%d", "End of %s exposure (logs)"
204 )+_makeHeaderSequence(
205 "OBJECT%d", "Object name for %s exposure"
206 )+_makeHeaderSequence(
207 "OBJTYP%d", "Object type of %s OBJECT"
208 )+_makeHeaderSequence(
209 "EXPTIM%d", " [s] Exposure time %s exposure")+[
210 ("OBSERVAT", "Observatory name"),
211 ("SITENAME", "Observatory site name."),
212 ("SITELONG", " [deg] East longitude of observatory"),
213 ("SITELAT", " [deg] Latitude of observatory"),
214 ("SITEELEV", " [m] Elevation of the observatory"),
215 ("TELESCOP", "Telescope name"),
216 ("OTA-NAME", "Designation of the optical tube assembly"),
217 ("OTA-DIAM", " [m] Clear aperture of the telescope"),
218 ("OTA-APER", " [m] Clear aperture of the telescope"),
219 ("FOCLEN", " [m] Focal length of the telescope"),
220 ("PLTSCALE", " [arcsec/mm] Plate scale of the OTA"),
221 ("INSTRUME", "Instrument name"),
222 ("DETNAM", "Detector name"),
223 ("METHOD", "Observation method as in WFPDB"),
224 ("FILTER", "Filter type"),
225 ("PRISM", "Objective prism used"),
226 ("PRISMANG", " [deg] Angle of the objective prism"),
227 ("DISPERS", " [Angstrom/mm] Dispersion"),
228 ("GRATING", "Fix this comment."),
229 ("FOCUS", "Focus value (from logbook)."),
230 ("TEMPERAT", "Air temperature (from logbook)"),
231 ("CALMNESS", "Calmness (seeing conditions), scale 1-5"),
232 ("SHARPNES", "Sharpness, scale 1-5"),
233 ("TRANSPAR", "Transparency, scale 1-5"),
234 ("SEEING", "Quantitative measure on the seeing"),
235 ("SKYCOND", "Notes on sky conditions (logs)"),
236 ("OBSERVER", "Observer name"),
237 ("OBSNOTES", "Observer notes (logs)"),
238 ("NOTES", "Miscellaneous notes found in the observation logbook"),
239
240 pyfits.Card(value="-------------------- Photographic plate"),
241 ("PLATENUM", "Plate number in logs"),
242 ("WFPDB-ID", "Plate identifier in WFPDB"),
243 ("SERIES", "Series or survey of plate"),
244 ("PLATESZ1", " [cm] Plate size along axis1"),
245 ("PLATESZ2", " [cm] Plate size along axis2"),
246 ("EMULSION", "Type of the photographic emulsion"),
247 ("DEVELOP", "Plate development (developer, time)"),
248 ("PQUALITY", "Quality of the plate"),
249 ("PLATNOTE", "Notes about the plate"),
250 ("PRE-PROC", "Processing applied to the plate before scanning"),
251
252 pyfits.Card(value="-------------------- Derived observation data"),
253 ("DATE-OBS", "UT date and time of obs. start"),
254 ]+_makeHeaderSequence(
255 "DT-OBS%d", "UT d/t of start of %s exposure")+[
256 ("DATE-AVG", "UT d/t mid-point of observation"),
257 ]+_makeHeaderSequence(
258 "DT-AVG%d", "UT d/t mid-point of %s exposure")+[
259 ("DATE-END", "UT d/t end of observation"),
260 ]+_makeHeaderSequence(
261 "DT-END%d", "UT d/t of end of %s exposure")+[
262 ("YEAR", "Julian year at start of obs"),
263 ]+_makeHeaderSequence(
264 "YEAR%d", "Julian year at start of %s obs")+[
265 ("YEAR-AVG", "Julian year at mid-point of obs"),
266 ]+_makeHeaderSequence(
267 "YR-AVG%d", "Julian year at mid-point of %s obs")+[
268 ("JD", "Julian date at start of obs"),
269 ]+_makeHeaderSequence(
270 "JD%d", "Julian date at start of %s obs")+[
271 ("JD-AVG", "Julian date at mid-point of obs")
272 ]+_makeHeaderSequence(
273 "JD-AVG%d", "Julian date at mid-point of %s obs")+[
274 ("JD-AVG", "Julian date at mid-point of obs"),
275 ]+_makeHeaderSequence(
276 "JD-AVG%d", "Julian date at mid-point of %s obs")+[
277 ("RA", "ICRS center of plate RA h:m:s"),
278 ("DEC", "ICRS center of plate Dec d:m:s"),
279 ("RA_DEG", "[deg] ICRS center of plate RA"),
280 ("DEC_DEG", "[deg] ICRS center of plate Dec"),
281 ]+_makeHeaderSequence(
282 "RA_DEG%d", " [deg] ICRS center RA %s obs"
283 )+_makeHeaderSequence(
284 "DEC_DE%d", " [deg] ICRS center DEC %s obs")+[
285 ("AIRMASS", "Airmass at mean epoch"),
286 ("HA", "Hour angle at mean epoch"),
287 ("ZD", "Zenith distance at mean epoch"),
288
289 pyfits.Card(value="-------------------- Scan details"),
290 ("SCANNER", "Scanner hardware used"),
291 ("SCANRES1", " [in-1] Scan resolution along axis 1"),
292 ("SCANRES2", " [in-1] Scan resolution along axis 2"),
293 ("PIXSIZE1", " [um] Pixel size along axis 1"),
294 ("PIXSIZE2", " [um] Pixel size along axis 2"),
295 ("SCANSOFT", "Scan software used"),
296 ("SCANGAM", "Scan gamma value"),
297 ("SCANFOC", "Scan focus"),
298 ("WEDGE", "Photometric step-wedge type"),
299 ("DATESCAN", "UT scan date and time"),
300 ("SCANAUTH", "Author of the scan"),
301 ("SCANNOTE", "Notes about the scan"),
302
303 pyfits.Card(value="-------------------- Data files"),
304 ("FILENAME", "Filename of this file"),
305 ("PID", "Persistent identifier for the plate"),
306 ]+_makeHeaderSequence(
307 "FN-SCN%d", "Filename of %s scan of this plate")+[
308 ("FN-WEDGE", "Filename of the wedge scan"),
309 ("FN-PRE", "Filename of the preview image"),
310 ("FN-COVER", "Filename of the envelope image"),
311 ("FN-LOGB", "Filename of the logbook image"),
312 ("ORIGIN", "Origin of this file"),
313 ("DATE", "File last changed"),
314 ("SVC-URI", "Where to get these files"),
315
316 ] + WCS_TEMPLATE + [
317 pyfits.Card(value="-------------------- Legal"),
318 ("LICENCE", "URI for conditions of use"),
319
320 pyfits.Card(value="-------------------- Other header cards"),]
321
322
323 _TEMPLATE_NAMES = [
324 ("minimal", MINIMAL_IMAGE_TEMPLATE),
325 ("wcs", WCS_TEMPLATE),
326 ("wfpdb", WFPDB_TEMPLATE),]
327
328
329 def registerTemplate(templateName, template):
330 """registers a named FITS header template.
331
332 Registering lets DaCHS figure out the template from a history entry
333 it leaves, so it's certainly a good idea to do that.
334
335 For templateName, use something containing a bit of your signature
336 (e.g., ariAncientPlate rather than just ancientPlate).
337 """
338 _TEMPLATE_NAMES.append((templateName, template))
339
340
341 def getTemplateForName(templateName):
342 """returns the FITS template sequence for templateName.
343
344 A NotFoundError is raised if no such template exists.
345 """
346 for name, template in _TEMPLATE_NAMES:
347 if name==templateName:
348 return template
349 raise base.NotFoundError(templateName, "FITS template",
350 "registered templates", hint="If you used a custom template,"
351 " have you called fitstricks.registerTemplate(name, template)"
352 " for it?")
353
354
355 def getNameForTemplate(template):
356 """returns the name under which the FITS template has been registered.
357 """
358 for name, namedTemplate in _TEMPLATE_NAMES:
359 if template is namedTemplate:
360 return name
361 raise base.NotFoundError("template "+str(id(template)),
362 "FITS template",
363 "registered templates", hint="If you used a custom template,"
364 " have you called fitstricks.registerTemplate(name, template)"
365 " for it?")
366
367
368 def getTemplateNameFromHistory(hdr):
369 """returns the template name used for generating hdr.
370
371 A ReportableError is raised if the info signature is missing.
372 """
373 for card in hdr["HISTORY"]:
374 mat = re.search(r"GAVO DaCHS template used: (\w+)", card)
375 if mat:
376 return mat.group(1)
377 raise base.ReportableError("DaCHS template signature not found.",
378 hint="This means that a function needed to figure out which"
379 " FITS template DaCHS used to generate that header, and no"
380 " such information was found in the Header's HISTORY cards."
381 " Either this file hasn't been written by DaCHS FITS templating"
382 " engine, or some intervening thing hosed the history.")
383
384
385 def _applyTemplate(hdr, template, values):
386 """helps makeHeaderFromTemplate.
387
388 Specifically, it moves items in values mentioned in template into
389 header in template's order. hdr and values are modified in that process.
390 """
391 for tp in template:
392 if isinstance(tp, pyfits.Card):
393 tp.value = values.pop(tp.keyword, tp.value)
394 hdr.append(tp, end=True)
395 else:
396 key, comment = tp
397
398 argKey = key
399 val = values.get(argKey)
400 if val is None:
401 argKey = argKey.replace("-", "_")
402 val = values.get(argKey)
403
404 if val is not None:
405 try:
406 hdr.append(pyfits.Card(key, val, comment), end=True)
407 except Exception as ex:
408 if hasattr(ex, "args") and isinstance(ex.args[0], str):
409 ex.args = ("While constructing card %s: %s"%(
410 key, ex.args[0]),)+ex.args[1:]
411 raise
412
413 values.pop(argKey, None)
414
415
416 def _copyMissingCards(newHdr, oldHdr):
417 """helps makeHeaderFromTemplate.
418
419 Specifically, it copies over all cards from oldHder to newHdr not yet
420 present there. It will also move over history and comment cards.
421
422 This will modify newHdr in place.
423 """
424 commentCs, historyCs = [], []
425
426 for card in oldHdr.cards:
427 if card.keyword=="COMMENT":
428 commentCs.append(card)
429 elif card.keyword=="HISTORY":
430 if not "GAVO DaCHS template used" in card.value:
431 historyCs.append(card)
432 elif card.keyword:
433 if card.keyword not in newHdr:
434 newHdr.append(card, end=True)
435
436 for card in historyCs:
437 newHdr.append(card, end=True)
438 newHdr.append(pyfits.Card(value=""), end=True)
439 for card in commentCs:
440 newHdr.append(card, end=True)
441
442
443 def makeHeaderFromTemplate(template, originalHeader=None, **values):
444 """returns a new pyfits.Header from template with values filled in.
445
446 template usually is the name of a template previously registered with
447 registerTemplate, or one of DaCHS predefined template names (currently,
448 minimal and wfpdb). In a pinch, you can also pass in an immediate
449 headers.
450
451 originalHeader can be a pre-existing header; the history and comment
452 cards are copied over from it, and if any of its other cards have not
453 yet been added to the header, they will be added in the order that they
454 apprear there.
455
456 values for which no template item is given are added in random order
457 after the template unless an originalHeader is passed. In that case,
458 they are assumed to originate there and are ignored.
459 """
460 values = values.copy()
461 hdr = pyfits.Header()
462
463 if isinstance(template, str):
464 templateName = template
465 template = getTemplateForName(templateName)
466 else:
467 try:
468 templateName = getNameForTemplate(template)
469 except base.NotFoundError:
470 base.ui.notifyWarning("Using anonymous FITS template.")
471 templateName = "anonymous"
472
473 _applyTemplate(hdr, template, values)
474
475 if originalHeader:
476 _copyMissingCards(hdr, originalHeader)
477 elif values:
478 base.ui.notifyWarning("The following values were left after"
479 " applying a FITS template and will be added in random order: %s"%
480 (", ").join(list(values.keys())))
481 for key, value in values.items():
482 hdr.append(pyfits.Card(key, value), end=True)
483
484
485 hdr.add_history("GAVO DaCHS template used: "+templateName)
486 return hdr
487
488
489 def updateTemplatedHeader(hdr, templateName=None, **kwargs):
490 """return hdr updated with kwargs.
491
492 hdr is assumed to have been created with makeHeaderFromTemplate
493 and contain the template name in a history entry.
494
495 You can pass in templateName to keep DaCHS from trying to get things
496 from the header.
497
498 [It is probably better to use makeHeaderFromTemplate directly, passing
499 in the orginalHeader; that preserves the order of non-templated
500 headers].
501 """
502 if templateName is None:
503 templateName = getTemplateNameFromHistory(hdr)
504 template = getTemplateForName(templateName)
505
506 vals = getHeaderAsDict(hdr)
507 vals.update(kwargs)
508
509 res = makeHeaderFromTemplate(template, originalHeader=hdr, **vals)
510 return res