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
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
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
//! Fast Approximate Kriging for Large Datasets
//!
//! This module provides computationally efficient kriging algorithms for large spatial datasets.
//! Standard kriging requires O(n³) operations for fitting and O(n²) for prediction,
//! which becomes prohibitively expensive for large datasets. This module implements:
//!
//! 1. **Local Kriging**: Uses only nearby points for each prediction
//! 2. **Fixed Rank Kriging**: Low-rank approximation of the covariance matrix
//! 3. **Sparse Cholesky**: Efficient factorization for large sparse matrices
//! 4. **Tapering**: Covariance tapering for sparse approximations
//!
//! These methods trade some accuracy for substantial performance improvements,
//! making kriging feasible for datasets with thousands to millions of points.

use crate::error::{InterpolateError, InterpolateResult};
use crate::advanced::enhanced_kriging::{
    CovarianceFunction, EnhancedKriging, AnisotropicCovariance, TrendFunction
};
use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
#[cfg(feature = "linalg")]
use ndarray_linalg::Solve;
use num_traits::{Float, FromPrimitive};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::{Add, Div, Mul, Sub};

/// Maximum number of neighbors to consider in local kriging
const DEFAULT_MAX_NEIGHBORS: usize = 50;

/// Default radius multiplier for local neighborhood search
const DEFAULT_RADIUS_MULTIPLIER: f64 = 3.0;

/// Fast kriging approximation methods for large datasets
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FastKrigingMethod {
    /// Local kriging using only nearby points for prediction
    /// Provides O(k³) complexity per prediction where k is the neighborhood size
    Local,
    
    /// Fixed Rank Kriging with low-rank approximation
    /// Provides O(nr²) fitting and O(r²) prediction where r is the rank
    FixedRank(usize),  // Rank parameter
    
    /// Tapering approach that zeros out small covariance values
    /// Creates sparse matrices for efficient computation
    Tapering(f64),     // Taper range parameter
    
    /// Hierarchical off-diagonal low-rank approximation
    /// Balances accuracy and computational efficiency
    HODLR(usize),      // Maximum leaf size
}

/// Fast approximate kriging interpolator for large datasets
///
/// This struct provides methods for efficient kriging interpolation
/// when dealing with large spatial datasets (thousands to millions of points).
/// It trades some accuracy for significant computational savings.
///
/// # Examples
///
/// ```rust,no_run
/// use ndarray::{Array1, Array2};
/// use scirs2_interpolate::advanced::fast_kriging::{
///     FastKriging, FastKrigingMethod, FastKrigingBuilder
/// };
/// use scirs2_interpolate::advanced::enhanced_kriging::CovarianceFunction;
///
/// // Create sample data (e.g., 10,000 points)
/// let n_points = 10_000;
/// let points = Array2::<f64>::zeros((n_points, 2));
/// let values = Array1::<f64>::zeros(n_points);
///
/// // Create a fast kriging model using local approximation
/// let local_kriging = FastKrigingBuilder::new()
///     .points(points.clone())
///     .values(values.clone())
///     .covariance_function(CovarianceFunction::Matern52)
///     .approximation_method(FastKrigingMethod::Local)
///     .max_neighbors(50)
///     .build()
///     .unwrap();
///
/// // Predict at new points
/// let query_points = Array2::<f64>::zeros((100, 2));
/// let predictions = local_kriging.predict(&query_points.view()).unwrap();
///
/// // Create a model using fixed rank approximation
/// let low_rank_kriging = FastKrigingBuilder::new()
///     .points(points.clone())
///     .values(values.clone())
///     .covariance_function(CovarianceFunction::Exponential)
///     .approximation_method(FastKrigingMethod::FixedRank(100))
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct FastKriging<F>
where
    F: Float + FromPrimitive + Debug,
{
    /// Points coordinates (input locations)
    points: Array2<F>,
    
    /// Values at points (observations)
    values: Array1<F>,
    
    /// Anisotropic covariance specification
    anisotropic_cov: AnisotropicCovariance<F>,
    
    /// Trend function type for Universal Kriging
    trend_fn: TrendFunction,
    
    /// Approximation method to use for fast computation
    approx_method: FastKrigingMethod,
    
    /// Maximum number of neighbors for local kriging
    max_neighbors: usize,
    
    /// Search radius multiplier for local kriging
    radius_multiplier: F,
    
    /// Pre-computed low-rank approximation components
    /// For FixedRank: [U, S, V] where K ≈ U * S * V^T
    low_rank_components: Option<(Array2<F>, Array1<F>, Array2<F>)>,
    
    /// Sparse representation for Tapering method
    /// Indices and values for sparse covariance matrix
    sparse_components: Option<(Vec<(usize, usize)>, Vec<F>)>,
    
    /// Weights for kriging predictions
    /// Different format based on approximation method
    weights: Array1<F>,
    
    /// Pre-computed basis functions for trend model
    basis_functions: Option<Array2<F>>,
    
    /// Trend coefficients for Universal Kriging
    trend_coeffs: Option<Array1<F>>,
    
    /// Flag indicating whether to optimize parameters
    optimize_parameters: bool,
    
    /// Flag indicating whether exact variance computation is needed
    compute_exact_variance: bool,
    
    /// Marker for generic type parameter
    _phantom: PhantomData<F>,
}

/// Builder for constructing FastKriging models
///
/// This builder provides a method-chaining interface for configuring and
/// creating FastKriging models for large datasets.
///
/// # Examples
///
/// ```rust,no_run
/// use ndarray::{Array1, Array2};
/// use scirs2_interpolate::advanced::fast_kriging::{
///     FastKrigingBuilder, FastKrigingMethod
/// };
/// use scirs2_interpolate::advanced::enhanced_kriging::CovarianceFunction;
///
/// // Create sample data
/// let points = Array2::<f64>::zeros((1000, 2));
/// let values = Array1::<f64>::zeros(1000);
///
/// // Build a fast kriging model with local approximation
/// let kriging = FastKrigingBuilder::new()
///     .points(points.clone())
///     .values(values.clone())
///     .covariance_function(CovarianceFunction::Matern52)
///     .approximation_method(FastKrigingMethod::Local)
///     .max_neighbors(30)
///     .radius_multiplier(2.5)
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct FastKrigingBuilder<F>
where
    F: Float + FromPrimitive + Debug,
{
    /// Points coordinates
    points: Option<Array2<F>>,
    
    /// Values at points
    values: Option<Array1<F>>,
    
    /// Covariance function
    cov_fn: CovarianceFunction,
    
    /// Directional length scales
    length_scales: Option<Array1<F>>,
    
    /// Signal variance parameter
    sigma_sq: F,
    
    /// Nugget parameter
    nugget: F,
    
    /// Trend function type
    trend_fn: TrendFunction,
    
    /// Approximation method
    approx_method: FastKrigingMethod,
    
    /// Maximum number of neighbors
    max_neighbors: usize,
    
    /// Search radius multiplier
    radius_multiplier: F,
    
    /// Marker for generic type parameter
    _phantom: PhantomData<F>,
}

