1use std::fmt;
10
11use crate::benktander::{BenktanderEngine, BenktanderProjection};
12use crate::bf::{BornhuetterFergusonEngine, BornhuetterFergusonProjection};
13use crate::bootstrap_odp::{
14 OdpBootstrapOptions, OdpBootstrapResult, OdpFit, bootstrap_odp, fit_odp,
15};
16use crate::brosius::{self, Brosius};
17use crate::cape_cod::{CapeCodEngine, CapeCodProjection};
18use crate::chain_ladder::{ChainLadderEngine, ChainLadderProjection};
19use crate::clark_mle::{self, ClarkMleResult, ClarkOptions};
20use crate::diagnostics::triangle_diagnostics::{self, TriangleDiagnostics};
21use crate::exhibit::{ExhibitBundle, build_exhibit_bundle};
22use crate::generalized_cape_cod::{GeneralizedCapeCodEngine, GeneralizedCapeCodProjection};
23use crate::glm_reserving::{self, GlmOptions, GlmReservingResult};
24use crate::ldf::{DevelopmentFactorEngine, DevelopmentFactors};
25use crate::mack::{self, Mack};
26use crate::merz_wuthrich::{self, MerzWuthrichResult};
27use crate::ptf_regression::{self, PtfOptions, PtfResult};
28use crate::triangle::{cumulative_to_incremental, latest_diagonal};
29use crate::validate::{MonotonicityPolicy, ValidationError, validate_triangle};
30
31fn deserialize_vec_f64_null_as_nan<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
35where
36 D: serde::Deserializer<'de>,
37{
38 use serde::Deserialize;
39 let opts: Vec<Option<f64>> = Vec::deserialize(deserializer)?;
40 Ok(opts.into_iter().map(|v| v.unwrap_or(f64::NAN)).collect())
41}
42
43#[derive(serde::Deserialize)]
44struct RawTriangle {
45 n_origins: usize,
46 n_devs: usize,
47 #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
48 data: Vec<f64>,
49}
50
51impl TryFrom<RawTriangle> for Triangle {
52 type Error = ValidationError;
53
54 fn try_from(raw: RawTriangle) -> Result<Self, Self::Error> {
55 Self::try_new(raw.n_origins, raw.n_devs, raw.data)
56 }
57}
58
59#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
70#[serde(try_from = "RawTriangle")]
71pub struct Triangle {
72 n_origins: usize,
73 n_devs: usize,
74 data: Vec<f64>,
75}
76
77impl PartialEq for Triangle {
78 fn eq(&self, other: &Self) -> bool {
79 self.view() == other.view()
80 }
81}
82
83impl Triangle {
84 #[inline]
90 pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
91 debug_assert_eq!(data.len(), n_origins * n_devs);
92 Self {
93 n_origins,
94 n_devs,
95 data,
96 }
97 }
98
99 pub fn try_new(
105 n_origins: usize,
106 n_devs: usize,
107 data: Vec<f64>,
108 ) -> Result<Self, ValidationError> {
109 let triangle = Self {
110 n_origins,
111 n_devs,
112 data,
113 };
114 validate_triangle(&triangle.view())?;
115 Ok(triangle)
116 }
117
118 pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
138 Self::try_from_rows(rows)
139 }
140
141 pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
144 let n = rows.len();
145 if n == 0 {
146 return Err(ValidationError::ShapeMismatch);
147 }
148 let mut data = vec![f64::NAN; n * n];
149 for (i, row) in rows.iter().enumerate() {
150 let row = row.as_ref();
151 if row.len() != n - i {
152 return Err(ValidationError::ShapeMismatch);
153 }
154 data[i * n..i * n + row.len()].copy_from_slice(row);
155 }
156 Self::try_new(n, n, data)
157 }
158
159 pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
164 let n = rows.len();
165 if n == 0 {
166 return Err(ValidationError::ShapeMismatch);
167 }
168 let mut data = vec![f64::NAN; n * n];
169 for (i, row) in rows.iter().enumerate() {
170 if row.len() != n - i {
171 return Err(ValidationError::ShapeMismatch);
172 }
173 let mut acc = 0.0;
174 for (j, &inc) in row.iter().enumerate() {
175 if !inc.is_finite() {
176 return Err(ValidationError::NotFinite);
177 }
178 acc += inc;
179 data[i * n + j] = acc;
180 }
181 }
182 Self::try_new(n, n, data)
183 }
184
185 #[inline]
187 pub fn get(&self, i: usize, j: usize) -> f64 {
188 self.data[i * self.n_devs + j]
189 }
190
191 #[inline]
193 pub fn origin_row(&self, i: usize) -> &[f64] {
194 let n = self.n();
195 let len = n.saturating_sub(i);
196 let start = i * self.n_devs;
197 &self.data[start..start + len]
198 }
199
200 #[inline]
202 pub fn n_origins(&self) -> usize {
203 self.n_origins
204 }
205
206 #[inline]
208 pub fn n_devs(&self) -> usize {
209 self.n_devs
210 }
211
212 #[inline]
214 pub fn data(&self) -> &[f64] {
215 &self.data
216 }
217
218 #[inline]
220 pub fn n(&self) -> usize {
221 self.n_origins.min(self.n_devs)
222 }
223
224 #[inline]
226 pub fn is_empty(&self) -> bool {
227 self.n_origins == 0 || self.n_devs == 0
228 }
229
230 #[inline]
232 pub fn view(&self) -> TriangleView<'_> {
233 TriangleView {
234 n_origins: self.n_origins,
235 n_devs: self.n_devs,
236 data: &self.data,
237 }
238 }
239
240 pub fn latest_diagonal(&self) -> Vec<f64> {
242 latest_diagonal(&self.view())
243 }
244
245 pub fn to_incremental(&self) -> Self {
247 let n = self.n();
248 Self::new(n, n, cumulative_to_incremental(&self.view()))
249 }
250
251 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
253 self.view().ldfs(tail)
254 }
255
256 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
258 self.view().chain_ladder(tail)
259 }
260
261 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
263 self.view().mack(tail)
264 }
265
266 pub fn mack_with_policy(
268 &self,
269 tail: f64,
270 policy: MonotonicityPolicy,
271 ) -> Result<Mack, ValidationError> {
272 self.view().mack_with_policy(tail, policy)
273 }
274
275 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
277 self.view().merz_wuthrich()
278 }
279
280 pub fn merz_wuthrich_with_policy(
282 &self,
283 policy: MonotonicityPolicy,
284 ) -> Result<MerzWuthrichResult, ValidationError> {
285 self.view().merz_wuthrich_with_policy(policy)
286 }
287
288 pub fn bf(
290 &self,
291 expected_ultimate: &[f64],
292 tail: f64,
293 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
294 self.view().bf(expected_ultimate, tail)
295 }
296
297 pub fn cape_cod(
299 &self,
300 premium: &[f64],
301 tail: f64,
302 ) -> Result<CapeCodProjection, ValidationError> {
303 self.view().cape_cod(premium, tail)
304 }
305
306 pub fn bootstrap_odp(
308 &self,
309 tail: f64,
310 options: OdpBootstrapOptions,
311 ) -> Result<OdpBootstrapResult, ValidationError> {
312 self.view().bootstrap_odp(tail, options)
313 }
314
315 pub fn exhibit(
317 &self,
318 premium: Option<&[f64]>,
319 expected_ultimate: Option<&[f64]>,
320 tail: f64,
321 ) -> Result<ExhibitBundle, ValidationError> {
322 self.view().exhibit(premium, expected_ultimate, tail)
323 }
324
325 pub fn benktander(
327 &self,
328 expected_ultimate: &[f64],
329 iterations: usize,
330 tail: f64,
331 ) -> Result<BenktanderProjection, ValidationError> {
332 self.view().benktander(expected_ultimate, iterations, tail)
333 }
334
335 pub fn generalized_cape_cod(
337 &self,
338 premium: &[f64],
339 decay: f64,
340 tail: f64,
341 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
342 self.view().generalized_cape_cod(premium, decay, tail)
343 }
344
345 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
347 self.view().brosius(tail)
348 }
349
350 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
352 self.view().fit_odp(tail)
353 }
354
355 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
357 self.view().glm(options)
358 }
359
360 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
362 self.view().clark_ldf(options)
363 }
364
365 pub fn clark_cape_cod(
367 &self,
368 premium: &[f64],
369 options: &ClarkOptions,
370 ) -> Result<ClarkMleResult, ValidationError> {
371 self.view().clark_cape_cod(premium, options)
372 }
373
374 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
376 self.view().ptf(options)
377 }
378
379 pub fn diagnostics(&self) -> TriangleDiagnostics {
381 self.view().diagnostics()
382 }
383}
384
385impl fmt::Display for Triangle {
386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 self.view().fmt(f)
388 }
389}
390
391#[derive(Debug, Clone, Copy)]
393pub struct TriangleView<'a> {
394 pub n_origins: usize,
396 pub n_devs: usize,
398 pub data: &'a [f64],
400}
401
402impl PartialEq for TriangleView<'_> {
403 fn eq(&self, other: &Self) -> bool {
404 self.n_origins == other.n_origins
405 && self.n_devs == other.n_devs
406 && self.data.len() == other.data.len()
407 && self
408 .data
409 .iter()
410 .zip(other.data.iter())
411 .all(|(&a, &b)| (a.is_nan() && b.is_nan()) || a == b)
412 }
413}
414
415impl fmt::Display for TriangleView<'_> {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 for i in 0..self.n_origins {
418 if i > 0 {
419 writeln!(f)?;
420 }
421 for j in 0..self.n_devs {
422 if j > 0 {
423 write!(f, "\t")?;
424 }
425 let v = self.data[i * self.n_devs + j];
426 if v.is_finite() {
427 write!(f, "{v:.2}")?;
428 } else {
429 write!(f, "-")?;
430 }
431 }
432 }
433 Ok(())
434 }
435}
436
437impl TriangleView<'_> {
438 #[inline]
440 pub fn get(&self, i: usize, j: usize) -> f64 {
441 self.data[i * self.n_devs + j]
442 }
443
444 #[inline]
447 pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
448 let n = self.n_origins.min(self.n_devs);
449 i < n && j < n && i + j < n
450 }
451
452 #[inline]
454 pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
455 self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
456 }
457
458 #[inline]
464 pub fn is_observed(&self, i: usize, j: usize) -> bool {
465 self.is_valid_observed(i, j)
466 }
467
468 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
470 DevelopmentFactorEngine::volume_weighted(self, tail)
471 }
472
473 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
475 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
476 ChainLadderEngine::project(self, &factors)
477 }
478
479 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
481 mack::analyze(self, tail)
482 }
483
484 pub fn mack_with_policy(
486 &self,
487 tail: f64,
488 policy: MonotonicityPolicy,
489 ) -> Result<Mack, ValidationError> {
490 mack::analyze_with_policy(self, tail, policy)
491 }
492
493 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
495 merz_wuthrich::analyze(self)
496 }
497
498 pub fn merz_wuthrich_with_policy(
500 &self,
501 policy: MonotonicityPolicy,
502 ) -> Result<MerzWuthrichResult, ValidationError> {
503 merz_wuthrich::analyze_with_policy(self, policy)
504 }
505
506 pub fn bf(
508 &self,
509 expected_ultimate: &[f64],
510 tail: f64,
511 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
512 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
513 BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
514 }
515
516 pub fn cape_cod(
518 &self,
519 premium: &[f64],
520 tail: f64,
521 ) -> Result<CapeCodProjection, ValidationError> {
522 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
523 CapeCodEngine::project(self, &factors, premium)
524 }
525
526 pub fn bootstrap_odp(
528 &self,
529 tail: f64,
530 options: OdpBootstrapOptions,
531 ) -> Result<OdpBootstrapResult, ValidationError> {
532 bootstrap_odp(self, tail, options)
533 }
534
535 pub fn exhibit(
537 &self,
538 premium: Option<&[f64]>,
539 expected_ultimate: Option<&[f64]>,
540 tail: f64,
541 ) -> Result<ExhibitBundle, ValidationError> {
542 build_exhibit_bundle(self, premium, expected_ultimate, tail)
543 }
544
545 pub fn benktander(
547 &self,
548 expected_ultimate: &[f64],
549 iterations: usize,
550 tail: f64,
551 ) -> Result<BenktanderProjection, ValidationError> {
552 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
553 BenktanderEngine::project_from_expected_ultimate(
554 self,
555 &factors,
556 expected_ultimate,
557 iterations,
558 )
559 }
560
561 pub fn generalized_cape_cod(
563 &self,
564 premium: &[f64],
565 decay: f64,
566 tail: f64,
567 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
568 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
569 GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
570 }
571
572 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
574 brosius::project(self, tail)
575 }
576
577 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
579 fit_odp(self, tail, MonotonicityPolicy::Strict)
580 }
581
582 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
584 glm_reserving::fit_glm(self, options)
585 }
586
587 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
589 clark_mle::fit_clark_ldf(self, options)
590 }
591
592 pub fn clark_cape_cod(
594 &self,
595 premium: &[f64],
596 options: &ClarkOptions,
597 ) -> Result<ClarkMleResult, ValidationError> {
598 clark_mle::fit_clark_cape_cod(self, premium, options)
599 }
600
601 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
603 ptf_regression::fit_ptf(self, options)
604 }
605
606 pub fn diagnostics(&self) -> TriangleDiagnostics {
608 triangle_diagnostics::analyze(self)
609 }
610}
611
612#[cfg(test)]
613mod tests {
614 use super::*;
615 use crate::validate::ValidationError;
616
617 #[test]
618 fn try_new_rejects_shape_mismatch() {
619 assert_eq!(
620 Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
621 Err(ValidationError::ShapeMismatch)
622 );
623 }
624
625 #[test]
626 fn try_new_accepts_valid_square_triangle() {
627 let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
628
629 assert_eq!(triangle.n_origins, 2);
630 assert_eq!(triangle.n_devs, 2);
631 assert_eq!(triangle, triangle.clone());
632 assert_eq!(triangle.view(), triangle.view());
633 }
634
635 #[test]
636 fn triangle_serde_json_roundtrips_nan_and_validates() {
637 let triangle =
638 Triangle::try_from_upper_rows(&[&[100.0, 160.0, 195.0], &[120.0, 190.0], &[135.0]])
639 .expect("triangle");
640 let json = serde_json::to_string(&triangle).expect("serialize");
641 let decoded: Triangle = serde_json::from_str(&json).expect("deserialize");
642 assert_eq!(triangle, decoded);
643
644 let malformed = r#"{"n_origins":3,"n_devs":3,"data":[1.0]}"#;
645 assert!(serde_json::from_str::<Triangle>(malformed).is_err());
646 }
647}