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.

Files changed (59) hide show
  1. unitcorn/__init__.py +110 -0
  2. unitcorn/airQuality/__init__.py +99 -0
  3. unitcorn/area/__init__.py +3 -0
  4. unitcorn/area/area.py +103 -0
  5. unitcorn/base/Decorators.py +72 -0
  6. unitcorn/base/Registry.py +75 -0
  7. unitcorn/base/SmartBases.py +26 -0
  8. unitcorn/base/_Algebra.py +205 -0
  9. unitcorn/base/_Measurement.py +1122 -0
  10. unitcorn/base/_ScalingMeasurement.py +398 -0
  11. unitcorn/base/_SmartFloat.py +1635 -0
  12. unitcorn/base/__init__.py +6 -0
  13. unitcorn/config/__init__.py +318 -0
  14. unitcorn/config/__main__.py +8 -0
  15. unitcorn/config/si.toml +53 -0
  16. unitcorn/config/template.toml +146 -0
  17. unitcorn/config/us.toml +53 -0
  18. unitcorn/defaults/WeatherFlow/__init__.py +176 -0
  19. unitcorn/defaults/__init__.py +1 -0
  20. unitcorn/derived/__init__.py +16 -0
  21. unitcorn/derived/density.py +26 -0
  22. unitcorn/derived/partsPer.py +96 -0
  23. unitcorn/derived/precipitation.py +96 -0
  24. unitcorn/derived/rate.py +80 -0
  25. unitcorn/derived/volume.py +122 -0
  26. unitcorn/derived/wind.py +54 -0
  27. unitcorn/digital/__init__.py +21 -0
  28. unitcorn/energy/__init__.py +4 -0
  29. unitcorn/energy/energy.py +120 -0
  30. unitcorn/energy/power.py +83 -0
  31. unitcorn/errors/Conversion.py +12 -0
  32. unitcorn/errors/Unit.py +4 -0
  33. unitcorn/errors/__init__.py +7 -0
  34. unitcorn/length/__init__.py +19 -0
  35. unitcorn/length/imperial.py +46 -0
  36. unitcorn/length/length.py +74 -0
  37. unitcorn/length/metric.py +56 -0
  38. unitcorn/mass/__init__.py +15 -0
  39. unitcorn/mass/imperial.py +47 -0
  40. unitcorn/mass/mass.py +57 -0
  41. unitcorn/mass/metric.py +47 -0
  42. unitcorn/others/__init__.py +338 -0
  43. unitcorn/others/light.py +51 -0
  44. unitcorn/pressure/__init__.py +3 -0
  45. unitcorn/pressure/pressure.py +189 -0
  46. unitcorn/py.typed +0 -0
  47. unitcorn/temperature/__init__.py +19 -0
  48. unitcorn/temperature/celsius.py +23 -0
  49. unitcorn/temperature/change.py +156 -0
  50. unitcorn/temperature/fahrenheit.py +24 -0
  51. unitcorn/temperature/kelvin.py +25 -0
  52. unitcorn/temperature/temperature.py +154 -0
  53. unitcorn/time_/__init__.py +1 -0
  54. unitcorn/time_/time.py +387 -0
  55. unitcorn/utils.py +399 -0
  56. unitcorn-0.9.0.dist-info/METADATA +536 -0
  57. unitcorn-0.9.0.dist-info/RECORD +59 -0
  58. unitcorn-0.9.0.dist-info/WHEEL +4 -0
  59. unitcorn-0.9.0.dist-info/licenses/LICENSE.txt +17 -0
