crisol-core 1.2.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Units of measure on columns, with linear conversion.

use super::column::{Column, ColumnValues};

/// A linear unit: `base = value * scale + offset`.
///
/// # Example
///
/// ```
/// use crisol_core::data::parse_unit;
///
/// let unit = parse_unit("m").expect("meter");
/// assert_eq!(unit.symbol, "m");
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Unit {
    /// Canonical symbol.
    pub symbol: &'static str,
    /// Multiplier into the base unit.
    pub scale: f64,
    /// Offset into the base unit.
    pub offset: f64,
}

/// Every unit this crate knows, grouped by physical quantity.
const UNITS: &[Unit] = &[
    Unit {
        symbol: "m",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "cm",
        scale: 0.01,
        offset: 0.0,
    },
    Unit {
        symbol: "mm",
        scale: 0.001,
        offset: 0.0,
    },
    Unit {
        symbol: "um",
        scale: 1.0e-6,
        offset: 0.0,
    },
    Unit {
        symbol: "nm",
        scale: 1.0e-9,
        offset: 0.0,
    },
    Unit {
        symbol: "km",
        scale: 1000.0,
        offset: 0.0,
    },
    Unit {
        symbol: "s",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "ms",
        scale: 0.001,
        offset: 0.0,
    },
    Unit {
        symbol: "us",
        scale: 1.0e-6,
        offset: 0.0,
    },
    Unit {
        symbol: "ns",
        scale: 1.0e-9,
        offset: 0.0,
    },
    Unit {
        symbol: "min",
        scale: 60.0,
        offset: 0.0,
    },
    Unit {
        symbol: "h",
        scale: 3600.0,
        offset: 0.0,
    },
    Unit {
        symbol: "V",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "mV",
        scale: 0.001,
        offset: 0.0,
    },
    Unit {
        symbol: "kV",
        scale: 1000.0,
        offset: 0.0,
    },
    Unit {
        symbol: "A",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "mA",
        scale: 0.001,
        offset: 0.0,
    },
    Unit {
        symbol: "Hz",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "kHz",
        scale: 1000.0,
        offset: 0.0,
    },
    Unit {
        symbol: "MHz",
        scale: 1.0e6,
        offset: 0.0,
    },
    Unit {
        symbol: "GHz",
        scale: 1.0e9,
        offset: 0.0,
    },
    Unit {
        symbol: "Pa",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "kPa",
        scale: 1000.0,
        offset: 0.0,
    },
    Unit {
        symbol: "MPa",
        scale: 1.0e6,
        offset: 0.0,
    },
    Unit {
        symbol: "K",
        scale: 1.0,
        offset: -273.15,
    },
    Unit {
        symbol: "degC",
        scale: 1.0,
        offset: 0.0,
    },
    Unit {
        symbol: "degF",
        scale: 5.0 / 9.0,
        offset: -32.0 * 5.0 / 9.0,
    },
    Unit {
        symbol: "%",
        scale: 0.01,
        offset: 0.0,
    },
    Unit {
        symbol: "1",
        scale: 1.0,
        offset: 0.0,
    },
];

/// Look up a unit by symbol.
///
/// # Example
///
/// ```
/// use crisol_core::data::parse_unit;
///
/// assert!(parse_unit("mV").is_some());
/// ```
pub fn parse(symbol: &str) -> Option<Unit> {
    UNITS.iter().copied().find(|unit| unit.symbol == symbol)
}

/// Convert `value` from one unit to another.
///
/// # Example
///
/// ```
/// use crisol_core::data::convert_unit;
///
/// assert_eq!(convert_unit(1.0, "m", "cm"), Some(100.0));
/// ```
pub fn convert(value: f64, from: &str, to: &str) -> Option<f64> {
    let from = parse(from)?;
    let to = parse(to)?;
    Some((value * from.scale + from.offset - to.offset) / to.scale)
}

