scirs2-interpolate 0.4.2

Interpolation module for SciRS2 (scirs2-interpolate)
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
use scirs2_core::ndarray::ArrayView1;
use scirs2_core::numeric::Float;

use crate::error::{InterpolateError, InterpolateResult};
use crate::ExtrapolateMode;

/// Enhanced boundary handling modes for interpolation.
///
/// This enum provides specialized boundary handling methods that go beyond
/// basic extrapolation. These methods are particularly useful for scientific
/// and engineering applications where specific boundary behaviors are required.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BoundaryMode {
    /// Extrapolate according to the specified ExtrapolateMode
    Extrapolate(ExtrapolateMode),

    /// Zero-gradient (Neumann) boundary condition: df/dx = 0 at the boundary
    ZeroGradient,

    /// Zero-value (Dirichlet) boundary condition: f = 0 at the boundary
    ZeroValue,

    /// Linear extension with explicit gradient
    LinearGradient(f64),

    /// Cyclic/periodic boundary (wraps around)
    Periodic,

    /// Symmetric/reflection boundary (mirror image across boundary)
    Symmetric,

    /// Antisymmetric boundary (mirror image with sign change)
    Antisymmetric,

    /// Custom function for boundary handling
    /// (stored as function index in a registry)
    Custom(usize),
}

/// Parameters for enhancing boundary handling
#[derive(Debug, Clone)]
pub struct BoundaryParameters<T: Float> {
    /// Lower boundary of the domain
    lower_bound: T,

    /// Upper boundary of the domain
    upper_bound: T,

    /// Boundary handling mode for the lower boundary
    lower_mode: BoundaryMode,

    /// Boundary handling mode for the upper boundary
    upper_mode: BoundaryMode,

    /// Value at the lower boundary (for some modes)
    lower_value: Option<T>,

    /// Value at the upper boundary (for some modes)
    upper_value: Option<T>,

    /// Derivative at the lower boundary (for some modes)
    lower_derivative: Option<T>,

    /// Derivative at the upper boundary (for some modes)
    upper_derivative: Option<T>,

    /// Custom functions registry for Custom boundary mode
    /// (not actually stored here, referenced by index)
    custom_functions: Vec<usize>,
}

impl<T: Float + std::fmt::Display> BoundaryParameters<T> {
    /// Get the custom functions registry
    pub fn custom_functions(&self) -> &Vec<usize> {
        &self.custom_functions
    }
}

impl<T: Float + std::fmt::Display> BoundaryParameters<T> {
    /// Creates new boundary parameters with the specified modes.
    ///
    /// # Arguments
    ///
    /// * `lower_bound` - Lower boundary of the domain
    /// * `upper_bound` - Upper boundary of the domain
    /// * `lower_mode` - Boundary handling mode for the lower boundary
    /// * `upper_mode` - Boundary handling mode for the upper boundary
    ///
    /// # Returns
    ///
    /// A new `BoundaryParameters` instance
    pub fn new(
        lower_bound: T,
        upper_bound: T,
        lower_mode: BoundaryMode,
        upper_mode: BoundaryMode,
    ) -> Self {
        Self {
            lower_bound,
            upper_bound,
            lower_mode,
            upper_mode,
            lower_value: None,
            upper_value: None,
            lower_derivative: None,
            upper_derivative: None,
            custom_functions: Vec::new(),
        }
    }

    /// Sets the values at the boundaries.
    ///
    /// # Arguments
    ///
    /// * `lower_value` - Value at the lower boundary
    /// * `upper_value` - Value at the upper boundary
    ///
    /// # Returns
    ///
    /// A reference to the modified parameters
    pub fn with_values(mut self, lower_value: T, uppervalue: T) -> Self {
        self.lower_value = Some(lower_value);
        self.upper_value = Some(uppervalue);
        self
    }

    /// Sets the derivatives at the boundaries.
    ///
    /// # Arguments
    ///
    /// * `lower_derivative` - Derivative at the lower boundary
    /// * `upper_derivative` - Derivative at the upper boundary
    ///
    /// # Returns
    ///
    /// A reference to the modified parameters
    pub fn with_derivatives(mut self, lower_derivative: T, upperderivative: T) -> Self {
        self.lower_derivative = Some(lower_derivative);
        self.upper_derivative = Some(upperderivative);
        self
    }

