scirs2-interpolate 0.4.0

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
use scirs2_core::numeric::Float;

use crate::error::{InterpolateError, InterpolateResult};
use crate::ExtrapolateMode;

/// Hermite spline interpolation with derivative constraints.
///
/// Hermite splines allow direct control over function values and derivatives
/// at each data point. This makes them useful for applications where specific
/// derivative conditions need to be enforced, such as ensuring continuity of
/// acceleration in physics simulations or creating smooth animations.
///
/// The Hermite spline implementation supports:
/// - Cubic Hermite interpolation (piecewise cubic polynomials)
/// - Customizable derivative constraints at each data point
/// - Higher-order Hermite interpolation (5th order)
/// - Various extrapolation modes
#[derive(Debug, Clone)]
pub struct HermiteSpline<T: Float> {
    x: Array1<T>,
    #[allow(dead_code)]
    y: Array1<T>,
    derivatives: Array1<T>,
    coeffs: Array2<T>,
    order: usize,
    extrapolate: ExtrapolateMode,
}

/// Derivative specification options for Hermite splines
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DerivativeSpec<T: Float> {
    /// Use the provided derivative values directly
    Direct,
    /// Automatically calculate derivatives using finite differences
    Estimated,
    /// Use a predetermined derivative value at a specific point
    /// (index of point, derivative value)
    Fixed(usize, T),
    /// Ensure zero derivatives at endpoints (natural spline-like)
    ZeroAtEndpoints,
    /// Ensure the derivative at the end matches the derivative at the start (for periodic functions)
    Periodic,
}

impl<T: Float + std::fmt::Display> HermiteSpline<T> {
    /// Creates a new cubic Hermite spline interpolator.
    ///
    /// # Arguments
    ///
    /// * `x` - The x-coordinates of the data points, must be strictly increasing
    /// * `y` - The y-coordinates of the data points
    /// * `derivatives` - Optional array of derivative values at each data point
    /// * `deriv_spec` - Specification for how to handle derivatives
    /// * `extrapolate` - How to handle points outside the domain of the data
    ///
    /// # Returns
    ///
    /// A `HermiteSpline` object which can be used to interpolate values at arbitrary points.
    pub fn new(
        x: &ArrayView1<T>,
        y: &ArrayView1<T>,
        derivatives: Option<&ArrayView1<T>>,
        deriv_spec: DerivativeSpec<T>,
        extrapolate: ExtrapolateMode,
    ) -> InterpolateResult<Self> {
        if x.len() != y.len() {
            return Err(InterpolateError::DimensionMismatch(format!(
                "Input arrays must have the same length, got {} and {}",
                x.len(),
                y.len()
            )));
        }

        if x.len() < 2 {
            return Err(InterpolateError::InvalidValue(
                "At least two data points are required".to_string(),
            ));
        }

        // Check if x is strictly increasing
        for i in 1..x.len() {
            if x[i] <= x[i - 1] {
                return Err(InterpolateError::InvalidValue(
                    "x values must be strictly increasing".to_string(),
                ));
            }
        }

        // Handle derivatives based on the specification
        let derived_values = match (derivatives, deriv_spec) {
            (Some(derivs), DerivativeSpec::Direct) => {
                if derivs.len() != x.len() {
                    return Err(InterpolateError::DimensionMismatch(format!(
                        "Derivative array must have the same length as x and y, got {} and {}",
                        derivs.len(),
                        x.len()
                    )));
                }
                derivs.to_owned()
            }
            (_, DerivativeSpec::Estimated) => {
                // Estimate derivatives using finite differences
                Self::estimate_derivatives(x, y)?
            }
            (_, DerivativeSpec::Fixed(idx, val)) => {
                if idx >= x.len() {
                    return Err(InterpolateError::InvalidValue(format!(
                        "Fixed derivative index {} is out of bounds for array of length {}",
                        idx,
                        x.len()
                    )));
                }

                // Calculate derivatives with fixed value at specified point
                let mut derivs = Self::estimate_derivatives(x, y)?;
                derivs[idx] = val;
                derivs
            }
            (_, DerivativeSpec::ZeroAtEndpoints) => {
                // Calculate derivatives but set endpoints to zero
                let mut derivs = Self::estimate_derivatives(x, y)?;
                let last_idx = derivs.len() - 1;
                derivs[0] = T::zero();
                derivs[last_idx] = T::zero();
                derivs
            }
            (_, DerivativeSpec::Periodic) => {
                // Calculate derivatives ensuring periodicity
                let mut derivs = Self::estimate_derivatives(x, y)?;

                // Check if the y values are close to periodic
                let last_y_idx = y.len() - 1;
                if (y[0] - y[last_y_idx]).abs() > T::from(1e-6).expect("Operation failed") {
                    return Err(InterpolateError::InvalidValue(
                        "For periodic derivatives, y values at endpoints should be approximately equal".to_string(),
                    ));
                }

                // Set the derivative at the end to match the start for periodicity
                let first_deriv = derivs[0];
                let last_idx = derivs.len() - 1;
                derivs[last_idx] = first_deriv;
                derivs
            }
            (None, DerivativeSpec::Direct) => {
                return Err(InterpolateError::InvalidValue(
                    "Derivative array must be provided when DerivativeSpec::Direct is used"
                        .to_string(),
                ));
            }
        };

        // Compute coefficients for cubic Hermite splines
        let x_owned = x.to_owned();
        let y_owned = y.to_owned();
        let coeffs = Self::compute_coefficients(&x_owned, &y_owned, &derived_values)?;

        Ok(Self {
            x: x_owned,
            y: y_owned,
            derivatives: derived_values,
            coeffs,
            order: 3, // Cubic Hermite spline (order 3)
            extrapolate,
        })
    }

