KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Column provenance for experimental kinetics columns.
//!
//! The goal is to keep a readable chain of how a column was produced:
//! raw import, binding, and transformation steps such as smoothing or resampling.
//! Each step can also carry a quality report when the operation preserves
//! row alignment and a before/after comparison is meaningful.

use crate::Kinetics::experimental_kinetics::math::ndarray_statistics::FilterQualityReport;

/// Full provenance chain for one column.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ColumnProvenance {
    /// Root columns that ultimately feed this column.
    pub root_columns: Vec<String>,
    /// Ordered transformation history for the current column.
    pub steps: Vec<ColumnTransformStep>,
}

/// One provenance step together with optional quality metadata.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ColumnTransformStep {
    pub input_columns: Vec<String>,
    pub output_column: String,
    pub kind: ColumnTransformKind,
    pub quality: Option<TransformQuality>,
    pub operation_id: Option<usize>,
    pub reversible: bool,
    /// Row coverage for the operation; absent in older serialized documents.
    #[serde(default)]
    pub coverage: Option<TransformCoverage>,
}

/// Counts valid and undefined rows without conflating gaps with trimmed edges.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct TransformCoverage {
    pub input_rows: usize,
    pub input_valid_rows: usize,
    pub input_missing_leading: usize,
    pub input_missing_internal: usize,
    pub input_missing_trailing: usize,
    #[serde(default)]
    pub input_non_finite_rows: usize,
    pub output_rows: usize,
    pub output_defined_rows: usize,
    pub output_undefined_leading: usize,
    pub output_undefined_internal: usize,
    pub output_undefined_trailing: usize,
    #[serde(default)]
    pub output_non_finite_rows: usize,
    pub rows_removed: usize,
}

impl TransformCoverage {
    pub fn from_values(
        input: &[Option<f64>],
        output: &[Option<f64>],
        rows_removed: usize,
    ) -> Self {
        fn counts(values: &[Option<f64>]) -> (usize, usize, usize, usize, usize) {
            let is_finite = |value: &Option<f64>| value.is_some_and(f64::is_finite);
            let first = values.iter().position(is_finite);
            let last = values.iter().rposition(is_finite);
            let non_finite = values
                .iter()
                .filter(|value| value.is_some_and(|value| !value.is_finite()))
                .count();
            match (first, last) {
                (Some(first), Some(last)) => (
                    values.iter().filter(|value| is_finite(value)).count(),
                    first,
                    values[first..=last]
                        .iter()
                        .filter(|value| !is_finite(value))
                        .count(),
                    values.len() - last - 1,
                    non_finite,
                ),
                _ => (0, values.len(), 0, 0, non_finite),
            }
        }

        let (
            input_valid_rows,
            input_missing_leading,
            input_missing_internal,
            input_missing_trailing,
            input_non_finite_rows,
        ) = counts(input);
        let (
            output_defined_rows,
            output_undefined_leading,
            output_undefined_internal,
            output_undefined_trailing,
            output_non_finite_rows,
        ) = counts(output);
        Self {
            input_rows: input.len(),
            input_valid_rows,
            input_missing_leading,
            input_missing_internal,
            input_missing_trailing,
            input_non_finite_rows,
            output_rows: output.len(),
            output_defined_rows,
            output_undefined_leading,
            output_undefined_internal,
            output_undefined_trailing,
            output_non_finite_rows,
            rows_removed,
        }
    }

    pub fn summary(&self) -> String {
        format!(
            "Input: {}/{} finite (undefined edges {}+{}, internal {}, non-finite {}); output: {}/{} finite (undefined edges {}+{}, internal {}, non-finite {}); rows removed: {}",
            self.input_valid_rows,
            self.input_rows,
            self.input_missing_leading,
            self.input_missing_trailing,
            self.input_missing_internal,
            self.input_non_finite_rows,
            self.output_defined_rows,
            self.output_rows,
            self.output_undefined_leading,
            self.output_undefined_trailing,
            self.output_undefined_internal,
            self.output_non_finite_rows,
            self.rows_removed,
        )
    }
}

/// Comparison target used by quality reports.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum QualityReference {
    PreviousStep,
    RawRoot,
    NamedColumn(String),
}

/// Quality status for a transformation.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum QualityStatus {
    Computed,
    NotApplicable(String),
    Failed(String),
}

