unitcorn 0.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of unitcorn might be problematic. Click here for more details.
- unitcorn/__init__.py +110 -0
- unitcorn/airQuality/__init__.py +99 -0
- unitcorn/area/__init__.py +3 -0
- unitcorn/area/area.py +103 -0
- unitcorn/base/Decorators.py +72 -0
- unitcorn/base/Registry.py +75 -0
- unitcorn/base/SmartBases.py +26 -0
- unitcorn/base/_Algebra.py +205 -0
- unitcorn/base/_Measurement.py +1122 -0
- unitcorn/base/_ScalingMeasurement.py +398 -0
- unitcorn/base/_SmartFloat.py +1635 -0
- unitcorn/base/__init__.py +6 -0
- unitcorn/config/__init__.py +318 -0
- unitcorn/config/__main__.py +8 -0
- unitcorn/config/si.toml +53 -0
- unitcorn/config/template.toml +146 -0
- unitcorn/config/us.toml +53 -0
- unitcorn/defaults/WeatherFlow/__init__.py +176 -0
- unitcorn/defaults/__init__.py +1 -0
- unitcorn/derived/__init__.py +16 -0
- unitcorn/derived/density.py +26 -0
- unitcorn/derived/partsPer.py +96 -0
- unitcorn/derived/precipitation.py +96 -0
- unitcorn/derived/rate.py +80 -0
- unitcorn/derived/volume.py +122 -0
- unitcorn/derived/wind.py +54 -0
- unitcorn/digital/__init__.py +21 -0
- unitcorn/energy/__init__.py +4 -0
- unitcorn/energy/energy.py +120 -0
- unitcorn/energy/power.py +83 -0
- unitcorn/errors/Conversion.py +12 -0
- unitcorn/errors/Unit.py +4 -0
- unitcorn/errors/__init__.py +7 -0
- unitcorn/length/__init__.py +19 -0
- unitcorn/length/imperial.py +46 -0
- unitcorn/length/length.py +74 -0
- unitcorn/length/metric.py +56 -0
- unitcorn/mass/__init__.py +15 -0
- unitcorn/mass/imperial.py +47 -0
- unitcorn/mass/mass.py +57 -0
- unitcorn/mass/metric.py +47 -0
- unitcorn/others/__init__.py +338 -0
- unitcorn/others/light.py +51 -0
- unitcorn/pressure/__init__.py +3 -0
- unitcorn/pressure/pressure.py +189 -0
- unitcorn/py.typed +0 -0
- unitcorn/temperature/__init__.py +19 -0
- unitcorn/temperature/celsius.py +23 -0
- unitcorn/temperature/change.py +156 -0
- unitcorn/temperature/fahrenheit.py +24 -0
- unitcorn/temperature/kelvin.py +25 -0
- unitcorn/temperature/temperature.py +154 -0
- unitcorn/time_/__init__.py +1 -0
- unitcorn/time_/time.py +387 -0
- unitcorn/utils.py +399 -0
- unitcorn-0.9.0.dist-info/METADATA +536 -0
- unitcorn-0.9.0.dist-info/RECORD +59 -0
- unitcorn-0.9.0.dist-info/WHEEL +4 -0
- unitcorn-0.9.0.dist-info/licenses/LICENSE.txt +17 -0
|
@@ -0,0 +1,1122 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import ChainMap
|
|
3
|
+
|
|
4
|
+
from functools import lru_cache, cached_property
|
|
5
|
+
import logging
|
|
6
|
+
from datetime import datetime, timedelta
|
|
7
|
+
from numbers import Number
|
|
8
|
+
from typing import Callable, ClassVar, Dict, List, Optional, Type, Union, Final, Literal, Iterable, TypeVar, TypeAlias
|
|
9
|
+
|
|
10
|
+
__all__ = ['Measurement', 'DerivedMeasurement', 'Dimension', 'metric', 'imperial', 'both', 'Dimensionless', 'Quantity', 'Index', 'NonPlural']
|
|
11
|
+
|
|
12
|
+
from .. import errors
|
|
13
|
+
from . import SmartFloat, FormatSpec, MetaUnitClass
|
|
14
|
+
from .Registry import UnitRegistry
|
|
15
|
+
from ..utils import HashSlice, Other, Self
|
|
16
|
+
from ..config import config
|
|
17
|
+
|
|
18
|
+
log = logging.getLogger('unitcorn').getChild('Measurement')
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
from math import isclose, isinf, isnan, nan
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@lru_cache(maxsize=None)
|
|
26
|
+
def _conversionParams(toUnit: type, fromUnit: type) -> tuple:
|
|
27
|
+
"""Return the affine ``(factor, offset)`` pair for converting a raw value expressed
|
|
28
|
+
in ``fromUnit`` into ``toUnit`` via ``value * factor + offset``.
|
|
29
|
+
|
|
30
|
+
The pair is derived once from the existing (correct) conversion path by sampling the
|
|
31
|
+
conversion of ``0.0`` and ``1.0`` and is then cached for reuse. This works uniformly
|
|
32
|
+
for multiplicative units (``offset == 0``) and affine units such as temperature.
|
|
33
|
+
"""
|
|
34
|
+
offset = float(toUnit(fromUnit(0.0)))
|
|
35
|
+
factor = float(toUnit(fromUnit(1.0))) - offset
|
|
36
|
+
return factor, offset
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Measurement(SmartFloat):
|
|
40
|
+
__unitDict__ = ChainMap()
|
|
41
|
+
_derived: bool
|
|
42
|
+
_type: type
|
|
43
|
+
_updateFunction: Optional[Callable]
|
|
44
|
+
_timestamp: datetime
|
|
45
|
+
_indoor: bool
|
|
46
|
+
_calculated: bool
|
|
47
|
+
_category: str
|
|
48
|
+
_subTypes: ClassVar[Dict[str, Type['Measurement']]]
|
|
49
|
+
|
|
50
|
+
def __init_subclass__(cls, **kwargs):
|
|
51
|
+
if kwargs.get('type', False):
|
|
52
|
+
cls._type = cls
|
|
53
|
+
|
|
54
|
+
def __new__(cls, value, title: str = None, key: str = None, timestamp: datetime = None, period: timedelta = None, **kwargs):
|
|
55
|
+
value = nan if value is None else float(value)
|
|
56
|
+
# NaN is a gap, not a number: sorting it into the limits would land it on the upper one
|
|
57
|
+
if not isnan(value):
|
|
58
|
+
value = sorted((*cls.limits, value))[1]
|
|
59
|
+
return SmartFloat.__new__(cls, value)
|
|
60
|
+
|
|
61
|
+
def __class_getitem__(cls, item):
|
|
62
|
+
if (underItem := f'_{item}') in cls.__annotations__:
|
|
63
|
+
return cls.__annotations__[underItem]
|
|
64
|
+
if item in cls.__dict__:
|
|
65
|
+
return cls.__dict__[item]
|
|
66
|
+
if isinstance(item, str):
|
|
67
|
+
item = cls.__findUnitClass__(item)
|
|
68
|
+
if isinstance(item, type) and issubclass(item, Measurement):
|
|
69
|
+
if item in cls.subTypes:
|
|
70
|
+
return item
|
|
71
|
+
parentType = cls.type
|
|
72
|
+
name = f'{parentType.__name__}[{item.__name__}]'
|
|
73
|
+
newCls = type(name, (item, cls,), {})
|
|
74
|
+
return newCls
|
|
75
|
+
|
|
76
|
+
raise TypeError(f'{cls.__name__} does not support {item}')
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def getClass(cls, unit: str) -> Type['Measurement'] | None:
|
|
80
|
+
if isinstance(unit, Iterable) and not isinstance(unit, str):
|
|
81
|
+
unit = ''.join(unit)
|
|
82
|
+
return cls.__findUnitClass__(unit)
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def get_conversion(cls, from_unit: Union[Type['Measurement'], 'Measurement']) -> tuple:
|
|
86
|
+
"""Return the cached affine ``(factor, offset)`` used to convert a raw value
|
|
87
|
+
expressed in ``from_unit`` into ``cls`` via ``value * factor + offset``.
|
|
88
|
+
|
|
89
|
+
Supports both multiplicative units (``offset == 0``) and affine units such as
|
|
90
|
+
temperature. The result is cached, so repeated conversions between the same two
|
|
91
|
+
units avoid re-running the per-instance conversion machinery.
|
|
92
|
+
"""
|
|
93
|
+
if not isinstance(from_unit, type):
|
|
94
|
+
from_unit = type(from_unit)
|
|
95
|
+
return _conversionParams(cls, from_unit)
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def convert_array(cls, values, from_unit: Union[Type['Measurement'], 'Measurement'] = None):
|
|
99
|
+
"""Vectorized conversion of an array of raw values from ``from_unit`` into ``cls``.
|
|
100
|
+
|
|
101
|
+
Converts an entire array in a single ``values * factor + offset`` operation using
|
|
102
|
+
the cached conversion parameters, returning a raw array without constructing a
|
|
103
|
+
``Measurement`` per element. Accepts any array-like; when :mod:`numpy` is available
|
|
104
|
+
the input is coerced to a ``float64`` ``ndarray``.
|
|
105
|
+
|
|
106
|
+
This is the array-first conversion path intended for bulk/plotting pipelines where
|
|
107
|
+
values are flattened into numeric arrays anyway.
|
|
108
|
+
"""
|
|
109
|
+
if from_unit is None:
|
|
110
|
+
from_unit = cls
|
|
111
|
+
factor, offset = cls.get_conversion(from_unit)
|
|
112
|
+
try:
|
|
113
|
+
import numpy as np
|
|
114
|
+
values = np.asarray(values, dtype='float64')
|
|
115
|
+
except ImportError:
|
|
116
|
+
pass
|
|
117
|
+
return values * factor + offset
|
|
118
|
+
|
|
119
|
+
def __init__(self, value, title: str = None, key: str = None, timestamp: datetime = None, category: str = None, period: timedelta = None):
|
|
120
|
+
if isinstance(value, Measurement):
|
|
121
|
+
if value._timestamp and timestamp is None:
|
|
122
|
+
timestamp = value._timestamp
|
|
123
|
+
if period is None:
|
|
124
|
+
period = getattr(value, '_period', None)
|
|
125
|
+
if title:
|
|
126
|
+
self._title = title
|
|
127
|
+
if key:
|
|
128
|
+
self._key = key
|
|
129
|
+
self.category = category
|
|
130
|
+
|
|
131
|
+
self._timestamp = timestamp
|
|
132
|
+
self._period = period
|
|
133
|
+
|
|
134
|
+
SmartFloat.__init__(self, value)
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def category(self):
|
|
138
|
+
if (category := getattr(self, '_category', None)) is None:
|
|
139
|
+
return self.__class__.__name__.lower()
|
|
140
|
+
return self._category
|
|
141
|
+
|
|
142
|
+
@category.setter
|
|
143
|
+
def category(self, value):
|
|
144
|
+
self._category = value
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def localize(self):
|
|
148
|
+
if self.convertible:
|
|
149
|
+
try:
|
|
150
|
+
if (newUnit := type(self).localizedUnit) is not None:
|
|
151
|
+
return newUnit(self)
|
|
152
|
+
return self
|
|
153
|
+
except (AttributeError, KeyError) as e:
|
|
154
|
+
# `except AttributeError or KeyError` only ever caught
|
|
155
|
+
# AttributeError (the `or` short-circuits to its first,
|
|
156
|
+
# always-truthy operand at class-definition time) and never
|
|
157
|
+
# returned/raised on catch, so failed localization (e.g. no
|
|
158
|
+
# config loaded) silently produced None instead of falling
|
|
159
|
+
# back to self - matching DerivedMeasurement.localize's
|
|
160
|
+
# existing, correct fallback below.
|
|
161
|
+
log.error("Unable to get localized type for {}: {}".format(self.name, e))
|
|
162
|
+
return self
|
|
163
|
+
else:
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def convertible(self) -> bool:
|
|
168
|
+
return getattr(self, '_convertable', True)
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def str(self):
|
|
172
|
+
return str(self)
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def type(self) -> Type[Self]:
|
|
176
|
+
return type(self).type
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def period(self) -> Optional[timedelta]:
|
|
180
|
+
"""The window this value covers (rain in the last 24 h), if it has one.
|
|
181
|
+
|
|
182
|
+
Metadata beside `timestamp`: conversion and arithmetic never touch it.
|
|
183
|
+
"""
|
|
184
|
+
return getattr(self, '_period', None)
|
|
185
|
+
|
|
186
|
+
@period.setter
|
|
187
|
+
def period(self, value: Optional[timedelta]):
|
|
188
|
+
self._period = value
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def timestamp(self) -> datetime:
|
|
192
|
+
return self._timestamp
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def updateFunction(self):
|
|
196
|
+
return self._updateFunction
|
|
197
|
+
|
|
198
|
+
@updateFunction.setter
|
|
199
|
+
def updateFunction(self, function: callable):
|
|
200
|
+
self._updateFunction = function
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def indoor(self) -> bool:
|
|
204
|
+
return self._indoor
|
|
205
|
+
|
|
206
|
+
@indoor.setter
|
|
207
|
+
def indoor(self, value: bool):
|
|
208
|
+
self._indoor = value
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def calculated(self) -> bool:
|
|
212
|
+
return self._calculated
|
|
213
|
+
|
|
214
|
+
@calculated.setter
|
|
215
|
+
def calculated(self, value: bool):
|
|
216
|
+
self._calculated = value
|
|
217
|
+
|
|
218
|
+
def _convert(self, other: 'Measurement') -> Self:
|
|
219
|
+
"""For comparisons, convert other to own type"""
|
|
220
|
+
if self._sameDimension(other):
|
|
221
|
+
return self.__class__(other)
|
|
222
|
+
if isinstance(other, (float, int)):
|
|
223
|
+
return self.__class__(other)
|
|
224
|
+
else:
|
|
225
|
+
return other
|
|
226
|
+
|
|
227
|
+
@cached_property
|
|
228
|
+
def valuePrecision(self) -> int:
|
|
229
|
+
if isinf(self):
|
|
230
|
+
return 0
|
|
231
|
+
_, value = self.intFloatLength(float(self))
|
|
232
|
+
return value
|
|
233
|
+
|
|
234
|
+
def transform(self, other, transformTo: type = None):
|
|
235
|
+
if isinstance(other, type) and issubclass(other, Measurement):
|
|
236
|
+
other = other(self)
|
|
237
|
+
nonTransferred = ['_unit', '_suffix', '_scale', '_denominator', '_numerator']
|
|
238
|
+
if self.type != other.type:
|
|
239
|
+
log.warning(f'{self.withUnit} and {other.withUnit} are not identical types, this may cause issues')
|
|
240
|
+
other.__dict__.update({key: value for key, value in self.__dict__.items() if key not in nonTransferred and value is not None})
|
|
241
|
+
if getattr(other, '_updateFunction', None):
|
|
242
|
+
other._updateFunction(other)
|
|
243
|
+
return other
|
|
244
|
+
|
|
245
|
+
def _sameDimension(self, other) -> bool:
|
|
246
|
+
"""`other` measures what this does, in whatever unit or system.
|
|
247
|
+
|
|
248
|
+
`.type` alone is not that test: a scaling unit's type is its system's family,
|
|
249
|
+
so `Meter.type` is MetricLength and `Foot.type` is ImperialLength.
|
|
250
|
+
"""
|
|
251
|
+
if not isinstance(other, Measurement):
|
|
252
|
+
return False
|
|
253
|
+
if isinstance(other, self.type):
|
|
254
|
+
return True
|
|
255
|
+
if isinstance(self, Dimensionless) or isinstance(other, Dimensionless):
|
|
256
|
+
return False
|
|
257
|
+
if (dimension := type(self).dimension) is not None and dimension is type(other).dimension:
|
|
258
|
+
return True
|
|
259
|
+
if isinstance(self, DerivedMeasurement) and isinstance(other, DerivedMeasurement):
|
|
260
|
+
# A rain rate and a wind speed are both a distance over a time.
|
|
261
|
+
from ._Algebra import hasDimension, vectorOf
|
|
262
|
+
return hasDimension(self) and hasDimension(other) and vectorOf(self) == vectorOf(other)
|
|
263
|
+
return False
|
|
264
|
+
|
|
265
|
+
def _inThisUnit(self, other: 'Measurement') -> float:
|
|
266
|
+
"""`other`, a measurement of this dimension, as a number of this unit."""
|
|
267
|
+
if type(other) is type(self):
|
|
268
|
+
return float(other)
|
|
269
|
+
try:
|
|
270
|
+
return float(type(self)(other))
|
|
271
|
+
except (TypeError, ValueError, AttributeError, errors.BadConversion):
|
|
272
|
+
return float(other[self.unit])
|
|
273
|
+
|
|
274
|
+
def __wrapOther(self, other: Union['Measurement', float, int]) -> float:
|
|
275
|
+
if self._sameDimension(other):
|
|
276
|
+
return self._inThisUnit(other)
|
|
277
|
+
# Dimensionality guard: two measurements of different, non-dimensionless
|
|
278
|
+
# dimensions can not be combined (e.g. Length + Temperature).
|
|
279
|
+
# Note: Measurement subclasses float, so this must precede the numeric check.
|
|
280
|
+
if isinstance(other, Measurement) and not isinstance(other, Dimensionless) and not isinstance(self, Dimensionless):
|
|
281
|
+
raise errors.BadConversion(self, other)
|
|
282
|
+
if isinstance(other, (float, int)):
|
|
283
|
+
return float(other)
|
|
284
|
+
if isinstance(other, timedelta):
|
|
285
|
+
return other.total_seconds()
|
|
286
|
+
if isinstance(other, str):
|
|
287
|
+
if (match := FormatSpec.number.search(other)) is not None:
|
|
288
|
+
return float(match.groupdict()['number'])
|
|
289
|
+
return float(other)
|
|
290
|
+
|
|
291
|
+
@cached_property
|
|
292
|
+
def _canonicalValue(self) -> float:
|
|
293
|
+
"""One number for this quantity whatever its unit, for `__hash__`.
|
|
294
|
+
|
|
295
|
+
The SI value where the dimension algebra knows one, else the value in the
|
|
296
|
+
base unit of its scale, else the value itself.
|
|
297
|
+
"""
|
|
298
|
+
from ._Algebra import hasDimension, siValue
|
|
299
|
+
if not isinstance(self, Dimensionless) and hasDimension(self):
|
|
300
|
+
try:
|
|
301
|
+
return siValue(self)
|
|
302
|
+
except TypeError:
|
|
303
|
+
# A temperature reading has no SI magnitude to multiply by, but kelvin still orders and equates it.
|
|
304
|
+
from ..temperature import Kelvin
|
|
305
|
+
return float(Kelvin(self))
|
|
306
|
+
if (scale := getattr(self, '_Scale', None)) is not None:
|
|
307
|
+
return float(self.changeScale(scale.Base))
|
|
308
|
+
return float(self)
|
|
309
|
+
|
|
310
|
+
def __operands(self, other: Union['Measurement', float, int]) -> tuple[float, float]:
|
|
311
|
+
"""This value and `other` as two numbers of this unit.
|
|
312
|
+
|
|
313
|
+
Raises `BadConversion` for a measurement of another dimension.
|
|
314
|
+
"""
|
|
315
|
+
return float(self), self.__wrapOther(other)
|
|
316
|
+
|
|
317
|
+
def __eq__(self, other: Union['Measurement', float, int]) -> bool:
|
|
318
|
+
"""The values are equal, not their display: `Celsius(20) != Celsius(20.05)`; see `displays_same`.
|
|
319
|
+
|
|
320
|
+
Within a relative 1e-9, since a conversion leaves float noise (`Meter(Foot(Meter(1)))`), and an absolute 1e-12
|
|
321
|
+
for the zero of an offset scale: `Kelvin(273.15)` in Celsius is not exactly 0.
|
|
322
|
+
"""
|
|
323
|
+
try:
|
|
324
|
+
mine, theirs = self.__operands(other)
|
|
325
|
+
except (ValueError, TypeError, errors.BadConversion):
|
|
326
|
+
return False
|
|
327
|
+
return isclose(mine, theirs, rel_tol=1e-9, abs_tol=1e-12)
|
|
328
|
+
|
|
329
|
+
def __ne__(self, other: Union['Measurement', float, int]) -> bool:
|
|
330
|
+
# float's own `!=` would compare the raw magnitudes: `Meter(1) != Celsius(1)` would be False.
|
|
331
|
+
return not self.__eq__(other)
|
|
332
|
+
|
|
333
|
+
def displays_same(self, other: Union['Measurement', float, int]) -> bool:
|
|
334
|
+
"""`other`, put into this unit, formats to the same text as this value: does a readout need repainting?"""
|
|
335
|
+
try:
|
|
336
|
+
mine, theirs = self.__operands(other)
|
|
337
|
+
except (ValueError, TypeError, errors.BadConversion):
|
|
338
|
+
return False
|
|
339
|
+
return str(self) == str(self._sameType(theirs))
|
|
340
|
+
|
|
341
|
+
def __getitem__(self: Self, item: Other | Number):
|
|
342
|
+
try:
|
|
343
|
+
return self.__getattribute__(item)
|
|
344
|
+
except AttributeError:
|
|
345
|
+
if isinstance(item, str):
|
|
346
|
+
# type(self)[item] goes through __class_getitem__, which is for
|
|
347
|
+
# building composite/generic types (e.g. DerivedMeasurement
|
|
348
|
+
# numerator/denominator pairing) - it resolves the unit class
|
|
349
|
+
# correctly via __findUnitClass__ internally, then discards
|
|
350
|
+
# that result and synthesizes a bogus multi-inheritance class
|
|
351
|
+
# when the unit isn't a literal subType of cls (true for any
|
|
352
|
+
# sibling unit in the same scale family, e.g. Week vs Month).
|
|
353
|
+
# Go straight to the unit lookup instead.
|
|
354
|
+
if (unitClass := type(self).__findUnitClass__(item)) is not None:
|
|
355
|
+
return unitClass(self)
|
|
356
|
+
raise errors.Conversion.UnknownUnit(self, str(item))
|
|
357
|
+
raise errors.Conversion.UnknownUnit(self, str(item))
|
|
358
|
+
|
|
359
|
+
def __mul__(self: Self, other: Other | Number) -> Self:
|
|
360
|
+
# Simplify a derived measurement multiplied by its denominator's dimension:
|
|
361
|
+
# e.g. (m/s) * s -> m
|
|
362
|
+
if isinstance(self, DerivedMeasurement) and isinstance(other, Measurement):
|
|
363
|
+
denominator = self.denominator
|
|
364
|
+
if isinstance(other, denominator.type):
|
|
365
|
+
otherValue = float(other[denominator.unit])
|
|
366
|
+
return type(self).numerator(float(self) * otherValue)
|
|
367
|
+
# Multiplication commutes: allow <Measurement> * <derived> to simplify too
|
|
368
|
+
if isinstance(other, DerivedMeasurement) and not isinstance(self, DerivedMeasurement):
|
|
369
|
+
if isinstance(self, other.denominator.type):
|
|
370
|
+
return other.__mul__(self)
|
|
371
|
+
if isinstance(other, Measurement) and self._algebraic(other):
|
|
372
|
+
from ._Algebra import multiply
|
|
373
|
+
return multiply(self, other)
|
|
374
|
+
other = self.__wrapOther(other)
|
|
375
|
+
return type(self)(super().__mul__(other))
|
|
376
|
+
|
|
377
|
+
def __add__(self: Self, other: Other | Number) -> Self:
|
|
378
|
+
other = self.__wrapOther(other)
|
|
379
|
+
return type(self)(super().__add__(other))
|
|
380
|
+
|
|
381
|
+
def __radd__(self: Self, other: Other | Number) -> Self :
|
|
382
|
+
if isinstance(other, SmartFloat):
|
|
383
|
+
return other.__add__(self)
|
|
384
|
+
other = self.__wrapOther(other)
|
|
385
|
+
return type(self)(super().__radd__(other))
|
|
386
|
+
|
|
387
|
+
def __sub__(self: Self, other: Other | Number) -> Self:
|
|
388
|
+
other = self.__wrapOther(other)
|
|
389
|
+
return type(self)(super().__sub__(other))
|
|
390
|
+
|
|
391
|
+
def __rsub__(self: Self, other: Other | Number) -> Self | Other:
|
|
392
|
+
other = self.__wrapOther(other)
|
|
393
|
+
return type(self)(super().__rsub__(other))
|
|
394
|
+
|
|
395
|
+
def __pow__(self: Self, power: Other | Number, modulo=None) -> Self:
|
|
396
|
+
other = self.__wrapOther(power)
|
|
397
|
+
return type(self)(super().__pow__(other, modulo))
|
|
398
|
+
|
|
399
|
+
def _algebraic(self, other) -> bool:
|
|
400
|
+
"""Both sides have a dimension, so `*` and `/` follow the dimension algebra."""
|
|
401
|
+
from ._Algebra import hasDimension
|
|
402
|
+
return not isinstance(self, Dimensionless) and not isinstance(other, Dimensionless) and hasDimension(self) and hasDimension(other)
|
|
403
|
+
|
|
404
|
+
def __truediv__(self: Self, other: Other | Number) -> Self:
|
|
405
|
+
if type(self) is type(other) and not isinstance(self, Dimensionless):
|
|
406
|
+
# Two values in the same unit divide to a ratio. This also covers a
|
|
407
|
+
# temperature span over a temperature span, which has no reading in it.
|
|
408
|
+
return float(self) / float(other)
|
|
409
|
+
if isinstance(other, Measurement) and self._algebraic(other):
|
|
410
|
+
from ._Algebra import divide, vectorOf
|
|
411
|
+
if vectorOf(self) == vectorOf(other):
|
|
412
|
+
return float(divide(self, other))
|
|
413
|
+
if vectorOf(self) == (1, 0, 0, 0) and vectorOf(other) == (0, 0, 1, 0):
|
|
414
|
+
# A distance over a time keeps the units it was given (mm / h -> mm/hr)
|
|
415
|
+
# instead of going through SI.
|
|
416
|
+
if matched := UnitRegistry.get_derived(type(self), type(other)):
|
|
417
|
+
return matched(self, other)
|
|
418
|
+
from ..derived import DistanceOverTime
|
|
419
|
+
return DistanceOverTime(self, other)
|
|
420
|
+
return divide(self, other)
|
|
421
|
+
if isinstance(self, DerivedMeasurement) and not isinstance(other, Measurement):
|
|
422
|
+
# Dividing a derived measurement by a scalar scales its numerator:
|
|
423
|
+
# e.g. (6m / 2s) / 2 -> (3m / 2s)
|
|
424
|
+
numerator = self.numerator / other
|
|
425
|
+
return type(self)(numerator, self.denominator)
|
|
426
|
+
|
|
427
|
+
if isinstance(other, Measurement) and not isinstance(self, DerivedMeasurement):
|
|
428
|
+
if matched := UnitRegistry.get_derived(type(self), type(other)):
|
|
429
|
+
return matched(self, other)
|
|
430
|
+
return DerivedMeasurement(self, other)
|
|
431
|
+
|
|
432
|
+
if isinstance(other, (float, int)):
|
|
433
|
+
v = type(self)(super().__truediv__(other))
|
|
434
|
+
v.__dict__.update({k: v for k, v in self.__dict__.items() if k != '_calculated'})
|
|
435
|
+
return v
|
|
436
|
+
|
|
437
|
+
other = self.__wrapOther(other)
|
|
438
|
+
return type(self)(super().__truediv__(other))
|
|
439
|
+
|
|
440
|
+
def _sameType(self, value: float) -> Self:
|
|
441
|
+
"""A new measurement of this type holding `value`, with this one's metadata."""
|
|
442
|
+
new = type(self)(value)
|
|
443
|
+
for key in ('_title', '_key', '_timestamp', '_period', '_category'):
|
|
444
|
+
if (kept := self.__dict__.get(key)) is not None:
|
|
445
|
+
new.__dict__[key] = kept
|
|
446
|
+
return new
|
|
447
|
+
|
|
448
|
+
def __rmul__(self: Self, other: Other | Number) -> Self:
|
|
449
|
+
if isinstance(other, Measurement):
|
|
450
|
+
return other.__mul__(self)
|
|
451
|
+
return self._sameType(float(other) * float(self))
|
|
452
|
+
|
|
453
|
+
def __neg__(self: Self) -> Self:
|
|
454
|
+
return self._sameType(-float(self))
|
|
455
|
+
|
|
456
|
+
def __pos__(self: Self) -> Self:
|
|
457
|
+
return self._sameType(float(self))
|
|
458
|
+
|
|
459
|
+
def __mod__(self: Self, other: Other | Number) -> Self:
|
|
460
|
+
return self._sameType(float(self) % self.__wrapOther(other))
|
|
461
|
+
|
|
462
|
+
def __floor__(self: Self)-> Self:
|
|
463
|
+
return type(self)(super().__floor__())
|
|
464
|
+
|
|
465
|
+
def __ceil__(self: Self) -> Self:
|
|
466
|
+
return type(self)(super().__ceil__())
|
|
467
|
+
|
|
468
|
+
def __floordiv__(self: Self, other: Other | Number) -> Self:
|
|
469
|
+
return type(self)(super().__floordiv__(other))
|
|
470
|
+
|
|
471
|
+
def __order(self, other: Other | Number, symbol: str) -> tuple[float, float] | None:
|
|
472
|
+
"""The operands of an ordering, or None when `other` is not a number at all."""
|
|
473
|
+
try:
|
|
474
|
+
return self.__operands(other)
|
|
475
|
+
except errors.BadConversion:
|
|
476
|
+
# Python's contract for unorderable types; a silent False would make `sorted()` lie.
|
|
477
|
+
raise TypeError(f"'{symbol}' not supported between {type(self).__name__} and {type(other).__name__}") from None
|
|
478
|
+
except (ValueError, TypeError):
|
|
479
|
+
return None
|
|
480
|
+
|
|
481
|
+
def __lt__(self: Self, other: Other | Number) -> bool:
|
|
482
|
+
if (operands := self.__order(other, '<')) is None:
|
|
483
|
+
return False
|
|
484
|
+
mine, theirs = operands
|
|
485
|
+
return mine < theirs and not isclose(mine, theirs, rel_tol=1e-9, abs_tol=1e-12)
|
|
486
|
+
|
|
487
|
+
def __gt__(self: Self, other: Other | Number) -> bool:
|
|
488
|
+
if (operands := self.__order(other, '>')) is None:
|
|
489
|
+
return False
|
|
490
|
+
mine, theirs = operands
|
|
491
|
+
return mine > theirs and not isclose(mine, theirs, rel_tol=1e-9, abs_tol=1e-12)
|
|
492
|
+
|
|
493
|
+
def __ge__(self: Self, other: Other | Number) -> bool:
|
|
494
|
+
if (operands := self.__order(other, '>=')) is None:
|
|
495
|
+
return False
|
|
496
|
+
mine, theirs = operands
|
|
497
|
+
return mine >= theirs or isclose(mine, theirs, rel_tol=1e-9, abs_tol=1e-12)
|
|
498
|
+
|
|
499
|
+
def __le__(self: Self, other: Other | Number) -> bool:
|
|
500
|
+
if (operands := self.__order(other, '<=')) is None:
|
|
501
|
+
return False
|
|
502
|
+
mine, theirs = operands
|
|
503
|
+
return mine <= theirs or isclose(mine, theirs, rel_tol=1e-9, abs_tol=1e-12)
|
|
504
|
+
|
|
505
|
+
def __abs__(self: Self) -> Self:
|
|
506
|
+
v = type(self)(super().__abs__())
|
|
507
|
+
v.__dict__.update(self.__dict__)
|
|
508
|
+
return v
|
|
509
|
+
|
|
510
|
+
def __hash__(self):
|
|
511
|
+
# Agrees with `==` in all but one case: `isclose` is not transitive, so two values a hair either side of a
|
|
512
|
+
# 9-significant-digit rounding boundary can compare equal and still hash apart.
|
|
513
|
+
return hash(float(f'{self._canonicalValue:.9g}'))
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
class DimensionlessMeta(MetaUnitClass):
|
|
517
|
+
|
|
518
|
+
def __new__(cls, name, bases, attrs, **kwargs):
|
|
519
|
+
return super().__new__(cls, name, bases, attrs, **kwargs)
|
|
520
|
+
|
|
521
|
+
@property
|
|
522
|
+
def type(cls):
|
|
523
|
+
return getattr(cls, '_type', None) or next((base for base in cls.__mro__ if SmartFloat.__Dimensionless__ in base.__bases__), cls)
|
|
524
|
+
|
|
525
|
+
@property
|
|
526
|
+
def isGeneric(cls):
|
|
527
|
+
return cls is Dimensionless
|
|
528
|
+
|
|
529
|
+
@property
|
|
530
|
+
def dimension(self):
|
|
531
|
+
return Dimensionless
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
class Dimensionless(SmartFloat.__Dimensionless__, Measurement, metaclass=DimensionlessMeta):
|
|
535
|
+
pass
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
class NonPlural(SmartFloat.__NonPlural__, Measurement):
|
|
539
|
+
pass
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
class Quantity(Dimensionless):
|
|
543
|
+
_digit_budget = 3
|
|
544
|
+
_precision = 0
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
class Index(Dimensionless, NonPlural):
|
|
548
|
+
_digit_budget = 3
|
|
549
|
+
_precision = 0
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
class DerivedMeasurementMeta(MetaUnitClass):
|
|
553
|
+
numerator: Type[Measurement]
|
|
554
|
+
_numerator: Type[Measurement]
|
|
555
|
+
|
|
556
|
+
denominator: Type[Measurement]
|
|
557
|
+
_denominator: Type[Measurement]
|
|
558
|
+
|
|
559
|
+
def __new__(mcs, name, bases, attrs, numerator: Type[Measurement] = None, denominator: Type[Measurement] = None, **kwargs):
|
|
560
|
+
if numerator is None:
|
|
561
|
+
# Prefer a CONCRETE numerator over a generic one. Inheriting from
|
|
562
|
+
# both a unit type and a concrete unit - `class MilesPerHour(Wind,
|
|
563
|
+
# DistanceOverTime.MilesPerHour)` - put the generic `<Length>` from
|
|
564
|
+
# Wind ahead of `Mile` from the concrete base purely because Wind
|
|
565
|
+
# is listed first, so the class no longer knew it was miles.
|
|
566
|
+
candidates = [j for i in bases if (j := getattr(i, 'numerator', None)) is not None]
|
|
567
|
+
numerator = next(
|
|
568
|
+
(c for c in candidates if not getattr(c, 'isGeneric', False)),
|
|
569
|
+
next(iter(candidates), None),
|
|
570
|
+
)
|
|
571
|
+
if numerator:
|
|
572
|
+
attrs['_numerator'] = numerator
|
|
573
|
+
annotations = attrs.get('__annotations__', {})
|
|
574
|
+
annotations['numerator'] = Type[numerator]
|
|
575
|
+
attrs['__annotations__'] = annotations
|
|
576
|
+
|
|
577
|
+
if denominator is None:
|
|
578
|
+
# Same concrete-over-generic preference as the numerator above.
|
|
579
|
+
d_candidates = [
|
|
580
|
+
base_d for base in bases
|
|
581
|
+
if (base_d := getattr(base, 'denominator', None)) is not Measurement and base_d is not None
|
|
582
|
+
]
|
|
583
|
+
denominator = next(
|
|
584
|
+
(c for c in d_candidates if not getattr(c, 'isGeneric', False)),
|
|
585
|
+
next(iter(d_candidates), None),
|
|
586
|
+
)
|
|
587
|
+
if denominator:
|
|
588
|
+
attrs['_denominator'] = denominator
|
|
589
|
+
annotations = attrs.get('__annotations__', {})
|
|
590
|
+
annotations['denominator'] = Type[denominator]
|
|
591
|
+
attrs['__annotations__'] = annotations
|
|
592
|
+
|
|
593
|
+
cls = super().__new__(mcs, name, bases, attrs, **kwargs)
|
|
594
|
+
UnitRegistry.register_derived(cls)
|
|
595
|
+
return cls
|
|
596
|
+
|
|
597
|
+
def _addSpecials(cls):
|
|
598
|
+
return
|
|
599
|
+
|
|
600
|
+
@property
|
|
601
|
+
def isGeneric(cls):
|
|
602
|
+
return cls.numerator.isGeneric or cls.denominator.isGeneric
|
|
603
|
+
|
|
604
|
+
@property
|
|
605
|
+
def numerator(self) -> Type[Measurement]:
|
|
606
|
+
return getattr(self, '_numerator', None)
|
|
607
|
+
|
|
608
|
+
@property
|
|
609
|
+
def denominator(self) -> Type[Measurement]:
|
|
610
|
+
return getattr(self, '_denominator', None)
|
|
611
|
+
|
|
612
|
+
@property
|
|
613
|
+
def numeratorClass(self) -> Type[Measurement]:
|
|
614
|
+
return getattr(self, '_numerator', None)
|
|
615
|
+
|
|
616
|
+
@numeratorClass.setter
|
|
617
|
+
def numeratorClass(self, value: Type[Measurement]):
|
|
618
|
+
self._numerator = value
|
|
619
|
+
|
|
620
|
+
@property
|
|
621
|
+
def denominatorClass(self) -> Type[Measurement]:
|
|
622
|
+
return getattr(self, '_denominator', None)
|
|
623
|
+
|
|
624
|
+
@denominatorClass.setter
|
|
625
|
+
def denominatorClass(self, value: Type[Measurement]):
|
|
626
|
+
self._denominator = value
|
|
627
|
+
|
|
628
|
+
@property
|
|
629
|
+
def pluralName(self) -> Optional[str]:
|
|
630
|
+
if not self.numerator.isGeneric:
|
|
631
|
+
return None
|
|
632
|
+
return f'{self.numerator.pluralName}/{self.denominator.name}'
|
|
633
|
+
|
|
634
|
+
@property
|
|
635
|
+
def pluralUnit(self) -> Optional[str]:
|
|
636
|
+
if not self.numerator.isGeneric:
|
|
637
|
+
return None
|
|
638
|
+
return f'{self.numerator.pluralUnit}/{self.denominator.unit}'
|
|
639
|
+
|
|
640
|
+
@property
|
|
641
|
+
def unitArray(mcs):
|
|
642
|
+
return [mcs.numerator.unit, mcs.denominator.unit]
|
|
643
|
+
|
|
644
|
+
@property
|
|
645
|
+
def Generic(self) -> Type:
|
|
646
|
+
genericBases = self.genericBases
|
|
647
|
+
genericBases = sorted(
|
|
648
|
+
(
|
|
649
|
+
base for base in genericBases
|
|
650
|
+
if base is not self
|
|
651
|
+
and issubclass(base, DerivedMeasurement)
|
|
652
|
+
and base.numerator.isGeneric
|
|
653
|
+
and base.denominator.isGeneric),
|
|
654
|
+
key=lambda base: self.__mro__.index(base)
|
|
655
|
+
)
|
|
656
|
+
return next(iter(genericBases), None)
|
|
657
|
+
|
|
658
|
+
@property
|
|
659
|
+
def genericBases(self):
|
|
660
|
+
return super().genericBases | self.numerator.genericBases | self.denominator.genericBases
|
|
661
|
+
|
|
662
|
+
@property
|
|
663
|
+
def compatibleUnits(cls) -> dict:
|
|
664
|
+
parentCls = cls.type
|
|
665
|
+
n = parentCls.numerator.type.compatibleUnits
|
|
666
|
+
d = parentCls.denominator.type.compatibleUnits
|
|
667
|
+
specifiedUnits = {u: t for t in parentCls.subTypes if (u := getattr(t, '_unit', None))}
|
|
668
|
+
return {**specifiedUnits, **n, **d}
|
|
669
|
+
|
|
670
|
+
# @property
|
|
671
|
+
# def subTypes(cls):
|
|
672
|
+
# subs = super().subTypes
|
|
673
|
+
# fixed = cls.fixedUnits
|
|
674
|
+
# if fixed[0] is None:
|
|
675
|
+
# subs |= cls.numerator.subTypes
|
|
676
|
+
# else:
|
|
677
|
+
# subs |= {cls.numerator}
|
|
678
|
+
# if fixed[1] is None:
|
|
679
|
+
# subs |= cls.denominator.subTypes
|
|
680
|
+
# else:
|
|
681
|
+
# subs |= {cls.denominator}
|
|
682
|
+
# return subs
|
|
683
|
+
|
|
684
|
+
@property
|
|
685
|
+
def unit(cls):
|
|
686
|
+
clsUnit = getattr(cls, '_unit', None)
|
|
687
|
+
if clsUnit:
|
|
688
|
+
return clsUnit
|
|
689
|
+
numUnit = cls.numerator.unit or f'({cls.numerator.__name__})'
|
|
690
|
+
denUnit = cls.denominator.unit or f'({cls.denominator.__name__})'
|
|
691
|
+
return f'{numUnit}/{denUnit}'
|
|
692
|
+
|
|
693
|
+
def __parse_unit__(self, unit: str | None):
|
|
694
|
+
if unit is None:
|
|
695
|
+
return None
|
|
696
|
+
units = re.sub(r'((?<=[A-Z_\-\s])(per)(?=[A-Z_\-\s]))|\\', '/', unit).split('/')
|
|
697
|
+
return tuple(i.strip(' ') for i in units)
|
|
698
|
+
|
|
699
|
+
@property
|
|
700
|
+
def id(cls):
|
|
701
|
+
clsID = getattr(cls, '_id', None)
|
|
702
|
+
if clsID:
|
|
703
|
+
return clsID
|
|
704
|
+
clsUnit = getattr(cls, '_unit', None)
|
|
705
|
+
if clsUnit:
|
|
706
|
+
return clsUnit
|
|
707
|
+
|
|
708
|
+
numUnit = cls.numerator.id or f'{cls.numerator.__name__}'
|
|
709
|
+
denUnit = cls.denominator.id or f'{cls.denominator.__name__}'
|
|
710
|
+
return f'{cls.__name__}({numUnit}/{denUnit})'
|
|
711
|
+
|
|
712
|
+
@property
|
|
713
|
+
def type(cls):
|
|
714
|
+
if (t := getattr(cls, '_type', None)) is not None:
|
|
715
|
+
return t
|
|
716
|
+
bases = cls.genericBases
|
|
717
|
+
n = {i for i in bases if (j := getattr(i, 'numerator', None)) is not None and j.isGeneric}
|
|
718
|
+
d = {i for i in bases if (j := getattr(i, 'denominator', None)) is not None and j.isGeneric}
|
|
719
|
+
_both = n | d
|
|
720
|
+
return sorted(_both, key=lambda i: cls.mro().index(i))[0]
|
|
721
|
+
|
|
722
|
+
@property
|
|
723
|
+
@lru_cache(maxsize=512)
|
|
724
|
+
def __unitDict__(self) -> ChainMap:
|
|
725
|
+
return ChainMap(self.numerator.__unitDict__, self.denominator.__unitDict__)
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
metric: Final = 'metric'
|
|
729
|
+
imperial: Final = 'imperial'
|
|
730
|
+
both: Final = 'mixed'
|
|
731
|
+
systemName: Final = Literal['metric', 'imperial', 'mixed']
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
class Dimension(MetaUnitClass):
|
|
735
|
+
__systems__: Dict[str, Type['Dimension']] = {metric: {}, imperial: {}, both: ChainMap()}
|
|
736
|
+
__dimension__: Type['Dimension']
|
|
737
|
+
_system: systemName
|
|
738
|
+
|
|
739
|
+
def __new__(mcs, name, bases, attrs, *args, **kwargs):
|
|
740
|
+
system = kwargs.get('system', None)
|
|
741
|
+
if system is not None:
|
|
742
|
+
attrs['_systemName'] = system
|
|
743
|
+
|
|
744
|
+
if symbol := kwargs.pop('symbol', None):
|
|
745
|
+
attrs['_symbol'] = symbol
|
|
746
|
+
|
|
747
|
+
newCls = super().__new__(mcs, name, bases, attrs, **kwargs)
|
|
748
|
+
|
|
749
|
+
if system is not None:
|
|
750
|
+
newCls._system = newCls
|
|
751
|
+
if dimension := getattr(newCls, 'dimension', None):
|
|
752
|
+
dimension.register(newCls)
|
|
753
|
+
else:
|
|
754
|
+
mcs.registerDimension(newCls)
|
|
755
|
+
|
|
756
|
+
return newCls
|
|
757
|
+
|
|
758
|
+
@classmethod
|
|
759
|
+
def registerDimension(mcs, dimension: 'Dimension') -> None:
|
|
760
|
+
systems = mcs.__systems__
|
|
761
|
+
dimension.__dimension__ = dimension
|
|
762
|
+
if dimension not in systems[both]:
|
|
763
|
+
dimensionDictMetric, dimensionDictImperial = {}, {}
|
|
764
|
+
|
|
765
|
+
dimensionDictBoth = ChainMap(dimensionDictMetric, dimensionDictImperial)
|
|
766
|
+
|
|
767
|
+
systems[metric][dimension] = dimensionDictMetric
|
|
768
|
+
systems[metric][dimension.__name__] = dimensionDictImperial
|
|
769
|
+
|
|
770
|
+
systems[imperial][dimension] = dimensionDictImperial
|
|
771
|
+
systems[imperial][dimension.__name__] = dimensionDictImperial
|
|
772
|
+
|
|
773
|
+
systems[both][dimension] = dimensionDictBoth
|
|
774
|
+
systems[both][dimension.__name__] = dimensionDictBoth
|
|
775
|
+
|
|
776
|
+
@classmethod
|
|
777
|
+
def register(mcs, newCls: 'Dimension') -> None:
|
|
778
|
+
systems = mcs.__systems__
|
|
779
|
+
|
|
780
|
+
dimension = newCls.dimension or newCls
|
|
781
|
+
|
|
782
|
+
unit = newCls.unit
|
|
783
|
+
if unit:
|
|
784
|
+
if newCls.systemName is both:
|
|
785
|
+
systems[imperial][dimension][unit] = newCls
|
|
786
|
+
systems[metric][dimension][unit] = newCls
|
|
787
|
+
else:
|
|
788
|
+
systems[newCls.systemName][dimension][unit] = newCls
|
|
789
|
+
else:
|
|
790
|
+
newCls._unitSystem = newCls
|
|
791
|
+
newCls._systemID = f'{newCls.__dimension__.__name__}[{newCls._systemName.title()}]'
|
|
792
|
+
# newCls.__name__ = newCls.systemName
|
|
793
|
+
|
|
794
|
+
@property
|
|
795
|
+
def isGeneric(cls) -> bool:
|
|
796
|
+
return cls is cls.__dimension__ or (cls is cls._system and bool(cls.__subclasses__()))
|
|
797
|
+
|
|
798
|
+
@property
|
|
799
|
+
def systemName(self) -> metric or imperial:
|
|
800
|
+
return getattr(self, '_systemName', None)
|
|
801
|
+
|
|
802
|
+
@property
|
|
803
|
+
def system(self) -> str:
|
|
804
|
+
return getattr(self, '_system', None)
|
|
805
|
+
|
|
806
|
+
@property
|
|
807
|
+
def systems(self):
|
|
808
|
+
if self.systemName is None:
|
|
809
|
+
return self.__systems__
|
|
810
|
+
return self.__systems__[self.systemName]
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
class DerivedMeasurement(Measurement, metaclass=DerivedMeasurementMeta):
|
|
814
|
+
_derived = True
|
|
815
|
+
_type: Type[Measurement] = Measurement
|
|
816
|
+
_numerator: Union[Measurement, Type[Measurement]] = Measurement
|
|
817
|
+
_denominator: Union[Measurement, Type[Measurement]] = Measurement
|
|
818
|
+
|
|
819
|
+
def __new__(cls, numerator: Measurement, denominator: Measurement = None, *args, **kwargs):
|
|
820
|
+
if denominator is None:
|
|
821
|
+
if (d := getattr(numerator, 'denominator', None)) is not None:
|
|
822
|
+
denominator = d
|
|
823
|
+
numerator = numerator.numerator
|
|
824
|
+
else:
|
|
825
|
+
denominator = 1
|
|
826
|
+
if not isinstance(numerator, Measurement) and cls.numerator.isGeneric:
|
|
827
|
+
raise TypeError(
|
|
828
|
+
f'{cls.__name__} does not say which {cls.numerator.__name__} unit a bare number is in; '
|
|
829
|
+
f'pass a measurement (e.g. {cls.numerator.__name__}.Meter(5)) or use a concrete unit class'
|
|
830
|
+
)
|
|
831
|
+
if not cls.numerator.isGeneric:
|
|
832
|
+
numerator = cls.numerator(numerator)
|
|
833
|
+
if not isinstance(denominator, Measurement) and cls.denominatorClass.isGeneric:
|
|
834
|
+
raise TypeError(
|
|
835
|
+
f'{cls.__name__} does not say which {cls.denominatorClass.__name__} unit a bare number is in; '
|
|
836
|
+
f'pass a measurement or use a concrete unit class'
|
|
837
|
+
)
|
|
838
|
+
if not cls.denominatorClass.isGeneric:
|
|
839
|
+
denominator = cls.denominator(denominator)
|
|
840
|
+
value = float(numerator)/float(denominator)
|
|
841
|
+
|
|
842
|
+
if isinstance(numerator, cls.numeratorClass) and isinstance(denominator, cls.denominatorClass):
|
|
843
|
+
if cls.isGeneric:
|
|
844
|
+
cls = cls[type(numerator):type(denominator)]
|
|
845
|
+
elif items := [i for i in cls.type.subTypes if getattr(i, 'denominator', None) is type(denominator)]:
|
|
846
|
+
if len(items) == 1:
|
|
847
|
+
cls = items[0]
|
|
848
|
+
else:
|
|
849
|
+
items = [i for i in items if i.numerator is type(numerator)]
|
|
850
|
+
if len(items) == 1:
|
|
851
|
+
cls = items[0]
|
|
852
|
+
else:
|
|
853
|
+
raise TypeError(f'{cls.__name__} does not support {numerator.__class__.__name__} as numerator')
|
|
854
|
+
elif cls.isGeneric:
|
|
855
|
+
cls = cls[type(numerator):type(denominator)]
|
|
856
|
+
return Measurement.__new__(cls, value, *args, **kwargs)
|
|
857
|
+
|
|
858
|
+
def __class_getitem__(cls, item):
|
|
859
|
+
# By default, this method respects fixed units
|
|
860
|
+
# To get a class regardless of fixed units, use cls.getClass(item)
|
|
861
|
+
if isinstance(item, str):
|
|
862
|
+
item = cls.__parse_unit__(item)
|
|
863
|
+
if isinstance(item, tuple):
|
|
864
|
+
item = tuple(cls.type.__findUnitClass__(i) if isinstance(i, str) else i for i in item)
|
|
865
|
+
return cls.__getSlice__(HashSlice(item))
|
|
866
|
+
|
|
867
|
+
@classmethod
|
|
868
|
+
def getClass(cls, units):
|
|
869
|
+
if isinstance(units, str):
|
|
870
|
+
units = units,
|
|
871
|
+
clsType = cls.type
|
|
872
|
+
units = tuple(clsType.__findUnitClass__(i) for i in units)
|
|
873
|
+
n = next((i for i in units if cls.numerator.dimension is not None and issubclass(i, cls.numerator.dimension)), None) or cls.numeratorClass
|
|
874
|
+
d = next((i for i in units if cls.denominator.dimension is not None and issubclass(i, cls.denominator.dimension)), None) or cls.denominatorClass
|
|
875
|
+
return cls[n:d:True]
|
|
876
|
+
|
|
877
|
+
@classmethod
|
|
878
|
+
@lru_cache(maxsize=32)
|
|
879
|
+
def __getSlice__(cls, item: HashSlice, ignoreFixed=False):
|
|
880
|
+
if isinstance(getattr(item, 'step', None), bool):
|
|
881
|
+
ignoreFixed = item.step
|
|
882
|
+
fixedN, fixedD = cls.fixedUnits if not ignoreFixed else (None, None)
|
|
883
|
+
if item in cls.__dict__:
|
|
884
|
+
return cls.__dict__[item]
|
|
885
|
+
if isinstance(item, HashSlice):
|
|
886
|
+
sliceNType, sliceDType = fixedN or item.start, fixedD or item.stop
|
|
887
|
+
nType, dType = cls.numerator, cls.denominator
|
|
888
|
+
if isinstance(sliceNType, str):
|
|
889
|
+
sliceNType = nType.__findUnitClass__(sliceNType)
|
|
890
|
+
if isinstance(sliceDType, str):
|
|
891
|
+
sliceDType = dType.__findUnitClass__(sliceDType)
|
|
892
|
+
if sliceNType is not None and not isinstance(sliceNType, type):
|
|
893
|
+
sliceNType = type(sliceNType)
|
|
894
|
+
elif sliceNType is None:
|
|
895
|
+
sliceNType = nType
|
|
896
|
+
|
|
897
|
+
if sliceDType is not None and not isinstance(sliceDType, type):
|
|
898
|
+
sliceDType = type(sliceDType)
|
|
899
|
+
elif sliceDType is None:
|
|
900
|
+
sliceDType = dType
|
|
901
|
+
|
|
902
|
+
genericType = cls if cls.isGeneric else cls.type
|
|
903
|
+
if ignoreFixed and any(i is not None for i in genericType.fixedUnits):
|
|
904
|
+
genericType = cls.Generic
|
|
905
|
+
subTypes = genericType.subTypes
|
|
906
|
+
sameDType = {i for i in subTypes if i.denominator is sliceDType}
|
|
907
|
+
sameNType = {i for i in subTypes if i.numerator is sliceNType}
|
|
908
|
+
|
|
909
|
+
if exactMatch := sameDType & sameNType:
|
|
910
|
+
matchedType = exactMatch.pop()
|
|
911
|
+
if not issubclass(matchedType._type, genericType) and issubclass(cls._type, matchedType._type):
|
|
912
|
+
return type(f'{cls._type.__name__}[{matchedType.unit}]', (matchedType, cls._type), {})
|
|
913
|
+
|
|
914
|
+
if sameDType and (generics := {i for i in sameDType if i.numeratorClass.isGeneric}):
|
|
915
|
+
if len(generics) == 1:
|
|
916
|
+
generic = generics.pop()
|
|
917
|
+
if not dType.isGeneric:
|
|
918
|
+
return generic[sliceNType or nType]
|
|
919
|
+
if generic.denominatorClass is sliceDType:
|
|
920
|
+
return generic[sliceNType or nType]
|
|
921
|
+
if sameNType and (generics := {i for i in sameNType if i.denominatorClass.isGeneric}):
|
|
922
|
+
if len(generics) == 1:
|
|
923
|
+
generic = generics.pop()
|
|
924
|
+
if not nType.isGeneric:
|
|
925
|
+
return generic[sliceDType or dType]
|
|
926
|
+
if generic.numeratorClass is sliceNType:
|
|
927
|
+
return generic[sliceDType or dType]
|
|
928
|
+
|
|
929
|
+
name = f'{genericType.__name__}[{sliceNType.id or sliceNType.__name__}/{sliceDType.id or sliceDType.__name__}]'
|
|
930
|
+
return type(name, (genericType,), {}, numerator=sliceNType, denominator=sliceDType)
|
|
931
|
+
item = item.start
|
|
932
|
+
if issubclass(item, cls.numerator):
|
|
933
|
+
if not cls.denominator.isGeneric:
|
|
934
|
+
name = f'{cls.__name__}'
|
|
935
|
+
newCls = type(name, (cls,), {'_numerator': item})
|
|
936
|
+
return newCls
|
|
937
|
+
print(f'{cls.__name__} does not support {item.__name__} as numerator')
|
|
938
|
+
|
|
939
|
+
elif issubclass(item, cls.denominator):
|
|
940
|
+
if not cls.numeratorClass.isGeneric:
|
|
941
|
+
name = f'{cls.__name__}[{item.__name__}]'
|
|
942
|
+
newCls = type(name, (cls,), {'_denominator': item})
|
|
943
|
+
return newCls
|
|
944
|
+
print(f'{cls.__name__} does not support {item.__name__} as denominator')
|
|
945
|
+
|
|
946
|
+
raise TypeError(f'{cls.__name__} does not support {item.__name__} as unit')
|
|
947
|
+
|
|
948
|
+
def __init__(self, numerator, denominator=None, *args, **kwargs):
|
|
949
|
+
# A derived value is one number in its unit, like every measurement.
|
|
950
|
+
# `numerator` and `denominator` are the implied "value of these units
|
|
951
|
+
# per ONE of those units"; the window an amount was reported over
|
|
952
|
+
# ("6 mm in 3 h") is spent on the rate and is not kept. See `period`
|
|
953
|
+
# for a value that has to remember its window.
|
|
954
|
+
if isinstance(numerator, DerivedMeasurement) and denominator is None:
|
|
955
|
+
n, d = numerator.numerator, numerator.denominator
|
|
956
|
+
elif denominator is None:
|
|
957
|
+
n, d = numerator, None
|
|
958
|
+
else:
|
|
959
|
+
n, d = numerator, denominator
|
|
960
|
+
cls = type(self)
|
|
961
|
+
nCls = cls.numerator if not cls.numerator.isGeneric else type(n)
|
|
962
|
+
dCls = cls.denominator if not cls.denominator.isGeneric else (type(d) if d is not None else cls.denominator)
|
|
963
|
+
if not isinstance(n, nCls):
|
|
964
|
+
n = nCls(n)
|
|
965
|
+
d = dCls(1) if d is None else (d if isinstance(d, dCls) else dCls(d))
|
|
966
|
+
value = float(n)/float(d)
|
|
967
|
+
self._numerator = nCls(value)
|
|
968
|
+
self._denominator = dCls(1)
|
|
969
|
+
Measurement.__init__(self, value, *args, **kwargs)
|
|
970
|
+
|
|
971
|
+
def __pow__(self, power, modulo=None):
|
|
972
|
+
return type(self)(float.__pow__(float(self), float(power)) if modulo is None else pow(float(self), float(power), modulo))
|
|
973
|
+
|
|
974
|
+
def __getitem__(self, item):
|
|
975
|
+
converted = self._getUnit(item)
|
|
976
|
+
if isinstance(converted, Measurement) and converted is not self and converted.period is None:
|
|
977
|
+
converted._period = self.period
|
|
978
|
+
return converted
|
|
979
|
+
|
|
980
|
+
def _getUnit(self, item):
|
|
981
|
+
if isinstance(item, str):
|
|
982
|
+
item = type(self).__parse_unit__(item)
|
|
983
|
+
if len(item) == 2:
|
|
984
|
+
item = HashSlice(*item, True)
|
|
985
|
+
elif len(item) == 1:
|
|
986
|
+
item = item[0]
|
|
987
|
+
cls = self.type.__findUnitClass__(item)
|
|
988
|
+
if issubclass(cls, self.type):
|
|
989
|
+
return cls(self.numerator, self.denominator)
|
|
990
|
+
if issubclass(cls, self.numerator.type):
|
|
991
|
+
cls = type(self)[cls: type(self.denominator): True]
|
|
992
|
+
else:
|
|
993
|
+
cls = type(self)[type(self.numerator): cls: True]
|
|
994
|
+
return cls(self.numerator, self.denominator)
|
|
995
|
+
if hasattr(item, 'denominator'):
|
|
996
|
+
item = HashSlice(item.numerator, item.denominator, True)
|
|
997
|
+
|
|
998
|
+
if isinstance(item, (slice, HashSlice)):
|
|
999
|
+
newCls = self.type[item]
|
|
1000
|
+
if newCls is not type(self):
|
|
1001
|
+
return newCls(self.numerator, self.denominator)
|
|
1002
|
+
numerator = item.start or self._numerator
|
|
1003
|
+
denominator = item.stop or self._denominator
|
|
1004
|
+
|
|
1005
|
+
if isinstance(numerator, str):
|
|
1006
|
+
numeratorCls = self.type.__findUnitClass__(numerator)
|
|
1007
|
+
else:
|
|
1008
|
+
numeratorCls = type(self).numerator
|
|
1009
|
+
|
|
1010
|
+
if isinstance(denominator, str):
|
|
1011
|
+
denomDict = self._denominator.__unitDict__
|
|
1012
|
+
denominatorCls = denomDict.get(denominator, None) or {
|
|
1013
|
+
v.__name__.lower(): v for k, v in denomDict.items()
|
|
1014
|
+
if v.__name__.lower() == denominator.lower()
|
|
1015
|
+
}.get(denominator, None) or type(self).denominator
|
|
1016
|
+
else:
|
|
1017
|
+
denominatorCls = type(self).denominator
|
|
1018
|
+
|
|
1019
|
+
return self.__class__[numeratorCls, denominatorCls, True](self._numerator, self._denominator)
|
|
1020
|
+
return self.__class__(self._numerator[item], self._denominator)
|
|
1021
|
+
|
|
1022
|
+
def transform(self, other, transformTo: type = None):
|
|
1023
|
+
if isinstance(other, type) and issubclass(other, Measurement):
|
|
1024
|
+
other = other(self)
|
|
1025
|
+
nonTransferred = ['_unit', '_suffix', '_scale', '_denominator', '_numerator']
|
|
1026
|
+
if self.type != other.type:
|
|
1027
|
+
log.warning(f'{self.withUnit} and {other.withUnit} are not identical types, this may cause issues')
|
|
1028
|
+
other.__dict__.update({key: value for key, value in self.__dict__.items() if key not in nonTransferred and value is not None})
|
|
1029
|
+
if other._updateFunction:
|
|
1030
|
+
other._updateFunction(other)
|
|
1031
|
+
return other
|
|
1032
|
+
|
|
1033
|
+
def _convert(self, other):
|
|
1034
|
+
if isinstance(other, (int, float)):
|
|
1035
|
+
return self.__class__(self.n.__class__(other), self.d.__class__(1))
|
|
1036
|
+
if isinstance(other, self.n.type):
|
|
1037
|
+
try:
|
|
1038
|
+
other = other[self.n.unit]
|
|
1039
|
+
except AttributeError:
|
|
1040
|
+
pass
|
|
1041
|
+
return self.__class__(other, self.d)
|
|
1042
|
+
else:
|
|
1043
|
+
return super(DerivedMeasurement, self)._convert(other)
|
|
1044
|
+
|
|
1045
|
+
def _getUnitTypes(self):
|
|
1046
|
+
return self._numerator.type, self._denominator.type
|
|
1047
|
+
|
|
1048
|
+
@property
|
|
1049
|
+
def type(self) -> Type[Measurement]:
|
|
1050
|
+
return type(self).type
|
|
1051
|
+
|
|
1052
|
+
@property
|
|
1053
|
+
def localize(self):
|
|
1054
|
+
try:
|
|
1055
|
+
units = type(self).localizedUnit
|
|
1056
|
+
if units is None:
|
|
1057
|
+
# No localization config loaded for this composite type -
|
|
1058
|
+
# same fallback as the non-derived Measurement.localize
|
|
1059
|
+
# above; without this guard, `len(units)` below raises
|
|
1060
|
+
# TypeError (uncaught - only KeyError is handled here),
|
|
1061
|
+
# crashing any caller that reads `.value` on a derived
|
|
1062
|
+
# measurement (e.g. Wind speed) with no localized unit set.
|
|
1063
|
+
return self
|
|
1064
|
+
if len(units) == 1:
|
|
1065
|
+
unit = units[0]
|
|
1066
|
+
if issubclass(unit, self.type):
|
|
1067
|
+
return unit(self.numerator, self.denominator)
|
|
1068
|
+
if issubclass(unit.type, self.n.type):
|
|
1069
|
+
n, d = unit, None
|
|
1070
|
+
elif issubclass(unit.type, self.d.type):
|
|
1071
|
+
n, d = None, unit
|
|
1072
|
+
else:
|
|
1073
|
+
n, d = self.n, self.d
|
|
1074
|
+
else:
|
|
1075
|
+
n, d = units
|
|
1076
|
+
t = self.type[n:d:True]
|
|
1077
|
+
return t(self.n, self.d)
|
|
1078
|
+
except KeyError:
|
|
1079
|
+
log.error('Measurement {} was unable to localize from {}'.format(self.name, self.unit))
|
|
1080
|
+
return self
|
|
1081
|
+
|
|
1082
|
+
@property
|
|
1083
|
+
def unit(self):
|
|
1084
|
+
return getattr(self, '_unit', '') or f'{self.numerator.unit}/{self.denominator.unit}'
|
|
1085
|
+
|
|
1086
|
+
@property
|
|
1087
|
+
def unitArray(self) -> list[str]:
|
|
1088
|
+
return [*self._numerator.unitArray, *self._denominator.unitArray]
|
|
1089
|
+
|
|
1090
|
+
@property
|
|
1091
|
+
def numerator(self) -> Measurement:
|
|
1092
|
+
return self._numerator
|
|
1093
|
+
|
|
1094
|
+
n = numerator
|
|
1095
|
+
|
|
1096
|
+
@property
|
|
1097
|
+
def denominator(self) -> Measurement:
|
|
1098
|
+
return self._denominator
|
|
1099
|
+
|
|
1100
|
+
d = denominator
|
|
1101
|
+
|
|
1102
|
+
@property
|
|
1103
|
+
def dArr(self):
|
|
1104
|
+
arr = []
|
|
1105
|
+
if isinstance(self.n, DerivedMeasurement):
|
|
1106
|
+
arr += [*self.n.dArr]
|
|
1107
|
+
if isinstance(self.d, DerivedMeasurement):
|
|
1108
|
+
arr += [*self.d.dArr]
|
|
1109
|
+
else:
|
|
1110
|
+
arr += [self.d.unit]
|
|
1111
|
+
return arr
|
|
1112
|
+
|
|
1113
|
+
@property
|
|
1114
|
+
def nArr(self):
|
|
1115
|
+
arr = []
|
|
1116
|
+
if isinstance(self.d, DerivedMeasurement):
|
|
1117
|
+
arr += [*self.n.nArr]
|
|
1118
|
+
if isinstance(self.n, DerivedMeasurement):
|
|
1119
|
+
arr += [*self.n.nArr]
|
|
1120
|
+
else:
|
|
1121
|
+
arr += [self.n.unit]
|
|
1122
|
+
return arr
|