neopdf 0.2.0-alpha3

A modern, fast, and reliable PDF interpolation library
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
//! This module defines various interpolation strategies used within the `neopdf` library.
//!
//! It provides implementations for 1D, 2D, and 3D interpolation, including:
//! - `BilinearInterpolation`: Standard bilinear interpolation for 2D data.
//! - `LogBilinearInterpolation`: Bilinear interpolation performed in logarithmic space for both
//!   coordinates, suitable for data that exhibits linear behavior in log-log plots.
//! - `LogBicubicInterpolation`: Bicubic interpolation with logarithmic coordinate scaling,
//!   providing C1 continuity and higher accuracy for 2D data.
//! - `LogTricubicInterpolation`: Tricubic interpolation with logarithmic coordinate scaling,
//!   extending bicubic interpolation to 3D data with C1 continuity.
//! - `AlphaSCubicInterpolation`: A specialized 1D cubic interpolation strategy for alpha_s values,
//!   incorporating specific extrapolation rules as defined in LHAPDF.
//!
//! All interpolation strategies are designed to work with `ninterp`'s data structures and traits,
//! ensuring compatibility and extensibility.

use ndarray::{Data, RawDataClone};
use ninterp::data::{InterpData1D, InterpData2D, InterpData3D};
use ninterp::error::{InterpolateError, ValidateError};
use ninterp::strategy::traits::{Strategy1D, Strategy2D, Strategy3D};
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;

use super::utils;

/// Implements bilinear interpolation for 2D data.
///
/// This strategy performs linear interpolation sequentially along two dimensions.
/// It is suitable for smooth, continuous 2D datasets where a simple linear
/// approximation between grid points is sufficient.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BilinearInterpolation;

impl BilinearInterpolation {
    /// Performs linear interpolation between two points.
    ///
    /// Given two points `(x1, y1)` and `(x2, y2)`, this function calculates the
    /// y-value corresponding to a given `x` using linear interpolation.
    ///
    /// # Arguments
    ///
    /// * `x1` - The x-coordinate of the first point.
    /// * `x2` - The x-coordinate of the second point.
    /// * `y1` - The y-coordinate of the first point.
    /// * `y2` - The y-coordinate of the second point.
    /// * `x` - The x-coordinate at which to interpolate.
    ///
    /// # Returns
    ///
    /// The interpolated y-value.
    fn linear_interpolate(x1: f64, x2: f64, y1: f64, y2: f64, x: f64) -> f64 {
        if x1 == x2 {
            return y1;
        }
        y1 + (y2 - y1) * (x - x1) / (x2 - x1)
    }
}

impl<D> Strategy2D<D> for BilinearInterpolation
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    /// Performs bilinear interpolation at a given point.
    ///
    /// # Arguments
    ///
    /// * `data` - The interpolation data containing grid coordinates and values.
    /// * `point` - A 2-element array `[x, y]` representing the coordinates to interpolate at.
    ///
    /// # Returns
    ///
    /// The interpolated value as a `Result`.
    fn interpolate(
        &self,
        data: &InterpData2D<D>,
        point: &[f64; 2],
    ) -> Result<f64, InterpolateError> {
        let [x, y] = *point;

        // Get the coordinate arrays and data values
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();
        let values = &data.values;

        // Find the indices for interpolation
        let x_idx = utils::find_interval_index(x_coords, x)?;
        let y_idx = utils::find_interval_index(y_coords, y)?;

        // Get the four corner points
        let x1 = x_coords[x_idx];
        let x2 = x_coords[x_idx + 1];
        let y1 = y_coords[y_idx];
        let y2 = y_coords[y_idx + 1];

        // Get the four corner values
        let q11 = values[[x_idx, y_idx]]; // f(x1, y1)
        let q12 = values[[x_idx, y_idx + 1]]; // f(x1, y2)
        let q21 = values[[x_idx + 1, y_idx]]; // f(x2, y1)
        let q22 = values[[x_idx + 1, y_idx + 1]]; // f(x2, y2)

        // Perform bilinear interpolation
        let r1 = Self::linear_interpolate(x1, x2, q11, q21, x);
        let r2 = Self::linear_interpolate(x1, x2, q12, q22, x);

        // Then interpolate in y-direction
        let result = Self::linear_interpolate(y1, y2, r1, r2, y);

        Ok(result)
    }

    /// Indicates that this strategy does not allow extrapolation.
    fn allow_extrapolate(&self) -> bool {
        true
    }
}

/// Performs bilinear interpolation in log space.
///
/// This strategy transforms the input coordinates to their natural logarithms
/// before performing bilinear interpolation, which is suitable for data
/// that is linear in log-log space. It is particularly useful for physical
/// quantities that span several orders of magnitude, such as momentum transfer
/// squared (Q²) or Bjorken x.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LogBilinearInterpolation;

impl<D> Strategy2D<D> for LogBilinearInterpolation
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    /// Initializes the strategy, performing validation checks.
    ///
    /// # Arguments
    ///
    /// * `data` - The interpolation data to validate.
    fn init(&mut self, _data: &InterpData2D<D>) -> Result<(), ValidateError> {
        Ok(())
    }

    /// Performs log-bilinear interpolation at a given point.
    ///
    /// The input `point` coordinates are first transformed to log space,
    /// then bilinear interpolation is applied.
    ///
    /// # Arguments
    ///
    /// * `data` - The interpolation data containing grid coordinates and values.
    /// * `point` - A 2-element array `[x, y]` representing the coordinates to interpolate at.
    ///
    /// # Returns
    ///
    /// The interpolated value as a `Result`.
    fn interpolate(
        &self,
        data: &InterpData2D<D>,
        point: &[f64; 2],
    ) -> Result<f64, InterpolateError> {
        let [x, y] = *point;

        // Get the coordinate arrays and data values
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();
        let values = &data.values;

        // Find the indices for interpolation
        let x_idx = utils::find_interval_index(x_coords, x)?;
        let y_idx = utils::find_interval_index(y_coords, y)?;

        // Get the four corner points
        let x1 = x_coords[x_idx];
        let x2 = x_coords[x_idx + 1];
        let y1 = y_coords[y_idx];
        let y2 = y_coords[y_idx + 1];

        // Get the four corner values
        let q11 = values[[x_idx, y_idx]]; // f(x1, y1)
        let q12 = values[[x_idx, y_idx + 1]]; // f(x1, y2)
        let q21 = values[[x_idx + 1, y_idx]]; // f(x2, y1)
        let q22 = values[[x_idx + 1, y_idx + 1]]; // f(x2, y2)

        // Perform bilinear interpolation
        let r1 = BilinearInterpolation::linear_interpolate(x1, x2, q11, q21, x);
        let r2 = BilinearInterpolation::linear_interpolate(x1, x2, q12, q22, x);

        // Then interpolate in y-direction
        let result = BilinearInterpolation::linear_interpolate(y1, y2, r1, r2, y);

        Ok(result)
    }

    /// Indicates that this strategy does not allow extrapolation.
    fn allow_extrapolate(&self) -> bool {
        true
    }
}

/// LogBicubic interpolation strategy for PDF-like data.
///
/// This strategy implements bicubic interpolation with logarithmic coordinate scaling.
/// It is designed for interpolating Parton Distribution Functions (PDFs) where:
/// - x-coordinates (e.g., Bjorken x) are logarithmically spaced.
/// - y-coordinates (e.g., Q² values) are logarithmically spaced.
/// - z-values (PDF values) are interpolated using bicubic splines.
///
/// Bicubic interpolation uses a 4x4 grid of points around the interpolation point
/// and provides C1 continuity (continuous first derivatives), resulting in a
/// smoother and more accurate interpolation compared to bilinear methods.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct LogBicubicInterpolation {
    coeffs: Vec<f64>,
}