/// Why a column cannot be converted.
///
/// # Example
///
/// ```
/// use crisol_core::data::UnitError;
///
/// let error = UnitError::UnknownUnit("parsec".to_owned());
/// assert!(error.to_string().contains("parsec"));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnitError {
    /// The unit symbol is unknown.
    UnknownUnit(String),
    /// The column stores text, booleans, or dates.
    NonNumericColumn(String),
}

impl std::fmt::Display for UnitError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownUnit(unit) => write!(formatter, "unknown unit `{unit}`"),
            Self::NonNumericColumn(name) => write!(formatter, "column `{name}` is not numeric"),
        }
    }
}

impl std::error::Error for UnitError {}

impl Column {
    /// Convert this numeric column to `unit`, preserving nulls and metadata.
    ///
    /// # Errors
    /// When either unit is unknown or the column is not numeric.
    pub fn converted(&self, unit: &str) -> Result<Self, UnitError> {
        let from = self
            .unit
            .as_deref()
            .ok_or_else(|| UnitError::UnknownUnit(String::new()))?;
        let target = parse(unit).ok_or_else(|| UnitError::UnknownUnit(unit.to_owned()))?;
        let source = parse(from).ok_or_else(|| UnitError::UnknownUnit(from.to_owned()))?;
        let values = match &self.values {
            ColumnValues::Float(values) => values
                .iter()
                .map(|value| (value * source.scale + source.offset - target.offset) / target.scale)
                .collect::<Vec<_>>(),
            ColumnValues::Int(values) => values
                .iter()
                .map(|value| (*value as f64 * source.scale + source.offset - target.offset) / target.scale)
                .collect::<Vec<_>>(),
            _ => return Err(UnitError::NonNumericColumn(self.name.clone())),
        };
        let validity = self.validity.clone().unwrap_or_else(|| vec![true; values.len()]);
        let column = Column::floats(self.name.clone(), values)
            .with_unit(unit)
            .with_validity(validity);
        Ok(column)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::Column;

    #[test]
    fn length_and_temperature_convert() {
        assert_eq!(convert(1.0, "m", "cm"), Some(100.0));
        assert!((convert(0.0, "degC", "K").unwrap_or_default() - 273.15).abs() < 1.0e-9);
        assert!((convert(32.0, "degF", "degC").unwrap_or_default()).abs() < 1.0e-9);
    }

    #[test]
    fn a_column_keeps_nulls_when_converted() {
        let column = Column::floats("v", vec![1.0, f64::NAN])
            .with_unit("V")
            .with_validity([true, false]);
        let converted = column.converted("mV").expect("convert");
        assert_eq!(converted.unit.as_deref(), Some("mV"));
        assert_eq!(converted.cell(0), crate::data::CellValue::Float(1000.0));
        assert!(converted.cell(1).is_null());
    }

    #[test]
    fn unknown_units_are_rejected() {
        let column = Column::ints("n", vec![1]).with_unit("parsec");
        assert!(matches!(column.converted("m"), Err(UnitError::UnknownUnit(_))));
        assert_eq!(convert(1.0, "parsec", "m"), None);
        assert_eq!(convert(1.0, "m", "parsec"), None);
        assert_eq!(parse("parsec"), None);
        let no_unit = Column::ints("n", vec![1]);
        assert!(matches!(no_unit.converted("m"), Err(UnitError::UnknownUnit(_))));
        let good = Column::ints("n", vec![1]).with_unit("m");
        assert!(matches!(good.converted("parsec"), Err(UnitError::UnknownUnit(_))));
        let text = Column::text("s", ["a"]).with_unit("m");
        assert!(matches!(text.converted("cm"), Err(UnitError::NonNumericColumn(_))));
    }

    #[test]
    fn integers_and_columns_without_validity_convert() {
        let column = Column::ints("n", vec![1, 2]).with_unit("m");
        let converted = column.converted("cm").expect("convert");
        assert_eq!(converted.cell(1), crate::data::CellValue::Float(200.0));
        assert!(converted.validity.is_none() || converted.validity.as_deref().is_some_and(|v| v.iter().all(|x| *x)));
    }
}