Skip to main content

lib_jsl_utils/
unit_conversion.rs

1//! Conversion between common units of measure.
2//!
3//! Units are looked up by symbol or name, ignoring spaces. An exact, case-sensitive match is tried
4//! first (`mW` is a milliwatt and `MW` a megawatt, `MB` a megabyte and `Mb` a megabit); otherwise
5//! case is ignored if that leaves only one unit (`hz`, `pa` and `kwh` work), and a spelling that
6//! fits several units, such as `mw`, is an error rather than a guess. Conversion is allowed only
7//! within one physical dimension; temperatures use affine conversions.
8//!
9//! See the book entry [Shared types, constants and utilities](https://jwkunz.github.io/lib_jsl/book/foundations/core-utils.html#unit-conversion).
10
11use lib_jsl_core::ErrorsJSL;
12
13/// Physical dimension of a unit.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Dimension {
16    Length,
17    Mass,
18    Time,
19    Temperature,
20    Angle,
21    Frequency,
22    Area,
23    Volume,
24    Speed,
25    Pressure,
26    Energy,
27    Power,
28    Force,
29    Data,
30}
31
32struct Unit {
33    names: &'static [&'static str],
34    dim: Dimension,
35    /// Value in the dimension's base unit of one of this unit (`base = value * scale + offset`).
36    scale: f64,
37    offset: f64,
38}
39
40macro_rules! unit {
41    ($dim:ident, $scale:expr, [$($n:expr),+]) => {
42        Unit { names: &[$($n),+], dim: Dimension::$dim, scale: $scale, offset: 0.0 }
43    };
44}
45
46// Base units: m, kg, s, K, rad, Hz, m², m³, m/s, Pa, J, W, N, bit.
47const UNITS: &[Unit] = &[
48    unit!(Length, 1.0, ["m", "meter", "meters", "metre", "metres"]),
49    unit!(Length, 1e-3, ["mm", "millimeter", "millimeters"]),
50    unit!(Length, 1e-2, ["cm", "centimeter", "centimeters"]),
51    unit!(Length, 1e3, ["km", "kilometer", "kilometers"]),
52    unit!(Length, 1e-6, ["um", "µm", "micrometer", "micron"]),
53    unit!(Length, 1e-9, ["nm", "nanometer"]),
54    unit!(Length, 0.0254, ["in", "inch", "inches"]),
55    unit!(Length, 0.3048, ["ft", "foot", "feet"]),
56    unit!(Length, 0.9144, ["yd", "yard", "yards"]),
57    unit!(Length, 1609.344, ["mi", "mile", "miles"]),
58    unit!(Length, 1852.0, ["nmi", "nauticalmile", "nauticalmiles"]),
59    unit!(Length, 149_597_870_700.0, ["au", "astronomicalunit"]),
60    unit!(Length, 9_460_730_472_580_800.0, ["ly", "lightyear", "lightyears"]),
61    unit!(Mass, 1.0, ["kg", "kilogram", "kilograms"]),
62    unit!(Mass, 1e-3, ["g", "gram", "grams"]),
63    unit!(Mass, 1e-6, ["mg", "milligram"]),
64    unit!(Mass, 1e3, ["t", "tonne", "tonnes"]),
65    unit!(Mass, 0.453_592_37, ["lb", "lbs", "pound", "pounds"]),
66    unit!(Mass, 0.028_349_523_125, ["oz", "ounce", "ounces"]),
67    unit!(Time, 1.0, ["s", "sec", "second", "seconds"]),
68    unit!(Time, 1e-3, ["ms", "millisecond"]),
69    unit!(Time, 1e-6, ["us", "µs", "microsecond"]),
70    unit!(Time, 1e-9, ["ns", "nanosecond"]),
71    unit!(Time, 60.0, ["min", "minute", "minutes"]),
72    unit!(Time, 3600.0, ["h", "hr", "hour", "hours"]),
73    unit!(Time, 86_400.0, ["d", "day", "days"]),
74    unit!(Time, 604_800.0, ["week", "weeks"]),
75    Unit { names: &["k", "kelvin"], dim: Dimension::Temperature, scale: 1.0, offset: 0.0 },
76    Unit { names: &["c", "degc", "celsius"], dim: Dimension::Temperature, scale: 1.0, offset: 273.15 },
77    Unit { names: &["f", "degf", "fahrenheit"], dim: Dimension::Temperature, scale: 5.0 / 9.0, offset: 255.372_222_222_222_2 },
78    Unit { names: &["r", "rankine"], dim: Dimension::Temperature, scale: 5.0 / 9.0, offset: 0.0 },
79    unit!(Angle, 1.0, ["rad", "radian", "radians"]),
80    unit!(Angle, std::f64::consts::PI / 180.0, ["deg", "degree", "degrees"]),
81    unit!(Angle, std::f64::consts::PI / 200.0, ["grad", "gradian", "gradians"]),
82    unit!(Angle, std::f64::consts::TAU, ["turn", "turns", "rev", "revolution"]),
83    unit!(Angle, std::f64::consts::PI / 10_800.0, ["arcmin"]),
84    unit!(Angle, std::f64::consts::PI / 648_000.0, ["arcsec"]),
85    unit!(Frequency, 1.0, ["hz", "hertz"]),
86    unit!(Frequency, 1e3, ["kHz", "kilohertz"]),
87    unit!(Frequency, 1e6, ["MHz", "megahertz"]),
88    unit!(Frequency, 1e9, ["GHz", "gigahertz"]),
89    unit!(Frequency, 1.0 / 60.0, ["rpm"]),
90    unit!(Frequency, std::f64::consts::TAU, ["rad/s"]),
91    unit!(Area, 1.0, ["m2", "m^2", "sqm"]),
92    unit!(Area, 1e-4, ["cm2", "cm^2"]),
93    unit!(Area, 1e6, ["km2", "km^2"]),
94    unit!(Area, 10_000.0, ["ha", "hectare", "hectares"]),
95    unit!(Area, 4_046.856_422_4, ["acre", "acres"]),
96    unit!(Area, 0.092_903_04, ["ft2", "ft^2", "sqft"]),
97    unit!(Volume, 1.0, ["m3", "m^3"]),
98    unit!(Volume, 1e-3, ["l", "liter", "liters", "litre", "litres"]),
99    unit!(Volume, 1e-6, ["ml", "milliliter", "cm3", "cc"]),
100    unit!(Volume, 3.785_411_784e-3, ["gal", "gallon", "gallons"]),
101    unit!(Volume, 2.365_882_365e-4, ["cup", "cups"]),
102    unit!(Volume, 0.028_316_846_592, ["ft3", "ft^3"]),
103    unit!(Speed, 1.0, ["m/s", "mps"]),
104    unit!(Speed, 1.0 / 3.6, ["km/h", "kph", "kmh"]),
105    unit!(Speed, 0.447_04, ["mph", "mi/h"]),
106    unit!(Speed, 1852.0 / 3600.0, ["kn", "kt", "knot", "knots"]),
107    unit!(Speed, 0.3048, ["ft/s", "fps"]),
108    unit!(Speed, 299_792_458.0, ["c0", "lightspeed"]),
109    unit!(Pressure, 1.0, ["pa", "pascal"]),
110    unit!(Pressure, 1e3, ["kpa"]),
111    unit!(Pressure, 1e5, ["bar"]),
112    unit!(Pressure, 100.0, ["mbar", "hpa"]),
113    unit!(Pressure, 101_325.0, ["atm"]),
114    unit!(Pressure, 133.322_387_415, ["mmHg"]),
115    unit!(Pressure, 101_325.0 / 760.0, ["torr"]),
116    unit!(Pressure, 6_894.757_293_168_361, ["psi"]),
117    unit!(Energy, 1.0, ["j", "joule", "joules"]),
118    unit!(Energy, 1e3, ["kj"]),
119    unit!(Energy, 4.184, ["cal"]),
120    unit!(Energy, 4184.0, ["kcal"]),
121    unit!(Energy, 3.6e6, ["kwh"]),
122    unit!(Energy, 1.602_176_634e-19, ["ev"]),
123    unit!(Energy, 1_055.055_852_62, ["btu"]),
124    unit!(Power, 1.0, ["w", "watt", "watts"]),
125    unit!(Power, 1e3, ["kW", "kilowatt", "kilowatts"]),
126    unit!(Power, 1e-3, ["mW", "milliwatt", "milliwatts"]),
127    unit!(Power, 1e6, ["MW", "megawatt", "megawatts"]),
128    unit!(Power, 745.699_871_582_270_2, ["hp"]),
129    unit!(Force, 1.0, ["n", "newton", "newtons"]),
130    unit!(Force, 4.448_221_615_260_5, ["lbf"]),
131    unit!(Force, 9.806_65, ["kgf"]),
132    unit!(Data, 1.0, ["bit", "bits"]),
133    unit!(Data, 8.0, ["byte", "bytes"]),
134    unit!(Data, 1e3, ["kb", "kbit", "kilobit"]),
135    unit!(Data, 1e6, ["Mb", "Mbit", "megabit"]),
136    unit!(Data, 1e9, ["Gb", "Gbit", "gigabit"]),
137    unit!(Data, 8e3, ["kB", "kilobyte"]),
138    unit!(Data, 8e6, ["MB", "megabyte"]),
139    unit!(Data, 8e9, ["GB", "gigabyte"]),
140    unit!(Data, 8192.0, ["KiB", "kibibyte"]),
141    unit!(Data, 8_388_608.0, ["MiB", "mebibyte"]),
142    unit!(Data, 8_589_934_592.0, ["GiB", "gibibyte"]),
143];
144
145fn lookup(name: &str) -> Result<&'static Unit, ErrorsJSL> {
146    let key: String = name.chars().filter(|c| !c.is_whitespace()).collect();
147    if let Some(unit) = UNITS.iter().find(|u| u.names.contains(&key.as_str())) {
148        return Ok(unit);
149    }
150    let lower = key.to_lowercase();
151    let mut matches = UNITS.iter().filter(|u| u.names.iter().any(|n| n.to_lowercase() == lower));
152    match (matches.next(), matches.next()) {
153        (Some(unit), None) => Ok(unit),
154        (Some(_), Some(_)) => Err(ErrorsJSL::InvalidInputRange("Ambiguous unit: give its case-sensitive symbol, such as mW or MW.")),
155        _ => Err(ErrorsJSL::InvalidInputRange("Unknown unit.")),
156    }
157}
158
159/// The dimension of a named unit.
160pub fn unit_dimension(name: &str) -> Result<Dimension, ErrorsJSL> {
161    lookup(name).map(|u| u.dim)
162}
163
164/// Converts `value` from unit `from` to unit `to`, e.g. `unit_conversion(100.0, "km/h", "mph")`.
165///
166/// Errors for unknown units or when the units belong to different dimensions.
167pub fn unit_conversion(value: f64, from: &str, to: &str) -> Result<f64, ErrorsJSL> {
168    let (a, b) = (lookup(from)?, lookup(to)?);
169    if a.dim != b.dim {
170        return Err(ErrorsJSL::InvalidInputRange("Units have different dimensions."));
171    }
172    Ok(((value * a.scale + a.offset) - b.offset) / b.scale)
173}
174
175/// Converts a power ratio to decibels, `10 log10(ratio)`.
176pub fn linear_power_to_db(ratio: f64) -> f64 {
177    10.0 * ratio.log10()
178}
179
180/// Converts decibels to a power ratio.
181pub fn db_to_linear_power(db: f64) -> f64 {
182    10f64.powf(db / 10.0)
183}
184
185/// Converts an amplitude (voltage) ratio to decibels, `20 log10(ratio)`.
186pub fn linear_amplitude_to_db(ratio: f64) -> f64 {
187    20.0 * ratio.log10()
188}
189
190/// Converts decibels to an amplitude ratio.
191pub fn db_to_linear_amplitude(db: f64) -> f64 {
192    10f64.powf(db / 20.0)
193}
194
195/// Power in watts to dBm.
196pub fn watts_to_dbm(watts: f64) -> f64 {
197    10.0 * (watts * 1e3).log10()
198}
199
200/// dBm to power in watts.
201pub fn dbm_to_watts(dbm: f64) -> f64 {
202    10f64.powf(dbm / 10.0) * 1e-3
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    fn close(a: f64, b: f64) -> bool {
210        (a - b).abs() <= 1e-9 * b.abs().max(1.0)
211    }
212
213    #[test]
214    fn linear_conversions() {
215        assert!(close(unit_conversion(1.0, "mi", "km").unwrap(), 1.609344));
216        assert!(close(unit_conversion(100.0, "km/h", "mph").unwrap(), 62.137_119_223_733_4));
217        assert!(close(unit_conversion(180.0, "deg", "rad").unwrap(), std::f64::consts::PI));
218        assert!(close(unit_conversion(1.0, "atm", "psi").unwrap(), 14.695_948_775_513_4));
219        assert!(close(unit_conversion(1.0, "GiB", "MB").unwrap(), 1_073.741_824));
220        assert!(close(unit_conversion(60.0, "rpm", "Hz").unwrap(), 1.0));
221        assert!(close(unit_conversion(2.0, " Hours ", "min").unwrap(), 120.0));
222    }
223
224    #[test]
225    fn temperatures_are_affine() {
226        assert!(close(unit_conversion(100.0, "C", "F").unwrap(), 212.0));
227        assert!(close(unit_conversion(32.0, "F", "C").unwrap(), 0.0));
228        assert!(close(unit_conversion(0.0, "K", "C").unwrap(), -273.15));
229        assert!(close(unit_conversion(-40.0, "C", "F").unwrap(), -40.0));
230    }
231
232    #[test]
233    fn round_trips_and_errors() {
234        for (a, b) in [("m", "ft"), ("kcal", "kwh"), ("gal", "l"), ("F", "R")] {
235            let v = unit_conversion(unit_conversion(3.7, a, b).unwrap(), b, a).unwrap();
236            assert!(close(v, 3.7), "{a}->{b}");
237        }
238        assert!(unit_conversion(1.0, "m", "kg").is_err());
239        // Case decides SI prefixes when it must; an ambiguous spelling is refused.
240        assert!(close(unit_conversion(1.0, "mW", "W").unwrap(), 1e-3));
241        assert!(close(unit_conversion(1.0, "MW", "W").unwrap(), 1e6));
242        assert!(unit_conversion(1.0, "mw", "W").is_err());
243        assert!(close(unit_conversion(1.0, "MB", "Mb").unwrap(), 8.0));
244        assert!(close(unit_conversion(1.0, "mhz", "kHz").unwrap(), 1000.0));
245        assert!(close(unit_conversion(760.0, "torr", "atm").unwrap(), 1.0));
246        // The conventional millimetre of mercury is 1.4e-7 larger than the torr (101 325/760 Pa).
247        let ratio = unit_conversion(1.0, "mmHg", "torr").unwrap();
248        assert!(ratio > 1.0 + 1e-7 && ratio < 1.0 + 2e-7);
249        assert!(unit_conversion(1.0, "parsec", "m").is_err());
250        assert_eq!(unit_dimension("psi").unwrap(), Dimension::Pressure);
251    }
252
253    #[test]
254    fn decibel_helpers() {
255        assert!(close(linear_power_to_db(100.0), 20.0));
256        assert!(close(db_to_linear_power(3.0), 1.995_262_314_968_88));
257        assert!(close(linear_amplitude_to_db(10.0), 20.0));
258        assert!(close(db_to_linear_amplitude(-6.0), 0.501_187_233_627_272_3));
259        assert!(close(watts_to_dbm(1.0), 30.0));
260        assert!(close(dbm_to_watts(0.0), 1e-3));
261    }
262}