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 pub n_origins: usize,
74 pub n_devs: usize,
76 pub data: Vec<f64>,
78}
79
80impl PartialEq for Triangle {
81 fn eq(&self, other: &Self) -> bool {
82 self.view() == other.view()
83 }
84}
85
86impl Triangle {
87 #[inline]
93 pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
94 debug_assert_eq!(data.len(), n_origins * n_devs);
95 Self {
96 n_origins,
97 n_devs,
98 data,
99 }
100 }
101
102 pub fn try_new(
108 n_origins: usize,
109 n_devs: usize,
110 data: Vec<f64>,
111 ) -> Result<Self, ValidationError> {
112 let triangle = Self {
113 n_origins,
114 n_devs,
115 data,
116 };
117 validate_triangle(&triangle.view())?;
118 Ok(triangle)
119 }
120
121 pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
141 Self::try_from_rows(rows)
142 }
143
144 pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
147 let n = rows.len();
148 if n == 0 {
149 return Err(ValidationError::ShapeMismatch);
150 }
151 let mut data = vec![f64::NAN; n * n];
152 for (i, row) in rows.iter().enumerate() {
153 let row = row.as_ref();
154 if row.len() != n - i {
155 return Err(ValidationError::ShapeMismatch);
156 }
157 data[i * n..i * n + row.len()].copy_from_slice(row);
158 }
159 Self::try_new(n, n, data)
160 }
161
162 pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
167 let n = rows.len();
168 if n == 0 {
169 return Err(ValidationError::ShapeMismatch);
170 }
171 let mut data = vec![f64::NAN; n * n];
172 for (i, row) in rows.iter().enumerate() {
173 if row.len() != n - i {
174 return Err(ValidationError::ShapeMismatch);
175 }
176 let mut acc = 0.0;
177 for (j, &inc) in row.iter().enumerate() {
178 if !inc.is_finite() {
179 return Err(ValidationError::NotFinite);
180 }
181 acc += inc;
182 data[i * n + j] = acc;
183 }
184 }
185 Self::try_new(n, n, data)
186 }
187
188 #[inline]
190 pub fn get(&self, i: usize, j: usize) -> f64 {
191 self.data[i * self.n_devs + j]
192 }
193
194 #[inline]
196 pub fn origin_row(&self, i: usize) -> &[f64] {
197 let n = self.n();
198 let len = n.saturating_sub(i);
199 let start = i * self.n_devs;
200 &self.data[start..start + len]
201 }
202
203 #[inline]
205 pub fn n(&self) -> usize {
206 self.n_origins.min(self.n_devs)
207 }
208
209 #[inline]
211 pub fn is_empty(&self) -> bool {
212 self.n_origins == 0 || self.n_devs == 0
213 }
214
215 #[inline]
217 pub fn view(&self) -> TriangleView<'_> {
218 TriangleView {
219 n_origins: self.n_origins,
220 n_devs: self.n_devs,
221 data: &self.data,
222 }
223 }
224
225 pub fn latest_diagonal(&self) -> Vec<f64> {
227 latest_diagonal(&self.view())
228 }
229
230 pub fn to_incremental(&self) -> Self {
232 let n = self.n();
233 Self::new(n, n, cumulative_to_incremental(&self.view()))
234 }
235
236 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
238 self.view().ldfs(tail)
239 }
240
241 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
243 self.view().chain_ladder(tail)
244 }
245
246 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
248 self.view().mack(tail)
249 }
250
251 pub fn mack_with_policy(
253 &self,
254 tail: f64,
255 policy: MonotonicityPolicy,
256 ) -> Result<Mack, ValidationError> {
257 self.view().mack_with_policy(tail, policy)
258 }
259
260 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
262 self.view().merz_wuthrich()
263 }
264
265 pub fn merz_wuthrich_with_policy(
267 &self,
268 policy: MonotonicityPolicy,
269 ) -> Result<MerzWuthrichResult, ValidationError> {
270 self.view().merz_wuthrich_with_policy(policy)
271 }
272
273 pub fn bf(
275 &self,
276 expected_ultimate: &[f64],
277 tail: f64,
278 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
279 self.view().bf(expected_ultimate, tail)
280 }
281
282 pub fn cape_cod(
284 &self,
285 premium: &[f64],
286 tail: f64,
287 ) -> Result<CapeCodProjection, ValidationError> {
288 self.view().cape_cod(premium, tail)
289 }
290
291 pub fn bootstrap_odp(
293 &self,
294 tail: f64,
295 options: OdpBootstrapOptions,
296 ) -> Result<OdpBootstrapResult, ValidationError> {
297 self.view().bootstrap_odp(tail, options)
298 }
299
300 pub fn exhibit(
302 &self,
303 premium: Option<&[f64]>,
304 expected_ultimate: Option<&[f64]>,
305 tail: f64,
306 ) -> Result<ExhibitBundle, ValidationError> {
307 self.view().exhibit(premium, expected_ultimate, tail)
308 }
309
310 pub fn benktander(
312 &self,
313 expected_ultimate: &[f64],
314 iterations: usize,
315 tail: f64,
316 ) -> Result<BenktanderProjection, ValidationError> {
317 self.view().benktander(expected_ultimate, iterations, tail)
318 }
319
320 pub fn generalized_cape_cod(
322 &self,
323 premium: &[f64],
324 decay: f64,
325 tail: f64,
326 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
327 self.view().generalized_cape_cod(premium, decay, tail)
328 }
329
330 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
332 self.view().brosius(tail)
333 }
334
335 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
337 self.view().fit_odp(tail)
338 }
339
340 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
342 self.view().glm(options)
343 }
344
345 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
347 self.view().clark_ldf(options)
348 }
349
350 pub fn clark_cape_cod(
352 &self,
353 premium: &[f64],
354 options: &ClarkOptions,
355 ) -> Result<ClarkMleResult, ValidationError> {
356 self.view().clark_cape_cod(premium, options)
357 }
358
359 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
361 self.view().ptf(options)
362 }
363
364 pub fn diagnostics(&self) -> TriangleDiagnostics {
366 self.view().diagnostics()
367 }
368}
369
370impl fmt::Display for Triangle {
371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
372 self.view().fmt(f)
373 }
374}
375
376#[derive(Debug, Clone, Copy)]
378pub struct TriangleView<'a> {
379 pub n_origins: usize,
381 pub n_devs: usize,
383 pub data: &'a [f64],
385}
386
387impl PartialEq for TriangleView<'_> {
388 fn eq(&self, other: &Self) -> bool {
389 self.n_origins == other.n_origins
390 && self.n_devs == other.n_devs
391 && self.data.len() == other.data.len()
392 && self
393 .data
394 .iter()
395 .zip(other.data.iter())
396 .all(|(&a, &b)| (a.is_nan() && b.is_nan()) || a == b)
397 }
398}
399
400impl fmt::Display for TriangleView<'_> {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 for i in 0..self.n_origins {
403 if i > 0 {
404 writeln!(f)?;
405 }
406 for j in 0..self.n_devs {
407 if j > 0 {
408 write!(f, "\t")?;
409 }
410 let v = self.data[i * self.n_devs + j];
411 if v.is_finite() {
412 write!(f, "{v:.2}")?;
413 } else {
414 write!(f, "-")?;
415 }
416 }
417 }
418 Ok(())
419 }
420}
421
422impl TriangleView<'_> {
423 #[inline]
425 pub fn get(&self, i: usize, j: usize) -> f64 {
426 self.data[i * self.n_devs + j]
427 }
428
429 #[inline]
432 pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
433 let n = self.n_origins.min(self.n_devs);
434 i < n && j < n && i + j < n
435 }
436
437 #[inline]
439 pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
440 self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
441 }
442
443 #[inline]
449 pub fn is_observed(&self, i: usize, j: usize) -> bool {
450 self.is_valid_observed(i, j)
451 }
452
453 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
455 DevelopmentFactorEngine::volume_weighted(self, tail)
456 }
457
458 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
460 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
461 ChainLadderEngine::project(self, &factors)
462 }
463
464 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
466 mack::analyze(self, tail)
467 }
468
469 pub fn mack_with_policy(
471 &self,
472 tail: f64,
473 policy: MonotonicityPolicy,
474 ) -> Result<Mack, ValidationError> {
475 mack::analyze_with_policy(self, tail, policy)
476 }
477
478 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
480 merz_wuthrich::analyze(self)
481 }
482
483 pub fn merz_wuthrich_with_policy(
485 &self,
486 policy: MonotonicityPolicy,
487 ) -> Result<MerzWuthrichResult, ValidationError> {
488 merz_wuthrich::analyze_with_policy(self, policy)
489 }
490
491 pub fn bf(
493 &self,
494 expected_ultimate: &[f64],
495 tail: f64,
496 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
497 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
498 BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
499 }
500
501 pub fn cape_cod(
503 &self,
504 premium: &[f64],
505 tail: f64,
506 ) -> Result<CapeCodProjection, ValidationError> {
507 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
508 CapeCodEngine::project(self, &factors, premium)
509 }
510
511 pub fn bootstrap_odp(
513 &self,
514 tail: f64,
515 options: OdpBootstrapOptions,
516 ) -> Result<OdpBootstrapResult, ValidationError> {
517 bootstrap_odp(self, tail, options)
518 }
519
520 pub fn exhibit(
522 &self,
523 premium: Option<&[f64]>,
524 expected_ultimate: Option<&[f64]>,
525 tail: f64,
526 ) -> Result<ExhibitBundle, ValidationError> {
527 build_exhibit_bundle(self, premium, expected_ultimate, tail)
528 }
529
530 pub fn benktander(
532 &self,
533 expected_ultimate: &[f64],
534 iterations: usize,
535 tail: f64,
536 ) -> Result<BenktanderProjection, ValidationError> {
537 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
538 BenktanderEngine::project_from_expected_ultimate(
539 self,
540 &factors,
541 expected_ultimate,
542 iterations,
543 )
544 }
545
546 pub fn generalized_cape_cod(
548 &self,
549 premium: &[f64],
550 decay: f64,
551 tail: f64,
552 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
553 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
554 GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
555 }
556
557 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
559 brosius::project(self, tail)
560 }
561
562 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
564 fit_odp(self, tail, MonotonicityPolicy::Strict)
565 }
566
567 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
569 glm_reserving::fit_glm(self, options)
570 }
571
572 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
574 clark_mle::fit_clark_ldf(self, options)
575 }
576
577 pub fn clark_cape_cod(
579 &self,
580 premium: &[f64],
581 options: &ClarkOptions,
582 ) -> Result<ClarkMleResult, ValidationError> {
583 clark_mle::fit_clark_cape_cod(self, premium, options)
584 }
585
586 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
588 ptf_regression::fit_ptf(self, options)
589 }
590
591 pub fn diagnostics(&self) -> TriangleDiagnostics {
593 triangle_diagnostics::analyze(self)
594 }
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600 use crate::validate::ValidationError;
601
602 #[test]
603 fn try_new_rejects_shape_mismatch() {
604 assert_eq!(
605 Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
606 Err(ValidationError::ShapeMismatch)
607 );
608 }
609
610 #[test]
611 fn try_new_accepts_valid_square_triangle() {
612 let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
613
614 assert_eq!(triangle.n_origins, 2);
615 assert_eq!(triangle.n_devs, 2);
616 assert_eq!(triangle, triangle.clone());
617 assert_eq!(triangle.view(), triangle.view());
618 }
619
620 #[test]
621 fn triangle_serde_json_roundtrips_nan_and_validates() {
622 let triangle =
623 Triangle::try_from_upper_rows(&[&[100.0, 160.0, 195.0], &[120.0, 190.0], &[135.0]])
624 .expect("triangle");
625 let json = serde_json::to_string(&triangle).expect("serialize");
626 let decoded: Triangle = serde_json::from_str(&json).expect("deserialize");
627 assert_eq!(triangle, decoded);
628
629 let malformed = r#"{"n_origins":3,"n_devs":3,"data":[1.0]}"#;
630 assert!(serde_json::from_str::<Triangle>(malformed).is_err());
631 }
632}