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
unitcorn/__init__.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from typing import Type, overload, Tuple
|
|
2
|
+
|
|
3
|
+
from .config import config
|
|
4
|
+
|
|
5
|
+
from . import base
|
|
6
|
+
|
|
7
|
+
SmartFloat = base.SmartFloat
|
|
8
|
+
Measurement = base.Measurement
|
|
9
|
+
ScalingMeasurement = base.ScalingMeasurement
|
|
10
|
+
Dimension = base.Dimension
|
|
11
|
+
Dimensionless = base.Dimensionless
|
|
12
|
+
NonPlural = base.NonPlural
|
|
13
|
+
DerivedMeasurement = base.DerivedMeasurement
|
|
14
|
+
Index = base.Index
|
|
15
|
+
Quantity = base.Quantity
|
|
16
|
+
SystemVariant = base.SystemVariant
|
|
17
|
+
FiniteField = base.FiniteField
|
|
18
|
+
|
|
19
|
+
from .others import (Light, Angle, Percentage, Voltage,
|
|
20
|
+
LightningStrike, Humidity, Direction,
|
|
21
|
+
Coverage, Probability)
|
|
22
|
+
from .temperature import Temperature
|
|
23
|
+
from .length import Length
|
|
24
|
+
from .mass import Mass
|
|
25
|
+
from .time_ import Time
|
|
26
|
+
from .pressure import Pressure
|
|
27
|
+
from .area import Area
|
|
28
|
+
from .energy import Energy, Power
|
|
29
|
+
from . import airQuality as AirQuality
|
|
30
|
+
from . import digital as Digital
|
|
31
|
+
from . import derived
|
|
32
|
+
|
|
33
|
+
Rate = derived.DistanceOverTime
|
|
34
|
+
Wind = derived.Wind
|
|
35
|
+
Precipitation = derived.Precipitation
|
|
36
|
+
Other = others
|
|
37
|
+
Light = others.Light
|
|
38
|
+
PartsPer = derived.PartsPer
|
|
39
|
+
Volume = derived.Volume
|
|
40
|
+
Density = derived.Density
|
|
41
|
+
PartsPer = derived.PartsPer
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@overload
|
|
45
|
+
def auto(value: int | float | int, unit: str) -> Measurement: ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@overload
|
|
49
|
+
def auto(value: str) -> Measurement: ...
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@overload
|
|
53
|
+
def auto(unit: str) -> Type[Measurement] | Tuple[Type[Measurement], ...]: ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def auto(*args, dimension: Type[Dimension | Dimensionless] = None) -> Measurement | Type[Measurement] | Tuple[Type[Measurement], ...]:
|
|
57
|
+
dimension = dimension or Measurement
|
|
58
|
+
match args:
|
|
59
|
+
case [int(value) | float(value) | str(value), str(unit)]:
|
|
60
|
+
measurement = float(value)
|
|
61
|
+
cls = dimension.__findUnitClass__(unit)
|
|
62
|
+
if cls is None:
|
|
63
|
+
raise ValueError(f'Unknown unit: {unit!r}')
|
|
64
|
+
return cls(measurement)
|
|
65
|
+
|
|
66
|
+
case [str(value)]:
|
|
67
|
+
number = base.FormatSpec.number.search(value)
|
|
68
|
+
if number is not None:
|
|
69
|
+
number = number.groupdict()['number']
|
|
70
|
+
|
|
71
|
+
unit = DerivedMeasurement.__parse_unit__(value.replace(number, ''))
|
|
72
|
+
cls = tuple(dimension.__findUnitClass__(u) for u in unit)
|
|
73
|
+
|
|
74
|
+
if len(cls) == 1:
|
|
75
|
+
if number != '':
|
|
76
|
+
return cls[0](float(number))
|
|
77
|
+
return cls[0]
|
|
78
|
+
raise NotImplementedError('Multi-Unit values are not supported yet')
|
|
79
|
+
|
|
80
|
+
case [str(unit)]:
|
|
81
|
+
unit = DerivedMeasurement.__parse_unit__(unit)
|
|
82
|
+
cls = tuple(dimension.__findUnitClass__(u) for u in unit)
|
|
83
|
+
return cls
|
|
84
|
+
case _:
|
|
85
|
+
raise ValueError
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
__all__ = ['auto', 'Measurement', 'Temperature', 'Length', 'Mass', 'Time', 'Pressure', 'Area', 'Energy', 'Power', 'Other', 'Light', 'PartsPer',
|
|
89
|
+
'Volume', 'Density', 'PartsPer', 'Rate', 'Wind', 'Precipitation', 'AirQuality', 'Voltage', 'Digital', 'config',
|
|
90
|
+
'Precipitation', 'LightningStrike', 'Angle', 'Percentage', 'Humidity', 'Direction', 'Coverage', 'Probability']
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _registerDimensions():
|
|
94
|
+
from .base import _Algebra
|
|
95
|
+
reg = _Algebra.register
|
|
96
|
+
reg(Length, (1, 0, 0, 0), Length.Meter)
|
|
97
|
+
reg(Mass, (0, 1, 0, 0), Mass.Kilogram)
|
|
98
|
+
reg(Time, (0, 0, 1, 0), Time.Second)
|
|
99
|
+
reg(Temperature, (0, 0, 0, 1), Temperature.Kelvin)
|
|
100
|
+
reg(Pressure, (-1, 1, -2, 0), Pressure.Pascal)
|
|
101
|
+
reg(Temperature.Change, (0, 0, 0, 1))
|
|
102
|
+
reg(Area, (2, 0, 0, 0), Area.SquareMeter)
|
|
103
|
+
reg(Energy, (2, 1, -2, 0), Energy.Joule)
|
|
104
|
+
reg(Power, (2, 1, -3, 0), Power.Watt)
|
|
105
|
+
# Irradiance is power per area: kg·s⁻³. Only Irradiance, not Light, which also holds lux and the UV index.
|
|
106
|
+
reg(Light.Irradiance, (0, 1, -3, 0), Light.Irradiance)
|
|
107
|
+
_Algebra._references[(1, 0, -1, 0)] = derived.DistanceOverTime.MetersPerSecond
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
_registerDimensions()
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
|
|
3
|
+
__all__ = ['PrimaryPollutant', 'HeathConcern', 'AQI', 'PollutionIndex']
|
|
4
|
+
|
|
5
|
+
from ..base import Measurement
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DescriptiveEnum(Enum):
|
|
9
|
+
|
|
10
|
+
def __new__(cls, *args, **kwargs):
|
|
11
|
+
obj = object.__new__(cls)
|
|
12
|
+
obj._value_ = args[0]
|
|
13
|
+
return obj
|
|
14
|
+
|
|
15
|
+
def __init__(self, _: str, text: str = None):
|
|
16
|
+
self._text_ = text
|
|
17
|
+
|
|
18
|
+
def __str__(self):
|
|
19
|
+
return self.text
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def text(self):
|
|
23
|
+
return self._text_
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PrimaryPollutant(DescriptiveEnum):
|
|
27
|
+
PM2_5 = 0, 'PM2.5'
|
|
28
|
+
PM10 = 1, 'PM10'
|
|
29
|
+
O3 = 2, 'O₃'
|
|
30
|
+
NO2 = 3, 'NO₂'
|
|
31
|
+
CO = 4, 'CO'
|
|
32
|
+
SO2 = 5, 'SO₂'
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PollutionIndex(DescriptiveEnum):
|
|
36
|
+
none = 0, 'None'
|
|
37
|
+
VeryLow = 1, 'Very Low'
|
|
38
|
+
Low = 2, 'Low'
|
|
39
|
+
Medium = 3, 'Medium'
|
|
40
|
+
High = 4, 'High'
|
|
41
|
+
VeryHigh = 5, 'Very High'
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class EmojiEnum(Enum):
|
|
45
|
+
|
|
46
|
+
def __new__(cls, *args, **kwargs):
|
|
47
|
+
obj = object.__new__(cls)
|
|
48
|
+
obj._value_ = args[0]
|
|
49
|
+
return obj
|
|
50
|
+
|
|
51
|
+
def __init__(self, _: str, text: str = None, emoji: str = None):
|
|
52
|
+
self._text_ = text
|
|
53
|
+
self._emoji_ = emoji
|
|
54
|
+
|
|
55
|
+
def __str__(self):
|
|
56
|
+
return self.text
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def emoji(self):
|
|
60
|
+
return self._emoji_
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def text(self):
|
|
64
|
+
return self._text_
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class HeathConcern(EmojiEnum):
|
|
68
|
+
Good = 0, 'Good', '☺️'
|
|
69
|
+
Moderate = 1, 'Moderate', '😀'
|
|
70
|
+
UnhealthyForSensitiveGroups = 2, 'Unhealthy For Sensitive Groups', '😯'
|
|
71
|
+
Unhealthy = 3, 'Unhealthy', '🙁'
|
|
72
|
+
VeryUnhealthy = 4, 'Very Unhealthy', '☹️'
|
|
73
|
+
Hazardous = 5, 'Hazardous', '😷'
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class AQI(Measurement):
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def text(self) -> str:
|
|
80
|
+
return self.enum.text
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def emoji(self) -> str:
|
|
84
|
+
return self.enum.emoji
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def enum(self) -> HeathConcern:
|
|
88
|
+
if self >= 50:
|
|
89
|
+
return HeathConcern.Good
|
|
90
|
+
elif self >= 100:
|
|
91
|
+
return HeathConcern.Moderate
|
|
92
|
+
elif self >= 150:
|
|
93
|
+
return HeathConcern.UnhealthyForSensitiveGroups
|
|
94
|
+
elif self >= 200:
|
|
95
|
+
return HeathConcern.Unhealthy
|
|
96
|
+
elif self >= 300:
|
|
97
|
+
return HeathConcern.VeryUnhealthy
|
|
98
|
+
else:
|
|
99
|
+
return HeathConcern.Hazardous
|
unitcorn/area/area.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from ..base.Decorators import UnitType, Tiny, Small, Medium, Large, Huge
|
|
2
|
+
from ..base import both, Scale, ScalingMeasurement
|
|
3
|
+
|
|
4
|
+
__all__ = ['Area']
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@UnitType
|
|
8
|
+
class Area(ScalingMeasurement, baseUnit='SquareMeter', system=both):
|
|
9
|
+
SquareMeter: type
|
|
10
|
+
SquareCentimeter: type
|
|
11
|
+
SquareKilometer: type
|
|
12
|
+
Hectare: type
|
|
13
|
+
SquareInch: type
|
|
14
|
+
SquareFoot: type
|
|
15
|
+
SquareMile: type
|
|
16
|
+
Acre: type
|
|
17
|
+
|
|
18
|
+
class _Scale(Scale):
|
|
19
|
+
SquareMeter = 1
|
|
20
|
+
Base = 'SquareMeter'
|
|
21
|
+
# Variants are given as their size in square metres.
|
|
22
|
+
SquareCentimeter = 1e-4
|
|
23
|
+
SquareKilometer = 1e6
|
|
24
|
+
Hectare = 1e4
|
|
25
|
+
SquareInch = 0.00064516
|
|
26
|
+
SquareFoot = 0.09290304
|
|
27
|
+
SquareMile = 2589988.110336
|
|
28
|
+
Acre = 4046.8564224
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def squareMeter(self):
|
|
32
|
+
return SquareMeter(self)
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def squareCentimeter(self):
|
|
36
|
+
return SquareCentimeter(self)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def squareKilometer(self):
|
|
40
|
+
return SquareKilometer(self)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def hectare(self):
|
|
44
|
+
return Hectare(self)
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def squareInch(self):
|
|
48
|
+
return SquareInch(self)
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def squareFoot(self):
|
|
52
|
+
return SquareFoot(self)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def squareMile(self):
|
|
56
|
+
return SquareMile(self)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def acre(self):
|
|
60
|
+
return Acre(self)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@Medium
|
|
64
|
+
class SquareMeter(Area):
|
|
65
|
+
_unit = 'm²'
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class SquareCentimeter(Area):
|
|
69
|
+
_unit = 'cm²'
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SquareKilometer(Area):
|
|
73
|
+
_unit = 'km²'
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Hectare(Area):
|
|
77
|
+
_unit = 'ha'
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class SquareInch(Area):
|
|
81
|
+
_unit = 'in²'
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class SquareFoot(Area):
|
|
85
|
+
_unit = 'ft²'
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class SquareMile(Area):
|
|
89
|
+
_unit = 'mi²'
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Acre(Area):
|
|
93
|
+
_unit = 'ac'
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
Area.SquareMeter = SquareMeter
|
|
97
|
+
Area.SquareCentimeter = SquareCentimeter
|
|
98
|
+
Area.SquareKilometer = SquareKilometer
|
|
99
|
+
Area.Hectare = Hectare
|
|
100
|
+
Area.SquareInch = SquareInch
|
|
101
|
+
Area.SquareFoot = SquareFoot
|
|
102
|
+
Area.SquareMile = SquareMile
|
|
103
|
+
Area.Acre = Acre
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
__all__ = ['UnitType', 'Synonym', 'Tiny', 'Small', 'Medium', 'Large', 'Huge']
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
from .Registry import UnitRegistry
|
|
7
|
+
|
|
8
|
+
def UnitType(*args, **kwargs):
|
|
9
|
+
if args:
|
|
10
|
+
cls = args[0]
|
|
11
|
+
cls._type = cls
|
|
12
|
+
UnitRegistry.register_derived(cls)
|
|
13
|
+
return cls
|
|
14
|
+
else:
|
|
15
|
+
def wrapper(cls):
|
|
16
|
+
cls._type = cls
|
|
17
|
+
UnitRegistry.register_derived(cls)
|
|
18
|
+
return cls
|
|
19
|
+
|
|
20
|
+
return wrapper
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def strToDict(string: str, cls: type) -> type:
|
|
24
|
+
|
|
25
|
+
def parseString(item: str):
|
|
26
|
+
key, value = item.split('=')
|
|
27
|
+
# expectedTypes = {'max': int, 'precision': int, 'unit_spacer': stringToBool, 'shorten': stringToBool, 'thousandsSeparator': stringToBool, 'cardinal': stringToBool, 'degrees': stringToBool}
|
|
28
|
+
if value.isnumeric():
|
|
29
|
+
value = float(value)
|
|
30
|
+
if value.is_integer():
|
|
31
|
+
value = int(value)
|
|
32
|
+
if value == 'True':
|
|
33
|
+
value = True
|
|
34
|
+
elif value == 'False':
|
|
35
|
+
value = False
|
|
36
|
+
return f'_{key}', value
|
|
37
|
+
|
|
38
|
+
conf = [parseString(a) for a in [(y.strip(' ')) for y in string.split(',')]]
|
|
39
|
+
for item in conf:
|
|
40
|
+
setattr(cls, *item)
|
|
41
|
+
|
|
42
|
+
return cls
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def Tiny(cls):
|
|
46
|
+
cls._size = 'tiny'
|
|
47
|
+
return cls
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def Small(cls):
|
|
51
|
+
cls._size = 'small'
|
|
52
|
+
return cls
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def Medium(cls):
|
|
56
|
+
cls._size = 'medium'
|
|
57
|
+
return cls
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def Large(cls):
|
|
61
|
+
cls._size = 'large'
|
|
62
|
+
return cls
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def Huge(cls):
|
|
66
|
+
cls._size = 'huge'
|
|
67
|
+
return cls
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def Synonym(cls):
|
|
71
|
+
cls.__name__ = cls.__mro__[1].__name__
|
|
72
|
+
return cls
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from typing import Dict, Type, TYPE_CHECKING, Optional, Set, Union, Tuple, List
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
if TYPE_CHECKING:
|
|
5
|
+
from ._Measurement import Measurement
|
|
6
|
+
|
|
7
|
+
log = logging.getLogger('unitcorn').getChild('Registry')
|
|
8
|
+
|
|
9
|
+
class UnitRegistry:
|
|
10
|
+
_units_by_symbol: Dict[str, Type['Measurement']] = {}
|
|
11
|
+
_units_by_name: Dict[str, Type['Measurement']] = {}
|
|
12
|
+
_units_by_alias: Dict[str, Type['Measurement']] = {}
|
|
13
|
+
_all_units: Set[Type['Measurement']] = set()
|
|
14
|
+
_derived_units: Dict[Tuple[Type['Measurement'], Type['Measurement']], List[Type['Measurement']]] = {}
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def register(cls, unit_class: Type['Measurement']):
|
|
18
|
+
cls._all_units.add(unit_class)
|
|
19
|
+
|
|
20
|
+
# Register by name
|
|
21
|
+
name = getattr(unit_class, '_name', unit_class.__name__).lower()
|
|
22
|
+
cls._units_by_name[name] = unit_class
|
|
23
|
+
|
|
24
|
+
# Register by unit symbol
|
|
25
|
+
if hasattr(unit_class, '_unit') and unit_class._unit:
|
|
26
|
+
cls._units_by_symbol[unit_class._unit.lower()] = unit_class
|
|
27
|
+
|
|
28
|
+
# Register by plural unit
|
|
29
|
+
if hasattr(unit_class, '_pluralUnit') and unit_class._pluralUnit:
|
|
30
|
+
cls._units_by_symbol[unit_class._pluralUnit.lower()] = unit_class
|
|
31
|
+
|
|
32
|
+
# Register by aliases
|
|
33
|
+
if hasattr(unit_class, '_aliases') and unit_class._aliases:
|
|
34
|
+
for alias in unit_class._aliases:
|
|
35
|
+
cls._units_by_alias[alias.lower()] = unit_class
|
|
36
|
+
|
|
37
|
+
# Register derived units by (numerator_dim, denominator_dim)
|
|
38
|
+
if getattr(unit_class, 'isDerived', False):
|
|
39
|
+
cls.register_derived(unit_class)
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def register_derived(cls, derived_class: Type['Measurement']):
|
|
43
|
+
if not (hasattr(derived_class, 'numerator') and hasattr(derived_class, 'denominator')):
|
|
44
|
+
return
|
|
45
|
+
num = derived_class.numerator
|
|
46
|
+
den = derived_class.denominator
|
|
47
|
+
if num and den and not (num.isGeneric or den.isGeneric):
|
|
48
|
+
key = (num.type, den.type)
|
|
49
|
+
if key not in cls._derived_units:
|
|
50
|
+
cls._derived_units[key] = []
|
|
51
|
+
if derived_class not in cls._derived_units[key]:
|
|
52
|
+
cls._derived_units[key].append(derived_class)
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def get_derived(cls, numerator: Type['Measurement'], denominator: Type['Measurement']) -> Optional[Type['Measurement']]:
|
|
56
|
+
key = (numerator.type, denominator.type)
|
|
57
|
+
matches = cls._derived_units.get(key, [])
|
|
58
|
+
for match in matches:
|
|
59
|
+
if match.numerator == numerator and match.denominator == denominator:
|
|
60
|
+
return match
|
|
61
|
+
|
|
62
|
+
# If no exact match, return a generic one if available
|
|
63
|
+
for match in matches:
|
|
64
|
+
if match.isGeneric:
|
|
65
|
+
return match[numerator:denominator]
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def get(cls, unit_str: str) -> Optional[Type['Measurement']]:
|
|
70
|
+
unit_str = unit_str.lower()
|
|
71
|
+
return (cls._units_by_symbol.get(unit_str) or
|
|
72
|
+
cls._units_by_name.get(unit_str) or
|
|
73
|
+
cls._units_by_alias.get(unit_str))
|
|
74
|
+
|
|
75
|
+
UnitRegistryInstance = UnitRegistry()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
|
|
2
|
+
class SmartString(str):
|
|
3
|
+
_title = ''
|
|
4
|
+
_key = ''
|
|
5
|
+
|
|
6
|
+
def __new__(cls, value: str, title: str = None, key: str = None):
|
|
7
|
+
return str(value)
|
|
8
|
+
|
|
9
|
+
def __init__(self, value: str, title: str = None, key: str = None):
|
|
10
|
+
self._key = key
|
|
11
|
+
self._title = title
|
|
12
|
+
super(SmartString, self).__init__(value)
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def title(self):
|
|
16
|
+
return self._title
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def key(self):
|
|
20
|
+
return self._key
|
|
21
|
+
|
|
22
|
+
def type(self):
|
|
23
|
+
return type(self)
|
|
24
|
+
|
|
25
|
+
def category(self):
|
|
26
|
+
return self.__class__.__name__
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Dimension algebra: `*` and `/` between measurements of different dimensions.
|
|
2
|
+
|
|
3
|
+
Every algebraic dimension carries an exponent vector over the SI base
|
|
4
|
+
dimensions (length, mass, time, temperature), so a product or quotient adds or
|
|
5
|
+
subtracts vectors and multiplies the values *in the SI reference units*. SI is
|
|
6
|
+
coherent, so the result is already the reference unit of the result's
|
|
7
|
+
dimension (m × m = m², kg·m⁻¹·s⁻² = Pa) and no conversion tables are needed.
|
|
8
|
+
|
|
9
|
+
The result is a registered named type when one exists for the vector (speed,
|
|
10
|
+
pressure, length, ...), a dimensionless `float` when the vector is zero, and
|
|
11
|
+
otherwise a `Compound`, which carries its vector and prints its SI unit.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Optional
|
|
16
|
+
|
|
17
|
+
from ._Measurement import Measurement, DerivedMeasurement
|
|
18
|
+
|
|
19
|
+
__all__ = ['Compound', 'register', 'vectorOf', 'siValue', 'multiply', 'divide', 'hasDimension']
|
|
20
|
+
|
|
21
|
+
Vector = tuple[int, int, int, int]
|
|
22
|
+
|
|
23
|
+
BASES = ('m', 'kg', 's', 'K')
|
|
24
|
+
ZERO: Vector = (0, 0, 0, 0)
|
|
25
|
+
MAX_EXPONENT = 3
|
|
26
|
+
|
|
27
|
+
_dimensions: dict[type, Vector] = {}
|
|
28
|
+
_references: dict[Vector, type] = {}
|
|
29
|
+
_SUPERSCRIPT = str.maketrans('-0123456789', '⁻⁰¹²³⁴⁵⁶⁷⁸⁹')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def register(dimension: type, vector: Vector, reference: Optional[type] = None) -> None:
|
|
33
|
+
"""Declare `dimension`'s exponent vector. `reference` is the SI coherent unit
|
|
34
|
+
class, which results with that vector are built as."""
|
|
35
|
+
_dimensions[dimension] = tuple(vector)
|
|
36
|
+
if reference is not None:
|
|
37
|
+
_references[tuple(vector)] = reference
|
|
38
|
+
_references[ZERO] = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def hasDimension(measurement) -> bool:
|
|
42
|
+
try:
|
|
43
|
+
vectorOf(measurement)
|
|
44
|
+
except TypeError:
|
|
45
|
+
return False
|
|
46
|
+
return True
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def vectorOf(m) -> Vector:
|
|
50
|
+
if isinstance(m, Compound):
|
|
51
|
+
return m._vector
|
|
52
|
+
if isinstance(m, DerivedMeasurement):
|
|
53
|
+
n, d = vectorOf(m.numerator), vectorOf(m.denominator)
|
|
54
|
+
return tuple(a - b for a, b in zip(n, d))
|
|
55
|
+
for klass in type(m).__mro__:
|
|
56
|
+
if klass in _dimensions:
|
|
57
|
+
return _dimensions[klass]
|
|
58
|
+
raise TypeError(f'{type(m).__name__} has no dimension to multiply or divide by')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def siValue(m) -> float:
|
|
62
|
+
"""The measurement's magnitude in the coherent SI unit of its dimension."""
|
|
63
|
+
if isinstance(m, Compound):
|
|
64
|
+
return float(m)
|
|
65
|
+
if isinstance(m, DerivedMeasurement):
|
|
66
|
+
return siValue(m.numerator) / siValue(m.denominator)
|
|
67
|
+
vector = vectorOf(m)
|
|
68
|
+
if (factor := getattr(m, '_factor', None)) is not None and vector == (0, 0, 0, 1):
|
|
69
|
+
return float(m) * factor # a change in temperature: kelvin per degree
|
|
70
|
+
reference = _references.get(vector)
|
|
71
|
+
if vector == (0, 0, 0, 1):
|
|
72
|
+
# A temperature *reading* is not a quantity: 20 °C × 2 is not 40 °C.
|
|
73
|
+
from ..temperature import Temperature
|
|
74
|
+
if isinstance(m, Temperature) and type(m).__name__ != 'Kelvin':
|
|
75
|
+
raise TypeError(f'{m.withUnit} is a temperature reading and does not multiply or divide; use Kelvin or a change in temperature')
|
|
76
|
+
return float(reference(m))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _combine(a, b, sign: int):
|
|
80
|
+
va, vb = vectorOf(a), vectorOf(b)
|
|
81
|
+
vector = tuple(x + sign * y for x, y in zip(va, vb))
|
|
82
|
+
if any(abs(e) > MAX_EXPONENT for e in vector):
|
|
83
|
+
raise ValueError(f'{_symbol(vector)} is beyond the supported exponent range of ±{MAX_EXPONENT}')
|
|
84
|
+
x, y = siValue(a), siValue(b)
|
|
85
|
+
value = x * y if sign > 0 else x / y
|
|
86
|
+
return build(value, vector)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def build(value: float, vector: Vector):
|
|
90
|
+
"""A registered named type for `vector` if there is one, else a `Compound`."""
|
|
91
|
+
if vector == ZERO:
|
|
92
|
+
return float(value)
|
|
93
|
+
if (reference := _references.get(vector)) is not None:
|
|
94
|
+
return reference(value)
|
|
95
|
+
return Compound(value, vector)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def multiply(a, b):
|
|
99
|
+
return _combine(a, b, 1)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def divide(a, b):
|
|
103
|
+
return _combine(a, b, -1)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _symbol(vector: Vector) -> str:
|
|
107
|
+
def term(base, e):
|
|
108
|
+
return base if e == 1 else f'{base}{str(e).translate(_SUPERSCRIPT)}'
|
|
109
|
+
pos = [term(b, e) for b, e in zip(BASES, vector) if e > 0]
|
|
110
|
+
neg = [term(b, e) for b, e in zip(BASES, vector) if e < 0]
|
|
111
|
+
if not pos:
|
|
112
|
+
pos = ['1']
|
|
113
|
+
if len(neg) == 1 and len(pos) == 1 and vector[BASES.index(neg[0].rstrip('⁻⁰¹²³⁴⁵⁶⁷⁸⁹'))] == -1:
|
|
114
|
+
return f'{pos[0]}/{neg[0].rstrip("⁻⁰¹²³⁴⁵⁶⁷⁸⁹")}'
|
|
115
|
+
return '·'.join(pos + neg)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Compound(Measurement):
|
|
120
|
+
"""A value in a coherent SI unit with no named type (m², kg·m²·s⁻³).
|
|
121
|
+
|
|
122
|
+
It knows its exponent vector, so it takes part in further `*` and `/`.
|
|
123
|
+
"""
|
|
124
|
+
_vector: Vector = ZERO
|
|
125
|
+
_precision = 3
|
|
126
|
+
|
|
127
|
+
def __new__(cls, value, vector: Vector = None, *args, **kwargs):
|
|
128
|
+
if isinstance(value, Compound) and vector is None:
|
|
129
|
+
vector = value._vector
|
|
130
|
+
return Measurement.__new__(cls, value, *args, **kwargs)
|
|
131
|
+
|
|
132
|
+
def __init__(self, value, vector: Vector = None, *args, **kwargs):
|
|
133
|
+
if isinstance(value, Compound) and vector is None:
|
|
134
|
+
vector = value._vector
|
|
135
|
+
if vector is None:
|
|
136
|
+
raise TypeError('Compound needs an exponent vector')
|
|
137
|
+
self._vector = tuple(vector)
|
|
138
|
+
self._unit = _symbol(self._vector)
|
|
139
|
+
Measurement.__init__(self, float(value), *args, **kwargs)
|
|
140
|
+
|
|
141
|
+
def _same(self, value):
|
|
142
|
+
return Compound(value, self._vector)
|
|
143
|
+
|
|
144
|
+
def __neg__(self):
|
|
145
|
+
return self._same(-float(self))
|
|
146
|
+
|
|
147
|
+
def __pos__(self):
|
|
148
|
+
return self._same(float(self))
|
|
149
|
+
|
|
150
|
+
def __abs__(self):
|
|
151
|
+
return self._same(abs(float(self)))
|
|
152
|
+
|
|
153
|
+
def __add__(self, other):
|
|
154
|
+
return self._same(float(self) + self._operand(other))
|
|
155
|
+
|
|
156
|
+
__radd__ = __add__
|
|
157
|
+
|
|
158
|
+
def __sub__(self, other):
|
|
159
|
+
return self._same(float(self) - self._operand(other))
|
|
160
|
+
|
|
161
|
+
def __rsub__(self, other):
|
|
162
|
+
return self._same(self._operand(other) - float(self))
|
|
163
|
+
|
|
164
|
+
def __mul__(self, other):
|
|
165
|
+
if isinstance(other, Measurement) and hasDimension(other):
|
|
166
|
+
return multiply(self, other)
|
|
167
|
+
return self._same(float(self) * float(other))
|
|
168
|
+
|
|
169
|
+
__rmul__ = __mul__
|
|
170
|
+
|
|
171
|
+
def __truediv__(self, other):
|
|
172
|
+
if isinstance(other, Measurement) and hasDimension(other):
|
|
173
|
+
return divide(self, other)
|
|
174
|
+
return self._same(float(self) / float(other))
|
|
175
|
+
|
|
176
|
+
def __rtruediv__(self, other):
|
|
177
|
+
return build(float(other) / float(self), tuple(-e for e in self._vector))
|
|
178
|
+
|
|
179
|
+
def __pow__(self, power, modulo=None):
|
|
180
|
+
vector = tuple(e * int(power) for e in self._vector)
|
|
181
|
+
if int(power) != power or any(abs(e) > MAX_EXPONENT for e in vector):
|
|
182
|
+
raise ValueError(f'{self.unit} ** {power} is beyond the supported integer powers')
|
|
183
|
+
return build(float(self) ** int(power), vector)
|
|
184
|
+
|
|
185
|
+
def _operand(self, other) -> float:
|
|
186
|
+
if isinstance(other, Compound):
|
|
187
|
+
if other._vector != self._vector:
|
|
188
|
+
from .. import errors
|
|
189
|
+
raise errors.BadConversion(self, other)
|
|
190
|
+
return float(other)
|
|
191
|
+
if isinstance(other, Measurement) and hasDimension(other):
|
|
192
|
+
if vectorOf(other) != self._vector:
|
|
193
|
+
from .. import errors
|
|
194
|
+
raise errors.BadConversion(self, other)
|
|
195
|
+
return siValue(other)
|
|
196
|
+
return float(other)
|
|
197
|
+
|
|
198
|
+
def __eq__(self, other):
|
|
199
|
+
try:
|
|
200
|
+
return abs(float(self) - self._operand(other)) <= 1e-9 * max(1.0, abs(float(self)))
|
|
201
|
+
except Exception:
|
|
202
|
+
return False
|
|
203
|
+
|
|
204
|
+
def __hash__(self):
|
|
205
|
+
return hash((round(float(self), 9), self._vector))
|