Skip to main content

qualia_core_db/solvers/units/
conversion.rs

1//! Units and conversion. A [`Unit`] maps its own scale to coherent SI by an affine
2//! transform `si = value·factor + offset` (the offset is only non-zero for the
3//! temperature scales — Celsius, Fahrenheit). Conversion between two units requires
4//! matching dimensions and fails closed otherwise.
5
6use super::dimension::Dimension;
7use super::quantity::Quantity;
8use super::UnitsError;
9
10/// A named unit of a given dimension, defined by its affine map to coherent SI base
11/// units: `si_value = value * to_si_factor + to_si_offset`.
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct Unit {
14    pub name: &'static str,
15    pub dimension: Dimension,
16    pub to_si_factor: f64,
17    pub to_si_offset: f64,
18}
19
20impl Unit {
21    /// `Unit::linear`.
22    pub const fn linear(name: &'static str, dimension: Dimension, factor: f64) -> Self {
23        Self {
24            name,
25            dimension,
26            to_si_factor: factor,
27            to_si_offset: 0.0,
28        }
29    }
30    /// `Unit::affine`.
31    pub const fn affine(
32        name: &'static str,
33        dimension: Dimension,
34        factor: f64,
35        offset: f64,
36    ) -> Self {
37        Self {
38            name,
39            dimension,
40            to_si_factor: factor,
41            to_si_offset: offset,
42        }
43    }
44
45    /// Convert a magnitude in this unit to coherent SI.
46    pub fn to_si(&self, value: f64) -> f64 {
47        value * self.to_si_factor + self.to_si_offset
48    }
49    /// Convert a magnitude in coherent SI back to this unit.
50    pub fn from_si(&self, si: f64) -> f64 {
51        (si - self.to_si_offset) / self.to_si_factor
52    }
53
54    /// A magnitude in this unit as a dimensioned [`Quantity`] (in SI).
55    pub fn quantity(&self, value: f64) -> Quantity {
56        Quantity::new(self.to_si(value), self.dimension)
57    }
58
59    // ── Length ──
60    pub const METRE: Unit = Unit::linear("m", Dimension::LENGTH, 1.0);
61    pub const KILOMETRE: Unit = Unit::linear("km", Dimension::LENGTH, 1000.0);
62    pub const CENTIMETRE: Unit = Unit::linear("cm", Dimension::LENGTH, 0.01);
63    pub const MILLIMETRE: Unit = Unit::linear("mm", Dimension::LENGTH, 0.001);
64    pub const INCH: Unit = Unit::linear("in", Dimension::LENGTH, 0.0254);
65    pub const FOOT: Unit = Unit::linear("ft", Dimension::LENGTH, 0.3048);
66    pub const MILE: Unit = Unit::linear("mi", Dimension::LENGTH, 1609.344);
67    // ── Mass ──
68    pub const KILOGRAM: Unit = Unit::linear("kg", Dimension::MASS, 1.0);
69    pub const GRAM: Unit = Unit::linear("g", Dimension::MASS, 0.001);
70    pub const POUND: Unit = Unit::linear("lb", Dimension::MASS, 0.45359237);
71    // ── Time ──
72    pub const SECOND: Unit = Unit::linear("s", Dimension::TIME, 1.0);
73    pub const MINUTE: Unit = Unit::linear("min", Dimension::TIME, 60.0);
74    pub const HOUR: Unit = Unit::linear("h", Dimension::TIME, 3600.0);
75    // ── Force / energy / pressure ──
76    pub const NEWTON: Unit = Unit::linear("N", Dimension::FORCE, 1.0);
77    pub const JOULE: Unit = Unit::linear("J", Dimension::ENERGY, 1.0);
78    pub const KILOWATT_HOUR: Unit = Unit::linear("kWh", Dimension::ENERGY, 3.6e6);
79    pub const PASCAL: Unit = Unit::linear("Pa", Dimension::PRESSURE, 1.0);
80    pub const BAR: Unit = Unit::linear("bar", Dimension::PRESSURE, 1.0e5);
81    // ── Temperature (affine) ──
82    pub const KELVIN: Unit = Unit::linear("K", Dimension::TEMPERATURE, 1.0);
83    pub const CELSIUS: Unit = Unit::affine("°C", Dimension::TEMPERATURE, 1.0, 273.15);
84    pub const FAHRENHEIT: Unit = Unit::affine(
85        "°F",
86        Dimension::TEMPERATURE,
87        5.0 / 9.0,
88        255.372_222_222_222_2,
89    );
90}
91
92/// Convert `value` from one unit to another. Fails closed if the units have different
93/// dimensions (e.g. metres → seconds).
94pub fn convert(value: f64, from: &Unit, to: &Unit) -> Result<f64, UnitsError> {
95    if from.dimension != to.dimension {
96        return Err(UnitsError::IncompatibleDimensions);
97    }
98    Ok(to.from_si(from.to_si(value)))
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    const EPS: f64 = 1e-6;
105
106    #[test]
107    fn length_conversions() {
108        assert!((convert(1.0, &Unit::INCH, &Unit::CENTIMETRE).unwrap() - 2.54).abs() < EPS);
109        assert!((convert(1.0, &Unit::MILE, &Unit::KILOMETRE).unwrap() - 1.609344).abs() < EPS);
110        assert!((convert(3.0, &Unit::FOOT, &Unit::METRE).unwrap() - 0.9144).abs() < EPS);
111    }
112
113    #[test]
114    fn temperature_is_affine() {
115        // 0 °C = 273.15 K
116        assert!((convert(0.0, &Unit::CELSIUS, &Unit::KELVIN).unwrap() - 273.15).abs() < EPS);
117        // 100 °C = 212 °F
118        assert!((convert(100.0, &Unit::CELSIUS, &Unit::FAHRENHEIT).unwrap() - 212.0).abs() < 1e-3);
119        // 32 °F = 0 °C
120        assert!((convert(32.0, &Unit::FAHRENHEIT, &Unit::CELSIUS).unwrap()).abs() < 1e-3);
121        // −40 °C = −40 °F (the classic crossover)
122        assert!((convert(-40.0, &Unit::CELSIUS, &Unit::FAHRENHEIT).unwrap() + 40.0).abs() < 1e-3);
123    }
124
125    #[test]
126    fn energy_conversion() {
127        // 1 kWh = 3.6 MJ
128        assert!((convert(1.0, &Unit::KILOWATT_HOUR, &Unit::JOULE).unwrap() - 3.6e6).abs() < 1.0);
129    }
130
131    #[test]
132    fn cross_dimension_conversion_fails_closed() {
133        assert_eq!(
134            convert(1.0, &Unit::METRE, &Unit::SECOND).unwrap_err(),
135            UnitsError::IncompatibleDimensions
136        );
137    }
138}