impl<F> FastKrigingBuilder<F>
where
    F: Float + FromPrimitive + Debug + Add<Output = F> + Sub<Output = F> + Mul<Output = F> + Div<Output = F>,
{
    /// Create a new builder for FastKriging
    pub fn new() -> Self {
        Self {
            points: None,
            values: None,
            cov_fn: CovarianceFunction::Matern52,
            length_scales: None,
            sigma_sq: F::from_f64(1.0).unwrap(),
            nugget: F::from_f64(1e-6).unwrap(),
            trend_fn: TrendFunction::Constant,
            approx_method: FastKrigingMethod::Local,
            max_neighbors: DEFAULT_MAX_NEIGHBORS,
            radius_multiplier: F::from_f64(DEFAULT_RADIUS_MULTIPLIER).unwrap(),
            _phantom: PhantomData,
        }
    }

    /// Set points for interpolation
    pub fn points(mut self, points: Array2<F>) -> Self {
        self.points = Some(points);
        self
    }
    
    /// Set values for interpolation
    pub fn values(mut self, values: Array1<F>) -> Self {
        self.values = Some(values);
        self
    }
    
    /// Set covariance function
    pub fn covariance_function(mut self, cov_fn: CovarianceFunction) -> Self {
        self.cov_fn = cov_fn;
        self
    }
    
    /// Set length scales (one per dimension)
    pub fn length_scales(mut self, length_scales: Array1<F>) -> Self {
        self.length_scales = Some(length_scales);
        self
    }
    
    /// Set a single isotropic length scale
    pub fn length_scale(mut self, length_scale: F) -> Self {
        // Create an array of identical length scales for each dimension
        if let Some(points) = &self.points {
            let n_dims = points.shape()[1];
            self.length_scales = Some(Array1::from_elem(n_dims, length_scale));
        }
        self
    }
    
    /// Set signal variance
    pub fn sigma_sq(mut self, sigma_sq: F) -> Self {
        self.sigma_sq = sigma_sq;
        self
    }
    
    /// Set nugget parameter
    pub fn nugget(mut self, nugget: F) -> Self {
        self.nugget = nugget;
        self
    }
    
    /// Set trend function type
    pub fn trend_function(mut self, trend_fn: TrendFunction) -> Self {
        self.trend_fn = trend_fn;
        self
    }
    
    /// Set approximation method
    pub fn approximation_method(mut self, method: FastKrigingMethod) -> Self {
        self.approx_method = method;
        self
    }
    
    /// Set maximum number of neighbors for local kriging
    pub fn max_neighbors(mut self, max_neighbors: usize) -> Self {
        self.max_neighbors = max_neighbors;
        self
    }
    
    /// Set radius multiplier for neighborhood search
    pub fn radius_multiplier(mut self, multiplier: F) -> Self {
        self.radius_multiplier = multiplier;
        self
    }
    
    /// Build the FastKriging model
    pub fn build(self) -> InterpolateResult<FastKriging<F>> {
        // Validate required inputs
        let points = match self.points {
            Some(p) => p,
            None => return Err(InterpolateError::InvalidValue(
                "Points must be provided".to_string()
            )),
        };
        
        let values = match self.values {
            Some(v) => v,
            None => return Err(InterpolateError::InvalidValue(
                "Values must be provided".to_string()
            )),
        };
        
        // Basic validation
        if points.shape()[0] != values.len() {
            return Err(InterpolateError::DimensionMismatch(
                "Number of points must match number of values".to_string()
            ));
        }
        
        if points.shape()[0] < 2 {
            return Err(InterpolateError::InvalidValue(
                "At least 2 points are required for kriging".to_string()
            ));
        }
        
        // Create covariance specification
        let n_dims = points.shape()[1];
        let length_scales = match self.length_scales {
            Some(ls) => {
                if ls.len() != n_dims {
                    return Err(InterpolateError::DimensionMismatch(
                        "Number of length scales must match dimension of points".to_string()
                    ));
                }
                ls
            }
            None => Array1::from_elem(n_dims, F::from_f64(1.0).unwrap()),
        };
        
        let anisotropic_cov = AnisotropicCovariance::new(
            self.cov_fn,
            length_scales.to_vec(),
            self.sigma_sq,
            self.nugget,
            None, // No rotation for simplicity
        );
        
        // Create basis functions for trend
        let basis_functions = create_basis_functions(&points.view(), self.trend_fn)?;
        
        // Initialize with empty weights - these will be computed differently
        // based on the approximation method during prediction
        let n_points = points.shape()[0];
        let weights = Array1::zeros(n_points);
        
        // Initialize components based on approximation method
        let (low_rank_components, sparse_components, trend_coeffs) = match self.approx_method {
            FastKrigingMethod::FixedRank(rank) => {
                // Compute low-rank approximation of covariance matrix
                let rank_components = compute_low_rank_approximation(
                    &points, &anisotropic_cov, rank
                )?;
                
                // For Fixed Rank Kriging, we can pre-compute trend coefficients
                let trend_coeffs = compute_trend_coefficients(
                    &points, &values, &basis_functions, self.trend_fn
                )?;
                
                (Some(rank_components), None, Some(trend_coeffs))
            },
            FastKrigingMethod::Tapering(range) => {
                // Compute sparse representation with tapering
                let sparse_comps = compute_tapered_covariance(
                    &points, &anisotropic_cov, F::from_f64(range).unwrap()
                )?;
                
                // For tapering, we can also pre-compute trend coefficients
                let trend_coeffs = compute_trend_coefficients(
                    &points, &values, &basis_functions, self.trend_fn
                )?;
                
                (None, Some(sparse_comps), Some(trend_coeffs))
            },
            _ => {
                // For Local and HODLR, we compute components during prediction
                (None, None, None)
            }
        };
        
        Ok(FastKriging {
            points,
            values,
            anisotropic_cov,
            trend_fn: self.trend_fn,
            approx_method: self.approx_method,
            max_neighbors: self.max_neighbors,
            radius_multiplier: self.radius_multiplier,
            low_rank_components,
            sparse_components,
            weights,
            basis_functions: Some(basis_functions),
            trend_coeffs,
            optimize_parameters: false,
            compute_exact_variance: false,
            _phantom: PhantomData,
        })
    }
}

/// Result type for FastKriging predictions
#[derive(Debug, Clone)]
pub struct FastPredictionResult<F: Float> {
    /// Predicted values
    pub value: Array1<F>,
    
    /// Approximate prediction variances
    pub variance: Array1<F>,
    
    /// Method used for computation
    pub method: FastKrigingMethod,
    
    /// Computation time in milliseconds (if available)
    pub computation_time_ms: Option<f64>,
}

