| 1 |
""" |
| 2 |
A python module to parse VOUnit strings and compute conversion factors. |
| 3 |
|
| 4 |
We believe this implements the full VOUnit specification. |
| 5 |
|
| 6 |
To use this, you must have the gavo utils package installed. For |
| 7 |
details, see http://soft.g-vo.org. The changes required to make this |
| 8 |
work without gavo.utils are minute, though. If you want that, talk to |
| 9 |
the authors. |
| 10 |
""" |
| 11 |
|
| 12 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 13 |
#c |
| 14 |
#c This program is free software, covered by the GNU GPL. See the |
| 15 |
#c COPYING file in the source distribution. |
| 16 |
|
| 17 |
|
| 18 |
import functools |
| 19 |
import math |
| 20 |
|
| 21 |
from gavo import utils |
| 22 |
from gavo.utils import parsetricks |
| 23 |
from gavo.imp.pyparsing import ParseResults |
| 24 |
|
| 25 |
from gavo.utils.dachstypes import (cast, |
| 26 |
Callable, Dict, Optional, Sequence, |
| 27 |
Tuple, TYPE_CHECKING, Union) |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from gavo.rscdef import ColumnList |
| 31 |
|
| 32 |
# This is what is returned from getSI; it's a scalar factor and an SI |
| 33 |
# conversion, which maps SI unit strings to their powers; if there are |
| 34 |
# functions involved, the dict keys can also be tuples |
| 35 |
# (see FunctionApplication) |
| 36 |
_SIPower = Union[str, Tuple] |
| 37 |
_SIPowers = Dict[_SIPower, float] |
| 38 |
_SIFactor = Tuple[float, _SIPowers] |
| 39 |
|
| 40 |
|
| 41 |
class IncompatibleUnits(utils.Error): |
| 42 |
pass |
| 43 |
|
| 44 |
class BadUnit(utils.Error): |
| 45 |
pass |
| 46 |
|
| 47 |
PLANCK_H = 6.62607015e-34 |
| 48 |
LIGHT_C = 299792458.0 |
| 49 |
BOLTZMANN_K = 1.380649e-23 |
| 50 |
ELECTRON_CHARGE = 1.602176634e-19 |
| 51 |
|
| 52 |
|
| 53 |
# We can't yet restructure the tree, so we don't do SI-base-casting for |
| 54 |
# compound units. Also, we don't change anything when a change of exponent |
| 55 |
# would be necessary |
| 56 |
PLAIN_UNITS = units = { |
| 57 |
"a": (3600*24*365.25, "s"), # This is the SI/julian year! |
| 58 |
"A": (1, "A"), # *Ampere* not Angstrom |
| 59 |
"adu": (1, "adu"), |
| 60 |
"\xc5": (1e-10, "m"), |
| 61 |
"Angstrom": (1e-10, "m"), |
| 62 |
"angstrom": (1e-10, "m"), |
| 63 |
"AU": (1.495978701e11, "m"), # as per ESA/SP-1200 |
| 64 |
"arcmin": (math.pi/180./60., "rad"), |
| 65 |
"arcsec": (math.pi/180./3600., "rad"), |
| 66 |
"barn": (1, "barn"), # 1e-28 m2 |
| 67 |
"beam": (1, "beam"), |
| 68 |
"bit": (1, "bit"), |
| 69 |
"bin": (1, "bin"), |
| 70 |
"byte": (1, "byte"), # I don't think we ever want to unify bit and byte |
| 71 |
"C": (1, "C"), # A.s |
| 72 |
"cd": (1, "cd"), |
| 73 |
"ct": (1, "ct"), |
| 74 |
"count": (1, "ct"), |
| 75 |
"chan": (1, "chan"), |
| 76 |
"D": (1e-19/3., "D"), # C.m |
| 77 |
"d": (3600*24, "s"), |
| 78 |
"deg": (math.pi/180., "rad"), |
| 79 |
"erg": (1e-7, "J"), |
| 80 |
"eV": (1.6021766208e-19, "J"), |
| 81 |
"F": (1, "F"), # C/V |
| 82 |
"g": (1e-3, "kg"), |
| 83 |
"G": (1e-4, "T"), |
| 84 |
"h": (3600., "s"), |
| 85 |
"H": (1, "H"), # Wb/A |
| 86 |
"Hz": (1, "Hz"), # s-1 |
| 87 |
"J": (1, "J"), # kg m^2/s^2 |
| 88 |
"Jy": (1, "Jy"), # 1e-26 W/m2/Hz |
| 89 |
"K": (1, "K"), |
| 90 |
"lm": (1, "lm"), |
| 91 |
"lx": (1, "lx"), |
| 92 |
"lyr": (2627980686828.0, "m"), |
| 93 |
"m": (1, "m"), |
| 94 |
"mag": (1, "mag"), # correlate that with, erm, lux? |
| 95 |
"mas": (math.pi/180./3.6e6, "rad"), |
| 96 |
"min": (60, "s"), |
| 97 |
"mol": (1, "mol"), |
| 98 |
"N": (1, "N"), # kg.m/s2 |
| 99 |
"Ohm": (1, "Ohm"), # V/A |
| 100 |
"Pa": (1, "Pa"), # N/m^2 |
| 101 |
"pc": (3.0857e16, "m"), |
| 102 |
"ph": (1, "ph"), |
| 103 |
"photon": (1, "ph"), |
| 104 |
"pix": (1, "pix"), |
| 105 |
"pixel": (1, "pix"), |
| 106 |
"R": (1, "R"), # Rayleigh |
| 107 |
"rad": (1, "rad"), |
| 108 |
"Ry": (2.17989e-18, "J"), |
| 109 |
"s": (1, "s"), |
| 110 |
"S": (1, "S"), # A/V |
| 111 |
"solLum": (3.826e26, "W"), |
| 112 |
"solMass": (1.989e30, "kg"), |
| 113 |
"solRad": (6.9559e8, "m"), |
| 114 |
"sr": (1, "sr"), |
| 115 |
"T": (1, "T"), # V.s/m2 |
| 116 |
"u": (1.66053886e-27, "kg"), |
| 117 |
"V": (1, "V"), |
| 118 |
"voxel": (1, "voxel"), |
| 119 |
"W": (1, "W"), # kg.m2/s3 or A.V -- that's going to be a tough one |
| 120 |
"Wb": (1, "Wb"), |
| 121 |
"yr": (3600*24*365.25, "s"), # This is the SI/julian year! |
| 122 |
"%": (1, "%"), # This is the SI/julian year! |
| 123 |
} |
| 124 |
|
| 125 |
|
| 126 |
EXCEPTIONAL_CONVERSIONS: Dict[Tuple[Sequence[_SIPower], Sequence[_SIPower]], float] = { |
| 127 |
# tuple-form of units: conversions that are still linear but |
| 128 |
# somehow idiosyncratic. |
| 129 |
|
| 130 |
# wave number to energy |
| 131 |
((('m', -1.0),), (('J', 1),)): PLANCK_H*LIGHT_C, |
| 132 |
} |
| 133 |
|
| 134 |
# These are the keys from PLAIN_UNITS that cannot take SI prefixes |
| 135 |
NON_PREFIXABLE = frozenset([ |
| 136 |
"AU", "au", "D", "Ry", "arcmin", "beam", "bin", "chan", "d", "h", "mas", |
| 137 |
"min", "ph", "photon", "pix", "pixel", "solLum", "solMass", "solRad", |
| 138 |
"voxel", "%"]) |
| 139 |
|
| 140 |
|
| 141 |
PREFIXES = prefixes = {"d": 1e-1, "c": 1e-2, "m":1e-3, "u":1e-6, |
| 142 |
"n":1e-9, "p":1e-12, "f":1e-15, "a":1e-18, "z":1e-21, "y":1e-24, |
| 143 |
"da": 10., "h":1e2, "k":1e3, "M":1e6, "G":1e9, "T":1e12, "P":1e15, |
| 144 |
"E":1e18, "Z":1e21, "Y":1e24, "": 1} |
| 145 |
|
| 146 |
|
| 147 |
# these map VOUnit Table 5 "magic" units to UnitNode constructor arguments |
| 148 |
AMBIGUOUS_STRINGS = { |
| 149 |
'Pa': ('Pa', ''), |
| 150 |
'ha': ('yr', 'h'), |
| 151 |
'cd': ('cd', ''), |
| 152 |
'dB': ('Bel', 'd'), |
| 153 |
'B': ('Byte', ''), |
| 154 |
'au': ('AU', ''), |
| 155 |
'dadu': ('adu', 'd'), |
| 156 |
} |
| 157 |
|
| 158 |
|
| 159 |
def formatScaleFactor(aFloat: float) -> str: |
| 160 |
"""returns a reasonable decorative but python-readable representation |
| 161 |
of aFloat. |
| 162 |
|
| 163 |
Floats looking good as simple decimals (modulus between 0.01 and 1000) |
| 164 |
are returned without exponent. |
| 165 |
""" |
| 166 |
if 0.01<=abs(aFloat)<=1000: |
| 167 |
return ("%f"%aFloat).rstrip("0") |
| 168 |
|
| 169 |
exponent = int(math.log10(aFloat)) |
| 170 |
mantissa = ("%f"%(aFloat/10**exponent)).rstrip("0") |
| 171 |
return "%se%+d"%(mantissa, exponent) |
| 172 |
|
| 173 |
|
| 174 |
class _Node: |
| 175 |
"""the abstract base for a node in a Unit tree. |
| 176 |
|
| 177 |
All these must implement fromToks methods that can be called |
| 178 |
as pyparsing callbacks. |
| 179 |
""" |
| 180 |
@classmethod |
| 181 |
def fromToks(cls, s, p, toks): |
| 182 |
raise NotImplementedError("%s objects have no implementation of" |
| 183 |
" fromToks (i.e., they are broken)."%cls.__name__) |
| 184 |
|
| 185 |
|
| 186 |
class UnitNode(_Node): |
| 187 |
"""a terminal node containing a unit, possibly with a prefix |
| 188 |
|
| 189 |
This is normally constructed through the fromToks constructor. |
| 190 |
|
| 191 |
Check out the unit, prefix, and isUnknown attributes. The prefix |
| 192 |
can be turned to a factor using the PREFIXES dictionary. An empty |
| 193 |
prefix (factor 1) is represented by an empty string. |
| 194 |
|
| 195 |
There is also isValid; that's isUnknown except if an unknown unit is |
| 196 |
quoted. |
| 197 |
""" |
| 198 |
def __init__(self, unit: str, prefix: str = "") -> None: |
| 199 |
self.unit = unit |
| 200 |
self.isUnknown: bool = self.unit not in PLAIN_UNITS |
| 201 |
self.isValid: bool = not self.isUnknown |
| 202 |
self.prefix = prefix |
| 203 |
|
| 204 |
@classmethod |
| 205 |
def fromToks(cls, s: str, p: int, toks: ParseResults) -> "UnitNode": |
| 206 |
assert len(toks)==1 |
| 207 |
unitString = toks[0] |
| 208 |
|
| 209 |
if unitString in AMBIGUOUS_STRINGS: |
| 210 |
return cls(*AMBIGUOUS_STRINGS[unitString]) |
| 211 |
|
| 212 |
elif unitString in PLAIN_UNITS: |
| 213 |
return cls(unitString) |
| 214 |
|
| 215 |
elif len(unitString)>2 and unitString[:2]=="da": |
| 216 |
return cls(unitString[2:], "da") |
| 217 |
|
| 218 |
elif len(unitString)>1 and unitString[0] in PREFIXES: |
| 219 |
if unitString[1:] in NON_PREFIXABLE: |
| 220 |
raise BadUnit("No Prefixes allowed on %s"%unitString[1:]) |
| 221 |
return cls(unitString[1:], unitString[0]) |
| 222 |
|
| 223 |
else: |
| 224 |
return cls(unitString, '') |
| 225 |
|
| 226 |
def __eq__(self, other: object) -> bool: |
| 227 |
return (isinstance(other, UnitNode) |
| 228 |
and self.unit==other.unit |
| 229 |
and self.prefix==other.prefix) |
| 230 |
|
| 231 |
def __str__(self) -> str: |
| 232 |
return "%s%s"%(self.prefix, self.unit) |
| 233 |
|
| 234 |
def __repr__(self): |
| 235 |
if self.isUnknown: |
| 236 |
return "U?(%s ; %s)"%(self.prefix, repr(self.unit)) |
| 237 |
else: |
| 238 |
return "U(%s ; %s)"%(self.prefix, repr(self.unit)) |
| 239 |
|
| 240 |
def getSI(self) -> _SIFactor: |
| 241 |
"""returns a pair of factor and basic unit. |
| 242 |
|
| 243 |
Basic units are what's in the defining pairs in the PLAIN_UNITS dict. |
| 244 |
""" |
| 245 |
if self.isUnknown: |
| 246 |
# these don't hurt if they're on both sides of an equation |
| 247 |
return PREFIXES[self.prefix], {self.unit: 1} |
| 248 |
|
| 249 |
factor, basic = PLAIN_UNITS[self.unit] |
| 250 |
return PREFIXES[self.prefix]*factor, {basic: 1} |
| 251 |
|
| 252 |
|
| 253 |
class FunctionApplication(_Node): |
| 254 |
"""A function applied to a term. |
| 255 |
""" |
| 256 |
_pythonFunc: Dict[str, Callable[[float], float]] = { |
| 257 |
"ln": math.log, |
| 258 |
"log": math.log10, |
| 259 |
"exp": math.exp, |
| 260 |
"sqrt": math.sqrt, |
| 261 |
} |
| 262 |
|
| 263 |
def __init__(self, funcName: str, term: Union["Factor", "Term"]) -> None: |
| 264 |
self.funcName = funcName |
| 265 |
self.term = term |
| 266 |
self.isUnknown: bool = (self.funcName not in self._pythonFunc |
| 267 |
) or self.term.isUnknown |
| 268 |
self.isValid: bool = (self.funcName in self._pythonFunc |
| 269 |
) and self.term.isValid |
| 270 |
|
| 271 |
@classmethod |
| 272 |
def fromToks(cls, s: str, p: int, toks: ParseResults |
| 273 |
) -> "FunctionApplication": |
| 274 |
assert len(toks)==2 |
| 275 |
return cls(toks[0], toks[1]) |
| 276 |
|
| 277 |
def __str__(self) -> str: |
| 278 |
return f"{self.funcName}({self.term})" |
| 279 |
|
| 280 |
def __repr__(self): |
| 281 |
return "A(%s ; %s)"%(repr(self.funcName), repr(self.term)) |
| 282 |
|
| 283 |
def getFactorWithUnit(self, unit: UnitNode |
| 284 |
) -> Tuple[Optional[_Node], Optional[float]]: |
| 285 |
"""see this method in Term. |
| 286 |
|
| 287 |
We don't simplify any units here, as that's a bit hard in |
| 288 |
the current logic -- though there's something to be won, in particular |
| 289 |
with sqrt. Ah well. |
| 290 |
""" |
| 291 |
return None, None |
| 292 |
|
| 293 |
def getSI(self) -> _SIFactor: |
| 294 |
factor, powers = self.term.getSI() |
| 295 |
if self.funcName=="sqrt": |
| 296 |
powers = dict((key, value/2.) |
| 297 |
for key, value in powers.items()) |
| 298 |
else: |
| 299 |
powers = dict(((self.funcName, key), value) |
| 300 |
for key, value in powers.items()) |
| 301 |
return self._pythonFunc[self.funcName](factor), powers |
| 302 |
|
| 303 |
|
| 304 |
class QuotedUnitNode(_Node): |
| 305 |
"""a quoted ("defined unknown") unit. |
| 306 |
""" |
| 307 |
def __init__(self, unit: str) -> None: |
| 308 |
self.unit = unit |
| 309 |
self.isUnknown: bool = True |
| 310 |
self.isValid: bool = True |
| 311 |
|
| 312 |
@classmethod |
| 313 |
def fromToks(cls, s: str, p: int, toks: ParseResults) -> "QuotedUnitNode": |
| 314 |
return cls(toks[1]) |
| 315 |
|
| 316 |
def __str__(self) -> str: |
| 317 |
return f"'{self.unit}'" |
| 318 |
|
| 319 |
def __repr__(self): |
| 320 |
return "U?('%s')"%(repr(self.unit)) |
| 321 |
|
| 322 |
def getSI(self) -> _SIFactor: |
| 323 |
# These units stand for themselves. They don't really hurt if |
| 324 |
# they're in both terms of a conversion |
| 325 |
return 1, {self.unit: 1} |
| 326 |
|
| 327 |
|
| 328 |
class Factor(_Node): |
| 329 |
"""A UnitNode with a power. |
| 330 |
""" |
| 331 |
def __init__(self, unit: UnitNode, power: float) -> None: |
| 332 |
self.unit, self.power = unit, power |
| 333 |
self.isUnknown: bool = self.unit.isUnknown |
| 334 |
self.isValid: bool = self.unit.isValid |
| 335 |
|
| 336 |
@classmethod |
| 337 |
def fromToks(cls, s: str, p: int, toks: ParseResults) -> "Factor": |
| 338 |
if len(toks)==2: |
| 339 |
return cls(toks[0], toks[1]) |
| 340 |
elif len(toks)==1: |
| 341 |
return cls(toks[0], 1) |
| 342 |
else: |
| 343 |
raise Exception("This cannot happen") |
| 344 |
|
| 345 |
def __str__(self) -> str: |
| 346 |
if self.power==0: |
| 347 |
return "1" |
| 348 |
|
| 349 |
powerLit = repr(self.power).rstrip("0").rstrip(".") |
| 350 |
if "." in powerLit: |
| 351 |
# see if we can come up with a nice fraction |
| 352 |
for denom in range(2, 8): |
| 353 |
if abs(int(self.power*denom)-self.power*denom)<1e-13: |
| 354 |
powerLit = "(%d/%d)"%(round(self.power*denom), denom) |
| 355 |
break |
| 356 |
|
| 357 |
if powerLit=="1": |
| 358 |
powerLit = "" |
| 359 |
else: |
| 360 |
powerLit = "**"+powerLit |
| 361 |
|
| 362 |
return "%s%s"%(self.unit, powerLit) |
| 363 |
|
| 364 |
def __repr__(self): |
| 365 |
return "F(%s ; %s)"%(repr(self.unit), repr(self.power)) |
| 366 |
|
| 367 |
def getFactorWithUnit(self, unit: UnitNode |
| 368 |
) -> Tuple[Optional[_Node], Optional[float]]: |
| 369 |
"""see Term.getFactorWithUnit. |
| 370 |
""" |
| 371 |
if self.unit==unit: |
| 372 |
return self, 1 |
| 373 |
else: |
| 374 |
return None, None |
| 375 |
|
| 376 |
def getSI(self) -> _SIFactor: |
| 377 |
factor, powers = self.unit.getSI() |
| 378 |
powers[list(powers.keys())[0]] = self.power |
| 379 |
return factor**self.power, powers |
| 380 |
|
| 381 |
|
| 382 |
class Term(_Node): |
| 383 |
"""A Node containing two factors and an operator. |
| 384 |
|
| 385 |
The operator here is either . (product) or / (division). |
| 386 |
""" |
| 387 |
_expoMapping = { |
| 388 |
'.': 1, |
| 389 |
'/': -1, |
| 390 |
} |
| 391 |
|
| 392 |
def __init__(self, op1: Factor, operator: str, op2: Union["Factor", "Term"]) -> None: |
| 393 |
assert operator in {'.', '/'} |
| 394 |
self.op1, self.operator, self.op2 = op1, operator, op2 |
| 395 |
self.isUnknown: bool = self.op1.isUnknown or self.op2.isUnknown |
| 396 |
self.isValid: bool = self.op1.isValid and self.op2.isValid |
| 397 |
|
| 398 |
@classmethod |
| 399 |
def fromToks(cls, s: str, p: int, toks: ParseResults) -> Union["Factor", "Term"]: |
| 400 |
if len(toks)==1: |
| 401 |
# avoid to many internal nodes: a 1-operand expression is the operand |
| 402 |
return toks[0] |
| 403 |
op1, operator, op2 = toks |
| 404 |
|
| 405 |
if isinstance(op2, Factor): |
| 406 |
# for now we only simplify with simple factors in the second |
| 407 |
# operand. If there are complete expressions there, I'd |
| 408 |
# have to do a lot more complex operations (e.g., take out |
| 409 |
# factors from there). |
| 410 |
existingFactorWithUnit, ef = op1.getFactorWithUnit(op2.unit) |
| 411 |
if existingFactorWithUnit: |
| 412 |
existingFactorWithUnit.power += \ |
| 413 |
op2.power*cls._expoMapping[operator]*ef |
| 414 |
return op1 |
| 415 |
|
| 416 |
return cls(op1, operator, op2) |
| 417 |
|
| 418 |
def __str__(self) -> str: |
| 419 |
op1Lit, op2Lit = str(self.op1), str(self.op2) |
| 420 |
if self.operator=='/' and isinstance(self.op2, Term): |
| 421 |
op2Lit = "(%s)"%op2Lit |
| 422 |
return "%s%s%s"%(op1Lit, self.operator, op2Lit) |
| 423 |
|
| 424 |
def __repr__(self): |
| 425 |
return "T(%s ; %s ; %s)"%(repr(self.op1), |
| 426 |
repr(self.operator), repr(self.op2)) |
| 427 |
|
| 428 |
def getFactorWithUnit(self, unit: UnitNode |
| 429 |
) -> Tuple[Optional[_Node], Optional[float]]: |
| 430 |
"""returns a factor within self with unit if it exists. |
| 431 |
|
| 432 |
Actually, it will return that factor and the exponentiation factor, |
| 433 |
which is -1 if that factor is in the denominator, 1 otherwise. |
| 434 |
This returns None, None if no such factor exists. |
| 435 |
""" |
| 436 |
from1, expo1 = self.op1.getFactorWithUnit(unit) |
| 437 |
from2, expo2 = self.op2.getFactorWithUnit(unit) |
| 438 |
if from1: |
| 439 |
return from1, expo1 |
| 440 |
elif from2: |
| 441 |
return from2, -1*cast(float, expo2) if self.operator=='/' else 1 |
| 442 |
else: |
| 443 |
return None, None |
| 444 |
|
| 445 |
def getSI(self) -> _SIFactor: |
| 446 |
factor1, powers1 = self.op1.getSI() |
| 447 |
factor2, powers2 = self.op2.getSI() |
| 448 |
newPowers = powers1 |
| 449 |
if self.operator==".": |
| 450 |
for si, power in powers2.items(): |
| 451 |
newPowers[si] = newPowers.get(si, 0)+power |
| 452 |
return factor1*factor2, newPowers |
| 453 |
elif self.operator=="/": |
| 454 |
for si, power in powers2.items(): |
| 455 |
newPowers[si] = newPowers.get(si, 0)-power |
| 456 |
return factor1/factor2, newPowers |
| 457 |
else: |
| 458 |
raise Exception("This can't happen") |
| 459 |
|
| 460 |
|
| 461 |
class Expression(_Node): |
| 462 |
"""The root node of an expression tree. |
| 463 |
|
| 464 |
This contains a term and optionally a scale factor. |
| 465 |
""" |
| 466 |
def __init__(self, term: Union[Factor, Term], scaleFactor: float) -> None: |
| 467 |
self.term, self.scaleFactor = term, scaleFactor |
| 468 |
self.isUnknown: bool = self.term.isUnknown |
| 469 |
self.isValid: bool = self.term.isValid |
| 470 |
|
| 471 |
@classmethod |
| 472 |
def fromToks(cls, s: str, p: int, toks: ParseResults) -> "Expression": |
| 473 |
if len(toks)==2: |
| 474 |
return cls(toks[1], float(toks[0])) |
| 475 |
|
| 476 |
elif len(toks)==1: |
| 477 |
return cls(toks[0], 1) |
| 478 |
|
| 479 |
else: |
| 480 |
raise Exception("This can't happen") |
| 481 |
|
| 482 |
def __str__(self) -> str: |
| 483 |
if self.scaleFactor==1: |
| 484 |
return str(self.term) |
| 485 |
else: |
| 486 |
return "%s %s"%(formatScaleFactor(self.scaleFactor), self.term) |
| 487 |
|
| 488 |
def __repr__(self): |
| 489 |
return "R(%s ; %s)"%(repr(self.scaleFactor), repr(self.term)) |
| 490 |
|
| 491 |
def getSI(self) -> _SIFactor: |
| 492 |
"""returns a pair of a numeric factor and a dict mapping SI units to |
| 493 |
their powers. |
| 494 |
""" |
| 495 |
factor, siPowers = self.term.getSI() |
| 496 |
return factor*self.scaleFactor, siPowers |
| 497 |
|
| 498 |
|
| 499 |
def _buildTerm(s: str, pos: int, toks: ParseResults) -> _Node: |
| 500 |
"""a parseAction for terms, making trees out of parse lists |
| 501 |
left-associatively. |
| 502 |
|
| 503 |
This will also normalise products of the same units to powers. |
| 504 |
""" |
| 505 |
tokens = list(toks) |
| 506 |
curOperand = tokens.pop(0) |
| 507 |
while len(tokens)>1: |
| 508 |
curOperand = Term.fromToks(s, pos, |
| 509 |
cast(ParseResults, [curOperand, tokens[0], tokens[1]])) |
| 510 |
del tokens[:2] |
| 511 |
return curOperand |
| 512 |
|
| 513 |
|
| 514 |
def evalAll(s: str, p: int, toks: ParseResults) -> float: |
| 515 |
"""a parse action evaluating the whole match as a python expression. |
| 516 |
|
| 517 |
Obviously, this should only be applied to carefully screened nonterminals. |
| 518 |
""" |
| 519 |
return eval("".join(str(tok) for tok in toks)) |
| 520 |
|
| 521 |
|
| 522 |
@functools.cache |
| 523 |
def getUnitGrammar(debugging: bool = False) -> utils.ParserElement: |
| 524 |
"""the grammar to parse VOUnits. |
| 525 |
|
| 526 |
After initialization, the class has a "symbols" dictionary containing |
| 527 |
the individual nonterminals. |
| 528 |
""" |
| 529 |
from gavo.utils.parsetricks import (Word, Literal, Regex, |
| 530 |
Optional, ZeroOrMore, alphas, |
| 531 |
Suppress, Forward, pyparsingWhitechars, ParserElement) |
| 532 |
|
| 533 |
with pyparsingWhitechars(''): |
| 534 |
unit_atom = (Word(alphas) | '%').addParseAction(UnitNode.fromToks) |
| 535 |
unit_atom.setName("atomic unit") |
| 536 |
quoted_unit_atom = ("'" + Word(alphas) + "'" |
| 537 |
).addParseAction(QuotedUnitNode.fromToks) |
| 538 |
quoted_unit_atom.setName("quoted atomic unit") |
| 539 |
|
| 540 |
OPEN_P = Literal('(') |
| 541 |
CLOSE_P = Literal(')') |
| 542 |
SIGN = Literal('+') | Literal('-') |
| 543 |
FUNCTION_NAME = Word(alphas) |
| 544 |
UNSIGNED_INTEGER = Word("01234567890") |
| 545 |
SIGNED_INTEGER = SIGN + UNSIGNED_INTEGER |
| 546 |
FLOAT = Regex(r"[+-]?([0-9]+(\.[0-9]*)?)") |
| 547 |
VOFLOAT = Regex(r"0.[0-9]+([eE][+-]?[0-9]+)?" |
| 548 |
r"|[1-9][0-9]*(\.[0-9]+)?([eE][+-]?[0-9]+)?") |
| 549 |
|
| 550 |
integer = (SIGNED_INTEGER | UNSIGNED_INTEGER).setName("integer") |
| 551 |
power_operator = Literal('**') |
| 552 |
multiplication_operator = Literal(".") |
| 553 |
division_operator = Literal("/") |
| 554 |
numeric_power = (integer |
| 555 |
| OPEN_P + integer + CLOSE_P |
| 556 |
| OPEN_P + FLOAT + CLOSE_P |
| 557 |
| OPEN_P + integer + '/' |
| 558 |
+ UNSIGNED_INTEGER.addParseAction(lambda s, p, t: t[0]+".") |
| 559 |
+ CLOSE_P) |
| 560 |
numeric_power.setParseAction(evalAll) |
| 561 |
|
| 562 |
pow_10 = Literal("10") + power_operator + numeric_power |
| 563 |
scale_factor = (pow_10 | VOFLOAT |
| 564 |
).setName("scale_factor" |
| 565 |
).setParseAction(evalAll) |
| 566 |
|
| 567 |
any_unit_atom = unit_atom | quoted_unit_atom |
| 568 |
factor = (any_unit_atom |
| 569 |
+ Optional( Suppress(power_operator) + numeric_power ) |
| 570 |
).setName("factor" |
| 571 |
).addParseAction(Factor.fromToks) |
| 572 |
|
| 573 |
complete_expression = Forward() |
| 574 |
function_application = (FUNCTION_NAME + |
| 575 |
Suppress(OPEN_P) + complete_expression + Suppress(CLOSE_P) |
| 576 |
).setName("function application") |
| 577 |
function_application.addParseAction(FunctionApplication.fromToks) |
| 578 |
|
| 579 |
unit_expression = ( |
| 580 |
Suppress(OPEN_P) + complete_expression + Suppress(CLOSE_P) |
| 581 |
| ( factor |
| 582 |
^ function_application )).setName("unit expression") |
| 583 |
|
| 584 |
product_of_units = (unit_expression |
| 585 |
+ ZeroOrMore(multiplication_operator + unit_expression) |
| 586 |
).setName("units term" |
| 587 |
).setParseAction(_buildTerm) |
| 588 |
|
| 589 |
complete_expression << ( |
| 590 |
product_of_units + Optional(division_operator + unit_expression) ) |
| 591 |
complete_expression.setParseAction(Term.fromToks) |
| 592 |
|
| 593 |
input = (Optional(scale_factor) |
| 594 |
+ complete_expression |
| 595 |
).setName("unit expression" |
| 596 |
).setParseAction(Expression.fromToks) |
| 597 |
|
| 598 |
if debugging: |
| 599 |
for name, sym in locals().items(): |
| 600 |
if isinstance(sym, ParserElement): |
| 601 |
sym.setDebug(True) |
| 602 |
sym.setName(name) |
| 603 |
del debugging |
| 604 |
getUnitGrammar.symbols = locals() # type: ignore # dynamic attribute |
| 605 |
|
| 606 |
return input |
| 607 |
|
| 608 |
|
| 609 |
def asSequence(unitDict: _SIPowers |
| 610 |
) -> Sequence[Tuple[Union[str, Tuple], float]]: |
| 611 |
"""returns a sorted tuple of (si, power) for a result of getSI(). |
| 612 |
|
| 613 |
These should be more suitable for dimensional analysis. |
| 614 |
""" |
| 615 |
return tuple(sorted(unitDict.items())) |
| 616 |
|
| 617 |
|
| 618 |
def parseUnit(unitStr: str, unitGrammar: utils.ParserElement = getUnitGrammar() |
| 619 |
) -> Expression: |
| 620 |
try: |
| 621 |
return utils.pyparseString(unitGrammar, unitStr, parseAll=True)[0] |
| 622 |
except parsetricks.ParseException as msg: |
| 623 |
raise utils.logOldExc( |
| 624 |
BadUnit("%s at col. %d"%(repr(unitStr), msg.column))) |
| 625 |
|
| 626 |
|
| 627 |
def computeConversionFactor(unitStr1: str, unitStr2: str) -> float: |
| 628 |
"""returns the factor needed to get from quantities given in unitStr1 |
| 629 |
to unitStr2. |
| 630 |
|
| 631 |
Both must be given in VOUnits form. |
| 632 |
|
| 633 |
This function may raise a BadUnit if one of the strings are |
| 634 |
malformed, or an IncompatibleUnit exception if the units don't have |
| 635 |
the same SI base. |
| 636 |
|
| 637 |
If the function is successful, unitStr1 = result*unitStr2 |
| 638 |
""" |
| 639 |
if unitStr1==unitStr2: |
| 640 |
return 1 |
| 641 |
factor1, powers1 = parseUnit(unitStr1).getSI() |
| 642 |
factor2, powers2 = parseUnit(unitStr2).getSI() |
| 643 |
powerSeq1 = asSequence(powers1) |
| 644 |
powerSeq2 = asSequence(powers2) |
| 645 |
|
| 646 |
if (powerSeq1, powerSeq2) in EXCEPTIONAL_CONVERSIONS: |
| 647 |
return factor1/factor2*EXCEPTIONAL_CONVERSIONS[powerSeq1, powerSeq2] |
| 648 |
if (powerSeq2, powerSeq1) in EXCEPTIONAL_CONVERSIONS: |
| 649 |
return factor1/factor2/EXCEPTIONAL_CONVERSIONS[powerSeq2, powerSeq1] |
| 650 |
|
| 651 |
if powerSeq1!=powerSeq2: |
| 652 |
raise IncompatibleUnits("%s and %s do not have the same SI base"%( |
| 653 |
unitStr1, unitStr2)) |
| 654 |
|
| 655 |
# tuples as keys in powers come from non-polynomial function |
| 656 |
# applications; in such cases, multiplication is not good enough |
| 657 |
# for conversions, and thus we give up. |
| 658 |
for u, _ in powerSeq1: |
| 659 |
if isinstance(u, tuple): |
| 660 |
raise IncompatibleUnits("%s has a non-polynomial function. No" |
| 661 |
" conversion by multiplication possible"%(unitStr1)) |
| 662 |
for u, _ in powerSeq2: |
| 663 |
if isinstance(u, tuple): |
| 664 |
raise IncompatibleUnits("%s has a non-polynomial function. No" |
| 665 |
" conversion by multiplication possible"%(unitStr2)) |
| 666 |
|
| 667 |
return factor1/factor2 |
| 668 |
|
| 669 |
|
| 670 |
def computeColumnConversions( |
| 671 |
newColumns: "ColumnList", oldColumns: "ColumnList") -> Dict: |
| 672 |
"""returns a dict of conversion factors between newColumns and oldColumns. |
| 673 |
|
| 674 |
Both arguments are iterables of columns. |
| 675 |
|
| 676 |
For every column in newColumn, the function sees if the units of |
| 677 |
newColumn and oldColumn match. If they don't, compute a conversion |
| 678 |
factor to be multiplied to oldColumns values to make them newColumns |
| 679 |
values and add it to the result dict. |
| 680 |
|
| 681 |
The function raises a DataError if a column in newColumns has no |
| 682 |
match in oldColumns. |
| 683 |
""" |
| 684 |
res = {} |
| 685 |
for newCol in newColumns: |
| 686 |
if not newCol.name in oldColumns: |
| 687 |
raise utils.DataError( |
| 688 |
"Request for column %s from %s cannot be satisfied in %s"%( |
| 689 |
newCol.name, newColumns, oldColumns)) |
| 690 |
oldCol = oldColumns.getColumnByName(newCol.name) |
| 691 |
try: |
| 692 |
if newCol.unit!=oldCol.unit: |
| 693 |
res[newCol.name] = computeConversionFactor(oldCol.unit, newCol.unit) |
| 694 |
except BadUnit: # we ignore bad units, assume they'll be handled by |
| 695 |
# valuemappers. |
| 696 |
pass |
| 697 |
return res |
| 698 |
|
| 699 |
|
| 700 |
if __name__=="__main__": |
| 701 |
g = getUnitGrammar(debugging=True) |
| 702 |
res = g.parseString("10**28s", parseAll=True)[0] |
| 703 |
print(res) |