Skip to main content

reserving_kernels/deterministic/
brosius.rs

1//! Brosius least-squares development.
2//!
3//! For each development link `j → j+1`, Brosius fits the best linear
4//! predictor of `C_{i, j+1}` given `C_{i, j}`:
5//!
6//! `C_{i, j+1} ≈ a_j + b_j × C_{i, j}`.
7//!
8//! OLS gives `b_j = cov(x, y) / var(x)` and `a_j = mean(y) − b_j × mean(x)`,
9//! where `(x, y) = (C_{·,j}, C_{·,j+1})` over origins `i = 0..n−j−2`.
10//!
11//! Brosius is a credibility-weighted estimator: `b_j = 0` recovers a pure
12//! budget method (expected next value is constant), `b_j = f_j` with
13//! `a_j = 0` recovers chain-ladder. Real triangles typically fall between.
14//!
15//! Returns `(a, b, next_projection)` per link, and per-origin ultimates by
16//! chaining projections forward from each origin's latest observation.
17
18use crate::preprocessing::triangle::latest_diagonal;
19use crate::types::TriangleView;
20use crate::validate::{
21    MonotonicityPolicy, ValidationError, validate_finite_slice, validate_monotone_cumulative,
22    validate_observed_count_inputs, validate_tail, validate_triangle,
23};
24
25/// Brosius projection result.
26#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
27pub struct Brosius {
28    /// Intercept per link: `a_j`, length `n − 1`.
29    pub intercept: Vec<f64>,
30    /// Slope per link: `b_j`, length `n − 1`.
31    pub slope: Vec<f64>,
32    /// Estimated ultimate per origin.
33    pub ultimate: Vec<f64>,
34    /// Unpaid reserve per origin.
35    pub reserve: Vec<f64>,
36    /// Latest observed cumulative value per origin.
37    pub latest: Vec<f64>,
38    /// OLS fit diagnostics per development link.
39    pub diagnostics: Vec<BrosiusLinkDiagnostic>,
40}
41
42impl Brosius {
43    /// Credibility weight `Z_j = b_j * mean_x / mean_y` per link (Brosius 1993).
44    ///
45    /// Expresses the OLS predictor `a_j + b_j * x` in credibility form
46    /// `Z_j * (f_j * x) + (1 - Z_j) * mean_y` where `f_j = mean_y / mean_x`
47    /// is the volume-weighted link ratio.
48    pub fn credibility_weights(&self) -> Vec<f64> {
49        self.diagnostics
50            .iter()
51            .map(|d| {
52                if d.mean_y.is_finite() && d.mean_y > 0.0 && d.mean_x.is_finite() {
53                    d.slope * d.mean_x / d.mean_y
54                } else {
55                    f64::NAN
56                }
57            })
58            .collect()
59    }
60}
61
62/// Brosius OLS fit diagnostics for one development link.
63#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
64pub struct BrosiusLinkDiagnostic {
65    /// Development link start index.
66    pub dev: usize,
67    /// Number of observed pairs used.
68    pub n: usize,
69    /// Mean prior cumulative value.
70    pub mean_x: f64,
71    /// Mean next cumulative value.
72    pub mean_y: f64,
73    /// Population variance of prior cumulative values.
74    pub var_x: f64,
75    /// Population covariance between prior and next cumulative values.
76    pub cov_xy: f64,
77    /// Fitted intercept.
78    pub intercept: f64,
79    /// Fitted slope.
80    pub slope: f64,
81    /// Whether the single-pair chain-ladder-ratio fallback was used.
82    pub fallback_used: bool,
83}
84
85/// Fit Brosius OLS parameters per link and project ultimates without validation.
86///
87/// `tail` is the multiplicative tail factor applied at development age
88/// `n − 1` (pass `1.0` for fully-developed).
89///
90/// Prefer [`project`] at external ingress boundaries.
91pub fn project_unchecked(t: &TriangleView<'_>, tail: f64) -> Brosius {
92    let n = t.n_origins.min(t.n_devs);
93    let latest = latest_diagonal(t);
94    let mut intercept = vec![0.0; n.saturating_sub(1)];
95    let mut slope = vec![0.0; n.saturating_sub(1)];
96    let mut diagnostics = Vec::with_capacity(n.saturating_sub(1));
97
98    for j in 0..n.saturating_sub(1) {
99        let k = n - j - 1; // number of origins with both (i, j) and (i, j+1)
100        let mut sx = 0.0;
101        let mut sy = 0.0;
102        for i in 0..k {
103            sx += t.get(i, j);
104            sy += t.get(i, j + 1);
105        }
106        let kf = k as f64;
107        let mut mean_x = f64::NAN;
108        let mut mean_y = f64::NAN;
109        let mut var_x = f64::NAN;
110        let mut cov_xy = f64::NAN;
111        let mut fallback_used = false;
112        if k >= 2 {
113            mean_x = sx / kf;
114            mean_y = sy / kf;
115            // Two-pass centered sums prevent catastrophic cancellation on large loss amounts.
116            let mut sum_dx2 = 0.0;
117            let mut sum_dxdy = 0.0;
118            for i in 0..k {
119                let dx = t.get(i, j) - mean_x;
120                let dy = t.get(i, j + 1) - mean_y;
121                sum_dx2 += dx * dx;
122                sum_dxdy += dx * dy;
123            }
124            var_x = sum_dx2 / kf;
125            cov_xy = sum_dxdy / kf;
126            let var_tol = 1e-12 * mean_x * mean_x;
127            let b = if var_x > var_tol { cov_xy / var_x } else { 0.0 };
128            let a = mean_y - b * mean_x;
129            intercept[j] = a;
130            slope[j] = b;
131        } else if k == 1 {
132            // Degenerate: single pair, use chain-ladder ratio as slope, no
133            // intercept (a = 0).
134            let x = t.get(0, j);
135            let y = t.get(0, j + 1);
136            intercept[j] = 0.0;
137            slope[j] = if x > 0.0 { y / x } else { f64::NAN };
138            mean_x = x;
139            mean_y = y;
140            var_x = 0.0;
141            cov_xy = 0.0;
142            fallback_used = true;
143        } else {
144            intercept[j] = f64::NAN;
145            slope[j] = f64::NAN;
146        }
147        diagnostics.push(BrosiusLinkDiagnostic {
148            dev: j,
149            n: k,
150            mean_x,
151            mean_y,
152            var_x,
153            cov_xy,
154            intercept: intercept[j],
155            slope: slope[j],
156            fallback_used,
157        });
158    }
159
160    let mut ultimate = vec![0.0; n];
161    let mut reserve = vec![0.0; n];
162    for i in 0..n {
163        let mut c = latest[i];
164        let start = n - 1 - i;
165        for j in start..n.saturating_sub(1) {
166            c = intercept[j] + slope[j] * c;
167        }
168        c *= tail;
169        ultimate[i] = c;
170        reserve[i] = c - latest[i];
171    }
172    Brosius {
173        intercept,
174        slope,
175        ultimate,
176        reserve,
177        latest,
178        diagnostics,
179    }
180}
181
182/// Fit Brosius OLS parameters per link and project ultimates from observed row widths.
183///
184/// `observed_counts[i]` is the number of observed development periods in row
185/// `i`. Each link fit uses rows where both `dev` and `dev + 1` are observed.
186pub fn project_observed_counts(
187    t: &TriangleView<'_>,
188    observed_counts: &[usize],
189    tail: f64,
190) -> Result<Brosius, ValidationError> {
191    validate_observed_count_inputs(t, observed_counts, tail)?;
192    let n_origin = t.n_origins;
193    let n_dev = t.n_devs;
194    let mut latest = vec![0.0; n_origin];
195    for i in 0..n_origin {
196        latest[i] = t.get(i, observed_counts[i] - 1);
197    }
198
199    let mut intercept = vec![0.0; n_dev.saturating_sub(1)];
200    let mut slope = vec![0.0; n_dev.saturating_sub(1)];
201    let mut diagnostics = Vec::with_capacity(n_dev.saturating_sub(1));
202    for dev in 0..n_dev.saturating_sub(1) {
203        let mut k = 0usize;
204        let mut first_origin = 0usize;
205        let mut sx = 0.0;
206        let mut sy = 0.0;
207        for (origin, &count) in observed_counts.iter().enumerate() {
208            if count > dev + 1 {
209                if k == 0 {
210                    first_origin = origin;
211                }
212                k += 1;
213                sx += t.get(origin, dev);
214                sy += t.get(origin, dev + 1);
215            }
216        }
217
218        let kf = k as f64;
219        let mut mean_x = f64::NAN;
220        let mut mean_y = f64::NAN;
221        let mut var_x = f64::NAN;
222        let mut cov_xy = f64::NAN;
223        let mut fallback_used = false;
224        if k >= 2 {
225            mean_x = sx / kf;
226            mean_y = sy / kf;
227            let mut sum_dx2 = 0.0;
228            let mut sum_dxdy = 0.0;
229            for (origin, &count) in observed_counts.iter().enumerate() {
230                if count > dev + 1 {
231                    let dx = t.get(origin, dev) - mean_x;
232                    let dy = t.get(origin, dev + 1) - mean_y;
233                    sum_dx2 += dx * dx;
234                    sum_dxdy += dx * dy;
235                }
236            }
237            var_x = sum_dx2 / kf;
238            cov_xy = sum_dxdy / kf;
239            let var_tol = 1e-12 * mean_x * mean_x;
240            let b = if var_x > var_tol { cov_xy / var_x } else { 0.0 };
241            let a = mean_y - b * mean_x;
242            intercept[dev] = a;
243            slope[dev] = b;
244        } else if k == 1 {
245            let x = t.get(first_origin, dev);
246            let y = t.get(first_origin, dev + 1);
247            intercept[dev] = 0.0;
248            slope[dev] = if x > 0.0 { y / x } else { f64::NAN };
249            mean_x = x;
250            mean_y = y;
251            var_x = 0.0;
252            cov_xy = 0.0;
253            fallback_used = true;
254        } else {
255            intercept[dev] = f64::NAN;
256            slope[dev] = f64::NAN;
257        }
258        diagnostics.push(BrosiusLinkDiagnostic {
259            dev,
260            n: k,
261            mean_x,
262            mean_y,
263            var_x,
264            cov_xy,
265            intercept: intercept[dev],
266            slope: slope[dev],
267            fallback_used,
268        });
269    }
270
271    let mut ultimate = vec![0.0; n_origin];
272    let mut reserve = vec![0.0; n_origin];
273    for i in 0..n_origin {
274        let mut c = latest[i];
275        for dev in (observed_counts[i] - 1)..n_dev.saturating_sub(1) {
276            c = intercept[dev] + slope[dev] * c;
277        }
278        c *= tail;
279        ultimate[i] = c;
280        reserve[i] = c - latest[i];
281    }
282
283    let projection = Brosius {
284        intercept,
285        slope,
286        ultimate,
287        reserve,
288        latest,
289        diagnostics,
290    };
291    validate_finite_slice(&projection.intercept)?;
292    validate_finite_slice(&projection.slope)?;
293    validate_finite_slice(&projection.ultimate)?;
294    validate_finite_slice(&projection.reserve)?;
295    Ok(projection)
296}
297
298/// Fit Brosius OLS parameters per link and project ultimates after validation.
299///
300/// The checked path enforces square-triangle shape, finite non-negative
301/// observed cells, monotone cumulative rows, `tail >= 1`, and finite projected
302/// parameters and outputs.
303pub fn project(t: &TriangleView<'_>, tail: f64) -> Result<Brosius, ValidationError> {
304    project_with_policy(t, tail, MonotonicityPolicy::Strict)
305}
306
307/// Fit Brosius OLS parameters per link and project ultimates under an explicit
308/// [`MonotonicityPolicy`].
309pub fn project_with_policy(
310    t: &TriangleView<'_>,
311    tail: f64,
312    policy: MonotonicityPolicy,
313) -> Result<Brosius, ValidationError> {
314    validate_triangle(t)?;
315    if policy == MonotonicityPolicy::Strict {
316        validate_monotone_cumulative(t)?;
317    }
318    validate_tail(tail)?;
319
320    let projection = project_unchecked(t, tail);
321    validate_finite_slice(&projection.intercept)?;
322    validate_finite_slice(&projection.slope)?;
323    validate_finite_slice(&projection.latest)?;
324    validate_finite_slice(&projection.ultimate)?;
325    validate_finite_slice(&projection.reserve)?;
326    for diagnostic in &projection.diagnostics {
327        if !diagnostic.mean_x.is_finite()
328            || !diagnostic.mean_y.is_finite()
329            || !diagnostic.var_x.is_finite()
330            || !diagnostic.cov_xy.is_finite()
331            || !diagnostic.intercept.is_finite()
332            || !diagnostic.slope.is_finite()
333        {
334            return Err(ValidationError::NotFinite);
335        }
336    }
337    Ok(projection)
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use crate::types::Triangle;
344
345    #[test]
346    fn project_rejects_non_cumulative_triangle() {
347        #[rustfmt::skip]
348        let triangle = Triangle::new(3, 3, vec![
349            100.0, 150.0, 180.0,
350            120.0, 110.0, f64::NAN,
351            140.0, f64::NAN, f64::NAN,
352        ]);
353
354        assert!(matches!(
355            project(&triangle.view(), 1.0),
356            Err(ValidationError::NonMonotoneCumulative {
357                origin: 1,
358                dev: 1,
359                previous: 120.0,
360                value: 110.0,
361            })
362        ));
363    }
364
365    #[test]
366    fn project_rejects_invalid_tail() {
367        #[rustfmt::skip]
368        let triangle = Triangle::new(3, 3, vec![
369            100.0, 150.0, 180.0,
370            120.0, 180.0, f64::NAN,
371            140.0, f64::NAN, f64::NAN,
372        ]);
373
374        assert!(matches!(
375            project(&triangle.view(), 0.99),
376            Err(ValidationError::InvalidTail { tail: 0.99 })
377        ));
378    }
379
380    #[test]
381    fn project_returns_link_diagnostics() {
382        #[rustfmt::skip]
383        let triangle = Triangle::new(3, 3, vec![
384            100.0, 150.0, 180.0,
385            120.0, 180.0, f64::NAN,
386            140.0, f64::NAN, f64::NAN,
387        ]);
388
389        let projection = project(&triangle.view(), 1.0).expect("brosius");
390
391        assert_eq!(projection.diagnostics.len(), 2);
392        assert_eq!(projection.diagnostics[0].n, 2);
393        assert!(!projection.diagnostics[0].fallback_used);
394        assert_eq!(projection.diagnostics[1].n, 1);
395        assert!(projection.diagnostics[1].fallback_used);
396    }
397
398    #[test]
399    fn project_observed_counts_projects_rectangular_triangle() {
400        #[rustfmt::skip]
401        let data = vec![
402            100.0, 150.0, 180.0, 198.0,
403            120.0, 180.0, 216.0, f64::NAN,
404            140.0, 210.0, f64::NAN, f64::NAN,
405        ];
406        let view = TriangleView {
407            n_origins: 3,
408            n_devs: 4,
409            data: &data,
410        };
411
412        let projection =
413            project_observed_counts(&view, &[4, 3, 2], 1.0).expect("brosius rectangular");
414
415        assert_eq!(projection.diagnostics.len(), 3);
416        assert_eq!(projection.reserve.len(), 3);
417        assert!(projection.ultimate[0].is_finite());
418        assert!(projection.ultimate[2] > projection.latest[2]);
419        assert!(projection.diagnostics[2].fallback_used);
420    }
421}