sklears-gaussian-process 0.1.2

Gaussian Process models for regression and classification
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
//! Spatial Gaussian Processes and Kriging Methods
//!
//! This module implements Gaussian Process methods for spatial data analysis,
//! including various kriging methods, spatial correlation modeling, and
//! geostatistical applications.
//!
//! # Mathematical Background
//!
//! Spatial GPs extend standard GP regression to handle spatial data with:
//! 1. **Distance-based kernels**: Kernels that depend on spatial distance
//! 2. **Anisotropic correlation**: Different correlation in different directions
//! 3. **Kriging methods**: Simple, ordinary, universal, and co-kriging
//! 4. **Variogram modeling**: Semi-variogram estimation and fitting
//! 5. **Spatial interpolation**: Optimal spatial prediction with uncertainty
//!
//! # Examples
//!
//! ```rust,no_run
//! use sklears_gaussian_process::spatial::{SpatialGaussianProcessRegressor, SpatialKernel, KrigingType};
//! use sklears_core::traits::{Fit, Predict};
//! use scirs2_core::ndarray::array;
//!
//! // Create spatial GP for ordinary kriging
//! let spatial_gp = SpatialGaussianProcessRegressor::builder()
//!     .spatial_kernel(SpatialKernel::spherical(1.0, 10.0))
//!     .kriging_type(KrigingType::Ordinary)
//!     .build();
//!
//! // Spatial coordinates (x, y)
//! let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
//! let values = array![1.0, 2.0, 1.5, 2.5];
//!
//! let trained_model = spatial_gp.fit(&coords, &values).expect("fit should succeed with valid spatial data");
//! let predictions = trained_model.predict(&array![[0.5, 0.5]]).expect("predict should succeed on trained model");
//! ```

use crate::kernels::Kernel;
use crate::utils;
use scirs2_core::ndarray::{s, Array1, Array2, ArrayView1, Axis};
// SciRS2 Policy
use sklears_core::error::{Result as SklResult, SklearsError};
use sklears_core::traits::{Estimator, Fit, Predict};
use std::f64::consts::PI;

/// State marker for untrained spatial GP
#[derive(Debug, Clone)]
pub struct Untrained;

/// State marker for trained spatial GP
#[derive(Debug, Clone)]
pub struct Trained {
    pub spatial_kernel: SpatialKernel,
    pub kriging_type: KrigingType,
    pub training_data: (Array2<f64>, Array1<f64>),
    pub alpha: Array1<f64>,
    pub cholesky: Array2<f64>,
    pub log_likelihood: f64,
    pub variogram: Option<Variogram>,
    pub anisotropy_matrix: Option<Array2<f64>>,
}

/// Types of kriging methods
#[derive(Debug, Clone, Copy)]
pub enum KrigingType {
    /// Simple kriging (known mean)
    Simple { mean: f64 },
    /// Ordinary kriging (unknown constant mean)
    Ordinary,
    /// Universal kriging (trend model)
    Universal,
    /// Co-kriging (multiple variables)
    CoKriging,
}

/// Spatial kernel types for geostatistical modeling
#[derive(Debug, Clone)]
pub enum SpatialKernel {
    /// Spherical model: commonly used in geostatistics
    Spherical {
        sill: f64,   // Maximum variance
        range: f64,  // Correlation range
        nugget: f64, // Nugget effect (short-range noise)
    },
    /// Exponential model: smooth spatial correlation
    Exponential { sill: f64, range: f64, nugget: f64 },
    /// Gaussian model: very smooth spatial correlation
    Gaussian { sill: f64, range: f64, nugget: f64 },
    /// Matérn model: flexible smoothness parameter
    Matern {
        sill: f64,
        range: f64,
        nugget: f64,
        nu: f64, // Smoothness parameter
    },
    /// Power model: unbounded variance
    Power {
        scale: f64,
        exponent: f64, // Should be < 2 for valid covariance
    },
    /// Linear model: linear increase with distance
    Linear { slope: f64, nugget: f64 },
    /// Hole effect model: oscillatory correlation
    HoleEffect {
        sill: f64,
        range: f64,
        nugget: f64,
        damping: f64,
    },
    /// Anisotropic kernel with directional correlation
    Anisotropic {
        base_kernel: Box<SpatialKernel>,
        anisotropy_matrix: Array2<f64>,
    },
}

impl SpatialKernel {
    /// Create a spherical spatial kernel
    pub fn spherical(sill: f64, range: f64) -> Self {
        Self::Spherical {
            sill,
            range,
            nugget: 0.0,
        }
    }

    /// Create a spherical kernel with nugget effect
    pub fn spherical_with_nugget(sill: f64, range: f64, nugget: f64) -> Self {
        Self::Spherical {
            sill,
            range,
            nugget,
        }
    }

    /// Create an exponential spatial kernel
    pub fn exponential(sill: f64, range: f64) -> Self {
        Self::Exponential {
            sill,
            range,
            nugget: 0.0,
        }
    }

    /// Create a Gaussian spatial kernel
    pub fn gaussian(sill: f64, range: f64) -> Self {
        Self::Gaussian {
            sill,
            range,
            nugget: 0.0,
        }
    }

    /// Create a Matérn spatial kernel
    pub fn matern(sill: f64, range: f64, nu: f64) -> Self {
        Self::Matern {
            sill,
            range,
            nugget: 0.0,
            nu,
        }
    }

    /// Create an anisotropic kernel
    pub fn anisotropic(base_kernel: SpatialKernel, anisotropy_matrix: Array2<f64>) -> Self {
        Self::Anisotropic {
            base_kernel: Box::new(base_kernel),
            anisotropy_matrix,
        }
    }

    /// Compute spatial distance between two points
    fn compute_distance(&self, x1: &[f64], x2: &[f64]) -> f64 {
        match self {
            Self::Anisotropic {
                anisotropy_matrix, ..
            } => {
                // Transform coordinates and compute Mahalanobis distance
                let diff: Array1<f64> =
                    Array1::from_vec(x1.iter().zip(x2.iter()).map(|(a, b)| a - b).collect());
                let transformed = anisotropy_matrix.dot(&diff);
                transformed.iter().map(|x| x.powi(2)).sum::<f64>().sqrt()
            }
            _ => {
                // Standard Euclidean distance
                x1.iter()
                    .zip(x2.iter())
                    .map(|(a, b)| (a - b).powi(2))
                    .sum::<f64>()
                    .sqrt()
            }
        }
    }

