1use std::f64::consts::TAU;
17
18use crate::validate::{ValidationError, validate_nonnegative_finite_vector};
19
20fn divide_vectors(numerator: &[f64], denominator: &[f64]) -> Result<Vec<f64>, ValidationError> {
21 let n = numerator.len();
22 validate_nonnegative_finite_vector(numerator, n)?;
23 validate_nonnegative_finite_vector(denominator, denominator.len())?;
24 if denominator.len() != n {
25 return Err(ValidationError::ShapeMismatch);
26 }
27
28 let mut out = Vec::with_capacity(n);
29 for i in 0..n {
30 if denominator[i] <= 0.0 {
31 return Err(ValidationError::DivideByZero("count"));
32 }
33 out.push(numerator[i] / denominator[i]);
34 }
35 Ok(out)
36}
37
38pub fn paid_severity(paid: &[f64], counts: &[f64]) -> Result<Vec<f64>, ValidationError> {
40 divide_vectors(paid, counts)
41}
42
43pub fn incurred_severity(incurred: &[f64], counts: &[f64]) -> Result<Vec<f64>, ValidationError> {
45 divide_vectors(incurred, counts)
46}
47
48pub fn ultimate_severity(
50 ultimate_loss: &[f64],
51 ultimate_count: &[f64],
52) -> Result<Vec<f64>, ValidationError> {
53 divide_vectors(ultimate_loss, ultimate_count)
54}
55
56pub fn open_claim_severity(
58 case_reserve: &[f64],
59 open_claims: &[f64],
60) -> Result<Vec<f64>, ValidationError> {
61 divide_vectors(case_reserve, open_claims)
62}
63
64pub fn closed_claim_severity(
66 paid: &[f64],
67 closed_claims: &[f64],
68) -> Result<Vec<f64>, ValidationError> {
69 divide_vectors(paid, closed_claims)
70}
71
72pub fn frequency_severity_ultimate(
74 ultimate_count: &[f64],
75 severity: &[f64],
76) -> Result<Vec<f64>, ValidationError> {
77 let n = ultimate_count.len();
78 validate_nonnegative_finite_vector(ultimate_count, n)?;
79 validate_nonnegative_finite_vector(severity, severity.len())?;
80 if severity.len() != n {
81 return Err(ValidationError::ShapeMismatch);
82 }
83 Ok(ultimate_count
84 .iter()
85 .zip(severity.iter())
86 .map(|(&count, &sev)| count * sev)
87 .collect())
88}
89
90pub(crate) fn normal_cdf_exact(z: f64) -> f64 {
97 0.5 * erfc_approx(-z / std::f64::consts::SQRT_2)
98}
99
100fn erfc_approx(x: f64) -> f64 {
102 if x.is_nan() {
103 return f64::NAN;
104 }
105 if x < 0.0 {
106 return 2.0 - erfc_approx(-x);
107 }
108 if x < 0.46875 {
109 const A: [f64; 5] = [
110 3.161_123_743_870_565_6e0,
111 1.138_641_541_510_501_6e2,
112 3.774_852_376_853_02e2,
113 3.209_377_589_138_469_5e3,
114 1.857_777_061_846_031_5e-1,
115 ];
116 const B: [f64; 4] = [
117 2.360_129_095_234_412_1e1,
118 2.440_246_379_344_441_7e2,
119 1.282_616_526_077_372_3e3,
120 2.844_236_833_439_171e3,
121 ];
122 let y = x * x;
123 let num = (((A[4] * y + A[0]) * y + A[1]) * y + A[2]) * y + A[3];
124 let den = (((y + B[0]) * y + B[1]) * y + B[2]) * y + B[3];
125 1.0 - x * num / den
126 } else if x <= 4.0 {
127 const C: [f64; 9] = [
128 5.641_884_969_886_701e-1,
129 8.883_149_794_388_375,
130 6.611_919_063_714_163e1,
131 2.986_351_381_974_001e2,
132 8.819_522_212_417_69e2,
133 1.712_047_612_634_070_6e3,
134 2.051_078_377_826_071_5e3,
135 1.230_339_354_797_997_2e3,
136 2.153_115_354_744_038_5e-8,
137 ];
138 const D: [f64; 8] = [
139 1.574_492_611_070_983_5e1,
140 1.176_939_508_913_125e2,
141 5.371_811_018_620_099e2,
142 1.621_389_574_566_690_2e3,
143 3.290_799_235_733_459_6e3,
144 4.362_619_090_143_247e3,
145 3.439_367_674_143_721_6e3,
146 1.230_339_354_803_749_4e3,
147 ];
148 let num = (((((((C[8] * x + C[0]) * x + C[1]) * x + C[2]) * x + C[3]) * x + C[4]) * x
149 + C[5])
150 * x
151 + C[6])
152 * x
153 + C[7];
154 let den = (((((((x + D[0]) * x + D[1]) * x + D[2]) * x + D[3]) * x + D[4]) * x + D[5]) * x
155 + D[6])
156 * x
157 + D[7];
158 (-x * x).exp() * num / den
159 } else if x < 26.5 {
160 const P: [f64; 6] = [
161 3.053_266_349_612_323_4e-1,
162 3.603_448_999_498_044_4e-1,
163 1.257_817_261_112_292_5e-1,
164 1.608_378_514_874_228e-2,
165 6.587_491_615_298_378e-4,
166 1.631_538_713_730_209_8e-2,
167 ];
168 const Q: [f64; 5] = [
169 2.568_520_192_289_822,
170 1.872_952_849_923_460_5e0,
171 5.279_051_029_514_285e-1,
172 6.051_834_131_244_132e-2,
173 2.335_204_976_268_691_9e-3,
174 ];
175 let y = 1.0 / (x * x);
176 let num = ((((P[5] * y + P[0]) * y + P[1]) * y + P[2]) * y + P[3]) * y + P[4];
177 let den = ((((y + Q[0]) * y + Q[1]) * y + Q[2]) * y + Q[3]) * y + Q[4];
178 let inv_sqrt_pi = std::f64::consts::FRAC_2_SQRT_PI * 0.5;
179 (-x * x).exp() / x * (inv_sqrt_pi - y * num / den)
180 } else {
181 0.0
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
188pub enum SeverityDistribution {
189 Lognormal {
191 mu: f64,
193 sigma: f64,
195 },
196 Pareto {
199 alpha: f64,
201 theta: f64,
203 },
204 SingleParameterPareto {
206 alpha: f64,
208 theta: f64,
210 },
211 Exponential {
213 mean: f64,
215 },
216 MixedExponential {
219 weights: Vec<f64>,
221 means: Vec<f64>,
223 },
224 GeneralizedPareto {
227 xi: f64,
229 beta: f64,
231 },
232}
233
234impl SeverityDistribution {
235 pub const fn lognormal(mu: f64, sigma: f64) -> Self {
237 Self::Lognormal { mu, sigma }
238 }
239
240 pub const fn pareto(alpha: f64, theta: f64) -> Self {
242 Self::Pareto { alpha, theta }
243 }
244
245 pub const fn single_parameter_pareto(alpha: f64, theta: f64) -> Self {
247 Self::SingleParameterPareto { alpha, theta }
248 }
249
250 pub const fn exponential(mean: f64) -> Self {
252 Self::Exponential { mean }
253 }
254
255 pub fn mixed_exponential(weights: impl Into<Vec<f64>>, means: impl Into<Vec<f64>>) -> Self {
257 Self::MixedExponential {
258 weights: weights.into(),
259 means: means.into(),
260 }
261 }
262
263 pub const fn gpd(xi: f64, beta: f64) -> Self {
265 Self::GeneralizedPareto { xi, beta }
266 }
267
268 pub fn discretize_rounding(
270 &self,
271 step: f64,
272 max_index: usize,
273 capture_upper_tail: bool,
274 ) -> Result<Vec<f64>, ValidationError> {
275 crate::aggregate_loss::discretize_rounding(self, step, max_index, capture_upper_tail)
276 }
277
278 pub fn discretize_mean_preserving(
280 &self,
281 step: f64,
282 max_index: usize,
283 ) -> Result<Vec<f64>, ValidationError> {
284 crate::aggregate_loss::discretize_mean_preserving(self, step, max_index)
285 }
286
287 pub fn lognormal_from_mean_cv(mean: f64, cv: f64) -> Result<Self, ValidationError> {
290 if !mean.is_finite() || !cv.is_finite() {
291 return Err(ValidationError::NotFinite);
292 }
293 if mean <= 0.0 || cv <= 0.0 {
294 return Err(ValidationError::InvalidParameter(
295 "lognormal mean and CV must be strictly positive",
296 ));
297 }
298 let sigma = (1.0 + cv * cv).ln().sqrt();
299 let mu = mean.ln() - 0.5 * sigma * sigma;
300 Ok(Self::Lognormal { mu, sigma })
301 }
302
303 pub fn validate(&self) -> Result<(), ValidationError> {
305 match self {
306 Self::Lognormal { mu, sigma } => {
307 if !mu.is_finite() || !sigma.is_finite() {
308 return Err(ValidationError::NotFinite);
309 }
310 if *sigma <= 0.0 {
311 return Err(ValidationError::InvalidParameter(
312 "lognormal sigma must be > 0",
313 ));
314 }
315 }
316 Self::Pareto { alpha, theta } | Self::SingleParameterPareto { alpha, theta } => {
317 if !alpha.is_finite() || !theta.is_finite() {
318 return Err(ValidationError::NotFinite);
319 }
320 if *alpha <= 0.0 || *theta <= 0.0 {
321 return Err(ValidationError::InvalidParameter(
322 "Pareto alpha and theta must be > 0",
323 ));
324 }
325 }
326 Self::Exponential { mean } => {
327 if !mean.is_finite() {
328 return Err(ValidationError::NotFinite);
329 }
330 if *mean <= 0.0 {
331 return Err(ValidationError::InvalidParameter(
332 "exponential mean must be > 0",
333 ));
334 }
335 }
336 Self::MixedExponential { weights, means } => {
337 if weights.is_empty() || weights.len() != means.len() {
338 return Err(ValidationError::ShapeMismatch);
339 }
340 let mut sum_w = 0.0;
341 for (&w, &m) in weights.iter().zip(means.iter()) {
342 if !w.is_finite() || !m.is_finite() {
343 return Err(ValidationError::NotFinite);
344 }
345 if w <= 0.0 || m <= 0.0 {
346 return Err(ValidationError::InvalidParameter(
347 "mixed exponential weights and means must be > 0",
348 ));
349 }
350 sum_w += w;
351 }
352 if (sum_w - 1.0).abs() > 1e-6 {
353 return Err(ValidationError::InvalidParameter(
354 "mixed exponential weights must sum to 1.0",
355 ));
356 }
357 }
358 Self::GeneralizedPareto { xi, beta } => {
359 if !xi.is_finite() || !beta.is_finite() {
360 return Err(ValidationError::NotFinite);
361 }
362 if *beta <= 0.0 {
363 return Err(ValidationError::InvalidParameter(
364 "GPD scale beta must be > 0",
365 ));
366 }
367 if *xi < 0.0 {
368 return Err(ValidationError::InvalidParameter(
369 "GPD shape xi must be >= 0 for unbounded positive support",
370 ));
371 }
372 }
373 }
374 Ok(())
375 }
376
377 pub fn survival(&self, x: f64) -> f64 {
379 if x <= 0.0 {
380 return 1.0;
381 }
382 match self {
383 Self::Lognormal { mu, sigma } => {
384 let z = (x.ln() - mu) / sigma;
385 normal_cdf_exact(-z)
386 }
387 Self::Pareto { alpha, theta } => (theta / (x + theta)).powf(*alpha),
388 Self::SingleParameterPareto { alpha, theta } => {
389 if x <= *theta {
390 1.0
391 } else {
392 (theta / x).powf(*alpha)
393 }
394 }
395 Self::Exponential { mean } => (-x / mean).exp(),
396 Self::MixedExponential { weights, means } => weights
397 .iter()
398 .zip(means.iter())
399 .map(|(&w, &m)| w * (-x / m).exp())
400 .sum(),
401 Self::GeneralizedPareto { xi, beta } => {
402 if xi.abs() <= 1e-12 {
403 (-x / beta).exp()
404 } else {
405 (-((xi * x / beta).ln_1p()) / xi).exp()
406 }
407 }
408 }
409 }
410
411 pub fn cdf(&self, x: f64) -> f64 {
413 1.0 - self.survival(x)
414 }
415
416 pub fn pdf(&self, x: f64) -> f64 {
418 if x <= 0.0 {
419 return 0.0;
420 }
421 match self {
422 Self::Lognormal { mu, sigma } => {
423 let z = (x.ln() - mu) / sigma;
424 (-0.5 * z * z).exp() / (x * sigma * TAU.sqrt())
425 }
426 Self::Pareto { alpha, theta } => {
427 (alpha / (x + theta)) * (theta / (x + theta)).powf(*alpha)
429 }
430 Self::SingleParameterPareto { alpha, theta } => {
431 if x < *theta {
432 0.0
433 } else {
434 (alpha / x) * (theta / x).powf(*alpha)
435 }
436 }
437 Self::Exponential { mean } => (-x / mean).exp() / mean,
438 Self::MixedExponential { weights, means } => weights
439 .iter()
440 .zip(means.iter())
441 .map(|(&w, &m)| w * (-x / m).exp() / m)
442 .sum(),
443 Self::GeneralizedPareto { xi, beta } => {
444 if xi.abs() <= 1e-12 {
445 (-x / beta).exp() / beta
446 } else {
447 (-(1.0 / xi + 1.0) * (xi * x / beta).ln_1p()).exp() / beta
448 }
449 }
450 }
451 }
452
453 pub fn unbounded_mean(&self) -> Option<f64> {
456 match self {
457 Self::Lognormal { mu, sigma } => Some((mu + 0.5 * sigma * sigma).exp()),
458 Self::Pareto { alpha, theta } => {
459 if *alpha > 1.0 {
460 Some(theta / (alpha - 1.0))
461 } else {
462 None
463 }
464 }
465 Self::SingleParameterPareto { alpha, theta } => {
466 if *alpha > 1.0 {
467 Some(alpha * theta / (alpha - 1.0))
468 } else {
469 None
470 }
471 }
472 Self::Exponential { mean } => Some(*mean),
473 Self::MixedExponential { weights, means } => {
474 Some(weights.iter().zip(means.iter()).map(|(&w, &m)| w * m).sum())
475 }
476 Self::GeneralizedPareto { xi, beta } => {
477 if *xi < 1.0 {
478 Some(beta / (1.0 - xi))
479 } else {
480 None
481 }
482 }
483 }
484 }
485
486 pub fn limited_expected_value(&self, limit: f64) -> Result<f64, ValidationError> {
489 self.validate()?;
490 if !limit.is_finite() {
491 return Err(ValidationError::NotFinite);
492 }
493 if limit < 0.0 {
494 return Err(ValidationError::Negative);
495 }
496 if limit == 0.0 {
497 return Ok(0.0);
498 }
499
500 let lev = match self {
501 Self::Lognormal { mu, sigma } => {
502 let z = (limit.ln() - mu) / sigma;
503 let cdf_shifted = normal_cdf_exact(z - sigma);
504 let term1 = if cdf_shifted == 0.0 {
505 0.0
506 } else {
507 (mu + 0.5 * sigma * sigma).exp() * cdf_shifted
508 };
509 term1 + limit * normal_cdf_exact(-z)
510 }
511 Self::Pareto { alpha, theta } => {
512 let ln_ratio = (limit / theta).ln_1p();
513 if (alpha - 1.0).abs() <= 1e-10 {
514 theta * ln_ratio
515 } else {
516 let am1 = alpha - 1.0;
517 theta * -((-am1 * ln_ratio).exp_m1()) / am1
518 }
519 }
520 Self::SingleParameterPareto { alpha, theta } => {
521 if limit <= *theta {
522 limit
523 } else {
524 let ln_ratio = (limit / theta).ln();
525 if (alpha - 1.0).abs() <= 1e-10 {
526 theta * (1.0 + ln_ratio)
527 } else {
528 let am1 = alpha - 1.0;
529 theta + theta * -((-am1 * ln_ratio).exp_m1()) / am1
530 }
531 }
532 }
533 Self::Exponential { mean } => mean * -((-limit / mean).exp_m1()),
534 Self::MixedExponential { weights, means } => weights
535 .iter()
536 .zip(means.iter())
537 .map(|(&w, &m)| w * m * -((-limit / m).exp_m1()))
538 .sum(),
539 Self::GeneralizedPareto { xi, beta } => {
540 if xi.abs() <= 1e-10 {
541 beta * -((-limit / beta).exp_m1())
542 } else {
543 let ln_u = (xi * limit / beta).ln_1p();
544 if (xi - 1.0).abs() <= 1e-10 {
545 beta * ln_u
546 } else {
547 let omx = 1.0 - xi;
548 beta * -(((-omx / xi) * ln_u).exp_m1()) / omx
549 }
550 }
551 }
552 };
553 Ok(lev)
554 }
555
556 pub fn layer_expected_loss(&self, attachment: f64, limit: f64) -> Result<f64, ValidationError> {
559 self.validate()?;
560 if !attachment.is_finite() || !limit.is_finite() {
561 return Err(ValidationError::NotFinite);
562 }
563 if attachment < 0.0 || limit < 0.0 {
564 return Err(ValidationError::Negative);
565 }
566 if limit == 0.0 {
567 return Ok(0.0);
568 }
569 let upper = self.limited_expected_value(attachment + limit)?;
570 let lower = self.limited_expected_value(attachment)?;
571 Ok((upper - lower).max(0.0))
572 }
573
574 pub fn excess_ratio(&self, retention: f64) -> Result<f64, ValidationError> {
576 self.validate()?;
577 let mean = self
578 .unbounded_mean()
579 .ok_or(ValidationError::InvalidParameter(
580 "excess ratio requires a finite unbounded mean",
581 ))?;
582 let lev = self.limited_expected_value(retention)?;
583 Ok(((mean - lev) / mean).clamp(0.0, 1.0))
584 }
585
586 pub fn ilf(&self, basic_limit: f64, increased_limit: f64) -> Result<f64, ValidationError> {
589 if basic_limit <= 0.0 || increased_limit < 0.0 {
590 return Err(ValidationError::InvalidParameter(
591 "basic_limit must be > 0 and increased_limit >= 0",
592 ));
593 }
594 let lev_b = self.limited_expected_value(basic_limit)?;
595 if !(lev_b > 0.0) {
596 return Err(ValidationError::DivideByZero("basic limit LEV"));
597 }
598 let lev_l = self.limited_expected_value(increased_limit)?;
599 Ok(lev_l / lev_b)
600 }
601}
602
603#[cfg(test)]
604mod tests {
605 use super::*;
606
607 #[test]
608 fn computes_paid_and_ultimate_severity() {
609 let paid = paid_severity(&[100.0, 120.0], &[10.0, 12.0]).expect("paid severity");
610 let ultimate =
611 ultimate_severity(&[150.0, 180.0], &[10.0, 12.0]).expect("ultimate severity");
612
613 assert_eq!(paid, vec![10.0, 10.0]);
614 assert_eq!(ultimate, vec![15.0, 15.0]);
615 }
616
617 #[test]
618 fn computes_frequency_severity_ultimate() {
619 let loss =
620 frequency_severity_ultimate(&[10.0, 12.0], &[15.0, 20.0]).expect("frequency severity");
621 assert_eq!(loss, vec![150.0, 240.0]);
622 }
623
624 #[test]
625 fn parametric_lev_matches_numerical_survival_integral() {
626 let dists = [
627 SeverityDistribution::lognormal_from_mean_cv(100_000.0, 1.5).unwrap(),
628 SeverityDistribution::Pareto {
629 alpha: 2.5,
630 theta: 150_000.0,
631 },
632 SeverityDistribution::Pareto {
633 alpha: 1.0,
634 theta: 100_000.0,
635 },
636 SeverityDistribution::SingleParameterPareto {
637 alpha: 2.0,
638 theta: 50_000.0,
639 },
640 SeverityDistribution::Exponential { mean: 100_000.0 },
641 SeverityDistribution::MixedExponential {
642 weights: vec![0.7, 0.3],
643 means: vec![40_000.0, 240_000.0],
644 },
645 SeverityDistribution::GeneralizedPareto {
646 xi: 0.35,
647 beta: 80_000.0,
648 },
649 ];
650
651 let limit = 250_000.0;
653 let steps = 5_000usize;
654 let dx = limit / steps as f64;
655 for dist in &dists {
656 let exact = dist.limited_expected_value(limit).expect("lev");
657 let mut trap = 0.0;
658 for i in 0..steps {
659 let x_mid = (i as f64 + 0.5) * dx;
660 trap += dist.survival(x_mid) * dx;
661 }
662 assert!(
663 (exact - trap).abs() / exact < 5e-4,
664 "dist={dist:?} exact={exact} numerical={trap}"
665 );
666 assert!(dist.ilf(100_000.0, 250_000.0).unwrap() >= 1.0);
667 }
668 }
669}