Skip to main content

qualia_core_db/solvers/units/
quantity.rs

1//! A dimensioned quantity: a value with a physical [`Dimension`], and arithmetic that
2//! is **dimensionally checked**. Adding incompatible dimensions fails closed; products
3//! and quotients compose dimensions automatically.
4
5use super::dimension::Dimension;
6use super::UnitsError;
7
8/// A value expressed in SI base units, tagged with its physical dimension.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Quantity {
11    /// Magnitude in coherent SI base units (e.g. metres, kilograms, seconds).
12    pub value: f64,
13    pub dimension: Dimension,
14}
15
16impl Quantity {
17    /// Creates a default `Quantity`.
18    pub const fn new(value: f64, dimension: Dimension) -> Self {
19        Self { value, dimension }
20    }
21
22    /// A dimensionless number.
23    pub const fn scalar(value: f64) -> Self {
24        Self {
25            value,
26            dimension: Dimension::DIMENSIONLESS,
27        }
28    }
29
30    /// Sum of two quantities — requires matching dimensions (fail closed otherwise).
31    pub fn add(&self, other: &Quantity) -> Result<Quantity, UnitsError> {
32        if self.dimension != other.dimension {
33            return Err(UnitsError::IncompatibleDimensions);
34        }
35        Ok(Quantity {
36            value: self.value + other.value,
37            dimension: self.dimension,
38        })
39    }
40
41    /// Difference — requires matching dimensions.
42    pub fn sub(&self, other: &Quantity) -> Result<Quantity, UnitsError> {
43        if self.dimension != other.dimension {
44            return Err(UnitsError::IncompatibleDimensions);
45        }
46        Ok(Quantity {
47            value: self.value - other.value,
48            dimension: self.dimension,
49        })
50    }
51
52    /// Product — values multiply, dimensions compose.
53    pub fn mul(&self, other: &Quantity) -> Quantity {
54        Quantity {
55            value: self.value * other.value,
56            dimension: self.dimension.mul(&other.dimension),
57        }
58    }
59
60    /// Quotient — values divide, dimensions subtract. `None` on divide-by-zero.
61    pub fn div(&self, other: &Quantity) -> Option<Quantity> {
62        if other.value == 0.0 {
63            return None;
64        }
65        Some(Quantity {
66            value: self.value / other.value,
67            dimension: self.dimension.div(&other.dimension),
68        })
69    }
70
71    /// Scale by a dimensionless factor.
72    pub fn scale(&self, factor: f64) -> Quantity {
73        Quantity {
74            value: self.value * factor,
75            dimension: self.dimension,
76        }
77    }
78
79    /// Integer power — value and dimension both raised to `n`.
80    pub fn powi(&self, n: i32) -> Quantity {
81        Quantity {
82            value: self.value.powi(n),
83            dimension: self.dimension.powi(n),
84        }
85    }
86
87    /// `true` iff dimensionally compatible with `other` (can be added/compared).
88    pub fn compatible_with(&self, other: &Quantity) -> bool {
89        self.dimension == other.dimension
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    const EPS: f64 = 1e-9;
97
98    fn metres(v: f64) -> Quantity {
99        Quantity::new(v, Dimension::LENGTH)
100    }
101    fn seconds(v: f64) -> Quantity {
102        Quantity::new(v, Dimension::TIME)
103    }
104
105    #[test]
106    fn adding_like_dimensions_works_unlike_fails() {
107        let total = metres(3.0).add(&metres(4.0)).unwrap();
108        assert!((total.value - 7.0).abs() < EPS);
109        assert_eq!(total.dimension, Dimension::LENGTH);
110        // length + time is a dimensional error.
111        assert_eq!(
112            metres(1.0).add(&seconds(1.0)).unwrap_err(),
113            UnitsError::IncompatibleDimensions
114        );
115    }
116
117    #[test]
118    fn products_derive_new_dimensions() {
119        // distance / time = velocity
120        let v = metres(100.0).div(&seconds(10.0)).unwrap();
121        assert!((v.value - 10.0).abs() < EPS);
122        assert_eq!(v.dimension, Dimension::VELOCITY);
123        // force × distance = energy
124        let force = Quantity::new(5.0, Dimension::FORCE);
125        let work = force.mul(&metres(2.0));
126        assert!((work.value - 10.0).abs() < EPS);
127        assert_eq!(work.dimension, Dimension::ENERGY);
128    }
129
130    #[test]
131    fn kinetic_energy_is_dimensionally_consistent() {
132        // ½ m v²  →  mass × velocity² = energy.
133        let m = Quantity::new(2.0, Dimension::MASS);
134        let v = Quantity::new(3.0, Dimension::VELOCITY);
135        let ke = m.mul(&v.powi(2)).scale(0.5);
136        assert!((ke.value - 9.0).abs() < EPS); // ½·2·9
137        assert_eq!(ke.dimension, Dimension::ENERGY);
138    }
139
140    #[test]
141    fn divide_by_zero_fails_closed() {
142        assert!(metres(1.0).div(&seconds(0.0)).is_none());
143    }
144}