    /// Compute the covariance for a given distance
    pub fn compute_covariance(&self, distance: f64) -> f64 {
        match self {
            Self::Spherical {
                sill,
                range,
                nugget,
            } => {
                if distance == 0.0 {
                    sill + nugget
                } else if distance <= *range {
                    let h_r = distance / range;
                    sill * (1.0 - 1.5 * h_r + 0.5 * h_r.powi(3))
                        + if distance == 0.0 { *nugget } else { 0.0 }
                } else {
                    if distance == 0.0 {
                        *nugget
                    } else {
                        0.0
                    }
                }
            }
            Self::Exponential {
                sill,
                range,
                nugget,
            } => {
                if distance == 0.0 {
                    sill + nugget
                } else {
                    sill * (-3.0 * distance / range).exp()
                }
            }
            Self::Gaussian {
                sill,
                range,
                nugget,
            } => {
                if distance == 0.0 {
                    sill + nugget
                } else {
                    sill * (-3.0 * (distance / range).powi(2)).exp()
                }
            }
            Self::Matern {
                sill,
                range,
                nugget,
                nu,
            } => {
                if distance == 0.0 {
                    return sill + nugget;
                }

                let h = distance / range;
                match nu {
                    0.5 => sill * (-h).exp(),
                    1.5 => sill * (1.0 + h * 3.0_f64.sqrt()) * (-h * 3.0_f64.sqrt()).exp(),
                    2.5 => {
                        sill * (1.0 + h * 5.0_f64.sqrt() + 5.0 * h.powi(2) / 3.0)
                            * (-h * 5.0_f64.sqrt()).exp()
                    }
                    _ => {
                        // General Matérn (simplified approximation)
                        sill * (1.0 + h).exp() * (-h).exp()
                    }
                }
            }
            Self::Power { scale, exponent } => {
                if distance == 0.0 {
                    0.0
                } else {
                    scale * distance.powf(*exponent)
                }
            }
            Self::Linear { slope, nugget } => {
                if distance == 0.0 {
                    *nugget
                } else {
                    slope * distance
                }
            }
            Self::HoleEffect {
                sill,
                range,
                nugget,
                damping,
            } => {
                if distance == 0.0 {
                    sill + nugget
                } else {
                    let h_r = distance / range;
                    sill * (1.0 - h_r) * (-damping * h_r).exp().max(0.0)
                }
            }
            Self::Anisotropic { base_kernel, .. } => {
                // Distance is already transformed, use base kernel
                base_kernel.compute_covariance(distance)
            }
        }
    }

    /// Compute the semi-variogram for a given distance
    pub fn compute_variogram(&self, distance: f64) -> f64 {
        match self {
            Self::Spherical {
                sill,
                range,
                nugget,
            } => {
                if distance == 0.0 {
                    0.0
                } else if distance <= *range {
                    let h_r = distance / range;
                    nugget + sill * (1.5 * h_r - 0.5 * h_r.powi(3))
                } else {
                    nugget + sill
                }
            }
            Self::Exponential {
                sill,
                range,
                nugget,
            } => {
                if distance == 0.0 {
                    0.0
                } else {
                    nugget + sill * (1.0 - (-3.0 * distance / range).exp())
                }
            }
            Self::Gaussian {
                sill,
                range,
                nugget,
            } => {
                if distance == 0.0 {
                    0.0
                } else {
                    nugget + sill * (1.0 - (-3.0 * (distance / range).powi(2)).exp())
                }
            }
            _ => {
                // For other kernels, use the relation: γ(h) = C(0) - C(h)
                let c0 = self.compute_covariance(0.0);
                let ch = self.compute_covariance(distance);
                (c0 - ch).max(0.0)
            }
        }
    }

    /// Get the effective range of the kernel
    pub fn effective_range(&self) -> f64 {
        match self {
            Self::Spherical { range, .. }
            | Self::Exponential { range, .. }
            | Self::Gaussian { range, .. }
            | Self::Matern { range, .. }
            | Self::HoleEffect { range, .. } => *range,
            Self::Power { .. } => f64::INFINITY,
            Self::Linear { .. } => f64::INFINITY,
            Self::Anisotropic { base_kernel, .. } => base_kernel.effective_range(),
        }
    }

    /// Get the sill (maximum variance) of the kernel
    pub fn sill(&self) -> f64 {
        match self {
            Self::Spherical { sill, .. }
            | Self::Exponential { sill, .. }
            | Self::Gaussian { sill, .. }
            | Self::Matern { sill, .. }
            | Self::HoleEffect { sill, .. } => *sill,
            Self::Power { scale, .. } => *scale,
            Self::Linear { slope, .. } => *slope,
            Self::Anisotropic { base_kernel, .. } => base_kernel.sill(),
        }
    }

    /// Get the nugget effect
    pub fn nugget(&self) -> f64 {
        match self {
            Self::Spherical { nugget, .. }
            | Self::Exponential { nugget, .. }
            | Self::Gaussian { nugget, .. }
            | Self::Matern { nugget, .. }
            | Self::HoleEffect { nugget, .. }
            | Self::Linear { nugget, .. } => *nugget,
            Self::Power { .. } => 0.0,
            Self::Anisotropic { base_kernel, .. } => base_kernel.nugget(),
        }
    }
}

#[allow(non_snake_case)]
impl Kernel for SpatialKernel {
    fn compute_kernel_matrix(
        &self,
        x1: &Array2<f64>,
        x2: Option<&Array2<f64>>,
    ) -> SklResult<Array2<f64>> {
        let x2 = x2.unwrap_or(x1);
        let n1 = x1.nrows();
        let n2 = x2.nrows();

        if x1.ncols() < 2 || x2.ncols() < 2 {
            return Err(SklearsError::InvalidInput(
                "Spatial kernels require at least 2D coordinates".to_string(),
            ));
        }

        let mut K = Array2::zeros((n1, n2));

        for i in 0..n1 {
            for j in 0..n2 {
                let x1_coords = x1.row(i).to_vec();
                let x2_coords = x2.row(j).to_vec();
                let distance = self.compute_distance(&x1_coords, &x2_coords);
                K[[i, j]] = self.compute_covariance(distance);
            }
        }

        Ok(K)
    }

    fn clone_box(&self) -> Box<dyn Kernel> {
        Box::new(self.clone())
    }

