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