scirs2-interpolate 0.4.2

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
//! PCHIP (Piecewise Cubic Hermite Interpolating Polynomial) interpolation
//!
//! This module provides an implementation of the PCHIP algorithm, which produces
//! shape-preserving interpolants that maintain monotonicity in the data.

use crate::error::{InterpolateError, InterpolateResult};
use scirs2_core::ndarray::{Array1, ArrayView1};
use scirs2_core::numeric::{Float, FromPrimitive};
use std::fmt::Debug;

/// Strategy for PCHIP extrapolation outside the data range.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum PchipExtrapolateMode {
    /// Linear extension using the endpoint derivative (bounded growth, stable
    /// for far extrapolation). This is the default.
    #[default]
    Linear,
    /// Hermite polynomial continuation of the boundary segment. Matches
    /// `scipy.interpolate.PchipInterpolator(extrapolate=True)` but can grow
    /// cubically for points far from the data range.
    Polynomial,
}

/// PCHIP (Piecewise Cubic Hermite Interpolating Polynomial) interpolator
///
/// This interpolator preserves monotonicity in the interpolation data and does
/// not overshoot if the data is not smooth. The first derivatives are guaranteed
/// to be continuous, but the second derivatives may jump at the knot points.
///
/// The algorithm determines the derivatives at points x_k by using the PCHIP algorithm
/// from Fritsch and Butland (1984).
///
/// # References
///
/// 1. F. N. Fritsch and J. Butland, "A method for constructing local monotone
///    piecewise cubic interpolants", SIAM J. Sci. Comput., 5(2), 300-304 (1984).
/// 2. C. Moler, "Numerical Computing with Matlab", 2004.
#[derive(Debug, Clone)]
pub struct PchipInterpolator<F: Float> {
    /// X coordinates (must be sorted)
    x: Array1<F>,
    /// Y coordinates
    y: Array1<F>,
    /// Derivatives at points
    derivatives: Array1<F>,
    /// Extrapolation mode
    extrapolate: bool,
    /// Extrapolation strategy (linear vs polynomial continuation)
    extrapolate_mode: PchipExtrapolateMode,
}

impl<F: Float + FromPrimitive + Debug> PchipInterpolator<F> {
    /// Create a new PCHIP interpolator
    ///
    /// # Arguments
    ///
    /// * `x` - The x coordinates (must be sorted in ascending order)
    /// * `y` - The y coordinates (must have the same length as x)
    /// * `extrapolate` - Whether to extrapolate beyond the data range
    ///
    /// # Returns
    ///
    /// A new `PchipInterpolator` object
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `x` and `y` have different lengths
    /// - `x` is not sorted in ascending order
    /// - There are fewer than 2 points
    /// - `y` contains complex values (not supported)
    ///
    /// # Examples
    ///
    /// ```
    /// use scirs2_core::ndarray::array;
    /// use scirs2_interpolate::interp1d::pchip::PchipInterpolator;
    ///
    /// let x = array![0.0f64, 1.0, 2.0, 3.0];
    /// let y = array![0.0f64, 1.0, 4.0, 9.0];
    ///
    /// // Create a PCHIP interpolator
    /// let interp = PchipInterpolator::new(&x.view(), &y.view(), true).expect("Operation failed");
    ///
    /// // Interpolate at x = 1.5
    /// let y_interp = interp.evaluate(1.5);
    /// ```
    pub fn new(x: &ArrayView1<F>, y: &ArrayView1<F>, extrapolate: bool) -> 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() < 2 {
            return Err(InterpolateError::insufficient_points(
                2,
                x.len(),
                "PCHIP interpolation",
            ));
        }

