lib_jsl_interpolation/
two_d.rs1use lib_jsl_core::*;
9
10pub trait Interpolation2D {
12 fn interpolate_at(&self, x: f64, y: f64) -> Result<f64, ErrorsJSL>;
14}
15
16pub(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
32pub(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
37pub(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
55pub(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
64pub(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
96pub(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}