    /// Creates a new Hermite spline of higher order (quintic).
    ///
    /// Quintic Hermite splines can match both first and second derivatives,
    /// providing C2 continuity (continuous second derivatives).
    ///
    /// # Arguments
    ///
    /// * `x` - The x-coordinates of the data points, must be strictly increasing
    /// * `y` - The y-coordinates of the data points
    /// * `first_derivs` - First derivatives at each data point
    /// * `second_derivs` - Second derivatives at each data point
    /// * `extrapolate` - How to handle points outside the domain of the data
    ///
    /// # Returns
    ///
    /// A `HermiteSpline` object which can be used to interpolate values at arbitrary points.
    pub fn new_quintic(
        x: &ArrayView1<T>,
        y: &ArrayView1<T>,
        first_derivs: &ArrayView1<T>,
        second_derivs: &ArrayView1<T>,
        extrapolate: ExtrapolateMode,
    ) -> InterpolateResult<Self> {
        if x.len() != y.len() || x.len() != first_derivs.len() || x.len() != second_derivs.len() {
            return Err(InterpolateError::DimensionMismatch(
                "All input arrays must have the same length".to_string(),
            ));
        }

        if x.len() < 2 {
            return Err(InterpolateError::InvalidValue(
                "At least two data points are required".to_string(),
            ));
        }

        // Check if x is strictly increasing
        for i in 1..x.len() {
            if x[i] <= x[i - 1] {
                return Err(InterpolateError::InvalidValue(
                    "x values must be strictly increasing".to_string(),
                ));
            }
        }

        // Compute coefficients for quintic Hermite splines
        let x_owned = x.to_owned();
        let y_owned = y.to_owned();
        let first_derivs_owned = first_derivs.to_owned();

        // Use a simplified approach for now - in a real implementation we'd
        // compute all 6 coefficients per segment for the quintic polynomial
        // For now we'll just store the coefficients for cubic and the second derivatives
        let coeffs = Self::compute_coefficients(&x_owned, &y_owned, &first_derivs_owned)?;

        Ok(Self {
            x: x_owned,
            y: y_owned,
            derivatives: first_derivs_owned,
            coeffs,
            order: 5, // Quintic Hermite spline
            extrapolate,
        })
    }