impl LogBicubicInterpolation {
    /// Find the interval for bicubic interpolation.
    ///
    /// This function determines the appropriate interval index `i` within a set of
    /// coordinates `coords` such that `coords[i] <= x < coords[i+1]`. For bicubic
    /// interpolation, this index `i` is used to select the 4x4 grid of points
    /// `[i-1, i, i+1, i+2]` that are relevant for the interpolation.
    ///
    /// # Arguments
    ///
    /// * `coords` - A slice of `f64` representing the sorted coordinate values.
    /// * `x` - The `f64` value for which to find the interval.
    ///
    /// # Returns
    ///
    /// A `Result` containing the `usize` index of the lower bound of the interval
    /// if successful, or an `InterpolateError` if `x` is out of bounds.
    fn find_bicubic_interval(coords: &[f64], x: f64) -> Result<usize, InterpolateError> {
        // Find the interval [i, i+1] such that coords[i] <= x < coords[i+1]
        let i = utils::find_interval_index(coords, x)?;
        Ok(i)
    }

    /// Cubic interpolation using a passed array of coefficients (a*x^3 + b*x^2 + c*x + d)
    pub fn hermite_cubic_interpolate_from_coeffs(t: f64, coeffs: &[f64; 4]) -> f64 {
        let x = t;
        let x2 = x * x;
        let x3 = x2 * x;
        coeffs[0] * x3 + coeffs[1] * x2 + coeffs[2] * x + coeffs[3]
    }

    /// Calculates the derivative with respect to x at a given knot.
    /// This mirrors the _ddx function in LHAPDF's C++ implementation.
    pub fn calculate_ddx<D>(data: &InterpData2D<D>, ix: usize, iq2: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let nxknots = data.grid[0].len();
        let x_coords = data.grid[0].as_slice().unwrap();
        let values = &data.values;

        let del1 = match ix {
            0 => 0.0,
            i => x_coords[i] - x_coords[i - 1],
        };

        let del2 = match x_coords.get(ix + 1) {
            Some(&next) => next - x_coords[ix],
            None => 0.0,
        };

        if ix != 0 && ix != nxknots - 1 {
            let lddx = (values[[ix, iq2]] - values[[ix - 1, iq2]]) / del1;
            let rddx = (values[[ix + 1, iq2]] - values[[ix, iq2]]) / del2;
            (lddx + rddx) / 2.0
        } else if ix == 0 {
            (values[[ix + 1, iq2]] - values[[ix, iq2]]) / del2
        } else if ix == nxknots - 1 {
            (values[[ix, iq2]] - values[[ix - 1, iq2]]) / del1
        } else {
            panic!("Should not reach here: Invalid index for derivative calculation.");
        }
    }

    /// Computes the polynomial coefficients for bicubic interpolation, mirroring LHAPDF's C++ implementation.
    fn compute_polynomial_coefficients<D>(data: &InterpData2D<D>) -> Vec<f64>
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let nxknots = data.grid[0].len();
        let nq2knots = data.grid[1].len();
        let values = &data.values;

        // The shape of the coefficients array: (nxknots-1) * nq2knots * 4 (for a,b,c,d)
        let mut coeffs: Vec<f64> = vec![0.0; (nxknots - 1) * nq2knots * 4];

        for ix in 0..nxknots - 1 {
            for iq2 in 0..nq2knots {
                let dx =
                    data.grid[0].as_slice().unwrap()[ix + 1] - data.grid[0].as_slice().unwrap()[ix];

                let vl = values[[ix, iq2]];
                let vh = values[[ix + 1, iq2]];
                let vdl = Self::calculate_ddx(data, ix, iq2) * dx;
                let vdh = Self::calculate_ddx(data, ix + 1, iq2) * dx;

                // polynomial coefficients
                let a = vdh + vdl - 2.0 * vh + 2.0 * vl;
                let b = 3.0 * vh - 3.0 * vl - 2.0 * vdl - vdh;
                let c = vdl;
                let d = vl;

                let base_idx = (ix * nq2knots + iq2) * 4;
                coeffs[base_idx] = a;
                coeffs[base_idx + 1] = b;
                coeffs[base_idx + 2] = c;
                coeffs[base_idx + 3] = d;
            }
        }
        coeffs
    }

    /// Performs bicubic interpolation using pre-computed coefficients.
    fn interpolate_with_coeffs<D>(
        &self,
        data: &InterpData2D<D>,
        ix: usize,
        iq2: usize,
        u: f64,
        v: f64,
    ) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let nq2knots = data.grid[1].len();

        // Get the coefficients for the current cell (x-interpolation)
        let base_idx_vl = (ix * nq2knots + iq2) * 4;
        let coeffs_vl: [f64; 4] = self.coeffs[base_idx_vl..base_idx_vl + 4]
            .try_into()
            .unwrap();
        let vl = Self::hermite_cubic_interpolate_from_coeffs(u, &coeffs_vl);

        let base_idx_vh = (ix * nq2knots + iq2 + 1) * 4;
        let coeffs_vh: [f64; 4] = self.coeffs[base_idx_vh..base_idx_vh + 4]
            .try_into()
            .unwrap();
        let vh = Self::hermite_cubic_interpolate_from_coeffs(u, &coeffs_vh);

        // Derivatives in Q2 (y-interpolation)
        let q2_grid: &[f64] = data.grid[1].as_slice().unwrap();

        let dq_1 = q2_grid[iq2 + 1] - q2_grid[iq2];

        let vdl: f64;
        let vdh: f64;

        if iq2 == 0 {
            // Forward difference for lower q
            vdl = vh - vl;
            // Central difference for higher q
            let vhh_base_idx = (ix * nq2knots + iq2 + 2) * 4;
            let coeffs_vhh: [f64; 4] = self.coeffs[vhh_base_idx..vhh_base_idx + 4]
                .try_into()
                .unwrap();
            let vhh = Self::hermite_cubic_interpolate_from_coeffs(u, &coeffs_vhh);
            let dq_2 = 1.0 / (q2_grid[iq2 + 2] - q2_grid[iq2 + 1]);
            vdh = (vdl + (vhh - vh) * dq_1 * dq_2) * 0.5;
        } else if iq2 == nq2knots - 2 {
            // Backward difference for higher q
            vdh = vh - vl;
            // Central difference for lower q
            let vll_base_idx = (ix * nq2knots + iq2 - 1) * 4;
            let coeffs_vll: [f64; 4] = self.coeffs[vll_base_idx..vll_base_idx + 4]
                .try_into()
                .unwrap();
            let vll = Self::hermite_cubic_interpolate_from_coeffs(u, &coeffs_vll);
            let dq_0 = 1.0 / (q2_grid[iq2] - q2_grid[iq2 - 1]);
            vdl = (vdh + (vl - vll) * dq_1 * dq_0) * 0.5;
        } else {
            // Central difference for both q
            let vll_base_idx = (ix * nq2knots + iq2 - 1) * 4;
            let coeffs_vll: [f64; 4] = self.coeffs[vll_base_idx..vll_base_idx + 4]
                .try_into()
                .unwrap();
            let vll = Self::hermite_cubic_interpolate_from_coeffs(u, &coeffs_vll);
            let dq_0 = 1.0 / (q2_grid[iq2] - q2_grid[iq2 - 1]);

            let vhh_base_idx = (ix * nq2knots + iq2 + 2) * 4;
            let coeffs_vhh: [f64; 4] = self.coeffs[vhh_base_idx..vhh_base_idx + 4]
                .try_into()
                .unwrap();
            let vhh = Self::hermite_cubic_interpolate_from_coeffs(u, &coeffs_vhh);
            let dq_2 = 1.0 / (q2_grid[iq2 + 2] - q2_grid[iq2 + 1]);

            vdl = ((vh - vl) + (vl - vll) * dq_1 * dq_0) * 0.5;
            vdh = ((vh - vl) + (vhh - vh) * dq_1 * dq_2) * 0.5;
        }

        utils::hermite_cubic_interpolate(v, vl, vdl, vh, vdh)
    }
}