    /// Maps a point outside the domain to an equivalent point according to boundary conditions.
    ///
    /// # Arguments
    ///
    /// * `x` - The point to map
    /// * `values` - Function values at domain points (for some modes)
    /// * `domain_points` - The domain points corresponding to the values
    ///
    /// # Returns
    ///
    /// Either the mapped point or a direct value, depending on the boundary mode
    pub fn map_point(
        &self,
        x: T,
        values: Option<&ArrayView1<T>>,
        domain_points: Option<&ArrayView1<T>>,
    ) -> InterpolateResult<BoundaryResult<T>> {
        // Check if point is inside the domain
        if x >= self.lower_bound && x <= self.upper_bound {
            return Ok(BoundaryResult::InsideDomain(x));
        }

        // Handle based on which boundary we're crossing
        if x < self.lower_bound {
            self.map_lower_boundary(x, values, domain_points)
        } else {
            self.map_upper_boundary(x, values, domain_points)
        }
    }

    /// Maps a point below the lower boundary according to the specified mode.
    fn map_lower_boundary(
        &self,
        x: T,
        values: Option<&ArrayView1<T>>,
        domain_points: Option<&ArrayView1<T>>,
    ) -> InterpolateResult<BoundaryResult<T>> {
        match self.lower_mode {
            BoundaryMode::Extrapolate(mode) => {
                match mode {
                    ExtrapolateMode::Error => Err(InterpolateError::OutOfBounds(format!(
                        "Point {} is below the lower boundary {}",
                        x, self.lower_bound
                    ))),
                    ExtrapolateMode::Extrapolate => {
                        // Allow extrapolation - return the original point
                        Ok(BoundaryResult::AllowExtrapolation(x))
                    }
                    ExtrapolateMode::Nan => {
                        // Return NaN for _points outside the interpolation domain
                        Ok(BoundaryResult::DirectValue(T::nan()))
                    }
                    ExtrapolateMode::Nearest => {
                        // Clamp to lower boundary
                        Ok(BoundaryResult::MappedPoint(self.lower_bound))
                    }
                }
            }
            BoundaryMode::ZeroGradient => {
                // Zero gradient means use the boundary value
                Ok(BoundaryResult::MappedPoint(self.lower_bound))
            }
            BoundaryMode::ZeroValue => {
                // Zero value means return 0
                Ok(BoundaryResult::DirectValue(T::zero()))
            }
            BoundaryMode::LinearGradient(gradient) => {
                // Linear extension with specified gradient
                let dx = x - self.lower_bound;
                let gradient_t = T::from(gradient).ok_or_else(|| {
                    InterpolateError::InvalidValue(
                        "Could not convert gradient to generic type".to_string(),
                    )
                })?;

                if let Some(lower_val) = self.lower_value {
                    // Use provided boundary value
                    Ok(BoundaryResult::DirectValue(lower_val + gradient_t * dx))
                } else if let (Some(vals), Some(_points)) = (values, domain_points) {
                    // Find the value at the lower boundary
                    let idx = self.find_nearest_point_index(self.lower_bound, _points)?;
                    let lower_val = vals[idx];
                    Ok(BoundaryResult::DirectValue(lower_val + gradient_t * dx))
                } else {
                    Err(InterpolateError::InvalidState(
                        "Values or domain _points not provided for LinearGradient mode".to_string(),
                    ))
                }
            }
            BoundaryMode::Periodic => {
                // Periodic boundary means wrap around
                let domain_width = self.upper_bound - self.lower_bound;
                let offset = self.lower_bound - x;
                let periods = (offset / domain_width).ceil();
                let x_mapped = x + periods * domain_width;

                // Handle numerical precision issues
                if x_mapped < self.lower_bound {
                    Ok(BoundaryResult::MappedPoint(self.lower_bound))
                } else if x_mapped > self.upper_bound {
                    Ok(BoundaryResult::MappedPoint(self.upper_bound))
                } else {
                    Ok(BoundaryResult::MappedPoint(x_mapped))
                }
            }
            BoundaryMode::Symmetric => {
                // Symmetric boundary means reflect across the boundary
                let offset = self.lower_bound - x;
                let x_mapped = self.lower_bound + offset;

                // Handle multiple reflections
                if x_mapped > self.upper_bound {
                    // Need to reflect again
                    let new_offset = x_mapped - self.upper_bound;
                    let x_mapped = self.upper_bound - new_offset;

                    // Recursive case for multiple reflections
                    if x_mapped < self.lower_bound {
                        self.map_point(x_mapped, values, domain_points)
                    } else {
                        Ok(BoundaryResult::MappedPoint(x_mapped))
                    }
                } else {
                    Ok(BoundaryResult::MappedPoint(x_mapped))
                }
            }
            BoundaryMode::Antisymmetric => {
                // Similar to symmetric, but the function value changes sign
                let offset = self.lower_bound - x;
                let x_mapped = self.lower_bound + offset;

                if let (Some(vals), Some(_points)) = (values, domain_points) {
                    // Find the value at the mapped point
                    let mapped_index = self.find_nearest_point_index(x_mapped, _points)?;
                    let mapped_value = vals[mapped_index];

                    // Negate the value for antisymmetric reflection
                    Ok(BoundaryResult::DirectValue(-mapped_value))
                } else {
                    // Can't determine value without function values
                    Ok(BoundaryResult::MappedPointWithSignChange(x_mapped))
                }
            }
            BoundaryMode::Custom(func_idx) => {
                // Custom function is not directly implemented here,
                // it's expected to be handled by the caller
                Ok(BoundaryResult::CustomHandling(func_idx, x))
            }
        }
    }

