Debian Codegraph @

gavo/votable/paramval.py

raw
1 """
2 Serialisation of python values to VOTable PARAM values.
3
4 This has two aspects:
5
6 - Guessing proper VOTable type descriptors for python values
7 (use guessParamAttrsForValue)
8 - Serialising the python values to strings suitable for the PARAM.
9 (use serializeToParam)
10 """
11
12 #c Copyright 2008-2025, the GAVO project <[email protected]>
13 #c
14 #c This program is free software, covered by the GNU GPL. See the
15 #c COPYING file in the source distribution.
16
17
18 import functools
19 import datetime
20
21 from gavo import utils
22 from gavo.utils import pgsphere
23 from gavo.utils import serializers
24 from gavo.votable import coding
25 from gavo.votable import common
26 from gavo.votable import enc_tabledata
27 from gavo.votable import dec_tabledata
28 from gavo.votable.model import VOTable as V
29
30 from gavo.utils.dachstypes import (cast,
31 Any, Callable, Dict, Optional, Sequence)
32
33
34 _SEQUENCE_TYPES = (tuple, list)
35 _ATOMIC_TYPES = [
36 (int, {"datatype": "int"}),
37 (str, {"datatype": "char", "arraysize": "*"}),
38 (str, {"datatype": "unicodeChar", "arraysize": "*"}),
39 (float, {"datatype": "double"}),
40 (type(None), {"datatype": "double"}),
41 (complex, {"datatype": "doubleComplex"}),
42 (datetime.datetime, {"datatype": "char",
43 "arraysize": "20",
44 "xtype": "timestamp"}),
45 (datetime.date, {"datatype": "char",
46 "arraysize": "20",
47 "xtype": "dachs:DATE"}),
48 (pgsphere.SPoint, {"datatype": "double precision",
49 "arraysize": "2",
50 "xtype": "point"}),
51 (pgsphere.SCircle, {"datatype": "double precision",
52 "arraysize": "3",
53 "xtype": "circle"}),
54 (pgsphere.SPoly, {"datatype": "double precision",
55 "arraysize": "*",
56 "xtype": "polygon"}),]
57
58
59 def _combineArraysize(arraysize: str, attrs: Dict[str, str]) -> None:
60 """makes an arraysize attribute for a value with attrs.
61
62 This will in particular check that any existing arraysize in
63 attrs does not end with a star (as variable length is only allowed
64 in the slowest coordinate).
65
66 attrs is changed in place.
67 """
68 if "arraysize" in attrs:
69 if attrs["arraysize"].endswith("*"):
70 raise ValueError("Arrays of variable-length arrays are not allowed.")
71 attrs["arraysize"] = "%sx%s"%(attrs["arraysize"], arraysize)
72 else:
73 attrs["arraysize"] = arraysize
74
75
76 def _guessParamAttrsForSequence(pythonVal: Sequence) -> Dict[str, str]:
77 """helps guessParamAttrsForValue when the value is a sequence.
78 """
79 arraysize = str(len(pythonVal))
80 if len(pythonVal)==0:
81 return {
82 "datatype": "char",
83 "arraysize": "0"}
84
85 elementVal = pythonVal[0]
86
87 if isinstance(elementVal, str):
88 # special case as this may become common
89 attrs = {
90 "arraysize": "%sx%s"%(
91 max(len(s) for s in pythonVal), arraysize),
92 "datatype": "char"}
93
94 elif isinstance(elementVal, _SEQUENCE_TYPES):
95 attrs = _guessParamAttrsForSequence(elementVal)
96 _combineArraysize(arraysize, attrs)
97
98 else:
99 attrs = _guessParamAttrsForAtom(elementVal)
100 _combineArraysize(arraysize, attrs)
101
102 return attrs
103
104
105 def _guessParamAttrsForAtom(pythonVal: Any) -> Dict[str, str]:
106 """helps guessParamAttrsForValue when the value is atomic.
107
108 (where "atomic" includes string, and other things that actually
109 have non-1 arraysize in VOTable, such as most xtyped things).
110 """
111 retval = None
112
113 for type, attrs in _ATOMIC_TYPES:
114 if isinstance(pythonVal, type):
115 retval = attrs.copy()
116 break
117
118 if retval is None:
119 raise utils.NotFoundError(repr(pythonVal),
120 "VOTable type code for", "paramval.py predefined types")
121
122 if retval.get("datatype")=="int":
123 if abs(pythonVal)<32768:
124 retval["datatype"] = "short"
125 elif abs(pythonVal)>2147483647:
126 retval["datatype"] = "long"
127 return retval
128
129
130 def guessParamAttrsForValue(pythonVal: Any) -> Dict[str, str]:
131 """returns a dict of proposed attributes for a PARAM to keep pythonVal.
132
133 There is, of course, quite a bit of heuristics involved. For instance,
134 we assume sequences are homogeneous.
135 """
136 if isinstance(pythonVal, _SEQUENCE_TYPES):
137 return _guessParamAttrsForSequence(pythonVal)
138
139 else:
140 return _guessParamAttrsForAtom(pythonVal)
141
142
143 def _setNULLValue(param: V.PARAM, val: str) -> None:
144 """sets the null literal of param to val.
145 """
146 valEls = list(param.iterChildrenWithName("VALUES"))
147 if valEls:
148 valEls[0](null=val)
149 else:
150 param[V.VALUES(null=val)]
151
152
153 def _serializeNULL(param: V.PARAM) -> None:
154 """changes the VOTable PARAM param so it evaluates to NULL.
155 """
156 if param.datatype in ["float", "double"]:
157 element = "NaN "
158 elif param.datatype in ["unsignedByte", "short", "int", "long"]:
159 element = "99 "
160 _setNULLValue(param, element)
161 elif param.datatype in ["char", "unicodeChar"]:
162 element = "x"
163 _setNULLValue(param, element)
164 else:
165 raise ValueError("No recipe for %s null values"%param.datatype)
166
167 if param.isScalar():
168 param.value = element.strip()
169 elif param.hasVarLength():
170 param.value = ""
171 else:
172 # getLength is non-None because otherwise isScalar would have been
173 # True above.
174 param.value = (element*cast(int, param.getLength())).strip()
175
176
177 class PrimitiveAnnotatedColumn(dict):
178 """A stand-in for serializers.AnnotatedColumn.
179
180 We don't want to use the full thing as it's too fat here, and
181 getVOTSerializer doesn't have the original param anyway (as
182 it shouldn't, as that would break memoization).
183 """
184
185 class original:
186 stc = None
187 xtype = None
188
189 def __init__(self,
190 datatype: str,
191 arraysize: Optional[str],
192 xtype: Optional[str]) -> None:
193 dict.__init__(self, {
194 "nullvalue": "",
195 "name": "anonymous",
196 "dbtype": None,
197 "displayHint": {},
198 "note": None,
199 "ucd": None,
200 "utype": None,
201 "unit": None,
202 "description": None,
203 "id": None,
204 "datatype": datatype,
205 "arraysize": arraysize,
206 "xtype": xtype})
207
208
209 @functools.lru_cache(None)
210 def getVOTSerializer(
211 datatype: str,
212 arraysize: Optional[str],
213 xtype: Optional[str]) -> Callable[[Any], str]:
214 """returns a function serializing for values of params with the
215 attributes given.
216 """
217 lines = "\n".join([
218 "def codec(val):"]+
219 common.indentList([
220 "val = mapper(val)",
221 "tokens = []"]+
222 enc_tabledata.getLinesFor(V.PARAM(**locals()))+[
223 "return tokens[0]"], " "))
224
225 mapper = serializers.defaultMFRegistry.getMapper(
226 cast(serializers.AnnotatedColumn,
227 PrimitiveAnnotatedColumn(datatype, arraysize, xtype)))
228 env = enc_tabledata.getGlobals(None).copy()
229 env["mapper"] = mapper
230
231 return coding.buildCodec(lines, env)
232
233
234 def serializeToParam(param: V.PARAM, val: Optional[Any]) -> None:
235 """changes the VOTable PARAM param such that val is represented.
236
237 This may involve adding a null value.
238 """
239 if val is None:
240 _serializeNULL(param)
241 else:
242 param.value = getVOTSerializer(
243 param.datatype, param.arraysize, param.xtype)(val)
244
245
246 @functools.lru_cache(None)
247 def getVOTParser(
248 datatype: str,
249 arraysize: Optional[str],
250 xtype: Optional[Any]) -> Callable[[str], Any]:
251 """returns a function deserializing values in a param with datatype,
252 arraysize, and xtype.
253 """
254 p = V.PARAM(name="anonymous", datatype=datatype, arraysize=arraysize,
255 xtype=xtype)
256
257 lines = "\n".join([
258 "def codec(val):"]
259 +common.indentList([
260 "row = []"]
261 +dec_tabledata.getLinesFor(p)
262 +[
263 "return row[0]"], " "))
264
265 return coding.buildCodec(lines, dec_tabledata.getGlobals(None))