impl<D> Strategy2D<D> for LogBicubicInterpolation
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    fn init(&mut self, data: &InterpData2D<D>) -> Result<(), ValidateError> {
        // Get the coordinate arrays and data values
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();

        // Check that we have at least 4x4 grid for bicubic interpolation
        if x_coords.len() < 4 || y_coords.len() < 4 {
            return Err(ValidateError::Other(
                "Need at least 4x4 grid for bicubic interpolation".to_string(),
            ));
        }

        self.coeffs = Self::compute_polynomial_coefficients(data);
        Ok(())
    }

    fn interpolate(
        &self,
        data: &InterpData2D<D>,
        point: &[f64; 2],
    ) -> Result<f64, InterpolateError> {
        let [x, y] = *point;

        // Get the coordinate arrays and data values
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();

        // Find the grid cell containing the point
        let i = Self::find_bicubic_interval(x_coords, x)?;
        let j = Self::find_bicubic_interval(y_coords, y)?;

        // Normalize coordinates to [0,1] within the central cell
        let dx = x_coords[i + 1] - x_coords[i];
        let dy = y_coords[j + 1] - y_coords[j];

        if dx == 0.0 || dy == 0.0 {
            return Err(InterpolateError::Other("Grid spacing is zero".to_string()));
        }

        let u = (x - x_coords[i]) / dx;
        let v = (y - y_coords[j]) / dy;

        // Perform bicubic interpolation using pre-computed coefficients
        let result = self.interpolate_with_coeffs(data, i, j, u, v);

        Ok(result)
    }

    fn allow_extrapolate(&self) -> bool {
        true
    }
}

/// LogTricubic interpolation strategy for PDF-like data
///
/// This strategy implements tricubic interpolation with logarithmic coordinate scaling:
/// - x-coordinates are logarithmically spaced (e.g., 1e-9 to 1)
/// - y-coordinates are logarithmically spaced (e.g., Q² values)
/// - z-coordinates are logarithmically spaced (e.g., Mass Atomic A, AlphaS)
/// - w-values (PDF values) are interpolated using tricubic splines
///
/// Tricubic interpolation uses a 4x4x4 grid of points around the interpolation point
/// and provides C1 continuity (continuous first derivatives).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct LogTricubicInterpolation;

impl LogTricubicInterpolation {
    /// Find the interval for tricubic interpolation
    /// Returns the index i such that we can use points [i-1, i, i+1, i+2] for interpolation
    fn find_tricubic_interval(coords: &[f64], x: f64) -> Result<usize, InterpolateError> {
        // Find the interval [i, i+1] such that coords[i] <= x < coords[i+1]
        let i = utils::find_interval_index(coords, x)?;
        Ok(i)
    }

    /// Cubic interpolation using a passed array of coefficients (a*x^3 + b*x^2 + c*x + d)
    pub fn hermite_cubic_interpolate_from_coeffs(t: f64, coeffs: &[f64; 4]) -> f64 {
        let x = t;
        let x2 = x * x;
        let x3 = x2 * x;
        coeffs[0] * x3 + coeffs[1] * x2 + coeffs[2] * x + coeffs[3]
    }

    /// Calculates the derivative with respect to x at a given knot.
    pub fn calculate_ddx<D>(data: &InterpData3D<D>, ix: usize, iq2: usize, iz: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let nxknots = data.grid[0].len();
        let x_coords = data.grid[0].as_slice().unwrap();
        let values = &data.values;

        let del1 = match ix {
            0 => 0.0,
            i => x_coords[i] - x_coords[i - 1],
        };

        let del2 = match x_coords.get(ix + 1) {
            Some(&next) => next - x_coords[ix],
            None => 0.0,
        };

        if ix != 0 && ix != nxknots - 1 {
            let lddx = (values[[ix, iq2, iz]] - values[[ix - 1, iq2, iz]]) / del1;
            let rddx = (values[[ix + 1, iq2, iz]] - values[[ix, iq2, iz]]) / del2;
            (lddx + rddx) / 2.0
        } else if ix == 0 {
            (values[[ix + 1, iq2, iz]] - values[[ix, iq2, iz]]) / del2
        } else if ix == nxknots - 1 {
            (values[[ix, iq2, iz]] - values[[ix - 1, iq2, iz]]) / del1
        } else {
            panic!("Should not reach here: Invalid index for derivative calculation.");
        }
    }

    /// Calculates the derivative with respect to y at a given knot.
    pub fn calculate_ddy<D>(data: &InterpData3D<D>, ix: usize, iq2: usize, iz: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let nq2knots = data.grid[1].len();
        let q2_coords = data.grid[1].as_slice().unwrap();
        let values = &data.values;

        let del1 = match iq2 {
            0 => 0.0,
            i => q2_coords[i] - q2_coords[i - 1],
        };

        let del2 = match q2_coords.get(iq2 + 1) {
            Some(&next) => next - q2_coords[iq2],
            None => 0.0,
        };

        if iq2 != 0 && iq2 != nq2knots - 1 {
            let lddq = (values[[ix, iq2, iz]] - values[[ix, iq2 - 1, iz]]) / del1;
            let rddq = (values[[ix, iq2 + 1, iz]] - values[[ix, iq2, iz]]) / del2;
            (lddq + rddq) / 2.0
        } else if iq2 == 0 {
            (values[[ix, iq2 + 1, iz]] - values[[ix, iq2, iz]]) / del2
        } else if iq2 == nq2knots - 1 {
            (values[[ix, iq2, iz]] - values[[ix, iq2 - 1, iz]]) / del1
        } else {
            panic!("Should not reach here: Invalid index for derivative calculation.");
        }
    }

    /// Calculates the derivative with respect to z at a given knot.
    pub fn calculate_ddz<D>(data: &InterpData3D<D>, ix: usize, iq2: usize, iz: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let nmu2knots = data.grid[2].len();
        let mu2_coords = data.grid[2].as_slice().unwrap();
        let values = &data.values;

        let del1 = match iz {
            0 => 0.0,
            i => mu2_coords[i] - mu2_coords[i - 1],
        };

        let del2 = match mu2_coords.get(iz + 1) {
            Some(&next) => next - mu2_coords[iz],
            None => 0.0,
        };

        if iz != 0 && iz != nmu2knots - 1 {
            let lddmu = (values[[ix, iq2, iz]] - values[[ix, iq2, iz - 1]]) / del1;
            let rddmu = (values[[ix, iq2, iz + 1]] - values[[ix, iq2, iz]]) / del2;
            (lddmu + rddmu) / 2.0
        } else if iz == 0 {
            (values[[ix, iq2, iz + 1]] - values[[ix, iq2, iz]]) / del2
        } else if iz == nmu2knots - 1 {
            (values[[ix, iq2, iz]] - values[[ix, iq2, iz - 1]]) / del1
        } else {
            panic!("Should not reach here: Invalid index for derivative calculation.");
        }
    }

    fn hermite_tricubic_interpolate<D>(
        &self,
        data: &InterpData3D<D>,
        indices: (usize, usize, usize),
        coords: (f64, f64, f64),
        derivatives: (f64, f64, f64),
    ) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let (ix, iq2, iz) = indices;
        let (u, v, w) = coords;
        let (dx, dy, dz) = derivatives;

        // Helper closures for cleaner indexing
        let get = |dx, dy, dz| data.values[[ix + dx, iq2 + dy, iz + dz]];
        let ddx = |dx, dy, dz| Self::calculate_ddx(data, ix + dx, iq2 + dy, iz + dz);
        let ddy = |dx, dy, dz| Self::calculate_ddy(data, ix + dx, iq2 + dy, iz + dz);
        let ddz = |dx, dy, dz| Self::calculate_ddz(data, ix + dx, iq2 + dy, iz + dz);

