Skip to main content

openbim_ifc_binding_core/
cost.rs

1//! Cost schedules, items and values (feature `cost`, #123).
2//!
3//! The facade's cost view reads schedules against the declared release and
4//! items, values and their nesting as the file states them. One snapshot
5//! carries every schedule with the objects assigned to it, every item with
6//! its parent, children, values and quantities, and each value's
7//! `AppliedValue` in the tagged encoding (`typed IFCMONETARYMEASURE(real
8//! 1500.5)`), its unit basis and its component tree. Nothing is summed: a
9//! cost value tree's operators are reported, not evaluated, as the facade
10//! leaves evaluation to the caller. A release other than IFC2X3, IFC4 or
11//! IFC4X3 is refused with `unsupported-schema`.
12
13use crate::record::{Field, Record, ToRecord};
14use crate::value::Tagged;
15use crate::{BindingError, IfcModel};
16
17/// Every cost schedule and cost item in a model.
18#[derive(Debug, Clone, PartialEq)]
19pub struct Cost {
20    /// `IfcCostSchedule`s, in file order.
21    pub schedules: Vec<CostSchedule>,
22    /// `IfcCostItem`s, in file order.
23    pub items: Vec<CostItem>,
24    /// Second parents the file states for nested items; the first nesting
25    /// in file order is the one `parent` and `children` report.
26    pub anomalies: Vec<CostAnomaly>,
27}
28
29/// An `IfcCostSchedule`.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct CostSchedule {
32    /// Its entity id.
33    pub id: u64,
34    /// `GlobalId`.
35    pub global_id: Option<String>,
36    /// `Name`.
37    pub name: Option<String>,
38    /// `Identification` (IFC2X3 `ID`).
39    pub identification: Option<String>,
40    /// `Status`.
41    pub status: Option<String>,
42    /// `PredefinedType`, e.g. `BUDGET`.
43    pub predefined_type: Option<String>,
44    /// Objects assigned to it (`IfcRelAssignsToControl`), usually its cost
45    /// items, in file order.
46    pub items: Vec<u64>,
47}
48
49/// An `IfcCostItem`.
50#[derive(Debug, Clone, PartialEq)]
51pub struct CostItem {
52    /// Its entity id.
53    pub id: u64,
54    /// `GlobalId`.
55    pub global_id: Option<String>,
56    /// `Name`.
57    pub name: Option<String>,
58    /// `Identification`.
59    pub identification: Option<String>,
60    /// `Description`.
61    pub description: Option<String>,
62    /// `PredefinedType`.
63    pub predefined_type: Option<String>,
64    /// The item it is nested in (`IfcRelNests`).
65    pub parent: Option<u64>,
66    /// Items nested in it, in authored order.
67    pub children: Vec<u64>,
68    /// `CostValues`, resolved.
69    pub values: Vec<CostValue>,
70    /// `CostQuantities`: the `IfcPhysicalQuantity` ids it is computed
71    /// against.
72    pub quantities: Vec<u64>,
73    /// Objects it prices (`IfcRelAssignsToControl`), in file order.
74    pub objects: Vec<u64>,
75}
76
77/// An `IfcCostValue` or `IfcAppliedValue`.
78#[derive(Debug, Clone, PartialEq)]
79pub struct CostValue {
80    /// Its entity id.
81    pub id: u64,
82    /// `Name`.
83    pub name: Option<String>,
84    /// `Description`.
85    pub description: Option<String>,
86    /// `Category`, e.g. `Labour`.
87    pub category: Option<String>,
88    /// `Condition`.
89    pub condition: Option<String>,
90    /// `AppliedValue` as authored, typed; `null` for a value that states
91    /// only components.
92    pub applied_value: Tagged,
93    /// `ArithmeticOperator`: `ADD`, `DIVIDE`, `MULTIPLY` or `SUBTRACT`.
94    pub operator: Option<String>,
95    /// `UnitBasis`: the value is a rate per this measure.
96    pub unit_basis: Option<UnitBasis>,
97    /// `Components`, resolved, in file order.
98    pub components: Vec<CostValue>,
99}
100
101/// The `IfcMeasureWithUnit` a rate is stated per.
102#[derive(Debug, Clone, PartialEq)]
103pub struct UnitBasis {
104    /// Its entity id.
105    pub id: u64,
106    /// `ValueComponent` as authored, typed.
107    pub value: Tagged,
108    /// `UnitComponent`.
109    pub unit: Option<u64>,
110}
111
112/// A cost item nested under two parents.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct CostAnomaly {
115    /// The item.
116    pub item: u64,
117    /// The parent kept.
118    pub kept: u64,
119    /// The parent rejected.
120    pub rejected: u64,
121    /// The rejected `IfcRelNests`.
122    pub relation: u64,
123}
124
125impl IfcModel {
126    /// Every cost schedule and cost item.
127    ///
128    /// Refused with `unsupported-schema` for a release other than IFC2X3,
129    /// IFC4 or IFC4X3, `missing-reference` for a cost value or component
130    /// the file does not contain, `budget-exceeded` for a component tree
131    /// that cycles or nests deeper than 64, and `feature-disabled` without
132    /// the `cost` feature.
133    pub fn cost(&self) -> Result<Cost, BindingError> {
134        #[cfg(feature = "cost")]
135        {
136            read::cost(self)
137        }
138        #[cfg(not(feature = "cost"))]
139        {
140            Err(BindingError::FeatureDisabled("cost"))
141        }
142    }
143}
144
145#[cfg(feature = "cost")]
146mod read {
147    use ifc::cost::{
148        children_of, controlled_by, nesting_anomalies, parent_of, CostAnomaly as Anomaly,
149        CostError, CostValue as View, CostView, MAX_NESTING_DEPTH,
150    };
151    use ifc::EntityId;
152
153    use super::{Cost, CostAnomaly, CostItem, CostSchedule, CostValue, UnitBasis};
154    use crate::value::Tagged;
155    use crate::{BindingError, IfcModel};
156
157    pub(super) fn cost(model: &IfcModel) -> Result<Cost, BindingError> {
158        let inner = &model.inner;
159        let view = CostView::new(inner);
160        let owned = |text: Option<&str>| text.map(str::to_owned);
161        let mut schedules = Vec::new();
162        for schedule in view.schedules().map_err(error)? {
163            let id = schedule.id();
164            schedules.push(CostSchedule {
165                id: id.0,
166                global_id: model.identity(id.0)?.global_id,
167                name: owned(schedule.name()),
168                identification: owned(schedule.identification()),
169                status: owned(schedule.status()),
170                predefined_type: owned(schedule.predefined_type()),
171                items: ids(controlled_by(inner, id)),
172            });
173        }
174        let mut items = Vec::new();
175        for item in view.items() {
176            let id = item.id();
177            let values = item
178                .value_refs()
179                .into_iter()
180                .map(|value| applied(model, id, value, 0, &mut Vec::new()))
181                .collect::<Result<_, _>>()?;
182            items.push(CostItem {
183                id: id.0,
184                global_id: model.identity(id.0)?.global_id,
185                name: owned(item.name()),
186                identification: owned(item.identification()),
187                description: owned(item.description()),
188                predefined_type: owned(item.predefined_type()),
189                parent: parent_of(inner, id).map(|EntityId(id)| id),
190                children: ids(children_of(inner, id)),
191                values,
192                quantities: ids(item.quantity_refs()),
193                objects: ids(controlled_by(inner, id)),
194            });
195        }
196        let anomalies = nesting_anomalies(inner)
197            .into_iter()
198            .filter_map(|anomaly| match anomaly {
199                Anomaly::NestedTwice {
200                    item,
201                    kept,
202                    rejected,
203                    relation,
204                } => Some(CostAnomaly {
205                    item: item.0,
206                    kept: kept.0,
207                    rejected: rejected.0,
208                    relation: relation.0,
209                }),
210                // An anomaly kind added after this binding.
211                _ => None,
212            })
213            .collect();
214        Ok(Cost {
215            schedules,
216            items,
217            anomalies,
218        })
219    }
220
221    /// Value `id`, referenced from `from`, with its component tree.
222    fn applied(
223        model: &IfcModel,
224        from: EntityId,
225        id: EntityId,
226        depth: usize,
227        path: &mut Vec<EntityId>,
228    ) -> Result<CostValue, BindingError> {
229        if path.contains(&id) || depth > MAX_NESTING_DEPTH {
230            return Err(BindingError::BudgetExceeded(format!(
231                "the cost value tree under #{} cycles or nests deeper than {MAX_NESTING_DEPTH}",
232                from.0
233            )));
234        }
235        let entity = model.inner.get(id).ok_or_else(|| {
236            BindingError::MissingReference(format!("#{} references missing #{}", from.0, id.0))
237        })?;
238        let value = View::new(id, entity);
239        path.push(id);
240        let components = value
241            .component_refs()
242            .into_iter()
243            .map(|component| applied(model, id, component, depth + 1, path))
244            .collect::<Result<_, _>>()?;
245        path.pop();
246        let owned = |text: Option<&str>| text.map(str::to_owned);
247        let unit_basis = value.unit_basis(&model.inner).map(|basis| UnitBasis {
248            id: basis.id.0,
249            value: value
250                .unit_basis_component(&model.inner)
251                .map_or(Tagged::Null, Tagged::from_value),
252            unit: basis.unit.map(|EntityId(id)| id),
253        });
254        Ok(CostValue {
255            id: id.0,
256            name: owned(value.name()),
257            description: owned(value.description()),
258            category: owned(value.category()),
259            condition: owned(value.condition()),
260            applied_value: value
261                .applied_value()
262                .map_or(Tagged::Null, Tagged::from_value),
263            operator: value
264                .operator()
265                .map(|operator| format!("{operator:?}").to_ascii_uppercase()),
266            unit_basis,
267            components,
268        })
269    }
270
271    fn ids(ids: Vec<EntityId>) -> Vec<u64> {
272        ids.into_iter().map(|EntityId(id)| id).collect()
273    }
274
275    fn error(error: CostError) -> BindingError {
276        match error {
277            CostError::UnsupportedSchema { schema } => BindingError::UnsupportedSchema(schema),
278            CostError::MultipleSchemas { schemas } => {
279                BindingError::UnsupportedSchema(format!("{schemas} schemas declared"))
280            }
281            CostError::MissingReference { .. } => BindingError::MissingReference(error.to_string()),
282            other => BindingError::InvalidModel(other.to_string()),
283        }
284    }
285}
286
287impl ToRecord for Cost {
288    fn to_record(&self) -> Record {
289        Record::new(
290            "Cost",
291            vec![
292                ("schedules", Field::records(&self.schedules)),
293                ("items", Field::records(&self.items)),
294                ("anomalies", Field::records(&self.anomalies)),
295            ],
296        )
297    }
298}
299
300impl ToRecord for CostSchedule {
301    fn to_record(&self) -> Record {
302        Record::new(
303            "CostSchedule",
304            vec![
305                ("id", Field::Id(self.id)),
306                ("global_id", Field::text(self.global_id.clone())),
307                ("name", Field::text(self.name.clone())),
308                ("identification", Field::text(self.identification.clone())),
309                ("status", Field::text(self.status.clone())),
310                ("predefined_type", Field::text(self.predefined_type.clone())),
311                ("items", Field::ids(self.items.iter().copied())),
312            ],
313        )
314    }
315}
316
317impl ToRecord for CostItem {
318    fn to_record(&self) -> Record {
319        Record::new(
320            "CostItem",
321            vec![
322                ("id", Field::Id(self.id)),
323                ("global_id", Field::text(self.global_id.clone())),
324                ("name", Field::text(self.name.clone())),
325                ("identification", Field::text(self.identification.clone())),
326                ("description", Field::text(self.description.clone())),
327                ("predefined_type", Field::text(self.predefined_type.clone())),
328                ("parent", Field::id(self.parent)),
329                ("children", Field::ids(self.children.iter().copied())),
330                ("values", Field::records(&self.values)),
331                ("quantities", Field::ids(self.quantities.iter().copied())),
332                ("objects", Field::ids(self.objects.iter().copied())),
333            ],
334        )
335    }
336}
337
338impl ToRecord for CostValue {
339    fn to_record(&self) -> Record {
340        Record::new(
341            "CostValue",
342            vec![
343                ("id", Field::Id(self.id)),
344                ("name", Field::text(self.name.clone())),
345                ("description", Field::text(self.description.clone())),
346                ("category", Field::text(self.category.clone())),
347                ("condition", Field::text(self.condition.clone())),
348                ("applied_value", Field::Value(self.applied_value.clone())),
349                ("operator", Field::text(self.operator.clone())),
350                ("unit_basis", Field::record(self.unit_basis.as_ref())),
351                ("components", Field::records(&self.components)),
352            ],
353        )
354    }
355}
356
357impl ToRecord for UnitBasis {
358    fn to_record(&self) -> Record {
359        Record::new(
360            "UnitBasis",
361            vec![
362                ("id", Field::Id(self.id)),
363                ("value", Field::Value(self.value.clone())),
364                ("unit", Field::id(self.unit)),
365            ],
366        )
367    }
368}
369
370impl ToRecord for CostAnomaly {
371    fn to_record(&self) -> Record {
372        Record::new(
373            "CostAnomaly",
374            vec![
375                ("item", Field::Id(self.item)),
376                ("kept", Field::Id(self.kept)),
377                ("rejected", Field::Id(self.rejected)),
378                ("relation", Field::Id(self.relation)),
379            ],
380        )
381    }
382}