Debian Codegraph @

gavo/stc/stcs.py

raw
1 """
2 Parsing and generating STC-S
3
4 The general plan is to parse STC-S into some sort of tree (dictionaries
5 with list values, possibly containing more such dictionaries). These
6 trees can then be processed into something roughly resembling the data
7 model, furnished with defaults, and processed by what essentially is
8 user code.
9
10 Extensions to what the note says:
11
12 - After flavor, you can add an epoch using something like "Epoch J2000.0".
13 - After the FK5, FK4 and ECLIPTIC frame specs, you can add an optional
14 astroYear (Bnnnn, Jnnnn) designating a custom equinox.
15 - There is a system subphrase that lets you specify a system from the
16 STC library (without the ivo:// decoration). It starts with System
17 and is specified last. It will override all other system specifications.
18 - If enabled, you can use identifiers in double quotes wherever values
19 are allowed; this will generate column references.
20 - After the reference position, you can optionally mention the planetary
21 ephemeris used; currently, only JPL-DE200 and JPL-DE405 are allowed.
22 """
23
24 #c Copyright 2008-2025, the GAVO project <[email protected]>
25 #c
26 #c This program is free software, covered by the GNU GPL. See the
27 #c COPYING file in the source distribution.
28
29
30 import itertools
31
32 from gavo import utils
33 from gavo.stc import common
34 from gavo.stc import stcsdefaults
35 from gavo.stc import times
36 from gavo.utils.parsetricks import (
37 Word, Literal, Optional, alphas, CaselessKeyword,
38 ZeroOrMore, OneOrMore, StringEnd,
39 Suppress, Forward,
40 Regex, alphanums,
41 ParseException, ParseResults,
42 ParseSyntaxException,
43 pyparsingWhitechars)
44
45
46 class AComputedDefault(object):
47 """A sentinel for computed default values.
48 """
49 pass
50
51
52 # STC-S spatial flavors, with dimensions and stc flavors
53 stcsFlavors = {
54 "SPHER2": (2, "SPHERICAL"),
55 "SPHER3": (3, "SPHERICAL"),
56 "UNITSPHER": (3, "UNITSPHERE"),
57 "CART1": (1, "CARTESIAN"),
58 "CART2": (2, "CARTESIAN"),
59 "CART3": (3, "CARTESIAN"),
60 }
61
62
63 spatialUnits = set(["deg", "arcmin", "arcsec", "m", "mm", "km", "AU",
64 "pc", "kpc", "Mpc", "rad"])
65 temporalUnits = set(["yr", "cy", "s", "d", "a"])
66 spectralUnits = set(["MHz", "GHz", "Hz", "Angstrom", "keV", "MeV",
67 "eV", "mm", "um", "nm", "m"])
68
69 def _assertGrammar(cond, msg, pos):
70 if not cond:
71 raise common.STCSParseError(msg, pos)
72
73
74 def _iterDictNode(node, path):
75 """does iterNode's work for dict nodes.
76 """
77 for k, v in node.items():
78 if isinstance(v, list):
79 subIter = _iterListNode(v, path+(k,))
80 elif isinstance(v, dict):
81 subIter = _iterDictNode(v, path+(k,))
82 else:
83 continue # content does not contain a subtree
84 for res in subIter:
85 yield res
86 yield path, node
87
88 def _iterListNode(node, path):
89 """does iterNode's work for list nodes.
90 """
91 for subNode in node:
92 if isinstance(subNode, dict):
93 for res in _iterDictNode(subNode, path):
94 yield res
95
96 def iterNodes(tree):
97 """traverses the concrete syntax tree in postorder, returning pairs of
98 paths and nodes.
99
100 A node returned here is always a dictionary. The path consists of the
101 keys leading to the node in a tuple.
102 """
103 if isinstance(tree, list):
104 return _iterListNode(tree, ())
105 elif isinstance(tree, dict):
106 return _iterDictNode(tree, ())
107 else:
108 raise common.STCInternalError("Bad node in tree %s"%tree)
109
110
111 def addDefaults(tree):
112 """adds defaults for missing values for a concrete syntax tree.
113
114 The tree is changed in place. For details, see stcsdefaults.
115 """
116 for path, node in iterNodes(tree):
117 if path and path[-1] in stcsdefaults.defaultingFunctions:
118 stcsdefaults.defaultingFunctions[path[-1]](node)
119 return tree
120
121
122 def removeDefaults(tree):
123 """removes defaults from a concrete syntax tree.
124
125 The tree is changed in place. For details, see stcsdefaults.
126 """
127 for path, node in iterNodes(tree):
128 if path and path[-1] in stcsdefaults.undefaultingFunctions:
129 stcsdefaults.undefaultingFunctions[path[-1]](node)
130 return tree
131
132
133 def makeTree(parseResult):
134 """returns the pyparsing parseResult as a data structure consisting
135 of simple python dicts and lists.
136
137 The "tree" has two kinds of nodes: Dictionaries having lists as
138 values, and lists containing (as a rule) literals or (for more deeply
139 nested constructs, which are rare in STC-S) other dictionaries of
140 this kind.
141
142 A parse node becomes a dict node if it has named children. The root
143 always is a dict.
144
145 Note that unnamed children of nodes becoming dicts will be lost in
146 the result.
147 """
148 if not len(parseResult): # empty parse results become Nones
149 res = None
150
151 elif list(parseResult.keys()): # named children, generate a dict
152 res = {}
153 for k in list(parseResult.keys()):
154 v = parseResult[k]
155 # discard empty branches
156 if isinstance(v, ParseResults):
157 v = makeTree(v)
158 if v is not None: # discard empty branches
159 res[k] = v
160
161 else: # no named children, generate a list
162 if isinstance(parseResult[0], ParseResults):
163 res = [makeTree(child) for child in parseResult]
164 else:
165 res = list(parseResult)
166
167 return res
168
169
170 def _reFromKeys(iterable):
171 """returns a regular expression matching any of the strings in iterable.
172
173 The trick is that the longest keys must come first.
174 """
175 return "|".join(sorted(iterable, key=lambda x:-len(x)))
176
177
178 def _makeSymDict(locals, exportAll):
179 """returns a dictionary of pyparsing symbols defined in the locals.
180
181 locals would be the value locals() as a rule.
182 """
183 syms = dict((n, v) for n, v in locals.items()
184 if hasattr(v, "setName"))
185 if not exportAll:
186 syms = dict((n, v) for n, v in syms.items()
187 if not n.startswith("_"))
188 return syms
189
190
191 def _stringifyBlank(s, p, t):
192 """a parse action joining items in parse results with blanks.
193 """
194 return " ".join(t)
195
196 def _stringify(s, p, t):
197 """a parse action joining items in parse results.
198 """
199 return "".join(t)
200
201 def _makeSingle(s, p, t):
202 """a parse action that returns the first item of the tokens.
203
204 You typically want this when you know there's only one token, e.g.,
205 on Disjunctions or such
206 """
207 return t[0]
208
209
210 def _unpackTime(s, p, t):
211 """unravels on level of list from t["coos"] or t["pos"].
212
213 We need this because of the way setResultsName works since pyparsing 2.4.
214 """
215 if "coos" in t:
216 coos = t.pop("coos")
217 for r in itertools.chain(*coos):
218 t["coos"] = r
219 if "pos" in t:
220 coos = t.pop("pos")
221 for r in itertools.chain(*coos):
222 t["pos"] = r
223 return None # (changes in place)
224
225
226 def _getSTCSGrammar(numberLiteral,
227 timeLiteral,
228 _exportAll=False,
229 _addGeoReferences=False,
230 _astroYearOverride=None):
231 """returns a dictionary of symbols for a grammar parsing STC-S into
232 a concrete syntax tree.
233
234 numberLiteral and timeLiteral are pyparsing symbols for numbers and
235 datetimes, respectively.
236
237 _addGeoReferences lets you write quoted references to vectors
238 (like Circle "center" 20.).
239 """
240 with pyparsingWhitechars("\n\t\r "):
241
242 number = numberLiteral
243 del numberLiteral
244
245 # units
246 _unitOpener = Suppress( CaselessKeyword("unit") )
247 _spaceUnitWord = Regex(_reFromKeys(spatialUnits))
248 _timeUnitWord = Regex(_reFromKeys(temporalUnits))
249 spaceUnit = _unitOpener - OneOrMore( _spaceUnitWord ).addParseAction(
250 _stringifyBlank)("unit")
251 timeUnit = _unitOpener - _timeUnitWord("unit")
252 spectralUnit = _unitOpener - Regex(_reFromKeys(spectralUnits))("unit")
253 redshiftUnit = _unitOpener - (
254 (_spaceUnitWord + "/" + _timeUnitWord).addParseAction(_stringify)
255 | CaselessKeyword("nil"))("unit")
256 velocityUnit = _unitOpener - (OneOrMore(
257 (_spaceUnitWord + "/" + _timeUnitWord).addParseAction(_stringify)
258 ).addParseAction(_stringifyBlank))("unit")
259
260 # basic productions common to most STC-S subphrases
261 literalAstroYear = Regex("[BJ][0-9]+([.][0-9]*)?")
262 if _astroYearOverride:
263 astroYear = _astroYearOverride
264 else:
265 astroYear = literalAstroYear
266
267 fillfactor = (Suppress( CaselessKeyword("fillfactor")
268 ) + number("fillfactor"))
269 noEqFrame = (CaselessKeyword("J2000")
270 | CaselessKeyword("B1950")
271 | CaselessKeyword("ICRS")
272 | CaselessKeyword("GALACTIC")
273 | CaselessKeyword("GALACTIC_I")
274 | CaselessKeyword("GALACTIC_II")
275 | CaselessKeyword("SUPER_GALACTIC")
276 | CaselessKeyword("GEO_C")
277 | CaselessKeyword("GEO_D")
278 | CaselessKeyword("HPR")
279 | CaselessKeyword("HGS")
280 | CaselessKeyword("HGC")
281 | CaselessKeyword("HPC")
282 | CaselessKeyword("UNKNOWNFrame"))("frame")
283 eqFrameName = (CaselessKeyword("FK5")
284 | CaselessKeyword("FK4")
285 | CaselessKeyword("ECLIPTIC"))("frame")
286 eqFrame = eqFrameName + Optional( literalAstroYear("equinox") )
287 frame = eqFrame | noEqFrame
288 plEphemeris = CaselessKeyword("JPL-DE200") | CaselessKeyword("JPL-DE405")
289 refpos = ((Regex(_reFromKeys(common.stcRefPositions)))("refpos")
290 + Optional( plEphemeris("plEphemeris") ))
291 flavor = (Regex(_reFromKeys(stcsFlavors)))("flavor")
292
293 # properties of coordinates
294 error = Suppress( CaselessKeyword("Error") ) + OneOrMore( number )
295 resolution = Suppress( CaselessKeyword("Resolution")
296 ) + OneOrMore( number )
297 size = Suppress( CaselessKeyword("Size") ) + OneOrMore(number)
298 pixSize = Suppress( CaselessKeyword("PixSize") ) + OneOrMore(number)
299 cooProps = (Optional(error("error"))
300 + Optional(resolution("resolution"))
301 + Optional(size("size"))
302 + Optional(pixSize("pixSize")))
303
304 # properties of most spatial specs
305 _coos = ZeroOrMore( number )("coos")
306 _pos = Optional( ZeroOrMore( number )("pos") )
307 if _addGeoReferences: # include references to vectors, for getColrefSymbols
308 complexColRef = Regex(r'\[[A-Za-z_][A-Za-z_0-9]*\]').addParseAction(
309 lambda s,p,toks: common.GeometryColRef(toks[0][1:-1]))
310 _coos = complexColRef("coos") | _coos
311 _pos = complexColRef("pos") | _pos
312 positionSpec = Suppress( CaselessKeyword("Position") ) + _pos
313 epochSpec = Suppress( CaselessKeyword("Epoch") ) - astroYear
314 _spatialProps = Optional(spaceUnit) + cooProps
315 velocitySpec = (CaselessKeyword("Velocity")("type")
316 + OneOrMore( number )("pos"))
317 velocityInterval = (
318 Optional(
319 CaselessKeyword("VelocityInterval")("type")
320 + Optional( fillfactor )
321 + _coos )
322 + Optional(velocitySpec)
323 + Optional(velocityUnit)
324 + cooProps).addParseAction(makeTree)
325 _spatialTail = (_spatialProps +
326 Optional( velocityInterval)("velocity"))
327 _regionTail = Optional( positionSpec ) + _spatialTail
328 _commonSpaceItems = ( frame + Optional( refpos ) +
329 Optional( flavor ) + Optional(
330 epochSpec("epoch").addParseAction(lambda s,p,t: t[0])))
331 _commonRegionItems = Optional( fillfactor ) + _commonSpaceItems
332
333 # times and time intervals
334 timescale = (Regex("|".join(common.stcTimeScales)))("timescale")
335 timephrase = Suppress( CaselessKeyword("Time") ) + timeLiteral
336 _commonTimeItems = Optional(timeUnit) + cooProps
337 _intervalOpener = ( Optional( fillfactor ) +
338 Optional( timescale("timescale") ) +
339 Optional( refpos ) )
340 _intervalCloser = (Optional(timephrase.setResultsName("pos", True))
341 + _commonTimeItems)
342
343 timeInterval = (CaselessKeyword("TimeInterval")("type") +
344 _intervalOpener + ZeroOrMore(timeLiteral.setResultsName("coos", True))
345 + _intervalCloser).addParseAction(_unpackTime)
346 startTime = (CaselessKeyword("StartTime")("type") + _intervalOpener +
347 timeLiteral.setResultsName("coos", True) + _intervalCloser
348 ).addParseAction(_unpackTime)
349 stopTime = (CaselessKeyword("StopTime")("type") + _intervalOpener +
350 timeLiteral.setResultsName("coos", True) + _intervalCloser
351 ).addParseAction(_unpackTime)
352 time = (CaselessKeyword("Time")("type")
353 + Optional(timescale("timescale"))
354 + Optional(refpos) + Optional(
355 timeLiteral.setResultsName("pos", True).addParseAction(_unpackTime))
356 + _commonTimeItems)
357 timeSubPhrase = (timeInterval
358 | startTime
359 | stopTime
360 | time).addParseAction(makeTree)
361
362 # atomic "geometries"; I do not bother to specify their actual
363 # arguments since, without knowing the frame, they may be basically
364 # anything. Also, I want to allow geometry column references.
365 _atomicGeometryKey = ( CaselessKeyword("AllSky").setName("sub-geometry")
366 | CaselessKeyword("Circle")
367 | CaselessKeyword("Ellipse")
368 | CaselessKeyword("Box")
369 | CaselessKeyword("Polygon")
370 | CaselessKeyword("Convex")
371 | CaselessKeyword("PositionInterval") )
372 atomicGeometry = ( _atomicGeometryKey("type")
373 + _commonRegionItems
374 + _coos
375 + _regionTail )
376
377 # compound "geometries"
378 _compoundGeoExpression = Forward()
379 _compoundGeoOperand = (( _atomicGeometryKey("subtype") + _coos )
380 | _compoundGeoExpression ).addParseAction(lambda s,p,t: dict(t))
381
382 _compoundGeoOperatorUnary = CaselessKeyword("Not")
383 _compoundGeoOperandsUnary = ( Suppress( '(' )
384 + _compoundGeoOperand + Suppress( ')' ) )
385 _compoundGeoExprUnary = ( _compoundGeoOperatorUnary("subtype")
386 + _compoundGeoOperandsUnary("children") )
387
388 _compoundGeoOperatorBinary = CaselessKeyword("Difference")
389 _compoundGeoOperandsBinary = ( Suppress( '(' )
390 + _compoundGeoOperand + _compoundGeoOperand + Suppress( ')' ) )
391 _compoundGeoExprBinary = ( _compoundGeoOperatorBinary("subtype")
392 + _compoundGeoOperandsBinary("children") )
393
394 _compoundGeoOperatorNary = ( CaselessKeyword("Union")
395 | CaselessKeyword("Intersection") )
396 _compoundGeoOperandsNary = ( Suppress( '(' )
397 + _compoundGeoOperand + _compoundGeoOperand
398 + ZeroOrMore( _compoundGeoOperand ) + Suppress( ')' ) )
399 _compoundGeoExprNary = ( _compoundGeoOperatorNary("subtype")
400 + _compoundGeoOperandsNary("children") )
401
402 _compoundGeoExpression << ( _compoundGeoExprUnary
403 | _compoundGeoExprBinary
404 | _compoundGeoExprNary )
405 compoundGeoPhrase = ( _compoundGeoOperatorUnary("type")
406 + _commonRegionItems
407 + _compoundGeoOperandsUnary("children") + _regionTail
408 | _compoundGeoOperatorBinary("type")
409 + _commonRegionItems
410 + _compoundGeoOperandsBinary("children") + _regionTail
411 | _compoundGeoOperatorNary("type")
412 + _commonRegionItems
413 - _compoundGeoOperandsNary("children") + _regionTail )
414
415 # space subphrase
416 positionInterval = ( CaselessKeyword("PositionInterval")("type")
417 + _commonRegionItems
418 + _coos
419 + _regionTail )
420 position = ( CaselessKeyword("Position")("type")
421 + _commonSpaceItems
422 + _pos
423 + _spatialTail )
424 spaceSubPhrase = ( positionInterval
425 | position
426 | atomicGeometry
427 | compoundGeoPhrase ).addParseAction(makeTree)
428
429 # spectral subphrase
430 spectralSpec = (Suppress( CaselessKeyword("Spectral") )
431 + number)("pos")
432 _spectralTail = Optional(spectralUnit) + cooProps
433 spectralInterval = (CaselessKeyword("SpectralInterval")("type")
434 + Optional( fillfactor )
435 + Optional( refpos )
436 + _coos
437 + Optional( spectralSpec )
438 + _spectralTail)
439 spectral = (CaselessKeyword("Spectral")("type")
440 + Optional( refpos )
441 + _pos
442 + _spectralTail)
443 spectralSubPhrase = (spectralInterval | spectral ).addParseAction(
444 makeTree)
445
446 # redshift subphrase
447 redshiftType = Regex("VELOCITY|REDSHIFT")("redshiftType")
448 redshiftSpec = (Suppress( CaselessKeyword("Redshift") ) + number)("pos")
449 dopplerdef = Regex("OPTICAL|RADIO|RELATIVISTIC")("dopplerdef")
450 _redshiftTail = Optional(redshiftUnit) + cooProps
451 redshiftInterval = (CaselessKeyword("RedshiftInterval")("type")
452 + Optional(fillfactor)
453 + Optional(refpos)
454 + Optional(redshiftType)
455 + Optional(dopplerdef)
456 + _coos
457 + Optional(redshiftSpec)
458 + _redshiftTail)
459 redshift = (CaselessKeyword("Redshift")("type")
460 + Optional(refpos)
461 + Optional(redshiftType)
462 + Optional(dopplerdef)
463 + _pos
464 + _redshiftTail)
465 redshiftSubPhrase = (redshiftInterval | redshift).addParseAction(
466 makeTree)
467
468 # system subphrase (extension, see docs)
469 # ids match Name from XML spec; we're not doing char refs and similar here
470 systemName = Word(alphas+"_:", alphanums+'.-_:').addParseAction(_stringify)
471 systemDefinition = (Suppress( CaselessKeyword("System") )
472 + systemName("libSystem"))
473
474
475 # top level
476 stcsPhrase = ( #noflake: stcsPhrase is returned through locals()
477 Optional( timeSubPhrase )("time") +
478 Optional( spaceSubPhrase )("space") +
479 Optional( spectralSubPhrase )("spectral") +
480 Optional( redshiftSubPhrase )("redshift") +
481 Optional( systemDefinition ) ) + StringEnd()
482
483 return _makeSymDict(locals(), _exportAll)
484
485
486 def getSymbols(_exportAll=False, _colrefLiteral=None,
487 _addGeoReferences=False):
488 """returns an STC-S grammar with terminal values.
489 """
490 with pyparsingWhitechars("\n\t\r "):
491 _exactNumericRE = r"[+-]?\d+(\.(\d+)?)?|[+-]?\.\d+"
492 exactNumericLiteral = Regex(_exactNumericRE)
493 numberLiteral = Regex(r"(?i)(%s)(E[+-]?\d+)?"%_exactNumericRE
494 ).addParseAction(lambda s,p,toks: float(toks[0]))
495
496 jdLiteral = (Suppress( Literal("JD") ) + exactNumericLiteral
497 ).addParseAction(lambda s,p,toks: times.jdnToDateTime(float(toks[0])))
498 mjdLiteral = (Suppress( Literal("MJD") ) + exactNumericLiteral
499 ).addParseAction(lambda s,p,toks: times.mjdToDateTime(float(toks[0])))
500 isoTimeLiteral = Regex(r"\d\d\d\d-?\d\d-?\d\d(T\d\d:?\d\d:?\d\d(\.\d*)?Z?)?"
501 ).addParseAction(lambda s,p,toks: times.parseISODT(toks[0]))
502 timeLiteral = (isoTimeLiteral | jdLiteral | mjdLiteral)
503 astroYear = Regex("[BJ][0-9]+([.][0-9]*)?")
504
505 if _colrefLiteral:
506 numberLiteral = _colrefLiteral ^ numberLiteral
507 timeLiteral = _colrefLiteral ^ timeLiteral
508 astroYear = _colrefLiteral ^ astroYear
509
510 res = _getSTCSGrammar(numberLiteral,
511 timeLiteral,
512 _exportAll,
513 _addGeoReferences=_addGeoReferences,
514 _astroYearOverride=astroYear)
515 res.update(_makeSymDict(locals(), _exportAll))
516 return res
517
518
519 def getColrefSymbols():
520 """returns an STC-S grammar with column references as values.
521
522 The column references used here have the form "<colref>" to cut down
523 on ambiguities. We only accept simple identifiers (i.e., not quoted in
524 the SQL sense), though.
525 """
526 def makeColRef(s, p, toks):
527 return common.ColRef(toks[0][1:-1])
528 with pyparsingWhitechars("\n\t\r "):
529 atomicColRef = Regex('"[A-Za-z_][A-Za-z_0-9]*"').addParseAction(
530 makeColRef)
531 return getSymbols(_colrefLiteral=atomicColRef, _addGeoReferences=True)
532
533
534 def enableDebug(syms, debugNames=None):
535 if not debugNames:
536 debugNames = syms
537 for name in debugNames:
538 ob = syms[name]
539 ob.setDebug(True)
540 ob.setName(name)
541
542
543 getGrammar = utils.CachedGetter(getSymbols)
544 getColrefGrammar = utils.CachedGetter(getColrefSymbols)
545
546
547 def getCST(literal, grammarFactory=None):
548 """returns a CST for an STC-S expression.
549
550 grammarFactory is a function returning the grammar, in this case
551 either getGrammar (which gets used if the argument is left out) or
552 getColrefGrammar.
553 """
554 # special case: the empty input yields an empty CST
555 if not literal.strip():
556 return {}
557
558 if grammarFactory is None:
559 grammarFactory = getGrammar
560 try:
561 tree = makeTree(utils.pyparseString(
562 grammarFactory()["stcsPhrase"], literal))
563 except (ParseException, ParseSyntaxException) as ex:
564 raise common.STCSParseError(
565 "Invalid STCS expression (%s at %s)"%(ex.msg, ex.loc),
566 expr=literal, pos=ex.loc)
567 addDefaults(tree)
568 return tree
569
570
571 if __name__=="__main__":
572 import pprint
573 syms = getColrefSymbols()
574 enableDebug(syms)
575 pprint.pprint(makeTree(syms["stcsPhrase"].parseString(
576 "Position ICRS Epoch J2000.0 20 21"
577 , parseAll=True)))