Skip to main content

reserving_kernels/
validate.rs

1//! Input validation — kept deliberately off the compute hot path.
2//!
3//! Call these at the ingress boundary (CSV/DB/API → `Triangle`). Kernels in
4//! the rest of the crate assume validated inputs and skip defensive checks.
5
6use std::fmt;
7
8use crate::types::TriangleView;
9
10/// Policy controlling whether cumulative rows must be monotonically non-decreasing.
11///
12/// Strict monotonicity (`Strict`) is appropriate for pure gross paid triangles
13/// without salvage/subrogation recoveries. Incurred triangles and reinsurance
14/// triangles (including Mack's 1993 RAA benchmark) legitimately exhibit downward
15/// case-reserve revisions and require [`MonotonicityPolicy::AllowNegativeIncrements`].
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
17pub enum MonotonicityPolicy {
18    /// Reject any observed cumulative cell strictly lower than its predecessor.
19    #[default]
20    Strict,
21    /// Permit downward cumulative movements (case-reserve releases, recoveries)
22    /// while still enforcing finite non-negative cumulative balances.
23    AllowNegativeIncrements,
24}
25
26/// Validation failure modes for triangle inputs.
27#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
28#[non_exhaustive]
29pub enum ValidationError {
30    /// `data.len() != n_origins * n_devs`.
31    ShapeMismatch,
32    /// Triangle must be square (`n_origins == n_devs`) for the reserving
33    /// kernels as implemented here.
34    NotSquare,
35    /// An observed cell held a non-finite value other than `NaN`.
36    NotFinite,
37    /// An observed cell held a negative cumulative loss.
38    Negative,
39    /// A required denominator was zero (column sum or observed-cell value).
40    DivideByZero(&'static str),
41    /// An observed cumulative row decreased.
42    NonMonotoneCumulative {
43        /// Origin row index.
44        origin: usize,
45        /// Development index holding the lower value.
46        dev: usize,
47        /// Previous cumulative value.
48        previous: f64,
49        /// Current cumulative value.
50        value: f64,
51    },
52    /// Tail factor is below the supported cumulative-development minimum.
53    InvalidTail {
54        /// Supplied tail factor.
55        tail: f64,
56    },
57    /// Maturity percentage is outside `[0, 1]`.
58    InvalidMaturity {
59        /// Maturity vector index.
60        index: usize,
61        /// Supplied maturity value.
62        value: f64,
63    },
64    /// Probability or confidence level is outside `[0, 1]`.
65    InvalidProbability {
66        /// Supplied probability value.
67        value: f64,
68    },
69    /// Simulation or bootstrap iteration count is zero.
70    InvalidIterations,
71    /// A required strictly positive input was zero or negative.
72    NonPositive(&'static str),
73    /// Model or matrix specification is invalid or numerically singular.
74    InvalidParameter(&'static str),
75}
76
77impl fmt::Display for ValidationError {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Self::ShapeMismatch => write!(f, "input dimensions do not match expected shape"),
81            Self::NotSquare => write!(f, "triangle must be square (n_origins == n_devs)"),
82            Self::NotFinite => write!(f, "input contains NaN or infinite values"),
83            Self::Negative => write!(
84                f,
85                "input contains negative values where non-negative required"
86            ),
87            Self::DivideByZero(ctx) => write!(f, "division by zero in {ctx}"),
88            Self::NonMonotoneCumulative {
89                origin,
90                dev,
91                previous,
92                value,
93            } => write!(
94                f,
95                "non-monotone cumulative triangle at origin {origin}, dev {dev}: {value} < {previous}"
96            ),
97            Self::InvalidTail { tail } => write!(f, "invalid tail factor {tail} (must be >= 1.0)"),
98            Self::InvalidMaturity { index, value } => {
99                write!(f, "invalid maturity/probability {value} at index {index}")
100            }
101            Self::InvalidProbability { value } => {
102                write!(f, "invalid probability {value} (must be in [0, 1])")
103            }
104            Self::InvalidIterations => write!(f, "iteration count must be at least 1"),
105            Self::NonPositive(ctx) => write!(f, "{ctx} must be strictly positive"),
106            Self::InvalidParameter(msg) => write!(f, "invalid parameter: {msg}"),
107        }
108    }
109}
110
111impl std::error::Error for ValidationError {}
112
113/// Validate a triangle view: square shape, finite non-negative observed
114/// cells. Unobserved cells (`i + j > n − 1`) are ignored.
115pub fn validate_triangle(t: &TriangleView<'_>) -> Result<(), ValidationError> {
116    if t.data.len() != t.n_origins * t.n_devs {
117        return Err(ValidationError::ShapeMismatch);
118    }
119    if t.n_origins != t.n_devs {
120        return Err(ValidationError::NotSquare);
121    }
122    let n = t.n_origins;
123    for i in 0..n {
124        let row = &t.data[i * n..i * n + (n - i)];
125        for &v in row {
126            if !v.is_finite() {
127                // NaN is our "unobserved" sentinel — within the observed
128                // upper triangle, NaN or infinity is an error.
129                return Err(ValidationError::NotFinite);
130            }
131            if v < 0.0 {
132                return Err(ValidationError::Negative);
133            }
134        }
135    }
136    Ok(())
137}
138
139/// Validate a premium vector: length matches origins, finite positive.
140pub fn validate_premium(premium: &[f64], n_origins: usize) -> Result<(), ValidationError> {
141    if premium.len() != n_origins {
142        return Err(ValidationError::ShapeMismatch);
143    }
144    for &p in premium {
145        if !p.is_finite() {
146            return Err(ValidationError::NotFinite);
147        }
148        if p <= 0.0 {
149            return Err(ValidationError::NonPositive("premium"));
150        }
151    }
152    Ok(())
153}
154
155/// Validate that observed cumulative rows are non-decreasing.
156pub(crate) fn validate_monotone_cumulative(t: &TriangleView<'_>) -> Result<(), ValidationError> {
157    let n = t.n_origins.min(t.n_devs);
158    for i in 0..n {
159        let row_len = n - i;
160        let row = &t.data[i * t.n_devs..i * t.n_devs + row_len];
161        let mut prev: Option<f64> = None;
162        for (j, &value) in row.iter().enumerate() {
163            if !value.is_finite() {
164                continue;
165            }
166            if let Some(prev_value) = prev
167                && value < prev_value
168            {
169                return Err(ValidationError::NonMonotoneCumulative {
170                    origin: i,
171                    dev: j,
172                    previous: prev_value,
173                    value,
174                });
175            }
176            prev = Some(value);
177        }
178    }
179    Ok(())
180}
181
182/// Validate a finite slice.
183pub(crate) fn validate_finite_slice(values: &[f64]) -> Result<(), ValidationError> {
184    if values.iter().any(|value| !value.is_finite()) {
185        return Err(ValidationError::NotFinite);
186    }
187    Ok(())
188}
189
190/// Validate a tail factor under the crate's cumulative-loss production policy.
191pub(crate) fn validate_tail(tail: f64) -> Result<(), ValidationError> {
192    if !tail.is_finite() {
193        return Err(ValidationError::NotFinite);
194    }
195    if tail < 1.0 {
196        return Err(ValidationError::InvalidTail { tail });
197    }
198    Ok(())
199}
200
201/// Validate a finite, non-negative slice.
202pub(crate) fn validate_nonnegative_finite_slice(values: &[f64]) -> Result<(), ValidationError> {
203    for &value in values {
204        if !value.is_finite() {
205            return Err(ValidationError::NotFinite);
206        }
207        if value < 0.0 {
208            return Err(ValidationError::Negative);
209        }
210    }
211    Ok(())
212}
213
214/// Validate a finite, non-negative vector length.
215pub(crate) fn validate_nonnegative_finite_vector(
216    values: &[f64],
217    expected_len: usize,
218) -> Result<(), ValidationError> {
219    if values.len() != expected_len {
220        return Err(ValidationError::ShapeMismatch);
221    }
222    validate_nonnegative_finite_slice(values)
223}
224
225/// Validate a finite, strictly positive slice.
226pub(crate) fn validate_positive_finite_slice(
227    values: &[f64],
228    zero_context: &'static str,
229) -> Result<(), ValidationError> {
230    for &value in values {
231        if !value.is_finite() {
232            return Err(ValidationError::NotFinite);
233        }
234        if value <= 0.0 {
235            return Err(ValidationError::DivideByZero(zero_context));
236        }
237    }
238    Ok(())
239}
240
241/// Validate LDF/CDF vector shape and positivity.
242pub(crate) fn validate_development_factor_slices(
243    ldfs: &[f64],
244    cdfs: &[f64],
245    tail: f64,
246    n_devs: usize,
247    zero_context: &'static str,
248) -> Result<(), ValidationError> {
249    if cdfs.len() != n_devs {
250        return Err(ValidationError::ShapeMismatch);
251    }
252    if ldfs.len() + 1 != cdfs.len() {
253        return Err(ValidationError::ShapeMismatch);
254    }
255    validate_tail(tail)?;
256    validate_positive_finite_slice(cdfs, zero_context)?;
257    validate_positive_finite_slice(ldfs, zero_context)?;
258    Ok(())
259}
260
261/// Validate latest values and latest development indices against CDF length.
262pub(crate) fn validate_latest_and_dev(
263    latest: &[f64],
264    latest_dev: &[usize],
265    cdfs: &[f64],
266) -> Result<(), ValidationError> {
267    if latest.len() != latest_dev.len() {
268        return Err(ValidationError::ShapeMismatch);
269    }
270    for i in 0..latest.len() {
271        if latest_dev[i] >= cdfs.len() {
272            return Err(ValidationError::ShapeMismatch);
273        }
274        if !latest[i].is_finite() {
275            return Err(ValidationError::NotFinite);
276        }
277    }
278    Ok(())
279}
280
281/// Validate rectangular/ragged cumulative triangle inputs keyed by per-origin observed counts.
282pub(crate) fn validate_observed_count_inputs(
283    t: &TriangleView<'_>,
284    observed_counts: &[usize],
285    tail: f64,
286) -> Result<(), ValidationError> {
287    if t.data.len() != t.n_origins * t.n_devs {
288        return Err(ValidationError::ShapeMismatch);
289    }
290    if observed_counts.len() != t.n_origins || t.n_devs < 2 {
291        return Err(ValidationError::ShapeMismatch);
292    }
293    validate_tail(tail)?;
294    for (origin, &count) in observed_counts.iter().enumerate() {
295        if count == 0 || count > t.n_devs {
296            return Err(ValidationError::ShapeMismatch);
297        }
298        let mut previous = None;
299        for dev in 0..count {
300            let value = t.get(origin, dev);
301            if !value.is_finite() {
302                return Err(ValidationError::NotFinite);
303            }
304            if value < 0.0 {
305                return Err(ValidationError::Negative);
306            }
307            if let Some(previous_value) = previous
308                && value < previous_value
309            {
310                return Err(ValidationError::NonMonotoneCumulative {
311                    origin,
312                    dev,
313                    previous: previous_value,
314                    value,
315                });
316            }
317            previous = Some(value);
318        }
319    }
320    Ok(())
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn validate_triangle_checks_shape_square_finite_and_sign() {
329        let bad_len = TriangleView {
330            n_origins: 2,
331            n_devs: 2,
332            data: &[1.0, 2.0, 3.0],
333        };
334        assert_eq!(
335            validate_triangle(&bad_len),
336            Err(ValidationError::ShapeMismatch)
337        );
338
339        let rect = TriangleView {
340            n_origins: 2,
341            n_devs: 3,
342            data: &[1.0, 2.0, 3.0, 4.0, 5.0, f64::NAN],
343        };
344        assert_eq!(validate_triangle(&rect), Err(ValidationError::NotSquare));
345
346        let nan_obs = TriangleView {
347            n_origins: 2,
348            n_devs: 2,
349            data: &[1.0, f64::NAN, 3.0, f64::NAN],
350        };
351        assert_eq!(validate_triangle(&nan_obs), Err(ValidationError::NotFinite));
352
353        let neg = TriangleView {
354            n_origins: 2,
355            n_devs: 2,
356            data: &[1.0, -2.0, 3.0, f64::NAN],
357        };
358        assert_eq!(validate_triangle(&neg), Err(ValidationError::Negative));
359    }
360
361    #[test]
362    fn validate_premium_checks_length_finiteness_and_positivity() {
363        assert_eq!(
364            validate_premium(&[100.0], 2),
365            Err(ValidationError::ShapeMismatch)
366        );
367        assert_eq!(
368            validate_premium(&[100.0, f64::NAN], 2),
369            Err(ValidationError::NotFinite)
370        );
371        assert_eq!(
372            validate_premium(&[100.0, 0.0], 2),
373            Err(ValidationError::NonPositive("premium"))
374        );
375        assert_eq!(validate_premium(&[100.0, 200.0], 2), Ok(()));
376    }
377}