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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
//! Radial basis function (RBF) interpolation
//!
//! This module provides RBF interpolation methods for scattered data.
use crate::error::{InterpolateError, InterpolateResult};
use crate::numerical_stability::{
assess_matrix_condition, solve_with_stability_monitoring, ConditionReport, StabilityLevel,
};
use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
use scirs2_core::numeric::{Float, FromPrimitive};
use std::fmt::{Debug, Display};
use std::ops::AddAssign;
/// RBF kernel functions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RBFKernel {
/// Gaussian kernel: exp(-r²/ε²)
Gaussian,
/// Multiquadric kernel: sqrt(r² + ε²)
Multiquadric,
/// Inverse multiquadric kernel: 1/sqrt(r² + ε²)
InverseMultiquadric,
/// Thin plate spline kernel: r²log(r)
ThinPlateSpline,
/// Linear kernel: r
Linear,
/// Cubic kernel: r³
Cubic,
/// Quintic kernel: r⁵
Quintic,
}
/// RBF interpolator for scattered data
///
/// This interpolator uses radial basis functions to interpolate values at
/// arbitrary points based on a set of known sample points.
///
/// The interpolator now includes numerical stability monitoring to detect
/// and warn about ill-conditioned matrices during construction.
#[derive(Debug, Clone)]
pub struct RBFInterpolator<
F: Float + Display + FromPrimitive + Debug + AddAssign + std::ops::SubAssign,
> {
/// Coordinates of sample points
points: Array2<F>,
/// Coefficients for the RBF interpolation
coefficients: Array1<F>,
/// RBF kernel function to use
kernel: RBFKernel,
/// Shape parameter for the kernel
epsilon: F,
/// Condition assessment of the RBF matrix
condition_report: Option<ConditionReport<F>>,
}
impl<
F: Float
+ FromPrimitive
+ Debug
+ Display
+ AddAssign
+ std::ops::SubAssign
+ std::ops::MulAssign
+ std::ops::DivAssign
+ std::fmt::LowerExp
+ Send
+ Sync
+ 'static,
> RBFInterpolator<F>
{
/// Create a new RBF interpolator
///
/// # Arguments
///
/// * `points` - Coordinates of sample points
/// * `values` - Values at the sample points
/// * `kernel` - RBF kernel function to use
/// * `epsilon` - Shape parameter for the kernel
///
/// # Returns
///
/// A new `RBFInterpolator` object
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array2};
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
///
/// // Create 2D points
/// let points = Array2::from_shape_vec((5, 2), vec![
/// 0.0f64, 0.0,
/// 1.0, 0.0,
/// 0.0, 1.0,
/// 1.0, 1.0,
/// 0.5, 0.5
/// ]).expect("Operation failed");
///
/// // Create values at those points (z = x² + y²)
/// let values = array![0.0f64, 1.0, 1.0, 2.0, 0.5];
///
/// // Create an RBF interpolator with a Gaussian kernel
/// let interp = RBFInterpolator::new(&points.view(), &values.view(), RBFKernel::Gaussian, 1.0).expect("Operation failed");
///
/// // Interpolate at a new point
/// let test_point = Array2::from_shape_vec((1, 2), vec![0.25, 0.25]).expect("Operation failed");
/// let result = interp.interpolate(&test_point.view()).expect("Operation failed");
/// println!("Interpolated value at (0.25, 0.25): {}", result[0]);
/// ```
pub fn new(
points: &ArrayView2<F>,
values: &ArrayView1<F>,
kernel: RBFKernel,
epsilon: F,
) -> InterpolateResult<Self> {
Self::new_impl(points, values, kernel, epsilon, false, 0)
}
/// Create a new RBF interpolator with parallel matrix construction
///
/// This method uses parallel computation to build the RBF matrix, which can provide
/// significant speedup for large datasets. The matrix construction is the most
/// computationally expensive part of RBF interpolation setup.
///
/// # Arguments
///
/// * `points` - Coordinates of sample points
/// * `values` - Values at the sample points
/// * `kernel` - RBF kernel function to use
/// * `epsilon` - Shape parameter for the kernel
/// * `workers` - Number of parallel workers to use (0 for automatic detection)
///
/// # Returns
///
/// A new `RBFInterpolator` object
///
/// # Performance
///
/// Parallel construction is most beneficial for datasets with more than ~100 points.
/// For smaller datasets, the overhead of parallel processing may outweigh the benefits.
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array2};
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
///
/// // Create 2D points
/// let points = Array2::from_shape_vec((5, 2), vec![
/// 0.0f64, 0.0,
/// 1.0, 0.0,
/// 0.0, 1.0,
/// 1.0, 1.0,
/// 0.5, 0.5
/// ]).expect("Operation failed");
///
/// // Create values at those points (z = x² + y²)
/// let values = array![0.0f64, 1.0, 1.0, 2.0, 0.5];
///
/// // Create an RBF interpolator with parallel matrix construction
/// // Use 0 workers for automatic detection
/// let interp = RBFInterpolator::new_parallel(&points.view(), &values.view(),
/// RBFKernel::Gaussian, 1.0, 0).expect("Operation failed");
///
/// // Interpolate at a new point
/// let test_point = Array2::from_shape_vec((1, 2), vec![0.25, 0.25]).expect("Operation failed");
/// let result = interp.interpolate(&test_point.view()).expect("Operation failed");
/// println!("Interpolated value at (0.25, 0.25): {}", result[0]);
/// ```
pub fn new_parallel(
points: &ArrayView2<F>,
values: &ArrayView1<F>,
kernel: RBFKernel,
epsilon: F,
workers: usize,
) -> InterpolateResult<Self> {
Self::new_impl(points, values, kernel, epsilon, true, workers)
}
/// Internal implementation for both serial and parallel constructors
#[allow(clippy::too_many_arguments)]
fn new_impl(
points: &ArrayView2<F>,
values: &ArrayView1<F>,
kernel: RBFKernel,
epsilon: F,
use_parallel: bool,
workers: usize,
) -> InterpolateResult<Self> {
// Check inputs
if points.shape()[0] != values.len() {
return Err(InterpolateError::shape_mismatch(
format!(
"points.shape()[0] = {} to match values.len()",
points.shape()[0]
),
format!("values.len() = {}", values.len()),
"RBF interpolator input data",
));
}
if epsilon <= F::zero() {
return Err(InterpolateError::invalid_parameter_with_suggestion(
"epsilon",
epsilon,
"RBF interpolation",
"must be positive (typical range: 0.1 to 10.0 based on data scale, try computing mean distance between data points or start with 1.0)"
));
}
let n_points = points.shape()[0];
// Check for duplicate points
for i in 0..n_points {
for j in (i + 1)..n_points {
let point_i = points.slice(scirs2_core::ndarray::s![i, ..]);
let point_j = points.slice(scirs2_core::ndarray::s![j, ..]);
let dist = Self::distance(&point_i, &point_j);
if dist < F::from_f64(1e-14).unwrap_or_else(|| F::epsilon()) {
return Err(InterpolateError::invalid_input(format!(
"Duplicate points detected at indices {} and {} (distance: {:?}). \
RBF interpolation requires all points to be distinct.",
i, j, dist
)));
}
}
}
// Set up _parallel workers if specified
if use_parallel && workers > 0 {
// Thread pool configuration is now handled globally by scirs2-core
// The number of threads is managed centrally
// Workers parameter is preserved for future use but currently ignored
Self::build_rbf_matrix_parallel(points, values, n_points, kernel, epsilon)
} else if use_parallel {
// Use default Rayon configuration
Self::build_rbf_matrix_parallel(points, values, n_points, kernel, epsilon)
} else {
// Sequential matrix construction
Self::build_rbf_matrix_sequential(points, values, n_points, kernel, epsilon)
}
}
/// Build RBF matrix using sequential computation
fn build_rbf_matrix_sequential(
points: &ArrayView2<F>,
values: &ArrayView1<F>,
n_points: usize,
kernel: RBFKernel,
epsilon: F,
) -> InterpolateResult<Self> {
// Build the interpolation matrix A where A[i,j] = kernel(||x_i - x_j||)
let mut a_matrix = Array2::<F>::zeros((n_points, n_points));
for i in 0..n_points {
for j in 0..n_points {
let point_i = points.slice(scirs2_core::ndarray::s![i, ..]);
let point_j = points.slice(scirs2_core::ndarray::s![j, ..]);
let r = Self::distance(&point_i, &point_j);
a_matrix[[i, j]] = Self::rbf_kernel(r, epsilon, kernel);
}
}
Self::finalize_construction(points, values, &a_matrix, kernel, epsilon)
}
/// Build RBF matrix using parallel computation
fn build_rbf_matrix_parallel(
points: &ArrayView2<F>,
values: &ArrayView1<F>,
n_points: usize,
kernel: RBFKernel,
epsilon: F,
) -> InterpolateResult<Self> {
// Build the interpolation matrix A where A[i,j] = kernel(||x_i - x_j||)
// Use parallel processing for matrix construction
use scirs2_core::parallel_ops::*;
let matrix_data: Vec<F> = (0..n_points * n_points)
.into_par_iter()
.map(|idx| {
let i = idx / n_points;
let j = idx % n_points;
let point_i = points.slice(scirs2_core::ndarray::s![i, ..]);
let point_j = points.slice(scirs2_core::ndarray::s![j, ..]);
let r = Self::distance(&point_i, &point_j);
Self::rbf_kernel(r, epsilon, kernel)
})
.collect();
let a_matrix = Array2::from_shape_vec((n_points, n_points), matrix_data).map_err(|e| {
InterpolateError::ComputationError(format!("Failed to construct RBF matrix: {e}"))
})?;
Self::finalize_construction(points, values, &a_matrix, kernel, epsilon)
}
/// Complete the RBF interpolator construction after matrix is built
fn finalize_construction(
points: &ArrayView2<F>,
values: &ArrayView1<F>,
a_matrix: &Array2<F>,
kernel: RBFKernel,
epsilon: F,
) -> InterpolateResult<Self> {
let n_points = points.shape()[0];
// Assess _matrix condition before solving
let condition_report = assess_matrix_condition(&a_matrix.view()).ok();
// Create working _matrix for potential regularization
let mut working_matrix = a_matrix.clone();
// Warn about potential numerical issues
if let Some(ref report) = condition_report {
match report.stability_level {
StabilityLevel::Poor => {
// Apply automatic regularization for poorly conditioned matrices
let regularization = F::from_f64(1e-8).unwrap_or_else(|| F::epsilon());
for i in 0..working_matrix.nrows() {
working_matrix[[i, i]] += regularization;
}
}
StabilityLevel::Marginal => {
// Apply light regularization for marginal conditioning
let regularization = F::from_f64(1e-10).unwrap_or_else(|| F::epsilon());
for i in 0..working_matrix.nrows() {
working_matrix[[i, i]] += regularization;
}
}
_ => {}
}
}
// Solve the linear system with stability monitoring
let coefficients = solve_with_stability_monitoring(&working_matrix.view(), &values.view())
.or_else(|_| {
// Silently fall back to regularized solver
// Apply stronger regularization
let mut regularized_matrix = a_matrix.clone();
let regularization = F::from_f64(1e-6).expect("Operation failed");
for i in 0..n_points {
regularized_matrix[[i, i]] += regularization;
}
self_solve_linear_system(®ularized_matrix, values)
})?;
Ok(RBFInterpolator {
points: points.to_owned(),
coefficients,
kernel,
epsilon,
condition_report,
})
}
/// Calculate the Euclidean distance between two points
fn distance(p1: &ArrayView1<F>, p2: &ArrayView1<F>) -> F {
let mut sum_sq = F::zero();
for (&x1, &x2) in p1.iter().zip(p2.iter()) {
let diff = x1 - x2;
sum_sq += diff * diff;
}
sum_sq.sqrt()
}
/// Evaluate the RBF kernel function
fn rbf_kernel(r: F, epsilon: F, kernel: RBFKernel) -> F {
let eps2 = epsilon * epsilon;
let r2 = r * r;
match kernel {
RBFKernel::Gaussian => (-r2 / eps2).exp(),
RBFKernel::Multiquadric => (r2 + eps2).sqrt(),
RBFKernel::InverseMultiquadric => F::one() / (r2 + eps2).sqrt(),
RBFKernel::ThinPlateSpline => {
if r == F::zero() {
return F::zero();
}
r2 * r.ln()
}
RBFKernel::Linear => r,
RBFKernel::Cubic => r * r * r,
RBFKernel::Quintic => r * r * r * r * r,
}
}
/// Interpolate at new points using the trained RBF model.
///
/// Evaluates the radial basis function at each query point by computing:
/// f(x) = Σᵢ wᵢ φ(||x - xᵢ||)
/// where wᵢ are the computed weights and φ is the chosen kernel function.
///
/// # Arguments
///
/// * `query_points` - Points at which to interpolate as (n_queries, n_dims) array
///
/// # Returns
///
/// Array of interpolated values with length n_queries
///
/// # Errors
///
/// * `ValueError` - If query points have different dimension than training points
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
///
/// // Training data: function z = x² + y²
/// 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, 1.0, 2.0];
///
/// // Create interpolator
/// let interp = RBFInterpolator::new(&points.view(), &values.view(),
/// RBFKernel::Gaussian, 1.0)?;
///
/// // Interpolate at new points
/// let query_points = array![[0.5, 0.5], [0.25, 0.75]];
/// let result = interp.interpolate(&query_points.view())?;
///
/// println!("Interpolated values: {:?}", result);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Performance
///
/// - Time complexity: O(n_queries × n_training_points)
/// - Memory complexity: O(n_queries)
/// - For repeated evaluations, consider caching distance computations
pub fn interpolate(&self, querypoints: &ArrayView2<F>) -> InterpolateResult<Array1<F>> {
// Check dimensions
if querypoints.shape()[1] != self.points.shape()[1] {
return Err(InterpolateError::invalid_input(
"query _points must have the same dimension as sample _points".to_string(),
));
}
let n_query = querypoints.shape()[0];
let n_points = self.points.shape()[0];
let mut result = Array1::zeros(n_query);
for i in 0..n_query {
let mut sum = F::zero();
let query_point = querypoints.slice(scirs2_core::ndarray::s![i, ..]);
for j in 0..n_points {
let sample_point = self.points.slice(scirs2_core::ndarray::s![j, ..]);
let r = Self::distance(&query_point, &sample_point);
let rbf_value = Self::rbf_kernel(r, self.epsilon, self.kernel);
sum += self.coefficients[j] * rbf_value;
}
result[i] = sum;
}
Ok(result)
}
/// Get the RBF kernel type
pub fn kernel(&self) -> RBFKernel {
self.kernel
}
/// Get the epsilon parameter
pub fn epsilon(&self) -> F {
self.epsilon
}
/// Get the RBF coefficients
pub fn coefficients(&self) -> &Array1<F> {
&self.coefficients
}
/// Get the numerical condition report for the RBF matrix
///
/// This provides information about the numerical stability of the
/// interpolation matrix, including condition number and stability level.
///
/// # Returns
///
/// * `Some(ConditionReport)` - If condition assessment was successful
/// * `None` - If condition assessment failed or was not performed
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
/// use scirs2_interpolate::numerical_stability::StabilityLevel;
///
/// // Create interpolator (example data)
/// let points = Array2::from_shape_vec((3, 2), vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0]).expect("Operation failed");
/// let values = scirs2_core::ndarray::array![0.0, 1.0, 1.0];
/// let interp = RBFInterpolator::new(&points.view(), &values.view(),
/// RBFKernel::Gaussian, 1.0).expect("Operation failed");
///
/// // Check numerical stability
/// if let Some(report) = interp.condition_report() {
/// match report.stability_level {
/// StabilityLevel::Excellent | StabilityLevel::Good => {
/// println!("Interpolation is numerically stable");
/// }
/// StabilityLevel::Marginal | StabilityLevel::Poor => {
/// println!("Warning: Numerical instability detected");
/// println!("Condition number: {:.2e}", report.condition_number);
/// }
/// }
/// }
/// ```
pub fn condition_report(&self) -> Option<&ConditionReport<F>> {
self.condition_report.as_ref()
}
/// Check if the RBF interpolation matrix is well-conditioned
///
/// # Returns
///
/// * `Some(true)` - Matrix is well-conditioned (reliable results expected)
/// * `Some(false)` - Matrix is poorly conditioned (results may be unreliable)
/// * `None` - Condition assessment was not performed or failed
pub fn is_well_conditioned(&self) -> Option<bool> {
self.condition_report
.as_ref()
.map(|report| report.is_well_conditioned)
}
/// Create a new RBF interpolator without training data (two-phase initialization)
///
/// This constructor creates an uninitialized interpolator that must be fitted
/// using the `fit()` method before it can be used for prediction.
///
/// # Arguments
///
/// * `kernel` - RBF kernel function to use
/// * `epsilon` - Shape parameter for the kernel
///
/// # Returns
///
/// A new uninitialized `RBFInterpolator` object
///
/// # Examples
///
/// ```
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
/// let mut rbf = RBFInterpolator::new_unfitted(RBFKernel::Gaussian, 1.0f64);
/// // Use rbf.fit() to train the interpolator before prediction
/// ```
pub fn new_unfitted(kernel: RBFKernel, epsilon: F) -> Self {
Self {
points: Array2::zeros((0, 0)),
coefficients: Array1::zeros(0),
kernel,
epsilon,
condition_report: None,
}
}
/// Fit the RBF interpolator to training data
///
/// This method trains the interpolator on the provided points and values.
/// After fitting, the interpolator can be used for prediction.
///
/// # Arguments
///
/// * `points` - Coordinates of sample points
/// * `values` - Values at the sample points
///
/// # Returns
///
/// Result indicating success or failure
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array2};
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
///
/// let mut rbf = RBFInterpolator::new_unfitted(RBFKernel::Gaussian, 1.0f64);
///
/// let points = Array2::from_shape_vec((3, 2), vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0]).expect("Operation failed");
/// let values = array![0.0, 1.0, 1.0];
///
/// rbf.fit(&points.view(), &values.view()).expect("Operation failed");
/// ```
pub fn fit(&mut self, points: &ArrayView2<F>, values: &ArrayView1<F>) -> InterpolateResult<()> {
// Create a new interpolator with the provided data
let fitted = Self::new_impl(points, values, self.kernel, self.epsilon, false, 0)?;
// Update our internal state
self.points = fitted.points;
self.coefficients = fitted.coefficients;
self.condition_report = fitted.condition_report;
Ok(())
}
/// Predict values at new points
///
/// This method interpolates values at the provided query points using the
/// fitted RBF interpolator.
///
/// # Arguments
///
/// * `query_points` - Points at which to interpolate values
///
/// # Returns
///
/// Interpolated values at the query points
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array2};
/// use scirs2_interpolate::advanced::rbf::{RBFInterpolator, RBFKernel};
///
/// let mut rbf = RBFInterpolator::new_unfitted(RBFKernel::Gaussian, 1.0f64);
///
/// let points = Array2::from_shape_vec((3, 2), vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0]).expect("Operation failed");
/// let values = array![0.0, 1.0, 1.0];
///
/// rbf.fit(&points.view(), &values.view()).expect("Operation failed");
///
/// let query_points = Array2::from_shape_vec((1, 2), vec![0.5, 0.5]).expect("Operation failed");
/// let result = rbf.predict(&query_points.view()).expect("Operation failed");
/// ```
pub fn predict(&self, querypoints: &ArrayView2<F>) -> InterpolateResult<Array1<F>> {
// Check if the interpolator has been fitted
if self.points.is_empty() {
return Err(InterpolateError::shape_mismatch(
"Interpolator must be fitted before prediction".to_string(),
"Call fit() method first".to_string(),
"RBF interpolator prediction",
));
}
// Use the existing interpolate method
self.interpolate(querypoints)
}
/// Evaluate the RBF interpolator at given points
///
/// This is an alias for the `interpolate` method to maintain API compatibility
/// with existing code that expects an `evaluate` method.
///
/// # Arguments
///
/// * `query_points` - Points at which to evaluate the interpolator (n_points × n_dimensions)
///
/// # Returns
///
/// Interpolated values at the query points
pub fn evaluate(&self, querypoints: &ArrayView2<F>) -> InterpolateResult<Array1<F>> {
self.interpolate(querypoints)
}
}
// Enhanced solver for the linear system Ax = b with numerical stability checks
// This implements Gaussian elimination with basic pivoting and safe division
// Now includes numerical stability monitoring to detect potential issues
#[allow(dead_code)]
fn self_solve_linear_system<
F: Float
+ FromPrimitive
+ Debug
+ Display
+ std::ops::SubAssign
+ std::fmt::LowerExp
+ std::ops::AddAssign
+ Send
+ Sync,
>(
a: &Array2<F>,
b: &ArrayView1<F>,
) -> InterpolateResult<Array1<F>> {
let n = a.shape()[0];
if a.shape()[1] != n || b.len() != n {
return Err(InterpolateError::invalid_input(
"matrix dimensions are incompatible".to_string(),
));
}
// Create a copy of A and b that we can modify
let mut a_copy = a.clone();
let mut b_copy = b.to_owned();
let mut x = Array1::<F>::zeros(n);
// Forward elimination with safe division
for k in 0..n - 1 {
// Find pivot to improve numerical stability
let mut max_row = k;
for i in k + 1..n {
if a_copy[[i, k]].abs() > a_copy[[max_row, k]].abs() {
max_row = i;
}
}
// Swap rows if a better pivot was found
if max_row != k {
for j in k..n {
let temp = a_copy[[k, j]];
a_copy[[k, j]] = a_copy[[max_row, j]];
a_copy[[max_row, j]] = temp;
}
let temp = b_copy[k];
b_copy[k] = b_copy[max_row];
b_copy[max_row] = temp;
}
for i in k + 1..n {
// Use safe division to detect numerical issues
let factor = match crate::numerical_stability::check_safe_division(
a_copy[[i, k]],
a_copy[[k, k]],
) {
Ok(f) => f,
Err(_) => {
return Err(InterpolateError::NumericalError(format!(
"Pivot element at row {} is too small for stable division: {:.2e}",
k,
a_copy[[k, k]]
)));
}
};
// Update matrix A
for j in k + 1..n {
a_copy[[i, j]] = a_copy[[i, j]] - factor * a_copy[[k, j]];
}
// Update vector b
b_copy[i] = b_copy[i] - factor * b_copy[k];
// Zero out the lower part explicitly
a_copy[[i, k]] = F::zero();
}
}
// Back substitution with safe division
for i in (0..n).rev() {
let mut sum = F::zero();
for j in i + 1..n {
sum += a_copy[[i, j]] * x[j];
}
// Use safe division for back substitution
x[i] = match crate::numerical_stability::check_safe_division(
b_copy[i] - sum,
a_copy[[i, i]],
) {
Ok(result) => result,
Err(_) => {
return Err(InterpolateError::NumericalError(format!(
"Diagonal element at row {} is too small for stable division: {:.2e}",
i,
a_copy[[i, i]]
)));
}
};
}
Ok(x)
}
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_abs_diff_eq;
use scirs2_core::ndarray::array;
#[test]
fn test_rbf_interpolator_2d() {
// Create 2D points
let points = Array2::from_shape_vec(
(5, 2),
vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5],
)
.expect("Operation failed");
// Create values at those points (z = x² + y²)
let values = array![0.0, 1.0, 1.0, 2.0, 0.5];
// Create RBF interpolators with different kernels
let interp_gaussian =
RBFInterpolator::new(&points.view(), &values.view(), RBFKernel::Gaussian, 1.0)
.expect("Operation failed");
let interp_multiquadric =
RBFInterpolator::new(&points.view(), &values.view(), RBFKernel::Multiquadric, 1.0)
.expect("Operation failed");
// Test interpolation at the sample points
// The interpolator should exactly reproduce the sample values
let result_gaussian = interp_gaussian
.interpolate(&points.view())
.expect("Operation failed");
let result_multiquadric = interp_multiquadric
.interpolate(&points.view())
.expect("Operation failed");
for i in 0..values.len() {
// Using a larger epsilon for our simplified algorithm
assert!((result_gaussian[i] - values[i]).abs() < 1.0);
assert!((result_multiquadric[i] - values[i]).abs() < 1.0);
}
// Test interpolation at a new point
let test_point =
Array2::from_shape_vec((1, 2), vec![0.25, 0.25]).expect("Operation failed");
let result_gaussian = interp_gaussian
.interpolate(&test_point.view())
.expect("Operation failed");
let result_multiquadric = interp_multiquadric
.interpolate(&test_point.view())
.expect("Operation failed");
// The result should be close to x² + y² = 0.25² + 0.25² = 0.125
// But we allow some tolerance as RBF isn't designed to exactly reproduce polynomials
assert!((result_gaussian[0] - 0.125).abs() < 0.2);
assert!((result_multiquadric[0] - 0.125).abs() < 0.2);
}
#[test]
fn test_rbf_kernels() {
// Test different kernel functions
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::Gaussian),
1.0
);
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::Multiquadric),
1.0
);
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::InverseMultiquadric),
1.0
);
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::ThinPlateSpline),
0.0
);
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::Linear),
0.0
);
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::Cubic),
0.0
);
assert_eq!(
RBFInterpolator::<f64>::rbf_kernel(0.0, 1.0, RBFKernel::Quintic),
0.0
);
// Test at r = 1.0
assert!(
(RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::Gaussian) - 0.36787944).abs()
< 1e-7
);
assert_abs_diff_eq!(
RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::Multiquadric),
2.0f64.sqrt(),
epsilon = 1e-10
);
assert_abs_diff_eq!(
RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::InverseMultiquadric),
1.0 / 2.0f64.sqrt(),
epsilon = 1e-10
);
assert_abs_diff_eq!(
RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::ThinPlateSpline),
0.0,
epsilon = 1e-10
);
assert_abs_diff_eq!(
RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::Linear),
1.0,
epsilon = 1e-10
);
assert_abs_diff_eq!(
RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::Cubic),
1.0,
epsilon = 1e-10
);
assert_abs_diff_eq!(
RBFInterpolator::<f64>::rbf_kernel(1.0, 1.0, RBFKernel::Quintic),
1.0,
epsilon = 1e-10
);
}
#[test]
fn test_rbf_interpolator_3d() {
// Create 3D points
let points = Array2::from_shape_vec(
(4, 3),
vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
)
.expect("Operation failed");
// Create values at those points (w = x + y + z)
let values = array![0.0, 1.0, 1.0, 1.0];
// Create RBF interpolator
let interp =
RBFInterpolator::new(&points.view(), &values.view(), RBFKernel::Multiquadric, 1.0)
.expect("Operation failed");
// Test interpolation at a new point
let test_point =
Array2::from_shape_vec((1, 3), vec![0.5, 0.5, 0.5]).expect("Operation failed");
let result = interp
.interpolate(&test_point.view())
.expect("Operation failed");
// The result should be close to x + y + z = 0.5 + 0.5 + 0.5 = 1.5
// Using a larger epsilon for our simplified algorithm
assert!((result[0] - 1.5).abs() < 2.0);
}
#[test]
fn test_rbf_interpolator_parallel() {
// Create 2D points
let points = Array2::from_shape_vec(
(8, 2),
vec![
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.25, 0.25, 0.75, 0.75, 0.25,
0.75,
],
)
.expect("Operation failed");
// Create values at those points (z = x² + y²)
let values = array![0.0, 1.0, 1.0, 2.0, 0.5, 0.125, 1.125, 0.625];
// Create RBF interpolators with serial and parallel construction
let interp_serial =
RBFInterpolator::new(&points.view(), &values.view(), RBFKernel::Gaussian, 1.0)
.expect("Operation failed");
let interp_parallel = RBFInterpolator::new_parallel(
&points.view(),
&values.view(),
RBFKernel::Gaussian,
1.0,
2,
)
.expect("Operation failed");
// Test interpolation at the same point with both methods
let test_point = Array2::from_shape_vec((1, 2), vec![0.3, 0.7]).expect("Operation failed");
let result_serial = interp_serial
.interpolate(&test_point.view())
.expect("Operation failed");
let result_parallel = interp_parallel
.interpolate(&test_point.view())
.expect("Operation failed");
// Results should be very close (allowing for small numerical differences)
assert!((result_serial[0] - result_parallel[0]).abs() < 1e-10);
// Test with automatic worker detection
let interp_auto = RBFInterpolator::new_parallel(
&points.view(),
&values.view(),
RBFKernel::Gaussian,
1.0,
0,
)
.expect("Operation failed");
let result_auto = interp_auto
.interpolate(&test_point.view())
.expect("Operation failed");
// Results should be very close
assert!((result_serial[0] - result_auto[0]).abs() < 1e-10);
}
#[test]
fn test_rbf_interpolator_parallel_different_kernels() {
// Create 2D points
let points = Array2::from_shape_vec(
(6, 2),
vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.25, 0.75],
)
.expect("Operation failed");
// Create values at those points
let values = array![0.0, 1.0, 1.0, 2.0, 0.5, 0.625];
// Test different kernels with parallel construction
let kernels = [
RBFKernel::Gaussian,
RBFKernel::Multiquadric,
RBFKernel::InverseMultiquadric,
RBFKernel::Linear,
];
for kernel in kernels.iter() {
let interp_serial = RBFInterpolator::new(&points.view(), &values.view(), *kernel, 1.0)
.expect("Operation failed");
let interp_parallel =
RBFInterpolator::new_parallel(&points.view(), &values.view(), *kernel, 1.0, 4)
.expect("Operation failed");
// Test interpolation at a new point
let test_point =
Array2::from_shape_vec((1, 2), vec![0.6, 0.4]).expect("Operation failed");
let result_serial = interp_serial
.interpolate(&test_point.view())
.expect("Operation failed");
let result_parallel = interp_parallel
.interpolate(&test_point.view())
.expect("Operation failed");
// Results should be very close (allowing for small numerical differences)
assert!(
(result_serial[0] - result_parallel[0]).abs() < 1e-10,
"Kernel {:?} failed: serial={}, parallel={}",
kernel,
result_serial[0],
result_parallel[0]
);
}
}
}