Debian Codegraph @

gavo/stc/tapstc.py

raw
1 """
2 The subset of STC proposed by the TAP spec.
3
4 Use this rather than the full-blown STC library for TAP and friends.
5 TAP's semi-sanitation of STC needs some special handling anyway,
6 and this is much faster than the full-blown mess.
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 functools
16
17 from gavo import utils
18 from gavo.stc import common
19 from gavo.stc import stcsast
20 from gavo.utils import pgsphere
21
22
23 TAP_SYSTEMS = set(
24 ['ICRS', 'FK4', 'FK5', 'GALACTIC', 'RELOCATABLE', 'UNKNOWN', '', "BROKEN",
25 'J2000', 'B1950',
26 "UNKNOWNFrame"])
27
28 # universally ignored
29 TAP_REFPOS = set(
30 ['BARYCENTER', 'GEOCENTER', 'HELIOCENTER', 'LSR', 'TOPOCENTER',
31 'RELOCATABLE', 'UNKNOWNREFPOS'])
32
33 # only SPHERICAL2 supported, all others raise errors
34 TAP_FLAVORS = set(
35 ["CARTESIAN2", "CARTESIAN3", "SPHERICAL2"])
36
37
38 ################## transformations between TAP STC reference systems
39
40 UNIVERSALLY_COMPATIBLE = set(['RELOCATABLE', 'UNKNOWN', '', "BROKEN", None])
41
42 TRANSFORMS = {
43 # From "ICRS" (really, FK5 J2000, and the lo-prec) to...
44 'FK4': (1.5651864333666516, -0.0048590552804904244, -1.5763681043529187),
45 'FK5': None,
46 'ICRS': None,
47 'GALACTIC': (1.3463560974407338, -1.0973190018372752, 0.57477052472873258),
48 }
49
50
51 def _getEulersFor(frame):
52 if not frame in TRANSFORMS:
53 raise common.STCValueError("Unknown reference frame: %s"%frame)
54 return TRANSFORMS[frame]
55
56
57 def getPGSphereTrafo(fromSys, toSys):
58 """returns a pgsphere expression fragment to turn a pgsphere geometry
59 from fromSys to toSys.
60
61 fromSys and toSys are system designations like for TAP.
62
63 If the systems are "compatible" (i.e., no transformation is deemed necessary),
64 None is returned. An STCValueError is raised for incomprehensible system
65 specifications.
66 """
67 if (fromSys in UNIVERSALLY_COMPATIBLE
68 or toSys in UNIVERSALLY_COMPATIBLE):
69 return None
70 if fromSys=='ICRS':
71 template = "+strans(%.12f,%.12f,%.12f)"
72 angles = _getEulersFor(toSys)
73 elif toSys=='ICRS':
74 angles = _getEulersFor(fromSys)
75 template = "-strans(%.12f,%.12f,%.12f)"
76 else:
77 t1 = getPGSphereTrafo(fromSys, 'ICRS')
78 t2 = getPGSphereTrafo('ICRS', toSys)
79 return "%s%s"%(t1 or "", t2 or "")
80 if angles:
81 return template%angles
82 return None
83
84
85 def getTAPSTC(stcInstance):
86 """returns a tap system identifier for an STC AstroSystem.
87
88 This is stc.astroSystem.spaceFrame.refFrame if existing and
89 TAP-defined, UNKNOWN otherwise.
90 """
91 rf = None
92 if stcInstance.astroSystem and stcInstance.astroSystem.spaceFrame:
93 rf = stcInstance.astroSystem.spaceFrame.refFrame
94 if rf not in TAP_SYSTEMS:
95 return "UNKNOWN"
96 return rf
97
98
99 @functools.lru_cache()
100 def getSTCForTAP(tapIdentifier):
101 """returns an stc AST for a tap reference system identifier.
102
103 The tapIdentifier is any string in which the first item is the reference
104 system. Everything else is ignored (this is because it seems someone
105 intended additional specs like "BARYCENTER" to be legal, although
106 there really is nothing we can do about them).
107 """
108 if tapIdentifier:
109 tapIdentifier = utils.identifierPattern.findall(tapIdentifier)[0]
110 if tapIdentifier in ["BROKEN", '', "UNKNOWN", None]:
111 tapIdentifier = "UNKNOWNFrame"
112 ast = stcsast.parseSTCS("Position %s"%tapIdentifier)
113 if tapIdentifier=='BROKEN':
114 ast.broken = True
115 return ast
116
117
118
119 ############################# TAP simplified STC-S
120 # The simplified STC-S is a simple regular grammar for the position specs
121 # plus a context-free part for set operations. The regular part we
122 # do with REs, for the rest there's a simple recursive descent parser.
123 #
124 # From the literal we either create a pgsphere geometry ready for ingestion
125 # or, when operators enter, an GeomExpr object. Since at least pgsphere
126 # does not support geometric operators, this must be handled in the morph code.
127 # To make this clear, its flatten method just raises an Exception.
128 #
129 # The regions expressible in pgsphere are returned as pgsphre objects.
130 # This is because I feel all this should only be used for ingesting data
131 # ("table upload") and thus carrying around the frame is pointless;
132 # you can, however, retrieve a guess for the frame from the returned
133 # object's cooSys attribute (which is convenient for the morphers).
134
135
136 class GeomExpr(object):
137 """a sentinel object to be processed by morphers.
138 """
139 def __init__(self, frame, operator, operands):
140 self.cooSys = frame
141 self.operator, self.operands = operator.upper(), operands
142 self.type = self.operator
143
144 def flatten(self):
145 raise common.STCSParseError("Cannot serialize STC-S. Did you use"
146 " Union or Intersection outside of CONTAINS or INTERSECTS?")
147
148 def _flatLogic(self, template, operand):
149 if isinstance(operand, GeomExpr):
150 return operand.asLogic(template)
151 else:
152 return template%operand.asPgSphere()
153
154 def asLogic(self, template):
155 if self.operator=="UNION":
156 logOp = " OR "
157 elif self.operator=="INTERSECTION":
158 logOp = " AND "
159 elif self.operator=="NOT":
160 return "NOT (%s)"%self._flatLogic(template, self.operands[0])
161 else:
162 raise NotImplementedError("No logic for operator '%s'"%self.operator)
163 return logOp.join(
164 '(%s)'%self._flatLogic(template, op) for op in self.operands)
165
166
167 def _make_pgsposition(coords):
168 if len(coords)!=2:
169 raise common.STCSParseError("STC-S points want two coordinates.")
170 return pgsphere.SPoint(*coords)
171
172
173 def _make_pgscircle(coords):
174 if len(coords)!=3:
175 raise common.STCSParseError("STC-S circles want three numbers.")
176 return pgsphere.SCircle(pgsphere.SPoint(*coords[:2]), coords[2])
177
178
179 def _make_pgsbox(coords):
180 if len(coords)!=4:
181 raise common.STCSParseError("STC-S boxes want four numbers.")
182 x,y,w,h = coords
183 return pgsphere.SPoly((
184 pgsphere.SPoint(x-w/2, y-h/2),
185 pgsphere.SPoint(x-w/2, y+h/2),
186 pgsphere.SPoint(x+w/2, y+h/2),
187 pgsphere.SPoint(x+w/2, y-h/2)))
188
189
190 def _make_pgspolygon(coords):
191 if len(coords)<6 or len(coords)%2:
192 raise common.STCSParseError(
193 "STC-S polygons want at least three number pairs")
194 return pgsphere.SPoly(
195 [pgsphere.SPoint(*p) for p in utils.iterConsecutivePairs(coords)])
196
197
198 def _makePgSphereInstance(match):
199 """returns a utils.pgsphere instance from a match of simpleStatement in
200 the simple STCS parser below.
201 """
202 if match["flavor"] and match["flavor"].strip().upper()!="SPHERICAL2":
203 raise common.STCSParseError("Only SPHERICAL2 STC-S supported here")
204 refFrame = 'UnknownFrame'
205 if match["frame"]:
206 refFrame = match["frame"].strip()
207 # refFrame gets thrown away here; to use it, we'd have to generate
208 # ADQL nodes, and that would be clumsy for uploads. See rant above.
209 handler = globals()["_make_pgs%s"%match["shape"].lower()]
210 res = handler(
211 tuple(float(s)*utils.DEG for s in match["coords"].strip().split() if s))
212 res.cooSys = refFrame
213 return res
214
215 def _makeRE(strings):
216 return "|".join(sorted(strings, key=lambda s: -len(s)))
217
218 @functools.lru_cache()
219 def getSimpleSTCSParser():
220 from gavo.utils.parsetricks import (
221 Regex, CaselessKeyword, OneOrMore, Forward, Suppress,
222 Optional, ParseException, ParseSyntaxException,
223 pyparsingWhitechars)
224
225 with pyparsingWhitechars(" \t\n\r"):
226 frameRE = _makeRE(TAP_SYSTEMS)
227 refposRE = _makeRE(TAP_REFPOS)
228 flavorRE = _makeRE(TAP_FLAVORS)
229 systemRE = (r"\s*"
230 r"(?P<frame>%s)?\s*"
231 r"(?P<refpos>%s)?\s*"
232 r"(?P<flavor>%s)?\s*")%(
233 frameRE, refposRE, flavorRE)
234 coordsRE = r"(?P<coords>(%s\s*)+)"%utils.floatRE
235
236 simpleStatement = Regex(r"(?i)\s*"
237 "(?P<shape>position|circle|box|polygon)"
238 +systemRE
239 +coordsRE)
240 simpleStatement.setName("STC-S geometry")
241 simpleStatement.addParseAction(lambda s,p,t: _makePgSphereInstance(t))
242 system = Regex("(?i)"+systemRE)
243 system.setName("STC-S system spec")
244 region = Forward()
245 notExpr = CaselessKeyword("NOT") + Suppress('(') + region + Suppress(')')
246 notExpr.addParseAction(lambda s,p,t: GeomExpr("UNKNOWN", "NOT", (t[1],)))
247 opExpr = (
248 (CaselessKeyword("UNION") | CaselessKeyword("INTERSECTION"))("op")
249 + Optional(Regex(frameRE))("frame")
250 + Optional(Regex(refposRE)) + Optional(Regex(flavorRE))
251 + Suppress("(")
252 + region + OneOrMore(region)
253 + Suppress(")"))
254 opExpr.addParseAction(
255 lambda s,p,t: GeomExpr(str(t["frame"]), t[0].upper(), t[2:]))
256 region << (simpleStatement | opExpr | notExpr)
257
258 def parse(s):
259 if isinstance(s, pgsphere.PgSAdapter):
260 return s
261 if s is None or not s.strip(): # special service: Null values
262 return None
263
264 try:
265 res = utils.pyparseString(region, s, parseAll=True)[0]
266 if not res.cooSys or res.cooSys.lower()=='unknownframe': # Sigh.
267 res.cooSys = "UNKNOWN"
268 return res
269 except (ParseException, ParseSyntaxException) as msg:
270 raise common.STCSParseError("Invalid STCS (%s)"%str(msg))
271
272 return parse
273
274
275 parseSimpleSTCS = getSimpleSTCSParser()
276
277
278 def simpleSTCSToPolygon(stcsExpr):
279 """returns an spoly for an STC-S region specification.
280
281 This is used to let people upload VOTables with REGION items.
282 """
283 if stcsExpr is None:
284 return None
285 return parseSimpleSTCS(stcsExpr).asPoly()
286
287
288 if __name__=="__main__":
289 # compute the Euler angles given above. pgsphere has its rotation
290 # matrices opposite to ours (ccw rather than cw), hence the negation
291 from kapteyn import celestial
292 from gavo.stc import sphermath
293 print("FK4:", tuple(-a for a in
294 sphermath.getEulerAnglesFromMatrix(
295 celestial.skymatrix("icrs", "fk4 B1950.0")[0])))
296 print("GAL:", tuple(-a for a in
297 sphermath.getEulerAnglesFromMatrix(
298 celestial.skymatrix("icrs", "galactic")[0])))
299