chrom-rs 0.2.0

Liquid chromatography simulator — Langmuir isotherms, numerical solvers (Euler, RK4), CLI and config-file interface
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
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
//! n-dimensional domain boundaries with time convention
//!
//! # Design Philosophy
//!
//! Instead of enumerating 1D, 2D, 3D separately, we use a generic
//! structure that works for n dimensions:
//!
//! - `Vec<DimensionBoundary>`: boundaries for each dimension
//! - `TimeAxisConvention`: which dimension (if any) is temporal
//!
//! This allows arbitrary dimensional problems without artificial limits.

use crate::physics::PhysicalState;
use serde::{Deserialize, Serialize};
use std::fmt;

// =================================================================================================
// Domain Boundaries
// =================================================================================================

/// n-dimensional domain boundaries
///
/// # Design
///
/// Stores boundary states directly as vectors of PhysicalState,
/// without typing them as Dirichlet/Neumann/etc.
///
/// - Spatial dimension: \[left_state, right_state\]
/// - Temporal dimension: \[initial_state\] or \[initial, final\]
///
/// The solver interprets how to use these states.
///
/// ```rust
/// # use chrom_rs::solver::DomainBoundaries;
/// # use chrom_rs::solver::Scenario;
/// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
/// # use nalgebra::DVector;
/// # let initial_state = PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(DVector::from_vec(vec![1.0])));
/// // ODE: temporal only
/// let boundaries = DomainBoundaries::temporal(initial_state);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DomainBoundaries {
    /// Boundaries for each dimension
    pub dimensions: Vec<DimensionBoundary>,

    /// Convention for identifying time dimensions
    pub convention: TimeAxisConvention,
}

impl DomainBoundaries {
    /// Create without axis convention
    ///
    /// default axis convention is set to default ```rust TimeAxisConvention::Last```
    pub fn new(dimensions: Vec<DimensionBoundary>) -> Self {
        Self {
            dimensions,
            convention: TimeAxisConvention::Last,
        }
    }

    /// Create with defined axis convention
    ///
    ///
    pub fn create(
        dimensions: Vec<DimensionBoundary>,
        convention: Option<TimeAxisConvention>,
    ) -> Self {
        Self {
            dimensions,
            convention: convention.unwrap_or(TimeAxisConvention::Last),
        }
    }

    // ====================================== Factory methods ======================================

    /// Create temporal-only domain (ODE)
    ///
    /// Creates a 1D domain with time as the only dimension.
    /// Convention is automatically set to First.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use chrom_rs::solver::DomainBoundaries;
    /// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
    /// # use nalgebra::DVector;
    /// let initial = PhysicalState::new(
    ///     PhysicalQuantity::Concentration,
    ///     PhysicalData::Vector(DVector::from_vec(vec![1.0]))
    /// );
    ///
    /// let boundaries = DomainBoundaries::temporal(initial);
    ///
    /// assert_eq!(boundaries.ndim(), 1);
    /// assert!(boundaries.is_time_dependent());
    /// ```
    pub fn temporal(initial: PhysicalState) -> Self {
        Self::new(vec![DimensionBoundary::new("t", vec![initial])])
    }

