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
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
//! Core cubic spline interpolation algorithms
//!
//! This module contains the computational functions for various types of cubic spline
//! interpolation with different boundary conditions. These functions implement the mathematical
//! algorithms for solving the tridiagonal systems that arise in spline construction.
//!
//! ## Overview
//!
//! Cubic splines are piecewise cubic polynomials that provide smooth interpolation through
//! a set of data points. The different functions in this module handle various boundary
//! conditions:
//!
//! - **Natural**: Zero second derivative at endpoints
//! - **Not-a-knot**: Continuous third derivative at second and second-to-last points
//! - **Clamped**: Specified first derivatives at endpoints
//! - **Periodic**: Function and derivatives match at endpoints
//! - **Second derivative**: Specified second derivatives at endpoints
//! - **Parabolic runout**: Zero third derivative at endpoints
//!
//! ## Computational Approach
//!
//! All spline algorithms follow a similar pattern:
//! 1. Set up a tridiagonal system based on continuity and boundary conditions
//! 2. Solve for second derivatives at each point using Thomas algorithm
//! 3. Calculate polynomial coefficients for each segment
//!
//! The resulting coefficients define cubic polynomials of the form:
//! ```text
//! y(x) = a + b(x-xᵢ) + c(x-xᵢ)² + d(x-xᵢ)³
//! ```

use crate::error::{InterpolateError, InterpolateResult};
use crate::traits::InterpolationFloat;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1};

/// Compute the coefficients for a natural cubic spline
///
/// Natural boundary conditions: second derivative is zero at the endpoints.
/// This minimizes the total curvature of the spline and is often the default choice
/// when no specific endpoint behavior is required.
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates (must have the same length as x)
///
/// # Returns
///
/// A 2D array of shape (n-1, 4) containing the polynomial coefficients for each segment.
/// Each row contains [a, b, c, d] for the polynomial: a + b(x-xᵢ) + c(x-xᵢ)² + d(x-xᵢ)³
///
/// # Errors
///
/// Returns `InterpolateError::ComputationError` if:
/// - Any interval has zero length (duplicate x values)
/// - Numerical issues in the tridiagonal solver
/// - Float conversion failures
#[allow(dead_code)]
pub fn compute_natural_cubic_spline<F: InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
) -> InterpolateResult<Array2<F>> {
    let n = x.len();
    let n_segments = n - 1;

    // Create array to hold the coefficients (n-1 segments x 4 coefficients)
    let mut coeffs = Array2::<F>::zeros((n_segments, 4));

    // Step 1: Calculate the second derivatives at each point
    // We solve the tridiagonal system to get these

    // Set up the tridiagonal system
    let mut a = Array1::<F>::zeros(n);
    let mut b = Array1::<F>::zeros(n);
    let mut c = Array1::<F>::zeros(n);
    let mut d = Array1::<F>::zeros(n);

    // Natural boundary conditions
    b[0] = F::one();
    d[0] = F::zero();
    b[n - 1] = F::one();
    d[n - 1] = F::zero();

    // Fill in the tridiagonal system
    for i in 1..n - 1 {
        let h_i_minus_1 = x[i] - x[i - 1];
        let h_i = x[i + 1] - x[i];

        a[i] = h_i_minus_1;
        let two = F::from_f64(2.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 2.0 to float type".to_string(),
            )
        })?;
        b[i] = two * (h_i_minus_1 + h_i);
        c[i] = h_i;

        let dy_i_minus_1 = y[i] - y[i - 1];
        let dy_i = y[i + 1] - y[i];

        // Check for division by zero in slope calculations
        if h_i.is_zero() || h_i_minus_1.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in spline computation".to_string(),
            ));
        }

        let six = F::from_f64(6.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 6.0 to float type".to_string(),
            )
        })?;
        d[i] = six * (dy_i / h_i - dy_i_minus_1 / h_i_minus_1);
    }

    // Solve the tridiagonal system using the Thomas algorithm
    let mut sigma = Array1::<F>::zeros(n);

    // Forward sweep
    for i in 1..n {
        // Check for division by zero
        if b[i - 1].is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero diagonal element in Thomas algorithm forward sweep".to_string(),
            ));
        }
        let m = a[i] / b[i - 1];
        b[i] -= m * c[i - 1];
        d[i] = d[i] - m * d[i - 1];
    }

    // Back substitution
    if b[n - 1].is_zero() {
        return Err(InterpolateError::ComputationError(
            "Zero diagonal element in Thomas algorithm back substitution".to_string(),
        ));
    }
    sigma[n - 1] = d[n - 1] / b[n - 1];
    for i in (0..n - 1).rev() {
        if b[i].is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero diagonal element in Thomas algorithm back substitution".to_string(),
            ));
        }
        sigma[i] = (d[i] - c[i] * sigma[i + 1]) / b[i];
    }

    // Step 2: Calculate the polynomial coefficients
    for i in 0..n_segments {
        let h_i = x[i + 1] - x[i];

        // Check for division by zero in coefficient calculation
        if h_i.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in spline coefficient calculation".to_string(),
            ));
        }

        let two = F::from_f64(2.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 2.0 to float type".to_string(),
            )
        })?;
        let six = F::from_f64(6.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 6.0 to float type".to_string(),
            )
        })?;

        // a is just the y value at the left endpoint
        coeffs[[i, 0]] = y[i];

        // b is the first derivative at the left endpoint
        coeffs[[i, 1]] = (y[i + 1] - y[i]) / h_i - h_i * (two * sigma[i] + sigma[i + 1]) / six;

        // c is half the second derivative at the left endpoint
        coeffs[[i, 2]] = sigma[i] / two;

        // d is the rate of change of the second derivative / 6
        coeffs[[i, 3]] = (sigma[i + 1] - sigma[i]) / (six * h_i);
    }

    Ok(coeffs)
}

