| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import numbers |
| 4 |
import re |
| 5 |
from dataclasses import dataclass |
| 6 |
from typing import TYPE_CHECKING, Any, Callable |
| 7 |
|
| 8 |
from flexparser import flexparser as fp |
| 9 |
|
| 10 |
from . import common, errors |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from pint import Quantity, UnitsContainer |
| 14 |
|
| 15 |
|
| 16 |
class ParserHelper: |
| 17 |
@classmethod |
| 18 |
def from_string(cls, s, *args): |
| 19 |
return s |
| 20 |
|
| 21 |
|
| 22 |
@dataclass(frozen=True) |
| 23 |
class _Relation: |
| 24 |
_varname_re = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") |
| 25 |
|
| 26 |
src: UnitsContainer |
| 27 |
dst: UnitsContainer |
| 28 |
equation: str |
| 29 |
|
| 30 |
@classmethod |
| 31 |
def _from_string_and_context_sep( |
| 32 |
cls, s: str, config: common.Config, separator: str |
| 33 |
) -> fp.NullableParsedResult[_Relation]: |
| 34 |
if separator not in s: |
| 35 |
return None |
| 36 |
if ":" not in s: |
| 37 |
return None |
| 38 |
|
| 39 |
rel, eq = s.split(":") |
| 40 |
|
| 41 |
parts = rel.split(separator) |
| 42 |
|
| 43 |
try: |
| 44 |
src, dst = (config.to_dimension_container(s) for s in parts) |
| 45 |
except errors.DefinitionSyntaxError as ex: |
| 46 |
return ex |
| 47 |
|
| 48 |
return cls(src, dst, eq.strip()) |
| 49 |
|
| 50 |
@property |
| 51 |
def variables(self) -> set[str, ...]: |
| 52 |
"""Find all variables names in the equation.""" |
| 53 |
return set(self._varname_re.findall(self.equation)) |
| 54 |
|
| 55 |
@property |
| 56 |
def transformation(self) -> Callable[..., Quantity[Any]]: |
| 57 |
"""Return a transformation callable that uses the registry |
| 58 |
to parse the transformation equation. |
| 59 |
""" |
| 60 |
return lambda ureg, value, **kwargs: ureg.parse_expression( |
| 61 |
self.equation, value=value, **kwargs |
| 62 |
) |
| 63 |
|
| 64 |
|
| 65 |
@dataclass(frozen=True) |
| 66 |
class ForwardRelation(fp.ParsedStatement, _Relation): |
| 67 |
"""A relation connecting a dimension to another via a transformation function. |
| 68 |
|
| 69 |
<source dimension> -> <target dimension>: <transformation function> |
| 70 |
""" |
| 71 |
|
| 72 |
@property |
| 73 |
def bidirectional(self): |
| 74 |
return False |
| 75 |
|
| 76 |
@classmethod |
| 77 |
def from_string_and_config( |
| 78 |
cls, s: str, config: common.Config |
| 79 |
) -> fp.NullableParsedResult[ForwardRelation]: |
| 80 |
return super()._from_string_and_context_sep(s, config, "->") |
| 81 |
|
| 82 |
|
| 83 |
@dataclass(frozen=True) |
| 84 |
class BidirectionalRelation(fp.ParsedStatement, _Relation): |
| 85 |
"""A bidirectional relation connecting a dimension to another |
| 86 |
via a simple transformation function. |
| 87 |
|
| 88 |
<source dimension> <-> <target dimension>: <transformation function> |
| 89 |
|
| 90 |
""" |
| 91 |
|
| 92 |
@property |
| 93 |
def bidirectional(self): |
| 94 |
return True |
| 95 |
|
| 96 |
@classmethod |
| 97 |
def from_string_and_config( |
| 98 |
cls, s: str, config: common.Config |
| 99 |
) -> fp.NullableParsedResult[BidirectionalRelation]: |
| 100 |
return super()._from_string_and_context_sep(s, config, "<->") |
| 101 |
|
| 102 |
|
| 103 |
@dataclass(frozen=True) |
| 104 |
class BeginContext(fp.ParsedStatement): |
| 105 |
"""Being of a context directive. |
| 106 |
|
| 107 |
@context[(defaults)] <canonical name> [= <alias>] [= <alias>] |
| 108 |
""" |
| 109 |
|
| 110 |
_header_re = re.compile( |
| 111 |
r"@context\s*(?P<defaults>\(.*\))?\s+(?P<name>\w+)\s*(=(?P<aliases>.*))*" |
| 112 |
) |
| 113 |
|
| 114 |
name: str |
| 115 |
aliases: tuple[str, ...] |
| 116 |
defaults: dict[str, numbers.Number] |
| 117 |
|
| 118 |
@classmethod |
| 119 |
def from_string_and_config( |
| 120 |
cls, s: str, config: common.Config |
| 121 |
) -> fp.NullableParsedResult[BeginContext]: |
| 122 |
try: |
| 123 |
r = cls._header_re.search(s) |
| 124 |
if r is None: |
| 125 |
return None |
| 126 |
name = r.groupdict()["name"].strip() |
| 127 |
aliases = r.groupdict()["aliases"] |
| 128 |
if aliases: |
| 129 |
aliases = tuple(a.strip() for a in r.groupdict()["aliases"].split("=")) |
| 130 |
else: |
| 131 |
aliases = () |
| 132 |
defaults = r.groupdict()["defaults"] |
| 133 |
except Exception as ex: |
| 134 |
return errors.DefinitionSyntaxError( |
| 135 |
"Could not parse the Context header", ex |
| 136 |
) |
| 137 |
|
| 138 |
if defaults: |
| 139 |
|
| 140 |
txt = defaults |
| 141 |
try: |
| 142 |
defaults = (part.split("=") for part in defaults.strip("()").split(",")) |
| 143 |
defaults = {str(k).strip(): config.to_number(v) for k, v in defaults} |
| 144 |
except (ValueError, TypeError) as exc: |
| 145 |
return errors.DefinitionSyntaxError( |
| 146 |
f"Could not parse Context definition defaults: '{txt}'", exc |
| 147 |
) |
| 148 |
else: |
| 149 |
defaults = {} |
| 150 |
|
| 151 |
return cls(name, tuple(aliases), defaults) |
| 152 |
|
| 153 |
|
| 154 |
@dataclass(frozen=True) |
| 155 |
class ContextDefinition(common.DirectiveBlock): |
| 156 |
"""Definition of a Context |
| 157 |
|
| 158 |
@context[(defaults)] <canonical name> [= <alias>] [= <alias>] |
| 159 |
# units can be redefined within the context |
| 160 |
<redefined unit> = <relation to another unit> |
| 161 |
|
| 162 |
# can establish unidirectional relationships between dimensions |
| 163 |
<dimension 1> -> <dimension 2>: <transformation function> |
| 164 |
|
| 165 |
# can establish bidirectionl relationships between dimensions |
| 166 |
<dimension 3> <-> <dimension 4>: <transformation function> |
| 167 |
@end |
| 168 |
|
| 169 |
See BeginContext, Equality, ForwardRelation, BidirectionalRelation and |
| 170 |
Comment for more parsing related information. |
| 171 |
|
| 172 |
Example:: |
| 173 |
|
| 174 |
@context(n=1) spectroscopy = sp |
| 175 |
# n index of refraction of the medium. |
| 176 |
[length] <-> [frequency]: speed_of_light / n / value |
| 177 |
[frequency] -> [energy]: planck_constant * value |
| 178 |
[energy] -> [frequency]: value / planck_constant |
| 179 |
# allow wavenumber / kayser |
| 180 |
[wavenumber] <-> [length]: 1 / value |
| 181 |
@end |
| 182 |
""" |
| 183 |
|
| 184 |
@property |
| 185 |
def variables(self) -> set[str, ...]: |
| 186 |
"""Return all variable names in all transformations.""" |
| 187 |
return set.union(*(r.variables for r in self.body if isinstance(r, _Relation))) |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|