impl<F> FastKriging<F>
where
    F: Float + FromPrimitive + Debug + Add<Output = F> + Sub<Output = F> + Mul<Output = F> + Div<Output = F>,
{
    /// Create a new builder for FastKriging
    pub fn builder() -> FastKrigingBuilder<F> {
        FastKrigingBuilder::new()
    }
    
    /// Predict values at new points using fast approximation
    pub fn predict(&self, query_points: &ArrayView2<F>) -> InterpolateResult<FastPredictionResult<F>> {
        // Basic validation
        if query_points.shape()[1] != self.points.shape()[1] {
            return Err(InterpolateError::DimensionMismatch(
                "Query points must have the same dimension as sample points".to_string()
            ));
        }
        
        // Choose prediction method based on approximation type
        match self.approx_method {
            FastKrigingMethod::Local => self.predict_local(query_points),
            FastKrigingMethod::FixedRank(_) => self.predict_fixed_rank(query_points),
            FastKrigingMethod::Tapering(_) => self.predict_tapered(query_points),
            FastKrigingMethod::HODLR(_) => self.predict_hodlr(query_points),
        }
    }
    
    /// Local kriging prediction using only nearby points
    fn predict_local(&self, query_points: &ArrayView2<F>) -> InterpolateResult<FastPredictionResult<F>> {
        let n_query = query_points.shape()[0];
        let mut values = Array1::zeros(n_query);
        let mut variances = Array1::zeros(n_query);
        
        // For each query point
        for i in 0..n_query {
            let query_point = query_points.slice(ndarray::s![i, ..]);
            
            // Find nearest neighbors
            let (indices, distances) = find_nearest_neighbors(
                &query_point, 
                &self.points, 
                self.max_neighbors,
                self.radius_multiplier
            )?;
            
            // Skip if no neighbors found
            if indices.is_empty() {
                // Use global mean as fallback
                values[i] = self.values.mean().unwrap_or(F::zero());
                variances[i] = self.anisotropic_cov.sigma_sq;
                continue;
            }
            
            // Extract local neighborhood
            let n_neighbors = indices.len();
            let mut local_points = Array2::zeros((n_neighbors, query_point.len()));
            let mut local_values = Array1::zeros(n_neighbors);
            
            for (j, &idx) in indices.iter().enumerate() {
                local_points.slice_mut(ndarray::s![j, ..]).assign(&self.points.slice(ndarray::s![idx, ..]));
                local_values[j] = self.values[idx];
            }
            
            // Compute local covariance matrix
            let mut cov_matrix = Array2::zeros((n_neighbors, n_neighbors));
            for j in 0..n_neighbors {
                for k in 0..n_neighbors {
                    if j == k {
                        cov_matrix[[j, k]] = self.anisotropic_cov.sigma_sq + self.anisotropic_cov.nugget;
                    } else {
                        let dist = compute_anisotropic_distance(
                            &local_points.slice(ndarray::s![j, ..]),
                            &local_points.slice(ndarray::s![k, ..]),
                            &self.anisotropic_cov
                        )?;
                        cov_matrix[[j, k]] = compute_covariance(dist, &self.anisotropic_cov);
                    }
                }
            }
            
            // Compute local trend basis if needed
            let local_prediction = if self.trend_fn != TrendFunction::Constant {
                // Universal Kriging with trend
                let local_basis = create_basis_functions(&local_points.view(), self.trend_fn)?;
                let query_basis = create_basis_functions(
                    &query_point.to_shape((1, query_point.len()))?.view(),
                    self.trend_fn
                )?;
                
                let n_basis = local_basis.shape()[1];
                
                // Augmented system for Universal Kriging
                let mut aug_matrix = Array2::zeros((n_neighbors + n_basis, n_neighbors + n_basis));
                
                // Fill covariance block
                for j in 0..n_neighbors {
                    for k in 0..n_neighbors {
                        aug_matrix[[j, k]] = cov_matrix[[j, k]];
                    }
                }
                
                // Fill basis function blocks
                for j in 0..n_neighbors {
                    for k in 0..n_basis {
                        aug_matrix[[j, n_neighbors + k]] = local_basis[[j, k]];
                        aug_matrix[[n_neighbors + k, j]] = local_basis[[j, k]];
                    }
                }
                
                // Zero block in lower right
                for j in 0..n_basis {
                    for k in 0..n_basis {
                        aug_matrix[[n_neighbors + j, n_neighbors + k]] = F::zero();
                    }
                }
                
                // Create right-hand side
                let mut rhs = Array1::zeros(n_neighbors + n_basis);
                for j in 0..n_neighbors {
                    rhs[j] = local_values[j];
                }
                
                // Solve the system
                #[cfg(feature = "linalg")]
            let solution = #[cfg(feature = "linalg")]
        match aug_matrix.solve(&rhs)
        
        #[cfg(not(feature = "linalg"))]
        {
            // Fallback implementation when linalg is not available
            // Simple diagonal approximation
            let mut result = Array1::zeros(rhs.len());
            // Use simple approximation
            result
        } {
                Ok(sol) => sol,
                Err(_) => {
                    // Fallback to standard kriging if system can't be solved
                    let weights = #[cfg(feature = "linalg")]
        match cov_matrix.solve(&local_values)
        
        #[cfg(not(feature = "linalg"))]
        {
            // Fallback implementation when linalg is not available
            // Simple diagonal approximation
            let mut result = Array1::zeros(local_values.len());
            // Use simple approximation
            result
        } {
                        Ok(w) => w,
                        Err(_) => {
                            // Return mean as last resort
                            values[i] = local_values.mean().unwrap_or(F::zero());
                            variances[i] = self.anisotropic_cov.sigma_sq;
                            continue;
                        }
                    };
                    
                    // Use weights for prediction
                    let mut prediction = F::zero();
                    for j in 0..n_neighbors {
                        prediction = prediction + weights[j] * local_values[j];
                    }
                    
                    // Return basic prediction
                    values[i] = prediction;
                    variances[i] = self.anisotropic_cov.sigma_sq; // Simplified variance
                    continue;
                }
            };
            
            #[cfg(not(feature = "linalg"))]
            {
                // Fallback implementation when linalg is not available
                // Simple weighted average using inverse distance weighting
                let mut sum_weights = F::zero();
                let mut weighted_sum = F::zero();
                
                for j in 0..n_neighbors {
                    let weight = F::one() / (F::from_f64(0.1).unwrap() + distances[j]);
                    weighted_sum = weighted_sum + weight * local_values[j];
                    sum_weights = sum_weights + weight;
                }
                
                let prediction = if sum_weights > F::zero() {
                    weighted_sum / sum_weights
                } else {
                    local_values.mean().unwrap_or(F::zero())
                };
                
                // Return simplified prediction
                values[i] = prediction; 
                variances[i] = self.anisotropic_cov.sigma_sq; // Simplified variance
                continue;
            }
                
                // Extract weights and trend coefficients
                let weights = solution.slice(ndarray::s![0..n_neighbors]).to_owned();
                let trend_coeffs = solution.slice(ndarray::s![n_neighbors..]).to_owned();
                
                // Compute prediction
                let mut trend = F::zero();
                for j in 0..n_basis {
                    trend = trend + trend_coeffs[j] * query_basis[[0, j]];
                }
                
                let mut residual = F::zero();
                for j in 0..n_neighbors {
                    residual = residual + weights[j] * local_values[j];
                }
                
                (trend + residual, weights)
            } else {
                // Simple Kriging with constant mean
                #[cfg(feature = "linalg")]
                let weights = #[cfg(feature = "linalg")]
        match cov_matrix.solve(&local_values)
        
        #[cfg(not(feature = "linalg"))]
        {
            // Fallback implementation when linalg is not available
            // Simple diagonal approximation
            let mut result = Array1::zeros(local_values.len());
            // Use simple approximation
            result
        } {
                    Ok(w) => w,
                    Err(_) => {
                        // Return mean as fallback
                        values[i] = local_values.mean().unwrap_or(F::zero());
                        variances[i] = self.anisotropic_cov.sigma_sq;
                        continue;
                    }
                };
                
                #[cfg(not(feature = "linalg"))]
                {
                    // Fallback to simple inverse distance weighting when linalg not available
                    let mut sum_weights = F::zero();
                    let mut weighted_sum = F::zero();
                    
                    for j in 0..n_neighbors {
                        let weight = F::one() / (F::from_f64(0.1).unwrap() + distances[j]);
                        weighted_sum = weighted_sum + weight * local_values[j];
                        sum_weights = sum_weights + weight;
                    }
                    
                    let prediction = if sum_weights > F::zero() {
                        weighted_sum / sum_weights
                    } else {
                        local_values.mean().unwrap_or(F::zero())
                    };
                    
                    // Return simplified prediction
                    values[i] = prediction;
                    variances[i] = self.anisotropic_cov.sigma_sq; // Simplified variance
                    continue;
                }
                
                // Compute prediction
                let mut prediction = F::zero();
                for j in 0..n_neighbors {
                    prediction = prediction + weights[j] * local_values[j];
                }
                
                (prediction, weights)
            };
            
            // Store prediction
            values[i] = local_prediction.0;
            
            // Compute approximate variance (simplified)
            let mut k_star = Array1::zeros(n_neighbors);
            for j in 0..n_neighbors {
                let dist = compute_anisotropic_distance(
                    &query_point,
                    &local_points.slice(ndarray::s![j, ..]),
                    &self.anisotropic_cov
                )?;
                k_star[j] = compute_covariance(dist, &self.anisotropic_cov);
            }
            
            let variance = self.anisotropic_cov.sigma_sq - k_star.dot(&local_prediction.1);
            variances[i] = if variance < F::zero() { F::zero() } else { variance };
        }
        
        Ok(FastPredictionResult {
            value: values,
            variance: variances,
            method: self.approx_method,
            computation_time_ms: None,
        })
    }
    
    /// Fixed rank kriging prediction using low-rank approximation
    fn predict_fixed_rank(&self, query_points: &ArrayView2<F>) -> InterpolateResult<FastPredictionResult<F>> {
        // Ensure we have the low-rank components
        let (u, s, v) = match &self.low_rank_components {
            Some(components) => components,
            None => {
                return Err(InterpolateError::InvalidOperation(
                    "Low-rank components not pre-computed for FixedRank method".to_string()
                ));
            }
        };
        
        // Ensure we have the trend coefficients
        let trend_coeffs = match &self.trend_coeffs {
            Some(coeffs) => coeffs,
            None => {
                return Err(InterpolateError::InvalidOperation(
                    "Trend coefficients not pre-computed for FixedRank method".to_string()
                ));
            }
        };
        
        let n_query = query_points.shape()[0];
        let mut values = Array1::zeros(n_query);
        let mut variances = Array1::zeros(n_query);
        
        // Compute basis functions for query points
        let query_basis = create_basis_functions(query_points, self.trend_fn)?;
        
        // Compute cross-covariance matrix between query and training points
        let rank = u.shape()[1];
        let mut query_features = Array2::zeros((n_query, rank));
        
        // Project query points into low-rank feature space
        for i in 0..n_query {
            let query_point = query_points.slice(ndarray::s![i, ..]);
            
            // Compute projection
            for j in 0..rank {
                let feature = project_to_feature(&query_point, &self.points, j, &self.anisotropic_cov)?;
                query_features[[i, j]] = feature;
            }
        }
        
        // Compute predictions efficiently using low-rank structure
        for i in 0..n_query {
            // Compute trend component
            let mut trend = F::zero();
            for j in 0..query_basis.shape()[1] {
                trend = trend + trend_coeffs[j] * query_basis[[i, j]];
            }
            
            // Compute residual using low-rank approximation
            let query_feature = query_features.slice(ndarray::s![i, ..]);
            let projected = u.dot(&(s.mapv(|x| x.recip()) * v.t().dot(&self.values)));
            
            let residual = query_feature.dot(&projected);
            
            // Final prediction
            values[i] = trend + residual;
            
            // Approximate variance (simplified)
            let variance = self.anisotropic_cov.sigma_sq - 
                query_feature.dot(&s.mapv(|x| x.recip())) * query_feature.dot(&s.mapv(|x| x.recip()));
            
            variances[i] = if variance < F::zero() { F::zero() } else { variance };
        }
        
        Ok(FastPredictionResult {
            value: values,
            variance: variances,
            method: self.approx_method,
            computation_time_ms: None,
        })
    }
    
    /// Tapered kriging prediction using sparse matrices
    fn predict_tapered(&self, query_points: &ArrayView2<F>) -> InterpolateResult<FastPredictionResult<F>> {
        // Ensure we have the sparse components
        let (indices, values) = match &self.sparse_components {
            Some(components) => components,
            None => {
                return Err(InterpolateError::InvalidOperation(
                    "Sparse components not pre-computed for Tapering method".to_string()
                ));
            }
        };
        
        // Ensure we have the trend coefficients
        let trend_coeffs = match &self.trend_coeffs {
            Some(coeffs) => coeffs,
            None => {
                return Err(InterpolateError::InvalidOperation(
                    "Trend coefficients not pre-computed for Tapering method".to_string()
                ));
            }
        };
        
        let n_query = query_points.shape()[0];
        let mut pred_values = Array1::zeros(n_query);
        let mut pred_variances = Array1::zeros(n_query);
        
        // Extract taper range from method
        let taper_range = match self.approx_method {
            FastKrigingMethod::Tapering(range) => F::from_f64(range).unwrap(),
            _ => {
                return Err(InterpolateError::InvalidOperation(
                    "Invalid method type for tapered prediction".to_string()
                ));
            }
        };
        
        // Compute basis functions for query points
        let query_basis = create_basis_functions(query_points, self.trend_fn)?;
        
        // For each query point
        for i in 0..n_query {
            let query_point = query_points.slice(ndarray::s![i, ..]);
            
            // Compute trend component
            let mut trend = F::zero();
            for j in 0..query_basis.shape()[1] {
                trend = trend + trend_coeffs[j] * query_basis[[i, j]];
            }
            
            // Find training points within taper range
            let n_train = self.points.shape()[0];
            let mut nonzero_indices = Vec::new();
            let mut k_star = Vec::new();
            
            for j in 0..n_train {
                let dist = compute_anisotropic_distance(
                    &query_point,
                    &self.points.slice(ndarray::s![j, ..]),
                    &self.anisotropic_cov
                )?;
                
                if dist <= taper_range {
                    nonzero_indices.push(j);
                    k_star.push(compute_covariance(dist, &self.anisotropic_cov));
                }
            }
            
            // If no points within range, use trend only
            if nonzero_indices.is_empty() {
                pred_values[i] = trend;
                pred_variances[i] = self.anisotropic_cov.sigma_sq;
                continue;
            }
            
            // Create sparse vector for cross-covariance
            // This is a simplified sparse operation - a full implementation would 
            // use a proper sparse matrix library
            let n_nonzero = nonzero_indices.len();
            let mut alpha = Array1::zeros(n_nonzero);
            
            // Create a lookup map for faster access
            let mut row_indices: Vec<Vec<(usize, F)>> = vec![Vec::new(); self.points.shape()[0]];
            for (&(row, col), &val) in indices.iter().zip(values.iter()) {
                row_indices[row].push((col, val));
            }
            
            // For each training point with non-zero covariance
            for (idx, &j) in nonzero_indices.iter().enumerate() {
                // Find corresponding values in the sparse representation using the lookup
                let mut a_j = F::zero();
                
                // Use the precomputed lookup for this row
                for &(col, val) in &row_indices[j] {
                    // Multiply sparse row by residual vector
                    a_j = a_j + val * (self.values[col] - trend);
                }
                alpha[idx] = a_j;
            }
            
            // Compute prediction
            let mut residual = F::zero();
            for idx in 0..n_nonzero {
                residual = residual + k_star[idx] * alpha[idx];
            }
            
            // Final prediction
            pred_values[i] = trend + residual;
            
            // Compute approximate variance (simplified for sparse case)
            let mut variance = self.anisotropic_cov.sigma_sq;
            for idx in 0..n_nonzero {
                variance = variance - k_star[idx] * k_star[idx] / self.anisotropic_cov.sigma_sq;
            }
            
            pred_variances[i] = if variance < F::zero() { F::zero() } else { variance };
        }
        
        Ok(FastPredictionResult {
            value: pred_values,
            variance: pred_variances,
            method: self.approx_method,
            computation_time_ms: None,
        })
    }
    
    /// HODLR kriging prediction using hierarchical matrices
    fn predict_hodlr(&self, query_points: &ArrayView2<F>) -> InterpolateResult<FastPredictionResult<F>> {
        // Extract leaf size from method
        let leaf_size = match self.approx_method {
            FastKrigingMethod::HODLR(size) => size,
            _ => {
                return Err(InterpolateError::InvalidOperation(
                    "Invalid method type for HODLR prediction".to_string()
                ));
            }
        };
        
        // For HODLR, we divide the dataset into a hierarchical tree of blocks
        // For this implementation, we'll use a simplified approach with recursion
        
        let n_query = query_points.shape()[0];
        let mut values = Array1::zeros(n_query);
        let mut variances = Array1::zeros(n_query);
        
        // Compute basis functions for query points if needed for universal kriging
        let query_basis = create_basis_functions(query_points, self.trend_fn)?;
        
        // Create temporary trend coefficients if not pre-computed
        let trend_coeffs = match &self.trend_coeffs {
            Some(coeffs) => coeffs.clone(),
            None => {
                // We need to compute trend coefficients
                let basis_functions = match &self.basis_functions {
                    Some(basis) => basis,
                    None => {
                        // Create basis functions first
                        let basis = create_basis_functions(&self.points.view(), self.trend_fn)?;
                        compute_trend_coefficients(&self.points, &self.values, &basis, self.trend_fn)?
                    }
                };
                
                compute_trend_coefficients(
                    &self.points, &self.values, 
                    basis_functions, self.trend_fn
                )?
            }
        };
        
        // Recursion helper: Start with the full dataset
        let n_train = self.points.shape()[0];
        let mut train_indices: Vec<usize> = (0..n_train).collect();
        
        // For each query point
        for i in 0..n_query {
            let query_point = query_points.slice(ndarray::s![i, ..]);
            
            // Compute trend component
            let mut trend = F::zero();
            for j in 0..query_basis.shape()[1] {
                trend = trend + trend_coeffs[j] * query_basis[[i, j]];
            }
            
            // Compute prediction using HODLR approximation
            let residual = self.hodlr_predict_point(
                &query_point, 
                &train_indices,
                leaf_size,
                trend
            )?;
            
            // Store results
            values[i] = trend + residual;
            
            // Compute variance using a more accurate method for HODLR
            // This uses a simplified approximation based on the nearest points
            let query_point = query_points.slice(ndarray::s![i, ..]);
            let k_star = self.compute_hodlr_variance(&query_point, leaf_size)?;
            variances[i] = if k_star < F::zero() { F::zero() } else { k_star };
        }
        
        Ok(FastPredictionResult {
            value: values,
            variance: variances,
            method: self.approx_method,
            computation_time_ms: None,
        })
    }
    
    /// Compute more accurate variance estimation for HODLR method
    fn compute_hodlr_variance(
        &self,
        query_point: &ArrayView1<F>,
        leaf_size: usize,
    ) -> InterpolateResult<F> {
        // Find a set of nearby points to compute a local approximation of the variance
        let n_dims = query_point.len();
        let n_points = self.points.shape()[0];
        
        // Find k nearest neighbors for local approximation
        let max_local = std::cmp::min(leaf_size * 2, n_points);
        let mut distances = Vec::with_capacity(n_points);
        
        // Compute distances to all points
        for i in 0..n_points {
            let mut dist_sq = F::zero();
            for j in 0..n_dims {
                let diff = query_point[j] - self.points[[i, j]];
                dist_sq = dist_sq + diff * diff;
            }
            distances.push((i, dist_sq.sqrt()));
        }
        
        // Sort by distance
        distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
        
        // Take closest max_local points
        let local_indices: Vec<usize> = distances.iter()
            .take(max_local)
            .map(|&(idx, _)| idx)
            .collect();
            
        // Build local covariance matrix
        let n_local = local_indices.len();
        let mut cov_matrix = Array2::zeros((n_local, n_local));
        let mut k_star = Array1::zeros(n_local);
        
        // Compute covariance matrix and cross-covariance vector
        for i in 0..n_local {
            for j in 0..n_local {
                let idx_i = local_indices[i];
                let idx_j = local_indices[j];
                
                if i == j {
                    cov_matrix[[i, j]] = self.anisotropic_cov.sigma_sq + self.anisotropic_cov.nugget;
                } else {
                    let dist = compute_anisotropic_distance(
                        &self.points.slice(ndarray::s![idx_i, ..]),
                        &self.points.slice(ndarray::s![idx_j, ..]),
                        &self.anisotropic_cov
                    )?;
                    cov_matrix[[i, j]] = compute_covariance(dist, &self.anisotropic_cov);
                }
            }
            
            // Also compute k* (covariance between query point and training points)
            let dist = compute_anisotropic_distance(
                query_point,
                &self.points.slice(ndarray::s![local_indices[i], ..]),
                &self.anisotropic_cov
            )?;
            k_star[i] = compute_covariance(dist, &self.anisotropic_cov);
        }
        
        // Compute variance using local approximation: σ² - k*ᵀ K⁻¹ k*
        // To avoid numerically unstable matrix inversion, solve K α = k*
        // Then variance = σ² - k*ᵀ α
        
        // Check if the covariance matrix is well-conditioned
        #[cfg(feature = "linalg")]
        let alpha = #[cfg(feature = "linalg")]
        match cov_matrix.solve(&k_star)
        
        #[cfg(not(feature = "linalg"))]
        {
            // Fallback implementation when linalg is not available
            // Simple diagonal approximation
            let mut result = Array1::zeros(k_star.len());
            // Use simple approximation
            result
        } {
            Ok(a) => a,
            Err(_) => {
                // Fallback to diagonal approximation if matrix is ill-conditioned
                return Ok(self.anisotropic_cov.sigma_sq * F::from_f64(0.8).unwrap());
            }
        };
        
        #[cfg(not(feature = "linalg"))]
        {
            // Simple approximation when linalg is not available
            return Ok(self.anisotropic_cov.sigma_sq * F::from_f64(0.8).unwrap());
        }
        
        // Compute kriging variance
        let variance = self.anisotropic_cov.sigma_sq - k_star.dot(&alpha);
        
        // Ensure we don't return negative variance due to numerical issues
        Ok(if variance < F::zero() { F::zero() } else { variance })
    }
    
    /// Helper function for HODLR prediction of a single point
    fn hodlr_predict_point(
        &self,
        query_point: &ArrayView1<F>,
        indices: &[usize],
        leaf_size: usize,
        trend: F,
    ) -> InterpolateResult<F> {
        // If we're at a leaf node or only have a few points, solve directly
        if indices.len() <= leaf_size {
            // Use direct solution for small blocks
            let n_points = indices.len();
            
            // Extract subset of points
            let mut block_points = Array2::zeros((n_points, query_point.len()));
            let mut block_values = Array1::zeros(n_points);
            
            for (i, &idx) in indices.iter().enumerate() {
                block_points.slice_mut(ndarray::s![i, ..])
                    .assign(&self.points.slice(ndarray::s![idx, ..]));
                block_values[i] = self.values[idx] - trend; // Use residuals
            }
            
            // Compute covariance matrix for this block
            let mut cov_matrix = Array2::zeros((n_points, n_points));
            for i in 0..n_points {
                for j in 0..n_points {
                    if i == j {
                        cov_matrix[[i, j]] = self.anisotropic_cov.sigma_sq + self.anisotropic_cov.nugget;
                    } else {
                        let dist = compute_anisotropic_distance(
                            &block_points.slice(ndarray::s![i, ..]),
                            &block_points.slice(ndarray::s![j, ..]),
                            &self.anisotropic_cov
                        )?;
                        cov_matrix[[i, j]] = compute_covariance(dist, &self.anisotropic_cov);
                    }
                }
            }
            
            // Compute cross-covariance vector
            let mut k_star = Array1::zeros(n_points);
            for i in 0..n_points {
                let dist = compute_anisotropic_distance(
                    query_point,
                    &block_points.slice(ndarray::s![i, ..]),
                    &self.anisotropic_cov
                )?;
                k_star[i] = compute_covariance(dist, &self.anisotropic_cov);
            }
            
            // Solve the system for weights
            #[cfg(feature = "linalg")]
            let weights = #[cfg(feature = "linalg")]
        match cov_matrix.solve(&block_values)
        
        #[cfg(not(feature = "linalg"))]
        {
            // Fallback implementation when linalg is not available
            // Simple diagonal approximation
            let mut result = Array1::zeros(block_values.len());
            // Use simple approximation
            result
        } {
                Ok(w) => w,
                Err(_) => {
                    // Fallback to diagonal approximation
                    let mut w = Array1::zeros(n_points);
                    for i in 0..n_points {
                        w[i] = block_values[i] / (self.anisotropic_cov.sigma_sq + self.anisotropic_cov.nugget);
                    }
                    w
                }
            };
            
            #[cfg(not(feature = "linalg"))]
            let weights = {
                // Simple diagonal approximation when linalg not available
                let mut w = Array1::zeros(n_points);
                for i in 0..n_points {
                    w[i] = block_values[i] / (self.anisotropic_cov.sigma_sq + self.anisotropic_cov.nugget);
                }
                w
            };
            
            // Compute prediction
            let prediction = k_star.dot(&weights);
            
            return Ok(prediction);
        }
        
        // Otherwise, partition the points into near and far sets
        // For simplicity, we split on the dimension with largest extent
        let n_dims = self.points.shape()[1];
        let mut max_extent = F::zero();
        let mut split_dim = 0;
        
        for d in 0..n_dims {
            let mut min_val = F::infinity();
            let mut max_val = F::neg_infinity();
            
            for &idx in indices {
                let val = self.points[[idx, d]];
                if val < min_val {
                    min_val = val;
                }
                if val > max_val {
                    max_val = val;
                }
            }
            
            let extent = max_val - min_val;
            if extent > max_extent {
                max_extent = extent;
                split_dim = d;
            }
        }
        
        // Find median value for splitting
        let mut values_at_dim: Vec<F> = indices.iter()
            .map(|&idx| self.points[[idx, split_dim]])
            .collect();
        values_at_dim.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        
        let median = if values_at_dim.len() % 2 == 0 {
            (values_at_dim[values_at_dim.len() / 2 - 1] + values_at_dim[values_at_dim.len() / 2]) * F::from_f64(0.5).unwrap()
        } else {
            values_at_dim[values_at_dim.len() / 2]
        };
        
        // Partition into near and far sets
        let query_val = query_point[split_dim];
        let (near_indices, far_indices): (Vec<usize>, Vec<usize>) = indices.iter()
            .map(|&idx| idx)
            .partition(|&idx| {
                let dist = (self.points[[idx, split_dim]] - query_val).abs();
                dist <= max_extent * F::from_f64(0.5).unwrap()
            });
        
        // Recursively compute prediction for near points
        let near_prediction = if !near_indices.is_empty() {
            self.hodlr_predict_point(query_point, &near_indices, leaf_size, trend)?
        } else {
            F::zero()
        };
        
        // For far points, use low-rank approximation based on a few sample points
        let far_prediction = if !far_indices.is_empty() {
            // Select a subsample of far points for low-rank approximation
            let n_samples = std::cmp::min(
                far_indices.len(),
                std::cmp::max(5, far_indices.len() / 10)
            );
            
            let step = if n_samples >= far_indices.len() {
                1
            } else {
                far_indices.len() / n_samples
            };
            
            let mut sample_indices = Vec::with_capacity(n_samples);
            for i in (0..far_indices.len()).step_by(step) {
                if sample_indices.len() < n_samples {
                    sample_indices.push(far_indices[i]);
                } else {
                    break;
                }
            }
            
            // Compute a simplified low-rank approximation for the far points
            self.hodlr_predict_point(query_point, &sample_indices, leaf_size, trend)? 
            * F::from_f64(far_indices.len() as f64 / sample_indices.len() as f64).unwrap()
        } else {
            F::zero()
        };
        
        // Combine results with appropriate weighting
        let total_points = near_indices.len() + far_indices.len();
        let near_weight = F::from_f64(near_indices.len() as f64 / total_points as f64).unwrap();
        let far_weight = F::from_f64(far_indices.len() as f64 / total_points as f64).unwrap();
        
        Ok(near_weight * near_prediction + far_weight * far_prediction)
    }
}