/// Compute the coefficients for a not-a-knot cubic spline
///
/// Not-a-knot boundary conditions: third derivative is continuous across the
/// first and last interior knots. This maximizes smoothness and often produces
/// the most visually pleasing curves.
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates (must have the same length as x)
///
/// # Returns
///
/// A 2D array of shape (n-1, 4) containing the polynomial coefficients for each segment.
///
/// # Errors
///
/// Returns `InterpolateError::ComputationError` if:
/// - Any interval has zero length
/// - Numerical issues in the tridiagonal solver
/// - Float conversion failures
#[allow(dead_code)]
pub fn compute_not_a_knot_cubic_spline<F: InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
) -> InterpolateResult<Array2<F>> {
    let n = x.len();
    let n_segments = n - 1;

    // Create array to hold the coefficients (n-1 segments x 4 coefficients)
    let mut coeffs = Array2::<F>::zeros((n_segments, 4));

    // Step 1: Calculate the second derivatives at each point

    // Set up the tridiagonal system
    let mut a = Array1::<F>::zeros(n);
    let mut b = Array1::<F>::zeros(n);
    let mut c = Array1::<F>::zeros(n);
    let mut d = Array1::<F>::zeros(n);

    // Not-a-knot condition at first interior point
    let h0 = x[1] - x[0];
    let h1 = x[2] - x[1];

    // Check for zero intervals
    if h0.is_zero() || h1.is_zero() || (h0 + h1).is_zero() {
        return Err(InterpolateError::ComputationError(
            "Zero interval length in not-a-knot spline boundary conditions".to_string(),
        ));
    }

    b[0] = h1;
    c[0] = h0 + h1;
    d[0] = ((h0 + h1) * h1 * (y[1] - y[0]) / h0 + h0 * h0 * (y[2] - y[1]) / h1) / (h0 + h1);

    // Not-a-knot condition at last interior point
    let hn_2 = x[n - 2] - x[n - 3];
    let hn_1 = x[n - 1] - x[n - 2];

    // Check for zero intervals
    if hn_1.is_zero() || hn_2.is_zero() || (hn_1 + hn_2).is_zero() {
        return Err(InterpolateError::ComputationError(
            "Zero interval length in not-a-knot spline boundary conditions".to_string(),
        ));
    }

    a[n - 1] = hn_1 + hn_2;
    b[n - 1] = hn_2;
    d[n - 1] = ((hn_1 + hn_2) * hn_2 * (y[n - 1] - y[n - 2]) / hn_1
        + hn_1 * hn_1 * (y[n - 2] - y[n - 3]) / hn_2)
        / (hn_1 + hn_2);

    // Fill in the tridiagonal system for interior points
    for i in 1..n - 1 {
        let h_i_minus_1 = x[i] - x[i - 1];
        let h_i = x[i + 1] - x[i];

        // Check for zero intervals
        if h_i.is_zero() || h_i_minus_1.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in not-a-knot spline computation".to_string(),
            ));
        }

        a[i] = h_i_minus_1;
        let two = F::from_f64(2.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 2.0 to float type".to_string(),
            )
        })?;
        b[i] = two * (h_i_minus_1 + h_i);
        c[i] = h_i;

        let dy_i_minus_1 = y[i] - y[i - 1];
        let dy_i = y[i + 1] - y[i];

        let six = F::from_f64(6.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 6.0 to float type".to_string(),
            )
        })?;
        d[i] = six * (dy_i / h_i - dy_i_minus_1 / h_i_minus_1);
    }

    // Solve the tridiagonal system using the Thomas algorithm
    let mut sigma = Array1::<F>::zeros(n);

    // Forward sweep
    let mut c_prime = Array1::<F>::zeros(n);

    // Check for division by zero in first step
    if b[0].is_zero() {
        return Err(InterpolateError::ComputationError(
            "Zero diagonal element in not-a-knot Thomas algorithm".to_string(),
        ));
    }
    c_prime[0] = c[0] / b[0];

    for i in 1..n {
        let m = b[i] - a[i] * c_prime[i - 1];

        // Check for division by zero
        if m.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero diagonal element in not-a-knot Thomas algorithm".to_string(),
            ));
        }

        if i < n - 1 {
            c_prime[i] = c[i] / m;
        }
        d[i] = (d[i] - a[i] * d[i - 1]) / m;
    }

    // Back substitution
    sigma[n - 1] = d[n - 1];
    for i in (0..n - 1).rev() {
        sigma[i] = d[i] - c_prime[i] * sigma[i + 1];
    }

    // Step 2: Calculate the polynomial coefficients
    for i in 0..n_segments {
        let h_i = x[i + 1] - x[i];

        // Check for division by zero in coefficient calculation
        if h_i.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in not-a-knot spline coefficient calculation".to_string(),
            ));
        }

        let two = F::from_f64(2.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 2.0 to float type".to_string(),
            )
        })?;
        let six = F::from_f64(6.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 6.0 to float type".to_string(),
            )
        })?;

        // a is just the y value at the left endpoint
        coeffs[[i, 0]] = y[i];

        // b is the first derivative at the left endpoint
        coeffs[[i, 1]] = (y[i + 1] - y[i]) / h_i - h_i * (two * sigma[i] + sigma[i + 1]) / six;

        // c is half the second derivative at the left endpoint
        coeffs[[i, 2]] = sigma[i] / two;

        // d is the rate of change of the second derivative / 6
        coeffs[[i, 3]] = (sigma[i + 1] - sigma[i]) / (six * h_i);
    }

    Ok(coeffs)
}