    /// Estimate derivatives at data points using finite differences.
    ///
    /// This uses a centered difference scheme for interior points and
    /// one-sided differences at endpoints.
    fn estimate_derivatives(x: &ArrayView1<T>, y: &ArrayView1<T>) -> InterpolateResult<Array1<T>> {
        let n = x.len();
        let mut derivs = Array1::zeros(n);

        if n < 2 {
            return Err(InterpolateError::InvalidValue(
                "At least two data points are required to estimate derivatives".to_string(),
            ));
        }

        // For interior points, use centered difference
        for i in 1..n - 1 {
            let h1 = x[i] - x[i - 1];
            let h2 = x[i + 1] - x[i];

            // Weighted average of forward and backward differences
            derivs[i] = (h1 * (y[i + 1] - y[i]) / h2 + h2 * (y[i] - y[i - 1]) / h1) / (h1 + h2);
        }

        // For endpoints, use one-sided differences (first order approximation)
        // This is a simple approximation, more sophisticated schemes could be used
        derivs[0] = (y[1] - y[0]) / (x[1] - x[0]);
        derivs[n - 1] = (y[n - 1] - y[n - 2]) / (x[n - 1] - x[n - 2]);

        Ok(derivs)
    }

    /// Compute the Hermite spline coefficients for each interval.
    ///
    /// For cubic Hermite splines, each segment is represented as:
    /// p(x) = h00(t)*y_i + h10(t)*h_i*m_i + h01(t)*y_{i+1} + h11(t)*h_i*m_{i+1}
    ///
    /// where:
    /// - t = (x - x_i) / (x_{i+1} - x_i) ∈ [0,1]
    /// - y_i is the value at x_i
    /// - m_i is the derivative at x_i
    /// - h_i is the interval width (x_{i+1} - x_i)
    /// - h00, h10, h01, h11 are the Hermite basis functions
    fn compute_coefficients(
        x: &Array1<T>,
        y: &Array1<T>,
        derivatives: &Array1<T>,
    ) -> InterpolateResult<Array2<T>> {
        let n = x.len();
        let nm1 = n - 1;

        // For each interval we compute the cubic polynomial coefficients
        // p(x) = a + b*(x-x_i) + c*(x-x_i)^2 + d*(x-x_i)^3
        let mut coeffs = Array2::zeros((nm1, 4));

        for i in 0..nm1 {
            let h = x[i + 1] - x[i];
            let y_i = y[i];
            let y_ip1 = y[i + 1];
            let m_i = derivatives[i];
            let m_ip1 = derivatives[i + 1];

            // Convert Hermite form to polynomial coefficients
            // These are derived from the Hermite basis functions

            // a = y_i
            coeffs[[i, 0]] = y_i;

            // b = m_i
            coeffs[[i, 1]] = m_i;

            // c = (3*(y_ip1 - y_i)/h - 2*m_i - m_ip1)/h
            coeffs[[i, 2]] = (T::from(3.0).expect("Operation failed") * (y_ip1 - y_i) / h
                - T::from(2.0).expect("Operation failed") * m_i
                - m_ip1)
                / h;

            // d = (2*(y_i - y_ip1)/h + m_i + m_ip1)/(h*h)
            coeffs[[i, 3]] =
                (T::from(2.0).expect("Operation failed") * (y_i - y_ip1) / h + m_i + m_ip1)
                    / (h * h);
        }

        Ok(coeffs)
    }

    /// Evaluate the Hermite spline at the given points.
    ///
    /// # Arguments
    ///
    /// * `xnew` - The points at which to evaluate the spline
    ///
    /// # Returns
    ///
    /// A `Result` containing the interpolated values at the given points.
    pub fn evaluate(&self, xnew: &ArrayView1<T>) -> InterpolateResult<Array1<T>> {
        let n = xnew.len();
        let mut result = Array1::zeros(n);

        for (i, &xi) in xnew.iter().enumerate() {
            result[i] = self.evaluate_single(xi)?;
        }

        Ok(result)
    }

