scirs2-spatial 0.4.0

Spatial algorithms module for SciRS2 (scirs2-spatial)
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
//! Radial Basis Function interpolation
//!
//! This module provides Radial Basis Function (RBF) interpolation, a flexible
//! technique for interpolating scattered data in any number of dimensions.
//!
//! RBF interpolation works by representing the interpolant as a weighted sum of
//! radial basis functions centered at each data point. The weights are determined
//! by solving a linear system to enforce that the interpolant passes through all
//! data points.
//!
//! Various radial basis functions are provided, each with different smoothness
//! and locality properties:
//!
//! - Gaussian: Infinitely smooth but highly local
//! - Multiquadric: Moderately smooth and less local
//! - Inverse Multiquadric: Infinitely smooth with moderate locality
//! - Thin Plate Spline: Minimizes curvature, very smooth
//! - Linear: Simplest RBF, not smooth at data points
//! - Cubic: Good compromise between smoothness and locality

use crate::error::{SpatialError, SpatialResult};
use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
use scirs2_core::random::{thread_rng, Rng};
// Simple linear system solver
#[allow(dead_code)]
fn solve_linear_system(a: Array2<f64>, b: Array1<f64>) -> SpatialResult<Array1<f64>> {
    // We should use a proper linear algebra library, but for now we'll use a simple approach
    // This is not numerically stable for ill-conditioned matrices
    let n = a.nrows();
    if n != a.ncols() {
        return Err(SpatialError::DimensionError(
            "Matrix A must be square".to_string(),
        ));
    }

    if n != b.len() {
        return Err(SpatialError::DimensionError(
            "Matrix A and vector b dimensions must match".to_string(),
        ));
    }

    // Very simple implementation - in production code, use a proper linear algebra library
    let mut x = Array1::zeros(n);

    // Add a small value to the diagonal to improve stability (regularization)
    let mut a_reg = a.clone();
    for i in 0..n {
        a_reg[[i, i]] += 1e-10;
    }

    // Simple Gaussian elimination - not suitable for large or ill-conditioned systems
    let mut aug = Array2::zeros((n, n + 1));
    for i in 0..n {
        for j in 0..n {
            aug[[i, j]] = a_reg[[i, j]];
        }
        aug[[i, n]] = b[i];
    }

    // Forward elimination
    for i in 0..n {
        let mut max_row = i;
        let mut max_val = aug[[i, i]].abs();

        // Partial pivoting
        for j in i + 1..n {
            if aug[[j, i]].abs() > max_val {
                max_row = j;
                max_val = aug[[j, i]].abs();
            }
        }

        if max_val < 1e-10 {
            return Err(SpatialError::ComputationError(
                "Matrix is singular or nearly singular".to_string(),
            ));
        }

        // Swap rows if needed
        if max_row != i {
            for j in 0..=n {
                let temp = aug[[i, j]];
                aug[[i, j]] = aug[[max_row, j]];
                aug[[max_row, j]] = temp;
            }
        }

        // Eliminate below
        for j in i + 1..n {
            let factor = aug[[j, i]] / aug[[i, i]];
            aug[[j, i]] = 0.0;

            for k in i + 1..=n {
                aug[[j, k]] -= factor * aug[[i, k]];
            }
        }
    }

    // Back substitution
    for i in (0..n).rev() {
        x[i] = aug[[i, n]];

        for j in i + 1..n {
            x[i] -= aug[[i, j]] * x[j];
        }

        x[i] /= aug[[i, i]];
    }

    Ok(x)
}

/// Available radial basis function kernels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RBFKernel {
    /// Gaussian: φ(r) = exp(-ε²r²)
    /// Infinitely smooth but highly local
    Gaussian,

    /// Multiquadric: φ(r) = sqrt(1 + (εr)²)
    /// Moderately smooth and less local
    Multiquadric,

    /// Inverse Multiquadric: φ(r) = 1/sqrt(1 + (εr)²)
    /// Infinitely smooth with moderate locality
    InverseMultiquadric,

    /// Thin Plate Spline: φ(r) = r² ln(r)
    /// Minimizes curvature, very smooth
    ThinPlateSpline,

    /// Linear: φ(r) = r
    /// Simplest RBF, not smooth at data points
    Linear,

    /// Cubic: φ(r) = r³
    /// Good compromise between smoothness and locality
    Cubic,
}

