Debian Codegraph @

pint/facets/plain/definitions.py

raw
1 """
2 pint.facets.plain.definitions
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
6 :license: BSD, see LICENSE for more details.
7 """
8
9 from __future__ import annotations
10
11 import itertools
12 import numbers
13 import typing as ty
14 from dataclasses import dataclass
15 from functools import cached_property
16 from typing import Any
17
18 from ... import errors
19 from ..._typing import Magnitude
20 from ...converters import Converter
21 from ...util import UnitsContainer
22
23
24 class NotNumeric(Exception):
25 """Internal exception. Do not expose outside Pint"""
26
27 def __init__(self, value: Any):
28 self.value = value
29
30
31 ########################
32 # Convenience functions
33 ########################
34
35
36 @dataclass(frozen=True)
37 class Equality:
38 """An equality statement contains a left and right hand separated
39 by and equal (=) sign.
40
41 lhs = rhs
42
43 lhs and rhs are space stripped.
44 """
45
46 lhs: str
47 rhs: str
48
49
50 @dataclass(frozen=True)
51 class CommentDefinition:
52 """A comment"""
53
54 comment: str
55
56
57 @dataclass(frozen=True)
58 class DefaultsDefinition:
59 """Directive to store default values."""
60
61 group: ty.Optional[str]
62 system: ty.Optional[str]
63
64 def items(self):
65 if self.group is not None:
66 yield "group", self.group
67 if self.system is not None:
68 yield "system", self.system
69
70
71 @dataclass(frozen=True)
72 class NamedDefinition:
73 #: name of the prefix
74 name: str
75
76
77 @dataclass(frozen=True)
78 class PrefixDefinition(NamedDefinition, errors.WithDefErr):
79 """Definition of a prefix."""
80
81 #: scaling value for this prefix
82 value: numbers.Number
83 #: canonical symbol
84 defined_symbol: str | None = ""
85 #: additional names for the same prefix
86 aliases: ty.Tuple[str, ...] = ()
87
88 @property
89 def symbol(self) -> str:
90 return self.defined_symbol or self.name
91
92 @property
93 def has_symbol(self) -> bool:
94 return bool(self.defined_symbol)
95
96 @cached_property
97 def converter(self) -> ScaleConverter:
98 return ScaleConverter(self.value)
99
100 def __post_init__(self):
101 if not errors.is_valid_prefix_name(self.name):
102 raise self.def_err(errors.MSG_INVALID_PREFIX_NAME)
103
104 if self.defined_symbol and not errors.is_valid_prefix_symbol(self.name):
105 raise self.def_err(
106 f"the symbol {self.defined_symbol} " + errors.MSG_INVALID_PREFIX_SYMBOL
107 )
108
109 for alias in self.aliases:
110 if not errors.is_valid_prefix_alias(alias):
111 raise self.def_err(
112 f"the alias {alias} " + errors.MSG_INVALID_PREFIX_ALIAS
113 )
114
115
116 @dataclass(frozen=True)
117 class UnitDefinition(NamedDefinition, errors.WithDefErr):
118 """Definition of a unit."""
119
120 #: canonical symbol
121 defined_symbol: str | None
122 #: additional names for the same unit
123 aliases: tuple[str, ...]
124 #: A functiont that converts a value in these units into the reference units
125 # TODO: this has changed as converter is now annotated as converter.
126 # Briefly, in several places converter attributes like as_multiplicative were
127 # accesed. So having a generic function is a no go.
128 # I guess this was never used as errors where not raised.
129 converter: Converter | None
130 #: Reference units.
131 reference: UnitsContainer | None
132
133 def __post_init__(self):
134 if not errors.is_valid_unit_name(self.name):
135 raise self.def_err(errors.MSG_INVALID_UNIT_NAME)
136
137 # TODO: check why reference: Optional[UnitsContainer]
138 assert isinstance(self.reference, UnitsContainer)
139
140 if not any(map(errors.is_dim, self.reference.keys())):
141 invalid = tuple(
142 itertools.filterfalse(errors.is_valid_unit_name, self.reference.keys())
143 )
144 if invalid:
145 raise self.def_err(
146 f"refers to {', '.join(invalid)} that "
147 + errors.MSG_INVALID_UNIT_NAME
148 )
149 is_base = False
150
151 elif all(map(errors.is_dim, self.reference.keys())):
152 invalid = tuple(
153 itertools.filterfalse(
154 errors.is_valid_dimension_name, self.reference.keys()
155 )
156 )
157 if invalid:
158 raise self.def_err(
159 f"refers to {', '.join(invalid)} that "
160 + errors.MSG_INVALID_DIMENSION_NAME
161 )
162
163 is_base = True
164 scale = getattr(self.converter, "scale", 1)
165 if scale != 1:
166 return self.def_err(
167 "Base unit definitions cannot have a scale different to 1. "
168 f"(`{scale}` found)"
169 )
170 else:
171 raise self.def_err(
172 "Cannot mix dimensions and units in the same definition. "
173 "Base units must be referenced only to dimensions. "
174 "Derived units must be referenced only to units."
175 )
176
177 super.__setattr__(self, "_is_base", is_base)
178
179 if self.defined_symbol and not errors.is_valid_unit_symbol(self.name):
180 raise self.def_err(
181 f"the symbol {self.defined_symbol} " + errors.MSG_INVALID_UNIT_SYMBOL
182 )
183
184 for alias in self.aliases:
185 if not errors.is_valid_unit_alias(alias):
186 raise self.def_err(
187 f"the alias {alias} " + errors.MSG_INVALID_UNIT_ALIAS
188 )
189
190 @property
191 def is_base(self) -> bool:
192 """Indicates if it is a base unit."""
193
194 # TODO: This is set in __post_init__
195 return self._is_base
196
197 @property
198 def is_multiplicative(self) -> bool:
199 # TODO: Check how to avoid this check
200 assert isinstance(self.converter, Converter)
201 return self.converter.is_multiplicative
202
203 @property
204 def is_logarithmic(self) -> bool:
205 # TODO: Check how to avoid this check
206 assert isinstance(self.converter, Converter)
207 return self.converter.is_logarithmic
208
209 @property
210 def symbol(self) -> str:
211 return self.defined_symbol or self.name
212
213 @property
214 def has_symbol(self) -> bool:
215 return bool(self.defined_symbol)
216
217
218 @dataclass(frozen=True)
219 class DimensionDefinition(NamedDefinition, errors.WithDefErr):
220 """Definition of a root dimension"""
221
222 @property
223 def is_base(self) -> bool:
224 return True
225
226 def __post_init__(self) -> None:
227 if not errors.is_valid_dimension_name(self.name):
228 raise self.def_err(errors.MSG_INVALID_DIMENSION_NAME)
229
230
231 @dataclass(frozen=True)
232 class DerivedDimensionDefinition(DimensionDefinition):
233 """Definition of a derived dimension."""
234
235 #: reference dimensions.
236 reference: UnitsContainer
237
238 @property
239 def is_base(self) -> bool:
240 return False
241
242 def __post_init__(self):
243 if not errors.is_valid_dimension_name(self.name):
244 raise self.def_err(errors.MSG_INVALID_DIMENSION_NAME)
245
246 if not all(map(errors.is_dim, self.reference.keys())):
247 return self.def_err(
248 "derived dimensions must only reference other dimensions"
249 )
250
251 invalid = tuple(
252 itertools.filterfalse(errors.is_valid_dimension_name, self.reference.keys())
253 )
254
255 if invalid:
256 raise self.def_err(
257 f"refers to {', '.join(invalid)} that "
258 + errors.MSG_INVALID_DIMENSION_NAME
259 )
260
261
262 @dataclass(frozen=True)
263 class AliasDefinition(errors.WithDefErr):
264 """Additional alias(es) for an already existing unit."""
265
266 #: name of the already existing unit
267 name: str
268 #: aditional names for the same unit
269 aliases: ty.Tuple[str, ...]
270
271 def __post_init__(self):
272 if not errors.is_valid_unit_name(self.name):
273 raise self.def_err(errors.MSG_INVALID_UNIT_NAME)
274
275 for alias in self.aliases:
276 if not errors.is_valid_unit_alias(alias):
277 raise self.def_err(
278 f"the alias {alias} " + errors.MSG_INVALID_UNIT_ALIAS
279 )
280
281
282 @dataclass(frozen=True)
283 class ScaleConverter(Converter):
284 """A linear transformation without offset."""
285
286 scale: float
287
288 def to_reference(self, value: Magnitude, inplace: bool = False) -> Magnitude:
289 if inplace:
290 value *= self.scale
291 else:
292 value = value * self.scale
293
294 return value
295
296 def from_reference(self, value: Magnitude, inplace: bool = False) -> Magnitude:
297 if inplace:
298 value /= self.scale
299 else:
300 value = value / self.scale
301
302 return value