oxiflow 0.6.0

Generic PDE solving engine for transport, reaction and diffusion phenomena (∂u/∂t + ∇·F = S)
Documentation
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
//! # Module `context::calculators::tabulated`
//!
//! Tabulated time-dependent data calculator with interpolation.

use crate::context::calculator::ContextCalculator;
use crate::context::compute::ComputeContext;
use crate::context::error::OxiflowError;
use crate::context::value::ContextValue;
use crate::context::variable::ContextVariable;
use crate::model::traits::RequiresContext;

// ── Interpolation ─────────────────────────────────────────────────────────────

/// Interpolation strategy for [`ExternalTabulated`].
///
/// # Variants
///
/// - `Linear` — piecewise linear (1st-order accurate). Exact for linear f(t).
///
/// # Reserved
///
/// `PiecewiseCubic` (natural cubic spline, 4th-order accurate) is planned for
/// J5 (v0.7.0) and requires the `spline` feature flag.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Interpolation {
    /// Piecewise linear interpolation: `f(t) = f_i + (f_{i+1} − f_i) · (t − t_i) / (t_{i+1} − t_i)`.
    Linear,
    // PiecewiseCubic — RESERVED J5 (v0.7.0), requires feature `spline`.
}

// ── ExternalTabulated ─────────────────────────────────────────────────────────

/// Provides a time-dependent scalar from tabulated (t, value) data.
///
/// Data points must be sorted by ascending `t`. The calculator interpolates at
/// `ctx.time()` using the chosen [`Interpolation`] strategy.
///
/// Outside the data range the calculator clamps to the nearest endpoint value
/// rather than extrapolating, and emits an `ExternalData` error if `data` is
/// empty or has only one point (interpolation is undefined).
///
/// # Examples
///
/// ```rust
/// use std::borrow::Cow;
/// use oxiflow::context::calculator::ContextCalculator;
/// use oxiflow::context::calculators::{ExternalTabulated, Interpolation};
/// use oxiflow::context::compute::ComputeContext;
/// use oxiflow::context::value::ContextValue;
/// use oxiflow::context::variable::ContextVariable;
///
/// let var = ContextVariable::External { name: Cow::Borrowed("feed_conc") };
/// let data = vec![(0.0, 1.0), (1.0, 2.0), (2.0, 1.5)];
/// let calc = ExternalTabulated::new(var, data, Interpolation::Linear).unwrap();
///
/// // Interpolate at t = 0.5  →  1.0 + (2.0 − 1.0) × 0.5 = 1.5
/// let ctx = ComputeContext::new(0.5, 0.01);
/// let val = calc.compute(&ContextValue::Scalar(0.0), &ctx).unwrap();
/// assert!((val.as_scalar().unwrap() - 1.5).abs() < 1e-10);
/// ```
#[derive(Debug)]
pub struct ExternalTabulated {
    variable: ContextVariable,
    /// (t, value) pairs, sorted by t ascending.
    data: Vec<(f64, f64)>,
    interpolation: Interpolation,
}

