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
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
754
755
756
757
758
759
760
761
762
763
//! Temporal injection profiles for chromatography
//!
//! Defines how concentration at the column inlet varies with TIME.
//!
//! # Difference from Spatial Injection
//!
//! - **Spatial injection** (injection.rs): C(z, t=0) - initial distribution in space
//! - **Temporal injection** (this file): C(z=0, t) - inlet concentration over time
//!
//! # Use Case
//!
//! This is what happens in real chromatography:
//! - Sample is injected at inlet (z=0) for a certain duration
//! - Injection can be instantaneous (Dirac) or gradual (Gaussian)
//! - After injection ends, inlet returns to baseline
//!
//! # Example
//!
//! ```rust
//! use chrom_rs::models::TemporalInjection;
//! // Gaussian injection: peak at t=10s, width 3s, height 0.1 mol/L
//! let injection = TemporalInjection::gaussian(10.0, 3.0, 0.1);
//!
//! // At different times:
//! assert!(injection.evaluate(0.0) < 1e-3);      // Before injection (nearly zero)
//! assert!((injection.evaluate(10.0) - 0.1).abs() < 1e-10);     // Peak
//! assert!(injection.evaluate(20.0) < 1e-3);    // After injection (nearly zero)
//! ```

use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Temporal injection profile at column inlet
///
/// Defines how C(z=0, t) varies with time.
///
/// # Types
///
/// - **Dirac**: Instantaneous injection at a single time point
/// - **Gaussian**: Smooth injection over time with bell-shaped profile
/// - **Rectangle**: Constant injection for a duration
/// - **Custom**: User-defined temporal profile
use std::sync::Arc;

// ==================== Serialisation snapshot (internal) ====================

/// Internal representation for serde serialisation of [`TemporalInjection`].
///
/// Mirrors all serialisable variants of [`TemporalInjection`].
/// [`TemporalInjection::Custom`] is excluded — closures cannot be serialised.
///
/// The `type` field is used as a tag in the JSON/YAML output:
/// ```json
/// { "type": "Dirac", "time": 5.0, "amount": 0.1 }
/// ```
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum TemporalInjectionSnapshot {
    Dirac {
        time: f64,
        amount: f64,
    },
    Gaussian {
        center: f64,
        width: f64,
        peak_concentration: f64,
    },
    Rectangle {
        start: f64,
        end: f64,
        concentration: f64,
    },
    None,
}

/// Temporal injection profile at the column inlet ($z = 0$).
///
/// Defines how the inlet concentration $C(t, z=0)$ varies over time.
/// The solver evaluates the profile at each time step and applies it as
/// a boundary condition.
///
/// All variants except [`TemporalInjection::Custom`] are serialisable and
/// can be specified in `scenario.yml`.
///
/// # Choosing a profile
///
/// | Variant | Use case |
/// |---------|----------|
/// | [`Dirac`](TemporalInjection::Dirac) | Instantaneous pulse (sharp injection) |
/// | [`Gaussian`](TemporalInjection::Gaussian) | Smooth finite-width pulse |
/// | [`Rectangle`](TemporalInjection::Rectangle) | Constant-concentration step injection |
/// | [`Custom`](TemporalInjection::Custom) | Arbitrary closure (not serialisable) |
/// | [`None`](TemporalInjection::None) | No injection (zero inlet concentration) |
pub enum TemporalInjection {
    /// Dirac delta injection at a single time point
    ///
    /// # Parameters
    ///
    /// - `time` : Time of injection \[s\]
    /// - `amount` : Amount injected (integral) \[mol/L·s\]
    ///
    /// # Physics
    ///
    /// Approximated as a narrow Gaussian with σ = dt/2
    ///
    /// # Example
    ///
    /// ```rust
    /// use chrom_rs::models::TemporalInjection;
    /// // Inject at t=5s
    /// let injection = TemporalInjection::dirac(5.0, 0.1);
    /// ```
    Dirac { time: f64, amount: f64 },

