Skip to main content

reserving_kernels/
types.rs

1//! Prevalidated columnar triangle inputs.
2//!
3//! A loss-development triangle is an `n_origins × n_devs` grid of cumulative
4//! amounts (paid or incurred). Cell `(i, j)` is observed iff `i + j ≤ n - 1`
5//! for a square triangle. Unobserved cells are represented as `NaN` so the
6//! compute kernels stay branch-light — null-handling lives at the ingress
7//! boundary (see [`crate::validate`]).
8
9use std::fmt;
10
11use crate::benktander::{BenktanderEngine, BenktanderProjection};
12use crate::bf::{BornhuetterFergusonEngine, BornhuetterFergusonProjection};
13use crate::bootstrap_odp::{
14    OdpBootstrapOptions, OdpBootstrapResult, OdpFit, bootstrap_odp, fit_odp,
15};
16use crate::brosius::{self, Brosius};
17use crate::cape_cod::{CapeCodEngine, CapeCodProjection};
18use crate::chain_ladder::{ChainLadderEngine, ChainLadderProjection};
19use crate::clark_mle::{self, ClarkMleResult, ClarkOptions};
20use crate::diagnostics::triangle_diagnostics::{self, TriangleDiagnostics};
21use crate::exhibit::{ExhibitBundle, build_exhibit_bundle};
22use crate::generalized_cape_cod::{GeneralizedCapeCodEngine, GeneralizedCapeCodProjection};
23use crate::glm_reserving::{self, GlmOptions, GlmReservingResult};
24use crate::ldf::{DevelopmentFactorEngine, DevelopmentFactors};
25use crate::mack::{self, Mack};
26use crate::merz_wuthrich::{self, MerzWuthrichResult};
27use crate::ptf_regression::{self, PtfOptions, PtfResult};
28use crate::triangle::{cumulative_to_incremental, latest_diagonal};
29use crate::validate::{MonotonicityPolicy, ValidationError, validate_triangle};
30
31/// Deserialize a `Vec<f64>` where JSON `null` values map back to `f64::NAN`,
32/// enabling lossless `serde_json` round-trips for triangles containing `NaN`
33/// sentinels in unobserved cells.
34fn deserialize_vec_f64_null_as_nan<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
35where
36    D: serde::Deserializer<'de>,
37{
38    use serde::Deserialize;
39    let opts: Vec<Option<f64>> = Vec::deserialize(deserializer)?;
40    Ok(opts.into_iter().map(|v| v.unwrap_or(f64::NAN)).collect())
41}
42
43#[derive(serde::Deserialize)]
44struct RawTriangle {
45    n_origins: usize,
46    n_devs: usize,
47    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
48    data: Vec<f64>,
49}
50
51impl TryFrom<RawTriangle> for Triangle {
52    type Error = ValidationError;
53
54    fn try_from(raw: RawTriangle) -> Result<Self, Self::Error> {
55        Self::try_new(raw.n_origins, raw.n_devs, raw.data)
56    }
57}
58
59/// An `n_origins × n_devs` cumulative loss triangle in row-major layout.
60///
61/// `data[i * n_devs + j]` is the cumulative loss for origin `i` at
62/// development age `j`. Unobserved cells are `NaN`. The kernels assume the
63/// triangle is *square* (`n_origins == n_devs`) and that cell `(i, j)` is
64/// observed for `i + j ≤ n - 1`.
65///
66/// Equality (`PartialEq`) treats two `NaN` cells at the same position as equal
67/// so `tri == tri.clone()` holds for triangles with unobserved cells.
68/// Deserialization maps JSON `null` to `NaN` and validates via [`Self::try_new`].
69#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
70#[serde(try_from = "RawTriangle")]
71pub struct Triangle {
72    n_origins: usize,
73    n_devs: usize,
74    data: Vec<f64>,
75}
76
77impl PartialEq for Triangle {
78    fn eq(&self, other: &Self) -> bool {
79        self.view() == other.view()
80    }
81}
82
83impl Triangle {
84    /// Construct a triangle from a row-major slice without validation.
85    ///
86    /// Callers must ensure `data.len() == n_origins * n_devs`. Use
87    /// [`Self::try_new`] at external ingress boundaries when full validation
88    /// (square, finite, non-negative observed cells) is required.
89    #[inline]
90    pub fn new(n_origins: usize, n_devs: usize, data: Vec<f64>) -> Self {
91        debug_assert_eq!(data.len(), n_origins * n_devs);
92        Self {
93            n_origins,
94            n_devs,
95            data,
96        }
97    }
98
99    /// Construct and validate a square cumulative triangle.
100    ///
101    /// This enforces the same shape, finiteness, and non-negative observed-cell
102    /// contract used by the checked reserving engines. Row monotonicity is
103    /// still method-specific and is validated by those engines.
104    pub fn try_new(
105        n_origins: usize,
106        n_devs: usize,
107        data: Vec<f64>,
108    ) -> Result<Self, ValidationError> {
109        let triangle = Self {
110            n_origins,
111            n_devs,
112            data,
113        };
114        validate_triangle(&triangle.view())?;
115        Ok(triangle)
116    }
117
118    /// Construct and validate a square cumulative triangle directly from
119    /// ragged upper-triangle rows (no manual `f64::NAN` padding required).
120    ///
121    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
122    /// For owned `Vec<Vec<f64>>` inputs, see [`Self::try_from_rows`].
123    ///
124    /// # Example
125    /// ```rust
126    /// use reserving_kernels::Triangle;
127    ///
128    /// let tri = Triangle::try_from_upper_rows(&[
129    ///     &[100.0, 160.0, 195.0],
130    ///     &[120.0, 190.0],
131    ///     &[135.0],
132    /// ])?;
133    /// assert_eq!(tri.n(), 3);
134    /// assert_eq!(tri.latest_diagonal(), vec![195.0, 190.0, 135.0]);
135    /// # Ok::<(), reserving_kernels::validate::ValidationError>(())
136    /// ```
137    pub fn try_from_upper_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
138        Self::try_from_rows(rows)
139    }
140
141    /// Generic variant of [`Self::try_from_upper_rows`] accepting any slice of
142    /// row buffers (`&[Vec<f64>]`, `&[&[f64]]`, etc.).
143    pub fn try_from_rows<R: AsRef<[f64]>>(rows: &[R]) -> Result<Self, ValidationError> {
144        let n = rows.len();
145        if n == 0 {
146            return Err(ValidationError::ShapeMismatch);
147        }
148        let mut data = vec![f64::NAN; n * n];
149        for (i, row) in rows.iter().enumerate() {
150            let row = row.as_ref();
151            if row.len() != n - i {
152                return Err(ValidationError::ShapeMismatch);
153            }
154            data[i * n..i * n + row.len()].copy_from_slice(row);
155        }
156        Self::try_new(n, n, data)
157    }
158
159    /// Construct and validate a square cumulative triangle by cumulating
160    /// incremental upper-triangle rows along each origin period.
161    ///
162    /// Row `i` must have length `n - i` where `n = rows.len() > 0`.
163    pub fn try_from_incremental_rows(rows: &[&[f64]]) -> Result<Self, ValidationError> {
164        let n = rows.len();
165        if n == 0 {
166            return Err(ValidationError::ShapeMismatch);
167        }
168        let mut data = vec![f64::NAN; n * n];
169        for (i, row) in rows.iter().enumerate() {
170            if row.len() != n - i {
171                return Err(ValidationError::ShapeMismatch);
172            }
173            let mut acc = 0.0;
174            for (j, &inc) in row.iter().enumerate() {
175                if !inc.is_finite() {
176                    return Err(ValidationError::NotFinite);
177                }
178                acc += inc;
179                data[i * n + j] = acc;
180            }
181        }
182        Self::try_new(n, n, data)
183    }
184
185    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
186    #[inline]
187    pub fn get(&self, i: usize, j: usize) -> f64 {
188        self.data[i * self.n_devs + j]
189    }
190
191    /// Observed cumulative slice for origin `i` (length `n - i`, excluding trailing `NaN`s).
192    #[inline]
193    pub fn origin_row(&self, i: usize) -> &[f64] {
194        let n = self.n();
195        let len = n.saturating_sub(i);
196        let start = i * self.n_devs;
197        &self.data[start..start + len]
198    }
199
200    /// Number of origin (accident / policy) periods.
201    #[inline]
202    pub fn n_origins(&self) -> usize {
203        self.n_origins
204    }
205
206    /// Number of development periods.
207    #[inline]
208    pub fn n_devs(&self) -> usize {
209        self.n_devs
210    }
211
212    /// Borrow the underlying row-major slice of length `n_origins * n_devs`.
213    #[inline]
214    pub fn data(&self) -> &[f64] {
215        &self.data
216    }
217
218    /// Square triangle dimension `min(n_origins, n_devs)`.
219    #[inline]
220    pub fn n(&self) -> usize {
221        self.n_origins.min(self.n_devs)
222    }
223
224    /// `true` iff the triangle has zero origins or zero development periods.
225    #[inline]
226    pub fn is_empty(&self) -> bool {
227        self.n_origins == 0 || self.n_devs == 0
228    }
229
230    /// Borrow as a [`TriangleView`].
231    #[inline]
232    pub fn view(&self) -> TriangleView<'_> {
233        TriangleView {
234            n_origins: self.n_origins,
235            n_devs: self.n_devs,
236            data: &self.data,
237        }
238    }
239
240    /// Extract the latest-observed cumulative anti-diagonal.
241    pub fn latest_diagonal(&self) -> Vec<f64> {
242        latest_diagonal(&self.view())
243    }
244
245    /// Convert this cumulative triangle to an incremental [`Triangle`].
246    pub fn to_incremental(&self) -> Self {
247        let n = self.n();
248        Self::new(n, n, cumulative_to_incremental(&self.view()))
249    }
250
251    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
252    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
253        self.view().ldfs(tail)
254    }
255
256    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
257    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
258        self.view().chain_ladder(tail)
259    }
260
261    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
262    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
263        self.view().mack(tail)
264    }
265
266    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
267    pub fn mack_with_policy(
268        &self,
269        tail: f64,
270        policy: MonotonicityPolicy,
271    ) -> Result<Mack, ValidationError> {
272        self.view().mack_with_policy(tail, policy)
273    }
274
275    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
276    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
277        self.view().merz_wuthrich()
278    }
279
280    /// Merz & Wüthrich (2008) 1-year CDR MSEP under an explicit [`MonotonicityPolicy`].
281    pub fn merz_wuthrich_with_policy(
282        &self,
283        policy: MonotonicityPolicy,
284    ) -> Result<MerzWuthrichResult, ValidationError> {
285        self.view().merz_wuthrich_with_policy(policy)
286    }
287
288    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
289    pub fn bf(
290        &self,
291        expected_ultimate: &[f64],
292        tail: f64,
293    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
294        self.view().bf(expected_ultimate, tail)
295    }
296
297    /// Cape Cod projection using volume-weighted LDFs.
298    pub fn cape_cod(
299        &self,
300        premium: &[f64],
301        tail: f64,
302    ) -> Result<CapeCodProjection, ValidationError> {
303        self.view().cape_cod(premium, tail)
304    }
305
306    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
307    pub fn bootstrap_odp(
308        &self,
309        tail: f64,
310        options: OdpBootstrapOptions,
311    ) -> Result<OdpBootstrapResult, ValidationError> {
312        self.view().bootstrap_odp(tail, options)
313    }
314
315    /// Build a complete JSON-serializable reserving exhibit bundle.
316    pub fn exhibit(
317        &self,
318        premium: Option<&[f64]>,
319        expected_ultimate: Option<&[f64]>,
320        tail: f64,
321    ) -> Result<ExhibitBundle, ValidationError> {
322        self.view().exhibit(premium, expected_ultimate, tail)
323    }
324
325    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
326    pub fn benktander(
327        &self,
328        expected_ultimate: &[f64],
329        iterations: usize,
330        tail: f64,
331    ) -> Result<BenktanderProjection, ValidationError> {
332        self.view().benktander(expected_ultimate, iterations, tail)
333    }
334
335    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
336    pub fn generalized_cape_cod(
337        &self,
338        premium: &[f64],
339        decay: f64,
340        tail: f64,
341    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
342        self.view().generalized_cape_cod(premium, decay, tail)
343    }
344
345    /// Brosius (1993) OLS credibility development projection.
346    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
347        self.view().brosius(tail)
348    }
349
350    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
351    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
352        self.view().fit_odp(tail)
353    }
354
355    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
356    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
357        self.view().glm(options)
358    }
359
360    /// Fit Clark (2003) LDF parametric growth-curve MLE.
361    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
362        self.view().clark_ldf(options)
363    }
364
365    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
366    pub fn clark_cape_cod(
367        &self,
368        premium: &[f64],
369        options: &ClarkOptions,
370    ) -> Result<ClarkMleResult, ValidationError> {
371        self.view().clark_cape_cod(premium, options)
372    }
373
374    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
375    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
376        self.view().ptf(options)
377    }
378
379    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
380    pub fn diagnostics(&self) -> TriangleDiagnostics {
381        self.view().diagnostics()
382    }
383}
384
385impl fmt::Display for Triangle {
386    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387        self.view().fmt(f)
388    }
389}
390
391/// A non-owning view over a triangle's row-major buffer.
392#[derive(Debug, Clone, Copy)]
393pub struct TriangleView<'a> {
394    /// Number of origin periods.
395    pub n_origins: usize,
396    /// Number of development periods.
397    pub n_devs: usize,
398    /// Row-major buffer.
399    pub data: &'a [f64],
400}
401
402impl PartialEq for TriangleView<'_> {
403    fn eq(&self, other: &Self) -> bool {
404        self.n_origins == other.n_origins
405            && self.n_devs == other.n_devs
406            && self.data.len() == other.data.len()
407            && self
408                .data
409                .iter()
410                .zip(other.data.iter())
411                .all(|(&a, &b)| (a.is_nan() && b.is_nan()) || a == b)
412    }
413}
414
415impl fmt::Display for TriangleView<'_> {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        for i in 0..self.n_origins {
418            if i > 0 {
419                writeln!(f)?;
420            }
421            for j in 0..self.n_devs {
422                if j > 0 {
423                    write!(f, "\t")?;
424                }
425                let v = self.data[i * self.n_devs + j];
426                if v.is_finite() {
427                    write!(f, "{v:.2}")?;
428                } else {
429                    write!(f, "-")?;
430                }
431            }
432        }
433        Ok(())
434    }
435}
436
437impl TriangleView<'_> {
438    /// Cumulative value at origin `i`, development `j`. `NaN` if unobserved.
439    #[inline]
440    pub fn get(&self, i: usize, j: usize) -> f64 {
441        self.data[i * self.n_devs + j]
442    }
443
444    /// `true` iff cell `(i, j)` is scheduled to be observed under the
445    /// upper-triangular square-triangle convention (`i + j < n`).
446    #[inline]
447    pub fn is_scheduled_observed(&self, i: usize, j: usize) -> bool {
448        let n = self.n_origins.min(self.n_devs);
449        i < n && j < n && i + j < n
450    }
451
452    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
453    #[inline]
454    pub fn is_valid_observed(&self, i: usize, j: usize) -> bool {
455        self.is_scheduled_observed(i, j) && self.get(i, j).is_finite()
456    }
457
458    /// `true` iff cell `(i, j)` is scheduled observed and holds a finite value.
459    ///
460    /// This preserves the original hot-path predicate. Use
461    /// [`Self::is_scheduled_observed`] when validation needs to distinguish
462    /// triangle geometry from numeric validity.
463    #[inline]
464    pub fn is_observed(&self, i: usize, j: usize) -> bool {
465        self.is_valid_observed(i, j)
466    }
467
468    /// Volume-weighted development factors and CDFs (`tail = 1.0` for fully developed).
469    pub fn ldfs(&self, tail: f64) -> Result<DevelopmentFactors, ValidationError> {
470        DevelopmentFactorEngine::volume_weighted(self, tail)
471    }
472
473    /// Volume-weighted Chain-Ladder projection (`tail = 1.0` for fully developed).
474    pub fn chain_ladder(&self, tail: f64) -> Result<ChainLadderProjection, ValidationError> {
475        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
476        ChainLadderEngine::project(self, &factors)
477    }
478
479    /// Mack (1993) distribution-free chain-ladder reserve & standard error analysis.
480    pub fn mack(&self, tail: f64) -> Result<Mack, ValidationError> {
481        mack::analyze(self, tail)
482    }
483
484    /// Mack (1993) analysis under an explicit [`MonotonicityPolicy`].
485    pub fn mack_with_policy(
486        &self,
487        tail: f64,
488        policy: MonotonicityPolicy,
489    ) -> Result<Mack, ValidationError> {
490        mack::analyze_with_policy(self, tail, policy)
491    }
492
493    /// Merz & Wüthrich (2008) 1-year Solvency II Claims Development Result (CDR) MSEP.
494    pub fn merz_wuthrich(&self) -> Result<MerzWuthrichResult, ValidationError> {
495        merz_wuthrich::analyze(self)
496    }
497
498    /// Merz & Wüthrich (2008) 1-year CDR MSEP under an explicit [`MonotonicityPolicy`].
499    pub fn merz_wuthrich_with_policy(
500        &self,
501        policy: MonotonicityPolicy,
502    ) -> Result<MerzWuthrichResult, ValidationError> {
503        merz_wuthrich::analyze_with_policy(self, policy)
504    }
505
506    /// Bornhuetter–Ferguson projection using volume-weighted LDFs.
507    pub fn bf(
508        &self,
509        expected_ultimate: &[f64],
510        tail: f64,
511    ) -> Result<BornhuetterFergusonProjection, ValidationError> {
512        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
513        BornhuetterFergusonEngine::project_from_expected_ultimate(self, &factors, expected_ultimate)
514    }
515
516    /// Cape Cod projection using volume-weighted LDFs.
517    pub fn cape_cod(
518        &self,
519        premium: &[f64],
520        tail: f64,
521    ) -> Result<CapeCodProjection, ValidationError> {
522        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
523        CapeCodEngine::project(self, &factors, premium)
524    }
525
526    /// Run England & Verrall / Shapland ODP bootstrap reserve simulation.
527    pub fn bootstrap_odp(
528        &self,
529        tail: f64,
530        options: OdpBootstrapOptions,
531    ) -> Result<OdpBootstrapResult, ValidationError> {
532        bootstrap_odp(self, tail, options)
533    }
534
535    /// Build a complete JSON-serializable reserving exhibit bundle.
536    pub fn exhibit(
537        &self,
538        premium: Option<&[f64]>,
539        expected_ultimate: Option<&[f64]>,
540        tail: f64,
541    ) -> Result<ExhibitBundle, ValidationError> {
542        build_exhibit_bundle(self, premium, expected_ultimate, tail)
543    }
544
545    /// Benktander (1976) / Hovinen credibility projection using volume-weighted LDFs.
546    pub fn benktander(
547        &self,
548        expected_ultimate: &[f64],
549        iterations: usize,
550        tail: f64,
551    ) -> Result<BenktanderProjection, ValidationError> {
552        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
553        BenktanderEngine::project_from_expected_ultimate(
554            self,
555            &factors,
556            expected_ultimate,
557            iterations,
558        )
559    }
560
561    /// Generalized Cape Cod (Gluck 1997) decay-weighted projection.
562    pub fn generalized_cape_cod(
563        &self,
564        premium: &[f64],
565        decay: f64,
566        tail: f64,
567    ) -> Result<GeneralizedCapeCodProjection, ValidationError> {
568        let factors = DevelopmentFactorEngine::volume_weighted(self, tail)?;
569        GeneralizedCapeCodEngine::project(self, &factors, premium, decay)
570    }
571
572    /// Brosius (1993) OLS credibility development projection.
573    pub fn brosius(&self, tail: f64) -> Result<Brosius, ValidationError> {
574        brosius::project(self, tail)
575    }
576
577    /// Fit the Over-Dispersed Poisson GLM (`fit_odp`) with strict monotonicity.
578    pub fn fit_odp(&self, tail: f64) -> Result<OdpFit, ValidationError> {
579        fit_odp(self, tail, MonotonicityPolicy::Strict)
580    }
581
582    /// Fit a reserving GLM (`Odp`, `Gamma`, `Tweedie`, or `LogNormal`) via Householder QR IRLS.
583    pub fn glm(&self, options: &GlmOptions) -> Result<GlmReservingResult, ValidationError> {
584        glm_reserving::fit_glm(self, options)
585    }
586
587    /// Fit Clark (2003) LDF parametric growth-curve MLE.
588    pub fn clark_ldf(&self, options: &ClarkOptions) -> Result<ClarkMleResult, ValidationError> {
589        clark_mle::fit_clark_ldf(self, options)
590    }
591
592    /// Fit Clark (2003) Cape Cod parametric growth-curve MLE.
593    pub fn clark_cape_cod(
594        &self,
595        premium: &[f64],
596        options: &ClarkOptions,
597    ) -> Result<ClarkMleResult, ValidationError> {
598        clark_mle::fit_clark_cape_cod(self, premium, options)
599    }
600
601    /// Fit Barnett & Zehnwirth (2000) Probabilistic Trend Family log-linear regression.
602    pub fn ptf(&self, options: &PtfOptions) -> Result<PtfResult, ValidationError> {
603        ptf_regression::fit_ptf(self, options)
604    }
605
606    /// Structural triangle diagnostics (observed/missing counts, monotonicity, zero latest).
607    pub fn diagnostics(&self) -> TriangleDiagnostics {
608        triangle_diagnostics::analyze(self)
609    }
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615    use crate::validate::ValidationError;
616
617    #[test]
618    fn try_new_rejects_shape_mismatch() {
619        assert_eq!(
620            Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0]),
621            Err(ValidationError::ShapeMismatch)
622        );
623    }
624
625    #[test]
626    fn try_new_accepts_valid_square_triangle() {
627        let triangle = Triangle::try_new(2, 2, vec![1.0, 2.0, 3.0, f64::NAN]).expect("triangle");
628
629        assert_eq!(triangle.n_origins, 2);
630        assert_eq!(triangle.n_devs, 2);
631        assert_eq!(triangle, triangle.clone());
632        assert_eq!(triangle.view(), triangle.view());
633    }
634
635    #[test]
636    fn triangle_serde_json_roundtrips_nan_and_validates() {
637        let triangle =
638            Triangle::try_from_upper_rows(&[&[100.0, 160.0, 195.0], &[120.0, 190.0], &[135.0]])
639                .expect("triangle");
640        let json = serde_json::to_string(&triangle).expect("serialize");
641        let decoded: Triangle = serde_json::from_str(&json).expect("deserialize");
642        assert_eq!(triangle, decoded);
643
644        let malformed = r#"{"n_origins":3,"n_devs":3,"data":[1.0]}"#;
645        assert!(serde_json::from_str::<Triangle>(malformed).is_err());
646    }
647}