oxiflow 0.3.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
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
//! # Module `boundary::danckwerts`
//!
//! Danckwerts boundary conditions for convection-diffusion problems (issue #35).
//!
//! ## Physical context
//!
//! Danckwerts conditions arise from a mass balance at the boundaries of a porous
//! medium column (chromatography, fixed-bed reactors, dispersion in soil). They
//! account for both convective and dispersive fluxes at the inlet and impose zero
//! dispersive flux at the outlet.
//!
//! ## Inlet — Robin condition
//!
//! At $x = 0$, the total mass flux is continuous:
//!
//! $$v \, u(0, t) - D \left.\frac{\partial u}{\partial x}\right|_{x=0}
//!   = v \, u_{\text{feed}}(t)$$
//!
//! Rearranged into an explicit assignment for the inlet node:
//!
//! $$u(0, t) = u_{\text{feed}}(t) + \frac{D}{v}
//!   \left.\frac{\partial u}{\partial x}\right|_{x=0}$$
//!
//! The feed concentration $u_{\text{feed}}(t)$ is read from [`ComputeContext`] via
//! a typed [`ContextVariable`] key — it can be constant, time-dependent, or
//! produced by any user-supplied [`ContextCalculator`].
//!
//! ## Outlet — Neumann condition
//!
//! At $x = L$, the dispersive flux vanishes:
//!
//! $$\left.\frac{\partial u}{\partial x}\right|_{x=L} = 0$$
//!
//! Applied as a first-order finite-difference approximation: the last node value
//! is set equal to its immediate predecessor, enforcing zero gradient.
//!
//! ## Souplesse
//!
//! The physical parameters $D$ (dispersion) and $v$ (velocity) are struct fields —
//! they characterise the medium and do not change during a simulation. The feed
//! concentration is deliberately read from context via a [`ContextVariable`] key,
//! allowing any dynamics: constant injection, step injection, gradient elution, or
//! a user-computed profile that itself depends on `Time` or other variables.
//!
//! ## Serialisation
//!
//! Both types implement `serde::Serialize` / `serde::Deserialize` under the `serde`
//! feature flag. All fields are either `f64` or [`ContextVariable`] — both
//! already serialisable.
//!
//! [`ComputeContext`]: crate::context::compute::ComputeContext
//! [`ContextCalculator`]: crate::context::calculator::ContextCalculator
//! [`ContextVariable`]: crate::context::variable::ContextVariable

use crate::boundary::BoundaryCondition;
use crate::context::compute::ComputeContext;
use crate::context::error::OxiflowError;
use crate::context::variable::ContextVariable;
use crate::mesh::Mesh;
use crate::model::traits::RequiresContext;
use nalgebra::DVector;

// ── DanckwertsInlet ───────────────────────────────────────────────────────────

/// Danckwerts inlet condition — Robin BC at $x = 0$.
///
/// Enforces mass-flux continuity at the column inlet:
///
/// $$u(0, t) = u_{\text{feed}}(t) + \frac{D}{v}
///   \left.\frac{\partial u}{\partial x}\right|_{x=0}$$
///
/// # Parameters
///
/// - `dispersion` — axial dispersion coefficient $D$ $[\text{m}^2 \cdot \text{s}^{-1}]$.
/// - `velocity` — interstitial velocity $v$ $[\text{m} \cdot \text{s}^{-1}]$.
/// - `feed_variable` — typed key used to read $u_{\text{feed}}(t)$ from
///   [`ComputeContext`]. Any `ContextVariable` is accepted — typically an
///   [`External`](crate::context::variable::ContextVariable::External) variable
///   produced by a user-supplied calculator (constant, step, gradient elution…).
///
/// # Requirements
///
/// Declares two required context variables:
///
/// - `ContextVariable::SpatialGradient { dimension: 0, component: None }` —
///   the nodal gradient field $\partial u / \partial x$ computed by a gradient
///   calculator registered in `SolverConfiguration`.
/// - `feed_variable` — the feed concentration $u_{\text{feed}}(t)$.
///
/// The solver validates that both are covered before the first time step.
///
/// # Serialisation
///
/// Implements `Serialize` / `Deserialize` under the `serde` feature flag.
///
/// # Examples
///
/// ```rust
/// use oxiflow::boundary::danckwerts::DanckwertsInlet;
/// use oxiflow::context::variable::ContextVariable;
/// use oxiflow::model::RequiresContext;
///
/// let feed_var = ContextVariable::External { name: "feed_concentration".into() };
/// let inlet = DanckwertsInlet::new(1e-7, 1e-3, feed_var);
/// assert_eq!(inlet.priority(), 50);
/// ```
///
/// [`ComputeContext`]: crate::context::compute::ComputeContext
#[non_exhaustive]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DanckwertsInlet {
    /// Axial dispersion coefficient $D$.
    pub dispersion: f64,
    /// Interstitial velocity $v$.
    pub velocity: f64,
    /// Context key used to read the feed concentration $u_{\text{feed}}(t)$.
    pub feed_variable: ContextVariable,
}

