sklears-feature-extraction 0.2.0

Feature extraction from raw data (text, images)
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
//! Feature engineering utilities

use crate::{Float, SklResult};
use rayon::prelude::*;
use scirs2_core::ndarray::{s, Array1, Array2, ArrayView1, ArrayView2, Axis};
use sklears_core::prelude::{Fit, SklearsError, Transform};
use sklears_core::traits::{Estimator, Untrained};

// Re-export basic feature engineering methods
pub use crate::basic_features::*;

// Re-export RBF and kernel approximation methods
pub use crate::rbf_methods::*;

// Re-export temporal feature extraction methods
pub use crate::temporal_features::*;

// Re-export statistical feature extraction methods
pub use crate::statistical_features::*;

// Re-export sketching and sampling methods
pub use crate::sketching_sampling::*;

// =============================================================================
// Re-exports from time_series_features for backward compatibility
// =============================================================================

// Time series wavelet transform components have been moved to time_series_features.rs
pub use crate::time_series_features::{
    TimeSeriesWaveletExtractor, TimeSeriesWaveletType, WaveletFeatureType,
};

// Time-frequency feature extractor has been moved to time_series_features.rs
pub use crate::time_series_features::TimeFrequencyExtractor;

// =============================================================================
// Re-exports from topological_features for backward compatibility
// =============================================================================

// Topological feature extractors have been moved to topological_features.rs
pub use crate::topological_features::{
    MapperExtractor, PersistentHomologyExtractor, SimplicialComplexExtractor,
};

#[allow(non_snake_case)]
#[cfg(test)]
mod simplicial_complex_tests {
    use super::*;
    use scirs2_core::ndarray::Array2;

    #[test]
    fn test_simplicial_complex_extractor_basic() {
        // Create a simple 2D dataset forming a triangle
        let data = Array2::from_shape_vec(
            (3, 2),
            vec![
                0.0, 0.0, // Point 0
                1.0, 0.0, // Point 1
                0.5, 0.8, // Point 2
            ],
        )
        .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .max_dimension(2)
            .distance_threshold(1.5)
            .include_face_counts(true)
            .include_euler_characteristic(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have features for face counts (3 dimensions: 0, 1, 2) + euler characteristic
        assert_eq!(features.len(), 4);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }

        // Should have 3 vertices
        assert_eq!(features[0], 3.0);

        // Should have 3 edges (triangle)
        assert_eq!(features[1], 3.0);

        // Should have 1 triangle
        assert_eq!(features[2], 1.0);

        // Euler characteristic for triangle should be 1 (3 - 3 + 1 = 1)
        assert_eq!(features[3], 1.0);
    }

    #[test]
    fn test_simplicial_complex_extractor_depth_measures() {
        let data = Array2::from_shape_vec(
            (4, 2),
            vec![
                0.0, 0.0, // Point 0
                1.0, 0.0, // Point 1
                0.5, 0.8, // Point 2
                0.5, 0.2, // Point 3
            ],
        )
        .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .max_dimension(2)
            .distance_threshold(1.0)
            .include_face_counts(false)
            .include_euler_characteristic(false)
            .include_depth_measures(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have depth measures: max_dim, mean_depth, max_depth, min_depth, complexity
        assert_eq!(features.len(), 5);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }

        // Max dimension should be <= 2
        assert!(features[0] <= 2.0);

        // Mean, max, min depths should be positive
        assert!(features[1] > 0.0);
        assert!(features[2] > 0.0);
        assert!(features[3] > 0.0);

        // Complexity should be between 0 and 1
        assert!(features[4] >= 0.0 && features[4] <= 1.0);
    }

    #[test]
    fn test_simplicial_complex_extractor_boundary_properties() {
        let data = Array2::from_shape_vec(
            (4, 2),
            vec![
                0.0, 0.0, // Point 0
                1.0, 0.0, // Point 1
                0.0, 1.0, // Point 2
                1.0, 1.0, // Point 3
            ],
        )
        .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .max_dimension(2)
            .distance_threshold(1.5)
            .include_face_counts(false)
            .include_euler_characteristic(false)
            .include_boundary_properties(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have boundary properties for dimensions 1 and 2
        // For each dimension: faces_dim, faces_dim_minus_1, density
        assert_eq!(features.len(), 6);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }

        // All counts should be non-negative
        for &feature in &features {
            assert!(
                feature >= 0.0,
                "Feature should be non-negative: {}",
                feature
            );
        }
    }

    #[test]
    fn test_simplicial_complex_extractor_normalization() {
        let data = Array2::from_shape_vec(
            (5, 2),
            vec![
                0.0, 0.0, // Point 0
                1.0, 0.0, // Point 1
                0.5, 0.8, // Point 2
                0.0, 1.0, // Point 3
                1.0, 1.0, // Point 4
            ],
        )
        .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .max_dimension(2)
            .distance_threshold(1.5)
            .include_face_counts(true)
            .include_euler_characteristic(false)
            .normalize_by_vertices(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have face counts normalized by number of vertices
        assert_eq!(features.len(), 3);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }

        // Vertices count should be 1.0 (normalized)
        assert_eq!(features[0], 1.0);

        // Other counts should be between 0 and some reasonable upper bound
        for i in 1..features.len() {
            assert!(features[i] >= 0.0 && features[i] <= 10.0);
        }
    }

    #[test]
    fn test_simplicial_complex_extractor_manhattan_distance() {
        let data = Array2::from_shape_vec(
            (3, 2),
            vec![
                0.0, 0.0, // Point 0
                1.0, 0.0, // Point 1
                0.0, 1.0, // Point 2
            ],
        )
        .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .max_dimension(2)
            .distance_threshold(1.5)
            .distance_metric("manhattan")
            .include_face_counts(true)
            .include_euler_characteristic(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have face counts + euler characteristic
        assert_eq!(features.len(), 4);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }

        // Should still form a valid simplicial complex
        assert_eq!(features[0], 3.0); // vertices
        assert!(features[1] > 0.0); // edges
        assert!(features[3].is_finite()); // euler characteristic
    }

