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
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
//! PDE-constrained RBF interpolation.
//!
//! Provides radial basis function interpolation where the solution is constrained
//! to satisfy a given PDE (Laplacian, heat-steady, Poisson) at a set of
//! collocation points via a penalty formulation.
//!
//! # Method
//!
//! Given data sites `x` with values `y` and collocation points `c`, we fit
//! coefficients `α` so that:
//!
//! ```text
//! f(x) = Σ_j α_j φ(||x - x_j||)      (multiquadric RBF)
//! ```
//!
//! The augmented normal equations are:
//!
//! ```text
//! (Φᵀ Φ + λ Lᵀ L) α = Φᵀ y
//! ```
//!
//! where `Φ` is the n×n RBF matrix at the data sites and `L` is the m×n PDE
//! operator matrix evaluated at the collocation points.

use crate::error::InterpolateError;

// ─────────────────────────────────────────────────────────────────────────────
// Public configuration / enum types
// ─────────────────────────────────────────────────────────────────────────────

/// Configuration for the PDE-constrained RBF interpolant.
#[derive(Debug, Clone)]
pub struct PdeConfig {
    /// Penalty weight λ that controls how strongly the PDE is enforced.
    pub lambda_pde: f64,
    /// Shape parameter ε of the multiquadric kernel φ(r) = √(1 + (εr)²).
    pub rbf_shape: f64,
    /// Maximum number of (dummy) iterations (reserved for future iterative
    /// refinement; the current implementation uses a direct solve).
    pub max_iter: usize,
    /// Convergence tolerance (reserved for future use).
    pub tol: f64,
}

impl Default for PdeConfig {
    fn default() -> Self {
        Self {
            lambda_pde: 1.0,
            rbf_shape: 1.0,
            max_iter: 100,
            tol: 1e-8,
        }
    }
}

/// The PDE operator to enforce at the collocation points.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum PdeType {
    /// ∇²u = 0  (Laplace equation; forces harmonic functions).
    Laplacian,
    /// Steady-state heat equation ∇²u = 0 (alias for `Laplacian`).
    HeatSteady,
    /// ∇²u = f(x)  (Poisson; rhs currently set to zero).
    Poisson,
    /// User-supplied operator: apply no extra PDE penalty.
    Custom,
}

// ─────────────────────────────────────────────────────────────────────────────
// Kernel helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Multiquadric kernel:  φ(r) = √(1 + (ε r)²).
#[inline]
pub fn multiquadric(r: f64, eps: f64) -> f64 {
    (1.0 + (eps * r) * (eps * r)).sqrt()
}

/// Second partial derivative of the multiquadric kernel with respect to a
/// single coordinate `coord` (0-indexed), evaluated at distance `r`.
///
/// For a kernel centred at `c`, evaluated at `x` with `r = ||x - c||`:
///
/// ```text
/// ∂²φ/∂xₖ² = ε² (r² − (xₖ − cₖ)²) / (1 + ε²r²)^(3/2)
///           + ε² / (1 + ε²r²)^(1/2)
/// ```
///
/// When `n_dim` is 2 the Laplacian is `∂²φ/∂x₀² + ∂²φ/∂x₁²`.
/// This function returns the contribution of **one** coordinate, so the full
/// Laplacian is obtained by summing over all coordinates.
///
/// # Arguments
/// * `r`       – Euclidean distance between evaluation point and RBF centre.
/// * `eps`     – Shape parameter.
/// * `delta_k` – Signed difference `(xₖ − cₖ)` for the coordinate of interest.
/// * `_n_dim`  – Total number of space dimensions (unused here but kept for
///               symmetry with the caller interface described in the spec).
#[inline]
pub fn multiquadric_d2(r: f64, eps: f64, delta_k: f64, _n_dim: usize) -> f64 {
    let eps2 = eps * eps;
    let r2 = r * r;
    let dk2 = delta_k * delta_k;
    let denom32 = (1.0 + eps2 * r2).powf(1.5);
    let denom12 = (1.0 + eps2 * r2).sqrt();
    // ∂²φ/∂xₖ² = ε²(r² − δₖ²) / denom^(3/2)  +  ε² / denom^(1/2)
    //            … simplifies to  ε² / denom^(3/2)   (after algebra)
    // Full derivation:
    //   φ = (1 + ε²r²)^(1/2)
    //   ∂φ/∂xₖ = ε² (xₖ − cₖ) / φ
    //   ∂²φ/∂xₖ² = ε²/φ − ε⁴ δₖ² / φ³
    //             = ε²(φ² − ε² δₖ²) / φ³
    //             = ε²(1 + ε²(r² − δₖ²)) / φ³
    eps2 * (1.0 + eps2 * (r2 - dk2)) / denom32 + 0.0 * denom12 // denom12 used to silence unused
}

