ucon 0.3.3rc2__py3-none-any.whl → 0.3.5__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.
@@ -0,0 +1,370 @@
1
+ # © 2025 The Radiativity Company
2
+ # Licensed under the Apache License, Version 2.0
3
+ # See the LICENSE file for details.
4
+
5
+ import unittest
6
+
7
+ from ucon import units
8
+ from ucon.core import UnitProduct, UnitFactor, Dimension, Scale, Unit
9
+ from ucon.quantity import Number, Ratio
10
+
11
+
12
+ class TestNumber(unittest.TestCase):
13
+
14
+ number = Number(unit=units.gram, quantity=1)
15
+
16
+ def test_as_ratio(self):
17
+ ratio = self.number.as_ratio()
18
+ self.assertIsInstance(ratio, Ratio)
19
+ self.assertEqual(ratio.numerator, self.number)
20
+ self.assertEqual(ratio.denominator, Number())
21
+
22
+ @unittest.skip("Requires ConversionGraph implementation")
23
+ def test_simplify(self):
24
+ decagram = UnitFactor(dimension=Dimension.mass, name='gram', scale=Scale.deca)
25
+ kibigram = UnitFactor(dimension=Dimension.mass, name='gram', scale=Scale.kibi)
26
+
27
+ ten_decagrams = Number(unit=decagram, quantity=10)
28
+ point_one_decagrams = Number(unit=decagram, quantity=0.1)
29
+ two_kibigrams = Number(unit=kibigram, quantity=2)
30
+
31
+ self.assertEqual(Number(unit=units.gram, quantity=100), ten_decagrams.simplify())
32
+ self.assertEqual(Number(unit=units.gram, quantity=1), point_one_decagrams.simplify())
33
+ self.assertEqual(Number(unit=units.gram, quantity=2048), two_kibigrams.simplify())
34
+
35
+ @unittest.skip("Requires ConversionGraph implementation")
36
+ def test_to(self):
37
+ kg = UnitFactor(dimension=Dimension.mass, name='gram', scale=Scale.kilo)
38
+ mg = UnitFactor(dimension=Dimension.mass, name='gram', scale=Scale.milli)
39
+ kibigram = UnitFactor(dimension=Dimension.mass, name='gram', scale=Scale.kibi)
40
+
41
+ thousandth_of_a_kilogram = Number(unit=kg, quantity=0.001)
42
+ thousand_milligrams = Number(unit=mg, quantity=1000)
43
+ kibigram_fraction = Number(unit=kibigram, quantity=0.0009765625)
44
+
45
+ self.assertEqual(thousandth_of_a_kilogram, self.number.to(Scale.kilo))
46
+ self.assertEqual(thousand_milligrams, self.number.to(Scale.milli))
47
+ self.assertEqual(kibigram_fraction, self.number.to(Scale.kibi))
48
+
49
+ @unittest.skip("TODO: revamp: Unit.scale is deprecated.")
50
+ def test___repr__(self):
51
+ self.assertIn(str(self.number.quantity), str(self.number))
52
+ self.assertIn(str(self.number.unit.scale.value.evaluated), str(self.number))
53
+ self.assertIn(self.number.unit.shorthand, str(self.number))
54
+
55
+ def test___truediv__(self):
56
+ dal = Scale.deca * units.gram
57
+ mg = Scale.milli * units.gram
58
+ kibigram = Scale.kibi * units.gram
59
+
60
+ some_number = Number(unit=dal, quantity=10)
61
+ another_number = Number(unit=mg, quantity=10)
62
+ that_number = Number(unit=kibigram, quantity=10)
63
+
64
+ some_quotient = self.number / some_number
65
+ another_quotient = self.number / another_number
66
+ that_quotient = self.number / that_number
67
+
68
+ self.assertEqual(some_quotient.value, 0.01)
69
+ self.assertEqual(another_quotient.value, 100.0)
70
+ self.assertEqual(that_quotient.value, 0.00009765625)
71
+
72
+ def test___eq__(self):
73
+ self.assertEqual(self.number, Ratio(self.number)) # 1 gram / 1
74
+ with self.assertRaises(TypeError):
75
+ self.number == 1
76
+
77
+
78
+ class TestNumberEdgeCases(unittest.TestCase):
79
+
80
+ def test_density_times_volume_preserves_user_scale(self):
81
+ mL = Scale.milli * units.liter
82
+ density = Ratio(Number(unit=units.gram, quantity=3.119),
83
+ Number(unit=mL, quantity=1))
84
+ two_mL = Number(unit=mL, quantity=2)
85
+
86
+ result = density.evaluate() * two_mL
87
+ self.assertIsInstance(result.unit, UnitProduct)
88
+ self.assertDictEqual(result.unit.factors, {units.gram: 1})
89
+ self.assertAlmostEqual(result.quantity, 6.238, places=12)
90
+
91
+ mg = Scale.milli * units.gram
92
+ mg_factor = UnitFactor(unit=units.gram, scale=Scale.milli)
93
+ mg_density = Ratio(Number(unit=mg, quantity=3119), Number(unit=mL, quantity=1))
94
+
95
+ mg_result = mg_density.evaluate() * two_mL
96
+ self.assertIsInstance(mg_result.unit, UnitProduct)
97
+ self.assertDictEqual(mg_result.unit.factors, {mg_factor: 1})
98
+ self.assertAlmostEqual(mg_result.quantity, 6238, places=12)
99
+
100
+ def test_number_mul_asymmetric_density_volume(self):
101
+ g = units.gram
102
+ mL = Scale.milli * units.liter
103
+
104
+ density = Number(unit=g, quantity=3.119) / Number(unit=mL, quantity=1)
105
+ two_mL = Number(unit=mL, quantity=2)
106
+
107
+ result = density * two_mL
108
+
109
+ assert result.unit == g
110
+ assert abs(result.quantity - 6.238) < 1e-12
111
+
112
+ def test_number_mul_retains_scale_when_scaling_lengths(self):
113
+ km = Scale.kilo * units.meter
114
+ m = units.meter
115
+
116
+ n1 = Number(unit=km, quantity=2) # 2 km
117
+ n2 = Number(unit=m, quantity=500) # 500 m
118
+
119
+ result = n1 * n2
120
+
121
+ assert result.unit.dimension == Dimension.area
122
+ # scale stays on unit expression, not folded into numeric
123
+ assert "km" in result.unit.shorthand or "m" in result.unit.shorthand
124
+
125
+ def test_number_mul_mixed_scales_do_not_auto_cancel(self):
126
+ km = Scale.kilo * units.meter
127
+ m = units.meter
128
+
129
+ result = Number(unit=km, quantity=1) * Number(unit=m, quantity=1)
130
+
131
+ # Should remain composite rather than collapsing to base m^2
132
+ assert isinstance(result.unit, UnitProduct)
133
+ assert "km" in result.unit.shorthand
134
+ assert "m" in result.unit.shorthand
135
+
136
+ def test_number_div_uses_canonical_rhs_value(self):
137
+ dal = Scale.deca * units.gram # 10 g
138
+ n = Number(unit=units.gram, quantity=1)
139
+
140
+ quotient = n / Number(unit=dal, quantity=10)
141
+
142
+ # 1 g / (10 × 10 g) = 0.01
143
+ assert abs(quotient.value - 0.01) < 1e-12
144
+
145
+ def test_ratio_times_number_preserves_user_scale(self):
146
+ mL = Scale.milli * units.liter
147
+ density = Ratio(Number(unit=units.gram, quantity=3.119),
148
+ Number(unit=mL, quantity=1))
149
+ two_mL = Number(unit=mL, quantity=2)
150
+
151
+ result = density * two_mL.as_ratio()
152
+ evaluated = result.evaluate()
153
+
154
+ assert evaluated.unit == units.gram
155
+ assert abs(evaluated.quantity - 6.238) < 1e-12
156
+
157
+ @unittest.skip("TODO: revamp: Unit.scale is deprecated.")
158
+ def test_default_number_is_dimensionless_one(self):
159
+ n = Number()
160
+ self.assertEqual(n.unit, units.none)
161
+ self.assertEqual(n.unit.scale, Scale.one)
162
+ self.assertEqual(n.quantity, 1)
163
+ self.assertAlmostEqual(n.value, 1.0)
164
+ self.assertIn("1", repr(n))
165
+
166
+ @unittest.skip("Requires ConversionGraph implementation")
167
+ def test_to_new_scale_changes_value(self):
168
+ thousand = UnitFactor(dimension=Dimension.none, name='', scale=Scale.kilo)
169
+ n = Number(quantity=1000, unit=thousand)
170
+ converted = n.to(Scale.one)
171
+ self.assertNotEqual(n.value, converted.value)
172
+ self.assertAlmostEqual(converted.value, 1000)
173
+
174
+ @unittest.skip("TODO: revamp: Unit.scale is deprecated.")
175
+ @unittest.skip("Requires ConversionGraph implementation")
176
+ def test_simplify_uses_value_as_quantity(self):
177
+ thousand = UnitFactor(dimension=Dimension.none, name='', scale=Scale.kilo)
178
+ n = Number(quantity=2, unit=thousand)
179
+ simplified = n.simplify()
180
+ self.assertEqual(simplified.quantity, n.value)
181
+ self.assertNotEqual(simplified.unit.scale, n.unit.scale)
182
+ self.assertEqual(simplified.value, n.value)
183
+
184
+ def test_multiplication_combines_units_and_quantities(self):
185
+ n1 = Number(unit=units.joule, quantity=2)
186
+ n2 = Number(unit=units.second, quantity=3)
187
+ result = n1 * n2
188
+ self.assertEqual(result.quantity, 6)
189
+ self.assertEqual(result.unit.dimension, Dimension.energy * Dimension.time)
190
+
191
+ @unittest.skip("TODO: revamp: Unit.scale is deprecated.")
192
+ @unittest.skip("Requires ConversionGraph implementation")
193
+ def test_division_combines_units_scales_and_quantities(self):
194
+ km = UnitFactor('m', name='meter', dimension=Dimension.length, scale=Scale.kilo)
195
+ n1 = Number(unit=km, quantity=1000)
196
+ n2 = Number(unit=units.second, quantity=2)
197
+
198
+ result = n1 / n2 # should yield <500 km/s>
199
+
200
+ cu = result.unit
201
+ self.assertIsInstance(cu, UnitProduct)
202
+
203
+ # --- quantity check ---
204
+ self.assertAlmostEqual(result.quantity, 500)
205
+
206
+ # --- dimension check ---
207
+ self.assertEqual(cu.dimension, Dimension.velocity)
208
+
209
+ # --- scale check: km/s should have a kilo-scaled meter in the numerator ---
210
+ # find the meter-like unit in the components
211
+ meter_like = next(u for u, exp in cu.components.items() if u.dimension == Dimension.length)
212
+ self.assertEqual(meter_like.scale, Scale.kilo)
213
+ self.assertEqual(cu.components[meter_like], 1) # exponent = 1 in numerator
214
+
215
+ # --- symbolic shorthand ---
216
+ self.assertEqual(cu.shorthand, "km/s")
217
+
218
+ # --- optional canonicalization ---
219
+ canonical = result.to(Scale.one)
220
+ self.assertAlmostEqual(canonical.quantity, 500000)
221
+ self.assertEqual(canonical.unit.shorthand, "m/s")
222
+
223
+ def test_equality_with_non_number_raises_value_error(self):
224
+ n = Number()
225
+ with self.assertRaises(TypeError):
226
+ n == '5'
227
+
228
+ def test_equality_between_numbers_and_ratios(self):
229
+ n1 = Number(quantity=10)
230
+ n2 = Number(quantity=10)
231
+ r = Ratio(n1, n2)
232
+ self.assertTrue(r == Number())
233
+
234
+ def test_repr_includes_scale_and_unit(self):
235
+ kV = Scale.kilo * Unit('V', name='volt', dimension=Dimension.voltage)
236
+ n = Number(unit=kV, quantity=5)
237
+ rep = repr(n)
238
+ self.assertIn("kV", rep)
239
+
240
+
241
+ class TestRatio(unittest.TestCase):
242
+
243
+ point_five = Number(quantity=0.5)
244
+ one = Number()
245
+ two = Number(quantity=2)
246
+ three = Number(quantity=3)
247
+ four = Number(quantity=4)
248
+
249
+ one_half = Ratio(numerator=one, denominator=two)
250
+ three_fourths = Ratio(numerator=three, denominator=four)
251
+ one_ratio = Ratio(numerator=one)
252
+ three_halves = Ratio(numerator=three, denominator=two)
253
+ two_ratio = Ratio(numerator=two, denominator=one)
254
+
255
+ def test_evaluate(self):
256
+ self.assertEqual(self.one_ratio.numerator, self.one)
257
+ self.assertEqual(self.one_ratio.denominator, self.one)
258
+ self.assertEqual(self.one_ratio.evaluate(), self.one)
259
+ self.assertEqual(self.two_ratio.evaluate(), self.two)
260
+
261
+ def test_reciprocal(self):
262
+ self.assertEqual(self.two_ratio.reciprocal().numerator, self.one)
263
+ self.assertEqual(self.two_ratio.reciprocal().denominator, self.two)
264
+ self.assertEqual(self.two_ratio.reciprocal().evaluate(), self.point_five)
265
+
266
+ def test___mul__commutivity(self):
267
+ # Does commutivity hold?
268
+ self.assertEqual(self.three_halves * self.one_half, self.three_fourths)
269
+ self.assertEqual(self.one_half * self.three_halves, self.three_fourths)
270
+
271
+ def test___mul__(self):
272
+ mL = Scale.milli * Unit('L', name='liter', dimension=Dimension.volume)
273
+ n1 = Number(unit=units.gram, quantity=3.119)
274
+ n2 = Number(unit=mL)
275
+ bromine_density = Ratio(n1, n2)
276
+
277
+ # How many grams of bromine are in 2 milliliters?
278
+ two_milliliters_bromine = Number(unit=mL, quantity=2)
279
+ ratio = two_milliliters_bromine.as_ratio() * bromine_density
280
+ answer = ratio.evaluate()
281
+ self.assertEqual(answer.unit.dimension, Dimension.mass)
282
+ self.assertEqual(answer.value, 6.238) # Grams
283
+
284
+ def test___truediv__(self):
285
+ seconds_per_hour = Ratio(
286
+ numerator=Number(unit=units.second, quantity=3600),
287
+ denominator=Number(unit=units.hour, quantity=1)
288
+ )
289
+
290
+ # How many Wh from 20 kJ?
291
+ twenty_kilojoules = Number(
292
+ unit=Scale.kilo * Unit('J', name='joule', dimension=Dimension.energy),
293
+ quantity=20
294
+ )
295
+ ratio = twenty_kilojoules.as_ratio() / seconds_per_hour
296
+ answer = ratio.evaluate()
297
+ self.assertEqual(answer.unit.dimension, Dimension.energy)
298
+ # When the ConversionGraph is implemented, conversion to watt-hours will be possible.
299
+ self.assertEqual(round(answer.value, 5), 0.00556) # kilowatt * hours
300
+
301
+ def test___eq__(self):
302
+ self.assertEqual(self.one_half, self.point_five)
303
+ with self.assertRaises(ValueError):
304
+ self.one_half == 1/2
305
+
306
+ def test___repr__(self):
307
+ self.assertEqual(str(self.one_ratio), '<1.0>')
308
+ self.assertEqual(str(self.two_ratio), '<2> / <1.0>')
309
+ self.assertEqual(str(self.two_ratio.evaluate()), '<2.0>')
310
+
311
+
312
+ class TestRatioEdgeCases(unittest.TestCase):
313
+
314
+ def test_default_ratio_is_dimensionless_one(self):
315
+ r = Ratio()
316
+ self.assertEqual(r.numerator.unit, units.none)
317
+ self.assertEqual(r.denominator.unit, units.none)
318
+ self.assertAlmostEqual(r.evaluate().value, 1.0)
319
+
320
+ def test_reciprocal_swaps_numerator_and_denominator(self):
321
+ n1 = Number(quantity=10)
322
+ n2 = Number(quantity=2)
323
+ r = Ratio(n1, n2)
324
+ reciprocal = r.reciprocal()
325
+ self.assertEqual(reciprocal.numerator, r.denominator)
326
+ self.assertEqual(reciprocal.denominator, r.numerator)
327
+
328
+ def test_evaluate_returns_number_division_result(self):
329
+ r = Ratio(Number(unit=units.meter), Number(unit=units.second))
330
+ result = r.evaluate()
331
+ self.assertIsInstance(result, Number)
332
+ self.assertEqual(result.unit.dimension, Dimension.velocity)
333
+
334
+ def test_multiplication_between_compatible_ratios(self):
335
+ r1 = Ratio(Number(unit=units.meter), Number(unit=units.second))
336
+ r2 = Ratio(Number(unit=units.second), Number(unit=units.meter))
337
+ product = r1 * r2
338
+ self.assertIsInstance(product, Ratio)
339
+ self.assertEqual(product.evaluate().unit.dimension, Dimension.none)
340
+
341
+ def test_multiplication_with_incompatible_units_fallback(self):
342
+ r1 = Ratio(Number(unit=units.meter), Number(unit=units.ampere))
343
+ r2 = Ratio(Number(unit=units.ampere), Number(unit=units.meter))
344
+ result = r1 * r2
345
+ self.assertIsInstance(result, Ratio)
346
+
347
+ def test_division_between_ratios_yields_new_ratio(self):
348
+ r1 = Ratio(Number(quantity=2), Number(quantity=1))
349
+ r2 = Ratio(Number(quantity=4), Number(quantity=2))
350
+ result = r1 / r2
351
+ self.assertIsInstance(result, Ratio)
352
+ self.assertAlmostEqual(result.evaluate().value, 1.0)
353
+
354
+ def test_equality_with_non_ratio_raises_value_error(self):
355
+ r = Ratio()
356
+ with self.assertRaises(ValueError):
357
+ _ = (r == "not_a_ratio")
358
+
359
+ def test_repr_handles_equal_numerator_denominator(self):
360
+ r = Ratio()
361
+ self.assertEqual(str(r.evaluate().value), "1.0")
362
+ rep = repr(r)
363
+ self.assertTrue(rep.startswith("<1"))
364
+
365
+ def test_repr_of_non_equal_ratio_includes_slash(self):
366
+ n1 = Number(quantity=2)
367
+ n2 = Number(quantity=1)
368
+ r = Ratio(n1, n2)
369
+ rep = repr(r)
370
+ self.assertIn("/", rep)
tests/ucon/test_units.py CHANGED
@@ -1,10 +1,12 @@
1
1
 
