Debian Codegraph @

pint/facets/nonmultiplicative/registry.py

raw
1 """
2 pint.facets.nonmultiplicative.registry
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 from typing import Any, Generic, TypeVar
12
13 from ...compat import TypeAlias
14 from ...errors import DimensionalityError, UndefinedUnitError
15 from ...util import UnitsContainer, logger
16 from ..plain import GenericPlainRegistry, QuantityT, UnitDefinition, UnitT
17 from . import objects
18 from .definitions import OffsetConverter, ScaleConverter
19
20 T = TypeVar("T")
21
22
23 class GenericNonMultiplicativeRegistry(
24 Generic[QuantityT, UnitT], GenericPlainRegistry[QuantityT, UnitT]
25 ):
26 """Handle of non multiplicative units (e.g. Temperature).
27
28 Capabilities:
29 - Register non-multiplicative units and their relations.
30 - Convert between non-multiplicative units.
31
32 Parameters
33 ----------
34 default_as_delta : bool
35 If True, non-multiplicative units are interpreted as
36 their *delta* counterparts in multiplications.
37 autoconvert_offset_to_baseunit : bool
38 If True, non-multiplicative units are
39 converted to plain units in multiplications.
40
41 """
42
43 def __init__(
44 self,
45 default_as_delta: bool = True,
46 autoconvert_offset_to_baseunit: bool = False,
47 **kwargs: Any,
48 ) -> None:
49 super().__init__(**kwargs)
50
51 #: When performing a multiplication of units, interpret
52 #: non-multiplicative units as their *delta* counterparts.
53 self.default_as_delta = default_as_delta
54
55 # Determines if quantities with offset units are converted to their
56 # plain units on multiplication and division.
57 self.autoconvert_offset_to_baseunit = autoconvert_offset_to_baseunit
58
59 def parse_units_as_container(
60 self,
61 input_string: str,
62 as_delta: bool | None = None,
63 case_sensitive: bool | None = None,
64 ) -> UnitsContainer:
65 """ """
66 if as_delta is None:
67 as_delta = self.default_as_delta
68
69 return super().parse_units_as_container(input_string, as_delta, case_sensitive)
70
71 def _add_unit(self, definition: UnitDefinition) -> None:
72 super()._add_unit(definition)
73
74 if definition.is_multiplicative:
75 return
76
77 if definition.is_logarithmic:
78 return
79
80 if not isinstance(definition.converter, OffsetConverter):
81 logger.debug(
82 "Cannot autogenerate delta version for a unit in "
83 "which the converter is not an OffsetConverter"
84 )
85 return
86
87 delta_name = "delta_" + definition.name
88 if definition.symbol:
89 delta_symbol = "Δ" + definition.symbol
90 else:
91 delta_symbol = None
92
93 delta_aliases = tuple("Δ" + alias for alias in definition.aliases) + tuple(
94 "delta_" + alias for alias in definition.aliases
95 )
96
97 delta_reference = self.UnitsContainer(
98 {ref: value for ref, value in definition.reference.items()}
99 )
100
101 delta_def = UnitDefinition(
102 delta_name,
103 delta_symbol,
104 delta_aliases,
105 ScaleConverter(definition.converter.scale),
106 delta_reference,
107 )
108 super()._add_unit(delta_def)
109
110 def _is_multiplicative(self, unit_name: str) -> bool:
111 """True if the unit is multiplicative.
112
113 Parameters
114 ----------
115 unit_name
116 Name of the unit to check.
117 Can be prefixed, pluralized or even an alias
118
119 Raises
120 ------
121 UndefinedUnitError
122 If the unit is not in the registry.
123 """
124 if unit_name in self._units:
125 return self._units[unit_name].is_multiplicative
126
127 # If the unit is not in the registry might be because it is not
128 # registered with its prefixed version.
129 # TODO: Might be better to register them.
130 names = self.parse_unit_name(unit_name)
131 assert len(names) == 1
132 _, base_name, _ = names[0]
133 try:
134 return self._units[base_name].is_multiplicative
135 except KeyError:
136 raise UndefinedUnitError(unit_name)
137
138 def _validate_and_extract(self, units: UnitsContainer) -> str | None:
139 """Used to check if a given units is suitable for a simple
140 conversion.
141
142 Return None if all units are non-multiplicative
143 Return the unit name if a single non-multiplicative unit is found
144 and is raised to a power equals to 1.
145
146 Otherwise, raise an Exception.
147
148 Parameters
149 ----------
150 units
151 Compound dictionary.
152
153 Raises
154 ------
155 ValueError
156 If the more than a single non-multiplicative unit is present,
157 or a single one is present but raised to a power different from 1.
158
159 """
160
161 # TODO: document what happens if autoconvert_offset_to_baseunit
162 # TODO: Clarify docs
163
164 # u is for unit, e is for exponent
165 nonmult_units = [
166 (u, e) for u, e in units.items() if not self._is_multiplicative(u)
167 ]
168
169 # Let's validate source offset units
170 if len(nonmult_units) > 1:
171 # More than one src offset unit is not allowed
172 raise ValueError("more than one offset unit.")
173
174 elif len(nonmult_units) == 1:
175 # A single src offset unit is present. Extract it
176 # But check that:
177 # - the exponent is 1
178 # - is not used in multiplicative context
179 nonmult_unit, exponent = nonmult_units.pop()
180
181 if exponent != 1:
182 raise ValueError("offset units in higher order.")
183
184 if len(units) > 1 and not self.autoconvert_offset_to_baseunit:
185 raise ValueError("offset unit used in multiplicative context.")
186
187 return nonmult_unit
188
189 return None
190
191 def _add_ref_of_log_or_offset_unit(
192 self, offset_unit: str, all_units: UnitsContainer
193 ) -> UnitsContainer:
194 slct_unit = self._units[offset_unit]
195 if slct_unit.is_logarithmic:
196 # Extract reference unit
197 slct_ref = slct_unit.reference
198
199 # TODO: Check that reference is None
200
201 # If reference unit is not dimensionless
202 if slct_ref != UnitsContainer():
203 # Extract reference unit
204 (u, e) = [(u, e) for u, e in slct_ref.items()].pop()
205 # Add it back to the unit list
206 return all_units.add(u, e)
207
208 if not slct_unit.is_multiplicative: # is offset unit
209 # Extract reference unit
210 return slct_unit.reference
211
212 # Otherwise, return the units unmodified
213 return all_units
214
215 def _convert(
216 self,
217 value: T,
218 src: UnitsContainer,
219 dst: UnitsContainer,
220 inplace: bool = False,
221 **ctx_kwargs: Any,
222 ) -> T:
223 """Convert value from some source to destination units.
224
225 In addition to what is done by the PlainRegistry,
226 converts between non-multiplicative units.
227
228 Parameters
229 ----------
230 value :
231 value
232 src : UnitsContainer
233 source units.
234 dst : UnitsContainer
235 destination units.
236 inplace :
237 (Default value = False)
238
239 Returns
240 -------
241 type
242 converted value
243
244 """
245
246 # Conversion needs to consider if non-multiplicative (AKA offset
247 # units) are involved. Conversion is only possible if src and dst
248 # have at most one offset unit per dimension. Other rules are applied
249 # by validate and extract.
250 try:
251 src_offset_unit = self._validate_and_extract(src)
252 except ValueError as ex:
253 raise DimensionalityError(src, dst, extra_msg=f" - In source units, {ex}")
254
255 try:
256 dst_offset_unit = self._validate_and_extract(dst)
257 except ValueError as ex:
258 raise DimensionalityError(
259 src, dst, extra_msg=f" - In destination units, {ex}"
260 )
261
262 # convert if no offset units are present
263 if not (src_offset_unit or dst_offset_unit):
264 return super()._convert(value, src, dst, inplace)
265
266 src_dim = self._get_dimensionality(src)
267 dst_dim = self._get_dimensionality(dst)
268
269 # If the source and destination dimensionality are different,
270 # then the conversion cannot be performed.
271 if src_dim != dst_dim:
272 raise DimensionalityError(src, dst, src_dim, dst_dim)
273
274 # clean src from offset units by converting to reference
275 if src_offset_unit:
276 if any(u.startswith("delta_") for u in dst):
277 raise DimensionalityError(src, dst)
278 value = self._units[src_offset_unit].converter.to_reference(value, inplace)
279 src = src.remove([src_offset_unit])
280 # Add reference unit for multiplicative section
281 src = self._add_ref_of_log_or_offset_unit(src_offset_unit, src)
282
283 # clean dst units from offset units
284 if dst_offset_unit:
285 if any(u.startswith("delta_") for u in src):
286 raise DimensionalityError(src, dst)
287 dst = dst.remove([dst_offset_unit])
288 # Add reference unit for multiplicative section
289 dst = self._add_ref_of_log_or_offset_unit(dst_offset_unit, dst)
290
291 # Convert non multiplicative units to the dst.
292 value = super()._convert(value, src, dst, inplace, False, **ctx_kwargs)
293
294 # Finally convert to offset units specified in destination
295 if dst_offset_unit:
296 value = self._units[dst_offset_unit].converter.from_reference(
297 value, inplace
298 )
299
300 return value
301
302
303 class NonMultiplicativeRegistry(
304 GenericNonMultiplicativeRegistry[
305 objects.NonMultiplicativeQuantity, objects.NonMultiplicativeUnit
306 ]
307 ):
308 Quantity: TypeAlias = objects.NonMultiplicativeQuantity
309 Unit: TypeAlias = objects.NonMultiplicativeUnit