    /// Maps a point above the upper boundary according to the specified mode.
    fn map_upper_boundary(
        &self,
        x: T,
        values: Option<&ArrayView1<T>>,
        domain_points: Option<&ArrayView1<T>>,
    ) -> InterpolateResult<BoundaryResult<T>> {
        match self.upper_mode {
            BoundaryMode::Extrapolate(mode) => {
                match mode {
                    ExtrapolateMode::Error => Err(InterpolateError::OutOfBounds(format!(
                        "Point {} is above the upper boundary {}",
                        x, self.upper_bound
                    ))),
                    ExtrapolateMode::Extrapolate => {
                        // Allow extrapolation - return the original point
                        Ok(BoundaryResult::AllowExtrapolation(x))
                    }
                    ExtrapolateMode::Nan => {
                        // Return NaN for _points outside the interpolation domain
                        Ok(BoundaryResult::DirectValue(T::nan()))
                    }
                    ExtrapolateMode::Nearest => {
                        // Clamp to upper boundary
                        Ok(BoundaryResult::MappedPoint(self.upper_bound))
                    }
                }
            }
            BoundaryMode::ZeroGradient => {
                // Zero gradient means use the boundary value
                Ok(BoundaryResult::MappedPoint(self.upper_bound))
            }
            BoundaryMode::ZeroValue => {
                // Zero value means return 0
                Ok(BoundaryResult::DirectValue(T::zero()))
            }
            BoundaryMode::LinearGradient(gradient) => {
                // Linear extension with specified gradient
                let dx = x - self.upper_bound;
                let gradient_t = T::from(gradient).ok_or_else(|| {
                    InterpolateError::InvalidValue(
                        "Could not convert gradient to generic type".to_string(),
                    )
                })?;

                if let Some(upper_val) = self.upper_value {
                    // Use provided boundary value
                    Ok(BoundaryResult::DirectValue(upper_val + gradient_t * dx))
                } else if let (Some(vals), Some(_points)) = (values, domain_points) {
                    // Find the value at the upper boundary
                    let idx = self.find_nearest_point_index(self.upper_bound, _points)?;
                    let upper_val = vals[idx];
                    Ok(BoundaryResult::DirectValue(upper_val + gradient_t * dx))
                } else {
                    Err(InterpolateError::InvalidState(
                        "Values or domain _points not provided for LinearGradient mode".to_string(),
                    ))
                }
            }
            BoundaryMode::Periodic => {
                // Periodic boundary means wrap around
                let domain_width = self.upper_bound - self.lower_bound;
                let offset = x - self.lower_bound;
                let periods = (offset / domain_width).floor();
                let x_mapped = x - periods * domain_width;

                // Handle numerical precision issues
                if x_mapped < self.lower_bound {
                    Ok(BoundaryResult::MappedPoint(self.lower_bound))
                } else if x_mapped > self.upper_bound {
                    Ok(BoundaryResult::MappedPoint(self.upper_bound))
                } else {
                    Ok(BoundaryResult::MappedPoint(x_mapped))
                }
            }
            BoundaryMode::Symmetric => {
                // Symmetric boundary means reflect across the boundary
                let offset = x - self.upper_bound;
                let x_mapped = self.upper_bound - offset;

                // Handle multiple reflections
                if x_mapped < self.lower_bound {
                    // Need to reflect again
                    let new_offset = self.lower_bound - x_mapped;
                    let x_mapped = self.lower_bound + new_offset;

                    // Recursive case for multiple reflections
                    if x_mapped > self.upper_bound {
                        self.map_point(x_mapped, values, domain_points)
                    } else {
                        Ok(BoundaryResult::MappedPoint(x_mapped))
                    }
                } else {
                    Ok(BoundaryResult::MappedPoint(x_mapped))
                }
            }
            BoundaryMode::Antisymmetric => {
                // Similar to symmetric, but the function value changes sign
                let offset = x - self.upper_bound;
                let x_mapped = self.upper_bound - offset;

                if let (Some(vals), Some(_points)) = (values, domain_points) {
                    // Find the value at the mapped point
                    let mapped_index = self.find_nearest_point_index(x_mapped, _points)?;
                    let mapped_value = vals[mapped_index];

                    // Negate the value for antisymmetric reflection
                    Ok(BoundaryResult::DirectValue(-mapped_value))
                } else {
                    // Can't determine value without function values
                    Ok(BoundaryResult::MappedPointWithSignChange(x_mapped))
                }
            }
            BoundaryMode::Custom(func_idx) => {
                // Custom function is not directly implemented here,
                // it's expected to be handled by the caller
                Ok(BoundaryResult::CustomHandling(func_idx, x))
            }
        }
    }