    /// Evaluate the Hermite spline at a single point.
    fn evaluate_single(&self, xval: T) -> InterpolateResult<T> {
        let n = self.x.len();

        // Handle extrapolation
        if xval < self.x[0] || xval > self.x[n - 1] {
            match self.extrapolate {
                ExtrapolateMode::Extrapolate => {
                    // Allow extrapolation - use nearest segment
                    let idx = if xval < self.x[0] { 0 } else { n - 2 };
                    return self.evaluate_segment(idx, xval);
                }
                ExtrapolateMode::Nearest => {
                    // Clamp to domain boundary and evaluate there
                    let clamped = xval.max(self.x[0]).min(self.x[n - 1]);
                    return self.evaluate_single(clamped);
                }
                ExtrapolateMode::Error => {
                    return Err(InterpolateError::OutOfBounds(format!(
                        "x value {} is outside the interpolation range [{}, {}]",
                        xval,
                        self.x[0],
                        self.x[n - 1]
                    )));
                }
                ExtrapolateMode::Nan => {
                    // Return NaN for points outside the interpolation domain
                    return Ok(T::nan());
                }
            }
        }

        // Find the segment containing xval
        let mut idx = 0;
        for i in 0..n - 1 {
            if xval >= self.x[i] && xval <= self.x[i + 1] {
                idx = i;
                break;
            }
        }

        self.evaluate_segment(idx, xval)
    }

    /// Evaluate the spline on a specific segment.
    fn evaluate_segment(&self, idx: usize, xval: T) -> InterpolateResult<T> {
        let dx = xval - self.x[idx];

        // Use the coefficient representation
        let a = self.coeffs[[idx, 0]];
        let b = self.coeffs[[idx, 1]];
        let c = self.coeffs[[idx, 2]];
        let d = self.coeffs[[idx, 3]];

        // Polynomial evaluation using Horner's method
        // p(x) = a + dx * (b + dx * (c + dx * d))
        Ok(a + dx * (b + dx * (c + dx * d)))
    }

    /// Calculate derivative of the Hermite spline at the given points.
    ///
    /// # Arguments
    ///
    /// * `deriv_order` - The order of the derivative (1 for first derivative, 2 for second, etc.)
    /// * `xnew` - The points at which to evaluate the derivative
    ///
    /// # Returns
    ///
    /// A `Result` containing the derivative values at the given points.
    pub fn derivative(
        &self,
        deriv_order: usize,
        xnew: &ArrayView1<T>,
    ) -> InterpolateResult<Array1<T>> {
        if deriv_order == 0 {
            return self.evaluate(xnew);
        }

        // For cubic Hermite splines, derivatives above 3 are zero
        // For quintic Hermite splines, derivatives above 5 are zero
        let max_deriv = if self.order == 3 { 3 } else { 5 };

        if deriv_order > max_deriv {
            // Return zeros for higher derivatives that are known to be zero
            return Ok(Array1::zeros(xnew.len()));
        }

        let n = xnew.len();
        let mut result = Array1::zeros(n);

        for (i, &xi) in xnew.iter().enumerate() {
            result[i] = self.derivative_single(deriv_order, xi)?;
        }

        Ok(result)
    }

    /// Calculate derivative of the Hermite spline at a single point.
    fn derivative_single(&self, deriv_order: usize, xval: T) -> InterpolateResult<T> {
        let n = self.x.len();

        // Handle derivatives for extrapolation
        if xval < self.x[0] || xval > self.x[n - 1] {
            match self.extrapolate {
                ExtrapolateMode::Extrapolate => {
                    // Allow extrapolation - use nearest segment
                    let idx = if xval < self.x[0] { 0 } else { n - 2 };
                    return self.derivative_segment(deriv_order, idx, xval);
                }
                ExtrapolateMode::Nearest => {
                    // Clamp to domain boundary and evaluate derivative there
                    let clamped = xval.max(self.x[0]).min(self.x[n - 1]);
                    return self.derivative_single(deriv_order, clamped);
                }
                ExtrapolateMode::Error => {
                    return Err(InterpolateError::OutOfBounds(format!(
                        "x value {} is outside the interpolation range [{}, {}]",
                        xval,
                        self.x[0],
                        self.x[n - 1]
                    )));
                }
                ExtrapolateMode::Nan => {
                    // Return NaN for points outside the interpolation domain
                    return Ok(T::nan());
                }
            }
        }

        // Find the segment containing xval
        let mut idx = 0;
        for i in 0..n - 1 {
            if xval >= self.x[i] && xval <= self.x[i + 1] {
                idx = i;
                break;
            }
        }

        self.derivative_segment(deriv_order, idx, xval)
    }

