Skip to main content

logicaffeine_base/
dimension.rs

1//! Physical dimensions as an abelian group of rational exponent vectors.
2//!
3//! A *dimension* is what a quantity measures — length, mass, time, or a product/quotient of
4//! them (area = L², speed = L·T⁻¹, force = M·L·T⁻²). It is NOT a unit: metres and feet share
5//! the dimension Length. We model a dimension as a vector of rational exponents over the base
6//! dimensions, so dimensional algebra is exact vector arithmetic:
7//!
8//! - `×` adds exponent vectors (`Length × Length = Length²`),
9//! - `÷` subtracts them (`Area ÷ Length = Length`),
10//! - integer powers scale them, and the `n`th root divides them (so `√(Length²) = Length`).
11//!
12//! Exponents are *rational* (not just integer) because real derived quantities need fractional
13//! powers — noise density is `V·Hz^(−1/2)`. The group's identity is the dimensionless vector;
14//! every dimension has an inverse (`recip`). `Dimension` is `Copy + Eq + Hash`, so it is a cheap
15//! catalog key, rides inside the compiler's type lattice, and tags a runtime quantity.
16
17use std::fmt;
18
19/// The base dimensions: the SI seven, plus the extensions Logos tracks end-to-end. Plane angle
20/// and solid angle are SI-dimensionless but tracked here to catch radian/steradian mix-ups;
21/// information (the bit) is tracked so data sizes are first-class. "Dimensionless" is the
22/// all-zero vector, not an axis.
23#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
24#[repr(usize)]
25pub enum BaseDim {
26    Length = 0,
27    Mass,
28    Time,
29    Current,
30    Temperature,
31    Amount,
32    Luminous,
33    Angle,
34    SolidAngle,
35    Information,
36}
37
38impl BaseDim {
39    /// The number of base axes (the length of a [`Dimension`]'s exponent vector).
40    pub const COUNT: usize = 10;
41
42    /// Every base dimension, in canonical order (the order exponents are stored and displayed).
43    pub const ALL: [BaseDim; BaseDim::COUNT] = [
44        BaseDim::Length,
45        BaseDim::Mass,
46        BaseDim::Time,
47        BaseDim::Current,
48        BaseDim::Temperature,
49        BaseDim::Amount,
50        BaseDim::Luminous,
51        BaseDim::Angle,
52        BaseDim::SolidAngle,
53        BaseDim::Information,
54    ];
55
56    /// This axis's index into the exponent vector.
57    #[inline]
58    pub const fn index(self) -> usize {
59        self as usize
60    }
61
62    /// The conventional one-symbol tag used when displaying a dimension signature.
63    pub const fn symbol(self) -> &'static str {
64        match self {
65            BaseDim::Length => "L",
66            BaseDim::Mass => "M",
67            BaseDim::Time => "T",
68            BaseDim::Current => "I",
69            BaseDim::Temperature => "Θ",
70            BaseDim::Amount => "N",
71            BaseDim::Luminous => "J",
72            BaseDim::Angle => "rad",
73            BaseDim::SolidAngle => "sr",
74            BaseDim::Information => "bit",
75        }
76    }
77}
78
79/// `gcd(|a|, |b|)` by the Euclidean algorithm (`gcd(a, 0) == |a|`).
80const fn igcd(mut a: i32, mut b: i32) -> i32 {
81    a = a.abs();
82    b = b.abs();
83    while b != 0 {
84        let t = b;
85        b = a % b;
86        a = t;
87    }
88    a
89}
90
91/// A signed rational exponent in lowest terms with a strictly positive denominator — so equal
92/// exponents share one representation (`Eq`/`Hash` are structural). Admits fractional powers
93/// (`L^(1/2)`) while the common integer case is just `den == 1`.
94#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
95pub struct Exp {
96    num: i32,
97    den: i32,
98}
99
100impl Exp {
101    /// The zero exponent (an axis that does not appear).
102    pub const ZERO: Exp = Exp { num: 0, den: 1 };
103    /// The unit exponent.
104    pub const ONE: Exp = Exp { num: 1, den: 1 };
105
106    /// Reduce `num/den` to lowest terms with a positive denominator. Panics on a zero denominator.
107    pub fn new(num: i32, den: i32) -> Exp {
108        assert!(den != 0, "exponent denominator must be nonzero");
109        let (mut num, mut den) = (num, den);
110        if den < 0 {
111            num = -num;
112            den = -den;
113        }
114        if num == 0 {
115            return Exp::ZERO;
116        }
117        let g = igcd(num, den);
118        Exp {
119            num: num / g,
120            den: den / g,
121        }
122    }
123
124    /// The whole exponent `n` (`n/1`).
125    #[inline]
126    pub const fn int(n: i32) -> Exp {
127        Exp { num: n, den: 1 }
128    }
129
130    pub const fn numerator(self) -> i32 {
131        self.num
132    }
133
134    pub const fn denominator(self) -> i32 {
135        self.den
136    }
137
138    #[inline]
139    pub const fn is_zero(self) -> bool {
140        self.num == 0
141    }
142
143    /// `self + other` (exact rational addition).
144    pub fn add(self, other: Exp) -> Exp {
145        Exp::new(
146            self.num * other.den + other.num * self.den,
147            self.den * other.den,
148        )
149    }
150
151    /// `self − other`.
152    pub fn sub(self, other: Exp) -> Exp {
153        Exp::new(
154            self.num * other.den - other.num * self.den,
155            self.den * other.den,
156        )
157    }
158
159    /// `−self`.
160    pub fn neg(self) -> Exp {
161        Exp {
162            num: -self.num,
163            den: self.den,
164        }
165    }
166
167    /// `self · k` — scaling by an integer (raising a dimension to the `k`th power).
168    pub fn scale(self, k: i32) -> Exp {
169        Exp::new(self.num * k, self.den)
170    }
171
172    /// `self / k` — dividing the exponent by an integer (taking the `k`th root). Panics for `k == 0`.
173    pub fn div_int(self, k: i32) -> Exp {
174        Exp::new(self.num, self.den * k)
175    }
176}
177
178impl fmt::Display for Exp {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        if self.den == 1 {
181            write!(f, "{}", self.num)
182        } else {
183            write!(f, "{}/{}", self.num, self.den)
184        }
185    }
186}
187
188/// A physical dimension: a vector of rational exponents over [`BaseDim`]. The group operation is
189/// `mul` (axiswise exponent addition); the identity is [`Dimension::DIMENSIONLESS`]; the inverse
190/// is [`Dimension::recip`].
191#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
192pub struct Dimension {
193    e: [Exp; BaseDim::COUNT],
194}
195
196impl Dimension {
197    /// The identity dimension — the all-zero exponent vector (a pure number, e.g. a count or ratio).
198    pub const DIMENSIONLESS: Dimension = Dimension {
199        e: [Exp::ZERO; BaseDim::COUNT],
200    };
201
202    /// The dimension of a single base axis raised to the first power (e.g. `base(Length)` = L).
203    pub fn base(d: BaseDim) -> Dimension {
204        let mut e = [Exp::ZERO; BaseDim::COUNT];
205        e[d.index()] = Exp::ONE;
206        Dimension { e }
207    }
208
209    /// Build a dimension directly from its exponent vector (in [`BaseDim::ALL`] order) — the inverse
210    /// of reading [`exponent`](Self::exponent) for each axis. Used to reconstruct a dimension from
211    /// the wire, where the exponents travel as their `(numerator, denominator)` pairs.
212    pub fn from_exps(e: [Exp; BaseDim::COUNT]) -> Dimension {
213        Dimension { e }
214    }
215
216    /// The exponent on a given base axis.
217    #[inline]
218    pub fn exponent(self, d: BaseDim) -> Exp {
219        self.e[d.index()]
220    }
221
222    /// True for the dimensionless identity (every exponent zero).
223    pub fn is_dimensionless(self) -> bool {
224        self.e.iter().all(|x| x.is_zero())
225    }
226
227    /// `self × other` — axiswise exponent ADDITION (`Length × Length = Length²`).
228    pub fn mul(self, other: Dimension) -> Dimension {
229        let mut e = self.e;
230        for (i, slot) in e.iter_mut().enumerate() {
231            *slot = slot.add(other.e[i]);
232        }
233        Dimension { e }
234    }
235
236    /// `self ÷ other` — axiswise exponent SUBTRACTION (`Area ÷ Length = Length`).
237    pub fn div(self, other: Dimension) -> Dimension {
238        let mut e = self.e;
239        for (i, slot) in e.iter_mut().enumerate() {
240            *slot = slot.sub(other.e[i]);
241        }
242        Dimension { e }
243    }
244
245    /// `1 / self` — the multiplicative inverse (negate every exponent). `Frequency = recip(Time)`.
246    pub fn recip(self) -> Dimension {
247        let mut e = self.e;
248        for slot in e.iter_mut() {
249            *slot = slot.neg();
250        }
251        Dimension { e }
252    }
253
254    /// `self^k` — the `k`th power (scale every exponent). `powi(0)` is dimensionless.
255    pub fn powi(self, k: i32) -> Dimension {
256        let mut e = self.e;
257        for slot in e.iter_mut() {
258            *slot = slot.scale(k);
259        }
260        Dimension { e }
261    }
262
263    /// The `k`th root — divide every exponent by `k` (`nth_root(Area, 2) = Length`). Panics for `k == 0`.
264    pub fn nth_root(self, k: i32) -> Dimension {
265        let mut e = self.e;
266        for slot in e.iter_mut() {
267            *slot = slot.div_int(k);
268        }
269        Dimension { e }
270    }
271
272    // ---- The SI base dimensions, by name ----
273    pub fn length() -> Dimension {
274        Dimension::base(BaseDim::Length)
275    }
276    pub fn mass() -> Dimension {
277        Dimension::base(BaseDim::Mass)
278    }
279    pub fn time() -> Dimension {
280        Dimension::base(BaseDim::Time)
281    }
282    pub fn current() -> Dimension {
283        Dimension::base(BaseDim::Current)
284    }
285    pub fn temperature() -> Dimension {
286        Dimension::base(BaseDim::Temperature)
287    }
288    pub fn amount() -> Dimension {
289        Dimension::base(BaseDim::Amount)
290    }
291    pub fn luminous() -> Dimension {
292        Dimension::base(BaseDim::Luminous)
293    }
294    pub fn angle() -> Dimension {
295        Dimension::base(BaseDim::Angle)
296    }
297    pub fn solid_angle() -> Dimension {
298        Dimension::base(BaseDim::SolidAngle)
299    }
300    pub fn information() -> Dimension {
301        Dimension::base(BaseDim::Information)
302    }
303
304    // ---- Common derived dimensions, composed from the base ones ----
305    pub fn area() -> Dimension {
306        Self::length().powi(2)
307    }
308    pub fn volume() -> Dimension {
309        Self::length().powi(3)
310    }
311    pub fn speed() -> Dimension {
312        Self::length().div(Self::time())
313    }
314    pub fn acceleration() -> Dimension {
315        Self::speed().div(Self::time())
316    }
317    pub fn frequency() -> Dimension {
318        Self::time().recip()
319    }
320    pub fn force() -> Dimension {
321        Self::mass().mul(Self::acceleration())
322    }
323    pub fn energy() -> Dimension {
324        Self::force().mul(Self::length())
325    }
326    pub fn power() -> Dimension {
327        Self::energy().div(Self::time())
328    }
329    pub fn pressure() -> Dimension {
330        Self::force().div(Self::area())
331    }
332    pub fn charge() -> Dimension {
333        Self::current().mul(Self::time())
334    }
335    pub fn voltage() -> Dimension {
336        Self::power().div(Self::current())
337    }
338    pub fn resistance() -> Dimension {
339        Self::voltage().div(Self::current())
340    }
341    pub fn conductance() -> Dimension {
342        Self::resistance().recip()
343    } // siemens: A/V = Ω⁻¹
344    pub fn capacitance() -> Dimension {
345        Self::charge().div(Self::voltage())
346    } // farad: C/V
347    pub fn magnetic_flux() -> Dimension {
348        Self::voltage().mul(Self::time())
349    } // weber: V·s
350    pub fn inductance() -> Dimension {
351        Self::magnetic_flux().div(Self::current())
352    } // henry: Wb/A
353    pub fn magnetic_flux_density() -> Dimension {
354        Self::magnetic_flux().div(Self::area())
355    } // tesla: Wb/m²
356    pub fn surface_tension() -> Dimension {
357        Self::force().div(Self::length())
358    } // N/m = M·T⁻²
359    pub fn density() -> Dimension {
360        Self::mass().div(Self::volume())
361    }
362    // Radiation.
363    pub fn absorbed_dose() -> Dimension {
364        Self::energy().div(Self::mass())
365    } // gray, sievert: J/kg = L²·T⁻²
366    pub fn radioactivity() -> Dimension {
367        Self::frequency()
368    } // becquerel: decays per second = T⁻¹
369    pub fn exposure() -> Dimension {
370        Self::charge().div(Self::mass())
371    } // roentgen: C/kg
372    pub fn catalytic_activity() -> Dimension {
373        Self::amount().div(Self::time())
374    } // katal: mol/s
375      // Photometry.
376    pub fn luminous_flux() -> Dimension {
377        Self::luminous().mul(Self::solid_angle())
378    } // lumen: cd·sr
379    pub fn illuminance() -> Dimension {
380        Self::luminous_flux().div(Self::area())
381    } // lux: lm/m²
382    pub fn luminance() -> Dimension {
383        Self::luminous().div(Self::area())
384    } // nit: cd/m²
385      // Rate / flow / concentration / viscosity / efficiency.
386    pub fn data_rate() -> Dimension {
387        Self::information().div(Self::time())
388    } // bit/s
389    pub fn volumetric_flow() -> Dimension {
390        Self::volume().div(Self::time())
391    } // m³/s
392    pub fn molar_concentration() -> Dimension {
393        Self::amount().div(Self::volume())
394    } // mol/m³
395    pub fn molality() -> Dimension {
396        Self::amount().div(Self::mass())
397    } // mol/kg
398    pub fn dynamic_viscosity() -> Dimension {
399        Self::pressure().mul(Self::time())
400    } // Pa·s = M·L⁻¹·T⁻¹
401    pub fn kinematic_viscosity() -> Dimension {
402        Self::area().div(Self::time())
403    } // m²/s = L²·T⁻¹
404    pub fn fuel_economy() -> Dimension {
405        Self::length().div(Self::volume())
406    } // distance/volume (mpg) = L⁻²
407
408    /// Resolve a **named dimension** (case-insensitive) to its exponent vector — the lookup behind
409    /// the `Quantity of <Dimension>` type annotation (`Quantity of Length`, `Quantity of Area`). The
410    /// names are the human dimension words, not units; `None` for an unknown name.
411    pub fn by_name(name: &str) -> Option<Dimension> {
412        let n = name.trim().to_ascii_lowercase();
413        Some(match n.as_str() {
414            "dimensionless" | "scalar" | "number" => Dimension::DIMENSIONLESS,
415            // SI base dimensions.
416            "length" | "distance" => Self::length(),
417            "mass" => Self::mass(),
418            "time" | "duration" => Self::time(),
419            "current" | "electriccurrent" | "electric current" => Self::current(),
420            "temperature" => Self::temperature(),
421            "amount" | "amountofsubstance" => Self::amount(),
422            "luminous" | "luminousintensity" => Self::luminous(),
423            "angle" | "planeangle" => Self::angle(),
424            "solidangle" | "solid angle" => Self::solid_angle(),
425            "information" | "data" => Self::information(),
426            // Common derived dimensions.
427            "area" => Self::area(),
428            "volume" => Self::volume(),
429            "speed" | "velocity" => Self::speed(),
430            "acceleration" => Self::acceleration(),
431            "frequency" => Self::frequency(),
432            "force" | "weight" => Self::force(),
433            "energy" | "work" | "heat" => Self::energy(),
434            "power" => Self::power(),
435            "pressure" | "stress" => Self::pressure(),
436            "charge" | "electriccharge" => Self::charge(),
437            "voltage" | "potential" | "emf" => Self::voltage(),
438            "resistance" => Self::resistance(),
439            "conductance" => Self::conductance(),
440            "capacitance" => Self::capacitance(),
441            "inductance" => Self::inductance(),
442            "magneticflux" | "magnetic flux" => Self::magnetic_flux(),
443            "magneticfluxdensity" | "fluxdensity" => Self::magnetic_flux_density(),
444            "density" => Self::density(),
445            "surfacetension" | "surface tension" => Self::surface_tension(),
446            "datarate" | "data rate" | "bandwidth" => Self::data_rate(),
447            "flow" | "volumetricflow" | "volumetric flow" => Self::volumetric_flow(),
448            "concentration" | "molarconcentration" | "molarity" => Self::molar_concentration(),
449            "molality" => Self::molality(),
450            "absorbeddose" | "dose" => Self::absorbed_dose(),
451            "radioactivity" | "activity" => Self::radioactivity(),
452            "exposure" => Self::exposure(),
453            "catalyticactivity" | "catalysis" => Self::catalytic_activity(),
454            "luminousflux" => Self::luminous_flux(),
455            "illuminance" => Self::illuminance(),
456            "luminance" => Self::luminance(),
457            "fueleconomy" | "fuel economy" => Self::fuel_economy(),
458            _ => return None,
459        })
460    }
461}
462
463impl fmt::Display for Dimension {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        if self.is_dimensionless() {
466            return write!(f, "1");
467        }
468        let mut first = true;
469        for d in BaseDim::ALL {
470            let x = self.exponent(d);
471            if x.is_zero() {
472                continue;
473            }
474            if !first {
475                write!(f, "·")?;
476            }
477            first = false;
478            if x == Exp::ONE {
479                write!(f, "{}", d.symbol())?;
480            } else {
481                write!(f, "{}^{}", d.symbol(), x)?;
482            }
483        }
484        Ok(())
485    }
486}
487
488#[cfg(test)]
489#[path = "../../logicaffeine_tests/unit/logicaffeine_base/dimension/tests.rs"]
490mod tests;