reserving-kernels 0.4.0

Pure Rust numeric kernels for P&C actuarial reserving and reserve-risk capital modeling.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! C-ABI exports for the browser WASM demo.
//!
//! Built only with `--features wasm`. All exports take/return `f64` (or
//! `u32` for counts/sizes) so JavaScript can call them directly through
//! `WebAssembly.Instance.exports` with no bindgen glue.
//!
//! # Safety
//!
//! These exports exchange data through process-global `static mut` scratch
//! buffers and are **strictly for single-threaded `wasm32` hosts**. Do not
//! invoke them concurrently from multiple threads on native targets.
//!
//! Data is exchanged through static buffers:
//!
//! * `rk_tri_ptr`  — cumulative triangle, row-major, `N_MAX × N_MAX`
//!   (write `NaN` for unobserved cells).
//! * `rk_prem_ptr` — per-origin premium vector, length `N_MAX`.
//! * `rk_ldf_ptr`  — output LDFs, length `N_MAX − 1` meaningful.
//! * `rk_cdf_ptr`  — output CDFs (cumulative dev factors), length `N_MAX`.
//! * `rk_ult_ptr`  — output ultimates, length `N_MAX`.
//! * `rk_res_ptr`  — output reserves, length `N_MAX`.
//! * `rk_exp_ptr`  — BF input: expected ultimate per origin, length `N_MAX`.
//! * `rk_se_ptr`   — Mack output: standard error per origin, length `N_MAX`.
//! * `rk_sig_ptr`  — Mack output: σ² per development link, length `N_MAX`.
//! * `rk_int_ptr`  — Brosius output: intercept per link.
//! * `rk_slp_ptr`  — Brosius output: slope per link.

#![allow(unsafe_code)]
#![allow(missing_docs)]

use crate::types::TriangleView;
use crate::{
    deterministic::bf, deterministic::brosius, deterministic::cape_cod,
    deterministic::chain_ladder, deterministic::ldf, stochastic::mack,
};

const N_MAX: usize = 20;
const TRI_CAP: usize = N_MAX * N_MAX;

static mut TRI: [f64; TRI_CAP] = [0.0; TRI_CAP];
static mut PREM: [f64; N_MAX] = [0.0; N_MAX];
static mut LDF: [f64; N_MAX] = [0.0; N_MAX];
static mut CDF: [f64; N_MAX] = [0.0; N_MAX];
static mut ULT: [f64; N_MAX] = [0.0; N_MAX];
static mut RES: [f64; N_MAX] = [0.0; N_MAX];
static mut EXP: [f64; N_MAX] = [0.0; N_MAX];
static mut SE: [f64; N_MAX] = [0.0; N_MAX];
static mut SIG: [f64; N_MAX] = [0.0; N_MAX];
static mut INT: [f64; N_MAX] = [0.0; N_MAX];
static mut SLP: [f64; N_MAX] = [0.0; N_MAX];
static mut MACK_TOTAL_RESERVE: f64 = 0.0;

fn clamp_n(n: u32) -> usize {
    (n as usize).min(N_MAX)
}

unsafe fn read_buf(ptr: *const f64, len: usize) -> Vec<f64> {
    let mut out = Vec::with_capacity(len);
    for i in 0..len {
        // SAFETY: Caller guarantees `ptr` points to at least `len` initialized `f64` elements
        // in a static WASM exchange buffer with exclusive single-threaded access.
        out.push(unsafe { *ptr.add(i) });
    }
    out
}

unsafe fn write_buf(dst: *mut f64, src: &[f64]) {
    let take = src.len().min(N_MAX);
    for i in 0..take {
        // SAFETY: Caller guarantees `dst` points to a static `N_MAX`-element `f64` buffer
        // with exclusive single-threaded access, and `i < take <= N_MAX`.
        unsafe { *dst.add(i) = src[i] };
    }
    for i in take..N_MAX {
        // SAFETY: Same preconditions as above; `i < N_MAX` stays within the static buffer.
        unsafe { *dst.add(i) = f64::NAN };
    }
}

fn valid_tail(tail: f64) -> bool {
    tail.is_finite() && tail >= 1.0
}