    /// Calculate derivative of the spline on a specific segment.
    fn derivative_segment(&self, deriv_order: usize, idx: usize, xval: T) -> InterpolateResult<T> {
        let dx = xval - self.x[idx];

        // Get the polynomial coefficients
        let a = self.coeffs[[idx, 0]];
        let b = self.coeffs[[idx, 1]];
        let c = self.coeffs[[idx, 2]];
        let d = self.coeffs[[idx, 3]];

        // Calculate the requested derivative
        match deriv_order {
            0 => Ok(a + dx * (b + dx * (c + dx * d))),
            1 => Ok(b + dx
                * (T::from(2.0).expect("Operation failed") * c
                    + T::from(3.0).expect("Operation failed") * dx * d)),
            2 => Ok(T::from(2.0).expect("Operation failed") * c
                + T::from(6.0).expect("Operation failed") * dx * d),
            3 => Ok(T::from(6.0).expect("Operation failed") * d),
            _ => Ok(T::zero()), // Higher derivatives are zero for cubic splines
        }
    }

    /// Get the derivative values at the data points.
    pub fn get_derivatives(&self) -> &Array1<T> {
        &self.derivatives
    }

    /// Get the order of the Hermite spline (3 for cubic, 5 for quintic).
    pub fn get_order(&self) -> usize {
        self.order
    }

    /// Compute the definite integral of the Hermite spline over an interval.
    ///
    /// # Arguments
    ///
    /// * `a` - Lower bound of the interval
    /// * `b` - Upper bound of the interval
    ///
    /// # Returns
    ///
    /// The definite integral of the Hermite spline over [a, b]
    pub fn integrate(&self, a: T, b: T) -> InterpolateResult<T> {
        let n = self.x.len();

        // Check bounds
        if a < self.x[0] || b > self.x[n - 1] {
            match self.extrapolate {
                ExtrapolateMode::Extrapolate => {
                    // Allow extrapolation
                }
                ExtrapolateMode::Nearest => {
                    // Clamp both integration bounds to domain and integrate there
                    let a_clamped = a.max(self.x[0]).min(self.x[n - 1]);
                    let b_clamped = b.max(self.x[0]).min(self.x[n - 1]);
                    return self.integrate(a_clamped, b_clamped);
                }
                ExtrapolateMode::Error => {
                    return Err(InterpolateError::OutOfBounds(format!(
                        "Integration bounds [{}, {}] are outside the interpolation range [{}, {}]",
                        a,
                        b,
                        self.x[0],
                        self.x[n - 1]
                    )));
                }
                ExtrapolateMode::Nan => {
                    return Ok(T::nan());
                }
            }
        }

        if a > b {
            // If a > b, swap and negate the result
            return Ok(-self.integrate(b, a)?);
        }

        // Find the indices of segments containing a and b
        let mut idx_a = 0;
        let mut idx_b = n - 2;

        for i in 0..n - 1 {
            if a >= self.x[i] && a <= self.x[i + 1] {
                idx_a = i;
            }
            if b >= self.x[i] && b <= self.x[i + 1] {
                idx_b = i;
                break;
            }
        }

        let mut result = T::zero();

        // Special case: a and b are in the same segment
        if idx_a == idx_b {
            result = self.integrate_segment(idx_a, a, b)?;
            return Ok(result);
        }

        // First segment (partial)
        result = result + self.integrate_segment(idx_a, a, self.x[idx_a + 1])?;

        // Middle segments (complete)
        for i in idx_a + 1..idx_b {
            result = result + self.integrate_segment(i, self.x[i], self.x[i + 1])?;
        }

        // Last segment (partial)
        result = result + self.integrate_segment(idx_b, self.x[idx_b], b)?;

        Ok(result)
    }

