Debian Codegraph @

gavo/votable/simple.py

raw
1 """
2 A simplified API to single-table VOTables.
3
4 The basic idea is: open(...) -> (table, metadata),
5
6 where table is a numpy array.
7 """
8
9 #c Copyright 2008-2025, the GAVO project <[email protected]>
10 #c
11 #c This program is free software, covered by the GNU GPL. See the
12 #c COPYING file in the source distribution.
13
14
15 import io
16
17 try:
18 import numpy
19
20 # map from VOTable datatypes to numpy type designators:
21 numpyType = {
22 "short": numpy.int16,
23 "int": numpy.int32,
24 "long": numpy.int64,
25 "float": numpy.float32,
26 "double": numpy.float64,
27 "boolean": numpy.bool_,
28 "char": numpy.str_,
29 "floatComplex": numpy.complex64,
30 "doubleComplex": numpy.complex128,
31 "unsignedByte": numpy.uint8,
32 "unicodeChar": numpy.str_
33 }
34 except ImportError:
35 # keep numpy optional
36 pass
37
38 from gavo.votable import votparse
39 from gavo.votable import tablewriter
40 from gavo.votable import tableparser
41 from gavo.votable.model import VOTable as V
42
43 from gavo.utils.dachstypes import (cast,
44 Any, Dict, Iterable, Iterator, List, Tuple, Union)
45
46
47 class TableMetadata:
48 """Metadata for a VOTable table instance, i.e., column definitions, groups,
49 etc.
50
51 These are constructed with a VOTable TABLE instance and infos, a dictionary
52 mapping info names to lists of V.INFO items.
53 """
54 def __init__(self,
55 tableElement: V.TABLE,
56 infos: Dict[str, List[V.INFO]]) -> None:
57 self.votTable = tableElement
58 self.infos = infos
59 self.fields = list(tableElement.iterChildrenOfType(V.FIELD))
60
61 def __iter__(self) -> Iterator[V.FIELD]:
62 return iter(self.fields)
63
64 def __len__(self) -> int:
65 return len(self.fields)
66
67 def __getitem__(self, index: int) -> V.FIELD:
68 return self.fields[index]
69
70 def getFields(self) -> List[V.FIELD]:
71 return self.votTable.getFields()
72
73 def iterDicts(self, data: List[List[Any]]) -> Iterator[Dict[str, Any]]:
74 """iterates over data, but returns each row as a dict.
75
76 data is a result set as returned by load.
77 """
78 names = [f.name for f in self]
79 for row in data:
80 yield dict(list(zip(names, row)))
81
82
83 _NumpyDType = Union[
84 Tuple[str, Union[type, str], Tuple[int, ...] | int],
85 Tuple[str, type]]
86
87
88 def makeDtype(tableMetadata: TableMetadata, defaultStringLength: int = 20
89 ) -> List[_NumpyDType]:
90 """returns an record array datatype for a given table metadata.
91
92 defaultStringLength lets you specify a length for char(*) fields;
93 since makeDtype has no access to the tabular data and numpy insists on
94 having string length, DaCHS needs to guess here.
95
96 If this isn't fine-grained enough for you, you can always patch tableMetadata,
97 replacing * arraysizes with more appropriate values in individual cases.
98 """
99 dtypes: List[_NumpyDType] = []
100 seen = set()
101
102 for f in tableMetadata:
103 name = f.getDesignation()
104 while name in seen:
105 name = name+"_"
106 seen.add(name)
107 shape = f.getShape()
108 if shape is None:
109
110 # Perhaps stupidly, the library interprets 1D char array as
111 # atoms; numpy doesn't, so we have a special case.
112 if f.datatype=="char":
113 # as far as numpy recarrays are concerned; TODO: unicodeChar?
114 if f.arraysize=="*":
115 dtypes.append((name, "a", defaultStringLength))
116 elif f.arraysize is None:
117 dtypes.append((name, "a", 1))
118 else:
119 # anything weird leads to non-NULL shape
120 dtypes.append((name, "a", int(f.arraysize)))
121
122 else:
123 dtypes.append((name, numpyType[f.datatype]))
124
125 else:
126 dtypes.append((
127 name,
128 numpyType[f.datatype],
129 shape))
130 return dtypes
131
132
133 def load(source: io.BytesIO, raiseOnInvalid: bool = True
134 ) -> Tuple[List[List[Any]], TableMetadata] | Tuple[None, None]:
135 """returns (data, metadata) from the first table of a VOTable.
136
137 data is a list of records (as a list), metadata a TableMetadata instance.
138
139 source can be a string that is then interpreted as a local file name,
140 or it can be a file-like object.
141 """
142 if isinstance(source, str):
143 source = open(source)
144 infos: Dict[str, List[V.INFO]] = {}
145
146 # the following loop is a bit weird since we want to catch info items
147 # after the table and thus only exit the loop when the next table starts
148 # or the iterator is exhausted.
149 rows = None
150 for element in votparse.parse(source, {V.INFO}, raiseOnInvalid):
151 if isinstance(element, V.INFO):
152 infos.setdefault(element.name, []).append(element)
153 else:
154 # by votparse.parse's logic,element now is a tableparser.Rows instance
155 if rows is not None:
156 break
157 fields = TableMetadata(
158 cast(tableparser.Rows, element).tableDefinition, infos)
159 rows = list(element)
160 if rows is None: # No table included
161 return None, None
162 return rows, fields
163
164
165 def loads(stuff: bytes, raiseOnInvalid: bool = True
166 ) -> Tuple[List[List[Any]], TableMetadata] | Tuple[None, None]:
167 """returns data,metadata for a VOTable literal in stuff.
168 """
169 return load(io.BytesIO(stuff), raiseOnInvalid)
170
171
172 def save(
173 data: Iterable[Dict[str, Any]],
174 tableDef: V.TABLE, destF: io.BytesIO) -> None:
175 """saves (data, tableDef) in VOTable format to destF.
176
177 data is a sequence of tuples, tableDef a V.TABLE instance as, for example,
178 obtainable from metadata.votTable as returned by load. data must contain
179 type-right python values that match the table definition.
180
181 A load-save cycle loses all top-level and resource level metadata in the
182 simplified interface. Use the full interface if that hurts you.
183 """
184 root: V.VOTABLE = V.VOTABLE()[
185 V.RESOURCE[
186 tablewriter.DelayedTable(tableDef, data, V.BINARY)]]
187 tablewriter.write(root, destF)