impl DanckwertsInlet {
    /// Creates a new `DanckwertsInlet`.
    ///
    /// # Parameters
    ///
    /// - `dispersion` — axial dispersion coefficient $D$.
    /// - `velocity`   — interstitial velocity $v$ (must be non-zero at apply time).
    /// - `feed_variable` — context key for $u_{\text{feed}}(t)$.
    pub fn new(dispersion: f64, velocity: f64, feed_variable: ContextVariable) -> Self {
        Self {
            dispersion,
            velocity,
            feed_variable,
        }
    }
}

impl RequiresContext for DanckwertsInlet {
    fn required_variables(&self) -> Vec<ContextVariable> {
        vec![
            ContextVariable::SpatialGradient {
                dimension: 0,
                component: None,
            },
            self.feed_variable.clone(),
        ]
    }

    fn priority(&self) -> u32 {
        50
    }
}

impl BoundaryCondition for DanckwertsInlet {
    fn boundary_type(&self) -> crate::boundary::BoundaryType {
        crate::boundary::BoundaryType::Robin
    }

    fn location(&self) -> Option<crate::boundary::BoundaryLocation> {
        Some(crate::boundary::BoundaryLocation::Inlet)
    }

    /// Applies the Danckwerts inlet condition to `state[0]`.
    ///
    /// Reads `∂u/∂x|_{x=0}` from the gradient field at node 0 and
    /// $u_{\text{feed}}$ from the context variable declared at construction.
    ///
    /// # Errors
    ///
    /// - [`OxiflowError::MissingCalculator`] if the gradient field or the feed
    ///   variable is absent from the context.
    /// - [`OxiflowError::TypeMismatch`] if the feed variable is not a `Scalar`.
    /// - [`OxiflowError::PreconditionFailed`] if the mesh has no nodes or if
    ///   `velocity` is zero (division by zero in $D/v$).
    fn apply(
        &self,
        state: &mut DVector<f64>,
        ctx: &ComputeContext,
        mesh: &dyn Mesh,
    ) -> Result<(), OxiflowError> {
        if mesh.n_dof() == 0 {
            return Err(OxiflowError::PreconditionFailed {
                context: "DanckwertsInlet",
                message: "mesh has no degrees of freedom".into(),
            });
        }
        if self.velocity == 0.0 {
            return Err(OxiflowError::PreconditionFailed {
                context: "DanckwertsInlet",
                message: "velocity must be non-zero".into(),
            });
        }

        let gradient = ctx.gradient(0)?;
        let du_dx_0 = gradient[0];
        let u_feed = ctx.external(self.feed_variable.clone())?.as_scalar()?;

        state[0] = u_feed + (self.dispersion / self.velocity) * du_dx_0;
        Ok(())
    }
}

// ── DanckwertsOutlet ──────────────────────────────────────────────────────────

/// Danckwerts outlet condition — Neumann BC at $x = L$.
///
/// Enforces zero dispersive flux at the column outlet:
///
/// $$\left.\frac{\partial u}{\partial x}\right|_{x=L} = 0$$
///
/// Applied as a first-order finite-difference approximation:
///
/// $$u_{n-1} = u_{n-2}$$
///
/// No context variables are required — the condition depends only on the
/// current field state and the mesh geometry.
///
/// # Serialisation
///
/// Implements `Serialize` / `Deserialize` under the `serde` feature flag.
///
/// # Examples
///
/// ```rust
/// use oxiflow::boundary::danckwerts::DanckwertsOutlet;
/// use oxiflow::model::RequiresContext;
///
/// let outlet = DanckwertsOutlet::new();
/// assert_eq!(outlet.priority(), 60);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DanckwertsOutlet;