// ─────────────────────────────────────────────────────────────────────────────
// PDE-constrained RBF struct
// ─────────────────────────────────────────────────────────────────────────────

/// PDE-constrained RBF interpolant.
///
/// Fits multiquadric RBF coefficients so that:
/// 1. The interpolant passes (approximately) through the data `(x, y)`.
/// 2. The PDE residual at a set of collocation points is penalised towards zero.
#[derive(Debug, Clone)]
pub struct PdeConstrainedRbf {
    config: PdeConfig,
    /// RBF centres (= data sites after fitting).
    centers: Vec<Vec<f64>>,
    /// RBF coefficients.
    coeffs: Vec<f64>,
    /// Space dimensionality (inferred from data at fit time).
    n_dim: usize,
}

impl PdeConstrainedRbf {
    /// Create a new (un-fitted) `PdeConstrainedRbf`.
    pub fn new(config: PdeConfig) -> Self {
        Self {
            config,
            centers: Vec::new(),
            coeffs: Vec::new(),
            n_dim: 0,
        }
    }

    // ── private geometry helpers ───────────────────────────────────────────

    fn dist(a: &[f64], b: &[f64]) -> f64 {
        a.iter()
            .zip(b.iter())
            .map(|(&ai, &bi)| (ai - bi) * (ai - bi))
            .sum::<f64>()
            .sqrt()
    }

    // ── Φ matrix  (n×n) ───────────────────────────────────────────────────

    fn rbf_matrix(centers: &[Vec<f64>], eps: f64) -> Vec<Vec<f64>> {
        let n = centers.len();
        let mut phi = vec![vec![0.0; n]; n];
        for i in 0..n {
            for j in 0..n {
                let r = Self::dist(&centers[i], &centers[j]);
                phi[i][j] = multiquadric(r, eps);
            }
        }
        phi
    }

    // ── PDE operator matrix  L  (m×n) ─────────────────────────────────────
    // Each row corresponds to one collocation point; each column to one RBF centre.
    // The entry L[i][j] = (∇² φ_j)(collocation_pts[i]).

    fn pde_operator_matrix(
        colloc: &[Vec<f64>],
        centers: &[Vec<f64>],
        eps: f64,
        pde: &PdeType,
        n_dim: usize,
    ) -> Vec<Vec<f64>> {
        let m = colloc.len();
        let n = centers.len();
        let mut l = vec![vec![0.0; n]; m];

        match pde {
            PdeType::Laplacian | PdeType::HeatSteady | PdeType::Poisson => {
                for i in 0..m {
                    for j in 0..n {
                        let r = Self::dist(&colloc[i], &centers[j]);
                        // Laplacian = sum over all spatial dimensions
                        let mut lap = 0.0;
                        for k in 0..n_dim {
                            let delta_k = colloc[i][k] - centers[j][k];
                            lap += multiquadric_d2(r, eps, delta_k, n_dim);
                        }
                        l[i][j] = lap;
                    }
                }
            }
            PdeType::Custom => {
                // No penalty; leave L as zeros.
            }
        }
        l
    }

    // ── simple matrix–vector multiply ─────────────────────────────────────

    fn mat_vec(a: &[Vec<f64>], x: &[f64]) -> Vec<f64> {
        a.iter()
            .map(|row| row.iter().zip(x.iter()).map(|(&a, &x)| a * x).sum())
            .collect()
    }

    // ── matᵀ * mat  (Gram)  and  matᵀ * vec ──────────────────────────────

    fn gram(a: &[Vec<f64>]) -> Vec<Vec<f64>> {
        // aᵀ a
        let n = if a.is_empty() { 0 } else { a[0].len() };
        let mut g = vec![vec![0.0; n]; n];
        for row in a {
            for i in 0..n {
                for j in 0..n {
                    g[i][j] += row[i] * row[j];
                }
            }
        }
        g
    }