    fn kernel(&self, x1: &ArrayView1<f64>, x2: &ArrayView1<f64>) -> f64 {
        if x1.len() < 2 || x2.len() < 2 {
            return 0.0; // Invalid spatial coordinates
        }
        let distance = self.compute_distance(&x1.to_vec(), &x2.to_vec());
        self.compute_covariance(distance)
    }

    fn get_params(&self) -> Vec<f64> {
        match self {
            Self::Spherical {
                range,
                sill,
                nugget,
            } => vec![*range, *sill, *nugget],
            Self::Exponential {
                range,
                sill,
                nugget,
            } => vec![*range, *sill, *nugget],
            Self::Gaussian {
                range,
                sill,
                nugget,
            } => vec![*range, *sill, *nugget],
            Self::Matern {
                range,
                sill,
                nugget,
                nu,
            } => vec![*range, *sill, *nugget, *nu],
            Self::Linear { slope, nugget } => vec![*slope, *nugget],
            Self::Power { scale, exponent } => vec![*scale, *exponent],
            Self::HoleEffect {
                range,
                sill,
                nugget,
                damping,
            } => vec![*range, *sill, *nugget, *damping],
            Self::Anisotropic {
                base_kernel,
                anisotropy_matrix,
            } => {
                let mut params = base_kernel.get_params();
                // Add anisotropy matrix elements (flattened)
                for row in anisotropy_matrix.rows() {
                    for &val in row {
                        params.push(val);
                    }
                }
                params
            }
        }
    }

    fn set_params(&mut self, params: &[f64]) -> SklResult<()> {
        match self {
            Self::Spherical {
                range,
                sill,
                nugget,
            } => {
                if params.len() != 3 {
                    return Err(SklearsError::InvalidInput(
                        "Spherical kernel requires 3 parameters".to_string(),
                    ));
                }
                *range = params[0];
                *sill = params[1];
                *nugget = params[2];
            }
            Self::Exponential {
                range,
                sill,
                nugget,
            } => {
                if params.len() != 3 {
                    return Err(SklearsError::InvalidInput(
                        "Exponential kernel requires 3 parameters".to_string(),
                    ));
                }
                *range = params[0];
                *sill = params[1];
                *nugget = params[2];
            }
            Self::Gaussian {
                range,
                sill,
                nugget,
            } => {
                if params.len() != 3 {
                    return Err(SklearsError::InvalidInput(
                        "Gaussian kernel requires 3 parameters".to_string(),
                    ));
                }
                *range = params[0];
                *sill = params[1];
                *nugget = params[2];
            }
            Self::Matern {
                range,
                sill,
                nugget,
                nu,
            } => {
                if params.len() != 4 {
                    return Err(SklearsError::InvalidInput(
                        "Matern kernel requires 4 parameters".to_string(),
                    ));
                }
                *range = params[0];
                *sill = params[1];
                *nugget = params[2];
                *nu = params[3];
            }
            Self::Linear { slope, nugget } => {
                if params.len() != 2 {
                    return Err(SklearsError::InvalidInput(
                        "Linear kernel requires 2 parameters".to_string(),
                    ));
                }
                *slope = params[0];
                *nugget = params[1];
            }
            Self::Power { scale, exponent } => {
                if params.len() != 2 {
                    return Err(SklearsError::InvalidInput(
                        "Power kernel requires 2 parameters".to_string(),
                    ));
                }
                *scale = params[0];
                *exponent = params[1];
            }
            Self::HoleEffect {
                range,
                sill,
                nugget,
                damping,
            } => {
                if params.len() != 4 {
                    return Err(SklearsError::InvalidInput(
                        "HoleEffect kernel requires 4 parameters".to_string(),
                    ));
                }
                *range = params[0];
                *sill = params[1];
                *nugget = params[2];
                *damping = params[3];
            }
            Self::Anisotropic {
                base_kernel,
                anisotropy_matrix,
            } => {
                let base_params_len = base_kernel.get_params().len();
                if params.len() < base_params_len {
                    return Err(SklearsError::InvalidInput(
                        "Not enough parameters for anisotropic kernel".to_string(),
                    ));
                }

                // Set base kernel parameters
                base_kernel.set_params(&params[..base_params_len])?;

                // Set anisotropy matrix
                let matrix_size = anisotropy_matrix.nrows() * anisotropy_matrix.ncols();
                if params.len() != base_params_len + matrix_size {
                    return Err(SklearsError::InvalidInput(
                        "Incorrect number of parameters for anisotropy matrix".to_string(),
                    ));
                }

                let matrix_params = &params[base_params_len..];
                let ncols = anisotropy_matrix.ncols();
                for (i, mut row) in anisotropy_matrix.rows_mut().into_iter().enumerate() {
                    for (j, val) in row.iter_mut().enumerate() {
                        *val = matrix_params[i * ncols + j];
                    }
                }
            }
        }
        Ok(())
    }
}

/// Empirical variogram computation and modeling
#[derive(Debug, Clone)]
pub struct Variogram {
    pub distances: Array1<f64>,
    pub semivariances: Array1<f64>,
    pub n_pairs: Array1<usize>,
    pub fitted_model: Option<SpatialKernel>,
}