/// Filter quality together with the comparison target and status.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TransformQuality {
    pub compared_to: QualityReference,
    pub report: Option<FilterQualityReport>,
    pub status: QualityStatus,
}

/// The kind of transformation applied to a column.
///
/// This is intentionally compact and human-readable so it can be shown in GUI
/// tooltips, side panels, or debug logs without extra decoding.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum ColumnTransformKind {
    Raw {
        source: String,
    },
    Import {
        source: String,
    },
    Binding {
        role: String,
        unit: String,
    },
    RollingMean {
        window: usize,
    },
    SynchronizedRollingMean {
        window: usize,
        x_column: String,
        common_mask: bool,
        output_x_column: Option<String>,
    },
    Hampel {
        window: usize,
        n_sigma: f64,
        strategy: String,
    },
    SavitzkyGolay {
        window: usize,
        poly_order: usize,
        deriv: usize,
        delta: f64,
        mode: String,
    },
    Lowess {
        frac: f64,
    },
    SplineResample {
        time_col: String,
        new_time_col: String,
        n_points: usize,
        kind: String,
    },
    LsqSplineResample {
        time_col: String,
        new_time_col: String,
        n_points: usize,
        degree: usize,
        n_internal_knots: usize,
        solver: String,
    },
    Fitting {
        model: String,
        #[serde(default)]
        equation: String,
        x_col: String,
        y_col: String,
        method: String,
        parameters: Vec<(String, f64)>,
        r2: f64,
        tolerance: f64,
        max_iter: usize,
    },
    Formula {
        x_column: String,
        expression: String,
    },
    FormulaFromColumns {
        variable_columns: Vec<(String, String)>,
        expression: String,
    },
    Manual {
        operation: String,
        details: Option<String>,
    },
}

impl ColumnProvenance {
    /// Create provenance that starts from raw data.
    pub fn raw(column_name: impl Into<String>) -> Self {
        let column_name = column_name.into();
        Self {
            root_columns: vec![column_name.clone()],
            steps: vec![ColumnTransformStep::new(
                vec![column_name.clone()],
                column_name.clone(),
                ColumnTransformKind::Raw {
                    source: column_name,
                },
                None,
                None,
                false,
            )],
        }
    }

    /// Create provenance for a column imported from an external file.
    pub fn imported(column_name: impl Into<String>, source: impl Into<String>) -> Self {
        let column_name = column_name.into();
        let source = source.into();
        Self {
            root_columns: vec![source.clone()],
            steps: vec![ColumnTransformStep::new(
                vec![source.clone()],
                column_name.clone(),
                ColumnTransformKind::Import { source },
                None,
                None,
                false,
            )],
        }
    }

    /// Create provenance for a column that originated from a manual or external action.
    pub fn manual(
        column_name: impl Into<String>,
        operation: impl Into<String>,
        details: Option<String>,
    ) -> Self {
        let column_name = column_name.into();
        Self {
            root_columns: vec![column_name.clone()],
            steps: vec![ColumnTransformStep::new(
                vec![column_name.clone()],
                column_name.clone(),
                ColumnTransformKind::Manual {
                    operation: operation.into(),
                    details,
                },
                None,
                None,
                true,
            )],
        }
    }

    /// Clone an existing provenance chain for a new column name.
    pub fn inherited(column_name: impl Into<String>, source: &ColumnProvenance) -> Self {
        let column_name = column_name.into();
        let mut cloned = source.clone();
        cloned.rename_output(column_name);
        cloned
    }

    /// Append one new step to the chain.
    pub fn append_step(&mut self, step: ColumnTransformStep) {
        for root in &step.input_columns {
            if !self.root_columns.contains(root) {
                self.root_columns.push(root.clone());
            }
        }
        self.steps.push(step);
    }

    /// Append a new step using the common transformation parameters.
    pub fn push_step(
        &mut self,
        input_columns: Vec<String>,
        output_column: impl Into<String>,
        kind: ColumnTransformKind,
        quality: Option<TransformQuality>,
        operation_id: Option<usize>,
        reversible: bool,
    ) {
        self.append_step(ColumnTransformStep::new(
            input_columns,
            output_column,
            kind,
            quality,
            operation_id,
            reversible,
        ));
    }

    /// Rename the current column without rewriting historical output names.
    pub fn rename_output(&mut self, new_name: impl Into<String>) {
        let new_name = new_name.into();
        if let Some(last_step) = self.steps.last_mut() {
            last_step.output_column = new_name;
        }
    }

