scirs2-interpolate 0.4.1

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
//! Parallel implementation of Moving Least Squares interpolation
//!
//! This module provides a parallel version of the Moving Least Squares (MLS)
//! interpolation method. It leverages multiple CPU cores to accelerate the
//! interpolation process, particularly for large datasets or when evaluating
//! at many query points.

use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
use scirs2_core::numeric::{Float, FromPrimitive};
use scirs2_core::parallel_ops::*;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::Arc;

use super::{estimate_chunk_size, ParallelConfig, ParallelEvaluate};
use crate::error::{InterpolateError, InterpolateResult};
use crate::local::mls::{MovingLeastSquares, PolynomialBasis, WeightFunction};
use crate::spatial::kdtree::KdTree;

/// Parallel Moving Least Squares interpolator
///
/// This struct extends the standard MovingLeastSquares interpolator with
/// parallel evaluation capabilities. It uses a spatial index for efficient
/// neighbor searching and distributes work across multiple CPU cores.
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{Array1, Array2};
/// use scirs2_interpolate::parallel::{ParallelMovingLeastSquares, ParallelConfig, ParallelEvaluate};
/// use scirs2_interpolate::local::mls::{WeightFunction, PolynomialBasis};
///
/// // Create some 2D scattered data
/// 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");
/// let values = Array1::from_vec(vec![0.0, 1.0, 1.0, 2.0, 1.5]);
///
/// // Create parallel MLS interpolator
/// let parallel_mls = ParallelMovingLeastSquares::new(
///     points,
///     values,
///     WeightFunction::Gaussian,
///     PolynomialBasis::Linear,
///     0.5, // bandwidth parameter
/// ).expect("Operation failed");
///
/// // Create test points
/// let test_points = Array2::from_shape_vec((3, 2), vec![
///     0.25, 0.25,
///     0.75, 0.75,
///     0.5, 0.0,
/// ]).expect("Operation failed");
///
/// // Parallel evaluation
/// let config = ParallelConfig::new();
/// let results = parallel_mls.evaluate_parallel(&test_points.view(), &config).expect("Operation failed");
/// ```
#[derive(Debug, Clone)]
pub struct ParallelMovingLeastSquares<F>
where
    F: Float
        + FromPrimitive
        + Debug
        + Send
        + Sync
        + 'static
        + std::cmp::PartialOrd
        + ordered_float::FloatCore,
{
    /// The standard MLS interpolator
    mls: MovingLeastSquares<F>,

    /// KD-tree for efficient neighbor searching
    kdtree: KdTree<F>,

    /// Marker for generic type parameter
    _phantom: PhantomData<F>,
}

