Skip to main content

ifc_cost/
relation.rs

1//! Cost item nesting and control assignment.
2//!
3//! # Two different relationships, two different meanings
4//!
5//! ```text
6//! IfcRelNests             cost item -> sub-items      (the breakdown tree)
7//!   4 RelatingObject      the parent
8//!   5 RelatedObjects      LIST of children, order significant
9//!
10//! IfcRelAssignsToControl  cost item -> products       (what it prices)
11//!   4 RelatedObjects      SET of assigned objects
12//!   5 RelatedObjectsType
13//!   6 RelatingControl     the cost item
14//! ```
15//!
16//! `RelatingControl` is slot **6**, not 5: `IfcRelAssigns` contributes both
17//! `RelatedObjects` and `RelatedObjectsType` before the subtype's own field.
18//!
19//! # Why nesting needs a cycle budget
20//!
21//! `IfcRelNests` has a `NoSelfReference` WHERE rule, so a file cannot state
22//! that an item nests itself directly. It says nothing about longer cycles:
23//! A nests B nests A satisfies every stated rule and is what a naive recursive
24//! total does not survive. Depth is therefore bounded and a cycle is reported
25//! as data, not discovered as a stack overflow.
26
27use std::collections::{HashMap, HashSet};
28
29use ifc_model::{EntityId, Model, Value};
30
31/// `IfcRelNests` slots.
32mod nests {
33    /// `RelatingObject`, the parent.
34    pub const RELATING: usize = 4;
35    /// `RelatedObjects`, the children.
36    pub const RELATED: usize = 5;
37}
38
39/// `IfcRelAssignsToControl` slots.
40mod assigns {
41    /// `RelatedObjects`, what the control applies to.
42    pub const RELATED: usize = 4;
43    /// `RelatingControl`, the controlling entity.
44    pub const RELATING: usize = 6;
45}
46
47/// The maximum nesting depth walked before reporting a runaway tree.
48///
49/// Cost breakdowns are authored by humans and are shallow in practice; a tree
50/// deeper than this is a malformed or adversarial file, not a real estimate.
51pub const MAX_NESTING_DEPTH: usize = 64;
52
53/// A refusal to resolve a cost relationship.
54#[derive(Debug, Clone, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum CostRelationError {
57    /// A nesting cycle was found: the item is its own ancestor.
58    NestingCycle {
59        /// The item the walk returned to.
60        repeated: EntityId,
61        /// The path taken, from the root to the repeat.
62        path: Vec<EntityId>,
63    },
64    /// The tree exceeded [`MAX_NESTING_DEPTH`] without terminating.
65    DepthExceeded {
66        /// Where the walk stopped.
67        at: EntityId,
68        /// The budget that was exhausted.
69        limit: usize,
70    },
71}
72
73/// A nesting the file states but the schema forbids, and how it was resolved.
74///
75/// IFC4 `IfcObjectDefinition.Nests` and IFC2X3 `Decomposes` are both
76/// `SET [0:1]`: a cost item has at most one parent. When a file names two,
77/// the first `IfcRelNests` in file order wins everywhere ([`parent_of`],
78/// [`children_of`], [`descendants_of`], the rollups), so an item is never
79/// counted under two parents. The losing claim is reported here.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum CostAnomaly {
83    /// A cost item nested under two different parents.
84    NestedTwice {
85        /// The item with two parents.
86        item: EntityId,
87        /// The parent kept.
88        kept: EntityId,
89        /// The parent rejected; it does not list the item.
90        rejected: EntityId,
91        /// The `IfcRelNests` that was rejected.
92        relation: EntityId,
93    },
94}
95
96/// Each nested child's kept parent: the first `IfcRelNests` naming it.
97fn kept_parents(model: &Model) -> HashMap<EntityId, EntityId> {
98    let mut kept = HashMap::new();
99    for (_, entity) in model.of_type("IFCRELNESTS") {
100        let Some(Value::Ref(parent)) = entity.attribute(nests::RELATING) else {
101            continue;
102        };
103        if let Some(v) = entity.attribute(nests::RELATED) {
104            v.for_each_ref(&mut |child| {
105                kept.entry(child).or_insert(*parent);
106            });
107        }
108    }
109    kept
110}
111
112/// Second parents the file states for nested items, in file order.
113///
114/// Empty for a conformant file. Restating the same parent in another
115/// relationship is redundant, not contradictory, and is not reported.
116#[must_use]
117pub fn nesting_anomalies(model: &Model) -> Vec<CostAnomaly> {
118    let kept = kept_parents(model);
119    let mut out = Vec::new();
120    for (relation, entity) in model.of_type("IFCRELNESTS") {
121        let Some(Value::Ref(parent)) = entity.attribute(nests::RELATING) else {
122            continue;
123        };
124        if let Some(v) = entity.attribute(nests::RELATED) {
125            v.for_each_ref(&mut |item| {
126                if let Some(&first) = kept.get(&item) {
127                    if first != *parent {
128                        out.push(CostAnomaly::NestedTwice {
129                            item,
130                            kept: first,
131                            rejected: *parent,
132                            relation,
133                        });
134                    }
135                }
136            });
137        }
138    }
139    out
140}
141
142/// Direct children of a cost item, in authored order.
143///
144/// Order is preserved: `RelatedObjects` is a LIST in `IfcRelNests`, so a file
145/// stating `[Labour, Plant, Material]` means that sequence, and a caller
146/// rendering a breakdown should not reorder it.
147///
148/// Only children whose kept parent is `parent` are listed, each once, so this
149/// agrees with [`parent_of`]. A child a malformed file also nests elsewhere
150/// is listed under its first parent only; see [`nesting_anomalies`].
151#[must_use]
152pub fn children_of(model: &Model, parent: EntityId) -> Vec<EntityId> {
153    let kept = kept_parents(model);
154    let mut out = Vec::new();
155    for (_, entity) in model.of_type("IFCRELNESTS") {
156        let relating = match entity.attribute(nests::RELATING) {
157            Some(Value::Ref(id)) => *id,
158            _ => continue,
159        };
160        if relating != parent {
161            continue;
162        }
163        if let Some(v) = entity.attribute(nests::RELATED) {
164            v.for_each_ref(&mut |id| {
165                if kept.get(&id) == Some(&parent) && !out.contains(&id) {
166                    out.push(id);
167                }
168            });
169        }
170    }
171    out
172}
173
174/// The parent of a cost item, if it is nested.
175///
176/// `IfcObjectDefinition.Nests` is `SET [0:1]`, so an item has at most one
177/// parent. A file stating two is malformed; the first in file order is
178/// returned, every other view agrees with it, and [`nesting_anomalies`]
179/// reports the rejected claim. [`parents_of`] still lists every claimant.
180#[must_use]
181pub fn parent_of(model: &Model, child: EntityId) -> Option<EntityId> {
182    parents_of(model, child).into_iter().next()
183}
184
185/// Every parent claiming this item, for detecting malformed multi-parenting.
186///
187/// Returns more than one element only for a file that violates the `[0:1]`
188/// cardinality of `Nests`.
189#[must_use]
190pub fn parents_of(model: &Model, child: EntityId) -> Vec<EntityId> {
191    let mut out = Vec::new();
192    for (_, entity) in model.of_type("IFCRELNESTS") {
193        let mut names_child = false;
194        if let Some(v) = entity.attribute(nests::RELATED) {
195            v.for_each_ref(&mut |id| {
196                if id == child {
197                    names_child = true;
198                }
199            });
200        }
201        if !names_child {
202            continue;
203        }
204        if let Some(Value::Ref(parent)) = entity.attribute(nests::RELATING) {
205            if !out.contains(parent) {
206                out.push(*parent);
207            }
208        }
209    }
210    out
211}
212
213/// Every descendant of a cost item, depth-first in authored order.
214///
215/// Excludes the root itself. Returns an error rather than looping if the file
216/// states a cycle or an unreasonably deep tree.
217///
218/// # Errors
219///
220/// [`CostRelationError::NestingCycle`] if an item is its own ancestor, or
221/// [`CostRelationError::DepthExceeded`] past [`MAX_NESTING_DEPTH`].
222pub fn descendants_of(model: &Model, root: EntityId) -> Result<Vec<EntityId>, CostRelationError> {
223    let mut out = Vec::new();
224    let mut path = Vec::new();
225    let mut on_path = HashSet::new();
226    walk(model, root, &mut out, &mut path, &mut on_path)?;
227    Ok(out)
228}
229
230fn walk(
231    model: &Model,
232    node: EntityId,
233    out: &mut Vec<EntityId>,
234    path: &mut Vec<EntityId>,
235    on_path: &mut HashSet<EntityId>,
236) -> Result<(), CostRelationError> {
237    if path.len() >= MAX_NESTING_DEPTH {
238        return Err(CostRelationError::DepthExceeded {
239            at: node,
240            limit: MAX_NESTING_DEPTH,
241        });
242    }
243    path.push(node);
244    on_path.insert(node);
245
246    for child in children_of(model, node) {
247        if on_path.contains(&child) {
248            let mut cycle = path.clone();
249            cycle.push(child);
250            return Err(CostRelationError::NestingCycle {
251                repeated: child,
252                path: cycle,
253            });
254        }
255        out.push(child);
256        walk(model, child, out, path, on_path)?;
257    }
258
259    path.pop();
260    on_path.remove(&node);
261    Ok(())
262}
263
264/// Objects a cost item is assigned to price, via `IfcRelAssignsToControl`.
265///
266/// This is how a cost item reaches the products it costs. Deduplicated and
267/// returned in file order.
268#[must_use]
269pub fn controlled_by(model: &Model, control: EntityId) -> Vec<EntityId> {
270    let mut out = Vec::new();
271    for (_, entity) in model.of_type("IFCRELASSIGNSTOCONTROL") {
272        let relating = match entity.attribute(assigns::RELATING) {
273            Some(Value::Ref(id)) => *id,
274            _ => continue,
275        };
276        if relating != control {
277            continue;
278        }
279        if let Some(v) = entity.attribute(assigns::RELATED) {
280            v.for_each_ref(&mut |id| {
281                if !out.contains(&id) {
282                    out.push(id);
283                }
284            });
285        }
286    }
287    out
288}
289
290/// The controls assigned to an object: the inverse of [`controlled_by`].
291#[must_use]
292pub fn controls_of(model: &Model, object: EntityId) -> Vec<EntityId> {
293    let mut out = Vec::new();
294    for (_, entity) in model.of_type("IFCRELASSIGNSTOCONTROL") {
295        let mut names_object = false;
296        if let Some(v) = entity.attribute(assigns::RELATED) {
297            v.for_each_ref(&mut |id| {
298                if id == object {
299                    names_object = true;
300                }
301            });
302        }
303        if !names_object {
304            continue;
305        }
306        if let Some(Value::Ref(control)) = entity.attribute(assigns::RELATING) {
307            if !out.contains(control) {
308                out.push(*control);
309            }
310        }
311    }
312    out
313}