scirs2-interpolate 0.4.1

Interpolation module for SciRS2 (scirs2-interpolate)
Documentation
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Core cubic spline data structures and implementations
//!
//! This module contains the main `CubicSpline` struct and `CubicSplineBuilder` struct
//! along with their core implementations. These provide the fundamental data structures
//! for cubic spline interpolation.

use crate::error::{InterpolateError, InterpolateResult};
use crate::traits::InterpolationFloat;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
use super::types::SplineBoundaryCondition;
use super::algorithms::*;

/// A cubic spline interpolator
///
/// This struct represents a constructed cubic spline that can be used for interpolation
/// and derivative computation. Each spline consists of piecewise cubic polynomials that
/// maintain C² continuity (continuous function, first, and second derivatives).
///
/// # Type Parameters
///
/// * `F` - The floating point type (f32 or f64)
///
/// # Structure
///
/// The spline stores:
/// - `x`: The sorted x coordinates of the data points
/// - `y`: The y coordinates of the data points
/// - `coeffs`: Polynomial coefficients for each segment
///
/// Each row of `coeffs` contains [a, b, c, d] representing the cubic polynomial:
/// ```text
/// y(x) = a + b*(x-x_i) + c*(x-x_i)² + d*(x-x_i)³
/// ```
///
/// # Examples
///
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_interpolate::spline::CubicSpline;
///
/// let x = array![0.0, 1.0, 2.0, 3.0];
/// let y = array![0.0, 1.0, 4.0, 9.0];
///
/// let spline = CubicSpline::new(&x.view(), &y.view()).expect("Operation failed");
/// let value = spline.evaluate(1.5).expect("Operation failed");
/// ```
#[derive(Debug, Clone)]
pub struct CubicSpline<F: InterpolationFloat> {
    /// X coordinates (must be sorted)
    x: Array1<F>,
    /// Y coordinates
    y: Array1<F>,
    /// Coefficients for cubic polynomials (n-1 segments, 4 coefficients each)
    /// Each row represents [a, b, c, d] for a segment
    /// y(x) = a + b*(x-x_i) + c*(x-x_i)^2 + d*(x-x_i)^3
    coeffs: Array2<F>,
}

/// Builder for cubic splines with custom boundary conditions
///
/// This builder allows for flexible construction of cubic splines with different
/// boundary conditions. It uses the builder pattern to provide a fluent API
/// for spline configuration.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_interpolate::spline::{CubicSpline, SplineBoundaryCondition};
///
/// let x = array![0.0, 1.0, 2.0, 3.0];
/// let y = array![0.0, 1.0, 4.0, 9.0];
///
/// let spline = CubicSpline::builder()
///     .x(x)
///     .y(y)
///     .boundary_condition(SplineBoundaryCondition::NotAKnot)
///     .build()
///     .expect("doc example: should succeed");
/// ```
#[derive(Debug, Clone)]
pub struct CubicSplineBuilder<F: InterpolationFloat> {
    x: Option<Array1<F>>,
    y: Option<Array1<F>>,
    boundary_condition: SplineBoundaryCondition<F>,
}

impl<F: InterpolationFloat> CubicSplineBuilder<F> {
    /// Create a new builder with default settings
    ///
    /// Default boundary condition is Natural (zero second derivative at endpoints).
    pub fn new() -> Self {
        Self {
            x: None,
            y: None,
            boundary_condition: SplineBoundaryCondition::Natural,
        }
    }

    /// Set the x coordinates
    ///
    /// # Arguments
    ///
    /// * `x` - Array of x coordinates (must be sorted in ascending order)
    ///
    /// # Returns
    ///
    /// The builder with x coordinates set
    pub fn x(mut self, x: Array1<F>) -> Self {
        self.x = Some(x);
        self
    }

    /// Set the y coordinates
    ///
    /// # Arguments
    ///
    /// * `y` - Array of y coordinates (must have same length as x)
    ///
    /// # Returns
    ///
    /// The builder with y coordinates set
    pub fn y(mut self, y: Array1<F>) -> Self {
        self.y = Some(y);
        self
    }

    /// Set the boundary condition
    ///
    /// # Arguments
    ///
    /// * `bc` - The boundary condition to use
    ///
    /// # Returns
    ///
    /// The builder with boundary condition set
    pub fn boundary_condition(mut self, bc: SplineBoundaryCondition<F>) -> Self {
        self.boundary_condition = bc;
        self
    }