impl DanckwertsOutlet {
    /// Creates a new `DanckwertsOutlet`.
    pub fn new() -> Self {
        Self
    }
}

impl Default for DanckwertsOutlet {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn priority(&self) -> u32 {
        60
    }
}

impl BoundaryCondition for DanckwertsOutlet {
    fn boundary_type(&self) -> crate::boundary::BoundaryType {
        crate::boundary::BoundaryType::Neumann
    }

    fn location(&self) -> Option<crate::boundary::BoundaryLocation> {
        Some(crate::boundary::BoundaryLocation::Outlet)
    }

    /// Applies the Danckwerts outlet condition.
    ///
    /// Sets `state[n-1] = state[n-2]` — first-order approximation of zero
    /// gradient at the outlet. Requires at least two nodes.
    ///
    /// # Errors
    ///
    /// - [`OxiflowError::PreconditionFailed`] if the mesh has fewer than two nodes.
    fn apply(
        &self,
        state: &mut DVector<f64>,
        _ctx: &ComputeContext,
        mesh: &dyn Mesh,
    ) -> Result<(), OxiflowError> {
        let n = mesh.n_dof();
        if n < 2 {
            return Err(OxiflowError::PreconditionFailed {
                context: "DanckwertsOutlet",
                message: "mesh must have at least 2 nodes".into(),
            });
        }
        state[n - 1] = state[n - 2];
        Ok(())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::value::ContextValue;
    use crate::mesh::structured::UniformGrid1D;
    use nalgebra::DVector;

    // ── Fixtures ──────────────────────────────────────────────────────────────

    fn feed_var() -> ContextVariable {
        ContextVariable::External {
            name: "feed_concentration".into(),
        }
    }

    fn make_inlet(d: f64, v: f64) -> DanckwertsInlet {
        DanckwertsInlet::new(d, v, feed_var())
    }

    fn make_mesh(n: usize) -> UniformGrid1D {
        UniformGrid1D::new(n, 0.0, 1.0).unwrap()
    }

    fn make_ctx_with_gradient_and_feed(gradient_at_0: f64, u_feed: f64) -> ComputeContext {
        let mut ctx = ComputeContext::new(0.0, 0.01);
        let n = 5;
        let mut grad = DVector::zeros(n);
        grad[0] = gradient_at_0;
        ctx.insert(
            ContextVariable::SpatialGradient {
                dimension: 0,
                component: None,
            },
            ContextValue::ScalarField(grad),
        );
        ctx.insert(feed_var(), ContextValue::Scalar(u_feed));
        ctx
    }

    // ── boundary_type() and location() ───────────────────────────────────────

    #[test]
    fn inlet_boundary_type_is_robin() {
        assert_eq!(
            make_inlet(1e-7, 1e-3).boundary_type(),
            crate::boundary::BoundaryType::Robin
        );
    }

    #[test]
    fn inlet_location_is_inlet() {
        assert_eq!(
            make_inlet(1e-7, 1e-3).location(),
            Some(crate::boundary::BoundaryLocation::Inlet)
        );
    }

    #[test]
    fn outlet_boundary_type_is_neumann() {
        assert_eq!(
            DanckwertsOutlet::new().boundary_type(),
            crate::boundary::BoundaryType::Neumann
        );
    }

    #[test]
    fn outlet_location_is_outlet() {
        assert_eq!(
            DanckwertsOutlet::new().location(),
            Some(crate::boundary::BoundaryLocation::Outlet)
        );
    }

    // ── RequiresContext — DanckwertsInlet ─────────────────────────────────────

    #[test]
    fn inlet_required_variables_contains_gradient_and_feed() {
        let inlet = make_inlet(1e-7, 1e-3);
        let reqs = inlet.required_variables();
        assert!(reqs.contains(&ContextVariable::SpatialGradient {
            dimension: 0,
            component: None,
        }));
        assert!(reqs.contains(&feed_var()));
        assert_eq!(reqs.len(), 2);
    }

    #[test]
    fn inlet_optional_variables_default_empty() {
        assert!(make_inlet(1e-7, 1e-3).optional_variables().is_empty());
    }

    #[test]
    fn inlet_depends_on_default_empty() {
        assert!(make_inlet(1e-7, 1e-3).depends_on().is_empty());
    }

    #[test]
    fn inlet_priority_is_50() {
        assert_eq!(make_inlet(1e-7, 1e-3).priority(), 50);
    }

    // ── RequiresContext — DanckwertsOutlet ────────────────────────────────────

    #[test]
    fn outlet_required_variables_is_empty() {
        assert!(DanckwertsOutlet::new().required_variables().is_empty());
    }

    #[test]
    fn outlet_priority_is_60() {
        assert_eq!(DanckwertsOutlet::new().priority(), 60);
    }

    // ── apply — DanckwertsInlet ───────────────────────────────────────────────

    #[test]
    fn inlet_apply_zero_gradient_equals_u_feed() {
        // When ∂u/∂x|₀ = 0, state[0] = u_feed exactly.
        let inlet = make_inlet(1e-7, 1e-3);
        let mesh = make_mesh(5);
        let ctx = make_ctx_with_gradient_and_feed(0.0, 1.0);
        let mut state = DVector::zeros(5);
        inlet.apply(&mut state, &ctx, &mesh).unwrap();
        assert!((state[0] - 1.0).abs() < 1e-12);
    }

    #[test]
    fn inlet_apply_formula_is_correct() {
        // u(0) = u_feed + (D/v) * du_dx_0
        // With D=1e-4, v=1e-2, du_dx_0=0.5, u_feed=0.8:
        // u(0) = 0.8 + (1e-4/1e-2)*0.5 = 0.8 + 0.005 = 0.805
        let inlet = make_inlet(1e-4, 1e-2);
        let mesh = make_mesh(5);
        let ctx = make_ctx_with_gradient_and_feed(0.5, 0.8);
        let mut state = DVector::zeros(5);
        inlet.apply(&mut state, &ctx, &mesh).unwrap();
        let expected = 0.8 + (1e-4 / 1e-2) * 0.5;
        assert!((state[0] - expected).abs() < 1e-12);
    }

    #[test]
    fn inlet_apply_does_not_modify_other_nodes() {
        let inlet = make_inlet(1e-7, 1e-3);
        let mesh = make_mesh(5);
        let ctx = make_ctx_with_gradient_and_feed(0.0, 1.0);
        let mut state = DVector::from_element(5, 2.0);
        inlet.apply(&mut state, &ctx, &mesh).unwrap();
        // Only node 0 is changed.
        for i in 1..5 {
            assert!((state[i] - 2.0).abs() < 1e-12, "node {i} was modified");
        }
    }

    #[test]
    fn inlet_apply_missing_gradient_returns_error() {
        let inlet = make_inlet(1e-7, 1e-3);
        let mesh = make_mesh(5);
        let mut ctx = ComputeContext::new(0.0, 0.01);
        ctx.insert(feed_var(), ContextValue::Scalar(1.0));
        // Gradient not inserted.
        let mut state = DVector::zeros(5);
        let err = inlet.apply(&mut state, &ctx, &mesh).unwrap_err();
        assert!(matches!(err, OxiflowError::MissingCalculator(_)));
    }

    #[test]
    fn inlet_apply_missing_feed_returns_error() {
        let inlet = make_inlet(1e-7, 1e-3);
        let mesh = make_mesh(5);
        let mut ctx = ComputeContext::new(0.0, 0.01);
        let grad = ContextValue::ScalarField(DVector::zeros(5));
        ctx.insert(
            ContextVariable::SpatialGradient {
                dimension: 0,
                component: None,
            },
            grad,
        );
        // Feed not inserted.
        let mut state = DVector::zeros(5);
        let err = inlet.apply(&mut state, &ctx, &mesh).unwrap_err();
        assert!(matches!(err, OxiflowError::MissingCalculator(_)));
    }

    #[test]
    fn inlet_apply_zero_velocity_returns_error() {
        let inlet = make_inlet(1e-7, 0.0);
        let mesh = make_mesh(5);
        let ctx = make_ctx_with_gradient_and_feed(0.0, 1.0);
        let mut state = DVector::zeros(5);
        let err = inlet.apply(&mut state, &ctx, &mesh).unwrap_err();
        assert!(matches!(err, OxiflowError::PreconditionFailed { .. }));
    }

    #[test]
    fn inlet_apply_empty_mesh_returns_error() {
        let inlet = make_inlet(1e-7, 1e-3);
        // UniformGrid1D requires n >= 2, so we use a DummyMesh for this edge case.
        struct EmptyMesh;
        impl Mesh for EmptyMesh {
            fn n_dof(&self) -> usize {
                0
            }
            fn coordinates(&self, _: usize) -> &[f64] {
                &[]
            }
            fn spatial_dimension(&self) -> usize {
                1
            }
            fn characteristic_length(&self) -> f64 {
                0.0
            }
        }
        impl std::fmt::Debug for EmptyMesh {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "EmptyMesh")
            }
        }
        let mesh = EmptyMesh;
        let ctx = make_ctx_with_gradient_and_feed(0.0, 1.0);
        let mut state = DVector::zeros(0);
        let err = inlet.apply(&mut state, &ctx, &mesh).unwrap_err();
        assert!(matches!(err, OxiflowError::PreconditionFailed { .. }));
    }

    // ── apply — DanckwertsOutlet ──────────────────────────────────────────────

    #[test]
    fn outlet_apply_sets_last_node_to_predecessor() {
        let mesh = make_mesh(5);
        let ctx = ComputeContext::new(0.0, 0.01);
        let mut state = DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0, 9.9]);
        DanckwertsOutlet::new()
            .apply(&mut state, &ctx, &mesh)
            .unwrap();
        assert!((state[4] - state[3]).abs() < 1e-12);
        assert!((state[4] - 4.0).abs() < 1e-12);
    }

    #[test]
    fn outlet_apply_does_not_modify_other_nodes() {
        let mesh = make_mesh(5);
        let ctx = ComputeContext::new(0.0, 0.01);
        let values = vec![1.0, 2.0, 3.0, 4.0, 9.9];
        let mut state = DVector::from_vec(values.clone());
        DanckwertsOutlet::new()
            .apply(&mut state, &ctx, &mesh)
            .unwrap();
        for i in 0..4 {
            assert!(
                (state[i] - values[i]).abs() < 1e-12,
                "node {i} was modified"
            );
        }
    }

    #[test]
    fn outlet_apply_two_node_mesh() {
        let mesh = make_mesh(2);
        let ctx = ComputeContext::new(0.0, 0.01);
        let mut state = DVector::from_vec(vec![3.0, 0.0]);
        DanckwertsOutlet::new()
            .apply(&mut state, &ctx, &mesh)
            .unwrap();
        assert!((state[1] - 3.0).abs() < 1e-12);
    }

    #[test]
    fn outlet_apply_single_node_returns_error() {
        struct SingleMesh;
        impl Mesh for SingleMesh {
            fn n_dof(&self) -> usize {
                1
            }
            fn coordinates(&self, _: usize) -> &[f64] {
                &[0.0]
            }
            fn spatial_dimension(&self) -> usize {
                1
            }
            fn characteristic_length(&self) -> f64 {
                0.0
            }
        }
        impl std::fmt::Debug for SingleMesh {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "SingleMesh")
            }
        }
        let mesh = SingleMesh;
        let ctx = ComputeContext::new(0.0, 0.01);
        let mut state = DVector::from_element(1, 1.0);
        let err = DanckwertsOutlet::new()
            .apply(&mut state, &ctx, &mesh)
            .unwrap_err();
        assert!(matches!(err, OxiflowError::PreconditionFailed { .. }));
    }

    // ── Object safety ─────────────────────────────────────────────────────────

    #[test]
    fn both_bcs_are_object_safe() {
        let bcs: Vec<Box<dyn BoundaryCondition>> = vec![
            Box::new(make_inlet(1e-7, 1e-3)),
            Box::new(DanckwertsOutlet::new()),
        ];
        assert_eq!(bcs.len(), 2);
    }

    #[test]
    fn debug_inlet_is_non_empty() {
        let s = format!("{:?}", make_inlet(1e-7, 1e-3));
        assert!(s.contains("DanckwertsInlet"));
        assert!(s.contains("dispersion"));
    }

    #[test]
    fn debug_outlet_is_non_empty() {
        assert!(!format!("{:?}", DanckwertsOutlet::new()).is_empty());
    }
}