Skip to main content

ifc_properties/unit/
assignment.rs

1//! SI, conversion-based and derived units, and the project unit context.
2//!
3//! # Slots, verified against the IFC4 EXPRESS schema
4//!
5//! ```text
6//! IfcUnitAssignment        0 = Units
7//! IfcNamedUnit             0 = Dimensions   1 = UnitType
8//! IfcSIUnit                2 = Prefix       3 = Name
9//! IfcConversionBasedUnit   2 = Name         3 = ConversionFactor
10//! IfcConversionBasedUnitWithOffset          4 = ConversionOffset (IFC4)
11//! IfcMeasureWithUnit       0 = ValueComponent  1 = UnitComponent
12//! IfcDerivedUnit           0 = Elements     1 = UnitType  2 = UserDefinedType
13//! IfcDerivedUnitElement    0 = Unit         1 = Exponent
14//! IfcMonetaryUnit          0 = Currency     (IfcCurrencyEnum in IFC2X3,
15//!                                            IfcLabel from IFC4 on)
16//! ```
17//!
18//! `IfcSIUnit` inherits `Dimensions`/`UnitType` from `IfcNamedUnit`, so its
19//! own `Prefix` and `Name` start at slot 2. `IfcDerivedUnit` is NOT a
20//! `IfcNamedUnit`, so its slots start at 0 -- the two cannot share a reader.
21//!
22//! # Prefixes are exact
23//!
24//! `MILLI` is 1e-3 exactly as a decimal, and `f64` cannot hold it exactly.
25//! The factor is therefore returned as a power of ten and applied by the
26//! caller, so `mm -> m` is one multiplication rather than a chain of
27//! roundings.
28//!
29//! A prefix applies to the unit before its power: `MILLI SQUARE_METRE` is
30//! (10⁻³ m)², so its scale is 1e-6, not 1e-3 (ISO 80000-1).
31
32use std::sync::Arc;
33
34use ifc_model::{EntityId, Model, Value};
35
36const NAMED_UNIT_TYPE: usize = 1;
37const SI_PREFIX: usize = 2;
38const SI_NAME: usize = 3;
39const CONVERSION_NAME: usize = 2;
40const CONVERSION_FACTOR: usize = 3;
41const CONVERSION_OFFSET: usize = 4;
42const MEASURE_VALUE: usize = 0;
43const MEASURE_UNIT: usize = 1;
44const DERIVED_ELEMENTS: usize = 0;
45const DERIVED_TYPE: usize = 1;
46const DERIVED_ELEMENT_UNIT: usize = 0;
47const DERIVED_ELEMENT_EXPONENT: usize = 1;
48const MONETARY_CURRENCY: usize = 0;
49const ASSIGNMENT_UNITS: usize = 0;
50
51/// A unit as the file states it.
52#[derive(Debug, Clone, PartialEq)]
53pub enum UnitKind {
54    /// `IfcSIUnit`: a base SI unit with an optional decimal prefix.
55    Si {
56        /// `IfcUnitEnum`, e.g. `LENGTHUNIT`.
57        unit_type: Arc<str>,
58        /// `IfcSIUnitName`, e.g. `METRE`.
59        name: Arc<str>,
60        /// `IfcSIPrefix`, e.g. `MILLI`. `None` means unprefixed.
61        prefix: Option<Arc<str>>,
62        /// Decimal exponent of the prefix: `MILLI` is `Some(-3)`, absent is
63        /// `Some(0)`, and a prefix that is not an `IfcSIPrefix` is `None`.
64        ///
65        /// Exposed as an exponent rather than a factor so callers can apply
66        /// it exactly instead of multiplying by a rounded 0.001. An unknown
67        /// prefix is not read as "unprefixed": that would silently rescale
68        /// every value in the unit.
69        prefix_exponent: Option<i32>,
70    },
71    /// `IfcConversionBasedUnit`: a named unit defined by a factor.
72    Conversion {
73        /// `IfcUnitEnum`.
74        unit_type: Arc<str>,
75        /// The unit's name, e.g. `inch`.
76        name: Option<Arc<str>>,
77        /// The numeric conversion factor, when readable.
78        factor: Option<f64>,
79        /// The unit the factor is expressed in.
80        factor_unit: Option<EntityId>,
81        /// `IfcConversionBasedUnitWithOffset.ConversionOffset`, as stated.
82        ///
83        /// `None` for a plain conversion-based unit. Kept raw: IFC4's own
84        /// documentation contradicts itself on which direction the offset
85        /// applies, so this crate does not apply it.
86        offset: Option<f64>,
87    },
88    /// `IfcDerivedUnit`: a product of powers of other units.
89    Derived {
90        /// `IfcDerivedUnitEnum`, e.g. `VOLUMETRICFLOWRATEUNIT`.
91        unit_type: Arc<str>,
92        /// The (unit, exponent) elements.
93        elements: Vec<(EntityId, i64)>,
94    },
95    /// `IfcMonetaryUnit`: a currency, with no dimension.
96    Monetary {
97        /// ISO currency code as stated: the `IfcCurrencyEnum` token in
98        /// IFC2X3, the `IfcLabel` text from IFC4 on.
99        currency: Option<Arc<str>>,
100    },
101    /// `IfcContextDependentUnit` or another named unit form.
102    ContextDependent {
103        /// `IfcUnitEnum`.
104        unit_type: Arc<str>,
105    },
106}
107
108impl UnitKind {
109    /// The `IfcUnitEnum` this unit declares, when it has one.
110    ///
111    /// `IfcMonetaryUnit` has none: it is not an `IfcNamedUnit`.
112    pub fn unit_type(&self) -> Option<&str> {
113        match self {
114            Self::Si { unit_type, .. }
115            | Self::Conversion { unit_type, .. }
116            | Self::ContextDependent { unit_type } => Some(unit_type),
117            Self::Derived { unit_type, .. } => Some(unit_type),
118            Self::Monetary { .. } => None,
119        }
120    }
121
122    /// Multiplier converting a value in this unit to the unprefixed SI unit.
123    ///
124    /// The prefix is raised to the unit's power: `MILLI SQUARE_METRE` gives
125    /// 1e-6 and `MILLI CUBIC_METRE` 1e-9. `None` for an unknown prefix.
126    ///
127    /// Only defined for `Si`: a conversion-based unit needs its factor unit
128    /// resolved too, and a derived unit needs its elements combined, so
129    /// neither can answer honestly on its own. [`crate::exact_unit`] resolves
130    /// all three to the SI base unit.
131    pub fn si_scale(&self) -> Option<f64> {
132        match self {
133            Self::Si {
134                name,
135                prefix_exponent,
136                ..
137            } => prefix_exponent.map(|exponent| 10f64.powi(exponent * super::si::name_power(name))),
138            _ => None,
139        }
140    }
141}
142
143/// The decimal exponent of an `IfcSIPrefix`.
144///
145/// Returns `None` for an unrecognised constant rather than assuming 0: a
146/// silent 1.0 would misreport every value using it.
147pub fn prefix_exponent(prefix: &str) -> Option<i32> {
148    Some(match prefix {
149        "EXA" => 18,
150        "PETA" => 15,
151        "TERA" => 12,
152        "GIGA" => 9,
153        "MEGA" => 6,
154        "KILO" => 3,
155        "HECTO" => 2,
156        "DECA" => 1,
157        "DECI" => -1,
158        "CENTI" => -2,
159        "MILLI" => -3,
160        "MICRO" => -6,
161        "NANO" => -9,
162        "PICO" => -12,
163        "FEMTO" => -15,
164        "ATTO" => -18,
165        _ => return None,
166    })
167}
168
169/// Read one unit by id.
170pub fn unit(model: &Model, id: EntityId) -> Option<UnitKind> {
171    let entity = model.get(id)?;
172    let ty = entity.type_name.to_ascii_uppercase();
173    match ty.as_str() {
174        "IFCSIUNIT" => {
175            let prefix = entity.attributes.get(SI_PREFIX).and_then(enum_text);
176            Some(UnitKind::Si {
177                unit_type: entity
178                    .attributes
179                    .get(NAMED_UNIT_TYPE)
180                    .and_then(enum_text)
181                    .unwrap_or_else(|| "".into()),
182                name: entity
183                    .attributes
184                    .get(SI_NAME)
185                    .and_then(enum_text)
186                    .unwrap_or_else(|| "".into()),
187                prefix_exponent: prefix.as_deref().map_or(Some(0), prefix_exponent),
188                prefix,
189            })
190        }
191        "IFCCONVERSIONBASEDUNIT" | "IFCCONVERSIONBASEDUNITWITHOFFSET" => {
192            let factor_entity = entity.attributes.get(CONVERSION_FACTOR).and_then(one_ref);
193            let (factor, factor_unit) = match factor_entity.and_then(|f| model.get(f)) {
194                Some(measure) => (
195                    measure
196                        .attributes
197                        .get(MEASURE_VALUE)
198                        .and_then(|v| v.unwrap_typed().as_f64()),
199                    measure.attributes.get(MEASURE_UNIT).and_then(one_ref),
200                ),
201                None => (None, None),
202            };
203            Some(UnitKind::Conversion {
204                unit_type: entity
205                    .attributes
206                    .get(NAMED_UNIT_TYPE)
207                    .and_then(enum_text)
208                    .unwrap_or_else(|| "".into()),
209                name: entity.attributes.get(CONVERSION_NAME).and_then(text),
210                factor,
211                factor_unit,
212                offset: if ty == "IFCCONVERSIONBASEDUNITWITHOFFSET" {
213                    entity
214                        .attributes
215                        .get(CONVERSION_OFFSET)
216                        .and_then(|v| v.unwrap_typed().as_f64())
217                } else {
218                    None
219                },
220            })
221        }
222        "IFCDERIVEDUNIT" => {
223            let elements = entity
224                .attributes
225                .get(DERIVED_ELEMENTS)
226                .and_then(refs)
227                .unwrap_or_default()
228                .into_iter()
229                .filter_map(|e| {
230                    let element = model.get(e)?;
231                    let unit = element
232                        .attributes
233                        .get(DERIVED_ELEMENT_UNIT)
234                        .and_then(one_ref)?;
235                    let exponent = match element
236                        .attributes
237                        .get(DERIVED_ELEMENT_EXPONENT)?
238                        .unwrap_typed()
239                    {
240                        Value::Integer(v) => *v,
241                        Value::Real(v) => *v as i64,
242                        _ => return None,
243                    };
244                    Some((unit, exponent))
245                })
246                .collect();
247            Some(UnitKind::Derived {
248                unit_type: entity
249                    .attributes
250                    .get(DERIVED_TYPE)
251                    .and_then(enum_text)
252                    .unwrap_or_else(|| "".into()),
253                elements,
254            })
255        }
256        "IFCMONETARYUNIT" => Some(UnitKind::Monetary {
257            // IFC2X3 declares `IfcCurrencyEnum` (`.EUR.`), IFC4 on an
258            // `IfcLabel` (`'EUR'`); both state the same currency.
259            currency: entity.attributes.get(MONETARY_CURRENCY).and_then(enum_text),
260        }),
261        "IFCCONTEXTDEPENDENTUNIT" => Some(UnitKind::ContextDependent {
262            unit_type: entity
263                .attributes
264                .get(NAMED_UNIT_TYPE)
265                .and_then(enum_text)
266                .unwrap_or_else(|| "".into()),
267        }),
268        _ => None,
269    }
270}
271
272/// The `IfcUnitEnum` a unit declares, without building the whole value.
273///
274/// Used by the quantity reader to check `WR21` cheaply.
275pub fn unit_type(model: &Model, id: EntityId) -> Option<Arc<str>> {
276    let entity = model.get(id)?;
277    let ty = entity.type_name.to_ascii_uppercase();
278    let slot = if ty == "IFCDERIVEDUNIT" {
279        DERIVED_TYPE
280    } else {
281        NAMED_UNIT_TYPE
282    };
283    entity.attributes.get(slot).and_then(enum_text)
284}
285
286/// Project default units, from `IfcProject.UnitsInContext`.
287///
288/// Returned in file order. These are the units a measure without its own
289/// unit is expressed in, so a consumer needs them to interpret bare values.
290pub fn project_units(model: &Model) -> Vec<(EntityId, UnitKind)> {
291    let mut out = Vec::new();
292    let mut ids: Vec<_> = model.ids_of_type("IFCUNITASSIGNMENT").to_vec();
293    ids.sort_unstable();
294    for id in ids {
295        let Some(assignment) = model.get(id) else {
296            continue;
297        };
298        for unit_id in assignment
299            .attributes
300            .get(ASSIGNMENT_UNITS)
301            .and_then(refs)
302            .unwrap_or_default()
303        {
304            if let Some(kind) = unit(model, unit_id) {
305                out.push((unit_id, kind));
306            }
307        }
308    }
309    out
310}
311
312/// The project default unit for a given `IfcUnitEnum`.
313///
314/// `IfcCorrectUnitAssignment` makes at most one named unit per type, so the
315/// first match is the only match in a well-formed file. In a malformed one
316/// this permissive view still returns the first; [`crate::exact_unit`]
317/// refuses the duplicate instead.
318pub fn project_unit_for(model: &Model, unit_type_name: &str) -> Option<(EntityId, UnitKind)> {
319    project_units(model)
320        .into_iter()
321        .find(|(_, kind)| kind.unit_type() == Some(unit_type_name))
322}
323
324fn text(value: &Value) -> Option<Arc<str>> {
325    match value.unwrap_typed() {
326        Value::Text(t) => Some(t.clone()),
327        _ => None,
328    }
329}
330
331fn enum_text(value: &Value) -> Option<Arc<str>> {
332    match value.unwrap_typed() {
333        Value::Enum(t) | Value::Text(t) => Some(t.clone()),
334        _ => None,
335    }
336}
337
338fn one_ref(value: &Value) -> Option<EntityId> {
339    match value.unwrap_typed() {
340        Value::Ref(id) => Some(*id),
341        _ => None,
342    }
343}
344
345fn refs(value: &Value) -> Option<Vec<EntityId>> {
346    match value {
347        Value::List(items) => Some(items.iter().filter_map(one_ref).collect()),
348        _ => None,
349    }
350}