impl Variogram {
    /// Compute empirical variogram from spatial data
    pub fn compute_empirical(
        coords: &Array2<f64>,
        values: &Array1<f64>,
        n_bins: usize,
    ) -> SklResult<Self> {
        let n_points = coords.nrows();
        if coords.nrows() != values.len() {
            return Err(SklearsError::DimensionMismatch {
                expected: coords.nrows(),
                actual: values.len(),
            });
        }

        // Compute all pairwise distances and semivariances
        let mut all_distances = Vec::new();
        let mut all_semivariances = Vec::new();

        for i in 0..n_points {
            for j in i + 1..n_points {
                let dist = coords
                    .row(i)
                    .iter()
                    .zip(coords.row(j).iter())
                    .map(|(a, b)| (a - b).powi(2))
                    .sum::<f64>()
                    .sqrt();

                let semivar = 0.5 * (values[i] - values[j]).powi(2);

                all_distances.push(dist);
                all_semivariances.push(semivar);
            }
        }

        if all_distances.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Not enough data points for variogram".to_string(),
            ));
        }

        // Create distance bins
        let max_dist = all_distances.iter().fold(0.0f64, |a, &b| a.max(b));
        let min_dist = all_distances.iter().fold(f64::INFINITY, |a, &b| a.min(b));
        let bin_width = (max_dist - min_dist) / n_bins as f64;

        let mut bin_distances: Array1<f64> = Array1::zeros(n_bins);
        let mut bin_semivariances: Array1<f64> = Array1::zeros(n_bins);
        let mut bin_counts: Array1<f64> = Array1::zeros(n_bins);

        // Assign pairs to bins
        for (dist, semivar) in all_distances.iter().zip(all_semivariances.iter()) {
            let bin_idx = ((*dist - min_dist) / bin_width).floor() as usize;
            let bin_idx = bin_idx.min(n_bins - 1);

            bin_distances[bin_idx] += dist;
            bin_semivariances[bin_idx] += semivar;
            bin_counts[bin_idx] += 1.0;
        }

        // Compute bin averages
        let mut distances = Vec::new();
        let mut semivariances = Vec::new();
        let mut n_pairs = Vec::new();

        for i in 0..n_bins {
            if bin_counts[i] > 0.0 {
                distances.push(bin_distances[i] / bin_counts[i] as f64);
                semivariances.push(bin_semivariances[i] / bin_counts[i] as f64);
                n_pairs.push(bin_counts[i] as usize);
            }
        }

        Ok(Self {
            distances: Array1::from_vec(distances),
            semivariances: Array1::from_vec(semivariances),
            n_pairs: Array1::from_vec(n_pairs),
            fitted_model: None,
        })
    }

    /// Fit a spatial kernel model to the empirical variogram
    pub fn fit_model(&mut self, model_type: &str) -> SklResult<()> {
        if self.distances.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No variogram data to fit".to_string(),
            ));
        }

        // Simple parameter estimation (could be improved with non-linear optimization)
        let max_semivar = self.semivariances.iter().fold(0.0f64, |a, &b| a.max(b));
        let max_dist = self.distances.iter().fold(0.0f64, |a, &b| a.max(b));

        // Estimate nugget as the y-intercept
        let nugget = if self.distances[0] > 0.0 {
            0.0
        } else {
            self.semivariances[0]
        };

        // Estimate sill as maximum semivariance
        let sill = max_semivar - nugget;

        // Estimate range as distance where semivariance reaches ~95% of sill
        let target_semivar = nugget + 0.95 * sill;
        let mut range = max_dist;
        for i in 0..self.distances.len() {
            if self.semivariances[i] >= target_semivar {
                range = self.distances[i];
                break;
            }
        }

        let fitted_model = match model_type {
            "spherical" => SpatialKernel::Spherical {
                sill,
                range,
                nugget,
            },
            "exponential" => SpatialKernel::Exponential {
                sill,
                range,
                nugget,
            },
            "gaussian" => SpatialKernel::Gaussian {
                sill,
                range,
                nugget,
            },
            "matern15" => SpatialKernel::Matern {
                sill,
                range,
                nugget,
                nu: 1.5,
            },
            _ => {
                return Err(SklearsError::InvalidInput(format!(
                    "Unknown model type: {}",
                    model_type
                )))
            }
        };

        self.fitted_model = Some(fitted_model);
        Ok(())
    }

    /// Compute goodness of fit for the fitted model
    pub fn goodness_of_fit(&self) -> SklResult<f64> {
        let model = self
            .fitted_model
            .as_ref()
            .ok_or_else(|| SklearsError::InvalidInput("No model fitted".to_string()))?;

        let mut ss_res = 0.0;
        let mut ss_tot = 0.0;
        let mean_semivar = self.semivariances.mean().unwrap_or(0.0);

        for i in 0..self.distances.len() {
            let predicted = model.compute_variogram(self.distances[i]);
            let observed = self.semivariances[i];

            ss_res += (observed - predicted).powi(2);
            ss_tot += (observed - mean_semivar).powi(2);
        }

        let r_squared = 1.0 - (ss_res / ss_tot.max(1e-12));
        Ok(r_squared)
    }
}

/// Spatial Gaussian Process Regressor
#[derive(Debug, Clone)]
pub struct SpatialGaussianProcessRegressor<S = Untrained> {
    spatial_kernel: Option<SpatialKernel>,
    kriging_type: KrigingType,
    estimate_variogram: bool,
    variogram_bins: usize,
    anisotropy_matrix: Option<Array2<f64>>,
    alpha: f64,
    _state: S,
}

/// Configuration for spatial GP
#[derive(Debug, Clone)]
pub struct SpatialGPConfig {
    pub kriging_type: KrigingType,
    pub estimate_variogram: bool,
    pub variogram_bins: usize,
    pub regularization: f64,
}

impl Default for SpatialGPConfig {
    fn default() -> Self {
        Self {
            kriging_type: KrigingType::Ordinary,
            estimate_variogram: false,
            variogram_bins: 20,
            regularization: 1e-6,
        }
    }
}

impl Default for SpatialGaussianProcessRegressor<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl SpatialGaussianProcessRegressor<Untrained> {
    /// Create a new spatial GP regressor
    pub fn new() -> Self {
        Self {
            spatial_kernel: None,
            kriging_type: KrigingType::Ordinary,
            estimate_variogram: false,
            variogram_bins: 20,
            anisotropy_matrix: None,
            alpha: 1e-6,
            _state: Untrained,
        }
    }

    /// Create a builder for spatial GP
    pub fn builder() -> SpatialGPBuilder {
        SpatialGPBuilder::new()
    }

    /// Set the spatial kernel
    pub fn spatial_kernel(mut self, kernel: SpatialKernel) -> Self {
        self.spatial_kernel = Some(kernel);
        self
    }

    /// Set the kriging type
    pub fn kriging_type(mut self, kriging_type: KrigingType) -> Self {
        self.kriging_type = kriging_type;
        self
    }

    /// Enable automatic variogram estimation
    pub fn estimate_variogram(mut self, estimate: bool) -> Self {
        self.estimate_variogram = estimate;
        self
    }

    /// Set anisotropy matrix for directional correlation
    pub fn anisotropy_matrix(mut self, matrix: Array2<f64>) -> Self {
        self.anisotropy_matrix = Some(matrix);
        self
    }

    /// Set regularization parameter
    pub fn alpha(mut self, alpha: f64) -> Self {
        self.alpha = alpha;
        self
    }
}

/// Builder for spatial GP regressor
#[derive(Debug, Clone)]
pub struct SpatialGPBuilder {
    kernel: Option<SpatialKernel>,
    kriging_type: KrigingType,
    estimate_variogram: bool,
    variogram_bins: usize,
    anisotropy_matrix: Option<Array2<f64>>,
    alpha: f64,
}

