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)]
237pub struct AggregateLossDistribution {
238    /// Grid step size `h > 0`.
239    pub step: f64,
240    /// Discrete aggregate PMF `g_k = P(S = k * step)` (length `n_steps`).
241    pub pmf: Vec<f64>,
242    /// Cumulative distribution function `G_k = P(S <= k * step)` (length `n_steps`).
243    pub cdf: Vec<f64>,
244    /// Total captured probability mass `sum_k g_k` (`<= 1.0`; `< 1.0` reflects right truncation).
245    pub total_mass: f64,
246    /// Numerical mean `sum_k (k * step) * g_k`.
247    pub mean: f64,
248    /// Numerical variance `sum_k (k * step - mean)^2 * g_k`.
249    pub variance: f64,
250    /// Numerical standard deviation `sqrt(variance)`.
251    pub std_dev: f64,
252    /// Exact compound theoretical mean `E[N] * E[X]` from the input severity PMF.
253    pub exact_theoretical_mean: f64,
254    /// Exact compound theoretical variance `E[N] * Var(X) + Var(N) * E[X]^2`.
255    pub exact_theoretical_variance: f64,
256}
257
258impl AggregateLossDistribution {
259    /// Discrete Value at Risk `VaR_alpha(S) = inf { x : F_S(x) >= alpha }`.
260    pub fn var(&self, alpha: f64) -> Result<f64, ValidationError> {
261        if !alpha.is_finite() {
262            return Err(ValidationError::NotFinite);
263        }
264        if !(0.0..=1.0).contains(&alpha) {
265            return Err(ValidationError::InvalidMaturity {
266                index: 0,
267                value: alpha,
268            });
269        }
270        for (k, &f) in self.cdf.iter().enumerate() {
271            if f >= alpha - 1e-15 {
272                return Ok(k as f64 * self.step);
273            }
274        }
275        Ok((self.pmf.len().saturating_sub(1)) as f64 * self.step)
276    }
277
278    /// Exact coherent Tail Value at Risk `TVaR_alpha(S)` on the discrete lattice
279    /// (`(1 / (1 - alpha)) * int_alpha^1 F^-(u) du`), normalized by `total_mass`.
280    pub fn tvar(&self, alpha: f64) -> Result<f64, ValidationError> {
281        if !alpha.is_finite() {
282            return Err(ValidationError::NotFinite);
283        }
284        if !(0.0..=1.0).contains(&alpha) {
285            return Err(ValidationError::InvalidMaturity {
286                index: 0,
287                value: alpha,
288            });
289        }
290        if alpha <= 0.0 {
291            if !(self.total_mass > 0.0) {
292                return Err(ValidationError::InvalidParameter(
293                    "aggregate loss distribution has zero captured probability mass",
294                ));
295            }
296            return Ok(self.mean / self.total_mass);
297        }
298        if alpha >= 1.0 {
299            return Ok((self.pmf.len().saturating_sub(1)) as f64 * self.step);
300        }
301        let mut prev_cdf = 0.0_f64;
302        let mut integral = 0.0_f64;
303        for (k, &pk) in self.pmf.iter().enumerate() {
304            let next_cdf = (prev_cdf + pk).min(1.0);
305            let lo = prev_cdf.max(alpha);
306            let hi = next_cdf;
307            if hi > lo {
308                integral += (hi - lo) * (k as f64 * self.step);
309            }
310            prev_cdf = next_cdf;
311        }
312        let captured_tail = prev_cdf - alpha;
313        if !(captured_tail > 1e-15) {
314            return Err(ValidationError::InvalidParameter(
315                "truncated aggregate grid has insufficient probability mass above alpha for TVaR",
316            ));
317        }
318        Ok(integral / captured_tail)
319    }
320
321    /// Exact net stop-loss premium `E[(S - retention)_+] = sum_k max(0, k*h - retention) * g_k`.
322    pub fn stop_loss_premium(&self, retention: f64) -> Result<f64, ValidationError> {
323        if !retention.is_finite() {
324            return Err(ValidationError::NotFinite);
325        }
326        if retention < 0.0 {
327            return Err(ValidationError::Negative);
328        }
329        let mut premium = 0.0;
330        for (k, &pk) in self.pmf.iter().enumerate() {
331            let x = k as f64 * self.step;
332            if x > retention {
333                premium += (x - retention) * pk;
334            }
335        }
336        Ok(premium)
337    }
338}
339
340/// Evaluate a compound aggregate loss distribution using Panjer's (1981) exact
341/// `(a, b, 0)` recursion up to `n_steps` grid points (`0, step, ..., (n_steps - 1) * step`).
342///
343/// Uses a zero-allocation contiguous inner loop over `g[..n_steps]` suitable
344/// for compiler SIMD auto-vectorization.
345pub fn panjer_recursion(
346    frequency: FrequencyDistribution,
347    severity_pmf: &[f64],
348    step: f64,
349    n_steps: usize,
350) -> Result<AggregateLossDistribution, ValidationError> {
351    validate_compound_inputs(frequency, severity_pmf, step, n_steps)?;
352    let (a, b) = frequency.panjer_ab();
353    let f0 = severity_pmf[0];
354    let denom = 1.0 - a * f0;
355    if !denom.is_finite() || denom <= 1e-15 {
356        return Err(ValidationError::InvalidParameter(
357            "Panjer recursion denominator 1 - a * f_0 is non-positive",
358        ));
359    }
360    let inv_denom = 1.0 / denom;
361
362    let g0 = frequency.pgf_real(f0);
363    if !g0.is_finite() || g0 < f64::MIN_POSITIVE {
364        return Err(ValidationError::InvalidParameter(
365            "Panjer recursion g_0 underflowed normal f64 range; use fft_aggregate_loss instead",
366        ));
367    }
368
369    let mut g = vec![0.0_f64; n_steps];
370    g[0] = g0;
371    let m_max = severity_pmf.len() - 1;
372    // Precompute f_y and y * f_y for y = 1..=m_max so the inner loop splits into
373    // two pure dot-products without per-element float casts or branchy index math.
374    let f_pos = &severity_pmf[1..=m_max];
375    let yf_pos: Vec<f64> = f_pos
376        .iter()
377        .enumerate()
378        .map(|(idx, &fy)| (idx + 1) as f64 * fy)
379        .collect();
380    let is_poisson = a == 0.0;
381
382    for x in 1..n_steps {
383        let upper = x.min(m_max);
384        let inv_x = 1.0 / x as f64;
385        let g_slice = &g[(x - upper)..x];
386        let acc = if is_poisson {
387            let mut acc_b = 0.0;
388            for (&yfy, &g_prev) in yf_pos[..upper].iter().zip(g_slice.iter().rev()) {
389                acc_b += yfy * g_prev;
390            }
391            (b * inv_x) * acc_b
392        } else {
393            let mut acc_a = 0.0;
394            let mut acc_b = 0.0;
395            for ((&fy, &yfy), &g_prev) in f_pos[..upper]
396                .iter()
397                .zip(yf_pos[..upper].iter())
398                .zip(g_slice.iter().rev())
399            {
400                acc_a += fy * g_prev;
401                acc_b += yfy * g_prev;
402            }
403            a * acc_a + (b * inv_x) * acc_b
404        };
405        let gx = acc * inv_denom;
406        if !gx.is_finite() || gx < -1e-6 {
407            return Err(ValidationError::InvalidParameter(
408                "Panjer recursion became numerically unstable (e.g. high-q Binomial); use fft_aggregate_loss",
409            ));
410        }
411        g[x] = gx.max(0.0);
412    }
413
414    Ok(summarize_aggregate(frequency, severity_pmf, step, g))
415}
416
417/// Evaluate a compound aggregate loss distribution using Robertson's (1992)
418/// radix-2 FFT characteristic-function inversion with exponential tilting.
419///
420/// * `fft_size` — power of two (`>= severity_pmf.len()` and `>= 2`).
421/// * `tilt` — exponential tilting parameter `theta >= 0.0` (`None` uses the
422///   automatic `f64`-balanced default `14.0 / fft_size as f64`, suppressing
423///   wrap-around aliasing by `exp(-14) ≈ 8.3e-7` while limiting right-edge
424///   amplification to ~`1e-10`).
425pub fn fft_aggregate_loss(
426    frequency: FrequencyDistribution,
427    severity_pmf: &[f64],
428    step: f64,
429    fft_size: usize,
430    tilt: Option<f64>,
431) -> Result<AggregateLossDistribution, ValidationError> {
432    validate_compound_inputs(frequency, severity_pmf, step, fft_size)?;
433    if fft_size < 2 || !fft_size.is_power_of_two() {
434        return Err(ValidationError::InvalidParameter(
435            "fft_size must be a power of two >= 2",
436        ));
437    }
438    if fft_size < severity_pmf.len() {
439        return Err(ValidationError::InvalidParameter(
440            "fft_size must be >= severity_pmf.len()",
441        ));
442    }
443    let theta = match tilt {
444        Some(t) => {
445            if !t.is_finite() || t < 0.0 || t * (fft_size - 1) as f64 > 700.0 {
446                return Err(ValidationError::InvalidParameter(
447                    "exponential tilt must be finite, >= 0, and satisfy tilt * (fft_size - 1) <= 700",
448                ));
449            }
450            t
451        }
452        None => 14.0 / fft_size as f64,
453    };
454
455    let mut re = vec![0.0; fft_size];
456    let mut im = vec![0.0; fft_size];
457    if theta > 0.0 {
458        let step_down = (-theta).exp();
459        let mut scale = 1.0;
460        for (k, &fk) in severity_pmf.iter().enumerate() {
461            if k.trailing_zeros() >= 6 {
462                scale = (-theta * k as f64).exp();
463            }
464            re[k] = fk * scale;
465            scale *= step_down;
466        }
467    } else {
468        re[..severity_pmf.len()].copy_from_slice(severity_pmf);
469    }
470
471    // Precompute exact N/2 twiddle table once and share across forward & inverse FFTs
472    // (cuts sin_cos calls by 4x while preserving exact twiddle precision).
473    let (tw_re, tw_im) = build_fft_twiddles(fft_size);
474
475    // Forward radix-2 FFT: severity characteristic function.
476    fft_radix2_in_place(&mut re, &mut im, &tw_re, &tw_im, false);
477
478    // Compound PGF evaluation in frequency domain: phi_S(u) = P_N(phi_X(u)).
479    for u in 0..fft_size {
480        let (gr, gi) = frequency.pgf_complex(re[u], im[u]);
481        re[u] = gr;
482        im[u] = gi;
483    }
484
485    // Inverse radix-2 FFT back to loss lattice.
486    fft_radix2_in_place(&mut re, &mut im, &tw_re, &tw_im, true);
487
488    // Untilt and suppress sub-noise-floor FFT roundoff dust that exponential
489    // untilting by exp(theta * k) would otherwise amplify into one-sided bias.
490    let noise_floor = if theta > 0.0 { 4.0 * f64::EPSILON } else { 0.0 };
491    let mut g = vec![0.0; fft_size];
492    if theta > 0.0 {
493        let step_up = theta.exp();
494        let mut scale = 1.0;
495        for k in 0..fft_size {
496            if k.trailing_zeros() >= 6 {
497                scale = (theta * k as f64).exp();
498            }
499            let rk = re[k];
500            if rk.is_finite() && rk > noise_floor {
501                let raw = rk * scale;
502                if raw.is_finite() && raw > 0.0 {
503                    g[k] = raw;
504                }
505            }
506            scale *= step_up;
507        }
508    } else {
509        for k in 0..fft_size {
510            let rk = re[k];
511            if rk.is_finite() && rk > 0.0 {
512                g[k] = rk;
513            }
514        }
515    }
516
517    Ok(summarize_aggregate(frequency, severity_pmf, step, g))
518}
519
520/// Discretize a continuous [`SeverityDistribution`] onto the lattice
521/// `0, step, 2*step, ..., max_index * step` using the **Method of Rounding**
522/// (Klugman, Panjer & Willmot, §9.6.1):
523///
524/// `f_0 = F(step / 2)`, `f_k = F((k + 0.5) * step) - F((k - 0.5) * step)`.
525///
526/// If `capture_upper_tail` is `true`, the remaining survival mass
527/// `S((max_index - 0.5) * step)` is placed on `f_{max_index}` so `sum(f) == 1`.
528pub fn discretize_rounding(
529    dist: &SeverityDistribution,
530    step: f64,
531    max_index: usize,
532    capture_upper_tail: bool,
533) -> Result<Vec<f64>, ValidationError> {
534    dist.validate()?;
535    if !step.is_finite() || step <= 0.0 || max_index == 0 {
536        return Err(ValidationError::InvalidParameter(
537            "discretization requires step > 0 and max_index >= 1",
538        ));
539    }
540    let mut pmf = vec![0.0; max_index + 1];
541    let mut prev_cdf = 0.0_f64;
542    for k in 0..=max_index {
543        let next_cdf = if k == max_index && capture_upper_tail {
544            1.0
545        } else {
546            let x_hi = (k as f64 + 0.5) * step;
547            1.0 - dist.survival(x_hi)
548        };
549        pmf[k] = (next_cdf - prev_cdf).max(0.0);
550        prev_cdf = next_cdf;
551    }
552    Ok(pmf)
553}
554
555/// Discretize a continuous [`SeverityDistribution`] onto the lattice
556/// `0, step, 2*step, ..., max_index * step` using **mean-preserving Limited
557/// Expected Value (LEV) local moment matching** (Klugman, Panjer & Willmot
558/// §9.6.2 / Wang 1998):
559///
560/// `f_0 = 1 - LEV(step) / step`,
561/// `f_k = (2 LEV(k * step) - LEV((k - 1) * step) - LEV((k + 1) * step)) / step`
562/// for `1 <= k < max_index`, and remaining mass at `max_index`.
563///
564/// Preserves `E[X ∧ (max_index * step)]` identically!
565pub fn discretize_mean_preserving(
566    dist: &SeverityDistribution,
567    step: f64,
568    max_index: usize,
569) -> Result<Vec<f64>, ValidationError> {
570    dist.validate()?;
571    if !step.is_finite() || step <= 0.0 || max_index < 2 {
572        return Err(ValidationError::InvalidParameter(
573            "mean-preserving discretization requires step > 0 and max_index >= 2",
574        ));
575    }
576    let mut levs = vec![0.0; max_index + 1];
577    for k in 1..=max_index {
578        levs[k] = dist.limited_expected_value(k as f64 * step)?;
579    }
580
581    let mut pmf = vec![0.0; max_index + 1];
582    pmf[0] = (1.0 - levs[1] / step).max(0.0);
583    for k in 1..max_index {
584        pmf[k] = ((2.0 * levs[k] - levs[k - 1] - levs[k + 1]) / step).max(0.0);
585    }
586    pmf[max_index] = ((levs[max_index] - levs[max_index - 1]) / step).max(0.0);
587    Ok(pmf)
588}
589
590fn validate_compound_inputs(
591    frequency: FrequencyDistribution,
592    severity_pmf: &[f64],
593    step: f64,
594    n_steps: usize,
595) -> Result<(), ValidationError> {
596    frequency.validate()?;
597    if severity_pmf.is_empty() || n_steps < 2 {
598        return Err(ValidationError::ShapeMismatch);
599    }
600    if !step.is_finite() || step <= 0.0 {
601        return Err(ValidationError::InvalidParameter(
602            "lattice step size must be finite and strictly positive",
603        ));
604    }
605    validate_nonnegative_finite_slice(severity_pmf)?;
606    let sum_f: f64 = severity_pmf.iter().sum();
607    if !(sum_f > 0.0) || sum_f > 1.0 + 1e-6 {
608        return Err(ValidationError::InvalidParameter(
609            "severity PMF must sum to <= 1.0 and be non-zero",
610        ));
611    }
612    Ok(())
613}
614
615fn summarize_aggregate(
616    frequency: FrequencyDistribution,
617    severity_pmf: &[f64],
618    step: f64,
619    pmf: Vec<f64>,
620) -> AggregateLossDistribution {
621    // Exact moments of input discrete severity X (two-pass centered variance avoids cancellation).
622    let mut ex = 0.0;
623    for (k, &fk) in severity_pmf.iter().enumerate() {
624        ex += (k as f64 * step) * fk;
625    }
626    let mut var_x = 0.0;
627    for (k, &fk) in severity_pmf.iter().enumerate() {
628        let dx = k as f64 * step - ex;
629        var_x += dx * dx * fk;
630    }
631    let var_x = var_x.max(0.0);
632    let en = frequency.mean();
633    let var_n = frequency.variance();
634    let exact_theoretical_mean = en * ex;
635    let exact_theoretical_variance = en * var_x + var_n * ex * ex;
636
637    let mut cdf = Vec::with_capacity(pmf.len());
638    let mut running = 0.0;
639    let mut mean = 0.0;
640    for (k, &gk) in pmf.iter().enumerate() {
641        running += gk;
642        cdf.push(running);
643        mean += (k as f64 * step) * gk;
644    }
645    let mut variance = 0.0;
646    for (k, &gk) in pmf.iter().enumerate() {
647        let dx = k as f64 * step - mean;
648        variance += dx * dx * gk;
649    }
650    let variance = variance.max(0.0);
651
652    AggregateLossDistribution {
653        step,
654        pmf,
655        cdf,
656        total_mass: running,
657        mean,
658        variance,
659        std_dev: variance.sqrt(),
660        exact_theoretical_mean,
661        exact_theoretical_variance,
662    }
663}
664
665/// Build exact forward twiddle factors `exp(-i * 2*pi*k / n)` for `k = 0..n/2`.
666fn build_fft_twiddles(n: usize) -> (Vec<f64>, Vec<f64>) {
667    let half = n >> 1;
668    let mut tw_re = Vec::with_capacity(half);
669    let mut tw_im = Vec::with_capacity(half);
670    let angle_step = -TAU / n as f64;
671    for k in 0..half {
672        let (s, c) = (k as f64 * angle_step).sin_cos();
673        tw_re.push(c);
674        tw_im.push(s);
675    }
676    (tw_re, tw_im)
677}
678
679/// Pure-Rust iterative in-place radix-2 Cooley–Tukey FFT (`len` must be power of 2).
680fn fft_radix2_in_place(
681    re: &mut [f64],
682    im: &mut [f64],
683    tw_re: &[f64],
684    tw_im: &[f64],
685    inverse: bool,
686) {
687    let n = re.len();
688    debug_assert_eq!(n, im.len());
689    debug_assert!(n.is_power_of_two());
690
691    // Bit-reversal permutation.
692    let mut j = 0usize;
693    for i in 1..n {
694        let mut bit = n >> 1;
695        while j & bit != 0 {
696            j ^= bit;
697            bit >>= 1;
698        }
699        j ^= bit;
700        if i < j {
701            re.swap(i, j);
702            im.swap(i, j);
703        }
704    }
705
706    // Cooley–Tukey butterfly stages using precomputed exact twiddles (inverse conjugates wi).
707    let im_sign = if inverse { -1.0 } else { 1.0 };
708    let mut len = 2usize;
709    while len <= n {
710        let half = len >> 1;
711        let stride = n / len;
712
713        for k in 0..half {
714            let tw_idx = k * stride;
715            let wr = tw_re[tw_idx];
716            let wi = im_sign * tw_im[tw_idx];
717            let mut start = k;
718            while start < n {
719                let odd = start + half;
720                let tr = wr * re[odd] - wi * im[odd];
721                let ti = wr * im[odd] + wi * re[odd];
722                let er = re[start];
723                let ei = im[start];
724                re[start] = er + tr;
725                im[start] = ei + ti;
726                re[odd] = er - tr;
727                im[odd] = ei - ti;
728                start += len;
729            }
730        }
731        len <<= 1;
732    }
733
734    if inverse {
735        let inv_n = 1.0 / n as f64;
736        for i in 0..n {
737            re[i] *= inv_n;
738            im[i] *= inv_n;
739        }
740    }
741}
742
743#[cfg(test)]
744mod tests {
745    use super::*;
746
747    #[test]
748    fn panjer_and_tilted_fft_agree_to_high_precision_and_match_exact_moments() {
749        // Klugman, Panjer & Willmot style discrete severity on {0, 1, 2, 3}.
750        let sev = [0.0, 0.5, 0.3, 0.2];
751        let step = 100.0;
752        let n_grid = 256usize;
753
754        for freq in [
755            FrequencyDistribution::Poisson { lambda: 3.5 },
756            FrequencyDistribution::NegativeBinomial { r: 2.5, beta: 1.4 },
757            FrequencyDistribution::Binomial { m: 10, q: 0.35 },
758        ] {
759            let panjer = panjer_recursion(freq, &sev, step, n_grid).expect("panjer");
760            let fft = fft_aggregate_loss(freq, &sev, step, n_grid, None).expect("fft");
761
762            assert!((panjer.total_mass - 1.0).abs() < 1e-10);
763            assert!(
764                (panjer.mean - panjer.exact_theoretical_mean).abs() / panjer.exact_theoretical_mean
765                    < 1e-10
766            );
767            assert!(
768                (panjer.variance - panjer.exact_theoretical_variance).abs()
769                    / panjer.exact_theoretical_variance
770                    < 1e-9
771            );
772
773            // L_inf agreement between Panjer recursion and tilted FFT.
774            let max_diff = panjer
775                .pmf
776                .iter()
777                .zip(fft.pmf.iter())
778                .map(|(a, b)| (a - b).abs())
779                .fold(0.0_f64, f64::max);
780            assert!(max_diff < 1e-10, "freq={freq:?} max_diff={max_diff}");
781        }
782    }
783
784    #[test]
785    fn mean_preserving_discretization_matches_exact_lev() {
786        let dist = SeverityDistribution::Lognormal {
787            mu: 9.0,
788            sigma: 0.8,
789        };
790        let step = 1_000.0;
791        let max_idx = 200usize;
792        let pmf = discretize_mean_preserving(&dist, step, max_idx).unwrap();
793        let disc_mean: f64 = pmf
794            .iter()
795            .enumerate()
796            .map(|(k, &p)| k as f64 * step * p)
797            .sum();
798        let exact_lev = dist.limited_expected_value(max_idx as f64 * step).unwrap();
799        assert!((disc_mean - exact_lev).abs() / exact_lev < 1e-12);
800    }
801}