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