@@ -0,0 +1,398 @@
1
+ from abc import abstractmethod
2
+ from enum import Enum, EnumMeta
3
+ from functools import lru_cache, cached_property
4
+ from itertools import groupby
5
+ from math import nan, prod
6
+ from typing import Optional, Type, Tuple, Set, Dict, Union
7
+
8
+ from ._Measurement import systemName
9
+ from .. import errors
10
+ from . import Measurement, DerivedMeasurement, MetaUnitClass
11
+ from ..utils import Self, classproperty
12
+
13
+ __all__ = ['ScalingMeasurement', 'SystemVariant', 'Scale']
14
+
15
+
16
+ @lru_cache(maxsize=None)
17
+ def _scaleFactor(fromScale: 'Scale', toScale: 'Scale') -> float:
18
+ """Cached multiplicative factor to convert a value from ``fromScale`` to ``toScale``.
19
+
20
+ Scale relationships are fixed at class-registration time, so the factor is stable and
21
+ safe to cache. This replaces the per-call ``Scale`` enum arithmetic that previously ran
22
+ on every element of the conversion hot path.
23
+ """
24
+ return fromScale / toScale
25
+
26
+
27
+ class AddressableEnum(EnumMeta):
28
+ _list: list['Scale']
29
+
30
+ def __new__(cls, *args, **kwargs):
31
+ instance = super().__new__(cls, *args, **kwargs)
32
+ instance._list = [i for i in instance if not i.isVariant]
33
+ instance._sorted = sorted(instance, key=lambda x: x.absoluteValue)
34
+ for i, scale in enumerate(instance._sorted):
35
+ scale._index_ = i
36
+ return instance
37
+
38
+ def __getitem__(self, indexOrName):
39
+ if isinstance(indexOrName, str):
40
+ return super().__getitem__(indexOrName)
41
+ elif isinstance(indexOrName, int) and indexOrName < super().__len__():
42
+ return self._list[indexOrName]
43
+ elif isinstance(indexOrName, slice):
44
+ indices = range(*indexOrName.indices(len(self._list)))
45
+ return [self._list[i] for i in indices]
46
+
47
+
48
+
49
+ class Indexer:
50
+ # Todo: this could probably be moved inside or declared as a class variable of Scale
51
+
52
+ i = 0
53
+ lastClass: object = None
54
+
55
+ @classmethod
56
+ def get(cls, caller):
57
+ cls.i, cls.lastClass = (0, caller) if not caller == cls.lastClass else (cls.i + 1, caller)
58
+ return cls.i
59
+
60
+
61
+ class Scale(Enum, metaclass=AddressableEnum):
62
+ _index_: int
63
+
64
+ Base: 'Scale'
65
+
66
+ def __new__(cls, *args):
67
+ if isinstance(args[0], int):
68
+ obj = object.__new__(cls)
69
+ obj._value_ = Indexer.get(cls)
70
+ obj._mul_ = args[0]
71
+ obj.isVariant = False
72
+ elif isinstance(args[0], float):
73
+ obj = object.__new__(cls)
74
+ obj._value_ = Indexer.get(cls)
75
+ obj._mul_ = args[0]
76
+ obj.isVariant = True
77
+ elif isinstance(args[0], str):
78
+ obj = object.__new__(cls)
79
+ obj._value_ = getattr(cls, args[0]).index
80
+ obj._mul_ = getattr(cls, args[0]).value
81
+ obj.isVariant = False
82
+ else:
83
+ obj = None
84
+
85
+ return obj
86
+
87
+ def __repr__(self):
88
+ index = self.sortedIndex
89
+ value = self.value
90
+ absoluteValue = self.absoluteValue
91
+ return f"{self.__class__.__name__}({index=:g}, {value=:g}, {absoluteValue=:g})"
92
+
93
+ # this makes sure that the description is read-only
94
+ @property
95
+ def index(self):
96
+ if self.isVariant:
97
+ return self.Base.index + 1
98
+ return self._value_
99
+
100
+ @property
101
+ def sortedIndex(self) -> int:
102
+ return self._index_
103
+
104
+ @property
105
+ def value(self):
106
+ return self._mul_
107
+
108
+ @property
109
+ def absoluteValue(self) -> int | float:
110
+ if not self.isVariant:
111
+ return prod(i._mul_ for i in self._list if i.index <= self.index)
112
+ return self._mul_
113
+
114
+ def __truediv__(self, other):
115
+ if isinstance(other, self.__class__):
116
+ return self.absoluteValue / other.absoluteValue
117
+ return self.absoluteValue / other
118
+
119
+ def __mul__(self, other):
120
+ if isinstance(other, self.__class__):
121
+ return other.absoluteValue * self.absoluteValue
122
+ return self.absoluteValue * other
123
+
124
+ def __rmul__(self, other):
125
+ return self.__mul__(other)
126
+
127
+ def __rtruediv__(self, other):
128
+ if isinstance(other, self.__class__):
129
+ return other.absoluteValue / self.absoluteValue
130
+ else:
131
+ return other / self.absoluteValue
132
+
133
+ def __gt__(self, other):
134
+ if isinstance(other, self.__class__):
135
+ return self.index > other.index
136
+ else:
137
+ return self.index > int(other)
138
+
139
+ def __lt__(self, other):
140
+ if isinstance(other, self.__class__):
141
+ return self.index < other.index
142
+ else:
143
+ return self.index < int(other)
144
+
145
+ def __eq__(self, other):
146
+ if isinstance(other, self.__class__):
147
+ return self.index == other.index
148
+ elif isinstance(other, Scale):
149
+ # A member of another unit family's scale. `lru_cache` keys on the
150
+ # scale members and Enum hashes by member name, so `Base` of one
151
+ # family meets `Base` of another in a bucket; that is not an error.
152
+ return False
153
+ else:
154
+ if (scale := getattr(other, 'scale', None)) is not None and (index := getattr(scale, 'index', None)) is not None:
155
+ return self.index == index
156
+ return self.index == int(other)
157
+
158
+ def __le__(self, other):
159
+ if isinstance(other, self.__class__):
160
+ return self.index <= other.index
161
+ else:
162
+ return self.index <= int(other)
163
+
164
+ def __ge__(self, other):
165
+ if isinstance(other, self.__class__):
166
+ return self.index >= other.index
167
+ else:
168
+ return self.index >= int(other)
169
+
170
+ def __hash__(self):
171
+ return hash((self.index, self.value))
172
+
173
+ @property
174
+ def up(self) -> 'Scale':
175
+ try:
176
+ return self._sorted[self.sortedIndex + 1]
177
+ except IndexError:
178
+ return self
179
+
180
+ @property
181
+ def down(self) -> 'Scale':
182
+ try:
183
+ return self._sorted[self.sortedIndex - 1]
184
+ except IndexError:
185
+ return self
186
+
187
+
188
+ class BaseUnit:
189
+
190
+ @abstractmethod
191
+ def changeSystem(self, system):
192
+ pass
193
+
194
+
195
+ class ScalingMeasurement(Measurement):
196
+ _baseUnit: Type['ScalingMeasurement']
197
+ _Scale: Scale | None = None
198
+ _systemName: systemName
199
+ _system: Type['ScalingMeasurement']
200
+
201
+ common: Set[Type[_Scale]] = set()
202
+
203
+ def __init_subclass__(cls, **kwargs):
204
+ baseUnit = kwargs.get('baseUnit', None)
205
+ if baseUnit:
206
+ cls._baseUnitRef = baseUnit
207
+ cls._system = cls
208
+ cls._systemName = kwargs.get('system', 'mixed')
209
+ else:
210
+ baseUnitRef = getattr(cls, '_baseUnitRef', None)
211
+ if baseUnitRef == cls.__name__:
212
+ cls._system._baseUnit = cls
213
+ if cls.name in cls.common:
214
+ cls.common.discard(cls.name)
215
+ cls.common.add(cls.scale)
216
+ elif cls in cls.common:
217
+ cls.common.discard(cls)
218
+ cls.common.add(cls.scale)
219
+ super().__init_subclass__(**kwargs)
220
+
221
+ def __new__(cls, value, *args, **kwargs):
222
+ if isinstance(value, DerivedMeasurement):
223
+ return value
224
+ if value is None:
225
+ value = nan
226
+ valueCls = type(value)
227
+
228
+ if not issubclass(valueCls, Measurement) and issubclass(valueCls, (float, int)):
229
+ value = float(value)
230
+ return super().__new__(cls, value, *args, **kwargs)
231
+
232
+ if isinstance(value, ScalingMeasurement) and (not cls._baseUnit or not value.__class__._baseUnit):
233
+ '''For this to work each unit class must have a _baseUnit defined for each scale'''
234
+ raise errors.Unit.NoBaseUnitDefined(cls)
235
+
236
+ sameDimension = cls.dimension is valueCls.dimension
237
+ sameSystem = cls.system is valueCls.system
238
+ sameUnit = cls.unit is valueCls.unit
239
+
240
+ if sameUnit and issubclass(valueCls, cls.type):
241
+ return Measurement.__new__(cls, float(value), *args, **kwargs)
242
+
243
+ if sameSystem and sameDimension:
244
+ if isinstance(value, ScalingMeasurement) and not isinstance(value, value._baseUnit):
245
+ value = value.changeScale(value._Scale.Base)
246
+ if cls is cls._baseUnit:
247
+ return Measurement.__new__(cls, float(value), *args, **kwargs)
248
+ else:
249
+ value = cls._baseUnit.changeScale(value, cls._Scale[cls.__name__], cls._Scale.Base)
250
+ return cls(value)
251
+
252
+ # If values are cousins initiate with values base sibling causing a recursive call to __new__
253
+ elif sameDimension:
254
+ if not isinstance(value, value._baseUnit):
255
+ value = value.toBaseUnit()
256
+ if (converter := getattr(value, f'_{cls._baseUnitRef.lower()}', None)) is not None:
257
+ value = cls._baseUnit(converter())
258
+ return cls(value)
259
+
260
+ raise errors.Conversion.BadConversion(cls.__name__, value.__class__.__name__)
261
+
262
+ @property
263
+ def up(self: Self) -> Self:
264
+ value = self.changeScale(self.nextScale)
265
+ return getattr(self.type, self.nextScale.name)(value)
266
+
267
+ @property
268
+ def down(self: Self) -> Self:
269
+ value = self.changeScale(self.previousScale)
270
+ return getattr(self.type, self.previousScale.name)(value)
271
+
272
+ @property
273
+ def downCommon(self: Self) -> Self:
274
+ down = self.down
275
+ while down.scale not in (self.common or self._Scale) and down.scale is not self.scale:
276
+ down_down = down.down
277
+ if down_down.scale is down.scale:
278
+ return down
279
+ down = down_down
280
+ return down
281
+
282
+ @property
283
+ def upCommon(self: Self) -> Self:
284
+ up = self.up
285
+ while up.scale not in (self.common or self._Scale) and up.scale is not self.scale:
286
+ up_up = up.up
287
+ if up_up.scale is up.scale:
288
+ return up
289
+ up = up_up
290
+ return up
291
+
292
+ @property
293
+ def nextScale(self) -> Scale:
294
+ return self.scale.up
295
+
296
+ @property
297
+ def previousScale(self) -> Scale:
298
+ return self.scale.down
299
+
300
+ @property
301
+ def remainder(self: Self) -> Self:
302
+ return sum(i for i in self.splitIntoDict() if i.scale < self.scale)
303
+
304
+ @property
305
+ def remainderInt(self) -> int:
306
+ return int(self.remainder)
307
+
308
+ @property
309
+ def only(self: Self) -> Self:
310
+ return self.splitIntoDict().get(self.name, None) or type(self)(0)
311
+
312
+ @property
313
+ def onlyInt(self) -> int:
314
+ return int(self.only)
315
+
316
+ def splitInto(self: Self, *into: Type[Self]) -> Tuple[Self, ...]:
317
+ into = into or type(self).common or self.type.subTypes
318
+ into = sorted(into, key=lambda x: x(self).int)
319
+ if self.down == type(self)(0):
320
+ return self,
321
+ top = into.pop(0)(self).typedInt
322
+ values = [top]
323
+ while into:
324
+ nextVal = into.pop(0)(self)
325
+ if into:
326
+ nextVal = nextVal.typedInt
327
+ nextVal = nextVal - top
328
+ top = nextVal + top
329
+ if abs(nextVal) < type(nextVal)(1):
330
+ values[-1] += nextVal
331
+ else:
332
+ if values[-1] == 0:
333
+ values[-1] = nextVal
334
+ else:
335
+ values.append(nextVal)
336
+ return tuple(values)
337
+
338
+ def splitIntoDict(self: Self, *into: Type[Self]) -> Dict[str, Self]:
339
+ values = self.splitInto(*into)
340
+ return {type(i).name: i for i in values}
341
+
342
+ def changeScale(self, newUnit: Scale, scale: Scale = None) -> Optional[float]:
343
+ scale = getattr(self, 'scale', scale)
344
+ return float(self) * _scaleFactor(scale, newUnit)
345
+
346
+ @staticmethod
347
+ def getConversionFactor(
348
+ fromUnit: Union[Type['ScalingMeasurement'], 'ScalingMeasurement'],
349
+ toUnit: Union[Type['ScalingMeasurement'], 'ScalingMeasurement'],
350
+ ) -> float:
351
+ return _scaleFactor(fromUnit.scale, toUnit.scale)
352
+
353
+ def toBaseUnit(self) -> Measurement:
354
+ return self._baseUnit(self.changeScale(self._Scale.Base))
355
+
356
+ @classproperty
357
+ def scale(cls) -> Scale:
358
+ return cls._Scale[cls.__name__]
359
+
360
+ @classproperty
361
+ def Scale(cls) -> Type[Scale]:
362
+ return cls._Scale
363
+
364
+ @property
365
+ def isSystemVariant(self):
366
+ return issubclass(self.__class__, SystemVariant)
367
+
368
+ @property
369
+ def auto(self: Self) -> Self:
370
+ # "Automagic" display: localize to the user's preferred unit for this
371
+ # dimension, then fit within that system's scale for the digit
372
+ # budget. The original implementation (pre-2026) referenced a `.one`
373
+ # property that was never defined anywhere in the library's history -
374
+ # broken since the commit that introduced it, masked because every
375
+ # call site wraps `.auto` in getattr(..., None)/hasattr, which
376
+ # swallows an AttributeError raised from inside a property getter
377
+ # indistinguishably from the attribute not existing at all.
378
+ return self.localize.bestFit()
379
+
380
+ def bestFit(self, max_digits: int = None) -> Self:
381
+ """Returns the best fit unit for the value"""
382
+ if max_digits is None:
383
+ max_digits = self.digit_budget
384
+
385
+ int_digits_count = self.intLength
386
+ value = self
387
+
388
+ while int_digits_count > max_digits:
389
+ old, value = value, value.upCommon
390
+ if type(old) is type(value):
391
+ return value
392
+ if (int_digits_count := value.intLength) <= max_digits:
393
+ return value
394
+ return value
395
+
396
+
397
+ class SystemVariant:
398
+ _multiplier: float = 1.0