    #[test]
    fn test_simplicial_complex_extractor_empty_data() {
        let data = Array2::zeros((0, 2));
        let extractor = SimplicialComplexExtractor::new();

        let result = extractor.extract_features(&data.view());
        assert!(result.is_err(), "Should return error for empty data");
    }

    #[test]
    fn test_simplicial_complex_extractor_no_features_selected() {
        let data = Array2::from_shape_vec((3, 2), vec![0.0, 0.0, 1.0, 0.0, 0.5, 0.8])
            .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .include_face_counts(false)
            .include_euler_characteristic(false)
            .include_boundary_properties(false)
            .include_depth_measures(false);

        let result = extractor.extract_features(&data.view());
        assert!(
            result.is_err(),
            "Should return error when no features are selected"
        );
    }

    #[test]
    fn test_simplicial_complex_extractor_single_point() {
        let data =
            Array2::from_shape_vec((1, 2), vec![0.0, 0.0]).expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new()
            .max_dimension(2)
            .distance_threshold(1.0)
            .include_face_counts(true)
            .include_euler_characteristic(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have face counts + euler characteristic
        assert_eq!(features.len(), 4);

        // Should have 1 vertex, 0 edges, 0 triangles
        assert_eq!(features[0], 1.0);
        assert_eq!(features[1], 0.0);
        assert_eq!(features[2], 0.0);

        // Euler characteristic should be 1
        assert_eq!(features[3], 1.0);
    }

    #[test]
    fn test_simplicial_complex_extractor_invalid_distance_metric() {
        let data = Array2::from_shape_vec((3, 2), vec![0.0, 0.0, 1.0, 0.0, 0.5, 0.8])
            .expect("operation should succeed");

        let extractor = SimplicialComplexExtractor::new().distance_metric("invalid");

        let result = extractor.extract_features(&data.view());
        assert!(
            result.is_err(),
            "Should return error for invalid distance metric"
        );
    }
}

#[allow(non_snake_case)]
#[cfg(test)]
mod parallel_feature_tests {
    use super::*;
    use scirs2_core::ndarray::Array2;

    #[test]
    fn test_parallel_feature_extractor_basic() {
        let data = Array2::from_shape_vec((100, 5), (0..500).map(|x| x as f64).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(20)
            .include_statistical_features(true)
            .include_distance_matrix(false)
            .include_correlation_features(false);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have statistical features: 9 features total
        assert_eq!(features.len(), 9);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }
    }

    #[test]
    fn test_parallel_feature_extractor_distance_matrix() {
        let data = Array2::from_shape_vec((50, 3), (0..150).map(|x| (x as f64) * 0.1).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(10)
            .include_statistical_features(false)
            .include_distance_matrix(true)
            .distance_metric("euclidean");

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have distance matrix features: mean, std, min, max
        assert_eq!(features.len(), 4);

        // All features should be finite and non-negative
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
            assert!(
                feature >= 0.0,
                "Distance feature should be non-negative: {}",
                feature
            );
        }

        // Mean distance should be > 0 for non-identical points
        assert!(features[0] > 0.0, "Mean distance should be positive");
    }