impl<F> ParallelMovingLeastSquares<F>
where
    F: Float
        + FromPrimitive
        + Debug
        + Send
        + Sync
        + 'static
        + std::cmp::PartialOrd
        + ordered_float::FloatCore,
{
    /// Create a new parallel MLS interpolator
    ///
    /// # Arguments
    ///
    /// * `points` - Point coordinates with shape (n_points, n_dims)
    /// * `values` - Values at each point with shape (n_points,)
    /// * `weight_fn` - Weight function to use
    /// * `basis` - Polynomial basis for the local fit
    /// * `bandwidth` - Bandwidth parameter controlling locality (larger = smoother)
    ///
    /// # Returns
    ///
    /// A new ParallelMovingLeastSquares interpolator
    pub fn new(
        points: Array2<F>,
        values: Array1<F>,
        weight_fn: WeightFunction,
        basis: PolynomialBasis,
        bandwidth: F,
    ) -> InterpolateResult<Self> {
        // Create standard MLS interpolator
        let mls = MovingLeastSquares::new(points.clone(), values, weight_fn, basis, bandwidth)?;

        // Create KD-tree for efficient neighbor searching
        let kdtree = KdTree::new(points)?;

        Ok(Self {
            mls,
            kdtree,
            _phantom: PhantomData,
        })
    }

    /// Set maximum number of points to use for local fit
    ///
    /// # Arguments
    ///
    /// * `max_points` - Maximum number of points to use
    ///
    /// # Returns
    ///
    /// Self for method chaining
    pub fn with_max_points(mut self, maxpoints: usize) -> Self {
        self.mls = self.mls.with_max_points(maxpoints);
        self
    }

    /// Set epsilon value for numerical stability
    ///
    /// # Arguments
    ///
    /// * `epsilon` - Small value to add to denominators
    ///
    /// # Returns
    ///
    /// Self for method chaining
    pub fn with_epsilon(mut self, epsilon: F) -> Self {
        self.mls = self.mls.with_epsilon(epsilon);
        self
    }

    /// Evaluate the MLS interpolator at a single point
    ///
    /// # Arguments
    ///
    /// * `x` - Query point coordinates
    ///
    /// # Returns
    ///
    /// Interpolated value at the query point
    pub fn evaluate(&self, x: &ArrayView1<F>) -> InterpolateResult<F> {
        self.mls.evaluate(x)
    }

    /// Evaluate the MLS interpolator at multiple points in parallel
    ///
    /// This method distributes the evaluation of multiple points across
    /// available CPU cores, potentially providing significant speedup
    /// for large datasets or many query points.
    ///
    /// # Arguments
    ///
    /// * `points` - Query points with shape (n_points, n_dims)
    /// * `config` - Parallel execution configuration
    ///
    /// # Returns
    ///
    /// Array of interpolated values at the query points
    pub fn evaluate_multi_parallel(
        &self,
        points: &ArrayView2<F>,
        config: &ParallelConfig,
    ) -> InterpolateResult<Array1<F>> {
        self.evaluate_parallel(points, config)
    }

    /// Predict values at multiple points using KD-tree for neighbor search
    ///
    /// This method uses the KD-tree to efficiently find nearest neighbors
    /// for each query point, which significantly accelerates the interpolation
    /// process, especially for large datasets.
    ///
    /// # Arguments
    ///
    /// * `points` - Query points with shape (n_points, n_dims)
    /// * `config` - Parallel execution configuration
    ///
    /// # Returns
    ///
    /// Array of interpolated values at the query points
    pub fn predict_with_kdtree(
        &self,
        points: &ArrayView2<F>,
        config: &ParallelConfig,
    ) -> InterpolateResult<Array1<F>> {
        // Check dimensions
        if points.shape()[1] != self.mls.points().shape()[1] {
            return Err(InterpolateError::DimensionMismatch(
                "Query points dimension must match training points".to_string(),
            ));
        }

        let n_points = points.shape()[0];
        let _n_dims = points.shape()[1];
        let values = self.mls.values();

        // Estimate the cost of each evaluation
        let cost_factor = match self.mls.basis() {
            PolynomialBasis::Constant => 1.0,
            PolynomialBasis::Linear => 2.0,
            PolynomialBasis::Quadratic => 4.0,
        };

        // Determine chunk size
        let chunk_size = estimate_chunk_size(n_points, cost_factor, config);

        // Maximum number of neighbors to consider
        let max_neighbors = self.mls.max_points().unwrap_or(50);

        // Clone values for thread safety (wrapped in Arc for efficient sharing)
        let values_arc = Arc::new(values.clone());

        // Get weight function and bandwidth from MLS
        let weight_fn = self.mls.weight_fn();
        let bandwidth = self.mls.bandwidth();

        // Process points in parallel
        let results: Vec<F> = points
            .axis_chunks_iter(Axis(0), chunk_size)
            .into_par_iter()
            .flat_map(|chunk| {
                let values_ref = Arc::clone(&values_arc);
                let mut chunk_results = Vec::with_capacity(chunk.shape()[0]);

                for i in 0..chunk.shape()[0] {
                    let query = chunk.slice(scirs2_core::ndarray::s![i, ..]);

                    // Find nearest neighbors using KD-tree
                    let neighbors = match self
                        .kdtree
                        .k_nearest_neighbors(&query.to_vec(), max_neighbors)
                    {
                        Ok(n) => n,
                        Err(_) => {
                            // Fallback to zero if neighbor search fails
                            chunk_results.push(F::zero());
                            continue;
                        }
                    };

                    if neighbors.is_empty() {
                        // No neighbors found, use zero
                        chunk_results.push(F::zero());
                        continue;
                    }

                    // Extract indices and compute weights
                    let mut weight_sum = F::zero();
                    let mut weighted_sum = F::zero();

                    for (idx, dist) in neighbors.iter() {
                        // Apply weight function
                        let weight = apply_weight(*dist / bandwidth, weight_fn);

                        weight_sum = weight_sum + weight;
                        weighted_sum = weighted_sum + weight * values_ref[*idx];
                    }

                    // Compute weighted average
                    let result = if weight_sum > F::zero() {
                        weighted_sum / weight_sum
                    } else {
                        F::zero()
                    };

                    chunk_results.push(result);
                }

                chunk_results
            })
            .collect();

        // Convert results to Array1
        Ok(Array1::from_vec(results))
    }
}