    /// Build the spline
    ///
    /// # Returns
    ///
    /// A new `CubicSpline` object or an error if construction fails
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - x or y coordinates are not set
    /// - Arrays have different lengths
    /// - Insufficient points for the boundary condition
    /// - x coordinates are not sorted
    /// - Numerical issues during construction
    pub fn build(self) -> InterpolateResult<CubicSpline<F>> {
        let x = self
            .x
            .ok_or_else(|| InterpolateError::invalid_input("x coordinates not set".to_string()))?;
        let y = self
            .y
            .ok_or_else(|| InterpolateError::invalid_input("y coordinates not set".to_string()))?;

        CubicSpline::with_boundary_condition(&x.view(), &y.view(), self.boundary_condition)
    }
}

impl<F: InterpolationFloat> Default for CubicSplineBuilder<F> {
    fn default() -> Self {
        Self::new()
    }
}

impl<F: InterpolationFloat + ToString> CubicSpline<F> {
    /// Create a new builder for cubic splines
    ///
    /// # Returns
    ///
    /// A new `CubicSplineBuilder` instance
    pub fn builder() -> CubicSplineBuilder<F> {
        CubicSplineBuilder::new()
    }

    /// Create a new cubic spline with natural boundary conditions
    ///
    /// Natural boundary conditions set the second derivative to zero at both endpoints,
    /// which minimizes the total curvature of the spline.
    ///
    /// # Arguments
    ///
    /// * `x` - The x coordinates (must be sorted in ascending order)
    /// * `y` - The y coordinates (must have the same length as x)
    ///
    /// # Returns
    ///
    /// A new `CubicSpline` object
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Arrays have different lengths
    /// - Less than 3 points provided
    /// - x coordinates are not sorted
    /// - Numerical issues during construction
    ///
    /// # Examples
    ///
    /// ```rust
    /// use scirs2_core::ndarray::array;
    /// use scirs2_interpolate::spline::CubicSpline;
    ///
    /// let x = array![0.0, 1.0, 2.0, 3.0];
    /// let y = array![0.0, 1.0, 4.0, 9.0];
    ///
    /// let spline = CubicSpline::new(&x.view(), &y.view()).expect("Operation failed");
    ///
    /// // Interpolate at x = 1.5
    /// let y_interp = spline.evaluate(1.5).expect("Operation failed");
    /// println!("Interpolated value at x=1.5: {}", y_interp);
    /// ```
    pub fn new(x: &ArrayView1<F>, y: &ArrayView1<F>) -> InterpolateResult<Self> {
        // Check inputs
        if x.len() != y.len() {
            return Err(InterpolateError::invalid_input(
                "x and y arrays must have the same length".to_string(),
            ));
        }

        if x.len() < 3 {
            return Err(InterpolateError::insufficient_points(
                3,
                x.len(),
                "cubic spline",
            ));
        }

        // Check that x is sorted
        for i in 1..x.len() {
            if x[i] <= x[i - 1] {
                return Err(InterpolateError::invalid_input(
                    "x values must be sorted in ascending order".to_string(),
                ));
            }
        }

        // Get coefficients for natural cubic spline
        let coeffs = compute_natural_cubic_spline(x, y)?;

        Ok(CubicSpline {
            x: x.to_owned(),
            y: y.to_owned(),
            coeffs,
        })
    }

    /// Get the x coordinates
    ///
    /// # Returns
    ///
    /// Reference to the array of x coordinates
    pub fn x(&self) -> &Array1<F> {
        &self.x
    }

    /// Get the y coordinates
    ///
    /// # Returns
    ///
    /// Reference to the array of y coordinates
    pub fn y(&self) -> &Array1<F> {
        &self.y
    }

    /// Get the polynomial coefficients
    ///
    /// # Returns
    ///
    /// Reference to the 2D array of polynomial coefficients
    /// Shape: (n-1, 4) where n is the number of data points
    /// Each row contains [a, b, c, d] for the polynomial in that segment
    pub fn coeffs(&self) -> &Array2<F> {
        &self.coeffs
    }

