Skip to main content

openbim_ifc_binding_core/
units.rs

1//! Unit conversion and a model's length unit (feature `properties`, #469).
2//!
3//! A unit is named as text, as `ifc::properties::ConversionUnit::parse`
4//! reads it: an SI unit with its prefix written before it (`METRE`,
5//! `MILLIMETRE`, `MILLI METRE`, `SQUARE_MILLIMETRE`, `KILOGRAM`; `METER`
6//! spellings accepted), or a named conversion-based unit of IFC4 Table 673
7//! with exact factors (`inch`, `foot`, `yard`, `mile`, `square foot`,
8//! `gallon US`, `pound`, `degree` ...) or `US survey foot`.
9//!
10//! - [`convert_unit`] converts a value between two named units;
11//!   [`IfcModel::convert_unit_value`] between two unit entities of the
12//!   model (an `IfcSIUnit`, `IfcConversionBasedUnit` or `IfcDerivedUnit`).
13//! - [`format_length`] writes a length as decimal text in a unit, or as
14//!   feet and inches with fractions.
15//! - [`IfcModel::convert_length_unit`] rescales every length-dimensioned
16//!   value of the model to a new project length unit as one checked
17//!   transaction (the facade's `convert_length_unit`), or with `dry_run`
18//!   only reports. Its [`LengthUnitReport`] lists the rescaled attributes,
19//!   the values kept with the reason, and the units written and removed.
20//!
21//! Refusals: `invalid-value` for text that names no unit, an unknown
22//! prefix, a target that is not a length unit, or a bad format;
23//! `type-mismatch` for units of different dimensions; `unsupported` for a
24//! monetary or context-dependent unit, a unit with an offset (degree
25//! Fahrenheit, `IfcConversionBasedUnitWithOffset`: not applied until #110
26//! is settled), and values the conversion cannot carry (each named in the
27//! detail); `invalid-model` when the project length unit cannot be
28//! resolved; `unsupported-schema` for a release other than IFC2X3, IFC4 or
29//! IFC4X3; `missing-entity` for a unit id the model lacks;
30//! `feature-disabled` without `properties`.
31
32use crate::record::{Field, Record, ToRecord};
33use crate::{BindingError, IfcModel};
34
35/// What [`IfcModel::convert_length_unit`] does beyond the length unit.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct LengthUnitOptions {
39    /// Replace the area and volume units by the square and cube of the new
40    /// length unit, rescaling their values (default `true`).
41    pub area_and_volume: bool,
42    /// Remove replaced units nothing else uses (default `true`).
43    pub remove_replaced_units: bool,
44    /// Report what would change without changing the model.
45    pub dry_run: bool,
46}
47
48impl Default for LengthUnitOptions {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl LengthUnitOptions {
55    /// The defaults: areas and volumes follow, replaced units are removed,
56    /// applied.
57    #[must_use]
58    pub const fn new() -> Self {
59        Self {
60            area_and_volume: true,
61            remove_replaced_units: true,
62            dry_run: false,
63        }
64    }
65}
66
67/// Values of one attribute of one entity type that were rescaled.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ConvertedValues {
70    /// The entity type, upper case.
71    pub entity_type: String,
72    /// The attribute.
73    pub attribute: String,
74    /// `length`, `area`, `volume`, `inverse-length`, `inverse-area` or
75    /// `map-scale`.
76    pub kind: String,
77    /// Entities with a value rescaled here.
78    pub entities: usize,
79    /// Numbers rescaled.
80    pub values: usize,
81}
82
83/// Length-like values of one attribute left as they are.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct KeptValues {
86    /// The entity type, upper case.
87    pub entity_type: String,
88    /// The attribute.
89    pub attribute: String,
90    /// `explicit-unit`, `map-unit`, `unitless-parameter` or
91    /// `unit-not-followed`.
92    pub reason: String,
93    /// Numbers kept.
94    pub values: usize,
95}
96
97/// What a length-unit conversion did, or, for a dry run, would do.
98#[derive(Debug, Clone, PartialEq)]
99pub struct LengthUnitReport {
100    /// The project length unit before, as named.
101    pub from: String,
102    /// The project length unit after.
103    pub to: String,
104    /// The factor lengths were multiplied by.
105    pub length_factor: f64,
106    /// The factor areas were multiplied by, when the area unit followed.
107    pub area_factor: Option<f64>,
108    /// The factor volumes were multiplied by, when the volume unit followed.
109    pub volume_factor: Option<f64>,
110    /// The new length unit entity; `None` when nothing changes.
111    pub length_unit: Option<u64>,
112    /// The new area unit entity.
113    pub area_unit: Option<u64>,
114    /// The new volume unit entity.
115    pub volume_unit: Option<u64>,
116    /// Rescaled values per entity type and attribute.
117    pub converted: Vec<ConvertedValues>,
118    /// Values left as they are, with the reason.
119    pub kept: Vec<KeptValues>,
120    /// Entities with at least one rescaled value.
121    pub entities_changed: usize,
122    /// Numbers rescaled.
123    pub values_converted: usize,
124    /// Entities created, or for a dry run the ids the commit will create.
125    pub created: Vec<u64>,
126    /// Entities removed, or for a dry run planned for removal.
127    pub removed: Vec<u64>,
128    /// Whether the model was changed.
129    pub applied: bool,
130}
131
132impl ToRecord for ConvertedValues {
133    fn to_record(&self) -> Record {
134        Record::new(
135            "ConvertedValues",
136            vec![
137                ("entity_type", Field::Text(self.entity_type.clone())),
138                ("attribute", Field::Text(self.attribute.clone())),
139                ("kind", Field::Text(self.kind.clone())),
140                ("entities", Field::Count(self.entities)),
141                ("values", Field::Count(self.values)),
142            ],
143        )
144    }
145}
146
147impl ToRecord for KeptValues {
148    fn to_record(&self) -> Record {
149        Record::new(
150            "KeptValues",
151            vec![
152                ("entity_type", Field::Text(self.entity_type.clone())),
153                ("attribute", Field::Text(self.attribute.clone())),
154                ("reason", Field::Text(self.reason.clone())),
155                ("values", Field::Count(self.values)),
156            ],
157        )
158    }
159}
160
161impl ToRecord for LengthUnitReport {
162    fn to_record(&self) -> Record {
163        Record::new(
164            "LengthUnitReport",
165            vec![
166                ("from", Field::Text(self.from.clone())),
167                ("to", Field::Text(self.to.clone())),
168                ("length_factor", Field::Real(self.length_factor)),
169                (
170                    "area_factor",
171                    Field::optional(self.area_factor, Field::Real),
172                ),
173                (
174                    "volume_factor",
175                    Field::optional(self.volume_factor, Field::Real),
176                ),
177                ("length_unit", Field::id(self.length_unit)),
178                ("area_unit", Field::id(self.area_unit)),
179                ("volume_unit", Field::id(self.volume_unit)),
180                ("converted", Field::records(&self.converted)),
181                ("kept", Field::records(&self.kept)),
182                ("entities_changed", Field::Count(self.entities_changed)),
183                ("values_converted", Field::Count(self.values_converted)),
184                ("created", Field::ids(self.created.iter().copied())),
185                ("removed", Field::ids(self.removed.iter().copied())),
186                ("applied", Field::Bool(self.applied)),
187            ],
188        )
189    }
190}
191
192/// Convert `value` from the unit named `from` to the unit named `to`.
193///
194/// # Errors
195///
196/// See the module docs.
197pub fn convert_unit(value: f64, from: &str, to: &str) -> Result<f64, BindingError> {
198    #[cfg(feature = "properties")]
199    {
200        let from = imp::parse(from)?;
201        let to = imp::parse(to)?;
202        ifc::properties::convert_value(value, &from, &to).map_err(imp::error)
203    }
204    #[cfg(not(feature = "properties"))]
205    {
206        let _ = (value, from, to);
207        Err(BindingError::FeatureDisabled("properties"))
208    }
209}
210
211/// Write `value`, a length in the unit named `unit`, as text. `style` is
212/// `decimal` (in `display_unit`, default `unit`, with `places` digits after
213/// the point), `feet-inches` (rounded to `1/places` of an inch, `5' - 6
214/// 1/2"`; with `suppress_zero_inches`, a whole foot is `5'`) or `inches`
215/// (`66 1/2"`).
216///
217/// # Errors
218///
219/// See the module docs.
220pub fn format_length(
221    value: f64,
222    unit: &str,
223    style: &str,
224    places: u32,
225    display_unit: Option<&str>,
226    suppress_zero_inches: bool,
227) -> Result<String, BindingError> {
228    #[cfg(feature = "properties")]
229    {
230        use ifc::properties::LengthFormat;
231        let unit = imp::parse(unit)?;
232        let format = match style {
233            "decimal" => {
234                let display = match display_unit {
235                    Some(display) => imp::parse(display)?,
236                    None => unit.clone(),
237                };
238                let places = u8::try_from(places)
239                    .map_err(|_| BindingError::OutOfRange(format!("{places} decimal places")))?;
240                LengthFormat::decimal(display, places)
241            }
242            "feet-inches" => LengthFormat::feet_inches(places, suppress_zero_inches),
243            "inches" => LengthFormat::inches(places),
244            other => {
245                return Err(BindingError::InvalidValue(format!(
246                    "{other:?} is not a length style: decimal, feet-inches or inches"
247                )))
248            }
249        };
250        ifc::properties::format_length(value, &unit, &format).map_err(imp::error)
251    }
252    #[cfg(not(feature = "properties"))]
253    {
254        let _ = (
255            value,
256            unit,
257            style,
258            places,
259            display_unit,
260            suppress_zero_inches,
261        );
262        Err(BindingError::FeatureDisabled("properties"))
263    }
264}
265
266impl IfcModel {
267    /// Convert `value` from unit entity `from` to unit entity `to` of this
268    /// model.
269    ///
270    /// # Errors
271    ///
272    /// See the module docs.
273    pub fn convert_unit_value(&self, value: f64, from: u64, to: u64) -> Result<f64, BindingError> {
274        #[cfg(feature = "properties")]
275        {
276            for id in [from, to] {
277                if self.inner.get(ifc::EntityId(id)).is_none() {
278                    return Err(BindingError::MissingEntity(id));
279                }
280            }
281            ifc::properties::convert_between(
282                &self.inner,
283                value,
284                ifc::EntityId(from),
285                ifc::EntityId(to),
286            )
287            .map_err(imp::error)
288        }
289        #[cfg(not(feature = "properties"))]
290        {
291            let _ = (value, from, to);
292            Err(BindingError::FeatureDisabled("properties"))
293        }
294    }
295
296    /// Convert the model's length unit to the unit named `target` (an SI
297    /// `METRE` with any prefix, or `inch`, `foot`, `yard`, `mile`, `US
298    /// survey foot`), rescaling every length, area and volume value, as one
299    /// checked transaction; with `options.dry_run`, only report.
300    ///
301    /// # Errors
302    ///
303    /// See the module docs.
304    pub fn convert_length_unit(
305        &mut self,
306        target: &str,
307        options: LengthUnitOptions,
308    ) -> Result<LengthUnitReport, BindingError> {
309        #[cfg(feature = "properties")]
310        {
311            self.tracked(|this| imp::convert_length_unit(this, target, options))
312        }
313        #[cfg(not(feature = "properties"))]
314        {
315            let _ = (target, options);
316            Err(BindingError::FeatureDisabled("properties"))
317        }
318    }
319}
320
321#[cfg(feature = "properties")]
322mod imp {
323    use ifc::properties::{ConversionUnit, UnitConversionError};
324    use ifc::{ConvertedKind, KeptReason, LengthUnitError, RefusalReason};
325
326    use super::{ConvertedValues, KeptValues, LengthUnitOptions, LengthUnitReport};
327    use crate::{BindingError, IfcModel};
328
329    pub(super) fn parse(spec: &str) -> Result<ConversionUnit, BindingError> {
330        ConversionUnit::parse(spec).map_err(error)
331    }
332
333    pub(super) fn error(error: UnitConversionError) -> BindingError {
334        match error {
335            UnitConversionError::DimensionMismatch { .. } => {
336                BindingError::TypeMismatch(error.to_string())
337            }
338            UnitConversionError::MonetaryUnit { .. }
339            | UnitConversionError::ContextDependentUnit { .. }
340            | UnitConversionError::OffsetUnit { .. } => {
341                BindingError::Unsupported(error.to_string())
342            }
343            UnitConversionError::Resolve(_) => BindingError::InvalidModel(error.to_string()),
344            _ => BindingError::InvalidValue(error.to_string()),
345        }
346    }
347
348    fn kind(kind: ConvertedKind) -> &'static str {
349        match kind {
350            ConvertedKind::Length => "length",
351            ConvertedKind::Area => "area",
352            ConvertedKind::Volume => "volume",
353            ConvertedKind::InverseLength => "inverse-length",
354            ConvertedKind::InverseArea => "inverse-area",
355            ConvertedKind::MapScale => "map-scale",
356            _ => "other",
357        }
358    }
359
360    fn reason(reason: KeptReason) -> &'static str {
361        match reason {
362            KeptReason::ExplicitUnit => "explicit-unit",
363            KeptReason::MapUnit => "map-unit",
364            KeptReason::UnitlessParameter => "unitless-parameter",
365            KeptReason::UnitNotFollowed => "unit-not-followed",
366            _ => "other",
367        }
368    }
369
370    fn refusal(reason: &RefusalReason) -> String {
371        match reason {
372            RefusalReason::ParameterSpace {
373                host,
374                host_type,
375                detail,
376            } => format!("a parameter value on #{} {host_type}: {detail}", host.0),
377            RefusalReason::ParameterSpaceCurve {
378                surface,
379                surface_type,
380            } => format!(
381                "a p-curve in the parameter space of #{} {surface_type}, which is not a plane",
382                surface.0
383            ),
384            RefusalReason::PolynomialCoefficients => {
385                "IfcPolynomialCurve coefficients, whose unit IFC4.3 does not state".into()
386            }
387            RefusalReason::TextureGeneratorParameters => {
388                "IfcTextureCoordinateGenerator parameters, whose meaning depends on the mode".into()
389            }
390            RefusalReason::UntypedSelectValue { select } => {
391                format!("an untyped number in a {select}")
392            }
393            RefusalReason::MapTarget { target_type } => {
394                format!("a coordinate operation onto a {target_type}")
395            }
396            RefusalReason::AmbiguousUnit => "a value two owners give different units".into(),
397            RefusalReason::NotInSchema => "an entity the release does not declare".into(),
398            RefusalReason::Unresolved { detail } => detail.to_string(),
399            RefusalReason::ContextUnits => "a context with units of its own".into(),
400            other => format!("{other:?}"),
401        }
402    }
403
404    fn length_error(error: LengthUnitError) -> BindingError {
405        match error {
406            LengthUnitError::Target { target, reason } => {
407                BindingError::InvalidValue(format!("{target}: {reason}"))
408            }
409            LengthUnitError::Schema(error) => BindingError::UnsupportedSchema(error.to_string()),
410            LengthUnitError::ProjectUnit { unit_type, error } => match error {
411                UnitConversionError::Resolve(_) => {
412                    BindingError::InvalidModel(format!("the project {unit_type}: {error}"))
413                }
414                other => super::imp::error(other),
415            },
416            LengthUnitError::Refused(refusals) => BindingError::Unsupported(format!(
417                "{} value(s) cannot be converted: {}",
418                refusals.len(),
419                refusals
420                    .iter()
421                    .take(10)
422                    .map(|r| {
423                        let attribute = r
424                            .attribute
425                            .as_deref()
426                            .map(|a| format!(".{a}"))
427                            .unwrap_or_default();
428                        format!(
429                            "#{} {}{attribute}: {}",
430                            r.entity.0,
431                            r.entity_type,
432                            refusal(&r.reason)
433                        )
434                    })
435                    .collect::<Vec<_>>()
436                    .join("; ")
437            )),
438            LengthUnitError::Authoring(error) => BindingError::InvalidValue(error.to_string()),
439            LengthUnitError::Conflict(conflicts) => {
440                BindingError::InvalidModel(format!("{} conflict(s)", conflicts.len()))
441            }
442            other => BindingError::InvalidModel(other.to_string()),
443        }
444    }
445
446    pub(super) fn convert_length_unit(
447        model: &mut IfcModel,
448        target: &str,
449        options: LengthUnitOptions,
450    ) -> Result<LengthUnitReport, BindingError> {
451        let target = parse(target)?;
452        let facade = ifc::LengthUnitOptions::new()
453            .area_and_volume(options.area_and_volume)
454            .remove_replaced_units(options.remove_replaced_units);
455        let report = if options.dry_run {
456            ifc::stage_length_unit_conversion(&model.inner, &target, &facade)
457                .map_err(length_error)?
458                .report
459        } else {
460            ifc::convert_length_unit(&mut model.inner, &target, &facade).map_err(length_error)?
461        };
462        Ok(LengthUnitReport {
463            from: report.from.name.to_string(),
464            to: report.to.name.to_string(),
465            length_factor: report.length.factor(),
466            area_factor: report.area.map(|c| c.factor()),
467            volume_factor: report.volume.map(|c| c.factor()),
468            length_unit: report.length_unit.map(|id| id.0),
469            area_unit: report.area_unit.map(|id| id.0),
470            volume_unit: report.volume_unit.map(|id| id.0),
471            converted: report
472                .converted
473                .iter()
474                .map(|c| ConvertedValues {
475                    entity_type: c.entity_type.to_string(),
476                    attribute: c.attribute.to_string(),
477                    kind: kind(c.kind).into(),
478                    entities: c.entities,
479                    values: c.values,
480                })
481                .collect(),
482            kept: report
483                .kept
484                .iter()
485                .map(|k| KeptValues {
486                    entity_type: k.entity_type.to_string(),
487                    attribute: k.attribute.to_string(),
488                    reason: reason(k.reason).into(),
489                    values: k.values,
490                })
491                .collect(),
492            entities_changed: report.entities_changed,
493            values_converted: report.values_converted,
494            created: report.created.iter().map(|id| id.0).collect(),
495            removed: report.removed.iter().map(|id| id.0).collect(),
496            applied: report.applied,
497        })
498    }
499}