impl ExternalTabulated {
    /// Loads tabulated data from an HDF5 file (DD-027, issue #105).
    ///
    /// `variable` must be [`ContextVariable::External`] — its `name` is used
    /// as the HDF5 group to read from. The group must contain two 1D `f64`
    /// datasets, `t` and `value`, of equal length. Delegates to [`Self::new`]
    /// for validation (≥ 2 points, strictly ascending `t`) — no duplicated
    /// logic.
    ///
    /// Requires the `hdf5` feature.
    ///
    /// # Errors
    ///
    /// Returns `Err(OxiflowError::ExternalData)` if `variable` is not
    /// `ContextVariable::External`. Returns `Err(OxiflowError::Persistence)`
    /// if the file/group/dataset cannot be opened or read, or if `t` and
    /// `value` have different lengths. Returns `Err(OxiflowError::ExternalData)`
    /// (via [`Self::new`]) if the loaded data has fewer than 2 points or is
    /// not sorted by ascending `t`.
    #[cfg(feature = "hdf5")]
    pub fn from_hdf5(
        path: &std::path::Path,
        variable: ContextVariable,
        interpolation: Interpolation,
    ) -> Result<Self, OxiflowError> {
        let group_name = match &variable {
            ContextVariable::External { name } => name.as_ref(),
            _ => {
                return Err(OxiflowError::ExternalData(
                    "ExternalTabulated::from_hdf5 requires a ContextVariable::External \
                     (its `name` is used as the HDF5 group to read)"
                        .to_string(),
                ));
            }
        };

        let file = hdf5::File::open(path)
            .map_err(|e| OxiflowError::Persistence(format!("cannot open {path:?}: {e}")))?;
        let group = file.group(group_name).map_err(|e| {
            OxiflowError::Persistence(format!("no group {group_name:?} in {path:?}: {e}"))
        })?;

        let read_column = |name: &str| -> Result<Vec<f64>, OxiflowError> {
            let ds = group.dataset(name).map_err(|e| {
                OxiflowError::Persistence(format!(
                    "no dataset {name:?} in group {group_name:?} ({path:?}): {e}"
                ))
            })?;
            let arr = ds.read_1d::<f64>().map_err(|e| {
                OxiflowError::Persistence(format!(
                    "cannot read dataset {name:?} in group {group_name:?} ({path:?}): {e}"
                ))
            })?;
            Ok(arr.iter().copied().collect())
        };

        let t = read_column("t")?;
        let value = read_column("value")?;

        if t.len() != value.len() {
            return Err(OxiflowError::Persistence(format!(
                "group {group_name:?} ({path:?}): 't' has {} points, 'value' has {}\
                 must match",
                t.len(),
                value.len()
            )));
        }

        let data: Vec<(f64, f64)> = t.into_iter().zip(value).collect();
        Self::new(variable, data, interpolation)
    }

    /// Creates a new tabulated external calculator.
    ///
    /// # Arguments
    ///
    /// - `variable` — the `ContextVariable` this calculator provides.
    /// - `data` — `(t, value)` pairs; must be sorted by ascending `t` and
    ///   contain at least 2 points.
    /// - `interpolation` — interpolation strategy.
    ///
    /// # Errors
    ///
    /// Returns `Err(OxiflowError::ExternalData)` if `data` has fewer than 2 points
    /// or is not sorted by ascending `t`.
    pub fn new(
        variable: ContextVariable,
        data: Vec<(f64, f64)>,
        interpolation: Interpolation,
    ) -> Result<Self, OxiflowError> {
        if data.len() < 2 {
            return Err(OxiflowError::ExternalData(format!(
                "ExternalTabulated requires at least 2 data points, got {}",
                data.len()
            )));
        }

        // Verify ascending t order.
        for w in data.windows(2) {
            if w[0].0 >= w[1].0 {
                return Err(OxiflowError::ExternalData(format!(
                    "ExternalTabulated data must be sorted by ascending t: \
                     t[i]={} >= t[i+1]={}",
                    w[0].0, w[1].0
                )));
            }
        }

        Ok(Self {
            variable,
            data,
            interpolation,
        })
    }

    /// Interpolates the tabulated data at time `t`.
    ///
    /// Clamps to endpoint values outside the data range.
    fn interpolate(&self, t: f64) -> f64 {
        let (t_min, v_min) = self.data[0];
        let (t_max, v_max) = *self.data.last().unwrap();

        // Clamp outside range.
        if t <= t_min {
            return v_min;
        }
        if t >= t_max {
            return v_max;
        }

        // Binary search for the bracketing interval.
        let idx = self
            .data
            .partition_point(|(ti, _)| *ti <= t)
            .saturating_sub(1);

        let (t0, v0) = self.data[idx];
        let (t1, v1) = self.data[idx + 1];

        match self.interpolation {
            Interpolation::Linear => v0 + (v1 - v0) * (t - t0) / (t1 - t0),
            // J5+: PiecewiseCubic will be added here.
            #[allow(unreachable_patterns)]
            _ => v0, // unreachable at J2
        }
    }
}