/// Create basis functions for the trend model
fn create_basis_functions<F: Float + FromPrimitive>(
    points: &ArrayView2<F>,
    trend_fn: TrendFunction,
) -> InterpolateResult<Array2<F>> {
    let n_points = points.shape()[0];
    let n_dims = points.shape()[1];
    
    match trend_fn {
        TrendFunction::Constant => {
            // Just a constant term: X = [1, 1, ..., 1]
            let mut basis = Array2::zeros((n_points, 1));
            for i in 0..n_points {
                basis[[i, 0]] = F::one();
            }
            Ok(basis)
        },
        TrendFunction::Linear => {
            // Constant term + linear terms: X = [1, x1, x2, ..., xn]
            let n_basis = n_dims + 1;
            let mut basis = Array2::zeros((n_points, n_basis));
            
            // Constant term
            for i in 0..n_points {
                basis[[i, 0]] = F::one();
            }
            
            // Linear terms
            for i in 0..n_points {
                for j in 0..n_dims {
                    basis[[i, j + 1]] = points[[i, j]];
                }
            }
            
            Ok(basis)
        },
        TrendFunction::Quadratic => {
            // Constant + linear + quadratic terms
            // X = [1, x1, x2, ..., xn, x1^2, x1*x2, ..., xn^2]
            
            // Number of basis functions:
            // 1 (constant) + n_dims (linear) + n_dims*(n_dims+1)/2 (quadratic)
            let n_quad_terms = n_dims * (n_dims + 1) / 2;
            let n_basis = 1 + n_dims + n_quad_terms;
            
            let mut basis = Array2::zeros((n_points, n_basis));
            
            // Constant term
            for i in 0..n_points {
                basis[[i, 0]] = F::one();
            }
            
            // Linear terms
            for i in 0..n_points {
                for j in 0..n_dims {
                    basis[[i, j + 1]] = points[[i, j]];
                }
            }
            
            // Quadratic terms
            let mut term_idx = 1 + n_dims;
            for i in 0..n_points {
                for j in 0..n_dims {
                    for k in j..n_dims {
                        if j == k {
                            // x_j^2
                            basis[[i, term_idx]] = points[[i, j]] * points[[i, j]];
                        } else {
                            // x_j * x_k
                            basis[[i, term_idx]] = points[[i, j]] * points[[i, k]];
                        }
                        term_idx += 1;
                    }
                }
            }
            
            Ok(basis)
        },
        TrendFunction::Custom(_) => {
            // For custom basis functions, default to constant
            let mut basis = Array2::zeros((n_points, 1));
            for i in 0..n_points {
                basis[[i, 0]] = F::one();
            }
            Ok(basis)
        },
    }
}

