Debian Codegraph @

gavo/utils/fitstools.py

raw
1 """
2 Some utility functions to deal with FITS files.
3
4 It's unclear if pyfits coming from astropy is now threadsafe, but I'm hoping
5 it might be, so for now I'm making fitslock a no-op.
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 itertools
16 import re
17 import struct
18 import threading
19 import warnings
20 from contextlib import contextmanager
21
22 import numpy
23 # the following is the original import of pyfits, and only it should be used
24 from astropy.io import fits as pyfits # type:ignore
25 from astropy.utils.exceptions import AstropyDeprecationWarning # type:ignore
26 warnings.filterwarnings('ignore', category=AstropyDeprecationWarning)
27
28 from gavo.utils import codetricks
29 from gavo.utils import excs
30 from gavo.utils import ostricks
31
32 from gavo.utils.dachstypes import (Any, BinaryIO, Callable, Dict, Filename,
33 Generator, List, NDArray, Optional, StrOrBytes, StrToStrMap, Tuple)
34
35
36
37 _FITS_TABLE_LOCK = threading.RLock()
38
39 @contextmanager
40 def fitsLock():
41 _FITS_TABLE_LOCK.acquire()
42 try:
43 yield
44 finally:
45 _FITS_TABLE_LOCK.release()
46
47
48 CARD_SIZE = 80
49
50 END_CARD = b'END'+b' '*(CARD_SIZE-3)
51
52 FITS_BLOCK_SIZE = CARD_SIZE*36
53
54
55 class FITSError(Exception):
56 pass
57
58
59 # pyfits is a bit too liberal in throwing depreciation warnings. Filter them
60 # for now TODO: Figure out a system to check them now and then
61 warnings.filterwarnings('ignore', category=DeprecationWarning)
62 try:
63 warnings.filterwarnings('ignore', category=pyfits.PyfitsDeprecationWarning)
64 except AttributeError: # pyfits too old to produce these: Good.
65 pass
66
67 def padCard(input: StrOrBytes, length: int=CARD_SIZE) -> bytes:
68 """pads input (a string or bytes) with blanks until len(result)%80=0
69
70 The length keyword argument lets you adjust the "card size". Use
71 this to pad headers with length=FITS_BLOCK_SIZE
72
73 This always returns bytes.
74
75 >>> padCard("")
76 b''
77 >>> len(padCard(b"end"))
78 80
79 >>> len(padCard(b"whacko"*20))
80 160
81 >>> len(padCard("junkodumnk"*17, 27))%27
82 0
83 """
84 # This is like pyfits._pad, but I'd rather not depend on pyfits internals
85 # to much.
86 if isinstance(input, str):
87 input = input.encode("ascii")
88
89 l = len(input)
90 if not l%length:
91 return input
92 return input+b' '*(length-l%length)
93
94
95 def readHeaderBytes(f: BinaryIO, maxHeaderBlocks: int=80) -> bytes:
96 """returns the bytes belonging to a FITS header starting at the current
97 position within the file f.
98
99 If the header is not complete after reading maxHeaderBlocks blocks,
100 a FITSError is raised.
101 """
102 if hasattr(f, "encoding"):
103 raise IOError("fitstools only works with files opened in binary mode.")
104 parts = []
105
106 while True:
107 block = f.read(FITS_BLOCK_SIZE)
108 if not block:
109 raise EOFError('Premature end of file while reading header')
110
111 parts.append(block)
112 endCardPos = block.find(END_CARD)
113 if not endCardPos%CARD_SIZE:
114 break
115
116 if len(parts)>=maxHeaderBlocks:
117 raise FITSError("No end card found within %d blocks"%maxHeaderBlocks)
118 return b"".join(parts)
119
120
121 def readPrimaryHeaderQuick(f: BinaryIO, maxHeaderBlocks: int=80
122 ) -> pyfits.Header:
123 """returns a pyfits header for the primary hdu of the opened file f.
124
125 f must be opened in binary mode.
126
127 This is mostly code lifted from pyfits._File._readHDU. The way
128 that class is made, it's hard to use it with stuff from a gzipped
129 source, and that's why this function is here. It is used in the quick
130 mode of fits grammars.
131
132 This function is adapted from pyfits.
133 """
134 return pyfits.Header.fromstring(
135 readHeaderBytes(f, maxHeaderBlocks).decode("ascii", "ignore"))
136
137
138 def parseCards(aString: StrOrBytes) -> pyfits.Header:
139 """returns a list of pyfits Cards parsed from aString.
140
141 This will raise a ValueError if aString's length is not divisible by 80.
142 It may also raise pyfits errors for malformed cards.
143
144 Empty (i.e., all-whitespace) cards are ignored. If an END card is
145 encountered processing is aborted.
146 """
147 if isinstance(aString, str):
148 aString = aString.encode("ascii")
149
150 cards = []
151 if len(aString)%CARD_SIZE:
152 raise ValueError("parseCards argument has impossible length %s"%(
153 len(aString)))
154 for offset in range(0, len(aString), CARD_SIZE):
155 rawCard = aString[offset:offset+CARD_SIZE]
156 if rawCard==END_CARD:
157 break
158 if not rawCard.strip():
159 continue
160 cards.append(pyfits.Card().fromstring(rawCard.decode("ascii")))
161 return cards
162
163
164 def serializeHeader(hdr: pyfits.Header) -> bytes:
165 """returns the FITS serialization of a FITS header hdr.
166
167 This is always bytes.
168 """
169 parts = []
170 for card in hdr.cards:
171 r = card.image.encode("ascii")
172 assert not len(r)%CARD_SIZE
173 parts.append(r)
174 serForm = b"".join(parts)+padCard('END')
175 return padCard(serForm, length=FITS_BLOCK_SIZE)
176
177
178 def replacePrimaryHeader(
179 inputFile: BinaryIO,
180 newHeader: pyfits.Header,
181 targetFile: BinaryIO,
182 bufSize: int=100000) -> None:
183 """writes a FITS to targetFile having newHeader as the primary header,
184 where the rest of the data is taken from inputFile.
185
186 inputFile must be a file freshly opened for binary reading, targetFile one
187 freshly opened for binary writing.
188
189 This function is (among other things) a workaround for pyfits' misfeature of
190 unscaling scaled data in images when extending a header.
191 """
192 readPrimaryHeaderQuick(inputFile)
193 targetFile.write(serializeHeader(newHeader))
194 while True:
195 buf = inputFile.read(bufSize)
196 if not buf:
197 break
198 targetFile.write(buf)
199
200
201 def replacePrimaryHeaderInPlace(
202 fitsName: Filename, newHeader: pyfits.Header) -> None:
203 """replaces the primary header of fitsName with newHeader.
204
205 Doing this, it tries to minimize the amount of writing necessary; if
206 fitsName has enough space for newHeader, just the header is written,
207 and newHeader is extended if necessary. Only if newHeader is longer than
208 the existing header is fitsName actually copied. We try to be safe in
209 this case, only overwriting the old entry when the new data is safely
210 on disk.
211
212 gzipped inputs used to be supported here, but they aren't any more.
213 """
214 fitsName = str(fitsName)
215 if fitsName.endswith(".gz"):
216 raise NotImplementedError("replacePrimaryHeaderInPlace no longer"
217 " supports gzipped files.")
218
219 serializedNew = serializeHeader(newHeader)
220 with open(fitsName, "rb") as inputFile:
221 serializedOld = readHeaderBytes(inputFile)
222 inputFile.seek(0)
223
224 if len(serializedNew)<len(serializedOld):
225 # the new header is shorter than the old one; pad it with empty
226 # cards, then make sure the end card is in the last block
227 serializedNew = serializedNew+(
228 len(serializedOld)-len(serializedNew))*b" "
229 serializedNew = serializedNew.replace(END_CARD, b" "*len(END_CARD))
230 serializedNew = serializedNew[:-len(END_CARD)]+END_CARD
231 assert len(serializedNew)==len(serializedOld)
232
233 if len(serializedNew)==len(serializedOld):
234 # header lengths match (after possible padding); just write
235 # the new header and be done
236 with open(fitsName, "rb+") as targetFile:
237 targetFile.seek(0)
238 targetFile.write(serializedNew)
239
240 else:
241 # New header is longer than the old one, write the whole mess.
242 with ostricks.safeReplaced(fitsName) as targetFile:
243 replacePrimaryHeader(inputFile, newHeader, targetFile)
244
245
246 # enforced sequence of well-known keywords, and whether they are mandatory
247 STANDARD_CARD_SEQUENCE = [
248 ("SIMPLE", True),
249 ("BITPIX", True),
250 ("NAXIS", True),
251 ("NAXIS1", False),
252 ("NAXIS2", False),
253 ("NAXIS3", False),
254 ("NAXIS4", False),
255 ("EXTEND", False),
256 ("BZERO", False),
257 ("BSCALE", False),
258 ]
259
260 def _iterForcedPairs(seq: List) -> Generator:
261 """helps _enforceHeaderConstraints.
262 """
263 if seq is None:
264 return
265 for item in seq:
266 if isinstance(item, tuple):
267 yield item
268 else:
269 yield (item, False)
270
271
272 def _enforceHeaderConstraints(
273 cardList: List[pyfits.Card],
274 cardSequence: Optional[List[Tuple[str, bool]]]):
275 """returns a pyfits header containing the cards in cardList with FITS
276 sequence constraints satisfied.
277
278 This may raise a FITSError if mandatory cards are missing.
279
280 This will only work correctly for image FITSes with less than five
281 dimensions.
282
283 On cardSequence, see sortHeaders (except that this function always
284 requires sequences of pairs).
285 """
286 # I can't use pyfits.verify for this since cardList may not refer to
287 # a data set that's actually in memory
288 cardsAdded = set()
289 newCards: List[pyfits.Card] = []
290 cardDict = dict((card.keyword, card) for card in cardList)
291
292 for kw, mandatory in itertools.chain(
293 STANDARD_CARD_SEQUENCE, _iterForcedPairs(cardSequence or [])):
294 if isinstance(kw, pyfits.Card):
295 newCards.append(kw)
296 continue
297
298 if kw in cardsAdded:
299 continue
300
301 try:
302 newCards.append(cardDict[kw])
303 cardsAdded.add(kw)
304 except KeyError:
305 if mandatory:
306 raise FITSError("Mandatory card '%s' missing"%kw)
307
308 for card in cardList: # use cardList rather than cardDict to maintain
309 # cardList order
310 if card.keyword not in cardsAdded or card.keyword=='':
311 newCards.append(card)
312 return pyfits.Header(newCards)
313
314
315 def sortHeaders(header: pyfits.Header,
316 commentFilter: Optional[Callable[[str], bool]]=None,
317 historyFilter: Optional[Callable[[str], bool]]=None,
318 cardSequence: Optional[List[Tuple[str, bool]]]=None) -> pyfits.Header:
319 """returns a pyfits header with "real" cards first, then history, then
320 comment cards.
321
322 Blanks in the input are discarded, and one blank each is added in
323 between the sections of real cards, history and comments.
324
325 Header can be an iterable yielding Cards or a pyfits header.
326
327 Duplicate history or comment entries will be swallowed.
328
329 cardSequence, if present, is a sequence of (item, mandatory) pairs.
330 There item can be a card name, in which case the corresponding
331 card will be inserted at this point in the sequence. If mandatory is
332 True, a missing card is an error. Keywords already in
333 fitstools.STANDARD_CARD_SEQUENCE are ignored.
334
335 Item can also a pyfits.Card instance; it will be put into the header
336 as-is.
337
338 As a shortcut, a sequence item may be something else then a tuple;
339 it will then be combined with a False to make one.
340
341 These days, if you think you need this, have a look at
342 fitstricks.makeHeaderFromTemplate first.
343 """
344 commentCs, historyCs, realCs = [], [], []
345
346 for card in getattr(header, "cards", header):
347 if card.keyword=="COMMENT":
348 commentCs.append(card)
349 elif card.keyword=="HISTORY":
350 historyCs.append(card)
351 else:
352 realCs.append(card)
353
354 newCards = []
355 for card in realCs:
356 newCards.append(card)
357
358 historySeen = set()
359 if historyCs:
360 newCards.append(pyfits.Card(keyword=""))
361 for card in historyCs:
362 if historyFilter is None or historyFilter(card.value):
363 if card.value not in historySeen:
364 newCards.append(card)
365 historySeen.add(card.value)
366
367 commentsSeen = set()
368 if commentCs:
369 newCards.append(pyfits.Card(keyword=""))
370 for card in commentCs:
371 if commentFilter is None or commentFilter(card.value):
372 if card.value not in commentsSeen:
373 commentsSeen.add(card.value)
374 newCards.append(card)
375
376 return _enforceHeaderConstraints(newCards, cardSequence)
377
378
379 def openFits(fitsName: Filename) -> pyfits.HDUList:
380 """returns the hdus for fName.
381
382 This is simulating legacy pyfits behaviour in that it will use
383 memmap I/O if it thinks that works. You'll probably want to use
384 astropy directly these days if this gives you a headache.
385 """
386 hdus = pyfits.open(fitsName, memmap=True)
387 # memmapping will bomb later if data needs to be scaled, so we
388 # guess now if that's going to happen
389 if (hdus[0].header.get("BZERO", 0)!=0
390 or hdus[0].header.get("BSCALE", 1)!=1
391 or "BLANK" in hdus[0].header):
392 hdus.close()
393 hdus = pyfits.open(fitsName, memmap=False)
394 return hdus
395
396
397 def getAxisLengths(hdr: pyfits.Header) -> List[int]:
398 """returns a sequence of the lengths of the axes of a FITS image
399 described by hdr.
400 """
401 return [hdr["NAXIS%d"%i] for i in range(1, hdr["NAXIS"]+1)]
402
403
404 _FitsCuts = Tuple[Optional[float], ...]
405
406 def cutoutHeader(header: pyfits.Header, *cuts: _FitsCuts
407 ) -> Tuple[List, pyfits.Header]:
408 """returns a array slices and a new pyfits header reflecting cuts.
409
410 (see cutoutFits for what cuts is).
411 """
412 cutDict = dict((c[0], c[1:]) for c in cuts)
413 slices = []
414 newHeader = header.copy()
415
416 for index, length in enumerate(getAxisLengths(header)):
417 firstPix, lastPix = cutDict.get(index+1, (None, None))
418
419 if firstPix is None:
420 firstPix = 1
421 if lastPix is None:
422 lastPix = length
423 firstPix = min(max(1, firstPix), length)
424 lastPix = min(length, max(1, lastPix))
425
426 if (firstPix, lastPix)==(1, length):
427 slices.append(slice(None, None, None))
428 else:
429 firstPix -= 1
430 newAxisLength = lastPix-firstPix
431 if newAxisLength==0:
432 newAxisLength = 1
433 lastPix = firstPix+1
434 slices.append(slice(int(firstPix), int(lastPix), 1))
435
436 newHeader["NAXIS%d"%(index+1)] = newAxisLength
437 refpixKey = "CRPIX%d"%(index+1)
438 newHeader.set(refpixKey, newHeader[refpixKey]-firstPix)
439
440 return slices, newHeader
441
442
443 def cutoutFITS(hdu: pyfits.ImageHDU, *cuts: _FitsCuts) -> pyfits.ImageHDU:
444 """returns a cutout of hdu restricted to cuts.
445
446 hdu is a primary FITS hdu. cuts is a list of cut specs, each of which is
447 a triple (axis, lower, upper). axis is between 1 and naxis, lower and
448 upper a 1-based pixel coordinates of the limits, and "border" pixels
449 are included. Specifications outside of the image are legal and will
450 be cropped back. Open limits are supported via a specification of
451 None.
452
453 If an axis would vanish (i.e. length 0 or less), the function fudges
454 things such that the axis gets a length of 1.
455
456 axis is counted here in the FORTRAN/FITS sense, *not* in the C sense,
457 i.e., axis=1 cuts along NAXIS1, which is the *last* index in a numpy
458 array.
459
460 WCS CRPIXes in hdu's header will be updated. Axes and specified will
461 not be touched. It is an error to specify cuts for an axis twice
462 (behaviour is undefined).
463
464 Note that this will lose all extensions the original FITS file might have
465 had.
466 """
467 slices, newHeader = cutoutHeader(hdu.header, *cuts)
468 slices.reverse()
469 newHDU = hdu.__class__(data=hdu.data[tuple(slices)].copy(order='C'),
470 header=newHeader)
471 # Fix astropy 1.3 foulup
472 if "BZERO" in newHeader:
473 newHDU.header["BZERO"] = newHeader["BZERO"]
474 if "BSCALE" in newHeader:
475 newHDU.header["BSCALE"] = newHeader["BSCALE"]
476
477 return newHDU
478
479
480 def shrinkWCSHeader(oldHeader: pyfits.Header, factor: float) -> pyfits.Header:
481 """returns a FITS header suitable for a shrunken version of the image
482 described by oldHeader.
483
484 This only works for 2d images, scale must be an integer>1. The function
485 assumes no "fractional" pixels are handled, i.e, remainders in divisions
486 with factors are discarded. It is thus a companion for
487 iterScaledRows.
488
489 Note that oldHeader must be an actual pyfits header instance; a dictionary
490 will not do.
491
492 This is a pretty straight port of wcstools's imutil.c#ShrinkFITSHeader,
493 except we clear BZERO and BSCALE and set BITPIX to -32 (float array)
494 under the assumption that in the returned image, 32-bit floats are used.
495 """
496 assert oldHeader["NAXIS"]==2
497
498 factor = int(factor)
499 newHeader = oldHeader.copy()
500 newHeader.set("SIMPLE", True,"GAVO DaCHS, %s"%datetime.datetime.utcnow())
501 newHeader["NAXIS1"] = oldHeader["NAXIS1"]//factor
502 newHeader["NAXIS2"] = oldHeader["NAXIS2"]//factor
503 newHeader["BITPIX"] = -32
504
505 try:
506 ffac = float(factor)
507 newHeader["CRPIX1"] = oldHeader["CRPIX1"]/ffac+0.5
508 newHeader["CRPIX2"] = oldHeader["CRPIX2"]/ffac+0.5
509 for key in ("CDELT1", "CDELT2",
510 "CD1_1", "CD2_1", "CD1_2", "CD2_2"):
511 if key in oldHeader:
512 newHeader[key] = oldHeader[key]*ffac
513 except KeyError: # no WCS, we're fine either way
514 pass
515
516 newHeader.set("IMSHRINK", "Image scaled down %s-fold by DaCHS"%factor)
517
518 for hField in ["BZERO", "BSCALE"]:
519 if hField in newHeader:
520 del newHeader[hField]
521
522 return newHeader
523
524
525 NUM_CODE = {
526 8: 'uint8',
527 16: '>i2',
528 32: '>i4',
529 64: '>i8',
530 -32: '>f4',
531 -64: '>f8'}
532
533 def _makeDecoder(hdr: pyfits.Header) -> Callable[[BinaryIO], NDArray]:
534 """returns a decoder for the rows of FITS primary image data.
535
536 The decoder is called with an open file and returns the next row.
537 You need to keep track of the total number of rows yourself.
538 """
539 numType = NUM_CODE[hdr["BITPIX"]]
540 rowLength = hdr["NAXIS1"]
541 nBytes = abs(rowLength*hdr["BITPIX"]//8)
542
543 bzero, bscale = hdr.get("BZERO", 0), hdr.get("BSCALE", 1)
544 if bzero!=0 or bscale!=1:
545 def read(f: BinaryIO) -> NDArray:
546 return numpy.asarray(
547 numpy.frombuffer(f.read(nBytes), numType, rowLength),
548 'float32')*bscale+bzero
549 else:
550 def read(f: BinaryIO) -> NDArray: #noflake: conditional definition
551 return numpy.frombuffer(f.read(nBytes), numType, rowLength)
552
553 return read
554
555
556 def iterFITSRows(hdr: pyfits.Header, f: BinaryIO
557 ) -> Generator[NDArray, None, None]:
558 """iterates over the rows of a FITS (primary) image.
559
560 You pass in a FITS header and a file positioned to the start of
561 the image data.
562
563 What's returned are 1d numpy arrays of the datatype implied by bitpix. The
564 function understands only very basic FITSes (BSCALE and BZERO are known,
565 though, and lead to floats arrays).
566
567 We do this ourselves since pyfits may pull in the whole thing or at least
568 mmaps it; both are not attractive when I want to stream-process large
569 images.
570 """
571 decoder = _makeDecoder(hdr)
572 for col in range(hdr["NAXIS2"]):
573 yield decoder(f)
574
575
576 def _iterSetupFast(inFile: BinaryIO, hdr: pyfits.Header
577 ) -> Tuple[pyfits.Header, Generator[NDArray, None, None]]:
578 """helps iterScaledRows for the case of a simple, real-file FITS.
579 """
580 if hdr is None:
581 hdr = readPrimaryHeaderQuick(inFile)
582 if hdr["NAXIS"]==0:
583 # presumably a compressed FITS
584 return _iterSetupCompatible(inFile, hdr)
585 return hdr, iterFITSRows(hdr, inFile)
586
587
588 def fixImageExtind(hdus: List, extInd: int) -> int:
589 """returns the index of a compressed image HDU if it immediately
590 follows extInd.
591
592 If hdus[extInd] is a CompImageHDU itself, this will return extInd
593 unchanged.
594 """
595 if isinstance(hdus[extInd], pyfits.CompImageHDU):
596 return extInd
597 try:
598 if isinstance(hdus[extInd+1], pyfits.CompImageHDU):
599 return extInd+1
600 except IndexError:
601 # no extension following, least of all a CompImageHDU. Fall through
602 pass
603 return extInd
604
605
606 def _iterSetupCompatible(
607 inFile: BinaryIO, hdr: pyfits.Header, extInd: int=0
608 ) -> Tuple[pyfits.Header, Generator[NDArray, None, None]]:
609 """helps iterScaledRows for when _iterSetupFast will not work.
610
611 Using extInd, you can select a different extension. extInd=0
612 will automatically select extension 1 if that's a compressed image
613 HDU.
614 """
615 hdus = pyfits.open(inFile)
616 extInd = fixImageExtind(hdus, extInd)
617
618 def iterRows():
619 for row in hdus[extInd].data[:,:]:
620 yield row
621
622 return hdus[extInd].header, iterRows()
623
624
625 def iterScaledRows(
626 inFile: BinaryIO,
627 factor: Optional[float]=None,
628 destSize: Optional[int]=None,
629 hdr: Optional[pyfits.Header]=None,
630 slow: bool=False,
631 extInd: int=0) -> Generator[NDArray, None, None]:
632 """iterates over numpy arrays of pixel rows within the open FITS
633 stream inFile scaled by it integer in factor.
634
635 The arrays are always float32, regardless of the input. When the
636 image size is not a multiple of factor, border pixels are discarded.
637
638 A FITS header for this data can be obtained using shrinkWCSHeader.
639
640 You can pass in either a factor the file is to be scaled down, or
641 an approximate size desired. If both are given, factor takes precedence,
642 if none is given, it's an error.
643
644 If you pass in hdr, it will not be read from inFile; the function then
645 expects the file pointer to point to the start of the first data block.
646 Use this if you've already read the header of a non-seekable FITS.
647
648 extInd lets you select a different extension. extInd=0 means the first
649 image HDU, which may be in extension 1 for compressed images.
650
651 iterScaledRows will try to use a hand-hacked interface guaranteed to
652 stream. This only works for plain, 2D-FITSes from real files.
653 iterScaledRows normally notices when it should fall back to
654 pyfits code, but if it doesn't you can pass slow=True.
655 """
656 if hasattr(inFile, "read") and not slow and extInd==0:
657 hdr, rows = _iterSetupFast(inFile, hdr)
658 else:
659 hdr, rows = _iterSetupCompatible(inFile, hdr, extInd)
660
661 if factor is None:
662 if destSize is None:
663 raise excs.DataError("iterScaledRows needs either factor or destSize.")
664 size = max(hdr["NAXIS1"], hdr["NAXIS2"])
665 factor = max(1, size//destSize+1)
666
667 factor = int(factor)
668 assert factor>0
669
670 rowLength = hdr["NAXIS1"]
671 destRowLength = rowLength//factor
672 summedInds = list(range(factor))
673
674 for index in range(hdr["NAXIS2"]//factor):
675 newRow = numpy.zeros((rowLength,), 'float32')
676 for i in summedInds:
677 try:
678 newRow += next(rows)
679 except StopIteration:
680 break
681 newRow /= factor
682
683 # horizontal scaling via reshaping to a matrix and then summing over
684 # its columns...
685 newRow = newRow[:destRowLength*factor]
686 # mypy 1.0.1 type inference bad
687 yield sum(numpy.transpose( # type: ignore
688 (newRow/factor).reshape((destRowLength, factor))))
689
690
691 def iterScaledBytes(
692 inFileName: Filename,
693 factor: float,
694 extraCards: StrToStrMap={}) -> Generator[bytes, None, None]:
695 """iterates over the bytes for a simple FITS file generated by scaling
696 down the 2D image inFileName by factor.
697
698 factor must be an integer between 1 and something reasonable.
699
700 This function acquires the FITS lock itself.
701 """
702 with fitsLock():
703 with open(inFileName, "rb") as f:
704 oldHdr = readPrimaryHeaderQuick(f)
705 newHdr = shrinkWCSHeader(oldHdr, factor)
706 newHdr.update(extraCards)
707 yield serializeHeader(newHdr)
708
709 for row in iterScaledRows(f, factor, hdr=oldHdr):
710 # Unfortunately, numpy's byte swapping for floats is broken in
711 # many wide-spread revisions. So, we cannot do the fast
712 # yield row.newbyteorder(">").tostring()
713 # but rather, for now, have to try the slow:
714 yield struct.pack("!%df"%len(row), *row)
715
716
717 def headerFromDict(d: StrToStrMap) -> pyfits.Header:
718 """returns a primary header sporting the key/value pairs given in the
719 dictionary d.
720
721 In all likelihood, this header will *not* work properly as a primary
722 header because, e.g., there are certain rules on the sequence of
723 header items. fitstricks.copyFields can make a valid header out
724 of what's returned here.
725
726 keys mapped to None are skipped, i.e., you have to do nullvalue handling
727 yourself.
728 """
729 hdr = pyfits.PrimaryHDU().header
730 for key, value in d.items():
731 if value is not None:
732 hdr.set(key, value)
733 return hdr
734
735
736 class WCSAxis(object):
737 """represents a single 1D WCS axis and allows easy metadata discovery.
738
739 You'll usually use the fromHeader constructor.
740
741 The idea of using this rather than astropy.wcs or similar is that this is
742 simple and robust. It doesn't know many of the finer points of WCS,
743 though, and in particular it's 1D only.
744
745 However, for the purposes of cutouts it probably should do for the
746 overwhelming majority of non-spatial FITS axes.
747
748 The default pixel coordinates are handled in the FITS sense here,
749 i.e., the first pixel has the index 1. Three are methods that have
750 pix0 in their names; these assume 0-based arrays. All the transforms
751 return Nones unchanged.
752
753 To retrieve the metadata shoved in, use the name, crval, crpix, cdelt,
754 ctype, cunit, and axisLength attributes.
755 """
756 def __init__(self,
757 name: str,
758 crval: float,
759 crpix: float,
760 cdelt: float,
761 ctype: str="UNKNOWN",
762 cunit: Optional[str]="",
763 axisLength: int=1):
764 assert cdelt!=0
765 self.crval, self.crpix, self.cdelt = crval, crpix, cdelt
766 self.ctype, self.cunit, self.axisLength = ctype, cunit, axisLength
767 self.name = name
768
769 def pixToPhys(self, pixCoo: float) -> float:
770 """returns the physical value for a 1-based pixel coordinate.
771 """
772 if pixCoo is None:
773 return None
774 return self.crval+(pixCoo-self.crpix)*self.cdelt
775
776 def pix0ToPhys(self, pix0Coo: float) -> float:
777 """returns the physical value for a 0-based pixel coordinate.
778 """
779 if pix0Coo is None:
780 return None
781 return self.pixToPhys(pix0Coo+1)
782
783 def physToPix(self, physCoo: float) -> float:
784 """returns a 1-based pixel coordinate for a physical value.
785 """
786 if physCoo is None:
787 return None
788 return (physCoo-self.crval)/self.cdelt+self.crpix
789
790 def physToPix0(self, physCoo: float) -> float:
791 """returns a 0-based pixel coordinate for a physical value.
792 """
793 if physCoo is None:
794 return None
795 return self.physToPix(physCoo)-1
796
797 def getLimits(self) -> Tuple[float, float]:
798 """returns the minimal and maximal physical values this axis
799 takes within the image.
800 """
801 limits = self.pixToPhys(1), self.pixToPhys(self.axisLength)
802 return min(limits), max(limits)
803
804 @staticmethod
805 def _bailIfInseparable(header, axisIndex):
806 """raises a ValueError if axisIndex appears to be entangled
807 with another axis in header.
808 """
809 headerPattern = re.compile(rf"(PC|CD){axisIndex}_(\d)")
810 entangledWith = {int(headerPattern.match(key).group(2))
811 for key in header
812 if headerPattern.match(key)}
813 if entangledWith and entangledWith!={axisIndex}:
814 raise ValueError("FITS axis %s appears not separable. WCSAxis"
815 " cannot handle this."%axisIndex)
816
817 @classmethod
818 def fromHeader(cls,
819 header: pyfits.Header,
820 axisIndex: int,
821 forceSeparable: bool=False) -> 'WCSAxis':
822 """returns a WCSAxis for the specified axis in header.
823
824 If the axis is mentioned in a transformation matrix (CD or PC),
825 a ValueError is raised; this is strictly for 1D coordinates.
826
827 The axisIndex is 1-based; to get a transform for the axis described
828 by CTYPE1, pass 1 here.
829 """
830 if not forceSeparable:
831 cls._bailIfInseparable(header, axisIndex)
832
833 def get(key, default):
834 return header.get("%s%d"%(key, axisIndex), default)
835
836 guessedName = get("CNAME", "").strip()
837 if not guessedName:
838 guessedName = get("CTYPE", "").split("-", 1)[0].strip()
839 if not guessedName or guessedName=="UNKNOWN":
840 guessedName = "COO"
841
842 guessedName = "%s_%d"%(guessedName, axisIndex)
843
844 return cls(guessedName,
845 get("CRVAL", 0), get("CRPIX", 0), get("CDELT", 1),
846 get("CTYPE", "UNKNOWN").strip(),
847 get("CUNIT", "").strip() or None,
848 get("NAXIS", 1))
849
850
851 # WCSAxis.fromHeader wrapper for rmkfuncs
852 @codetricks.document
853 def getWCSAxis(
854 header: pyfits.Header,
855 axisIndex: int,
856 forceSeparable: bool=False) -> WCSAxis:
857 """returns a WCSAxis instance from an axis index and a FITS header.
858
859 If the axis is mentioned in a transformation matrix (CD or PC),
860 a ``ValueError`` is raised (use ``forceSeparable`` to override).
861
862 The ``axisIndex`` is 1-based; to get a transform for the axis described
863 by CTYPE1, pass 1 here.
864
865 The object returned has methods like ``pixToPhys``, ``physToPix`` (and their
866 ``pix0`` brethren), and ``getLimits``.
867
868 Note that at this point WCSAxis only supports linear transforms (it's
869 a DaCHS-specific implementation). We'll extend it on request.
870 """
871 return WCSAxis.fromHeader(header, axisIndex, forceSeparable)
872
873
874 class ESODescriptorsError(excs.SourceParseError):
875 """is raised when something goes wrong while parsing ESO descriptors.
876 """
877
878
879 def _makeNamed(name: str, re: str) -> str:
880 # A helper to construct REs for the ESO parser.
881 return "(?P<%s>%s)"%(name, re)
882
883
884 def _makeTypeScanner(
885 typeName: str,
886 literalRE: re.Pattern,
887 constructor: Callable[[str], Any]):
888 """returns a scanner method for the _ESODescriptorsParser.
889
890 This is a helper method for building the class; typeName
891 must be the same as the name in _scan_name. constructor is
892 a function that turns string literals into objects of the desired
893 type.
894 """
895 def scanner(self) -> str:
896 mat = literalRE.match(self.data, self.curPos)
897 if not mat:
898 raise ValueError("Expected a %s here"%typeName)
899 self.curPos = mat.end()
900
901 self.curCol.append(constructor(mat.group()))
902 self.yetToRead -= 1
903 if self.yetToRead==0:
904 return "harvest"
905 else:
906 return typeName
907
908 return scanner
909
910
911 class _ESODescriptorsParser:
912 """an ad-hoc parser for ESO's descriptors.
913
914 These are sometimes in FITS files produced by MIDAS. What I'm pretending
915 to parse here is the contatenation of the cards' values without the
916 boundaries.
917
918 The parse is happening at construction time, after which you fetch the result
919 in the result attribute.
920
921 I'm adhoccing this. If someone digs up the docs on what the actual
922 grammar is, I'll do it properly.
923 """
924
925 stringPat = "'[^']*'"
926 intPat = r"-?\d+"
927 floatPat = r"-?\d+\.\d+E[+-]\d+"
928 white = r"\s+"
929 nextToken = r"\s*"
930 headerSep = nextToken+','+nextToken
931
932 headerRE = re.compile(nextToken
933 +_makeNamed("colName", stringPat)+headerSep
934 +_makeNamed("typeCode", stringPat)+headerSep
935 +_makeNamed("startInd", intPat)+headerSep
936 +_makeNamed("endInd", intPat)+headerSep
937 +stringPat+headerSep
938 +stringPat+headerSep
939 +stringPat)
940 floatRE = re.compile(nextToken+floatPat)
941 integerRE = re.compile(nextToken+intPat)
942
943 def __init__(self, data: str):
944 self.data, state = data, "header"
945 self.result: Dict[str, List[float]] = {}
946 self.curPos:int = 0
947 while state!="end":
948 try:
949 state = getattr(self, "_scan_"+state)()
950 except Exception as msg:
951 raise ESODescriptorsError(str(msg),
952 location="character %s"%self.curPos,
953 offending=repr(self.data[self.curPos:self.curPos+20]))
954
955 @classmethod
956 def fromFITSHeader(cls, hdr: pyfits.Header) -> '_ESODescriptorsParser':
957 """returns a parser from the data in the pyfits hdr.
958 """
959 descLines, collecting = [], False
960
961 for card in hdr.cards:
962 if card.keyword=="HISTORY":
963 if " ESO-DESCRIPTORS END" in card.value:
964 collecting = False
965 if collecting:
966 descLines.append(card.value)
967 if " ESO-DESCRIPTORS START" in card.value:
968 collecting = True
969
970 return cls("\n".join(descLines))
971
972 def _scan_header(self) -> str:
973 """reads the next descriptor header and returns a type name for it.
974 """
975 mat = self.headerRE.match(self.data, self.curPos)
976 if not mat:
977 if not self.data[self.curPos:].strip():
978 return "end"
979 else:
980 raise ValueError("Could not find next header")
981
982 self.curPos = mat.end()
983 self.curCol: List[float] = []
984 self.curColName = mat.group("colName")[1:-1]
985 self.yetToRead = int(mat.group("endInd"))-int(mat.group("startInd"))+1
986
987 if mat.group("typeCode")[1:-1].startswith("R"):
988 return "float"
989 elif mat.group("typeCode")[1:-1].startswith("I"):
990 return "integer"
991 else:
992 raise ValueError("Unknown type code %s"%mat.group("typeCode"))
993
994 def _scan_harvest(self):
995 """enter a parsed column into result and prepare for the next column.
996 """
997 self.result[self.curColName] = self.curCol
998 del self.curCol
999 del self.curColName
1000 del self.yetToRead
1001 return "header"
1002
1003 _scan_float = _makeTypeScanner("float", floatRE, float)
1004 _scan_integer = _makeTypeScanner("integer", integerRE, int)
1005
1006 del _makeTypeScanner
1007
1008
1009 def parseESODescriptors(hdr: pyfits.Header) -> Dict[str, List[float]]:
1010 """returns parsed ESO descriptors from a pyfits header hdr.
1011
1012 ESO descriptors are data columns stuck into FITS history lines.
1013 They were produced by MIDAS. This implementation was made
1014 without actual documentation, is largely based on conjecture,
1015 and is certainly incomplete.
1016
1017 What's returned is a dictionary mapping column keywords to lists of
1018 column values.
1019 """
1020 return _ESODescriptorsParser.fromFITSHeader(hdr).result
1021
1022
1023 if __name__=="__main__": # pragma: no cover
1024 import doctest
1025 doctest.testmod()