Debian Codegraph @

gavo/stc/stcsast.py

raw
1 """
2 Transformation of STC-S CSTs to STC ASTs.
3
4 The central function here is buildTree; the rest of the module basically
5 provides the handler functions. All this is tied together in parseSTCS.
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 from gavo.stc import common
15 from gavo.stc import dm
16 from gavo.stc import stcs
17 from gavo.stc import syslib
18
19
20 def buildTree(tree, context, pathFunctions={}, nameFunctions={},
21 typeFunctions={}):
22 """traverses tree, calling functions on nodes.
23
24 pathFunctions is a dictionary mapping complete paths (i.e., tuples
25 of node labels) to handler functions, nameFunctions name a single
26 label and are called for nodes that don't match a pathFunction if
27 the last item of their paths is the label. Both of these currently
28 are not used. Instead, everything hinges on the fallback, which is
29 a node's type value (generated from the key words), matched against
30 typeFunctions.
31
32 The handler functions must be iterators. If they yield anything,
33 it must be key-value pairs.
34
35 All key-value pairs are collected in a dictionary that is then
36 returned. If value is a tuple, it is appended to the current value
37 for the key.
38
39 Context is an arbitrary object containing ancillary information for
40 building nodes. What's in there and what's not is up to the functions
41 and their callers.
42 """
43 resDict = {}
44 for path, node in stcs.iterNodes(tree):
45 if path in pathFunctions:
46 handler = pathFunctions[path]
47 elif path and path[-1] in nameFunctions:
48 handler = nameFunctions[path[-1]]
49 elif node.get("type") in typeFunctions:
50 handler = typeFunctions[node["type"]]
51 else: # No handler, ignore this node
52 continue
53 for res in handler(node, context):
54 k, v = res
55 if isinstance(v, tuple):
56 resDict.setdefault(k, []).extend(v)
57 else:
58 if k in resDict:
59 raise common.STCInternalError("Attempt to overwrite key '%s', old"
60 " value %s, new value %s (this should probably have been"
61 " a tuple)"%(k, resDict[k], v))
62 resDict[k] = v
63 return resDict
64
65
66 class GenericContext(object):
67 """is an object that can be used for context.
68
69 It simply exposes all its constructor arguments as attributes.
70 """
71 def __init__(self, **kwargs):
72 for k, v in kwargs.items():
73 setattr(self, k, v)
74
75
76 ############## Coordinate systems
77
78 def _makeRefpos(node):
79 refposName = node.get("refpos")
80 if refposName=="UNKNOWNRefPos":
81 refposName = None
82 return dm.RefPos(standardOrigin=refposName,
83 planetaryEphemeris=node.get("plEphemeris"))
84
85 def _buildRedshiftFrame(node, context):
86 yield "redshiftFrame", dm.RedshiftFrame(dopplerDef=node["dopplerdef"],
87 type=node["redshiftType"], refPos=_makeRefpos(node))
88
89 # Simple translations of reference frame names from STC-S to STC-X
90
91 _frameTrans = {
92 "GALACTIC": "GALACTIC_II",
93 "UNKNOWNFrame": None,}
94
95 def _buildSpaceFrame(node, context):
96 nDim, flavor = stcs.stcsFlavors[node["flavor"]]
97 frame = node["frame"]
98 frame = _frameTrans.get(frame, frame)
99 equinox = None
100 if node.get("equinox"):
101 if "." in node["equinox"]:
102 equinox = node["equinox"]
103 else: # allow J2000 and expand it to J2000.0
104 equinox = node["equinox"]+".0"
105 yield "spaceFrame", dm.SpaceFrame(refPos=_makeRefpos(node),
106 flavor=flavor, nDim=nDim, refFrame=frame, equinox=equinox)
107
108 def _buildSpectralFrame(node, context):
109 yield "spectralFrame", dm.SpectralFrame(
110 refPos=_makeRefpos(node))
111
112 def _buildTimeFrame(node, context):
113 ts = node.get("timescale")
114 if ts=="nil":
115 ts = None
116 yield "timeFrame", dm.TimeFrame(refPos=_makeRefpos(node),
117 timeScale=ts)
118
119 def getCoordSys(cst):
120 """returns constructor arguments for a CoordSys from an STC-S CST.
121 """
122 args = buildTree(cst, None, nameFunctions={
123 'redshift': _buildRedshiftFrame,
124 'space': _buildSpaceFrame,
125 'spectral': _buildSpectralFrame,
126 'time': _buildTimeFrame,
127 })
128 return "system", dm.CoordSys(**args)
129
130
131 ############## Coordinates and their intervals
132
133
134 def iterVectors(values, dim, spatial):
135 """iterates over dim-dimensional vectors made of values.
136
137 The function does not check if the last vector is actually complete.
138 """
139 if isinstance(values, common.ColRef):
140 yield values
141 return
142 if dim==1 and not spatial:
143 for v in values:
144 yield v
145 else:
146 for index in range(0, len(values), dim):
147 yield tuple(values[index:index+dim])
148
149
150 def _iterIntervals(coos, dim, spatial=False):
151 """iterates over pairs dim-dimensional vectors.
152
153 It will always return at least one empty (i.e., None, None) pair.
154 The last pair returned may be incomplete (specifying a start
155 value only, supposedly) but not empty.
156 """
157 first, startValue = True, None
158 for item in iterVectors(coos, dim, spatial):
159 if startValue is None:
160 if first:
161 first = False
162 startValue = item
163 else:
164 yield (startValue, item)
165 startValue = None
166 if startValue is None:
167 if first:
168 yield (None, None)
169 else:
170 yield (startValue, None)
171
172
173 def _makeWiggleValues(nDim, val, minItems=None, maxItems=None, spatial=False):
174 if val is None:
175 return
176 values = _makeCooValues(nDim, val, minItems, maxItems, spatial)
177 if not values:
178 return
179 if nDim>1: # might be error radii if all values are equal
180 if set([1])==set(len(set(v)) for v in values):
181 return dm.RadiusWiggle(radii=tuple(v[0] for v in values))
182 return dm.CooWiggle(values=values)
183
184
185 def _validateCoos(values, nDim, minItems, maxItems):
186 """makes sure values is valid a source of between minItems and maxItems
187 nDim-dimensional tuples.
188
189 minItems and maxItems may both be None to signify no limit.
190 """
191 if isinstance(values, common.GeometryColRef):
192 values.expectedLength = nDim
193 numItems = len(values)//nDim
194 if numItems*nDim!=len(values):
195 # special case: a *single* ColRef is good for anything (could be
196 # an array or something)
197 if len(values)==1 and isinstance(values[0], common.ColRef):
198 return
199 raise common.STCSParseError("%s is not valid input to create %d-dimensional"
200 " coordinates"%(values, nDim))
201 if minItems is not None and numItems<minItems:
202 raise common.STCSParseError("Expected at least %d coordinates in %s."%(
203 minItems, values))
204 if maxItems is not None and numItems>maxItems:
205 raise common.STCValueError(
206 "Expected not more than %d coordinates in %s."%(maxItems, values))
207
208
209 def _makeCooValues(nDim, values, minItems=None, maxItems=None, spatial=False):
210 """returns a list of nDim-Tuples made up of values.
211
212 If values does not contain an integral multiple of nDim items,
213 the function will raise an STCSParseError. You can also optionally
214 give a minimally or maximally expected number of tuples. If the
215 constraints are violated, again an STCSParseError is raised.
216
217 If spatial is true, tuples will be returned even for 1D data.
218 """
219 if values is None:
220 if minItems:
221 raise common.STCSParseError("Expected at least %s coordinate items but"
222 " found none."%minItems)
223 else:
224 return
225 _validateCoos(values, nDim, minItems, maxItems)
226 return tuple(v for v in iterVectors(values, nDim, spatial))
227
228
229 def _addUnitPlain(args, node, frame):
230 args["unit"] = node.get("unit")
231
232
233 def _addUnitRedshift(args, node, frame):
234 unit = node.get("unit", [None])
235 assert isinstance(unit, list), "not a list"
236 unit = unit[0]
237
238 if unit=="nil":
239 args["unit"] = ""
240 args["velTimeUnit"] = None
241 elif unit:
242 parts = unit.split("/")
243 if len(parts)!=2:
244 raise common.STCSParseError("'%s' is not a valid unit for redshifts"%unit)
245 args["unit"] = parts[0]
246 args["velTimeUnit"] = parts[1]
247
248
249 def _mogrifySpaceUnit(unit, nDim):
250 if unit:
251 parts = unit.split()
252 if len(parts)==nDim:
253 return tuple(parts)
254 elif len(parts)==1:
255 return (unit,)*nDim
256 else:
257 raise common.STCSParseError("'%s' is not a valid for unit %d-dimensional"
258 " spatial coordinates"%(unit, nDim))
259
260
261 def _addUnitSpatial(args, node, frame):
262 unit, nDim = node.get("unit"), frame.nDim
263 args["unit"] = _mogrifySpaceUnit(unit, nDim)
264
265
266 def _addUnitVelocity(args, node, frame):
267 unit, nDim = node.get("unit"), frame.nDim
268 if unit:
269 su, vu = [], []
270 parts = unit.split()
271 for uS in parts:
272 up = uS.split("/")
273 if len(up)!=2:
274 raise common.STCSParseError(
275 "'%s' is not a valid unit for velocities."%uS)
276 su.append(up[0])
277 vu.append(up[1])
278 args["unit"] = _mogrifySpaceUnit(" ".join(su), nDim)
279 args["velTimeUnit"] = _mogrifySpaceUnit(" ".join(vu), nDim)
280
281
282 _unitMakers = {
283 dm.SpectralType: _addUnitPlain,
284 dm.TimeType: _addUnitPlain,
285 dm.SpaceType: _addUnitSpatial,
286 dm.RedshiftType: _addUnitRedshift,
287 dm.VelocityType: _addUnitVelocity,
288 }
289
290
291 def _makeBasicCooArgs(node, frame, posClass, spatial=False):
292 """returns a dictionary containing constructor arguments common to
293 all items dealing with coordinates.
294 """
295 nDim = frame.nDim
296 args = {
297 "error": _makeWiggleValues(nDim, node.get("error"), maxItems=2,
298 spatial=spatial),
299 "resolution": _makeWiggleValues(nDim, node.get("resolution"), maxItems=2,
300 spatial=spatial),
301 "pixSize": _makeWiggleValues(nDim, node.get("pixSize"), maxItems=2,
302 spatial=spatial),
303 "size": _makeWiggleValues(nDim, node.get("size"), maxItems=2,
304 spatial=spatial),
305 "frame": frame,
306 }
307 if spatial and node.get("epoch"):
308 if isinstance(node["epoch"], common.ColRef):
309 args["epoch"] = node["epoch"]
310 args["yearDef"] = "J"
311 else:
312 args["epoch"] = float(node["epoch"][1:])
313 args["yearDef"] = node["epoch"][0]
314 _unitMakers[posClass.cType](args, node, frame)
315 return args
316
317
318 def _makeCooBuilder(frameName, intervalClass, intervalKey,
319 posClass, posKey, iterIntervKeys, spatial=False):
320 """returns a function(node, context) -> ASTNode for building a
321 coordinate-like AST node.
322
323 frameName is the name of the coordinate frame within
324 context.system,
325
326 (interval|pos)(Class|Key) are the class (key) to be used
327 (returned) for the interval/geometry and simple coordinate found
328 in the phrase. If intervalClass is None, no interval/geometry
329 will be built.
330
331 iterIntervKeys is an iterator that yields key/value pairs for intervals
332 or geometries embedded.
333
334 Single positions are always expected under the coo key.
335 """
336 positionExclusiveKeys = ["error", "resolution", "pixSize", "value",
337 "size", "unit", "velTimeUnit", "epoch", "yearDef"]
338 def builder(node, context):
339 frame = getattr(context.system, frameName)
340 nDim = frame.nDim
341 args = _makeBasicCooArgs(node, frame, posClass, spatial)
342
343 # Yield a coordinate
344 if "pos" in node:
345 args["value"] = _makeCooValues(nDim, node["pos"],
346 minItems=1, maxItems=1, spatial=spatial)[0]
347 else:
348 args["value"] = None
349 yield posKey, posClass(**args)
350
351 # Yield an area if defined in this phrase and non-empty
352 if intervalClass is None:
353 return
354 for key in positionExclusiveKeys:
355 if key in args:
356 del args[key]
357 for k, v in iterIntervKeys(node, nDim, spatial=spatial):
358 args[k] = v
359 if "fillfactor" in node:
360 args["fillFactor"] = node["fillfactor"]
361 if len(set(args))>1: # don't yield intervals that just define a frame
362 yield intervalKey, (intervalClass(**args),)
363
364 return builder
365
366
367 def _makeIntervalKeyIterator(preferUpper=False):
368 """returns a function yielding ASTNode constructor keys for intervals.
369 """
370 def iterKeys(node, nDim, spatial=False):
371 res, coos = {}, node.get("coos", ())
372 _validateCoos(coos, nDim, None, None)
373 for interval in _iterIntervals(coos, nDim, spatial):
374 if preferUpper:
375 res["upperLimit"], res["lowerLimit"] = interval
376 else:
377 res["lowerLimit"], res["upperLimit"] = interval
378 if res["upperLimit"]:
379 yield "upperLimit", res["upperLimit"]
380 if res["lowerLimit"]:
381 yield "lowerLimit", res["lowerLimit"]
382 return iterKeys
383
384
385
386 ###################### Geometries
387
388
389 def _makeGeometryKeyIterator(argDesc, clsName):
390 """returns a key iterator for use with _makeCooBuilder that yields
391 the keys particular to certain geometries.
392
393 ArgDesc describes what keys should be parsed from the node's coos key.
394 It consists for tuples of name and type code, where type code is one of:
395
396 - r -- a single real value.
397 - v -- a vector of dimensionality given by the system (i.e., nDim).
398 - rv -- a sequence of v items of arbitrary length.
399 - cv -- a sequence of "Convex" vectors (dim 4) of arbitrary length.
400
401 rv may only occur at the end of argDesc since it will consume all
402 remaining coordinates.
403 """
404 parseLines = [
405 "def iterKeys(node, nDim, spatial=True):",
406 ' if False: yield', # make sure the thing is an iterator
407 ' coos = node.get("coos", ())',
408 ' yield "origUnit",'
409 ' _mogrifySpaceUnit(node.get("unit"), nDim)',
410 " try:",
411 " pass"]
412 # Everything below here just coordinates
413 parseLines.extend([
414 ' if isinstance(coos, common.GeometryColRef):',
415 ' yield "geoColRef", coos',
416 ' return'])
417 for name, code in argDesc:
418 if code=="r":
419 parseLines.append(' yield "%s", coos.pop(0)'%name)
420 elif code=="v":
421 parseLines.append(' vec = coos[:nDim]')
422 parseLines.append(' coos = coos[nDim:]')
423 parseLines.append(' _validateCoos(vec, nDim, 1, 1)')
424 parseLines.append(' yield "%s", tuple(vec)'%name)
425 elif code=="rv":
426 parseLines.append(' yield "%s", _makeCooValues(nDim, coos)'%name)
427 parseLines.append(' coos = []')
428 elif code=="cv":
429 parseLines.append(' yield "%s", _makeCooValues(4, coos)'%name)
430 parseLines.append(' coos = []')
431 parseLines.append(' except IndexError:')
432 parseLines.append(' raise common.STCSParseError("Not enough coordinates'
433 ' while parsing %s")'%clsName)
434 parseLines.append(
435 ' if coos: raise common.STCSParseError("Too many coordinates'
436 ' while building %s, remaining: %%s"%%coos)'%clsName)
437
438 vars = locals()
439 exec("\n".join(parseLines), globals(), vars)
440 return vars["iterKeys"]
441
442
443 def _makeGeometryKeyIterators():
444 return dict(
445 (clsName, _makeGeometryKeyIterator(argDesc, clsName))
446 for clsName, argDesc in [
447 ("AllSky", []),
448 ("Circle", [('center', 'v'), ('radius', 'r')]),
449 ("Ellipse", [('center', 'v'), ('smajAxis', 'r'), ('sminAxis', 'r'),
450 ('posAngle', 'r')]),
451 ("Box", [('center', 'v'), ('boxsize', 'v')]),
452 ("Polygon", [("vertices", "rv")]),
453 ("Convex", [("vectors", "cv")]),
454 ("PositionInterval", [("lowerLimit", "v"), ("upperLimit", "v")]),
455 ])
456
457 _geometryKeyIterators = _makeGeometryKeyIterators()
458
459
460 def _makeGeometryBuilder(cls):
461 """returns a builder for Geometries.
462
463 See _makeGeometryKeyIterator for the meaning of the arguments.
464 """
465 return _makeCooBuilder("spaceFrame", cls, "areas", dm.SpaceCoo,
466 "place", _geometryKeyIterators[cls.__name__], spatial=True)
467
468
469 def _compoundGeometryKeyIterator(node, nDim, spatial):
470 """yields keys to configure compound geometries.
471 """
472 children = []
473 for c in node["children"]:
474 childType = c["subtype"]
475 destCls = getattr(dm, childType)
476 if childType in _geometryKeyIterators:
477 children.append(destCls(**dict(
478 _geometryKeyIterators[childType](c, nDim, True))))
479 else: # child is another compound geometry
480 children.append(destCls(**dict(
481 _compoundGeometryKeyIterator(c, nDim, True))))
482 yield "children", children
483
484
485 def _makeCompoundGeometryBuilder(cls):
486 """returns a builder for compound geometries.
487 """
488 return _makeCooBuilder("spaceFrame", cls, "areas", dm.SpaceCoo,
489 "place", _compoundGeometryKeyIterator, spatial=True)
490
491
492 ###################### Top level
493
494
495 def getCoords(cst, system):
496 """returns an argument dict for constructing STCSpecs for plain coordinates.
497 """
498 context = GenericContext(system=system)
499
500 return buildTree(cst, context, typeFunctions = {
501 "Time": _makeCooBuilder("timeFrame", None, None,
502 dm.TimeCoo, "time", None),
503 "StartTime": _makeCooBuilder("timeFrame", dm.TimeInterval, "timeAs",
504 dm.TimeCoo, "time", _makeIntervalKeyIterator()),
505 "StopTime": _makeCooBuilder("timeFrame", dm.TimeInterval, "timeAs",
506 dm.TimeCoo, "time", _makeIntervalKeyIterator(preferUpper=True)),
507 "TimeInterval": _makeCooBuilder("timeFrame", dm.TimeInterval, "timeAs",
508 dm.TimeCoo, "time", _makeIntervalKeyIterator()),
509
510 "Position": _makeCooBuilder("spaceFrame", None, None, dm.SpaceCoo,
511 "place", None, spatial=True),
512 "PositionInterval": _makeCooBuilder("spaceFrame",
513 dm.SpaceInterval, "areas", dm.SpaceCoo, "place",
514 _makeIntervalKeyIterator(), spatial=True),
515 "Velocity": _makeCooBuilder("spaceFrame",
516 dm.VelocityInterval, "velocityAs", dm.VelocityCoo, "velocity",
517 _makeIntervalKeyIterator(), spatial=True),
518 "VelocityInterval": _makeCooBuilder("spaceFrame",
519 dm.VelocityInterval, "velocityAs", dm.VelocityCoo, "velocity",
520 _makeIntervalKeyIterator(), spatial=True),
521 "AllSky": _makeGeometryBuilder(dm.AllSky),
522 "Circle": _makeGeometryBuilder(dm.Circle),
523 "Ellipse": _makeGeometryBuilder(dm.Ellipse),
524 "Box": _makeGeometryBuilder(dm.Box),
525 "Polygon": _makeGeometryBuilder(dm.Polygon),
526 "Convex": _makeGeometryBuilder(dm.Convex),
527
528 "Union": _makeCompoundGeometryBuilder(dm.Union),
529 "Intersection": _makeCompoundGeometryBuilder(dm.Intersection),
530 "Difference": _makeCompoundGeometryBuilder(dm.Difference),
531 "Not": _makeCompoundGeometryBuilder(dm.Not),
532
533 "Spectral": _makeCooBuilder("spectralFrame", None, None,
534 dm.SpectralCoo, "freq", None),
535 "SpectralInterval": _makeCooBuilder("spectralFrame",
536 dm.SpectralInterval, "freqAs", dm.SpectralCoo, "freq",
537 _makeIntervalKeyIterator()),
538
539 "Redshift": _makeCooBuilder("redshiftFrame", None, None,
540 dm.RedshiftCoo, "redshift", None),
541 "RedshiftInterval": _makeCooBuilder("redshiftFrame",
542 dm.RedshiftInterval, "redshiftAs", dm.RedshiftCoo, "redshift",
543 _makeIntervalKeyIterator()),
544
545 })
546
547
548 def parseSTCS(literal, grammarFactory=None):
549 """returns an STC AST for an STC-S expression.
550 """
551 cst = stcs.getCST(literal, grammarFactory)
552 if "libSystem" in cst:
553 system = syslib.getLibrarySystem(cst["libSystem"])
554 else:
555 system = getCoordSys(cst)[1]
556 args = {"astroSystem": system}
557 args.update(getCoords(cst, system))
558 return dm.STCSpec(**args).polish()
559
560
561 def parseQSTCS(literal):
562 """returns an STC AST for an STC-S expression with identifiers instead of
563 values.
564
565 The identifiers are denoted in double-quoted strings. Legal identifiers
566 follow the python syntax (i.e., these are *not* SQL quoted identifiers).
567 """
568 return parseSTCS(literal, grammarFactory=stcs.getColrefGrammar)
569
570
571 if __name__=="__main__":
572 print(parseSTCS("Union FK5 (Box 12 -13 2 2 Not (Circle 14 -13.5 3))"))