1use std::fmt;
7
8use crate::types::TriangleView;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
17pub enum MonotonicityPolicy {
18 #[default]
20 Strict,
21 AllowNegativeIncrements,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
28#[non_exhaustive]
29pub enum ValidationError {
30 ShapeMismatch,
32 NotSquare,
35 NotFinite,
37 Negative,
39 DivideByZero(&'static str),
41 NonMonotoneCumulative {
43 origin: usize,
45 dev: usize,
47 previous: f64,
49 value: f64,
51 },
52 InvalidTail {
54 tail: f64,
56 },
57 InvalidMaturity {
59 index: usize,
61 value: f64,
63 },
64 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
99pub 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 return Err(ValidationError::NotFinite);
116 }
117 if v < 0.0 {
118 return Err(ValidationError::Negative);
119 }
120 }
121 }
122 Ok(())
123}
124
125pub 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
141pub(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
168pub(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
176pub(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
187pub(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
200pub(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
211pub(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
227pub(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
247pub(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
267pub(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}