    /// Gaussian (bell-shaped) injection over time
    ///
    /// # Parameters
    ///
    /// - `center` : Peak injection time \[s\]
    /// - `width` : Standard deviation σ \[s\]
    /// - `peak_concentration` : Maximum concentration \[mol/L\]
    ///
    /// # Formula
    ///
    /// ```text
    /// C(t) = C₀ · exp(-((t - μ)² / (2σ²)))
    /// ```
    ///
    /// # Example
    ///
    /// ```rust
    /// use chrom_rs::models::TemporalInjection;
    /// // Gaussian injection: peak at t=10s, width 3s, max 0.1 mol/L
    /// let injection = TemporalInjection::gaussian(10.0, 3.0, 0.1);
    /// ```
    Gaussian {
        center: f64,
        width: f64,
        peak_concentration: f64,
    },

    /// Rectangular (constant) injection for a duration
    ///
    /// # Parameters
    ///
    /// - `start` : Start time \[s\]
    /// - `end` : End time \[s\]
    /// - `concentration` : Constant concentration during injection \[mol/L\]
    ///
    /// # Example
    ///
    /// ```rust
    /// use chrom_rs::models::TemporalInjection;
    /// // Constant injection from t=5s to t=15s
    /// let injection = TemporalInjection::rectangle(5.0, 15.0, 0.05);
    /// ```
    Rectangle {
        start: f64,
        end: f64,
        concentration: f64,
    },

    /// Custom temporal profile from user function
    ///
    /// # Example
    ///
    /// ```rust
    /// use chrom_rs::models::TemporalInjection;
    /// let injection = TemporalInjection::custom(|t| {
    ///     if t < 10.0 { 0.1 * t / 10.0 } else { 0.0 }
    /// });
    /// ```
    Custom(Arc<dyn Fn(f64) -> f64 + Send + Sync>),

    /// No injection (baseline = 0)
    None,
}

// ==================== Manual Clone Implementation ====================

impl Clone for TemporalInjection {
    fn clone(&self) -> Self {
        match self {
            Self::Dirac { time, amount } => Self::Dirac {
                time: *time,
                amount: *amount,
            },
            Self::Gaussian {
                center,
                width,
                peak_concentration,
            } => Self::Gaussian {
                center: *center,
                width: *width,
                peak_concentration: *peak_concentration,
            },
            Self::Rectangle {
                start,
                end,
                concentration,
            } => Self::Rectangle {
                start: *start,
                end: *end,
                concentration: *concentration,
            },
            Self::Custom(f) => Self::Custom(Arc::clone(f)), // ✅ Arc allows cloning
            Self::None => Self::None,
        }
    }
}

// ==================== Manual Debug Implementation ====================

impl std::fmt::Debug for TemporalInjection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Dirac { time, amount } => f
                .debug_struct("Dirac")
                .field("time", time)
                .field("amount", amount)
                .finish(),
            Self::Gaussian {
                center,
                width,
                peak_concentration,
            } => f
                .debug_struct("Gaussian")
                .field("center", center)
                .field("width", width)
                .field("peak_concentration", peak_concentration)
                .finish(),
            Self::Rectangle {
                start,
                end,
                concentration,
            } => f
                .debug_struct("Rectangle")
                .field("start", start)
                .field("end", end)
                .field("concentration", concentration)
                .finish(),
            Self::Custom(_) => f
                .debug_struct("Custom")
                .field("function", &"<user-defined>")
                .finish(),
            Self::None => f.debug_struct("None").finish(),
        }
    }
}

// ==================== Manual Serialize Implementation ====================

