lib_jsl_interpolation/one_d/
hermite.rs1use crate::interpolation_trait::InterpolationTrait;
6use lib_jsl_core::*;
7
8#[derive(Debug)]
14pub struct PiecewiseHermite<'a> {
15 x_values: VR1D<'a>,
16 y_values: VR1D<'a>,
17 slopes: R1D,
18 location: Option<usize>,
19}
20
21impl<'a> PiecewiseHermite<'a> {
22 pub fn from_slopes(x_values: VR1D<'a>, y_values: VR1D<'a>, slopes: R1D) -> Result<Self, ErrorsJSL> {
24 let mut result = PiecewiseHermite { x_values, y_values, slopes, location: None };
25 result.verify_sizes(2)?;
26 if result.slopes.len() != x_values.len() {
27 return Err(ErrorsJSL::IncompatibleArraySizes((x_values.len(), result.slopes.len())));
28 }
29 if x_values.iter().zip(x_values.iter().skip(1)).any(|(a, b)| b <= a) {
30 return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
31 }
32 Ok(result)
33 }
34
35 pub fn slopes(&self) -> &R1D {
37 &self.slopes
38 }
39
40 pub fn to_ppoly(&self) -> super::ppoly::PPoly {
43 super::ppoly::PPoly::cubic_hermite(&self.x_values.to_vec(), &self.y_values.to_vec(), &self.slopes.to_vec()).expect("validated on construction")
44 }
45}
46
47impl<'a> InterpolationTrait<'a> for PiecewiseHermite<'a> {
48 fn get_x_values(&self) -> VR1D<'a> {
49 self.x_values
50 }
51 fn set_x_values(&mut self, x: VR1D<'a>) {
52 self.x_values = x;
53 }
54 fn get_y_values(&self) -> VR1D<'a> {
55 self.y_values
56 }
57 fn set_y_values(&mut self, y: VR1D<'a>) {
58 self.y_values = y;
59 }
60 fn get_cached_location(&self) -> Option<usize> {
61 self.location
62 }
63 fn set_cached_location(&mut self, x: usize) {
64 self.location = Some(x)
65 }
66
67 fn raw_interpolate(&mut self, j: usize, x: f64) -> Result<f64, ErrorsJSL> {
68 let (x0, x1) = (self.x_values[j], self.x_values[j + 1]);
69 let (y0, y1) = (self.y_values[j], self.y_values[j + 1]);
70 let h = x1 - x0;
71 let t = (x - x0) / h;
72 let (t2, t3) = (t * t, t * t * t);
73 let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
74 let h10 = t3 - 2.0 * t2 + t;
75 let h01 = -2.0 * t3 + 3.0 * t2;
76 let h11 = t3 - t2;
77 Ok(h00 * y0 + h10 * h * self.slopes[j] + h01 * y1 + h11 * h * self.slopes[j + 1])
78 }
79}
80
81pub(crate) fn secants(x: VR1D, y: VR1D) -> Result<Vec<f64>, ErrorsJSL> {
83 if x.len() != y.len() {
84 return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
85 }
86 if x.iter().zip(x.iter().skip(1)).any(|(a, b)| b <= a) {
87 return Err(ErrorsJSL::InvalidInputRange("x values must be strictly increasing"));
88 }
89 Ok((0..x.len().saturating_sub(1)).map(|i| (y[i + 1] - y[i]) / (x[i + 1] - x[i])).collect())
90}