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::capital::aggregate_loss::discretize_rounding(
276 self,
277 step,
278 max_index,
279 capture_upper_tail,
280 )
281 }
282
283 pub fn discretize_mean_preserving(
285 &self,
286 step: f64,
287 max_index: usize,
288 ) -> Result<Vec<f64>, ValidationError> {
289 crate::capital::aggregate_loss::discretize_mean_preserving(self, step, max_index)
290 }
291
292 pub fn lognormal_from_mean_cv(mean: f64, cv: f64) -> Result<Self, ValidationError> {
295 if !mean.is_finite() || !cv.is_finite() {
296 return Err(ValidationError::NotFinite);
297 }
298 if mean <= 0.0 || cv <= 0.0 {
299 return Err(ValidationError::InvalidParameter(
300 "lognormal mean and CV must be strictly positive",
301 ));
302 }
303 let sigma = (cv * cv).ln_1p().sqrt();
304 let mu = mean.ln() - 0.5 * sigma * sigma;
305 Ok(Self::Lognormal { mu, sigma })
306 }
307
308 pub fn validate(&self) -> Result<(), ValidationError> {
310 match self {
311 Self::Lognormal { mu, sigma } => {
312 if !mu.is_finite() || !sigma.is_finite() {
313 return Err(ValidationError::NotFinite);
314 }
315 if *sigma <= 0.0 {
316 return Err(ValidationError::InvalidParameter(
317 "lognormal sigma must be > 0",
318 ));
319 }
320 }
321 Self::Pareto { alpha, theta } | Self::SingleParameterPareto { alpha, theta } => {
322 if !alpha.is_finite() || !theta.is_finite() {
323 return Err(ValidationError::NotFinite);
324 }
325 if *alpha <= 0.0 || *theta <= 0.0 {
326 return Err(ValidationError::InvalidParameter(
327 "Pareto alpha and theta must be > 0",
328 ));
329 }
330 }
331 Self::Exponential { mean } => {
332 if !mean.is_finite() {
333 return Err(ValidationError::NotFinite);
334 }
335 if *mean <= 0.0 {
336 return Err(ValidationError::InvalidParameter(
337 "exponential mean must be > 0",
338 ));
339 }
340 }
341 Self::MixedExponential { weights, means } => {
342 if weights.is_empty() || weights.len() != means.len() {
343 return Err(ValidationError::ShapeMismatch);
344 }
345 let mut sum_w = 0.0;
346 for (&w, &m) in weights.iter().zip(means.iter()) {
347 if !w.is_finite() || !m.is_finite() {
348 return Err(ValidationError::NotFinite);
349 }
350 if w <= 0.0 || m <= 0.0 {
351 return Err(ValidationError::InvalidParameter(
352 "mixed exponential weights and means must be > 0",
353 ));
354 }
355 sum_w += w;
356 }
357 if (sum_w - 1.0).abs() > 1e-6 {
358 return Err(ValidationError::InvalidParameter(
359 "mixed exponential weights must sum to 1.0",
360 ));
361 }
362 }
363 Self::GeneralizedPareto { xi, beta } => {
364 if !xi.is_finite() || !beta.is_finite() {
365 return Err(ValidationError::NotFinite);
366 }
367 if *beta <= 0.0 {
368 return Err(ValidationError::InvalidParameter(
369 "GPD scale beta must be > 0",
370 ));
371 }
372 if *xi < 0.0 {
373 return Err(ValidationError::InvalidParameter(
374 "GPD shape xi must be >= 0 for unbounded positive support",
375 ));
376 }
377 }
378 }
379 Ok(())
380 }
381
382 pub fn survival(&self, x: f64) -> f64 {
384 if x <= 0.0 {
385 return 1.0;
386 }
387 match self {
388 Self::Lognormal { mu, sigma } => {
389 let z = (x.ln() - mu) / sigma;
390 normal_cdf_exact(-z)
391 }
392 Self::Pareto { alpha, theta } => (theta / (x + theta)).powf(*alpha),
393 Self::SingleParameterPareto { alpha, theta } => {
394 if x <= *theta {
395 1.0
396 } else {
397 (theta / x).powf(*alpha)
398 }
399 }
400 Self::Exponential { mean } => (-x / mean).exp(),
401 Self::MixedExponential { weights, means } => weights
402 .iter()
403 .zip(means.iter())
404 .map(|(&w, &m)| w * (-x / m).exp())
405 .sum(),
406 Self::GeneralizedPareto { xi, beta } => {
407 if xi.abs() <= 1e-12 {
408 (-x / beta).exp()
409 } else {
410 (-((xi * x / beta).ln_1p()) / xi).exp()
411 }
412 }
413 }
414 }
415
416 pub fn cdf(&self, x: f64) -> f64 {
418 1.0 - self.survival(x)
419 }
420
421 pub fn pdf(&self, x: f64) -> f64 {
423 if x <= 0.0 {
424 return 0.0;
425 }
426 match self {
427 Self::Lognormal { mu, sigma } => {
428 let z = (x.ln() - mu) / sigma;
429 (-0.5 * z * z).exp() / (x * sigma * TAU.sqrt())
430 }
431 Self::Pareto { alpha, theta } => {
432 (alpha / (x + theta)) * (theta / (x + theta)).powf(*alpha)
434 }
435 Self::SingleParameterPareto { alpha, theta } => {
436 if x < *theta {
437 0.0
438 } else {
439 (alpha / x) * (theta / x).powf(*alpha)
440 }
441 }
442 Self::Exponential { mean } => (-x / mean).exp() / mean,
443 Self::MixedExponential { weights, means } => weights
444 .iter()
445 .zip(means.iter())
446 .map(|(&w, &m)| w * (-x / m).exp() / m)
447 .sum(),
448 Self::GeneralizedPareto { xi, beta } => {
449 if xi.abs() <= 1e-12 {
450 (-x / beta).exp() / beta
451 } else {
452 (-(1.0 / xi + 1.0) * (xi * x / beta).ln_1p()).exp() / beta
453 }
454 }
455 }
456 }
457
458 pub fn unbounded_mean(&self) -> Option<f64> {
461 match self {
462 Self::Lognormal { mu, sigma } => Some((mu + 0.5 * sigma * sigma).exp()),
463 Self::Pareto { alpha, theta } => {
464 if *alpha > 1.0 {
465 Some(theta / (alpha - 1.0))
466 } else {
467 None
468 }
469 }
470 Self::SingleParameterPareto { alpha, theta } => {
471 if *alpha > 1.0 {
472 Some(alpha * theta / (alpha - 1.0))
473 } else {
474 None
475 }
476 }
477 Self::Exponential { mean } => Some(*mean),
478 Self::MixedExponential { weights, means } => {
479 Some(weights.iter().zip(means.iter()).map(|(&w, &m)| w * m).sum())
480 }
481 Self::GeneralizedPareto { xi, beta } => {
482 if *xi < 1.0 {
483 Some(beta / (1.0 - xi))
484 } else {
485 None
486 }
487 }
488 }
489 }
490
491 pub fn limited_expected_value(&self, limit: f64) -> Result<f64, ValidationError> {
494 self.validate()?;
495 if !limit.is_finite() {
496 return Err(ValidationError::NotFinite);
497 }
498 if limit < 0.0 {
499 return Err(ValidationError::Negative);
500 }
501 if limit == 0.0 {
502 return Ok(0.0);
503 }
504
505 let lev = match self {
506 Self::Lognormal { mu, sigma } => {
507 let z = (limit.ln() - mu) / sigma;
508 let cdf_shifted = normal_cdf_exact(z - sigma);
509 let term1 = if cdf_shifted == 0.0 {
510 0.0
511 } else {
512 (mu + 0.5 * sigma * sigma).exp() * cdf_shifted
513 };
514 term1 + limit * normal_cdf_exact(-z)
515 }
516 Self::Pareto { alpha, theta } => {
517 let ln_ratio = (limit / theta).ln_1p();
518 if (alpha - 1.0).abs() <= 1e-10 {
519 theta * ln_ratio
520 } else {
521 let am1 = alpha - 1.0;
522 theta * -((-am1 * ln_ratio).exp_m1()) / am1
523 }
524 }
525 Self::SingleParameterPareto { alpha, theta } => {
526 if limit <= *theta {
527 limit
528 } else {
529 let ln_ratio = (limit / theta).ln();
530 if (alpha - 1.0).abs() <= 1e-10 {
531 theta * (1.0 + ln_ratio)
532 } else {
533 let am1 = alpha - 1.0;
534 theta + theta * -((-am1 * ln_ratio).exp_m1()) / am1
535 }
536 }
537 }
538 Self::Exponential { mean } => mean * -((-limit / mean).exp_m1()),
539 Self::MixedExponential { weights, means } => weights
540 .iter()
541 .zip(means.iter())
542 .map(|(&w, &m)| w * m * -((-limit / m).exp_m1()))
543 .sum(),
544 Self::GeneralizedPareto { xi, beta } => {
545 if xi.abs() <= 1e-10 {
546 beta * -((-limit / beta).exp_m1())
547 } else {
548 let ln_u = (xi * limit / beta).ln_1p();
549 if (xi - 1.0).abs() <= 1e-10 {
550 beta * ln_u
551 } else {
552 let omx = 1.0 - xi;
553 beta * -(((-omx / xi) * ln_u).exp_m1()) / omx
554 }
555 }
556 }
557 };
558 Ok(lev)
559 }
560
561 pub fn layer_expected_loss(&self, attachment: f64, limit: f64) -> Result<f64, ValidationError> {
564 self.validate()?;
565 if !attachment.is_finite() || !limit.is_finite() {
566 return Err(ValidationError::NotFinite);
567 }
568 if attachment < 0.0 || limit < 0.0 {
569 return Err(ValidationError::Negative);
570 }
571 if limit == 0.0 {
572 return Ok(0.0);
573 }
574 let upper = self.limited_expected_value(attachment + limit)?;
575 let lower = self.limited_expected_value(attachment)?;
576 Ok((upper - lower).max(0.0))
577 }
578
579 pub fn excess_ratio(&self, retention: f64) -> Result<f64, ValidationError> {
581 self.validate()?;
582 let mean = self
583 .unbounded_mean()
584 .ok_or(ValidationError::InvalidParameter(
585 "excess ratio requires a finite unbounded mean",
586 ))?;
587 let lev = self.limited_expected_value(retention)?;
588 Ok(((mean - lev) / mean).clamp(0.0, 1.0))
589 }
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595
596 #[test]
597 fn computes_paid_and_ultimate_severity() {
598 let paid = paid_severity(&[100.0, 120.0], &[10.0, 12.0]).expect("paid severity");
599 let ultimate =
600 ultimate_severity(&[150.0, 180.0], &[10.0, 12.0]).expect("ultimate severity");
601
602 assert_eq!(paid, vec![10.0, 10.0]);
603 assert_eq!(ultimate, vec![15.0, 15.0]);
604 }
605
606 #[test]
607 fn computes_frequency_severity_ultimate() {
608 let loss =
609 frequency_severity_ultimate(&[10.0, 12.0], &[15.0, 20.0]).expect("frequency severity");
610 assert_eq!(loss, vec![150.0, 240.0]);
611 }
612
613 #[test]
614 fn parametric_lev_matches_numerical_survival_integral() {
615 let dists = [
616 SeverityDistribution::lognormal_from_mean_cv(100_000.0, 1.5).unwrap(),
617 SeverityDistribution::Pareto {
618 alpha: 2.5,
619 theta: 150_000.0,
620 },
621 SeverityDistribution::Pareto {
622 alpha: 1.0,
623 theta: 100_000.0,
624 },
625 SeverityDistribution::SingleParameterPareto {
626 alpha: 2.0,
627 theta: 50_000.0,
628 },
629 SeverityDistribution::Exponential { mean: 100_000.0 },
630 SeverityDistribution::MixedExponential {
631 weights: vec![0.7, 0.3],
632 means: vec![40_000.0, 240_000.0],
633 },
634 SeverityDistribution::GeneralizedPareto {
635 xi: 0.35,
636 beta: 80_000.0,
637 },
638 ];
639
640 let limit = 250_000.0;
642 let steps = 5_000usize;
643 let dx = limit / steps as f64;
644 for dist in &dists {
645 let exact = dist.limited_expected_value(limit).expect("lev");
646 let mut trap = 0.0;
647 for i in 0..steps {
648 let x_mid = (i as f64 + 0.5) * dx;
649 trap += dist.survival(x_mid) * dx;
650 }
651 assert!(
652 (exact - trap).abs() / exact < 5e-4,
653 "dist={dist:?} exact={exact} numerical={trap}"
654 );
655 }
656 }
657}