    /// Finds the index of the nearest point in the domain to the given point.
    fn find_nearest_point_index(
        &self,
        point: T,
        domain_points: &ArrayView1<T>,
    ) -> InterpolateResult<usize> {
        let mut nearest_idx = 0;
        let mut min_distance = T::infinity();

        for (i, &p) in domain_points.iter().enumerate() {
            let distance = (p - point).abs();
            if distance < min_distance {
                min_distance = distance;
                nearest_idx = i;
            }
        }

        Ok(nearest_idx)
    }

    /// Get the lower boundary mode.
    pub fn get_lower_mode(&self) -> BoundaryMode {
        self.lower_mode
    }

    /// Get the upper boundary mode.
    pub fn get_upper_mode(&self) -> BoundaryMode {
        self.upper_mode
    }

    /// Set the lower boundary mode.
    pub fn set_lower_mode(&mut self, mode: BoundaryMode) {
        self.lower_mode = mode;
    }

    /// Set the upper boundary mode.
    pub fn set_upper_mode(&mut self, mode: BoundaryMode) {
        self.upper_mode = mode;
    }
}

/// The result of applying a boundary condition
#[derive(Debug, Clone)]
pub enum BoundaryResult<T: Float> {
    /// Point is inside the domain, no boundary handling needed
    InsideDomain(T),

    /// Point has been mapped to an equivalent point inside the domain
    MappedPoint(T),

    /// Point has been mapped to an equivalent point inside the domain,
    /// and the function value should be negated
    MappedPointWithSignChange(T),

    /// Extrapolation is allowed for this point
    AllowExtrapolation(T),

    /// A direct function value is returned (no interpolation needed)
    DirectValue(T),

    /// Custom handling is required (function index and original point)
    CustomHandling(usize, T),
}

/// Creates boundary parameters with zero-gradient boundary conditions.
///
/// Zero-gradient (Neumann) boundary conditions set df/dx = 0 at the boundaries,
/// which is useful for physical problems where there's no flux across boundaries.
///
/// # Arguments
///
/// * `lower_bound` - Lower boundary of the domain
/// * `upper_bound` - Upper boundary of the domain
///
/// # Returns
///
/// A new `BoundaryParameters` instance with zero-gradient boundary conditions
#[allow(dead_code)]
pub fn make_zero_gradient_boundary<T: Float + std::fmt::Display>(
    lower_bound: T,
    upper_bound: T,
) -> BoundaryParameters<T> {
    BoundaryParameters::new(
        lower_bound,
        upper_bound,
        BoundaryMode::ZeroGradient,
        BoundaryMode::ZeroGradient,
    )
}