        // Step 1: X-interpolation for each (y, z) pair
        let interp_y: [[f64; 2]; 4] = [0, 1]
            .iter()
            .flat_map(|&y_offset| {
                [0, 1].iter().map(move |&z_offset| {
                    let (f0, f1) = (get(0, y_offset, z_offset), get(1, y_offset, z_offset));
                    let (d0, d1) = (
                        ddx(0, y_offset, z_offset) * dx,
                        ddx(1, y_offset, z_offset) * dx,
                    );
                    let interp_val = Self::cubic_interpolate(u, f0, d0, f1, d1);

                    let (df0, df1) = (
                        ddy(0, y_offset, z_offset) * dy,
                        ddy(1, y_offset, z_offset) * dy,
                    );
                    let interp_deriv = (1.0 - u) * df0 + u * df1;

                    [interp_val, interp_deriv]
                })
            })
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        // Step 2: Y-interpolation for each z
        let interp_z: [[f64; 2]; 2] = [0, 1]
            .iter()
            .enumerate()
            .map(|(iz_, &z_offset)| {
                let (f0, f1) = (interp_y[iz_][0], interp_y[2 + iz_][0]);
                let (d0, d1) = (interp_y[iz_][1], interp_y[2 + iz_][1]);
                let interp_val = Self::cubic_interpolate(v, f0, d0, f1, d1);

                let calc_z_deriv = |y_offset| {
                    let (df0, df1) = (
                        ddz(0, y_offset, z_offset) * dz,
                        ddz(1, y_offset, z_offset) * dz,
                    );
                    (1.0 - u) * df0 + u * df1
                };

                let interp_deriv = (1.0 - v) * calc_z_deriv(0) + v * calc_z_deriv(1);
                [interp_val, interp_deriv]
            })
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        // Step 3: Z-interpolation
        let (f0, f1) = (interp_z[0][0], interp_z[1][0]);
        let (d0, d1) = (interp_z[0][1], interp_z[1][1]);
        Self::cubic_interpolate(w, f0, d0, f1, d1)
    }

    /// Hermite cubic interpolation with derivatives
    fn cubic_interpolate(t: f64, f0: f64, f0_prime: f64, f1: f64, f1_prime: f64) -> f64 {
        let t2 = t * t;
        let t3 = t2 * t;

        // Hermite basis functions
        let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
        let h10 = t3 - 2.0 * t2 + t;
        let h01 = -2.0 * t3 + 3.0 * t2;
        let h11 = t3 - t2;

        h00 * f0 + h10 * f0_prime + h01 * f1 + h11 * f1_prime
    }
}

impl<D> Strategy3D<D> for LogTricubicInterpolation
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    fn init(&mut self, data: &InterpData3D<D>) -> Result<(), ValidateError> {
        // Get the coordinate arrays
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();
        let z_coords = data.grid[2].as_slice().unwrap();

        // Check that we have at least 4x4x4 grid for tricubic interpolation
        if x_coords.len() < 4 || y_coords.len() < 4 || z_coords.len() < 4 {
            return Err(ValidateError::Other(
                "Need at least 4x4x4 grid for tricubic interpolation".to_string(),
            ));
        }

        // Use the Hermite approach instead of coefficient precomputation
        // This is more straightforward and avoids the complex 64x64 matrix
        Ok(())
    }

    fn interpolate(
        &self,
        data: &InterpData3D<D>,
        point: &[f64; 3],
    ) -> Result<f64, InterpolateError> {
        let [x, y, z] = *point;

        // Get the coordinate arrays
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();
        let z_coords = data.grid[2].as_slice().unwrap();

        // Find the grid cell containing the point
        let i = Self::find_tricubic_interval(x_coords, x)?;
        let j = Self::find_tricubic_interval(y_coords, y)?;
        let k = Self::find_tricubic_interval(z_coords, z)?;

        // Normalize coordinates to [0,1] within the cell
        let dx = x_coords[i + 1] - x_coords[i];
        let dy = y_coords[j + 1] - y_coords[j];
        let dz = z_coords[k + 1] - z_coords[k];

        if dx == 0.0 || dy == 0.0 || dz == 0.0 {
            return Err(InterpolateError::Other("Grid spacing is zero".to_string()));
        }

        let u = (x - x_coords[i]) / dx;
        let v = (y - y_coords[j]) / dy;
        let w = (z - z_coords[k]) / dz;

        // Use the corrected Hermite tricubic interpolation
        let result = self.hermite_tricubic_interpolate(data, (i, j, k), (u, v, w), (dx, dy, dz));

        Ok(result)
    }

    fn allow_extrapolate(&self) -> bool {
        true
    }
}

/// Implements cubic interpolation for alpha_s values in log-Q2 space.
///
/// This strategy handles the specific extrapolation and interpolation rules
/// for alpha_s as defined in LHAPDF.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct AlphaSCubicInterpolation;

impl AlphaSCubicInterpolation {
    /// Get the index of the closest Q2 knot row <= q2
    ///
    /// If the value is >= q2_max, return (i_max-1).
    fn ilogq2below<D>(data: &InterpData1D<D>, logq2: f64) -> usize
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let logq2s = data.grid[0].as_slice().unwrap();
        // Test that Q2 is in the grid range
        if logq2 < *logq2s.first().unwrap() {
            panic!(
                "Q2 value {} is lower than lowest-Q2 grid point at {}",
                logq2.exp(),
                logq2s.first().unwrap().exp()
            );
        }
        if logq2 > *logq2s.last().unwrap() {
            panic!(
                "Q2 value {} is higher than highest-Q2 grid point at {}",
                logq2.exp(),
                logq2s.last().unwrap().exp()
            );
        }

        // Find the closest knot below the requested value
        let idx = logq2s.partition_point(|&x| x < logq2);

        if idx == logq2s.len() {
            idx - 1
        } else if (logq2s[idx] - logq2).abs() < 1e-9 {
            if idx == logq2s.len() - 1 && logq2s.len() >= 2 {
                idx - 1
            } else {
                idx
            }
        } else {
            idx - 1
        }
    }

    /// Forward derivative w.r.t. logQ2
    fn ddlogq_forward<D>(data: &InterpData1D<D>, i: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let logq2s = data.grid[0].as_slice().unwrap();
        let alphas = data.values.as_slice().unwrap();
        (alphas[i + 1] - alphas[i]) / (logq2s[i + 1] - logq2s[i])
    }

    /// Backward derivative w.r.t. logQ2
    fn ddlogq_backward<D>(data: &InterpData1D<D>, i: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        let logq2s = data.grid[0].as_slice().unwrap();
        let alphas = data.values.as_slice().unwrap();
        (alphas[i] - alphas[i - 1]) / (logq2s[i] - logq2s[i - 1])
    }

    /// Central (avg of forward and backward) derivative w.r.t. logQ2
    fn ddlogq_central<D>(data: &InterpData1D<D>, i: usize) -> f64
    where
        D: Data<Elem = f64> + RawDataClone + Clone,
    {
        0.5 * (Self::ddlogq_forward(data, i) + Self::ddlogq_backward(data, i))
    }
}