fn tri_packed(n: usize) -> Vec<f64> {
    // The TRI buffer is laid out N_MAX × N_MAX row-major so JS can write
    // any cell at a stable stride. Pack into a fresh n × n Vec per call —
    // simple, allocation is cheap and eliminates aliasing concerns.
    let mut out = vec![0.0; n * n];
    // SAFETY: WASM execution is single-threaded with no concurrent mutable alias to `TRI`;
    // callers pass `n <= N_MAX` (via `clamp_n`), so `i * N_MAX + j < TRI_CAP`.
    unsafe {
        for i in 0..n {
            for j in 0..n {
                out[i * n + j] = TRI[i * N_MAX + j];
            }
        }
    }
    out
}

fn view_of(data: &[f64], n: usize) -> TriangleView<'_> {
    TriangleView {
        n_origins: n,
        n_devs: n,
        data,
    }
}

// ---- Buffer accessors ------------------------------------------------------

#[unsafe(no_mangle)]
pub extern "C" fn rk_n_max() -> u32 {
    N_MAX as u32
}

#[unsafe(no_mangle)]
pub extern "C" fn rk_tri_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(TRI).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_tri_stride() -> u32 {
    N_MAX as u32
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_prem_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(PREM).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_ldf_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(LDF).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_cdf_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(CDF).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_ult_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(ULT).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_res_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(RES).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_exp_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(EXP).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_se_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(SE).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_sig_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(SIG).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_int_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(INT).cast()
}
#[unsafe(no_mangle)]
pub extern "C" fn rk_slp_ptr() -> *mut f64 {
    core::ptr::addr_of_mut!(SLP).cast()
}

// ---- Helpers to write into static output buffers --------------------------

unsafe fn write_ldf(src: &[f64]) {
    // SAFETY: Single-threaded WASM C-ABI boundary with exclusive access to static `LDF`;
    // all indices are strictly bounded by `N_MAX`.
    unsafe {
        for (i, v) in src.iter().enumerate().take(N_MAX) {
            LDF[i] = *v;
        }
        for i in src.len()..N_MAX {
            LDF[i] = f64::NAN;
        }
    }
}
unsafe fn write_cdf(src: &[f64]) {
    // SAFETY: Single-threaded WASM C-ABI boundary with exclusive access to static `CDF`;
    // all indices are strictly bounded by `N_MAX`.
    unsafe {
        for (i, v) in src.iter().enumerate().take(N_MAX) {
            CDF[i] = *v;
        }
        for i in src.len()..N_MAX {
            CDF[i] = f64::NAN;
        }
    }
}
unsafe fn write_ult(src: &[f64]) {
    // SAFETY: Single-threaded WASM C-ABI boundary with exclusive access to static `ULT`;
    // all indices are strictly bounded by `N_MAX`.
    unsafe {
        for (i, v) in src.iter().enumerate().take(N_MAX) {
            ULT[i] = *v;
        }
        for i in src.len()..N_MAX {
            ULT[i] = f64::NAN;
        }
    }
}
unsafe fn write_res(src: &[f64]) {
    // SAFETY: Single-threaded WASM C-ABI boundary with exclusive access to static `RES`;
    // all indices are strictly bounded by `N_MAX`.
    unsafe {
        for (i, v) in src.iter().enumerate().take(N_MAX) {
            RES[i] = *v;
        }
        for i in src.len()..N_MAX {
            RES[i] = f64::NAN;
        }
    }
}

// ---- LDF selection methods ------------------------------------------------

#[unsafe(no_mangle)]
pub extern "C" fn rk_ldf_volume_weighted(n: u32) -> u32 {
    let n = clamp_n(n);
    let packed = tri_packed(n);
    let v = ldf::volume_weighted(&view_of(&packed, n));
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `LDF`.
    unsafe { write_ldf(&v) }
    v.len() as u32
}

#[unsafe(no_mangle)]
pub extern "C" fn rk_ldf_simple_average(n: u32) -> u32 {
    let n = clamp_n(n);
    let packed = tri_packed(n);
    let v = ldf::simple_average(&view_of(&packed, n));
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `LDF`.
    unsafe { write_ldf(&v) }
    v.len() as u32
}

#[unsafe(no_mangle)]
pub extern "C" fn rk_ldf_ex_hi_lo(n: u32) -> u32 {
    let n = clamp_n(n);
    let packed = tri_packed(n);
    let v = ldf::ex_hi_lo(&view_of(&packed, n));
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `LDF`.
    unsafe { write_ldf(&v) }
    v.len() as u32
}

#[unsafe(no_mangle)]
pub extern "C" fn rk_ldf_volume_weighted_last_n(n: u32, last_n: u32) -> u32 {
    let n = clamp_n(n);
    let packed = tri_packed(n);
    let v = ldf::volume_weighted_last_n(&view_of(&packed, n), last_n as usize);
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `LDF`.
    unsafe { write_ldf(&v) }
    v.len() as u32
}

