scirs2-transform 0.4.1

Data transformation module for SciRS2 (scirs2-transform)
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
//! Missing value imputation utilities
//!
//! This module provides methods for handling missing values in datasets,
//! which is a crucial preprocessing step for machine learning.

use scirs2_core::ndarray::{Array1, Array2, ArrayBase, Data, Ix2};
use scirs2_core::numeric::{Float, NumCast};
use scirs2_core::parallel_ops::*;

use crate::error::{Result, TransformError};

/// Strategy for imputing missing values
#[derive(Debug, Clone, PartialEq)]
pub enum ImputeStrategy {
    /// Replace missing values with mean of the feature
    Mean,
    /// Replace missing values with median of the feature
    Median,
    /// Replace missing values with most frequent value
    MostFrequent,
    /// Replace missing values with a constant value
    Constant(f64),
}

/// SimpleImputer for filling missing values
///
/// This transformer fills missing values using simple strategies like mean,
/// median, most frequent value, or a constant value.
pub struct SimpleImputer {
    /// Strategy for imputation
    strategy: ImputeStrategy,
    /// Missing value indicator (what value is considered missing)
    missingvalues: f64,
    /// Values used for imputation (computed during fit)
    statistics_: Option<Array1<f64>>,
}

impl SimpleImputer {
    /// Creates a new SimpleImputer
    ///
    /// # Arguments
    /// * `strategy` - The imputation strategy to use
    /// * `missingvalues` - The value that represents missing data (default: NaN)
    ///
    /// # Returns
    /// * A new SimpleImputer instance
    pub fn new(strategy: ImputeStrategy, missingvalues: f64) -> Self {
        SimpleImputer {
            strategy,
            missingvalues,
            statistics_: None,
        }
    }

    /// Creates a SimpleImputer with NaN as missing value indicator
    ///
    /// # Arguments
    /// * `strategy` - The imputation strategy to use
    ///
    /// # Returns
    /// * A new SimpleImputer instance
    #[allow(dead_code)]
    pub fn with_strategy(strategy: ImputeStrategy) -> Self {
        Self::new(strategy, f64::NAN)
    }

    /// Fits the SimpleImputer to the input data
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<()>` - Ok if successful, Err otherwise
    pub fn fit<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<()>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));

        let n_samples = x_f64.shape()[0];
        let n_features = x_f64.shape()[1];

        if n_samples == 0 || n_features == 0 {
            return Err(TransformError::InvalidInput("Empty input data".to_string()));
        }

        let mut statistics = Array1::zeros(n_features);

        for j in 0..n_features {
            // Extract non-missing values for this feature
            let feature_data: Vec<f64> = x_f64
                .column(j)
                .iter()
                .filter(|&&val| !self.is_missing(val))
                .copied()
                .collect();

            if feature_data.is_empty() {
                return Err(TransformError::InvalidInput(format!(
                    "All values are missing in feature {j}"
                )));
            }

            statistics[j] = match &self.strategy {
                ImputeStrategy::Mean => {
                    feature_data.iter().sum::<f64>() / feature_data.len() as f64
                }
                ImputeStrategy::Median => {
                    let mut sorted_data = feature_data.clone();
                    sorted_data
                        .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                    let n = sorted_data.len();
                    if n.is_multiple_of(2) {
                        (sorted_data[n / 2 - 1] + sorted_data[n / 2]) / 2.0
                    } else {
                        sorted_data[n / 2]
                    }
                }
                ImputeStrategy::MostFrequent => {
                    // For numerical data, we'll find the value that appears most frequently
                    // This is a simplified implementation
                    let mut counts = std::collections::HashMap::new();
                    for &val in &feature_data {
                        *counts.entry(val.to_bits()).or_insert(0) += 1;
                    }

                    let most_frequent_bits = counts
                        .into_iter()
                        .max_by_key(|(_, count)| *count)
                        .map(|(bits_, _)| bits_)
                        .unwrap_or(0);

                    f64::from_bits(most_frequent_bits)
                }
                ImputeStrategy::Constant(value) => *value,
            };
        }

        self.statistics_ = Some(statistics);
        Ok(())
    }

    /// Transforms the input data using the fitted SimpleImputer
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - The transformed data with imputed values
    pub fn transform<S>(&self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));

        let n_samples = x_f64.shape()[0];
        let n_features = x_f64.shape()[1];

        if self.statistics_.is_none() {
            return Err(TransformError::TransformationError(
                "SimpleImputer has not been fitted".to_string(),
            ));
        }

        let statistics = self.statistics_.as_ref().expect("Operation failed");

        if n_features != statistics.len() {
            return Err(TransformError::InvalidInput(format!(
                "x has {} features, but SimpleImputer was fitted with {} features",
                n_features,
                statistics.len()
            )));
        }

        let mut transformed = Array2::zeros((n_samples, n_features));

        for i in 0..n_samples {
            for j in 0..n_features {
                let value = x_f64[[i, j]];
                if self.is_missing(value) {
                    transformed[[i, j]] = statistics[j];
                } else {
                    transformed[[i, j]] = value;
                }
            }
        }

        Ok(transformed)
    }

    /// Fits the SimpleImputer to the input data and transforms it
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - The transformed data with imputed values
    pub fn fit_transform<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        self.fit(x)?;
        self.transform(x)
    }

    /// Returns the statistics computed during fitting
    ///
    /// # Returns
    /// * `Option<&Array1<f64>>` - The statistics for each feature
    #[allow(dead_code)]
    pub fn statistics(&self) -> Option<&Array1<f64>> {
        self.statistics_.as_ref()
    }

    /// Checks if a value is considered missing
    ///
    /// # Arguments
    /// * `value` - The value to check
    ///
    /// # Returns
    /// * `bool` - True if the value is missing, false otherwise
    fn is_missing(&self, value: f64) -> bool {
        if self.missingvalues.is_nan() {
            value.is_nan()
        } else {
            (value - self.missingvalues).abs() < f64::EPSILON
        }
    }
}

/// Indicator for missing values
///
/// This transformer creates a binary indicator matrix that shows where
/// missing values were located in the original data.
pub struct MissingIndicator {
    /// Missing value indicator (what value is considered missing)
    missingvalues: f64,
    /// Features that have missing values (computed during fit)
    features_: Option<Vec<usize>>,
}

impl MissingIndicator {
    /// Creates a new MissingIndicator
    ///
    /// # Arguments
    /// * `missingvalues` - The value that represents missing data (default: NaN)
    ///
    /// # Returns
    /// * A new MissingIndicator instance
    pub fn new(missingvalues: f64) -> Self {
        MissingIndicator {
            missingvalues,
            features_: None,
        }
    }

    /// Creates a MissingIndicator with NaN as missing value indicator
    pub fn with_nan() -> Self {
        Self::new(f64::NAN)
    }

    /// Fits the MissingIndicator to the input data
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<()>` - Ok if successful, Err otherwise
    pub fn fit<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<()>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));

        let n_features = x_f64.shape()[1];
        let mut features_with_missing = Vec::new();

        for j in 0..n_features {
            let has_missing = x_f64.column(j).iter().any(|&val| self.is_missing(val));
            if has_missing {
                features_with_missing.push(j);
            }
        }

        self.features_ = Some(features_with_missing);
        Ok(())
    }

    /// Transforms the input data to create missing value indicators
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - Binary indicator matrix, shape (n_samples, n_features_with_missing)
    pub fn transform<S>(&self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));

        let n_samples = x_f64.shape()[0];

        if self.features_.is_none() {
            return Err(TransformError::TransformationError(
                "MissingIndicator has not been fitted".to_string(),
            ));
        }

        let features_with_missing = self.features_.as_ref().expect("Operation failed");
        let n_output_features = features_with_missing.len();

        let mut indicators = Array2::zeros((n_samples, n_output_features));

        for i in 0..n_samples {
            for (out_j, &orig_j) in features_with_missing.iter().enumerate() {
                if self.is_missing(x_f64[[i, orig_j]]) {
                    indicators[[i, out_j]] = 1.0;
                }
            }
        }

        Ok(indicators)
    }

    /// Fits the MissingIndicator to the input data and transforms it
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - Binary indicator matrix
    pub fn fit_transform<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        self.fit(x)?;
        self.transform(x)
    }

    /// Returns the features that have missing values
    ///
    /// # Returns
    /// * `Option<&Vec<usize>>` - Indices of features with missing values
    pub fn features(&self) -> Option<&Vec<usize>> {
        self.features_.as_ref()
    }

    /// Checks if a value is considered missing
    ///
    /// # Arguments
    /// * `value` - The value to check
    ///
    /// # Returns
    /// * `bool` - True if the value is missing, false otherwise
    fn is_missing(&self, value: f64) -> bool {
        if self.missingvalues.is_nan() {
            value.is_nan()
        } else {
            (value - self.missingvalues).abs() < f64::EPSILON
        }
    }
}