impl<D> Strategy1D<D> for AlphaSCubicInterpolation
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    fn interpolate(
        &self,
        data: &InterpData1D<D>,
        point: &[f64; 1],
    ) -> Result<f64, InterpolateError> {
        let logq2 = point[0];
        let logq2s = data.grid[0].as_slice().unwrap();
        let alphas = data.values.as_slice().unwrap();

        if logq2 < *logq2s.first().unwrap() {
            let mut next_point = 1;
            while logq2s[0] == logq2s[next_point] {
                next_point += 1;
            }
            let dlogq2 = logq2s[next_point] - logq2s[0];
            let dlogas = (alphas[next_point] / alphas[0]).ln();
            let loggrad = dlogas / dlogq2;
            return Ok(alphas[0] * (loggrad * (logq2 - logq2s[0])).exp());
        }

        if logq2 > *logq2s.last().unwrap() {
            return Ok(*alphas.last().unwrap());
        }

        let i = Self::ilogq2below(data, logq2);

        // Calculate derivatives
        let didlogq2: f64;
        let di1dlogq2: f64;
        if i == 0 {
            didlogq2 = Self::ddlogq_forward(data, i);
            di1dlogq2 = Self::ddlogq_central(data, i + 1);
        } else if i == logq2s.len() - 2 {
            didlogq2 = Self::ddlogq_central(data, i);
            di1dlogq2 = Self::ddlogq_backward(data, i + 1);
        } else {
            didlogq2 = Self::ddlogq_central(data, i);
            di1dlogq2 = Self::ddlogq_central(data, i + 1);
        }

        // Calculate alpha_s
        let dlogq2 = logq2s[i + 1] - logq2s[i];
        let tlogq2 = (logq2 - logq2s[i]) / dlogq2;
        Ok(utils::hermite_cubic_interpolate(
            tlogq2,
            alphas[i],
            didlogq2 * dlogq2,
            alphas[i + 1],
            di1dlogq2 * dlogq2,
        ))
    }

    fn allow_extrapolate(&self) -> bool {
        true
    }
}

/// Implements a global N-dimensional interpolation using Chebyshev polynomials with logarithmic
/// coordinate scaling.
///
/// This strategy, inspired by the method described in arXiv:2112.09703, first transforms the input
/// coordinates to their natural logarithms, and then fits a single, high-degree Chebyshev polynomial
/// to the entire dataset in the log-transformed space.
///
/// Key features:
/// - **Logarithmic Scaling**: Coordinates are transformed via `x -> ln(x)` before interpolation.
/// - **Global Nature**: The interpolation at any point depends on all data points in the grid.
/// - **High Degree**: The degree of the interpolating polynomial is `N-1`, where `N` is the
///   number of grid points in each dimension.
/// - **Grid Requirement**: For optimal stability and to avoid Runge's phenomenon, the grid
///   points should correspond to the roots or extrema of Chebyshev polynomials.
#[derive(Debug, Clone)]
pub struct LogChebyshevInterpolation<const DIM: usize> {
    // Pre-computed weights for the barycentric formula for each dimension.
    weights: [Vec<f64>; DIM],
    // Grid points in the t-domain [-1, 1] for each dimension.
    t_coords: [Vec<f64>; DIM],
}

impl<const DIM: usize> Default for LogChebyshevInterpolation<DIM> {
    fn default() -> Self {
        Self {
            weights: std::array::from_fn(|_| Vec::new()),
            t_coords: std::array::from_fn(|_| Vec::new()),
        }
    }
}

impl<const DIM: usize> Serialize for LogChebyshevInterpolation<DIM> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("LogChebyshevInterpolation", 2)?;
        state.serialize_field("weights", &self.weights.as_slice())?;
        state.serialize_field("t_coords", &self.t_coords.as_slice())?;
        state.end()
    }
}

impl<'de, const DIM: usize> Deserialize<'de> for LogChebyshevInterpolation<DIM> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Helper {
            weights: Vec<Vec<f64>>,
            t_coords: Vec<Vec<f64>>,
        }

        let helper = Helper::deserialize(deserializer)?;
        let weights = helper.weights.try_into().map_err(|v: Vec<Vec<f64>>| {
            serde::de::Error::invalid_length(v.len(), &"an array of the correct length")
        })?;
        let t_coords = helper.t_coords.try_into().map_err(|v: Vec<Vec<f64>>| {
            serde::de::Error::invalid_length(v.len(), &"an array of the correct length")
        })?;

        Ok(Self { weights, t_coords })
    }
}

impl<const DIM: usize> LogChebyshevInterpolation<DIM> {
    /// Computes the barycentric weights for a given set of Chebyshev points.
    /// The formula for the weights is `w_j = (-1)^j * delta_j`, where `delta_j`
    /// is 1/2 for the first and last points, and 1 otherwise.
    fn compute_barycentric_weights(n: usize) -> Vec<f64> {
        let mut weights = vec![1.0; n];
        (0..n).for_each(|j| {
            if j % 2 == 1 {
                weights[j] = -1.0;
            }
        });
        weights[0] *= 0.5;
        if n > 1 {
            weights[n - 1] *= 0.5;
        }
        weights
    }

    /// Computes normalized barycentric coefficients for interpolation
    /// Returns a vector of coefficients that sum to 1
    fn barycentric_coefficients(t: f64, t_coords: &[f64], weights: &[f64]) -> Vec<f64> {
        let mut coeffs = vec![0.0; t_coords.len()];

        for (j, &t_j) in t_coords.iter().enumerate() {
            if (t - t_j).abs() < 1e-15 {
                // t is exactly at grid point j - return unit vector
                coeffs[j] = 1.0;
                return coeffs;
            }
        }

        let mut terms = Vec::with_capacity(t_coords.len());
        for (j, &t_j) in t_coords.iter().enumerate() {
            terms.push(weights[j] / (t - t_j));
        }

        let sum: f64 = terms.iter().sum();
        for (j, &term) in terms.iter().enumerate() {
            coeffs[j] = term / sum;
        }

        coeffs
    }

    /// Legacy barycentric interpolation method (kept for compatibility)
    fn barycentric_interpolate(t: f64, t_coords: &[f64], f_values: &[f64], weights: &[f64]) -> f64 {
        let mut numer = 0.0;
        let mut denom = 0.0;

        for (j, &t_j) in t_coords.iter().enumerate() {
            if (t - t_j).abs() < 1e-15 {
                return f_values[j];
            }

            let term = weights[j] / (t - t_j);
            numer += term * f_values[j];
            denom += term;
        }

        numer / denom
    }
}

impl<D> Strategy1D<D> for LogChebyshevInterpolation<1>
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    fn init(&mut self, data: &InterpData1D<D>) -> Result<(), ValidateError> {
        let x_coords = data.grid[0].as_slice().unwrap();
        let n = x_coords.len();
        if n < 2 {
            return Err(ValidateError::Other(
                "LogChebyshevInterpolation requires at least 2 grid points.".to_string(),
            ));
        }

        self.t_coords[0] = (0..n)
            .map(|j| (PI * (n - 1 - j) as f64 / (n - 1) as f64).cos())
            .collect();

        self.weights[0] = Self::compute_barycentric_weights(n);

        Ok(())
    }

    fn interpolate(
        &self,
        data: &InterpData1D<D>,
        point: &[f64; 1],
    ) -> Result<f64, InterpolateError> {
        let x = point[0];
        let x_coords = data.grid[0].as_slice().unwrap();
        let f_values = data.values.as_slice().unwrap();

        let x_min = *x_coords.first().unwrap();
        let x_max = *x_coords.last().unwrap();

        if x < x_min || x > x_max {
            return Err(InterpolateError::Other(format!(
                "Input point {} is outside the grid range [{}, {}]",
                x, x_min, x_max
            )));
        }

        if (x_max - x_min).abs() < 1e-15 {
            return Ok(f_values[0]);
        }
        let t = 2.0 * (x - x_min) / (x_max - x_min) - 1.0;

        Ok(Self::barycentric_interpolate(
            t,
            &self.t_coords[0],
            f_values,
            &self.weights[0],
        ))
    }

    fn allow_extrapolate(&self) -> bool {
        true
    }
}