        // 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(),
                ));
            }
        }

        // Clone input arrays
        let x_arr = x.to_owned();
        let y_arr = y.to_owned();

        // Compute derivatives at points
        let derivatives = Self::find_derivatives(&x_arr, &y_arr)?;

        Ok(PchipInterpolator {
            x: x_arr,
            y: y_arr,
            derivatives,
            extrapolate,
            extrapolate_mode: PchipExtrapolateMode::Linear,
        })
    }

    /// Set the extrapolation mode (builder pattern).
    ///
    /// # Arguments
    ///
    /// * `mode` - The extrapolation strategy to use
    pub fn with_extrapolate_mode(mut self, mode: PchipExtrapolateMode) -> Self {
        self.extrapolate_mode = mode;
        self
    }

    /// Evaluate the interpolation at the given point
    ///
    /// # Arguments
    ///
    /// * `xnew` - The x coordinate at which to evaluate the interpolation
    ///
    /// # Returns
    ///
    /// The interpolated y value at `xnew`
    ///
    /// # Errors
    ///
    /// Returns an error if `xnew` is outside the interpolation range and
    /// extrapolation is disabled.
    pub fn evaluate(&self, xnew: F) -> InterpolateResult<F> {
        let n = self.x.len();

        // Check if we're extrapolating
        let is_extrapolating = xnew < self.x[0] || xnew > self.x[n - 1];
        if is_extrapolating && !self.extrapolate {
            return Err(InterpolateError::OutOfBounds(
                "xnew is outside the interpolation range".to_string(),
            ));
        }

        // Handle linear extrapolation mode
        if is_extrapolating && self.extrapolate_mode == PchipExtrapolateMode::Linear {
            if xnew < self.x[0] {
                let dx = xnew - self.x[0];
                return Ok(self.y[0] + self.derivatives[0] * dx);
            } else {
                let dx = xnew - self.x[n - 1];
                return Ok(self.y[n - 1] + self.derivatives[n - 1] * dx);
            }
        }

        // Special case: xnew is exactly the last point (non-extrapolating)
        if !is_extrapolating && xnew == self.x[n - 1] {
            return Ok(self.y[n - 1]);
        }

        // Find the segment index
        let idx = if is_extrapolating {
            // Polynomial extrapolation: use boundary segment
            if xnew < self.x[0] {
                0
            } else {
                n - 2
            }
        } else {
            // In-bounds: binary/linear search
            let mut seg = 0;
            for i in 0..n - 1 {
                if xnew >= self.x[i] && xnew <= self.x[i + 1] {
                    seg = i;
                    break;
                }
            }
            seg
        };

        // Get coordinates and derivatives for the segment
        let x1 = self.x[idx];
        let x2 = self.x[idx + 1];
        let y1 = self.y[idx];
        let y2 = self.y[idx + 1];
        let d1 = self.derivatives[idx];
        let d2 = self.derivatives[idx + 1];

        // Normalized position within the interval [x1, x2]
        // For polynomial extrapolation t may be outside [0,1]
        let h = x2 - x1;
        let t = (xnew - x1) / h;

        // Compute Hermite basis functions
        let h00 = Self::h00(t);
        let h10 = Self::h10(t);
        let h01 = Self::h01(t);
        let h11 = Self::h11(t);

        // Evaluate cubic Hermite polynomial
        let result = h00 * y1 + h10 * h * d1 + h01 * y2 + h11 * h * d2;

        Ok(result)
    }

    /// Evaluate the interpolation at multiple points
    ///
    /// # Arguments
    ///
    /// * `xnew` - The x coordinates at which to evaluate the interpolation
    ///
    /// # Returns
    ///
    /// The interpolated y values at `xnew`
    ///
    /// # Errors
    ///
    /// Returns an error if any point in `xnew` is outside the interpolation range
    /// and extrapolation is disabled.
    pub fn evaluate_array(&self, xnew: &ArrayView1<F>) -> InterpolateResult<Array1<F>> {
        let mut result = Array1::zeros(xnew.len());
        for (i, &x) in xnew.iter().enumerate() {
            result[i] = self.evaluate(x)?;
        }
        Ok(result)
    }

    /// Hermite basis function h₀₀(t)
    fn h00(t: F) -> F {
        let two = F::from_f64(2.0).expect("Operation failed");
        let three = F::from_f64(3.0).expect("Operation failed");
        (two * t * t * t) - (three * t * t) + F::one()
    }

    /// Hermite basis function h₁₀(t)
    fn h10(t: F) -> F {
        let two = F::from_f64(2.0).expect("Operation failed");
        // three is not used in this function
        (t * t * t) - (two * t * t) + t
    }

    /// Hermite basis function h₀₁(t)
    fn h01(t: F) -> F {
        let two = F::from_f64(2.0).expect("Operation failed");
        let three = F::from_f64(3.0).expect("Operation failed");
        -(two * t * t * t) + (three * t * t)
    }

    /// Hermite basis function h₁₁(t)
    fn h11(t: F) -> F {
        // No constants needed for this function
        (t * t * t) - (t * t)
    }

    /// Helper for edge case derivative estimation
    ///
    /// # Arguments
    ///
    /// * `h0` - Spacing: x[1] - x[0] for the first point, or x[n-1] - x[n-2] for the last point
    /// * `h1` - Spacing: x[2] - x[1] for the first point, or x[n] - x[n-1] for the last point
    /// * `m0` - Slope of the first segment
    /// * `m1` - Slope of the second segment
    ///
    /// # Returns
    ///
    /// The estimated derivative at the endpoint
    fn edge_case(h0: F, h1: F, m0: F, m1: F) -> F {
        // One-sided three-point estimate for the derivative
        let two = F::from_f64(2.0).expect("Operation failed");
        let three = F::from_f64(3.0).expect("Operation failed");

        let d = ((two * h0 + h1) * m0 - h0 * m1) / (h0 + h1);

        // Try to preserve shape
        let sign_d = if d >= F::zero() { F::one() } else { -F::one() };
        let sign_m0 = if m0 >= F::zero() { F::one() } else { -F::one() };
        let sign_m1 = if m1 >= F::zero() { F::one() } else { -F::one() };

        // If the signs are different or abs(d) > 3*abs(m0), adjust d
        if sign_d != sign_m0 {
            F::zero()
        } else if (sign_m0 != sign_m1) && (d.abs() > three * m0.abs()) {
            three * m0
        } else {
            d
        }
    }

    /// Compute derivatives at points for PCHIP interpolation
    ///
    /// # Arguments
    ///
    /// * `x` - X coordinates
    /// * `y` - Y coordinates
    ///
    /// # Returns
    ///
    /// Array of derivatives, one for each point in x
    fn find_derivatives(x: &Array1<F>, y: &Array1<F>) -> InterpolateResult<Array1<F>> {
        let n = x.len();
        let mut derivatives = Array1::zeros(n);

        // Handle special case: only two points, use linear interpolation
        if n == 2 {
            let slope = (y[1] - y[0]) / (x[1] - x[0]);
            derivatives[0] = slope;
            derivatives[1] = slope;
            return Ok(derivatives);
        }

        // Calculate slopes between segments: m_k = (y_{k+1} - y_k) / (x_{k+1} - x_k)
        let mut slopes = Array1::zeros(n - 1);
        for i in 0..n - 1 {
            slopes[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]);
        }

        // Calculate spacings: h_k = x_{k+1} - x_k
        let mut h = Array1::zeros(n - 1);
        for i in 0..n - 1 {
            h[i] = x[i + 1] - x[i];
        }

        // For interior points, use PCHIP formula
        let two = F::from_f64(2.0).expect("Operation failed");

        for i in 1..n - 1 {
            // Determine if slopes have different signs or if either is zero
            let prev_slope = slopes[i - 1];
            let curr_slope = slopes[i];

            let sign_prev = if prev_slope > F::zero() {
                F::one()
            } else if prev_slope < F::zero() {
                -F::one()
            } else {
                F::zero()
            };

            let sign_curr = if curr_slope > F::zero() {
                F::one()
            } else if curr_slope < F::zero() {
                -F::one()
            } else {
                F::zero()
            };

            // If signs are different or either slope is zero, set derivative to zero
            if sign_prev * sign_curr <= F::zero() {
                derivatives[i] = F::zero();
            } else {
                // Use weighted harmonic mean
                let w1 = two * h[i] + h[i - 1];
                let w2 = h[i] + two * h[i - 1];

                // Compute harmonic mean
                if prev_slope.abs() < F::epsilon() || curr_slope.abs() < F::epsilon() {
                    derivatives[i] = F::zero();
                } else {
                    let whmean_inv = (w1 / prev_slope + w2 / curr_slope) / (w1 + w2);
                    derivatives[i] = F::one() / whmean_inv;
                }
            }
        }

        // Special case: endpoints
        // For the first point
        derivatives[0] = Self::edge_case(h[0], h[1], slopes[0], slopes[1]);

        // For the last point
        derivatives[n - 1] = Self::edge_case(h[n - 2], h[n - 3], slopes[n - 2], slopes[n - 3]);

        Ok(derivatives)
    }
}

