Skip to main content

vibe/
quantity.rs

1//! Quantity dimension algebra and unit conversions (T73).
2//!
3//! SI base dimensions and derived unit conversions computed via dimensional exponents.
4
5use std::ops::{Div, Mul};
6
7/// SI Base Dimensions: Length (m), Mass (kg), Time (s), Current (A),
8/// Temperature (K), Amount of substance (mol), Luminous intensity (cd).
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
10pub struct Dimension {
11    pub length: i8,      // m (L)
12    pub mass: i8,        // kg (M)
13    pub time: i8,        // s (T)
14    pub current: i8,     // A (I)
15    pub temperature: i8, // K (Θ)
16    pub amount: i8,      // mol (N)
17    pub luminous: i8,    // cd (J)
18}
19
20impl Dimension {
21    /// Dimensionless quantity.
22    pub const fn dimensionless() -> Self {
23        Self {
24            length: 0,
25            mass: 0,
26            time: 0,
27            current: 0,
28            temperature: 0,
29            amount: 0,
30            luminous: 0,
31        }
32    }
33
34    /// Length dimension.
35    pub const fn length() -> Self {
36        let mut d = Self::dimensionless();
37        d.length = 1;
38        d
39    }
40
41    /// Mass dimension.
42    pub const fn mass() -> Self {
43        let mut d = Self::dimensionless();
44        d.mass = 1;
45        d
46    }
47
48    /// Time dimension.
49    pub const fn time() -> Self {
50        let mut d = Self::dimensionless();
51        d.time = 1;
52        d
53    }
54
55    /// Frequency dimension.
56    pub const fn frequency() -> Self {
57        let mut d = Self::dimensionless();
58        d.time = -1;
59        d
60    }
61
62    /// Current dimension.
63    pub const fn current() -> Self {
64        let mut d = Self::dimensionless();
65        d.current = 1;
66        d
67    }
68
69    /// Temperature dimension.
70    pub const fn temperature() -> Self {
71        let mut d = Self::dimensionless();
72        d.temperature = 1;
73        d
74    }
75
76    /// Amount-of-substance dimension.
77    pub const fn amount() -> Self {
78        let mut d = Self::dimensionless();
79        d.amount = 1;
80        d
81    }
82
83    /// Luminous-intensity dimension.
84    pub const fn luminous() -> Self {
85        let mut d = Self::dimensionless();
86        d.luminous = 1;
87        d
88    }
89
90    // Common derived dimensions
91    /// Area dimension.
92    pub const fn area() -> Self {
93        let mut d = Self::dimensionless();
94        d.length = 2;
95        d
96    }
97
98    /// Volume dimension.
99    pub const fn volume() -> Self {
100        let mut d = Self::dimensionless();
101        d.length = 3;
102        d
103    }
104
105    /// Velocity dimension.
106    pub const fn velocity() -> Self {
107        let mut d = Self::dimensionless();
108        d.length = 1;
109        d.time = -1;
110        d
111    }
112
113    /// Acceleration dimension.
114    pub const fn acceleration() -> Self {
115        let mut d = Self::dimensionless();
116        d.length = 1;
117        d.time = -2;
118        d
119    }
120
121    /// Force dimension.
122    pub const fn force() -> Self {
123        let mut d = Self::dimensionless();
124        d.mass = 1;
125        d.length = 1;
126        d.time = -2;
127        d
128    }
129
130    /// Pressure dimension.
131    pub const fn pressure() -> Self {
132        let mut d = Self::dimensionless();
133        d.mass = 1;
134        d.length = -1;
135        d.time = -2;
136        d
137    }
138
139    /// Energy dimension.
140    pub const fn energy() -> Self {
141        let mut d = Self::dimensionless();
142        d.mass = 1;
143        d.length = 2;
144        d.time = -2;
145        d
146    }
147
148    /// Power dimension.
149    pub const fn power() -> Self {
150        let mut d = Self::dimensionless();
151        d.mass = 1;
152        d.length = 2;
153        d.time = -3;
154        d
155    }
156}
157
158impl Mul for Dimension {
159    type Output = Self;
160
161    fn mul(self, rhs: Self) -> Self::Output {
162        Self {
163            length: self.length + rhs.length,
164            mass: self.mass + rhs.mass,
165            time: self.time + rhs.time,
166            current: self.current + rhs.current,
167            temperature: self.temperature + rhs.temperature,
168            amount: self.amount + rhs.amount,
169            luminous: self.luminous + rhs.luminous,
170        }
171    }
172}
173
174impl Div for Dimension {
175    type Output = Self;
176
177    fn div(self, rhs: Self) -> Self::Output {
178        Self {
179            length: self.length - rhs.length,
180            mass: self.mass - rhs.mass,
181            time: self.time - rhs.time,
182            current: self.current - rhs.current,
183            temperature: self.temperature - rhs.temperature,
184            amount: self.amount - rhs.amount,
185            luminous: self.luminous - rhs.luminous,
186        }
187    }
188}
189
190/// A physical unit with a dimension, scaling factor to SI base units, and optional affine offset.
191#[derive(Debug, Clone, PartialEq)]
192pub struct Unit {
193    pub symbol: String,
194    pub dimension: Dimension,
195    pub scale: f64,
196    pub offset: f64,
197}
198
199impl Unit {
200    /// Creates a new `Unit`.
201    pub fn new(symbol: impl Into<String>, dimension: Dimension, scale: f64) -> Self {
202        Self {
203            symbol: symbol.into(),
204            dimension,
205            scale,
206            offset: 0.0,
207        }
208    }
209
210    /// Builder — sets offset.
211    pub fn with_offset(
212        symbol: impl Into<String>,
213        dimension: Dimension,
214        scale: f64,
215        offset: f64,
216    ) -> Self {
217        Self {
218            symbol: symbol.into(),
219            dimension,
220            scale,
221            offset,
222        }
223    }
224
225    /// Convert a numeric value from `self` to `target`.
226    /// Returns Err if the dimensions do not match.
227    pub fn convert(&self, value: f64, target: &Unit) -> Result<f64, String> {
228        if self.dimension != target.dimension {
229            return Err(format!(
230                "incompatible dimensions: cannot convert '{}' ({:?}) to '{}' ({:?})",
231                self.symbol, self.dimension, target.symbol, target.dimension
232            ));
233        }
234
235        // To SI base: (value + self.offset) * self.scale
236        let si_base = (value + self.offset) * self.scale;
237        // From SI base: (si_base / target.scale) - target.offset
238        let target_val = (si_base / target.scale) - target.offset;
239        Ok(target_val)
240    }
241}
242
243/// Look up standard units by symbol.
244pub fn lookup_unit(symbol: &str) -> Option<Unit> {
245    match symbol {
246        "m" => Some(Unit::new("m", Dimension::length(), 1.0)),
247        "km" => Some(Unit::new("km", Dimension::length(), 1_000.0)),
248        "cm" => Some(Unit::new("cm", Dimension::length(), 0.01)),
249        "mm" => Some(Unit::new("mm", Dimension::length(), 0.001)),
250        "s" => Some(Unit::new("s", Dimension::time(), 1.0)),
251        "ms" => Some(Unit::new("ms", Dimension::time(), 0.001)),
252        "kg" => Some(Unit::new("kg", Dimension::mass(), 1.0)),
253        "g" => Some(Unit::new("g", Dimension::mass(), 0.001)),
254        "A" => Some(Unit::new("A", Dimension::current(), 1.0)),
255        "K" => Some(Unit::new("K", Dimension::temperature(), 1.0)),
256        "°C" | "degC" => Some(Unit::with_offset(
257            "°C",
258            Dimension::temperature(),
259            1.0,
260            273.15,
261        )),
262        // (°F + 459.67) × 5/9 = K
263        "°F" | "degF" => Some(Unit::with_offset(
264            "°F",
265            Dimension::temperature(),
266            5.0 / 9.0,
267            459.67,
268        )),
269        "N" => Some(Unit::new("N", Dimension::force(), 1.0)),
270        "kN" => Some(Unit::new("kN", Dimension::force(), 1_000.0)),
271        "Pa" => Some(Unit::new("Pa", Dimension::pressure(), 1.0)),
272        "kPa" => Some(Unit::new("kPa", Dimension::pressure(), 1_000.0)),
273        "MPa" => Some(Unit::new("MPa", Dimension::pressure(), 1_000_000.0)),
274        "N/m²" => Some(Unit::new("N/m²", Dimension::pressure(), 1.0)),
275        "J" => Some(Unit::new("J", Dimension::energy(), 1.0)),
276        "kJ" => Some(Unit::new("kJ", Dimension::energy(), 1_000.0)),
277        "W" => Some(Unit::new("W", Dimension::power(), 1.0)),
278        "kW" => Some(Unit::new("kW", Dimension::power(), 1_000.0)),
279        "Hz" => Some(Unit::new("Hz", Dimension::frequency(), 1.0)),
280        "kHz" => Some(Unit::new("kHz", Dimension::frequency(), 1_000.0)),
281        "MHz" => Some(Unit::new("MHz", Dimension::frequency(), 1_000_000.0)),
282        "GHz" => Some(Unit::new("GHz", Dimension::frequency(), 1_000_000_000.0)),
283        "fps" => Some(Unit::new("fps", Dimension::frequency(), 1.0)),
284        "nm" => Some(Unit::new("nm", Dimension::length(), 1e-9)),
285        "deg" => Some(Unit::new("deg", Dimension::dimensionless(), 1.0)),
286        "rad" => Some(Unit::new("rad", Dimension::dimensionless(), 1.0)),
287        "%" => Some(Unit::new("%", Dimension::dimensionless(), 0.01)),
288        "m/s" => Some(Unit::new("m/s", Dimension::velocity(), 1.0)),
289        _ => None,
290    }
291}
292
293/// Canonical unit identifier used at check time (T73 / UnitId).
294#[derive(Debug, Clone, PartialEq, Eq, Hash)]
295pub struct UnitId {
296    pub symbol: String,
297}
298
299impl UnitId {
300    /// Creates a new `UnitId`.
301    pub fn new(symbol: impl Into<String>) -> Self {
302        Self {
303            symbol: symbol.into(),
304        }
305    }
306
307    ///  when dimensions are compatible.
308    pub fn compatible(&self, other: &Self) -> bool {
309        match (lookup_unit(&self.symbol), lookup_unit(&other.symbol)) {
310            (Some(a), Some(b)) => a.dimension == b.dimension,
311            _ => self.symbol == other.symbol,
312        }
313    }
314}
315
316/// Linear tween of two same-unit scalars. `t` is clamped to `[0, 1]`.
317pub fn tween(a: f64, a_unit: &str, b: f64, b_unit: &str, t: f64) -> Result<f64, String> {
318    let ua = UnitId::new(a_unit);
319    let ub = UnitId::new(b_unit);
320    if !ua.compatible(&ub) {
321        return Err(format!(
322            "unit mismatch: cannot tween `{a_unit}` with `{b_unit}`"
323        ));
324    }
325    let t = t.clamp(0.0, 1.0);
326    Ok(a + (b - a) * t)
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn dimension_multiplication() {
335        let force = Dimension::force();
336        let length = Dimension::length();
337        let energy = force * length;
338        assert_eq!(energy, Dimension::energy());
339    }
340
341    #[test]
342    fn kpa_to_pa() {
343        let kpa = lookup_unit("kPa").unwrap();
344        let pa = lookup_unit("Pa").unwrap();
345        let result = kpa.convert(1.0, &pa).unwrap();
346        assert!((result - 1000.0).abs() < 1e-9);
347    }
348
349    #[test]
350    fn pa_to_n_per_m2() {
351        let pa = lookup_unit("Pa").unwrap();
352        let n_m2 = lookup_unit("N/m²").unwrap();
353        let result = pa.convert(1.0, &n_m2).unwrap();
354        assert!((result - 1.0).abs() < 1e-9);
355    }
356
357    #[test]
358    fn dimension_mismatch_fails() {
359        let pa = lookup_unit("Pa").unwrap();
360        let m = lookup_unit("m").unwrap();
361        assert!(pa.convert(1.0, &m).is_err());
362    }
363
364    #[test]
365    fn celsius_to_kelvin() {
366        let c = lookup_unit("°C").unwrap();
367        let k = lookup_unit("K").unwrap();
368        let result = c.convert(0.0, &k).unwrap();
369        assert!((result - 273.15).abs() < 1e-9);
370    }
371
372    #[test]
373    fn tween_same_unit() {
374        assert_eq!(tween(0.0, "m", 10.0, "m", 0.5).unwrap(), 5.0);
375    }
376
377    #[test]
378    fn tween_compatible_length_units() {
379        assert!(tween(1.0, "m", 2.0, "km", 0.5).is_ok());
380    }
381
382    #[test]
383    fn tween_rejects_dimension_mismatch() {
384        assert!(tween(1.0, "m", 2.0, "s", 0.5).is_err());
385    }
386}