impl Default for SpatialGPBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl SpatialGPBuilder {
    pub fn new() -> Self {
        Self {
            kernel: None,
            kriging_type: KrigingType::Ordinary,
            estimate_variogram: false,
            variogram_bins: 20,
            anisotropy_matrix: None,
            alpha: 1e-6,
        }
    }

    pub fn spatial_kernel(mut self, kernel: SpatialKernel) -> Self {
        self.kernel = Some(kernel);
        self
    }

    pub fn kriging_type(mut self, kriging_type: KrigingType) -> Self {
        self.kriging_type = kriging_type;
        self
    }

    pub fn estimate_variogram(mut self, estimate: bool) -> Self {
        self.estimate_variogram = estimate;
        self
    }

    pub fn variogram_bins(mut self, bins: usize) -> Self {
        self.variogram_bins = bins;
        self
    }

    pub fn anisotropy_matrix(mut self, matrix: Array2<f64>) -> Self {
        self.anisotropy_matrix = Some(matrix);
        self
    }

    pub fn alpha(mut self, alpha: f64) -> Self {
        self.alpha = alpha;
        self
    }

    pub fn build(self) -> SpatialGaussianProcessRegressor<Untrained> {
        SpatialGaussianProcessRegressor {
            spatial_kernel: self.kernel,
            kriging_type: self.kriging_type,
            estimate_variogram: self.estimate_variogram,
            variogram_bins: self.variogram_bins,
            anisotropy_matrix: self.anisotropy_matrix.clone(),
            alpha: self.alpha,
            _state: Untrained,
        }
    }
}

impl Estimator for SpatialGaussianProcessRegressor<Untrained> {
    type Config = SpatialGPConfig;
    type Error = SklearsError;
    type Float = f64;

    fn config(&self) -> &Self::Config {
        static DEFAULT_CONFIG: SpatialGPConfig = SpatialGPConfig {
            kriging_type: KrigingType::Ordinary,
            estimate_variogram: false,
            variogram_bins: 20,
            regularization: 1e-6,
        };
        &DEFAULT_CONFIG
    }
}

impl Estimator for SpatialGaussianProcessRegressor<Trained> {
    type Config = SpatialGPConfig;
    type Error = SklearsError;
    type Float = f64;

    fn config(&self) -> &Self::Config {
        static DEFAULT_CONFIG: SpatialGPConfig = SpatialGPConfig {
            kriging_type: KrigingType::Ordinary,
            estimate_variogram: false,
            variogram_bins: 20,
            regularization: 1e-6,
        };
        &DEFAULT_CONFIG
    }
}

#[allow(non_snake_case)]
impl Fit<Array2<f64>, Array1<f64>> for SpatialGaussianProcessRegressor<Untrained> {
    type Fitted = SpatialGaussianProcessRegressor<Trained>;

    fn fit(self, X: &Array2<f64>, y: &Array1<f64>) -> SklResult<Self::Fitted> {
        if X.nrows() != y.len() {
            return Err(SklearsError::DimensionMismatch {
                expected: X.nrows(),
                actual: y.len(),
            });
        }

        if X.ncols() < 2 {
            return Err(SklearsError::InvalidInput(
                "Spatial GP requires at least 2D coordinates".to_string(),
            ));
        }

        let X_owned = X.to_owned();
        let y_owned = y.to_owned();

        // Estimate variogram if requested
        let variogram = if self.estimate_variogram {
            Some(Variogram::compute_empirical(
                &X_owned,
                &y_owned,
                self.variogram_bins,
            )?)
        } else {
            None
        };

        // Get spatial kernel
        let mut spatial_kernel = self.spatial_kernel.clone().ok_or_else(|| {
            SklearsError::InvalidInput("Spatial kernel must be specified".to_string())
        })?;

        // Apply anisotropy if specified
        if let Some(anisotropy_matrix) = &self.anisotropy_matrix {
            spatial_kernel = SpatialKernel::anisotropic(spatial_kernel, anisotropy_matrix.clone());
        }

        // Compute kernel matrix
        let K = spatial_kernel.compute_kernel_matrix(&X_owned, None)?;

        // Handle different kriging types
        let (y_for_gp, augmented_matrix) = match self.kriging_type {
            KrigingType::Simple { mean } => {
                // Subtract known mean
                let y_centered = &y_owned - mean;
                (y_centered, K.clone())
            }
            KrigingType::Ordinary => {
                // Add constraint for constant mean
                let n = K.nrows();
                let mut augmented = Array2::zeros((n + 1, n + 1));

                // Copy kernel matrix
                for i in 0..n {
                    for j in 0..n {
                        augmented[[i, j]] = K[[i, j]];
                    }
                }

                // Add constraint equations
                for i in 0..n {
                    augmented[[i, n]] = 1.0;
                    augmented[[n, i]] = 1.0;
                }

                (y_owned.clone(), augmented)
            }
            KrigingType::Universal => {
                // For universal kriging, we would add trend terms
                // Simplified implementation: treat as ordinary kriging for now
                let n = K.nrows();
                let mut augmented = Array2::zeros((n + 1, n + 1));

                for i in 0..n {
                    for j in 0..n {
                        augmented[[i, j]] = K[[i, j]];
                    }
                }

                for i in 0..n {
                    augmented[[i, n]] = 1.0;
                    augmented[[n, i]] = 1.0;
                }

                (y_owned.clone(), augmented)
            }
            KrigingType::CoKriging => {
                // Co-kriging would handle multiple variables
                // For now, treat as ordinary kriging
                let n = K.nrows();
                let mut augmented = Array2::zeros((n + 1, n + 1));

                for i in 0..n {
                    for j in 0..n {
                        augmented[[i, j]] = K[[i, j]];
                    }
                }

                for i in 0..n {
                    augmented[[i, n]] = 1.0;
                    augmented[[n, i]] = 1.0;
                }

                (y_owned.clone(), augmented)
            }
        };

        // Regularize the covariance (kernel) block of the system. The kernel
        // block `K` is symmetric positive semi-definite; `alpha` (the user
        // nugget/observation noise) lifts the smallest eigenvalue and makes it
        // positive definite so that a Cholesky factorization is well defined.
        let n_train = K.nrows();
        let mut k_block_reg = K.clone();
        for i in 0..n_train {
            k_block_reg[[i, i]] += self.alpha;
        }

        // Cholesky factor of the (regularized) kernel block only. This factor
        // is symmetric-positive-definite by construction (adaptive jitter is
        // applied internally if `alpha` alone is insufficient) and is reused
        // downstream for the kriging *variance*, which is a Gaussian-process
        // posterior variance defined purely by the covariance block.
        let chol_block = utils::robust_cholesky(&k_block_reg)?;

        // Solve for the kriging weights. The numerical character of the system
        // differs fundamentally between simple and ordinary/universal kriging.
        let alpha = match self.kriging_type {
            KrigingType::Simple { .. } => {
                // Simple kriging: weights solve the SPD system `K w = y_c`,
                // handled directly and stably by the Cholesky factor above.
                utils::triangular_solve(&chol_block, &y_for_gp)?
            }
            _ => {
                // Ordinary / universal / co-kriging augment `K` with an
                // unbiasedness (Lagrange) constraint, producing a SYMMETRIC
                // INDEFINITE saddle-point (KKT) system:
                //
                //     [ K   1 ] [ w ]   [ y ]
                //     [ 1^T 0 ] [ λ ] = [ 0 ]
                //
                // Such a system can never be Cholesky-factored (it always has a
                // negative eigenvalue), so we regularize the SPD kernel block
                // with the same nugget used above and solve the full system with
                // a general LU-based solver, which correctly handles indefinite
                // matrices. This is the principled fix for the instability:
                // Cholesky is used only where it is mathematically valid.
                let mut a = augmented_matrix.clone();
                for i in 0..n_train {
                    a[[i, i]] += self.alpha;
                }

                let mut rhs = Array1::zeros(n_train + 1);
                for i in 0..n_train {
                    rhs[i] = y_for_gp[i];
                }
                // The trailing entry (Lagrange multiplier row) is the
                // unbiasedness condition sum(w) = 1, hence rhs = 0 there.

                scirs2_linalg::solve(&a.view(), &rhs.view(), None).map_err(|e| {
                    SklearsError::NumericalError(format!(
                        "Failed to solve ordinary/universal kriging system: {e}"
                    ))
                })?
            }
        };

        // Log marginal likelihood is defined for the Gaussian-process model on
        // the covariance block (the unbiasedness constraint is not part of the
        // likelihood). Use the SPD kernel block and the matching weight vector.
        let weights_block = alpha.slice(s![0..n_train]).to_owned();
        let log_det = chol_block.diag().iter().map(|x| x.ln()).sum::<f64>() * 2.0;
        let data_fit = y_for_gp.dot(&weights_block);
        let log_likelihood = -0.5 * (data_fit + log_det + n_train as f64 * (2.0 * PI).ln());

        let chol_decomp = chol_block;

        Ok(SpatialGaussianProcessRegressor {
            spatial_kernel: self.spatial_kernel,
            kriging_type: self.kriging_type,
            estimate_variogram: self.estimate_variogram,
            variogram_bins: self.variogram_bins,
            anisotropy_matrix: self.anisotropy_matrix.clone(),
            alpha: self.alpha,
            _state: Trained {
                spatial_kernel,
                kriging_type: self.kriging_type,
                training_data: (X_owned, y_owned),
                alpha,
                cholesky: chol_decomp,
                log_likelihood,
                variogram,
                anisotropy_matrix: self.anisotropy_matrix.clone(),
            },
        })
    }
}

