Skip to main content

crisol_core/data/
units.rs

1//! Units of measure on columns, with linear conversion.
2
3use super::column::{Column, ColumnValues};
4
5/// A linear unit: `base = value * scale + offset`.
6///
7/// # Example
8///
9/// ```
10/// use crisol_core::data::parse_unit;
11///
12/// let unit = parse_unit("m").expect("meter");
13/// assert_eq!(unit.symbol, "m");
14/// ```
15#[non_exhaustive]
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct Unit {
18    /// Canonical symbol.
19    pub symbol: &'static str,
20    /// Multiplier into the base unit.
21    pub scale: f64,
22    /// Offset into the base unit.
23    pub offset: f64,
24}
25
26/// Every unit this crate knows, grouped by physical quantity.
27const UNITS: &[Unit] = &[
28    Unit {
29        symbol: "m",
30        scale: 1.0,
31        offset: 0.0,
32    },
33    Unit {
34        symbol: "cm",
35        scale: 0.01,
36        offset: 0.0,
37    },
38    Unit {
39        symbol: "mm",
40        scale: 0.001,
41        offset: 0.0,
42    },
43    Unit {
44        symbol: "um",
45        scale: 1.0e-6,
46        offset: 0.0,
47    },
48    Unit {
49        symbol: "nm",
50        scale: 1.0e-9,
51        offset: 0.0,
52    },
53    Unit {
54        symbol: "km",
55        scale: 1000.0,
56        offset: 0.0,
57    },
58    Unit {
59        symbol: "s",
60        scale: 1.0,
61        offset: 0.0,
62    },
63    Unit {
64        symbol: "ms",
65        scale: 0.001,
66        offset: 0.0,
67    },
68    Unit {
69        symbol: "us",
70        scale: 1.0e-6,
71        offset: 0.0,
72    },
73    Unit {
74        symbol: "ns",
75        scale: 1.0e-9,
76        offset: 0.0,
77    },
78    Unit {
79        symbol: "min",
80        scale: 60.0,
81        offset: 0.0,
82    },
83    Unit {
84        symbol: "h",
85        scale: 3600.0,
86        offset: 0.0,
87    },
88    Unit {
89        symbol: "V",
90        scale: 1.0,
91        offset: 0.0,
92    },
93    Unit {
94        symbol: "mV",
95        scale: 0.001,
96        offset: 0.0,
97    },
98    Unit {
99        symbol: "kV",
100        scale: 1000.0,
101        offset: 0.0,
102    },
103    Unit {
104        symbol: "A",
105        scale: 1.0,
106        offset: 0.0,
107    },
108    Unit {
109        symbol: "mA",
110        scale: 0.001,
111        offset: 0.0,
112    },
113    Unit {
114        symbol: "Hz",
115        scale: 1.0,
116        offset: 0.0,
117    },
118    Unit {
119        symbol: "kHz",
120        scale: 1000.0,
121        offset: 0.0,
122    },
123    Unit {
124        symbol: "MHz",
125        scale: 1.0e6,
126        offset: 0.0,
127    },
128    Unit {
129        symbol: "GHz",
130        scale: 1.0e9,
131        offset: 0.0,
132    },
133    Unit {
134        symbol: "Pa",
135        scale: 1.0,
136        offset: 0.0,
137    },
138    Unit {
139        symbol: "kPa",
140        scale: 1000.0,
141        offset: 0.0,
142    },
143    Unit {
144        symbol: "MPa",
145        scale: 1.0e6,
146        offset: 0.0,
147    },
148    Unit {
149        symbol: "K",
150        scale: 1.0,
151        offset: -273.15,
152    },
153    Unit {
154        symbol: "degC",
155        scale: 1.0,
156        offset: 0.0,
157    },
158    Unit {
159        symbol: "degF",
160        scale: 5.0 / 9.0,
161        offset: -32.0 * 5.0 / 9.0,
162    },
163    Unit {
164        symbol: "%",
165        scale: 0.01,
166        offset: 0.0,
167    },
168    Unit {
169        symbol: "1",
170        scale: 1.0,
171        offset: 0.0,
172    },
173];
174
175/// Look up a unit by symbol.
176///
177/// # Example
178///
179/// ```
180/// use crisol_core::data::parse_unit;
181///
182/// assert!(parse_unit("mV").is_some());
183/// ```
184pub fn parse(symbol: &str) -> Option<Unit> {
185    UNITS.iter().copied().find(|unit| unit.symbol == symbol)
186}
187
188/// Convert `value` from one unit to another.
189///
190/// # Example
191///
192/// ```
193/// use crisol_core::data::convert_unit;
194///
195/// assert_eq!(convert_unit(1.0, "m", "cm"), Some(100.0));
196/// ```
197pub fn convert(value: f64, from: &str, to: &str) -> Option<f64> {
198    let from = parse(from)?;
199    let to = parse(to)?;
200    Some((value * from.scale + from.offset - to.offset) / to.scale)
201}
202
203/// Why a column cannot be converted.
204///
205/// # Example
206///
207/// ```
208/// use crisol_core::data::UnitError;
209///
210/// let error = UnitError::UnknownUnit("parsec".to_owned());
211/// assert!(error.to_string().contains("parsec"));
212/// ```
213#[derive(Clone, Debug, PartialEq, Eq)]
214#[non_exhaustive]
215pub enum UnitError {
216    /// The unit symbol is unknown.
217    UnknownUnit(String),
218    /// The column stores text, booleans, or dates.
219    NonNumericColumn(String),
220}
221
222impl std::fmt::Display for UnitError {
223    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        match self {
225            Self::UnknownUnit(unit) => write!(formatter, "unknown unit `{unit}`"),
226            Self::NonNumericColumn(name) => write!(formatter, "column `{name}` is not numeric"),
227        }
228    }
229}
230
231impl std::error::Error for UnitError {}
232
233impl Column {
234    /// Convert this numeric column to `unit`, preserving nulls and metadata.
235    ///
236    /// # Errors
237    /// When either unit is unknown or the column is not numeric.
238    pub fn converted(&self, unit: &str) -> Result<Self, UnitError> {
239        let from = self
240            .unit
241            .as_deref()
242            .ok_or_else(|| UnitError::UnknownUnit(String::new()))?;
243        let target = parse(unit).ok_or_else(|| UnitError::UnknownUnit(unit.to_owned()))?;
244        let source = parse(from).ok_or_else(|| UnitError::UnknownUnit(from.to_owned()))?;
245        let values = match &self.values {
246            ColumnValues::Float(values) => values
247                .iter()
248                .map(|value| (value * source.scale + source.offset - target.offset) / target.scale)
249                .collect::<Vec<_>>(),
250            ColumnValues::Int(values) => values
251                .iter()
252                .map(|value| (*value as f64 * source.scale + source.offset - target.offset) / target.scale)
253                .collect::<Vec<_>>(),
254            _ => return Err(UnitError::NonNumericColumn(self.name.clone())),
255        };
256        let validity = self.validity.clone().unwrap_or_else(|| vec![true; values.len()]);
257        let column = Column::floats(self.name.clone(), values)
258            .with_unit(unit)
259            .with_validity(validity);
260        Ok(column)
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::data::Column;
268
269    #[test]
270    fn length_and_temperature_convert() {
271        assert_eq!(convert(1.0, "m", "cm"), Some(100.0));
272        assert!((convert(0.0, "degC", "K").unwrap_or_default() - 273.15).abs() < 1.0e-9);
273        assert!((convert(32.0, "degF", "degC").unwrap_or_default()).abs() < 1.0e-9);
274    }
275
276    #[test]
277    fn a_column_keeps_nulls_when_converted() {
278        let column = Column::floats("v", vec![1.0, f64::NAN])
279            .with_unit("V")
280            .with_validity([true, false]);
281        let converted = column.converted("mV").expect("convert");
282        assert_eq!(converted.unit.as_deref(), Some("mV"));
283        assert_eq!(converted.cell(0), crate::data::CellValue::Float(1000.0));
284        assert!(converted.cell(1).is_null());
285    }
286
287    #[test]
288    fn unknown_units_are_rejected() {
289        let column = Column::ints("n", vec![1]).with_unit("parsec");
290        assert!(matches!(column.converted("m"), Err(UnitError::UnknownUnit(_))));
291        assert_eq!(convert(1.0, "parsec", "m"), None);
292        assert_eq!(convert(1.0, "m", "parsec"), None);
293        assert_eq!(parse("parsec"), None);
294        let no_unit = Column::ints("n", vec![1]);
295        assert!(matches!(no_unit.converted("m"), Err(UnitError::UnknownUnit(_))));
296        let good = Column::ints("n", vec![1]).with_unit("m");
297        assert!(matches!(good.converted("parsec"), Err(UnitError::UnknownUnit(_))));
298        let text = Column::text("s", ["a"]).with_unit("m");
299        assert!(matches!(text.converted("cm"), Err(UnitError::NonNumericColumn(_))));
300    }
301
302    #[test]
303    fn integers_and_columns_without_validity_convert() {
304        let column = Column::ints("n", vec![1, 2]).with_unit("m");
305        let converted = column.converted("cm").expect("convert");
306        assert_eq!(converted.cell(1), crate::data::CellValue::Float(200.0));
307        assert!(converted.validity.is_none() || converted.validity.as_deref().is_some_and(|v| v.iter().all(|x| *x)));
308    }
309}