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