/// PCHIP (Piecewise Cubic Hermite Interpolating Polynomial) interpolation convenience function
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates
/// * `xnew` - The points at which to interpolate
/// * `extrapolate` - Whether to extrapolate beyond the data range
///
/// # Returns
///
/// The interpolated values
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::array;
/// use scirs2_interpolate::pchip_interpolate;
///
/// let x = array![0.0f64, 1.0, 2.0, 3.0];
/// let y = array![0.0f64, 1.0, 4.0, 9.0];
/// let xnew = array![0.5f64, 1.5, 2.5];
///
/// let y_interp = pchip_interpolate(&x.view(), &y.view(), &xnew.view(), true).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn pchip_interpolate<F: crate::traits::InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
    xnew: &ArrayView1<F>,
    extrapolate: bool,
) -> InterpolateResult<Array1<F>> {
    let interp = PchipInterpolator::new(x, y, extrapolate)?;
    interp.evaluate_array(xnew)
}

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

    #[test]
    fn test_pchip_interpolation_basic() {
        let x = array![0.0, 1.0, 2.0, 3.0];
        let y = array![0.0, 1.0, 4.0, 9.0];

        let interp = PchipInterpolator::new(&x.view(), &y.view(), false).expect("Operation failed");

        // Test points exactly at data points
        assert_relative_eq!(interp.evaluate(0.0).expect("Operation failed"), 0.0);
        assert_relative_eq!(interp.evaluate(1.0).expect("Operation failed"), 1.0);
        assert_relative_eq!(interp.evaluate(2.0).expect("Operation failed"), 4.0);
        assert_relative_eq!(interp.evaluate(3.0).expect("Operation failed"), 9.0);

        // Test points between data points - PCHIP should preserve shape
        let y_interp_0_5 = interp.evaluate(0.5).expect("Operation failed");
        let y_interp_1_5 = interp.evaluate(1.5).expect("Operation failed");
        let y_interp_2_5 = interp.evaluate(2.5).expect("Operation failed");

        // For this monotonically increasing data, PCHIP should preserve monotonicity
        assert!(y_interp_0_5 > 0.0 && y_interp_0_5 < 1.0);
        assert!(y_interp_1_5 > 1.0 && y_interp_1_5 < 4.0);
        assert!(y_interp_2_5 > 4.0 && y_interp_2_5 < 9.0);
    }

    #[test]
    fn test_pchip_monotonicity_preservation() {
        // Test with data that has monotonic segments
        let x = array![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
        let y = array![0.0, 1.0, 0.5, 0.0, 0.5, 2.0];

        let interp = PchipInterpolator::new(&x.view(), &y.view(), false).expect("Operation failed");

        // Check monotonicity preservation in the first segment (increasing)
        let y_0_25 = interp.evaluate(0.25).expect("Operation failed");
        let y_0_50 = interp.evaluate(0.50).expect("Operation failed");
        let y_0_75 = interp.evaluate(0.75).expect("Operation failed");
        assert!(y_0_25 <= y_0_50 && y_0_50 <= y_0_75);

        // Check monotonicity preservation in the second segment (decreasing)
        let y_1_25 = interp.evaluate(1.25).expect("Operation failed");
        let y_1_50 = interp.evaluate(1.50).expect("Operation failed");
        let y_1_75 = interp.evaluate(1.75).expect("Operation failed");
        assert!(y_1_25 >= y_1_50 && y_1_50 >= y_1_75);

        // Check monotonicity preservation in the last segment (increasing)
        let y_4_25 = interp.evaluate(4.25).expect("Operation failed");
        let y_4_50 = interp.evaluate(4.50).expect("Operation failed");
        let y_4_75 = interp.evaluate(4.75).expect("Operation failed");
        assert!(y_4_25 <= y_4_50 && y_4_50 <= y_4_75);
    }

    #[test]
    fn test_pchip_extrapolation() {
        let x = array![0.0, 1.0, 2.0, 3.0];
        let y = array![0.0, 1.0, 4.0, 9.0];

        // Test with extrapolation enabled
        let interp_extrap =
            PchipInterpolator::new(&x.view(), &y.view(), true).expect("Operation failed");
        let y_minus_1 = interp_extrap.evaluate(-1.0).expect("Operation failed");
        let y_plus_4 = interp_extrap.evaluate(4.0).expect("Operation failed");

        // For this data, PCHIP computes derivatives that preserve shape
        // The extrapolation uses linear extension based on endpoint derivatives
        // Verify that extrapolation above the range increases beyond the last point
        assert!(
            y_plus_4 > 9.0,
            "Extrapolation above should be greater than last point"
        );

        // Verify that extrapolation is finite (not NaN or infinite)
        assert!(
            y_minus_1.is_finite(),
            "Extrapolation should produce finite values"
        );
        assert!(
            y_plus_4.is_finite(),
            "Extrapolation should produce finite values"
        );

        // Test with extrapolation disabled
        let interp_no_extrap =
            PchipInterpolator::new(&x.view(), &y.view(), false).expect("Operation failed");
        assert!(interp_no_extrap.evaluate(-1.0).is_err());
        assert!(interp_no_extrap.evaluate(4.0).is_err());
    }

    #[test]
    fn test_pchip_extrapolation_far_beyond_range() {
        // Regression test for issue #96
        // PCHIP extrapolation should use linear extension, not cubic polynomial
        let x = array![0.0, 1.0, 2.0, 3.0];
        let y = array![0.0, 1.0, 4.0, 9.0];

        let interp = PchipInterpolator::new(&x.view(), &y.view(), true).expect("Operation failed");

        // Test far extrapolation (the bug case)
        let y_50 = interp.evaluate(50.0).expect("Operation failed");

        // THE KEY FIX: Before the fix, this returned -24008 (wrong!)
        // After the fix with linear extrapolation, it should:
        // 1. Be positive (not -24008 as in the bug)
        // 2. Be greater than the last data point (9.0)
        // 3. Be reasonable (linear extension, not explosive)
        assert!(
            y_50 > 9.0,
            "Extrapolation at x=50 should be > 9.0, got {}",
            y_50
        );
        assert!(
            y_50 < 1000.0,
            "Extrapolation should be reasonable (linear), got {}",
            y_50
        );
        assert!(
            y_50.is_finite(),
            "Extrapolation should produce finite values"
        );

        // Test far extrapolation in the negative direction
        // Should be finite and reasonable (not explosive)
        let y_minus_50 = interp.evaluate(-50.0).expect("Operation failed");
        assert!(
            y_minus_50.is_finite(),
            "Extrapolation should produce finite values"
        );
        assert!(
            y_minus_50.abs() < 1000.0,
            "Extrapolation should be reasonable (linear), got {}",
            y_minus_50
        );
    }

    #[test]
    fn test_pchip_extrapolation_linear_behavior() {
        // Verify that extrapolation uses linear extension (not cubic)
        let x = array![0.0, 1.0, 2.0, 3.0];
        let y = array![0.0, 1.0, 4.0, 9.0];

        let interp = PchipInterpolator::new(&x.view(), &y.view(), true).expect("Operation failed");

        // Get extrapolated values at two points beyond the range
        let y_4 = interp.evaluate(4.0).expect("Operation failed");
        let y_5 = interp.evaluate(5.0).expect("Operation failed");

        // If using linear extrapolation, the slope should be constant
        // slope = (y_5 - y_4) / (5.0 - 4.0) = y_5 - y_4
        let extrap_slope = y_5 - y_4;

        // The slope should be equal to the derivative at the last point
        let last_derivative = interp.derivatives[interp.derivatives.len() - 1];

        // Allow small numerical differences
        assert_relative_eq!(extrap_slope, last_derivative, epsilon = 1e-10);
    }

    #[test]
    fn test_pchip_interpolate_function() {
        let x = array![0.0, 1.0, 2.0, 3.0];
        let y = array![0.0, 1.0, 4.0, 9.0];
        let xnew = array![0.5, 1.5, 2.5];

        let y_interp =
            pchip_interpolate(&x.view(), &y.view(), &xnew.view(), false).expect("Operation failed");

        // Test that the function returns the expected number of points
        assert_eq!(y_interp.len(), 3);

        // For this monotonically increasing data, all interpolated values should be monotonically increasing
        assert!(y_interp[0] > 0.0 && y_interp[0] < 1.0);
        assert!(y_interp[1] > 1.0 && y_interp[1] < 4.0);
        assert!(y_interp[2] > 4.0 && y_interp[2] < 9.0);
    }

    #[test]
    fn test_pchip_error_conditions() {
        // Test with different length arrays
        let x = array![0.0, 1.0, 2.0, 3.0];
        let y = array![0.0, 1.0, 4.0];
        assert!(PchipInterpolator::new(&x.view(), &y.view(), false).is_err());

        // Test with unsorted x
        let x_unsorted = array![0.0, 2.0, 1.0, 3.0];
        let y_valid = array![0.0, 1.0, 4.0, 9.0];
        assert!(PchipInterpolator::new(&x_unsorted.view(), &y_valid.view(), false).is_err());

        // Test with too few points
        let x_short = array![0.0];
        let y_short = array![0.0];
        assert!(PchipInterpolator::new(&x_short.view(), &y_short.view(), false).is_err());
    }
}