-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdynamic_interpolator.rs
More file actions
79 lines (72 loc) · 2.3 KB
/
dynamic_interpolator.rs
File metadata and controls
79 lines (72 loc) · 2.3 KB
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
use ndarray::prelude::*;
use ninterp::prelude::*;
fn main() {
using_enum();
using_boxdyn();
}
/// Use a provided interpolator enum to allow interpolator swapping.
/// - serde compatible
/// - Statically dispatched (faster runtime)
/// - **NOT** compatible with custom strategies
fn using_enum() {
// Create `InterpolatorEnum`
let mut interp = InterpolatorEnum::new_2d(
array![0., 1.],
array![0., 1., 2.],
array![[2., 4., 6.], [4., 16., 32.]],
strategy::Linear,
Extrapolate::Enable,
)
.unwrap();
assert_eq!(interp.interpolate(&[1.5, -0.5]).unwrap(), -3.5);
// Change interpolator variant
interp = Interp1D::new(
array![0., 1., 2.],
array![0., 4., 8.],
strategy::Nearest.into(),
Extrapolate::Error,
)
.unwrap()
.into(); // `.into()` converts the `Interp1D` into an `InterpolatorEnum::Interp1D(...)`
assert_eq!(interp.interpolate(&[1.75]).unwrap(), 8.);
// Change interpolator variant again, using alternate syntax
interp = InterpolatorEnum::new_3d(
array![0., 1.],
array![0., 1.],
array![0., 1.],
array![[[0., 1.], [0.1, 1.1]], [[0.2, 1.2], [0.3, 1.3]]],
strategy::Nearest,
Extrapolate::Error,
)
.unwrap(); // `.into()` converts the `Interp1D` into an `InterpolatorEnum::Interp1D(...)`
assert_eq!(interp.interpolate(&[0.8, 0.7, 0.6]).unwrap(), 1.3);
}
/// Use a provided interpolator enum to allow interpolator swapping.
/// - **NOT** serde compatible
/// - Dynamically dispatched (slower runtime)
/// - Compatible with custom strategies
fn using_boxdyn() {
// Create `Interpolator` trait object
let mut boxed: Box<dyn Interpolator<_>> = Box::new(
Interp2D::new(
array![0., 1.],
array![0., 1., 2.],
array![[2., 4., 6.], [4., 16., 32.]],
strategy::Linear,
Extrapolate::Enable,
)
.unwrap(),
);
assert_eq!(boxed.interpolate(&[1.5, -0.5]).unwrap(), -3.5);
// Change underlying interpolator
boxed = Box::new(
Interp1D::new(
array![0., 1., 2.],
array![0., 4., 8.],
strategy::Nearest,
Extrapolate::Error,
)
.unwrap(),
);
assert_eq!(boxed.interpolate(&[1.75]).unwrap(), 8.);
}