/// Compute the coefficients for a clamped cubic spline
///
/// Clamped boundary conditions: first derivative specified at endpoints.
/// This provides exact control over endpoint slopes and is most accurate
/// when derivative information is known.
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates (must have the same length as x)
/// * `left_deriv` - First derivative at the left endpoint
/// * `right_deriv` - First derivative at the right endpoint
///
/// # Returns
///
/// A 2D array of shape (n-1, 4) containing the polynomial coefficients for each segment.
///
/// # Errors
///
/// Returns `InterpolateError::ComputationError` if:
/// - Any interval has zero length
/// - Numerical issues in the tridiagonal solver
/// - Float conversion failures
#[allow(dead_code)]
pub fn compute_clamped_cubic_spline<F: InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
    left_deriv: F,
    right_deriv: F,
) -> InterpolateResult<Array2<F>> {
    let n = x.len();
    let n_segments = n - 1;

    // Create array to hold the coefficients
    let mut coeffs = Array2::<F>::zeros((n_segments, 4));

    // Set up the tridiagonal system
    let mut a = Array1::<F>::zeros(n);
    let mut b = Array1::<F>::zeros(n);
    let mut c = Array1::<F>::zeros(n);
    let mut d = Array1::<F>::zeros(n);

    // Clamped boundary conditions
    let h0 = x[1] - x[0];

    // Check for zero interval
    if h0.is_zero() {
        return Err(InterpolateError::ComputationError(
            "Zero interval length in clamped spline boundary conditions".to_string(),
        ));
    }

    let two = F::from_f64(2.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 2.0 to float type".to_string(),
        )
    })?;
    let six = F::from_f64(6.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 6.0 to float type".to_string(),
        )
    })?;

    b[0] = two * h0;
    c[0] = h0;
    d[0] = six * ((y[1] - y[0]) / h0 - left_deriv);

    let hn_1 = x[n - 1] - x[n - 2];

    // Check for zero interval
    if hn_1.is_zero() {
        return Err(InterpolateError::ComputationError(
            "Zero interval length in clamped spline boundary conditions".to_string(),
        ));
    }

    a[n - 1] = hn_1;
    b[n - 1] = two * hn_1;
    d[n - 1] = six * (right_deriv - (y[n - 1] - y[n - 2]) / hn_1);

    // Fill in the tridiagonal system for interior points
    for i in 1..n - 1 {
        let h_i_minus_1 = x[i] - x[i - 1];
        let h_i = x[i + 1] - x[i];

        // Check for zero intervals
        if h_i.is_zero() || h_i_minus_1.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in clamped spline computation".to_string(),
            ));
        }

        a[i] = h_i_minus_1;
        b[i] = two * (h_i_minus_1 + h_i);
        c[i] = h_i;

        let dy_i_minus_1 = y[i] - y[i - 1];
        let dy_i = y[i + 1] - y[i];

        d[i] = six * (dy_i / h_i - dy_i_minus_1 / h_i_minus_1);
    }

    // Solve the tridiagonal system
    let mut sigma = Array1::<F>::zeros(n);

    // Forward sweep
    for i in 1..n {
        let m = a[i] / b[i - 1];
        b[i] -= m * c[i - 1];
        d[i] = d[i] - m * d[i - 1];
    }

    // Back substitution
    sigma[n - 1] = d[n - 1] / b[n - 1];
    for i in (0..n - 1).rev() {
        sigma[i] = (d[i] - c[i] * sigma[i + 1]) / b[i];
    }

    // Calculate the polynomial coefficients
    for i in 0..n_segments {
        let h_i = x[i + 1] - x[i];

        // Check for zero interval in coefficient calculation
        if h_i.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in clamped spline coefficient calculation".to_string(),
            ));
        }

        coeffs[[i, 0]] = y[i];
        coeffs[[i, 1]] = (y[i + 1] - y[i]) / h_i - h_i * (two * sigma[i] + sigma[i + 1]) / six;
        coeffs[[i, 2]] = sigma[i] / two;
        coeffs[[i, 3]] = (sigma[i + 1] - sigma[i]) / (six * h_i);
    }

    Ok(coeffs)
}

