Skip to main content

lib_jsl_interpolation/
interpolation_trait.rs

1use lib_jsl_core::*;
2
3pub trait InterpolationTrait<'a> : Sized{
4
5    /// Setters and getters for required fields
6    fn get_x_values(&self) -> VR1D<'a>;
7    fn set_x_values(&mut self,x : VR1D<'a>);
8    fn get_y_values(&self) -> VR1D<'a>;
9    fn set_y_values(&mut self,y : VR1D<'a>);
10    fn get_cached_location(&self) -> Option<usize>;
11    fn set_cached_location(&mut self,x : usize);
12
13    /// Check if x range is ascending
14    fn x_range_is_ascending(&self) -> bool{
15        let x_values = self.get_x_values();
16        x_values.last()>=x_values.first()
17    }
18
19    /// Thie function checks to make sure x and y are the same length and greater than 2
20    fn verify_sizes(&mut self, limit : usize) -> Result<(),ErrorsJSL>{
21        let n = self.get_x_values().len();
22        let mm = self.get_y_values().len();
23        if (n != mm) || n < limit{
24            return Err(ErrorsJSL::IncompatibleArraySizes((n,mm)));
25        }
26        Ok(())
27    }
28
29    /// Finds the index immediately before x, optionally relying on the cache of the previous value
30    /// The location will not exceed N-2 so it always indicates to two valid sequential indexes, even if at the end
31    fn locate(&mut self, x : f64) -> Result<usize,ErrorsJSL>{
32        let x_values = self.get_x_values();
33        let mut jm : usize;
34
35        // Check if cached value has the location 
36        let mut jl = self.get_cached_location().unwrap_or(0);
37        if x < x_values[jl]{
38            jl = 0; // Unknown start point
39        }
40        // Either the next or the end
41        let mut ju  = jl+1;
42        if ju >= x_values.len(){
43            return Ok(x_values.len()-2); // Start just before end
44        }else if x < x_values[ju]{
45            return Ok(jl); // Cache hit
46        }else{
47            ju = x_values.len()-1; // Unknown upper bound
48        }
49
50        // No cache hit, proceed with bisection
51        while ju-jl > 1{ 
52            // Get the midpoint
53            jm = (ju + jl) >> 1; 
54            // Compare point with bounds
55            if x >= x_values[jm]{
56                jl = jm; // Replace the lower limit
57            }else{
58                ju = jm; // Replace upper limit
59            }
60        }
61        // Cache the hunt or locate decision for next time (speed up optimization)
62        self.set_cached_location(jl);
63        Ok(std::cmp::min(jl,x_values.len()-1))
64    }
65
66
67    /// This is where the interpolation gets computed based on the method
68    fn raw_interpolate(&mut self, jlo : usize, x : f64) -> Result<f64,ErrorsJSL>;
69
70    /// Top level wrapper for evaluation
71    fn interpolate_at(&mut self, x : f64) -> Result<f64,ErrorsJSL>{
72        let jlo = self.locate(x)?;
73        self.raw_interpolate(jlo, x)
74    }
75}