/// Creates boundary parameters with zero-value boundary conditions.
///
/// Zero-value (Dirichlet) boundary conditions set f = 0 at the boundaries,
/// which is useful for physical problems where the quantity vanishes at boundaries.
///
/// # Arguments
///
/// * `lower_bound` - Lower boundary of the domain
/// * `upper_bound` - Upper boundary of the domain
///
/// # Returns
///
/// A new `BoundaryParameters` instance with zero-value boundary conditions
#[allow(dead_code)]
pub fn make_zero_value_boundary<T: Float + std::fmt::Display>(
    lower_bound: T,
    upper_bound: T,
) -> BoundaryParameters<T> {
    BoundaryParameters::new(
        lower_bound,
        upper_bound,
        BoundaryMode::ZeroValue,
        BoundaryMode::ZeroValue,
    )
}

/// Creates boundary parameters with periodic boundary conditions.
///
/// Periodic boundary conditions treat the function as if it repeats outside
/// the domain, which is useful for analyzing periodic phenomena.
///
/// # Arguments
///
/// * `lower_bound` - Lower boundary of the domain
/// * `upper_bound` - Upper boundary of the domain
///
/// # Returns
///
/// A new `BoundaryParameters` instance with periodic boundary conditions
#[allow(dead_code)]
pub fn make_periodic_boundary<T: Float + std::fmt::Display>(
    lower_bound: T,
    upper_bound: T,
) -> BoundaryParameters<T> {
    BoundaryParameters::new(
        lower_bound,
        upper_bound,
        BoundaryMode::Periodic,
        BoundaryMode::Periodic,
    )
}

/// Creates boundary parameters with symmetric boundary conditions.
///
/// Symmetric boundary conditions reflect the function across the boundaries,
/// which is useful for problems with symmetry about the boundaries.
///
/// # Arguments
///
/// * `lower_bound` - Lower boundary of the domain
/// * `upper_bound` - Upper boundary of the domain
///
/// # Returns
///
/// A new `BoundaryParameters` instance with symmetric boundary conditions
#[allow(dead_code)]
pub fn make_symmetric_boundary<T: Float + std::fmt::Display>(
    lower_bound: T,
    upper_bound: T,
) -> BoundaryParameters<T> {
    BoundaryParameters::new(
        lower_bound,
        upper_bound,
        BoundaryMode::Symmetric,
        BoundaryMode::Symmetric,
    )
}

/// Creates boundary parameters with antisymmetric boundary conditions.
///
/// Antisymmetric boundary conditions reflect the function across the boundaries
/// with a sign change, which is useful for odd functions.
///
/// # Arguments
///
/// * `lower_bound` - Lower boundary of the domain
/// * `upper_bound` - Upper boundary of the domain
///
/// # Returns
///
/// A new `BoundaryParameters` instance with antisymmetric boundary conditions
#[allow(dead_code)]
pub fn make_antisymmetric_boundary<T: Float + std::fmt::Display>(
    lower_bound: T,
    upper_bound: T,
) -> BoundaryParameters<T> {
    BoundaryParameters::new(
        lower_bound,
        upper_bound,
        BoundaryMode::Antisymmetric,
        BoundaryMode::Antisymmetric,
    )
}

