Skip to main content

reserving_kernels/
aggregate_loss.rs

1//! Compound aggregate loss distributions via Panjer (1981) recursion and
2//! Robertson (1992) tilted radix-2 FFT characteristic-function inversion.
3//!
4//! Implements:
5//!
6//! * H. H. Panjer, *"Recursive Evaluation of a Family of Compound
7//!   Distributions"*, *ASTIN Bulletin*, Vol. 12, No. 1 (1981), pp. 22–26.
8//! * J. P. Robertson, *"The Computation of Aggregate Loss Distributions"*,
9//!   *PCAS*, Vol. LXXIX (1992), pp. 57–133.
10//! * S. A. Klugman, H. H. Panjer & G. E. Willmot, *Loss Models: From Data to
11//!   Decisions* (5th ed.), Chapter 9 (Panjer `(a, b, 0)` class, method of
12//!   rounding, and mean-preserving LEV discretization).
13//!
14//! ## Panjer `(a, b, 0)` Recursion
15//!
16//! For compound sum `S = sum_{i=1}^N X_i` where `N` belongs to the `(a, b, 0)`
17//! class (`p_k / p_{k-1} = a + b / k` for `k >= 1`: Poisson, Binomial,
18//! Negative Binomial) and discrete severity `X` has PMF `f_0, f_1, ..., f_m`
19//! on grid `0, h, 2h, ..., m*h`:
20//!
21//! `g_0 = P_N(f_0)`,
22//! `g_x = (1 / (1 - a * f_0)) * sum_{y=1}^{min(x, m)} (a + b * y / x) * f_y * g_{x - y}`.
23//!
24//! ## Tilted Radix-2 FFT Inversion
25//!
26//! For large grids (`N >= 2^12`) where `O(N^2)` Panjer recursion slows down or
27//! `g_0 = P_N(f_0)` risks underflow, [`fft_aggregate_loss`] computes
28//! `phi_S(t) = P_N(phi_X(t))` in `O(N log N)` using a pure-Rust, zero-unsafe
29//! iterative radix-2 Cooley–Tukey FFT with exponential tilting
30//! `f_tilde_k = exp(-theta * k) * f_k` to suppress circular wrap-around
31//! aliasing by `exp(-theta * N)`.
32
33use std::f64::consts::TAU;
34
35use crate::severity::SeverityDistribution;
36use crate::validate::{ValidationError, validate_nonnegative_finite_slice};
37
38/// Claim-count frequency distribution in the Panjer `(a, b, 0)` class.
39#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
40pub enum FrequencyDistribution {
41    /// Poisson(`lambda`): `E[N] = Var(N) = lambda`, `a = 0`, `b = lambda`.
42    Poisson {
43        /// Poisson mean intensity `lambda > 0`.
44        lambda: f64,
45    },
46    /// Binomial(`m`, `q`): `E[N] = m q`, `Var(N) = m q (1 - q)`,
47    /// `a = -q / (1 - q)`, `b = (m + 1) q / (1 - q)`.
48    Binomial {
49        /// Number of trials `m >= 1`.
50        m: u64,
51        /// Per-trial claim probability `q in (0, 1)`.
52        q: f64,
53    },
54    /// Negative Binomial(`r`, `beta`) in Klugman–Panjer–Willmot parameterization:
55    /// `E[N] = r * beta`, `Var(N) = r * beta * (1 + beta)`,
56    /// `a = beta / (1 + beta)`, `b = (r - 1) * beta / (1 + beta)`.
57    NegativeBinomial {
58        /// Shape / dispersion parameter `r > 0`.
59        r: f64,
60        /// Scale parameter `beta > 0`.
61        beta: f64,
62    },
63}
64
65impl FrequencyDistribution {
66    /// Construct a `Poisson(lambda)` frequency distribution.
67    pub const fn poisson(lambda: f64) -> Self {
68        Self::Poisson { lambda }
69    }
70
71    /// Construct a `Binomial(m, q)` frequency distribution.
72    pub const fn binomial(m: u64, q: f64) -> Self {
73        Self::Binomial { m, q }
74    }
75
76    /// Construct a `NegativeBinomial(r, beta)` frequency distribution.
77    pub const fn negative_binomial(r: f64, beta: f64) -> Self {
78        Self::NegativeBinomial { r, beta }
79    }
80
81    /// Evaluate the compound aggregate distribution via exact Panjer `(a, b, 0)` recursion.
82    pub fn compound_panjer(
83        self,
84        severity_pmf: &[f64],
85        step: f64,
86        n_steps: usize,
87    ) -> Result<AggregateLossDistribution, ValidationError> {
88        panjer_recursion(self, severity_pmf, step, n_steps)
89    }
90
91    /// Evaluate the compound aggregate distribution via exponentially tilted radix-2 FFT.
92    pub fn compound_fft(
93        self,
94        severity_pmf: &[f64],
95        step: f64,
96        fft_size: usize,
97        tilt: Option<f64>,
98    ) -> Result<AggregateLossDistribution, ValidationError> {
99        fft_aggregate_loss(self, severity_pmf, step, fft_size, tilt)
100    }
101
102    /// Construct a Negative Binomial distribution matching a target `mean > 0`
103    /// and overdispersed `variance > mean`.
104    pub fn negative_binomial_from_mean_variance(
105        mean: f64,
106        variance: f64,
107    ) -> Result<Self, ValidationError> {
108        if !mean.is_finite() || !variance.is_finite() {
109            return Err(ValidationError::NotFinite);
110        }
111        if !(mean > 0.0) || !(variance > mean) {
112            return Err(ValidationError::InvalidParameter(
113                "Negative Binomial requires 0 < mean < variance",
114            ));
115        }
116        let beta = variance / mean - 1.0;
117        let r = mean / beta;
118        Ok(Self::NegativeBinomial { r, beta })
119    }
120
121    /// Validate distribution parameters.
122    pub fn validate(&self) -> Result<(), ValidationError> {
123        match *self {
124            Self::Poisson { lambda } => {
125                if !lambda.is_finite() {
126                    return Err(ValidationError::NotFinite);
127                }
128                if !(lambda > 0.0) {
129                    return Err(ValidationError::InvalidParameter(
130                        "Poisson lambda must be strictly positive",
131                    ));
132                }
133            }
134            Self::Binomial { m, q } => {
135                if !q.is_finite() {
136                    return Err(ValidationError::NotFinite);
137                }
138                if m == 0 || !(q > 0.0 && q < 1.0) {
139                    return Err(ValidationError::InvalidParameter(
140                        "Binomial requires m >= 1 and 0 < q < 1",
141                    ));
142                }
143            }
144            Self::NegativeBinomial { r, beta } => {
145                if !r.is_finite() || !beta.is_finite() {
146                    return Err(ValidationError::NotFinite);
147                }
148                if !(r > 0.0) || !(beta > 0.0) {
149                    return Err(ValidationError::InvalidParameter(
150                        "Negative Binomial requires r > 0 and beta > 0",
151                    ));
152                }
153            }
154        }
155        Ok(())
156    }
157
158    /// Panjer `(a, b)` recursion parameters.
159    #[inline]
160    pub fn panjer_ab(&self) -> (f64, f64) {
161        match *self {
162            Self::Poisson { lambda } => (0.0, lambda),
163            Self::Binomial { m, q } => {
164                let ratio = q / (1.0 - q);
165                (-ratio, (m as f64 + 1.0) * ratio)
166            }
167            Self::NegativeBinomial { r, beta } => {
168                let p = beta / (1.0 + beta);
169                (p, (r - 1.0) * p)
170            }
171        }
172    }
173
174    /// Theoretical frequency mean `E[N]`.
175    #[inline]
176    pub fn mean(&self) -> f64 {
177        match *self {
178            Self::Poisson { lambda } => lambda,
179            Self::Binomial { m, q } => m as f64 * q,
180            Self::NegativeBinomial { r, beta } => r * beta,
181        }
182    }
183
184    /// Theoretical frequency variance `Var(N)`.
185    #[inline]
186    pub fn variance(&self) -> f64 {
187        match *self {
188            Self::Poisson { lambda } => lambda,
189            Self::Binomial { m, q } => m as f64 * q * (1.0 - q),
190            Self::NegativeBinomial { r, beta } => r * beta * (1.0 + beta),
191        }
192    }
193
194    /// Real probability generating function `P_N(z)` for real `z in [0, 1]`.
195    #[inline]
196    pub fn pgf_real(&self, z: f64) -> f64 {
197        match *self {
198            Self::Poisson { lambda } => (lambda * (z - 1.0)).exp(),
199            Self::Binomial { m, q } => (1.0 - q + q * z).powf(m as f64),
200            Self::NegativeBinomial { r, beta } => (1.0 - beta * (z - 1.0)).powf(-r),
201        }
202    }
203
204    /// Complex probability generating function `P_N(re + i * im)`.
205    #[inline]
206    fn pgf_complex(&self, re: f64, im: f64) -> (f64, f64) {
207        match *self {
208            Self::Poisson { lambda } => {
209                let mag = (lambda * (re - 1.0)).exp();
210                let angle = lambda * im;
211                (mag * angle.cos(), mag * angle.sin())
212            }
213            Self::Binomial { m, q } => {
214                let wr = 1.0 - q + q * re;
215                let wi = q * im;
216                let r = wr.hypot(wi);
217                let phi = wi.atan2(wr);
218                let mag = r.powf(m as f64);
219                let ang = (m as f64) * phi;
220                (mag * ang.cos(), mag * ang.sin())
221            }
222            Self::NegativeBinomial { r, beta } => {
223                let wr = 1.0 + beta - beta * re;
224                let wi = -beta * im;
225                let radius = wr.hypot(wi);
226                let phi = wi.atan2(wr);
227                let mag = radius.powf(-r);
228                let ang = -r * phi;
229                (mag * ang.cos(), mag * ang.sin())
230            }
231        }
232    }
233}
234
235/// Discretized aggregate loss distribution on the uniform lattice `0, step, 2*step, ...`.
236#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
237#[non_exhaustive]
238pub struct AggregateLossDistribution {
239    /// Grid step size `h > 0`.
240    pub step: f64,
241    /// Discrete aggregate PMF `g_k = P(S = k * step)` (length `n_steps`).
242    pub pmf: Vec<f64>,
243    /// Cumulative distribution function `G_k = P(S <= k * step)` (length `n_steps`).
244    pub cdf: Vec<f64>,
245    /// Total captured probability mass `sum_k g_k` (`<= 1.0`; `< 1.0` reflects right truncation).
246    pub total_mass: f64,
247    /// Numerical mean `sum_k (k * step) * g_k`.
248    pub mean: f64,
249    /// Numerical variance `sum_k (k * step - mean)^2 * g_k`.
250    pub variance: f64,
251    /// Numerical standard deviation `sqrt(variance)`.
252    pub std_dev: f64,
253    /// Exact compound theoretical mean `E[N] * E[X]` from the input severity PMF.
254    pub exact_theoretical_mean: f64,
255    /// Exact compound theoretical variance `E[N] * Var(X) + Var(N) * E[X]^2`.
256    pub exact_theoretical_variance: f64,
257}
258
259impl AggregateLossDistribution {
260    /// Discrete Value at Risk `VaR_alpha(S) = inf { x : F_S(x) >= alpha }`.
261    pub fn var(&self, alpha: f64) -> Result<f64, ValidationError> {
262        if !alpha.is_finite() {
263            return Err(ValidationError::NotFinite);
264        }
265        if !(0.0..=1.0).contains(&alpha) {
266            return Err(ValidationError::InvalidProbability { value: alpha });
267        }
268        for (k, &f) in self.cdf.iter().enumerate() {
269            if f >= alpha - 1e-15 {
270                return Ok(k as f64 * self.step);
271            }
272        }
273        Ok((self.pmf.len().saturating_sub(1)) as f64 * self.step)
274    }
275
276    /// Exact coherent Tail Value at Risk `TVaR_alpha(S)` on the discrete lattice
277    /// (`(1 / (1 - alpha)) * int_alpha^1 F^-(u) du`), normalized by `total_mass`.
278    pub fn tvar(&self, alpha: f64) -> Result<f64, ValidationError> {
279        if !alpha.is_finite() {
280            return Err(ValidationError::NotFinite);
281        }
282        if !(0.0..=1.0).contains(&alpha) {
283            return Err(ValidationError::InvalidProbability { value: alpha });
284        }
285        if alpha <= 0.0 {
286            if !(self.total_mass > 0.0) {
287                return Err(ValidationError::InvalidParameter(
288                    "aggregate loss distribution has zero captured probability mass",
289                ));
290            }
291            return Ok(self.mean / self.total_mass);
292        }
293        if alpha >= 1.0 {
294            return Ok((self.pmf.len().saturating_sub(1)) as f64 * self.step);
295        }
296        let mut prev_cdf = 0.0_f64;
297        let mut integral = 0.0_f64;
298        for (k, &pk) in self.pmf.iter().enumerate() {
299            let next_cdf = (prev_cdf + pk).min(1.0);
300            let lo = prev_cdf.max(alpha);
301            let hi = next_cdf;
302            if hi > lo {
303                integral += (hi - lo) * (k as f64 * self.step);
304            }
305            prev_cdf = next_cdf;
306        }
307        let captured_tail = prev_cdf - alpha;
308        if !(captured_tail > 1e-15) {
309            return Err(ValidationError::InvalidParameter(
310                "truncated aggregate grid has insufficient probability mass above alpha for TVaR",
311            ));
312        }
313        Ok(integral / captured_tail)
314    }
315
316    /// Exact net stop-loss premium `E[(S - retention)_+] = sum_k max(0, k*h - retention) * g_k`.
317    pub fn stop_loss_premium(&self, retention: f64) -> Result<f64, ValidationError> {
318        if !retention.is_finite() {
319            return Err(ValidationError::NotFinite);
320        }
321        if retention < 0.0 {
322            return Err(ValidationError::Negative);
323        }
324        let mut premium = 0.0;
325        for (k, &pk) in self.pmf.iter().enumerate() {
326            let x = k as f64 * self.step;
327            if x > retention {
328                premium += (x - retention) * pk;
329            }
330        }
331        Ok(premium)
332    }
333}
334
335/// Evaluate a compound aggregate loss distribution using Panjer's (1981) exact
336/// `(a, b, 0)` recursion up to `n_steps` grid points (`0, step, ..., (n_steps - 1) * step`).
337///
338/// Uses a zero-allocation contiguous inner loop over `g[..n_steps]` suitable
339/// for compiler SIMD auto-vectorization.
340pub fn panjer_recursion(
341    frequency: FrequencyDistribution,
342    severity_pmf: &[f64],
343    step: f64,
344    n_steps: usize,
345) -> Result<AggregateLossDistribution, ValidationError> {
346    validate_compound_inputs(frequency, severity_pmf, step, n_steps)?;
347    let (a, b) = frequency.panjer_ab();
348    let f0 = severity_pmf[0];
349    let denom = 1.0 - a * f0;
350    if !denom.is_finite() || denom <= 1e-15 {
351        return Err(ValidationError::InvalidParameter(
352            "Panjer recursion denominator 1 - a * f_0 is non-positive",
353        ));
354    }
355    let inv_denom = 1.0 / denom;
356
357    let g0 = frequency.pgf_real(f0);
358    if !g0.is_finite() || g0 < f64::MIN_POSITIVE {
359        return Err(ValidationError::InvalidParameter(
360            "Panjer recursion g_0 underflowed normal f64 range; use fft_aggregate_loss instead",
361        ));
362    }
363
364    let mut g = vec![0.0_f64; n_steps];
365    g[0] = g0;
366    let m_max = severity_pmf.len() - 1;
367    // Precompute f_y and y * f_y for y = 1..=m_max so the inner loop splits into
368    // two pure dot-products without per-element float casts or branchy index math.
369    let f_pos = &severity_pmf[1..=m_max];
370    let yf_pos: Vec<f64> = f_pos
371        .iter()
372        .enumerate()
373        .map(|(idx, &fy)| (idx + 1) as f64 * fy)
374        .collect();
375    let is_poisson = a == 0.0;
376
377    for x in 1..n_steps {
378        let upper = x.min(m_max);
379        let inv_x = 1.0 / x as f64;
380        let g_slice = &g[(x - upper)..x];
381        let acc = if is_poisson {
382            let mut acc_b = 0.0;
383            for (&yfy, &g_prev) in yf_pos[..upper].iter().zip(g_slice.iter().rev()) {
384                acc_b += yfy * g_prev;
385            }
386            (b * inv_x) * acc_b
387        } else {
388            let mut acc_a = 0.0;
389            let mut acc_b = 0.0;
390            for ((&fy, &yfy), &g_prev) in f_pos[..upper]
391                .iter()
392                .zip(yf_pos[..upper].iter())
393                .zip(g_slice.iter().rev())
394            {
395                acc_a += fy * g_prev;
396                acc_b += yfy * g_prev;
397            }
398            a * acc_a + (b * inv_x) * acc_b
399        };
400        let gx = acc * inv_denom;
401        if !gx.is_finite() || gx < -1e-6 {
402            return Err(ValidationError::InvalidParameter(
403                "Panjer recursion became numerically unstable (e.g. high-q Binomial); use fft_aggregate_loss",
404            ));
405        }
406        g[x] = gx.max(0.0);
407    }
408
409    Ok(summarize_aggregate(frequency, severity_pmf, step, g))
410}
411
412/// Evaluate a compound aggregate loss distribution using Robertson's (1992)
413/// radix-2 FFT characteristic-function inversion with exponential tilting.
414///
415/// * `fft_size` — power of two (`>= severity_pmf.len()` and `>= 2`).
416/// * `tilt` — exponential tilting parameter `theta >= 0.0` (`None` uses the
417///   automatic `f64`-balanced default `14.0 / fft_size as f64`, suppressing
418///   wrap-around aliasing by `exp(-14) ≈ 8.3e-7` while limiting right-edge
419///   amplification to ~`1e-10`).
420pub fn fft_aggregate_loss(
421    frequency: FrequencyDistribution,
422    severity_pmf: &[f64],
423    step: f64,
424    fft_size: usize,
425    tilt: Option<f64>,
426) -> Result<AggregateLossDistribution, ValidationError> {
427    validate_compound_inputs(frequency, severity_pmf, step, fft_size)?;
428    if fft_size < 2 || !fft_size.is_power_of_two() {
429        return Err(ValidationError::InvalidParameter(
430            "fft_size must be a power of two >= 2",
431        ));
432    }
433    if fft_size < severity_pmf.len() {
434        return Err(ValidationError::InvalidParameter(
435            "fft_size must be >= severity_pmf.len()",
436        ));
437    }
438    let theta = match tilt {
439        Some(t) => {
440            if !t.is_finite() || t < 0.0 || t * (fft_size - 1) as f64 > 700.0 {
441                return Err(ValidationError::InvalidParameter(
442                    "exponential tilt must be finite, >= 0, and satisfy tilt * (fft_size - 1) <= 700",
443                ));
444            }
445            t
446        }
447        None => 14.0 / fft_size as f64,
448    };
449
450    let mut re = vec![0.0; fft_size];
451    let mut im = vec![0.0; fft_size];
452    if theta > 0.0 {
453        let step_down = (-theta).exp();
454        let mut scale = 1.0;
455        for (k, &fk) in severity_pmf.iter().enumerate() {
456            if k.trailing_zeros() >= 6 {
457                scale = (-theta * k as f64).exp();
458            }
459            re[k] = fk * scale;
460            scale *= step_down;
461        }
462    } else {
463        re[..severity_pmf.len()].copy_from_slice(severity_pmf);
464    }
465
466    // Precompute exact N/2 twiddle table once and share across forward & inverse FFTs
467    // (cuts sin_cos calls by 4x while preserving exact twiddle precision).
468    let (tw_re, tw_im) = build_fft_twiddles(fft_size);
469
470    // Forward radix-2 FFT: severity characteristic function.
471    fft_radix2_in_place(&mut re, &mut im, &tw_re, &tw_im, false);
472
473    // Compound PGF evaluation in frequency domain: phi_S(u) = P_N(phi_X(u)).
474    for u in 0..fft_size {
475        let (gr, gi) = frequency.pgf_complex(re[u], im[u]);
476        re[u] = gr;
477        im[u] = gi;
478    }
479
480    // Inverse radix-2 FFT back to loss lattice.
481    fft_radix2_in_place(&mut re, &mut im, &tw_re, &tw_im, true);
482
483    // Untilt and suppress sub-noise-floor FFT roundoff dust that exponential
484    // untilting by exp(theta * k) would otherwise amplify into one-sided bias.
485    let noise_floor = if theta > 0.0 { 4.0 * f64::EPSILON } else { 0.0 };
486    let mut g = vec![0.0; fft_size];
487    if theta > 0.0 {
488        let step_up = theta.exp();
489        let mut scale = 1.0;
490        for k in 0..fft_size {
491            if k.trailing_zeros() >= 6 {
492                scale = (theta * k as f64).exp();
493            }
494            let rk = re[k];
495            if rk.is_finite() && rk > noise_floor {
496                let raw = rk * scale;
497                if raw.is_finite() && raw > 0.0 {
498                    g[k] = raw;
499                }
500            }
501            scale *= step_up;
502        }
503    } else {
504        for k in 0..fft_size {
505            let rk = re[k];
506            if rk.is_finite() && rk > 0.0 {
507                g[k] = rk;
508            }
509        }
510    }
511
512    Ok(summarize_aggregate(frequency, severity_pmf, step, g))
513}
514
515/// Discretize a continuous [`SeverityDistribution`] onto the lattice
516/// `0, step, 2*step, ..., max_index * step` using the **Method of Rounding**
517/// (Klugman, Panjer & Willmot, §9.6.1):
518///
519/// `f_0 = F(step / 2)`, `f_k = F((k + 0.5) * step) - F((k - 0.5) * step)`.
520///
521/// If `capture_upper_tail` is `true`, the remaining survival mass
522/// `S((max_index - 0.5) * step)` is placed on `f_{max_index}` so `sum(f) == 1`.
523pub fn discretize_rounding(
524    dist: &SeverityDistribution,
525    step: f64,
526    max_index: usize,
527    capture_upper_tail: bool,
528) -> Result<Vec<f64>, ValidationError> {
529    dist.validate()?;
530    if !step.is_finite() || step <= 0.0 || max_index == 0 {
531        return Err(ValidationError::InvalidParameter(
532            "discretization requires step > 0 and max_index >= 1",
533        ));
534    }
535    let mut pmf = vec![0.0; max_index + 1];
536    let mut prev_cdf = 0.0_f64;
537    for k in 0..=max_index {
538        let next_cdf = if k == max_index && capture_upper_tail {
539            1.0
540        } else {
541            let x_hi = (k as f64 + 0.5) * step;
542            1.0 - dist.survival(x_hi)
543        };
544        pmf[k] = (next_cdf - prev_cdf).max(0.0);
545        prev_cdf = next_cdf;
546    }
547    Ok(pmf)
548}
549
550/// Discretize a continuous [`SeverityDistribution`] onto the lattice
551/// `0, step, 2*step, ..., max_index * step` using **mean-preserving Limited
552/// Expected Value (LEV) local moment matching** (Klugman, Panjer & Willmot
553/// §9.6.2 / Wang 1998):
554///
555/// `f_0 = 1 - LEV(step) / step`,
556/// `f_k = (2 LEV(k * step) - LEV((k - 1) * step) - LEV((k + 1) * step)) / step`
557/// for `1 <= k < max_index`, and remaining mass at `max_index`.
558///
559/// Preserves `E[X ∧ (max_index * step)]` identically!
560pub fn discretize_mean_preserving(
561    dist: &SeverityDistribution,
562    step: f64,
563    max_index: usize,
564) -> Result<Vec<f64>, ValidationError> {
565    dist.validate()?;
566    if !step.is_finite() || step <= 0.0 || max_index < 2 {
567        return Err(ValidationError::InvalidParameter(
568            "mean-preserving discretization requires step > 0 and max_index >= 2",
569        ));
570    }
571    let mut levs = vec![0.0; max_index + 1];
572    for k in 1..=max_index {
573        levs[k] = dist.limited_expected_value(k as f64 * step)?;
574    }
575
576    let mut pmf = vec![0.0; max_index + 1];
577    pmf[0] = (1.0 - levs[1] / step).max(0.0);
578    for k in 1..max_index {
579        pmf[k] = ((2.0 * levs[k] - levs[k - 1] - levs[k + 1]) / step).max(0.0);
580    }
581    pmf[max_index] = ((levs[max_index] - levs[max_index - 1]) / step).max(0.0);
582    Ok(pmf)
583}
584
585fn validate_compound_inputs(
586    frequency: FrequencyDistribution,
587    severity_pmf: &[f64],
588    step: f64,
589    n_steps: usize,
590) -> Result<(), ValidationError> {
591    frequency.validate()?;
592    if severity_pmf.is_empty() || n_steps < 2 {
593        return Err(ValidationError::ShapeMismatch);
594    }
595    if !step.is_finite() || step <= 0.0 {
596        return Err(ValidationError::InvalidParameter(
597            "lattice step size must be finite and strictly positive",
598        ));
599    }
600    validate_nonnegative_finite_slice(severity_pmf)?;
601    let sum_f: f64 = severity_pmf.iter().sum();
602    if (sum_f - 1.0).abs() > 1e-6 {
603        return Err(ValidationError::InvalidParameter(
604            "severity PMF must sum to 1.0 within 1e-6",
605        ));
606    }
607    Ok(())
608}
609
610fn summarize_aggregate(
611    frequency: FrequencyDistribution,
612    severity_pmf: &[f64],
613    step: f64,
614    pmf: Vec<f64>,
615) -> AggregateLossDistribution {
616    // Exact moments of input discrete severity X (two-pass centered variance avoids cancellation).
617    let mut ex = 0.0;
618    for (k, &fk) in severity_pmf.iter().enumerate() {
619        ex += (k as f64 * step) * fk;
620    }
621    let mut var_x = 0.0;
622    for (k, &fk) in severity_pmf.iter().enumerate() {
623        let dx = k as f64 * step - ex;
624        var_x += dx * dx * fk;
625    }
626    let var_x = var_x.max(0.0);
627    let en = frequency.mean();
628    let var_n = frequency.variance();
629    let exact_theoretical_mean = en * ex;
630    let exact_theoretical_variance = en * var_x + var_n * ex * ex;
631
632    let mut cdf = Vec::with_capacity(pmf.len());
633    let mut running = 0.0;
634    let mut mean = 0.0;
635    for (k, &gk) in pmf.iter().enumerate() {
636        running += gk;
637        cdf.push(running);
638        mean += (k as f64 * step) * gk;
639    }
640    let mut variance = 0.0;
641    for (k, &gk) in pmf.iter().enumerate() {
642        let dx = k as f64 * step - mean;
643        variance += dx * dx * gk;
644    }
645    let variance = variance.max(0.0);
646
647    AggregateLossDistribution {
648        step,
649        pmf,
650        cdf,
651        total_mass: running,
652        mean,
653        variance,
654        std_dev: variance.sqrt(),
655        exact_theoretical_mean,
656        exact_theoretical_variance,
657    }
658}
659
660/// Build exact forward twiddle factors `exp(-i * 2*pi*k / n)` for `k = 0..n/2`.
661fn build_fft_twiddles(n: usize) -> (Vec<f64>, Vec<f64>) {
662    let half = n >> 1;
663    let mut tw_re = Vec::with_capacity(half);
664    let mut tw_im = Vec::with_capacity(half);
665    let angle_step = -TAU / n as f64;
666    for k in 0..half {
667        let (s, c) = (k as f64 * angle_step).sin_cos();
668        tw_re.push(c);
669        tw_im.push(s);
670    }
671    (tw_re, tw_im)
672}
673
674/// Pure-Rust iterative in-place radix-2 Cooley–Tukey FFT (`len` must be power of 2).
675fn fft_radix2_in_place(
676    re: &mut [f64],
677    im: &mut [f64],
678    tw_re: &[f64],
679    tw_im: &[f64],
680    inverse: bool,
681) {
682    let n = re.len();
683    debug_assert_eq!(n, im.len());
684    debug_assert!(n.is_power_of_two());
685
686    // Bit-reversal permutation.
687    let mut j = 0usize;
688    for i in 1..n {
689        let mut bit = n >> 1;
690        while j & bit != 0 {
691            j ^= bit;
692            bit >>= 1;
693        }
694        j ^= bit;
695        if i < j {
696            re.swap(i, j);
697            im.swap(i, j);
698        }
699    }
700
701    // Cooley–Tukey butterfly stages using precomputed exact twiddles (inverse conjugates wi).
702    let im_sign = if inverse { -1.0 } else { 1.0 };
703    let mut len = 2usize;
704    while len <= n {
705        let half = len >> 1;
706        let stride = n / len;
707
708        for k in 0..half {
709            let tw_idx = k * stride;
710            let wr = tw_re[tw_idx];
711            let wi = im_sign * tw_im[tw_idx];
712            let mut start = k;
713            while start < n {
714                let odd = start + half;
715                let tr = wr * re[odd] - wi * im[odd];
716                let ti = wr * im[odd] + wi * re[odd];
717                let er = re[start];
718                let ei = im[start];
719                re[start] = er + tr;
720                im[start] = ei + ti;
721                re[odd] = er - tr;
722                im[odd] = ei - ti;
723                start += len;
724            }
725        }
726        len <<= 1;
727    }
728
729    if inverse {
730        let inv_n = 1.0 / n as f64;
731        for i in 0..n {
732            re[i] *= inv_n;
733            im[i] *= inv_n;
734        }
735    }
736}
737
738#[cfg(test)]
739mod tests {
740    use super::*;
741
742    #[test]
743    fn panjer_and_tilted_fft_agree_to_high_precision_and_match_exact_moments() {
744        // Klugman, Panjer & Willmot style discrete severity on {0, 1, 2, 3}.
745        let sev = [0.0, 0.5, 0.3, 0.2];
746        let step = 100.0;
747        let n_grid = 256usize;
748
749        for freq in [
750            FrequencyDistribution::Poisson { lambda: 3.5 },
751            FrequencyDistribution::NegativeBinomial { r: 2.5, beta: 1.4 },
752            FrequencyDistribution::Binomial { m: 10, q: 0.35 },
753        ] {
754            let panjer = panjer_recursion(freq, &sev, step, n_grid).expect("panjer");
755            let fft = fft_aggregate_loss(freq, &sev, step, n_grid, None).expect("fft");
756
757            assert!((panjer.total_mass - 1.0).abs() < 1e-10);
758            assert!(
759                (panjer.mean - panjer.exact_theoretical_mean).abs() / panjer.exact_theoretical_mean
760                    < 1e-10
761            );
762            assert!(
763                (panjer.variance - panjer.exact_theoretical_variance).abs()
764                    / panjer.exact_theoretical_variance
765                    < 1e-9
766            );
767
768            // L_inf agreement between Panjer recursion and tilted FFT.
769            let max_diff = panjer
770                .pmf
771                .iter()
772                .zip(fft.pmf.iter())
773                .map(|(a, b)| (a - b).abs())
774                .fold(0.0_f64, f64::max);
775            assert!(max_diff < 1e-10, "freq={freq:?} max_diff={max_diff}");
776        }
777    }
778
779    #[test]
780    fn mean_preserving_discretization_matches_exact_lev() {
781        let dist = SeverityDistribution::Lognormal {
782            mu: 9.0,
783            sigma: 0.8,
784        };
785        let step = 1_000.0;
786        let max_idx = 200usize;
787        let pmf = discretize_mean_preserving(&dist, step, max_idx).unwrap();
788        let disc_mean: f64 = pmf
789            .iter()
790            .enumerate()
791            .map(|(k, &p)| k as f64 * step * p)
792            .sum();
793        let exact_lev = dist.limited_expected_value(max_idx as f64 * step).unwrap();
794        assert!((disc_mean - exact_lev).abs() / exact_lev < 1e-12);
795    }
796}