2
+ # © 2025 The Radiativity Company
3
+ # Licensed under the Apache License, Version 2.0
4
+ # See the LICENSE file for details.
2
5
 
3
6
  from unittest import TestCase
4
7
 
5
8
  from ucon import units
6
- from ucon.dimension import Dimension
7
- from ucon.unit import Unit
9
+ from ucon.core import Dimension
8
10
 
9
11
 
10
12
  class TestUnits(TestCase):
@@ -18,4 +20,6 @@ class TestUnits(TestCase):
18
20
  self.assertEqual(units.none, units.gram / units.gram)
19
21
  self.assertEqual(units.gram, units.gram / units.none)
20
22
 
21
- self.assertEqual(Unit(name='(g/L)', dimension=Dimension.density), units.gram / units.liter)
23
+ composite_unit = units.gram / units.liter
24
+ self.assertEqual("g/L", composite_unit.shorthand)
25
+ self.assertEqual(Dimension.density, composite_unit.dimension)
ucon/__init__.py CHANGED
@@ -1,3 +1,7 @@
1
+ # © 2025 The Radiativity Company
2
+ # Licensed under the Apache License, Version 2.0
3
+ # See the LICENSE file for details.
4
+
1
5
  """
2
6
  ucon
3
7
  ====
@@ -33,9 +37,9 @@ Design Philosophy
33
37
  data-driven framework that is generalizable to arbitrary unit systems.
34
38
  """
