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
31#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
38pub struct Triangle {
39 pub n_origins: usize,
41 pub n_devs: usize,
43 pub data: Vec<f64>,
45}
46
47impl Triangle {
48 #[inline]
54 pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
55 debug_assert_eq!(data.len(), n_origins * n_devs);
56 Self {
57 n_origins,
58 n_devs,
59 data,
60 }
61 }
62
63 pub fn try_new(
69 n_origins: usize,
70 n_devs: usize,
71 data: Vec<f64>,
72 ) -> Result<Self, ValidationError> {
73 let triangle = Self {
74 n_origins,
75 n_devs,
76 data,
77 };
78 validate_triangle(&triangle.view())?;
79 Ok(triangle)
80 }
81
82 pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
102 Self::try_from_rows(rows)
103 }
104
105 pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
108 let n = rows.len();
109 if n == 0 {
110 return Err(ValidationError::ShapeMismatch);
111 }
112 let mut data = vec![f64::NAN; n * n];
113 for (i, row) in rows.iter().enumerate() {
114 let row = row.as_ref();
115 if row.len() != n - i {
116 return Err(ValidationError::ShapeMismatch);
117 }
118 data[i * n..i * n + row.len()].copy_from_slice(row);
119 }
120 Self::try_new(n, n, data)
121 }
122
123 pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
128 let n = rows.len();
129 if n == 0 {
130 return Err(ValidationError::ShapeMismatch);
131 }
132 let mut data = vec![f64::NAN; n * n];
133 for (i, row) in rows.iter().enumerate() {
134 if row.len() != n - i {
135 return Err(ValidationError::ShapeMismatch);
136 }
137 let mut acc = 0.0;
138 for (j, &inc) in row.iter().enumerate() {
139 if !inc.is_finite() {
140 return Err(ValidationError::NotFinite);
141 }
142 acc += inc;
143 data[i * n + j] = acc;
144 }
145 }
146 Self::try_new(n, n, data)
147 }
148
149 #[inline]
151 pub fn get(&self, i: usize, j: usize) -> f64 {
152 self.data[i * self.n_devs + j]
153 }
154
155 #[inline]
157 pub fn origin_row(&self, i: usize) -> &[f64] {
158 let n = self.n();
159 let len = n.saturating_sub(i);
160 let start = i * self.n_devs;
161 &self.data[start..start + len]
162 }
163
164 #[inline]
166 pub fn n(&self) -> usize {
167 self.n_origins.min(self.n_devs)
168 }
169
170 #[inline]
172 pub fn is_empty(&self) -> bool {
173 self.n_origins == 0 || self.n_devs == 0
174 }
175
176 #[inline]
178 pub fn view(&self) -> TriangleView<'_> {
179 TriangleView {
180 n_origins: self.n_origins,
181 n_devs: self.n_devs,
182 data: &self.data,
183 }
184 }
185
186 pub fn latest_diagonal(&self) -> Vec<f64> {
188 latest_diagonal(&self.view())
189 }
190
191 pub fn to_incremental(&self) -> Self {
193 let n = self.n();
194 Self::new(n, n, cumulative_to_incremental(&self.view()))
195 }
196
197 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
199 self.view().ldfs(tail)
200 }
201
202 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
204 self.view().chain_ladder(tail)
205 }
206
207 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
209 self.view().mack(tail)
210 }
211
212 pub fn mack_with_policy(
214 &self,
215 tail: f64,
216 policy: MonotonicityPolicy,
217 ) -> Result<Mack, ValidationError> {
218 self.view().mack_with_policy(tail, policy)
219 }
220
221 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
223 self.view().merz_wuthrich()
224 }
225
226 pub fn bf(
228 &self,
229 expected_ultimate: &[f64],
230 tail: f64,
231 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
232 self.view().bf(expected_ultimate, tail)
233 }
234
235 pub fn cape_cod(
237 &self,
238 premium: &[f64],
239 tail: f64,
240 ) -> Result<CapeCodProjection, ValidationError> {
241 self.view().cape_cod(premium, tail)
242 }
243
244 pub fn bootstrap_odp(
246 &self,
247 tail: f64,
248 options: OdpBootstrapOptions,
249 ) -> Result<OdpBootstrapResult, ValidationError> {
250 self.view().bootstrap_odp(tail, options)
251 }
252
253 pub fn exhibit(
255 &self,
256 premium: Option<&[f64]>,
257 expected_ultimate: Option<&[f64]>,
258 tail: f64,
259 ) -> Result<ExhibitBundle, ValidationError> {
260 self.view().exhibit(premium, expected_ultimate, tail)
261 }
262
263 pub fn benktander(
265 &self,
266 expected_ultimate: &[f64],
267 iterations: usize,
268 tail: f64,
269 ) -> Result<BenktanderProjection, ValidationError> {
270 self.view().benktander(expected_ultimate, iterations, tail)
271 }
272
273 pub fn generalized_cape_cod(
275 &self,
276 premium: &[f64],
277 decay: f64,
278 tail: f64,
279 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
280 self.view().generalized_cape_cod(premium, decay, tail)
281 }
282
283 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
285 self.view().brosius(tail)
286 }
287
288 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
290 self.view().fit_odp(tail)
291 }
292
293 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
295 self.view().glm(options)
296 }
297
298 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
300 self.view().clark_ldf(options)
301 }
302
303 pub fn clark_cape_cod(
305 &self,
306 premium: &[f64],
307 options: &ClarkOptions,
308 ) -> Result<ClarkMleResult, ValidationError> {
309 self.view().clark_cape_cod(premium, options)
310 }
311
312 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
314 self.view().ptf(options)
315 }
316
317 pub fn diagnostics(&self) -> TriangleDiagnostics {
319 self.view().diagnostics()
320 }
321}
322
323impl fmt::Display for Triangle {
324 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325 self.view().fmt(f)
326 }
327}
328
329#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct TriangleView<'a> {
332 pub n_origins: usize,
334 pub n_devs: usize,
336 pub data: &'a [f64],
338}
339
340impl fmt::Display for TriangleView<'_> {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 for i in 0..self.n_origins {
343 if i > 0 {
344 writeln!(f)?;
345 }
346 for j in 0..self.n_devs {
347 if j > 0 {
348 write!(f, "\t")?;
349 }
350 let v = self.data[i * self.n_devs + j];
351 if v.is_finite() {
352 write!(f, "{v:.2}")?;
353 } else {
354 write!(f, "-")?;
355 }
356 }
357 }
358 Ok(())
359 }
360}
361
362impl TriangleView<'_> {
363 #[inline]
365 pub fn get(&self, i: usize, j: usize) -> f64 {
366 self.data[i * self.n_devs + j]
367 }
368
369 #[inline]
372 pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
373 let n = self.n_origins.min(self.n_devs);
374 i < n && j < n && i + j < n
375 }
376
377 #[inline]
379 pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
380 self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
381 }
382
383 #[inline]
389 pub fn is_observed(&self, i: usize, j: usize) -> bool {
390 self.is_valid_observed(i, j)
391 }
392
393 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
395 DevelopmentFactorEngine::volume_weighted(self, tail)
396 }
397
398 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
400 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
401 ChainLadderEngine::project(self, &factors)
402 }
403
404 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
406 mack::analyze(self, tail)
407 }
408
409 pub fn mack_with_policy(
411 &self,
412 tail: f64,
413 policy: MonotonicityPolicy,
414 ) -> Result<Mack, ValidationError> {
415 mack::analyze_with_policy(self, tail, policy)
416 }
417
418 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
420 merz_wuthrich::analyze(self)
421 }
422
423 pub fn bf(
425 &self,
426 expected_ultimate: &[f64],
427 tail: f64,
428 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
429 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
430 BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
431 }
432
433 pub fn cape_cod(
435 &self,
436 premium: &[f64],
437 tail: f64,
438 ) -> Result<CapeCodProjection, ValidationError> {
439 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
440 CapeCodEngine::project(self, &factors, premium)
441 }
442
443 pub fn bootstrap_odp(
445 &self,
446 tail: f64,
447 options: OdpBootstrapOptions,
448 ) -> Result<OdpBootstrapResult, ValidationError> {
449 bootstrap_odp(self, tail, options)
450 }
451
452 pub fn exhibit(
454 &self,
455 premium: Option<&[f64]>,
456 expected_ultimate: Option<&[f64]>,
457 tail: f64,
458 ) -> Result<ExhibitBundle, ValidationError> {
459 build_exhibit_bundle(self, premium, expected_ultimate, tail)
460 }
461
462 pub fn benktander(
464 &self,
465 expected_ultimate: &[f64],
466 iterations: usize,
467 tail: f64,
468 ) -> Result<BenktanderProjection, ValidationError> {
469 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
470 BenktanderEngine::project_from_expected_ultimate(
471 self,
472 &factors,
473 expected_ultimate,
474 iterations,
475 )
476 }
477
478 pub fn generalized_cape_cod(
480 &self,
481 premium: &[f64],
482 decay: f64,
483 tail: f64,
484 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
485 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
486 GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
487 }
488
489 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
491 brosius::project(self, tail)
492 }
493
494 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
496 fit_odp(self, tail, MonotonicityPolicy::Strict)
497 }
498
499 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
501 glm_reserving::fit_glm(self, options)
502 }
503
504 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
506 clark_mle::fit_clark_ldf(self, options)
507 }
508
509 pub fn clark_cape_cod(
511 &self,
512 premium: &[f64],
513 options: &ClarkOptions,
514 ) -> Result<ClarkMleResult, ValidationError> {
515 clark_mle::fit_clark_cape_cod(self, premium, options)
516 }
517
518 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
520 ptf_regression::fit_ptf(self, options)
521 }
522
523 pub fn diagnostics(&self) -> TriangleDiagnostics {
525 triangle_diagnostics::analyze(self)
526 }
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532 use crate::validate::ValidationError;
533
534 #[test]
535 fn try_new_rejects_shape_mismatch() {
536 assert_eq!(
537 Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
538 Err(ValidationError::ShapeMismatch)
539 );
540 }
541
542 #[test]
543 fn try_new_accepts_valid_square_triangle() {
544 let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
545
546 assert_eq!(triangle.n_origins, 2);
547 assert_eq!(triangle.n_devs, 2);
548 }
549}