/// Compute trend coefficients using least squares
fn compute_trend_coefficients<F: Float + FromPrimitive>(
    points: &Array2<F>,
    values: &Array1<F>,
    basis_functions: &Array2<F>,
    trend_fn: TrendFunction,
) -> InterpolateResult<Array1<F>> {
    // Basic least squares: β = (X'X)^(-1) X'y
    let xtx = basis_functions.t().dot(basis_functions);
    let xty = basis_functions.t().dot(values);
    
    #[cfg(feature = "linalg")]
    match xtx.solve(&xty) {
        Ok(coeffs) => Ok(coeffs),
        Err(_) => {
            // Fallback to simple mean for constant trend
            let mut coeffs = Array1::zeros(basis_functions.shape()[1]);
            coeffs[0] = values.mean().unwrap_or(F::zero());
            Ok(coeffs)
        }
    }
    
    #[cfg(not(feature = "linalg"))]
    {
        // When linalg is not available, use simple mean for constant trend
        let mut coeffs = Array1::zeros(basis_functions.shape()[1]);
        coeffs[0] = values.mean().unwrap_or(F::zero());
        Ok(coeffs)
    }
}

/// Find the k nearest neighbors to a query point
fn find_nearest_neighbors<F: Float + FromPrimitive>(
    query_point: &ArrayView1<F>,
    points: &Array2<F>,
    max_neighbors: usize,
    radius_multiplier: F,
) -> InterpolateResult<(Vec<usize>, Vec<F>)> {
    let n_points = points.shape()[0];
    let n_dims = points.shape()[1];
    
    // Calculate distances
    let mut distances = Vec::with_capacity(n_points);
    for i in 0..n_points {
        let mut dist_sq = F::zero();
        for j in 0..n_dims {
            let diff = query_point[j] - points[[i, j]];
            dist_sq = dist_sq + diff * diff;
        }
        distances.push((i, dist_sq.sqrt()));
    }
    
    // Sort by distance
    distances.sort_by(|a, b| {
        a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)
    });
    
    // Determine search radius based on max_neighbors
    let radius = if distances.len() > max_neighbors {
        distances[max_neighbors - 1].1 * radius_multiplier
    } else {
        // If we have fewer points than max_neighbors, use all points
        F::infinity()
    };
    
    // Select points within radius, up to max_neighbors
    let mut indices = Vec::with_capacity(max_neighbors);
    let mut selected_distances = Vec::with_capacity(max_neighbors);
    
    for (idx, dist) in distances {
        if dist <= radius && indices.len() < max_neighbors {
            indices.push(idx);
            selected_distances.push(dist);
        }
    }
    
    Ok((indices, selected_distances))
}