    /// Human-readable history for GUI panels and logs.
    pub fn feed_lines(&self) -> Vec<String> {
        let mut lines = vec![format!("roots: {}", self.root_columns.join(", "))];
        lines.extend(
            self.steps
                .iter()
                .enumerate()
                .map(|(idx, step)| format!("{:02}: {}", idx, step.feed_line())),
        );
        lines
    }

    /// Human-readable history as a multiline block.
    pub fn feed_text(&self) -> String {
        if self.steps.is_empty() {
            format!(
                "Column provenance is empty for roots: {}",
                self.root_columns.join(", ")
            )
        } else {
            self.feed_lines().join("\n")
        }
    }
}

impl ColumnTransformStep {
    pub fn new(
        input_columns: Vec<String>,
        output_column: impl Into<String>,
        kind: ColumnTransformKind,
        quality: Option<TransformQuality>,
        operation_id: Option<usize>,
        reversible: bool,
    ) -> Self {
        Self {
            input_columns,
            output_column: output_column.into(),
            kind,
            quality,
            operation_id,
            reversible,
            coverage: None,
        }
    }

    pub fn feed_line(&self) -> String {
        let quality = self
            .quality
            .as_ref()
            .map(|q| format!("\n{}", q.pretty_lines().join("\n")))
            .unwrap_or_default();

        let coverage = self.coverage.as_ref()
            .map(|coverage| format!("\n    coverage: {}", coverage.summary()))
            .unwrap_or_default();

        format!(
            "{} -> {} | input: [{}] | reversible: {} | op_id: {:?}{}",
            self.kind,
            self.output_column,
            self.input_columns.join(", "),
            self.reversible,
            self.operation_id,
            format!("{}{}", quality, coverage)
        )
    }
}

impl TransformQuality {
    pub fn computed(report: FilterQualityReport, compared_to: QualityReference) -> Self {
        Self {
            compared_to,
            report: Some(report),
            status: QualityStatus::Computed,
        }
    }

    pub fn unavailable(compared_to: QualityReference, reason: impl Into<String>) -> Self {
        Self {
            compared_to,
            report: None,
            status: QualityStatus::Failed(reason.into()),
        }
    }

    pub fn pretty_lines(&self) -> Vec<String> {
        let direction = match &self.compared_to {
            QualityReference::PreviousStep => "previous step".to_string(),
            QualityReference::RawRoot => "raw root".to_string(),
            QualityReference::NamedColumn(name) => format!("column {}", name),
        };
        let status = self.status.to_string();
        let mut lines = vec![format!("    quality: {} ({})", status, direction)];
        if let Some(report) = &self.report {
            lines.extend([
                format!(
                    "      comparing {} -> {}",
                    report.column_raw, report.column_filtered
                ),
                format!("      RMSE: {:.6} (lower is better)", report.rmse),
                format!(
                    "      NRMSE: {:.6} (lower is better)",
                    report.normalized_rmse
                ),
                format!("      Corr: {:.6} (higher is better)", report.correlation),
                format!(
                    "      Roughness 1st: {:.6} (lower is better)",
                    report.roughness_ratio_1st
                ),
                format!(
                    "      Roughness 2nd: {:.6} (lower is better)",
                    report.roughness_ratio_2nd
                ),
            ]);
        }
        lines
    }
}

impl std::fmt::Display for QualityReference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            QualityReference::PreviousStep => write!(f, "previous_step"),
            QualityReference::RawRoot => write!(f, "raw_root"),
            QualityReference::NamedColumn(name) => write!(f, "column({})", name),
        }
    }
}

impl std::fmt::Display for QualityStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            QualityStatus::Computed => write!(f, "computed"),
            QualityStatus::NotApplicable(reason) => write!(f, "not_applicable({})", reason),
            QualityStatus::Failed(reason) => write!(f, "failed({})", reason),
        }
    }
}

impl std::fmt::Display for TransformQuality {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.report {
            Some(report) => write!(
                f,
                "comparing {} vs {} [{}] | RMSE={:.6} | NRMSE={:.6} | Corr={:.6} | Roughness 1st={:.6} | Roughness 2nd={:.6}",
                report.column_raw,
                report.column_filtered,
                self.status,
                report.rmse,
                report.normalized_rmse,
                report.correlation,
                report.roughness_ratio_1st,
                report.roughness_ratio_2nd
            ),
            None => write!(f, "quality unavailable [{}]", self.status),
        }
    }
}