impl RequiresContext for ExternalTabulated {
    fn required_variables(&self) -> Vec<ContextVariable> {
        vec![]
    }

    // External data runs before derived quantities (priority 100) but after
    // time built-ins (priority 0).
    fn priority(&self) -> u32 {
        50
    }
}

impl ContextCalculator for ExternalTabulated {
    fn provides(&self) -> ContextVariable {
        self.variable.clone()
    }

    fn compute(
        &self,
        _state: &ContextValue,
        ctx: &ComputeContext,
    ) -> Result<ContextValue, OxiflowError> {
        let value = self.interpolate(ctx.time());
        Ok(ContextValue::Scalar(value))
    }

    fn name(&self) -> &str {
        "external_tabulated (built-in)"
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::*;

    fn var() -> ContextVariable {
        ContextVariable::External {
            name: Cow::Borrowed("feed"),
        }
    }

    fn linear_data() -> Vec<(f64, f64)> {
        vec![(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]
    }

    fn calc(data: Vec<(f64, f64)>) -> ExternalTabulated {
        ExternalTabulated::new(var(), data, Interpolation::Linear).unwrap()
    }

    fn ctx(t: f64) -> ComputeContext {
        ComputeContext::new(t, 0.01)
    }

    // ── constructor ───────────────────────────────────────────────────────────

    #[test]
    fn new_succeeds_with_valid_data() {
        assert!(ExternalTabulated::new(var(), linear_data(), Interpolation::Linear).is_ok());
    }

    #[test]
    fn new_fails_with_single_point() {
        let result = ExternalTabulated::new(var(), vec![(0.0, 1.0)], Interpolation::Linear);
        assert!(matches!(result, Err(OxiflowError::ExternalData(_))));
    }

    #[test]
    fn new_fails_with_empty_data() {
        let result = ExternalTabulated::new(var(), vec![], Interpolation::Linear);
        assert!(matches!(result, Err(OxiflowError::ExternalData(_))));
    }

    #[test]
    fn new_fails_when_not_sorted() {
        let result =
            ExternalTabulated::new(var(), vec![(1.0, 1.0), (0.0, 0.0)], Interpolation::Linear);
        assert!(matches!(result, Err(OxiflowError::ExternalData(_))));
    }

    #[test]
    fn new_fails_on_duplicate_t() {
        let result = ExternalTabulated::new(
            var(),
            vec![(0.0, 0.0), (0.0, 1.0), (1.0, 2.0)],
            Interpolation::Linear,
        );
        assert!(matches!(result, Err(OxiflowError::ExternalData(_))));
    }

    // ── provides / priority ───────────────────────────────────────────────────

    #[test]
    fn provides_configured_variable() {
        let v = var();
        let c = calc(linear_data());
        assert_eq!(c.provides(), v);
    }

    #[test]
    fn priority_is_fifty() {
        assert_eq!(calc(linear_data()).priority(), 50);
    }

    // ── linear interpolation ──────────────────────────────────────────────────

    #[test]
    fn interpolates_at_midpoint() {
        // data: (0,0), (1,1), (2,2)  →  at t=0.5: value = 0.5
        let c = calc(linear_data());
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(0.5)).unwrap();
        assert!((val.as_scalar().unwrap() - 0.5).abs() < 1e-10);
    }

    #[test]
    fn interpolates_exactly_at_knot() {
        let c = calc(linear_data());
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(1.0)).unwrap();
        assert!((val.as_scalar().unwrap() - 1.0).abs() < 1e-10);
    }