/// Compute anisotropic distance between two points
fn compute_anisotropic_distance<F: Float + FromPrimitive>(
    p1: &ArrayView1<F>,
    p2: &ArrayView1<F>,
    anisotropic_cov: &AnisotropicCovariance<F>,
) -> InterpolateResult<F> {
    let n_dims = p1.len();
    
    if n_dims != anisotropic_cov.length_scales.len() {
        return Err(InterpolateError::DimensionMismatch(
            "Number of length scales must match dimension of points".to_string()
        ));
    }
    
    // Simple anisotropic distance (no rotation)
    let mut sum_sq = F::zero();
    for i in 0..n_dims {
        let diff = (p1[i] - p2[i]) / anisotropic_cov.length_scales[i];
        sum_sq = sum_sq + diff * diff;
    }
    
    Ok(sum_sq.sqrt())
}

/// Evaluate the covariance function
fn compute_covariance<F: Float + FromPrimitive>(
    r: F,
    anisotropic_cov: &AnisotropicCovariance<F>,
) -> F {
    match anisotropic_cov.cov_fn {
        CovarianceFunction::SquaredExponential => {
            // σ² exp(-r²)
            anisotropic_cov.sigma_sq * (-r * r).exp()
        }
        CovarianceFunction::Exponential => {
            // σ² exp(-r)
            anisotropic_cov.sigma_sq * (-r).exp()
        }
        CovarianceFunction::Matern32 => {
            // σ² (1 + √3r) exp(-√3r)
            let sqrt3_r = F::from_f64(3.0).unwrap().sqrt() * r;
            anisotropic_cov.sigma_sq * (F::one() + sqrt3_r) * (-sqrt3_r).exp()
        }
        CovarianceFunction::Matern52 => {
            // σ² (1 + √5r + 5r²/3) exp(-√5r)
            let sqrt5_r = F::from_f64(5.0).unwrap().sqrt() * r;
            let factor = F::one()
                + sqrt5_r
                + F::from_f64(5.0).unwrap() * r * r / F::from_f64(3.0).unwrap();
            anisotropic_cov.sigma_sq * factor * (-sqrt5_r).exp()
        }
        CovarianceFunction::RationalQuadratic => {
            // σ² (1 + r²/(2α))^(-α)
            let alpha = anisotropic_cov.extra_params;
            let r_sq_div_2a = r * r / (F::from_f64(2.0).unwrap() * alpha);
            anisotropic_cov.sigma_sq * (F::one() + r_sq_div_2a).powf(-alpha)
        }
    }
}