#[allow(non_snake_case)]
impl SpatialGaussianProcessRegressor<Trained> {
    /// Access the trained state
    pub fn trained_state(&self) -> &Trained {
        &self._state
    }

    /// Get the empirical variogram if computed
    pub fn variogram(&self) -> Option<&Variogram> {
        self._state.variogram.as_ref()
    }

    /// Predict with uncertainty (kriging variance)
    pub fn predict_with_variance(&self, X: &Array2<f64>) -> SklResult<(Array1<f64>, Array1<f64>)> {
        let n_test = X.nrows();
        let n_train = self._state.training_data.0.nrows();

        // Compute cross-covariance matrix
        let K_star = self
            ._state
            .spatial_kernel
            .compute_kernel_matrix(&self._state.training_data.0, Some(X))?;

        // Handle different kriging types for prediction
        let (predictions, variances) = match self._state.kriging_type {
            KrigingType::Simple { mean } => {
                // Simple kriging predictions
                let pred = K_star.t().dot(&self._state.alpha.slice(s![0..n_train])) + mean;

                // Compute prediction variance
                let K_star_star = self._state.spatial_kernel.compute_kernel_matrix(X, None)?;
                let cholesky_slice = self
                    ._state
                    .cholesky
                    .slice(s![0..n_train, 0..n_train])
                    .to_owned();
                let v = utils::triangular_solve_matrix(&cholesky_slice, &K_star)?;
                let pred_var =
                    K_star_star.diag().to_owned() - &v.map(|x| x.powi(2)).sum_axis(Axis(0));

                (pred, pred_var)
            }
            _ => {
                // Ordinary/Universal kriging
                let mut extended_k_star = Array2::zeros((n_train + 1, n_test));

                // Copy cross-covariances
                for i in 0..n_train {
                    for j in 0..n_test {
                        extended_k_star[[i, j]] = K_star[[i, j]];
                    }
                }

                // Add constraint (unitary condition)
                for j in 0..n_test {
                    extended_k_star[[n_train, j]] = 1.0;
                }

                let pred = extended_k_star.t().dot(&self._state.alpha);

                // Compute prediction variance (simplified)
                let K_star_star = self._state.spatial_kernel.compute_kernel_matrix(X, None)?;
                let cholesky_slice = self
                    ._state
                    .cholesky
                    .slice(s![0..n_train, 0..n_train])
                    .to_owned();
                let v = utils::triangular_solve_matrix(&cholesky_slice, &K_star)?;
                let pred_var =
                    K_star_star.diag().to_owned() - &v.map(|x| x.powi(2)).sum_axis(Axis(0));

                (pred, pred_var.map(|x| x.max(0.0)))
            }
        };

        Ok((predictions, variances.map(|x| x.sqrt())))
    }

    /// Compute spatial correlation structure
    pub fn correlation_structure(
        &self,
        max_distance: f64,
        n_points: usize,
    ) -> (Array1<f64>, Array1<f64>) {
        let distances = Array1::linspace(0.0, max_distance, n_points);
        let correlations = distances.map(|&d| self._state.spatial_kernel.compute_covariance(d));
        (distances, correlations)
    }