impl RBFKernel {
    /// Apply the kernel function to a distance
    ///
    /// # Arguments
    ///
    /// * `r` - Distance
    /// * `epsilon` - Shape parameter (for kernels that use it)
    ///
    /// # Returns
    ///
    /// Value of the kernel function at distance r
    fn apply(&self, r: f64, epsilon: f64) -> f64 {
        match self {
            RBFKernel::Gaussian => (-epsilon * epsilon * r * r).exp(),
            RBFKernel::Multiquadric => (1.0 + (epsilon * r).powi(2)).sqrt(),
            RBFKernel::InverseMultiquadric => 1.0 / (1.0 + (epsilon * r).powi(2)).sqrt(),
            RBFKernel::ThinPlateSpline => {
                if r < 1e-10 {
                    0.0
                } else {
                    r * r * r.ln()
                }
            }
            RBFKernel::Linear => r,
            RBFKernel::Cubic => r.powi(3),
        }
    }
}

/// Radial Basis Function interpolator for scattered data
///
/// # Examples
///
/// ```
/// use scirs2_spatial::interpolate::{RBFInterpolator, RBFKernel};
/// use scirs2_core::ndarray::array;
///
/// // Create sample points and values
/// let points = array![
///     [0.0, 0.0],
///     [1.0, 0.0],
///     [0.0, 1.0],
///     [1.0, 1.0],
/// ];
/// let values = array![0.0, 1.0, 2.0, 3.0];
///
/// // Create interpolator with Gaussian kernel
/// let interp = RBFInterpolator::new(
///     &points.view(),
///     &values.view(),
///     RBFKernel::Gaussian,
///     Some(1.0),
///     None,
/// ).expect("Operation failed");
///
/// // Interpolate at a point
/// let query_point = array![0.5, 0.5];
/// let result = interp.interpolate(&query_point.view()).expect("Operation failed");
///
/// // For this simple example, should be close to 1.5
/// ```
#[derive(Debug, Clone)]
pub struct RBFInterpolator {
    /// Input points (N x D)
    points: Array2<f64>,
    /// Input values (N)
    _values: Array1<f64>,
    /// Dimensionality of the input points
    dim: usize,
    /// Number of input points
    n_points: usize,
    /// RBF kernel function
    kernel: RBFKernel,
    /// Shape parameter for the kernel
    epsilon: f64,
    /// Whether to include polynomial terms
    polynomial: bool,
    /// Weights for the RBF terms
    weights: Array1<f64>,
    /// Coefficients for the polynomial terms (if included)
    poly_coefs: Option<Array1<f64>>,
}

impl RBFInterpolator {
    /// Create a new RBF interpolator
    ///
    /// # Arguments
    ///
    /// * `points` - Input points with shape (n_samples, n_dims)
    /// * `values` - Input values with shape (n_samples,)
    /// * `kernel` - RBF kernel function to use
    /// * `epsilon` - Shape parameter for the kernel (default depends on kernel)
    /// * `polynomial` - Whether to include polynomial terms (default: false)
    ///
    /// # Returns
    ///
    /// A new RBFInterpolator
    ///
    /// # Errors
    ///
    /// * If points and values have different lengths
    /// * If fewer than d+1 points are provided (where d is the dimensionality)
    /// * If the system of equations is singular
    pub fn new(
        points: &ArrayView2<'_, f64>,
        values: &ArrayView1<f64>,
        kernel: RBFKernel,
        epsilon: Option<f64>,
        polynomial: Option<bool>,
    ) -> SpatialResult<Self> {
        // Check input dimensions
        let n_points = points.nrows();
        let dim = points.ncols();

        if n_points != values.len() {
            return Err(SpatialError::DimensionError(format!(
                "Number of points ({}) must match number of values ({})",
                n_points,
                values.len()
            )));
        }

        if n_points < dim + 1 {
            return Err(SpatialError::ValueError(format!(
                "At least {} points required for {}D interpolation",
                dim + 1,
                dim
            )));
        }

        // Set default epsilon based on kernel
        let epsilon = epsilon.unwrap_or_else(|| Self::default_epsilon(kernel, points));

        // Set default polynomial option
        let polynomial = polynomial.unwrap_or(false);

        // Build the interpolation system
        let (weights, poly_coefs) =
            Self::solve_rbf_system(points, values, kernel, epsilon, polynomial)?;

        Ok(Self {
            points: points.to_owned(),
            _values: values.to_owned(),
            dim,
            n_points,
            kernel,
            epsilon,
            polynomial,
            weights,
            poly_coefs,
        })
    }