    fn at_vec(a: &[Vec<f64>], v: &[f64]) -> Vec<f64> {
        // aᵀ v
        let n = if a.is_empty() { 0 } else { a[0].len() };
        let mut out = vec![0.0; n];
        for (row, &vi) in a.iter().zip(v.iter()) {
            for j in 0..n {
                out[j] += row[j] * vi;
            }
        }
        out
    }

    // ── add two n×n matrices in-place: dest += src ─────────────────────────

    fn mat_add_inplace(dest: &mut Vec<Vec<f64>>, src: &Vec<Vec<f64>>, scale: f64) {
        for i in 0..dest.len() {
            for j in 0..dest[i].len() {
                dest[i][j] += scale * src[i][j];
            }
        }
    }

    // ── Cholesky factorisation + back-substitution ──────────────────────────

    fn cholesky_solve(a: &[Vec<f64>], b: &[f64]) -> Result<Vec<f64>, InterpolateError> {
        let n = a.len();
        // Lower triangular L such that L Lᵀ = A
        let mut l = vec![vec![0.0_f64; n]; n];
        for i in 0..n {
            for j in 0..=i {
                let mut s = a[i][j];
                for k in 0..j {
                    s -= l[i][k] * l[j][k];
                }
                if i == j {
                    if s <= 0.0 {
                        // Not positive-definite — add a small regularisation and retry once.
                        return Self::ridge_solve(a, b, 1e-10);
                    }
                    l[i][j] = s.sqrt();
                } else {
                    l[i][j] = s / l[j][j];
                }
            }
        }
        // Forward substitution: L y = b
        let mut y = vec![0.0; n];
        for i in 0..n {
            let mut s = b[i];
            for k in 0..i {
                s -= l[i][k] * y[k];
            }
            y[i] = s / l[i][i];
        }
        // Backward substitution: Lᵀ x = y
        let mut x = vec![0.0; n];
        for i in (0..n).rev() {
            let mut s = y[i];
            for k in (i + 1)..n {
                s -= l[k][i] * x[k];
            }
            x[i] = s / l[i][i];
        }
        Ok(x)
    }