    /// Detect spatial outliers using leave-one-out kriging cross-validation.
    ///
    /// A kriging model interpolates its training data exactly, so *in-sample*
    /// residuals are identically zero and carry no information about outliers.
    /// The standard geostatistical diagnostic is therefore the **leave-one-out
    /// (LOO) cross-validated, studentized residual**: each observation is
    /// removed, predicted from the remaining points, and the prediction error
    /// is standardized by the kriging standard deviation at that location:
    ///
    /// ```text
    /// z_i = (y_i - yhat_{-i}) / sigma_{-i}
    /// ```
    ///
    /// Spatially anomalous observations are those whose value disagrees with
    /// what their neighbours predict, yielding a large |z_i|. Points are
    /// flagged when |z_i| exceeds `threshold` (a number of standard deviations).
    pub fn detect_spatial_outliers(&self, threshold: f64) -> SklResult<Vec<usize>> {
        let coords = &self._state.training_data.0;
        let targets = &self._state.training_data.1;
        let n = coords.nrows();
        let n_features = coords.ncols();

        let mut outliers = Vec::new();

        for i in 0..n {
            // Build the leave-one-out training set (all points except `i`).
            let mut train_coords = Vec::with_capacity((n - 1) * n_features);
            let mut train_values = Vec::with_capacity(n - 1);
            for j in 0..n {
                if j != i {
                    train_coords.extend(coords.row(j).iter().copied());
                    train_values.push(targets[j]);
                }
            }

            let train_coords_array = Array2::from_shape_vec((n - 1, n_features), train_coords)
                .map_err(|_| {
                    SklearsError::InvalidInput(
                        "Failed to build leave-one-out coordinates".to_string(),
                    )
                })?;
            let train_values_array = Array1::from_vec(train_values);

            let reduced_gp = SpatialGaussianProcessRegressor::builder()
                .spatial_kernel(self._state.spatial_kernel.clone())
                .kriging_type(self._state.kriging_type)
                .alpha(self.alpha)
                .build();

            let fitted = reduced_gp.fit(&train_coords_array, &train_values_array)?;

            let test_coords = coords.slice(s![i..i + 1, ..]).to_owned();
            let (prediction, std_dev) = fitted.predict_with_variance(&test_coords)?;

            let residual = targets[i] - prediction[0];
            // Standardize by the kriging standard deviation. Guard against a
            // degenerate (zero) predictive std with a trace-proportional floor
            // derived from the data scale so the z-score stays finite.
            let sigma = std_dev[0];
            let sigma = if sigma.is_finite() && sigma > 1e-12 {
                sigma
            } else {
                let scale = targets.std(0.0);
                (scale * 1e-6).max(1e-12)
            };

            let z_score = residual / sigma;
            if z_score.is_finite() && z_score.abs() > threshold {
                outliers.push(i);
            }
        }

        Ok(outliers)
    }

    /// Cross-validation for spatial data (leave-one-out)
    pub fn spatial_cross_validation(&self) -> SklResult<f64> {
        let n = self._state.training_data.0.nrows();
        let mut errors = Vec::new();

        for i in 0..n {
            // Create training data excluding point i
            let mut train_coords = Vec::new();
            let mut train_values = Vec::new();

            for j in 0..n {
                if j != i {
                    train_coords.push(self._state.training_data.0.row(j).to_vec());
                    train_values.push(self._state.training_data.1[j]);
                }
            }

            // Convert back to arrays
            let train_coords_array = Array2::from_shape_vec(
                (n - 1, self._state.training_data.0.ncols()),
                train_coords.into_iter().flatten().collect(),
            )
            .map_err(|_| {
                SklearsError::InvalidInput("Failed to create training coordinates".to_string())
            })?;

            let train_values_array = Array1::from_vec(train_values);

            // Fit model on reduced data
            let reduced_gp = SpatialGaussianProcessRegressor::builder()
                .spatial_kernel(self._state.spatial_kernel.clone())
                .kriging_type(self._state.kriging_type)
                .alpha(self.alpha)
                .build();

            if let Ok(fitted) = reduced_gp.fit(&train_coords_array, &train_values_array) {
                // Predict for the left-out point
                let test_coords = self._state.training_data.0.slice(s![i..i + 1, ..]);
                if let Ok(pred) = fitted.predict(&test_coords.to_owned()) {
                    let error = (pred[0] - self._state.training_data.1[i]).powi(2);
                    errors.push(error);
                }
            }
        }

        if errors.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Cross-validation failed".to_string(),
            ));
        }

        let mse = errors.iter().sum::<f64>() / errors.len() as f64;
        Ok(mse.sqrt()) // Return RMSE
    }
}