#[unsafe(no_mangle)]
pub extern "C" fn rk_ldf_simple_average_last_n(n: u32, last_n: u32) -> u32 {
    let n = clamp_n(n);
    let packed = tri_packed(n);
    let v = ldf::simple_average_last_n(&view_of(&packed, n), last_n as usize);
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `LDF`.
    unsafe { write_ldf(&v) }
    v.len() as u32
}

/// Compute CDFs from the currently-loaded LDF buffer. Writes into the CDF
/// buffer. Returns the count written (`n`).
#[unsafe(no_mangle)]
pub extern "C" fn rk_cdf_compute(n: u32, tail: f64) -> u32 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return 0;
    }
    if n < 2 {
        // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `CDF`.
        unsafe { write_cdf(&[tail]) };
        return 1;
    }
    // SAFETY: `LDF` has length `N_MAX` and `n - 1 < N_MAX`; single-threaded WASM read.
    let ldf_slice = unsafe { read_buf(core::ptr::addr_of!(LDF).cast(), n - 1) };
    let cdf = ldf::cdf_from_ldf(&ldf_slice, tail);
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffer `CDF`.
    unsafe { write_cdf(&cdf) }
    cdf.len() as u32
}

// ---- Chain-ladder projection (reads LDF buffer) ---------------------------

#[unsafe(no_mangle)]
pub extern "C" fn rk_chain_ladder(n: u32, tail: f64) -> u32 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return 0;
    }
    let ldf_slice: Vec<f64> = if n >= 2 {
        // SAFETY: `LDF` has length `N_MAX` and `n - 1 < N_MAX`; single-threaded WASM read.
        unsafe { read_buf(core::ptr::addr_of!(LDF).cast(), n - 1) }
    } else {
        Vec::new()
    };
    let packed = tri_packed(n);
    let cl = chain_ladder::project_unchecked(&view_of(&packed, n), &ldf_slice, tail);
    let cdf = ldf::cdf_from_ldf(&ldf_slice, tail);
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffers.
    unsafe {
        write_ult(&cl.ultimates);
        write_res(&cl.reserves);
        write_cdf(&cdf);
    }
    n as u32
}

// ---- Bornhuetter–Ferguson (reads LDF + EXP buffers) -----------------------

#[unsafe(no_mangle)]
pub extern "C" fn rk_bf(n: u32, tail: f64) -> u32 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return 0;
    }
    let ldf_slice: Vec<f64> = if n >= 2 {
        // SAFETY: `LDF` has length `N_MAX` and `n - 1 < N_MAX`; single-threaded WASM read.
        unsafe { read_buf(core::ptr::addr_of!(LDF).cast(), n - 1) }
    } else {
        Vec::new()
    };
    // SAFETY: `EXP` has length `N_MAX` and `n <= N_MAX`; single-threaded WASM read.
    let exp_slice = unsafe { read_buf(core::ptr::addr_of!(EXP).cast(), n) };
    let packed = tri_packed(n);
    let r = bf::project_unchecked(&view_of(&packed, n), &ldf_slice, tail, &exp_slice);
    let cdf = ldf::cdf_from_ldf(&ldf_slice, tail);
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffers.
    unsafe {
        write_ult(&r.ultimates);
        write_res(&r.reserves);
        write_cdf(&cdf);
    }
    n as u32
}

/// Fill the EXP buffer from `premium × elr`.
#[unsafe(no_mangle)]
pub extern "C" fn rk_bf_expected_from_premium(n: u32, elr: f64) -> u32 {
    let n = clamp_n(n);
    // SAFETY: `PREM` has length `N_MAX` and `n <= N_MAX`; single-threaded WASM read.
    let prem = unsafe { read_buf(core::ptr::addr_of!(PREM).cast(), n) };
    let exp: Vec<f64> = prem.into_iter().map(|p| p * elr).collect();
    // SAFETY: `EXP` is a static `N_MAX`-element buffer with exclusive single-threaded access.
    unsafe { write_buf(core::ptr::addr_of_mut!(EXP).cast(), &exp) };
    n as u32
}

// ---- Cape Cod (reads LDF + PREM buffers) ----------------------------------