    /// Get a default shape parameter based on the kernel and data
    ///
    /// # Arguments
    ///
    /// * `kernel` - The RBF kernel
    /// * `points` - The input points
    ///
    /// # Returns
    ///
    /// A reasonable default value for epsilon
    fn default_epsilon(kernel: RBFKernel, points: &ArrayView2<'_, f64>) -> f64 {
        match kernel {
            RBFKernel::Gaussian => {
                // For Gaussian, a typical choice is 1 / (2 * average distance^2)
                let avg_dist = Self::average_distance(points);
                if avg_dist > 0.0 {
                    1.0 / (2.0 * avg_dist * avg_dist)
                } else {
                    1.0
                }
            }
            RBFKernel::Multiquadric | RBFKernel::InverseMultiquadric => {
                // For multiquadrics, a typical choice is 1 / average distance
                let avg_dist = Self::average_distance(points);
                if avg_dist > 0.0 {
                    1.0 / avg_dist
                } else {
                    1.0
                }
            }
            // Other kernels don't use epsilon (or it's absorbed into the coefficients)
            _ => 1.0,
        }
    }

    /// Calculate average distance between points
    ///
    /// # Arguments
    ///
    /// * `points` - The input points
    ///
    /// # Returns
    ///
    /// The average distance between points
    fn average_distance(points: &ArrayView2<'_, f64>) -> f64 {
        let n_points = points.nrows();

        if n_points <= 1 {
            return 0.0;
        }

        // Sample a subset of pairs for efficiency if there are too many _points
        let max_pairs = 1000;
        let mut total_dist = 0.0;
        let mut n_pairs = 0;

        // Calculate average distance
        if n_points * (n_points - 1) / 2 <= max_pairs {
            // Use all pairs for small datasets
            for i in 0..n_points {
                for j in (i + 1)..n_points {
                    let pi = points.row(i);
                    let pj = points.row(j);
                    total_dist += Self::euclidean_distance(&pi, &pj);
                    n_pairs += 1;
                }
            }
        } else {
            // Sample pairs for large datasets
            let mut rng = thread_rng();
            let mut seen_pairs = std::collections::HashSet::new();

            for _ in 0..max_pairs {
                let i = rng.random_range(0..n_points);
                let j = rng.random_range(0..n_points);

                if i != j {
                    let pair = if i < j { (i, j) } else { (j, i) };
                    if !seen_pairs.contains(&pair) {
                        seen_pairs.insert(pair);
                        let pi = points.row(i);
                        let pj = points.row(j);
                        total_dist += Self::euclidean_distance(&pi, &pj);
                        n_pairs += 1;
                    }
                }
            }
        }

        if n_pairs > 0 {
            total_dist / (n_pairs as f64)
        } else {
            1.0
        }
    }