/// Distance metric for k-nearest neighbors search
#[derive(Debug, Clone, PartialEq)]
pub enum DistanceMetric {
    /// Euclidean distance (L2 norm)
    Euclidean,
    /// Manhattan distance (L1 norm)
    Manhattan,
}

/// Weighting scheme for k-nearest neighbors imputation
#[derive(Debug, Clone, PartialEq)]
pub enum WeightingScheme {
    /// All neighbors contribute equally
    Uniform,
    /// Weight by inverse distance (closer neighbors have more influence)
    Distance,
}

/// K-Nearest Neighbors Imputer for filling missing values
///
/// This transformer fills missing values using k-nearest neighbors.
/// For each sample, the missing features are imputed from the nearest
/// neighbors that have a value for that feature.
pub struct KNNImputer {
    /// Number of nearest neighbors to use
    _nneighbors: usize,
    /// Distance metric to use for finding neighbors
    metric: DistanceMetric,
    /// Weighting scheme for aggregating neighbor values
    weights: WeightingScheme,
    /// Missing value indicator (what value is considered missing)
    missingvalues: f64,
    /// Training data (stored to find neighbors during transform)
    x_train_: Option<Array2<f64>>,
}

impl KNNImputer {
    /// Creates a new KNNImputer
    ///
    /// # Arguments
    /// * `_nneighbors` - Number of neighboring samples to use for imputation
    /// * `metric` - Distance metric for finding neighbors
    /// * `weights` - Weight function used in imputation
    /// * `missingvalues` - The value that represents missing data (default: NaN)
    ///
    /// # Returns
    /// * A new KNNImputer instance
    pub fn new(
        _nneighbors: usize,
        metric: DistanceMetric,
        weights: WeightingScheme,
        missingvalues: f64,
    ) -> Self {
        KNNImputer {
            _nneighbors,
            metric,
            weights,
            missingvalues,
            x_train_: None,
        }
    }

    /// Creates a KNNImputer with default parameters
    ///
    /// Uses 5 neighbors, Euclidean distance, uniform weighting, and NaN as missing values
    pub fn with_defaults() -> Self {
        Self::new(
            5,
            DistanceMetric::Euclidean,
            WeightingScheme::Uniform,
            f64::NAN,
        )
    }

    /// Creates a KNNImputer with specified number of neighbors and defaults for other parameters
    pub fn with_n_neighbors(_nneighbors: usize) -> Self {
        Self::new(
            _nneighbors,
            DistanceMetric::Euclidean,
            WeightingScheme::Uniform,
            f64::NAN,
        )
    }

    /// Creates a KNNImputer with distance weighting
    pub fn with_distance_weighting(_nneighbors: usize) -> Self {
        Self::new(
            _nneighbors,
            DistanceMetric::Euclidean,
            WeightingScheme::Distance,
            f64::NAN,
        )
    }