/// Serialises [`TemporalInjection`] to JSON/YAML via an internal snapshot type.
///
/// # Errors
///
/// Returns a serialisation error if called on [`TemporalInjection::Custom`],
/// which holds a closure that cannot be represented in a data format.
impl Serialize for TemporalInjection {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let snapshot = match self {
            Self::Dirac { time, amount } => TemporalInjectionSnapshot::Dirac {
                time: *time,
                amount: *amount,
            },
            Self::Gaussian {
                center,
                width,
                peak_concentration,
            } => TemporalInjectionSnapshot::Gaussian {
                center: *center,
                width: *width,
                peak_concentration: *peak_concentration,
            },
            Self::Rectangle {
                start,
                end,
                concentration,
            } => TemporalInjectionSnapshot::Rectangle {
                start: *start,
                end: *end,
                concentration: *concentration,
            },
            Self::None => TemporalInjectionSnapshot::None,
            Self::Custom(_) => {
                return Err(serde::ser::Error::custom(
                    "Temporal Injection::Custom cannot be serialized",
                ));
            }
        };
        snapshot.serialize(serializer)
    }
}

// ==================== Manual Deserialize Implementation ====================

/// Deserializes [`TemporalInjection`] from JSON/YAML via an internal snapshot type.
///
/// [`TemporalInjection::Custom`] cannot be deserialized — it must be constructed
/// programmatically via [`TemporalInjection::custom`].
impl<'de> Deserialize<'de> for TemporalInjection {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let snapshot = match TemporalInjectionSnapshot::deserialize(deserializer)? {
            TemporalInjectionSnapshot::Dirac { time, amount } => Self::Dirac { time, amount },
            TemporalInjectionSnapshot::Gaussian {
                center,
                width,
                peak_concentration,
            } => Self::Gaussian {
                center,
                width,
                peak_concentration,
            },
            TemporalInjectionSnapshot::Rectangle {
                start,
                end,
                concentration,
            } => Self::Rectangle {
                start,
                end,
                concentration,
            },
            TemporalInjectionSnapshot::None => Self::None,
        };
        Ok(snapshot)
    }
}

// ==================== Implementation ====================
impl TemporalInjection {
    /// Create a Dirac delta injection
    ///
    /// # Arguments
    ///
    /// * `time` - Time of injection \[s\]
    /// * `amount` - Amount to inject \[mol/L·s\]
    ///
    /// # Note
    ///
    /// In discrete time, this is approximated as a narrow Gaussian
    /// with width = dt/2 to conserve total injected amount.
    pub fn dirac(time: f64, amount: f64) -> Self {
        Self::Dirac { time, amount }
    }

    /// Create a Gaussian temporal injection
    ///
    /// # Arguments
    ///
    /// * `center` - Peak time \[s\]
    /// * `width` - Standard deviation \[s\]
    /// * `peak_concentration` - Maximum concentration \[mol/L\]
    pub fn gaussian(center: f64, width: f64, peak_concentration: f64) -> Self {
        Self::Gaussian {
            center,
            width,
            peak_concentration,
        }
    }

    /// Create a rectangular temporal injection
    ///
    /// # Arguments
    ///
    /// * `start` - Start time \[s\]
    /// * `end` - End time \[s\]
    /// * `concentration` - Constant concentration \[mol/L\]
    pub fn rectangle(start: f64, end: f64, concentration: f64) -> Self {
        assert!(end > start, "Rectangle end must be > start");
        Self::Rectangle {
            start,
            end,
            concentration,
        }
    }

    /// Create a custom temporal injection
    ///
    /// # Arguments
    ///
    /// * `f` - Function that takes time and returns concentration
    pub fn custom<F>(f: F) -> Self
    where
        F: Fn(f64) -> f64 + Send + Sync + 'static,
    {
        Self::Custom(Arc::new(f))
    }

    /// Create a "no injection" profile (always returns 0)
    pub fn none() -> Self {
        Self::None
    }

