| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import numbers |
| 4 |
import typing as ty |
| 5 |
from dataclasses import dataclass |
| 6 |
from functools import cached_property |
| 7 |
from typing import Callable |
| 8 |
|
| 9 |
from flexparser import flexparser as fp |
| 10 |
|
| 11 |
from . import common, errors |
| 12 |
from .pintimports import Converter, UnitsContainer |
| 13 |
|
| 14 |
|
| 15 |
@dataclass(frozen=True) |
| 16 |
class PrefixDefinition(fp.ParsedStatement): |
| 17 |
"""Definition of a prefix:: |
| 18 |
|
| 19 |
<prefix>- = <value> [= <symbol>] [= <alias>] [ = <alias> ] [...] |
| 20 |
|
| 21 |
Example:: |
| 22 |
|
| 23 |
deca- = 1e+1 = da- = deka- |
| 24 |
""" |
| 25 |
|
| 26 |
name: str |
| 27 |
value: numbers.Number |
| 28 |
defined_symbol: str | None |
| 29 |
aliases: ty.Tuple[str, ...] |
| 30 |
|
| 31 |
@classmethod |
| 32 |
def from_string_and_config( |
| 33 |
cls, s: str, config: common.Config |
| 34 |
) -> fp.NullableParsedResult[PrefixDefinition]: |
| 35 |
if "=" not in s: |
| 36 |
return None |
| 37 |
|
| 38 |
name, value, *aliases = s.split("=") |
| 39 |
|
| 40 |
name = name.strip() |
| 41 |
if not name.endswith("-"): |
| 42 |
return None |
| 43 |
|
| 44 |
aliases = tuple(alias.strip().rstrip("-") for alias in aliases) |
| 45 |
|
| 46 |
if aliases and aliases[0].strip() != "_": |
| 47 |
defined_symbol, *aliases = aliases |
| 48 |
else: |
| 49 |
defined_symbol = None |
| 50 |
|
| 51 |
try: |
| 52 |
value = config.to_number(value) |
| 53 |
except common.NotNumeric as ex: |
| 54 |
return errors.DefinitionSyntaxError( |
| 55 |
f"Prefix definition ('{name}') must contain only numbers, not {ex.value}" |
| 56 |
) |
| 57 |
|
| 58 |
return cls(name, value, defined_symbol, aliases) |
| 59 |
|
| 60 |
@property |
| 61 |
def symbol(self) -> str: |
| 62 |
return self.defined_symbol or self.name |
| 63 |
|
| 64 |
@property |
| 65 |
def has_symbol(self) -> bool: |
| 66 |
return bool(self.defined_symbol) |
| 67 |
|
| 68 |
@cached_property |
| 69 |
def converter(self): |
| 70 |
return Converter.from_arguments(scale=self.value) |
| 71 |
|
| 72 |
|
| 73 |
@dataclass(frozen=True) |
| 74 |
class UnitDefinition(fp.ParsedStatement): |
| 75 |
"""Definition of a unit:: |
| 76 |
|
| 77 |
<canonical name> = <relation to another unit or dimension> [= <symbol>] [= <alias>] [ = <alias> ] [...] |
| 78 |
|
| 79 |
Example:: |
| 80 |
|
| 81 |
millennium = 1e3 * year = _ = millennia |
| 82 |
|
| 83 |
Parameters |
| 84 |
---------- |
| 85 |
reference : UnitsContainer |
| 86 |
Reference units. |
| 87 |
is_base : bool |
| 88 |
Indicates if it is a base unit. |
| 89 |
|
| 90 |
""" |
| 91 |
|
| 92 |
name: str |
| 93 |
defined_symbol: ty.Optional[str] |
| 94 |
aliases: ty.Tuple[str, ...] |
| 95 |
converter: ty.Optional[ty.Union[Callable, Converter]] |
| 96 |
|
| 97 |
reference: ty.Optional[UnitsContainer] |
| 98 |
is_base: bool |
| 99 |
|
| 100 |
@classmethod |
| 101 |
def from_string_and_config( |
| 102 |
cls, s: str, config: common.Config |
| 103 |
) -> fp.NullableParsedResult[UnitDefinition]: |
| 104 |
if "=" not in s: |
| 105 |
return None |
| 106 |
|
| 107 |
name, value, *aliases = (p.strip() for p in s.split("=")) |
| 108 |
|
| 109 |
if aliases and aliases[0].strip() == "_": |
| 110 |
defined_symbol, *aliases = aliases |
| 111 |
else: |
| 112 |
defined_symbol = None |
| 113 |
|
| 114 |
if ";" in value: |
| 115 |
[converter, modifiers] = value.split(";", 1) |
| 116 |
|
| 117 |
try: |
| 118 |
modifiers = { |
| 119 |
key.strip(): config.to_number(value) |
| 120 |
for key, value in (part.split(":") for part in modifiers.split(";")) |
| 121 |
} |
| 122 |
except common.NotNumeric as ex: |
| 123 |
return errors.DefinitionSyntaxError( |
| 124 |
f"Unit definition ('{name}') must contain only numbers in modifier, not {ex.value}" |
| 125 |
) |
| 126 |
|
| 127 |
else: |
| 128 |
converter = value |
| 129 |
modifiers = {} |
| 130 |
|
| 131 |
converter = config.to_scaled_units_container(converter) |
| 132 |
if not any(common.is_dim(key) for key in converter.keys()): |
| 133 |
is_base = False |
| 134 |
elif all(common.is_dim(key) for key in converter.keys()): |
| 135 |
is_base = True |
| 136 |
if converter.scale != 1: |
| 137 |
return errors.DefinitionSyntaxError( |
| 138 |
"Base unit definitions cannot have a scale different to 1. " |
| 139 |
f"(`{converter.scale}` found)" |
| 140 |
) |
| 141 |
else: |
| 142 |
return errors.DefinitionSyntaxError( |
| 143 |
"Cannot mix dimensions and units in the same definition. " |
| 144 |
"Base units must be referenced only to dimensions. " |
| 145 |
"Derived units must be referenced only to units." |
| 146 |
) |
| 147 |
|
| 148 |
try: |
| 149 |
from pint.util import UnitsContainer |
| 150 |
|
| 151 |
reference = UnitsContainer(converter) |
| 152 |
|
| 153 |
except errors.DefinitionSyntaxError as ex: |
| 154 |
return errors.DefinitionSyntaxError(f"While defining {name}", ex) |
| 155 |
|
| 156 |
try: |
| 157 |
converter = Converter.from_arguments(scale=converter.scale, **modifiers) |
| 158 |
except Exception as ex: |
| 159 |
return errors.DefinitionSyntaxError( |
| 160 |
"Unable to assign a converter to the unit", ex |
| 161 |
) |
| 162 |
|
| 163 |
return cls( |
| 164 |
name, |
| 165 |
defined_symbol, |
| 166 |
aliases, |
| 167 |
converter, |
| 168 |
reference, |
| 169 |
is_base, |
| 170 |
) |
| 171 |
|
| 172 |
@property |
| 173 |
def is_multiplicative(self) -> bool: |
| 174 |
return self.converter.is_multiplicative |
| 175 |
|
| 176 |
@property |
| 177 |
def is_logarithmic(self) -> bool: |
| 178 |
return self.converter.is_logarithmic |
| 179 |
|
| 180 |
@property |
| 181 |
def symbol(self) -> str: |
| 182 |
return self.defined_symbol or self.name |
| 183 |
|
| 184 |
@property |
| 185 |
def has_symbol(self) -> bool: |
| 186 |
return bool(self.defined_symbol) |
| 187 |
|
| 188 |
|
| 189 |
@dataclass(frozen=True) |
| 190 |
class DimensionDefinition(fp.ParsedStatement): |
| 191 |
"""Definition of a root dimension:: |
| 192 |
|
| 193 |
[dimension name] |
| 194 |
|
| 195 |
Example:: |
| 196 |
|
| 197 |
[volume] |
| 198 |
""" |
| 199 |
|
| 200 |
name: str |
| 201 |
|
| 202 |
@property |
| 203 |
def is_base(self): |
| 204 |
return False |
| 205 |
|
| 206 |
@classmethod |
| 207 |
def from_string(cls, s: str) -> fp.NullableParsedResult[DimensionDefinition]: |
| 208 |
s = s.strip() |
| 209 |
|
| 210 |
if not (s.startswith("[") and "=" not in s): |
| 211 |
return None |
| 212 |
|
| 213 |
try: |
| 214 |
s = common.check_dim(s) |
| 215 |
except errors.DefinitionSyntaxError as ex: |
| 216 |
return ex |
| 217 |
|
| 218 |
return cls(s) |
| 219 |
|
| 220 |
|
| 221 |
@dataclass(frozen=True) |
| 222 |
class DerivedDimensionDefinition(fp.ParsedStatement): |
| 223 |
"""Definition of a derived dimension:: |
| 224 |
|
| 225 |
[dimension name] = <relation to other dimensions> |
| 226 |
|
| 227 |
Example:: |
| 228 |
|
| 229 |
[density] = [mass] / [volume] |
| 230 |
""" |
| 231 |
|
| 232 |
name: str |
| 233 |
reference: UnitsContainer |
| 234 |
|
| 235 |
@property |
| 236 |
def is_base(self): |
| 237 |
return False |
| 238 |
|
| 239 |
@classmethod |
| 240 |
def from_string_and_config( |
| 241 |
cls, s: str, config: common.Config |
| 242 |
) -> fp.NullableParsedResult[DerivedDimensionDefinition]: |
| 243 |
if not (s.startswith("[") and "=" in s): |
| 244 |
return None |
| 245 |
|
| 246 |
name, value, *aliases = s.split("=") |
| 247 |
|
| 248 |
if not (s.startswith("[") and "=" not in s): |
| 249 |
return None |
| 250 |
|
| 251 |
try: |
| 252 |
name = common.check_dim(name) |
| 253 |
except errors.DefinitionSyntaxError as ex: |
| 254 |
return ex |
| 255 |
|
| 256 |
if aliases: |
| 257 |
return errors.DefinitionSyntaxError( |
| 258 |
"Derived dimensions cannot have aliases." |
| 259 |
) |
| 260 |
|
| 261 |
try: |
| 262 |
reference = config.to_dimension_container(value) |
| 263 |
except errors.DefinitionSyntaxError as ex: |
| 264 |
return errors.DefinitionSyntaxError( |
| 265 |
f"In {name} derived dimensions must only be referenced " |
| 266 |
"to dimensions.", |
| 267 |
ex, |
| 268 |
) |
| 269 |
|
| 270 |
return cls(name.strip(), reference) |
| 271 |
|
| 272 |
|
| 273 |
@dataclass(frozen=True) |
| 274 |
class AliasDefinition(fp.ParsedStatement): |
| 275 |
"""Additional alias(es) for an already existing unit:: |
| 276 |
|
| 277 |
@alias <canonical name or previous alias> = <alias> [ = <alias> ] [...] |
| 278 |
|
| 279 |
Example:: |
| 280 |
|
| 281 |
@alias meter = my_meter |
| 282 |
""" |
| 283 |
|
| 284 |
name: str |
| 285 |
aliases: ty.Tuple[str, ...] |
| 286 |
|
| 287 |
@classmethod |
| 288 |
def from_string(cls, s: str) -> fp.NullableParsedResult[AliasDefinition]: |
| 289 |
if not s.startswith("@alias "): |
| 290 |
return None |
| 291 |
name, *aliases = s[len("@alias ") :].split("=") |
| 292 |
|
| 293 |
name = name.strip() |
| 294 |
if name.startswith("["): |
| 295 |
return errors.DefinitionSyntaxError( |
| 296 |
"Derived dimensions cannot have aliases." |
| 297 |
) |
| 298 |
if name.endswith("-"): |
| 299 |
return errors.DefinitionSyntaxError( |
| 300 |
"Prefixes aliases cannot be added after initial definition." |
| 301 |
) |
| 302 |
|
| 303 |
return cls(name.strip(), tuple(alias.strip() for alias in aliases)) |