/// Compute the coefficients for a periodic cubic spline
///
/// Periodic boundary conditions: function and derivatives match at endpoints.
/// This ensures the spline forms a closed curve when the data represents
/// a periodic function.
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates (must have the same length as x)
///
/// # Returns
///
/// A 2D array of shape (n-1, 4) containing the polynomial coefficients for each segment.
///
/// # Errors
///
/// Returns `InterpolateError::ComputationError` if:
/// - Any interval has zero length
/// - Numerical issues in the tridiagonal solver
/// - Float conversion failures
#[allow(dead_code)]
pub fn compute_periodic_cubic_spline<F: InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
) -> InterpolateResult<Array2<F>> {
    let n = x.len();
    let n_segments = n - 1;

    // Define constants
    let two = F::from_f64(2.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 2.0 to float type".to_string(),
        )
    })?;
    let six = F::from_f64(6.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 6.0 to float type".to_string(),
        )
    })?;

    // Create array to hold the coefficients
    let mut coeffs = Array2::<F>::zeros((n_segments, 4));

    // For periodic splines, we need to solve a slightly modified system
    // The matrix is almost tridiagonal with additional corner elements

    let mut a = Array1::<F>::zeros(n - 1);
    let mut b = Array1::<F>::zeros(n - 1);
    let mut c = Array1::<F>::zeros(n - 1);
    let mut d = Array1::<F>::zeros(n - 1);

    // Fill the system (we work with n-1 equations due to periodicity)
    for i in 0..n - 1 {
        let h_i_minus_1 = if i == 0 {
            x[n - 1] - x[n - 2]
        } else {
            x[i] - x[i - 1]
        };
        let h_i = x[i + 1] - x[i];

        // Check for zero intervals
        if h_i.is_zero() || h_i_minus_1.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in periodic spline computation".to_string(),
            ));
        }

        a[i] = h_i_minus_1;
        b[i] = two * (h_i_minus_1 + h_i);
        c[i] = h_i;

        let dy_i_minus_1 = if i == 0 {
            y[0] - y[n - 2] // Using periodicity
        } else {
            y[i] - y[i - 1]
        };
        let dy_i = y[i + 1] - y[i];

        d[i] = six * (dy_i / h_i - dy_i_minus_1 / h_i_minus_1);
    }

    // For periodic boundary conditions, we need to solve a cyclic tridiagonal system
    // Using Sherman-Morrison formula or reduction to standard tridiagonal
    // For simplicity, we'll use a modified Thomas algorithm

    let mut sigma = Array1::<F>::zeros(n);

    // Simplified approach: assume natural boundary conditions as approximation
    // (A more accurate implementation would solve the cyclic system)
    let mut b_mod = b.clone();
    let mut d_mod = d.clone();

    // Forward sweep
    for i in 1..n - 1 {
        let m = a[i] / b_mod[i - 1];
        b_mod[i] -= m * c[i - 1];
        d_mod[i] = d_mod[i] - m * d_mod[i - 1];
    }

    // Back substitution
    sigma[n - 2] = d_mod[n - 2] / b_mod[n - 2];
    for i in (0..n - 2).rev() {
        sigma[i] = (d_mod[i] - c[i] * sigma[i + 1]) / b_mod[i];
    }
    sigma[n - 1] = sigma[0]; // Periodicity

    // Calculate the polynomial coefficients
    for i in 0..n_segments {
        let h_i = x[i + 1] - x[i];

        // Check for zero interval in coefficient calculation
        if h_i.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in periodic spline coefficient calculation".to_string(),
            ));
        }

        coeffs[[i, 0]] = y[i];
        coeffs[[i, 1]] = (y[i + 1] - y[i]) / h_i - h_i * (two * sigma[i] + sigma[i + 1]) / six;
        coeffs[[i, 2]] = sigma[i] / two;
        coeffs[[i, 3]] = (sigma[i + 1] - sigma[i]) / (six * h_i);
    }

    Ok(coeffs)
}