    /// Evaluate the injection profile at a given time
    ///
    /// # Arguments
    ///
    /// * `t` - Current time \[s\]
    ///
    /// # Returns
    ///
    /// Concentration at inlet at time t \[mol/L\]
    pub fn evaluate(&self, t: f64) -> f64 {
        match self {
            Self::Dirac { time, amount } => {
                // Approximate as narrow Gaussian
                // Width chosen to give reasonable discrete representation
                let width = 0.1; // 0.1 second width for Dirac approximation
                let distance = (t - time) / width;
                let peak = amount / (width * (2.0 * std::f64::consts::PI).sqrt());
                let exposant = -(distance * distance) / (2.0 * width * width);

                peak * exposant.exp()
            }

            Self::Gaussian {
                center,
                width,
                peak_concentration,
            } => {
                let distance = (t - center) / width;
                peak_concentration * (-distance * distance / 2.0).exp()
            }

            Self::Rectangle {
                start,
                end,
                concentration,
            } => {
                if t >= *start && t < *end {
                    *concentration
                } else {
                    0.0
                }
            }

            Self::Custom(f) => f(t),

            Self::None => 0.0,
        }
    }

    /// Evaluate at multiple time points
    ///
    /// # Arguments
    ///
    /// * `times` - Vector of time points
    ///
    /// # Returns
    ///
    /// Vector of concentrations at each time
    pub fn evaluate_series(&self, times: &[f64]) -> Vec<f64> {
        times.iter().map(|&t| self.evaluate(t)).collect()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dirac_injection() {
        let injection = TemporalInjection::dirac(10.0, 1.0);

        // Before injection
        assert!(injection.evaluate(0.0) < 0.01);

        // At injection time (should have high concentration)
        assert!(injection.evaluate(10.0) > 1.0);

        // After injection
        assert!(injection.evaluate(20.0) < 0.01);
    }

    #[test]
    fn test_gaussian_injection() {
        let injection = TemporalInjection::gaussian(10.0, 2.0, 0.1);

        // At center
        assert!((injection.evaluate(10.0) - 0.1).abs() < 1e-10);

        // At ±σ should be exp(-0.5) ≈ 0.606 of peak
        let expected = 0.1 * 0.606;
        assert!((injection.evaluate(8.0) - expected).abs() < 0.01);
        assert!((injection.evaluate(12.0) - expected).abs() < 0.01);

        // Far from center
        assert!(injection.evaluate(0.0) < 0.001);
        assert!(injection.evaluate(20.0) < 0.001);
    }

    #[test]
    fn test_rectangle_injection() {
        let injection = TemporalInjection::rectangle(5.0, 15.0, 0.05);

        // Before
        assert_eq!(injection.evaluate(4.0), 0.0);

        // During
        assert_eq!(injection.evaluate(5.0), 0.05);
        assert_eq!(injection.evaluate(10.0), 0.05);
        assert_eq!(injection.evaluate(14.9), 0.05);

        // After
        assert_eq!(injection.evaluate(15.0), 0.0);
    }

    #[test]
    fn test_custom_injection() {
        let injection = TemporalInjection::custom(|t| if t < 10.0 { 0.01 * t } else { 0.0 });

        assert_eq!(injection.evaluate(0.0), 0.0);
        assert_eq!(injection.evaluate(5.0), 0.05);
        assert_eq!(injection.evaluate(10.0), 0.0);
    }

    #[test]
    fn test_none_injection() {
        let injection = TemporalInjection::none();

        assert_eq!(injection.evaluate(0.0), 0.0);
        assert_eq!(injection.evaluate(100.0), 0.0);
    }

    #[test]
    fn test_evaluate_series() {
        let injection = TemporalInjection::gaussian(10.0, 2.0, 0.1);
        let times = vec![0.0, 5.0, 10.0, 15.0, 20.0];
        let values = injection.evaluate_series(&times);

        assert_eq!(values.len(), 5);
        assert!((values[2] - 0.1).abs() < 1e-10); // Peak at t=10
    }

    #[test]
    #[should_panic(expected = "Rectangle end must be > start")]
    fn test_rectangle_invalid() {
        TemporalInjection::rectangle(10.0, 10.0, 0.05);
    }

    #[test]
    fn test_debug_temporal_injection_dirac() {
        let injection = TemporalInjection::dirac(0.0, 10.0);
        let debug = format!("{:?}", injection);

        assert_eq!(debug, "Dirac { time: 0.0, amount: 10.0 }");
    }

    #[test]
    fn test_debug_temporal_injection_gaussian() {
        let injection = TemporalInjection::gaussian(10.0, 2.0, 0.1);
        let debug = format!("{:?}", injection);

        assert_eq!(
            debug,
            "Gaussian { center: 10.0, width: 2.0, peak_concentration: 0.1 }"
        );
    }

    #[test]
    fn test_debug_temporal_injection_rectangle() {
        let injection = TemporalInjection::rectangle(5.0, 9.0, 0.25);
        let debug = format!("{:?}", injection);

        assert_eq!(
            debug,
            "Rectangle { start: 5.0, end: 9.0, concentration: 0.25 }"
        );
    }

    #[test]
    fn test_debug_temporal_injection_custom() {
        let injection = TemporalInjection::custom(|t| t.exp());
        let debug = format!("{:?}", injection);

        assert_eq!(debug, "Custom { function: \"<user-defined>\" }");
    }

    #[test]
    fn test_debug_temporal_injection_none() {
        let injection = TemporalInjection::none();
        let debug = format!("{:?}", injection);

        assert_eq!(debug, "None");
    }

    #[test]
    fn test_clone_temporal_injection_dirac() {
        let injection = TemporalInjection::dirac(10.0, 1.0);
        let clone = injection.clone();

        // Before injection
        assert!(injection.evaluate(0.0) < 0.01);
        assert!(clone.evaluate(0.0) < 0.01);

        // At injection time (should have high concentration)
        assert!(injection.evaluate(10.0) > 1.0);
        assert!(clone.evaluate(10.0) > 1.0);

        // After injection
        assert!(injection.evaluate(20.0) < 0.01);
        assert!(clone.evaluate(20.0) < 0.01);
    }

    #[test]
    fn test_clone_temporal_injection_gaussian() {
        let injection = TemporalInjection::gaussian(10.0, 2.0, 0.1);
        let clone = injection.clone();

        // At center
        assert!((injection.evaluate(10.0) - 0.1).abs() < 1e-10);
        assert!((clone.evaluate(10.0) - 0.1).abs() < 1e-10);

        // At ±σ should be exp(-0.5) ≈ 0.606 of peak
        let expected = 0.1 * 0.606;
        assert!((injection.evaluate(8.0) - expected).abs() < 0.01);
        assert!((injection.evaluate(12.0) - expected).abs() < 0.01);

        assert!((clone.evaluate(8.0) - expected).abs() < 0.01);
        assert!((clone.evaluate(12.0) - expected).abs() < 0.01);

        // Far from center
        assert!(injection.evaluate(0.0) < 0.001);
        assert!(injection.evaluate(20.0) < 0.001);

        assert!(clone.evaluate(0.0) < 0.001);
        assert!(clone.evaluate(20.0) < 0.001);
    }

    #[test]
    fn test_clone_temporal_injection_rectangle() {
        let injection = TemporalInjection::rectangle(5.0, 15.0, 0.05);
        let clone = injection.clone();

        // Before
        assert_eq!(injection.evaluate(4.0), 0.0);
        assert_eq!(clone.evaluate(4.0), 0.0);

        // During
        assert_eq!(injection.evaluate(5.0), 0.05);
        assert_eq!(injection.evaluate(10.0), 0.05);
        assert_eq!(injection.evaluate(14.9), 0.05);

        assert_eq!(clone.evaluate(5.0), 0.05);
        assert_eq!(clone.evaluate(10.0), 0.05);
        assert_eq!(clone.evaluate(14.9), 0.05);

        // After
        assert_eq!(injection.evaluate(15.0), 0.0);
        assert_eq!(clone.evaluate(15.0), 0.0);
    }

    #[test]
    fn test_clone_temporal_injection_custom() {
        let injection = TemporalInjection::custom(|t| if t < 10.0 { 0.01 * t } else { 0.0 });
        let clone = injection.clone();

        assert_eq!(injection.evaluate(0.0), 0.0);
        assert_eq!(clone.evaluate(0.0), 0.0);
        assert_eq!(injection.evaluate(5.0), 0.05);
        assert_eq!(clone.evaluate(5.0), 0.05);
        assert_eq!(injection.evaluate(10.0), 0.0);
        assert_eq!(clone.evaluate(10.0), 0.0);
    }

    #[test]
    fn test_clone_temporal_injection_none() {
        let injection = TemporalInjection::none();
        let clone = injection.clone();

        assert_eq!(clone.evaluate(0.0), 0.0);
        assert_eq!(clone.evaluate(100.0), 0.0);
    }

    // ==================== Serde round-trip tests ====================

    #[test]
    fn test_serialize_dirac() {
        let injection = TemporalInjection::dirac(5.0, 0.1);
        let json = serde_json::to_string(&injection).unwrap();
        assert!(json.contains("\"type\":\"Dirac\""));
        assert!(json.contains("\"time\":5.0"));
        assert!(json.contains("\"amount\":0.1"));
    }

    #[test]
    fn test_serialize_gaussian() {
        let injection = TemporalInjection::gaussian(10.0, 3.0, 0.1);
        let json = serde_json::to_string(&injection).unwrap();
        assert!(json.contains("\"type\":\"Gaussian\""));
        assert!(json.contains("\"center\":10.0"));
    }

    #[test]
    fn test_serialize_rectangle() {
        let injection = TemporalInjection::rectangle(5.0, 15.0, 0.05);
        let json = serde_json::to_string(&injection).unwrap();
        assert!(json.contains("\"type\":\"Rectangle\""));
        assert!(json.contains("\"start\":5.0"));
        assert!(json.contains("\"end\":15.0"));
    }

    #[test]
    fn test_serialize_none() {
        let injection = TemporalInjection::none();
        let json = serde_json::to_string(&injection).unwrap();
        assert!(json.contains("\"type\":\"None\""));
    }

    #[test]
    fn test_serialize_custom_fails() {
        let injection = TemporalInjection::custom(|t| t);
        assert!(serde_json::to_string(&injection).is_err());
    }

    #[test]
    fn test_round_trip_dirac() {
        let original = TemporalInjection::dirac(5.0, 0.1);
        let json = serde_json::to_string(&original).unwrap();
        let restored: TemporalInjection = serde_json::from_str(&json).unwrap();
        assert!((restored.evaluate(5.0) - original.evaluate(5.0)).abs() < 1e-10);
    }

    #[test]
    fn test_round_trip_gaussian() {
        let original = TemporalInjection::gaussian(10.0, 3.0, 0.1);
        let json = serde_json::to_string(&original).unwrap();
        let restored: TemporalInjection = serde_json::from_str(&json).unwrap();
        assert!((restored.evaluate(10.0) - original.evaluate(10.0)).abs() < 1e-10);
    }

    #[test]
    fn test_round_trip_rectangle() {
        let original = TemporalInjection::rectangle(5.0, 15.0, 0.05);
        let json = serde_json::to_string(&original).unwrap();
        let restored: TemporalInjection = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.evaluate(10.0), original.evaluate(10.0));
    }

    #[test]
    fn test_round_trip_none() {
        let original = TemporalInjection::none();
        let json = serde_json::to_string(&original).unwrap();
        let restored: TemporalInjection = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.evaluate(0.0), 0.0);
    }

    #[test]
    fn test_round_trip_yaml() {
        let original = TemporalInjection::dirac(5.0, 0.1);
        let yaml = serde_yaml::to_string(&original).unwrap();
        let restored: TemporalInjection = serde_yaml::from_str(&yaml).unwrap();
        assert!((restored.evaluate(5.0) - original.evaluate(5.0)).abs() < 1e-10);
    }
}