impl<D> Strategy2D<D> for LogChebyshevInterpolation<2>
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    fn init(&mut self, data: &InterpData2D<D>) -> Result<(), ValidateError> {
        for dim in 0..2 {
            let x_coords = data.grid[dim].as_slice().unwrap();
            let n = x_coords.len();
            if n < 2 {
                return Err(ValidateError::Other(
                    "LogChebyshevInterpolation requires at least 2 grid points per dimension."
                        .to_string(),
                ));
            }
            self.t_coords[dim] = (0..n)
                .map(|j| (PI * (n - 1 - j) as f64 / (n - 1) as f64).cos())
                .collect();
            self.weights[dim] = Self::compute_barycentric_weights(n);
        }
        Ok(())
    }

    fn interpolate(
        &self,
        data: &InterpData2D<D>,
        point: &[f64; 2],
    ) -> Result<f64, InterpolateError> {
        let [x, y] = *point;
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();

        let x_min = *x_coords.first().unwrap();
        let x_max = *x_coords.last().unwrap();
        if x < x_min || x > x_max {
            return Err(InterpolateError::Other(format!(
                "Input point x={} is outside the grid range [{}, {}]",
                x, x_min, x_max
            )));
        }

        let y_min = *y_coords.first().unwrap();
        let y_max = *y_coords.last().unwrap();
        if y < y_min || y > y_max {
            return Err(InterpolateError::Other(format!(
                "Input point y={} is outside the grid range [{}, {}]",
                y, y_min, y_max
            )));
        }

        let t_x = 2.0 * (x - x_min) / (x_max - x_min) - 1.0;
        let t_y = 2.0 * (y - y_min) / (y_max - y_min) - 1.0;

        let x_coeffs = Self::barycentric_coefficients(t_x, &self.t_coords[0], &self.weights[0]);
        let y_coeffs = Self::barycentric_coefficients(t_y, &self.t_coords[1], &self.weights[1]);

        let mut result = 0.0;
        for (i, &x_coeff) in x_coeffs.iter().enumerate() {
            for (j, &y_coeff) in y_coeffs.iter().enumerate() {
                result += x_coeff * y_coeff * data.values[[i, j]];
            }
        }

        Ok(result)
    }

    fn allow_extrapolate(&self) -> bool {
        true
    }
}