    #[test]
    fn non_linear_interpolation_between_knots() {
        // data: (0, 1.0), (1, 2.0), (2, 1.5)
        let data = vec![(0.0, 1.0), (1.0, 2.0), (2.0, 1.5)];
        let c = calc(data);
        // t = 1.5 → between (1, 2.0) and (2, 1.5) → 2.0 + (1.5 - 2.0) * 0.5 = 1.75
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(1.5)).unwrap();
        assert!((val.as_scalar().unwrap() - 1.75).abs() < 1e-10);
    }

    // ── clamping ──────────────────────────────────────────────────────────────

    #[test]
    fn clamps_to_first_value_before_range() {
        let c = calc(linear_data());
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(-1.0)).unwrap();
        assert_eq!(val.as_scalar().unwrap(), 0.0);
    }

    #[test]
    fn clamps_to_last_value_after_range() {
        let c = calc(linear_data());
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(5.0)).unwrap();
        assert_eq!(val.as_scalar().unwrap(), 2.0);
    }

    #[test]
    fn clamps_exactly_at_lower_bound() {
        let c = calc(linear_data());
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(0.0)).unwrap();
        assert_eq!(val.as_scalar().unwrap(), 0.0);
    }

    #[test]
    fn clamps_exactly_at_upper_bound() {
        let c = calc(linear_data());
        let val = c.compute(&ContextValue::Scalar(0.0), &ctx(2.0)).unwrap();
        assert_eq!(val.as_scalar().unwrap(), 2.0);
    }

    // ── object safety ─────────────────────────────────────────────────────────

    #[test]
    fn is_object_safe() {
        let c: Box<dyn ContextCalculator> = Box::new(calc(linear_data()));
        assert_eq!(c.provides(), var());
    }

    // ── from_hdf5 ─────────────────────────────────────────────────────────────

    #[cfg(feature = "hdf5")]
    #[test]
    fn from_hdf5_round_trip() {
        let path = std::env::temp_dir().join("oxiflow_test_from_hdf5_round_trip.h5");

        // Write a fixture matching the schema from_hdf5 expects: one group
        // named after the variable, two 1D f64 datasets "t"/"value".
        {
            let file = hdf5::File::create(&path).unwrap();
            let group = file.create_group("feed_conc").unwrap();
            group
                .new_dataset::<f64>()
                .shape(3)
                .create("t")
                .unwrap()
                .write_raw(&[0.0, 1.0, 2.0])
                .unwrap();
            group
                .new_dataset::<f64>()
                .shape(3)
                .create("value")
                .unwrap()
                .write_raw(&[1.0, 2.0, 1.5])
                .unwrap();
        }

        let variable = ContextVariable::External {
            name: "feed_conc".into(),
        };
        let calc = ExternalTabulated::from_hdf5(&path, variable, Interpolation::Linear).unwrap();

        // Same fixture as the module-level rustdoc example (t=0.5 -> 1.5).
        let val = calc.compute(&ContextValue::Scalar(0.0), &ctx(0.5)).unwrap();
        assert!((val.as_scalar().unwrap() - 1.5).abs() < 1e-10);

        std::fs::remove_file(&path).ok();
    }

    #[cfg(feature = "hdf5")]
    #[test]
    fn from_hdf5_rejects_non_external_variable() {
        let path = std::env::temp_dir().join("oxiflow_test_from_hdf5_wrong_variant.h5");
        let result =
            ExternalTabulated::from_hdf5(&path, ContextVariable::Time, Interpolation::Linear);
        assert!(matches!(result, Err(OxiflowError::ExternalData(_))));
    }

    #[cfg(feature = "hdf5")]
    #[test]
    fn from_hdf5_missing_file_is_persistence_error() {
        let path = std::path::PathBuf::from("/nonexistent/path/data.h5");
        let variable = ContextVariable::External {
            name: "feed_conc".into(),
        };
        let result = ExternalTabulated::from_hdf5(&path, variable, Interpolation::Linear);
        assert!(matches!(result, Err(OxiflowError::Persistence(_))));
    }
}