Skip to main content

ifc_properties/exact/unit/
from_si.rs

1//! SI input to the unit that applies (#487).
2//!
3//! A writer holding an SI value needs the value in the model's unit for the
4//! measure. IFC states no SI default: a measure without an explicit `Unit`
5//! takes the project's unit of its unit type, and a model that declares none
6//! is refused ([`crate::ExactUnitError::NoProjectUnit`]) rather than written
7//! in an assumed unit.
8
9use ifc_model::{EntityId, Model};
10
11use super::{exact_unit, resolve_unit};
12use crate::convert::{unit_conversion, ConversionUnit, UnitConversion, UnitConversionError};
13
14/// The conversion from an SI value to the unit that applies to
15/// `measure_type`: `explicit_unit` when stated, otherwise the project unit of
16/// the measure's unit type. A dimensionless measure converts by the identity.
17///
18/// SI means the coherent unit of the measure's dimensions (metre, kilogram,
19/// kelvin, radian ...). A project unit of `DEGREE_CELSIUS` converts
20/// affinely; units with another offset are refused (#110).
21///
22/// # Errors
23///
24/// [`UnitConversionError::OffsetUnit`] for an offset unit, and
25/// [`UnitConversionError::Resolve`] with the refusal of [`exact_unit`]: a
26/// project without a unit of the type, an unmapped or non-measure type, a
27/// unit of the wrong type, or an unresolvable unit.
28pub fn si_conversion(
29    model: &Model,
30    measure_type: &str,
31    explicit_unit: Option<EntityId>,
32) -> Result<UnitConversion, UnitConversionError> {
33    let exact = exact_unit(model, measure_type, explicit_unit)?;
34    let Some(unit) = exact.unit else {
35        return Ok(UnitConversion::IDENTITY);
36    };
37    let target = resolve_unit(model, unit)?;
38    unit_conversion(&ConversionUnit::coherent_si(target.dimensions), &target)
39}
40
41/// An SI `value` in the project unit of `measure_type`.
42///
43/// # Errors
44///
45/// [`UnitConversionError::NonFinite`] for NaN or infinity, otherwise as
46/// [`si_conversion`] without an explicit unit.
47pub fn si_to_project(
48    model: &Model,
49    measure_type: &str,
50    value: f64,
51) -> Result<f64, UnitConversionError> {
52    if !value.is_finite() {
53        return Err(UnitConversionError::NonFinite { value });
54    }
55    Ok(si_conversion(model, measure_type, None)?.apply(value))
56}