Skip to main content

reserving_kernels/preprocessing/
exhibit.rs

1//! Typed actuarial exhibit DTOs over the reserving kernels.
2//!
3//! This module reshapes checked kernel outputs into stable, serializable
4//! structures for tables, heatmaps, and method-comparison charts. It does not
5//! reimplement reserving math.
6
7use serde::Serialize;
8
9use crate::deterministic::bf::{BornhuetterFergusonEngine, BornhuetterFergusonProjection};
10use crate::deterministic::brosius::{self, Brosius};
11use crate::deterministic::cape_cod::{CapeCodEngine, CapeCodProjection};
12use crate::deterministic::chain_ladder::ChainLadderEngine;
13use crate::deterministic::ldf::{DevelopmentFactorEngine, DevelopmentFactors};
14use crate::preprocessing::triangle::cumulative_to_incremental;
15use crate::stochastic::mack::{self, Mack};
16use crate::types::TriangleView;
17use crate::validate::{ValidationError, validate_monotone_cumulative, validate_triangle};
18
19/// Full exhibit payload for a visualization workbench.
20#[derive(Debug, Clone, Serialize)]
21pub struct ExhibitBundle {
22    /// Cumulative triangle heatmap/table exhibit.
23    pub triangle: TriangleExhibit,
24    /// Incremental triangle heatmap/table exhibit.
25    pub incremental_triangle: TriangleExhibit,
26    /// Selected factor calculation trail.
27    pub factors: FactorExhibit,
28    /// Per-origin method comparison table.
29    pub projections: ProjectionComparisonExhibit,
30    /// Validation and governance messages for display.
31    pub validation: ValidationExhibit,
32    /// Mack uncertainty exhibit, when Mack calculation succeeds.
33    pub mack: Option<MackExhibit>,
34    /// Brosius regression exhibit, when Brosius calculation succeeds.
35    pub brosius: Option<BrosiusExhibit>,
36}
37
38/// Validation status and display messages.
39#[derive(Debug, Clone, Serialize)]
40pub struct ValidationExhibit {
41    /// Whether the exhibit builder accepted the inputs.
42    pub ok: bool,
43    /// Validation errors suitable for display.
44    pub errors: Vec<String>,
45    /// Non-blocking governance warnings.
46    pub warnings: Vec<String>,
47}
48
49/// One triangle cell for heatmaps and dense tables.
50#[derive(Debug, Clone, Serialize)]
51pub struct TriangleCellDto {
52    /// Origin row index.
53    pub origin: usize,
54    /// Development column index.
55    pub dev: usize,
56    /// Cell value; `None` represents unobserved/missing values.
57    pub value: Option<f64>,
58    /// Whether the cell is scheduled observed under square right-triangle geometry.
59    pub observed: bool,
60    /// Whether the cell is on the latest diagonal.
61    pub latest: bool,
62    /// Whether this value is a projection rather than observed data.
63    pub projected: bool,
64}
65
66/// Triangle display payload.
67#[derive(Debug, Clone, Serialize)]
68pub struct TriangleExhibit {
69    /// Origin row count.
70    pub n_origins: usize,
71    /// Development column count.
72    pub n_devs: usize,
73    /// Row-major display cells.
74    pub cells: Vec<TriangleCellDto>,
75}
76
77/// One factor row tying factor selection, CDF, maturity, and credibility.
78#[derive(Debug, Clone, Serialize)]
79pub struct FactorExhibitRow {
80    /// Development age `j` for the `j -> j + 1` link.
81    pub dev: usize,
82    /// Sum of observed `C[i, j + 1]`.
83    pub numerator: f64,
84    /// Sum of observed `C[i, j]`.
85    pub denominator: f64,
86    /// Selected LDF.
87    pub selected_ldf: f64,
88    /// CDF at development age `j`.
89    pub cdf: f64,
90    /// Percent mature/reported at development age `j`.
91    pub maturity: f64,
92    /// Number of rows included in the link ratio.
93    pub included_rows: usize,
94}
95
96/// Factor exhibit payload.
97#[derive(Debug, Clone, Serialize)]
98pub struct FactorExhibit {
99    /// Factor rows by development age.
100    pub rows: Vec<FactorExhibitRow>,
101    /// Tail factor used in the CDFs.
102    pub tail: f64,
103}
104
105/// One origin row comparing reserving methods.
106#[derive(Debug, Clone, Serialize)]
107pub struct ProjectionRow {
108    /// Origin row index.
109    pub origin: usize,
110    /// Latest observed development index.
111    pub latest_dev: usize,
112    /// Latest observed cumulative value.
113    pub latest: f64,
114    /// Percent mature/reported at latest observed development.
115    pub maturity: Option<f64>,
116    /// Chain-ladder ultimate.
117    pub chain_ladder_ultimate: Option<f64>,
118    /// Chain-ladder reserve.
119    pub chain_ladder_reserve: Option<f64>,
120    /// BF expected ultimate.
121    pub bf_expected: Option<f64>,
122    /// BF ultimate.
123    pub bf_ultimate: Option<f64>,
124    /// BF reserve.
125    pub bf_reserve: Option<f64>,
126    /// Cape Cod expected ultimate.
127    pub cape_cod_expected: Option<f64>,
128    /// Cape Cod ultimate.
129    pub cape_cod_ultimate: Option<f64>,
130    /// Cape Cod reserve.
131    pub cape_cod_reserve: Option<f64>,
132    /// Mack ultimate.
133    pub mack_ultimate: Option<f64>,
134    /// Mack reserve.
135    pub mack_reserve: Option<f64>,
136    /// Mack standard error.
137    pub mack_se: Option<f64>,
138    /// Mack coefficient of variation.
139    pub mack_cv: Option<f64>,
140    /// Brosius ultimate.
141    pub brosius_ultimate: Option<f64>,
142    /// Brosius reserve.
143    pub brosius_reserve: Option<f64>,
144}
145
146/// Projection totals across methods.
147#[derive(Debug, Clone, Serialize)]
148pub struct ProjectionTotals {
149    /// Total latest observed loss.
150    pub latest: f64,
151    /// Chain-ladder reserve total.
152    pub chain_ladder_reserve: Option<f64>,
153    /// BF reserve total.
154    pub bf_reserve: Option<f64>,
155    /// Cape Cod reserve total.
156    pub cape_cod_reserve: Option<f64>,
157    /// Mack reserve total.
158    pub mack_reserve: Option<f64>,
159    /// Brosius reserve total.
160    pub brosius_reserve: Option<f64>,
161}
162
163/// Method comparison display payload.
164#[derive(Debug, Clone, Serialize)]
165pub struct ProjectionComparisonExhibit {
166    /// Per-origin method rows.
167    pub rows: Vec<ProjectionRow>,
168    /// Portfolio totals.
169    pub totals: ProjectionTotals,
170}
171
172/// Mack uncertainty display payload.
173#[derive(Debug, Clone, Serialize)]
174pub struct MackExhibit {
175    /// Origin rows with reserve uncertainty.
176    pub rows: Vec<MackOriginRiskRow>,
177    /// Sigma squared by development link.
178    pub sigma_rows: Vec<MackSigmaRow>,
179    /// Total reserve.
180    pub total_reserve: f64,
181    /// Total standard error.
182    pub total_standard_error: f64,
183    /// Total coefficient of variation.
184    pub total_cv: f64,
185    /// Normal-approximation portfolio quantiles.
186    pub quantiles: MackQuantiles,
187    /// Tail uncertainty disclosure for display.
188    pub tail_disclosure: String,
189}
190
191/// Per-origin Mack uncertainty row.
192#[derive(Debug, Clone, Serialize)]
193pub struct MackOriginRiskRow {
194    /// Origin row index.
195    pub origin: usize,
196    /// Mack reserve.
197    pub reserve: f64,
198    /// Mack standard error.
199    pub standard_error: f64,
200    /// Mack coefficient of variation.
201    pub cv: f64,
202    /// Reserve minus one standard error.
203    pub reserve_minus_1se: f64,
204    /// Reserve plus one standard error.
205    pub reserve_plus_1se: f64,
206}
207
208/// Mack sigma-squared row by development link.
209#[derive(Debug, Clone, Serialize)]
210pub struct MackSigmaRow {
211    /// Development link start index.
212    pub dev: usize,
213    /// Mack sigma squared.
214    pub sigma_sq: f64,
215}
216
217/// Normal-approximation Mack reserve quantiles.
218#[derive(Debug, Clone, Serialize)]
219pub struct MackQuantiles {
220    /// 50th percentile.
221    pub p50: f64,
222    /// 75th percentile.
223    pub p75: f64,
224    /// 90th percentile.
225    pub p90: f64,
226    /// 95th percentile.
227    pub p95: f64,
228}
229
230/// Brosius regression display payload.
231#[derive(Debug, Clone, Serialize)]
232pub struct BrosiusExhibit {
233    /// Link fit diagnostics.
234    pub links: Vec<BrosiusLinkExhibitRow>,
235    /// Scatterplot source points by link.
236    pub scatter_points: Vec<BrosiusScatterPoint>,
237}
238
239/// One Brosius link fit row.
240#[derive(Debug, Clone, Serialize)]
241pub struct BrosiusLinkExhibitRow {
242    /// Development link start index.
243    pub dev: usize,
244    /// Number of observed pairs used.
245    pub n: usize,
246    /// Fitted intercept.
247    pub intercept: f64,
248    /// Fitted slope.
249    pub slope: f64,
250    /// Chain-ladder LDF for comparison.
251    pub chain_ladder_ldf: Option<f64>,
252    /// Whether the single-pair fallback was used.
253    pub fallback_used: bool,
254}
255
256/// One observed point for a Brosius scatter/fitted-line chart.
257#[derive(Debug, Clone, Serialize)]
258pub struct BrosiusScatterPoint {
259    /// Development link start index.
260    pub dev: usize,
261    /// Origin row index.
262    pub origin: usize,
263    /// Prior cumulative value.
264    pub x: f64,
265    /// Next cumulative value.
266    pub y: f64,
267    /// Fitted next value.
268    pub fitted_y: f64,
269}
270
271/// Build a full exhibit bundle from a triangle and optional method inputs.
272///
273/// `premium` enables Cape Cod. `expected_ultimate` enables BF. Chain ladder,
274/// Mack, and Brosius are always attempted after shared validation succeeds.
275pub fn build_exhibit_bundle(
276    triangle: &TriangleView<'_>,
277    premium: Option<&[f64]>,
278    expected_ultimate: Option<&[f64]>,
279    tail: f64,
280) -> Result<ExhibitBundle, ValidationError> {
281    validate_triangle(triangle)?;
282    validate_monotone_cumulative(triangle)?;
283
284    let factors = DevelopmentFactorEngine::volume_weighted(triangle, tail)?;
285    let factor_diagnostics = DevelopmentFactorEngine::volume_weighted_diagnostics(triangle, tail)?;
286    let chain_ladder = ChainLadderEngine::project(triangle, &factors)?;
287    let bf = match expected_ultimate {
288        Some(expected) => Some(BornhuetterFergusonEngine::project_from_expected_ultimate(
289            triangle, &factors, expected,
290        )?),
291        None => None,
292    };
293    let cape_cod = match premium {
294        Some(premium) => Some(CapeCodEngine::project(triangle, &factors, premium)?),
295        None => None,
296    };
297    let mack = mack::analyze(triangle, tail)?;
298    let brosius = brosius::project(triangle, tail)?;
299
300    let triangle_exhibit = triangle_exhibit(triangle);
301    let incremental_triangle = incremental_triangle_exhibit(triangle);
302    let factor_exhibit = factor_exhibit(&factors, &factor_diagnostics);
303    let projections = projection_comparison_exhibit(
304        &factors,
305        &chain_ladder,
306        bf.as_ref(),
307        cape_cod.as_ref(),
308        &mack,
309        &brosius,
310    );
311    let mack_exhibit = mack_exhibit(&mack, tail);
312    let brosius_exhibit = brosius_exhibit(triangle, &factors, &brosius);
313
314    let mut warnings = Vec::new();
315    if tail > 1.0 {
316        warnings.push(
317            "Tail factor exceeds 1.0; Mack standard errors do not include tail uncertainty."
318                .to_string(),
319        );
320    }
321    if premium.is_none() {
322        warnings.push("Cape Cod exhibit omitted because premium was not supplied.".to_string());
323    }
324    if expected_ultimate.is_none() {
325        warnings.push("BF exhibit omitted because expected ultimate was not supplied.".to_string());
326    }
327
328    Ok(ExhibitBundle {
329        triangle: triangle_exhibit,
330        incremental_triangle,
331        factors: factor_exhibit,
332        projections,
333        validation: ValidationExhibit {
334            ok: true,
335            errors: Vec::new(),
336            warnings,
337        },
338        mack: Some(mack_exhibit),
339        brosius: Some(brosius_exhibit),
340    })
341}
342
343fn triangle_exhibit(triangle: &TriangleView<'_>) -> TriangleExhibit {
344    triangle_exhibit_from_data(triangle.n_origins, triangle.n_devs, triangle.data, false)
345}
346
347fn incremental_triangle_exhibit(triangle: &TriangleView<'_>) -> TriangleExhibit {
348    let incremental = cumulative_to_incremental(triangle);
349    triangle_exhibit_from_data(triangle.n_origins, triangle.n_devs, &incremental, false)
350}
351
352fn triangle_exhibit_from_data(
353    n_origins: usize,
354    n_devs: usize,
355    data: &[f64],
356    projected: bool,
357) -> TriangleExhibit {
358    let mut cells = Vec::with_capacity(n_origins * n_devs);
359    for origin in 0..n_origins {
360        for dev in 0..n_devs {
361            let observed = origin + dev <= n_devs.saturating_sub(1);
362            let latest = observed && origin + dev == n_devs.saturating_sub(1);
363            let raw = data[origin * n_devs + dev];
364            cells.push(TriangleCellDto {
365                origin,
366                dev,
367                value: raw.is_finite().then_some(raw),
368                observed,
369                latest,
370                projected,
371            });
372        }
373    }
374
375    TriangleExhibit {
376        n_origins,
377        n_devs,
378        cells,
379    }
380}
381
382fn factor_exhibit(
383    factors: &DevelopmentFactors,
384    diagnostics: &[crate::deterministic::ldf::LinkRatioDiagnostic],
385) -> FactorExhibit {
386    let maturity = factors.maturity_percentages();
387    let rows = diagnostics
388        .iter()
389        .map(|diagnostic| FactorExhibitRow {
390            dev: diagnostic.dev,
391            numerator: diagnostic.numerator,
392            denominator: diagnostic.denominator,
393            selected_ldf: diagnostic.selected_ldf,
394            cdf: factors.cdfs[diagnostic.dev],
395            maturity: maturity[diagnostic.dev],
396            included_rows: diagnostic.included_rows,
397        })
398        .collect();
399
400    FactorExhibit {
401        rows,
402        tail: factors.tail,
403    }
404}
405
406fn projection_comparison_exhibit(
407    factors: &DevelopmentFactors,
408    chain_ladder: &crate::deterministic::chain_ladder::ChainLadderProjection,
409    bf: Option<&BornhuetterFergusonProjection>,
410    cape_cod: Option<&CapeCodProjection>,
411    mack: &Mack,
412    brosius: &Brosius,
413) -> ProjectionComparisonExhibit {
414    let factor_maturity = factors.maturity_percentages();
415    let rows = chain_ladder
416        .latest
417        .iter()
418        .enumerate()
419        .map(|(origin, &latest)| {
420            let latest_dev = chain_ladder.latest_dev[origin];
421            ProjectionRow {
422                origin,
423                latest_dev,
424                latest,
425                maturity: bf
426                    .map(|projection| projection.maturity[origin])
427                    .or_else(|| cape_cod.map(|projection| projection.reported_percentage[origin]))
428                    .or_else(|| factor_maturity.get(latest_dev).copied()),
429                chain_ladder_ultimate: Some(chain_ladder.ultimates[origin]),
430                chain_ladder_reserve: Some(chain_ladder.reserves[origin]),
431                bf_expected: bf.map(|projection| projection.expected_ultimate[origin]),
432                bf_ultimate: bf.map(|projection| projection.ultimates[origin]),
433                bf_reserve: bf.map(|projection| projection.reserves[origin]),
434                cape_cod_expected: cape_cod.map(|projection| projection.expected_ultimate[origin]),
435                cape_cod_ultimate: cape_cod
436                    .map(|projection| projection.bf_projection.ultimates[origin]),
437                cape_cod_reserve: cape_cod
438                    .map(|projection| projection.bf_projection.reserves[origin]),
439                mack_ultimate: Some(mack.ultimate[origin]),
440                mack_reserve: Some(mack.reserve[origin]),
441                mack_se: Some(mack.standard_error[origin]),
442                mack_cv: Some(mack.cv[origin]),
443                brosius_ultimate: Some(brosius.ultimate[origin]),
444                brosius_reserve: Some(brosius.reserve[origin]),
445            }
446        })
447        .collect();
448
449    ProjectionComparisonExhibit {
450        rows,
451        totals: ProjectionTotals {
452            latest: chain_ladder.total_latest,
453            chain_ladder_reserve: Some(chain_ladder.total_reserve),
454            bf_reserve: bf.map(|projection| projection.total_reserve),
455            cape_cod_reserve: cape_cod.map(|projection| projection.bf_projection.total_reserve),
456            mack_reserve: Some(mack.total_reserve),
457            brosius_reserve: Some(brosius.reserve.iter().sum()),
458        },
459    }
460}
461
462fn mack_exhibit(mack: &Mack, tail: f64) -> MackExhibit {
463    let rows = mack
464        .reserve
465        .iter()
466        .enumerate()
467        .map(|(origin, &reserve)| {
468            let standard_error = mack.standard_error[origin];
469            MackOriginRiskRow {
470                origin,
471                reserve,
472                standard_error,
473                cv: mack.cv[origin],
474                reserve_minus_1se: reserve - standard_error,
475                reserve_plus_1se: reserve + standard_error,
476            }
477        })
478        .collect();
479    let sigma_rows = mack
480        .sigma_sq
481        .iter()
482        .enumerate()
483        .map(|(dev, &sigma_sq)| MackSigmaRow { dev, sigma_sq })
484        .collect();
485
486    MackExhibit {
487        rows,
488        sigma_rows,
489        total_reserve: mack.total_reserve,
490        total_standard_error: mack.total_standard_error,
491        total_cv: mack.total_cv,
492        quantiles: MackQuantiles {
493            p50: mack.total_reserve,
494            p75: mack.total_reserve + 0.674_489_750_196_081_7 * mack.total_standard_error,
495            p90: mack.total_reserve + 1.281_551_565_544_600_4 * mack.total_standard_error,
496            p95: mack.total_reserve + 1.644_853_626_951_472_2 * mack.total_standard_error,
497        },
498        tail_disclosure: if tail > 1.0 {
499            "Mack normal approximation; tail uncertainty is not modeled.".to_string()
500        } else {
501            "Mack normal approximation.".to_string()
502        },
503    }
504}
505
506fn brosius_exhibit(
507    triangle: &TriangleView<'_>,
508    factors: &DevelopmentFactors,
509    brosius: &Brosius,
510) -> BrosiusExhibit {
511    let links = brosius
512        .diagnostics
513        .iter()
514        .map(|diagnostic| BrosiusLinkExhibitRow {
515            dev: diagnostic.dev,
516            n: diagnostic.n,
517            intercept: diagnostic.intercept,
518            slope: diagnostic.slope,
519            chain_ladder_ldf: factors.ldfs.get(diagnostic.dev).copied(),
520            fallback_used: diagnostic.fallback_used,
521        })
522        .collect();
523
524    let mut scatter_points = Vec::new();
525    for diagnostic in &brosius.diagnostics {
526        for origin in 0..diagnostic.n {
527            let x = triangle.get(origin, diagnostic.dev);
528            let y = triangle.get(origin, diagnostic.dev + 1);
529            scatter_points.push(BrosiusScatterPoint {
530                dev: diagnostic.dev,
531                origin,
532                x,
533                y,
534                fitted_y: diagnostic.intercept + diagnostic.slope * x,
535            });
536        }
537    }
538
539    BrosiusExhibit {
540        links,
541        scatter_points,
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548    use crate::types::Triangle;
549
550    fn sample_triangle() -> Triangle {
551        #[rustfmt::skip]
552        let data = vec![
553            1000.0, 1500.0, 1700.0, 1800.0,
554            1200.0, 1800.0, 2000.0, f64::NAN,
555            1500.0, 2100.0, f64::NAN, f64::NAN,
556            1800.0, f64::NAN, f64::NAN, f64::NAN,
557        ];
558        Triangle::new(4, 4, data)
559    }
560
561    #[test]
562    fn bundle_contains_core_exhibits() {
563        let triangle = sample_triangle();
564        let premium = [4000.0, 4500.0, 5000.0, 5500.0];
565        let expected = [2500.0, 2750.0, 3000.0, 3250.0];
566
567        let bundle = build_exhibit_bundle(&triangle.view(), Some(&premium), Some(&expected), 1.0)
568            .expect("bundle");
569
570        assert!(bundle.validation.ok);
571        assert_eq!(bundle.triangle.cells.len(), 16);
572        assert_eq!(bundle.incremental_triangle.cells.len(), 16);
573        assert_eq!(bundle.factors.rows.len(), 3);
574        assert_eq!(bundle.projections.rows.len(), 4);
575        assert!(bundle.projections.totals.chain_ladder_reserve.is_some());
576        assert!(bundle.projections.totals.bf_reserve.is_some());
577        assert!(bundle.projections.totals.cape_cod_reserve.is_some());
578        assert!(bundle.mack.is_some());
579        assert!(bundle.brosius.is_some());
580    }
581
582    #[test]
583    fn triangle_exhibit_marks_latest_and_unobserved_cells() {
584        let triangle = sample_triangle();
585
586        let exhibit = triangle_exhibit(&triangle.view());
587
588        let latest_cells = exhibit.cells.iter().filter(|cell| cell.latest).count();
589        let unobserved_cells = exhibit.cells.iter().filter(|cell| !cell.observed).count();
590        assert_eq!(latest_cells, 4);
591        assert_eq!(unobserved_cells, 6);
592        assert_eq!(exhibit.cells[7].value, None);
593    }
594
595    #[test]
596    fn bundle_allows_optional_bf_and_cape_cod_inputs() {
597        let triangle = sample_triangle();
598
599        let bundle = build_exhibit_bundle(&triangle.view(), None, None, 1.0).expect("bundle");
600
601        assert!(
602            bundle
603                .projections
604                .rows
605                .iter()
606                .all(|row| row.bf_reserve.is_none())
607        );
608        assert!(
609            bundle
610                .projections
611                .rows
612                .iter()
613                .all(|row| row.cape_cod_reserve.is_none())
614        );
615        assert_eq!(bundle.validation.warnings.len(), 2);
616    }
617}