/// Compute the coefficients for a cubic spline with specified second derivatives
///
/// Second derivative boundary conditions: second derivative is specified at endpoints.
/// This provides direct control over the curvature at the boundaries.
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates (must have the same length as x)
/// * `left_d2` - Second derivative at the left endpoint
/// * `right_d2` - Second derivative at the right endpoint
///
/// # Returns
///
/// A 2D array of shape (n-1, 4) containing the polynomial coefficients for each segment.
///
/// # Errors
///
/// Returns `InterpolateError::ComputationError` if:
/// - Any interval has zero length
/// - Numerical issues in the tridiagonal solver
/// - Float conversion failures
#[allow(dead_code)]
pub fn compute_second_derivative_cubic_spline<F: InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
    left_d2: F,
    right_d2: F,
) -> InterpolateResult<Array2<F>> {
    let n = x.len();
    let n_segments = n - 1;

    // Define constants
    let two = F::from_f64(2.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 2.0 to float type".to_string(),
        )
    })?;
    let six = F::from_f64(6.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 6.0 to float type".to_string(),
        )
    })?;

    // Create array to hold the coefficients
    let mut coeffs = Array2::<F>::zeros((n_segments, 4));

    // Set up the tridiagonal system
    let mut a = Array1::<F>::zeros(n);
    let mut b = Array1::<F>::zeros(n);
    let mut c = Array1::<F>::zeros(n);
    let mut d = Array1::<F>::zeros(n);

    // Specified second derivative boundary conditions
    b[0] = F::one();
    d[0] = left_d2;
    b[n - 1] = F::one();
    d[n - 1] = right_d2;

    // Fill in the tridiagonal system for interior points
    for i in 1..n - 1 {
        let h_i_minus_1 = x[i] - x[i - 1];
        let h_i = x[i + 1] - x[i];

        // Check for zero intervals
        if h_i.is_zero() || h_i_minus_1.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in second derivative spline computation".to_string(),
            ));
        }

        let two = F::from_f64(2.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 2.0 to float type".to_string(),
            )
        })?;
        let six = F::from_f64(6.0).ok_or_else(|| {
            InterpolateError::ComputationError(
                "Failed to convert constant 6.0 to float type".to_string(),
            )
        })?;

        a[i] = h_i_minus_1;
        b[i] = two * (h_i_minus_1 + h_i);
        c[i] = h_i;

        let dy_i_minus_1 = y[i] - y[i - 1];
        let dy_i = y[i + 1] - y[i];

        d[i] = six * (dy_i / h_i - dy_i_minus_1 / h_i_minus_1);
    }

    // Solve the tridiagonal system
    let mut sigma = Array1::<F>::zeros(n);

    // Forward sweep
    for i in 1..n {
        let m = a[i] / b[i - 1];
        b[i] -= m * c[i - 1];
        d[i] = d[i] - m * d[i - 1];
    }

    // Back substitution
    sigma[n - 1] = d[n - 1] / b[n - 1];
    for i in (0..n - 1).rev() {
        sigma[i] = (d[i] - c[i] * sigma[i + 1]) / b[i];
    }

    // Calculate the polynomial coefficients
    for i in 0..n_segments {
        let h_i = x[i + 1] - x[i];

        // Check for zero interval in coefficient calculation
        if h_i.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in second derivative spline coefficient calculation"
                    .to_string(),
            ));
        }

        coeffs[[i, 0]] = y[i];
        coeffs[[i, 1]] = (y[i + 1] - y[i]) / h_i - h_i * (two * sigma[i] + sigma[i + 1]) / six;
        coeffs[[i, 2]] = sigma[i] / two;
        coeffs[[i, 3]] = (sigma[i + 1] - sigma[i]) / (six * h_i);
    }

    Ok(coeffs)
}