    #[test]
    fn test_parallel_feature_extractor_correlation() {
        let data = Array2::from_shape_vec((80, 4), (0..320).map(|x| (x as f64) * 0.01).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(15)
            .include_statistical_features(false)
            .include_distance_matrix(false)
            .include_correlation_features(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have correlation features: mean, std, max_abs
        assert_eq!(features.len(), 3);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }

        // Max absolute correlation should be between 0 and 1
        assert!(
            features[2] >= 0.0 && features[2] <= 1.0,
            "Max absolute correlation should be in [0,1]: {}",
            features[2]
        );
    }

    #[test]
    fn test_parallel_feature_extractor_all_features() {
        let data = Array2::from_shape_vec((60, 3), (0..180).map(|x| (x as f64) * 0.05).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(12)
            .include_statistical_features(true)
            .include_distance_matrix(true)
            .include_correlation_features(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should have 9 + 4 + 3 = 16 features
        assert_eq!(features.len(), 16);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }
    }

    #[test]
    fn test_parallel_feature_extractor_different_metrics() {
        let data = Array2::from_shape_vec((30, 2), (0..60).map(|x| x as f64).collect())
            .expect("operation should succeed");

        // Test Manhattan distance
        let extractor_manhattan = ParallelFeatureExtractor::new()
            .include_statistical_features(false)
            .include_distance_matrix(true)
            .distance_metric("manhattan");

        let features_manhattan = extractor_manhattan
            .extract_features(&data.view())
            .expect("operation should succeed");
        assert_eq!(features_manhattan.len(), 4);

        // Test Cosine distance
        let extractor_cosine = ParallelFeatureExtractor::new()
            .include_statistical_features(false)
            .include_distance_matrix(true)
            .distance_metric("cosine");

        let features_cosine = extractor_cosine
            .extract_features(&data.view())
            .expect("operation should succeed");
        assert_eq!(features_cosine.len(), 4);

        // Features should be different for different metrics
        assert_ne!(features_manhattan[0], features_cosine[0]);
    }

    #[test]
    fn test_parallel_feature_extractor_custom_threads() {
        let data = Array2::from_shape_vec((40, 3), (0..120).map(|x| x as f64).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(8)
            .num_threads(2)
            .include_statistical_features(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should extract features successfully with custom thread count
        assert_eq!(features.len(), 9);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }
    }

    #[test]
    fn test_parallel_feature_extractor_small_data() {
        let data = Array2::from_shape_vec(
            (5, 2),
            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
        )
        .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(2)
            .include_statistical_features(true)
            .include_distance_matrix(true)
            .include_correlation_features(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should handle small datasets gracefully
        assert_eq!(features.len(), 16);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }
    }

    #[test]
    fn test_parallel_feature_extractor_single_sample() {
        let data =
            Array2::from_shape_vec((1, 3), vec![1.0, 2.0, 3.0]).expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .include_statistical_features(true)
            .include_distance_matrix(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should handle single sample (distance matrix features will be zeros)
        assert_eq!(features.len(), 13); // 9 statistical + 4 distance (zeros)

        // Distance features should be zero for single sample
        for i in 9..13 {
            assert_eq!(
                features[i], 0.0,
                "Distance feature should be zero for single sample"
            );
        }
    }

    #[test]
    fn test_parallel_feature_extractor_empty_data() {
        let data = Array2::zeros((0, 3));
        let extractor = ParallelFeatureExtractor::new();

        let result = extractor.extract_features(&data.view());
        assert!(result.is_err(), "Should return error for empty data");
    }

    #[test]
    fn test_parallel_feature_extractor_no_features_selected() {
        let data = Array2::from_shape_vec((10, 2), (0..20).map(|x| x as f64).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .include_statistical_features(false)
            .include_distance_matrix(false)
            .include_correlation_features(false);

        let result = extractor.extract_features(&data.view());
        assert!(
            result.is_err(),
            "Should return error when no features are selected"
        );
    }

    #[test]
    fn test_parallel_feature_extractor_invalid_distance_metric() {
        let data = Array2::from_shape_vec((10, 2), (0..20).map(|x| x as f64).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .include_statistical_features(false)
            .include_distance_matrix(true)
            .include_correlation_features(false)
            .distance_metric("invalid");

        let result = extractor.extract_features(&data.view());
        assert!(
            result.is_err(),
            "Should return error for invalid distance metric"
        );
    }

    #[test]
    fn test_parallel_feature_extractor_large_chunk_size() {
        let data = Array2::from_shape_vec((20, 3), (0..60).map(|x| x as f64).collect())
            .expect("operation should succeed");

        let extractor = ParallelFeatureExtractor::new()
            .chunk_size(100) // Larger than data size
            .include_statistical_features(true);

        let features = extractor
            .extract_features(&data.view())
            .expect("operation should succeed");

        // Should handle large chunk sizes gracefully
        assert_eq!(features.len(), 9);

        // All features should be finite
        for &feature in &features {
            assert!(feature.is_finite(), "Feature should be finite: {}", feature);
        }
    }
}

/// Parallel Feature Extractor for High-Performance Computing
///
/// This extractor provides parallel computation of various feature types across data chunks,
/// optimized for large datasets and multi-core systems.
///
/// Features extracted include:
/// - Statistical features computed in parallel across columns and rows
/// - Distance matrix features with parallel distance computation
/// - Correlation features with parallel correlation computation
/// - Configurable chunk size and thread count for optimal performance
///
/// # Parameters
///
/// * `chunk_size` - Size of data chunks for parallel processing
/// * `num_threads` - Number of threads to use (None for automatic)
/// * `include_distance_matrix` - Whether to compute distance matrix features
/// * `include_statistical_features` - Whether to compute statistical features
/// * `include_correlation_features` - Whether to compute correlation features
/// * `distance_metric` - Distance metric for distance matrix computation
///
/// # Examples
///
/// ```
/// # use sklears_feature_extraction::engineering::ParallelFeatureExtractor;
/// # use scirs2_core::ndarray::Array2;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = Array2::from_shape_vec((1000, 50), (0..50000).map(|x| x as f64).collect())?;
///
/// let extractor = ParallelFeatureExtractor::new()
///     .chunk_size(100)
///     .num_threads(4)
///     .include_statistical_features(true)
///     .include_distance_matrix(true);
///
/// let features = extractor.extract_features(&data.view())?;
/// assert!(features.len() > 0);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ParallelFeatureExtractor {
    chunk_size: usize,
    num_threads: Option<usize>,
    include_distance_matrix: bool,
    include_statistical_features: bool,
    include_correlation_features: bool,
    distance_metric: String,
}

impl ParallelFeatureExtractor {
    /// Create a new parallel feature extractor
    pub fn new() -> Self {
        Self {
            chunk_size: 1000,
            num_threads: None,
            include_distance_matrix: false,
            include_statistical_features: true,
            include_correlation_features: false,
            distance_metric: "euclidean".to_string(),
        }
    }

    /// Set the chunk size for parallel processing
    pub fn chunk_size(mut self, size: usize) -> Self {
        self.chunk_size = size.max(1);
        self
    }

    /// Set the number of threads to use
    pub fn num_threads(mut self, threads: usize) -> Self {
        self.num_threads = Some(threads.max(1));
        self
    }

    /// Set whether to compute distance matrix features
    pub fn include_distance_matrix(mut self, include: bool) -> Self {
        self.include_distance_matrix = include;
        self
    }

    /// Set whether to compute statistical features
    pub fn include_statistical_features(mut self, include: bool) -> Self {
        self.include_statistical_features = include;
        self
    }

    /// Set whether to compute correlation features
    pub fn include_correlation_features(mut self, include: bool) -> Self {
        self.include_correlation_features = include;
        self
    }

    /// Set the distance metric for distance matrix computation
    pub fn distance_metric(mut self, metric: &str) -> Self {
        self.distance_metric = metric.to_string();
        self
    }

    /// Extract features using parallel processing
    pub fn extract_features(&self, data: &ArrayView2<Float>) -> SklResult<Array1<Float>> {
        if data.nrows() == 0 || data.ncols() == 0 {
            return Err(SklearsError::InvalidInput(
                "Input data cannot be empty".to_string(),
            ));
        }

        // Set up thread pool if specified
        let result = if let Some(threads) = self.num_threads {
            rayon::ThreadPoolBuilder::new()
                .num_threads(threads)
                .build()
                .map_err(|e| {
                    SklearsError::InvalidInput(format!("Failed to create thread pool: {}", e))
                })?
                .install(|| self.extract_features_impl(data))
        } else {
            self.extract_features_impl(data)
        };

        result
    }

    /// Internal implementation of feature extraction
    fn extract_features_impl(&self, data: &ArrayView2<Float>) -> SklResult<Array1<Float>> {
        let mut features = Vec::new();

        if self.include_statistical_features {
            features.extend(self.compute_parallel_statistical_features(data)?);
        }

        if self.include_distance_matrix {
            features.extend(self.compute_parallel_distance_matrix_features(data)?);
        }

        if self.include_correlation_features {
            features.extend(self.compute_parallel_correlation_features(data)?);
        }

        if features.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No features selected for extraction".to_string(),
            ));
        }

        // Verify all features are finite
        for &feature in &features {
            if !feature.is_finite() {
                return Err(SklearsError::InvalidInput(
                    "Non-finite feature detected".to_string(),
                ));
            }
        }

        Ok(Array1::from_vec(features))
    }

    /// Compute statistical features in parallel across data chunks
    fn compute_parallel_statistical_features(
        &self,
        data: &ArrayView2<Float>,
    ) -> SklResult<Vec<Float>> {
        let n_samples = data.nrows();
        let n_features = data.ncols();

        // Process columns in parallel
        let column_stats: Vec<Vec<Float>> = (0..n_features)
            .into_par_iter()
            .map(|col_idx| {
                let column = data.column(col_idx);
                self.compute_column_statistics(&column)
            })
            .collect();

        // Aggregate statistics across all columns
        let mut features = Vec::new();

        // Mean of column means
        let column_means: Vec<Float> = column_stats.iter().map(|stats| stats[0]).collect();
        features.push(column_means.iter().sum::<Float>() / n_features as Float);

        // Mean of column standard deviations
        let column_stds: Vec<Float> = column_stats.iter().map(|stats| stats[1]).collect();
        features.push(column_stds.iter().sum::<Float>() / n_features as Float);

        // Mean of column mins and maxs
        let column_mins: Vec<Float> = column_stats.iter().map(|stats| stats[2]).collect();
        let column_maxs: Vec<Float> = column_stats.iter().map(|stats| stats[3]).collect();
        features.push(column_mins.iter().sum::<Float>() / n_features as Float);
        features.push(column_maxs.iter().sum::<Float>() / n_features as Float);

        // Global statistics
        features.push(
            *column_mins
                .iter()
                .min_by(|a, b| a.partial_cmp(b).expect("operation should succeed"))
                .expect("operation should succeed"),
        );
        features.push(
            *column_maxs
                .iter()
                .max_by(|a, b| a.partial_cmp(b).expect("operation should succeed"))
                .expect("operation should succeed"),
        );

        // Parallel computation of row-wise statistics
        let row_stats: Vec<Vec<Float>> = (0..n_samples)
            .into_par_iter()
            .step_by(self.chunk_size)
            .map(|start_idx| {
                let end_idx = (start_idx + self.chunk_size).min(n_samples);
                let mut chunk_stats = Vec::new();

                for row_idx in start_idx..end_idx {
                    let row = data.row(row_idx);
                    let row_mean = row.iter().sum::<Float>() / n_features as Float;
                    let row_var = row.iter().map(|&x| (x - row_mean).powi(2)).sum::<Float>()
                        / n_features as Float;
                    chunk_stats.push(row_mean);
                    chunk_stats.push(row_var.sqrt());
                }

                chunk_stats
            })
            .collect();

        // Aggregate row statistics
        let all_row_stats: Vec<Float> = row_stats.into_iter().flatten().collect();
        if !all_row_stats.is_empty() {
            features.push(all_row_stats.iter().sum::<Float>() / all_row_stats.len() as Float);
            features.push(all_row_stats.iter().cloned().fold(0.0, Float::max));
            features.push(
                all_row_stats
                    .iter()
                    .cloned()
                    .fold(Float::INFINITY, Float::min),
            );
        }

        Ok(features)
    }

    /// Compute statistics for a single column
    fn compute_column_statistics(&self, column: &ArrayView1<Float>) -> Vec<Float> {
        let n = column.len() as Float;
        let mean = column.iter().sum::<Float>() / n;
        let variance = column.iter().map(|&x| (x - mean).powi(2)).sum::<Float>() / n;
        let std_dev = variance.sqrt();
        let min_val = column.iter().cloned().fold(Float::INFINITY, Float::min);
        let max_val = column.iter().cloned().fold(Float::NEG_INFINITY, Float::max);

        vec![mean, std_dev, min_val, max_val]
    }

    /// Compute distance matrix features in parallel
    fn compute_parallel_distance_matrix_features(
        &self,
        data: &ArrayView2<Float>,
    ) -> SklResult<Vec<Float>> {
        let n_samples = data.nrows();

        if n_samples < 2 {
            return Ok(vec![0.0, 0.0, 0.0, 0.0]); // mean, std, min, max distances
        }

        // Compute distance matrix in parallel using chunks
        let distance_chunks: Result<Vec<Vec<Float>>, SklearsError> = (0..n_samples)
            .into_par_iter()
            .step_by(self.chunk_size)
            .map(|start_i| -> SklResult<Vec<Float>> {
                let end_i = (start_i + self.chunk_size).min(n_samples);
                let mut chunk_distances = Vec::new();

                for i in start_i..end_i {
                    for j in (i + 1)..n_samples {
                        let dist = self.compute_distance(&data.row(i), &data.row(j))?;
                        chunk_distances.push(dist);
                    }
                }

                Ok(chunk_distances)
            })
            .collect();

        let distance_chunks = distance_chunks?;

        // Flatten and aggregate distances
        let all_distances: Vec<Float> = distance_chunks.into_iter().flatten().collect();

        if all_distances.is_empty() {
            return Ok(vec![0.0, 0.0, 0.0, 0.0]);
        }

        let n_distances = all_distances.len() as Float;
        let mean_distance = all_distances.iter().sum::<Float>() / n_distances;
        let variance = all_distances
            .iter()
            .map(|&d| (d - mean_distance).powi(2))
            .sum::<Float>()
            / n_distances;
        let std_distance = variance.sqrt();
        let min_distance = all_distances
            .iter()
            .cloned()
            .fold(Float::INFINITY, Float::min);
        let max_distance = all_distances
            .iter()
            .cloned()
            .fold(Float::NEG_INFINITY, Float::max);

        Ok(vec![
            mean_distance,
            std_distance,
            min_distance,
            max_distance,
        ])
    }

    /// Compute correlation features in parallel
    fn compute_parallel_correlation_features(
        &self,
        data: &ArrayView2<Float>,
    ) -> SklResult<Vec<Float>> {
        let n_features = data.ncols();

        if n_features < 2 {
            return Ok(vec![0.0, 0.0, 0.0]); // mean, std, max absolute correlation
        }

        // Compute column means in parallel
        let column_means: Vec<Float> = (0..n_features)
            .into_par_iter()
            .map(|col_idx| {
                let column = data.column(col_idx);
                column.iter().sum::<Float>() / data.nrows() as Float
            })
            .collect();

        // Compute correlations in parallel
        let correlation_chunks: Vec<Vec<Float>> = (0..n_features)
            .into_par_iter()
            .step_by(self.chunk_size)
            .map(|start_i| {
                let end_i = (start_i + self.chunk_size).min(n_features);
                let mut chunk_correlations = Vec::new();

                for i in start_i..end_i {
                    for j in (i + 1)..n_features {
                        let corr = self.compute_correlation(
                            &data.column(i),
                            &data.column(j),
                            column_means[i],
                            column_means[j],
                        );
                        chunk_correlations.push(corr);
                    }
                }

                chunk_correlations
            })
            .collect();

        // Aggregate correlations
        let all_correlations: Vec<Float> = correlation_chunks.into_iter().flatten().collect();

        if all_correlations.is_empty() {
            return Ok(vec![0.0, 0.0, 0.0]);
        }

        let n_correlations = all_correlations.len() as Float;
        let mean_correlation = all_correlations.iter().sum::<Float>() / n_correlations;
        let variance = all_correlations
            .iter()
            .map(|&c| (c - mean_correlation).powi(2))
            .sum::<Float>()
            / n_correlations;
        let std_correlation = variance.sqrt();
        let max_abs_correlation = all_correlations
            .iter()
            .map(|&c| c.abs())
            .fold(0.0, Float::max);

        Ok(vec![mean_correlation, std_correlation, max_abs_correlation])
    }

    /// Compute distance between two points using the specified metric
    fn compute_distance(&self, p1: &ArrayView1<Float>, p2: &ArrayView1<Float>) -> SklResult<Float> {
        match self.distance_metric.as_str() {
            "euclidean" => {
                let dist = p1
                    .iter()
                    .zip(p2.iter())
                    .map(|(a, b)| (a - b).powi(2))
                    .sum::<Float>()
                    .sqrt();
                Ok(dist)
            }
            "manhattan" => {
                let dist = p1
                    .iter()
                    .zip(p2.iter())
                    .map(|(a, b)| (a - b).abs())
                    .sum::<Float>();
                Ok(dist)
            }
            "cosine" => {
                let dot_product = p1.iter().zip(p2.iter()).map(|(a, b)| a * b).sum::<Float>();
                let norm1 = p1.iter().map(|&a| a.powi(2)).sum::<Float>().sqrt();
                let norm2 = p2.iter().map(|&a| a.powi(2)).sum::<Float>().sqrt();

                if norm1 == 0.0 || norm2 == 0.0 {
                    Ok(1.0) // Maximum cosine distance
                } else {
                    Ok(1.0 - dot_product / (norm1 * norm2))
                }
            }
            _ => Err(SklearsError::InvalidInput(format!(
                "Unsupported distance metric: {}",
                self.distance_metric
            ))),
        }
    }

    /// Compute Pearson correlation between two columns
    fn compute_correlation(
        &self,
        col1: &ArrayView1<Float>,
        col2: &ArrayView1<Float>,
        mean1: Float,
        mean2: Float,
    ) -> Float {
        let n = col1.len() as Float;

        let covariance = col1
            .iter()
            .zip(col2.iter())
            .map(|(&x, &y)| (x - mean1) * (y - mean2))
            .sum::<Float>()
            / n;

        let var1 = col1.iter().map(|&x| (x - mean1).powi(2)).sum::<Float>() / n;
        let var2 = col2.iter().map(|&x| (x - mean2).powi(2)).sum::<Float>() / n;

        let std1 = var1.sqrt();
        let std2 = var2.sqrt();

        if std1 == 0.0 || std2 == 0.0 {
            0.0
        } else {
            covariance / (std1 * std2)
        }
    }
}

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

/// Mixed-type feature extractor for handling heterogeneous data
///
/// This extractor can handle different types of features (numerical, categorical, binary, ordinal)
/// and apply appropriate transformations to each type, creating a unified feature matrix.
#[derive(Debug, Clone)]
pub struct MixedTypeFeatureExtractor {
    /// Types of features for each column
    pub feature_types: Vec<FeatureType>,
    /// Whether to normalize numerical features
    pub normalize_numerical: bool,
    /// Whether to handle missing values
    pub handle_missing_values: bool,
    /// Strategy for handling missing values
    pub missing_value_strategy: MissingValueStrategy,
    /// Categorical encoding strategy
    pub encoding_strategy: CategoricalEncoding,
    /// Whether to include interaction features
    pub include_interaction_features: bool,
    /// Random state for reproducible results
    pub random_state: Option<u64>,
}

/// Types of features that can be handled
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FeatureType {
    /// Continuous numerical features
    Numerical,
    /// Categorical features with no inherent order
    Categorical,
    /// Binary features (0/1)
    Binary,
    /// Ordinal features with inherent order
    Ordinal,
    /// Date/time features
    DateTime,
}

/// Strategies for handling missing values
#[derive(Debug, Clone, Copy)]
pub enum MissingValueStrategy {
    /// Replace with mean (for numerical) or mode (for categorical)
    Mean,
    /// Replace with median (for numerical) or mode (for categorical)
    Median,
    /// Replace with mode (most frequent value)
    Mode,
    /// Replace with zero
    Zero,
    /// Forward fill
    ForwardFill,
    /// Backward fill
    BackwardFill,
}

/// Categorical encoding strategies
#[derive(Debug, Clone, Copy)]
pub enum CategoricalEncoding {
    /// One-hot encoding
    OneHot,
    /// Label encoding (ordinal integers)
    LabelEncoding,
    /// Target encoding (mean of target for each category)
    TargetEncoding,
    /// Binary encoding
    BinaryEncoding,
    /// Frequency encoding
    FrequencyEncoding,
}

impl MixedTypeFeatureExtractor {
    /// Create a new mixed-type feature extractor
    pub fn new() -> Self {
        Self {
            feature_types: Vec::new(),
            normalize_numerical: true,
            handle_missing_values: true,
            missing_value_strategy: MissingValueStrategy::Mean,
            encoding_strategy: CategoricalEncoding::OneHot,
            include_interaction_features: false,
            random_state: None,
        }
    }

    /// Set feature types for each column
    pub fn feature_types(mut self, types: Vec<FeatureType>) -> Self {
        self.feature_types = types;
        self
    }

    /// Set whether to normalize numerical features
    pub fn normalize_numerical(mut self, normalize: bool) -> Self {
        self.normalize_numerical = normalize;
        self
    }

    /// Set whether to handle missing values
    pub fn handle_missing_values(mut self, handle: bool) -> Self {
        self.handle_missing_values = handle;
        self
    }

    /// Set missing value strategy
    pub fn missing_value_strategy(mut self, strategy: MissingValueStrategy) -> Self {
        self.missing_value_strategy = strategy;
        self
    }

    /// Set categorical encoding strategy
    pub fn encoding_strategy(mut self, strategy: CategoricalEncoding) -> Self {
        self.encoding_strategy = strategy;
        self
    }

    /// Set whether to include interaction features
    pub fn include_interaction_features(mut self, include: bool) -> Self {
        self.include_interaction_features = include;
        self
    }

    /// Set random state
    pub fn random_state(mut self, seed: u64) -> Self {
        self.random_state = Some(seed);
        self
    }

    /// Handle missing values in data
    fn handle_missing(
        &self,
        data: &Array2<f64>,
        col_idx: usize,
        feature_type: FeatureType,
    ) -> Array1<f64> {
        let column = data.column(col_idx);
        let mut result = Array1::zeros(column.len());

        // Find non-missing values
        let valid_values: Vec<f64> = column.iter().filter(|&&x| x.is_finite()).copied().collect();

        if valid_values.is_empty() {
            return result; // All zeros if no valid values
        }

        let replacement_value = match (self.missing_value_strategy, feature_type) {
            (MissingValueStrategy::Mean, FeatureType::Numerical) => {
                valid_values.iter().sum::<f64>() / valid_values.len() as f64
            }
            (MissingValueStrategy::Median, FeatureType::Numerical) => {
                let mut sorted = valid_values.clone();
                sorted.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
                let mid = sorted.len() / 2;
                if sorted.len().is_multiple_of(2) {
                    (sorted[mid - 1] + sorted[mid]) / 2.0
                } else {
                    sorted[mid]
                }
            }
            (MissingValueStrategy::Mode, _) => {
                // Find most frequent value
                let mut counts = std::collections::HashMap::new();
                for &val in &valid_values {
                    *counts.entry(val as i64).or_insert(0) += 1;
                }
                counts
                    .into_iter()
                    .max_by_key(|(_, count)| *count)
                    .map(|(val, _)| val as f64)
                    .unwrap_or(0.0)
            }
            (MissingValueStrategy::Zero, _) => 0.0,
            (MissingValueStrategy::ForwardFill, _) => {
                // Use first valid value
                valid_values[0]
            }
            (MissingValueStrategy::BackwardFill, _) => {
                // Use last valid value
                valid_values[valid_values.len() - 1]
            }
            _ => valid_values.iter().sum::<f64>() / valid_values.len() as f64, // Default to mean
        };

        // Replace missing values
        for (i, &value) in column.iter().enumerate() {
            result[i] = if value.is_finite() {
                value
            } else {
                replacement_value
            };
        }

        result
    }

    /// Normalize numerical features
    fn normalize_column(&self, column: &Array1<f64>) -> Array1<f64> {
        let mean = column.mean().unwrap_or(0.0);
        let std = column.iter().map(|&x| (x - mean).powi(2)).sum::<f64>() / column.len() as f64;
        let std = std.sqrt();

        if std == 0.0 {
            Array1::zeros(column.len())
        } else {
            column.mapv(|x| (x - mean) / std)
        }
    }

    /// Encode categorical features
    fn encode_categorical(&self, column: &Array1<f64>) -> Array2<f64> {
        match self.encoding_strategy {
            CategoricalEncoding::OneHot => {
                // Find unique values
                let mut unique_values: Vec<i64> = column
                    .iter()
                    .map(|&x| x as i64)
                    .collect::<std::collections::HashSet<_>>()
                    .into_iter()
                    .collect();
                unique_values.sort();

                let n_categories = unique_values.len();
                let mut encoded = Array2::zeros((column.len(), n_categories));

                for (row_idx, &value) in column.iter().enumerate() {
                    if let Some(cat_idx) = unique_values.iter().position(|&x| x == value as i64) {
                        encoded[[row_idx, cat_idx]] = 1.0;
                    }
                }

                encoded
            }
            CategoricalEncoding::LabelEncoding => {
                // Map each unique value to an integer
                let mut unique_values: Vec<i64> = column
                    .iter()
                    .map(|&x| x as i64)
                    .collect::<std::collections::HashSet<_>>()
                    .into_iter()
                    .collect();
                unique_values.sort();

                let mut encoded = Array2::zeros((column.len(), 1));
                for (row_idx, &value) in column.iter().enumerate() {
                    if let Some(label) = unique_values.iter().position(|&x| x == value as i64) {
                        encoded[[row_idx, 0]] = label as f64;
                    }
                }

                encoded
            }
            CategoricalEncoding::TargetEncoding => {
                // For simplicity, use the value itself (would normally use target mean)
                let mut encoded = Array2::zeros((column.len(), 1));
                for (row_idx, &value) in column.iter().enumerate() {
                    encoded[[row_idx, 0]] = value;
                }
                encoded
            }
            _ => {
                // Default to label encoding
                let mut encoded = Array2::zeros((column.len(), 1));
                for (row_idx, &value) in column.iter().enumerate() {
                    encoded[[row_idx, 0]] = value;
                }
                encoded
            }
        }
    }

    /// Process a single feature column
    fn process_feature(
        &self,
        data: &Array2<f64>,
        col_idx: usize,
        feature_type: FeatureType,
    ) -> Array2<f64> {
        // Handle missing values
        let column = if self.handle_missing_values {
            self.handle_missing(data, col_idx, feature_type)
        } else {
            data.column(col_idx).to_owned()
        };

        match feature_type {
            FeatureType::Numerical => {
                let processed = if self.normalize_numerical {
                    self.normalize_column(&column)
                } else {
                    column
                };
                processed.insert_axis(Axis(1))
            }
            FeatureType::Categorical => self.encode_categorical(&column),
            FeatureType::Binary => {
                // Ensure binary values are 0 or 1
                let binary = column.mapv(|x| if x > 0.5 { 1.0 } else { 0.0 });
                binary.insert_axis(Axis(1))
            }
            FeatureType::Ordinal => {
                // Treat as numerical but preserve order
                let processed = if self.normalize_numerical {
                    self.normalize_column(&column)
                } else {
                    column
                };
                processed.insert_axis(Axis(1))
            }
            FeatureType::DateTime => {
                // For simplicity, treat as numerical
                let processed = if self.normalize_numerical {
                    self.normalize_column(&column)
                } else {
                    column
                };
                processed.insert_axis(Axis(1))
            }
        }
    }

    /// Transform the data according to feature types
    fn transform_data(&self, data: &Array2<f64>) -> SklResult<Array2<f64>> {
        if data.is_empty() {
            return Err(SklearsError::InvalidInput("Empty input data".to_string()));
        }

        if self.feature_types.len() != data.ncols() {
            return Err(SklearsError::InvalidInput(format!(
                "Number of feature types ({}) doesn't match number of columns ({})",
                self.feature_types.len(),
                data.ncols()
            )));
        }

        let mut processed_features = Vec::new();

        // Process each feature according to its type
        for (col_idx, &feature_type) in self.feature_types.iter().enumerate() {
            let processed = self.process_feature(data, col_idx, feature_type);
            processed_features.push(processed);
        }

        // Concatenate all processed features
        if processed_features.is_empty() {
            return Ok(Array2::zeros((data.nrows(), 0)));
        }

        let total_cols: usize = processed_features.iter().map(|f| f.ncols()).sum();
        let mut result = Array2::zeros((data.nrows(), total_cols));

        let mut col_offset = 0;
        for feature_matrix in processed_features {
            let n_cols = feature_matrix.ncols();
            result
                .slice_mut(s![.., col_offset..col_offset + n_cols])
                .assign(&feature_matrix);
            col_offset += n_cols;
        }

        Ok(result)
    }
}

/// Fitted mixed-type feature extractor
pub struct FittedMixedTypeFeatureExtractor {
    extractor: MixedTypeFeatureExtractor,
    transformation_stats: std::collections::HashMap<String, f64>,
}

impl FittedMixedTypeFeatureExtractor {
    /// Get transformation statistics
    pub fn transformation_statistics(&self) -> &std::collections::HashMap<String, f64> {
        &self.transformation_stats
    }
}

impl Estimator<Untrained> for MixedTypeFeatureExtractor {
    type Config = ();
    type Error = SklearsError;
    type Float = Float;

    fn config(&self) -> &Self::Config {
        &()
    }
}

#[allow(non_snake_case)] // X follows sklearn/math convention for feature matrix
impl Fit<Array2<f64>, ()> for MixedTypeFeatureExtractor {
    type Fitted = FittedMixedTypeFeatureExtractor;

    fn fit(self, X: &Array2<f64>, _y: &()) -> SklResult<Self::Fitted> {
        if X.is_empty() {
            return Err(SklearsError::InvalidInput("Empty input data".to_string()));
        }

        // Set default feature types if not specified
        let feature_types = if self.feature_types.is_empty() {
            vec![FeatureType::Numerical; X.ncols()]
        } else {
            self.feature_types.clone()
        };

        // Calculate transformation statistics
        let mut stats = std::collections::HashMap::new();

        let n_numerical = feature_types
            .iter()
            .filter(|&&t| t == FeatureType::Numerical)
            .count();
        let n_categorical = feature_types
            .iter()
            .filter(|&&t| t == FeatureType::Categorical)
            .count();
        let n_binary = feature_types
            .iter()
            .filter(|&&t| t == FeatureType::Binary)
            .count();
        let n_ordinal = feature_types
            .iter()
            .filter(|&&t| t == FeatureType::Ordinal)
            .count();

        stats.insert("n_numerical_features".to_string(), n_numerical as f64);
        stats.insert("n_categorical_features".to_string(), n_categorical as f64);
        stats.insert("n_binary_features".to_string(), n_binary as f64);
        stats.insert("n_ordinal_features".to_string(), n_ordinal as f64);
        stats.insert("total_input_features".to_string(), X.ncols() as f64);

        // Estimate output feature count (simplified)
        let estimated_output_features = match self.encoding_strategy {
            CategoricalEncoding::OneHot => {
                // Estimate expanded size for one-hot encoding
                let categorical_expansion = n_categorical * 3; // Assume avg 3 categories
                n_numerical + n_binary + n_ordinal + categorical_expansion
            }
            _ => feature_types.len(),
        };

        stats.insert(
            "total_output_features".to_string(),
            estimated_output_features as f64,
        );

        let updated_extractor = MixedTypeFeatureExtractor {
            feature_types,
            ..self
        };

        Ok(FittedMixedTypeFeatureExtractor {
            extractor: updated_extractor,
            transformation_stats: stats,
        })
    }
}

#[allow(non_snake_case)] // X follows sklearn/math convention for feature matrix
impl Transform<Array2<f64>, Array2<f64>> for FittedMixedTypeFeatureExtractor {
    fn transform(&self, X: &Array2<f64>) -> SklResult<Array2<f64>> {
        self.extractor.transform_data(X)
    }
}

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

#[allow(non_snake_case)]
#[cfg(test)]
mod sketching_tests {
    use super::*;
    use scirs2_core::ndarray::Array2;

    #[test]
    fn test_mixed_type_feature_extractor_basic() {
        let data = Array2::from_shape_vec(
            (4, 6),
            vec![
                1.0, 2.0, 3.0, 1.0, 0.0,
                5.0, // numerical: 1,2,3  categorical: 1,0  ordinal: 5
                4.0, 5.0, 6.0, 2.0, 1.0,
                3.0, // numerical: 4,5,6  categorical: 2,1  ordinal: 3
                7.0, 8.0, 9.0, 1.0, 0.0,
                4.0, // numerical: 7,8,9  categorical: 1,0  ordinal: 4
                2.0, 3.0, 4.0, 3.0, 1.0,
                2.0, // numerical: 2,3,4  categorical: 3,1  ordinal: 2
            ],
        )
        .expect("operation should succeed");

        let feature_types = vec![
            FeatureType::Numerical,   // col 0
            FeatureType::Numerical,   // col 1
            FeatureType::Numerical,   // col 2
            FeatureType::Categorical, // col 3
            FeatureType::Binary,      // col 4
            FeatureType::Ordinal,     // col 5
        ];

        let extractor = MixedTypeFeatureExtractor::new()
            .feature_types(feature_types)
            .normalize_numerical(true)
            .encoding_strategy(CategoricalEncoding::OneHot);

        let fitted = extractor.fit(&data, &()).expect("operation should succeed");
        let features = fitted.transform(&data).expect("operation should succeed");

        assert_eq!(features.nrows(), 4);
        assert!(features.ncols() > 6); // Should be expanded due to one-hot encoding

        // Check that all features are finite
        for &value in features.iter() {
            assert!(value.is_finite());
        }
    }

    #[test]
    fn test_mixed_type_feature_extractor_different_encodings() {
        let data = Array2::from_shape_vec(
            (3, 4),
            vec![1.0, 1.0, 0.0, 5.0, 2.0, 2.0, 1.0, 3.0, 3.0, 1.0, 0.0, 4.0],
        )
        .expect("operation should succeed");

        let feature_types = vec![
            FeatureType::Numerical,
            FeatureType::Categorical,
            FeatureType::Binary,
            FeatureType::Ordinal,
        ];

        let encodings = vec![
            CategoricalEncoding::OneHot,
            CategoricalEncoding::LabelEncoding,
            CategoricalEncoding::TargetEncoding,
        ];

        for encoding in encodings {
            let extractor = MixedTypeFeatureExtractor::new()
                .feature_types(feature_types.clone())
                .encoding_strategy(encoding);

            let fitted = extractor.fit(&data, &()).expect("operation should succeed");
            let features = fitted.transform(&data).expect("operation should succeed");

            assert_eq!(features.nrows(), 3);
            assert!(features.ncols() > 0);

            // Check that all features are finite
            for &value in features.iter() {
                assert!(value.is_finite());
            }
        }
    }

    #[test]
    fn test_mixed_type_feature_extractor_empty_data() {
        let data = Array2::zeros((0, 0));
        let extractor = MixedTypeFeatureExtractor::new();

        let result = extractor.fit(&data, &());
        assert!(result.is_err());
    }

    #[test]
    fn test_mixed_type_feature_extractor_configuration() {
        let data =
            Array2::from_shape_vec((3, 3), vec![1.0, 1.0, 0.0, 2.0, 2.0, 1.0, 3.0, 1.0, 0.0])
                .expect("operation should succeed");

        let feature_types = vec![
            FeatureType::Numerical,
            FeatureType::Categorical,
            FeatureType::Binary,
        ];

        let extractor = MixedTypeFeatureExtractor::new()
            .feature_types(feature_types)
            .normalize_numerical(true)
            .handle_missing_values(true)
            .missing_value_strategy(MissingValueStrategy::Mean)
            .encoding_strategy(CategoricalEncoding::OneHot)
            .include_interaction_features(true)
            .random_state(42);

        let fitted = extractor.fit(&data, &()).expect("operation should succeed");
        let features = fitted.transform(&data).expect("operation should succeed");

        assert_eq!(features.nrows(), 3);

        // Check that configuration was applied
        let stats = fitted.transformation_statistics();
        assert!(stats.contains_key("n_numerical_features"));
        assert!(stats.contains_key("n_categorical_features"));
        assert!(stats.contains_key("n_binary_features"));
        assert!(stats.contains_key("total_output_features"));
    }

    #[test]
    fn test_mixed_type_feature_extractor_missing_values() {
        let data = Array2::from_shape_vec(
            (4, 3),
            vec![
                1.0,
                1.0,
                f64::NAN,
                2.0,
                f64::NAN,
                1.0,
                f64::NAN,
                2.0,
                0.0,
                3.0,
                1.0,
                1.0,
            ],
        )
        .expect("operation should succeed");

        let feature_types = vec![
            FeatureType::Numerical,
            FeatureType::Categorical,
            FeatureType::Binary,
        ];

        let strategies = vec![
            MissingValueStrategy::Mean,
            MissingValueStrategy::Median,
            MissingValueStrategy::Mode,
            MissingValueStrategy::Zero,
        ];

        for strategy in strategies {
            let extractor = MixedTypeFeatureExtractor::new()
                .feature_types(feature_types.clone())
                .handle_missing_values(true)
                .missing_value_strategy(strategy);

            let fitted = extractor.fit(&data, &()).expect("operation should succeed");
            let features = fitted.transform(&data).expect("operation should succeed");

            assert_eq!(features.nrows(), 4);

            // Check that no NaN values remain
            for &value in features.iter() {
                assert!(
                    value.is_finite(),
                    "All values should be finite after missing value handling"
                );
            }
        }
    }

    #[test]
    fn test_mixed_type_feature_extractor_consistency() {
        let data = Array2::from_shape_vec(
            (3, 4),
            vec![1.0, 1.0, 0.0, 5.0, 2.0, 2.0, 1.0, 3.0, 3.0, 1.0, 0.0, 4.0],
        )
        .expect("operation should succeed");

        let feature_types = vec![
            FeatureType::Numerical,
            FeatureType::Categorical,
            FeatureType::Binary,
            FeatureType::Ordinal,
        ];

        let extractor = MixedTypeFeatureExtractor::new()
            .feature_types(feature_types)
            .random_state(42);

        let fitted = extractor.fit(&data, &()).expect("operation should succeed");
        let features1 = fitted.transform(&data).expect("operation should succeed");
        let features2 = fitted.transform(&data).expect("operation should succeed");

        // Results should be identical
        assert_eq!(features1.shape(), features2.shape());
        for (a, b) in features1.iter().zip(features2.iter()) {
            assert_eq!(a, b);
        }
    }
}

// Temporal-spatial feature extractor has been moved to time_series_features.rs
pub use crate::time_series_features::TemporalSpatialExtractor;