Skip to main content

ifc_georef/conversion/
pset.rs

1//! IFC2X3 georeferencing through the `ePSet_MapConversion` and
2//! `ePSet_ProjectedCRS` property sets (#451).
3//!
4//! # Source
5//!
6//! IFC2X3 declares no `IfcMapConversion` or `IfcProjectedCRS`. The
7//! buildingSMART Australasia "User Guide for Geo-referencing in IFC",
8//! version 2.0 (January 2020), §5.1 "The IFC Site Concept", states the
9//! IFC2X3 mapping:
10//!
11//! - Table 2 maps the IFC4 entities to two IFC2X3 property sets,
12//!   `ePSet_ProjectedCRS` and `ePSet_MapConversion`.
13//! - Table 3 lists `ePSet_MapConversion`: `Eastings`, `Northings`,
14//!   `OrthogonalHeight` (`IfcLengthMeasure`), `XAxisAbscissa`,
15//!   `XAxisOrdinate` and `Scale` (`IfcReal`): the `IfcMapConversion`
16//!   attributes of the same names.
17//! - Table 4 lists `ePSet_ProjectedCRS`: `Name` (`IfcLabel`, an EPSG
18//!   name), `Description` (`IfcText`), `GeodeticDatum`, `VerticalDatum`,
19//!   `MapProjection` and `MapZone` (`IfcIdentifier`): the
20//!   `IfcProjectedCRS` attributes of the same names, without `MapUnit`.
21//! - The note closing §5.1: "For the IFC2x3 implementation the ePSets are
22//!   linked to ifcProject as the geo-referencing specification applies to
23//!   the entire project (model)."
24//!
25//! Each property is read as the `IfcMapConversion` or `IfcProjectedCRS`
26//! attribute it stands for and lowered by the same arithmetic
27//! (`map::linear_part`), so an IFC2X3 file and its IFC4 equivalent
28//! resolve to the same [`ProjectToMap`]. What IFC4 makes mandatory is
29//! required here too: `Eastings`, `Northings`, `OrthogonalHeight` and the
30//! CRS `Name`. The optional ones default as IFC4 defaults them (axis
31//! `(1, 0)`, scale `1`). The guide's §5.2 example applies `Scale` to
32//! eastings and northings only (its footnote 9); IFC4 `IfcMapConversion`
33//! scales heights too. The sets follow IFC4, so an IFC2X3 file and its
34//! IFC4 twin agree; the two readings differ only in height, and only when
35//! `Scale` is not `1`.
36//!
37//! # Where the guide is silent: established practice
38//!
39//! These follow what IFC2X3 exporters and readers do (IfcOpenShell's
40//! `ePSet_Georeferencing` templates and `util/geolocation.py`, tudelft3d
41//! `ifcgref`, ifc-lite), not the guide:
42//!
43//! - **Name case.** The guide spells `ePSet_`; exporters also write
44//!   `ePset_` and `EPset_`. Property-set names match ignoring ASCII case.
45//!   Property names inside the sets match exactly.
46//! - **`IfcSite` as a legacy host.** Some exporters attach the sets to
47//!   `IfcSite`. When an `IfcProject` carries either set, only the project
48//!   is read and every site is ignored. Otherwise each `IfcSite` that
49//!   carries the sets yields its own operation (the guide's §5.1.2 allows
50//!   one transformation per site). A pair is never joined across hosts: a
51//!   host with one set and not the other is refused with
52//!   [`GeorefError::IncompletePropertySets`].
53//! - **`MapUnit`.** An optional `ePSet_ProjectedCRS` property naming an SI
54//!   length unit as text (`METRE`, `MILLIMETRE`, ...), as IfcOpenShell
55//!   writes it. When absent the map unit is the project length unit, the
56//!   IFC4 rule for an omitted `IfcProjectedCRS.MapUnit`. `Eastings`,
57//!   `Northings` and `OrthogonalHeight` are in the map unit, as in IFC4; a
58//!   length property that states its own `Unit` must state that unit.
59//!
60//! # Precedence over the IFC4 entities
61//!
62//! The declared release decides, and the two are never merged: an IFC2X3
63//! file is read only through these property sets (it cannot declare the
64//! entities), and an IFC4 or IFC4X3 file only through its
65//! `IfcCoordinateOperation` entities; property sets of these names in an
66//! IFC4 or IFC4X3 file are not read for georeferencing.
67//!
68//! # Strictness
69//!
70//! A malformed set is refused, never partly read: two sets of one name on
71//! a host ([`GeorefError::AmbiguousPropertySets`]), a repeated property
72//! name (`IfcPropertySet.WR32`, [`GeorefError::RuleViolation`]), a required
73//! property without a value ([`GeorefError::MissingProperty`]), and a
74//! property that is not an `IfcPropertySingleValue`, a number that is not
75//! the guide's measure type or not finite, or a text that is not text
76//! ([`GeorefError::InvalidProperty`]). Unrecognised properties are ignored.
77
78use std::collections::BTreeMap;
79
80use ifc_model::value::Value;
81use ifc_model::{Entity, EntityId, Model};
82use ifc_schema::{for_version, SchemaVersion};
83
84use crate::context::OperationSource;
85use crate::crs::{resolve_length_unit, Damage, LengthUnit, ProjectedCrs};
86use crate::error::{GeorefError, GeorefResult};
87use crate::slot::{property_set, property_single_value, rel_defines_by_properties};
88use crate::view::declared_release;
89
90use super::map::linear_part;
91use super::operation::{OperationKind, ProjectToMap};
92
93/// The property set standing for `IfcMapConversion` (guide Table 3).
94pub const MAP_CONVERSION_PSET: &str = "ePSet_MapConversion";
95/// The property set standing for `IfcProjectedCRS` (guide Table 4).
96pub const PROJECTED_CRS_PSET: &str = "ePSet_ProjectedCRS";
97
98/// Whether `model` holds any `IfcPropertySet` named `ePSet_MapConversion`
99/// or `ePSet_ProjectedCRS` (ignoring ASCII case), attached or not.
100///
101/// A cheap presence test, so a caller can skip resolving the project
102/// length unit for a model with nothing to read.
103#[must_use]
104pub fn has_property_set_georeferencing(model: &Model) -> bool {
105    model
106        .of_type("IFCPROPERTYSET")
107        .any(|(_, set)| pset_kind(set).is_some())
108}
109
110/// Every IFC2X3 property-set georeferencing of `model`, resolved to
111/// project-to-map parameters: one for the `IfcProject`, or else one per
112/// `IfcSite` carrying the sets, in ascending host id.
113///
114/// `project_metres_per_unit` is the project's `IfcUnitAssignment` length
115/// scale, as for [`crate::resolve_project_to_map`]. In the result,
116/// [`ProjectToMap::source`] is [`OperationSource::PropertySet`] naming the
117/// host, [`ProjectToMap::operation`] is the `ePSet_MapConversion` set,
118/// [`ProjectedCrs::entity`] the `ePSet_ProjectedCRS` set, and the kind is
119/// [`OperationKind::MapConversion`]. A model with neither set yields an
120/// empty list. See the module documentation for the source, the rules
121/// where the guide is silent and the precedence over IFC4 entities.
122///
123/// # Errors
124///
125/// [`GeorefError::MissingSchema`], [`GeorefError::AmbiguousSchema`] or
126/// [`GeorefError::UnsupportedSchema`] unless the header declares exactly
127/// IFC2X3 (and this build links its table); [`GeorefError::InvalidUnit`]
128/// for a non-positive or non-finite project scale or an unusable
129/// `MapUnit`; and the property-set refusals listed in the module
130/// documentation.
131pub fn resolve_property_set_georeferencing(
132    model: &Model,
133    project_metres_per_unit: f64,
134) -> GeorefResult<Vec<ProjectToMap>> {
135    let (token, version) = declared_release(model)?;
136    if version != SchemaVersion::Ifc2x3 || for_version(version).is_err() {
137        return Err(GeorefError::UnsupportedSchema {
138            token: token.clone(),
139        });
140    }
141    let damage = Damage::of(model)?;
142    let hosts = hosts(model, &damage)?;
143    if hosts.is_empty() {
144        // A skipped record may have been the host or a set, so an empty list
145        // is not trusted when georeferencing sets are present (#690).
146        if damage.records_lost() && has_property_set_georeferencing(model) {
147            return Err(GeorefError::RecordsIncomplete {
148                diagnostics: damage.diagnostics(),
149            });
150        }
151        return damage.settle(Vec::new());
152    }
153    if !project_metres_per_unit.is_finite() || project_metres_per_unit <= 0.0 {
154        let (&host, _) = hosts.iter().next().expect("not empty");
155        return Err(GeorefError::InvalidUnit {
156            entity: host,
157            detail: "project length scale must be finite and positive",
158        });
159    }
160    let project_unit = LengthUnit {
161        name: "PROJECT_LENGTH_UNIT".into(),
162        metres_per_unit: project_metres_per_unit,
163    };
164    let any_project = hosts.values().any(|sets| sets.is_project);
165    let resolved = hosts
166        .iter()
167        .filter(|(_, sets)| sets.is_project == any_project)
168        .map(|(&host, sets)| resolve_host(model, host, sets, &project_unit, &damage))
169        .collect::<GeorefResult<Vec<_>>>()?;
170    damage.settle(resolved)
171}
172
173/// Which georeferencing set a property set is, by name ignoring case.
174#[derive(Clone, Copy, PartialEq, Eq)]
175enum Kind {
176    MapConversion,
177    ProjectedCrs,
178}
179
180fn pset_kind(set: &Entity) -> Option<Kind> {
181    let name = set.text(property_set::NAME)?;
182    if name.eq_ignore_ascii_case(MAP_CONVERSION_PSET) {
183        Some(Kind::MapConversion)
184    } else if name.eq_ignore_ascii_case(PROJECTED_CRS_PSET) {
185        Some(Kind::ProjectedCrs)
186    } else {
187        None
188    }
189}
190
191/// The georeferencing sets attached to one host.
192#[derive(Default)]
193struct HostSets {
194    is_project: bool,
195    map_conversion: Vec<EntityId>,
196    projected_crs: Vec<EntityId>,
197}
198
199/// Every `IfcProject` and `IfcSite` with a georeferencing set attached by
200/// an `IfcRelDefinesByProperties`, keyed by host id. Other objects are not
201/// hosts: the guide names the project, practice adds the site.
202fn hosts(model: &Model, damage: &Damage) -> GeorefResult<BTreeMap<EntityId, HostSets>> {
203    let mut hosts: BTreeMap<EntityId, HostSets> = BTreeMap::new();
204    for (rel_id, rel) in model.of_type("IFCRELDEFINESBYPROPERTIES") {
205        damage.check(rel_id)?;
206        let Some(set_id) = rel.reference(rel_defines_by_properties::RELATING_PROPERTY_DEFINITION)
207        else {
208            continue;
209        };
210        damage.check(set_id)?;
211        let Some(kind) = model
212            .get(set_id)
213            .filter(|set| set.is_type("IFCPROPERTYSET"))
214            .and_then(pset_kind)
215        else {
216            continue;
217        };
218        let related = rel
219            .attribute(rel_defines_by_properties::RELATED_OBJECTS)
220            .and_then(Value::as_list)
221            .unwrap_or(&[]);
222        for object in related.iter().filter_map(Value::as_ref_id) {
223            damage.check(object)?;
224            let host = model.get(object).ok_or(GeorefError::MissingEntity {
225                referrer: rel_id,
226                missing: object,
227            })?;
228            let is_project = host.is_type("IFCPROJECT");
229            if !is_project && !host.is_type("IFCSITE") {
230                continue;
231            }
232            let sets = hosts.entry(object).or_default();
233            sets.is_project = is_project;
234            let list = match kind {
235                Kind::MapConversion => &mut sets.map_conversion,
236                Kind::ProjectedCrs => &mut sets.projected_crs,
237            };
238            if !list.contains(&set_id) {
239                list.push(set_id);
240            }
241        }
242    }
243    Ok(hosts)
244}
245
246/// The one set of `name` on `host`, refusing none or several.
247fn one(host: EntityId, name: &'static str, sets: &[EntityId]) -> GeorefResult<EntityId> {
248    match sets {
249        [] => Err(GeorefError::IncompletePropertySets {
250            host,
251            missing: name,
252        }),
253        [one] => Ok(*one),
254        _ => {
255            let mut sets = sets.to_vec();
256            sets.sort_unstable();
257            Err(GeorefError::AmbiguousPropertySets { host, name, sets })
258        }
259    }
260}
261
262fn resolve_host(
263    model: &Model,
264    host: EntityId,
265    sets: &HostSets,
266    project_unit: &LengthUnit,
267    damage: &Damage,
268) -> GeorefResult<ProjectToMap> {
269    // Both ambiguity checks before completeness, so a host with two of one
270    // set and none of the other reports the ambiguity it has.
271    if sets.map_conversion.len() > 1 {
272        one(host, MAP_CONVERSION_PSET, &sets.map_conversion)?;
273    }
274    if sets.projected_crs.len() > 1 {
275        one(host, PROJECTED_CRS_PSET, &sets.projected_crs)?;
276    }
277    let conversion = Properties::read(
278        model,
279        one(host, MAP_CONVERSION_PSET, &sets.map_conversion)?,
280        damage,
281    )?;
282    let crs = Properties::read(
283        model,
284        one(host, PROJECTED_CRS_PSET, &sets.projected_crs)?,
285        damage,
286    )?;
287
288    let target_crs = projected_crs(&crs)?;
289    let map_unit = target_crs
290        .map_unit
291        .clone()
292        .unwrap_or_else(|| project_unit.clone());
293
294    let eastings = conversion.length(model, "Eastings", &map_unit)?;
295    let northings = conversion.length(model, "Northings", &map_unit)?;
296    let height = conversion.length(model, "OrthogonalHeight", &map_unit)?;
297    let a = conversion.real("XAxisAbscissa")?.map_or(1.0, |(_, v)| v);
298    let b = conversion.real("XAxisOrdinate")?.map_or(0.0, |(_, v)| v);
299    let norm = a.hypot(b);
300    if !norm.is_finite() || norm <= f64::EPSILON {
301        return Err(GeorefError::DegenerateAxis {
302            entity: conversion.set,
303        });
304    }
305    let (a, b) = (a / norm, b / norm);
306    let declared_scale = conversion.real("Scale")?.map_or(1.0, |(_, v)| v);
307    if declared_scale <= 0.0 {
308        return Err(GeorefError::InvalidScale {
309            entity: conversion.set,
310            value: declared_scale,
311        });
312    }
313    let scale = declared_scale * map_unit.metres_per_unit / project_unit.metres_per_unit;
314    if !scale.is_finite() || scale <= 0.0 {
315        return Err(GeorefError::InvalidScale {
316            entity: conversion.set,
317            value: scale,
318        });
319    }
320    let linear = linear_part(scale, (a, b), (1.0, 1.0, 1.0));
321    let metres = map_unit.metres_per_unit;
322    let translation = [eastings * metres, northings * metres, height * metres];
323    for (value, name) in translation
324        .iter()
325        .zip(["Eastings", "Northings", "OrthogonalHeight"])
326    {
327        if !value.is_finite() {
328            let (property, _) = conversion.get(name).expect("read above");
329            return Err(GeorefError::InvalidProperty {
330                property_set: conversion.set,
331                property,
332                name,
333                expected: "a length whose value in metres is finite",
334            });
335        }
336    }
337
338    Ok(ProjectToMap::new(
339        OperationSource::PropertySet(host),
340        conversion.set,
341        OperationKind::MapConversion,
342        target_crs,
343        [eastings, northings, height],
344        (project_unit.clone(), map_unit),
345        declared_scale,
346        (a, b),
347        linear,
348        translation,
349    ))
350}
351
352/// `ePSet_ProjectedCRS` read as an `IfcProjectedCRS` (guide Table 4).
353fn projected_crs(crs: &Properties) -> GeorefResult<ProjectedCrs> {
354    let name = crs.text("Name")?.ok_or(GeorefError::MissingProperty {
355        property_set: crs.set,
356        name: "Name",
357    })?;
358    let map_unit = match crs.text("MapUnit")? {
359        None => None,
360        Some(text) => {
361            let (property, _) = crs.get("MapUnit").expect("read above");
362            Some(si_length_unit(&text).ok_or(GeorefError::InvalidProperty {
363                property_set: crs.set,
364                property,
365                name: "MapUnit",
366                expected: "the name of an SI length unit, such as METRE or MILLIMETRE",
367            })?)
368        }
369    };
370    Ok(ProjectedCrs {
371        entity: crs.set,
372        name: Some(name),
373        description: crs.text("Description")?,
374        geodetic_datum: crs.text("GeodeticDatum")?,
375        vertical_datum: crs.text("VerticalDatum")?,
376        map_projection: crs.text("MapProjection")?,
377        map_zone: crs.text("MapZone")?,
378        map_unit,
379        well_known_text: None,
380    })
381}
382
383/// `METRE`, or an `IfcSIPrefix` followed by `METRE`, as written in
384/// `IfcSIUnitName` and `IfcSIPrefix` (ignoring ASCII case).
385fn si_length_unit(text: &str) -> Option<LengthUnit> {
386    const PREFIXES: &[(&str, f64)] = &[
387        ("", 1.0),
388        ("EXA", 1e18),
389        ("PETA", 1e15),
390        ("TERA", 1e12),
391        ("GIGA", 1e9),
392        ("MEGA", 1e6),
393        ("KILO", 1e3),
394        ("HECTO", 1e2),
395        ("DECA", 1e1),
396        ("DECI", 1e-1),
397        ("CENTI", 1e-2),
398        ("MILLI", 1e-3),
399        ("MICRO", 1e-6),
400        ("NANO", 1e-9),
401        ("PICO", 1e-12),
402        ("FEMTO", 1e-15),
403        ("ATTO", 1e-18),
404    ];
405    let upper = text.trim().to_ascii_uppercase();
406    let prefix = upper.strip_suffix("METRE")?;
407    PREFIXES
408        .iter()
409        .find(|(p, _)| *p == prefix)
410        .map(|&(_, metres_per_unit)| LengthUnit {
411            name: upper.clone(),
412            metres_per_unit,
413        })
414}
415
416/// The properties of one georeferencing set, by name.
417struct Properties<'m> {
418    set: EntityId,
419    damage: &'m Damage,
420    by_name: BTreeMap<&'m str, (EntityId, &'m Entity)>,
421}
422
423impl<'m> Properties<'m> {
424    /// Index `HasProperties` by name, refusing a dangling or non-reference
425    /// member and a repeated name (`WR32`).
426    fn read(model: &'m Model, set: EntityId, damage: &'m Damage) -> GeorefResult<Self> {
427        damage.check(set)?;
428        let entity = model.get(set).ok_or(GeorefError::MissingEntity {
429            referrer: set,
430            missing: set,
431        })?;
432        let members = entity
433            .attribute(property_set::HAS_PROPERTIES)
434            .and_then(Value::as_list)
435            .ok_or(GeorefError::InvalidAttribute {
436                entity: set,
437                index: property_set::HAS_PROPERTIES,
438                name: "HasProperties",
439            })?;
440        let mut by_name = BTreeMap::new();
441        for member in members {
442            let id = member.as_ref_id().ok_or(GeorefError::InvalidAttribute {
443                entity: set,
444                index: property_set::HAS_PROPERTIES,
445                name: "HasProperties",
446            })?;
447            damage.check(id)?;
448            let property = model.get(id).ok_or(GeorefError::MissingEntity {
449                referrer: set,
450                missing: id,
451            })?;
452            let Some(name) = property.text(property_single_value::NAME) else {
453                return Err(GeorefError::InvalidAttribute {
454                    entity: id,
455                    index: property_single_value::NAME,
456                    name: "Name",
457                });
458            };
459            if by_name.insert(name, (id, property)).is_some() {
460                return Err(GeorefError::RuleViolation {
461                    entity: set,
462                    rule: "WR32 : IfcUniquePropertyName(HasProperties)",
463                });
464            }
465        }
466        Ok(Self {
467            set,
468            damage,
469            by_name,
470        })
471    }
472
473    fn get(&self, name: &str) -> Option<(EntityId, &'m Entity)> {
474        self.by_name.get(name).copied()
475    }
476
477    /// The `NominalValue` of single-value property `name`: `None` when the
478    /// property is absent or its value unset.
479    fn nominal(
480        &self,
481        name: &'static str,
482        expected: &'static str,
483    ) -> GeorefResult<Option<(EntityId, &'m Entity, &'m Value)>> {
484        let Some((id, property)) = self.get(name) else {
485            return Ok(None);
486        };
487        if !property.is_type("IFCPROPERTYSINGLEVALUE") {
488            return Err(self.invalid(id, name, expected));
489        }
490        match property.attribute(property_single_value::NOMINAL_VALUE) {
491            None | Some(Value::Null) => Ok(None),
492            Some(value) => Ok(Some((id, property, value))),
493        }
494    }
495
496    fn invalid(
497        &self,
498        property: EntityId,
499        name: &'static str,
500        expected: &'static str,
501    ) -> GeorefError {
502        GeorefError::InvalidProperty {
503            property_set: self.set,
504            property,
505            name,
506            expected,
507        }
508    }
509
510    /// A finite number wrapped in `measure`, the guide's data type.
511    fn measure(
512        &self,
513        name: &'static str,
514        measure: &'static str,
515        expected: &'static str,
516    ) -> GeorefResult<Option<(EntityId, &'m Entity, f64)>> {
517        let Some((id, property, value)) = self.nominal(name, expected)? else {
518            return Ok(None);
519        };
520        match value {
521            Value::Typed { type_name, value } if type_name.eq_ignore_ascii_case(measure) => {
522                match value.as_f64() {
523                    Some(number) if number.is_finite() => Ok(Some((id, property, number))),
524                    _ => Err(self.invalid(id, name, expected)),
525                }
526            }
527            _ => Err(self.invalid(id, name, expected)),
528        }
529    }
530
531    /// A required `IfcLengthMeasure` in `map_unit`. A property `Unit`, when
532    /// stated, must resolve to the map unit.
533    fn length(
534        &self,
535        model: &Model,
536        name: &'static str,
537        map_unit: &LengthUnit,
538    ) -> GeorefResult<f64> {
539        const EXPECTED: &str = "an IfcPropertySingleValue with a finite IfcLengthMeasure";
540        let (id, property, value) = self.measure(name, "IFCLENGTHMEASURE", EXPECTED)?.ok_or(
541            GeorefError::MissingProperty {
542                property_set: self.set,
543                name,
544            },
545        )?;
546        match property.attribute(property_single_value::UNIT) {
547            None | Some(Value::Null) => {}
548            Some(unit) => {
549                let unit = unit.as_ref_id().ok_or(GeorefError::InvalidAttribute {
550                    entity: id,
551                    index: property_single_value::UNIT,
552                    name: "Unit",
553                })?;
554                let stated = resolve_length_unit(model, unit, self.damage)?;
555                if stated.metres_per_unit != map_unit.metres_per_unit {
556                    return Err(self.invalid(
557                        id,
558                        name,
559                        "a length in the map unit: its Unit states another",
560                    ));
561                }
562            }
563        }
564        Ok(value)
565    }
566
567    /// An optional `IfcReal`, refusing a stated `Unit` (a real has none).
568    fn real(&self, name: &'static str) -> GeorefResult<Option<(EntityId, f64)>> {
569        const EXPECTED: &str = "an IfcPropertySingleValue with a finite IfcReal and no Unit";
570        let Some((id, property, value)) = self.measure(name, "IFCREAL", EXPECTED)? else {
571            return Ok(None);
572        };
573        if !matches!(
574            property.attribute(property_single_value::UNIT),
575            None | Some(Value::Null)
576        ) {
577            return Err(self.invalid(id, name, EXPECTED));
578        }
579        Ok(Some((id, value)))
580    }
581
582    /// An optional text: `IfcLabel`, `IfcText` or `IfcIdentifier`.
583    fn text(&self, name: &'static str) -> GeorefResult<Option<String>> {
584        const EXPECTED: &str =
585            "an IfcPropertySingleValue with an IfcLabel, IfcText or IfcIdentifier";
586        let Some((id, _, value)) = self.nominal(name, EXPECTED)? else {
587            return Ok(None);
588        };
589        match value {
590            Value::Typed { type_name, value }
591                if ["IFCLABEL", "IFCTEXT", "IFCIDENTIFIER"]
592                    .iter()
593                    .any(|t| type_name.eq_ignore_ascii_case(t)) =>
594            {
595                value
596                    .as_text()
597                    .map(|text| Some(text.to_owned()))
598                    .ok_or_else(|| self.invalid(id, name, EXPECTED))
599            }
600            _ => Err(self.invalid(id, name, EXPECTED)),
601        }
602    }
603}
604
605#[cfg(test)]
606mod tests {
607    use super::si_length_unit;
608
609    #[test]
610    fn map_unit_names_resolve_only_si_length_units() {
611        assert_eq!(si_length_unit("METRE").unwrap().metres_per_unit, 1.0);
612        assert_eq!(si_length_unit("millimetre").unwrap().metres_per_unit, 1e-3);
613        assert_eq!(si_length_unit("KILOMETRE").unwrap().metres_per_unit, 1e3);
614        for refused in ["FOOT", "METER", "SQUARE_METRE", "MILLI", "", "XMETRE"] {
615            assert!(si_length_unit(refused).is_none(), "{refused}");
616        }
617    }
618}