Skip to main content

reserving_kernels/diagnostics/
triangle_diagnostics.rs

1//! Triangle sanity-check kernels.
2//!
3//! This module stays below method selection and reserve indication logic. It
4//! answers basic structural questions about a row-major triangle before any
5//! reserving method consumes it.
6
7use crate::triangle;
8use crate::types::TriangleView;
9
10/// Flag emitted for a cell-level diagnostic condition.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct CellFlag {
13    /// Origin row index.
14    pub origin: usize,
15    /// Development column index.
16    pub dev: usize,
17}
18
19/// Flag emitted for a row-level diagnostic condition.
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct RowFlag {
22    /// Origin row index.
23    pub origin: usize,
24}
25
26/// Summary diagnostics for one triangle.
27#[derive(Debug, Clone, PartialEq)]
28pub struct TriangleDiagnostics {
29    /// Number of origin rows.
30    pub n_origin: usize,
31    /// Number of development columns.
32    pub n_dev: usize,
33    /// Count of finite observed cells inside the scheduled triangle.
34    pub observed_count: usize,
35    /// Count of missing cells (`NaN`) inside the scheduled triangle.
36    pub missing_count: usize,
37    /// Count of observed incremental cells below zero after cumulative differencing.
38    pub negative_increment_count: usize,
39    /// Count of origin rows with at least one cumulative decrease.
40    pub non_monotone_row_count: usize,
41    /// Count of origin rows whose latest observed value is exactly zero.
42    pub zero_latest_count: usize,
43    /// Count of origin rows with zero or one observed cell.
44    pub sparse_origin_count: usize,
45    /// Latest observed cumulative value by origin under scheduled triangle geometry.
46    pub latest_diagonal: Vec<f64>,
47}
48
49/// Build a boolean mask for scheduled observed cells.
50pub fn observed_mask(t: &TriangleView<'_>) -> Vec<bool> {
51    let mut out = vec![false; t.n_origins * t.n_devs];
52    for i in 0..t.n_origins {
53        for j in 0..t.n_devs {
54            out[i * t.n_devs + j] = t.is_scheduled_observed(i, j);
55        }
56    }
57    out
58}
59
60/// Latest finite observed cumulative value by origin.
61///
62/// Returns `NaN` for rows with no finite scheduled observed cells.
63pub fn latest_diagonal(t: &TriangleView<'_>) -> Vec<f64> {
64    let ages = development_age_by_origin(t);
65    ages.iter()
66        .enumerate()
67        .map(|(origin, &dev)| {
68            if dev < t.n_devs {
69                t.get(origin, dev)
70            } else {
71                f64::NAN
72            }
73        })
74        .collect()
75}
76
77/// Convert cumulative to incremental using scheduled triangle geometry.
78pub fn incremental_from_cumulative(t: &TriangleView<'_>) -> Vec<f64> {
79    triangle::cumulative_to_incremental(t)
80}
81
82/// Convert incremental to cumulative using scheduled triangle geometry.
83pub fn cumulative_from_incremental(t: &TriangleView<'_>) -> Vec<f64> {
84    triangle::incremental_to_cumulative(t)
85}
86
87/// Flag cells whose incremental emergence is negative.
88pub fn negative_increment_flags(t: &TriangleView<'_>) -> Vec<CellFlag> {
89    let mut flags = Vec::new();
90    for i in 0..t.n_origins {
91        for j in 0..t.n_devs {
92            if !t.is_scheduled_observed(i, j) {
93                continue;
94            }
95            let cur = t.get(i, j);
96            if !cur.is_finite() {
97                continue;
98            }
99            let inc = if j == 0 {
100                cur
101            } else {
102                let prev = t.get(i, j - 1);
103                if !prev.is_finite() {
104                    continue;
105                }
106                cur - prev
107            };
108            if inc < 0.0 {
109                flags.push(CellFlag { origin: i, dev: j });
110            }
111        }
112    }
113    flags
114}
115
116/// Flag origin rows containing at least one cumulative decrease.
117pub fn monotonicity_flags(t: &TriangleView<'_>) -> Vec<RowFlag> {
118    let mut flags = Vec::new();
119    for origin in 0..t.n_origins {
120        let mut previous: Option<f64> = None;
121        let mut row_flagged = false;
122        for dev in 0..t.n_devs {
123            if !t.is_scheduled_observed(origin, dev) {
124                continue;
125            }
126            let value = t.get(origin, dev);
127            if !value.is_finite() {
128                continue;
129            }
130            if let Some(prev) = previous {
131                if value < prev {
132                    row_flagged = true;
133                    break;
134                }
135            }
136            previous = Some(value);
137        }
138        if row_flagged {
139            flags.push(RowFlag { origin });
140        }
141    }
142    flags
143}
144
145/// Latest finite observed development age by origin.
146///
147/// For rows with no finite scheduled observed cells, returns `n_dev`.
148pub fn development_age_by_origin(t: &TriangleView<'_>) -> Vec<usize> {
149    let mut out = vec![t.n_devs; t.n_origins];
150    for origin in 0..t.n_origins {
151        let mut latest = None;
152        for dev in 0..t.n_devs {
153            if t.is_scheduled_observed(origin, dev) && t.get(origin, dev).is_finite() {
154                latest = Some(dev);
155            }
156        }
157        if let Some(dev) = latest {
158            out[origin] = dev;
159        }
160    }
161    out
162}
163
164/// Summarize the structural state of a triangle.
165pub fn analyze(t: &TriangleView<'_>) -> TriangleDiagnostics {
166    let mask = observed_mask(t);
167    let latest = latest_diagonal(t);
168    let negative_increment = negative_increment_flags(t);
169    let monotonicity = monotonicity_flags(t);
170
171    let mut observed_count = 0;
172    let mut missing_count = 0;
173    let mut sparse_origin_count = 0;
174
175    for origin in 0..t.n_origins {
176        let mut row_observed = 0;
177        for dev in 0..t.n_devs {
178            if !mask[origin * t.n_devs + dev] {
179                continue;
180            }
181            let value = t.get(origin, dev);
182            if value.is_finite() {
183                observed_count += 1;
184                row_observed += 1;
185            } else {
186                missing_count += 1;
187            }
188        }
189        if row_observed <= 1 {
190            sparse_origin_count += 1;
191        }
192    }
193
194    let zero_latest_count = latest
195        .iter()
196        .filter(|value| value.is_finite() && **value == 0.0)
197        .count();
198
199    TriangleDiagnostics {
200        n_origin: t.n_origins,
201        n_dev: t.n_devs,
202        observed_count,
203        missing_count,
204        negative_increment_count: negative_increment.len(),
205        non_monotone_row_count: monotonicity.len(),
206        zero_latest_count,
207        sparse_origin_count,
208        latest_diagonal: latest,
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use crate::types::Triangle;
216
217    fn triangle_4x4() -> Triangle {
218        #[rustfmt::skip]
219        let data = vec![
220            100.0, 150.0, 170.0, 175.0,
221            110.0, 165.0, 190.0, f64::NAN,
222            120.0, 180.0, f64::NAN, f64::NAN,
223            130.0, f64::NAN, f64::NAN, f64::NAN,
224        ];
225        Triangle::new(4, 4, data)
226    }
227
228    #[test]
229    fn latest_and_development_age_follow_triangle_geometry() {
230        let tri = triangle_4x4();
231
232        assert_eq!(development_age_by_origin(&tri.view()), vec![3, 2, 1, 0]);
233        assert_eq!(
234            latest_diagonal(&tri.view()),
235            vec![175.0, 190.0, 180.0, 130.0]
236        );
237    }
238
239    #[test]
240    fn observed_mask_marks_only_scheduled_cells() {
241        let tri = triangle_4x4();
242        let mask = observed_mask(&tri.view());
243
244        assert_eq!(mask.len(), 16);
245        assert!(mask[0]);
246        assert!(mask[6]);
247        assert!(!mask[7]);
248        assert!(!mask[15]);
249    }
250
251    #[test]
252    fn negative_increment_and_monotonicity_flags_detect_problems() {
253        #[rustfmt::skip]
254        let tri = Triangle::new(3, 3, vec![
255            100.0, 90.0, 120.0,
256            80.0, 100.0, f64::NAN,
257            70.0, f64::NAN, f64::NAN,
258        ]);
259
260        assert_eq!(
261            negative_increment_flags(&tri.view()),
262            vec![CellFlag { origin: 0, dev: 1 }]
263        );
264        assert_eq!(monotonicity_flags(&tri.view()), vec![RowFlag { origin: 0 }]);
265    }
266
267    #[test]
268    fn analyze_counts_missing_sparse_and_zero_latest_rows() {
269        #[rustfmt::skip]
270        let tri = Triangle::new(4, 4, vec![
271            100.0, 150.0, 170.0, 0.0,
272            110.0, 165.0, f64::NAN, f64::NAN,
273            0.0, f64::NAN, f64::NAN, f64::NAN,
274            130.0, f64::NAN, f64::NAN, f64::NAN,
275        ]);
276
277        let diagnostics = analyze(&tri.view());
278
279        assert_eq!(diagnostics.observed_count, 8);
280        assert_eq!(diagnostics.missing_count, 2);
281        assert_eq!(diagnostics.zero_latest_count, 2);
282        assert_eq!(diagnostics.sparse_origin_count, 2);
283        assert_eq!(diagnostics.latest_diagonal, vec![0.0, 165.0, 0.0, 130.0]);
284    }
285}