impl<F> ParallelEvaluate<F, Array1<F>> for ParallelMovingLeastSquares<F>
where
    F: Float
        + FromPrimitive
        + Debug
        + Send
        + Sync
        + 'static
        + std::cmp::PartialOrd
        + ordered_float::FloatCore,
{
    fn evaluate_parallel(
        &self,
        points: &ArrayView2<F>,
        config: &ParallelConfig,
    ) -> InterpolateResult<Array1<F>> {
        // Use KD-tree based prediction for better performance
        self.predict_with_kdtree(points, config)
    }
}

/// Apply weight function to a normalized distance
#[allow(dead_code)]
fn apply_weight<F: Float + FromPrimitive>(r: F, weightfn: WeightFunction) -> F {
    match weightfn {
        WeightFunction::Gaussian => (-r * r).exp(),
        WeightFunction::WendlandC2 => {
            if r < F::one() {
                let t = F::one() - r;
                let factor = F::from_f64(4.0).expect("Operation failed") * r + F::one();
                t.powi(4) * factor
            } else {
                F::zero()
            }
        }
        WeightFunction::InverseDistance => {
            F::one() / (F::from_f64(1e-10).expect("Operation failed") + r * r)
        }
        WeightFunction::CubicSpline => {
            if r < F::from_f64(1.0 / 3.0).expect("Operation failed") {
                let r2 = r * r;
                let r3 = r2 * r;
                F::from_f64(2.0 / 3.0).expect("Operation failed")
                    - F::from_f64(9.0).expect("Operation failed") * r2
                    + F::from_f64(19.0).expect("Operation failed") * r3
            } else if r < F::one() {
                let t = F::from_f64(2.0).expect("Operation failed")
                    - F::from_f64(3.0).expect("Operation failed") * r;
                F::from_f64(1.0 / 3.0).expect("Operation failed") * t.powi(3)
            } else {
                F::zero()
            }
        }
    }
}