    /// Create n-dimensional spatial domain (steady-state)
    ///
    /// Creates a spatial domain with n dimensions, where each dimension
    /// has left and right boundary states. No time dimension is included.
    ///
    /// # Arguments
    ///
    /// * `names` - Names for each spatial dimension (e.g., `&["x", "y", "z"]`)
    /// * `begins` - Boundary states at lower bounds (left/bottom/front)
    /// * `ends` - Boundary states at upper bounds (right/top/back)
    ///
    /// # Panics
    ///
    /// Panics if `names`, `begins`, and `ends` have different lengths.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use chrom_rs::solver::DomainBoundaries;
    /// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
    /// # use nalgebra::DVector;
    /// # let state = || PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(DVector::from_vec(vec![1.0])));
    /// // 2D spatial domain
    /// let boundaries = DomainBoundaries::spatial(
    ///     &["x", "y"],
    ///     vec![state(), state()],
    ///     vec![state(), state()]
    /// );
    ///
    /// assert_eq!(boundaries.ndim(), 2);
    /// assert!(!boundaries.is_time_dependent());
    /// ```
    ///
    /// ```rust
    /// # use chrom_rs::solver::DomainBoundaries;
    /// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
    /// # use nalgebra::DVector;
    /// # let state = || PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(DVector::from_vec(vec![1.0])));
    /// // 3D spatial domain
    /// let boundaries = DomainBoundaries::spatial(
    ///     &["x", "y", "z"],
    ///     vec![state(), state(), state()],
    ///     vec![state(), state(), state()]
    /// );
    ///
    /// assert_eq!(boundaries.ndim(), 3);
    /// ```
    pub fn spatial(names: &[&str], begins: Vec<PhysicalState>, ends: Vec<PhysicalState>) -> Self {
        assert_eq!(names.len(), begins.len());
        assert_eq!(names.len(), ends.len());

        let dimensions: Vec<_> = names
            .iter()
            .zip(begins.iter().zip(ends.iter()))
            .map(|(name, (begin, end))| {
                DimensionBoundary::new(*name, vec![begin.clone(), end.clone()])
            })
            .collect();

        Self::create(dimensions, Some(TimeAxisConvention::None))
    }

    /// Create n-dimensional spatial + temporal domain
    ///
    /// Creates a mixed domain with n spatial dimensions and one temporal dimension.
    /// The temporal dimension is placed last (convention: Last).
    ///
    /// # Arguments
    ///
    /// * `names` - Names for spatial dimensions (e.g., `&["x", "y", "z"]`)
    /// * `begins` - Boundary states at spatial lower bounds
    /// * `ends` - Boundary states at spatial upper bounds
    /// * `initial` - Initial condition (temporal boundary at t=0)
    ///
    /// # Panics
    ///
    /// Panics if `names`, `begins`, and `ends` have different lengths.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use chrom_rs::solver::DomainBoundaries;
    /// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
    /// # use nalgebra::DVector;
    /// # let state = || PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(DVector::from_vec(vec![1.0])));
    /// // 1D space + time
    /// let boundaries = DomainBoundaries::mixed(
    ///     &["x"],
    ///     vec![state()],
    ///     vec![state()],
    ///     state()
    /// );
    ///
    /// assert_eq!(boundaries.ndim(), 2);
    /// assert!(boundaries.is_time_dependent());
    /// ```
    ///
    /// ```rust
    /// # use chrom_rs::solver::DomainBoundaries;
    /// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
    /// # use nalgebra::DVector;
    /// # let state = || PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(DVector::from_vec(vec![1.0])));
    /// // 3D space + time
    /// let boundaries = DomainBoundaries::mixed(
    ///     &["x", "y", "z"],
    ///     vec![state(), state(), state()],
    ///     vec![state(), state(), state()],
    ///     state()
    /// );
    ///
    /// assert_eq!(boundaries.ndim(), 4);
    /// ```
    pub fn mixed(
        names: &[&str],
        begins: Vec<PhysicalState>,
        ends: Vec<PhysicalState>,
        initial: PhysicalState,
    ) -> Self {
        assert_eq!(names.len(), begins.len());
        assert_eq!(names.len(), ends.len());

        let mut dimensions: Vec<_> = names
            .iter()
            .zip(begins.iter().zip(ends.iter()))
            .map(|(name, (begin, end))| {
                DimensionBoundary::new(*name, vec![begin.clone(), end.clone()])
            })
            .collect();

        dimensions.push(DimensionBoundary::new("t", vec![initial]));

        Self::create(dimensions, Some(TimeAxisConvention::Last))
    }

    // ===================================== Query methods =========================================

