ifc_cost/rollup.rs
1//! Totalling a cost tree.
2//!
3//! # Direct versus rolled-up totals
4//!
5//! A cost item may state its own values AND nest children that state theirs.
6//! Adding both double-counts if the parent's value is a summary of the
7//! children, and under-counts if it is not -- and IFC does not say which.
8//!
9//! So both readings are offered explicitly and neither is called "the total":
10//!
11//! - [`direct_total`]: this item's own values only.
12//! - [`rolled_up_total`]: the sum over descendants, ignoring the parent's own
13//! stated value.
14//!
15//! A caller who knows their authoring convention picks one. A caller who does
16//! not can compare them: when a parent's direct total equals its rolled-up
17//! total, the file is self-consistent and either reading works. When they
18//! differ, that difference is information, and [`consistency`] reports it
19//! rather than hiding it behind a chosen default.
20
21use ifc_model::{EntityId, Model};
22
23use crate::item::CostItem;
24use crate::relation::{descendants_of, CostRelationError};
25use crate::view::CostView;
26
27/// Total the direct cost values of one item.
28///
29/// Does not recurse. Composed values (those with `Components` and no stated
30/// `AppliedValue`) contribute nothing here, because this crate does not fold
31/// an arithmetic tree whose bracketing the schema leaves undefined.
32#[must_use]
33pub fn direct_total(view: &CostView<'_>, item: &CostItem<'_>) -> f64 {
34 view.values_of(item).iter().filter_map(|v| v.amount()).sum()
35}
36
37/// Total the direct values of every descendant, excluding the item itself.
38///
39/// # Errors
40///
41/// Propagates [`CostRelationError`] when the nesting graph cycles or exceeds
42/// its depth budget.
43pub fn rolled_up_total(view: &CostView<'_>, item: &CostItem<'_>) -> Result<f64, CostRelationError> {
44 let model = view.model();
45 let mut total = 0.0;
46 for id in descendants_of(model, item.id())? {
47 if let Some(entity) = model.get(id) {
48 total += direct_total(view, &CostItem::new(id, entity));
49 }
50 }
51 Ok(total)
52}
53
54/// How an item's own stated total compares with the sum of its children.
55#[derive(Debug, Clone, Copy, PartialEq)]
56#[non_exhaustive]
57pub struct Consistency {
58 /// The item's own stated values.
59 pub direct: f64,
60 /// The sum over its descendants.
61 pub rolled_up: f64,
62 /// Whether the item states any values of its own.
63 pub states_own_value: bool,
64 /// Whether it has any descendants.
65 pub has_children: bool,
66}
67
68impl Consistency {
69 /// Whether both readings agree within `tolerance`.
70 ///
71 /// An item with no children, or none of its own values, is trivially
72 /// consistent: there is only one reading to take.
73 #[must_use]
74 pub fn agrees(&self, tolerance: f64) -> bool {
75 if !self.has_children || !self.states_own_value {
76 return true;
77 }
78 (self.direct - self.rolled_up).abs() <= tolerance
79 }
80}
81
82/// Compare an item's direct total against its rolled-up total.
83///
84/// # Errors
85///
86/// Propagates [`CostRelationError`] from the nesting walk.
87pub fn consistency(
88 view: &CostView<'_>,
89 item: &CostItem<'_>,
90) -> Result<Consistency, CostRelationError> {
91 let direct = direct_total(view, item);
92 let rolled_up = rolled_up_total(view, item)?;
93 Ok(Consistency {
94 direct,
95 rolled_up,
96 states_own_value: !view.values_of(item).is_empty(),
97 has_children: !crate::relation::children_of(view.model(), item.id()).is_empty(),
98 })
99}
100
101/// Total the direct cost values of every item in the model.
102///
103/// A flat sum over every `IfcCostItem`, which double-counts any file whose
104/// parents summarise their children. Useful as a coarse figure and as a
105/// regression check, not as an estimate.
106#[must_use]
107pub fn grand_total(view: &CostView<'_>) -> f64 {
108 view.items().map(|item| direct_total(view, &item)).sum()
109}
110
111/// Cost items that are not nested under any other item.
112///
113/// These are the entry points of the breakdown: totalling their rolled-up
114/// values counts each leaf exactly once.
115#[must_use]
116pub fn roots(view: &CostView<'_>) -> Vec<EntityId> {
117 let model: &Model = view.model();
118 view.items()
119 .map(|item| item.id())
120 .filter(|id| crate::relation::parent_of(model, *id).is_none())
121 .collect()
122}