Debian Codegraph @

gavo/stc/dm.py

raw
1 """
2 Definition of the structure of the internal representation (the AST).
3
4 For now, we want to be able to capture what STC-S can do (and a bit more).
5 This means that we do not support generic coordinates (yet), elements,
6 xlink and all the other stuff.
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 itertools
16 import operator
17 import re
18
19 from gavo import utils
20 from gavo.stc import times
21 from gavo.stc import units
22 from gavo.stc import common
23 from gavo.utils import pgsphere
24 from functools import reduce
25
26
27 ################ Coordinate Systems
28
29
30 class RefPos(common.ASTNode):
31 """is a reference position.
32
33 Right now, this is just a wrapper for a RefPos id, as defined by STC-S,
34 or None for Unknown.
35 """
36 # If we ever support non-standard origins, they should go into a different
37 # class, I guess. Or, we'd need a sentinel for standardOrigin (like,
38 # NONSTANDARD). None, anyway, is for Unknown, and we shouldn't change that.
39 _a_standardOrigin = None
40 _a_planetaryEphemeris = None
41
42
43 NullRefPos = RefPos()
44
45 class _CoordFrame(common.ASTNode):
46 """is an astronomical coordinate frame.
47 """
48 _a_name = None
49 _a_refPos = None
50
51 def _setupNode(self):
52 if self.refPos is None:
53 self.refPos = NullRefPos
54
55 def isSpherical(self):
56 """returns True if this is a frame deemed suitable for space
57 frame transformations.
58
59 This is really a property of stc.sphermath rather than of the
60 data model, but it's more convenient to have this as a frame
61 method.
62 """
63 return (isinstance(self, SpaceFrame)
64 and self.nDim>1
65 and self.flavor=="SPHERICAL")
66
67
68 class TimeFrame(_CoordFrame):
69 nDim = 1
70 _a_timeScale = None
71
72
73 class SpaceFrame(_CoordFrame):
74 _a_flavor = "SPHERICAL"
75 _a_nDim = None
76 _a_refFrame = None
77 _a_equinox = None # if non-null, it has to match [BJ][0-9]+[.][0-9]+
78
79 def _setupNode(self):
80 if self.refFrame=="J2000":
81 self.refFrame = "FK5"
82 self.equinox = "J2000.0"
83 elif self.refFrame=="B1950":
84 self.refFrame = "FK4"
85 self.equinox = "B1950.0"
86 if self.nDim is None:
87 self.nDim = 2
88 _CoordFrame._setupNode(self)
89
90 def getEquinox(self):
91 """returns a datetime.datetime instance for the frame's equinox.
92
93 It will return None if no equinox is given, and it may raise an
94 STCValueError if an invalid equinox string has been set.
95 """
96 if self.equinox is None:
97 return None
98 mat = re.match("([B|J])([0-9.]+)", self.equinox)
99 if not mat:
100 raise common.STCValueError("Equinoxes must be [BJ]<float>, but %s isn't"%(
101 self.equinox))
102 if mat.group(1)=='B':
103 return times.bYearToDateTime(float(mat.group(2)))
104 else:
105 return times.jYearToDateTime(float(mat.group(2)))
106
107 def asTriple(self):
108 """returns a triple defining the space frame for spherc's purposes.
109
110 This is for the computation of coordinate transforms. Since we only
111 do coordinate transforms for spherical coordinate systems, this
112 will, for now, raise STCValueErrors if everything but 2 or 3D SPHERICAL
113 flavours. The other cases need more thought anyway.
114 """
115 if self.flavor!="SPHERICAL" or (self.nDim!=2 and self.nDim!=3):
116 raise common.STCValueError("Can only conform 2/3-spherical coordinates")
117 return (self.refFrame, self.getEquinox(), self.refPos.standardOrigin)
118
119
120 class SpectralFrame(_CoordFrame):
121 nDim = 1
122
123
124 class RedshiftFrame(_CoordFrame):
125 nDim = 1
126 _a_dopplerDef = None
127 _a_type = None
128
129
130 class CoordSys(common.ASTNode):
131 """is an astronomical coordinate system.
132 """
133 _a_timeFrame = None
134 _a_spaceFrame = None
135 _a_spectralFrame = None
136 _a_redshiftFrame = None
137 _a_name = None
138 _a_libraryId = None # for standard coordinate systems, the ivo://whatever.
139
140
141 class _CooTypeSentinel(object):
142 """is a base for type indicators.
143
144 Never instantiate any of these.
145 """
146
147 class SpectralType(_CooTypeSentinel):
148 posAttr = "freq"
149
150 class TimeType(_CooTypeSentinel):
151 posAttr = "time"
152
153 class SpaceType(_CooTypeSentinel):
154 posAttr = "place"
155
156 class RedshiftType(_CooTypeSentinel):
157 posAttr = "redshift"
158
159 class VelocityType(_CooTypeSentinel):
160 posAttr = "velocity"
161
162
163 ############### Coordinates and their intervals
164
165
166 class _WiggleSpec(common.ASTNode):
167 """A base for "wiggle" specifications.
168
169 These are Errors, Resolutions, Sizes, and PixSizes. They may come
170 as simple coordinates (i.e., scalars or vectors) or, in 2 and 3D,
171 as radii or matrices (see below). In all cases, two values may
172 be given to indicate ranges.
173
174 These need an adaptValuesWith(converter) method that will return a wiggle of
175 the same type but with every value replaced with the result of the
176 application of converter to that value.
177 """
178
179
180 class CooWiggle(_WiggleSpec):
181 """A wiggle given in coordinates.
182
183 The values attributes stores them just like coordinates are stored.
184 """
185 _a_values = ()
186 _a_origUnit = None
187
188 inexactAttrs = set(["values"])
189
190 def adaptValuesWith(self, unitConverter):
191 if unitConverter is None:
192 return self
193 return self.change(values=tuple(unitConverter(v) for v in self.values))
194
195 def getValues(self):
196 return self.values
197
198
199 class RadiusWiggle(_WiggleSpec):
200 """An wiggle given as a radius.
201
202 If unit adaption is necessary and the base value is a vector, the radii
203 are assumed to be of the dimension of the first vector component.
204 """
205 _a_radii = ()
206 _a_origUnit = None
207
208 inexactAttrs = set(["radii"])
209
210 def adaptValuesWith(self, unitConverter):
211 if unitConverter is None:
212 return self
213 return self.change(radii=tuple(unitConverter(itertools.repeat(r))[0]
214 for r in self.radii))
215
216 def getValues(self):
217 return self.radii
218
219
220 class MatrixWiggle(_WiggleSpec):
221 """A matrix for specifying wiggle.
222
223 The matrix/matrices are stored as sequences of sequences; see
224 stcxgen._wrapMatrix for details.
225 """
226 _a_matrices = ()
227 _a_origUnit = None
228
229 def adaptValuesWith(self, unitConverter):
230 raise common.STCValueError("Matrix wiggles cannot be transformed.")
231
232
233 class _CoordinateLike(common.ASTNode):
234 """An abstract base for everything that has a frame.
235
236 They can return a position object of the proper type and with the
237 same unit as self.
238
239 When deriving from _CoordinateLike, you have at some point to define
240 a cType class attribute that has values in the _CooTypeSentinels above.
241 """
242 _a_frame = None
243 _a_name = None
244
245 def getPosition(self, initArgs=None):
246 """returns a position appropriate for this class.
247
248 This is a shallow copy of the xCoo object itself for xCoos,
249 xCoo for xInterval, and SpaceCoo for Geometries. Common attributes
250 are copied to the new object.
251 """
252 posClass = _positionClassMap[self.cType]
253 if initArgs is None:
254 initArgs = {}
255 for name, default in posClass._nodeAttrs:
256 if name!="id" and name not in initArgs:
257 initArgs[name] = getattr(self, name, default)
258 return posClass(**initArgs)
259
260
261 class _Coordinate(_CoordinateLike):
262 """An abstract base for coordinates.
263
264 They have an iterTransformed(convFunc) method iterating over
265 constructor keys that have to be changed when some convFunc is
266 applied to the coordinate. These may be multiple values when,
267 e.g., errors are given or for geometries.
268
269 Since these only make sense together with units, some elementary
270 unit handling is required. Since we keep the basic unit model
271 of STC, this is a bit over-complicated.
272
273 First, for the benefit of STC-S, a method getUnitString() ->
274 string or None is required. It should return an STC-S-legal
275 unit string.
276
277 Second, a method getUnitArgs() -> dict or None is required.
278 It has to return a dictionary with all unit-related constructor
279 arguments (that's unit and velTimeUnit for the standard coordinate
280 types). No None values are allowed; if self's units are not
281 defined, return None.
282
283 Third, a method getUnitConverter(otherUnits) -> function or None is required.
284 OtherUnits can be a tuple or a result of getUnitArgs. The tuple is
285 interpreted as (baseUnit, timeUnit). The function returned must
286 accept self's coordinate values in otherUnit and return them in self's
287 unit(s). This is the function that iterTransformed requires.
288 """
289 _a_error = None
290 _a_resolution = None
291 _a_pixSize = None
292 _a_value = None
293 _a_size = None
294
295 _dimensionedAttrs = ["error", "resolution", "pixSize", "size"]
296
297 inexactAttrs = set(["value"])
298
299 def _setupNode(self):
300 for name in self._dimensionedAttrs:
301 wiggle = getattr(self, name)
302 if wiggle and wiggle.origUnit is not None:
303 setattr(self, name, wiggle.adaptValuesWith(
304 self.getUnitConverter(wiggle.origUnit)))
305 self._setupNodeNext(_Coordinate)
306
307 def iterTransformed(self, converter):
308 if self.value is not None:
309 yield "value", converter(self.value)
310 for attName in self._dimensionedAttrs:
311 wiggle = getattr(self, attName)
312 if wiggle:
313 yield attName, wiggle.adaptValuesWith(converter)
314
315
316 class _OneDMixin(object):
317 """provides attributes for 1D-Coordinates (Time, Spectral, Redshift)
318 """
319 _a_unit = None
320
321 def getUnitString(self):
322 return self.unit
323
324 def getUnitConverter(self, otherUnits):
325 if self.unit is None or not otherUnits:
326 return None
327 if isinstance(otherUnits, dict):
328 otherUnits = (otherUnits["unit"],)
329 return units.getBasicConverter(self.unit, otherUnits[0], True)
330
331 def getUnitArgs(self):
332 if self.unit:
333 return {"unit": self.unit}
334
335 def getValues(self):
336 return [self.value]
337
338
339 class _SpatialMixin(object):
340 """provides attributes for positional coordinates.
341
342 In addition to unit management, this is also carries an epoch in years.
343 You can, in addition, set yearDef. If None, Julian years are implied,
344 but you can have B for Bessel years.
345 """
346 _a_unit = ()
347 _a_epoch = None
348 _a_yearDef = None
349
350 cType = SpaceType
351
352 def getUnitString(self):
353 if self.unit:
354 if len(set(self.unit))==1:
355 return self.unit[0]
356 else:
357 return " ".join(self.unit)
358
359 def getUnitConverter(self, otherUnits):
360 if self.unit is None or not otherUnits:
361 return None
362 if isinstance(otherUnits, dict):
363 otherUnits = (otherUnits["unit"],)
364 f = units.getVectorConverter(self.unit, otherUnits[0], True)
365 return f
366
367 def getUnitArgs(self):
368 if self.unit==():
369 # horrendous default: an empty spatial coordinate as (deg, deg),
370 # because that's what most likely works with geometries.
371 # Oh boy, STC1 is *so* broken it's not funny any more.
372 return {"unit": ("deg", "deg")}
373 return {"unit": self.unit}
374
375 def getValues(self):
376 if self.value is None:
377 return []
378 return self.value
379
380
381 class _VelocityMixin(object):
382 """provides attributes for velocities.
383 """
384 _a_unit = ()
385 _a_velTimeUnit = ()
386 _a_epoch = None
387 _a_yearDef = None
388
389 cType = VelocityType
390
391 def _setupNode(self):
392 if self.unit:
393 if not self.velTimeUnit or len(self.unit)!=len(self.velTimeUnit):
394 raise common.STCValueError("Invalid units for Velocity: %s/%s."%(
395 repr(self.unit), repr(self.velTimeUnit)))
396 self._setupNodeNext(_VelocityMixin)
397
398 def getUnitString(self):
399 if self.unit:
400 strs = ["%s/%s"%(u, tu)
401 for u, tu in zip(self.unit, self.velTimeUnit)]
402 if len(set(strs))==1:
403 return strs[0]
404 else:
405 return " ".join(strs)
406
407 def getUnitConverter(self, otherUnits):
408 if self.unit is None or not otherUnits:
409 return None
410 if isinstance(otherUnits, dict):
411 otherUnits = (otherUnits["unit"], otherUnits["velTimeUnit"])
412 return units.getVelocityConverter(self.unit, self.velTimeUnit,
413 otherUnits[0], otherUnits[1], True)
414
415 def getUnitArgs(self):
416 return {"unit": self.unit, "velTimeUnit": self.velTimeUnit}
417
418
419 class _RedshiftMixin(object):
420 """provides attributes for redshifts.
421 """
422 _a_velTimeUnit = None
423 _a_unit = None
424
425 cType = RedshiftType
426
427 def _setupNode(self):
428 if self.unit and not self.velTimeUnit:
429 raise common.STCValueError("Invalid units for Redshift: %s/%s."%(
430 repr(self.unit), repr(self.velTimeUnit)))
431 self._setupNodeNext(_RedshiftMixin)
432
433 def getUnitString(self):
434 if self.unit:
435 return "%s/%s"%(self.unit, self.velTimeUnit)
436
437 def getUnitConverter(self, otherUnits):
438 if self.unit is None or not otherUnits:
439 return None
440 if isinstance(otherUnits, dict):
441 otherUnits = (otherUnits["unit"], otherUnits["velTimeUnit"])
442 return units.getRedshiftConverter(self.unit, self.velTimeUnit,
443 otherUnits[0], otherUnits[1], True)
444
445 def getUnitArgs(self):
446 return {"unit": self.unit, "velTimeUnit": self.velTimeUnit}
447
448
449 class SpaceCoo(_Coordinate, _SpatialMixin):
450 pgClass = pgsphere.SPoint
451
452 class VelocityCoo(_Coordinate, _VelocityMixin): pass
453 class RedshiftCoo(_Coordinate, _RedshiftMixin): pass
454
455 class TimeCoo(_Coordinate, _OneDMixin):
456 cType = TimeType
457
458 def iterTransformed(self, converter):
459 # here, we never transform the value (since it can be a datetime
460 # or whatever).
461 for attName in self._dimensionedAttrs:
462 wiggle = getattr(self, attName)
463 if wiggle:
464 yield attName, wiggle.adaptValuesWith(converter)
465
466 class SpectralCoo(_Coordinate, _OneDMixin):
467 cType = SpectralType
468
469
470 _positionClassMap = {
471 SpectralType: SpectralCoo,
472 TimeType: TimeCoo,
473 SpaceType: SpaceCoo,
474 RedshiftType: RedshiftCoo,
475 VelocityType: VelocityCoo,
476 }
477
478
479 class _CoordinateInterval(_CoordinateLike):
480 _a_lowerLimit = None
481 _a_upperLimit = None
482 _a_fillFactor = None
483 _a_origUnit = None
484
485 inexactAttrs = set(["lowerLimit", "upperLimit"])
486
487 def adaptValuesWith(self, converter):
488 changes = {"origUnit": None}
489 if self.lowerLimit is not None:
490 changes["lowerLimit"] = converter(self.lowerLimit)
491 if self.upperLimit is not None:
492 changes["upperLimit"] = converter(self.upperLimit)
493 return self.change(**changes)
494
495 def getTransformed(self, sTrafo, destFrame):
496 ll, ul = self.lowerLimit, self.upperLimit
497 if ll is None:
498 return self.change(upperLimit=sTrafo(ul), frame=destFrame)
499 elif ul is None:
500 return self.change(lowerLimit=sTrafo(ll), frame=destFrame)
501 else:
502 return self.change(upperLimit=sTrafo(ul), lowerLimit=sTrafo(ll),
503 frame=destFrame)
504
505
506 def getValues(self):
507 return [l for l in (self.lowerLimit, self.upperLimit) if l is not None]
508
509 class SpaceInterval(_CoordinateInterval):
510 cType = SpaceType
511
512 # See fromPgSphere docstring on this
513 pgClass = pgsphere.SBox
514
515 def getValues(self):
516 return reduce(lambda a,b: a+b, _CoordinateInterval.getValues(self))
517
518 def getTransformed(self, sTrafo, destFrame):
519 # for n-d coordinates, upper and lower limit can be difficult
520 # under rotations. We need to look into this (>2 would need separate
521 # support)
522 ll, ul = self.lowerLimit, self.upperLimit
523 if (self.frame.nDim==1
524 or (self.lowerLimit is None or self.upperLimit is None)):
525 return _CoordinateInterval.getTransformed(self, sTrafo, destFrame)
526 elif self.frame.nDim==2:
527 vertices = [sTrafo(coo) for coo in (
528 (ll[0], ll[1]), (ul[0], ll[1]), (ll[0], ul[1]), (ul[0], ul[1]))]
529 xVals = [coo[0] for coo in vertices]
530 yVals = [coo[1] for coo in vertices]
531 return self.change(upperLimit=(max(xVals), max(yVals)),
532 lowerLimit=(min(xVals), min(yVals)), frame=destFrame)
533 else:
534 raise NotImplementedError("Cannot yet transform coordinate intervals"
535 " in n>2 dims.")
536
537 @classmethod
538 def fromPg(cls, frame, pgBox):
539 return cls(frame=frame,
540 lowerLimit=(pgBox.corner1.x/utils.DEG, pgBox.corner1.y/utils.DEG),
541 upperLimit=(pgBox.corner2.x/utils.DEG, pgBox.corner2.y/utils.DEG))
542
543
544 # Service for stcsast -- this may go away again
545 PositionInterval = SpaceInterval
546
547
548 class VelocityInterval(_CoordinateInterval):
549 cType = VelocityType
550
551 class RedshiftInterval(_CoordinateInterval):
552 cType = RedshiftType
553
554 class TimeInterval(_CoordinateInterval):
555 cType = TimeType
556
557 def adaptValuesWith(self, converter):
558 # timeIntervals are unitless; units only refer to errors, etc,
559 # which we don't have here.
560 return self
561
562
563 class SpectralInterval(_CoordinateInterval):
564 cType = SpectralType
565
566
567
568 ################ Geometries
569
570 class _Geometry(_CoordinateLike):
571 """A base class for all kinds of geometries.
572
573 Geometries may have "dependent" quantities like radii, sizes, etc. For
574 those, the convention is that if they are 1D, they must be expressed in the
575 unit of the first component of the position units, otherwise (in particular,
576 for box size) in the full unit of the position. This has to be made sure by
577 the client.
578
579 To make this work, Geometries are unit adapted on STC adoption.
580 Since their dependents need to be adapted as well, they have to
581 define adaptDependents(...) methods. They take the units for
582 all dependent quantities (which may all be None). This is used
583 in stxast.
584
585 Also getTransformed usually needs to be overridden for these.
586
587 Geometries may contain two sorts of column references; ordinary ones
588 are just stand-ins of actual values, while GeometryColRefs describe the
589 whole thing in a database column.
590
591 For the spatial registry prototype, geometries can define an
592 asSMoc(order=6) method returning a pgpshere.SMoc coverage for them.
593 """
594 _a_size = None
595 _a_fillFactor = None
596 _a_origUnit = None
597 _a_geoColRef = None
598
599 cType = SpaceType
600
601 def getValues(self):
602 if self.geoColRef:
603 return [self.geoColRef]
604 else:
605 return self._getValuesSplit()
606
607
608 class AllSky(_Geometry):
609 def getTransformed(self, sTrafo, destFrame):
610 return self.change(frame=destFrame)
611
612 def adaptValuesWith(self, converter):
613 return self
614
615 def adaptDepUnits(self):
616 pass
617
618 def _getValuesSplit(self):
619 return []
620
621 def asSMoc(self, order=6):
622 return pgsphere.SMoc.fromCells(0, list(range(12)))
623
624
625 class Circle(_Geometry):
626 _a_center = None
627 _a_radius = None
628
629 pgClass = pgsphere.SCircle
630
631 def getTransformed(self, sTrafo, destFrame):
632 return self.change(center=sTrafo(self.center), frame=destFrame)
633
634 def adaptValuesWith(self, converter):
635 sTrafo = units.getBasicConverter(converter.fromUnit[0],
636 converter.toUnit[0])
637 return self.change(center=converter(self.center),
638 radius=sTrafo(self.radius))
639
640 def _getValuesSplit(self):
641 return [self.center[0], self.center[1], self.radius]
642
643 @classmethod
644 def fromPg(cls, frame, sCircle):
645 return cls(frame=frame,
646 center=(sCircle.center.x/utils.DEG, sCircle.center.y/utils.DEG),
647 radius=(sCircle.radius/utils.DEG))
648
649 def asSMoc(self, order):
650 return pgsphere.SCircle(
651 pgsphere.SPoint.fromDegrees(*self.center),
652 self.radius*utils.DEG
653 ).asPoly(
654 ).asSMoc()
655
656
657 class Ellipse(_Geometry):
658 _a_center = None
659 _a_smajAxis = _a_sminAxis = None
660 _a_posAngle = None
661
662 def getTransformed(self, sTrafo, destFrame):
663 # XXX TODO: actually rotate the ellipse.
664 return self.change(center=sTrafo(self.center), frame=destFrame)
665
666 def adaptValuesWith(self, converter):
667 sTrafo = units.getBasicConverter(converter.fromUnit[0],
668 converter.toUnit[0])
669 return self.change(center=converter(self.center),
670 smajAxis=sTrafo(self.smajAxis), sminAxis=sTrafo(self.sminAxis))
671
672 def _getValuesSplit(self):
673 return list(self.center)+[self.smajAxis]+[self.sminAxis]+[
674 self.posAngle]
675
676
677 class Box(_Geometry):
678 _a_center = None
679 _a_boxsize = None
680
681 def getTransformed(self, sTrafo, destFrame):
682 """returns a Polygon corresponding to this Box after rotation.
683 """
684 center, boxsize = self.center, self.boxsize
685 return Polygon(vertices=tuple(sTrafo(coo) for coo in (
686 (center[0]-boxsize[0], center[1]-boxsize[1]),
687 (center[0]-boxsize[0], center[1]+boxsize[1]),
688 (center[0]+boxsize[0], center[1]+boxsize[1]),
689 (center[0]+boxsize[0], center[1]-boxsize[1]))), frame=destFrame)
690
691 def adaptValuesWith(self, converter):
692 return self.change(center=converter(self.center),
693 boxsize=converter(self.boxsize))
694
695 def _getValuesSplit(self):
696 return list(self.center)+list(self.boxsize)
697
698
699 class Polygon(_Geometry):
700 _a_vertices = ()
701
702 pgClass = pgsphere.SPoly
703
704 def __init__(self, *args, **kwargs):
705 _Geometry.__init__(self, *args, **kwargs)
706
707 def getTransformed(self, sTrafo, destFrame):
708 return self.change(vertices=tuple(sTrafo(v) for v in self.vertices),
709 frame=destFrame)
710
711 def adaptValuesWith(self, converter):
712 return self.change(vertices=tuple(converter(v) for v in self.vertices))
713
714 def _getValuesSplit(self):
715 return reduce(operator.add, self.vertices)
716
717 @classmethod
718 def fromPg(cls, frame, sPoly):
719 return cls(frame=frame,
720 vertices=[(p.x/utils.DEG, p.y/utils.DEG)
721 for p in sPoly.points])
722
723 def asSMoc(self, order=6):
724 # let's assume points are in degrees here; this is hopefully only
725 # temporary, anyway
726 return pgsphere.SPoly(
727 [pgsphere.SPoint.fromDegrees(*p) for p in self.vertices]).asSMoc(order)
728
729
730 class Convex(_Geometry):
731 _a_vectors = ()
732
733 def getTransformed(self, sTrafo, destFrame):
734 raise common.STCNotImplementedError("Cannot transform convexes yet.")
735
736 def adaptValuesWith(self, converter):
737 raise common.STCNotImplementedError("Cannot adapt units for convexes yet.")
738
739 def _getValuesSplit(self):
740 return reduce(operator.add, self.vectors)
741
742
743 class _Compound(_Geometry):
744 """A set-like operator on geometries.
745 """
746 _a_children = ()
747
748 def polish(self):
749 for node in self.children:
750 if node.frame is None:
751 node.frame = self.frame
752 getattr(node, "polish", lambda: None)()
753
754
755 def adaptValuesWith(self, converter):
756 return self.change(children=[child.adaptValuesWith(converter)
757 for child in self.children])
758
759 def _applyToChildren(self, function):
760 newChildren, changes = [], False
761 for c in self.children:
762 nc = function(c)
763 newChildren.append(nc)
764 changes = changes or (c is not nc)
765 if changes:
766 return self.change(children=newChildren)
767 else:
768 return self
769
770 def binarizeOperands(self):
771 """returns self with binarized operands.
772
773 If no operand needed binarizing, self is returned.
774 """
775 res = self._applyToChildren(binarizeCompound)
776 return res
777
778 def debinarizeOperands(self):
779 """returns self with debinarized operands.
780
781 If no operand needed debinarizing, self is returned.
782 """
783 return self._applyToChildren(debinarizeCompound)
784
785 def getTransformed(self, sTrafo, destFrame):
786 return self.change(children=tuple(
787 child.getTransformed(sTrafo, destFrame) for child in self.children),
788 frame=destFrame)
789
790
791 class _MultiOpCompound(_Compound):
792 """is a compound that has a variable number of operands.
793 """
794
795
796 class Union(_MultiOpCompound): pass
797 class Intersection(_MultiOpCompound): pass
798 class Difference(_Compound): pass
799 class Not(_Compound): pass
800
801
802 def _buildBinaryTree(compound, items):
803 """returns a binary tree of nested instances compound instances.
804
805 items has to have at least length 2.
806 """
807 items = list(items)
808 root = compound.change(children=items[-2:])
809 items[-2:] = []
810 while items:
811 root = compound.change(children=[items.pop(), root])
812 return root
813
814
815 def binarizeCompound(compound):
816 """returns compound as a binary tree.
817
818 For unions and intersections, compounds consisting of more than two
819 operands will be split up into parts of two arguments each.
820 """
821 if not isinstance(compound, _Compound):
822 return compound
823 compound = compound.binarizeOperands()
824 if len(compound.children)==1:
825 return compound.children[0]
826 elif len(compound.children)==2:
827 return compound
828 else:
829 newChildren = [compound.children[0],
830 _buildBinaryTree(compound, compound.children[1:])]
831 return compound.change(children=newChildren)
832
833
834 def debinarizeCompound(compound):
835 """returns compound with flattened operators.
836 """
837 if not isinstance(compound, _Compound):
838 return compound
839 compound = compound.debinarizeOperands()
840 newChildren, changes = [], False
841 for c in compound.children:
842 if c.__class__==compound.__class__:
843 newChildren.extend(c.children)
844 changes = True
845 else:
846 newChildren.append(c)
847 if changes:
848 return compound.change(children=newChildren)
849 else:
850 return compound
851
852
853 ################ Toplevel
854
855 class STCSpec(common.ASTNode):
856 """is an STC specification, i.e., the root of an STC tree.
857 """
858 _a_astroSystem = None
859 _a_systems = ()
860 _a_time = None
861 _a_place = None
862 _a_freq = None
863 _a_redshift = None
864 _a_velocity = None
865 _a_timeAs = ()
866 _a_areas = ()
867 _a_freqAs = ()
868 _a_redshiftAs = ()
869 _a_velocityAs = ()
870
871 @property
872 def sys(self):
873 return self.astroSystem
874
875 def buildIdMap(self):
876 if hasattr(self, "idMap"):
877 return
878 self.idMap = {}
879 for node in self.iterNodes():
880 if node.id:
881 self.idMap[node.id] = node
882
883 def polish(self):
884 """does global fixups when parsing is finished.
885
886 This method has to be called after the element is complete. The
887 standard parsers do this.
888
889 For convenience, it returns the instance itself.
890 """
891 # Fix local frames if not given (e.g., manual construction)
892 if self.place is not None and self.place.frame is None:
893 self.place.frame = self.astroSystem.spaceFrame
894 for area in self.areas:
895 if area.frame is None:
896 area.frame = self.astroSystem.spaceFrame
897 getattr(area, "polish", lambda: None)()
898
899 # Operations here cannot be in a _setupNode since when parsing from
900 # XML, there may be IdProxies instead of real objects.
901 # Equinox for ecliptic defaults to observation time
902 if self.place:
903 frame = self.place.frame
904 if frame and frame.equinox is None and frame.refFrame=="ECLIPTIC":
905 if self.time and self.time.value:
906 frame.equinox = "J%.8f"%(times.dateTimeToJYear(self.time.value))
907 return self
908
909 def _applyToAreas(self, function):
910 newAreas, changes = [], False
911 for a in self.areas:
912 na = function(a)
913 changes = changes or na is not a
914 newAreas.append(na)
915 if changes:
916 return self.change(areas=newAreas)
917 else:
918 return self
919
920 def binarize(self):
921 """returns self with any compound present brought to a binary tree.
922
923 This will return self if nothing needs to change.
924 """
925 return self._applyToAreas(binarizeCompound)
926
927 def debinarize(self):
928 """returns self with any compound present brought to a binary tree.
929
930 This will return self if nothing needs to change.
931 """
932 return self._applyToAreas(debinarizeCompound)
933
934 def getColRefs(self):
935 """returns a list of column references embedded in this AST.
936 """
937 if not hasattr(self, "_colRefs"):
938 self._colRefs = []
939 for n in self.iterNodes():
940 if hasattr(n, "getValues"):
941 self._colRefs.extend(
942 v.dest for v in n.getValues() if isinstance(v, common.ColRef))
943 return self._colRefs
944
945 def stripUnits(self):
946 """removes all unit specifications from this AST.
947
948 This is intended for non-standalone STC, e.g., in VOTables, where
949 external unit specifications are present. Removing the units
950 prevents "bleeding out" of conflicting in-STC specifications
951 (that mostly enter through defaulting).
952
953 This ignores the immutability of nodes and is in general a major pain.
954 """
955 for node in self.iterNodes():
956 if hasattr(node, "unit"):
957 node.unit = node.__class__._a_unit
958 if hasattr(node, "velTimeUnit"):
959 node.velTimeUnit = node.__class__._a_unit
960
961
962 def fromPgSphere(refFrame, pgGeom):
963 """Returns an AST for a pgsphere object as defined in utils.pgsphere.
964
965 This interprets the pgSphere box as a coordinate interval, which is wrong
966 but probably what most VO protocols expect.
967 """
968 frame = SpaceFrame(refFrame=refFrame)
969
970 if isinstance(pgGeom, SpaceCoo.pgClass):
971 return STCSpec(place=SpaceCoo.fromPg(frame, pgGeom))
972
973 for stcGeo in [Circle, SpaceInterval, Polygon]:
974 if isinstance(pgGeom, stcGeo.pgClass):
975 return STCSpec(areas=[stcGeo.fromPg(frame, pgGeom)])
976
977 raise common.STCValueError("Unknown pgSphere object %r"%pgGeom)