/// Creates boundary parameters with linear gradient boundary conditions.
///
/// Linear gradient boundary conditions extend the function linearly with
/// the specified gradients at boundaries.
///
/// # Arguments
///
/// * `lower_bound` - Lower boundary of the domain
/// * `upper_bound` - Upper boundary of the domain
/// * `lower_gradient` - Gradient at the lower boundary
/// * `upper_gradient` - Gradient at the upper boundary
///
/// # Returns
///
/// A new `BoundaryParameters` instance with linear gradient boundary conditions
#[allow(dead_code)]
pub fn make_linear_gradient_boundary<T: Float + std::fmt::Display>(
    lower_bound: T,
    upper_bound: T,
    lower_gradient: f64,
    upper_gradient: f64,
) -> BoundaryParameters<T> {
    BoundaryParameters::new(
        lower_bound,
        upper_bound,
        BoundaryMode::LinearGradient(lower_gradient),
        BoundaryMode::LinearGradient(upper_gradient),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::ndarray::Array;

    #[test]
    fn test_zero_gradient_boundary() {
        let boundary = make_zero_gradient_boundary(0.0, 10.0);

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 0.0),
            _ => panic!("Expected MappedPoint result"),
        }

        // Test point above upper boundary
        let result = boundary
            .map_point(15.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 10.0),
            _ => panic!("Expected MappedPoint result"),
        }
    }

    #[test]
    fn test_zero_value_boundary() {
        let boundary = make_zero_value_boundary(0.0, 10.0);

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::DirectValue(v) => assert_abs_diff_eq!(v, 0.0),
            _ => panic!("Expected DirectValue result"),
        }

        // Test point above upper boundary
        let result = boundary
            .map_point(15.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::DirectValue(v) => assert_abs_diff_eq!(v, 0.0),
            _ => panic!("Expected DirectValue result"),
        }
    }

    #[test]
    fn test_periodic_boundary() {
        let boundary = make_periodic_boundary(0.0, 10.0);

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPoint result"),
        }

        // Test point above upper boundary
        let result = boundary
            .map_point(15.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPoint result"),
        }

        // Test multiple periods
        let result = boundary
            .map_point(25.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPoint result"),
        }
    }

    #[test]
    fn test_symmetric_boundary() {
        let boundary = make_symmetric_boundary(0.0, 10.0);

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPoint result"),
        }

        // Test point above upper boundary
        let result = boundary
            .map_point(15.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPoint result"),
        }

        // Test multiple reflections
        let result = boundary
            .map_point(-15.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPoint(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPoint result"),
        }
    }

    #[test]
    fn test_antisymmetric_boundary() {
        let boundary = make_antisymmetric_boundary(0.0, 10.0);

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::MappedPointWithSignChange(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected MappedPointWithSignChange result"),
        }

        // Test with provided values
        let domain_points = Array::linspace(0.0, 10.0, 11);
        let values = domain_points.mapv(|v| v * v);

        let result = boundary
            .map_point(-5.0, Some(&values.view()), Some(&domain_points.view()))
            .expect("Operation failed");
        match result {
            BoundaryResult::DirectValue(v) => {
                let expected = -(5.0 * 5.0); // Negative of f(5.0)
                assert_abs_diff_eq!(v, expected);
            }
            _ => panic!("Expected DirectValue result"),
        }
    }

    #[test]
    fn test_linear_gradient_boundary() {
        let boundary = make_linear_gradient_boundary(0.0, 10.0, 2.0, -3.0);

        // Test with provided values
        let domain_points = Array::linspace(0.0, 10.0, 11);
        let values = domain_points.mapv(|v| v * v);

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, Some(&values.view()), Some(&domain_points.view()))
            .expect("Operation failed");

        match result {
            BoundaryResult::DirectValue(v) => {
                let expected = 0.0 + 2.0 * (-5.0); // f(0) + gradient * dx
                assert_abs_diff_eq!(v, expected);
            }
            _ => panic!("Expected DirectValue result"),
        }

        // Test point above upper boundary
        let result = boundary
            .map_point(15.0, Some(&values.view()), Some(&domain_points.view()))
            .expect("Operation failed");

        match result {
            BoundaryResult::DirectValue(v) => {
                let expected = 100.0 + (-3.0) * (15.0 - 10.0); // f(10) + gradient * dx
                assert_abs_diff_eq!(v, expected);
            }
            _ => panic!("Expected DirectValue result"),
        }
    }

    #[test]
    fn test_inside_domain() {
        let boundary = make_zero_gradient_boundary(0.0, 10.0);

        // Test point inside domain
        let result = boundary
            .map_point(5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::InsideDomain(x) => assert_abs_diff_eq!(x, 5.0),
            _ => panic!("Expected InsideDomain result"),
        }
    }

    #[test]
    fn test_extrapolate_boundary() {
        let boundary = BoundaryParameters::new(
            0.0,
            10.0,
            BoundaryMode::Extrapolate(ExtrapolateMode::Extrapolate),
            BoundaryMode::Extrapolate(ExtrapolateMode::Extrapolate),
        );

        // Test point below lower boundary
        let result = boundary
            .map_point(-5.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::AllowExtrapolation(x) => assert_abs_diff_eq!(x, -5.0),
            _ => panic!("Expected AllowExtrapolation result"),
        }

        // Test point above upper boundary
        let result = boundary
            .map_point(15.0, None, None)
            .expect("Operation failed");
        match result {
            BoundaryResult::AllowExtrapolation(x) => assert_abs_diff_eq!(x, 15.0),
            _ => panic!("Expected AllowExtrapolation result"),
        }
    }
}