    /// Total number of dimensions
    pub fn ndim(&self) -> usize {
        self.dimensions.len()
    }

    /// Total number of spatial dimensions
    pub fn sdim(&self) -> usize {
        match self.convention {
            TimeAxisConvention::None => self.ndim(),
            _ => self.ndim() - 1,
        }
    }

    /// Check time dependant equation
    pub fn is_time_dependent(&self) -> bool {
        self.convention != TimeAxisConvention::None
    }

    /// Get time dimension index
    pub fn time_index(&self) -> Option<usize> {
        match self.convention {
            TimeAxisConvention::Last => Some(self.ndim() - 1),
            TimeAxisConvention::First => Some(0),
            TimeAxisConvention::None => None,
            TimeAxisConvention::Index(i) => Some(i),
        }
    }

    /// Get temporal boundary
    pub fn time_boundary(&self) -> Option<&DimensionBoundary> {
        self.time_index()
            .and_then(|index| self.dimensions.get(index))
    }

    /// Ges initial condition as the first physical state of temporal boundary
    pub fn initial_condition(&self) -> Option<&PhysicalState> {
        self.time_boundary()
            .and_then(|boundary| boundary.states.first())
    }

    /// Get spatial boundaries
    pub fn spatial_boundaries(&self) -> Vec<&DimensionBoundary> {
        let excl_idx = self.time_index();

        self.dimensions
            .iter()
            .enumerate()
            .filter(|(index, _)| Some(*index) != excl_idx)
            .map(|(_, dimension)| dimension)
            .collect()
    }

    /// Get dimension by its name
    pub fn get_boundary(&self, name: &str) -> Option<&DimensionBoundary> {
        self.dimensions
            .iter()
            .find(|boundary| boundary.name == name)
    }

    /// Validate the object contents
    pub fn validate(&self) -> Result<(), String> {
        // Validate it is not empty
        if self.dimensions.is_empty() {
            return Err("Dimension boundaries cannot be empty.".into());
        }

        // Validate each dimension
        for dimension in &self.dimensions {
            dimension.validate()?;
        }

        // Check unicity of dimension's name

        let names: Vec<&str> = self.dimensions.iter().map(|d| d.name.as_str()).collect();

        let unicity: std::collections::HashSet<&str> = names.iter().copied().collect();

        if unicity.len() != names.len() {
            return Err("It is impossible to store two dimensions with the same name.".into());
        }

        Ok(())
    }
}

impl Default for DomainBoundaries {
    fn default() -> Self {
        Self {
            dimensions: Vec::new(),
            convention: TimeAxisConvention::None,
        }
    }
}

// =================================================================================================
// Dimension Boundary
// =================================================================================================

/// Boundary for one dimension (variable)
///
/// # Design
///
/// Just stores boundary states - no typing as Spatial/Temporal.
/// TimeAxisConvention in DomainBoundaries identifies which is time.
///
/// # Convention
///
/// - 1 state: temporal dimension (initial condition)
/// - 2 states: spatial dimension (left, right boundaries)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DimensionBoundary {
    /// Dimension name
    pub name: String,

    /// Physical states at boundaries
    pub states: Vec<PhysicalState>,
}

impl DimensionBoundary {
    /// Generic constructor
    pub fn new(name: impl Into<String>, states: Vec<PhysicalState>) -> Self {
        Self {
            name: name.into(),
            states,
        }
    }

    /// Get first boundary state
    pub fn first(&self) -> Option<&PhysicalState> {
        Some(&self.states[0])
    }

    /// Get last boundary state
    pub fn last(&self) -> Option<&PhysicalState> {
        Some(&self.states[self.states.len() - 1])
    }

    /// Get size of boundaries
    pub fn size(&self) -> usize {
        self.states.len()
    }

    /// Verify if there are no boundaries
    pub fn is_empty(&self) -> bool {
        self.states.is_empty()
    }

