1use 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#[derive(Debug, Clone, Serialize)]
21pub struct ExhibitBundle {
22 pub triangle: TriangleExhibit,
24 pub incremental_triangle: TriangleExhibit,
26 pub factors: FactorExhibit,
28 pub projections: ProjectionComparisonExhibit,
30 pub validation: ValidationExhibit,
32 pub mack: Option<MackExhibit>,
34 pub brosius: Option<BrosiusExhibit>,
36}
37
38#[derive(Debug, Clone, Serialize)]
40pub struct ValidationExhibit {
41 pub ok: bool,
43 pub errors: Vec<String>,
45 pub warnings: Vec<String>,
47}
48
49#[derive(Debug, Clone, Serialize)]
51pub struct TriangleCellDto {
52 pub origin: usize,
54 pub dev: usize,
56 pub value: Option<f64>,
58 pub observed: bool,
60 pub latest: bool,
62 pub projected: bool,
64}
65
66#[derive(Debug, Clone, Serialize)]
68pub struct TriangleExhibit {
69 pub n_origins: usize,
71 pub n_devs: usize,
73 pub cells: Vec<TriangleCellDto>,
75}
76
77#[derive(Debug, Clone, Serialize)]
79pub struct FactorExhibitRow {
80 pub dev: usize,
82 pub numerator: f64,
84 pub denominator: f64,
86 pub selected_ldf: f64,
88 pub cdf: f64,
90 pub maturity: f64,
92 pub included_rows: usize,
94}
95
96#[derive(Debug, Clone, Serialize)]
98pub struct FactorExhibit {
99 pub rows: Vec<FactorExhibitRow>,
101 pub tail: f64,
103}
104
105#[derive(Debug, Clone, Serialize)]
107pub struct ProjectionRow {
108 pub origin: usize,
110 pub latest_dev: usize,
112 pub latest: f64,
114 pub maturity: Option<f64>,
116 pub chain_ladder_ultimate: Option<f64>,
118 pub chain_ladder_reserve: Option<f64>,
120 pub bf_expected: Option<f64>,
122 pub bf_ultimate: Option<f64>,
124 pub bf_reserve: Option<f64>,
126 pub cape_cod_expected: Option<f64>,
128 pub cape_cod_ultimate: Option<f64>,
130 pub cape_cod_reserve: Option<f64>,
132 pub mack_ultimate: Option<f64>,
134 pub mack_reserve: Option<f64>,
136 pub mack_se: Option<f64>,
138 pub mack_cv: Option<f64>,
140 pub brosius_ultimate: Option<f64>,
142 pub brosius_reserve: Option<f64>,
144}
145
146#[derive(Debug, Clone, Serialize)]
148pub struct ProjectionTotals {
149 pub latest: f64,
151 pub chain_ladder_reserve: Option<f64>,
153 pub bf_reserve: Option<f64>,
155 pub cape_cod_reserve: Option<f64>,
157 pub mack_reserve: Option<f64>,
159 pub brosius_reserve: Option<f64>,
161}
162
163#[derive(Debug, Clone, Serialize)]
165pub struct ProjectionComparisonExhibit {
166 pub rows: Vec<ProjectionRow>,
168 pub totals: ProjectionTotals,
170}
171
172#[derive(Debug, Clone, Serialize)]
174pub struct MackExhibit {
175 pub rows: Vec<MackOriginRiskRow>,
177 pub sigma_rows: Vec<MackSigmaRow>,
179 pub total_reserve: f64,
181 pub total_standard_error: f64,
183 pub total_cv: f64,
185 pub quantiles: MackQuantiles,
187 pub tail_disclosure: String,
189}
190
191#[derive(Debug, Clone, Serialize)]
193pub struct MackOriginRiskRow {
194 pub origin: usize,
196 pub reserve: f64,
198 pub standard_error: f64,
200 pub cv: f64,
202 pub reserve_minus_1se: f64,
204 pub reserve_plus_1se: f64,
206}
207
208#[derive(Debug, Clone, Serialize)]
210pub struct MackSigmaRow {
211 pub dev: usize,
213 pub sigma_sq: f64,
215}
216
217#[derive(Debug, Clone, Serialize)]
219pub struct MackQuantiles {
220 pub p50: f64,
222 pub p75: f64,
224 pub p90: f64,
226 pub p95: f64,
228}
229
230#[derive(Debug, Clone, Serialize)]
232pub struct BrosiusExhibit {
233 pub links: Vec<BrosiusLinkExhibitRow>,
235 pub scatter_points: Vec<BrosiusScatterPoint>,
237}
238
239#[derive(Debug, Clone, Serialize)]
241pub struct BrosiusLinkExhibitRow {
242 pub dev: usize,
244 pub n: usize,
246 pub intercept: f64,
248 pub slope: f64,
250 pub chain_ladder_ldf: Option<f64>,
252 pub fallback_used: bool,
254}
255
256#[derive(Debug, Clone, Serialize)]
258pub struct BrosiusScatterPoint {
259 pub dev: usize,
261 pub origin: usize,
263 pub x: f64,
265 pub y: f64,
267 pub fitted_y: f64,
269}
270
271pub 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}