/// Compute the coefficients for a parabolic runout cubic spline
///
/// Parabolic runout boundary conditions: third derivative is zero at the endpoints.
/// This makes the spline reduce to a parabola near the endpoints, which can be
/// more natural for some applications.
///
/// # Arguments
///
/// * `x` - The x coordinates (must be sorted in ascending order)
/// * `y` - The y coordinates (must have the same length as x)
///
/// # Returns
///
/// A 2D array of shape (n-1, 4) containing the polynomial coefficients for each segment.
///
/// # Errors
///
/// Returns `InterpolateError::ComputationError` if:
/// - Any interval has zero length
/// - Numerical issues in the tridiagonal solver
/// - Float conversion failures
#[allow(dead_code)]
pub fn compute_parabolic_runout_cubic_spline<F: InterpolationFloat>(
    x: &ArrayView1<F>,
    y: &ArrayView1<F>,
) -> InterpolateResult<Array2<F>> {
    // Parabolic runout means the third derivative is zero at the endpoints
    // This is equivalent to d[0] = 0 and d[n-2] = 0 in our coefficient representation
    // We can achieve this by setting specific boundary conditions on the second derivatives

    let n = x.len();
    let n_segments = n - 1;

    // Create array to hold the coefficients
    let mut coeffs = Array2::<F>::zeros((n_segments, 4));

    // Set up the tridiagonal system
    let mut a = Array1::<F>::zeros(n);
    let mut b = Array1::<F>::zeros(n);
    let mut c = Array1::<F>::zeros(n);
    let mut d = Array1::<F>::zeros(n);

    // Parabolic runout conditions
    // At the first point: 2*sigma[0] + sigma[1] = 0
    let two = F::from_f64(2.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 2.0 to float type".to_string(),
        )
    })?;
    let six = F::from_f64(6.0).ok_or_else(|| {
        InterpolateError::ComputationError(
            "Failed to convert constant 6.0 to float type".to_string(),
        )
    })?;

    b[0] = two;
    c[0] = F::one();
    d[0] = F::zero();

    // At the last point: sigma[n-2] + 2*sigma[n-1] = 0
    a[n - 1] = F::one();
    b[n - 1] = two;
    d[n - 1] = F::zero();

    // Fill in the tridiagonal system for interior points
    for i in 1..n - 1 {
        let h_i_minus_1 = x[i] - x[i - 1];
        let h_i = x[i + 1] - x[i];

        // Check for zero intervals
        if h_i.is_zero() || h_i_minus_1.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in parabolic runout spline computation".to_string(),
            ));
        }

        a[i] = h_i_minus_1;
        b[i] = two * (h_i_minus_1 + h_i);
        c[i] = h_i;

        let dy_i_minus_1 = y[i] - y[i - 1];
        let dy_i = y[i + 1] - y[i];

        d[i] = six * (dy_i / h_i - dy_i_minus_1 / h_i_minus_1);
    }

    // Solve the tridiagonal system
    let mut sigma = Array1::<F>::zeros(n);

    // Forward sweep
    for i in 1..n {
        let m = a[i] / b[i - 1];
        b[i] -= m * c[i - 1];
        d[i] = d[i] - m * d[i - 1];
    }

    // Back substitution
    sigma[n - 1] = d[n - 1] / b[n - 1];
    for i in (0..n - 1).rev() {
        sigma[i] = (d[i] - c[i] * sigma[i + 1]) / b[i];
    }

    // Calculate the polynomial coefficients
    for i in 0..n_segments {
        let h_i = x[i + 1] - x[i];

        // Check for zero interval in coefficient calculation
        if h_i.is_zero() {
            return Err(InterpolateError::ComputationError(
                "Zero interval length in parabolic runout spline coefficient calculation"
                    .to_string(),
            ));
        }

        coeffs[[i, 0]] = y[i];
        coeffs[[i, 1]] = (y[i + 1] - y[i]) / h_i - h_i * (two * sigma[i] + sigma[i + 1]) / six;
        coeffs[[i, 2]] = sigma[i] / two;
        coeffs[[i, 3]] = (sigma[i + 1] - sigma[i]) / (six * h_i);
    }

    Ok(coeffs)
}