ifc_cost/mutation/quantity.rs
1//! Authoring for the physical quantities a cost item is measured against.
2//!
3//! `IfcCostItem.CostQuantities` is what turns a rate into a sum: a value of
4//! 50/m2 means nothing until something states how many square metres. The
5//! quantity subtypes share a slot layout inherited through two levels --
6//! `IfcPhysicalQuantity` contributes Name and Description, then
7//! `IfcPhysicalSimpleQuantity` adds Unit -- so the measured number always
8//! lands in slot 3, whatever the subtype calls it. The reader in
9//! `crate::quantity` relies on exactly that, and these constructors must
10//! agree with it or an authored quantity reads back as None.
11//!
12//! # Release-bound, and written bare (#190)
13//!
14//! Unlike the rest of this crate's IFC4 authoring, [`create_quantity`] binds
15//! the model's declared release (`release.rs`) and places attributes by name
16//! from its table: IFC2X3 declares four attributes and no `Formula`, IFC4
17//! and IFC4X3 five, and only IFC4X3 declares `IfcQuantityNumber`. The value
18//! attribute is declared with a defined measure type, not a SELECT, so the
19//! value is written bare (`12.5`, never `IFCAREAMEASURE(12.5)`), as ISO
20//! 10303-21 requires. `ifc-properties` writes the same bytes; the facade
21//! test `quantity_writer_agreement.rs` holds the two together.
22
23use ifc_model::{EntityId, Model, Transaction, Value};
24
25use super::release::{bind, Release};
26use super::validate::invalid;
27use super::{CostAuthoringError, CostAuthoringResult};
28
29/// The physical dimension a simple quantity measures.
30///
31/// Each variant names its IFC entity and the typed measure its value slot
32/// carries. Keeping the pair together is what stops an area being written
33/// with a length measure, which parses and validates but is wrong.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum QuantityKind {
37 /// `IfcQuantityLength.LengthValue`, an `IfcLengthMeasure`.
38 Length,
39 /// `IfcQuantityArea.AreaValue`, an `IfcAreaMeasure`.
40 Area,
41 /// `IfcQuantityVolume.VolumeValue`, an `IfcVolumeMeasure`.
42 Volume,
43 /// `IfcQuantityCount.CountValue`, an `IfcCountMeasure`.
44 Count,
45 /// `IfcQuantityWeight.WeightValue`, an `IfcMassMeasure`.
46 Weight,
47 /// `IfcQuantityTime.TimeValue`, an `IfcTimeMeasure`.
48 Time,
49 /// `IfcQuantityNumber.NumberValue`, an `IfcNumericMeasure`.
50 ///
51 /// IFC4X3 only: a dimensionless count that is not a cardinality,
52 /// such as a rating or an index.
53 Number,
54}
55
56impl QuantityKind {
57 /// The IFC entity name for this dimension.
58 pub fn entity_name(self) -> &'static str {
59 match self {
60 Self::Length => "IFCQUANTITYLENGTH",
61 Self::Area => "IFCQUANTITYAREA",
62 Self::Volume => "IFCQUANTITYVOLUME",
63 Self::Count => "IFCQUANTITYCOUNT",
64 Self::Weight => "IFCQUANTITYWEIGHT",
65 Self::Time => "IFCQUANTITYTIME",
66 Self::Number => "IFCQUANTITYNUMBER",
67 }
68 }
69
70 /// The measure type the value slot is declared with.
71 ///
72 /// A defined type, not a SELECT, so [`create_quantity`] writes the value
73 /// bare; the declaration already states the measure.
74 pub fn measure_name(self) -> &'static str {
75 match self {
76 Self::Length => "IFCLENGTHMEASURE",
77 Self::Area => "IFCAREAMEASURE",
78 Self::Volume => "IFCVOLUMEMEASURE",
79 Self::Count => "IFCCOUNTMEASURE",
80 Self::Weight => "IFCMASSMEASURE",
81 Self::Time => "IFCTIMEMEASURE",
82 Self::Number => "IFCNUMERICMEASURE",
83 }
84 }
85
86 /// The value attribute's name, the same in every release that declares
87 /// the entity.
88 fn value_attribute(self) -> &'static str {
89 match self {
90 Self::Length => "LengthValue",
91 Self::Area => "AreaValue",
92 Self::Volume => "VolumeValue",
93 Self::Count => "CountValue",
94 Self::Weight => "WeightValue",
95 Self::Time => "TimeValue",
96 Self::Number => "NumberValue",
97 }
98 }
99}
100
101/// Authored fields for a simple physical quantity.
102#[derive(Debug, Clone, Copy)]
103#[non_exhaustive]
104pub struct QuantityDraft<'a> {
105 /// The dimension being measured.
106 pub kind: QuantityKind,
107 /// `IfcPhysicalQuantity.Name`. Required: an unnamed quantity cannot be
108 /// matched to the rate it is meant to multiply.
109 pub name: &'a str,
110 /// `IfcPhysicalQuantity.Description`, if given.
111 pub description: Option<&'a str>,
112 /// `IfcPhysicalSimpleQuantity.Unit`, an `IfcNamedUnit` reference, if
113 /// given. Absent means the project unit for the dimension applies.
114 pub unit: Option<EntityId>,
115 /// The measured amount.
116 pub value: f64,
117 /// `Formula`, the derivation note, if given.
118 pub formula: Option<&'a str>,
119}
120
121/// Stage one simple physical quantity, in the model's declared release.
122///
123/// A count is a cardinality, so a fractional or negative count is refused;
124/// the remaining dimensions refuse negatives because no physical extent is
125/// negative, and a sign error here silently inverts a cost sum.
126///
127/// # Errors
128///
129/// Besides those refusals and a `Unit` that is not an `IfcNamedUnit`:
130/// [`CostAuthoringError::MultipleSchemas`] or
131/// [`CostAuthoringError::UnsupportedSchema`] when the model binds no single
132/// known release (a model without `FILE_SCHEMA` binds IFC4);
133/// [`CostAuthoringError::EntityNotInSchema`] for a kind the release does not
134/// declare (`Number` outside IFC4X3); and
135/// [`CostAuthoringError::AuthoringNotInSchema`] for a `formula` in IFC2X3.
136/// Nothing is staged on an error.
137///
138/// [`CostAuthoringError::MultipleSchemas`]: super::CostAuthoringError::MultipleSchemas
139/// [`CostAuthoringError::UnsupportedSchema`]: super::CostAuthoringError::UnsupportedSchema
140/// [`CostAuthoringError::EntityNotInSchema`]: super::CostAuthoringError::EntityNotInSchema
141/// [`CostAuthoringError::AuthoringNotInSchema`]: super::CostAuthoringError::AuthoringNotInSchema
142pub fn create_quantity(
143 tx: &mut Transaction,
144 model: &Model,
145 draft: QuantityDraft<'_>,
146) -> CostAuthoringResult<EntityId> {
147 let release = bind(model)?;
148 let entity = draft.kind.entity_name();
149 if draft.name.trim().is_empty() {
150 return Err(invalid(entity, "Name", "expected a non-empty name"));
151 }
152 if !draft.value.is_finite() {
153 return Err(invalid(entity, "Value", "expected a finite measure"));
154 }
155 // Every dimension but Number measures a physical extent, and no
156 // extent is negative. A number is a plain count or index, so it may
157 // be negative -- a temperature delta or a rating, for instance.
158 if draft.kind != QuantityKind::Number && draft.value < 0.0 {
159 return Err(invalid(
160 entity,
161 "Value",
162 "expected a finite non-negative measure",
163 ));
164 }
165 if draft.kind == QuantityKind::Count && draft.value.fract() != 0.0 {
166 return Err(invalid(entity, "CountValue", "expected a whole count"));
167 }
168 if let Some(unit) = draft.unit {
169 super::validate::reference_type(tx, model, entity, "Unit", unit, "IFCNAMEDUNIT")?;
170 }
171 // Bare: the declared type is a defined measure, not a SELECT. A whole
172 // count is an INTEGER, valid for IfcCountMeasure as NUMBER (IFC2X3,
173 // IFC4) and as INTEGER (IFC4X3); every other measure here is REAL. The
174 // whole-count check above has already run, so the cast cannot lose a
175 // fraction.
176 let value = if draft.kind == QuantityKind::Count {
177 #[allow(clippy::cast_possible_truncation)]
178 Value::Integer(draft.value as i64)
179 } else {
180 Value::Real(draft.value)
181 };
182 let text = |text: Option<&str>| text.map_or(Value::Null, |text| Value::Text(text.into()));
183 let record = release.record(
184 entity,
185 vec![
186 ("Name", Value::Text(draft.name.into())),
187 ("Description", text(draft.description)),
188 ("Unit", draft.unit.map_or(Value::Null, Value::Ref)),
189 (draft.kind.value_attribute(), value),
190 ("Formula", text(draft.formula)),
191 ],
192 )?;
193 Ok(tx.create(record))
194}
195
196/// Attach quantities to an existing `IfcCostItem`, in the model's declared
197/// release.
198///
199/// Replaces `CostQuantities` wholesale rather than appending: a partial
200/// update would leave the caller unable to express removal, and silently
201/// accumulating duplicates would double a measured sum.
202///
203/// Every quantity must be an instantiable subtype of the release's own
204/// `CostQuantities` declaration (`IfcPhysicalQuantity`), read from its
205/// table rather than a fixed list (#203): IFC4X3 adds `IfcQuantityNumber`,
206/// which IFC4 does not declare. The slot is found by name, not assumed.
207///
208/// # Errors
209///
210/// A `cost_item` that is not an `IfcCostItem`; an empty or duplicated
211/// quantity list; a quantity that is missing (`MissingReference`) or not a
212/// physical quantity of the release (`WrongReferenceType`, such as an
213/// `IfcQuantityNumber` in IFC4); a header binding no single known release
214/// (`MultipleSchemas`, `UnsupportedSchema`); and an IFC2X3 model, whose
215/// `IfcCostItem` declares no `CostQuantities` (`AuthoringNotInSchema`).
216/// Nothing is staged on an error.
217///
218/// [`CostAuthoringError::AuthoringNotInSchema`]: super::CostAuthoringError::AuthoringNotInSchema
219pub fn assign_cost_quantities(
220 tx: &mut Transaction,
221 model: &Model,
222 cost_item: EntityId,
223 quantities: &[EntityId],
224) -> CostAuthoringResult<()> {
225 const ENTITY: &str = "IFCCOSTITEM";
226 let release = bind(model)?;
227 super::validate::reference_type(tx, model, ENTITY, "CostQuantities", cost_item, ENTITY)?;
228 let (slot, declared) = release.declared(ENTITY, "CostQuantities")?;
229 // Reuses the crate's own emptiness/duplicate rule rather than restating
230 // it: a duplicated quantity would double the measured sum.
231 super::validate::non_empty_unique(ENTITY, "CostQuantities", quantities)?;
232 for &quantity in quantities {
233 require_quantity(tx, model, release, &declared.type_name, quantity)?;
234 }
235 tx.set_attribute(
236 cost_item,
237 slot,
238 Value::List(quantities.iter().copied().map(Value::Ref).collect()),
239 );
240 Ok(())
241}
242
243/// Accept any instantiable subtype of `declared` in the bound release.
244///
245/// `validate::reference_type` compares one exact name, but `CostQuantities`
246/// is typed to the abstract `IfcPhysicalQuantity`: an area, a volume, a
247/// count and (in IFC4X3) a number are all valid there. The accepted set is
248/// the release's own subtype tree, so an unrelated entity, or a subtype
249/// another release added, is still refused.
250fn require_quantity(
251 tx: &Transaction,
252 model: &Model,
253 release: Release,
254 declared: &str,
255 target: EntityId,
256) -> CostAuthoringResult<()> {
257 let Some(actual) = super::validate::projected_type(tx, model, target) else {
258 return Err(CostAuthoringError::MissingReference {
259 entity: "IFCCOSTITEM",
260 attribute: "CostQuantities",
261 target,
262 });
263 };
264 let schema = release.schema();
265 let instantiable = schema.entity(&actual).is_some_and(|e| !e.abstract_);
266 if instantiable && schema.accepts_type(declared, &actual) {
267 return Ok(());
268 }
269 Err(CostAuthoringError::WrongReferenceType {
270 entity: "IFCCOSTITEM",
271 attribute: "CostQuantities",
272 target,
273 actual,
274 expected: "IFCPHYSICALQUANTITY",
275 })
276}
277
278impl<'a> QuantityDraft<'a> {
279 /// Starts a draft for a quantity of `kind` named `name` measuring
280 /// `value`, with every optional attribute unset.
281 #[must_use]
282 pub const fn new(kind: QuantityKind, name: &'a str, value: f64) -> Self {
283 Self {
284 kind,
285 name,
286 description: None,
287 unit: None,
288 value,
289 formula: None,
290 }
291 }
292
293 /// Sets `IfcPhysicalQuantity.Description`.
294 #[must_use]
295 pub fn description(mut self, value: &'a str) -> Self {
296 self.description = Some(value);
297 self
298 }
299
300 /// Sets `IfcPhysicalSimpleQuantity.Unit`, an `IfcNamedUnit` reference.
301 #[must_use]
302 pub fn unit(mut self, value: EntityId) -> Self {
303 self.unit = Some(value);
304 self
305 }
306
307 /// Sets `Formula`, the derivation note.
308 #[must_use]
309 pub fn formula(mut self, value: &'a str) -> Self {
310 self.formula = Some(value);
311 self
312 }
313}