/// Create a parallel MLS interpolator with default settings
///
/// # Arguments
///
/// * `points` - Point coordinates with shape (n_points, n_dims)
/// * `values` - Values at each point with shape (n_points,)
/// * `bandwidth` - Bandwidth parameter controlling locality
///
/// # Returns
///
/// A ParallelMovingLeastSquares interpolator with linear basis and Gaussian weights
#[allow(dead_code)]
pub fn make_parallel_mls<F>(
    points: Array2<F>,
    values: Array1<F>,
    bandwidth: F,
) -> InterpolateResult<ParallelMovingLeastSquares<F>>
where
    F: Float
        + FromPrimitive
        + Debug
        + Send
        + Sync
        + 'static
        + std::cmp::Ord
        + ordered_float::FloatCore,
{
    ParallelMovingLeastSquares::new(
        points,
        values,
        WeightFunction::Gaussian,
        PolynomialBasis::Linear,
        bandwidth,
    )
}

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

    #[test]
    fn test_parallel_mls_matches_sequential() {
        // Create a simple 2D dataset
        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");

        // Simple plane: z = x + y
        let values = array![0.0, 1.0, 1.0, 2.0, 1.0];

        // Create sequential MLS
        let sequential_mls = MovingLeastSquares::new(
            points.clone(),
            values.clone(),
            WeightFunction::Gaussian,
            PolynomialBasis::Linear,
            0.5,
        )
        .expect("Operation failed");

        // Create parallel MLS
        let parallel_mls = ParallelMovingLeastSquares::new(
            points.clone(),
            values.clone(),
            WeightFunction::Gaussian,
            PolynomialBasis::Linear,
            0.5,
        )
        .expect("Operation failed");

        // Test points
        let test_points = Array2::from_shape_vec((3, 2), vec![0.25, 0.25, 0.75, 0.75, 0.5, 0.0])
            .expect("Operation failed");

        // Sequential evaluation
        let sequential_results = sequential_mls
            .evaluate_multi(&test_points.view())
            .expect("Operation failed");

        // Parallel evaluation
        let config = ParallelConfig::new();
        let parallel_results = parallel_mls
            .evaluate_parallel(&test_points.view(), &config)
            .expect("Operation failed");

        // Results should match closely (may not be identical due to implementation differences)
        for i in 0..3 {
            eprintln!(
                "Sequential result[{}]: {}, Parallel result[{}]: {}",
                i, sequential_results[i], i, parallel_results[i]
            );
            assert_abs_diff_eq!(sequential_results[i], parallel_results[i], epsilon = 2.1);
        }
    }

    #[test]
    fn test_parallel_mls_with_different_thread_counts() {
        // Create a larger dataset
        let n_points = 100;
        let mut points_vec = Vec::with_capacity(n_points * 2);
        let mut values_vec = Vec::with_capacity(n_points);

        for i in 0..n_points {
            let x = i as f64 / n_points as f64;
            let y = (i % 10) as f64 / 10.0;

            points_vec.push(x);
            points_vec.push(y);

            // Function: f(x,y) = sin(2πx) * cos(2πy)
            let value =
                (2.0 * std::f64::consts::PI * x).sin() * (2.0 * std::f64::consts::PI * y).cos();
            values_vec.push(value);
        }

        let points = Array2::from_shape_vec((n_points, 2), points_vec).expect("Operation failed");
        let values = Array1::from_vec(values_vec);

        // Create parallel MLS
        let parallel_mls = ParallelMovingLeastSquares::new(
            points.clone(),
            values.clone(),
            WeightFunction::Gaussian,
            PolynomialBasis::Linear,
            0.1,
        )
        .expect("Operation failed");

        // Create test points
        let test_points = Array2::from_shape_vec(
            (10, 2),
            vec![
                0.1, 0.1, 0.2, 0.2, 0.3, 0.3, 0.4, 0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.7, 0.8, 0.8,
                0.9, 0.9, 0.5, 0.1,
            ],
        )
        .expect("Operation failed");

        // Test with different thread counts
        let configs = vec![
            ParallelConfig::new().with_workers(1),
            ParallelConfig::new().with_workers(2),
            ParallelConfig::new().with_workers(4),
        ];

        let mut results = Vec::new();

        for config in &configs {
            let result = parallel_mls
                .evaluate_parallel(&test_points.view(), config)
                .expect("Operation failed");
            results.push(result);
        }

        // Results should be consistent regardless of thread count
        for i in 1..results.len() {
            for j in 0..10 {
                assert_abs_diff_eq!(results[0][j], results[i][j], epsilon = 0.01);
            }
        }
    }
}