    /// Create a new cubic spline with not-a-knot boundary conditions
    ///
    /// Not-a-knot boundary conditions force the third derivative to be continuous
    /// at the second and second-to-last data points, providing maximum smoothness.
    ///
    /// # Arguments
    ///
    /// * `x` - The x coordinates (must be sorted in ascending order)
    /// * `y` - The y coordinates (must have the same length as x)
    ///
    /// # Returns
    ///
    /// A new `CubicSpline` object
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Arrays have different lengths
    /// - Less than 4 points provided (required for not-a-knot)
    /// - x coordinates are not sorted
    /// - Numerical issues during construction
    pub fn new_not_a_knot(x: &ArrayView1<F>, y: &ArrayView1<F>) -> InterpolateResult<Self> {
        // Check inputs
        if x.len() != y.len() {
            return Err(InterpolateError::invalid_input(
                "x and y arrays must have the same length".to_string(),
            ));
        }

        if x.len() < 4 {
            return Err(InterpolateError::insufficient_points(
                4,
                x.len(),
                "not-a-knot cubic spline",
            ));
        }

        // Check that x is sorted
        for i in 1..x.len() {
            if x[i] <= x[i - 1] {
                return Err(InterpolateError::invalid_input(
                    "x values must be sorted in ascending order".to_string(),
                ));
            }
        }

        // Get coefficients for not-a-knot cubic spline
        let coeffs = compute_not_a_knot_cubic_spline(x, y)?;

        Ok(CubicSpline {
            x: x.to_owned(),
            y: y.to_owned(),
            coeffs,
        })
    }

    /// Create a cubic spline with custom boundary conditions
    ///
    /// This is the most general constructor that supports all boundary condition types.
    ///
    /// # Arguments
    ///
    /// * `x` - The x coordinates (must be sorted in ascending order)
    /// * `y` - The y coordinates (must have the same length as x)
    /// * `bc` - The boundary condition to use
    ///
    /// # Returns
    ///
    /// A new `CubicSpline` object
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Arrays have different lengths
    /// - Insufficient points for the chosen boundary condition
    /// - x coordinates are not sorted
    /// - Numerical issues during construction
    /// - Invalid boundary condition parameters
    pub fn with_boundary_condition(
        x: &ArrayView1<F>,
        y: &ArrayView1<F>,
        bc: SplineBoundaryCondition<F>,
    ) -> InterpolateResult<Self> {
        // Check inputs
        if x.len() != y.len() {
            return Err(InterpolateError::invalid_input(
                "x and y arrays must have the same length".to_string(),
            ));
        }

        // Check minimum points based on boundary condition
        let min_points = match bc {
            SplineBoundaryCondition::NotAKnot => 4,
            _ => 3,
        };

        if x.len() < min_points {
            return Err(InterpolateError::insufficient_points(
                min_points,
                x.len(),
                &format!("cubic spline with {:?} boundary condition", bc),
            ));
        }

        // Check that x is sorted
        for i in 1..x.len() {
            if x[i] <= x[i - 1] {
                return Err(InterpolateError::invalid_input(
                    "x values must be sorted in ascending order".to_string(),
                ));
            }
        }

        // Validate periodic boundary condition
        if let SplineBoundaryCondition::Periodic = bc {
            let tolerance = F::from_f64(1e-10).unwrap_or_else(|| F::epsilon());
            if (y[0] - y[y.len() - 1]).abs() > tolerance {
                return Err(InterpolateError::invalid_input(
                    "For periodic boundary conditions, first and last y values must be equal".to_string(),
                ));
            }
        }

        // Get coefficients based on boundary condition
        let coeffs = match bc {
            SplineBoundaryCondition::Natural => compute_natural_cubic_spline(x, y)?,
            SplineBoundaryCondition::NotAKnot => compute_not_a_knot_cubic_spline(x, y)?,
            SplineBoundaryCondition::Clamped(dy0, dyn_) => {
                compute_clamped_cubic_spline(x, y, dy0, dyn_)?
            }
            SplineBoundaryCondition::Periodic => compute_periodic_cubic_spline(x, y)?,
            SplineBoundaryCondition::SecondDerivative(d2y0, d2yn) => {
                compute_second_derivative_cubic_spline(x, y, d2y0, d2yn)?
            }
            SplineBoundaryCondition::ParabolicRunout => {
                compute_parabolic_runout_cubic_spline(x, y)?
            }
        };

        Ok(CubicSpline {
            x: x.to_owned(),
            y: y.to_owned(),
            coeffs,
        })
    }
}