1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
"""
pint.facets.context.definitions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2022 by Pint Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import annotations
import numbers
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Dict, Tuple
from ...definitions import Definition
from ...errors import DefinitionSyntaxError
from ...util import ParserHelper, SourceIterator
from ..plain.definitions import UnitDefinition
if TYPE_CHECKING:
from ..plain.quantity import Quantity
_header_re = re.compile(
r"@context\s*(?P<defaults>\(.*\))?\s+(?P<name>\w+)\s*(=(?P<aliases>.*))*"
)
_varname_re = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
# TODO: Put back annotation when possible
# registry_cache: "UnitRegistry"
class Expression:
def __init__(self, eq):
self._eq = eq
def __call__(self, ureg, value: Any, **kwargs: Any):
return ureg.parse_expression(self._eq, value=value, **kwargs)
@dataclass(frozen=True)
class Relation:
bidirectional: True
src: ParserHelper
dst: ParserHelper
tranformation: Callable[..., Quantity[Any]]
@dataclass(frozen=True)
class ContextDefinition:
"""Definition of a Context
@context[(defaults)] <canonical name> [= <alias>] [= <alias>]
# units can be redefined within the context
<redefined unit> = <relation to another unit>
# can establish unidirectional relationships between dimensions
<dimension 1> -> <dimension 2>: <transformation function>
# can establish bidirectionl relationships between dimensions
<dimension 3> <-> <dimension 4>: <transformation function>
@end
Example::
@context(n=1) spectroscopy = sp
# n index of refraction of the medium.
[length] <-> [frequency]: speed_of_light / n / value
[frequency] -> [energy]: planck_constant * value
[energy] -> [frequency]: value / planck_constant
# allow wavenumber / kayser
[wavenumber] <-> [length]: 1 / value
@end
"""
name: str
aliases: Tuple[str, ...]
variables: Tuple[str, ...]
defaults: Dict[str, numbers.Number]
# Each element indicates: line number, is_bidirectional, src, dst, transformation func
relations: Tuple[Tuple[int, Relation], ...]
redefinitions: Tuple[Tuple[int, UnitDefinition], ...]
@staticmethod
def parse_definition(line, non_int_type) -> UnitDefinition:
definition = Definition.from_string(line, non_int_type)
if not isinstance(definition, UnitDefinition):
raise DefinitionSyntaxError(
"Expected <unit> = <converter>; got %s" % line.strip()
)
if definition.symbol != definition.name or definition.aliases:
raise DefinitionSyntaxError(
"Can't change a unit's symbol or aliases within a context"
)
if definition.is_base:
raise DefinitionSyntaxError("Can't define plain units within a context")
return definition
@classmethod
def from_lines(cls, lines, non_int_type=float) -> ContextDefinition:
lines = SourceIterator(lines)
lineno, header = next(lines)
try:
r = _header_re.search(header)
name = r.groupdict()["name"].strip()
aliases = r.groupdict()["aliases"]
if aliases:
aliases = tuple(a.strip() for a in r.groupdict()["aliases"].split("="))
else:
aliases = ()
defaults = r.groupdict()["defaults"]
except Exception as exc:
raise DefinitionSyntaxError(
"Could not parse the Context header '%s'" % header, lineno=lineno
) from exc
if defaults:
def to_num(val):
val = complex(val)
if not val.imag:
return val.real
return val
txt = defaults
try:
defaults = (part.split("=") for part in defaults.strip("()").split(","))
defaults = {str(k).strip(): to_num(v) for k, v in defaults}
except (ValueError, TypeError) as exc:
raise DefinitionSyntaxError(
f"Could not parse Context definition defaults: '{txt}'",
lineno=lineno,
) from exc
else:
defaults = {}
variables = set()
redefitions = []
relations = []
for lineno, line in lines:
try:
if "=" in line:
definition = cls.parse_definition(line, non_int_type)
redefitions.append((lineno, definition))
elif ":" in line:
rel, eq = line.split(":")
variables.update(_varname_re.findall(eq))
func = Expression(eq)
bidir = True
parts = rel.split("<->")
if len(parts) != 2:
bidir = False
parts = rel.split("->")
if len(parts) != 2:
raise Exception
src, dst = (
ParserHelper.from_string(s, non_int_type) for s in parts
)
relation = Relation(bidir, src, dst, func)
relations.append((lineno, relation))
else:
raise Exception
except Exception as exc:
raise DefinitionSyntaxError(
"Could not parse Context %s relation '%s': %s" % (name, line, exc),
lineno=lineno,
) from exc
if defaults:
missing_pars = defaults.keys() - set(variables)
if missing_pars:
raise DefinitionSyntaxError(
f"Context parameters {missing_pars} not found in any equation"
)
return cls(
name,
aliases,
tuple(variables),
defaults,
tuple(relations),
tuple(redefitions),
)
|