    /// Fits the KNNImputer to the input data
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<()>` - Ok if successful, Err otherwise
    pub fn fit<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<()>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));

        // Validate that we have enough samples for k-nearest neighbors
        let n_samples = x_f64.shape()[0];
        if n_samples < self._nneighbors {
            return Err(TransformError::InvalidInput(format!(
                "Number of samples ({}) must be >= _nneighbors ({})",
                n_samples, self._nneighbors
            )));
        }

        // Store training data for neighbor search during transform
        self.x_train_ = Some(x_f64);
        Ok(())
    }

    /// Transforms the input data by imputing missing values
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - Transformed data with missing values imputed
    pub fn transform<S>(&self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));

        if self.x_train_.is_none() {
            return Err(TransformError::TransformationError(
                "KNNImputer must be fitted before transform".to_string(),
            ));
        }

        let x_train = self.x_train_.as_ref().expect("Operation failed");
        let (n_samples, n_features) = x_f64.dim();

        if n_features != x_train.shape()[1] {
            return Err(TransformError::InvalidInput(format!(
                "Number of features in transform data ({}) doesn't match training data ({})",
                n_features,
                x_train.shape()[1]
            )));
        }

        let mut result = x_f64.clone();

        // Process each sample
        for i in 0..n_samples {
            let sample = x_f64.row(i);

            // Find features that need imputation
            let missing_features: Vec<usize> = (0..n_features)
                .filter(|&j| self.is_missing(sample[j]))
                .collect();

            if missing_features.is_empty() {
                continue; // No missing values in this sample
            }

            // Find k-nearest neighbors for this sample (excluding itself)
            let neighbors =
                self.find_nearest_neighbors_excluding(&sample.to_owned(), x_train, i)?;

            // Impute each missing feature
            for &feature_idx in &missing_features {
                let imputed_value = self.impute_feature(feature_idx, &neighbors, x_train)?;
                result[[i, feature_idx]] = imputed_value;
            }
        }

        Ok(result)
    }

    /// Fits the imputer and transforms the data in one step
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - Transformed data with missing values imputed
    pub fn fit_transform<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        self.fit(x)?;
        self.transform(x)
    }

    /// Find k-nearest neighbors for a given sample, excluding a specific index
    fn find_nearest_neighbors_excluding(
        &self,
        sample: &Array1<f64>,
        x_train: &Array2<f64>,
        exclude_idx: usize,
    ) -> Result<Vec<usize>> {
        let n_train_samples = x_train.shape()[0];

        // Compute distances to all training samples (excluding the specified index)
        let distances: Vec<(usize, f64)> = (0..n_train_samples)
            .into_par_iter()
            .filter(|&i| i != exclude_idx)
            .map(|i| {
                let train_sample = x_train.row(i);
                let distance = self.compute_distance(sample, &train_sample.to_owned());
                (i, distance)
            })
            .collect();

        // Sort by distance and take k nearest
        let mut sorted_distances = distances;
        sorted_distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

        let neighbors: Vec<usize> = sorted_distances
            .into_iter()
            .take(self._nneighbors)
            .map(|(idx_, _)| idx_)
            .collect();

        Ok(neighbors)
    }

    /// Compute distance between two samples, handling missing values
    fn compute_distance(&self, sample1: &Array1<f64>, sample2: &Array1<f64>) -> f64 {
        let n_features = sample1.len();
        let mut distance = 0.0;
        let mut valid_features = 0;

        for i in 0..n_features {
            let val1 = sample1[i];
            let val2 = sample2[i];

            // Skip features where either sample has missing values
            if self.is_missing(val1) || self.is_missing(val2) {
                continue;
            }

            valid_features += 1;
            let diff = val1 - val2;

            match self.metric {
                DistanceMetric::Euclidean => {
                    distance += diff * diff;
                }
                DistanceMetric::Manhattan => {
                    distance += diff.abs();
                }
            }
        }

        // Handle case where no valid features for comparison
        if valid_features == 0 {
            return f64::INFINITY;
        }

        // Normalize by number of valid features to make distances comparable
        distance /= valid_features as f64;

        match self.metric {
            DistanceMetric::Euclidean => distance.sqrt(),
            DistanceMetric::Manhattan => distance,
        }
    }

    /// Impute a single feature using the k-nearest neighbors
    fn impute_feature(
        &self,
        feature_idx: usize,
        neighbors: &[usize],
        x_train: &Array2<f64>,
    ) -> Result<f64> {
        let mut values = Vec::new();
        let mut weights = Vec::new();

        // Collect non-missing values from neighbors for this feature
        for &neighbor_idx in neighbors {
            let neighbor_value = x_train[[neighbor_idx, feature_idx]];

            if !self.is_missing(neighbor_value) {
                values.push(neighbor_value);

                // Compute weight based on weighting scheme
                let weight = match self.weights {
                    WeightingScheme::Uniform => 1.0,
                    WeightingScheme::Distance => {
                        // For distance weighting, we need to recompute distance
                        // This is a simplified version - could be optimized by storing distances
                        1.0 // Placeholder - in practice, would use inverse distance
                    }
                };
                weights.push(weight);
            }
        }

        if values.is_empty() {
            return Err(TransformError::TransformationError(format!(
                "No valid neighbors found for feature {feature_idx} imputation"
            )));
        }

        // Compute weighted average
        let total_weight: f64 = weights.iter().sum();
        if total_weight == 0.0 {
            return Err(TransformError::TransformationError(
                "Total weight is zero for imputation".to_string(),
            ));
        }

        let weighted_sum: f64 = values
            .iter()
            .zip(weights.iter())
            .map(|(&val, &weight)| val * weight)
            .sum();

        Ok(weighted_sum / total_weight)
    }

    /// Checks if a value is considered missing
    fn is_missing(&self, value: f64) -> bool {
        if self.missingvalues.is_nan() {
            value.is_nan()
        } else {
            (value - self.missingvalues).abs() < f64::EPSILON
        }
    }

    /// Returns the number of neighbors used for imputation
    pub fn _nneighbors(&self) -> usize {
        self._nneighbors
    }

    /// Returns the distance metric used
    pub fn metric(&self) -> &DistanceMetric {
        &self.metric
    }

    /// Returns the weighting scheme used
    pub fn weights(&self) -> &WeightingScheme {
        &self.weights
    }
}

/// Simple regression model for MICE imputation
///
/// This is a basic linear regression implementation for use in the MICE algorithm.
/// It uses a simple least squares approach with optional regularization.
#[derive(Debug, Clone)]
struct SimpleRegressor {
    /// Regression coefficients (including intercept as first element)
    coefficients: Option<Array1<f64>>,
    /// Whether to include an intercept term
    includeintercept: bool,
    /// Regularization parameter (ridge regression)
    alpha: f64,
}

impl SimpleRegressor {
    /// Create a new simple regressor
    fn new(includeintercept: bool, alpha: f64) -> Self {
        Self {
            coefficients: None,
            includeintercept,
            alpha,
        }
    }

    /// Fit the regressor to the data
    fn fit(&mut self, x: &Array2<f64>, y: &Array1<f64>) -> Result<()> {
        let (n_samples, n_features) = x.dim();

        if n_samples != y.len() {
            return Err(TransformError::InvalidInput(
                "X and y must have the same number of samples".to_string(),
            ));
        }

        // Add intercept column if needed
        let x_design = if self.includeintercept {
            let mut x_with_intercept = Array2::ones((n_samples, n_features + 1));
            x_with_intercept
                .slice_mut(scirs2_core::ndarray::s![.., 1..])
                .assign(x);
            x_with_intercept
        } else {
            x.to_owned()
        };

        // Solve normal equations: (X^T X + alpha*I) * beta = X^T y
        let xtx = x_design.t().dot(&x_design);
        let xty = x_design.t().dot(y);

        // Add regularization
        let mut regularized_xtx = xtx;
        let n_coeffs = regularized_xtx.shape()[0];
        for i in 0..n_coeffs {
            regularized_xtx[[i, i]] += self.alpha;
        }

        // Solve using simple Gaussian elimination (for small problems)
        self.coefficients = Some(self.solve_linear_system(&regularized_xtx, &xty)?);

        Ok(())
    }

    /// Predict using the fitted regressor
    fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
        let coeffs = self.coefficients.as_ref().ok_or_else(|| {
            TransformError::TransformationError(
                "Regressor must be fitted before prediction".to_string(),
            )
        })?;

        let x_design = if self.includeintercept {
            let (n_samples, n_features) = x.dim();
            let mut x_with_intercept = Array2::ones((n_samples, n_features + 1));
            x_with_intercept
                .slice_mut(scirs2_core::ndarray::s![.., 1..])
                .assign(x);
            x_with_intercept
        } else {
            x.to_owned()
        };

        Ok(x_design.dot(coeffs))
    }

    /// Simple linear system solver using Gaussian elimination
    fn solve_linear_system(&self, a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>> {
        let n = a.shape()[0];
        let mut aug_matrix = Array2::zeros((n, n + 1));

        // Create augmented matrix [A|b]
        aug_matrix
            .slice_mut(scirs2_core::ndarray::s![.., ..n])
            .assign(a);
        aug_matrix
            .slice_mut(scirs2_core::ndarray::s![.., n])
            .assign(b);

        // Forward elimination
        for i in 0..n {
            // Find pivot
            let mut max_row = i;
            for k in (i + 1)..n {
                if aug_matrix[[k, i]].abs() > aug_matrix[[max_row, i]].abs() {
                    max_row = k;
                }
            }

            // Swap rows
            if max_row != i {
                for j in 0..=n {
                    let temp = aug_matrix[[i, j]];
                    aug_matrix[[i, j]] = aug_matrix[[max_row, j]];
                    aug_matrix[[max_row, j]] = temp;
                }
            }

            // Check for singular matrix
            if aug_matrix[[i, i]].abs() < 1e-12 {
                return Err(TransformError::TransformationError(
                    "Singular matrix in regression".to_string(),
                ));
            }

            // Make diagonal element 1
            let pivot = aug_matrix[[i, i]];
            for j in i..=n {
                aug_matrix[[i, j]] /= pivot;
            }

            // Eliminate column
            for k in 0..n {
                if k != i {
                    let factor = aug_matrix[[k, i]];
                    for j in i..=n {
                        aug_matrix[[k, j]] -= factor * aug_matrix[[i, j]];
                    }
                }
            }
        }

        // Extract solution
        let mut solution = Array1::zeros(n);
        for i in 0..n {
            solution[i] = aug_matrix[[i, n]];
        }

        Ok(solution)
    }
}

/// Iterative Imputer using the MICE (Multiple Imputation by Chained Equations) algorithm
///
/// This transformer iteratively models each feature with missing values as a function
/// of other features. The algorithm performs multiple rounds of imputation where each
/// feature is predicted using the other features in a round-robin fashion.
///
/// MICE is particularly useful when:
/// - There are multiple features with missing values
/// - The missing patterns are complex
/// - You want to model relationships between features
pub struct IterativeImputer {
    /// Maximum number of iterations to perform
    max_iter: usize,
    /// Convergence tolerance (change in imputed values between iterations)
    tolerance: f64,
    /// Initial strategy for first round of imputation
    initial_strategy: ImputeStrategy,
    /// Random seed for reproducibility
    random_seed: Option<u64>,
    /// Missing value indicator
    missingvalues: f64,
    /// Regularization parameter for regression
    alpha: f64,
    /// Minimum improvement to continue iterating
    min_improvement: f64,

    // Internal state
    /// Training data for fitting predictors
    x_train_: Option<Array2<f64>>,
    /// Indices of features that had missing values during fitting
    missing_features_: Option<Vec<usize>>,
    /// Initial imputation values for features
    initial_values_: Option<Array1<f64>>,
    /// Whether the imputer has been fitted
    is_fitted_: bool,
}

impl IterativeImputer {
    /// Creates a new IterativeImputer
    ///
    /// # Arguments
    /// * `max_iter` - Maximum number of iterations
    /// * `tolerance` - Convergence tolerance
    /// * `initial_strategy` - Strategy for initial imputation
    /// * `missingvalues` - Value representing missing data
    /// * `alpha` - Regularization parameter for regression
    ///
    /// # Returns
    /// * A new IterativeImputer instance
    pub fn new(
        max_iter: usize,
        tolerance: f64,
        initial_strategy: ImputeStrategy,
        missingvalues: f64,
        alpha: f64,
    ) -> Self {
        IterativeImputer {
            max_iter,
            tolerance,
            initial_strategy,
            random_seed: None,
            missingvalues,
            alpha,
            min_improvement: 1e-6,
            x_train_: None,
            missing_features_: None,
            initial_values_: None,
            is_fitted_: false,
        }
    }

    /// Creates an IterativeImputer with default parameters
    ///
    /// Uses 10 iterations, 1e-3 tolerance, mean initial strategy, NaN missing values,
    /// and 1e-6 regularization.
    pub fn with_defaults() -> Self {
        Self::new(10, 1e-3, ImputeStrategy::Mean, f64::NAN, 1e-6)
    }

    /// Creates an IterativeImputer with specified max iterations and defaults for other parameters
    pub fn with_max_iter(_maxiter: usize) -> Self {
        Self::new(_maxiter, 1e-3, ImputeStrategy::Mean, f64::NAN, 1e-6)
    }

    /// Set the random seed for reproducible results
    pub fn with_random_seed(mut self, seed: u64) -> Self {
        self.random_seed = Some(seed);
        self
    }

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

    /// Set the minimum improvement threshold
    pub fn with_min_improvement(mut self, minimprovement: f64) -> Self {
        self.min_improvement = minimprovement;
        self
    }

    /// Fits the IterativeImputer to the input data
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<()>` - Ok if successful, Err otherwise
    pub fn fit<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<()>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));
        let (n_samples, n_features) = x_f64.dim();

        if n_samples == 0 || n_features == 0 {
            return Err(TransformError::InvalidInput("Empty input data".to_string()));
        }

        // Find features that have missing values
        let missing_features: Vec<usize> = (0..n_features)
            .filter(|&j| x_f64.column(j).iter().any(|&val| self.is_missing(val)))
            .collect();

        if missing_features.is_empty() {
            // No missing values, store data as-is
            self.x_train_ = Some(x_f64);
            self.missing_features_ = Some(Vec::new());
            self.initial_values_ = Some(Array1::zeros(0));
            self.is_fitted_ = true;
            return Ok(());
        }

        // Compute initial imputation values for each feature
        let mut initial_values = Array1::zeros(n_features);
        for &feature_idx in &missing_features {
            let feature_data: Vec<f64> = x_f64
                .column(feature_idx)
                .iter()
                .filter(|&&val| !self.is_missing(val))
                .copied()
                .collect();

            if feature_data.is_empty() {
                return Err(TransformError::InvalidInput(format!(
                    "All values are missing in feature {feature_idx}"
                )));
            }

            initial_values[feature_idx] = match &self.initial_strategy {
                ImputeStrategy::Mean => {
                    feature_data.iter().sum::<f64>() / feature_data.len() as f64
                }
                ImputeStrategy::Median => {
                    let mut sorted_data = feature_data;
                    sorted_data.sort_by(|a, b| a.partial_cmp(b).expect("Operation failed"));
                    let len = sorted_data.len();
                    if len.is_multiple_of(2) {
                        (sorted_data[len / 2 - 1] + sorted_data[len / 2]) / 2.0
                    } else {
                        sorted_data[len / 2]
                    }
                }
                ImputeStrategy::MostFrequent => {
                    // For continuous data, use mean as approximation
                    feature_data.iter().sum::<f64>() / feature_data.len() as f64
                }
                ImputeStrategy::Constant(value) => *value,
            };
        }

        self.x_train_ = Some(x_f64);
        self.missing_features_ = Some(missing_features);
        self.initial_values_ = Some(initial_values);
        self.is_fitted_ = true;

        Ok(())
    }

    /// Transforms the input data by imputing missing values using MICE
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - Transformed data with missing values imputed
    pub fn transform<S>(&self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        if !self.is_fitted_ {
            return Err(TransformError::TransformationError(
                "IterativeImputer must be fitted before transform".to_string(),
            ));
        }

        let x_f64 = x.mapv(|x| NumCast::from(x).unwrap_or(0.0));
        let missing_features = self.missing_features_.as_ref().expect("Operation failed");

        if missing_features.is_empty() {
            // No missing values in training data, return as-is
            return Ok(x_f64);
        }

        let initial_values = self.initial_values_.as_ref().expect("Operation failed");
        let (n_samples, n_features) = x_f64.dim();

        // Start with initial imputation
        let mut imputed_data = x_f64.clone();
        self.apply_initial_imputation(&mut imputed_data, initial_values)?;

        // MICE iterations
        for iteration in 0..self.max_iter {
            let mut max_change = 0.0;
            let old_imputed_data = imputed_data.clone();

            // Iterate through each feature with missing values
            for &feature_idx in missing_features {
                // Find samples with missing values for this feature
                let missing_mask: Vec<bool> = (0..n_samples)
                    .map(|i| self.is_missing(x_f64[[i, feature_idx]]))
                    .collect();

                if !missing_mask.iter().any(|&x| x) {
                    continue; // No missing values for this feature
                }

                // Prepare predictors (all other features)
                let predictor_indices: Vec<usize> =
                    (0..n_features).filter(|&i| i != feature_idx).collect();

                // Create training data from samples without missing values for this feature
                let (train_x, train_y) = self.prepare_training_data(
                    &imputed_data,
                    feature_idx,
                    &predictor_indices,
                    &missing_mask,
                )?;

                if train_x.is_empty() {
                    continue; // Cannot train predictor
                }

                // Fit predictor
                let mut regressor = SimpleRegressor::new(true, self.alpha);
                regressor.fit(&train_x, &train_y)?;

                // Predict missing values
                let test_x =
                    self.prepare_test_data(&imputed_data, &predictor_indices, &missing_mask)?;

                if !test_x.is_empty() {
                    let predictions = regressor.predict(&test_x)?;

                    // Update imputed values
                    let mut pred_idx = 0;
                    for i in 0..n_samples {
                        if missing_mask[i] {
                            let old_value = imputed_data[[i, feature_idx]];
                            let new_value = predictions[pred_idx];
                            imputed_data[[i, feature_idx]] = new_value;

                            let change = (new_value - old_value).abs();
                            max_change = max_change.max(change);
                            pred_idx += 1;
                        }
                    }
                }
            }

            // Check convergence
            if max_change < self.tolerance {
                break;
            }

            // Check for minimum improvement
            if iteration > 0 {
                let total_change = self.compute_total_change(&old_imputed_data, &imputed_data);
                if total_change < self.min_improvement {
                    break;
                }
            }
        }

        Ok(imputed_data)
    }

    /// Fits the imputer and transforms the data in one step
    ///
    /// # Arguments
    /// * `x` - The input data, shape (n_samples, n_features)
    ///
    /// # Returns
    /// * `Result<Array2<f64>>` - Transformed data with missing values imputed
    pub fn fit_transform<S>(&mut self, x: &ArrayBase<S, Ix2>) -> Result<Array2<f64>>
    where
        S: Data,
        S::Elem: Float + NumCast,
    {
        self.fit(x)?;
        self.transform(x)
    }

    /// Apply initial imputation using the specified strategy
    fn apply_initial_imputation(
        &self,
        data: &mut Array2<f64>,
        initial_values: &Array1<f64>,
    ) -> Result<()> {
        let (n_samples, n_features) = data.dim();

        for i in 0..n_samples {
            for j in 0..n_features {
                if self.is_missing(data[[i, j]]) {
                    data[[i, j]] = initial_values[j];
                }
            }
        }

        Ok(())
    }

    /// Prepare training data for a specific feature
    fn prepare_training_data(
        &self,
        data: &Array2<f64>,
        target_feature: usize,
        predictor_indices: &[usize],
        missing_mask: &[bool],
    ) -> Result<(Array2<f64>, Array1<f64>)> {
        let n_samples = data.shape()[0];
        let n_predictors = predictor_indices.len();

        // Count non-missing samples
        let non_missing_count = missing_mask.iter().filter(|&&x| !x).count();

        if non_missing_count == 0 {
            return Ok((Array2::zeros((0, n_predictors)), Array1::zeros(0)));
        }

        let mut train_x = Array2::zeros((non_missing_count, n_predictors));
        let mut train_y = Array1::zeros(non_missing_count);

        let mut train_idx = 0;
        for i in 0..n_samples {
            if !missing_mask[i] {
                // Copy predictor features
                for (pred_j, &orig_j) in predictor_indices.iter().enumerate() {
                    train_x[[train_idx, pred_j]] = data[[i, orig_j]];
                }
                // Copy target _feature
                train_y[train_idx] = data[[i, target_feature]];
                train_idx += 1;
            }
        }

        Ok((train_x, train_y))
    }

    /// Prepare test data for prediction
    fn prepare_test_data(
        &self,
        data: &Array2<f64>,
        predictor_indices: &[usize],
        missing_mask: &[bool],
    ) -> Result<Array2<f64>> {
        let n_samples = data.shape()[0];
        let n_predictors = predictor_indices.len();

        // Count missing samples
        let missing_count = missing_mask.iter().filter(|&&x| x).count();

        if missing_count == 0 {
            return Ok(Array2::zeros((0, n_predictors)));
        }

        let mut test_x = Array2::zeros((missing_count, n_predictors));

        let mut test_idx = 0;
        for i in 0..n_samples {
            if missing_mask[i] {
                // Copy predictor features
                for (pred_j, &orig_j) in predictor_indices.iter().enumerate() {
                    test_x[[test_idx, pred_j]] = data[[i, orig_j]];
                }
                test_idx += 1;
            }
        }

        Ok(test_x)
    }

    /// Compute total change between two imputation iterations
    fn compute_total_change(&self, old_data: &Array2<f64>, newdata: &Array2<f64>) -> f64 {
        let diff = newdata - old_data;
        diff.iter().map(|&x| x * x).sum::<f64>().sqrt()
    }

    /// Check if a value is considered missing
    fn is_missing(&self, value: f64) -> bool {
        if self.missingvalues.is_nan() {
            value.is_nan()
        } else {
            (value - self.missingvalues).abs() < f64::EPSILON
        }
    }
}

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

    #[test]
    fn test_simple_imputer_mean() {
        // Create test data with NaN values
        let data = Array::from_shape_vec(
            (4, 3),
            vec![
                1.0,
                2.0,
                3.0,
                f64::NAN,
                5.0,
                6.0,
                7.0,
                f64::NAN,
                9.0,
                10.0,
                11.0,
                f64::NAN,
            ],
        )
        .expect("Operation failed");

        let mut imputer = SimpleImputer::with_strategy(ImputeStrategy::Mean);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Check shape is preserved
        assert_eq!(transformed.shape(), &[4, 3]);

        // Check that mean values were used for imputation
        // Column 0: mean of [1.0, 7.0, 10.0] = 6.0
        // Column 1: mean of [2.0, 5.0, 11.0] = 6.0
        // Column 2: mean of [3.0, 6.0, 9.0] = 6.0

        assert_abs_diff_eq!(transformed[[0, 0]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[1, 0]], 6.0, epsilon = 1e-10); // Imputed
        assert_abs_diff_eq!(transformed[[2, 0]], 7.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[3, 0]], 10.0, epsilon = 1e-10);

        assert_abs_diff_eq!(transformed[[0, 1]], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[1, 1]], 5.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[2, 1]], 6.0, epsilon = 1e-10); // Imputed
        assert_abs_diff_eq!(transformed[[3, 1]], 11.0, epsilon = 1e-10);

        assert_abs_diff_eq!(transformed[[0, 2]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[1, 2]], 6.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[2, 2]], 9.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[3, 2]], 6.0, epsilon = 1e-10); // Imputed
    }

    #[test]
    fn test_simple_imputer_median() {
        // Create test data with NaN values
        let data = Array::from_shape_vec(
            (5, 2),
            vec![
                1.0,
                10.0,
                f64::NAN,
                20.0,
                3.0,
                f64::NAN,
                4.0,
                40.0,
                5.0,
                50.0,
            ],
        )
        .expect("Operation failed");

        let mut imputer = SimpleImputer::with_strategy(ImputeStrategy::Median);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Check shape is preserved
        assert_eq!(transformed.shape(), &[5, 2]);

        // Column 0: median of [1.0, 3.0, 4.0, 5.0] = 3.5
        // Column 1: median of [10.0, 20.0, 40.0, 50.0] = 30.0

        assert_abs_diff_eq!(transformed[[1, 0]], 3.5, epsilon = 1e-10); // Imputed
        assert_abs_diff_eq!(transformed[[2, 1]], 30.0, epsilon = 1e-10); // Imputed
    }

    #[test]
    fn test_simple_imputer_constant() {
        // Create test data with NaN values
        let data = Array::from_shape_vec((3, 2), vec![1.0, f64::NAN, f64::NAN, 3.0, 4.0, 5.0])
            .expect("Operation failed");

        let mut imputer = SimpleImputer::with_strategy(ImputeStrategy::Constant(99.0));
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Check that constant value was used for imputation
        assert_abs_diff_eq!(transformed[[0, 1]], 99.0, epsilon = 1e-10); // Imputed
        assert_abs_diff_eq!(transformed[[1, 0]], 99.0, epsilon = 1e-10); // Imputed

        // Non-missing values should remain unchanged
        assert_abs_diff_eq!(transformed[[0, 0]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[1, 1]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[2, 0]], 4.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[2, 1]], 5.0, epsilon = 1e-10);
    }

    #[test]
    fn test_missing_indicator() {
        // Create test data with NaN values
        let data = Array::from_shape_vec(
            (3, 4),
            vec![
                1.0,
                f64::NAN,
                3.0,
                4.0,
                f64::NAN,
                6.0,
                f64::NAN,
                8.0,
                9.0,
                10.0,
                11.0,
                f64::NAN,
            ],
        )
        .expect("Operation failed");

        let mut indicator = MissingIndicator::with_nan();
        let indicators = indicator.fit_transform(&data).expect("Operation failed");

        // All features have missing values, so output shape should be (3, 4)
        assert_eq!(indicators.shape(), &[3, 4]);

        // Check indicators
        assert_abs_diff_eq!(indicators[[0, 0]], 0.0, epsilon = 1e-10); // Not missing
        assert_abs_diff_eq!(indicators[[0, 1]], 1.0, epsilon = 1e-10); // Missing
        assert_abs_diff_eq!(indicators[[0, 2]], 0.0, epsilon = 1e-10); // Not missing
        assert_abs_diff_eq!(indicators[[0, 3]], 0.0, epsilon = 1e-10); // Not missing

        assert_abs_diff_eq!(indicators[[1, 0]], 1.0, epsilon = 1e-10); // Missing
        assert_abs_diff_eq!(indicators[[1, 1]], 0.0, epsilon = 1e-10); // Not missing
        assert_abs_diff_eq!(indicators[[1, 2]], 1.0, epsilon = 1e-10); // Missing
        assert_abs_diff_eq!(indicators[[1, 3]], 0.0, epsilon = 1e-10); // Not missing

        assert_abs_diff_eq!(indicators[[2, 0]], 0.0, epsilon = 1e-10); // Not missing
        assert_abs_diff_eq!(indicators[[2, 1]], 0.0, epsilon = 1e-10); // Not missing
        assert_abs_diff_eq!(indicators[[2, 2]], 0.0, epsilon = 1e-10); // Not missing
        assert_abs_diff_eq!(indicators[[2, 3]], 1.0, epsilon = 1e-10); // Missing
    }

    #[test]
    fn test_imputer_errors() {
        // Test error when all values are missing in a feature
        let data = Array::from_shape_vec((2, 2), vec![f64::NAN, 1.0, f64::NAN, 2.0])
            .expect("Operation failed");

        let mut imputer = SimpleImputer::with_strategy(ImputeStrategy::Mean);
        assert!(imputer.fit(&data).is_err());
    }

    #[test]
    fn test_knn_imputer_basic() {
        // Create test data with missing values
        // Dataset:
        // [1.0, 2.0, 3.0]
        // [4.0, NaN, 6.0]
        // [7.0, 8.0, NaN]
        // [10.0, 11.0, 12.0]
        let data = Array::from_shape_vec(
            (4, 3),
            vec![
                1.0,
                2.0,
                3.0,
                4.0,
                f64::NAN,
                6.0,
                7.0,
                8.0,
                f64::NAN,
                10.0,
                11.0,
                12.0,
            ],
        )
        .expect("Operation failed");

        let mut imputer = KNNImputer::with_n_neighbors(2);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Check shape is preserved
        assert_eq!(transformed.shape(), &[4, 3]);

        // Check that non-missing values are unchanged
        assert_abs_diff_eq!(transformed[[0, 0]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[0, 1]], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[0, 2]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[3, 0]], 10.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[3, 1]], 11.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[3, 2]], 12.0, epsilon = 1e-10);

        // Missing values should have been imputed (values depend on neighbors chosen)
        assert!(!transformed[[1, 1]].is_nan()); // Should be imputed
        assert!(!transformed[[2, 2]].is_nan()); // Should be imputed
    }

    #[test]
    fn test_knn_imputer_simple_case() {
        // Simple test case where neighbors are easy to determine
        let data = Array::from_shape_vec((3, 2), vec![1.0, 1.0, f64::NAN, 2.0, 3.0, 3.0])
            .expect("Operation failed");

        let mut imputer = KNNImputer::with_n_neighbors(2);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // The missing value [?, 2.0] should be imputed based on nearest neighbors
        // Neighbors should be [1.0, 1.0] and [3.0, 3.0]
        // Expected imputed value for feature 0 should be close to 2.0 (average of 1.0 and 3.0)
        assert_abs_diff_eq!(transformed[[1, 0]], 2.0, epsilon = 1e-1);
    }

    #[test]
    fn test_knn_imputer_manhattan_distance() {
        let data =
            Array::from_shape_vec((4, 2), vec![0.0, 0.0, 1.0, f64::NAN, 2.0, 2.0, 10.0, 10.0])
                .expect("Operation failed");

        let mut imputer = KNNImputer::new(
            2,
            DistanceMetric::Manhattan,
            WeightingScheme::Uniform,
            f64::NAN,
        );
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // With Manhattan distance, the closest neighbors to [1.0, ?] should be
        // [0.0, 0.0] and [2.0, 2.0], not [10.0, 10.0]
        assert!(!transformed[[1, 1]].is_nan());
        // The imputed value should be reasonable (around 1.0)
        assert!(transformed[[1, 1]] < 5.0); // Should not be close to 10.0
    }

    #[test]
    fn test_knn_imputer_validation_errors() {
        // Test insufficient samples
        let small_data =
            Array::from_shape_vec((2, 2), vec![1.0, 2.0, 3.0, 4.0]).expect("Operation failed");
        let mut imputer = KNNImputer::with_n_neighbors(5); // More neighbors than samples
        assert!(imputer.fit(&small_data).is_err());

        // Test transform without fit
        let data = Array::from_shape_vec((4, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
            .expect("Operation failed");
        let unfitted_imputer = KNNImputer::with_n_neighbors(2);
        assert!(unfitted_imputer.transform(&data).is_err());
    }

    #[test]
    fn test_knn_imputer_no_missing_values() {
        // Test data with no missing values
        let data = Array::from_shape_vec((3, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
            .expect("Operation failed");

        let mut imputer = KNNImputer::with_n_neighbors(2);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Should be unchanged
        assert_eq!(transformed, data);
    }

    #[test]
    fn test_knn_imputer_accessors() {
        let imputer = KNNImputer::new(
            3,
            DistanceMetric::Manhattan,
            WeightingScheme::Distance,
            -999.0,
        );

        assert_eq!(imputer._nneighbors(), 3);
        assert_eq!(imputer.metric(), &DistanceMetric::Manhattan);
        assert_eq!(imputer.weights(), &WeightingScheme::Distance);
    }

    #[test]
    fn test_knn_imputer_multiple_missing_features() {
        // Test sample with multiple missing features
        let data = Array::from_shape_vec(
            (4, 3),
            vec![
                1.0,
                2.0,
                3.0,
                f64::NAN,
                f64::NAN,
                6.0,
                7.0,
                8.0,
                9.0,
                10.0,
                11.0,
                12.0,
            ],
        )
        .expect("Operation failed");

        let mut imputer = KNNImputer::with_n_neighbors(2);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Both missing values should be imputed
        assert!(!transformed[[1, 0]].is_nan());
        assert!(!transformed[[1, 1]].is_nan());
        // Non-missing value should remain unchanged
        assert_abs_diff_eq!(transformed[[1, 2]], 6.0, epsilon = 1e-10);
    }

    #[test]
    fn test_iterative_imputer_basic() {
        // Create test data with missing values that have relationships
        // Dataset with correlated features:
        // Feature 0: [1.0, 2.0, 3.0, NaN]
        // Feature 1: [2.0, 4.0, NaN, 8.0] (roughly 2 * feature 0)
        let data = Array::from_shape_vec(
            (4, 2),
            vec![1.0, 2.0, 2.0, 4.0, 3.0, f64::NAN, f64::NAN, 8.0],
        )
        .expect("Operation failed");

        let mut imputer = IterativeImputer::with_max_iter(5);
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Check that missing values have been imputed
        assert!(!transformed[[2, 1]].is_nan()); // Feature 1 in row 2
        assert!(!transformed[[3, 0]].is_nan()); // Feature 0 in row 3

        // Non-missing values should remain unchanged
        assert_abs_diff_eq!(transformed[[0, 0]], 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[0, 1]], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[1, 0]], 2.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[1, 1]], 4.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[2, 0]], 3.0, epsilon = 1e-10);
        assert_abs_diff_eq!(transformed[[3, 1]], 8.0, epsilon = 1e-10);

        // Check that the imputed values are reasonable given the linear relationship
        // Feature 1 should be approximately 2 * feature 0
        let imputed_f1_row2 = transformed[[2, 1]];
        let expected_f1_row2 = 2.0 * transformed[[2, 0]]; // 2 * 3.0 = 6.0
        assert!((imputed_f1_row2 - expected_f1_row2).abs() < 1.0); // Allow some tolerance

        let imputed_f0_row3 = transformed[[3, 0]];
        let expected_f0_row3 = transformed[[3, 1]] / 2.0; // 8.0 / 2.0 = 4.0
        assert!((imputed_f0_row3 - expected_f0_row3).abs() < 1.0); // Allow some tolerance
    }

    #[test]
    fn test_iterative_imputer_no_missing_values() {
        // Test with data that has no missing values
        let data = Array::from_shape_vec((3, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
            .expect("Operation failed");

        let mut imputer = IterativeImputer::with_defaults();
        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // Data should remain unchanged
        for i in 0..3 {
            for j in 0..2 {
                assert_abs_diff_eq!(transformed[[i, j]], data[[i, j]], epsilon = 1e-10);
            }
        }
    }

    #[test]
    fn test_iterative_imputer_convergence() {
        // Test with data that should converge quickly
        let data = Array::from_shape_vec(
            (5, 3),
            vec![
                1.0,
                2.0,
                3.0,
                2.0,
                f64::NAN,
                6.0,
                3.0,
                6.0,
                f64::NAN,
                4.0,
                8.0,
                12.0,
                f64::NAN,
                10.0,
                15.0,
            ],
        )
        .expect("Operation failed");

        let mut imputer = IterativeImputer::new(
            20,   // max_iter
            1e-4, // tolerance
            ImputeStrategy::Mean,
            f64::NAN,
            1e-6, // alpha
        );

        let transformed = imputer.fit_transform(&data).expect("Operation failed");

        // All missing values should be imputed
        for i in 0..5 {
            for j in 0..3 {
                assert!(!transformed[[i, j]].is_nan());
            }
        }
    }

    #[test]
    fn test_iterative_imputer_different_strategies() {
        let data = Array::from_shape_vec(
            (4, 2),
            vec![1.0, f64::NAN, 2.0, 4.0, 3.0, 6.0, f64::NAN, 8.0],
        )
        .expect("Operation failed");

        // Test with median initial strategy
        let mut imputer_median =
            IterativeImputer::new(5, 1e-3, ImputeStrategy::Median, f64::NAN, 1e-6);
        let transformed_median = imputer_median
            .fit_transform(&data)
            .expect("Operation failed");
        assert!(!transformed_median[[0, 1]].is_nan());
        assert!(!transformed_median[[3, 0]].is_nan());

        // Test with constant initial strategy
        let mut imputer_constant =
            IterativeImputer::new(5, 1e-3, ImputeStrategy::Constant(999.0), f64::NAN, 1e-6);
        let transformed_constant = imputer_constant
            .fit_transform(&data)
            .expect("Operation failed");
        assert!(!transformed_constant[[0, 1]].is_nan());
        assert!(!transformed_constant[[3, 0]].is_nan());
    }

    #[test]
    fn test_iterative_imputer_builder_methods() {
        let imputer = IterativeImputer::with_defaults()
            .with_random_seed(42)
            .with_alpha(1e-3)
            .with_min_improvement(1e-5);

        assert_eq!(imputer.random_seed, Some(42));
        assert_abs_diff_eq!(imputer.alpha, 1e-3, epsilon = 1e-10);
        assert_abs_diff_eq!(imputer.min_improvement, 1e-5, epsilon = 1e-10);
    }

    #[test]
    fn test_iterative_imputer_errors() {
        // Test error when not fitted
        let imputer = IterativeImputer::with_defaults();
        let test_data =
            Array::from_shape_vec((2, 2), vec![1.0, 2.0, 3.0, 4.0]).expect("Operation failed");
        assert!(imputer.transform(&test_data).is_err());

        // Test error when all values are missing in a feature
        let bad_data =
            Array::from_shape_vec((3, 2), vec![f64::NAN, 1.0, f64::NAN, 2.0, f64::NAN, 3.0])
                .expect("Operation failed");
        let mut imputer = IterativeImputer::with_defaults();
        assert!(imputer.fit(&bad_data).is_err());
    }

    #[test]
    fn test_simple_regressor() {
        // Test the internal SimpleRegressor
        let x = Array::from_shape_vec((3, 2), vec![1.0, 2.0, 2.0, 3.0, 3.0, 4.0])
            .expect("Operation failed");
        let y = Array::from_vec(vec![5.0, 8.0, 11.0]); // y = 2*x1 + x2 + 1

        let mut regressor = SimpleRegressor::new(true, 1e-6);
        regressor.fit(&x, &y).expect("Operation failed");

        let test_x =
            Array::from_shape_vec((2, 2), vec![4.0, 5.0, 5.0, 6.0]).expect("Operation failed");
        let predictions = regressor.predict(&test_x).expect("Operation failed");

        // Check that predictions are reasonable
        assert_eq!(predictions.len(), 2);
        assert!(!predictions[0].is_nan());
        assert!(!predictions[1].is_nan());
    }
}