#[allow(non_snake_case)]
impl Predict<Array2<f64>, Array1<f64>> for SpatialGaussianProcessRegressor<Trained> {
    fn predict(&self, X: &Array2<f64>) -> SklResult<Array1<f64>> {
        let (predictions, _) = self.predict_with_variance(X)?;
        Ok(predictions)
    }
}

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

    #[test]
    fn test_spatial_kernel_spherical() {
        let kernel = SpatialKernel::spherical(1.0, 10.0);

        // Test at distance 0
        assert_abs_diff_eq!(kernel.compute_covariance(0.0), 1.0, epsilon = 1e-10);

        // Test within range
        let cov_5 = kernel.compute_covariance(5.0);
        assert!(cov_5 > 0.0 && cov_5 < 1.0);

        // Test beyond range
        let cov_15 = kernel.compute_covariance(15.0);
        assert_abs_diff_eq!(cov_15, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_spatial_kernel_exponential() {
        let kernel = SpatialKernel::exponential(1.0, 5.0);

        // Test exponential decay
        let cov_0 = kernel.compute_covariance(0.0);
        let cov_5 = kernel.compute_covariance(5.0);
        let cov_10 = kernel.compute_covariance(10.0);

        assert_abs_diff_eq!(cov_0, 1.0, epsilon = 1e-10);
        assert!(cov_5 > cov_10);
        assert!(cov_10 > 0.0);
    }

    #[test]
    fn test_variogram_computation() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let values = array![1.0, 2.0, 1.5, 2.5];

        let variogram =
            Variogram::compute_empirical(&coords, &values, 5).expect("operation should succeed");

        assert!(!variogram.distances.is_empty());
        assert_eq!(variogram.distances.len(), variogram.semivariances.len());
        assert_eq!(variogram.distances.len(), variogram.n_pairs.len());
    }

    #[test]
    fn test_spatial_gp_ordinary_kriging() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let values = array![1.0, 2.0, 1.5, 2.5];

        let spatial_gp = SpatialGaussianProcessRegressor::builder()
            .spatial_kernel(SpatialKernel::spherical(1.0, 2.0))
            .kriging_type(KrigingType::Ordinary)
            .build();

        let trained = spatial_gp
            .fit(&coords, &values)
            .expect("model fitting should succeed");
        let predictions = trained.predict(&coords).expect("prediction should succeed");

        assert_eq!(predictions.len(), coords.nrows());
    }

    #[test]
    fn test_spatial_gp_simple_kriging() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let values = array![1.0, 2.0, 1.5, 2.5];

        let spatial_gp = SpatialGaussianProcessRegressor::builder()
            .spatial_kernel(SpatialKernel::exponential(1.0, 2.0))
            .kriging_type(KrigingType::Simple { mean: 1.75 })
            .build();

        let trained = spatial_gp
            .fit(&coords, &values)
            .expect("model fitting should succeed");
        let predictions = trained.predict(&coords).expect("prediction should succeed");

        assert_eq!(predictions.len(), coords.nrows());
    }

    #[test]
    fn test_spatial_gp_with_variance() {
        let coords = array![[0.0, 0.0], [2.0, 0.0], [0.0, 2.0], [2.0, 2.0]];
        let values = array![1.0, 3.0, 2.0, 4.0];

        let spatial_gp = SpatialGaussianProcessRegressor::builder()
            .spatial_kernel(SpatialKernel::gaussian(2.0, 1.0))
            .kriging_type(KrigingType::Ordinary)
            .build();

        let trained = spatial_gp
            .fit(&coords, &values)
            .expect("model fitting should succeed");

        let test_coords = array![[1.0, 1.0]]; // Center point
        let (predictions, variances) = trained
            .predict_with_variance(&test_coords)
            .expect("operation should succeed");

        assert_eq!(predictions.len(), 1);
        assert_eq!(variances.len(), 1);
        assert!(variances[0] >= 0.0);
    }

    #[test]
    fn test_spatial_kernel_with_nugget() {
        let kernel = SpatialKernel::spherical_with_nugget(1.0, 5.0, 0.1);

        // At distance 0, should include nugget
        assert_abs_diff_eq!(kernel.compute_covariance(0.0), 1.1, epsilon = 1e-10);

        // At non-zero distance, no nugget contribution
        let cov_1 = kernel.compute_covariance(1.0);
        assert!(cov_1 > 0.0 && cov_1 < 1.0);
    }

    #[test]
    fn test_anisotropic_kernel() {
        let base_kernel = SpatialKernel::exponential(1.0, 2.0);
        let anisotropy_matrix = array![[2.0, 0.0], [0.0, 1.0]]; // Stretch in x-direction

        let aniso_kernel = SpatialKernel::anisotropic(base_kernel, anisotropy_matrix);

        let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let K = aniso_kernel
            .compute_kernel_matrix(&coords, None)
            .expect("operation should succeed");

        assert_eq!(K.shape(), &[3, 3]);
        assert_abs_diff_eq!(
            K[[0, 0]],
            aniso_kernel.compute_covariance(0.0),
            epsilon = 1e-10
        );
    }

    #[test]
    fn test_variogram_model_fitting() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0], [4.0, 0.0]];
        let values = array![1.0, 1.2, 1.8, 2.1, 2.5];

        let mut variogram =
            Variogram::compute_empirical(&coords, &values, 4).expect("operation should succeed");
        variogram
            .fit_model("spherical")
            .expect("operation should succeed");

        assert!(variogram.fitted_model.is_some());

        let goodness = variogram
            .goodness_of_fit()
            .expect("operation should succeed");
        assert!((0.0..=1.0).contains(&goodness));
    }

    #[test]
    fn test_spatial_outlier_detection() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]];
        let values = array![1.0, 2.0, 3.0, 10.0]; // Last value is outlier

        let spatial_gp = SpatialGaussianProcessRegressor::builder()
            .spatial_kernel(SpatialKernel::exponential(1.0, 2.0))
            .kriging_type(KrigingType::Ordinary)
            .build();

        let trained = spatial_gp
            .fit(&coords, &values)
            .expect("model fitting should succeed");
        let outliers = trained
            .detect_spatial_outliers(2.0)
            .expect("operation should succeed");

        // Should detect the outlier (index 3)
        assert!(!outliers.is_empty());
    }

    #[test]
    fn test_spatial_cross_validation() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.5, 0.5]];
        let values = array![1.0, 2.0, 1.5, 2.5, 1.8];

        let spatial_gp = SpatialGaussianProcessRegressor::builder()
            .spatial_kernel(SpatialKernel::spherical(1.0, 2.0))
            .kriging_type(KrigingType::Ordinary)
            .build();

        let trained = spatial_gp
            .fit(&coords, &values)
            .expect("model fitting should succeed");
        let cv_error = trained
            .spatial_cross_validation()
            .expect("operation should succeed");

        assert!(cv_error >= 0.0);
    }

    #[test]
    fn test_matern_kernel() {
        let kernel = SpatialKernel::matern(1.0, 2.0, 1.5);

        // Test at distance 0
        assert_abs_diff_eq!(kernel.compute_covariance(0.0), 1.0, epsilon = 1e-10);

        // Test decay properties
        let cov_1 = kernel.compute_covariance(1.0);
        let cov_2 = kernel.compute_covariance(2.0);
        assert!(cov_1 > cov_2);
        assert!(cov_2 > 0.0);
    }

    #[test]
    fn test_correlation_structure() {
        let coords = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
        let values = array![1.0, 2.0, 1.5];

        let spatial_gp = SpatialGaussianProcessRegressor::builder()
            .spatial_kernel(SpatialKernel::exponential(1.0, 2.0))
            .kriging_type(KrigingType::Ordinary)
            .build();

        let trained = spatial_gp
            .fit(&coords, &values)
            .expect("model fitting should succeed");
        let (distances, correlations) = trained.correlation_structure(5.0, 10);

        assert_eq!(distances.len(), 10);
        assert_eq!(correlations.len(), 10);
        assert_abs_diff_eq!(correlations[0], 1.0, epsilon = 1e-10); // At distance 0
    }
}