/// Compute low-rank approximation of the covariance matrix
fn compute_low_rank_approximation<F: Float + FromPrimitive>(
    points: &Array2<F>,
    anisotropic_cov: &AnisotropicCovariance<F>,
    rank: usize,
) -> InterpolateResult<(Array2<F>, Array1<F>, Array2<F>)> {
    // In a full implementation, you would use Nyström method or randomized SVD
    // For this simplified example, we'll compute a small sample covariance matrix
    
    let n_points = points.shape()[0];
    let max_sample = std::cmp::min(rank * 2, n_points);
    
    // Use a subset of points
    let mut sample_indices = Vec::with_capacity(max_sample);
    let step = n_points / max_sample;
    for i in 0..max_sample {
        sample_indices.push(i * step);
    }
    
    let mut sample_cov = Array2::zeros((max_sample, max_sample));
    
    // Compute sample covariance matrix
    for i in 0..max_sample {
        for j in 0..max_sample {
            let idx_i = sample_indices[i];
            let idx_j = sample_indices[j];
            
            if i == j {
                sample_cov[[i, j]] = anisotropic_cov.sigma_sq + anisotropic_cov.nugget;
            } else {
                let dist = compute_anisotropic_distance(
                    &points.slice(ndarray::s![idx_i, ..]),
                    &points.slice(ndarray::s![idx_j, ..]),
                    anisotropic_cov
                )?;
                sample_cov[[i, j]] = compute_covariance(dist, anisotropic_cov);
            }
        }
    }
    
    // Compute SVD of sample covariance
    let (u, s, vt) = #[cfg(feature = "linalg")]
        match sample_cov.svd(true, true)
        
        #[cfg(not(feature = "linalg"))]
        {
            // Fallback for SVD when linalg is not available
            return Err(InterpolateError::UnsupportedOperation(
                "SVD requires the linalg feature to be enabled".to_string()
            ));
        } {
        Ok((u, s, vt)) => (u, s, vt),
        Err(_) => {
            return Err(InterpolateError::ComputationError(
                "SVD computation failed for low-rank approximation".to_string()
            ));
        }
    };
    
    // Truncate to desired rank
    let actual_rank = std::cmp::min(rank, s.len());
    let u_r = u.slice(ndarray::s![.., 0..actual_rank]).to_owned();
    let s_r = s.slice(ndarray::s![0..actual_rank]).to_owned();
    let v_r = vt.slice(ndarray::s![0..actual_rank, ..]).t().to_owned();
    
    Ok((u_r, s_r, v_r))
}

/// Compute tapered covariance representation
fn compute_tapered_covariance<F: Float + FromPrimitive>(
    points: &Array2<F>,
    anisotropic_cov: &AnisotropicCovariance<F>,
    taper_range: F,
) -> InterpolateResult<(Vec<(usize, usize)>, Vec<F>)> {
    let n_points = points.shape()[0];
    let mut indices = Vec::new();
    let mut values = Vec::new();
    
    // Pre-allocate capacity for indices and values (estimating size)
    let estimated_nnz = n_points + (n_points * n_points / 4); // Rough estimate
    indices.reserve(estimated_nnz);
    values.reserve(estimated_nnz);
    
    // Compute sparse representation with tapering more efficiently
    for i in 0..n_points {
        // Diagonal element 
        let diagonal_value = anisotropic_cov.sigma_sq + anisotropic_cov.nugget;
        indices.push((i, i));
        values.push(diagonal_value);
        
        // Off-diagonal elements (lower triangular)
        for j in 0..i {  // Iterate only through lower triangular part
            // Compute distance
            let dist = compute_anisotropic_distance(
                &points.slice(ndarray::s![i, ..]),
                &points.slice(ndarray::s![j, ..]),
                anisotropic_cov
            )?;
            
            // Apply tapering
            if dist <= taper_range {
                let value = compute_covariance(dist, anisotropic_cov);
                
                // Add entries in sorted order (row, col) to allow for faster lookups
                indices.push((i, j));
                values.push(value);
                
                indices.push((j, i));
                values.push(value);
            }
        }
    }
    
    Ok((indices, values))
}

/// Project a point onto a feature in the feature space
fn project_to_feature<F: Float + FromPrimitive>(
    query_point: &ArrayView1<F>,
    points: &Array2<F>,
    feature_idx: usize,
    anisotropic_cov: &AnisotropicCovariance<F>,
) -> InterpolateResult<F> {
    let n_points = points.shape()[0];
    
    // In a full implementation, this would use the eigenvectors
    // For this simplified example, we'll use landmark points
    
    // Use a landmark point as basis for the feature
    let landmark_idx = feature_idx % n_points;
    let landmark = points.slice(ndarray::s![landmark_idx, ..]);
    
    // Project by computing covariance with landmark
    let dist = compute_anisotropic_distance(
        query_point,
        &landmark,
        anisotropic_cov
    )?;
    
    let projection = compute_covariance(dist, anisotropic_cov);
    
    Ok(projection)
}

/// Creates a new FastKriging model with local approximation
///
/// This convenience function provides a simpler interface for creating
/// a FastKriging model using the local approximation method, which is
/// suitable for most large datasets.
///
/// # Arguments
///
/// * `points` - Coordinates of sample points (n_points × n_dimensions)
/// * `values` - Values at sample points (n_points)
/// * `cov_fn` - Covariance function to use
/// * `length_scale` - Isotropic length scale parameter
/// * `max_neighbors` - Maximum number of neighbors to use
///
/// # Returns
///
/// A FastKriging interpolator with local approximation method
///
/// # Example
///
/// ```rust,no_run
/// use ndarray::{Array1, Array2};
/// use scirs2_interpolate::advanced::fast_kriging::{
///     make_local_kriging, CovarianceFunction
/// };
///
/// // Create sample data
/// let points = Array2::<f64>::zeros((1000, 2));
/// let values = Array1::<f64>::zeros(1000);
///
/// // Create a local kriging model
/// let kriging = make_local_kriging(
///     &points.view(),
///     &values.view(),
///     CovarianceFunction::Matern52,
///     1.0,  // length_scale
///     50    // max_neighbors
/// ).unwrap();
///
/// // Make a prediction
/// let query_point = Array2::<f64>::zeros((1, 2));
/// let pred = kriging.predict(&query_point.view()).unwrap();
/// ```
pub fn make_local_kriging<F: Float + FromPrimitive + Debug + Add<Output = F> + Sub<Output = F> + Mul<Output = F> + Div<Output = F>>(
    points: &ArrayView2<F>,
    values: &ArrayView1<F>,
    cov_fn: CovarianceFunction,
    length_scale: F,
    max_neighbors: usize,
) -> InterpolateResult<FastKriging<F>> {
    let mut builder = FastKriging::builder()
        .points(points.to_owned())
        .values(values.to_owned())
        .covariance_function(cov_fn)
        .approximation_method(FastKrigingMethod::Local)
        .max_neighbors(max_neighbors);
        
    // Set the length scale
    builder = builder.length_scale(length_scale);
    
    builder.build()
}