    /// Validate dimension
    pub fn validate(&self) -> Result<(), String> {
        if self.is_empty() {
            return Err(format!(
                "Dimensions '{}' must have at least one boundary state",
                self.name
            ));
        }

        Ok(())
    }
}

// =================================================================================================
// Time Axis Convention
// =================================================================================================

/// Convention for identifying registration of time variable
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum TimeAxisConvention {
    /// No time dimension (steady-state)
    None,

    /// First dimension is time (t, x, y, z, ...)
    First,

    /// Last dimension is time (x, y, z,..., t)
    Last,

    /// Explicit index: dimension 'u' is time dimension
    Index(usize),
}

impl fmt::Display for TimeAxisConvention {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TimeAxisConvention::None => write!(f, "None"),
            TimeAxisConvention::First => write!(f, "First"),
            TimeAxisConvention::Last => write!(f, "Last"),
            TimeAxisConvention::Index(u) => write!(f, "Index ({})", u),
        }
    }
}

// =================================================================================================
// Tests
// =================================================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::physics::{PhysicalData, PhysicalQuantity, PhysicalState};
    use nalgebra::DVector;

    // =================================== Time Axis Convention ===================================

    #[test]
    fn test_axis_convention_first() {
        let first = TimeAxisConvention::First;

        assert_eq!(format!("{}", first), "First");
    }

    #[test]
    fn test_axis_convention_last() {
        let last = TimeAxisConvention::Last;
        assert_eq!(format!("{}", last), "Last");
    }

    #[test]
    fn test_axis_convention_index() {
        let first = TimeAxisConvention::Index(10);
        assert_eq!(format!("{}", first), "Index (10)");
    }

    #[test]
    fn test_axis_convention_none() {
        let first = TimeAxisConvention::None;
        assert_eq!(format!("{}", first), "None");
    }

    // ==================================== Dimension Boundary ====================================

    #[test]
    fn test_dimension_boundary_new() {
        let dimension = DimensionBoundary::new(
            "volume",
            vec![PhysicalState::new(
                PhysicalQuantity::Concentration,
                PhysicalData::Scalar(0.6),
            )],
        );

        assert_eq!(dimension.name, "volume");
        assert_eq!(dimension.states.len(), 1);
        assert_eq!(dimension.size(), 1)
    }

    #[test]
    fn test_dimension_boundary_content() {
        let dimension = DimensionBoundary::new(
            "volume",
            vec![PhysicalState::new(
                PhysicalQuantity::Concentration,
                PhysicalData::Vector(DVector::from_row_slice(&[1., 2., 3., 4.])),
            )],
        );

        assert!(
            dimension
                .first()
                .unwrap()
                .available_quantities()
                .contains(&PhysicalQuantity::Concentration)
        );

        let data = dimension
            .first()
            .unwrap()
            .get(PhysicalQuantity::Concentration)
            .unwrap();

        assert_eq!(data.as_vector()[0], 1.0);
        assert_eq!(data.as_vector()[2], 3.0);
    }

    // ===================================== Domain Boundary =====================================

    #[test]
    #[should_panic(expected = "out of bounds")]
    fn test_dimension_boundary_first_last_on_empty() {
        let dim = DimensionBoundary::new("x", vec![]);
        assert!(dim.first().is_none());
        assert!(dim.last().is_none());
    }

    #[test]
    fn test_dimension_boundary_first_last_single() {
        let state = PhysicalState::empty();
        let dim = DimensionBoundary::new("t", vec![state.clone()]);

        // Single element: first and last point to the same state.
        assert!(dim.first().is_some());
        assert!(dim.last().is_some());
    }

    #[test]
    fn test_dimension_boundary_first_last_two() {
        let left = PhysicalState::empty();
        let right = PhysicalState::empty();
        let dim = DimensionBoundary::new("x", vec![left, right]);

        assert!(dim.first().is_some());
        assert!(dim.last().is_some());
        assert_eq!(dim.size(), 2);
    }
    #[test]
    fn test_temporal_only() {
        let initial = PhysicalState::empty();
        let boundary = DomainBoundaries::temporal(initial);

        assert_eq!(boundary.ndim(), 1);
        assert_eq!(boundary.sdim(), 0);
        assert!(boundary.is_time_dependent());
        assert_eq!(boundary.convention, TimeAxisConvention::Last);
    }

    #[test]
    fn test_spatial_only() {
        let domain = DomainBoundaries::spatial(
            &["x", "y", "z"],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
        );

        assert_eq!(domain.ndim(), 3);
        assert_eq!(domain.sdim(), 3);
        assert!(!domain.is_time_dependent());
        assert_eq!(domain.convention, TimeAxisConvention::None);
    }

    #[test]
    fn test_mixed() {
        let initial = PhysicalState::new(
            PhysicalQuantity::Concentration,
            PhysicalData::Vector(DVector::from_vec(vec![2.0])),
        );

        let boundary = DomainBoundaries::mixed(
            &["x", "y", "z"],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            initial,
        );

        assert_eq!(boundary.ndim(), 4);
        assert_eq!(boundary.sdim(), 3);
        assert!(boundary.is_time_dependent());
        assert_eq!(boundary.convention, TimeAxisConvention::Last);
        assert_eq!(boundary.time_index(), Some(3));

        assert!(boundary.dimensions[0].name.contains("x"));
        assert!(boundary.dimensions[1].name.contains("y"));
        assert!(boundary.dimensions[2].name.contains("z"));
        assert!(boundary.dimensions[3].name.contains("t"));
    }

    #[test]
    fn test_mixed_spatial() {
        let initial = PhysicalState::new(
            PhysicalQuantity::Concentration,
            PhysicalData::Vector(DVector::from_vec(vec![2.0])),
        );

        let boundary = DomainBoundaries::mixed(
            &["x", "y", "z"],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            initial,
        );

        let spatials = boundary.spatial_boundaries();

        assert_eq!(spatials.len(), 3);
        assert_eq!(spatials[0].name, "x");
        assert_eq!(spatials[1].name, "y");
        assert_eq!(spatials[2].name, "z");
    }

    #[test]
    fn test_mixed_temporal() {
        let initial = PhysicalState::new(
            PhysicalQuantity::Concentration,
            PhysicalData::Vector(DVector::from_vec(vec![2.0])),
        );

        let boundary = DomainBoundaries::mixed(
            &["x", "y", "z"],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            vec![
                PhysicalState::empty(),
                PhysicalState::empty(),
                PhysicalState::empty(),
            ],
            initial,
        );

        let temporal = boundary.time_boundary();

        assert_eq!(temporal.is_some(), true);
        assert_eq!(temporal.unwrap().name, "t");
    }

    // Validation tests
    #[test]
    fn test_empty_boundary() {
        let false_boundary = DomainBoundaries::new(vec![]);
        let result = false_boundary.validate();

        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap(),
            "Dimension boundaries cannot be empty."
        );
    }

    #[test]
    fn test_duplicate_dimensions() {
        let false_boundary = DomainBoundaries {
            dimensions: vec![
                DimensionBoundary::new("x", vec![PhysicalState::empty(), PhysicalState::empty()]),
                DimensionBoundary::new("x", vec![PhysicalState::empty(), PhysicalState::empty()]),
            ],
            convention: TimeAxisConvention::None,
        };

        let result = false_boundary.validate();
        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap(),
            "It is impossible to store two dimensions with the same name."
        );
    }

    #[test]
    fn test_domain_without_state() {
        let false_boundary = DomainBoundaries {
            dimensions: vec![DimensionBoundary::new("x", vec![])],
            convention: TimeAxisConvention::None,
        };

        let result = false_boundary.validate();
        assert!(result.is_err());
        assert_eq!(
            result.err().unwrap(),
            "Dimensions 'x' must have at least one boundary state"
        );
    }
}