Skip to main content

reserving_kernels/
excess_layers.rs

1//! Parameterized lognormal severity layering and Limited Expected Values (LEV).
2//!
3//! Provides exact closed-form lognormal limited expected value $E[X \wedge L]$
4//! and layer expectations via [`LognormalLayerModel`], alongside a
5//! deterministic SplitMix64 + antithetic Marsaglia polar Monte Carlo engine
6//! ([`LognormalLayerSampler`]) with sorted prefix-sum $O(\log N)$ layer queries.
7
8use crate::validate::ValidationError;
9
10const INV_SQRT_TAU: f64 = 0.398_942_280_401_432_7;
11
12/// Closed-form lognormal severity model parameterized by ground-up `mean > 0`
13/// and log-scale standard deviation `sigma > 0`.
14///
15/// The underlying lognormal parameters satisfy
16/// $\mu = \ln(\text{mean}) - \tfrac{1}{2}\sigma^2$ so `E[X] = mean`.
17#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
18pub struct LognormalLayerModel {
19    mean: f64,
20    sigma: f64,
21    inv_sigma: f64,
22    log_mean: f64,
23    pdf_scale: f64,
24}
25
26impl LognormalLayerModel {
27    /// Construct a validated lognormal layer model with ground-up `mean > 0`
28    /// and log-scale standard deviation `sigma > 0`.
29    pub fn try_new(mean: f64, sigma: f64) -> Result<Self, ValidationError> {
30        if !mean.is_finite() || !sigma.is_finite() {
31            return Err(ValidationError::NotFinite);
32        }
33        if mean <= 0.0 {
34            return Err(ValidationError::NonPositive("ground-up mean"));
35        }
36        if sigma <= 0.0 {
37            return Err(ValidationError::NonPositive("lognormal sigma"));
38        }
39        Ok(Self {
40            mean,
41            sigma,
42            inv_sigma: 1.0 / sigma,
43            log_mean: mean.ln() - 0.5 * sigma * sigma,
44            pdf_scale: INV_SQRT_TAU / sigma,
45        })
46    }
47
48    /// Ground-up expected severity `E[X]`.
49    #[inline]
50    pub fn mean(&self) -> f64 {
51        self.mean
52    }
53
54    /// Log-scale standard deviation $\sigma$.
55    #[inline]
56    pub fn sigma(&self) -> f64 {
57        self.sigma
58    }
59
60    /// Closed-form Limited Expected Value $E[X \wedge L]$.
61    ///
62    /// Returns `0.0` for `limit <= 0.0`, `mean` for `+∞`, and `NaN` for `NaN`.
63    #[inline]
64    pub fn exact_lev(&self, limit: f64) -> f64 {
65        if limit.is_nan() {
66            return f64::NAN;
67        }
68        if limit <= 0.0 {
69            return 0.0;
70        }
71        if !limit.is_finite() {
72            return self.mean;
73        }
74        let z = (limit.ln() - self.log_mean) * self.inv_sigma;
75        self.mean * crate::severity::normal_cdf_exact(z - self.sigma)
76            + limit * crate::severity::normal_cdf_exact(-z)
77    }
78
79    /// Closed-form expected loss in the layer `(attachment, top]`:
80    /// $E[\min(X, \text{top}) - \min(X, \text{attachment})]$.
81    ///
82    /// Returns `0.0` when `top <= attachment`.
83    #[inline]
84    pub fn exact_layer(&self, attachment: f64, top: f64) -> f64 {
85        if attachment.is_nan() || top.is_nan() {
86            return f64::NAN;
87        }
88        let att = attachment.max(0.0);
89        if top <= att {
90            return 0.0;
91        }
92        (self.exact_lev(top) - self.exact_lev(att)).max(0.0)
93    }
94
95    /// Exceedance probability $P(X > \text{threshold})$.
96    #[inline]
97    pub fn exceedance_prob(&self, threshold: f64) -> f64 {
98        if threshold.is_nan() {
99            return f64::NAN;
100        }
101        if threshold <= 0.0 {
102            return 1.0;
103        }
104        if !threshold.is_finite() {
105            return 0.0;
106        }
107        let z = (threshold.ln() - self.log_mean) * self.inv_sigma;
108        crate::severity::normal_cdf_exact(-z)
109    }
110
111    /// Lognormal probability density function $f_X(x)$ at loss amount `x`.
112    #[inline]
113    pub fn pdf(&self, x: f64) -> f64 {
114        if x <= 0.0 || !x.is_finite() {
115            return 0.0;
116        }
117        let z = (x.ln() - self.log_mean) * self.inv_sigma;
118        (self.pdf_scale / x) * (-0.5 * z * z).exp()
119    }
120}
121
122/// Deterministic antithetic Monte Carlo lognormal layer sampler with sorted
123/// prefix sums for $O(\log N)$ repeated layer evaluations.
124///
125/// No process-global caches are used; callers own the sampler lifetime.
126#[derive(Debug, Clone)]
127pub struct LognormalLayerSampler {
128    model: LognormalLayerModel,
129    inv_n: f64,
130    sorted_normals: Vec<f64>,
131    prefix_sums: Vec<f64>,
132}
133
134impl LognormalLayerSampler {
135    /// Generate `n_samples` (rounded up to an even count for exact antithetic
136    /// pairing) deterministic SplitMix64 + Marsaglia polar draws and build the
137    /// sorted prefix-sum table.
138    pub fn try_new(
139        model: LognormalLayerModel,
140        n_samples: usize,
141        seed: u64,
142    ) -> Result<Self, ValidationError> {
143        if n_samples < 2 {
144            return Err(ValidationError::InvalidParameter(
145                "LognormalLayerSampler requires at least 2 samples",
146            ));
147        }
148        let half = n_samples.div_ceil(2);
149        let total = half * 2;
150        let mut state = seed;
151        let mut pos = Vec::with_capacity(half);
152        while pos.len() < half {
153            let u = 2.0 * uniform(&mut state) - 1.0;
154            let v = 2.0 * uniform(&mut state) - 1.0;
155            let s = u * u + v * v;
156            if s > 0.0 && s < 1.0 {
157                let scale = (-2.0 * s.ln() / s).sqrt();
158                pos.push((u * scale).abs());
159                if pos.len() < half {
160                    pos.push((v * scale).abs());
161                }
162            }
163        }
164        pos.sort_unstable_by(f64::total_cmp);
165
166        let mut sorted_normals = Vec::with_capacity(total);
167        for &z in pos.iter().rev() {
168            sorted_normals.push(-z);
169        }
170        sorted_normals.extend_from_slice(&pos);
171
172        let mut prefix_sums = Vec::with_capacity(total + 1);
173        let mut acc = 0.0;
174        prefix_sums.push(0.0);
175        for &z in &sorted_normals {
176            acc += (model.log_mean + model.sigma * z).exp();
177            prefix_sums.push(acc);
178        }
179
180        Ok(Self {
181            model,
182            inv_n: 1.0 / (total as f64),
183            sorted_normals,
184            prefix_sums,
185        })
186    }
187
188    /// Underlying analytical [`LognormalLayerModel`].
189    #[inline]
190    pub fn model(&self) -> LognormalLayerModel {
191        self.model
192    }
193
194    /// Number of antithetic draws held by this sampler.
195    #[inline]
196    pub fn n_samples(&self) -> usize {
197        self.sorted_normals.len()
198    }
199
200    /// Simulated Limited Expected Value $E[X \wedge L]$ in $O(\log N)$.
201    #[inline]
202    pub fn simulated_lev(&self, limit: f64) -> f64 {
203        if limit.is_nan() {
204            return f64::NAN;
205        }
206        if limit <= 0.0 {
207            return 0.0;
208        }
209        let n = self.sorted_normals.len();
210        if !limit.is_finite() {
211            return self.prefix_sums[n] * self.inv_n;
212        }
213        let z_thresh = (limit.ln() - self.model.log_mean) * self.model.inv_sigma;
214        let k = self.sorted_normals.partition_point(|&z| z < z_thresh);
215        (self.prefix_sums[k] + ((n - k) as f64) * limit) * self.inv_n
216    }
217
218    /// Simulated expected loss in the layer `(attachment, top]` in $O(\log N)$.
219    #[inline]
220    pub fn simulated_layer(&self, attachment: f64, top: f64) -> f64 {
221        if attachment.is_nan() || top.is_nan() {
222            return f64::NAN;
223        }
224        let att = attachment.max(0.0);
225        if top <= att {
226            return 0.0;
227        }
228        (self.simulated_lev(top) - self.simulated_lev(att)).max(0.0)
229    }
230}
231
232fn uniform(state: &mut u64) -> f64 {
233    *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
234    let mut bits = *state;
235    bits = (bits ^ (bits >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
236    bits = (bits ^ (bits >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
237    bits ^= bits >> 31;
238    ((bits >> 12) as f64 + 0.5) / 4_503_599_627_370_496.0
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn first_layer_matches_reference_values() {
247        for (sigma, reference) in [(0.55, 78_331.62), (1.00, 61_707.51), (1.55, 43_833.97)] {
248            let model = LognormalLayerModel::try_new(100_000.0, sigma).expect("model");
249            assert!((model.exact_layer(0.0, 100_000.0) - reference).abs() < 0.03);
250        }
251    }
252
253    #[test]
254    fn layer_width_and_tail_change_relativities() {
255        let mut previous_ratio = 1.0;
256        for sigma in [0.55, 1.00, 1.55] {
257            let model = LognormalLayerModel::try_new(100_000.0, sigma).expect("model");
258            let lower = model.exact_layer(0.0, 100_000.0);
259            assert_eq!(model.exact_layer(100_000.0, 100_000.0), 0.0);
260            assert_eq!(model.exact_layer(100_000.0, 50_000.0), 0.0);
261            let mut previous_upper = 0.0;
262            for top in (150_000..=750_000).step_by(25_000) {
263                let upper = model.exact_layer(100_000.0, f64::from(top));
264                assert!(upper > previous_upper);
265                assert!(lower + upper <= model.mean());
266                previous_upper = upper;
267            }
268            let ratio = 1.0 + model.exact_layer(100_000.0, 350_000.0) / lower;
269            assert!(ratio > previous_ratio);
270            previous_ratio = ratio;
271        }
272    }
273
274    #[test]
275    fn fixed_seed_simulation_agrees_with_limited_expectations() {
276        for sigma in [0.55, 1.00, 1.55] {
277            let model = LognormalLayerModel::try_new(100_000.0, sigma).expect("model");
278            let sampler = LognormalLayerSampler::try_new(model, 65_536, 2026).expect("sampler");
279            for top in (150_000..=750_000).step_by(50_000) {
280                let exact = model.exact_layer(100_000.0, f64::from(top));
281                let simulated = sampler.simulated_layer(100_000.0, f64::from(top));
282                assert!(
283                    (exact - simulated).abs() < 1_000.0,
284                    "sigma {sigma}, top {top}: {exact} vs. {simulated}"
285                );
286            }
287        }
288    }
289
290    #[test]
291    fn exceedance_and_pdf_are_consistent() {
292        let model = LognormalLayerModel::try_new(100_000.0, 1.0).expect("model");
293        let p_att = model.exceedance_prob(100_000.0);
294        let p_top = model.exceedance_prob(350_000.0);
295        assert!(p_att > 0.0 && p_att < 1.0);
296        assert!(p_top > 0.0 && p_top < p_att);
297        assert_eq!(model.exceedance_prob(0.0), 1.0);
298        assert_eq!(model.pdf(0.0), 0.0);
299        assert!(model.pdf(50_000.0) > 0.0);
300        let dx = 1_000.0;
301        let area: f64 = (0..2_000)
302            .map(|i| model.pdf((f64::from(i) + 0.5) * dx) * dx)
303            .sum();
304        assert!(area > 0.95 && area <= 1.001, "area={area}");
305    }
306
307    #[test]
308    fn validates_model_and_sampler_inputs() {
309        assert_eq!(
310            LognormalLayerModel::try_new(0.0, 1.0),
311            Err(ValidationError::NonPositive("ground-up mean"))
312        );
313        assert_eq!(
314            LognormalLayerModel::try_new(100_000.0, -0.5),
315            Err(ValidationError::NonPositive("lognormal sigma"))
316        );
317        let model = LognormalLayerModel::try_new(100_000.0, 1.0).expect("model");
318        assert!(LognormalLayerSampler::try_new(model, 1, 42).is_err());
319    }
320}