Debian Codegraph @

gavo/grammars/fitstablegrammar.py

raw
1 """
2 A grammar taking rows from a FITS table.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import itertools
12
13 from gavo import base
14 from gavo.grammars import common
15
16 from astropy import table
17
18
19 class FITSTableIterator(common.RowIterator):
20 """The row iterator for FITSTableGrammars.
21 """
22 def _iterRows(self):
23 data = table.Table.read(
24 self.sourceToken,
25 format="fits",
26 hdu=self.grammar.hdu)
27 names = [n for n in data.dtype.names]
28
29 if self.grammar.lowerKeys:
30 names = [n.lower() for n in names]
31
32 mask = data.mask
33 if mask is None:
34 mask = itertools.cycle([[False]*len(names)])
35
36 for raw_row, mask in zip(data, mask):
37 row = {}
38 for i in range(len(raw_row)):
39 val = raw_row[i]
40 if mask[i]:
41 row[names[i]] = None
42 elif self.grammar.nanIsNULL and val!=val:
43 row[names[i]] = None
44 else:
45 row[names[i]] = val
46
47 yield row
48
49
50 class FITSTableGrammar(common.Grammar):
51 """A grammar parsing from FITS tables.
52
53 fitsTableGrammar result in typed records, i.e., values normally come
54 in the types they are supposed to have. Of course, that won't work
55 for datetimes, STC-S regions, and the like.
56
57 The keys of the result dictionaries are simpily the names given in
58 the FITS.
59 """
60 name_ = "fitsTableGrammar"
61
62 _hduIndex = base.IntAttribute("hdu", default=1,
63 description="Take the data from this extension (primary=0)."
64 " Tabular data typically resides in the first extension.")
65 _lowerKeys = base.BooleanAttribute("lowerKeys", default=False,
66 description="Convert column names to lower case when building"
67 " the rawdict.")
68 _mapNaN = base.BooleanAttribute("nanIsNULL", default=False,
69 description="Map NaN floats to NULL when building the rawdict.")
70
71 rowIterator = FITSTableIterator