Skip to main content

lib_jsl_interpolation/
two_d.rs

1//! Two-dimensional interpolation.
2//!
3//! See the book entry [Interpolation on grids](https://jwkunz.github.io/lib_jsl/book/interpolation/grids.html).
4//!
5//! Gridded interpolators take axes `x` (length `nx`), `y` (length `ny`) and a value matrix `z` of
6//! shape `(nx, ny)` with `z[[i, j]] = f(x[i], y[j])`.
7
8use lib_jsl_core::*;
9
10/// Evaluation interface shared by the 2D interpolators.
11pub trait Interpolation2D {
12    /// Interpolated value at `(x, y)`.
13    fn interpolate_at(&self, x: f64, y: f64) -> Result<f64, ErrorsJSL>;
14}
15
16/// Checks that axes are strictly increasing, long enough, and match the value matrix.
17pub(crate) fn validate_grid(x: VR1D, y: VR1D, z: VR2D, min_points: usize) -> Result<(), ErrorsJSL> {
18    if z.dim() != (x.len(), y.len()) {
19        return Err(ErrorsJSL::IncompatibleArraySizes((z.nrows(), x.len())));
20    }
21    if x.len() < min_points || y.len() < min_points {
22        return Err(ErrorsJSL::InvalidInputRange("not enough grid points along an axis"));
23    }
24    for axis in [x, y] {
25        if axis.iter().zip(axis.iter().skip(1)).any(|(a, b)| b <= a) {
26            return Err(ErrorsJSL::InvalidInputRange("axes must be strictly increasing"));
27        }
28    }
29    Ok(())
30}
31
32/// Index `i` of the cell `[axis[i], axis[i+1]]` containing `v`, clamped to `0..=len-2`.
33pub(crate) fn find_cell(axis: &[f64], v: f64) -> usize {
34    axis.partition_point(|&a| a <= v).saturating_sub(1).min(axis.len() - 2)
35}
36
37/// Cubic Hermite basis functions `(h00, h10, h01, h11)` at `t` in `[0, 1]`.
38pub(crate) fn hermite_basis(t: f64) -> [f64; 4] {
39    let (t2, t3) = (t * t, t * t * t);
40    [2.0 * t3 - 3.0 * t2 + 1.0, t3 - 2.0 * t2 + t, -2.0 * t3 + 3.0 * t2, t3 - t2]
41}
42
43pub mod nearest;
44pub mod bilinear;
45pub mod bicubic;
46pub mod lanczos;
47pub mod cubic_basis;
48pub mod all_phase;
49pub mod radial_basis_functions;
50pub mod fourier_2d;
51pub mod rect_bivariate_spline;
52pub mod scattered;
53pub mod smooth_bivariate;
54
55/// Start and spacing of a uniformly spaced axis (relative tolerance 1e-9).
56pub(crate) fn uniform_axis(axis: VR1D) -> Result<(f64, f64), ErrorsJSL> {
57    let step = (axis[axis.len() - 1] - axis[0]) / (axis.len() - 1) as f64;
58    if axis.iter().enumerate().any(|(i, &a)| (a - axis[0] - i as f64 * step).abs() > 1e-9 * step.abs()) {
59        return Err(ErrorsJSL::InvalidInputRange("axis must be uniformly spaced"));
60    }
61    Ok((axis[0], step))
62}
63
64/// Separable kernel resampling on a uniform grid: the value at `(x, y)` is a weighted sum of the
65/// `2 * support` nearest nodes per axis, with weights `kernel(distance in samples)` normalised to
66/// sum to one along each axis (so constants are preserved). Indices outside the grid replicate the
67/// edge samples.
68pub(crate) struct SeparableResampler<'k> {
69    pub x0: f64,
70    pub dx: f64,
71    pub y0: f64,
72    pub dy: f64,
73    pub support: isize,
74    pub kernel: &'k dyn Fn(f64) -> f64,
75}
76
77impl SeparableResampler<'_> {
78    fn axis_weights(&self, u: f64, n: usize) -> Vec<(usize, f64)> {
79        let base = u.floor() as isize;
80        let mut taps: Vec<(usize, f64)> = ((base - self.support + 1)..=(base + self.support))
81            .map(|i| (i.clamp(0, n as isize - 1) as usize, (self.kernel)(u - i as f64)))
82            .collect();
83        let sum: f64 = taps.iter().map(|t| t.1).sum();
84        taps.iter_mut().for_each(|t| t.1 /= sum);
85        taps
86    }
87
88    pub fn eval(&self, z: &R2D, x: f64, y: f64) -> f64 {
89        let (nx, ny) = z.dim();
90        let wx = self.axis_weights((x - self.x0) / self.dx, nx);
91        let wy = self.axis_weights((y - self.y0) / self.dy, ny);
92        wx.iter().map(|&(i, a)| a * wy.iter().map(|&(j, b)| b * z[[i, j]]).sum::<f64>()).sum()
93    }
94}
95
96/// Normalised sinc, `sin(πx)/(πx)`.
97pub(crate) fn sinc(x: f64) -> f64 {
98    if x == 0.0 { 1.0 } else { (std::f64::consts::PI * x).sin() / (std::f64::consts::PI * x) }
99}