impl std::fmt::Display for ColumnTransformKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ColumnTransformKind::Raw { source } => write!(f, "raw({})", source),
            ColumnTransformKind::Import { source } => write!(f, "import({})", source),
            ColumnTransformKind::Binding { role, unit } => {
                write!(f, "binding(role={}, unit={})", role, unit)
            }
            ColumnTransformKind::RollingMean { window } => {
                write!(f, "rolling_mean(window={})", window)
            }
            ColumnTransformKind::SynchronizedRollingMean {
                window,
                x_column,
                common_mask,
                output_x_column,
            } => write!(
                f,
                "synchronized_rolling_mean(window={}, x={}, common_mask={}, output_x={:?})",
                window, x_column, common_mask, output_x_column
            ),
            ColumnTransformKind::Hampel {
                window,
                n_sigma,
                strategy,
            } => write!(
                f,
                "hampel(window={}, n_sigma={}, strategy={})",
                window, n_sigma, strategy
            ),
            ColumnTransformKind::SavitzkyGolay {
                window,
                poly_order,
                deriv,
                delta,
                mode,
            } => write!(
                f,
                "savitzky_golay(window={}, poly_order={}, deriv={}, delta={}, mode={})",
                window, poly_order, deriv, delta, mode
            ),
            ColumnTransformKind::Lowess { frac } => write!(f, "lowess(frac={})", frac),
            ColumnTransformKind::SplineResample {
                time_col,
                new_time_col,
                n_points,
                kind,
            } => write!(
                f,
                "spline_resample(time={}, new_time={}, n_points={}, kind={})",
                time_col, new_time_col, n_points, kind
            ),
            ColumnTransformKind::LsqSplineResample {
                time_col,
                new_time_col,
                n_points,
                degree,
                n_internal_knots,
                solver,
            } => write!(
                f,
                "lsq_spline_resample(time={}, new_time={}, n_points={}, degree={}, knots={}, solver={})",
                time_col, new_time_col, n_points, degree, n_internal_knots, solver
            ),
            ColumnTransformKind::Fitting {
                model,
                equation,
                x_col,
                y_col,
                method,
                parameters,
                r2,
                tolerance,
                max_iter,
            } => {
                let params = parameters
                    .iter()
                    .map(|(name, value)| format!("{}={:.6}", name, value))
                    .collect::<Vec<_>>()
                    .join(", ");
                write!(
                    f,
                    "fitting(model={}, equation={}, x={}, y={}, method={}, params=[{}], R2={:.6}, tol={}, max_iter={})",
                    model, equation, x_col, y_col, method, params, r2, tolerance, max_iter
                )
            }
            ColumnTransformKind::Formula {
                x_column,
                expression,
            } => write!(f, "formula(x={}, y={})", x_column, expression),
            ColumnTransformKind::FormulaFromColumns {
                variable_columns,
                expression,
            } => {
                let inputs = variable_columns
                    .iter()
                    .map(|(variable, column)| format!("{variable}={column}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                write!(f, "formula(inputs=[{inputs}], y={expression})")
            }
            ColumnTransformKind::Manual { operation, details } => match details {
                Some(details) => write!(f, "manual({}: {})", operation, details),
                None => write!(f, "manual({})", operation),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Kinetics::experimental_kinetics::math::ndarray_statistics::FilterQualityReport;

    #[test]
    fn transform_quality_display_includes_all_report_metrics() {
        let report = FilterQualityReport {
            column_raw: "raw".to_string(),
            column_filtered: "filtered".to_string(),
            roughness_ratio_1st: 0.11,
            roughness_ratio_2nd: 0.22,
            rmse: 0.33,
            normalized_rmse: 0.44,
            correlation: 0.55,
        };
        let quality = TransformQuality::computed(report, QualityReference::PreviousStep);
        let rendered = quality.to_string();

        assert!(rendered.contains("comparing raw vs filtered"));
        assert!(rendered.contains("[computed]"));
        assert!(rendered.contains("Roughness 1st=0.110000"));
        assert!(rendered.contains("Roughness 2nd=0.220000"));
        assert!(rendered.contains("RMSE=0.330000"));
        assert!(rendered.contains("NRMSE=0.440000"));
        assert!(rendered.contains("Corr=0.550000"));
    }

    #[test]
    fn transform_quality_pretty_lines_are_human_readable() {
        let report = FilterQualityReport {
            column_raw: "mass".to_string(),
            column_filtered: "sg_mass".to_string(),
            roughness_ratio_1st: 0.171947,
            roughness_ratio_2nd: 0.122832,
            rmse: 4.442255,
            normalized_rmse: 0.114925,
            correlation: 0.993374,
        };
        let quality = TransformQuality::computed(report, QualityReference::PreviousStep);
        let rendered = quality.pretty_lines().join("\n");

        assert!(rendered.contains("quality: computed (previous step)"));
        assert!(rendered.contains("comparing mass -> sg_mass"));
        assert!(rendered.contains("RMSE: 4.442255"));
        assert!(rendered.contains("NRMSE: 0.114925"));
        assert!(rendered.contains("Corr: 0.993374"));
        assert!(rendered.contains("Roughness 1st: 0.171947"));
        assert!(rendered.contains("Roughness 2nd: 0.122832"));
    }

    #[test]
    fn unavailable_quality_has_status_without_fake_numeric_values() {
        let quality = TransformQuality::unavailable(
            QualityReference::PreviousStep,
            "too few aligned samples",
        );
        let lines = quality.pretty_lines().join("\n");
        assert!(lines.contains("failed(too few aligned samples)"));
        assert!(!lines.contains("RMSE:"));
        assert!(quality.report.is_none());
    }

    #[test]
    fn renaming_current_column_preserves_historical_step_outputs() {
        let mut provenance = ColumnProvenance::raw("mass");
        provenance.push_step(
            vec!["mass".to_string()],
            "sg_mass",
            ColumnTransformKind::SavitzkyGolay {
                window: 11,
                poly_order: 3,
                deriv: 0,
                delta: 1.0,
                mode: "FirPadding".to_string(),
            },
            None,
            Some(1),
            true,
        );

        provenance.rename_output("smoothed_mass");

        assert_eq!(provenance.steps[0].output_column, "mass");
        assert_eq!(provenance.steps[1].output_column, "smoothed_mass");
        assert_eq!(provenance.steps[1].input_columns, vec!["mass"]);
    }

    #[test]
    fn coverage_distinguishes_edges_from_internal_gaps_and_roundtrips() {
        let coverage = TransformCoverage::from_values(
            &[None, Some(1.0), None, Some(3.0), None],
            &[None, Some(1.1), None, Some(2.9), None],
            0,
        );
        assert_eq!(coverage.input_valid_rows, 2);
        assert_eq!(coverage.input_missing_leading, 1);
        assert_eq!(coverage.input_missing_internal, 1);
        assert_eq!(coverage.input_missing_trailing, 1);
        assert!(coverage.summary().contains("internal 1"));

        let mut provenance = ColumnProvenance::raw("mass");
        provenance.steps[0].coverage = Some(coverage);
        let encoded = serde_json::to_value(&provenance).unwrap();
        let decoded: ColumnProvenance = serde_json::from_value(encoded.clone()).unwrap();
        assert_eq!(
            decoded.steps[0].coverage.as_ref().unwrap().input_missing_internal,
            1
        );

        let mut legacy = encoded;
        legacy["steps"][0].as_object_mut().unwrap().remove("coverage");
        let decoded_legacy: ColumnProvenance = serde_json::from_value(legacy).unwrap();
        assert!(decoded_legacy.steps[0].coverage.is_none());
    }

    #[test]
    fn coverage_counts_non_finite_samples_as_invalid() {
        let coverage = TransformCoverage::from_values(
            &[
                None,
                Some(f64::NAN),
                Some(1.0),
                Some(f64::INFINITY),
                None,
            ],
            &[Some(1.0), Some(f64::NEG_INFINITY), None],
            0,
        );

        assert_eq!(coverage.input_valid_rows, 1);
        assert_eq!(coverage.input_missing_leading, 2);
        assert_eq!(coverage.input_missing_trailing, 2);
        assert_eq!(coverage.input_non_finite_rows, 2);
        assert_eq!(coverage.output_defined_rows, 1);
        assert_eq!(coverage.output_non_finite_rows, 1);
        assert!(coverage.summary().contains("non-finite 2"));

        let encoded = serde_json::to_value(&coverage).unwrap();
        let decoded: TransformCoverage = serde_json::from_value(encoded).unwrap();
        assert_eq!(decoded.input_non_finite_rows, 2);
        assert_eq!(decoded.output_non_finite_rows, 1);
    }
}