    /// Integrate a single segment of the Hermite spline.
    fn integrate_segment(&self, idx: usize, a: T, b: T) -> InterpolateResult<T> {
        // Get the polynomial coefficients for this segment
        let c0 = self.coeffs[[idx, 0]];
        let c1 = self.coeffs[[idx, 1]];
        let c2 = self.coeffs[[idx, 2]];
        let c3 = self.coeffs[[idx, 3]];

        let x_i = self.x[idx];

        // Shift to local coordinates
        let a_local = a - x_i;
        let b_local = b - x_i;

        // Integrate the polynomial: ∫(c0 + c1*x + c2*x^2 + c3*x^3) dx
        // = c0*x + c1*x^2/2 + c2*x^3/3 + c3*x^4/4
        let antiderivative = |x: T| -> T {
            c0 * x
                + c1 * x * x / T::from(2.0).expect("Operation failed")
                + c2 * x * x * x / T::from(3.0).expect("Operation failed")
                + c3 * x * x * x * x / T::from(4.0).expect("Operation failed")
        };

        // Evaluate the definite integral
        Ok(antiderivative(b_local) - antiderivative(a_local))
    }
}

/// Creates a cubic Hermite spline with automatically calculated derivatives.
///
/// # Arguments
///
/// * `x` - The x-coordinates of the data points
/// * `y` - The y-coordinates of the data points
/// * `extrapolate` - How to handle points outside the domain of the data
///
/// # Returns
///
/// A `Result` containing the Hermite spline interpolator.
#[allow(dead_code)]
pub fn make_hermite_spline<T: Float + std::fmt::Display>(
    x: &ArrayView1<T>,
    y: &ArrayView1<T>,
    extrapolate: ExtrapolateMode,
) -> InterpolateResult<HermiteSpline<T>> {
    HermiteSpline::new(x, y, None, DerivativeSpec::Estimated, extrapolate)
}

/// Creates a cubic Hermite spline with explicitly provided derivatives.
///
/// # Arguments
///
/// * `x` - The x-coordinates of the data points
/// * `y` - The y-coordinates of the data points
/// * `derivatives` - The derivative values at each data point
/// * `extrapolate` - How to handle points outside the domain of the data
///
/// # Returns
///
/// A `Result` containing the Hermite spline interpolator.
#[allow(dead_code)]
pub fn make_hermite_spline_with_derivatives<T: Float + std::fmt::Display>(
    x: &ArrayView1<T>,
    y: &ArrayView1<T>,
    derivatives: &ArrayView1<T>,
    extrapolate: ExtrapolateMode,
) -> InterpolateResult<HermiteSpline<T>> {
    HermiteSpline::new(x, y, Some(derivatives), DerivativeSpec::Direct, extrapolate)
}

/// Creates a cubic Hermite spline with zero derivatives at endpoints.
///
/// # Arguments
///
/// * `x` - The x-coordinates of the data points
/// * `y` - The y-coordinates of the data points
/// * `extrapolate` - How to handle points outside the domain of the data
///
/// # Returns
///
/// A `Result` containing the Hermite spline interpolator.
#[allow(dead_code)]
pub fn make_natural_hermite_spline<T: Float + std::fmt::Display>(
    x: &ArrayView1<T>,
    y: &ArrayView1<T>,
    extrapolate: ExtrapolateMode,
) -> InterpolateResult<HermiteSpline<T>> {
    HermiteSpline::new(x, y, None, DerivativeSpec::ZeroAtEndpoints, extrapolate)
}

