| 1 |
""" |
| 2 |
Definitions and shared code for STC processing. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import math |
| 12 |
import operator |
| 13 |
|
| 14 |
from gavo import utils |
| 15 |
from gavo.utils import ElementTree #noflake:clients expect this name |
| 16 |
from gavo.utils.stanxml import Stub, registerPrefix, schemaURL |
| 17 |
from functools import reduce |
| 18 |
|
| 19 |
|
| 20 |
class STCError(utils.Error): |
| 21 |
pass |
| 22 |
|
| 23 |
class STCSParseError(STCError): |
| 24 |
"""is raised if an STC-S expression could not be parsed. |
| 25 |
|
| 26 |
Low-level routines raise a pyparsing ParseException. Only higher |
| 27 |
level functions raise this error. The offending expression is in |
| 28 |
the expr attribute, the start position of the offending phrase in pos. |
| 29 |
""" |
| 30 |
def __init__(self, msg, expr=None, pos=None): |
| 31 |
STCError.__init__(self, msg) |
| 32 |
self.args = [msg, expr, pos] |
| 33 |
self.pos, self.expr = pos, expr |
| 34 |
|
| 35 |
|
| 36 |
class STCLiteralError(STCError): |
| 37 |
"""is raised when a literal is not well-formed. |
| 38 |
|
| 39 |
There is an attribute literal giving the malformed literal. |
| 40 |
""" |
| 41 |
def __init__(self, msg, literal=None): |
| 42 |
STCError.__init__(self, msg) |
| 43 |
self.args = [msg, literal] |
| 44 |
self.literal = literal |
| 45 |
|
| 46 |
class STCInternalError(STCError): |
| 47 |
"""is raised when assumptions about the library behaviour are violated. |
| 48 |
""" |
| 49 |
|
| 50 |
class STCValueError(STCError): |
| 51 |
"""is raised when some STC specification is inconsistent. |
| 52 |
""" |
| 53 |
|
| 54 |
class STCUnitError(STCError): |
| 55 |
"""is raised when some impossible operation on units is requested. |
| 56 |
""" |
| 57 |
|
| 58 |
class STCXBadError(STCError): |
| 59 |
"""is raised when something is wrong with STC-X. |
| 60 |
""" |
| 61 |
|
| 62 |
class STCNotImplementedError(STCError): |
| 63 |
"""is raised when the current implementation limits are reached. |
| 64 |
""" |
| 65 |
|
| 66 |
#### Constants |
| 67 |
|
| 68 |
TWO_PI = 2*math.pi |
| 69 |
tropicalYear = 365.242198781 # in days |
| 70 |
secsPerJCy = 36525*86400. |
| 71 |
|
| 72 |
STCNamespace = "http://www.ivoa.net/xml/STC/stc-v1.30.xsd" |
| 73 |
XlinkNamespace = "http://www.w3.org/1999/xlink" |
| 74 |
|
| 75 |
registerPrefix("stc", STCNamespace, |
| 76 |
schemaURL("stc-v1.30.xsd")) |
| 77 |
registerPrefix("xlink", XlinkNamespace, |
| 78 |
schemaURL("xlink.xsd")) |
| 79 |
|
| 80 |
|
| 81 |
# The following lists have to be updated when the STC standard is |
| 82 |
# updated. They are used for building the STC-X namespace. |
| 83 |
|
| 84 |
# known space reference frames |
| 85 |
stcSpaceRefFrames = set(["ICRS", "FK4", "FK5", "ECLIPTIC", "GALACTIC_I", |
| 86 |
"GALACTIC_II", "SUPER_GALACTIC", "AZ_EL", "BODY", "GEO_C", "GEO_D", "MAG", |
| 87 |
"GSE", "GSM", "SM", "HGC", "HGS", "HPC", "HPR", "HEE", "HEEQ", "HGI", |
| 88 |
"HRTN", "MERCURY_C", "VENUS_C", "LUNA_C", "MARS_C", "JUPITER_C_III", |
| 89 |
"SATURN_C_III", "UNKNOWNFrame"]) |
| 90 |
|
| 91 |
# known space reference positions |
| 92 |
stcRefPositions = set(["TOPOCENTER", "BARYCENTER", "HELIOCENTER", "GEOCENTER", |
| 93 |
"LSR", "LSRK", "LSRD", "GALACTIC_CENTER", "LOCAL_GROUP_CENTER", "MOON", |
| 94 |
"EMBARYCENTER", "MERCURY", "VENUS", "MARS", "JUPITER", "SATURN", "URANUS", |
| 95 |
"NEPTUNE", "PLUTO", "RELOCATABLE", "UNKNOWNRefPos", "CoordRefPos"]) |
| 96 |
|
| 97 |
# known flavors for coordinates |
| 98 |
stcCoordFlavors = set(["SPHERICAL", "CARTESIAN", "UNITSPHERE", "POLAR", |
| 99 |
"CYLINDRICAL", "STRING", "HEALPIX"]) |
| 100 |
|
| 101 |
# known time scales |
| 102 |
stcTimeScales = set(["TT", "TDT", "ET", "TAI", "IAT", "UTC", "TEB", "TDB", |
| 103 |
"TCG", "TCB", "LST", "nil"]) |
| 104 |
|
| 105 |
|
| 106 |
# Nodes for ASTs |
| 107 |
|
| 108 |
def _compareFloat(val1, val2): |
| 109 |
"""returns true if val1==val2 up to a fudge factor. |
| 110 |
|
| 111 |
This only works for floats. |
| 112 |
|
| 113 |
>>> _compareFloat(30.0, 29.999999999999996) |
| 114 |
True |
| 115 |
""" |
| 116 |
try: |
| 117 |
return abs(val1-val2)/val1<1e-12 |
| 118 |
except ZeroDivisionError: # val1 is zero |
| 119 |
return val2==0 |
| 120 |
|
| 121 |
|
| 122 |
def _aboutEqual(val1, val2): |
| 123 |
"""compares val1 and val2 inexactly. |
| 124 |
|
| 125 |
This is for comparing floats or sequences of floats. If you pass in |
| 126 |
other sequences, bad things will happen. |
| 127 |
|
| 128 |
It will return true if val1 and val2 are deemed equal. |
| 129 |
|
| 130 |
>>> _aboutEqual(2.3, 2.2999999999999997) |
| 131 |
True |
| 132 |
>>> _aboutEqual(2.3, 2.299999997) |
| 133 |
False |
| 134 |
>>> _aboutEqual(None, 2.3) |
| 135 |
False |
| 136 |
>>> _aboutEqual((1e-10,1e10), (1.00000000000001e-10,1.00000000000001e10)) |
| 137 |
True |
| 138 |
>>> _aboutEqual((1e-10,1e10), (1.0000000001e-10,1.000000001e10)) |
| 139 |
False |
| 140 |
""" |
| 141 |
if val1==val2: |
| 142 |
return True |
| 143 |
if isinstance(val1, float) and isinstance(val2, float): |
| 144 |
return _compareFloat(val1, val2) |
| 145 |
try: |
| 146 |
return reduce(operator.and_, (_compareFloat(*p) |
| 147 |
for p in zip(val1, val2))) |
| 148 |
except TypeError: # At least one value is not iterable |
| 149 |
return False |
| 150 |
|
| 151 |
|
| 152 |
class ASTNode(utils.AutoNode): |
| 153 |
"""The base class for all nodes in STC ASTs. |
| 154 |
""" |
| 155 |
_a_ucd = None |
| 156 |
_a_id = None |
| 157 |
|
| 158 |
inexactAttrs = set() |
| 159 |
|
| 160 |
# we want fast comparison for identitical objects. |
| 161 |
def __eq__(self, other): |
| 162 |
if not isinstance(other, self.__class__): |
| 163 |
return False |
| 164 |
if self is other: |
| 165 |
return True |
| 166 |
for name, _ in self._nodeAttrs: |
| 167 |
if name=="id": |
| 168 |
continue |
| 169 |
if name in self.inexactAttrs: |
| 170 |
if not _aboutEqual(getattr(self, name), getattr(other, name)): |
| 171 |
return False |
| 172 |
elif getattr(self, name)!=getattr(other, name): |
| 173 |
return False |
| 174 |
return True |
| 175 |
|
| 176 |
def __ne__(self, other): |
| 177 |
return not self==other |
| 178 |
|
| 179 |
def __hash__(self): |
| 180 |
return hash(id(self)) |
| 181 |
|
| 182 |
def ensureId(self): |
| 183 |
"""sets id to some value if still None. |
| 184 |
""" |
| 185 |
if self.id is None: |
| 186 |
self.id = utils.intToFunnyWord(id(self)) |
| 187 |
|
| 188 |
|
| 189 |
class ColRef(Stub): |
| 190 |
"""A column reference instead of a true value, occurring in an STC-S tree. |
| 191 |
""" |
| 192 |
name_ = "_colRef" |
| 193 |
|
| 194 |
# A ghastly hack: if someone sets this true at some point this |
| 195 |
# reference will be rendered to a PARAMref rather than a FIELDref |
| 196 |
# in VOTables. Well, this whole code needs overdoing. |
| 197 |
toParam = False |
| 198 |
|
| 199 |
def __str__(self): |
| 200 |
return self.dest |
| 201 |
# only for debugging: '"%s"'%self.dest |
| 202 |
|
| 203 |
def __mul__(self, other): |
| 204 |
raise STCValueError("ColRefs (here, %s) cannot be used in arithmetic" |
| 205 |
" expressions."%repr(self)) |
| 206 |
|
| 207 |
def encode(self, encoding): # for ElementTree.dump |
| 208 |
return self.dest.encode(encoding) |
| 209 |
|
| 210 |
def isoformat(self): |
| 211 |
return self |
| 212 |
|
| 213 |
def apply(self, func): |
| 214 |
return func(self, self.dest, {}, []) |
| 215 |
|
| 216 |
|
| 217 |
class GeometryColRef(ColRef): |
| 218 |
"""A ColRef that refers to an in-DB geometry. |
| 219 |
|
| 220 |
These comprise the entire arguments of a geometry (or all coordinates |
| 221 |
of a vector). They implement __len__ as soon as they are validated |
| 222 |
(in stcsast; we don't do col. refs in stc-x); their len is the |
| 223 |
expected number of elements. |
| 224 |
""" |
| 225 |
expectedLength = None |
| 226 |
|
| 227 |
def __len__(self): |
| 228 |
if self.expectedLength is None: |
| 229 |
raise STCValueError("No length on unvalidated geometry column" |
| 230 |
" reference") |
| 231 |
return self.expectedLength |
| 232 |
|
| 233 |
def __bool__(self): |
| 234 |
return True |
| 235 |
|
| 236 |
|
| 237 |
def clampLong(val): |
| 238 |
"""returns val standardized as a latitude. |
| 239 |
|
| 240 |
Our latitudes are always in [0, 2*pi]. |
| 241 |
""" |
| 242 |
val = math.fmod(val, TWO_PI) |
| 243 |
if val<0: |
| 244 |
val += TWO_PI |
| 245 |
return val |
| 246 |
|
| 247 |
|
| 248 |
def clampLat(val): |
| 249 |
"""returns val standardized as a latitude. |
| 250 |
|
| 251 |
Our latitudes are always in [-pi, pi]. |
| 252 |
""" |
| 253 |
val = math.fmod(val, TWO_PI) |
| 254 |
if val<-math.pi: |
| 255 |
val += TWO_PI |
| 256 |
if val>math.pi: |
| 257 |
val -= TWO_PI |
| 258 |
return val |
| 259 |
|
| 260 |
|
| 261 |
def _test(): |
| 262 |
import doctest |
| 263 |
doctest.testmod() |
| 264 |
|
| 265 |
if __name__=="__main__": |
| 266 |
_test() |