    /// Solve the RBF interpolation system
    ///
    /// # Arguments
    ///
    /// * `points` - Input points
    /// * `values` - Input values
    /// * `kernel` - RBF kernel function
    /// * `epsilon` - Shape parameter
    /// * `polynomial` - Whether to include polynomial terms
    ///
    /// # Returns
    ///
    /// A tuple (weights, poly_coefs) where poly_coefs is None if polynomial=false
    ///
    /// # Errors
    ///
    /// * If the system of equations is singular
    fn solve_rbf_system(
        points: &ArrayView2<'_, f64>,
        values: &ArrayView1<f64>,
        kernel: RBFKernel,
        epsilon: f64,
        polynomial: bool,
    ) -> SpatialResult<(Array1<f64>, Option<Array1<f64>>)> {
        let n_points = points.nrows();
        let dim = points.ncols();

        if !polynomial {
            // Without polynomial terms, we just need to solve A * w = y
            // where A_ij = kernel(||p_i - p_j||, epsilon)
            let mut a = Array2::zeros((n_points, n_points));

            for i in 0..n_points {
                let pi = points.row(i);
                for j in 0..n_points {
                    let pj = points.row(j);
                    let dist = Self::euclidean_distance(&pi, &pj);
                    a[[i, j]] = kernel.apply(dist, epsilon);
                }
            }

            // Manually solve using pseudo-inverse (not ideal but works for now)
            let trans_a = a.t();
            let ata = trans_a.dot(&a);
            let atb = trans_a.dot(&values.to_owned());
            let weights = solve_linear_system(ata, atb);
            match weights {
                Ok(weights) => Ok((weights, None)),
                Err(e) => Err(SpatialError::ComputationError(format!(
                    "Failed to solve RBF system: {e}"
                ))),
            }
        } else {
            // With polynomial terms, we need to set up an augmented system
            // [ A  P ] [ w ]   [ y ]
            // [ P' 0 ] [ c ] = [ 0 ]
            // where P contains the polynomial basis

            // For a linear polynomial, we need [1, x, y, z, ...]
            let poly_terms = dim + 1;

            // Set up the augmented matrix
            let mut aug_matrix = Array2::zeros((n_points + poly_terms, n_points + poly_terms));
            let mut aug_values = Array1::zeros(n_points + poly_terms);

            // Fill in the RBF part (top-left block)
            for i in 0..n_points {
                let pi = points.row(i);
                for j in 0..n_points {
                    let pj = points.row(j);
                    let dist = Self::euclidean_distance(&pi, &pj);
                    aug_matrix[[i, j]] = kernel.apply(dist, epsilon);
                }
            }

            // Fill in the polynomial part (top-right and bottom-left blocks)
            for i in 0..n_points {
                // Constant term
                aug_matrix[[i, n_points]] = 1.0;
                aug_matrix[[n_points, i]] = 1.0;

                // Linear terms
                for j in 0..dim {
                    aug_matrix[[i, n_points + 1 + j]] = points[[i, j]];
                    aug_matrix[[n_points + 1 + j, i]] = points[[i, j]];
                }
            }

            // Fill in the values
            for i in 0..n_points {
                aug_values[i] = values[i];
            }

            // Manually solve using pseudo-inverse (not ideal but works for now)
            let trans_a = aug_matrix.t();
            let ata = trans_a.dot(&aug_matrix);
            let atb = trans_a.dot(&aug_values);
            let solution = solve_linear_system(ata, atb);
            match solution {
                Ok(solution) => {
                    // Extract weights and polynomial coefficients
                    let weights = solution
                        .slice(scirs2_core::ndarray::s![0..n_points])
                        .to_owned();
                    let poly_coefs = solution
                        .slice(scirs2_core::ndarray::s![n_points..])
                        .to_owned();
                    Ok((weights, Some(poly_coefs)))
                }
                Err(e) => Err(SpatialError::ComputationError(format!(
                    "Failed to solve augmented RBF system: {e}"
                ))),
            }
        }
    }

