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 for i in 0..self.n_origins {
326 if i > 0 {
327 writeln!(f)?;
328 }
329 for j in 0..self.n_devs {
330 if j > 0 {
331 write!(f, "\t")?;
332 }
333 let v = self.data[i * self.n_devs + j];
334 if v.is_finite() {
335 write!(f, "{v:.2}")?;
336 } else {
337 write!(f, "-")?;
338 }
339 }
340 }
341 Ok(())
342 }
343}
344
345#[derive(Debug, Clone, Copy)]
347pub struct TriangleView<'a> {
348 pub n_origins: usize,
350 pub n_devs: usize,
352 pub data: &'a [f64],
354}
355
356impl<'a> TriangleView<'a> {
357 #[inline]
359 pub fn get(&self, i: usize, j: usize) -> f64 {
360 self.data[i * self.n_devs + j]
361 }
362
363 #[inline]
366 pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
367 let n = self.n_origins.min(self.n_devs);
368 i < n && j < n && i + j < n
369 }
370
371 #[inline]
373 pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
374 self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
375 }
376
377 #[inline]
383 pub fn is_observed(&self, i: usize, j: usize) -> bool {
384 self.is_valid_observed(i, j)
385 }
386
387 pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
389 DevelopmentFactorEngine::volume_weighted(self, tail)
390 }
391
392 pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
394 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
395 ChainLadderEngine::project(self, &factors)
396 }
397
398 pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
400 mack::analyze(self, tail)
401 }
402
403 pub fn mack_with_policy(
405 &self,
406 tail: f64,
407 policy: MonotonicityPolicy,
408 ) -> Result<Mack, ValidationError> {
409 mack::analyze_with_policy(self, tail, policy)
410 }
411
412 pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
414 merz_wuthrich::analyze(self)
415 }
416
417 pub fn bf(
419 &self,
420 expected_ultimate: &[f64],
421 tail: f64,
422 ) -> Result<BornhuetterFergusonProjection, ValidationError> {
423 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
424 BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
425 }
426
427 pub fn cape_cod(
429 &self,
430 premium: &[f64],
431 tail: f64,
432 ) -> Result<CapeCodProjection, ValidationError> {
433 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
434 CapeCodEngine::project(self, &factors, premium)
435 }
436
437 pub fn bootstrap_odp(
439 &self,
440 tail: f64,
441 options: OdpBootstrapOptions,
442 ) -> Result<OdpBootstrapResult, ValidationError> {
443 bootstrap_odp(self, tail, options)
444 }
445
446 pub fn exhibit(
448 &self,
449 premium: Option<&[f64]>,
450 expected_ultimate: Option<&[f64]>,
451 tail: f64,
452 ) -> Result<ExhibitBundle, ValidationError> {
453 build_exhibit_bundle(self, premium, expected_ultimate, tail)
454 }
455
456 pub fn benktander(
458 &self,
459 expected_ultimate: &[f64],
460 iterations: usize,
461 tail: f64,
462 ) -> Result<BenktanderProjection, ValidationError> {
463 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
464 BenktanderEngine::project_from_expected_ultimate(
465 self,
466 &factors,
467 expected_ultimate,
468 iterations,
469 )
470 }
471
472 pub fn generalized_cape_cod(
474 &self,
475 premium: &[f64],
476 decay: f64,
477 tail: f64,
478 ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
479 let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
480 GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
481 }
482
483 pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
485 brosius::project(self, tail)
486 }
487
488 pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
490 fit_odp(self, tail, MonotonicityPolicy::Strict)
491 }
492
493 pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
495 glm_reserving::fit_glm(self, options)
496 }
497
498 pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
500 clark_mle::fit_clark_ldf(self, options)
501 }
502
503 pub fn clark_cape_cod(
505 &self,
506 premium: &[f64],
507 options: &ClarkOptions,
508 ) -> Result<ClarkMleResult, ValidationError> {
509 clark_mle::fit_clark_cape_cod(self, premium, options)
510 }
511
512 pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
514 ptf_regression::fit_ptf(self, options)
515 }
516
517 pub fn diagnostics(&self) -> TriangleDiagnostics {
519 triangle_diagnostics::analyze(self)
520 }
521}
522
523#[cfg(test)]
524mod tests {
525 use super::*;
526 use crate::validate::ValidationError;
527
528 #[test]
529 fn try_new_rejects_shape_mismatch() {
530 assert_eq!(
531 Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
532 Err(ValidationError::ShapeMismatch)
533 );
534 }
535
536 #[test]
537 fn try_new_accepts_valid_square_triangle() {
538 let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
539
540 assert_eq!(triangle.n_origins, 2);
541 assert_eq!(triangle.n_devs, 2);
542 }
543}