35
39
  from ucon import units
36
- from ucon.unit import Unit
37
- from ucon.core import Exponent, Number, Scale, Ratio
38
- from ucon.dimension import Dimension
40
+ from ucon.algebra import Exponent
41
+ from ucon.core import Dimension, Scale, Unit, UnitFactor, UnitProduct
42
+ from ucon.quantity import Number, Ratio
39
43
 
40
44
 
41
45
  __all__ = [
@@ -45,5 +49,7 @@ __all__ = [
45
49
  'Ratio',
46
50
  'Scale',
47
51
  'Unit',
52
+ 'UnitFactor',
53
+ 'UnitProduct',
48
54
  'units',
49
55
  ]
ucon/algebra.py ADDED
@@ -0,0 +1,216 @@
1
+ # © 2025 The Radiativity Company
2
+ # Licensed under the Apache License, Version 2.0
3
+ # See the LICENSE file for details.
4
+
5
+ """
6
+ ucon.algebra
7
+ ============
8
+
9
+ Provides the low-level algebraic primitives that power the rest of the *ucon*
10
+ stack. These building blocks model exponent vectors for physical dimensions and
11
+ numeric base-exponent pairs for scale prefixes, enabling higher-level modules to
12
+ compose dimensions, units, and quantities without reimplementing arithmetic.
13
+
14
+ Other modules depend on these structures to ensure dimensional calculations,
15
+ prefix handling, and unit simplification all share the same semantics.
16
+
17
+ Classes
18
+ -------
19
+ - :class:`Vector` — Exponent tuple representing a physical dimension basis.
20
+ - :class:`Exponent` — Base/power pair supporting prefix arithmetic.
21
+ """
22
+ import math
23
+ from dataclasses import dataclass
24
+ from functools import partial, reduce, total_ordering
25
+ from operator import __sub__ as subtraction
26
+ from typing import Callable, Iterable, Iterator, Tuple, Union
27
+
28
+
29
+ diff: Callable[[Iterable], int] = partial(reduce, subtraction)
30
+
31
+
32
+ @dataclass
33
+ class Vector:
34
+ """
35
+ Represents the **exponent vector** of a physical quantity.
36
+
37
+ Each component corresponds to the power of a base dimension in the SI system:
38
+ time (T), length (L), mass (M), current (I), temperature (Θ),
39
+ luminous intensity (J), and amount of substance (N).
40
+
41
+ Arithmetic operations correspond to dimensional composition:
42
+ - Addition (`+`) → multiplication of quantities
43
+ - Subtraction (`-`) → division of quantities
44
+
45
+ e.g.
46
+ Vector(T=1, L=0, M=0, I=0, Θ=0, J=0, N=0) => "time"
47
+ Vector(T=0, L=2, M=0, I=0, Θ=0, J=0, N=0) => "area"
48
+ Vector(T=-2, L=1, M=1, I=0, Θ=0, J=0, N=0) => "force"
49
+ """
50
+ T: int = 0 # time
51
+ L: int = 0 # length
52
+ M: int = 0 # mass
53
+ I: int = 0 # current
54
+ Θ: int = 0 # temperature
55
+ J: int = 0 # luminous intensity
56
+ N: int = 0 # amount of substance
57
+
58
+ def __iter__(self) -> Iterator[int]:
59
+ yield self.T
60
+ yield self.L
61
+ yield self.M
62
+ yield self.I
63
+ yield self.Θ
64
+ yield self.J
65
+ yield self.N
66
+
67
+ def __len__(self) -> int:
68
+ return sum(tuple(1 for x in self))
69
+
70
+ def __add__(self, vector: 'Vector') -> 'Vector':
71
+ """
72
+ Addition, here, comes from the multiplication of base quantities
73
+
74
+ e.g. F = m * a
75
+ F =
76
+ (s^-2 * m^1 * kg * A * K * cd * mol) +
77
+ (s * m * kg^1 * A * K * cd * mol)
78
+ """
79
+ values = tuple(sum(pair) for pair in zip(tuple(self), tuple(vector)))
80
+ return Vector(*values)
81
+
82
+ def __sub__(self, vector: 'Vector') -> 'Vector':
83
+ """
84
+ Subtraction, here, comes from the division of base quantities
85
+ """
86
+ values = tuple(diff(pair) for pair in zip(tuple(self), tuple(vector)))
87
+ return Vector(*values)
88
+
89
+ def __mul__(self, scalar: Union[int, float]) -> 'Vector':
90
+ """
91
+ Scalar multiplication of the exponent vector.
92
+
93
+ e.g., raising a dimension to a power:
94
+
95
+ >>> Dimension.length ** 2 # area
96
+ >>> Dimension.time ** -1 # frequency
97
+ """
98
+ values = tuple(component * scalar for component in tuple(self))
99
+ return Vector(*values)
100
+
101
+ def __eq__(self, vector: 'Vector') -> bool:
102
+ assert isinstance(vector, Vector), "Can only compare Vector to another Vector"
103
+ return tuple(self) == tuple(vector)
104
+
105
+ def __hash__(self) -> int:
106
+ # Hash based on the string because tuples have been shown to collide
107
+ # Not the most performant, but effective
108
+ return hash(str(tuple(self)))
109
+
110
+
111
+ # TODO -- consider using a dataclass
112
+ @total_ordering
113
+ class Exponent:
114
+ """
115
+ Represents a **base–exponent pair** (e.g., 10³ or 2¹⁰).
116
+
117
+ Provides comparison and division semantics used internally to represent
118
+ magnitude prefixes (e.g., kilo, mega, micro).
119
+
120
+ TODO (wittwemms): embrace fractional exponents for closure on multiplication/division.
121
+ """
122
+ bases = {2: math.log2, 10: math.log10}
123
+
124
+ __slots__ = ("base", "power")
125
+
126
+ def __init__(self, base: int, power: Union[int, float]):
127
+ if base not in self.bases.keys():
128
+ raise ValueError(f'Only the following bases are supported: {reduce(lambda a,b: f"{a}, {b}", self.bases.keys())}')
129
+ self.base = base
130
+ self.power = power
131
+
132
+ @property
133
+ def evaluated(self) -> float:
134
+ """Return the numeric value of base ** power."""
135
+ return self.base ** self.power
136
+
137
+ def parts(self) -> Tuple[int, Union[int, float]]:
138
+ """Return (base, power) tuple, used for Scale lookups."""
139
+ return self.base, self.power
140
+
141
+ def __eq__(self, other: 'Exponent'):
142
+ if not isinstance(other, Exponent):
143
+ raise TypeError(f'Cannot compare Exponent to non-Exponent type: {type(other)}')
144
+ return self.evaluated == other.evaluated
145
+
146
+ def __lt__(self, other: 'Exponent'):
147
+ if not isinstance(other, Exponent):
148
+ return NotImplemented
149
+ return self.evaluated < other.evaluated
150
+
151
+ def __hash__(self):
152
+ # Hash by rounded numeric equivalence to maintain cross-base consistency
153
+ return hash(round(self.evaluated, 15))
154
+
155
+ # ---------- Arithmetic Semantics ----------
156
+
157
+ def __truediv__(self, other: 'Exponent'):
158
+ """
159
+ Divide two Exponents.
160
+ - If bases match, returns a relative Exponent.
161
+ - If bases differ, returns a numeric ratio (float).
162
+ """
163
+ if not isinstance(other, Exponent):
164
+ return NotImplemented
165
+ if self.base == other.base:
166
+ return Exponent(self.base, self.power - other.power)
167
+ return self.evaluated / other.evaluated
168
+
169
+ def __mul__(self, other: 'Exponent'):
170
+ if not isinstance(other, Exponent):
171
+ return NotImplemented
172
+ if self.base == other.base:
173
+ return Exponent(self.base, self.power + other.power)
174
+ return float(self.evaluated * other.evaluated)
175
+
176
+ def __pow__(self, exponent: Union[int, float]) -> "Exponent":
177
+ """
178
+ Raise this Exponent to a numeric power.
179
+
180
+ Example:
181
+ Exponent(10, 3) ** 2
182
+ # → Exponent(base=10, power=6)
183
+ """
184
+ return Exponent(self.base, self.power * exponent)
185
+
186
+ # ---------- Conversion Utilities ----------
187
+
188
+ def to_base(self, new_base: int) -> "Exponent":
189
+ """
190
+ Convert this Exponent to another base representation.
191
+
192
+ Example:
193
+ Exponent(2, 10).to_base(10)
194
+ # → Exponent(base=10, power=3.010299956639812)
195
+ """
196
+ if new_base not in self.bases:
197
+ supported = ", ".join(map(str, self.bases))
198
+ raise ValueError(f"Unsupported base {new_base!r}. Supported bases: {supported}")
199
+ new_power = self.bases[new_base](self.evaluated)
200
+ return Exponent(new_base, new_power)
201
+
202
+ # ---------- Numeric Interop ----------
203
+
204
+ def __float__(self) -> float:
205
+ return float(self.evaluated)
206
+
207
+ def __int__(self) -> int:
208
+ return int(self.evaluated)
209
+
210
+ # ---------- Representation ----------
211
+
212
+ def __repr__(self) -> str:
213
+ return f"Exponent(base={self.base}, power={self.power})"
214
+
215
+ def __str__(self) -> str:
216
+ return f"{self.base}^{self.power}"