/// Creates a new FastKriging model with fixed rank approximation
///
/// The fixed rank approximation provides significant speedup for large
/// datasets by using a low-rank representation of the covariance matrix.
///
/// # Arguments
///
/// * `points` - Coordinates of sample points (n_points × n_dimensions)
/// * `values` - Values at sample points (n_points)
/// * `cov_fn` - Covariance function to use
/// * `length_scale` - Isotropic length scale parameter
/// * `rank` - Rank of the low-rank approximation (smaller = faster, less accurate)
///
/// # Returns
///
/// A FastKriging interpolator with fixed rank approximation method
///
/// # Example
///
/// ```rust,no_run
/// use ndarray::{Array1, Array2};
/// use scirs2_interpolate::advanced::fast_kriging::{
///     make_fixed_rank_kriging, CovarianceFunction
/// };
///
/// // Create sample data
/// let points = Array2::<f64>::zeros((5000, 2));
/// let values = Array1::<f64>::zeros(5000);
///
/// // Create a fixed rank kriging model
/// let kriging = make_fixed_rank_kriging(
///     &points.view(),
///     &values.view(),
///     CovarianceFunction::Matern52,
///     1.0,  // length_scale
///     100   // rank
/// ).unwrap();
///
/// // Make a prediction
/// let query_point = Array2::<f64>::zeros((1, 2));
/// let pred = kriging.predict(&query_point.view()).unwrap();
/// ```
pub fn make_fixed_rank_kriging<F: Float + FromPrimitive + Debug + Add<Output = F> + Sub<Output = F> + Mul<Output = F> + Div<Output = F>>(
    points: &ArrayView2<F>,
    values: &ArrayView1<F>,
    cov_fn: CovarianceFunction,
    length_scale: F,
    rank: usize,
) -> InterpolateResult<FastKriging<F>> {
    let mut builder = FastKriging::builder()
        .points(points.to_owned())
        .values(values.to_owned())
        .covariance_function(cov_fn)
        .approximation_method(FastKrigingMethod::FixedRank(rank));
        
    // Set the length scale
    builder = builder.length_scale(length_scale);
    
    builder.build()
}

/// Creates a new FastKriging model with HODLR (Hierarchical Off-Diagonal Low-Rank) approximation
///
/// The HODLR approximation uses a hierarchical approach to partition the dataset
/// and approximate far-field interactions with low-rank representations.
///
/// # Arguments
///
/// * `points` - Coordinates of sample points (n_points × n_dimensions)
/// * `values` - Values at sample points (n_points)
/// * `cov_fn` - Covariance function to use
/// * `length_scale` - Isotropic length scale parameter
/// * `leaf_size` - Maximum size of leaf nodes in the hierarchical decomposition
///
/// # Returns
///
/// A FastKriging interpolator with HODLR approximation method
///
/// # Example
///
/// ```rust,no_run
/// use ndarray::{Array1, Array2};
/// use scirs2_interpolate::advanced::fast_kriging::{
///     make_hodlr_kriging, CovarianceFunction
/// };
///
/// // Create sample data
/// let points = Array2::<f64>::zeros((5000, 2));
/// let values = Array1::<f64>::zeros(5000);
///
/// // Create a HODLR kriging model
/// let kriging = make_hodlr_kriging(
///     &points.view(),
///     &values.view(),
///     CovarianceFunction::Matern52,
///     1.0,  // length_scale
///     64    // leaf_size
/// ).unwrap();
///
/// // Make a prediction
/// let query_point = Array2::<f64>::zeros((1, 2));
/// let pred = kriging.predict(&query_point.view()).unwrap();
/// ```
pub fn make_hodlr_kriging<F: Float + FromPrimitive + Debug + Add<Output = F> + Sub<Output = F> + Mul<Output = F> + Div<Output = F>>(
    points: &ArrayView2<F>,
    values: &ArrayView1<F>,
    cov_fn: CovarianceFunction,
    length_scale: F,
    leaf_size: usize,
) -> InterpolateResult<FastKriging<F>> {
    let mut builder = FastKriging::builder()
        .points(points.to_owned())
        .values(values.to_owned())
        .covariance_function(cov_fn)
        .approximation_method(FastKrigingMethod::HODLR(leaf_size));
        
    // Set the length scale
    builder = builder.length_scale(length_scale);
    
    builder.build()
}

/// Creates a new FastKriging model with covariance tapering
///
/// The tapering approach introduces sparsity in the covariance matrix
/// by setting small values to zero, enabling efficient sparse matrix operations.
///
/// # Arguments
///
/// * `points` - Coordinates of sample points (n_points × n_dimensions)
/// * `values` - Values at sample points (n_points)
/// * `cov_fn` - Covariance function to use
/// * `length_scale` - Isotropic length scale parameter
/// * `taper_range` - Distance beyond which covariances are set to zero
///
/// # Returns
///
/// A FastKriging interpolator with tapering approximation method
///
/// # Example
///
/// ```rust,no_run
/// use ndarray::{Array1, Array2};
/// use scirs2_interpolate::advanced::fast_kriging::{
///     make_tapered_kriging, CovarianceFunction
/// };
///
/// // Create sample data
/// let points = Array2::<f64>::zeros((2000, 2));
/// let values = Array1::<f64>::zeros(2000);
///
/// // Create a tapered kriging model
/// let kriging = make_tapered_kriging(
///     &points.view(),
///     &values.view(),
///     CovarianceFunction::Matern52,
///     1.0,  // length_scale
///     2.5   // taper_range
/// ).unwrap();
///
/// // Make a prediction
/// let query_point = Array2::<f64>::zeros((1, 2));
/// let pred = kriging.predict(&query_point.view()).unwrap();
/// ```
pub fn make_tapered_kriging<F: Float + FromPrimitive + Debug + Add<Output = F> + Sub<Output = F> + Mul<Output = F> + Div<Output = F>>(
    points: &ArrayView2<F>,
    values: &ArrayView1<F>,
    cov_fn: CovarianceFunction,
    length_scale: F,
    taper_range: f64,
) -> InterpolateResult<FastKriging<F>> {
    let mut builder = FastKriging::builder()
        .points(points.to_owned())
        .values(values.to_owned())
        .covariance_function(cov_fn)
        .approximation_method(FastKrigingMethod::Tapering(taper_range));
        
    // Set the length scale
    builder = builder.length_scale(length_scale);
    
    builder.build()
}

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

    #[test]
    fn test_fast_kriging_builder() {
        // Create 2D points
        let points = Array2::from_shape_vec(
            (5, 2),
            vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5],
        )
        .unwrap();

        // Create values at those points
        let values = array![0.0, 1.0, 1.0, 2.0, 1.0];

        // Create a fast kriging interpolator with local approximation
        let kriging = FastKriging::builder()
            .points(points.clone())
            .values(values.clone())
            .covariance_function(CovarianceFunction::SquaredExponential)
            .approximation_method(FastKrigingMethod::Local)
            .max_neighbors(3)
            .build()
            .unwrap();

        // Test prediction at a single point
        let test_point = Array2::from_shape_vec((1, 2), vec![0.5, 0.0]).unwrap();
        let result = kriging.predict(&test_point.view()).unwrap();

        // Prediction should be approximately 0.5 (halfway between 0 and 1)
        // Using a larger epsilon due to the approximation
        assert!((result.value[0] - 0.5).abs() < 0.3);
    }
}