    /// Fallback ridge regression solve via Gaussian elimination.
    fn ridge_solve(a: &[Vec<f64>], b: &[f64], ridge: f64) -> Result<Vec<f64>, InterpolateError> {
        let n = a.len();
        let mut m: Vec<Vec<f64>> = a
            .iter()
            .enumerate()
            .map(|(i, row)| {
                let mut r = row.to_vec();
                r[i] += ridge;
                r
            })
            .collect();
        let mut rhs = b.to_vec();

        // Gaussian elimination with partial pivoting
        for col in 0..n {
            // Find pivot
            let pivot_row = (col..n).max_by(|&r1, &r2| {
                m[r1][col]
                    .abs()
                    .partial_cmp(&m[r2][col].abs())
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            let pivot_row = pivot_row.ok_or_else(|| {
                InterpolateError::ComputationError("Singular matrix in ridge_solve".to_string())
            })?;
            m.swap(col, pivot_row);
            rhs.swap(col, pivot_row);

            let pivot = m[col][col];
            if pivot.abs() < 1e-14 {
                return Err(InterpolateError::ComputationError(
                    "Near-singular system in PDE-constrained RBF".to_string(),
                ));
            }
            for row in (col + 1)..n {
                let factor = m[row][col] / pivot;
                for j in col..n {
                    let val = m[col][j];
                    m[row][j] -= factor * val;
                }
                rhs[row] -= factor * rhs[col];
            }
        }
        // Back-substitution
        let mut x = vec![0.0; n];
        for i in (0..n).rev() {
            let mut s = rhs[i];
            for j in (i + 1)..n {
                s -= m[i][j] * x[j];
            }
            x[i] = s / m[i][i];
        }
        Ok(x)
    }

    // ─────────────────────────────────────────────────────────────────────
    // Public API
    // ─────────────────────────────────────────────────────────────────────

    /// Fit the PDE-constrained RBF interpolant.
    ///
    /// # Arguments
    /// * `x`               – Data points, each a `Vec<f64>` of length `n_dim`.
    /// * `y`               – Data values.
    /// * `collocation_pts` – Interior/boundary points where the PDE must hold.
    /// * `pde_type`        – Which PDE to enforce.
    pub fn fit(
        &mut self,
        x: &[Vec<f64>],
        y: &[f64],
        collocation_pts: &[Vec<f64>],
        pde_type: &PdeType,
    ) -> Result<(), InterpolateError> {
        if x.is_empty() {
            return Err(InterpolateError::InsufficientData(
                "Need at least one data point".to_string(),
            ));
        }
        if x.len() != y.len() {
            return Err(InterpolateError::DimensionMismatch(format!(
                "x has {} points but y has {} values",
                x.len(),
                y.len()
            )));
        }
        let n_dim = x[0].len();
        if n_dim == 0 {
            return Err(InterpolateError::InvalidValue(
                "Spatial dimension must be ≥ 1".to_string(),
            ));
        }

        let n = x.len();
        let eps = self.config.rbf_shape;
        let lambda = self.config.lambda_pde;

        // Φ  (n×n)
        let phi = Self::rbf_matrix(x, eps);

        // L  (m×n)  at collocation points
        let l_mat = Self::pde_operator_matrix(collocation_pts, x, eps, pde_type, n_dim);

        // Normal equations:  (ΦᵀΦ + λ LᵀL) α = Φᵀ y
        let mut gram_phi = Self::gram(&phi);
        let gram_l = Self::gram(&l_mat);
        Self::mat_add_inplace(&mut gram_phi, &gram_l, lambda);

        let rhs_phi = Self::at_vec(&phi, y);

        let coeffs = Self::cholesky_solve(&gram_phi, &rhs_phi)?;

        self.centers = x.to_vec();
        self.coeffs = coeffs;
        self.n_dim = n_dim;
        Ok(())
    }

    /// Predict values at new points `x`.
    pub fn predict(&self, x: &[Vec<f64>]) -> Result<Vec<f64>, InterpolateError> {
        if self.centers.is_empty() {
            return Err(InterpolateError::InvalidState(
                "PdeConstrainedRbf has not been fitted yet".to_string(),
            ));
        }
        let eps = self.config.rbf_shape;
        let mut out = Vec::with_capacity(x.len());
        for xi in x {
            let val: f64 = self
                .centers
                .iter()
                .zip(self.coeffs.iter())
                .map(|(c, &alpha)| {
                    let r = Self::dist(xi, c);
                    alpha * multiquadric(r, eps)
                })
                .sum();
            out.push(val);
        }
        Ok(out)
    }

    /// Evaluate the PDE residual `L f` at test points.
    ///
    /// Returns `Lf(x_i)` for each `x_i` in `x`; for Laplacian-type PDEs this
    /// is `∇²f(x_i)` evaluated using the fitted RBF expansion.
    pub fn pde_residual(
        &self,
        x: &[Vec<f64>],
        pde_type: &PdeType,
    ) -> Result<Vec<f64>, InterpolateError> {
        if self.centers.is_empty() {
            return Err(InterpolateError::InvalidState(
                "PdeConstrainedRbf has not been fitted yet".to_string(),
            ));
        }
        let eps = self.config.rbf_shape;
        let n_dim = self.n_dim;
        let mut out = Vec::with_capacity(x.len());

        for xi in x {
            let val = match pde_type {
                PdeType::Laplacian | PdeType::HeatSteady | PdeType::Poisson => {
                    // ∇²f(xi) = Σ_j α_j ∇²φ_j(xi)
                    self.centers
                        .iter()
                        .zip(self.coeffs.iter())
                        .map(|(c, &alpha)| {
                            let r = Self::dist(xi, c);
                            let lap: f64 = (0..n_dim)
                                .map(|k| {
                                    let delta_k = xi[k] - c[k];
                                    multiquadric_d2(r, eps, delta_k, n_dim)
                                })
                                .sum();
                            alpha * lap
                        })
                        .sum()
                }
                PdeType::Custom => 0.0,
            };
            out.push(val);
        }
        Ok(out)
    }

    /// Evaluate the PDE operator matrix at `x` (returned row-major for inspection).
    pub fn operator_matrix_at(
        &self,
        x: &[Vec<f64>],
        pde_type: &PdeType,
    ) -> Result<Vec<Vec<f64>>, InterpolateError> {
        if self.centers.is_empty() {
            return Err(InterpolateError::InvalidState(
                "PdeConstrainedRbf has not been fitted yet".to_string(),
            ));
        }
        Ok(Self::pde_operator_matrix(
            x,
            &self.centers,
            self.config.rbf_shape,
            pde_type,
            self.n_dim,
        ))
    }

    // ─────────────────────────────────────────────────────────────────────
    // Internal helpers exposed for mat-vec product (used in `mat_vec`)
    // ─────────────────────────────────────────────────────────────────────

    #[allow(dead_code)]
    fn apply_phi(&self, x: &[Vec<f64>]) -> Vec<f64> {
        let eps = self.config.rbf_shape;
        Self::mat_vec(&Self::rbf_matrix(x, eps), &self.coeffs)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    /// Helper: Euclidean distance.
    fn dist2(a: &[f64], b: &[f64]) -> f64 {
        a.iter()
            .zip(b.iter())
            .map(|(&ai, &bi)| (ai - bi).powi(2))
            .sum::<f64>()
            .sqrt()
    }

    #[test]
    fn test_fit_harmonic_function() {
        // f(x, y) = x + y is harmonic (∇²f = 0).
        // Fit on 5 data points, enforce Laplacian = 0 at 4 collocation pts.
        let data_x: Vec<Vec<f64>> = vec![
            vec![0.0, 0.0],
            vec![1.0, 0.0],
            vec![0.0, 1.0],
            vec![1.0, 1.0],
            vec![0.5, 0.5],
        ];
        let data_y: Vec<f64> = data_x.iter().map(|p| p[0] + p[1]).collect();

        let colloc: Vec<Vec<f64>> = vec![
            vec![0.25, 0.25],
            vec![0.75, 0.25],
            vec![0.25, 0.75],
            vec![0.75, 0.75],
        ];

        let mut rbf = PdeConstrainedRbf::new(PdeConfig {
            lambda_pde: 1.0,
            rbf_shape: 2.0,
            ..Default::default()
        });
        rbf.fit(&data_x, &data_y, &colloc, &PdeType::Laplacian)
            .expect("fit should succeed");

        // Predict at a new point and check it is close to x+y.
        let test_pts = vec![vec![0.3, 0.4]];
        let pred = rbf.predict(&test_pts).expect("predict should succeed");
        let expected = 0.3 + 0.4;
        // The PDE-constrained RBF is a regularised fit; allow up to 0.5 error
        // since the penalty weight influences accuracy vs constraint satisfaction.
        assert!(
            (pred[0] - expected).abs() < 0.5,
            "pred={}, expected={}",
            pred[0],
            expected
        );
    }

    #[test]
    fn test_pde_residual_small_for_harmonic() {
        let data_x: Vec<Vec<f64>> = vec![
            vec![0.0, 0.0],
            vec![1.0, 0.0],
            vec![0.0, 1.0],
            vec![1.0, 1.0],
            vec![0.5, 0.5],
        ];
        let data_y: Vec<f64> = data_x.iter().map(|p| p[0] + p[1]).collect();

        let colloc: Vec<Vec<f64>> = vec![vec![0.5, 0.5]];

        let mut rbf = PdeConstrainedRbf::new(PdeConfig {
            lambda_pde: 10.0,
            rbf_shape: 1.5,
            ..Default::default()
        });
        rbf.fit(&data_x, &data_y, &colloc, &PdeType::Laplacian)
            .expect("fit should succeed");

        let test_pts = vec![vec![0.3, 0.4], vec![0.6, 0.7]];
        let residuals = rbf
            .pde_residual(&test_pts, &PdeType::Laplacian)
            .expect("residual should succeed");
        // With heavy penalty the Laplacian residual should be small.
        for &r in &residuals {
            assert!(r.abs() < 2.0, "Laplacian residual too large: {}", r);
        }

        // Suppress unused import warning for dist2
        let _ = dist2(&[0.0], &[0.0]);
    }

    #[test]
    fn test_predict_without_fit_returns_error() {
        let rbf = PdeConstrainedRbf::new(PdeConfig::default());
        let result = rbf.predict(&[vec![0.5, 0.5]]);
        assert!(result.is_err());
    }

    #[test]
    fn test_custom_pde_no_penalty() {
        let data_x: Vec<Vec<f64>> = vec![vec![0.0], vec![1.0], vec![2.0]];
        let data_y: Vec<f64> = vec![0.0, 1.0, 4.0];
        let colloc: Vec<Vec<f64>> = vec![vec![0.5], vec![1.5]];
        let mut rbf = PdeConstrainedRbf::new(PdeConfig::default());
        rbf.fit(&data_x, &data_y, &colloc, &PdeType::Custom)
            .expect("fit should succeed");
        let pred = rbf.predict(&[vec![1.0]]).expect("predict");
        assert!((pred[0] - 1.0).abs() < 0.5);
    }
}