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    /// Model or matrix specification is invalid or numerically singular.
65    InvalidParameter(&'static str),
66}
67
68impl fmt::Display for ValidationError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::ShapeMismatch => write!(f, "input dimensions do not match expected shape"),
72            Self::NotSquare => write!(f, "triangle must be square (n_origins == n_devs)"),
73            Self::NotFinite => write!(f, "input contains NaN or infinite values"),
74            Self::Negative => write!(
75                f,
76                "input contains negative values where non-negative required"
77            ),
78            Self::DivideByZero(ctx) => write!(f, "division by zero in {ctx}"),
79            Self::NonMonotoneCumulative {
80                origin,
81                dev,
82                previous,
83                value,
84            } => write!(
85                f,
86                "non-monotone cumulative triangle at origin {origin}, dev {dev}: {value} < {previous}"
87            ),
88            Self::InvalidTail { tail } => write!(f, "invalid tail factor {tail} (must be >= 1.0)"),
89            Self::InvalidMaturity { index, value } => {
90                write!(f, "invalid maturity/probability {value} at index {index}")
91            }
92            Self::InvalidParameter(msg) => write!(f, "invalid parameter: {msg}"),
93        }
94    }
95}
96
97impl std::error::Error for ValidationError {}
98
99/// Validate a triangle view: square shape, finite non-negative observed
100/// cells. Unobserved cells (`i + j > n − 1`) are ignored.
101pub fn validate_triangle(t: &TriangleView<'_>) -> Result<(), ValidationError> {
102    if t.data.len() != t.n_origins * t.n_devs {
103        return Err(ValidationError::ShapeMismatch);
104    }
105    if t.n_origins != t.n_devs {
106        return Err(ValidationError::NotSquare);
107    }
108    let n = t.n_origins;
109    for i in 0..n {
110        let row = &t.data[i * n..i * n + (n - i)];
111        for &v in row {
112            if !v.is_finite() {
113                // NaN is our "unobserved" sentinel — within the observed
114                // upper triangle, NaN or infinity is an error.
115                return Err(ValidationError::NotFinite);
116            }
117            if v < 0.0 {
118                return Err(ValidationError::Negative);
119            }
120        }
121    }
122    Ok(())
123}
124
125/// Validate a premium vector: length matches origins, finite positive.
126pub fn validate_premium(premium: &[f64], n_origins: usize) -> Result<(), ValidationError> {
127    if premium.len() != n_origins {
128        return Err(ValidationError::ShapeMismatch);
129    }
130    for &p in premium {
131        if !p.is_finite() {
132            return Err(ValidationError::NotFinite);
133        }
134        if p <= 0.0 {
135            return Err(ValidationError::DivideByZero("premium"));
136        }
137    }
138    Ok(())
139}
140
141/// Validate that observed cumulative rows are non-decreasing.
142pub(crate) fn validate_monotone_cumulative(t: &TriangleView<'_>) -> Result<(), ValidationError> {
143    let n = t.n_origins.min(t.n_devs);
144    for i in 0..n {
145        let row_len = n - i;
146        let row = &t.data[i * t.n_devs..i * t.n_devs + row_len];
147        let mut prev: Option<f64> = None;
148        for (j, &value) in row.iter().enumerate() {
149            if !value.is_finite() {
150                continue;
151            }
152            if let Some(prev_value) = prev
153                && value < prev_value
154            {
155                return Err(ValidationError::NonMonotoneCumulative {
156                    origin: i,
157                    dev: j,
158                    previous: prev_value,
159                    value,
160                });
161            }
162            prev = Some(value);
163        }
164    }
165    Ok(())
166}
167
168/// Validate a finite slice.
169pub(crate) fn validate_finite_slice(values: &[f64]) -> Result<(), ValidationError> {
170    if values.iter().any(|value| !value.is_finite()) {
171        return Err(ValidationError::NotFinite);
172    }
173    Ok(())
174}
175
176/// Validate a tail factor under the crate's cumulative-loss production policy.
177pub(crate) fn validate_tail(tail: f64) -> Result<(), ValidationError> {
178    if !tail.is_finite() {
179        return Err(ValidationError::NotFinite);
180    }
181    if tail < 1.0 {
182        return Err(ValidationError::InvalidTail { tail });
183    }
184    Ok(())
185}
186
187/// Validate a finite, non-negative slice.
188pub(crate) fn validate_nonnegative_finite_slice(values: &[f64]) -> Result<(), ValidationError> {
189    for &value in values {
190        if !value.is_finite() {
191            return Err(ValidationError::NotFinite);
192        }
193        if value < 0.0 {
194            return Err(ValidationError::Negative);
195        }
196    }
197    Ok(())
198}
199
200/// Validate a finite, non-negative vector length.
201pub(crate) fn validate_nonnegative_finite_vector(
202    values: &[f64],
203    expected_len: usize,
204) -> Result<(), ValidationError> {
205    if values.len() != expected_len {
206        return Err(ValidationError::ShapeMismatch);
207    }
208    validate_nonnegative_finite_slice(values)
209}
210
211/// Validate a finite, strictly positive slice.
212pub(crate) fn validate_positive_finite_slice(
213    values: &[f64],
214    zero_context: &'static str,
215) -> Result<(), ValidationError> {
216    for &value in values {
217        if !value.is_finite() {
218            return Err(ValidationError::NotFinite);
219        }
220        if value <= 0.0 {
221            return Err(ValidationError::DivideByZero(zero_context));
222        }
223    }
224    Ok(())
225}
226
227/// Validate LDF/CDF vector shape and positivity.
228pub(crate) fn validate_development_factor_slices(
229    ldfs: &[f64],
230    cdfs: &[f64],
231    tail: f64,
232    n_devs: usize,
233    zero_context: &'static str,
234) -> Result<(), ValidationError> {
235    if cdfs.len() != n_devs {
236        return Err(ValidationError::ShapeMismatch);
237    }
238    if ldfs.len() + 1 != cdfs.len() {
239        return Err(ValidationError::ShapeMismatch);
240    }
241    validate_tail(tail)?;
242    validate_positive_finite_slice(cdfs, zero_context)?;
243    validate_positive_finite_slice(ldfs, zero_context)?;
244    Ok(())
245}
246
247/// Validate latest values and latest development indices against CDF length.
248pub(crate) fn validate_latest_and_dev(
249    latest: &[f64],
250    latest_dev: &[usize],
251    cdfs: &[f64],
252) -> Result<(), ValidationError> {
253    if latest.len() != latest_dev.len() {
254        return Err(ValidationError::ShapeMismatch);
255    }
256    for i in 0..latest.len() {
257        if latest_dev[i] >= cdfs.len() {
258            return Err(ValidationError::ShapeMismatch);
259        }
260        if !latest[i].is_finite() {
261            return Err(ValidationError::NotFinite);
262        }
263    }
264    Ok(())
265}
266
267/// Validate rectangular/ragged cumulative triangle inputs keyed by per-origin observed counts.
268pub(crate) fn validate_observed_count_inputs(
269    t: &TriangleView<'_>,
270    observed_counts: &[usize],
271    tail: f64,
272) -> Result<(), ValidationError> {
273    if t.data.len() != t.n_origins * t.n_devs {
274        return Err(ValidationError::ShapeMismatch);
275    }
276    if observed_counts.len() != t.n_origins || t.n_devs < 2 {
277        return Err(ValidationError::ShapeMismatch);
278    }
279    validate_tail(tail)?;
280    for (origin, &count) in observed_counts.iter().enumerate() {
281        if count == 0 || count > t.n_devs {
282            return Err(ValidationError::ShapeMismatch);
283        }
284        let mut previous = None;
285        for dev in 0..count {
286            let value = t.get(origin, dev);
287            if !value.is_finite() {
288                return Err(ValidationError::NotFinite);
289            }
290            if value < 0.0 {
291                return Err(ValidationError::Negative);
292            }
293            if let Some(previous_value) = previous
294                && value < previous_value
295            {
296                return Err(ValidationError::NonMonotoneCumulative {
297                    origin,
298                    dev,
299                    previous: previous_value,
300                    value,
301                });
302            }
303            previous = Some(value);
304        }
305    }
306    Ok(())
307}