/// Creates a periodic cubic Hermite spline.
///
/// Ensures the derivatives at the endpoints match, creating a smooth
/// periodic function.
///
/// # Arguments
///
/// * `x` - The x-coordinates of the data points
/// * `y` - The y-coordinates of the data points (first and last should be approximately equal)
/// * `extrapolate` - How to handle points outside the domain of the data
///
/// # Returns
///
/// A `Result` containing the Hermite spline interpolator.
#[allow(dead_code)]
pub fn make_periodic_hermite_spline<T: Float + std::fmt::Display>(
    x: &ArrayView1<T>,
    y: &ArrayView1<T>,
    extrapolate: ExtrapolateMode,
) -> InterpolateResult<HermiteSpline<T>> {
    HermiteSpline::new(x, y, None, DerivativeSpec::Periodic, extrapolate)
}

/// Creates a quintic Hermite spline with explicitly provided first and second derivatives.
///
/// # Arguments
///
/// * `x` - The x-coordinates of the data points
/// * `y` - The y-coordinates of the data points
/// * `first_derivs` - The first derivative values at each data point
/// * `second_derivs` - The second derivative values at each data point
/// * `extrapolate` - How to handle points outside the domain of the data
///
/// # Returns
///
/// A `Result` containing the Hermite spline interpolator.
#[allow(dead_code)]
pub fn make_quintic_hermite_spline<T: Float + std::fmt::Display>(
    x: &ArrayView1<T>,
    y: &ArrayView1<T>,
    first_derivs: &ArrayView1<T>,
    second_derivs: &ArrayView1<T>,
    extrapolate: ExtrapolateMode,
) -> InterpolateResult<HermiteSpline<T>> {
    HermiteSpline::new_quintic(x, y, first_derivs, second_derivs, extrapolate)
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use scirs2_core::ndarray::Array;

    #[test]
    fn test_hermite_spline_creation() {
        let x = Array::linspace(0.0, 10.0, 11);
        let y = x.mapv(|v| v.powi(2));

        // Create with estimated derivatives
        let spline = make_hermite_spline(&x.view(), &y.view(), ExtrapolateMode::Error)
            .expect("Operation failed");

        // Check that derivatives were computed
        assert_eq!(spline.get_derivatives().len(), x.len());
        assert_eq!(spline.get_order(), 3); // Should be cubic
    }

    #[test]
    fn test_hermite_spline_with_derivatives() {
        let x = Array::linspace(0.0, 10.0, 11);
        let y = x.mapv(|v| v.powi(2));

        // For y = x^2, the derivative is 2*x
        let derivatives = x.mapv(|v| v * 2.0);

        // Create with explicit derivatives
        let spline = make_hermite_spline_with_derivatives(
            &x.view(),
            &y.view(),
            &derivatives.view(),
            ExtrapolateMode::Error,
        )
        .expect("Operation failed");

        // Test interpolation at data points
        for i in 0..x.len() {
            let eval = spline.evaluate_single(x[i]).expect("Operation failed");
            assert_abs_diff_eq!(eval, y[i], epsilon = 1e-6);
        }

        // Test interpolation between data points
        let xnew = Array::linspace(0.5, 9.5, 10);
        let y_exact = xnew.mapv(|v| v.powi(2));

        let y_interp = spline.evaluate(&xnew.view()).expect("Operation failed");

        // Since we provided exact derivatives, the interpolation should be very accurate
        for i in 0..y_interp.len() {
            assert_abs_diff_eq!(y_interp[i], y_exact[i], epsilon = 1e-6);
        }
    }

    #[test]
    fn test_natural_hermite_spline() {
        let x = Array::linspace(0.0, 10.0, 11);
        let y = x.mapv(|v| v.powi(2));

        // Create with zero endpoint derivatives
        let spline = make_natural_hermite_spline(&x.view(), &y.view(), ExtrapolateMode::Error)
            .expect("Operation failed");

        // Check that the derivatives at endpoints are zero
        let derivs = spline.get_derivatives();
        assert_abs_diff_eq!(derivs[0], 0.0, epsilon = 1e-6);
        assert_abs_diff_eq!(derivs[derivs.len() - 1], 0.0, epsilon = 1e-6);
    }

    #[test]
    fn test_hermite_spline_derivatives() {
        let x = Array::linspace(0.0, 10.0, 11);
        let y = x.mapv(|v| v.powi(2));

        // For y = x^2, the derivative is 2*x
        let derivatives = x.mapv(|v| v * 2.0);

        let spline = make_hermite_spline_with_derivatives(
            &x.view(),
            &y.view(),
            &derivatives.view(),
            ExtrapolateMode::Error,
        )
        .expect("Operation failed");

        // Test first derivatives
        let x_test = Array::from_vec(vec![2.5, 5.0, 7.5]);
        let deriv1 = spline
            .derivative(1, &x_test.view())
            .expect("Operation failed");

        // Expected derivatives: 2*x
        let expected_deriv1 = x_test.mapv(|v| 2.0 * v);

        for i in 0..deriv1.len() {
            assert_abs_diff_eq!(deriv1[i], expected_deriv1[i], epsilon = 1e-6);
        }

        // Test second derivatives (should be 2 for y = x^2)
        let deriv2 = spline
            .derivative(2, &x_test.view())
            .expect("Operation failed");

        for i in 0..deriv2.len() {
            assert_abs_diff_eq!(deriv2[i], 2.0, epsilon = 1e-6);
        }
    }

    #[test]
    fn test_periodic_hermite_spline() {
        // Create a sine wave from 0 to 2π (periodic function)
        let x = Array::linspace(0.0, 2.0 * std::f64::consts::PI, 11);
        let y = x.mapv(|v| v.sin());

        // Create periodic Hermite spline
        let spline =
            make_periodic_hermite_spline(&x.view(), &y.view(), ExtrapolateMode::Extrapolate)
                .expect("Operation failed");

        // Check that derivatives at endpoints match (since it's periodic)
        let derivs = spline.get_derivatives();
        // The derivatives should match for a periodic spline
        assert_abs_diff_eq!(derivs[0], derivs[derivs.len() - 1], epsilon = 1e-6);

        // Test interpolation at data points - should match exactly
        for i in 0..x.len() {
            let eval = spline.evaluate_single(x[i]).expect("Operation failed");
            assert_abs_diff_eq!(eval, y[i], epsilon = 1e-6);
        }

        // Test interpolation inside the domain
        let x_test = Array::from_vec(vec![std::f64::consts::PI / 2.0, std::f64::consts::PI]);
        let y_test = spline.evaluate(&x_test.view()).expect("Operation failed");

        // sin(π/2) = 1.0, sin(π) = 0.0
        // Hermite splines with 11 points give good but not perfect accuracy
        assert_abs_diff_eq!(y_test[0], 1.0, epsilon = 5e-3);
        assert_abs_diff_eq!(y_test[1], 0.0, epsilon = 5e-3);
    }

    #[test]
    fn test_quintic_hermite_spline() {
        let x = Array::linspace(0.0, 10.0, 11);
        let y = x.mapv(|v| v.powi(2));

        // For y = x^2, the first derivative is 2*x and second derivative is 2
        let first_derivs = x.mapv(|v| v * 2.0);
        let second_derivs = Array::from_elem(x.len(), 2.0);

        // Create quintic Hermite spline
        let spline = make_quintic_hermite_spline(
            &x.view(),
            &y.view(),
            &first_derivs.view(),
            &second_derivs.view(),
            ExtrapolateMode::Error,
        )
        .expect("Operation failed");

        assert_eq!(spline.get_order(), 5); // Should be quintic

        // Test interpolation at data points
        for i in 0..x.len() {
            let eval = spline.evaluate_single(x[i]).expect("Operation failed");
            assert_abs_diff_eq!(eval, y[i], epsilon = 1e-6);
        }

        // Test interpolation between data points
        let xnew = Array::linspace(0.5, 9.5, 10);
        let y_exact = xnew.mapv(|v| v.powi(2));

        let y_interp = spline.evaluate(&xnew.view()).expect("Operation failed");

        // Since we provided exact derivatives, the interpolation should be very accurate
        for i in 0..y_interp.len() {
            assert_abs_diff_eq!(y_interp[i], y_exact[i], epsilon = 1e-6);
        }
    }
}