#[unsafe(no_mangle)]
pub extern "C" fn rk_cape_cod_elr(n: u32, tail: f64) -> f64 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return f64::NAN;
    }
    let ldf_slice: Vec<f64> = if n >= 2 {
        // SAFETY: `LDF` has length `N_MAX` and `n - 1 < N_MAX`; single-threaded WASM read.
        unsafe { read_buf(core::ptr::addr_of!(LDF).cast(), n - 1) }
    } else {
        Vec::new()
    };
    // SAFETY: `PREM` has length `N_MAX` and `n <= N_MAX`; single-threaded WASM read.
    let prem_slice = unsafe { read_buf(core::ptr::addr_of!(PREM).cast(), n) };
    let packed = tri_packed(n);
    cape_cod::elr(&view_of(&packed, n), &ldf_slice, tail, &prem_slice)
}

#[unsafe(no_mangle)]
pub extern "C" fn rk_cape_cod(n: u32, tail: f64) -> f64 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return f64::NAN;
    }
    let ldf_slice: Vec<f64> = if n >= 2 {
        // SAFETY: `LDF` has length `N_MAX` and `n - 1 < N_MAX`; single-threaded WASM read.
        unsafe { read_buf(core::ptr::addr_of!(LDF).cast(), n - 1) }
    } else {
        Vec::new()
    };
    // SAFETY: `PREM` has length `N_MAX` and `n <= N_MAX`; single-threaded WASM read.
    let prem_slice = unsafe { read_buf(core::ptr::addr_of!(PREM).cast(), n) };
    let packed = tri_packed(n);
    let (elr, r) = cape_cod::project_unchecked(&view_of(&packed, n), &ldf_slice, tail, &prem_slice);
    let cdf = ldf::cdf_from_ldf(&ldf_slice, tail);
    // SAFETY: Single-threaded WASM export writing exclusively to static output buffers
    // (`ULT`, `RES`, `CDF`, and `N_MAX`-element `EXP`).
    unsafe {
        write_ult(&r.ultimates);
        write_res(&r.reserves);
        write_cdf(&cdf);
        write_buf(core::ptr::addr_of_mut!(EXP).cast(), &r.expected_ultimate);
    }
    elr
}

// ---- Brosius -------------------------------------------------------------

#[unsafe(no_mangle)]
pub extern "C" fn rk_brosius(n: u32, tail: f64) -> u32 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return 0;
    }
    let packed = tri_packed(n);
    let r = brosius::project_unchecked(&view_of(&packed, n), tail);
    // SAFETY: Single-threaded WASM export writing exclusively to static `N_MAX`-element
    // output buffers (`INT`, `SLP`, `ULT`, `RES`).
    unsafe {
        write_buf(core::ptr::addr_of_mut!(INT).cast(), &r.intercept);
        write_buf(core::ptr::addr_of_mut!(SLP).cast(), &r.slope);
        write_ult(&r.ultimate);
        write_res(&r.reserve);
    }
    n as u32
}

// ---- Mack ----------------------------------------------------------------

/// Runs the Mack analysis. Writes LDF, CDF, ULT, RES, SE, SIG buffers.
/// Returns the total standard error across the portfolio reserve.
#[unsafe(no_mangle)]
pub extern "C" fn rk_mack(n: u32, tail: f64) -> f64 {
    let n = clamp_n(n);
    if n == 0 || !valid_tail(tail) {
        return f64::NAN;
    }
    let packed = tri_packed(n);
    let r = mack::analyze_unchecked(&view_of(&packed, n), tail);
    // SAFETY: Single-threaded WASM export writing exclusively to static `N_MAX`-element
    // output buffers and scalar `MACK_TOTAL_RESERVE`.
    unsafe {
        write_ldf(&r.ldf);
        write_ult(&r.ultimate);
        write_res(&r.reserve);
        write_buf(core::ptr::addr_of_mut!(SE).cast(), &r.standard_error);
        write_buf(core::ptr::addr_of_mut!(SIG).cast(), &r.sigma_sq);
        let cdf = ldf::cdf_from_ldf(&r.ldf, tail);
        write_cdf(&cdf);
        MACK_TOTAL_RESERVE = r.total_reserve;
    }
    r.total_standard_error
}

/// Returns the total reserve after the last Mack call.
#[unsafe(no_mangle)]
pub extern "C" fn rk_mack_total_reserve(_n: u32) -> f64 {
    // SAFETY: Single-threaded WASM export reading initialized static scalar `MACK_TOTAL_RESERVE`.
    unsafe { *core::ptr::addr_of!(MACK_TOTAL_RESERVE) }
}