impl<D> Strategy3D<D> for LogChebyshevInterpolation<3>
where
    D: Data<Elem = f64> + RawDataClone + Clone,
{
    fn init(&mut self, data: &InterpData3D<D>) -> Result<(), ValidateError> {
        for dim in 0..3 {
            let x_coords = data.grid[dim].as_slice().unwrap();
            let n = x_coords.len();
            if n < 2 {
                return Err(ValidateError::Other(
                    "LogChebyshevInterpolation requires at least 2 grid points per dimension."
                        .to_string(),
                ));
            }
            self.t_coords[dim] = (0..n)
                .map(|j| (PI * (n - 1 - j) as f64 / (n - 1) as f64).cos())
                .collect();
            self.weights[dim] = Self::compute_barycentric_weights(n);
        }
        Ok(())
    }

    fn interpolate(
        &self,
        data: &InterpData3D<D>,
        point: &[f64; 3],
    ) -> Result<f64, InterpolateError> {
        let [x, y, z] = *point;
        let x_coords = data.grid[0].as_slice().unwrap();
        let y_coords = data.grid[1].as_slice().unwrap();
        let z_coords = data.grid[2].as_slice().unwrap();

        let x_min = *x_coords.first().unwrap();
        let x_max = *x_coords.last().unwrap();
        if x < x_min || x > x_max {
            return Err(InterpolateError::Other(format!(
                "Input point x={} is outside the grid range [{}, {}]",
                x, x_min, x_max
            )));
        }

        let y_min = *y_coords.first().unwrap();
        let y_max = *y_coords.last().unwrap();
        if y < y_min || y > y_max {
            return Err(InterpolateError::Other(format!(
                "Input point y={} is outside the grid range [{}, {}]",
                y, y_min, y_max
            )));
        }

        let z_min = *z_coords.first().unwrap();
        let z_max = *z_coords.last().unwrap();
        if z < z_min || z > z_max {
            return Err(InterpolateError::Other(format!(
                "Input point z={} is outside the grid range [{}, {}]",
                z, z_min, z_max
            )));
        }

        let t_x = 2.0 * (x - x_min) / (x_max - x_min) - 1.0;
        let t_y = 2.0 * (y - y_min) / (y_max - y_min) - 1.0;
        let t_z = 2.0 * (z - z_min) / (z_max - z_min) - 1.0;

        let x_coeffs = Self::barycentric_coefficients(t_x, &self.t_coords[0], &self.weights[0]);
        let y_coeffs = Self::barycentric_coefficients(t_y, &self.t_coords[1], &self.weights[1]);
        let z_coeffs = Self::barycentric_coefficients(t_z, &self.t_coords[2], &self.weights[2]);

        let mut result = 0.0;
        for (i, &x_coeff) in x_coeffs.iter().enumerate() {
            for (j, &y_coeff) in y_coeffs.iter().enumerate() {
                for (k, &z_coeff) in z_coeffs.iter().enumerate() {
                    result += x_coeff * y_coeff * z_coeff * data.values[[i, j, k]];
                }
            }
        }

        Ok(result)
    }

    fn allow_extrapolate(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use itertools::Itertools;
    use ndarray::{Array1, Array2, Array3, OwnedRepr};
    use ninterp::data::{InterpData1D, InterpData2D};
    use ninterp::interpolator::{Extrapolate, InterpND};
    use ninterp::prelude::Interpolator;
    use ninterp::strategy::Linear;
    use std::f64::consts::PI;

    // Helper constants for commonly used values
    const EPSILON: f64 = 1e-9;

    fn assert_close(actual: f64, expected: f64, tolerance: f64) {
        assert!(
            (actual - expected).abs() < tolerance,
            "Expected {}, got {} (diff: {})",
            expected,
            actual,
            (actual - expected).abs()
        );
    }

    // Create the target test data in 2D by multiplying the indices.
    fn create_target_data_2d(max_num: i32) -> Vec<f64> {
        (1..=max_num)
            .flat_map(|i| (1..=max_num).map(move |j| (i * j) as f64))
            .collect()
    }

    // Create a logarithmically spaced vector of floating numbers.
    fn create_logspaced(start: f64, stop: f64, n: usize) -> Vec<f64> {
        (0..n)
            .map(|value| {
                let t = value as f64 / (n - 1) as f64;
                start * (stop / start).powf(t)
            })
            .collect()
    }

    // Create an instance of `create_test_data_1d` for 1-dimensional interpolations.
    fn create_test_data_1d(
        q2_values: Vec<f64>,
        alphas_vals: Vec<f64>,
    ) -> InterpData1D<OwnedRepr<f64>> {
        InterpData1D::new(Array1::from(q2_values), Array1::from(alphas_vals)).unwrap()
    }

    // Create an instance of `create_test_data_2d` for 2-dimensional interpolations.
    fn create_test_data_2d(
        x_coords: Vec<f64>,
        y_coords: Vec<f64>,
        values: Vec<f64>,
    ) -> InterpData2D<OwnedRepr<f64>> {
        let shape = (x_coords.len(), y_coords.len());
        let values_array = Array2::from_shape_vec(shape, values).unwrap();
        InterpData2D::new(x_coords.into(), y_coords.into(), values_array).unwrap()
    }

    // Create an instance of `create_test_data_3d` for 3-dimensional interpolations.
    fn create_test_data_3d(
        x_coords: Vec<f64>,
        y_coords: Vec<f64>,
        z_coords: Vec<f64>,
        values: Vec<f64>,
    ) -> InterpData3D<OwnedRepr<f64>> {
        let shape = (x_coords.len(), y_coords.len(), z_coords.len());
        let values_array = Array3::from_shape_vec(shape, values).unwrap();
        InterpData3D::new(
            x_coords.into(),
            y_coords.into(),
            z_coords.into(),
            values_array,
        )
        .unwrap()
    }

    // Create an instance of `create_chebyshev_grid` for 2- and 3-dimensional interpolations.
    fn create_cheby_grid(n_points: i32, x_min: f64, x_max: f64) -> Vec<f64> {
        let u_min = x_min.ln();
        let u_max = x_max.ln();
        (0..n_points)
            .map(|j| {
                let t_j = (PI * (n_points - 1 - j) as f64 / (n_points - 1) as f64).cos();
                let u_j = u_min + (u_max - u_min) * (t_j + 1.0) / 2.0;
                u_j.exp()
            })
            .collect::<Vec<f64>>()
    }

    #[test]
    fn test_linear_interpolate() {
        let test_cases = [
            // (x1, x2, y1, y2, x, expected)
            (0.0, 1.0, 0.0, 10.0, 0.5, 5.0),
            (0.0, 10.0, 0.0, 100.0, 2.5, 25.0),
            (0.0, 1.0, 0.0, 10.0, 0.0, 0.0),   // At start endpoint
            (0.0, 1.0, 0.0, 10.0, 1.0, 10.0),  // At end endpoint
            (5.0, 5.0, 10.0, 20.0, 5.0, 10.0), // x1 == x2 case
        ];

        for (x1, x2, y1, y2, x, expected) in test_cases {
            let result = BilinearInterpolation::linear_interpolate(x1, x2, y1, y2, x);
            assert_close(result, expected, EPSILON);
        }
    }

    #[test]
    fn test_bilinear_interpolation() {
        let data = create_test_data_2d(
            vec![0.0, 1.0, 2.0],
            vec![0.0, 1.0, 2.0],
            vec![0.0, 1.0, 2.0, 1.0, 2.0, 3.0, 2.0, 3.0, 4.0],
        );

        let test_cases = [
            ([0.5, 0.5], 1.0),
            ([1.0, 1.0], 2.0), // Grid point
            ([0.25, 0.75], 1.0),
        ];

        for (point, expected) in test_cases {
            let result = BilinearInterpolation.interpolate(&data, &point).unwrap();
            assert_close(result, expected, EPSILON);
        }
    }

    #[test]
    fn test_log_bilinear_interpolation() {
        let data = create_test_data_2d(
            vec![1.0f64.ln(), 10.0f64.ln(), 100.0f64.ln()],
            vec![1.0f64.ln(), 10.0f64.ln(), 100.0f64.ln()],
            vec![0.0, 1.0, 2.0, 1.0, 2.0, 3.0, 2.0, 3.0, 4.0],
        );
        LogBilinearInterpolation.init(&data).unwrap();

        let test_cases = [
            ([3.16227766f64.ln(), 3.16227766f64.ln()], 1.0), // sqrt(10)
            ([10.0f64.ln(), 10.0f64.ln()], 2.0),             // Grid point
            ([1.77827941f64.ln(), 5.62341325f64.ln()], 1.0), // 10^0.25, 10^0.75
        ];

        for (point, expected) in test_cases {
            let result = LogBilinearInterpolation.interpolate(&data, &point).unwrap();
            assert_close(result, expected, EPSILON);
        }
    }

    #[test]
    fn test_log_tricubic_interpolation() {
        let x_coords = create_logspaced(1e-5, 1e-3, 6);
        let y_coords = create_logspaced(1e2, 1e4, 6);
        let z_coords = vec![1.0, 5.0, 25.0, 100.0, 150.0, 200.0];
        let values: Vec<f64> = x_coords
            .iter()
            .cartesian_product(y_coords.iter())
            .cartesian_product(z_coords.iter())
            .map(|((&a, &b), &c)| a * b * c)
            .collect();

        // We need to logarithmically scale the data for `exponential-like curves`
        let values_ln: Vec<f64> = values.iter().map(|val| val.ln()).collect();
        let interp_data_ln = create_test_data_3d(
            x_coords.iter().map(|v| v.ln()).collect(),
            y_coords.iter().map(|v| v.ln()).collect(),
            z_coords.iter().map(|v| v.ln()).collect(),
            values_ln.clone(),
        );

        // Initi the interpolation strategy.
        let mut strategy = LogTricubicInterpolation;
        strategy.init(&interp_data_ln).unwrap();

        let point: [f64; 3] = [1e-4, 2e3, 25.0];
        let log_point = [point[0].ln(), point[1].ln(), point[2].ln()];
        let expected: f64 = point.iter().product();
        let result = strategy
            .interpolate(&interp_data_ln, &log_point)
            .unwrap()
            .exp();
        assert_close(result, expected, EPSILON);

        // Compare to general ND interpolation
        let interp_data_arr =
            Array3::from_shape_vec((x_coords.len(), y_coords.len(), z_coords.len()), values)
                .unwrap();
        let nd_interp = InterpND::new(
            vec![x_coords.into(), y_coords.into(), z_coords.into()],
            interp_data_arr.into_dyn(),
            Linear,
            Extrapolate::Error,
        )
        .unwrap();
        let nd_interp_res = nd_interp.interpolate(&point).unwrap();
        assert_close(nd_interp_res, expected, EPSILON);
    }

    #[test]
    fn test_alphas_cubic_interpolation() {
        let q_values = [1.0f64, 2.0, 3.0, 4.0, 5.0];
        let alphas_vals = vec![0.1, 0.11, 0.12, 0.13, 0.14];
        let logq2_values: Vec<f64> = q_values.iter().map(|&q| (q * q).ln()).collect();
        let data = create_test_data_1d(logq2_values, alphas_vals);
        let alphas_cubic = AlphaSCubicInterpolation;

        // Test within interpolation range
        let result = alphas_cubic.interpolate(&data, &[2.25f64.ln()]).unwrap(); // Q=1.5
        assert!(result > 0.1 && result < 0.14);

        // Test at grid point
        let result = alphas_cubic.interpolate(&data, &[4.0f64.ln()]).unwrap(); // Q=2.0
        assert_close(result, 0.11, EPSILON);

        // Test extrapolation below range
        let result = alphas_cubic.interpolate(&data, &[0.5f64.ln()]).unwrap(); // Q=sqrt(0.5)
        assert!(result < 0.1);

        // Test extrapolation above range
        let result = alphas_cubic.interpolate(&data, &[30.0f64.ln()]).unwrap(); // Q=sqrt(30)
        assert_close(result, 0.14, EPSILON);
    }

    #[test]
    fn test_find_bicubic_interval() {
        let coords = vec![1.0, 2.0, 3.0, 4.0, 5.0];

        let test_cases = [
            (1.5, Ok(0)),
            (3.5, Ok(2)),
            (2.0, Ok(1)),   // At knot point
            (1.0, Ok(0)),   // At boundary
            (4.99, Ok(3)),  // Near boundary
            (0.5, Err(())), // Out of bounds
            (5.5, Err(())), // Out of bounds
        ];

        for (value, expected) in test_cases {
            let result = LogBicubicInterpolation::find_bicubic_interval(&coords, value);
            match expected {
                Ok(expected_idx) => assert_eq!(result.unwrap(), expected_idx),
                Err(_) => assert!(result.is_err()),
            }
        }
    }

    #[test]
    fn test_hermite_cubic_interpolate_from_coeffs() {
        let test_cases = [
            // Linear function x: coeffs = [0, 0, 1, 0]
            ([0.0, 0.0, 1.0, 0.0], 0.5, 0.5),
            ([0.0, 0.0, 1.0, 0.0], 1.0, 1.0),
            // Constant function 5: coeffs = [0, 0, 0, 5]
            ([0.0, 0.0, 0.0, 5.0], 0.5, 5.0),
            // Cubic function x^3: coeffs = [1, 0, 0, 0]
            ([1.0, 0.0, 0.0, 0.0], 2.0, 8.0),
            ([1.0, 0.0, 0.0, 0.0], 0.5, 0.125),
            // Complex polynomial 2x^3 - 3x^2 + x + 4
            ([2.0, -3.0, 1.0, 4.0], 1.0, 4.0),
            ([2.0, -3.0, 1.0, 4.0], 0.0, 4.0),
            ([2.0, -3.0, 1.0, 4.0], 2.0, 10.0),
        ];

        for (coeffs, x, expected) in test_cases {
            let result = LogBicubicInterpolation::hermite_cubic_interpolate_from_coeffs(x, &coeffs);
            assert_close(result, expected, EPSILON);
        }
    }

    #[test]
    fn test_log_bicubic_interpolation() {
        let target_data = create_target_data_2d(4);
        let data = create_test_data_2d(
            vec![1.0f64.ln(), 10.0f64.ln(), 100.0f64.ln(), 1000.0f64.ln()],
            vec![1.0f64.ln(), 10.0f64.ln(), 100.0f64.ln(), 1000.0f64.ln()],
            target_data,
        );

        let mut log_bicubic = LogBicubicInterpolation::default();
        log_bicubic.init(&data).unwrap();

        let test_cases = [
            ([10.0f64.ln(), 10.0f64.ln()], 4.0),              // Grid point
            ([3.16227766f64.ln(), 3.16227766f64.ln()], 2.25), // sqrt(10)
            ([31.6227766f64.ln(), 31.6227766f64.ln()], 6.25), // 10^1.5
        ];

        for (point, expected) in test_cases {
            let result = log_bicubic.interpolate(&data, &point).unwrap();
            assert_close(result, expected, EPSILON);
        }
    }

    #[test]
    fn test_ddlogq_derivatives() {
        let data = create_test_data_1d(
            vec![1.0f64.ln(), 2.0f64.ln(), 3.0f64.ln(), 4.0f64.ln()],
            vec![0.1, 0.2, 0.3, 0.4],
        );

        // Forward derivative
        let expected_forward = 0.1 / (2.0f64.ln() - 1.0f64.ln());
        assert_close(
            AlphaSCubicInterpolation::ddlogq_forward(&data, 0),
            expected_forward,
            EPSILON,
        );

        // Backward derivative
        let expected_backward = 0.1 / (2.0f64.ln() - 1.0f64.ln());
        assert_close(
            AlphaSCubicInterpolation::ddlogq_backward(&data, 1),
            expected_backward,
            EPSILON,
        );

        // Central derivative
        let expected_central =
            0.5 * (0.1 / (3.0f64.ln() - 2.0f64.ln()) + 0.1 / (2.0f64.ln() - 1.0f64.ln()));
        assert_close(
            AlphaSCubicInterpolation::ddlogq_central(&data, 1),
            expected_central,
            EPSILON,
        );
    }

    #[test]
    fn test_ilogq2below() {
        let data = create_test_data_1d(
            vec![
                1.0f64.ln(),
                2.0f64.ln(),
                3.0f64.ln(),
                4.0f64.ln(),
                5.0f64.ln(),
            ],
            vec![0.1, 0.2, 0.3, 0.4, 0.5],
        );

        let test_cases = [
            (1.5f64.ln(), 0),
            (2.0f64.ln(), 1),
            (3.9f64.ln(), 2), // Within range
            (1.0f64.ln(), 0),
            (5.0f64.ln(), 3), // At boundaries
        ];

        for (q2_val, expected_idx) in test_cases {
            assert_eq!(
                AlphaSCubicInterpolation::ilogq2below(&data, q2_val),
                expected_idx
            );
        }

        // Test edge cases with different data sizes
        let data_small = create_test_data_1d(vec![1.0f64.ln(), 2.0f64.ln()], vec![0.1, 0.2]);
        assert_eq!(
            AlphaSCubicInterpolation::ilogq2below(&data_small, 2.0f64.ln()),
            0
        );

        let data_with_mid = create_test_data_1d(
            vec![1.0f64.ln(), 2.0f64.ln(), 3.0f64.ln()],
            vec![0.1, 0.2, 0.3],
        );
        assert_eq!(
            AlphaSCubicInterpolation::ilogq2below(&data_with_mid, 2.0f64.ln()),
            1
        );

        // Test panic conditions
        let data_single = create_test_data_1d(vec![1.0f64.ln()], vec![0.1]);

        let result = std::panic::catch_unwind(|| {
            AlphaSCubicInterpolation::ilogq2below(&data_single, 0.5f64.ln());
        });
        assert!(result.is_err());

        let result = std::panic::catch_unwind(|| {
            AlphaSCubicInterpolation::ilogq2below(&data_single, 1.5f64.ln());
        });
        assert!(result.is_err());
    }

    #[test]
    fn test_log_chebyshev_interpolation_1d() {
        let n = 21;
        let x_min: f64 = 0.1;
        let x_max: f64 = 10.0;
        let x_coords = create_cheby_grid(n, x_min, x_max);

        let f_values: Vec<f64> = x_coords.iter().map(|&x| x.ln()).collect();
        let data = create_test_data_1d(x_coords.iter().map(|v| v.ln()).collect(), f_values);
        let mut cheby = LogChebyshevInterpolation::<1>::default();
        cheby.init(&data).unwrap();

        let x_test: f64 = 2.5;
        let expected = x_test.ln();
        let result = cheby.interpolate(&data, &[x_test.ln()]).unwrap();
        assert_close(result, expected, EPSILON);

        let x_test_grid = data.grid[0].as_slice().unwrap()[n as usize / 2];
        let expected_grid = x_test_grid;
        let result_grid = cheby.interpolate(&data, &[x_test_grid]).unwrap();
        assert_close(result_grid, expected_grid, EPSILON);
    }

    #[test]
    fn test_log_chebyshev_interpolation_2d() {
        let n = 11;
        let x_coords = create_cheby_grid(n, 0.1, 10.0);
        let y_coords = create_cheby_grid(n, 0.1, 10.0);

        let f_values: Vec<f64> = x_coords
            .iter()
            .flat_map(|&x| y_coords.iter().map(move |&y| x.ln() + y.ln()))
            .collect();

        let data = create_test_data_2d(
            x_coords.iter().map(|v| v.ln()).collect(),
            y_coords.iter().map(|v| v.ln()).collect(),
            f_values,
        );
        let mut cheby = LogChebyshevInterpolation::<2>::default();
        cheby.init(&data).unwrap();

        let x_test: f64 = 2.5;
        let y_test: f64 = 3.5;
        let expected = x_test.ln() + y_test.ln();
        let result = cheby
            .interpolate(&data, &[x_test.ln(), y_test.ln()])
            .unwrap();

        assert_close(result, expected, EPSILON);
    }

    #[test]
    fn test_log_chebyshev_interpolation_3d() {
        let n = 7;
        let x_coords = create_cheby_grid(n, 0.1, 10.0);
        let y_coords = create_cheby_grid(n, 0.1, 10.0);
        let z_coords = create_cheby_grid(n, 0.1, 10.0);

        let f_values: Vec<f64> = x_coords
            .iter()
            .cartesian_product(y_coords.iter())
            .cartesian_product(z_coords.iter())
            .map(|((&x, &y), &z)| x.ln() + y.ln() + z.ln())
            .collect();

        let data = create_test_data_3d(
            x_coords.iter().map(|v| v.ln()).collect(),
            y_coords.iter().map(|v| v.ln()).collect(),
            z_coords.iter().map(|v| v.ln()).collect(),
            f_values,
        );
        let mut cheby = LogChebyshevInterpolation::<3>::default();
        cheby.init(&data).unwrap();

        let x_test: f64 = 2.5;
        let y_test: f64 = 3.5;
        let z_test: f64 = 4.5;
        let expected = x_test.ln() + y_test.ln() + z_test.ln();
        let result = cheby
            .interpolate(&data, &[x_test.ln(), y_test.ln(), z_test.ln()])
            .unwrap();

        assert_close(result, expected, EPSILON);
    }
}