    /// Interpolate at a single point
    ///
    /// # Arguments
    ///
    /// * `point` - Query point with shape (n_dims,)
    ///
    /// # Returns
    ///
    /// Interpolated value at the query point
    ///
    /// # Errors
    ///
    /// * If the point dimensions don't match the interpolator
    pub fn interpolate(&self, point: &ArrayView1<f64>) -> SpatialResult<f64> {
        // Check dimension
        if point.len() != self.dim {
            return Err(SpatialError::DimensionError(format!(
                "Query _point has dimension {}, expected {}",
                point.len(),
                self.dim
            )));
        }

        // Evaluate the RBF interpolant at the query _point
        let mut result = 0.0;

        // Sum over all RBF terms
        for i in 0..self.n_points {
            let pi = self.points.row(i);
            let dist = Self::euclidean_distance(&pi, point);
            result += self.weights[i] * self.kernel.apply(dist, self.epsilon);
        }

        // Add polynomial terms if present
        if let Some(ref poly_coefs) = self.poly_coefs {
            // Constant term
            result += poly_coefs[0];

            // Linear terms
            for j in 0..self.dim {
                result += poly_coefs[j + 1] * point[j];
            }
        }

        Ok(result)
    }

    /// Interpolate at multiple points
    ///
    /// # Arguments
    ///
    /// * `points` - Query points with shape (n_queries, n_dims)
    ///
    /// # Returns
    ///
    /// Interpolated values with shape (n_queries,)
    ///
    /// # Errors
    ///
    /// * If the points dimensions don't match the interpolator
    pub fn interpolate_many(&self, points: &ArrayView2<'_, f64>) -> SpatialResult<Array1<f64>> {
        // Check dimensions
        if points.ncols() != self.dim {
            return Err(SpatialError::DimensionError(format!(
                "Query _points have dimension {}, expected {}",
                points.ncols(),
                self.dim
            )));
        }

        let n_queries = points.nrows();
        let mut results = Array1::zeros(n_queries);

        // Interpolate each point
        for i in 0..n_queries {
            let point = points.row(i);
            results[i] = self.interpolate(&point)?;
        }

        Ok(results)
    }

    /// Get the kernel used by this interpolator
    pub fn kernel(&self) -> RBFKernel {
        self.kernel
    }

    /// Get the shape parameter (epsilon) used by this interpolator
    pub fn epsilon(&self) -> f64 {
        self.epsilon
    }

    /// Check if this interpolator includes polynomial terms
    pub fn has_polynomial(&self) -> bool {
        self.polynomial
    }

