ifc_properties/exact/unit.rs
1//! Exact, fail-closed resolution of a measure's effective unit.
2//!
3//! A value's effective unit is its explicit `Unit` if stated, otherwise the
4//! project default from `IfcProject.UnitsInContext`. This module resolves
5//! either to an exact conversion into SI base units, or refuses. Every table
6//! it reads belongs to the release `FILE_SCHEMA` declares.
7//!
8//! ## Lenient models (#615)
9//!
10//! Unit resolution does not refuse a model for having reader diagnostics. It
11//! refuses damage it reaches: a record it reads that the reader skipped is
12//! `MissingReference`; one the reader reported by id (a duplicate id, or a skipped record whose id a kept record holds) is
13//! [`ExactUnitError::DamagedRecord`]; no `IfcProject` after a skipped record
14//! is `IncompleteModel`, not `NoProject`, because the skipped record may have
15//! been the project. A REAL read without its decimal point and a dangling
16//! reference elsewhere change no unit record and are ignored. A diagnostic of
17//! a kind not classified here refuses the model. The classification is
18//! [`ifc_model::RecordDamage`], shared with `ifc-geometry` (#684). Property resolution and
19//! `exact_schema` still refuse any diagnostic: a skipped record may have been
20//! a relationship.
21//!
22//! One surviving `IfcProject` is trusted as the project. Every release
23//! constrains a file to one (`IfcSingleProjectInstance`: IFC2X3_TC1.exp:9563,
24//! IFC4.exp:12392, IFC4X3_ADD2.exp:13977), so a second project the reader
25//! skipped is not detected.
26//!
27//! ## Internal split
28//!
29//! - `damage.rs`: [`ifc_model::RecordDamage`]'s answers as this module's
30//! errors (#615, #684).
31//! - `resolve.rs`: one unit entity to its SI scale and dimensions, following
32//! conversion chains and derived elements under a depth budget.
33//! - `from_si.rs`: SI input to the unit that applies (#487).
34
35mod damage;
36mod from_si;
37mod resolve;
38
39use std::{fmt, sync::Arc};
40
41use ifc_model::{EntityId, Model, Value};
42use ifc_schema::{for_version, SchemaVersion};
43
44use super::measure::{measure_unit, MeasureUnit};
45use super::refs::{ref_at, refs_at};
46use super::release::{bind_release, Release};
47use super::value::select_accepts_entity;
48use super::ExactPropertyError;
49use damage::Damage;
50use resolve::{declared_unit_type, Resolver};
51
52pub use from_si::{si_conversion, si_to_project};
53
54use crate::convert::{normalise_decimal, unit_conversion, ConversionUnit, UnitConversionError};
55
56/// A measure's effective unit, resolved to SI base units.
57///
58/// `value_si = value * scale + offset`.
59#[derive(Debug, Clone, Copy, PartialEq)]
60#[non_exhaustive]
61pub struct ExactUnit {
62 /// The unit entity that applies, or `None` for a dimensionless measure
63 /// (`IFCCOUNTMEASURE`, `IFCRATIOMEASURE`, ...) that takes no unit.
64 pub unit: Option<EntityId>,
65 /// Whether `unit` is the project default rather than an explicit unit.
66 pub from_project: bool,
67 /// SI dimensional exponents `[L, M, T, I, Θ, N, J]`.
68 pub dimensions: [i32; 7],
69 /// Multiplier into the SI base unit (kilogram for mass, kelvin for
70 /// temperature, radian for plane angle).
71 pub scale: f64,
72 /// Added after scaling; nonzero only for `DEGREE_CELSIUS`.
73 pub offset: f64,
74}
75
76/// Why a measure's unit cannot be resolved exactly.
77#[derive(Debug, Clone, PartialEq, Eq)]
78#[non_exhaustive]
79pub enum ExactUnitError {
80 /// The model, or a record the resolution traversed, failed a check that
81 /// [`crate::exact_property`] applies the same way: header, missing
82 /// references, slot arity, malformed aggregates, or a construct the
83 /// declared release does not define. Reader diagnostics refuse only as
84 /// `IncompleteModel` when a diagnostic is of an unclassified kind, a
85 /// duplicate id the reader could not attribute, a skipped record without
86 /// an id, or when no `IfcProject` is left after a skipped record (#615).
87 Structure(ExactPropertyError),
88 /// The declared release defines no type of this name.
89 MeasureNotInSchema {
90 /// The measure type as requested.
91 measure_type: Arc<str>,
92 /// The release the header declares.
93 schema: SchemaVersion,
94 },
95 /// The type is not a measure (`IFCLABEL`, `IFCBOOLEAN`, ...), so no unit
96 /// can apply to it.
97 NotAMeasure {
98 /// The type as requested.
99 measure_type: Arc<str>,
100 },
101 /// A measure this resolver has no verified unit correspondence for,
102 /// such as a monetary, descriptive, logarithmic or list-valued measure.
103 UnmappedMeasureType {
104 /// The measure type as requested.
105 measure_type: Arc<str>,
106 },
107 /// A dimensionless measure was given an explicit unit.
108 UnexpectedUnit {
109 /// The explicit unit.
110 unit: EntityId,
111 },
112 /// The reader reported a record this resolution reads (#615): the file
113 /// defines the id more than once and the model keeps one of the records,
114 /// or a lenient read skipped a record with this id while another record
115 /// holds it. The record the model holds cannot be shown to be the one the
116 /// file meant.
117 DamagedRecord {
118 /// The record the resolution reached.
119 entity: EntityId,
120 /// Position in `Model::diagnostics()` of the first diagnostic naming
121 /// it.
122 diagnostic: usize,
123 },
124 /// The model has no `IfcProject` to take a default unit from.
125 NoProject,
126 /// The model has several `IfcProject`s, so no one project default applies.
127 /// A single project is trusted: every release requires one
128 /// (`IfcSingleProjectInstance`), so a skipped second project goes
129 /// undetected.
130 MultipleProjects {
131 /// The first project.
132 first: EntityId,
133 /// The second project.
134 second: EntityId,
135 },
136 /// No unit is stated and the project assigns none of the needed type.
137 NoProjectUnit {
138 /// The unit type the measure needs.
139 unit_type: Arc<str>,
140 },
141 /// The project assigns two units of the needed type, which
142 /// `IfcCorrectUnitAssignment` forbids; neither is "the" project unit.
143 DuplicateProjectUnit {
144 /// The unit type assigned twice.
145 unit_type: Arc<str>,
146 /// The first unit of that type.
147 first: EntityId,
148 /// The second unit of that type.
149 second: EntityId,
150 },
151 /// The entity is not a unit this resolver converts: not an `IfcUnit` at
152 /// all, or a context-dependent or monetary unit with no SI conversion.
153 UnsupportedUnit {
154 /// The rejected unit.
155 unit: EntityId,
156 /// Its IFC type name.
157 type_name: Arc<str>,
158 },
159 /// A unit attribute that must be an enumeration constant, a positive
160 /// number or a typed value is not.
161 MalformedUnit {
162 /// The unit entity or one of its parts.
163 entity: EntityId,
164 /// The offending attribute.
165 attribute: &'static str,
166 },
167 /// An `IfcSIUnit` prefix that is not an `IfcSIPrefix` constant.
168 UnknownPrefix {
169 /// The unit.
170 unit: EntityId,
171 /// The prefix as written.
172 prefix: Arc<str>,
173 },
174 /// An `IfcSIUnit` name that the release's `IfcDimensionsForSiUnit` does
175 /// not list, or a unit type its `IfcCorrectDimensions` does not list
176 /// (including `USERDEFINED`).
177 UnknownUnitName {
178 /// The unit.
179 unit: EntityId,
180 /// The name or unit type as written.
181 name: Arc<str>,
182 },
183 /// The unit declares another unit type than the measure needs.
184 UnitTypeMismatch {
185 /// The unit.
186 unit: EntityId,
187 /// The unit type the measure needs.
188 expected: Arc<str>,
189 /// The unit type the unit declares.
190 found: Arc<str>,
191 },
192 /// A unit's dimensions contradict its declared unit type, its declared
193 /// `Dimensions`, or the unit its conversion factor is expressed in.
194 DimensionMismatch {
195 /// The unit.
196 unit: EntityId,
197 /// The dimensions required.
198 expected: [i32; 7],
199 /// The dimensions found.
200 found: [i32; 7],
201 },
202 /// An offset unit: `IfcConversionBasedUnitWithOffset`, or a unit with an
203 /// offset used where only a scale can apply (inside a derived unit or as
204 /// a conversion factor). IFC4's prose on where the offset applies
205 /// contradicts its own Fahrenheit example (factor 1.8,
206 /// `f = k * 1.8 - 459.67`), so the offset is not applied until
207 /// buildingSMART settles it (IFC4.x-development#1193; tracked in #110).
208 UnsupportedOffset {
209 /// The unit carrying the offset.
210 unit: EntityId,
211 },
212 /// Conversion-based units form a cycle.
213 CyclicConversion {
214 /// The units on the cycle, closing on the first.
215 cycle: Vec<EntityId>,
216 },
217 /// The chain of conversion and derived units is deeper than the budget.
218 ConversionChainTooDeep {
219 /// The unit at which the budget ran out.
220 unit: EntityId,
221 /// The depth budget.
222 max_depth: usize,
223 },
224}
225
226impl From<ExactPropertyError> for ExactUnitError {
227 fn from(error: ExactPropertyError) -> Self {
228 Self::Structure(error)
229 }
230}
231
232impl fmt::Display for ExactUnitError {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 write!(f, "exact IFC unit resolution failed: {self:?}")
235 }
236}
237
238impl std::error::Error for ExactUnitError {}
239
240/// Resolve the effective unit of a measure to an exact SI conversion.
241///
242/// `measure_type` is the value's declared type, e.g. `IFCAREAMEASURE`;
243/// `explicit_unit` is `IfcPropertySingleValue.Unit` when stated. Without an
244/// explicit unit the project default of the needed type applies. The model
245/// binds to the release its `FILE_SCHEMA` declares, IFC2X3, IFC4 or IFC4X3,
246/// and every table is that release's.
247///
248/// # Errors
249///
250/// Any [`ExactUnitError`]: the answer is refused whenever the unit is
251/// missing, ambiguous, inconsistent, cyclic, or not convertible exactly, or
252/// when the reader reported a record the resolution reads
253/// ([`ExactUnitError::DamagedRecord`]).
254pub fn exact_unit(
255 model: &Model,
256 measure_type: &str,
257 explicit_unit: Option<EntityId>,
258) -> Result<ExactUnit, ExactUnitError> {
259 let release = bind_release(model)?;
260 let target = measure_unit(release, measure_type)?;
261 let Some(expected) = target.unit_type().cloned() else {
262 if let Some(unit) = explicit_unit {
263 return Err(ExactUnitError::UnexpectedUnit { unit });
264 }
265 return Ok(ExactUnit {
266 unit: None,
267 from_project: false,
268 dimensions: [0; 7],
269 scale: 1.0,
270 offset: 0.0,
271 });
272 };
273 let damage = Damage::of(model)?;
274 let (unit, from_project) = match explicit_unit {
275 Some(unit) => (unit, false),
276 None => (project_unit(model, release, &damage, &expected)?, true),
277 };
278 let resolved = Resolver::new(model, release, &damage).resolve(unit)?;
279 if !resolved.unit_type.eq_ignore_ascii_case(&expected) {
280 return Err(ExactUnitError::UnitTypeMismatch {
281 unit,
282 expected,
283 found: resolved.unit_type,
284 });
285 }
286 damage.settle(ExactUnit {
287 unit: Some(unit),
288 from_project,
289 dimensions: resolved.dimensions,
290 scale: resolved.scale,
291 offset: resolved.offset,
292 })
293}
294
295/// The one unit of `unit_type` in the single project's unit assignment.
296fn project_unit(
297 model: &Model,
298 release: Release,
299 damage: &Damage,
300 unit_type: &Arc<str>,
301) -> Result<EntityId, ExactUnitError> {
302 let project = match model.ids_of_type("IFCPROJECT") {
303 [] => return Err(damage.no_project()),
304 [project] => *project,
305 [first, second, ..] => {
306 return Err(ExactUnitError::MultipleProjects {
307 first: *first,
308 second: *second,
309 })
310 }
311 };
312 let entity = model.get(project).expect("type index is current");
313 damage.check(project)?;
314 release.require_exact_slots(project, entity)?;
315 let slot = release
316 .schema
317 .attribute_names("IFCPROJECT")
318 .iter()
319 .position(|name| name.eq_ignore_ascii_case("UnitsInContext"))
320 .expect("IfcProject declares UnitsInContext in every bundled release");
321 let no_unit = || ExactUnitError::NoProjectUnit {
322 unit_type: unit_type.clone(),
323 };
324 // Optional in IFC4, mandatory in IFC2X3; a `$` states no units either way.
325 if matches!(entity.attributes.get(slot), Some(ifc_model::Value::Null)) {
326 return Err(no_unit());
327 }
328 let assignment = ref_at(project, entity.attributes.get(slot), "UnitsInContext")?;
329 let assignment_entity = model
330 .get(assignment)
331 .ok_or(ExactPropertyError::MissingReference {
332 from: project,
333 to: assignment,
334 })?;
335 damage.check(assignment)?;
336 release.require_exact_slots(assignment, assignment_entity)?;
337 if !assignment_entity.is_type("IFCUNITASSIGNMENT") {
338 return Err(ExactUnitError::UnsupportedUnit {
339 unit: assignment,
340 type_name: assignment_entity.type_name.clone(),
341 });
342 }
343 let units = refs_at(assignment, assignment_entity.attributes.first(), "Units")?;
344 let mut found = None;
345 for unit in units {
346 let unit_entity = model
347 .get(unit)
348 .ok_or(ExactPropertyError::MissingReference {
349 from: assignment,
350 to: unit,
351 })?;
352 damage.check(unit)?;
353 release.require_exact_slots(unit, unit_entity)?;
354 if !select_accepts_entity(release.schema, "IFCUNIT", &unit_entity.type_name) {
355 return Err(ExactUnitError::UnsupportedUnit {
356 unit,
357 type_name: unit_entity.type_name.clone(),
358 });
359 }
360 let declared = declared_unit_type(release, unit, unit_entity)?;
361 if declared
362 .as_deref()
363 .is_some_and(|declared| declared.eq_ignore_ascii_case(unit_type))
364 {
365 if let Some(first) = found.replace(unit) {
366 return Err(ExactUnitError::DuplicateProjectUnit {
367 unit_type: unit_type.clone(),
368 first,
369 second: unit,
370 });
371 }
372 }
373 }
374 found.ok_or_else(no_unit)
375}
376
377/// The one unit of `unit_type` (an `IfcUnitEnum` or `IfcDerivedUnitEnum`
378/// constant such as `LENGTHUNIT`) the single project assigns, unresolved.
379///
380/// # Errors
381///
382/// [`ExactUnitError::NoProject`], [`ExactUnitError::MultipleProjects`],
383/// [`ExactUnitError::NoProjectUnit`] when the assignment has none of that
384/// type, [`ExactUnitError::DuplicateProjectUnit`],
385/// [`ExactUnitError::DamagedRecord`], and the structural refusals of
386/// [`exact_unit`].
387pub fn exact_project_unit(model: &Model, unit_type: &str) -> Result<EntityId, ExactUnitError> {
388 let release = bind_release(model)?;
389 let damage = Damage::of(model)?;
390 let unit = project_unit(
391 model,
392 release,
393 &damage,
394 &Arc::from(unit_type.to_ascii_uppercase()),
395 )?;
396 damage.settle(unit)
397}
398
399/// What unit a measure type takes in a release: none, a named unit of an
400/// `IfcUnitEnum` type, or a derived unit of an `IfcDerivedUnitEnum` type.
401#[derive(Debug, Clone, PartialEq, Eq)]
402#[non_exhaustive]
403pub enum MeasureUnitType {
404 /// A dimensionless measure (`IfcRatioMeasure`, `IfcCountMeasure` ...).
405 Dimensionless,
406 /// A named unit of this `IfcUnitEnum` constant: `IfcLengthMeasure`
407 /// and `IfcPositiveLengthMeasure` take a `LENGTHUNIT`.
408 Named(Arc<str>),
409 /// A derived unit of this `IfcDerivedUnitEnum` constant.
410 Derived(Arc<str>),
411}
412
413/// The unit a measure type takes in `schema`, derived from the release's
414/// own tables as [`exact_unit`] derives it (`IfcAreaMeasure` takes an
415/// `AREAUNIT`, `IfcNonNegativeLengthMeasure` a `LENGTHUNIT`).
416///
417/// # Errors
418///
419/// [`ExactUnitError::Structure`] with `UnsupportedSchema` for a release
420/// the exact resolver does not bind (IFC4X1, IFC4X2) or the build leaves
421/// out; [`ExactUnitError::MeasureNotInSchema`],
422/// [`ExactUnitError::NotAMeasure`] and
423/// [`ExactUnitError::UnmappedMeasureType`] as [`exact_unit`] refuses them.
424pub fn measure_unit_type(
425 schema: SchemaVersion,
426 measure_type: &str,
427) -> Result<MeasureUnitType, ExactUnitError> {
428 let unsupported = || {
429 ExactUnitError::Structure(ExactPropertyError::UnsupportedSchema {
430 schema: format!("{schema:?}"),
431 })
432 };
433 if !matches!(
434 schema,
435 SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3
436 ) {
437 return Err(unsupported());
438 }
439 let release = Release {
440 version: schema,
441 schema: for_version(schema).map_err(|_| unsupported())?,
442 };
443 Ok(match measure_unit(release, measure_type)? {
444 MeasureUnit::Dimensionless => MeasureUnitType::Dimensionless,
445 MeasureUnit::Named(unit_type) => MeasureUnitType::Named(unit_type),
446 MeasureUnit::Derived(unit_type) => MeasureUnitType::Derived(unit_type),
447 })
448}
449
450/// A model's unit entity reduced to a [`ConversionUnit`] (#469): an
451/// `IfcSIUnit` with its prefix, an `IfcConversionBasedUnit` through its
452/// `ConversionFactor` chain, or an `IfcDerivedUnit` by its elements'
453/// exponents, resolved exactly against the release the header declares.
454///
455/// # Errors
456///
457/// [`UnitConversionError::MonetaryUnit`],
458/// [`UnitConversionError::ContextDependentUnit`],
459/// [`UnitConversionError::OffsetUnit`] for an
460/// `IfcConversionBasedUnitWithOffset` (#110), and
461/// [`UnitConversionError::Resolve`] for every other refusal of the exact
462/// resolver (missing, malformed, cyclic or reader-damaged units, an unknown
463/// prefix ...).
464pub fn resolve_unit(model: &Model, unit: EntityId) -> Result<ConversionUnit, UnitConversionError> {
465 let release = bind_release(model).map_err(ExactUnitError::from)?;
466 let damage = Damage::of(model)?;
467 let entity = model.get(unit).ok_or(ExactUnitError::Structure(
468 ExactPropertyError::MissingReference {
469 from: unit,
470 to: unit,
471 },
472 ))?;
473 damage.check(unit)?;
474 let is_a = |ancestor| release.schema.is_a(&entity.type_name, ancestor);
475 if is_a("IFCMONETARYUNIT") {
476 return Err(UnitConversionError::MonetaryUnit { unit });
477 }
478 if is_a("IFCCONTEXTDEPENDENTUNIT") {
479 return Err(UnitConversionError::ContextDependentUnit { unit });
480 }
481 let resolved = Resolver::new(model, release, &damage).resolve(unit)?;
482 let (mantissa, decimal_exponent) =
483 normalise_decimal(resolved.mantissa, resolved.decimal_exponent);
484 Ok(damage.settle(ConversionUnit {
485 name: unit_label(model, unit).into(),
486 unit_type: Some(resolved.unit_type),
487 dimensions: resolved.dimensions,
488 mantissa,
489 decimal_exponent,
490 offset: resolved.offset,
491 })?)
492}
493
494/// Convert `value` from one of the model's units to another.
495///
496/// # Errors
497///
498/// As [`resolve_unit`] for either unit, and as
499/// [`crate::unit_conversion`].
500pub fn convert_between(
501 model: &Model,
502 value: f64,
503 from: EntityId,
504 to: EntityId,
505) -> Result<f64, UnitConversionError> {
506 if !value.is_finite() {
507 return Err(UnitConversionError::NonFinite { value });
508 }
509 let from = resolve_unit(model, from)?;
510 let to = resolve_unit(model, to)?;
511 Ok(unit_conversion(&from, &to)?.apply(value))
512}
513
514/// `MILLI METRE` for an SI unit, the `Name` of a conversion-based unit,
515/// otherwise `#id TYPE`.
516fn unit_label(model: &Model, unit: EntityId) -> String {
517 let Some(entity) = model.get(unit) else {
518 return format!("#{}", unit.0);
519 };
520 if entity.is_type("IFCSIUNIT") {
521 if let (Some(prefix), Some(Value::Enum(name))) =
522 (entity.attributes.get(2), entity.attributes.get(3))
523 {
524 return match prefix {
525 Value::Enum(prefix) => format!("{prefix} {name}"),
526 _ => name.to_string(),
527 };
528 }
529 }
530 if entity.type_name.starts_with("IFCCONVERSIONBASEDUNIT") {
531 if let Some(Value::Text(name)) = entity.attributes.get(2) {
532 return name.to_string();
533 }
534 }
535 format!("#{} {}", unit.0, entity.type_name)
536}