    /// Compute the Euclidean distance between two points
    ///
    /// # Arguments
    ///
    /// * `p1` - First point
    /// * `p2` - Second point
    ///
    /// # Returns
    ///
    /// Euclidean distance between the points
    fn euclidean_distance(p1: &ArrayView1<f64>, p2: &ArrayView1<f64>) -> f64 {
        let mut sum_sq = 0.0;
        for i in 0..p1.len().min(p2.len()) {
            let diff = p1[i] - p2[i];
            sum_sq += diff * diff;
        }
        sum_sq.sqrt()
    }
}

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

    #[test]
    fn test_rbf_interpolation_basic() {
        // Create a simple grid of points
        let points = array![
            [0.0, 0.0], // 0: bottom-left
            [1.0, 0.0], // 1: bottom-right
            [0.0, 1.0], // 2: top-left
            [1.0, 1.0], // 3: top-right
        ];

        // Set up a simple function z = x + y
        let values = array![0.0, 1.0, 1.0, 2.0];

        // Test different kernels
        let kernels = [
            RBFKernel::Gaussian,
            RBFKernel::Multiquadric,
            RBFKernel::InverseMultiquadric,
            RBFKernel::ThinPlateSpline,
            RBFKernel::Linear,
            RBFKernel::Cubic,
        ];

        for kernel in &kernels {
            // Create the interpolator
            let interp = RBFInterpolator::new(&points.view(), &values.view(), *kernel, None, None)
                .expect("Operation failed");

            // Test at the data points (should interpolate exactly)
            let val_00 = interp
                .interpolate(&array![0.0, 0.0].view())
                .expect("Operation failed");
            let val_10 = interp
                .interpolate(&array![1.0, 0.0].view())
                .expect("Operation failed");
            let val_01 = interp
                .interpolate(&array![0.0, 1.0].view())
                .expect("Operation failed");
            let val_11 = interp
                .interpolate(&array![1.0, 1.0].view())
                .expect("Operation failed");

            assert_relative_eq!(val_00, 0.0, epsilon = 1e-6);
            assert_relative_eq!(val_10, 1.0, epsilon = 1e-6);
            assert_relative_eq!(val_01, 1.0, epsilon = 1e-6);
            assert_relative_eq!(val_11, 2.0, epsilon = 1e-6);

            // Test at the center - we don't check exact value as it varies by kernel
            let val_center = interp
                .interpolate(&array![0.5, 0.5].view())
                .expect("Operation failed");

            // Instead of checking against 1.0, just make sure the value is finite
            assert!(val_center.is_finite());
        }
    }

    #[test]
    fn test_rbf_with_polynomial() {
        // Create data points on a line
        let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0],];

        // Linear function z = 2*x + 3*y + 1
        let values = array![1.0, 3.0, 4.0, 6.0];

        // Create interpolator with polynomial
        let interp = RBFInterpolator::new(
            &points.view(),
            &values.view(),
            RBFKernel::Gaussian,
            Some(1.0),
            Some(true),
        )
        .expect("Operation failed");

        assert!(interp.has_polynomial());

        // Test at data points
        let val_00 = interp
            .interpolate(&array![0.0, 0.0].view())
            .expect("Operation failed");
        let val_10 = interp
            .interpolate(&array![1.0, 0.0].view())
            .expect("Operation failed");
        let val_01 = interp
            .interpolate(&array![0.0, 1.0].view())
            .expect("Operation failed");
        let val_11 = interp
            .interpolate(&array![1.0, 1.0].view())
            .expect("Operation failed");

        assert_relative_eq!(val_00, 1.0, epsilon = 1e-6);
        assert_relative_eq!(val_10, 3.0, epsilon = 1e-6);
        assert_relative_eq!(val_01, 4.0, epsilon = 1e-6);
        assert_relative_eq!(val_11, 6.0, epsilon = 1e-6);

        // Test at a new point - should follow linear pattern
        let val_new = interp
            .interpolate(&array![2.0, 2.0].view())
            .expect("Operation failed");
        // 2*x + 3*y + 1 = 2*2 + 3*2 + 1 = 11
        assert_relative_eq!(val_new, 11.0, epsilon = 0.1);
    }

    #[test]
    fn test_interpolate_many() {
        // Create a simple grid of points
        let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0],];

        // Set up a simple function z = x + y
        let values = array![0.0, 1.0, 1.0, 2.0];

        // Create the interpolator
        let interp = RBFInterpolator::new(
            &points.view(),
            &values.view(),
            RBFKernel::Gaussian,
            None,
            None,
        )
        .expect("Operation failed");

        // Test multiple points at once
        let query_points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.5, 0.5],];

        let results = interp
            .interpolate_many(&query_points.view())
            .expect("Operation failed");

        assert_eq!(results.len(), 5);
        assert_relative_eq!(results[0], 0.0, epsilon = 1e-6);
        assert_relative_eq!(results[1], 1.0, epsilon = 1e-6);
        assert_relative_eq!(results[2], 1.0, epsilon = 1e-6);
        assert_relative_eq!(results[3], 2.0, epsilon = 1e-6);
        assert_relative_eq!(results[4], 1.0, epsilon = 0.1);
    }

    #[test]
    fn test_error_handling() {
        // Not enough points
        let points = array![[0.0, 0.0]];
        let values = array![0.0];

        let result = RBFInterpolator::new(
            &points.view(),
            &values.view(),
            RBFKernel::Gaussian,
            None,
            None,
        );
        assert!(result.is_err());

        // Mismatched lengths
        let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let values = array![0.0, 1.0];

        let result = RBFInterpolator::new(
            &points.view(),
            &values.view(),
            RBFKernel::Gaussian,
            None,
            None,
        );
        assert!(result.is_err());

        // Valid interpolator but wrong dimension for query
        let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let values = array![0.0, 1.0, 2.0];

        let interp = RBFInterpolator::new(
            &points.view(),
            &values.view(),
            RBFKernel::Gaussian,
            None,
            None,
        )
        .expect("Operation failed");

        let result = interp.interpolate(&array![0.0, 0.0, 0.0].view());
        assert!(result.is_err());
    }
}