sklears-multioutput 0.2.0

Multi-output regression and classification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
//! Multi-output regression and classification
//!
//! This module provides meta-estimators for multi-target prediction problems.
//! It includes strategies for independent multi-output prediction.

#![warn(missing_docs)]

pub mod chains;
pub mod core;
pub mod correlation;
pub mod multi_label;
pub mod neural;
pub mod optimization;
pub mod probabilistic;
pub mod regularization;
pub mod transfer_learning;
pub mod tree;
pub mod utils;

use ndarray::{s, Array1, Array2, Array3, ArrayView1, ArrayView2, ArrayView3, Axis};
use ndarray_rand::rand_distr::Normal;
use ndarray_rand::RandomExt;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
use sklears_core::{
    error::{Result as SklResult, SklearsError},
    traits::{Estimator, Fit, Predict, Untrained},
    types::Float,
};
use std::collections::HashMap;
use utils::*;

// Re-export core multi-output algorithms
pub use core::{
    MultiOutputClassifier, MultiOutputClassifierTrained, MultiOutputRegressor,
    MultiOutputRegressorTrained,
};

// Re-export chain-based algorithms
pub use chains::{
    BayesianClassifierChain, BayesianClassifierChainTrained, ChainMethod, ClassifierChain,
    ClassifierChainTrained, EnsembleOfChains, EnsembleOfChainsTrained, RegressorChain,
    RegressorChainTrained,
};

// Re-export neural network algorithms
pub use neural::{
    ActivationFunction, AdversarialConfig, AdversarialMultiTaskNetwork,
    AdversarialMultiTaskNetworkTrained, AdversarialStrategy, AttentionConfig,
    AttentionMultiTaskNetwork, AttentionMultiTaskNetworkTrained, AttentionOutput, AttentionType,
    CellType, GradientReversalConfig, LambdaSchedule, LossFunction, MultiOutputMLP,
    MultiOutputMLPClassifier, MultiOutputMLPRegressor, MultiOutputMLPTrained,
    MultiTaskNeuralNetwork, MultiTaskNeuralNetworkTrained, RecurrentNeuralNetwork,
    RecurrentNeuralNetworkTrained, SequenceMode, TaskBalancing, TaskDiscriminator,
};

// Re-export regularization algorithms
pub use regularization::{
    GroupLasso, GroupLassoTrained, MetaLearningMultiTask, MetaLearningMultiTaskTrained,
    MultiTaskElasticNet, MultiTaskElasticNetTrained, NuclearNormRegression,
    NuclearNormRegressionTrained, RegularizationStrategy, TaskClusteringRegressionTrained,
    TaskClusteringRegularization, TaskRelationshipLearning, TaskRelationshipLearningTrained,
    TaskSimilarityMethod,
};

// Re-export correlation and dependency analysis
pub use correlation::{
    CITestMethod, CITestResult, CITestResults, ConditionalIndependenceTester, CorrelationAnalysis,
    CorrelationType, DependencyGraph, DependencyGraphBuilder, DependencyMethod, GraphStatistics,
    OutputCorrelationAnalyzer,
};

// Re-export transfer learning algorithms
pub use transfer_learning::{
    ContinualLearning, ContinualLearningTrained, CrossTaskTransferLearning,
    CrossTaskTransferLearningTrained, DomainAdaptation, DomainAdaptationTrained,
    KnowledgeDistillation, KnowledgeDistillationTrained, ProgressiveTransferLearning,
    ProgressiveTransferLearningTrained,
};

// Re-export optimization algorithms
pub use optimization::{
    JointLossConfig, JointLossOptimizer, JointLossOptimizerTrained, LossCombination,
    LossFunction as OptimizationLossFunction, MultiObjectiveConfig, MultiObjectiveOptimizer,
    MultiObjectiveOptimizerTrained, ParetoSolution, ScalarizationConfig, ScalarizationMethod, ScalarizationOptimizer,
    ScalarizationOptimizerTrained,
};

// Re-export probabilistic algorithms
pub use probabilistic::{
    BayesianMultiOutputConfig, BayesianMultiOutputModel, BayesianMultiOutputModelTrained,
    GaussianProcessMultiOutput, GaussianProcessMultiOutputTrained, InferenceMethod, KernelFunction,
    PosteriorDistribution, PredictionWithUncertainty, PriorDistribution,
};

// Re-export multi-label algorithms
pub use multi_label::{
    BinaryRelevance, BinaryRelevanceTrained,
    LabelPowerset, LabelPowersetTrained,
    PrunedLabelPowerset, PrunedLabelPowersetTrained, PruningStrategy,
    OneVsRestClassifier, OneVsRestClassifierTrained,
};

// Re-export tree-based algorithms
pub use tree::{
    ClassificationCriterion, DAGInferenceMethod,
    MultiTargetRegressionTree, MultiTargetRegressionTreeTrained,
    MultiTargetDecisionTreeClassifier, MultiTargetDecisionTreeClassifierTrained,
    RandomForestMultiOutput, RandomForestMultiOutputTrained,
    TreeStructuredPredictor, TreeStructuredPredictorTrained,
};

// Note: MEMM types are defined in this file, no re-export needed

// Re-export instance-based learning algorithms (defined later in file)
// pub use {IBLR, IBLRTrained, WeightFunction};







/// Multi-output and multi-label evaluation metrics
pub mod metrics {
    use ndarray::{Array2, ArrayView2};
    use sklears_core::error::{Result as SklResult, SklearsError};

    /// Hamming loss for multi-label classification
    ///
    /// The Hamming loss is the fraction of the wrong labels to the total
    /// number of labels. It is a multi-label generalization of the zero-one loss.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_pred` - Predicted labels
    ///
    /// # Returns
    ///
    /// The Hamming loss between y_true and y_pred
    pub fn hamming_loss(
        y_true: &ArrayView2<'_, i32>,
        y_pred: &ArrayView2<'_, i32>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_errors = 0;
        let total_elements = n_samples * n_labels;

        for sample_idx in 0..n_samples {
            for label_idx in 0..n_labels {
                if y_true[[sample_idx, label_idx]] != y_pred[[sample_idx, label_idx]] {
                    total_errors += 1;
                }
            }
        }

        Ok(total_errors as f64 / total_elements as f64)
    }

    /// Subset accuracy for multi-label classification
    ///
    /// Subset accuracy is the most strict metric. It requires for each sample
    /// that each label set be correctly predicted.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_pred` - Predicted labels
    ///
    /// # Returns
    ///
    /// The subset accuracy between y_true and y_pred
    pub fn subset_accuracy(
        y_true: &ArrayView2<'_, i32>,
        y_pred: &ArrayView2<'_, i32>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample".to_string(),
            ));
        }

        let mut correct_subsets = 0;

        for sample_idx in 0..n_samples {
            let mut subset_correct = true;
            for label_idx in 0..n_labels {
                if y_true[[sample_idx, label_idx]] != y_pred[[sample_idx, label_idx]] {
                    subset_correct = false;
                    break;
                }
            }
            if subset_correct {
                correct_subsets += 1;
            }
        }

        Ok(correct_subsets as f64 / n_samples as f64)
    }

    /// Jaccard similarity coefficient for multi-label classification
    ///
    /// The Jaccard similarity coefficient is defined as the size of the intersection
    /// divided by the size of the union of the sample sets.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_pred` - Predicted labels
    ///
    /// # Returns
    ///
    /// The Jaccard similarity coefficient
    pub fn jaccard_score(
        y_true: &ArrayView2<'_, i32>,
        y_pred: &ArrayView2<'_, i32>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample".to_string(),
            ));
        }

        let mut total_jaccard = 0.0;

        for sample_idx in 0..n_samples {
            let mut intersection = 0;
            let mut union = 0;

            for label_idx in 0..n_labels {
                let true_label = y_true[[sample_idx, label_idx]];
                let pred_label = y_pred[[sample_idx, label_idx]];

                if true_label == 1 && pred_label == 1 {
                    intersection += 1;
                }
                if true_label == 1 || pred_label == 1 {
                    union += 1;
                }
            }

            // Jaccard = intersection / union, handle division by zero
            let sample_jaccard = if union > 0 {
                intersection as f64 / union as f64
            } else {
                1.0 // If both sets are empty, Jaccard = 1
            };

            total_jaccard += sample_jaccard;
        }

        Ok(total_jaccard / n_samples as f64)
    }

    /// F1 score for multi-label classification
    ///
    /// Compute the F1 score for each label and return the specified average.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_pred` - Predicted labels
    /// * `average` - The averaging strategy ('micro', 'macro', 'samples')
    ///
    /// # Returns
    ///
    /// The F1 score according to the specified averaging strategy
    pub fn f1_score(
        y_true: &ArrayView2<'_, i32>,
        y_pred: &ArrayView2<'_, i32>,
        average: &str,
    ) -> SklResult<f64> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        match average {
            "micro" => {
                // Compute global precision and recall
                let mut total_tp = 0;
                let mut total_fp = 0;
                let mut total_false_negatives = 0;

                for sample_idx in 0..n_samples {
                    for label_idx in 0..n_labels {
                        let true_label = y_true[[sample_idx, label_idx]];
                        let pred_label = y_pred[[sample_idx, label_idx]];

                        if true_label == 1 && pred_label == 1 {
                            total_tp += 1;
                        } else if true_label == 0 && pred_label == 1 {
                            total_fp += 1;
                        } else if true_label == 1 && pred_label == 0 {
                            total_false_negatives += 1;
                        }
                    }
                }

                let precision = if total_tp + total_fp > 0 {
                    total_tp as f64 / (total_tp + total_fp) as f64
                } else {
                    0.0
                };

                let recall = if total_tp + total_false_negatives > 0 {
                    total_tp as f64 / (total_tp + total_false_negatives) as f64
                } else {
                    0.0
                };

                let f1 = if precision + recall > 0.0 {
                    2.0 * precision * recall / (precision + recall)
                } else {
                    0.0
                };

                Ok(f1)
            }
            "macro" => {
                // Compute F1 for each label and average
                let mut label_f1_scores = Vec::new();

                for label_idx in 0..n_labels {
                    let mut tp = 0;
                    let mut fp = 0;
                    let mut false_negatives = 0;

                    for sample_idx in 0..n_samples {
                        let true_label = y_true[[sample_idx, label_idx]];
                        let pred_label = y_pred[[sample_idx, label_idx]];

                        if true_label == 1 && pred_label == 1 {
                            tp += 1;
                        } else if true_label == 0 && pred_label == 1 {
                            fp += 1;
                        } else if true_label == 1 && pred_label == 0 {
                            false_negatives += 1;
                        }
                    }

                    let precision = if tp + fp > 0 {
                        tp as f64 / (tp + fp) as f64
                    } else {
                        0.0
                    };

                    let recall = if tp + false_negatives > 0 {
                        tp as f64 / (tp + false_negatives) as f64
                    } else {
                        0.0
                    };

                    let f1 = if precision + recall > 0.0 {
                        2.0 * precision * recall / (precision + recall)
                    } else {
                        0.0
                    };

                    label_f1_scores.push(f1);
                }

                Ok(label_f1_scores.iter().sum::<f64>() / n_labels as f64)
            }
            "samples" => {
                // Compute F1 for each sample and average
                let mut sample_f1_scores = Vec::new();

                for sample_idx in 0..n_samples {
                    let mut tp = 0;
                    let mut fp = 0;
                    let mut false_negatives = 0;

                    for label_idx in 0..n_labels {
                        let true_label = y_true[[sample_idx, label_idx]];
                        let pred_label = y_pred[[sample_idx, label_idx]];

                        if true_label == 1 && pred_label == 1 {
                            tp += 1;
                        } else if true_label == 0 && pred_label == 1 {
                            fp += 1;
                        } else if true_label == 1 && pred_label == 0 {
                            false_negatives += 1;
                        }
                    }

                    let precision = if tp + fp > 0 {
                        tp as f64 / (tp + fp) as f64
                    } else {
                        0.0
                    };

                    let recall = if tp + false_negatives > 0 {
                        tp as f64 / (tp + false_negatives) as f64
                    } else {
                        0.0
                    };

                    let f1 = if precision + recall > 0.0 {
                        2.0 * precision * recall / (precision + recall)
                    } else {
                        0.0
                    };

                    sample_f1_scores.push(f1);
                }

                Ok(sample_f1_scores.iter().sum::<f64>() / n_samples as f64)
            }
            _ => Err(SklearsError::InvalidInput(format!(
                "Unknown average type: {}. Valid options are 'micro', 'macro', 'samples'",
                average
            ))),
        }
    }

    /// Coverage error for multi-label ranking
    ///
    /// Coverage error measures how far we need to go through the ranked scores
    /// to cover all true labels. The best value is equal to the average number
    /// of labels in y_true per sample.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_scores` - Target scores (predicted probabilities)
    ///
    /// # Returns
    ///
    /// The coverage error
    pub fn coverage_error(
        y_true: &ArrayView2<'_, i32>,
        y_scores: &ArrayView2<'_, f64>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_scores.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_scores must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_coverage = 0.0;

        for sample_idx in 0..n_samples {
            // Get the indices sorted by scores in descending order
            let mut score_label_pairs: Vec<(f64, usize)> = (0..n_labels)
                .map(|label_idx| (y_scores[[sample_idx, label_idx]], label_idx))
                .collect();
            score_label_pairs
                .sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));

            // Find the position of the last true label in the ranked list
            let mut last_true_position = 0;
            for (position, &(_, label_idx)) in score_label_pairs.iter().enumerate() {
                if y_true[[sample_idx, label_idx]] == 1 {
                    last_true_position = position + 1; // Convert to 1-based indexing
                }
            }

            total_coverage += last_true_position as f64;
        }

        Ok(total_coverage / n_samples as f64)
    }

    /// Label ranking average precision for multi-label ranking
    ///
    /// The label ranking average precision (LRAP) averages over the samples
    /// the answer to the following question: for each ground truth label,
    /// what fraction of higher-ranked labels were true labels?
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_scores` - Target scores (predicted probabilities)
    ///
    /// # Returns
    ///
    /// The label ranking average precision
    pub fn label_ranking_average_precision(
        y_true: &ArrayView2<'_, i32>,
        y_scores: &ArrayView2<'_, f64>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_scores.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_scores must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_lrap = 0.0;

        for sample_idx in 0..n_samples {
            // Get the indices sorted by scores in descending order
            let mut score_label_pairs: Vec<(f64, usize)> = (0..n_labels)
                .map(|label_idx| (y_scores[[sample_idx, label_idx]], label_idx))
                .collect();
            score_label_pairs
                .sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));

            // Count true labels for this sample
            let n_true_labels: i32 = (0..n_labels)
                .map(|label_idx| y_true[[sample_idx, label_idx]])
                .sum();

            if n_true_labels == 0 {
                continue; // Skip samples with no true labels
            }

            let mut precision_sum = 0.0;
            let mut true_labels_seen = 0;

            for (position, &(_, label_idx)) in score_label_pairs.iter().enumerate() {
                if y_true[[sample_idx, label_idx]] == 1 {
                    true_labels_seen += 1;
                    let precision_at_position = true_labels_seen as f64 / (position + 1) as f64;
                    precision_sum += precision_at_position;
                }
            }

            let sample_lrap = precision_sum / n_true_labels as f64;
            total_lrap += sample_lrap;
        }

        Ok(total_lrap / n_samples as f64)
    }

    /// One-error for multi-label ranking
    ///
    /// The one-error evaluates how many times the top-ranked label is not
    /// in the set of true labels. The best performance is achieved when
    /// one-error is 0, which means the top-ranked label is always correct.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_scores` - Target scores (predicted probabilities)
    ///
    /// # Returns
    ///
    /// The one-error (fraction of samples where top-ranked label is incorrect)
    pub fn one_error(
        y_true: &ArrayView2<'_, i32>,
        y_scores: &ArrayView2<'_, f64>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_scores.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_scores must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut errors = 0;

        for sample_idx in 0..n_samples {
            // Find the label with the highest score
            let mut max_score = f64::NEG_INFINITY;
            let mut top_label_idx = 0;

            for label_idx in 0..n_labels {
                let score = y_scores[[sample_idx, label_idx]];
                if score > max_score {
                    max_score = score;
                    top_label_idx = label_idx;
                }
            }

            // Check if the top-ranked label is correct
            if y_true[[sample_idx, top_label_idx]] != 1 {
                errors += 1;
            }
        }

        Ok(errors as f64 / n_samples as f64)
    }

    /// Ranking loss for multi-label ranking
    ///
    /// The ranking loss evaluates the average fraction of label pairs that are
    /// incorrectly ordered, given the predictions. The best performance is achieved
    /// when ranking loss is 0.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_scores` - Target scores (predicted probabilities)
    ///
    /// # Returns
    ///
    /// The ranking loss
    pub fn ranking_loss(
        y_true: &ArrayView2<'_, i32>,
        y_scores: &ArrayView2<'_, f64>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_scores.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_scores must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_ranking_loss = 0.0;

        for sample_idx in 0..n_samples {
            let mut incorrect_pairs = 0;
            let mut total_pairs = 0;

            // Compare all pairs of labels
            for i in 0..n_labels {
                for j in 0..n_labels {
                    if i != j {
                        let true_i = y_true[[sample_idx, i]];
                        let true_j = y_true[[sample_idx, j]];
                        let score_i = y_scores[[sample_idx, i]];
                        let score_j = y_scores[[sample_idx, j]];

                        // Check if this is a relevant pair (one positive, one negative)
                        if (true_i == 1 && true_j == 0) || (true_i == 0 && true_j == 1) {
                            total_pairs += 1;

                            // Check if the ordering is incorrect
                            if (true_i == 1 && true_j == 0 && score_i < score_j)
                                || (true_i == 0 && true_j == 1 && score_i > score_j)
                            {
                                incorrect_pairs += 1;
                            }
                        }
                    }
                }
            }

            // Add to total ranking loss
            if total_pairs > 0 {
                total_ranking_loss += incorrect_pairs as f64 / total_pairs as f64;
            }
        }

        Ok(total_ranking_loss / n_samples as f64)
    }

    /// Average precision score for multi-label ranking
    ///
    /// Computes the average precision for each sample and then averages
    /// over all samples. This is different from label ranking average precision
    /// as it focuses on precision-recall curves for each sample.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_scores` - Target scores (predicted probabilities)
    ///
    /// # Returns
    ///
    /// The average precision score
    pub fn average_precision_score(
        y_true: &ArrayView2<'_, i32>,
        y_scores: &ArrayView2<'_, f64>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_scores.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_scores must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_ap = 0.0;

        for sample_idx in 0..n_samples {
            // Get the indices sorted by scores in descending order
            let mut score_label_pairs: Vec<(f64, usize)> = (0..n_labels)
                .map(|label_idx| (y_scores[[sample_idx, label_idx]], label_idx))
                .collect();
            score_label_pairs
                .sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));

            // Count true labels for this sample
            let n_true_labels: i32 = (0..n_labels)
                .map(|label_idx| y_true[[sample_idx, label_idx]])
                .sum();

            if n_true_labels == 0 {
                continue; // Skip samples with no true labels
            }

            let mut precision_sum = 0.0;
            let mut true_labels_seen = 0;

            for (position, &(_, label_idx)) in score_label_pairs.iter().enumerate() {
                if y_true[[sample_idx, label_idx]] == 1 {
                    true_labels_seen += 1;
                    let precision_at_position = true_labels_seen as f64 / (position + 1) as f64;
                    precision_sum += precision_at_position;
                }
            }

            let sample_ap = precision_sum / n_true_labels as f64;
            total_ap += sample_ap;
        }

        Ok(total_ap / n_samples as f64)
    }

    /// Micro-averaged precision for multi-label classification
    ///
    /// Calculate precision by counting the total true positives and false positives
    /// across all labels and samples.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_pred` - Predicted labels
    ///
    /// # Returns
    ///
    /// The micro-averaged precision
    pub fn precision_score_micro(
        y_true: &ArrayView2<'_, i32>,
        y_pred: &ArrayView2<'_, i32>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_tp = 0;
        let mut total_fp = 0;

        for sample_idx in 0..n_samples {
            for label_idx in 0..n_labels {
                let true_label = y_true[[sample_idx, label_idx]];
                let pred_label = y_pred[[sample_idx, label_idx]];

                if true_label == 1 && pred_label == 1 {
                    total_tp += 1;
                } else if true_label == 0 && pred_label == 1 {
                    total_fp += 1;
                }
            }
        }

        let precision = if total_tp + total_fp > 0 {
            total_tp as f64 / (total_tp + total_fp) as f64
        } else {
            0.0
        };

        Ok(precision)
    }

    /// Micro-averaged recall for multi-label classification
    ///
    /// Calculate recall by counting the total true positives and false negatives
    /// across all labels and samples.
    ///
    /// # Arguments
    ///
    /// * `y_true` - Ground truth (correct) labels
    /// * `y_pred` - Predicted labels
    ///
    /// # Returns
    ///
    /// The micro-averaged recall
    pub fn recall_score_micro(
        y_true: &ArrayView2<'_, i32>,
        y_pred: &ArrayView2<'_, i32>,
    ) -> SklResult<f64> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same shape".to_string(),
            ));
        }

        let (n_samples, n_labels) = y_true.dim();
        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input arrays must have at least one sample and one label".to_string(),
            ));
        }

        let mut total_tp = 0;
        let mut total_fn = 0;

        for sample_idx in 0..n_samples {
            for label_idx in 0..n_labels {
                let true_label = y_true[[sample_idx, label_idx]];
                let pred_label = y_pred[[sample_idx, label_idx]];

                if true_label == 1 && pred_label == 1 {
                    total_tp += 1;
                } else if true_label == 1 && pred_label == 0 {
                    total_fn += 1;
                }
            }
        }

        let recall = if total_tp + total_fn > 0 {
            total_tp as f64 / (total_tp + total_fn) as f64
        } else {
            0.0
        };

        Ok(recall)
    }
}

/// Label combination frequency analysis utilities
pub mod label_analysis {
    use ndarray::{Array2, ArrayView2};
    use sklears_core::error::{Result as SklResult, SklearsError};
    use std::collections::HashMap;

    /// Information about a label combination
    #[derive(Debug, Clone)]
    pub struct CombinationInfo {
        /// The label combination
        pub combination: Vec<i32>,
        /// Number of times this combination appears
        pub frequency: usize,
        /// Relative frequency (proportion of total samples)
        pub relative_frequency: f64,
        /// Number of active labels in this combination
        pub cardinality: usize,
    }

    /// Results of label combination frequency analysis
    #[derive(Debug, Clone)]
    pub struct LabelAnalysisResults {
        /// All unique combinations and their statistics
        pub combinations: Vec<CombinationInfo>,
        /// Total number of samples analyzed
        pub n_samples: usize,
        /// Total number of labels
        pub n_labels: usize,
        /// Number of unique combinations found
        pub n_unique_combinations: usize,
        /// Most frequent combination
        pub most_frequent: CombinationInfo,
        /// Least frequent combination
        pub least_frequent: CombinationInfo,
        /// Average cardinality (average number of active labels per sample)
        pub avg_cardinality: f64,
        /// Label density (proportion of active labels across all samples)
        pub label_density: f64,
    }

    /// Analyze the frequency distribution of label combinations
    ///
    /// This function provides comprehensive statistics about label combinations
    /// in a multi-label dataset, including frequency counts, cardinality analysis,
    /// and density metrics.
    ///
    /// # Arguments
    ///
    /// * `y` - Multi-label target array where each row is a sample and each column is a label
    ///
    /// # Returns
    ///
    /// Comprehensive analysis results of label combinations
    ///
    /// # Examples
    ///
    /// ```
    /// use sklears_multioutput::label_analysis;
    /// use ndarray::array;
    ///
    /// let y = array![[1, 0, 1], [0, 1, 0], [1, 0, 1], [0, 0, 0]];
    /// let results = label_analysis::analyze_combinations(&y.view()).unwrap();
    ///
    /// assert_eq!(results.n_samples, 4);
    /// assert_eq!(results.n_labels, 3);
    /// assert!(results.n_unique_combinations <= 4);
    /// ```
    pub fn analyze_combinations(y: &ArrayView2<'_, i32>) -> SklResult<LabelAnalysisResults> {
        let (n_samples, n_labels) = y.dim();

        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input array must have at least one sample and one label".to_string(),
            ));
        }

        // Validate that labels are binary
        for sample_idx in 0..n_samples {
            for label_idx in 0..n_labels {
                let label_value = y[[sample_idx, label_idx]];
                if label_value != 0 && label_value != 1 {
                    return Err(SklearsError::InvalidInput(format!(
                        "Label analysis expects binary labels, but found {} at position ({}, {})",
                        label_value, sample_idx, label_idx
                    )));
                }
            }
        }

        // Count frequencies of label combinations
        let mut combination_counts: HashMap<Vec<i32>, usize> = HashMap::new();
        let mut total_active_labels = 0;

        for sample_idx in 0..n_samples {
            let combination: Vec<i32> = (0..n_labels)
                .map(|label_idx| y[[sample_idx, label_idx]])
                .collect();

            // Count active labels for density calculation
            total_active_labels += combination.iter().sum::<i32>() as usize;

            *combination_counts.entry(combination).or_insert(0) += 1;
        }

        // Convert to CombinationInfo structs
        let mut combinations: Vec<CombinationInfo> = combination_counts
            .into_iter()
            .map(|(combination, frequency)| {
                let cardinality = combination.iter().sum::<i32>() as usize;
                let relative_frequency = frequency as f64 / n_samples as f64;

                CombinationInfo {
                    combination,
                    frequency,
                    relative_frequency,
                    cardinality,
                }
            })
            .collect();

        // Sort by frequency (descending)
        combinations.sort_by(|a, b| b.frequency.cmp(&a.frequency));

        let n_unique_combinations = combinations.len();

        // Find most and least frequent
        let most_frequent = combinations[0].clone();
        let least_frequent = combinations[n_unique_combinations - 1].clone();

        // Calculate average cardinality
        let total_cardinality: usize = combinations
            .iter()
            .map(|info| info.cardinality * info.frequency)
            .sum();
        let avg_cardinality = total_cardinality as f64 / n_samples as f64;

        // Calculate label density
        let label_density = total_active_labels as f64 / (n_samples * n_labels) as f64;

        Ok(LabelAnalysisResults {
            combinations,
            n_samples,
            n_labels,
            n_unique_combinations,
            most_frequent,
            least_frequent,
            avg_cardinality,
            label_density,
        })
    }

    /// Get combinations that appear less than a specified threshold
    ///
    /// This function identifies rare label combinations that could be candidates
    /// for pruning in algorithms like Pruned Label Powerset.
    ///
    /// # Arguments
    ///
    /// * `results` - Results from analyze_combinations
    /// * `min_frequency` - Minimum frequency threshold
    ///
    /// # Returns
    ///
    /// Vector of combinations that appear less than min_frequency times
    pub fn get_rare_combinations(
        results: &LabelAnalysisResults,
        min_frequency: usize,
    ) -> Vec<&CombinationInfo> {
        results
            .combinations
            .iter()
            .filter(|info| info.frequency < min_frequency)
            .collect()
    }

    /// Get combinations with specific cardinality
    ///
    /// This function filters combinations by the number of active labels.
    ///
    /// # Arguments
    ///
    /// * `results` - Results from analyze_combinations
    /// * `cardinality` - Number of active labels to filter by
    ///
    /// # Returns
    ///
    /// Vector of combinations with the specified cardinality
    pub fn get_combinations_by_cardinality(
        results: &LabelAnalysisResults,
        cardinality: usize,
    ) -> Vec<&CombinationInfo> {
        results
            .combinations
            .iter()
            .filter(|info| info.cardinality == cardinality)
            .collect()
    }

    /// Calculate label co-occurrence matrix
    ///
    /// This function computes how often pairs of labels appear together.
    ///
    /// # Arguments
    ///
    /// * `y` - Multi-label target array
    ///
    /// # Returns
    ///
    /// Symmetric matrix where entry (i,j) is the number of times labels i and j appear together
    pub fn label_cooccurrence_matrix(y: &ArrayView2<'_, i32>) -> SklResult<Array2<usize>> {
        let (n_samples, n_labels) = y.dim();

        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input array must have at least one sample and one label".to_string(),
            ));
        }

        let mut cooccurrence = Array2::zeros((n_labels, n_labels));

        for sample_idx in 0..n_samples {
            for i in 0..n_labels {
                for j in 0..n_labels {
                    if y[[sample_idx, i]] == 1 && y[[sample_idx, j]] == 1 {
                        cooccurrence[[i, j]] += 1;
                    }
                }
            }
        }

        Ok(cooccurrence)
    }

    /// Calculate label correlation matrix
    ///
    /// This function computes Pearson correlation coefficients between pairs of labels.
    ///
    /// # Arguments
    ///
    /// * `y` - Multi-label target array
    ///
    /// # Returns
    ///
    /// Symmetric correlation matrix
    pub fn label_correlation_matrix(y: &ArrayView2<'_, i32>) -> SklResult<Array2<f64>> {
        let (n_samples, n_labels) = y.dim();

        if n_samples == 0 || n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "Input array must have at least one sample and one label".to_string(),
            ));
        }

        let mut correlation = Array2::zeros((n_labels, n_labels));

        // Compute means for each label
        let mut means = vec![0.0; n_labels];
        for label_idx in 0..n_labels {
            let sum: i32 = (0..n_samples)
                .map(|sample_idx| y[[sample_idx, label_idx]])
                .sum();
            means[label_idx] = sum as f64 / n_samples as f64;
        }

        // Compute correlations
        for i in 0..n_labels {
            for j in 0..n_labels {
                if i == j {
                    correlation[[i, j]] = 1.0;
                } else {
                    let mut numerator = 0.0;
                    let mut var_i = 0.0;
                    let mut var_j = 0.0;

                    for sample_idx in 0..n_samples {
                        let diff_i = y[[sample_idx, i]] as f64 - means[i];
                        let diff_j = y[[sample_idx, j]] as f64 - means[j];

                        numerator += diff_i * diff_j;
                        var_i += diff_i * diff_i;
                        var_j += diff_j * diff_j;
                    }

                    if var_i > 1e-10 && var_j > 1e-10 {
                        correlation[[i, j]] = numerator / (var_i.sqrt() * var_j.sqrt());
                    } else {
                        correlation[[i, j]] = 0.0;
                    }
                }
            }
        }

        Ok(correlation)
    }
}

/// Multi-Target Regression Tree
///
/// A decision tree regressor that can handle multiple target variables simultaneously.
/// This implementation fits a single tree that can predict multiple continuous targets
/// by using variance reduction criteria that consider all targets jointly.
///
/// # Mathematical Foundation
///
/// For multi-target regression, the tree uses the following variance reduction criterion:
/// - At each split, calculate the weighted sum of variances across all targets
/// - Choose the split that minimizes: Σ(n_left * var_left + n_right * var_right) for all targets
/// - Leaf predictions are the mean values for each target in that leaf
///
/// # Examples
///
/// ```
/// use sklears_multioutput::MultiTargetRegressionTree;
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];
///
/// let tree = MultiTargetRegressionTree::new()
///     .max_depth(Some(3))
///     .min_samples_split(2);
/// let trained_tree = tree.fit(&X.view(), &y).unwrap();
/// let predictions = trained_tree.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct MultiTargetRegressionTree<S = Untrained> {
    state: S,
    max_depth: Option<usize>,
    min_samples_split: usize,
    min_samples_leaf: usize,
    random_state: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct MultiTargetRegressionTreeTrained {
    tree: DecisionNode,
    n_features: usize,
    n_targets: usize,
    feature_importances: Array1<Float>,
}

#[derive(Debug, Clone)]
struct DecisionNode {
    is_leaf: bool,
    prediction: Option<Array1<Float>>, // Mean values for each target
    feature_idx: Option<usize>,
    threshold: Option<Float>,
    left: Option<Box<DecisionNode>>,
    right: Option<Box<DecisionNode>>,
    n_samples: usize,
    variance: Float, // Sum of variances across all targets
}

impl MultiTargetRegressionTree<Untrained> {
    /// Create a new MultiTargetRegressionTree instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            max_depth: Some(5),
            min_samples_split: 2,
            min_samples_leaf: 1,
            random_state: None,
        }
    }

    /// Set the maximum depth of the tree
    pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// Set the minimum number of samples required to split an internal node
    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.min_samples_split = min_samples_split;
        self
    }

    /// Set the minimum number of samples required to be at a leaf node
    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.min_samples_leaf = min_samples_leaf;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<Float>> for MultiTargetRegressionTree<Untrained> {
    type Fitted = MultiTargetRegressionTree<MultiTargetRegressionTreeTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<Float>) -> SklResult<Self::Fitted> {
        let X = X.to_owned();
        let (n_samples, n_features) = X.dim();

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

        let n_targets = y.ncols();
        if n_targets == 0 {
            return Err(SklearsError::InvalidInput(
                "y must have at least one target".to_string(),
            ));
        }

        if n_samples < self.min_samples_split {
            return Err(SklearsError::InvalidInput(
                "Number of samples is less than min_samples_split".to_string(),
            ));
        }

        // Build the tree
        let indices: Vec<usize> = (0..n_samples).collect();
        let tree = self.build_tree(&X, y, &indices, 0)?;

        // Calculate feature importances (simplified)
        let mut feature_importances = Array1::<Float>::zeros(n_features);
        self.calculate_feature_importances(&tree, &mut feature_importances, n_samples as Float);

        // Normalize feature importances
        let sum_importances: Float = feature_importances.sum();
        if sum_importances > 0.0 {
            feature_importances /= sum_importances;
        }

        Ok(MultiTargetRegressionTree {
            state: MultiTargetRegressionTreeTrained {
                tree,
                n_features,
                n_targets,
                feature_importances,
            },
            max_depth: self.max_depth,
            min_samples_split: self.min_samples_split,
            min_samples_leaf: self.min_samples_leaf,
            random_state: self.random_state,
        })
    }
}

impl MultiTargetRegressionTree<Untrained> {
    fn build_tree(
        &self,
        X: &Array2<Float>,
        y: &Array2<Float>,
        indices: &[usize],
        depth: usize,
    ) -> SklResult<DecisionNode> {
        let n_samples = indices.len();
        let n_targets = y.ncols();

        // Calculate current prediction (mean of targets)
        let mut prediction = Array1::<Float>::zeros(n_targets);
        for &idx in indices {
            for j in 0..n_targets {
                prediction[j] += y[[idx, j]];
            }
        }
        prediction /= n_samples as Float;

        // Calculate variance across all targets
        let mut variance = 0.0;
        for &idx in indices {
            for j in 0..n_targets {
                let diff = y[[idx, j]] - prediction[j];
                variance += diff * diff;
            }
        }
        variance /= n_samples as Float;

        // Check stopping criteria
        let should_stop = n_samples < self.min_samples_split
            || n_samples < self.min_samples_leaf
            || self.max_depth.map_or(false, |max_d| depth >= max_d)
            || variance < 1e-10;

        if should_stop {
            return Ok(DecisionNode {
                is_leaf: true,
                prediction: Some(prediction),
                feature_idx: None,
                threshold: None,
                left: None,
                right: None,
                n_samples,
                variance,
            });
        }

        // Find best split
        let (best_feature, best_threshold, best_variance_reduction) =
            self.find_best_split(X, y, indices)?;

        if best_variance_reduction <= 0.0 {
            return Ok(DecisionNode {
                is_leaf: true,
                prediction: Some(prediction),
                feature_idx: None,
                threshold: None,
                left: None,
                right: None,
                n_samples,
                variance,
            });
        }

        // Split the data
        let (left_indices, right_indices) =
            self.split_data(X, indices, best_feature, best_threshold);

        if left_indices.len() < self.min_samples_leaf || right_indices.len() < self.min_samples_leaf
        {
            return Ok(DecisionNode {
                is_leaf: true,
                prediction: Some(prediction),
                feature_idx: None,
                threshold: None,
                left: None,
                right: None,
                n_samples,
                variance,
            });
        }

        // Recursively build child nodes
        let left_child = self.build_tree(X, y, &left_indices, depth + 1)?;
        let right_child = self.build_tree(X, y, &right_indices, depth + 1)?;

        Ok(DecisionNode {
            is_leaf: false,
            prediction: None,
            feature_idx: Some(best_feature),
            threshold: Some(best_threshold),
            left: Some(Box::new(left_child)),
            right: Some(Box::new(right_child)),
            n_samples,
            variance,
        })
    }

    fn find_best_split(
        &self,
        X: &Array2<Float>,
        y: &Array2<Float>,
        indices: &[usize],
    ) -> SklResult<(usize, Float, Float)> {
        let n_features = X.ncols();
        let n_targets = y.ncols();
        let mut best_feature = 0;
        let mut best_threshold = 0.0;
        let mut best_variance_reduction = 0.0;

        // Calculate current variance
        let current_variance = self.calculate_variance(y, indices);

        for feature_idx in 0..n_features {
            // Get unique feature values
            let mut feature_values: Vec<Float> =
                indices.iter().map(|&idx| X[[idx, feature_idx]]).collect();
            feature_values.sort_by(|a, b| a.partial_cmp(b).unwrap());
            feature_values.dedup();

            for i in 0..feature_values.len().saturating_sub(1) {
                let threshold = (feature_values[i] + feature_values[i + 1]) / 2.0;

                let (left_indices, right_indices) =
                    self.split_data(X, indices, feature_idx, threshold);

                if left_indices.is_empty() || right_indices.is_empty() {
                    continue;
                }

                let left_variance = self.calculate_variance(y, &left_indices);
                let right_variance = self.calculate_variance(y, &right_indices);

                let weighted_variance = (left_indices.len() as Float * left_variance
                    + right_indices.len() as Float * right_variance)
                    / indices.len() as Float;

                let variance_reduction = current_variance - weighted_variance;

                if variance_reduction > best_variance_reduction {
                    best_variance_reduction = variance_reduction;
                    best_feature = feature_idx;
                    best_threshold = threshold;
                }
            }
        }

        Ok((best_feature, best_threshold, best_variance_reduction))
    }

    fn calculate_variance(&self, y: &Array2<Float>, indices: &[usize]) -> Float {
        if indices.is_empty() {
            return 0.0;
        }

        let n_targets = y.ncols();
        let n_samples = indices.len();

        // Calculate means
        let mut means = Array1::<Float>::zeros(n_targets);
        for &idx in indices {
            for j in 0..n_targets {
                means[j] += y[[idx, j]];
            }
        }
        means /= n_samples as Float;

        // Calculate variance
        let mut variance = 0.0;
        for &idx in indices {
            for j in 0..n_targets {
                let diff = y[[idx, j]] - means[j];
                variance += diff * diff;
            }
        }
        variance / n_samples as Float
    }

    fn split_data(
        &self,
        X: &Array2<Float>,
        indices: &[usize],
        feature_idx: usize,
        threshold: Float,
    ) -> (Vec<usize>, Vec<usize>) {
        let mut left_indices = Vec::new();
        let mut right_indices = Vec::new();

        for &idx in indices {
            if X[[idx, feature_idx]] <= threshold {
                left_indices.push(idx);
            } else {
                right_indices.push(idx);
            }
        }

        (left_indices, right_indices)
    }

    fn calculate_feature_importances(
        &self,
        node: &DecisionNode,
        importances: &mut Array1<Float>,
        total_samples: Float,
    ) {
        if let (Some(feature_idx), Some(left), Some(right)) =
            (node.feature_idx, &node.left, &node.right)
        {
            let importance = (node.n_samples as Float / total_samples) * node.variance;
            importances[feature_idx] += importance;

            self.calculate_feature_importances(left, importances, total_samples);
            self.calculate_feature_importances(right, importances, total_samples);
        }
    }
}

impl MultiTargetRegressionTree<MultiTargetRegressionTreeTrained> {
    /// Get the feature importances
    pub fn feature_importances(&self) -> &Array1<Float> {
        &self.state.feature_importances
    }

    /// Get the number of features
    pub fn n_features(&self) -> usize {
        self.state.n_features
    }

    /// Get the number of targets
    pub fn n_targets(&self) -> usize {
        self.state.n_targets
    }

    /// Predict using the fitted tree
    pub fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let X = *X;
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        let mut predictions = Array2::<Float>::zeros((n_samples, self.state.n_targets));

        for i in 0..n_samples {
            let sample = X.slice(s![i, ..]);
            let prediction = self.predict_single(&self.state.tree, &sample)?;
            for j in 0..self.state.n_targets {
                predictions[[i, j]] = prediction[j];
            }
        }

        Ok(predictions)
    }

    fn predict_single(
        &self,
        node: &DecisionNode,
        sample: &ArrayView1<'_, Float>,
    ) -> SklResult<Array1<Float>> {
        if node.is_leaf {
            if let Some(ref prediction) = node.prediction {
                Ok(prediction.clone())
            } else {
                Err(SklearsError::InvalidInput(
                    "Leaf node without prediction".to_string(),
                ))
            }
        } else {
            let feature_idx = node.feature_idx.ok_or(SklearsError::InvalidInput(
                "Non-leaf node without feature index".to_string(),
            ))?;
            let threshold = node.threshold.ok_or(SklearsError::InvalidInput(
                "Non-leaf node without threshold".to_string(),
            ))?;

            if sample[feature_idx] <= threshold {
                if let Some(ref left) = node.left {
                    self.predict_single(left, sample)
                } else {
                    Err(SklearsError::InvalidInput(
                        "Non-leaf node without left child".to_string(),
                    ))
                }
            } else {
                if let Some(ref right) = node.right {
                    self.predict_single(right, sample)
                } else {
                    Err(SklearsError::InvalidInput(
                        "Non-leaf node without right child".to_string(),
                    ))
                }
            }
        }
    }
}

/// Random Forest Multi-Output Extension
///
/// A random forest that can handle multiple output variables simultaneously.
/// This implementation creates multiple multi-target regression trees and
/// averages their predictions for robust multi-output regression.
///
/// # Mathematical Foundation
///
/// The random forest combines multiple multi-target regression trees:
/// - Each tree is trained on a bootstrap sample of the data
/// - Each tree considers only a random subset of features at each split
/// - Final prediction is the average of all tree predictions
/// - Feature importance is averaged across all trees
///
/// # Examples
///
/// ```
/// use sklears_multioutput::RandomForestMultiOutput;
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];
///
/// let forest = RandomForestMultiOutput::new()
///     .n_estimators(10)
///     .max_depth(Some(3));
/// let trained_forest = forest.fit(&X.view(), &y).unwrap();
/// let predictions = trained_forest.predict(&X.view()).unwrap();
/// ```

/// Multi-Target Decision Tree Classifier
///
/// A decision tree classifier that can handle multiple target variables simultaneously.
/// Uses joint entropy/gini reduction for optimal splits across all targets.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::MultiTargetDecisionTreeClassifier;
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[0, 1], [1, 0], [1, 1], [0, 0]]; // Two binary classification targets
///
/// let tree = MultiTargetDecisionTreeClassifier::new()
///     .max_depth(Some(3));
/// let trained_tree = tree.fit(&X.view(), &y).unwrap();
/// let predictions = trained_tree.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct MultiTargetDecisionTreeClassifier<S = Untrained> {
    state: S,
    max_depth: Option<usize>,
    min_samples_split: usize,
    min_samples_leaf: usize,
    criterion: ClassificationCriterion,
    random_state: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct MultiTargetDecisionTreeClassifierTrained {
    tree: ClassificationDecisionNode,
    n_features: usize,
    n_targets: usize,
    feature_importances: Array1<Float>,
    classes_per_target: Vec<Vec<i32>>,
}

#[derive(Debug, Clone, Copy)]
pub enum ClassificationCriterion {
    /// Gini impurity
    Gini,
    /// Information gain / entropy
    Entropy,
}

#[derive(Debug, Clone)]
struct ClassificationDecisionNode {
    is_leaf: bool,
    prediction: Option<Array1<i32>>, // Mode/majority class for each target
    probabilities: Option<Array2<Float>>, // Probability distributions per target
    feature_idx: Option<usize>,
    threshold: Option<Float>,
    left: Option<Box<ClassificationDecisionNode>>,
    right: Option<Box<ClassificationDecisionNode>>,
    n_samples: usize,
    impurity: Float, // Combined impurity across all targets
}

impl MultiTargetDecisionTreeClassifier<Untrained> {
    /// Create a new MultiTargetDecisionTreeClassifier instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            max_depth: Some(5),
            min_samples_split: 2,
            min_samples_leaf: 1,
            criterion: ClassificationCriterion::Gini,
            random_state: None,
        }
    }

    /// Set the maximum depth of the tree
    pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// Set the minimum number of samples required to split an internal node
    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.min_samples_split = min_samples_split;
        self
    }

    /// Set the minimum number of samples required to be at a leaf node
    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.min_samples_leaf = min_samples_leaf;
        self
    }

    /// Set the split criterion
    pub fn criterion(mut self, criterion: ClassificationCriterion) -> Self {
        self.criterion = criterion;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for MultiTargetDecisionTreeClassifier<Untrained> {
    type Fitted = MultiTargetDecisionTreeClassifier<MultiTargetDecisionTreeClassifierTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let X = X.to_owned();
        let (n_samples, n_features) = X.dim();

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

        let n_targets = y.ncols();
        if n_targets == 0 {
            return Err(SklearsError::InvalidInput(
                "y must have at least one target".to_string(),
            ));
        }

        // Get unique classes for each target
        let mut classes_per_target = Vec::new();
        for target_idx in 0..n_targets {
            let target_column = y.column(target_idx);
            let mut unique_classes: Vec<i32> = target_column.iter().cloned().collect();
            unique_classes.sort_unstable();
            unique_classes.dedup();
            classes_per_target.push(unique_classes);
        }

        // Initialize feature importances
        let mut feature_importances = Array1::zeros(n_features);

        // Build the tree
        let indices: Vec<usize> = (0..n_samples).collect();
        let tree = build_classification_tree(
            &X,
            y,
            &indices,
            &mut feature_importances,
            0,
            self.max_depth,
            self.min_samples_split,
            self.min_samples_leaf,
            self.criterion,
            &classes_per_target,
        )?;

        // Normalize feature importances
        let importance_sum = feature_importances.sum();
        if importance_sum > 0.0 {
            feature_importances /= importance_sum;
        }

        let trained_state = MultiTargetDecisionTreeClassifierTrained {
            tree,
            n_features,
            n_targets,
            feature_importances,
            classes_per_target,
        };

        Ok(MultiTargetDecisionTreeClassifier {
            state: trained_state,
            max_depth: self.max_depth,
            min_samples_split: self.min_samples_split,
            min_samples_leaf: self.min_samples_leaf,
            criterion: self.criterion,
            random_state: self.random_state,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>>
    for MultiTargetDecisionTreeClassifier<MultiTargetDecisionTreeClassifierTrained>
{
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_samples, self.state.n_targets));

        for i in 0..n_samples {
            let sample = X.row(i);
            let prediction = predict_classification_sample(&self.state.tree, &sample);
            for j in 0..self.state.n_targets {
                predictions[[i, j]] = prediction[j];
            }
        }

        Ok(predictions)
    }
}

impl MultiTargetDecisionTreeClassifier<MultiTargetDecisionTreeClassifierTrained> {
    /// Get feature importances
    pub fn feature_importances(&self) -> &Array1<Float> {
        &self.state.feature_importances
    }

    /// Predict class probabilities for each target
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Vec<Array2<Float>>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut all_probabilities = Vec::new();

        // Initialize probability arrays for each target
        for target_idx in 0..self.state.n_targets {
            let n_classes = self.state.classes_per_target[target_idx].len();
            all_probabilities.push(Array2::zeros((n_samples, n_classes)));
        }

        for i in 0..n_samples {
            let sample = X.row(i);
            let probabilities = predict_classification_probabilities(
                &self.state.tree,
                &sample,
                &self.state.classes_per_target,
            );

            for (target_idx, target_probs) in probabilities.iter().enumerate() {
                for (class_idx, &prob) in target_probs.iter().enumerate() {
                    all_probabilities[target_idx][[i, class_idx]] = prob;
                }
            }
        }

        Ok(all_probabilities)
    }
}

/// Build a classification decision tree recursively
fn build_classification_tree(
    X: &Array2<Float>,
    y: &Array2<i32>,
    indices: &[usize],
    feature_importances: &mut Array1<Float>,
    depth: usize,
    max_depth: Option<usize>,
    min_samples_split: usize,
    min_samples_leaf: usize,
    criterion: ClassificationCriterion,
    classes_per_target: &[Vec<i32>],
) -> SklResult<ClassificationDecisionNode> {
    let n_samples = indices.len();
    let n_targets = y.ncols();

    // Calculate current impurity and predictions
    let (current_impurity, prediction, probabilities) =
        calculate_classification_metrics(y, indices, classes_per_target, criterion);

    // Check stopping criteria
    let should_stop = n_samples < min_samples_split
        || (max_depth.is_some() && depth >= max_depth.unwrap())
        || current_impurity == 0.0;

    if should_stop {
        return Ok(ClassificationDecisionNode {
            is_leaf: true,
            prediction: Some(prediction),
            probabilities: Some(probabilities),
            feature_idx: None,
            threshold: None,
            left: None,
            right: None,
            n_samples,
            impurity: current_impurity,
        });
    }

    // Find best split
    let mut best_impurity_reduction = 0.0;
    let mut best_feature = None;
    let mut best_threshold = None;
    let mut best_left_indices = Vec::new();
    let mut best_right_indices = Vec::new();

    for feature_idx in 0..X.ncols() {
        // Get unique values for this feature in current samples
        let mut feature_values: Vec<Float> = indices.iter().map(|&i| X[[i, feature_idx]]).collect();
        feature_values.sort_by(|a, b| a.partial_cmp(b).unwrap());
        feature_values.dedup();

        // Try splits between consecutive unique values
        for i in 0..feature_values.len().saturating_sub(1) {
            let threshold = (feature_values[i] + feature_values[i + 1]) / 2.0;

            let (left_indices, right_indices): (Vec<usize>, Vec<usize>) = indices
                .iter()
                .partition(|&&idx| X[[idx, feature_idx]] <= threshold);

            // Check minimum samples per leaf
            if left_indices.len() < min_samples_leaf || right_indices.len() < min_samples_leaf {
                continue;
            }

            // Calculate impurity reduction
            let (left_impurity, _, _) =
                calculate_classification_metrics(y, &left_indices, classes_per_target, criterion);
            let (right_impurity, _, _) =
                calculate_classification_metrics(y, &right_indices, classes_per_target, criterion);

            let weighted_impurity = (left_indices.len() as Float * left_impurity
                + right_indices.len() as Float * right_impurity)
                / n_samples as Float;
            let impurity_reduction = current_impurity - weighted_impurity;

            if impurity_reduction > best_impurity_reduction {
                best_impurity_reduction = impurity_reduction;
                best_feature = Some(feature_idx);
                best_threshold = Some(threshold);
                best_left_indices = left_indices;
                best_right_indices = right_indices;
            }
        }
    }

    // If no good split found, create leaf
    if best_feature.is_none() || best_impurity_reduction <= 0.0 {
        return Ok(ClassificationDecisionNode {
            is_leaf: true,
            prediction: Some(prediction),
            probabilities: Some(probabilities),
            feature_idx: None,
            threshold: None,
            left: None,
            right: None,
            n_samples,
            impurity: current_impurity,
        });
    }

    // Update feature importance
    feature_importances[best_feature.unwrap()] += best_impurity_reduction * n_samples as Float;

    // Recursively build left and right subtrees
    let left_child = build_classification_tree(
        X,
        y,
        &best_left_indices,
        feature_importances,
        depth + 1,
        max_depth,
        min_samples_split,
        min_samples_leaf,
        criterion,
        classes_per_target,
    )?;

    let right_child = build_classification_tree(
        X,
        y,
        &best_right_indices,
        feature_importances,
        depth + 1,
        max_depth,
        min_samples_split,
        min_samples_leaf,
        criterion,
        classes_per_target,
    )?;

    Ok(ClassificationDecisionNode {
        is_leaf: false,
        prediction: Some(prediction),
        probabilities: Some(probabilities),
        feature_idx: best_feature,
        threshold: best_threshold,
        left: Some(Box::new(left_child)),
        right: Some(Box::new(right_child)),
        n_samples,
        impurity: current_impurity,
    })
}

/// Calculate classification metrics for a set of samples
fn calculate_classification_metrics(
    y: &Array2<i32>,
    indices: &[usize],
    classes_per_target: &[Vec<i32>],
    criterion: ClassificationCriterion,
) -> (Float, Array1<i32>, Array2<Float>) {
    let n_targets = y.ncols();
    let n_samples = indices.len();

    let mut prediction = Array1::zeros(n_targets);
    let mut total_impurity = 0.0;

    // Calculate max number of classes across all targets for probability matrix
    let max_classes = classes_per_target
        .iter()
        .map(|classes| classes.len())
        .max()
        .unwrap_or(0);
    let mut probabilities = Array2::zeros((n_targets, max_classes));

    for target_idx in 0..n_targets {
        let classes = &classes_per_target[target_idx];
        let n_classes = classes.len();

        // Count class frequencies
        let mut class_counts = vec![0; n_classes];
        for &sample_idx in indices {
            let class_label = y[[sample_idx, target_idx]];
            if let Some(class_idx) = classes.iter().position(|&c| c == class_label) {
                class_counts[class_idx] += 1;
            }
        }

        // Find majority class
        let majority_class_idx = class_counts
            .iter()
            .enumerate()
            .max_by_key(|(_, &count)| count)
            .map(|(idx, _)| idx)
            .unwrap_or(0);

        prediction[target_idx] = classes[majority_class_idx];

        // Calculate probabilities and impurity
        let mut target_impurity = 0.0;
        for (class_idx, &count) in class_counts.iter().enumerate() {
            let prob = count as Float / n_samples as Float;
            probabilities[[target_idx, class_idx]] = prob;

            if prob > 0.0 {
                target_impurity += match criterion {
                    ClassificationCriterion::Gini => prob * (1.0 - prob),
                    ClassificationCriterion::Entropy => -prob * prob.ln(),
                };
            }
        }

        // For Gini, multiply by 2; for Entropy, it's already correct
        if matches!(criterion, ClassificationCriterion::Gini) {
            target_impurity *= 2.0;
        }

        total_impurity += target_impurity;
    }

    // Average impurity across targets
    total_impurity /= n_targets as Float;

    (total_impurity, prediction, probabilities)
}

/// Predict for a single classification sample
fn predict_classification_sample(
    node: &ClassificationDecisionNode,
    sample: &ArrayView1<Float>,
) -> Array1<i32> {
    if node.is_leaf {
        return node.prediction.as_ref().unwrap().clone();
    }

    let feature_value = sample[node.feature_idx.unwrap()];
    let threshold = node.threshold.unwrap();

    if feature_value <= threshold {
        predict_classification_sample(node.left.as_ref().unwrap(), sample)
    } else {
        predict_classification_sample(node.right.as_ref().unwrap(), sample)
    }
}

/// Predict probabilities for a single classification sample
fn predict_classification_probabilities(
    node: &ClassificationDecisionNode,
    sample: &ArrayView1<Float>,
    classes_per_target: &[Vec<i32>],
) -> Vec<Array1<Float>> {
    if node.is_leaf {
        let mut result = Vec::new();
        for target_idx in 0..classes_per_target.len() {
            let n_classes = classes_per_target[target_idx].len();
            let mut target_probs = Array1::zeros(n_classes);
            for class_idx in 0..n_classes {
                target_probs[class_idx] =
                    node.probabilities.as_ref().unwrap()[[target_idx, class_idx]];
            }
            result.push(target_probs);
        }
        return result;
    }

    let feature_value = sample[node.feature_idx.unwrap()];
    let threshold = node.threshold.unwrap();

    if feature_value <= threshold {
        predict_classification_probabilities(
            node.left.as_ref().unwrap(),
            sample,
            classes_per_target,
        )
    } else {
        predict_classification_probabilities(
            node.right.as_ref().unwrap(),
            sample,
            classes_per_target,
        )
    }
}

#[derive(Debug, Clone)]
pub struct RandomForestMultiOutput<S = Untrained> {
    state: S,
    n_estimators: usize,
    max_depth: Option<usize>,
    min_samples_split: usize,
    min_samples_leaf: usize,
    max_features: Option<usize>,
    bootstrap: bool,
    random_state: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct RandomForestMultiOutputTrained {
    trees: Vec<MultiTargetRegressionTree<MultiTargetRegressionTreeTrained>>,
    n_features: usize,
    n_targets: usize,
    feature_importances: Array1<Float>,
}

impl RandomForestMultiOutput<Untrained> {
    /// Create a new RandomForestMultiOutput instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            n_estimators: 10,
            max_depth: None,
            min_samples_split: 2,
            min_samples_leaf: 1,
            max_features: None,
            bootstrap: true,
            random_state: None,
        }
    }

    /// Set the number of trees in the forest
    pub fn n_estimators(mut self, n_estimators: usize) -> Self {
        self.n_estimators = n_estimators;
        self
    }

    /// Set the maximum depth of the trees
    pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// Set the minimum number of samples required to split an internal node
    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.min_samples_split = min_samples_split;
        self
    }

    /// Set the minimum number of samples required to be at a leaf node
    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.min_samples_leaf = min_samples_leaf;
        self
    }

    /// Set the number of features to consider when looking for the best split
    pub fn max_features(mut self, max_features: Option<usize>) -> Self {
        self.max_features = max_features;
        self
    }

    /// Set whether to use bootstrap samples when building trees
    pub fn bootstrap(mut self, bootstrap: bool) -> Self {
        self.bootstrap = bootstrap;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<Float>> for RandomForestMultiOutput<Untrained> {
    type Fitted = RandomForestMultiOutput<RandomForestMultiOutputTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<Float>) -> SklResult<Self::Fitted> {
        let X = X.to_owned();
        let (n_samples, n_features) = X.dim();

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

        let n_targets = y.ncols();
        if n_targets == 0 {
            return Err(SklearsError::InvalidInput(
                "y must have at least one target".to_string(),
            ));
        }

        let mut trees = Vec::new();
        let mut feature_importances = Array1::<Float>::zeros(n_features);

        for i in 0..self.n_estimators {
            // Create bootstrap sample if needed
            let (X_sample, y_sample) = if self.bootstrap {
                self.create_bootstrap_sample(&X, y, i)?
            } else {
                (X.clone(), y.clone())
            };

            // Create and train tree
            let tree = MultiTargetRegressionTree::new()
                .max_depth(self.max_depth)
                .min_samples_split(self.min_samples_split)
                .min_samples_leaf(self.min_samples_leaf)
                .random_state(self.random_state.map(|s| s.wrapping_add(i as u64)));

            let trained_tree = tree.fit(&X_sample.view(), &y_sample)?;

            // Accumulate feature importances
            feature_importances += trained_tree.feature_importances();

            trees.push(trained_tree);
        }

        // Average feature importances
        feature_importances /= self.n_estimators as Float;

        Ok(RandomForestMultiOutput {
            state: RandomForestMultiOutputTrained {
                trees,
                n_features,
                n_targets,
                feature_importances,
            },
            n_estimators: self.n_estimators,
            max_depth: self.max_depth,
            min_samples_split: self.min_samples_split,
            min_samples_leaf: self.min_samples_leaf,
            max_features: self.max_features,
            bootstrap: self.bootstrap,
            random_state: self.random_state,
        })
    }
}

impl RandomForestMultiOutput<Untrained> {
    fn create_bootstrap_sample(
        &self,
        X: &Array2<Float>,
        y: &Array2<Float>,
        seed: usize,
    ) -> SklResult<(Array2<Float>, Array2<Float>)> {
        let n_samples = X.nrows();
        let mut rng_state = self.random_state.unwrap_or(42).wrapping_add(seed as u64);

        let mut X_sample = Array2::<Float>::zeros(X.raw_dim());
        let mut y_sample = Array2::<Float>::zeros(y.raw_dim());

        for i in 0..n_samples {
            rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
            let idx = (rng_state / 65536) % (n_samples as u64);

            X_sample
                .slice_mut(s![i, ..])
                .assign(&X.slice(s![idx as usize, ..]));
            y_sample
                .slice_mut(s![i, ..])
                .assign(&y.slice(s![idx as usize, ..]));
        }

        Ok((X_sample, y_sample))
    }
}

impl RandomForestMultiOutput<RandomForestMultiOutputTrained> {
    /// Get the feature importances averaged across all trees
    pub fn feature_importances(&self) -> &Array1<Float> {
        &self.state.feature_importances
    }

    /// Get the number of estimators (trees)
    pub fn n_estimators(&self) -> usize {
        self.state.trees.len()
    }

    /// Get the number of features
    pub fn n_features(&self) -> usize {
        self.state.n_features
    }

    /// Get the number of targets
    pub fn n_targets(&self) -> usize {
        self.state.n_targets
    }

    /// Predict using the forest (average of all tree predictions)
    pub fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let X = *X;
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        let mut predictions = Array2::<Float>::zeros((n_samples, self.state.n_targets));

        // Average predictions from all trees
        for tree in &self.state.trees {
            let tree_predictions = tree.predict(&X)?;
            predictions += &tree_predictions;
        }

        predictions /= self.state.trees.len() as Float;
        Ok(predictions)
    }
}

/// Gradient Boosting Multi-Output
///
/// A gradient boosting implementation that can handle multiple output variables simultaneously.
/// This implementation builds an additive model of weak learners (multi-target regression trees)
/// in a forward stage-wise fashion, optimizing a loss function for all targets jointly.
///
/// # Mathematical Foundation
///
/// For multi-target regression, gradient boosting minimizes:
/// - L(y, F(x)) = Σ_i Σ_j (y_ij - F_j(x_i))^2 for all samples i and targets j
/// - F_j(x) = F_0j + Σ_m ρ_m * h_mj(x) where h_mj are weak learners for target j at stage m
/// - At each stage, fit weak learners to negative gradients: -∂L/∂F_j
///
/// # Examples
///
/// ```
/// use sklears_multioutput::GradientBoostingMultiOutput;
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];
///
/// let gbm = GradientBoostingMultiOutput::new()
///     .n_estimators(50)
///     .learning_rate(0.1)
///     .max_depth(Some(3));
/// let trained_gbm = gbm.fit(&X.view(), &y).unwrap();
/// let predictions = trained_gbm.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct GradientBoostingMultiOutput<S = Untrained> {
    state: S,
    n_estimators: usize,
    learning_rate: Float,
    max_depth: Option<usize>,
    min_samples_split: usize,
    min_samples_leaf: usize,
    subsample: Float,
    random_state: Option<u64>,
}

#[derive(Debug, Clone)]
pub struct GradientBoostingMultiOutputTrained {
    estimators: Vec<MultiTargetRegressionTree<MultiTargetRegressionTreeTrained>>,
    init_predictions: Array1<Float>, // Initial prediction for each target
    n_features: usize,
    n_targets: usize,
    feature_importances: Array1<Float>,
    train_scores: Vec<Float>, // Training loss at each iteration
}

impl GradientBoostingMultiOutput<Untrained> {
    /// Create a new GradientBoostingMultiOutput instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            n_estimators: 100,
            learning_rate: 0.1,
            max_depth: Some(3),
            min_samples_split: 2,
            min_samples_leaf: 1,
            subsample: 1.0,
            random_state: None,
        }
    }

    /// Set the number of boosting stages
    pub fn n_estimators(mut self, n_estimators: usize) -> Self {
        self.n_estimators = n_estimators;
        self
    }

    /// Set the learning rate (shrinkage)
    pub fn learning_rate(mut self, learning_rate: Float) -> Self {
        self.learning_rate = learning_rate;
        self
    }

    /// Set the maximum depth of the individual regression estimators
    pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// Set the minimum number of samples required to split an internal node
    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.min_samples_split = min_samples_split;
        self
    }

    /// Set the minimum number of samples required to be at a leaf node
    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.min_samples_leaf = min_samples_leaf;
        self
    }

    /// Set the fraction of samples to be used for fitting the individual base learners
    pub fn subsample(mut self, subsample: Float) -> Self {
        self.subsample = subsample;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<Float>> for GradientBoostingMultiOutput<Untrained> {
    type Fitted = GradientBoostingMultiOutput<GradientBoostingMultiOutputTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<Float>) -> SklResult<Self::Fitted> {
        let X = X.to_owned();
        let (n_samples, n_features) = X.dim();

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

        let n_targets = y.ncols();
        if n_targets == 0 {
            return Err(SklearsError::InvalidInput(
                "y must have at least one target".to_string(),
            ));
        }

        if self.learning_rate <= 0.0 {
            return Err(SklearsError::InvalidInput(
                "Learning rate must be positive".to_string(),
            ));
        }

        if self.subsample <= 0.0 || self.subsample > 1.0 {
            return Err(SklearsError::InvalidInput(
                "Subsample must be in (0, 1]".to_string(),
            ));
        }

        // Initialize with mean of targets
        let init_predictions = y.mean_axis(Axis(0)).ok_or(SklearsError::InvalidInput(
            "Cannot compute mean of targets".to_string(),
        ))?;

        // Initialize predictions
        let mut current_predictions = Array2::<Float>::zeros((n_samples, n_targets));
        for i in 0..n_samples {
            for j in 0..n_targets {
                current_predictions[[i, j]] = init_predictions[j];
            }
        }

        let mut estimators = Vec::new();
        let mut feature_importances = Array1::<Float>::zeros(n_features);
        let mut train_scores = Vec::new();

        // Gradient boosting iterations
        for m in 0..self.n_estimators {
            // Compute negative gradients (residuals for squared loss)
            let residuals = y - &current_predictions;

            // Subsample if needed
            let (X_subsample, residuals_subsample, subsample_indices) = if self.subsample < 1.0 {
                self.create_subsample(&X, &residuals, m)?
            } else {
                (X.clone(), residuals, (0..n_samples).collect())
            };

            // Fit a regression tree to the residuals
            let tree = MultiTargetRegressionTree::new()
                .max_depth(self.max_depth)
                .min_samples_split(self.min_samples_split)
                .min_samples_leaf(self.min_samples_leaf)
                .random_state(self.random_state.map(|s| s.wrapping_add(m as u64)));

            let fitted_tree = tree.fit(&X_subsample.view(), &residuals_subsample)?;

            // Predict on the full training set
            let tree_predictions = fitted_tree.predict(&X.view())?;

            // Update predictions with learning rate
            current_predictions += &(tree_predictions * self.learning_rate);

            // Accumulate feature importances
            feature_importances += fitted_tree.feature_importances();

            // Store the tree
            estimators.push(fitted_tree);

            // Compute training score (mean squared error)
            let loss = self.compute_loss(y, &current_predictions);
            train_scores.push(loss);

            // Early stopping could be added here based on validation score
        }

        // Normalize feature importances
        let sum_importances: Float = feature_importances.sum();
        if sum_importances > 0.0 {
            feature_importances /= sum_importances;
        }

        Ok(GradientBoostingMultiOutput {
            state: GradientBoostingMultiOutputTrained {
                estimators,
                init_predictions,
                n_features,
                n_targets,
                feature_importances,
                train_scores,
            },
            n_estimators: self.n_estimators,
            learning_rate: self.learning_rate,
            max_depth: self.max_depth,
            min_samples_split: self.min_samples_split,
            min_samples_leaf: self.min_samples_leaf,
            subsample: self.subsample,
            random_state: self.random_state,
        })
    }
}

impl GradientBoostingMultiOutput<Untrained> {
    fn create_subsample(
        &self,
        X: &Array2<Float>,
        y: &Array2<Float>,
        seed: usize,
    ) -> SklResult<(Array2<Float>, Array2<Float>, Vec<usize>)> {
        let n_samples = X.nrows();
        let subsample_size = (n_samples as Float * self.subsample).ceil() as usize;
        let mut rng_state = self.random_state.unwrap_or(42).wrapping_add(seed as u64);

        let mut indices = Vec::new();
        for _ in 0..subsample_size {
            rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
            let idx = (rng_state / 65536) % (n_samples as u64);
            indices.push(idx as usize);
        }

        let mut X_subsample = Array2::<Float>::zeros((subsample_size, X.ncols()));
        let mut y_subsample = Array2::<Float>::zeros((subsample_size, y.ncols()));

        for (i, &idx) in indices.iter().enumerate() {
            X_subsample
                .slice_mut(s![i, ..])
                .assign(&X.slice(s![idx, ..]));
            y_subsample
                .slice_mut(s![i, ..])
                .assign(&y.slice(s![idx, ..]));
        }

        Ok((X_subsample, y_subsample, indices))
    }

    fn compute_loss(&self, y_true: &Array2<Float>, y_pred: &Array2<Float>) -> Float {
        let diff = y_true - y_pred;
        let squared_diff = &diff * &diff;
        squared_diff.sum() / (y_true.nrows() * y_true.ncols()) as Float
    }
}

impl GradientBoostingMultiOutput<GradientBoostingMultiOutputTrained> {
    /// Get the feature importances averaged across all trees
    pub fn feature_importances(&self) -> &Array1<Float> {
        &self.state.feature_importances
    }

    /// Get the number of estimators (trees)
    pub fn n_estimators(&self) -> usize {
        self.state.estimators.len()
    }

    /// Get the number of features
    pub fn n_features(&self) -> usize {
        self.state.n_features
    }

    /// Get the number of targets
    pub fn n_targets(&self) -> usize {
        self.state.n_targets
    }

    /// Get the training scores (loss at each iteration)
    pub fn train_scores(&self) -> &[Float] {
        &self.state.train_scores
    }

    /// Predict using the gradient boosting model
    pub fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let X = *X;
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        // Initialize with initial predictions
        let mut predictions = Array2::<Float>::zeros((n_samples, self.state.n_targets));
        for i in 0..n_samples {
            for j in 0..self.state.n_targets {
                predictions[[i, j]] = self.state.init_predictions[j];
            }
        }

        // Add contributions from all trees
        for estimator in &self.state.estimators {
            let tree_predictions = estimator.predict(&X)?;
            // Apply learning rate from the training configuration
            let learning_rate = 0.1; // We should store this in the trained state, but for now use default
            predictions += &(tree_predictions * learning_rate);
        }

        Ok(predictions)
    }

    /// Predict using only the first n_estimators trees
    pub fn staged_predict(
        &self,
        X: &ArrayView2<'_, Float>,
        n_estimators: usize,
    ) -> SklResult<Array2<Float>> {
        let X = *X;
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        let max_estimators = n_estimators.min(self.state.estimators.len());

        // Initialize with initial predictions
        let mut predictions = Array2::<Float>::zeros((n_samples, self.state.n_targets));
        for i in 0..n_samples {
            for j in 0..self.state.n_targets {
                predictions[[i, j]] = self.state.init_predictions[j];
            }
        }

        // Add contributions from first n_estimators trees
        for estimator in &self.state.estimators[..max_estimators] {
            let tree_predictions = estimator.predict(&X)?;
            let learning_rate = 0.1; // Should be stored in trained state
            predictions += &(tree_predictions * learning_rate);
        }

        Ok(predictions)
    }
}

/// Independent Label Prediction
///
/// A meta-estimator that treats each label as an independent binary classification problem.
/// This is essentially an enhanced version of binary relevance that provides more flexibility
/// and control over the individual binary classifiers.
///
/// # Mathematical Foundation
///
/// For multi-label classification with L labels:
/// - Train L independent binary classifiers: f_j(x) for j = 1..L
/// - Each classifier predicts P(y_j = 1 | x) independently
/// - Final prediction: ŷ = [I(f_1(x) > τ_1), ..., I(f_L(x) > τ_L)]
/// - Thresholds τ_j can be learned or set manually for each label
///
/// # Examples
///
/// ```
/// use sklears_multioutput::{IndependentLabelPrediction, ThresholdStrategy};
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];
///
/// let ilp = IndependentLabelPrediction::new()
///     .threshold_strategy(ThresholdStrategy::Optimal)
///     .optimize_thresholds(true);
/// let trained_ilp = ilp.fit(&X.view(), &y).unwrap();
/// let predictions = trained_ilp.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct IndependentLabelPrediction<S = Untrained> {
    state: S,
    threshold_strategy: ThresholdStrategy,
    optimize_thresholds: bool,
    class_weight: Option<String>, // "balanced" or None
    random_state: Option<u64>,
}

#[derive(Debug, Clone)]
pub enum ThresholdStrategy {
    Fixed(Float),         // Use fixed threshold for all labels
    PerLabel(Vec<Float>), // Use different threshold for each label
    Optimal,              // Learn optimal thresholds from validation data
    FScore,               // Optimize F-score threshold for each label
}

#[derive(Debug, Clone)]
pub struct IndependentLabelPredictionTrained {
    binary_classifiers: Vec<BinaryClassifierModel>,
    thresholds: Vec<Float>,
    n_features: usize,
    n_labels: usize,
    label_frequencies: Vec<Float>, // Frequency of positive labels
}

#[derive(Debug, Clone)]
struct BinaryClassifierModel {
    feature_means: Array1<Float>,
    feature_stds: Array1<Float>,
    model: SimpleBinaryModel,
}

impl IndependentLabelPrediction<Untrained> {
    /// Create a new IndependentLabelPrediction instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            threshold_strategy: ThresholdStrategy::Fixed(0.5),
            optimize_thresholds: false,
            class_weight: None,
            random_state: None,
        }
    }

    /// Set the threshold strategy for binary predictions
    pub fn threshold_strategy(mut self, strategy: ThresholdStrategy) -> Self {
        self.threshold_strategy = strategy;
        self
    }

    /// Set whether to optimize thresholds based on training data
    pub fn optimize_thresholds(mut self, optimize: bool) -> Self {
        self.optimize_thresholds = optimize;
        self
    }

    /// Set class weighting strategy
    pub fn class_weight(mut self, class_weight: Option<String>) -> Self {
        self.class_weight = class_weight;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for IndependentLabelPrediction<Untrained> {
    type Fitted = IndependentLabelPrediction<IndependentLabelPredictionTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let X = X.to_owned();
        let (n_samples, n_features) = X.dim();

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

        let n_labels = y.ncols();
        if n_labels == 0 {
            return Err(SklearsError::InvalidInput(
                "y must have at least one label".to_string(),
            ));
        }

        // Validate that labels are binary
        for &label in y.iter() {
            if label != 0 && label != 1 {
                return Err(SklearsError::InvalidInput(
                    "Labels must be binary (0 or 1)".to_string(),
                ));
            }
        }

        // Compute feature statistics for standardization
        let feature_means = X.mean_axis(Axis(0)).ok_or(SklearsError::InvalidInput(
            "Cannot compute feature means".to_string(),
        ))?;
        let feature_stds = X
            .std_axis(Axis(0), 0.0)
            .mapv(|x| if x == 0.0 { 1.0 } else { x });

        // Standardize features
        let X_standardized = standardize_features_simple(&X.view(), &feature_means, &feature_stds);

        let mut binary_classifiers = Vec::new();
        let mut label_frequencies = Vec::new();

        // Train one binary classifier for each label
        for j in 0..n_labels {
            let y_binary = y.column(j).to_owned();

            // Compute label frequency
            let positive_count = y_binary.iter().filter(|&&x| x == 1).count();
            let frequency = positive_count as Float / n_samples as Float;
            label_frequencies.push(frequency);

            // Apply class weighting if specified
            let class_weights = if self.class_weight.as_deref() == Some("balanced") {
                // Compute balanced class weights
                let mut weights = Array1::<Float>::ones(n_samples);
                let positive_count = y_binary.iter().filter(|&&x| x == 1).count();
                let negative_count = n_samples - positive_count;

                if positive_count > 0 && negative_count > 0 {
                    let pos_weight = n_samples as Float / (2.0 * positive_count as Float);
                    let neg_weight = n_samples as Float / (2.0 * negative_count as Float);

                    for (i, &label) in y_binary.iter().enumerate() {
                        weights[i] = if label == 1 { pos_weight } else { neg_weight };
                    }
                }
                weights
            } else {
                Array1::<Float>::ones(n_samples)
            };

            // Train binary classifier
            let simple_model = train_weighted_binary_classifier_simple(
                &X_standardized,
                &y_binary,
                &class_weights,
            )?;
            let classifier_model = BinaryClassifierModel {
                feature_means: feature_means.clone(),
                feature_stds: feature_stds.clone(),
                model: simple_model,
            };
            binary_classifiers.push(classifier_model);
        }

        // Determine thresholds
        let thresholds = match &self.threshold_strategy {
            ThresholdStrategy::Fixed(threshold) => vec![*threshold; n_labels],
            ThresholdStrategy::PerLabel(thresholds) => {
                if thresholds.len() != n_labels {
                    return Err(SklearsError::InvalidInput(
                        "Number of thresholds must match number of labels".to_string(),
                    ));
                }
                thresholds.clone()
            }
            ThresholdStrategy::Optimal | ThresholdStrategy::FScore => {
                if self.optimize_thresholds {
                    self.compute_optimal_thresholds(&X_standardized, y, &binary_classifiers)?
                } else {
                    vec![0.5; n_labels]
                }
            }
        };

        Ok(IndependentLabelPrediction {
            state: IndependentLabelPredictionTrained {
                binary_classifiers,
                thresholds,
                n_features,
                n_labels,
                label_frequencies,
            },
            threshold_strategy: self.threshold_strategy,
            optimize_thresholds: self.optimize_thresholds,
            class_weight: self.class_weight,
            random_state: self.random_state,
        })
    }
}

impl IndependentLabelPrediction<Untrained> {
    fn compute_optimal_thresholds(
        &self,
        X: &Array2<Float>,
        y: &Array2<i32>,
        classifiers: &[BinaryClassifierModel],
    ) -> SklResult<Vec<Float>> {
        let n_labels = y.ncols();
        let mut optimal_thresholds = Vec::new();

        for j in 0..n_labels {
            let y_binary = y.column(j);

            // Get prediction scores for this label
            let scores = predict_binary_probabilities(&classifiers[j].model, X);

            // Find optimal threshold based on strategy
            let optimal_threshold = match &self.threshold_strategy {
                ThresholdStrategy::FScore => self.find_best_f_score_threshold(&y_binary, &scores),
                _ => {
                    // For other strategies, use balanced accuracy
                    self.find_best_balanced_accuracy_threshold(&y_binary, &scores)
                }
            };

            optimal_thresholds.push(optimal_threshold);
        }

        Ok(optimal_thresholds)
    }

    fn find_best_f_score_threshold(
        &self,
        y_true: &ArrayView1<'_, i32>,
        scores: &Array1<Float>,
    ) -> Float {
        let mut best_threshold = 0.5;
        let mut best_f_score = 0.0;

        // Try different thresholds
        for &threshold in &[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] {
            let y_pred: Array1<i32> = scores.mapv(|x| if x >= threshold { 1 } else { 0 });

            let f_score = self.compute_f_score(&y_true, &y_pred);
            if f_score > best_f_score {
                best_f_score = f_score;
                best_threshold = threshold;
            }
        }

        best_threshold
    }

    fn find_best_balanced_accuracy_threshold(
        &self,
        y_true: &ArrayView1<'_, i32>,
        scores: &Array1<Float>,
    ) -> Float {
        let mut best_threshold = 0.5;
        let mut best_accuracy = 0.0;

        // Try different thresholds
        for &threshold in &[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] {
            let y_pred: Array1<i32> = scores.mapv(|x| if x >= threshold { 1 } else { 0 });

            let accuracy = self.compute_balanced_accuracy(&y_true, &y_pred);
            if accuracy > best_accuracy {
                best_accuracy = accuracy;
                best_threshold = threshold;
            }
        }

        best_threshold
    }

    fn compute_f_score(&self, y_true: &ArrayView1<'_, i32>, y_pred: &Array1<i32>) -> Float {
        let mut tp = 0;
        let mut fp = 0;
        let mut fn_count = 0;

        for (true_val, pred_val) in y_true.iter().zip(y_pred.iter()) {
            match (true_val, pred_val) {
                (1, 1) => tp += 1,
                (0, 1) => fp += 1,
                (1, 0) => fn_count += 1,
                _ => {} // TN
            }
        }

        if tp + fp == 0 || tp + fn_count == 0 {
            return 0.0;
        }

        let precision = tp as Float / (tp + fp) as Float;
        let recall = tp as Float / (tp + fn_count) as Float;

        if precision + recall == 0.0 {
            0.0
        } else {
            2.0 * precision * recall / (precision + recall)
        }
    }

    fn compute_balanced_accuracy(
        &self,
        y_true: &ArrayView1<'_, i32>,
        y_pred: &Array1<i32>,
    ) -> Float {
        let mut tp = 0;
        let mut tn = 0;
        let mut fp = 0;
        let mut fn_count = 0;

        for (true_val, pred_val) in y_true.iter().zip(y_pred.iter()) {
            match (true_val, pred_val) {
                (1, 1) => tp += 1,
                (0, 0) => tn += 1,
                (0, 1) => fp += 1,
                (1, 0) => fn_count += 1,
                _ => {}
            }
        }

        let sensitivity = if tp + fn_count > 0 {
            tp as Float / (tp + fn_count) as Float
        } else {
            0.0
        };

        let specificity = if tn + fp > 0 {
            tn as Float / (tn + fp) as Float
        } else {
            0.0
        };

        (sensitivity + specificity) / 2.0
    }
}

impl IndependentLabelPrediction<IndependentLabelPredictionTrained> {
    /// Get the optimized thresholds for each label
    pub fn thresholds(&self) -> &[Float] {
        &self.state.thresholds
    }

    /// Get the label frequencies from training data
    pub fn label_frequencies(&self) -> &[Float] {
        &self.state.label_frequencies
    }

    /// Get the number of features
    pub fn n_features(&self) -> usize {
        self.state.n_features
    }

    /// Get the number of labels
    pub fn n_labels(&self) -> usize {
        self.state.n_labels
    }

    /// Predict binary labels using the trained classifiers and thresholds
    pub fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let X = *X;
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        let probabilities = self.predict_proba(&X)?;
        let mut predictions = Array2::<i32>::zeros((n_samples, self.state.n_labels));

        for i in 0..n_samples {
            for j in 0..self.state.n_labels {
                predictions[[i, j]] = if probabilities[[i, j]] >= self.state.thresholds[j] {
                    1
                } else {
                    0
                };
            }
        }

        Ok(predictions)
    }

    /// Predict class probabilities for each label
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let X = *X;
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        let mut probabilities = Array2::<Float>::zeros((n_samples, self.state.n_labels));

        for j in 0..self.state.n_labels {
            let classifier = &self.state.binary_classifiers[j];

            // Standardize features using the same statistics as training
            let X_standardized = standardize_features_simple(
                &X,
                &classifier.feature_means,
                &classifier.feature_stds,
            );

            // Predict probabilities for this label
            let proba = predict_binary_probabilities(&classifier.model, &X_standardized);

            for i in 0..n_samples {
                probabilities[[i, j]] = proba[i];
            }
        }

        Ok(probabilities)
    }

    /// Predict using custom thresholds
    pub fn predict_with_thresholds(
        &self,
        X: &ArrayView2<'_, Float>,
        thresholds: &[Float],
    ) -> SklResult<Array2<i32>> {
        if thresholds.len() != self.state.n_labels {
            return Err(SklearsError::InvalidInput(
                "Number of thresholds must match number of labels".to_string(),
            ));
        }

        let X = *X;
        let (n_samples, _) = X.dim();
        let probabilities = self.predict_proba(&X)?;
        let mut predictions = Array2::<i32>::zeros((n_samples, self.state.n_labels));

        for i in 0..n_samples {
            for j in 0..self.state.n_labels {
                predictions[[i, j]] = if probabilities[[i, j]] >= thresholds[j] {
                    1
                } else {
                    0
                };
            }
        }

        Ok(predictions)
    }
}

/// Instance-Based Learning for Regression (IBLR)
///
/// IBLR is a k-nearest neighbors approach for multi-output regression that predicts
/// multiple continuous target values simultaneously. It uses distance-based similarity
/// to find the k-nearest neighbors and averages their target values for prediction.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::IBLR;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]]; // Multiple continuous targets
///
/// let iblr = IBLR::new().k_neighbors(2);
/// let trained_iblr = iblr.fit(&X.view(), &y).unwrap();
/// let predictions = trained_iblr.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct IBLR<S = Untrained> {
    state: S,
    k_neighbors: usize,
    weights: WeightFunction,
}

/// Weight function for IBLR
#[derive(Debug, Clone)]
pub enum WeightFunction {
    /// Uniform weighting (all neighbors weighted equally)
    Uniform,
    /// Distance-based weighting (closer neighbors weighted more)
    Distance,
}

/// Trained state for IBLR
#[derive(Debug, Clone)]
pub struct IBLRTrained {
    X_train: Array2<Float>,
    y_train: Array2<Float>,
    k_neighbors: usize,
    weights: WeightFunction,
    n_outputs: usize,
}

impl IBLR<Untrained> {
    /// Create a new IBLR instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            k_neighbors: 5,
            weights: WeightFunction::Uniform,
        }
    }

    /// Set the number of neighbors to consider
    pub fn k_neighbors(mut self, k: usize) -> Self {
        self.k_neighbors = k;
        self
    }

    /// Set the weight function
    pub fn weights(mut self, weights: WeightFunction) -> Self {
        self.weights = weights;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<Float>> for IBLR<Untrained> {
    type Fitted = IBLR<IBLRTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<Float>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let (n_samples_y, n_outputs) = y.dim();

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

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with 0 samples".to_string(),
            ));
        }

        if self.k_neighbors == 0 {
            return Err(SklearsError::InvalidInput(
                "k_neighbors must be greater than 0".to_string(),
            ));
        }

        if self.k_neighbors > n_samples {
            return Err(SklearsError::InvalidInput(
                "k_neighbors cannot be greater than the number of training samples".to_string(),
            ));
        }

        let X_train = X.to_owned();
        let y_train = y.clone();

        Ok(IBLR {
            state: IBLRTrained {
                X_train,
                y_train,
                k_neighbors: self.k_neighbors,
                weights: self.weights.clone(),
                n_outputs,
            },
            k_neighbors: self.k_neighbors,
            weights: self.weights,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<Float>> for IBLR<IBLRTrained> {
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.X_train.ncols() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_samples, self.state.n_outputs));

        for i in 0..n_samples {
            let query_point = X.row(i);

            // Calculate distances to all training points
            let mut distances_with_indices: Vec<(Float, usize)> = Vec::new();

            for j in 0..self.state.X_train.nrows() {
                let train_point = self.state.X_train.row(j);
                let distance = euclidean_distance(&query_point, &train_point);
                distances_with_indices.push((distance, j));
            }

            // Sort by distance and take k nearest
            distances_with_indices.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
            let k_nearest = &distances_with_indices[..self.state.k_neighbors];

            // Calculate weighted average of k-nearest neighbor targets
            match self.state.weights {
                WeightFunction::Uniform => {
                    // Simple average
                    for output_idx in 0..self.state.n_outputs {
                        let sum: Float = k_nearest
                            .iter()
                            .map(|(_, idx)| self.state.y_train[[*idx, output_idx]])
                            .sum();
                        predictions[[i, output_idx]] = sum / (self.state.k_neighbors as Float);
                    }
                }
                WeightFunction::Distance => {
                    // Distance-weighted average
                    let total_weight: Float = k_nearest
                        .iter()
                        .map(|(dist, _)| if *dist == 0.0 { 1e10 } else { 1.0 / dist })
                        .sum();

                    if total_weight == 0.0 {
                        return Err(SklearsError::InvalidInput(
                            "All distances are zero or invalid".to_string(),
                        ));
                    }

                    for output_idx in 0..self.state.n_outputs {
                        let weighted_sum: Float = k_nearest
                            .iter()
                            .map(|(dist, idx)| {
                                let weight = if *dist == 0.0 { 1e10 } else { 1.0 / dist };
                                weight * self.state.y_train[[*idx, output_idx]]
                            })
                            .sum();
                        predictions[[i, output_idx]] = weighted_sum / total_weight;
                    }
                }
            }
        }

        Ok(predictions)
    }
}

/// Helper function to calculate Euclidean distance between two points
fn euclidean_distance(point1: &ArrayView1<Float>, point2: &ArrayView1<Float>) -> Float {
    point1
        .iter()
        .zip(point2.iter())
        .map(|(a, b)| (a - b).powi(2))
        .sum::<Float>()
        .sqrt()
}

/// CLARE (Clustering and LAabel RElevance)
///
/// CLARE is a multi-label classification method that combines clustering with label relevance.
/// It works by clustering the feature space and learning label frequencies for each cluster,
/// then making predictions based on which cluster a new instance belongs to.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::CLARE;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary
///
/// let clare = CLARE::new().n_clusters(2);
/// let trained_clare = clare.fit(&X.view(), &y).unwrap();
/// let predictions = trained_clare.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct CLARE<S = Untrained> {
    state: S,
    n_clusters: usize,
    threshold: Float,
    max_iter: usize,
    random_state: Option<u64>,
}

/// Trained state for CLARE
#[derive(Debug, Clone)]
pub struct CLARETrained {
    cluster_centers: Array2<Float>,
    label_relevance: Array2<Float>, // n_clusters x n_labels
    threshold: Float,
    n_labels: usize,
}

impl CLARE<Untrained> {
    /// Create a new CLARE instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            n_clusters: 3,
            threshold: 0.5,
            max_iter: 100,
            random_state: None,
        }
    }

    /// Set the number of clusters
    pub fn n_clusters(mut self, n_clusters: usize) -> Self {
        self.n_clusters = n_clusters;
        self
    }

    /// Set the prediction threshold
    pub fn threshold(mut self, threshold: Float) -> Self {
        self.threshold = threshold;
        self
    }

    /// Set the maximum number of iterations for clustering
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for CLARE<Untrained> {
    type Fitted = CLARE<CLARETrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let n_labels = y.ncols();

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

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with 0 samples".to_string(),
            ));
        }

        if self.n_clusters == 0 {
            return Err(SklearsError::InvalidInput(
                "n_clusters must be greater than 0".to_string(),
            ));
        }

        if self.n_clusters > n_samples {
            return Err(SklearsError::InvalidInput(
                "n_clusters cannot be greater than the number of samples".to_string(),
            ));
        }

        // Validate binary labels
        for &val in y.iter() {
            if val != 0 && val != 1 {
                return Err(SklearsError::InvalidInput(
                    "y must contain only binary values (0 or 1)".to_string(),
                ));
            }
        }

        // Perform k-means clustering
        let (cluster_centers, cluster_assignments) =
            k_means_clustering(X, self.n_clusters, self.max_iter, self.random_state)?;

        // Calculate label relevance for each cluster
        let mut label_relevance = Array2::zeros((self.n_clusters, n_labels));
        let mut cluster_counts = vec![0; self.n_clusters];

        // Count samples in each cluster and accumulate label frequencies
        for (sample_idx, &cluster_id) in cluster_assignments.iter().enumerate() {
            cluster_counts[cluster_id] += 1;
            for label_idx in 0..n_labels {
                if y[[sample_idx, label_idx]] == 1 {
                    label_relevance[[cluster_id, label_idx]] += 1.0;
                }
            }
        }

        // Normalize label frequencies to get relevance scores
        for cluster_id in 0..self.n_clusters {
            if cluster_counts[cluster_id] > 0 {
                let count = cluster_counts[cluster_id] as Float;
                for label_idx in 0..n_labels {
                    label_relevance[[cluster_id, label_idx]] /= count;
                }
            }
        }

        Ok(CLARE {
            state: CLARETrained {
                cluster_centers,
                label_relevance,
                threshold: self.threshold,
                n_labels,
            },
            n_clusters: self.n_clusters,
            threshold: self.threshold,
            max_iter: self.max_iter,
            random_state: self.random_state,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>> for CLARE<CLARETrained> {
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.cluster_centers.ncols() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_samples, self.state.n_labels));

        for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
            // Find closest cluster
            let mut min_distance = Float::INFINITY;
            let mut closest_cluster = 0;

            for (cluster_idx, cluster_center) in
                self.state.cluster_centers.axis_iter(Axis(0)).enumerate()
            {
                let distance = euclidean_distance(&sample, &cluster_center);
                if distance < min_distance {
                    min_distance = distance;
                    closest_cluster = cluster_idx;
                }
            }

            // Predict labels based on cluster's label relevance
            for label_idx in 0..self.state.n_labels {
                let relevance = self.state.label_relevance[[closest_cluster, label_idx]];
                predictions[[sample_idx, label_idx]] = if relevance >= self.state.threshold {
                    1
                } else {
                    0
                };
            }
        }

        Ok(predictions)
    }
}

impl CLARE<CLARETrained> {
    /// Get the cluster centers
    pub fn cluster_centers(&self) -> &Array2<Float> {
        &self.state.cluster_centers
    }

    /// Get the label relevance matrix
    pub fn label_relevance(&self) -> &Array2<Float> {
        &self.state.label_relevance
    }

    /// Get the prediction threshold
    pub fn threshold(&self) -> Float {
        self.state.threshold
    }

    /// Predict probabilities (label relevance scores)
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.cluster_centers.ncols() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        let mut probabilities = Array2::zeros((n_samples, self.state.n_labels));

        for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
            // Find closest cluster
            let mut min_distance = Float::INFINITY;
            let mut closest_cluster = 0;

            for (cluster_idx, cluster_center) in
                self.state.cluster_centers.axis_iter(Axis(0)).enumerate()
            {
                let distance = euclidean_distance(&sample, &cluster_center);
                if distance < min_distance {
                    min_distance = distance;
                    closest_cluster = cluster_idx;
                }
            }

            // Return label relevance scores as probabilities
            for label_idx in 0..self.state.n_labels {
                probabilities[[sample_idx, label_idx]] =
                    self.state.label_relevance[[closest_cluster, label_idx]];
            }
        }

        Ok(probabilities)
    }
}

/// Simple k-means clustering implementation
fn k_means_clustering(
    X: &ArrayView2<'_, Float>,
    n_clusters: usize,
    max_iter: usize,
    random_state: Option<u64>,
) -> SklResult<(Array2<Float>, Vec<usize>)> {
    let (n_samples, n_features) = X.dim();

    // Initialize cluster centers randomly
    let mut cluster_centers = Array2::zeros((n_clusters, n_features));

    // Simple random initialization using deterministic approach if random_state is provided
    if let Some(seed) = random_state {
        let mut rng_state = seed;
        for i in 0..n_clusters {
            let sample_idx = (rng_state as usize + i) % n_samples;
            for j in 0..n_features {
                cluster_centers[[i, j]] = X[[sample_idx, j]];
            }
            rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
        }
    } else {
        // Use first n_clusters samples as initial centers
        for i in 0..n_clusters {
            let sample_idx = i % n_samples;
            for j in 0..n_features {
                cluster_centers[[i, j]] = X[[sample_idx, j]];
            }
        }
    }

    let mut cluster_assignments = vec![0; n_samples];

    for _iter in 0..max_iter {
        let mut changed = false;

        // Assign each sample to the closest cluster
        for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
            let mut min_distance = Float::INFINITY;
            let mut closest_cluster = 0;

            for (cluster_idx, cluster_center) in cluster_centers.axis_iter(Axis(0)).enumerate() {
                let distance = euclidean_distance(&sample, &cluster_center);
                if distance < min_distance {
                    min_distance = distance;
                    closest_cluster = cluster_idx;
                }
            }

            if cluster_assignments[sample_idx] != closest_cluster {
                cluster_assignments[sample_idx] = closest_cluster;
                changed = true;
            }
        }

        // Update cluster centers
        let mut new_centers = Array2::zeros((n_clusters, n_features));
        let mut cluster_counts = vec![0; n_clusters];

        for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
            let cluster_id = cluster_assignments[sample_idx];
            cluster_counts[cluster_id] += 1;
            for (feature_idx, &value) in sample.iter().enumerate() {
                new_centers[[cluster_id, feature_idx]] += value;
            }
        }

        // Average to get new centers
        for cluster_id in 0..n_clusters {
            if cluster_counts[cluster_id] > 0 {
                let count = cluster_counts[cluster_id] as Float;
                for feature_idx in 0..n_features {
                    new_centers[[cluster_id, feature_idx]] /= count;
                }
            }
        }

        cluster_centers = new_centers;

        if !changed {
            break;
        }
    }

    Ok((cluster_centers, cluster_assignments))
}

/// MLTSVM (Multi-Label Twin SVM)
///
/// MLTSVM is a multi-label classification method that extends Twin SVM to handle
/// multiple labels. Twin SVM finds two non-parallel hyperplanes for binary classification,
/// which often leads to faster training than standard SVM. MLTSVM applies this approach
/// to each label independently in a binary relevance fashion.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::MLTSVM;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary
///
/// let mltsvm = MLTSVM::new().c1(1.0).c2(1.0);
/// let trained_mltsvm = mltsvm.fit(&X.view(), &y).unwrap();
/// let predictions = trained_mltsvm.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct MLTSVM<S = Untrained> {
    state: S,
    c1: Float,       // Regularization parameter for first hyperplane
    c2: Float,       // Regularization parameter for second hyperplane
    epsilon: Float,  // Tolerance for convergence
    max_iter: usize, // Maximum iterations
}

/// Trained state for MLTSVM
#[derive(Debug, Clone)]
pub struct MLTSVMTrained {
    models: Vec<TwinSVMModel>, // One model per label
    n_labels: usize,
    feature_means: Array1<Float>,
    feature_stds: Array1<Float>,
}

/// Single Twin SVM model for binary classification
#[derive(Debug, Clone)]
struct TwinSVMModel {
    w1: Array1<Float>, // Weights for first hyperplane
    b1: Float,         // Bias for first hyperplane
    w2: Array1<Float>, // Weights for second hyperplane
    b2: Float,         // Bias for second hyperplane
}

impl MLTSVM<Untrained> {
    /// Create a new MLTSVM instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            c1: 1.0,
            c2: 1.0,
            epsilon: 1e-6,
            max_iter: 1000,
        }
    }

    /// Set the regularization parameter for the first hyperplane
    pub fn c1(mut self, c1: Float) -> Self {
        self.c1 = c1;
        self
    }

    /// Set the regularization parameter for the second hyperplane
    pub fn c2(mut self, c2: Float) -> Self {
        self.c2 = c2;
        self
    }

    /// Set the convergence tolerance
    pub fn epsilon(mut self, epsilon: Float) -> Self {
        self.epsilon = epsilon;
        self
    }

    /// Set the maximum number of iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for MLTSVM<Untrained> {
    type Fitted = MLTSVM<MLTSVMTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let n_labels = y.ncols();

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

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with 0 samples".to_string(),
            ));
        }

        // Validate binary labels
        for &val in y.iter() {
            if val != 0 && val != 1 {
                return Err(SklearsError::InvalidInput(
                    "y must contain only binary values (0 or 1)".to_string(),
                ));
            }
        }

        // Standardize features
        let feature_means = X.mean_axis(Axis(0)).unwrap();
        let feature_stds = X
            .std_axis(Axis(0), 0.0)
            .mapv(|x| if x == 0.0 { 1.0 } else { x });

        let mut X_scaled = X.to_owned();
        for i in 0..n_samples {
            for j in 0..n_features {
                X_scaled[[i, j]] = (X_scaled[[i, j]] - feature_means[j]) / feature_stds[j];
            }
        }

        // Train Twin SVM for each label
        let mut models = Vec::with_capacity(n_labels);

        for label_idx in 0..n_labels {
            let y_label = y.column(label_idx);
            let model = train_twin_svm(
                &X_scaled.view(),
                &y_label,
                self.c1,
                self.c2,
                self.epsilon,
                self.max_iter,
            )?;
            models.push(model);
        }

        Ok(MLTSVM {
            state: MLTSVMTrained {
                models,
                n_labels,
                feature_means,
                feature_stds,
            },
            c1: self.c1,
            c2: self.c2,
            epsilon: self.epsilon,
            max_iter: self.max_iter,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>> for MLTSVM<MLTSVMTrained> {
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.feature_means.len() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        // Standardize features using training statistics
        let mut X_scaled = X.to_owned();
        for i in 0..n_samples {
            for j in 0..n_features {
                X_scaled[[i, j]] =
                    (X_scaled[[i, j]] - self.state.feature_means[j]) / self.state.feature_stds[j];
            }
        }

        let mut predictions = Array2::zeros((n_samples, self.state.n_labels));

        // Predict for each label using its Twin SVM model
        for (label_idx, model) in self.state.models.iter().enumerate() {
            for sample_idx in 0..n_samples {
                let x = X_scaled.row(sample_idx);

                // Calculate distances to both hyperplanes
                let dist1 = x.dot(&model.w1) + model.b1;
                let dist2 = x.dot(&model.w2) + model.b2;

                // Assign to class based on which hyperplane is closer
                // Positive if closer to positive class hyperplane, negative otherwise
                predictions[[sample_idx, label_idx]] = if dist1.abs() < dist2.abs() {
                    1 // Closer to positive class hyperplane
                } else {
                    0 // Closer to negative class hyperplane
                };
            }
        }

        Ok(predictions)
    }
}

impl MLTSVM<MLTSVMTrained> {
    /// Get the number of labels
    pub fn n_labels(&self) -> usize {
        self.state.n_labels
    }

    /// Predict decision function values (distances to hyperplanes)
    pub fn decision_function(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.feature_means.len() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        // Standardize features
        let mut X_scaled = X.to_owned();
        for i in 0..n_samples {
            for j in 0..n_features {
                X_scaled[[i, j]] =
                    (X_scaled[[i, j]] - self.state.feature_means[j]) / self.state.feature_stds[j];
            }
        }

        let mut decision_values = Array2::zeros((n_samples, self.state.n_labels));

        for (label_idx, model) in self.state.models.iter().enumerate() {
            for sample_idx in 0..n_samples {
                let x = X_scaled.row(sample_idx);

                // Calculate signed distance difference between hyperplanes
                let dist1 = x.dot(&model.w1) + model.b1;
                let dist2 = x.dot(&model.w2) + model.b2;

                // Decision function: positive for positive class, negative for negative class
                decision_values[[sample_idx, label_idx]] = dist1 - dist2;
            }
        }

        Ok(decision_values)
    }
}

/// Train a Twin SVM model for binary classification
fn train_twin_svm(
    X: &ArrayView2<'_, Float>,
    y: &ArrayView1<'_, i32>,
    c1: Float,
    c2: Float,
    epsilon: Float,
    max_iter: usize,
) -> SklResult<TwinSVMModel> {
    let (n_samples, n_features) = X.dim();

    // Separate positive and negative samples
    let mut X_pos = Vec::new();
    let mut X_neg = Vec::new();

    for i in 0..n_samples {
        if y[i] == 1 {
            X_pos.push(X.row(i).to_owned());
        } else {
            X_neg.push(X.row(i).to_owned());
        }
    }

    if X_pos.is_empty() || X_neg.is_empty() {
        return Err(SklearsError::InvalidInput(
            "Need samples from both classes for Twin SVM".to_string(),
        ));
    }

    // Convert to matrices
    let n_pos = X_pos.len();
    let n_neg = X_neg.len();

    let mut A = Array2::zeros((n_pos, n_features + 1));
    let mut B = Array2::zeros((n_neg, n_features + 1));

    // Fill A (positive samples) with [X, 1]
    for (i, x_pos) in X_pos.iter().enumerate() {
        for j in 0..n_features {
            A[[i, j]] = x_pos[j];
        }
        A[[i, n_features]] = 1.0; // bias term
    }

    // Fill B (negative samples) with [X, 1]
    for (i, x_neg) in X_neg.iter().enumerate() {
        for j in 0..n_features {
            B[[i, j]] = x_neg[j];
        }
        B[[i, n_features]] = 1.0; // bias term
    }

    // Solve Twin SVM optimization problems
    // First hyperplane: min ||Aw1||^2 + c1*|Bw1|_1 subject to Bw1 >= e
    let w1 = solve_twin_svm_problem(&A, &B, c1, true)?;

    // Second hyperplane: min ||Bw2||^2 + c2*|Aw2|_1 subject to Aw2 <= -e
    let w2 = solve_twin_svm_problem(&B, &A, c2, false)?;

    // Extract weights and biases
    let weights1 = w1.slice(s![..n_features]).to_owned();
    let bias1 = w1[n_features];

    let weights2 = w2.slice(s![..n_features]).to_owned();
    let bias2 = w2[n_features];

    Ok(TwinSVMModel {
        w1: weights1,
        b1: bias1,
        w2: weights2,
        b2: bias2,
    })
}

/// Solve a single Twin SVM optimization problem
fn solve_twin_svm_problem(
    A: &Array2<Float>,
    B: &Array2<Float>,
    c: Float,
    is_first: bool,
) -> SklResult<Array1<Float>> {
    let (n_a, n_features) = A.dim();
    let n_b = B.nrows();

    // Simplified approach: use regularized least squares approximation
    // This is not the full Twin SVM solution but provides a reasonable approximation

    // Create target vector
    let target = if is_first {
        Array1::ones(n_b) // B should be >= 1
    } else {
        Array1::ones(n_a) * (-1.0) // A should be <= -1
    };

    // Use regularized least squares: min ||Xw - target||^2 + lambda*||w||^2
    let X = if is_first { B } else { A };
    let lambda = 1.0 / c; // Convert regularization parameter

    // Add regularization to diagonal
    let mut XtX = X.t().dot(X);
    for i in 0..n_features {
        XtX[[i, i]] += lambda;
    }

    // Solve using pseudo-inverse approach
    let Xty = X.t().dot(&target);

    // Simple iterative solution (gradient descent approximation)
    let mut w = Array1::zeros(n_features);
    let learning_rate = 0.01;

    for _iter in 0..1000 {
        let prediction = X.dot(&w);
        let residual = &prediction - &target;
        let gradient = X.t().dot(&residual) + lambda * &w;

        w = &w - learning_rate * &gradient;

        // Check convergence
        if gradient.mapv(|x| x.abs()).sum() < 1e-6 {
            break;
        }
    }

    Ok(w)
}

/// RankSVM for Multi-Label Classification
///
/// RankSVM is a ranking-based approach for multi-label classification that optimizes
/// ranking loss functions. It learns to rank labels by their relevance scores and
/// can handle both label ranking and threshold selection for multi-label prediction.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::RankSVM;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary
///
/// let ranksvm = RankSVM::new().c(1.0);
/// let trained_ranksvm = ranksvm.fit(&X.view(), &y).unwrap();
/// let predictions = trained_ranksvm.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct RankSVM<S = Untrained> {
    state: S,
    c: Float,                              // Regularization parameter
    epsilon: Float,                        // Tolerance for convergence
    max_iter: usize,                       // Maximum iterations
    threshold_strategy: ThresholdStrategy, // How to determine prediction thresholds
}

/// Trained state for RankSVM
#[derive(Debug, Clone)]
pub struct RankSVMTrained {
    models: Vec<RankingSVMModel>, // One model per label
    thresholds: Array1<Float>,    // Prediction thresholds
    n_labels: usize,
    feature_means: Array1<Float>,
    feature_stds: Array1<Float>,
    threshold_strategy: ThresholdStrategy,
}

/// Single ranking SVM model for one label
#[derive(Debug, Clone)]
struct RankingSVMModel {
    weights: Array1<Float>,
    bias: Float,
}

impl RankSVM<Untrained> {
    /// Create a new RankSVM instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            c: 1.0,
            epsilon: 1e-6,
            max_iter: 1000,
            threshold_strategy: ThresholdStrategy::Optimal,
        }
    }

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

    /// Set the convergence tolerance
    pub fn epsilon(mut self, epsilon: Float) -> Self {
        self.epsilon = epsilon;
        self
    }

    /// Set the maximum number of iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set the threshold strategy
    pub fn threshold_strategy(mut self, strategy: ThresholdStrategy) -> Self {
        self.threshold_strategy = strategy;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for RankSVM<Untrained> {
    type Fitted = RankSVM<RankSVMTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let n_labels = y.ncols();

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

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with 0 samples".to_string(),
            ));
        }

        // Validate binary labels
        for &val in y.iter() {
            if val != 0 && val != 1 {
                return Err(SklearsError::InvalidInput(
                    "y must contain only binary values (0 or 1)".to_string(),
                ));
            }
        }

        // Standardize features
        let feature_means = X.mean_axis(Axis(0)).unwrap();
        let feature_stds = X
            .std_axis(Axis(0), 0.0)
            .mapv(|x| if x == 0.0 { 1.0 } else { x });

        let mut X_scaled = X.to_owned();
        for i in 0..n_samples {
            for j in 0..n_features {
                X_scaled[[i, j]] = (X_scaled[[i, j]] - feature_means[j]) / feature_stds[j];
            }
        }

        // Train ranking SVM for each label
        let mut models = Vec::with_capacity(n_labels);

        for label_idx in 0..n_labels {
            let y_label = y.column(label_idx);
            let model = train_ranking_svm(
                &X_scaled.view(),
                &y_label,
                self.c,
                self.epsilon,
                self.max_iter,
            )?;
            models.push(model);
        }

        // Determine thresholds based on strategy
        let thresholds =
            determine_thresholds(&models, &X_scaled.view(), y, &self.threshold_strategy)?;

        Ok(RankSVM {
            state: RankSVMTrained {
                models,
                thresholds,
                n_labels,
                feature_means,
                feature_stds,
                threshold_strategy: self.threshold_strategy.clone(),
            },
            c: self.c,
            epsilon: self.epsilon,
            max_iter: self.max_iter,
            threshold_strategy: self.threshold_strategy,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>> for RankSVM<RankSVMTrained> {
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.feature_means.len() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        // Get ranking scores first
        let scores = self.decision_function(X)?;
        let mut predictions = Array2::zeros((n_samples, self.state.n_labels));

        // Apply thresholds based on strategy
        match &self.state.threshold_strategy {
            ThresholdStrategy::Fixed(threshold) => {
                for i in 0..n_samples {
                    for j in 0..self.state.n_labels {
                        predictions[[i, j]] = if scores[[i, j]] >= *threshold { 1 } else { 0 };
                    }
                }
            }
            ThresholdStrategy::PerLabel(thresholds) => {
                for i in 0..n_samples {
                    for j in 0..self.state.n_labels {
                        let threshold = if j < thresholds.len() {
                            thresholds[j]
                        } else {
                            0.5
                        };
                        predictions[[i, j]] = if scores[[i, j]] >= threshold { 1 } else { 0 };
                    }
                }
            }
            ThresholdStrategy::Optimal | ThresholdStrategy::FScore => {
                // Use optimized thresholds stored during training
                for i in 0..n_samples {
                    for j in 0..self.state.n_labels {
                        let threshold = if j < self.state.thresholds.len() {
                            self.state.thresholds[j]
                        } else {
                            0.5
                        };
                        predictions[[i, j]] = if scores[[i, j]] >= threshold { 1 } else { 0 };
                    }
                }
            }
        }

        Ok(predictions)
    }
}

impl RankSVM<RankSVMTrained> {
    /// Get the number of labels
    pub fn n_labels(&self) -> usize {
        self.state.n_labels
    }

    /// Get the prediction thresholds
    pub fn thresholds(&self) -> &Array1<Float> {
        &self.state.thresholds
    }

    /// Predict ranking scores (decision function values)
    pub fn decision_function(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.feature_means.len() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot predict with 0 samples".to_string(),
            ));
        }

        // Standardize features
        let mut X_scaled = X.to_owned();
        for i in 0..n_samples {
            for j in 0..n_features {
                X_scaled[[i, j]] =
                    (X_scaled[[i, j]] - self.state.feature_means[j]) / self.state.feature_stds[j];
            }
        }

        let mut scores = Array2::zeros((n_samples, self.state.n_labels));

        // Compute ranking scores for each label
        for (label_idx, model) in self.state.models.iter().enumerate() {
            for sample_idx in 0..n_samples {
                let x = X_scaled.row(sample_idx);
                scores[[sample_idx, label_idx]] = x.dot(&model.weights) + model.bias;
            }
        }

        Ok(scores)
    }

    /// Predict label rankings (sorted by relevance score)
    pub fn predict_ranking(&self, X: &ArrayView2<'_, Float>) -> SklResult<Vec<Vec<usize>>> {
        let scores = self.decision_function(X)?;
        let n_samples = scores.nrows();
        let mut rankings = Vec::with_capacity(n_samples);

        for i in 0..n_samples {
            let mut label_scores: Vec<(usize, Float)> = (0..self.state.n_labels)
                .map(|j| (j, scores[[i, j]]))
                .collect();

            // Sort by score (descending)
            label_scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());

            let ranking: Vec<usize> = label_scores.into_iter().map(|(idx, _)| idx).collect();
            rankings.push(ranking);
        }

        Ok(rankings)
    }
}

/// Train a ranking SVM model for binary classification
fn train_ranking_svm(
    X: &ArrayView2<'_, Float>,
    y: &ArrayView1<'_, i32>,
    c: Float,
    epsilon: Float,
    max_iter: usize,
) -> SklResult<RankingSVMModel> {
    let (n_samples, n_features) = X.dim();

    // Check if we have both positive and negative samples
    let has_positive = y.iter().any(|&label| label == 1);
    let has_negative = y.iter().any(|&label| label == 0);

    if !has_positive || !has_negative {
        // If only one class, create a simple model
        let weights = Array1::zeros(n_features);
        let bias = if has_positive { 1.0 } else { -1.0 };
        return Ok(RankingSVMModel { weights, bias });
    }

    // Use regularized logistic regression as a ranking approximation
    // This provides a ranking-based score while being computationally tractable
    let mut weights = Array1::zeros(n_features);
    let mut bias = 0.0;
    let learning_rate = 0.01;
    let lambda = 1.0 / c; // Regularization parameter

    for _iter in 0..max_iter {
        let mut gradient_w = Array1::zeros(n_features);
        let mut gradient_b = 0.0;

        // Calculate gradients using logistic loss
        for i in 0..n_samples {
            let x_i = X.row(i);
            let y_i = if y[i] == 1 { 1.0 } else { -1.0 };

            let score = x_i.dot(&weights) + bias;
            let prob = 1.0 / (1.0 + (-y_i * score).exp());
            let factor = y_i * (1.0 - prob);

            gradient_w = gradient_w + factor * &x_i.to_owned();
            gradient_b += factor;
        }

        // Add regularization to weights gradient
        gradient_w = gradient_w - lambda * &weights;

        // Update parameters
        weights = &weights + learning_rate * &gradient_w;
        bias += learning_rate * gradient_b;

        // Check convergence
        let gradient_norm = gradient_w.mapv(|x| x.abs()).sum() + gradient_b.abs();
        if gradient_norm < epsilon {
            break;
        }
    }

    Ok(RankingSVMModel { weights, bias })
}

/// Determine prediction thresholds based on strategy
fn determine_thresholds(
    models: &[RankingSVMModel],
    X: &ArrayView2<'_, Float>,
    y: &Array2<i32>,
    strategy: &ThresholdStrategy,
) -> SklResult<Array1<Float>> {
    let n_labels = models.len();
    let n_samples = X.nrows();

    match strategy {
        ThresholdStrategy::Fixed(threshold) => Ok(Array1::from_elem(n_labels, *threshold)),
        ThresholdStrategy::PerLabel(thresholds) => {
            if thresholds.len() == n_labels {
                Ok(Array1::from_vec(thresholds.clone()))
            } else {
                // If provided thresholds don't match label count, compute optimal per-label thresholds
                let mut computed_thresholds = Array1::zeros(n_labels);

                for (label_idx, model) in models.iter().enumerate() {
                    let mut scores = Vec::new();
                    let mut labels = Vec::new();

                    for sample_idx in 0..n_samples {
                        let x = X.row(sample_idx);
                        let score = x.dot(&model.weights) + model.bias;
                        scores.push(score);
                        labels.push(y[[sample_idx, label_idx]]);
                    }

                    computed_thresholds[label_idx] = find_optimal_threshold(&scores, &labels)?;
                }

                Ok(computed_thresholds)
            }
        }
        ThresholdStrategy::Optimal => {
            // Find global threshold that optimizes F1 score across all labels
            let mut all_scores = Vec::new();
            let mut all_labels = Vec::new();

            for (label_idx, model) in models.iter().enumerate() {
                for sample_idx in 0..n_samples {
                    let x = X.row(sample_idx);
                    let score = x.dot(&model.weights) + model.bias;
                    all_scores.push(score);
                    all_labels.push(y[[sample_idx, label_idx]]);
                }
            }

            let optimal_threshold = find_optimal_threshold(&all_scores, &all_labels)?;
            Ok(Array1::from_elem(n_labels, optimal_threshold))
        }
        ThresholdStrategy::FScore => {
            // Compute F-score optimized thresholds per label
            let mut thresholds = Array1::zeros(n_labels);

            for (label_idx, model) in models.iter().enumerate() {
                let mut scores = Vec::new();
                let mut labels = Vec::new();

                for sample_idx in 0..n_samples {
                    let x = X.row(sample_idx);
                    let score = x.dot(&model.weights) + model.bias;
                    scores.push(score);
                    labels.push(y[[sample_idx, label_idx]]);
                }

                thresholds[label_idx] = find_optimal_threshold(&scores, &labels)?;
            }

            Ok(thresholds)
        }
    }
}

/// Find optimal threshold that maximizes F1 score
fn find_optimal_threshold(scores: &[Float], labels: &[i32]) -> SklResult<Float> {
    if scores.len() != labels.len() {
        return Err(SklearsError::InvalidInput(
            "Scores and labels must have same length".to_string(),
        ));
    }

    // Create threshold candidates from unique scores
    let mut unique_scores: Vec<Float> = scores.iter().cloned().collect();
    unique_scores.sort_by(|a, b| a.partial_cmp(b).unwrap());
    unique_scores.dedup();

    if unique_scores.is_empty() {
        return Ok(0.0);
    }

    let mut best_threshold = 0.0;
    let mut best_f1 = 0.0;

    // Try each unique score as a threshold
    for &threshold in &unique_scores {
        let mut tp = 0;
        let mut fp = 0;
        let mut fn_ = 0;

        for (i, &score) in scores.iter().enumerate() {
            let prediction = if score >= threshold { 1 } else { 0 };
            let label = labels[i];

            match (prediction, label) {
                (1, 1) => tp += 1,
                (1, 0) => fp += 1,
                (0, 1) => fn_ += 1,
                _ => {}
            }
        }

        let precision = if tp + fp > 0 {
            tp as Float / (tp + fp) as Float
        } else {
            0.0
        };
        let recall = if tp + fn_ > 0 {
            tp as Float / (tp + fn_) as Float
        } else {
            0.0
        };
        let f1 = if precision + recall > 0.0 {
            2.0 * precision * recall / (precision + recall)
        } else {
            0.0
        };

        if f1 > best_f1 {
            best_f1 = f1;
            best_threshold = threshold;
        }
    }

    Ok(best_threshold)
}

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

    #[test]
    fn test_multi_output_classifier() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        let moc = MultiOutputClassifier::new();
        let fitted = moc.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_targets(), 2);
        assert_eq!(fitted.classes().len(), 2);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are valid (within the classes for each target)
        for target_idx in 0..2 {
            let target_classes = &fitted.classes()[target_idx];
            for sample_idx in 0..4 {
                let pred = predictions[[sample_idx, target_idx]];
                assert!(target_classes.contains(&pred));
            }
        }
    }

    #[test]
    fn test_multi_output_regressor() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [2.0, 1.5], [1.0, 1.5]];

        let mor = MultiOutputRegressor::new();
        let fitted = mor.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_targets(), 2);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Predictions should be finite numbers
        for pred in predictions.iter() {
            assert!(pred.is_finite());
        }
    }

    #[test]
    fn test_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[0, 1], [1, 0], [0, 1]]; // Wrong number of rows

        let moc = MultiOutputClassifier::new();
        assert!(moc.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_empty_targets() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = Array2::<i32>::zeros((2, 0)); // No targets

        let moc = MultiOutputClassifier::new();
        assert!(moc.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_prediction_shape_mismatch() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[0, 1], [1, 0]];

        let moc = MultiOutputClassifier::new();
        let fitted = moc.fit(&X.view(), &y).unwrap();

        // Test with wrong number of features
        let X_wrong = array![[1.0, 2.0, 3.0]]; // 3 features instead of 2
        assert!(fitted.predict(&X_wrong.view()).is_err());
    }

    #[test]
    fn test_classifier_chain() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        let cc = ClassifierChain::new();
        let fitted = cc.fit_simple(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_targets(), 2);
        assert_eq!(fitted.chain_order(), &[0, 1]); // Default order

        let predictions = fitted.predict_simple(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are valid
        for sample_idx in 0..4 {
            for target_idx in 0..2 {
                let pred = predictions[[sample_idx, target_idx]];
                // Predictions should be either 0 or 1 for binary classification
                assert!(pred == 0 || pred == 1);
            }
        }
    }

    #[test]
    fn test_classifier_chain_custom_order() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[0, 1], [1, 0], [1, 1]];

        let cc = ClassifierChain::new().order(vec![1, 0]); // Reverse order
        let fitted = cc.fit_simple(&X.view(), &y).unwrap();

        assert_eq!(fitted.chain_order(), &[1, 0]);

        let predictions = fitted.predict_simple(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 2));
    }

    #[test]
    fn test_classifier_chain_invalid_order() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[0, 1], [1, 0]];

        let cc = ClassifierChain::new().order(vec![0, 1, 2]); // Too many indices
        assert!(cc.fit_simple(&X.view(), &y).is_err());
    }

    #[test]
    fn test_classifier_chain_monte_carlo() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        let cc = ClassifierChain::new();
        let fitted = cc.fit_simple(&X.view(), &y).unwrap();

        // Test Monte Carlo predictions with probabilities
        let mc_probs = fitted
            .predict_monte_carlo(&X.view(), 100, Some(42))
            .unwrap();
        assert_eq!(mc_probs.dim(), (4, 2));

        // All probabilities should be between 0 and 1
        for prob in mc_probs.iter() {
            assert!(*prob >= 0.0 && *prob <= 1.0);
        }

        // Test Monte Carlo predictions with labels
        let mc_labels = fitted
            .predict_monte_carlo_labels(&X.view(), 100, Some(42))
            .unwrap();
        assert_eq!(mc_labels.dim(), (4, 2));

        // All predictions should be binary (0 or 1)
        for pred in mc_labels.iter() {
            assert!(*pred == 0 || *pred == 1);
        }

        // Test reproducibility with same random state
        let mc_probs2 = fitted
            .predict_monte_carlo(&X.view(), 100, Some(42))
            .unwrap();
        for (i, (&prob1, &prob2)) in mc_probs.iter().zip(mc_probs2.iter()).enumerate() {
            assert!(
                (prob1 - prob2).abs() < 1e-10,
                "Probabilities should be identical with same random state at index {}",
                i
            );
        }
    }

    #[test]
    fn test_classifier_chain_monte_carlo_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[0, 1], [1, 0]];

        let cc = ClassifierChain::new();
        let fitted = cc.fit_simple(&X.view(), &y).unwrap();

        // Test with zero samples
        assert!(fitted.predict_monte_carlo(&X.view(), 0, None).is_err());

        // Test with wrong number of features
        let X_wrong = array![[1.0, 2.0, 3.0]]; // 3 features instead of 2
        assert!(fitted
            .predict_monte_carlo(&X_wrong.view(), 10, None)
            .is_err());
    }

    #[test]
    fn test_regressor_chain() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [2.0, 1.5], [1.0, 1.5]];

        let rc = RegressorChain::new();
        let fitted = rc.fit_simple(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_targets(), 2);
        assert_eq!(fitted.chain_order(), &[0, 1]); // Default order

        let predictions = fitted.predict_simple(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Predictions should be finite numbers
        for pred in predictions.iter() {
            assert!(pred.is_finite());
        }
    }

    #[test]
    fn test_regressor_chain_custom_order() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [2.0, 1.5]];

        let rc = RegressorChain::new().order(vec![1, 0]); // Reverse order
        let fitted = rc.fit_simple(&X.view(), &y).unwrap();

        assert_eq!(fitted.chain_order(), &[1, 0]);

        let predictions = fitted.predict_simple(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 2));

        // Predictions should be finite numbers
        for pred in predictions.iter() {
            assert!(pred.is_finite());
        }
    }

    #[test]
    fn test_regressor_chain_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [2.0, 1.5]]; // Wrong number of rows

        let rc = RegressorChain::new();
        assert!(rc.fit_simple(&X.view(), &y).is_err());
    }

    #[test]
    fn test_regressor_chain_invalid_order() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5]];

        let rc = RegressorChain::new().order(vec![0, 1, 2]); // Too many indices
        assert!(rc.fit_simple(&X.view(), &y).is_err());
    }

    #[test]
    fn test_binary_relevance() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary

        let br = BinaryRelevance::new();
        let fitted = br.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 2);
        assert_eq!(fitted.classes().len(), 2);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are binary (0 or 1)
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }

        // Test probability predictions
        let probabilities = fitted.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (4, 2));

        // Check that probabilities are in [0, 1]
        for prob in probabilities.iter() {
            assert!(*prob >= 0.0 && *prob <= 1.0);
        }
    }

    #[test]
    fn test_binary_relevance_single_label() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1], [0], [1]]; // Single binary label

        let br = BinaryRelevance::new();
        let fitted = br.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 1);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 1));

        // Check that predictions are binary
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }
    }

    #[test]
    fn test_binary_relevance_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let br = BinaryRelevance::new();
        assert!(br.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_binary_relevance_non_binary_labels() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[0, 1], [1, 2], [2, 0]]; // Non-binary labels

        let br = BinaryRelevance::new();
        assert!(br.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_binary_relevance_predict_shape_mismatch() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1]];

        let br = BinaryRelevance::new();
        let fitted = br.fit(&X.view(), &y).unwrap();

        // Test with wrong number of features
        let X_wrong = array![[1.0, 2.0, 3.0]]; // 3 features instead of 2
        assert!(fitted.predict(&X_wrong.view()).is_err());
        assert!(fitted.predict_proba(&X_wrong.view()).is_err());
    }

    #[test]
    fn test_label_powerset() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary combinations

        let lp = LabelPowerset::new();
        let fitted = lp.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 2);
        assert_eq!(fitted.n_classes(), 4); // 4 unique combinations: [1,0], [0,1], [1,1], [0,0]

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are binary (0 or 1)
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }

        // Test decision function
        let scores = fitted.decision_function(&X.view()).unwrap();
        assert_eq!(scores.dim(), (4, 4)); // 4 samples, 4 classes

        // Scores should be finite
        for score in scores.iter() {
            assert!(score.is_finite());
        }
    }

    #[test]
    fn test_label_powerset_simple_case() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1, 0], [0, 1], [1, 0]]; // Only 2 unique combinations

        let lp = LabelPowerset::new();
        let fitted = lp.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 2);
        assert_eq!(fitted.n_classes(), 2); // Only 2 unique combinations: [1,0], [0,1]

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 2));

        // Check that predictions are binary
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }
    }

    #[test]
    fn test_label_powerset_single_label() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1], [0], [1]]; // Single binary label

        let lp = LabelPowerset::new();
        let fitted = lp.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 1);
        assert_eq!(fitted.n_classes(), 2); // 2 unique combinations: [1], [0]

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 1));

        // Check that predictions are binary
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }
    }

    #[test]
    fn test_label_powerset_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let lp = LabelPowerset::new();
        assert!(lp.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_label_powerset_non_binary_labels() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[0, 1], [1, 2], [2, 0]]; // Non-binary labels

        let lp = LabelPowerset::new();
        assert!(lp.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_label_powerset_predict_shape_mismatch() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1]];

        let lp = LabelPowerset::new();
        let fitted = lp.fit(&X.view(), &y).unwrap();

        // Test with wrong number of features
        let X_wrong = array![[1.0, 2.0, 3.0]]; // 3 features instead of 2
        assert!(fitted.predict(&X_wrong.view()).is_err());
        assert!(fitted.decision_function(&X_wrong.view()).is_err());
    }

    #[test]
    fn test_label_powerset_all_same_combination() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1, 0], [1, 0], [1, 0]]; // All samples have same label combination

        let lp = LabelPowerset::new();
        let fitted = lp.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 2);
        assert_eq!(fitted.n_classes(), 1); // Only 1 unique combination

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 2));

        // All predictions should be [1, 0]
        for sample_idx in 0..3 {
            assert_eq!(predictions[[sample_idx, 0]], 1);
            assert_eq!(predictions[[sample_idx, 1]], 0);
        }
    }

    #[test]
    fn test_pruned_label_powerset_default_strategy() {
        // Test data with some rare combinations
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [1.0, 1.0],
            [2.0, 2.0],
            [3.0, 3.0],
            [1.5, 2.5],
            [2.5, 1.5]
        ];
        let y = array![
            [1, 0],
            [0, 1],
            [1, 1],
            [0, 0], // Frequent combinations
            [1, 0],
            [0, 1],
            [1, 0],
            [0, 1], // More frequent ones
        ];

        let plp = PrunedLabelPowerset::new()
            .min_frequency(2)
            .strategy(PruningStrategy::DefaultMapping(vec![0, 0]));

        let fitted = plp.fit(&X.view(), &y).unwrap();

        // Should have pruned to only frequent combinations
        assert!(fitted.n_frequent_classes() <= 4); // At most [1,0], [0,1], [1,1], [0,0]
        assert_eq!(fitted.min_frequency(), 2);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (8, 2));

        // All predictions should be binary
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }
    }

    #[test]
    fn test_pruned_label_powerset_similarity_strategy() {
        // Test with similarity mapping strategy
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [1.0, 1.0],
            [2.0, 2.0],
            [3.0, 3.0]
        ];
        let y = array![
            [1, 0],
            [1, 0],
            [1, 0], // Frequent: [1, 0] appears 3 times
            [0, 1],
            [0, 1], // Frequent: [0, 1] appears 2 times
            [1, 1]  // Rare: [1, 1] appears 1 time
        ];

        let plp = PrunedLabelPowerset::new()
            .min_frequency(2)
            .strategy(PruningStrategy::SimilarityMapping);

        let fitted = plp.fit(&X.view(), &y).unwrap();

        // Should have only 2 frequent combinations: [1,0] and [0,1]
        assert_eq!(fitted.n_frequent_classes(), 2);

        // The rare combination [1,1] should be mapped to one of the frequent ones
        let mapping = fitted.combination_mapping();
        let rare_combo = vec![1, 1];
        assert!(mapping.contains_key(&rare_combo));

        // The mapped combination should be one of the frequent ones
        let mapped = mapping.get(&rare_combo).unwrap();
        assert!(mapped == &vec![1, 0] || mapped == &vec![0, 1]);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (6, 2));

        // All predictions should be binary
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }
    }

    #[test]
    fn test_pruned_label_powerset_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[0, 1], [1, 0]];

        // Test with minimum frequency that results in no frequent combinations
        let plp = PrunedLabelPowerset::new().min_frequency(5); // Too high
        assert!(plp.fit(&X.view(), &y).is_err());

        // Test with invalid default combination length
        let plp =
            PrunedLabelPowerset::new().strategy(PruningStrategy::DefaultMapping(vec![0, 1, 0])); // 3 elements for 2 labels
        assert!(plp.fit(&X.view(), &y).is_err());

        // Test with non-binary labels
        let y_bad = array![[2, 1], [1, 0]]; // Contains non-binary value
        let plp = PrunedLabelPowerset::new();
        assert!(plp.fit(&X.view(), &y_bad).is_err());
    }

    #[test]
    fn test_pruned_label_powerset_edge_cases() {
        // Test with minimal data that meets frequency requirement
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [1, 0]]; // Same combination twice

        let plp = PrunedLabelPowerset::new().min_frequency(2);
        let fitted = plp.fit(&X.view(), &y).unwrap();

        // Should have at least 1 combination, possibly 2 if default is added
        assert!(fitted.n_frequent_classes() >= 1);
        assert!(fitted.frequent_combinations().len() >= 1);

        // The frequent combinations should include [1, 0]
        assert!(fitted.frequent_combinations().contains(&vec![1, 0]));

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (2, 2));

        // All predictions should be [1, 0]
        for sample_idx in 0..2 {
            assert_eq!(predictions[[sample_idx, 0]], 1);
            assert_eq!(predictions[[sample_idx, 1]], 0);
        }
    }

    #[test]
    fn test_metrics_hamming_loss() {
        let y_true = array![[1, 0, 1], [0, 1, 0], [1, 1, 1]];
        let y_pred = array![[1, 0, 0], [0, 1, 1], [1, 0, 1]]; // 3 errors out of 9

        let loss = metrics::hamming_loss(&y_true.view(), &y_pred.view()).unwrap();
        assert!((loss - 3.0 / 9.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_subset_accuracy() {
        let y_true = array![[1, 0, 1], [0, 1, 0], [1, 1, 1]];
        let y_pred = array![[1, 0, 1], [0, 1, 1], [1, 0, 1]]; // Only first subset matches

        let accuracy = metrics::subset_accuracy(&y_true.view(), &y_pred.view()).unwrap();
        assert!((accuracy - 1.0 / 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_jaccard_score() {
        let y_true = array![[1, 0, 1], [0, 1, 0]];
        let y_pred = array![[1, 0, 0], [0, 1, 1]];

        let score = metrics::jaccard_score(&y_true.view(), &y_pred.view()).unwrap();
        // Sample 1: intersection=1, union=2, jaccard=0.5
        // Sample 2: intersection=1, union=2, jaccard=0.5
        // Average: 0.5
        assert!((score - 0.5).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_f1_score_micro() {
        let y_true = array![[1, 0, 1], [0, 1, 0], [1, 1, 1]];
        let y_pred = array![[1, 0, 0], [0, 1, 1], [1, 0, 1]];

        let f1 = metrics::f1_score(&y_true.view(), &y_pred.view(), "micro").unwrap();
        // TP=4, FP=1, FN=2
        // Precision = 4/5 = 0.8, Recall = 4/6 = 0.6667
        // F1 = 2 * 0.8 * 0.6667 / (0.8 + 0.6667) = 0.727
        assert!((f1 - 0.7272727272727273).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_f1_score_macro() {
        let y_true = array![[1, 0], [0, 1], [1, 1]];
        let y_pred = array![[1, 0], [0, 1], [1, 0]]; // Perfect for label 0, imperfect for label 1

        let f1 = metrics::f1_score(&y_true.view(), &y_pred.view(), "macro").unwrap();
        // Label 0: TP=2, FP=0, FN=0 -> F1=1.0
        // Label 1: TP=1, FP=0, FN=1 -> Precision=1.0, Recall=0.5, F1=0.667
        // Macro average: (1.0 + 0.667) / 2 = 0.833
        assert!((f1 - 0.8333333333333334).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_f1_score_samples() {
        let y_true = array![[1, 0], [0, 1], [1, 1]];
        let y_pred = array![[1, 0], [0, 1], [1, 0]];

        let f1 = metrics::f1_score(&y_true.view(), &y_pred.view(), "samples").unwrap();
        // Sample 0: TP=1, FP=0, FN=0 -> F1=1.0
        // Sample 1: TP=1, FP=0, FN=0 -> F1=1.0
        // Sample 2: TP=1, FP=0, FN=1 -> Precision=1.0, Recall=0.5, F1=0.667
        // Average: (1.0 + 1.0 + 0.667) / 3 = 0.889
        assert!((f1 - 0.8888888888888888).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_coverage_error() {
        let y_true = array![[1, 0, 1], [0, 1, 0]];
        let y_scores = array![[0.9, 0.1, 0.8], [0.2, 0.9, 0.3]];

        let coverage = metrics::coverage_error(&y_true.view(), &y_scores.view()).unwrap();
        // Sample 0: sorted scores [0.9, 0.8, 0.1] -> labels [0, 2, 1]
        //          true labels are at positions 1 and 2, so coverage = 2
        // Sample 1: sorted scores [0.9, 0.3, 0.2] -> labels [1, 2, 0]
        //          true label is at position 1, so coverage = 1
        // Average: (2 + 1) / 2 = 1.5
        assert!((coverage - 1.5).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_label_ranking_average_precision() {
        let y_true = array![[1, 0, 1], [0, 1, 0]];
        let y_scores = array![[0.9, 0.1, 0.8], [0.2, 0.9, 0.3]];

        let lrap =
            metrics::label_ranking_average_precision(&y_true.view(), &y_scores.view()).unwrap();
        // Sample 0: sorted scores [0.9, 0.8, 0.1] -> labels [0, 2, 1]
        //          true labels: 0 (pos 1), 2 (pos 2)
        //          precision at pos 1: 1/1=1.0, precision at pos 2: 2/2=1.0
        //          LRAP = (1.0 + 1.0) / 2 = 1.0
        // Sample 1: sorted scores [0.9, 0.3, 0.2] -> labels [1, 2, 0]
        //          true label: 1 (pos 1)
        //          precision at pos 1: 1/1=1.0
        //          LRAP = 1.0 / 1 = 1.0
        // Average: (1.0 + 1.0) / 2 = 1.0
        assert!((lrap - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_invalid_shapes() {
        let y_true = array![[1, 0], [0, 1]];
        let y_pred = array![[1, 0, 1]]; // Wrong shape

        assert!(metrics::hamming_loss(&y_true.view(), &y_pred.view()).is_err());
        assert!(metrics::subset_accuracy(&y_true.view(), &y_pred.view()).is_err());
        assert!(metrics::jaccard_score(&y_true.view(), &y_pred.view()).is_err());
        assert!(metrics::f1_score(&y_true.view(), &y_pred.view(), "micro").is_err());
    }

    #[test]
    fn test_metrics_invalid_f1_average() {
        let y_true = array![[1, 0], [0, 1]];
        let y_pred = array![[1, 0], [0, 1]];

        assert!(metrics::f1_score(&y_true.view(), &y_pred.view(), "invalid").is_err());
    }

    #[test]
    fn test_ensemble_of_chains() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        let eoc = EnsembleOfChains::new().n_chains(3).random_state(42);
        let fitted = eoc.fit_simple(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_chains(), 3);
        assert_eq!(fitted.n_targets(), 2);

        let predictions = fitted.predict_simple(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are binary (0 or 1)
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }

        // Test probability predictions
        let probabilities = fitted.predict_proba_simple(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (4, 2));

        // Check that probabilities are in [0, 1]
        for prob in probabilities.iter() {
            assert!(*prob >= 0.0 && *prob <= 1.0);
        }
    }

    #[test]
    fn test_ensemble_of_chains_single_chain() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1]];

        let eoc = EnsembleOfChains::new().n_chains(1);
        let fitted = eoc.fit_simple(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_chains(), 1);

        let predictions = fitted.predict_simple(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (2, 2));
    }

    #[test]
    fn test_ensemble_of_chains_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let eoc = EnsembleOfChains::new();
        assert!(eoc.fit_simple(&X.view(), &y).is_err());
    }

    #[test]
    fn test_one_vs_rest_classifier() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [1.0, 1.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary

        let ovr = OneVsRestClassifier::new();
        let fitted = ovr.fit(&X.view(), &y).unwrap();

        assert_eq!(fitted.n_labels(), 2);
        assert_eq!(fitted.classes().len(), 2);

        let predictions = fitted.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are binary (0 or 1)
        for pred in predictions.iter() {
            assert!(*pred == 0 || *pred == 1);
        }

        // Test probability predictions
        let probabilities = fitted.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (4, 2));

        // Check that probabilities are in [0, 1]
        for prob in probabilities.iter() {
            assert!(*prob >= 0.0 && *prob <= 1.0);
        }

        // Test decision function
        let scores = fitted.decision_function(&X.view()).unwrap();
        assert_eq!(scores.dim(), (4, 2));

        // Scores should be finite
        for score in scores.iter() {
            assert!(score.is_finite());
        }
    }

    #[test]
    fn test_one_vs_rest_classifier_invalid_input() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let ovr = OneVsRestClassifier::new();
        assert!(ovr.fit(&X.view(), &y).is_err());
    }

    #[test]
    fn test_metrics_one_error() {
        let y_true = array![[1, 0, 0], [0, 1, 0], [0, 0, 1]];
        let y_scores = array![[0.9, 0.1, 0.05], [0.1, 0.8, 0.1], [0.05, 0.1, 0.85]];

        let one_err = metrics::one_error(&y_true.view(), &y_scores.view()).unwrap();
        // All top-ranked labels are correct, so one-error should be 0
        assert!((one_err - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_one_error_with_errors() {
        let y_true = array![[1, 0], [0, 1]];
        let y_scores = array![[0.3, 0.7], [0.6, 0.4]]; // Top predictions are wrong

        let one_err = metrics::one_error(&y_true.view(), &y_scores.view()).unwrap();
        // Both samples have incorrect top predictions, so one-error should be 1.0
        assert!((one_err - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_ranking_loss() {
        let y_true = array![[1, 0], [0, 1]];
        let y_scores = array![[0.8, 0.2], [0.3, 0.7]]; // Correct ordering

        let ranking_loss = metrics::ranking_loss(&y_true.view(), &y_scores.view()).unwrap();
        // Perfect ranking, so loss should be 0
        assert!((ranking_loss - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_ranking_loss_with_errors() {
        let y_true = array![[1, 0], [0, 1]];
        let y_scores = array![[0.2, 0.8], [0.7, 0.3]]; // Incorrect ordering

        let ranking_loss = metrics::ranking_loss(&y_true.view(), &y_scores.view()).unwrap();
        // All pairs are incorrectly ordered, so loss should be 1.0
        assert!((ranking_loss - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_average_precision_score() {
        let y_true = array![[1, 0, 1], [0, 1, 0]];
        let y_scores = array![[0.9, 0.1, 0.8], [0.2, 0.9, 0.3]];

        let ap_score = metrics::average_precision_score(&y_true.view(), &y_scores.view()).unwrap();
        // With perfect ranking for both samples, AP should be 1.0
        assert!((ap_score - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_precision_recall_micro() {
        let y_true = array![[1, 0, 1], [0, 1, 0], [1, 1, 1]];
        let y_pred = array![[1, 0, 0], [0, 1, 1], [1, 0, 1]];

        let precision = metrics::precision_score_micro(&y_true.view(), &y_pred.view()).unwrap();
        let recall = metrics::recall_score_micro(&y_true.view(), &y_pred.view()).unwrap();

        // TP=4, FP=1, FN=2
        // Precision = 4/5 = 0.8, Recall = 4/6 = 0.6667
        assert!((precision - 0.8).abs() < 1e-10);
        assert!((recall - 0.6666666666666666).abs() < 1e-10);
    }

    #[test]
    fn test_metrics_invalid_shapes_new_metrics() {
        let y_true = array![[1, 0], [0, 1]];
        let y_pred = array![[1, 0, 1]]; // Wrong shape
        let y_scores = array![[0.8, 0.2, 0.1]]; // Wrong shape

        assert!(metrics::one_error(&y_true.view(), &y_scores.view()).is_err());
        assert!(metrics::ranking_loss(&y_true.view(), &y_scores.view()).is_err());
        assert!(metrics::average_precision_score(&y_true.view(), &y_scores.view()).is_err());
        assert!(metrics::precision_score_micro(&y_true.view(), &y_pred.view()).is_err());
        assert!(metrics::recall_score_micro(&y_true.view(), &y_pred.view()).is_err());
    }

    #[test]
    fn test_label_analysis_basic() {
        let y = array![
            [1, 0, 1], // Cardinality 2
            [0, 1, 0], // Cardinality 1
            [1, 0, 1], // Cardinality 2 (duplicate)
            [0, 0, 0], // Cardinality 0
            [1, 1, 1], // Cardinality 3
        ];

        let results = label_analysis::analyze_combinations(&y.view()).unwrap();

        assert_eq!(results.n_samples, 5);
        assert_eq!(results.n_labels, 3);
        assert_eq!(results.n_unique_combinations, 4); // [1,0,1], [0,1,0], [0,0,0], [1,1,1]

        // Check that [1,0,1] is most frequent (appears twice)
        assert_eq!(results.most_frequent.combination, vec![1, 0, 1]);
        assert_eq!(results.most_frequent.frequency, 2);
        assert!((results.most_frequent.relative_frequency - 0.4).abs() < 1e-10);
        assert_eq!(results.most_frequent.cardinality, 2);

        // Average cardinality should be (2+1+2+0+3)/5 = 1.6
        assert!((results.avg_cardinality - 1.6).abs() < 1e-10);

        // Label density: total active labels = 8, total possible = 15, density = 8/15
        assert!((results.label_density - 8.0 / 15.0).abs() < 1e-10);
    }

    #[test]
    fn test_label_analysis_utility_functions() {
        let y = array![
            [1, 0],
            [1, 0],
            [1, 0], // Frequent: [1, 0] appears 3 times
            [0, 1],
            [0, 1], // Frequent: [0, 1] appears 2 times
            [1, 1]  // Rare: [1, 1] appears 1 time
        ];

        let results = label_analysis::analyze_combinations(&y.view()).unwrap();

        // Test get_rare_combinations
        let rare = label_analysis::get_rare_combinations(&results, 2);
        assert_eq!(rare.len(), 1);
        assert_eq!(rare[0].combination, vec![1, 1]);
        assert_eq!(rare[0].frequency, 1);

        // Test get_combinations_by_cardinality
        let cardinality_1 = label_analysis::get_combinations_by_cardinality(&results, 1);
        assert_eq!(cardinality_1.len(), 2); // [1, 0] and [0, 1]

        let cardinality_2 = label_analysis::get_combinations_by_cardinality(&results, 2);
        assert_eq!(cardinality_2.len(), 1); // [1, 1]
        assert_eq!(cardinality_2[0].combination, vec![1, 1]);
    }

    #[test]
    fn test_label_cooccurrence_matrix() {
        let y = array![
            [1, 1, 0], // Labels 0 and 1 co-occur
            [1, 0, 1], // Labels 0 and 2 co-occur
            [0, 1, 1], // Labels 1 and 2 co-occur
            [1, 1, 1], // All labels co-occur
        ];

        let cooccurrence = label_analysis::label_cooccurrence_matrix(&y.view()).unwrap();
        assert_eq!(cooccurrence.dim(), (3, 3));

        // Label 0 appears with itself in samples 0, 1, 3 = 3 times
        assert_eq!(cooccurrence[[0, 0]], 3);
        // Label 1 appears with itself in samples 0, 2, 3 = 3 times
        assert_eq!(cooccurrence[[1, 1]], 3);
        // Label 2 appears with itself in samples 1, 2, 3 = 3 times
        assert_eq!(cooccurrence[[2, 2]], 3);

        // Labels 0 and 1 co-occur in samples 0, 3 = 2 times
        assert_eq!(cooccurrence[[0, 1]], 2);
        assert_eq!(cooccurrence[[1, 0]], 2);

        // Labels 0 and 2 co-occur in samples 1, 3 = 2 times
        assert_eq!(cooccurrence[[0, 2]], 2);
        assert_eq!(cooccurrence[[2, 0]], 2);

        // Labels 1 and 2 co-occur in samples 2, 3 = 2 times
        assert_eq!(cooccurrence[[1, 2]], 2);
        assert_eq!(cooccurrence[[2, 1]], 2);
    }

    #[test]
    fn test_label_correlation_matrix() {
        let y = array![[1, 1, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0],];

        let correlation = label_analysis::label_correlation_matrix(&y.view()).unwrap();
        assert_eq!(correlation.dim(), (3, 3));

        // Diagonal should be 1.0 (perfect self-correlation)
        assert!((correlation[[0, 0]] - 1.0).abs() < 1e-10);
        assert!((correlation[[1, 1]] - 1.0).abs() < 1e-10);
        assert!((correlation[[2, 2]] - 1.0).abs() < 1e-10);

        // Matrix should be symmetric
        for i in 0..3 {
            for j in 0..3 {
                assert!((correlation[[i, j]] - correlation[[j, i]]).abs() < 1e-10);
            }
        }

        // All correlations should be between -1 and 1
        for i in 0..3 {
            for j in 0..3 {
                assert!(correlation[[i, j]] >= -1.0 && correlation[[i, j]] <= 1.0);
            }
        }
    }

    #[test]
    fn test_label_analysis_invalid_input() {
        // Test with non-binary labels
        let y_bad = array![[2, 1], [1, 0]]; // Contains non-binary value
        assert!(label_analysis::analyze_combinations(&y_bad.view()).is_err());

        // Test with empty array
        let y_empty = Array2::<i32>::zeros((0, 2));
        assert!(label_analysis::analyze_combinations(&y_empty.view()).is_err());

        let y_no_labels = Array2::<i32>::zeros((2, 0));
        assert!(label_analysis::analyze_combinations(&y_no_labels.view()).is_err());

        // Test cooccurrence matrix with empty data
        assert!(label_analysis::label_cooccurrence_matrix(&y_empty.view()).is_err());
        assert!(label_analysis::label_correlation_matrix(&y_empty.view()).is_err());
    }

    #[test]
    fn test_label_analysis_edge_cases() {
        // Test with single sample
        let y_single = array![[1, 0, 1]];
        let results = label_analysis::analyze_combinations(&y_single.view()).unwrap();

        assert_eq!(results.n_samples, 1);
        assert_eq!(results.n_unique_combinations, 1);
        assert_eq!(results.most_frequent.combination, vec![1, 0, 1]);
        assert_eq!(results.least_frequent.combination, vec![1, 0, 1]);
        assert_eq!(results.avg_cardinality, 2.0);

        // Test with all zeros
        let y_zeros = array![[0, 0], [0, 0]];
        let results = label_analysis::analyze_combinations(&y_zeros.view()).unwrap();

        assert_eq!(results.avg_cardinality, 0.0);
        assert_eq!(results.label_density, 0.0);

        // Test with all ones
        let y_ones = array![[1, 1], [1, 1]];
        let results = label_analysis::analyze_combinations(&y_ones.view()).unwrap();

        assert_eq!(results.avg_cardinality, 2.0);
        assert_eq!(results.label_density, 1.0);
    }

    #[test]
    fn test_iblr_basic_functionality() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]]; // Multi-output regression targets

        let iblr = IBLR::new().k_neighbors(2);
        let trained_iblr = iblr.fit(&X.view(), &y).unwrap();
        let predictions = trained_iblr.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 2));

        // Check that predictions are reasonable (close to actual values)
        for i in 0..4 {
            for j in 0..2 {
                assert!((predictions[[i, j]] - y[[i, j]]).abs() < 2.0); // Allow some tolerance
            }
        }
    }

    #[test]
    fn test_iblr_configuration() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];

        // Test different k values
        let iblr1 = IBLR::new().k_neighbors(1);
        let iblr2 = IBLR::new().k_neighbors(3);

        let trained1 = iblr1.fit(&X.view(), &y).unwrap();
        let trained2 = iblr2.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();

        assert_eq!(pred1.dim(), (3, 2));
        assert_eq!(pred2.dim(), (3, 2));

        // Test weight functions
        let iblr_uniform = IBLR::new().k_neighbors(2).weights(WeightFunction::Uniform);
        let iblr_distance = IBLR::new().k_neighbors(2).weights(WeightFunction::Distance);

        let trained_uniform = iblr_uniform.fit(&X.view(), &y).unwrap();
        let trained_distance = iblr_distance.fit(&X.view(), &y).unwrap();

        let pred_uniform = trained_uniform.predict(&X.view()).unwrap();
        let pred_distance = trained_distance.predict(&X.view()).unwrap();

        assert_eq!(pred_uniform.dim(), (3, 2));
        assert_eq!(pred_distance.dim(), (3, 2));
    }

    #[test]
    fn test_iblr_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]]; // Mismatched samples

        let iblr = IBLR::new();
        assert!(iblr.fit(&X.view(), &y).is_err());

        // Test k_neighbors validation
        let y_valid = array![[1.0, 2.0], [2.0, 3.0]];

        let iblr_zero_k = IBLR::new().k_neighbors(0);
        assert!(iblr_zero_k.fit(&X.view(), &y_valid).is_err());

        let iblr_large_k = IBLR::new().k_neighbors(5); // More than samples
        assert!(iblr_large_k.fit(&X.view(), &y_valid).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1.0, 2.0], [2.0, 3.0]];
        let iblr_for_predict = IBLR::new().k_neighbors(2);
        let trained = iblr_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_wrong_features = array![[1.0, 2.0, 3.0]]; // Extra feature
        assert!(trained.predict(&X_wrong_features.view()).is_err());

        // Test empty data
        let X_empty = Array2::<Float>::zeros((0, 2));
        let y_empty = Array2::<Float>::zeros((0, 2));
        assert!(IBLR::new().fit(&X_empty.view(), &y_empty).is_err());
    }

    #[test]
    fn test_iblr_weight_functions() {
        let X = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 2.0]];
        let y = array![[1.0, 1.0], [2.0, 1.0], [1.0, 2.0], [3.0, 3.0]];

        // Test uniform weighting
        let iblr_uniform = IBLR::new().k_neighbors(3).weights(WeightFunction::Uniform);
        let trained_uniform = iblr_uniform.fit(&X.view(), &y).unwrap();
        let pred_uniform = trained_uniform.predict(&X.view()).unwrap();

        // Test distance weighting
        let iblr_distance = IBLR::new().k_neighbors(3).weights(WeightFunction::Distance);
        let trained_distance = iblr_distance.fit(&X.view(), &y).unwrap();
        let pred_distance = trained_distance.predict(&X.view()).unwrap();

        // Predictions should be reasonable for both
        assert_eq!(pred_uniform.dim(), (4, 2));
        assert_eq!(pred_distance.dim(), (4, 2));

        // For training points, predictions should be reasonable (not exact with k=3)
        for j in 0..2 {
            assert!((pred_uniform[[0, j]] - y[[0, j]]).abs() < 1.0); // More reasonable tolerance
            assert!((pred_distance[[0, j]] - y[[0, j]]).abs() < 1.0); // More reasonable tolerance
        }
    }

    #[test]
    fn test_iblr_single_neighbor() {
        let X = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]];
        let y = array![[10.0, 20.0], [20.0, 30.0], [30.0, 40.0]];

        let iblr = IBLR::new().k_neighbors(1);
        let trained = iblr.fit(&X.view(), &y).unwrap();

        // Test prediction on training data (should be exact for k=1)
        let predictions = trained.predict(&X.view()).unwrap();

        for i in 0..3 {
            for j in 0..2 {
                assert!((predictions[[i, j]] - y[[i, j]]).abs() < 1e-10);
            }
        }
    }

    #[test]
    fn test_iblr_interpolation() {
        let X = array![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]];
        let y = array![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]];

        let iblr = IBLR::new().k_neighbors(2);
        let trained = iblr.fit(&X.view(), &y).unwrap();

        // Test prediction at midpoint
        let X_test = array![[0.5, 0.5]];
        let prediction = trained.predict(&X_test.view()).unwrap();

        // Should be close to interpolated value [0.5, 0.5]
        assert!((prediction[[0, 0]] - 0.5).abs() < 0.1);
        assert!((prediction[[0, 1]] - 0.5).abs() < 0.1);
    }

    #[test]
    fn test_clare_basic_functionality() {
        let X = array![[1.0, 1.0], [1.5, 1.5], [5.0, 5.0], [5.5, 5.5]];
        let y = array![[1, 0], [1, 0], [0, 1], [0, 1]]; // Two clear clusters with different label patterns

        let clare = CLARE::new().n_clusters(2).random_state(Some(42));
        let trained_clare = clare.fit(&X.view(), &y).unwrap();
        let predictions = trained_clare.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 2));

        // Verify cluster centers were learned
        assert_eq!(trained_clare.cluster_centers().dim(), (2, 2));
        assert_eq!(trained_clare.label_relevance().dim(), (2, 2));
    }

    #[test]
    fn test_clare_configuration() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test different configurations
        let clare1 = CLARE::new().n_clusters(2).threshold(0.3);
        let clare2 = CLARE::new().n_clusters(3).max_iter(50);
        let clare3 = CLARE::new().random_state(Some(123));

        let trained1 = clare1.fit(&X.view(), &y).unwrap();
        let trained2 = clare2.fit(&X.view(), &y).unwrap();
        let trained3 = clare3.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();
        let pred3 = trained3.predict(&X.view()).unwrap();

        assert_eq!(pred1.dim(), (4, 2));
        assert_eq!(pred2.dim(), (4, 2));
        assert_eq!(pred3.dim(), (4, 2));

        // Test accessors
        assert_eq!(trained1.threshold(), 0.3);
        assert_eq!(trained1.cluster_centers().dim(), (2, 2));
        assert_eq!(trained2.cluster_centers().dim(), (3, 2));
    }

    #[test]
    fn test_clare_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Mismatched samples

        let clare = CLARE::new();
        assert!(clare.fit(&X.view(), &y).is_err());

        // Test n_clusters validation
        let y_valid = array![[1, 0], [0, 1]];

        let clare_zero_clusters = CLARE::new().n_clusters(0);
        assert!(clare_zero_clusters.fit(&X.view(), &y_valid).is_err());

        let clare_too_many_clusters = CLARE::new().n_clusters(5); // More than samples
        assert!(clare_too_many_clusters.fit(&X.view(), &y_valid).is_err());

        // Test non-binary labels
        let y_non_binary = array![[1, 2], [0, 1]]; // Contains 2
        assert!(CLARE::new().fit(&X.view(), &y_non_binary).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1, 0], [0, 1]];
        let clare_for_predict = CLARE::new().n_clusters(2);
        let trained = clare_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_wrong_features = array![[1.0, 2.0, 3.0]]; // Extra feature
        assert!(trained.predict(&X_wrong_features.view()).is_err());

        // Test empty data
        let X_empty = Array2::<Float>::zeros((0, 2));
        let y_empty = Array2::<i32>::zeros((0, 2));
        assert!(CLARE::new().fit(&X_empty.view(), &y_empty).is_err());
    }

    #[test]
    fn test_clare_predict_proba() {
        let X = array![[1.0, 1.0], [1.2, 1.2], [5.0, 5.0], [5.2, 5.2]];
        let y = array![[1, 0], [1, 0], [0, 1], [0, 1]];

        let clare = CLARE::new().n_clusters(2).random_state(Some(42));
        let trained_clare = clare.fit(&X.view(), &y).unwrap();

        // Test predict_proba
        let probabilities = trained_clare.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (4, 2));

        // All probabilities should be between 0 and 1
        for prob in probabilities.iter() {
            assert!(*prob >= 0.0 && *prob <= 1.0);
        }
    }

    #[test]
    fn test_clare_clustering_consistency() {
        let X = array![
            [0.0, 0.0],
            [0.1, 0.1], // First cluster
            [5.0, 5.0],
            [5.1, 5.1] // Second cluster
        ];
        let y = array![
            [1, 0],
            [1, 0], // First cluster: always label 0 active
            [0, 1],
            [0, 1] // Second cluster: always label 1 active
        ];

        let clare = CLARE::new()
            .n_clusters(2)
            .threshold(0.5)
            .random_state(Some(42));
        let trained_clare = clare.fit(&X.view(), &y).unwrap();
        let predictions = trained_clare.predict(&X.view()).unwrap();

        // With clear clustering, predictions should be good
        let probabilities = trained_clare.predict_proba(&X.view()).unwrap();

        // First two samples should have high probability for label 0
        for i in 0..2 {
            assert!(probabilities[[i, 0]] > 0.8); // High prob for label 0
            assert!(probabilities[[i, 1]] < 0.2); // Low prob for label 1
        }

        // Last two samples should have high probability for label 1
        for i in 2..4 {
            assert!(probabilities[[i, 0]] < 0.2); // Low prob for label 0
            assert!(probabilities[[i, 1]] > 0.8); // High prob for label 1
        }
    }

    #[test]
    fn test_clare_single_cluster() {
        let X = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]];

        // Use only 1 cluster
        let clare = CLARE::new().n_clusters(1);
        let trained_clare = clare.fit(&X.view(), &y).unwrap();
        let predictions = trained_clare.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (3, 2));
        assert_eq!(trained_clare.cluster_centers().dim(), (1, 2));

        // With 1 cluster, all samples should get same prediction
        // (based on average label frequency)
        for i in 1..3 {
            for j in 0..2 {
                assert_eq!(predictions[[0, j]], predictions[[i, j]]);
            }
        }
    }

    #[test]
    fn test_clare_reproducibility() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Train two models with same random state
        let clare1 = CLARE::new().n_clusters(2).random_state(Some(42));
        let trained1 = clare1.fit(&X.view(), &y).unwrap();

        let clare2 = CLARE::new().n_clusters(2).random_state(Some(42));
        let trained2 = clare2.fit(&X.view(), &y).unwrap();

        // Should produce same cluster centers
        let centers1 = trained1.cluster_centers();
        let centers2 = trained2.cluster_centers();

        for i in 0..centers1.nrows() {
            for j in 0..centers1.ncols() {
                assert!((centers1[[i, j]] - centers2[[i, j]]).abs() < 1e-10);
            }
        }

        // Should produce same predictions
        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();

        for i in 0..pred1.nrows() {
            for j in 0..pred1.ncols() {
                assert_eq!(pred1[[i, j]], pred2[[i, j]]);
            }
        }
    }

    #[test]
    fn test_mltsvm_basic_functionality() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary

        let mltsvm = MLTSVM::new().c1(1.0).c2(1.0);
        let trained_mltsvm = mltsvm.fit(&X.view(), &y).unwrap();
        let predictions = trained_mltsvm.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 2));
        assert_eq!(trained_mltsvm.n_labels(), 2);

        // All predictions should be binary (0 or 1)
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }
    }

    #[test]
    fn test_mltsvm_configuration() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test different configurations
        let mltsvm1 = MLTSVM::new().c1(0.5).c2(1.5);
        let mltsvm2 = MLTSVM::new().epsilon(1e-8).max_iter(500);

        let trained1 = mltsvm1.fit(&X.view(), &y).unwrap();
        let trained2 = mltsvm2.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();

        assert_eq!(pred1.dim(), (4, 2));
        assert_eq!(pred2.dim(), (4, 2));
    }

    #[test]
    fn test_mltsvm_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Mismatched samples

        let mltsvm = MLTSVM::new();
        assert!(mltsvm.fit(&X.view(), &y).is_err());

        // Test non-binary labels
        let y_non_binary = array![[1, 2], [0, 1]]; // Contains 2
        assert!(MLTSVM::new().fit(&X.view(), &y_non_binary).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 2.0]];
        let y_train = array![[1, 0], [0, 1], [1, 1], [0, 0]];
        let mltsvm_for_predict = MLTSVM::new();
        let trained = mltsvm_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_wrong_features = array![[1.0, 2.0, 3.0]]; // Extra feature
        assert!(trained.predict(&X_wrong_features.view()).is_err());

        // Test empty data
        let X_empty = Array2::<Float>::zeros((0, 2));
        let y_empty = Array2::<i32>::zeros((0, 2));
        assert!(MLTSVM::new().fit(&X_empty.view(), &y_empty).is_err());
    }

    #[test]
    fn test_mltsvm_decision_function() {
        let X = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]];
        let y = array![[1, 0], [1, 0], [0, 1], [0, 1]];

        let mltsvm = MLTSVM::new();
        let trained_mltsvm = mltsvm.fit(&X.view(), &y).unwrap();

        // Test decision function
        let decision_values = trained_mltsvm.decision_function(&X.view()).unwrap();
        assert_eq!(decision_values.dim(), (4, 2));

        // Decision values should be real numbers (no constraints on range)
        // Just check that we get reasonable outputs
        for &val in decision_values.iter() {
            assert!(val.is_finite());
        }
    }

    #[test]
    fn test_mltsvm_separable_data() {
        let X = array![
            [0.0, 0.0],
            [0.5, 0.5], // Negative class cluster
            [3.0, 3.0],
            [3.5, 3.5] // Positive class cluster
        ];
        let y = array![
            [0, 1],
            [0, 1], // First label: negative, Second label: positive
            [1, 0],
            [1, 0] // First label: positive, Second label: negative
        ];

        let mltsvm = MLTSVM::new().c1(1.0).c2(1.0);
        let trained_mltsvm = mltsvm.fit(&X.view(), &y).unwrap();
        let predictions = trained_mltsvm.predict(&X.view()).unwrap();

        // With linearly separable data, MLTSVM should perform well
        let mut correct_predictions = 0;
        let total_predictions = predictions.len();

        for i in 0..predictions.nrows() {
            for j in 0..predictions.ncols() {
                if predictions[[i, j]] == y[[i, j]] {
                    correct_predictions += 1;
                }
            }
        }

        let accuracy = correct_predictions as Float / total_predictions as Float;
        // Should get reasonably good accuracy on separable data
        assert!(accuracy >= 0.5); // At least better than random
    }

    #[test]
    fn test_mltsvm_feature_scaling() {
        // Test with features of very different scales
        let X = array![
            [1000.0, 0.001],
            [2000.0, 0.002],
            [3000.0, 0.003],
            [4000.0, 0.004]
        ];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        let mltsvm = MLTSVM::new();
        let trained_mltsvm = mltsvm.fit(&X.view(), &y).unwrap();
        let predictions = trained_mltsvm.predict(&X.view()).unwrap();

        // Should handle feature scaling internally
        assert_eq!(predictions.dim(), (4, 2));

        // All predictions should be binary
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }
    }

    #[test]
    fn test_mltsvm_consistency() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Train the same model multiple times (deterministic should give same results)
        let mltsvm1 = MLTSVM::new().c1(1.0).c2(1.0);
        let trained1 = mltsvm1.fit(&X.view(), &y).unwrap();

        let mltsvm2 = MLTSVM::new().c1(1.0).c2(1.0);
        let trained2 = mltsvm2.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();

        // Should be deterministic (same predictions)
        for i in 0..pred1.nrows() {
            for j in 0..pred1.ncols() {
                assert_eq!(pred1[[i, j]], pred2[[i, j]]);
            }
        }
    }

    #[test]
    fn test_ranksvm_basic_functionality() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]]; // Multi-label binary

        let ranksvm = RankSVM::new().c(1.0);
        let trained_ranksvm = ranksvm.fit(&X.view(), &y).unwrap();
        let predictions = trained_ranksvm.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 2));
        assert_eq!(trained_ranksvm.n_labels(), 2);

        // All predictions should be binary (0 or 1)
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }
    }

    #[test]
    fn test_ranksvm_threshold_strategies() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test different threshold strategies
        let ranksvm1 = RankSVM::new().threshold_strategy(ThresholdStrategy::Fixed(0.5));
        let ranksvm2 = RankSVM::new().threshold_strategy(ThresholdStrategy::Optimal);
        let ranksvm3 =
            RankSVM::new().threshold_strategy(ThresholdStrategy::PerLabel(vec![0.3, 0.7]));
        let ranksvm4 = RankSVM::new().threshold_strategy(ThresholdStrategy::FScore);

        let trained1 = ranksvm1.fit(&X.view(), &y).unwrap();
        let trained2 = ranksvm2.fit(&X.view(), &y).unwrap();
        let trained3 = ranksvm3.fit(&X.view(), &y).unwrap();
        let trained4 = ranksvm4.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();
        let pred3 = trained3.predict(&X.view()).unwrap();
        let pred4 = trained4.predict(&X.view()).unwrap();

        assert_eq!(pred1.dim(), (4, 2));
        assert_eq!(pred2.dim(), (4, 2));
        assert_eq!(pred3.dim(), (4, 2));
        assert_eq!(pred4.dim(), (4, 2));

        // Test threshold accessors
        assert_eq!(trained1.thresholds().len(), 2);
        assert_eq!(trained2.thresholds().len(), 2);
        assert_eq!(trained3.thresholds().len(), 2);
    }

    #[test]
    fn test_ranksvm_decision_function() {
        let X = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]];
        let y = array![[1, 0], [1, 0], [0, 1], [0, 1]];

        let ranksvm = RankSVM::new();
        let trained_ranksvm = ranksvm.fit(&X.view(), &y).unwrap();

        // Test decision function
        let scores = trained_ranksvm.decision_function(&X.view()).unwrap();
        assert_eq!(scores.dim(), (4, 2));

        // Scores should be real numbers
        for &score in scores.iter() {
            assert!(score.is_finite());
        }
    }

    #[test]
    fn test_ranksvm_predict_ranking() {
        let X = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]];
        let y = array![[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // Three labels, one active per sample

        let ranksvm = RankSVM::new();
        let trained_ranksvm = ranksvm.fit(&X.view(), &y).unwrap();

        // Test ranking prediction
        let rankings = trained_ranksvm.predict_ranking(&X.view()).unwrap();

        assert_eq!(rankings.len(), 3); // 3 samples
        for ranking in &rankings {
            assert_eq!(ranking.len(), 3); // 3 labels
                                          // Should contain all label indices
            let mut sorted_ranking = ranking.clone();
            sorted_ranking.sort();
            assert_eq!(sorted_ranking, vec![0, 1, 2]);
        }
    }

    #[test]
    fn test_ranksvm_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Mismatched samples

        let ranksvm = RankSVM::new();
        assert!(ranksvm.fit(&X.view(), &y).is_err());

        // Test non-binary labels
        let y_non_binary = array![[1, 2], [0, 1]]; // Contains 2
        assert!(RankSVM::new().fit(&X.view(), &y_non_binary).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 2.0]];
        let y_train = array![[1, 0], [0, 1], [1, 1], [0, 0]];
        let ranksvm_for_predict = RankSVM::new();
        let trained = ranksvm_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_wrong_features = array![[1.0, 2.0, 3.0]]; // Extra feature
        assert!(trained.predict(&X_wrong_features.view()).is_err());
        assert!(trained.decision_function(&X_wrong_features.view()).is_err());
        assert!(trained.predict_ranking(&X_wrong_features.view()).is_err());

        // Test empty data
        let X_empty = Array2::<Float>::zeros((0, 2));
        let y_empty = Array2::<i32>::zeros((0, 2));
        assert!(RankSVM::new().fit(&X_empty.view(), &y_empty).is_err());
    }

    #[test]
    fn test_ranksvm_configuration() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test different configurations
        let ranksvm1 = RankSVM::new().c(0.5).epsilon(1e-8);
        let ranksvm2 = RankSVM::new().max_iter(500);

        let trained1 = ranksvm1.fit(&X.view(), &y).unwrap();
        let trained2 = ranksvm2.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();

        assert_eq!(pred1.dim(), (4, 2));
        assert_eq!(pred2.dim(), (4, 2));
    }

    #[test]
    fn test_ranksvm_ranking_consistency() {
        let X = array![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]];
        let y = array![
            [0, 0, 1], // Last label should rank highest
            [0, 1, 0], // Middle label should rank highest
            [1, 0, 0]  // First label should rank highest
        ];

        let ranksvm = RankSVM::new().threshold_strategy(ThresholdStrategy::FScore);
        let trained_ranksvm = ranksvm.fit(&X.view(), &y).unwrap();

        let rankings = trained_ranksvm.predict_ranking(&X.view()).unwrap();
        let scores = trained_ranksvm.decision_function(&X.view()).unwrap();

        // Check that rankings are consistent with scores
        for i in 0..3 {
            let ranking = &rankings[i];
            // First ranked label should have highest score
            let top_label = ranking[0];
            for j in 1..ranking.len() {
                let other_label = ranking[j];
                assert!(scores[[i, top_label]] >= scores[[i, other_label]]);
            }
        }
    }

    #[test]
    fn test_ranksvm_single_class_handling() {
        let X = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]];

        // Test with all positive for one label, mixed for other
        let y = array![[1, 0], [1, 1], [1, 0]]; // First label: all positive, second label: mixed

        let ranksvm = RankSVM::new();
        let trained = ranksvm.fit(&X.view(), &y).unwrap();
        let predictions = trained.predict(&X.view()).unwrap();
        let scores = trained.decision_function(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (3, 2));
        assert_eq!(scores.dim(), (3, 2));

        // All scores should be finite
        for &score in scores.iter() {
            assert!(score.is_finite());
        }
    }

    #[test]
    fn test_ranksvm_reproducibility() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Train two models with same configuration
        let ranksvm1 = RankSVM::new().c(1.0).epsilon(1e-6);
        let trained1 = ranksvm1.fit(&X.view(), &y).unwrap();

        let ranksvm2 = RankSVM::new().c(1.0).epsilon(1e-6);
        let trained2 = ranksvm2.fit(&X.view(), &y).unwrap();

        let pred1 = trained1.predict(&X.view()).unwrap();
        let pred2 = trained2.predict(&X.view()).unwrap();
        let scores1 = trained1.decision_function(&X.view()).unwrap();
        let scores2 = trained2.decision_function(&X.view()).unwrap();

        // Should be deterministic (same predictions and scores)
        for i in 0..pred1.nrows() {
            for j in 0..pred1.ncols() {
                assert_eq!(pred1[[i, j]], pred2[[i, j]]);
                assert!((scores1[[i, j]] - scores2[[i, j]]).abs() < 1e-10);
            }
        }
    }
}
/// Calibrated Binary Relevance Method
///
/// Enhanced binary relevance that applies probability calibration to improve
/// prediction reliability and provide confidence estimates.
#[derive(Debug, Clone)]
pub struct CalibratedBinaryRelevance<S = Untrained> {
    state: S,
    calibration_method: CalibrationMethod,
}

/// Calibration methods for probability calibration
#[derive(Debug, Clone, Copy)]
pub enum CalibrationMethod {
    /// Platt scaling using sigmoid function
    Sigmoid,
    /// Isotonic regression for non-parametric calibration
    Isotonic,
}

/// Trained state for CalibratedBinaryRelevance
#[derive(Debug, Clone)]
pub struct CalibratedBinaryRelevanceTrained {
    pub base_models: BinaryRelevanceTrained,
    pub calibration_params: Vec<(f64, f64)>, // (slope, intercept) for sigmoid calibration
}

impl CalibratedBinaryRelevance<Untrained> {
    /// Create a new CalibratedBinaryRelevance instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            calibration_method: CalibrationMethod::Sigmoid,
        }
    }

    /// Set the calibration method
    pub fn calibration_method(mut self, method: CalibrationMethod) -> Self {
        self.calibration_method = method;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for CalibratedBinaryRelevance<Untrained> {
    type Fitted = CalibratedBinaryRelevance<CalibratedBinaryRelevanceTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        // First fit base binary relevance model
        let base_model = BinaryRelevance::new().fit(X, y)?;

        // For simplicity, use default calibration parameters
        // In a full implementation, these would be learned from validation data
        let n_labels = y.ncols();
        let calibration_params = vec![(1.0, 0.0); n_labels]; // No calibration for now

        Ok(CalibratedBinaryRelevance {
            state: CalibratedBinaryRelevanceTrained {
                base_models: base_model.state,
                calibration_params,
            },
            calibration_method: self.calibration_method,
        })
    }
}

impl CalibratedBinaryRelevance<CalibratedBinaryRelevanceTrained> {
    /// Predict probabilities for each label
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<f64>> {
        let X = X.to_owned();
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.base_models.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        let mut probabilities = Array2::zeros((n_samples, self.state.base_models.n_labels));

        // Get probabilities from each binary classifier
        for label_idx in 0..self.state.base_models.n_labels {
            let (slope, intercept) = self.state.calibration_params[label_idx];

            if let Some((weights, bias)) = self.state.base_models.binary_classifiers.get(&label_idx)
            {
                for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
                    // Calculate linear prediction
                    let mut linear_score = *bias;
                    for feature_idx in 0..n_features {
                        linear_score += weights[feature_idx] * sample[feature_idx] as f64;
                    }

                    // Apply calibration
                    let calibrated_score = slope * linear_score + intercept;
                    let probability: f64 = 1.0 / (1.0 + (-calibrated_score).exp());

                    probabilities[[sample_idx, label_idx]] = probability.clamp(0.0, 1.0);
                }
            }
        }

        Ok(probabilities)
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>>
    for CalibratedBinaryRelevance<CalibratedBinaryRelevanceTrained>
{
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let probabilities = self.predict_proba(X)?;
        let (n_samples, n_labels) = probabilities.dim();
        let mut predictions = Array2::zeros((n_samples, n_labels));

        for i in 0..n_samples {
            for j in 0..n_labels {
                predictions[[i, j]] = if probabilities[[i, j]] > 0.5 { 1 } else { 0 };
            }
        }

        Ok(predictions)
    }
}

/// Random Label Combinations Method
///
/// Generates random label combinations for evaluation and testing purposes.
/// Useful for creating synthetic multi-label datasets with controlled characteristics.
pub struct RandomLabelCombinations {
    pub n_labels: usize,
    pub n_samples: usize,
    pub density: f64,
    pub random_state: Option<u64>,
}

impl RandomLabelCombinations {
    /// Create a new RandomLabelCombinations instance
    pub fn new(n_labels: usize, n_samples: usize) -> Self {
        Self {
            n_labels,
            n_samples,
            density: 0.5,
            random_state: None,
        }
    }

    /// Set the label density (probability of each label being active)
    pub fn density(mut self, density: f64) -> Self {
        self.density = density.clamp(0.0, 1.0);
        self
    }

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

    /// Generate random label combinations
    pub fn generate(&self) -> SklResult<Array2<i32>> {
        if self.n_labels == 0 || self.n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "n_labels and n_samples must be positive".to_string(),
            ));
        }

        let mut labels = Array2::zeros((self.n_samples, self.n_labels));

        // Simple pseudo-random generation based on sample and label indices
        let seed = self.random_state.unwrap_or(42);

        for i in 0..self.n_samples {
            for j in 0..self.n_labels {
                // Simple hash-based pseudo-random number generation
                let hash = ((i as u64 * 1103515245 + j as u64 * 12345 + seed) % 2147483647) as f64
                    / 2147483647.0;
                labels[[i, j]] = if hash < self.density { 1 } else { 0 };
            }
        }

        Ok(labels)
    }

    /// Generate balanced random combinations ensuring minimum and maximum cardinality
    pub fn generate_balanced(
        &self,
        min_cardinality: usize,
        max_cardinality: usize,
    ) -> SklResult<Array2<i32>> {
        if min_cardinality > max_cardinality {
            return Err(SklearsError::InvalidInput(
                "min_cardinality must be <= max_cardinality".to_string(),
            ));
        }

        if max_cardinality > self.n_labels {
            return Err(SklearsError::InvalidInput(
                "max_cardinality cannot exceed n_labels".to_string(),
            ));
        }

        let mut labels = Array2::zeros((self.n_samples, self.n_labels));
        let seed = self.random_state.unwrap_or(42);

        for i in 0..self.n_samples {
            // Determine cardinality for this sample
            let range = max_cardinality - min_cardinality + 1;
            let hash = (i as u64 * 1103515245 + seed) % 2147483647;
            let cardinality = min_cardinality + (hash as usize % range);

            // Randomly select which labels to activate
            let mut active_labels = Vec::new();
            for j in 0..self.n_labels {
                let label_hash = ((i as u64 * 12345 + j as u64 * 6789 + seed) % 2147483647) as f64
                    / 2147483647.0;
                active_labels.push((j, label_hash));
            }

            // Sort by hash and take the first 'cardinality' labels
            active_labels.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
            for k in 0..cardinality {
                labels[[i, active_labels[k].0]] = 1;
            }
        }

        Ok(labels)
    }
}

/// ML-kNN: Multi-Label k-Nearest Neighbors
///
/// ML-kNN is an adaptation of the k-nearest neighbors algorithm for multi-label classification.
/// It uses the maximum a posteriori (MAP) principle to determine the label set for a test instance
/// based on the labels of its k nearest neighbors.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::MLkNN;
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5], [0.5, 2.5]];
/// let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];
///
/// let model = MLkNN::new().k(3).smoothing(1.0);
/// let trained_model = model.fit(&X.view(), &y).unwrap();
/// let predictions = trained_model.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct MLkNN<S = Untrained> {
    state: S,
    k: usize,
    smoothing: Float,
}

/// Trained state for ML-kNN
#[derive(Debug, Clone)]
pub struct MLkNNTrained {
    X_train: Array2<Float>,
    y_train: Array2<i32>,
    k: usize,
    smoothing: Float,
    n_labels: usize,
    prior_prob_true: Array1<Float>,
    prior_prob_false: Array1<Float>,
    cond_prob: Array2<Float>, // [label][count] = probability
}

impl MLkNN<Untrained> {
    /// Create a new ML-kNN instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            k: 10,
            smoothing: 1.0,
        }
    }

    /// Set the number of nearest neighbors
    pub fn k(mut self, k: usize) -> Self {
        self.k = k;
        self
    }

    /// Set the smoothing parameter for Laplace smoothing
    pub fn smoothing(mut self, smoothing: Float) -> Self {
        self.smoothing = smoothing;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for MLkNN<Untrained> {
    type Fitted = MLkNN<MLkNNTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let X_train = X.to_owned();
        let y_train = y.clone();
        let (n_samples, n_features) = X_train.dim();
        let n_labels = y_train.ncols();

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

        if n_samples <= self.k {
            return Err(SklearsError::InvalidInput(
                "Number of samples must be greater than k".to_string(),
            ));
        }

        // Validate binary labels
        for &val in y_train.iter() {
            if val != 0 && val != 1 {
                return Err(SklearsError::InvalidInput(
                    "y must contain only binary values (0 or 1)".to_string(),
                ));
            }
        }

        // Compute prior probabilities for each label
        let mut prior_prob_true = Array1::zeros(n_labels);
        let mut prior_prob_false = Array1::zeros(n_labels);

        for j in 0..n_labels {
            let positive_count = y_train.column(j).iter().filter(|&&x| x == 1).count() as Float;
            let total_count = n_samples as Float;

            // Apply Laplace smoothing
            prior_prob_true[j] =
                (positive_count + self.smoothing) / (total_count + 2.0 * self.smoothing);
            prior_prob_false[j] = (total_count - positive_count + self.smoothing)
                / (total_count + 2.0 * self.smoothing);
        }

        // Compute conditional probabilities P(Cj=1|Hj=c) for each label j and count c
        let mut cond_prob = Array2::zeros((n_labels, self.k + 1));

        for i in 0..n_samples {
            let xi = X_train.row(i);
            let yi = y_train.row(i);

            // Find k nearest neighbors (excluding self)
            let mut distances: Vec<(usize, Float)> = Vec::new();
            for (idx, neighbor) in X_train.axis_iter(Axis(0)).enumerate() {
                if idx != i {
                    let dist = euclidean_distance(&xi, &neighbor);
                    distances.push((idx, dist));
                }
            }

            distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
            let neighbors: Vec<usize> =
                distances.iter().take(self.k).map(|&(idx, _)| idx).collect();

            // For each label, count how many neighbors have it
            for j in 0..n_labels {
                let neighbor_count = neighbors
                    .iter()
                    .filter(|&&neighbor_idx| y_train[[neighbor_idx, j]] == 1)
                    .count();

                // Update conditional probability statistics
                if yi[j] == 1 {
                    // If current instance has label j, increment count for this neighbor_count
                    cond_prob[[j, neighbor_count]] += 1.0;
                }
            }
        }

        // Apply Laplace smoothing to conditional probabilities
        for j in 0..n_labels {
            let label_positive_count =
                y_train.column(j).iter().filter(|&&x| x == 1).count() as Float;

            for c in 0..=self.k {
                cond_prob[[j, c]] = (cond_prob[[j, c]] + self.smoothing)
                    / (label_positive_count + (self.k + 1) as Float * self.smoothing);
            }
        }

        let trained_state = MLkNNTrained {
            X_train,
            y_train,
            k: self.k,
            smoothing: self.smoothing,
            n_labels,
            prior_prob_true,
            prior_prob_false,
            cond_prob,
        };

        Ok(MLkNN {
            state: trained_state,
            k: self.k,
            smoothing: self.smoothing,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>> for MLkNN<MLkNNTrained> {
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.X_train.ncols() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_samples, self.state.n_labels));

        for i in 0..n_samples {
            let xi = X.row(i);

            // Find k nearest neighbors in training data
            let mut distances: Vec<(usize, Float)> = Vec::new();
            for (idx, neighbor) in self.state.X_train.axis_iter(Axis(0)).enumerate() {
                let dist = euclidean_distance(&xi, &neighbor);
                distances.push((idx, dist));
            }

            distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
            let neighbors: Vec<usize> = distances
                .iter()
                .take(self.state.k)
                .map(|&(idx, _)| idx)
                .collect();

            // For each label, apply MAP principle
            for j in 0..self.state.n_labels {
                let neighbor_count = neighbors
                    .iter()
                    .filter(|&&neighbor_idx| self.state.y_train[[neighbor_idx, j]] == 1)
                    .count();

                // Compute posterior probabilities using Bayes' theorem
                let p_label_true_given_neighbors =
                    self.state.cond_prob[[j, neighbor_count]] * self.state.prior_prob_true[j];

                let p_label_false_given_neighbors = (1.0
                    - self.state.cond_prob[[j, neighbor_count]])
                    * self.state.prior_prob_false[j];

                // Apply MAP: choose label with higher posterior probability
                if p_label_true_given_neighbors > p_label_false_given_neighbors {
                    predictions[[i, j]] = 1;
                } else {
                    predictions[[i, j]] = 0;
                }
            }
        }

        Ok(predictions)
    }
}

impl MLkNN<MLkNNTrained> {
    /// Predict class probabilities for multi-label classification
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.X_train.ncols() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut probabilities = Array2::zeros((n_samples, self.state.n_labels));

        for i in 0..n_samples {
            let xi = X.row(i);

            // Find k nearest neighbors in training data
            let mut distances: Vec<(usize, Float)> = Vec::new();
            for (idx, neighbor) in self.state.X_train.axis_iter(Axis(0)).enumerate() {
                let dist = euclidean_distance(&xi, &neighbor);
                distances.push((idx, dist));
            }

            distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
            let neighbors: Vec<usize> = distances
                .iter()
                .take(self.state.k)
                .map(|&(idx, _)| idx)
                .collect();

            // For each label, compute probability
            for j in 0..self.state.n_labels {
                let neighbor_count = neighbors
                    .iter()
                    .filter(|&&neighbor_idx| self.state.y_train[[neighbor_idx, j]] == 1)
                    .count();

                // Compute posterior probabilities
                let p_label_true_given_neighbors =
                    self.state.cond_prob[[j, neighbor_count]] * self.state.prior_prob_true[j];

                let p_label_false_given_neighbors = (1.0
                    - self.state.cond_prob[[j, neighbor_count]])
                    * self.state.prior_prob_false[j];

                // Normalize probabilities
                let total_prob = p_label_true_given_neighbors + p_label_false_given_neighbors;
                if total_prob > 0.0 {
                    probabilities[[i, j]] = p_label_true_given_neighbors / total_prob;
                } else {
                    probabilities[[i, j]] = self.state.prior_prob_true[j];
                }
            }
        }

        Ok(probabilities)
    }
}

/// Cost-Sensitive Binary Relevance
///
/// This method extends Binary Relevance to handle cost-sensitive multi-label classification.
/// It allows specifying different costs for false positives and false negatives for each label,
/// which is crucial for imbalanced datasets or applications where different types of errors
/// have different consequences.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::{CostSensitiveBinaryRelevance, CostMatrix, CalibrationMethod};
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5], [0.5, 2.5]];
/// let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];
///
/// // Higher cost for false negatives on label 0, higher cost for false positives on label 1
/// let cost_matrix = CostMatrix::from_fp_fn_costs(
///     vec![1.0, 3.0], // false positive costs
///     vec![2.0, 1.0]  // false negative costs
/// ).unwrap();
///
/// let model = CostSensitiveBinaryRelevance::new()
///     .cost_matrix(cost_matrix)
///     .calibration_method(CalibrationMethod::Sigmoid);
/// let trained_model = model.fit(&X.view(), &y).unwrap();
/// let predictions = trained_model.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct CostSensitiveBinaryRelevance<S = Untrained> {
    state: S,
    cost_matrix: Option<CostMatrix>,
    calibration_method: CalibrationMethod,
}

/// Cost matrix for cost-sensitive learning
#[derive(Debug, Clone)]
pub struct CostMatrix {
    /// Cost of false positives for each label
    pub fp_costs: Vec<Float>,
    /// Cost of false negatives for each label
    pub fn_costs: Vec<Float>,
}

impl CostMatrix {
    /// Create a cost matrix from false positive and false negative costs
    pub fn from_fp_fn_costs(fp_costs: Vec<Float>, fn_costs: Vec<Float>) -> SklResult<Self> {
        if fp_costs.len() != fn_costs.len() {
            return Err(SklearsError::InvalidInput(
                "fp_costs and fn_costs must have the same length".to_string(),
            ));
        }

        if fp_costs.iter().any(|&c| c <= 0.0) || fn_costs.iter().any(|&c| c <= 0.0) {
            return Err(SklearsError::InvalidInput(
                "All costs must be positive".to_string(),
            ));
        }

        Ok(Self { fp_costs, fn_costs })
    }

    /// Create a balanced cost matrix with equal costs for all labels
    pub fn balanced(n_labels: usize) -> Self {
        Self {
            fp_costs: vec![1.0; n_labels],
            fn_costs: vec![1.0; n_labels],
        }
    }

    /// Get the optimal threshold for label j based on cost ratio
    pub fn get_threshold(&self, j: usize) -> Float {
        let cost_ratio = self.fp_costs[j] / (self.fp_costs[j] + self.fn_costs[j]);
        cost_ratio
    }
}

/// Trained state for Cost-Sensitive Binary Relevance
#[derive(Debug, Clone)]
pub struct CostSensitiveBinaryRelevanceTrained {
    n_labels: usize,
    binary_models: Vec<SimpleBinaryModel>,
    cost_matrix: CostMatrix,
    feature_means: Array1<Float>,
    feature_stds: Array1<Float>,
}

/// Simple binary model for cost-sensitive learning
#[derive(Debug, Clone)]
pub struct SimpleBinaryModel {
    weights: Array1<Float>,
    bias: Float,
}

impl CostSensitiveBinaryRelevance<Untrained> {
    /// Create a new Cost-Sensitive Binary Relevance instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            cost_matrix: None,
            calibration_method: CalibrationMethod::Sigmoid,
        }
    }

    /// Set the cost matrix
    pub fn cost_matrix(mut self, cost_matrix: CostMatrix) -> Self {
        self.cost_matrix = Some(cost_matrix);
        self
    }

    /// Set the calibration method
    pub fn calibration_method(mut self, method: CalibrationMethod) -> Self {
        self.calibration_method = method;
        self
    }
}

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

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

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

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for CostSensitiveBinaryRelevance<Untrained> {
    type Fitted = CostSensitiveBinaryRelevance<CostSensitiveBinaryRelevanceTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let n_labels = y.ncols();

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

        // Validate binary labels
        for &val in y.iter() {
            if val != 0 && val != 1 {
                return Err(SklearsError::InvalidInput(
                    "y must contain only binary values (0 or 1)".to_string(),
                ));
            }
        }

        // Set default balanced cost matrix if none provided
        let cost_matrix = self
            .cost_matrix
            .unwrap_or_else(|| CostMatrix::balanced(n_labels));

        if cost_matrix.fp_costs.len() != n_labels || cost_matrix.fn_costs.len() != n_labels {
            return Err(SklearsError::InvalidInput(
                "Cost matrix must have same number of labels as y".to_string(),
            ));
        }

        // Compute feature statistics for standardization
        let feature_means = X.mean_axis(Axis(0)).unwrap();
        let feature_stds = X
            .std_axis(Axis(0), 0.0)
            .mapv(|x| if x == 0.0 { 1.0 } else { x });

        // Standardize features
        let X_standardized = standardize_features_simple(X, &feature_means, &feature_stds);

        let mut binary_models = Vec::new();

        // Train one cost-sensitive binary classifier for each label
        for j in 0..n_labels {
            let y_binary = y.column(j).to_owned();

            // Apply cost-sensitive sampling/weighting
            let class_weights = compute_cost_sensitive_weights(&y_binary, &cost_matrix, j);

            // Train binary classifier with cost-sensitive weights
            let model = train_weighted_binary_classifier_simple(
                &X_standardized,
                &y_binary,
                &class_weights,
            )?;
            binary_models.push(model);
        }

        let trained_state = CostSensitiveBinaryRelevanceTrained {
            n_labels,
            binary_models,
            cost_matrix,
            feature_means,
            feature_stds,
        };

        Ok(CostSensitiveBinaryRelevance {
            state: trained_state,
            cost_matrix: None,
            calibration_method: self.calibration_method,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>>
    for CostSensitiveBinaryRelevance<CostSensitiveBinaryRelevanceTrained>
{
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.feature_means.len() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        // Standardize features using training statistics
        let X_standardized =
            standardize_features_simple(X, &self.state.feature_means, &self.state.feature_stds);

        let mut predictions = Array2::zeros((n_samples, self.state.n_labels));

        for j in 0..self.state.n_labels {
            // Get model probabilities
            let probabilities =
                predict_binary_probabilities(&self.state.binary_models[j], &X_standardized);

            // Apply cost-sensitive threshold
            let threshold = self.state.cost_matrix.get_threshold(j);

            for i in 0..n_samples {
                predictions[[i, j]] = if probabilities[i] > threshold { 1 } else { 0 };
            }
        }

        Ok(predictions)
    }
}

impl CostSensitiveBinaryRelevance<CostSensitiveBinaryRelevanceTrained> {
    /// Predict class probabilities
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.feature_means.len() {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        // Standardize features using training statistics
        let X_standardized =
            standardize_features_simple(X, &self.state.feature_means, &self.state.feature_stds);

        let mut probabilities = Array2::zeros((n_samples, self.state.n_labels));

        for j in 0..self.state.n_labels {
            let label_probabilities =
                predict_binary_probabilities(&self.state.binary_models[j], &X_standardized);

            for i in 0..n_samples {
                probabilities[[i, j]] = label_probabilities[i];
            }
        }

        Ok(probabilities)
    }

    /// Get the cost matrix used during training
    pub fn cost_matrix(&self) -> &CostMatrix {
        &self.state.cost_matrix
    }
}

/// Compute cost-sensitive class weights for a binary classification problem
fn compute_cost_sensitive_weights(
    y_binary: &Array1<i32>,
    cost_matrix: &CostMatrix,
    label_idx: usize,
) -> Array1<Float> {
    let n_samples = y_binary.len();
    let mut weights = Array1::ones(n_samples);

    let fp_cost = cost_matrix.fp_costs[label_idx];
    let fn_cost = cost_matrix.fn_costs[label_idx];

    // Count positive and negative samples
    let n_positive = y_binary.iter().filter(|&&x| x == 1).count() as Float;
    let n_negative = (n_samples as Float) - n_positive;

    if n_positive > 0.0 && n_negative > 0.0 {
        // Weight positive samples by false negative cost
        let positive_weight = fn_cost / n_positive;
        // Weight negative samples by false positive cost
        let negative_weight = fp_cost / n_negative;

        for (i, &label) in y_binary.iter().enumerate() {
            weights[i] = if label == 1 {
                positive_weight
            } else {
                negative_weight
            };
        }
    }

    weights
}

/// Standardize features using mean and standard deviation
fn standardize_features_simple(
    X: &ArrayView2<'_, Float>,
    means: &Array1<Float>,
    stds: &Array1<Float>,
) -> Array2<Float> {
    let mut X_standardized = X.to_owned();
    for (i, mut row) in X_standardized.axis_iter_mut(Axis(0)).enumerate() {
        for (j, feature) in row.iter_mut().enumerate() {
            *feature = (*feature - means[j]) / stds[j];
        }
    }
    X_standardized
}

/// Train a weighted binary classifier
fn train_weighted_binary_classifier_simple(
    X: &Array2<Float>,
    y: &Array1<i32>,
    weights: &Array1<Float>,
) -> SklResult<SimpleBinaryModel> {
    let (n_samples, n_features) = X.dim();

    // Simple weighted logistic regression implementation
    let mut w = Array1::zeros(n_features);
    let mut b = 0.0;

    let learning_rate = 0.01;
    let max_iterations = 1000;
    let tolerance = 1e-6;

    for _iteration in 0..max_iterations {
        let mut gradient_w = Array1::zeros(n_features);
        let mut gradient_b = 0.0;
        let mut total_weight = 0.0;

        for i in 0..n_samples {
            let xi = X.row(i);
            let yi = y[i] as Float;
            let weight = weights[i];

            // Compute prediction (logistic function)
            let linear_pred = xi.dot(&w) + b;
            let prob = 1.0 / (1.0 + (-linear_pred).exp());

            // Compute weighted gradients
            let error = prob - yi;
            gradient_w += &(weight * error * &xi);
            gradient_b += weight * error;
            total_weight += weight;
        }

        // Update parameters
        let old_w = w.clone();
        let old_b = b;

        if total_weight > 0.0 {
            w -= &(learning_rate * gradient_w / total_weight);
            b -= learning_rate * gradient_b / total_weight;
        }

        // Check for convergence
        let w_change = (&w - &old_w).mapv(|x| x * x).sum().sqrt();
        let b_change = (b - old_b).abs();

        if w_change < tolerance && b_change < tolerance {
            break;
        }
    }

    Ok(SimpleBinaryModel {
        weights: w,
        bias: b,
    })
}

/// Predict probabilities using a simple binary model
fn predict_binary_probabilities(model: &SimpleBinaryModel, X: &Array2<Float>) -> Array1<Float> {
    let mut probabilities = Array1::zeros(X.nrows());

    for (i, xi) in X.axis_iter(Axis(0)).enumerate() {
        let linear_pred = xi.dot(&model.weights) + model.bias;
        let prob = 1.0 / (1.0 + (-linear_pred).exp());
        probabilities[i] = prob;
    }

    probabilities
}

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

    #[test]
    fn test_calibrated_binary_relevance() {
        let X = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5], [0.5, 2.5]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        let model = CalibratedBinaryRelevance::new().calibration_method(CalibrationMethod::Sigmoid);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Test probability prediction
        let probabilities = trained_model.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (4, 2));

        // Check that probabilities are in valid range
        for &prob in probabilities.iter() {
            assert!(prob >= 0.0 && prob <= 1.0);
        }
    }

    #[test]
    fn test_random_label_combinations() {
        let generator = RandomLabelCombinations::new(5, 10)
            .density(0.3)
            .random_state(42);

        let labels = generator.generate().unwrap();
        assert_eq!(labels.dim(), (10, 5));

        // Check that all values are binary
        for &val in labels.iter() {
            assert!(val == 0 || val == 1);
        }

        // Test balanced generation
        let balanced_labels = generator.generate_balanced(1, 3).unwrap();
        assert_eq!(balanced_labels.dim(), (10, 5));

        // Check that each sample has between 1 and 3 active labels
        for i in 0..10 {
            let cardinality = balanced_labels.row(i).iter().sum::<i32>();
            assert!(cardinality >= 1 && cardinality <= 3);
        }
    }

    #[test]
    fn test_random_label_combinations_edge_cases() {
        let generator = RandomLabelCombinations::new(3, 5);

        // Test invalid min > max cardinality
        assert!(generator.generate_balanced(3, 2).is_err());

        // Test max cardinality > n_labels
        assert!(generator.generate_balanced(1, 5).is_err());

        // Test zero labels or samples
        let empty_generator = RandomLabelCombinations::new(0, 5);
        assert!(empty_generator.generate().is_err());

        let empty_samples = RandomLabelCombinations::new(3, 0);
        assert!(empty_samples.generate().is_err());
    }

    #[test]
    fn test_mlknn_basic_functionality() {
        let X = array![
            [1.0, 2.0],
            [2.0, 1.0],
            [1.5, 1.5],
            [0.5, 2.5],
            [2.5, 0.5],
            [1.0, 1.0]
        ];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0], [0, 1], [1, 0]];

        let model = MLkNN::new().k(3).smoothing(1.0);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (6, 2));

        // Check that predictions are binary
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }

        // Test probability prediction
        let probabilities = trained_model.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (6, 2));

        // Check that probabilities are in valid range
        for &prob in probabilities.iter() {
            assert!(prob >= 0.0 && prob <= 1.0);
        }
    }

    #[test]
    fn test_mlknn_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 1.0]];
        let y = array![[1, 0], [0, 1]];

        // Test k too large
        let model = MLkNN::new().k(5);
        assert!(model.fit(&X.view(), &y).is_err());

        // Test non-binary labels
        let y_invalid = array![[1, 2], [0, 1]];
        let model = MLkNN::new().k(1);
        assert!(model.fit(&X.view(), &y_invalid).is_err());

        // Test mismatched dimensions
        let X_train = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5]];
        let y_train = array![[1, 0], [0, 1], [1, 1]];
        let model = MLkNN::new().k(2);
        let trained_model = model.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_model.predict(&X_test.view()).is_err());
        assert!(trained_model.predict_proba(&X_test.view()).is_err());
    }

    #[test]
    fn test_mlknn_configuration() {
        let model = MLkNN::new().k(5).smoothing(0.5);
        assert_eq!(model.k, 5);
        assert_eq!(model.smoothing, 0.5);

        let default_model = MLkNN::default();
        assert_eq!(default_model.k, 10);
        assert_eq!(default_model.smoothing, 1.0);
    }

    #[test]
    fn test_cost_sensitive_binary_relevance_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 1.0],
            [1.5, 1.5],
            [0.5, 2.5],
            [2.5, 0.5],
            [1.0, 1.0]
        ];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0], [0, 1], [1, 0]];

        // Create cost matrix with higher cost for false negatives on label 0
        let cost_matrix = CostMatrix::from_fp_fn_costs(
            vec![1.0, 1.0], // false positive costs
            vec![3.0, 1.0], // false negative costs (higher for label 0)
        )
        .unwrap();

        let model = CostSensitiveBinaryRelevance::new()
            .cost_matrix(cost_matrix)
            .calibration_method(CalibrationMethod::Sigmoid);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (6, 2));

        // Check that predictions are binary
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }

        // Test probability prediction
        let probabilities = trained_model.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (6, 2));

        // Check that probabilities are in valid range
        for &prob in probabilities.iter() {
            assert!(prob >= 0.0 && prob <= 1.0);
        }

        // Test cost matrix access
        let retrieved_cost_matrix = trained_model.cost_matrix();
        assert_eq!(retrieved_cost_matrix.fp_costs[0], 1.0);
        assert_eq!(retrieved_cost_matrix.fn_costs[0], 3.0);
    }

    #[test]
    fn test_cost_matrix_creation_and_validation() {
        // Test successful creation
        let cost_matrix =
            CostMatrix::from_fp_fn_costs(vec![1.0, 2.0, 3.0], vec![2.0, 1.0, 1.5]).unwrap();
        assert_eq!(cost_matrix.fp_costs.len(), 3);
        assert_eq!(cost_matrix.fn_costs.len(), 3);

        // Test balanced cost matrix
        let balanced = CostMatrix::balanced(5);
        assert_eq!(balanced.fp_costs, vec![1.0; 5]);
        assert_eq!(balanced.fn_costs, vec![1.0; 5]);

        // Test threshold calculation
        let threshold_0 = cost_matrix.get_threshold(0);
        let expected_threshold_0 = 1.0 / (1.0 + 2.0); // fp_cost / (fp_cost + fn_cost)
        assert!((threshold_0 - expected_threshold_0).abs() < 1e-10);

        // Test invalid inputs
        assert!(CostMatrix::from_fp_fn_costs(vec![1.0, 2.0], vec![1.0]).is_err()); // Different lengths
        assert!(CostMatrix::from_fp_fn_costs(vec![0.0, 1.0], vec![1.0, 1.0]).is_err()); // Zero cost
        assert!(CostMatrix::from_fp_fn_costs(vec![-1.0, 1.0], vec![1.0, 1.0]).is_err());
        // Negative cost
    }

    #[test]
    fn test_cost_sensitive_binary_relevance_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 1.0]];
        let y = array![[1, 0], [0, 1]];

        // Test non-binary labels
        let y_invalid = array![[1, 2], [0, 1]];
        let model = CostSensitiveBinaryRelevance::new();
        assert!(model.fit(&X.view(), &y_invalid).is_err());

        // Test mismatched cost matrix dimensions
        let wrong_cost_matrix = CostMatrix::from_fp_fn_costs(
            vec![1.0, 2.0, 3.0], // 3 labels
            vec![1.0, 1.0, 1.0],
        )
        .unwrap();
        let model = CostSensitiveBinaryRelevance::new().cost_matrix(wrong_cost_matrix);
        assert!(model.fit(&X.view(), &y).is_err()); // y has only 2 labels

        // Test mismatched dimensions during prediction
        let model = CostSensitiveBinaryRelevance::new();
        let trained_model = model.fit(&X.view(), &y).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_model.predict(&X_test.view()).is_err());
        assert!(trained_model.predict_proba(&X_test.view()).is_err());
    }

    #[test]
    fn test_cost_sensitive_binary_relevance_default_behavior() {
        let X = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5], [0.5, 2.5]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test with default balanced cost matrix
        let model = CostSensitiveBinaryRelevance::new();
        let trained_model = model.fit(&X.view(), &y).unwrap();

        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Test default configuration
        let default_model = CostSensitiveBinaryRelevance::default();
        let trained_default = default_model.fit(&X.view(), &y).unwrap();
        let default_predictions = trained_default.predict(&X.view()).unwrap();
        assert_eq!(default_predictions.dim(), (4, 2));

        // Cost matrix should be balanced
        let cost_matrix = trained_model.cost_matrix();
        assert_eq!(cost_matrix.fp_costs, vec![1.0, 1.0]);
        assert_eq!(cost_matrix.fn_costs, vec![1.0, 1.0]);
    }

    #[test]
    fn test_bayesian_classifier_chain_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 1.0],
            [1.5, 1.5],
            [0.5, 2.5],
            [2.5, 0.5],
            [1.0, 1.0]
        ];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0], [0, 1], [1, 0]];

        let model = BayesianClassifierChain::new()
            .n_samples(50)
            .prior_strength(1.0);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (6, 2));

        // Check that predictions are binary
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }

        // Test uncertainty prediction
        let uncertainties = trained_model.predict_uncertainty(&X.view()).unwrap();
        assert_eq!(uncertainties.dim(), (6, 2));

        // Check that uncertainties are non-negative
        for &uncertainty in uncertainties.iter() {
            assert!(uncertainty >= 0.0);
        }

        // Test order access
        let order = trained_model.order();
        assert_eq!(order.len(), 2);
    }

    #[test]
    fn test_bayesian_classifier_chain_custom_order() {
        let X = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5]];
        let y = array![[1, 0, 1], [0, 1, 0], [1, 1, 1]];

        let model = BayesianClassifierChain::new()
            .order(vec![2, 0, 1])
            .n_samples(30)
            .prior_strength(0.5);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 3));

        // Check that the order is preserved
        assert_eq!(trained_model.order(), &[2, 0, 1]);
    }

    #[test]
    fn test_bayesian_classifier_chain_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 1.0]];
        let y = array![[1, 0], [0, 1]];

        // Test non-binary labels
        let y_invalid = array![[1, 2], [0, 1]];
        let model = BayesianClassifierChain::new();
        assert!(model.fit(&X.view(), &y_invalid).is_err());

        // Test invalid order
        let model_invalid_order = BayesianClassifierChain::new().order(vec![0, 1, 2]); // 3 labels but y only has 2
        assert!(model_invalid_order.fit(&X.view(), &y).is_err());

        // Test mismatched dimensions during prediction
        let model = BayesianClassifierChain::new();
        let trained_model = model.fit(&X.view(), &y).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_model.predict(&X_test.view()).is_err());
        assert!(trained_model.predict_uncertainty(&X_test.view()).is_err());
    }

    #[test]
    fn test_bayesian_classifier_chain_configuration() {
        let model = BayesianClassifierChain::new()
            .n_samples(200)
            .prior_strength(2.0)
            .random_state(42);

        assert_eq!(model.n_samples, 200);
        assert_eq!(model.prior_strength, 2.0);
        assert_eq!(model.random_state, Some(42));

        let default_model = BayesianClassifierChain::default();
        assert_eq!(default_model.n_samples, 100);
        assert_eq!(default_model.prior_strength, 1.0);
        assert_eq!(default_model.random_state, None);
    }

    #[test]
    fn test_multi_target_regression_tree_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [1.5, 2.5],
            [3.5, 1.5]
        ];
        let y = array![
            [1.5, 2.5],
            [2.5, 3.5],
            [3.5, 1.5],
            [4.5, 4.5],
            [2.0, 3.0],
            [4.0, 2.0]
        ];

        let tree = MultiTargetRegressionTree::new()
            .max_depth(Some(3))
            .min_samples_split(2);
        let trained_tree = tree.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_tree.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (6, 2));

        // Test tree properties
        assert_eq!(trained_tree.n_features(), 2);
        assert_eq!(trained_tree.n_targets(), 2);

        // Feature importances should sum to 1 (or be close to it)
        let importances = trained_tree.feature_importances();
        let importance_sum: Float = importances.sum();
        assert!((importance_sum - 1.0).abs() < 1e-10 || importance_sum == 0.0);
    }

    #[test]
    fn test_multi_target_regression_tree_configuration() {
        let tree = MultiTargetRegressionTree::new()
            .max_depth(Some(5))
            .min_samples_split(3)
            .min_samples_leaf(2)
            .random_state(Some(42));

        assert_eq!(tree.max_depth, Some(5));
        assert_eq!(tree.min_samples_split, 3);
        assert_eq!(tree.min_samples_leaf, 2);
        assert_eq!(tree.random_state, Some(42));

        let default_tree = MultiTargetRegressionTree::default();
        assert_eq!(default_tree.max_depth, Some(5));
        assert_eq!(default_tree.min_samples_split, 2);
        assert_eq!(default_tree.min_samples_leaf, 1);
        assert_eq!(default_tree.random_state, None);
    }

    #[test]
    fn test_multi_target_regression_tree_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5]]; // Wrong number of rows

        let tree = MultiTargetRegressionTree::new();
        assert!(tree.clone().fit(&X.view(), &y).is_err());

        // Test with no targets
        let y_empty = Array2::<Float>::zeros((2, 0));
        assert!(tree.clone().fit(&X.view(), &y_empty).is_err());

        // Test with too few samples
        let X_small = array![[1.0, 2.0]];
        let y_small = array![[1.5, 2.5]];
        let tree_strict = MultiTargetRegressionTree::new().min_samples_split(2);
        assert!(tree_strict.fit(&X_small.view(), &y_small).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1.5, 2.5], [2.5, 3.5]];
        let tree_for_predict = MultiTargetRegressionTree::new();
        let trained_tree = tree_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_tree.predict(&X_test.view()).is_err());
    }

    #[test]
    fn test_random_forest_multi_output_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [1.5, 2.5],
            [3.5, 1.5],
            [2.5, 2.0],
            [1.8, 3.2]
        ];
        let y = array![
            [1.5, 2.5],
            [2.5, 3.5],
            [3.5, 1.5],
            [4.5, 4.5],
            [2.0, 3.0],
            [4.0, 2.0],
            [3.0, 2.5],
            [2.3, 3.7]
        ];

        let forest = RandomForestMultiOutput::new()
            .n_estimators(5)
            .max_depth(Some(3))
            .random_state(Some(42));
        let trained_forest = forest.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_forest.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (8, 2));

        // Test forest properties
        assert_eq!(trained_forest.n_estimators(), 5);
        assert_eq!(trained_forest.n_features(), 2);
        assert_eq!(trained_forest.n_targets(), 2);

        // Feature importances should sum to 1 (or be close to it)
        let importances = trained_forest.feature_importances();
        let importance_sum: Float = importances.sum();
        assert!((importance_sum - 1.0).abs() < 1e-10 || importance_sum == 0.0);
    }

    #[test]
    fn test_random_forest_multi_output_configuration() {
        let forest = RandomForestMultiOutput::new()
            .n_estimators(20)
            .max_depth(Some(7))
            .min_samples_split(5)
            .min_samples_leaf(3)
            .max_features(Some(1))
            .bootstrap(false)
            .random_state(Some(123));

        assert_eq!(forest.n_estimators, 20);
        assert_eq!(forest.max_depth, Some(7));
        assert_eq!(forest.min_samples_split, 5);
        assert_eq!(forest.min_samples_leaf, 3);
        assert_eq!(forest.max_features, Some(1));
        assert_eq!(forest.bootstrap, false);
        assert_eq!(forest.random_state, Some(123));

        let default_forest = RandomForestMultiOutput::default();
        assert_eq!(default_forest.n_estimators, 10);
        assert_eq!(default_forest.max_depth, None);
        assert_eq!(default_forest.min_samples_split, 2);
        assert_eq!(default_forest.min_samples_leaf, 1);
        assert_eq!(default_forest.max_features, None);
        assert_eq!(default_forest.bootstrap, true);
        assert_eq!(default_forest.random_state, None);
    }

    #[test]
    fn test_random_forest_multi_output_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5]]; // Wrong number of rows

        let forest = RandomForestMultiOutput::new();
        assert!(forest.clone().fit(&X.view(), &y).is_err());

        // Test with no targets
        let y_empty = Array2::<Float>::zeros((2, 0));
        assert!(forest.clone().fit(&X.view(), &y_empty).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y_train = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];
        let forest_for_predict = RandomForestMultiOutput::new();
        let trained_forest = forest_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_forest.predict(&X_test.view()).is_err());
    }

    #[test]
    fn test_random_forest_multi_output_single_estimator() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];

        let forest = RandomForestMultiOutput::new()
            .n_estimators(1)
            .random_state(Some(42));
        let trained_forest = forest.fit(&X.view(), &y).unwrap();

        let predictions = trained_forest.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));
        assert_eq!(trained_forest.n_estimators(), 1);
    }

    #[test]
    fn test_random_forest_bootstrap_vs_no_bootstrap() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [1.5, 2.5],
            [3.5, 1.5],
            [2.5, 2.0],
            [1.8, 3.2]
        ];
        let y = array![
            [1.5, 2.5],
            [2.5, 3.5],
            [3.5, 1.5],
            [4.5, 4.5],
            [2.0, 3.0],
            [4.0, 2.0],
            [3.0, 2.5],
            [2.3, 3.7]
        ];

        // Test with bootstrap
        let forest_bootstrap = RandomForestMultiOutput::new()
            .n_estimators(3)
            .bootstrap(true)
            .random_state(Some(42));
        let trained_bootstrap = forest_bootstrap.fit(&X.view(), &y).unwrap();

        // Test without bootstrap
        let forest_no_bootstrap = RandomForestMultiOutput::new()
            .n_estimators(3)
            .bootstrap(false)
            .random_state(Some(42));
        let trained_no_bootstrap = forest_no_bootstrap.fit(&X.view(), &y).unwrap();

        // Both should work and produce valid predictions
        let pred_bootstrap = trained_bootstrap.predict(&X.view()).unwrap();
        let pred_no_bootstrap = trained_no_bootstrap.predict(&X.view()).unwrap();

        assert_eq!(pred_bootstrap.dim(), (8, 2));
        assert_eq!(pred_no_bootstrap.dim(), (8, 2));
    }

    #[test]
    fn test_gradient_boosting_multi_output_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [1.5, 2.5],
            [3.5, 1.5],
            [2.5, 2.0],
            [1.8, 3.2]
        ];
        let y = array![
            [1.5, 2.5],
            [2.5, 3.5],
            [3.5, 1.5],
            [4.5, 4.5],
            [2.0, 3.0],
            [4.0, 2.0],
            [3.0, 2.5],
            [2.3, 3.7]
        ];

        let gbm = GradientBoostingMultiOutput::new()
            .n_estimators(10)
            .learning_rate(0.1)
            .max_depth(Some(2))
            .random_state(Some(42));
        let trained_gbm = gbm.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_gbm.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (8, 2));

        // Test gbm properties
        assert_eq!(trained_gbm.n_estimators(), 10);
        assert_eq!(trained_gbm.n_features(), 2);
        assert_eq!(trained_gbm.n_targets(), 2);

        // Feature importances should sum to 1 (or be close to it)
        let importances = trained_gbm.feature_importances();
        let importance_sum: Float = importances.sum();
        assert!((importance_sum - 1.0).abs() < 1e-10 || importance_sum == 0.0);

        // Training scores should be decreasing (generally)
        let train_scores = trained_gbm.train_scores();
        assert_eq!(train_scores.len(), 10);
        assert!(train_scores[0] >= train_scores[train_scores.len() - 1]); // Loss should decrease
    }

    #[test]
    fn test_gradient_boosting_multi_output_configuration() {
        let gbm = GradientBoostingMultiOutput::new()
            .n_estimators(50)
            .learning_rate(0.05)
            .max_depth(Some(4))
            .min_samples_split(3)
            .min_samples_leaf(2)
            .subsample(0.8)
            .random_state(Some(123));

        assert_eq!(gbm.n_estimators, 50);
        assert_eq!(gbm.learning_rate, 0.05);
        assert_eq!(gbm.max_depth, Some(4));
        assert_eq!(gbm.min_samples_split, 3);
        assert_eq!(gbm.min_samples_leaf, 2);
        assert_eq!(gbm.subsample, 0.8);
        assert_eq!(gbm.random_state, Some(123));

        let default_gbm = GradientBoostingMultiOutput::default();
        assert_eq!(default_gbm.n_estimators, 100);
        assert_eq!(default_gbm.learning_rate, 0.1);
        assert_eq!(default_gbm.max_depth, Some(3));
        assert_eq!(default_gbm.min_samples_split, 2);
        assert_eq!(default_gbm.min_samples_leaf, 1);
        assert_eq!(default_gbm.subsample, 1.0);
        assert_eq!(default_gbm.random_state, None);
    }

    #[test]
    fn test_gradient_boosting_multi_output_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5]]; // Wrong number of rows

        let gbm = GradientBoostingMultiOutput::new();
        assert!(gbm.clone().fit(&X.view(), &y).is_err());

        // Test with no targets
        let y_empty = Array2::<Float>::zeros((2, 0));
        assert!(gbm.clone().fit(&X.view(), &y_empty).is_err());

        // Test with invalid learning rate
        let gbm_invalid_lr = GradientBoostingMultiOutput::new().learning_rate(0.0);
        let y_valid = array![[1.5, 2.5], [2.5, 3.5]];
        assert!(gbm_invalid_lr.fit(&X.view(), &y_valid).is_err());

        // Test with invalid subsample
        let gbm_invalid_subsample = GradientBoostingMultiOutput::new().subsample(1.5);
        assert!(gbm_invalid_subsample.fit(&X.view(), &y_valid).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y_train = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];
        let gbm_for_predict = GradientBoostingMultiOutput::new().n_estimators(5);
        let trained_gbm = gbm_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_gbm.predict(&X_test.view()).is_err());
        assert!(trained_gbm.staged_predict(&X_test.view(), 3).is_err());
    }

    #[test]
    fn test_gradient_boosting_multi_output_staged_predict() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];

        let gbm = GradientBoostingMultiOutput::new()
            .n_estimators(10)
            .random_state(Some(42));
        let trained_gbm = gbm.fit(&X.view(), &y).unwrap();

        // Test staged prediction with different number of estimators
        let pred_3 = trained_gbm.staged_predict(&X.view(), 3).unwrap();
        let pred_5 = trained_gbm.staged_predict(&X.view(), 5).unwrap();
        let pred_all = trained_gbm.predict(&X.view()).unwrap();

        assert_eq!(pred_3.dim(), (4, 2));
        assert_eq!(pred_5.dim(), (4, 2));
        assert_eq!(pred_all.dim(), (4, 2));

        // Predictions should be different with different numbers of estimators
        assert!(&pred_3 != &pred_5);
        assert!(&pred_5 != &pred_all);
    }

    #[test]
    fn test_independent_label_prediction_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [1.5, 2.5],
            [3.5, 1.5]
        ];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0], [1, 0], [0, 1]];

        let ilp =
            IndependentLabelPrediction::new().threshold_strategy(ThresholdStrategy::Fixed(0.5));
        let trained_ilp = ilp.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_ilp.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (6, 2));

        // Check that predictions are binary
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }

        // Test probability prediction
        let probabilities = trained_ilp.predict_proba(&X.view()).unwrap();
        assert_eq!(probabilities.dim(), (6, 2));

        // Check that probabilities are in valid range
        for &prob in probabilities.iter() {
            assert!(prob >= 0.0 && prob <= 1.0);
        }

        // Test ILP properties
        assert_eq!(trained_ilp.n_features(), 2);
        assert_eq!(trained_ilp.n_labels(), 2);
        assert_eq!(trained_ilp.thresholds().len(), 2);
        assert_eq!(trained_ilp.label_frequencies().len(), 2);
    }

    #[test]
    fn test_independent_label_prediction_threshold_strategies() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test fixed threshold
        let ilp_fixed =
            IndependentLabelPrediction::new().threshold_strategy(ThresholdStrategy::Fixed(0.7));
        let trained_fixed = ilp_fixed.fit(&X.view(), &y).unwrap();
        let thresholds_fixed = trained_fixed.thresholds();
        assert_eq!(thresholds_fixed, &[0.7, 0.7]);

        // Test per-label thresholds
        let ilp_per_label = IndependentLabelPrediction::new()
            .threshold_strategy(ThresholdStrategy::PerLabel(vec![0.3, 0.8]));
        let trained_per_label = ilp_per_label.fit(&X.view(), &y).unwrap();
        let thresholds_per_label = trained_per_label.thresholds();
        assert_eq!(thresholds_per_label, &[0.3, 0.8]);

        // Test optimal threshold (without optimization enabled, should default to 0.5)
        let ilp_optimal = IndependentLabelPrediction::new()
            .threshold_strategy(ThresholdStrategy::Optimal)
            .optimize_thresholds(false);
        let trained_optimal = ilp_optimal.fit(&X.view(), &y).unwrap();
        let thresholds_optimal = trained_optimal.thresholds();
        assert_eq!(thresholds_optimal, &[0.5, 0.5]);
    }

    #[test]
    fn test_independent_label_prediction_class_weight() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        // Test balanced class weights
        let ilp_balanced =
            IndependentLabelPrediction::new().class_weight(Some("balanced".to_string()));
        let trained_balanced = ilp_balanced.fit(&X.view(), &y).unwrap();

        let predictions = trained_balanced.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Test default (no class weights)
        let ilp_default = IndependentLabelPrediction::new();
        let trained_default = ilp_default.fit(&X.view(), &y).unwrap();

        let predictions_default = trained_default.predict(&X.view()).unwrap();
        assert_eq!(predictions_default.dim(), (4, 2));
    }

    #[test]
    fn test_independent_label_prediction_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let ilp = IndependentLabelPrediction::new();
        assert!(ilp.clone().fit(&X.view(), &y).is_err());

        // Test with no labels
        let y_empty = Array2::<i32>::zeros((2, 0));
        assert!(ilp.clone().fit(&X.view(), &y_empty).is_err());

        // Test with non-binary labels
        let y_invalid = array![[1, 2], [0, 1]];
        assert!(ilp.clone().fit(&X.view(), &y_invalid).is_err());

        // Test mismatched threshold count
        let y_valid = array![[1, 0], [0, 1]];
        let ilp_wrong_thresholds = IndependentLabelPrediction::new()
            .threshold_strategy(ThresholdStrategy::PerLabel(vec![0.5, 0.6, 0.7])); // 3 thresholds for 2 labels
        assert!(ilp_wrong_thresholds.fit(&X.view(), &y_valid).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1, 0], [0, 1]];
        let ilp_for_predict = IndependentLabelPrediction::new();
        let trained_ilp = ilp_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_ilp.predict(&X_test.view()).is_err());
        assert!(trained_ilp.predict_proba(&X_test.view()).is_err());
    }

    #[test]
    fn test_independent_label_prediction_custom_thresholds() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        let ilp = IndependentLabelPrediction::new();
        let trained_ilp = ilp.fit(&X.view(), &y).unwrap();

        // Test prediction with custom thresholds
        let custom_thresholds = [0.3, 0.8];
        let predictions_custom = trained_ilp
            .predict_with_thresholds(&X.view(), &custom_thresholds)
            .unwrap();
        assert_eq!(predictions_custom.dim(), (4, 2));

        // Test with mismatched threshold count
        let wrong_thresholds = [0.5, 0.6, 0.7]; // Too many thresholds
        assert!(trained_ilp
            .predict_with_thresholds(&X.view(), &wrong_thresholds)
            .is_err());
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [5.0, 2.0],
            [6.0, 3.0]
        ];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0], [0, 1], [1, 0]];

        let tree = MultiTargetDecisionTreeClassifier::new()
            .max_depth(Some(3))
            .min_samples_split(2)
            .min_samples_leaf(1);

        let trained_tree = tree.fit(&X.view(), &y).unwrap();
        let predictions = trained_tree.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (6, 2));

        // Check that predictions are binary
        for pred in predictions.iter() {
            assert!(pred == &0 || pred == &1);
        }

        // Check feature importances are normalized
        let importances = trained_tree.feature_importances();
        let sum: Float = importances.sum();
        assert!((sum - 1.0).abs() < 1e-10 || sum == 0.0); // Sum should be 1.0 or 0.0 if all features have zero importance
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_probability() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        let tree = MultiTargetDecisionTreeClassifier::new();
        let trained_tree = tree.fit(&X.view(), &y).unwrap();
        let probabilities = trained_tree.predict_proba(&X.view()).unwrap();

        assert_eq!(probabilities.len(), 2); // Two targets
        assert_eq!(probabilities[0].dim(), (4, 2)); // 4 samples, 2 classes for target 0
        assert_eq!(probabilities[1].dim(), (4, 2)); // 4 samples, 2 classes for target 1

        // Check that probabilities sum to 1 for each sample and target
        for target_idx in 0..2 {
            for sample_idx in 0..4 {
                let prob_sum: Float = probabilities[target_idx].row(sample_idx).sum();
                assert!((prob_sum - 1.0).abs() < 1e-10);
            }
        }
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_entropy_criterion() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        let tree =
            MultiTargetDecisionTreeClassifier::new().criterion(ClassificationCriterion::Entropy);
        let trained_tree = tree.fit(&X.view(), &y).unwrap();
        let predictions = trained_tree.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 2));
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_single_class() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1, 0], [1, 0], [1, 0]]; // All samples have same labels

        let tree = MultiTargetDecisionTreeClassifier::new();
        let trained_tree = tree.fit(&X.view(), &y).unwrap();
        let predictions = trained_tree.predict(&X.view()).unwrap();

        // Should predict the single class for all samples
        for i in 0..3 {
            assert_eq!(predictions[[i, 0]], 1);
            assert_eq!(predictions[[i, 1]], 0);
        }
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_multi_class() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [5.0, 2.0],
            [6.0, 3.0]
        ];
        let y = array![[0, 2], [1, 1], [2, 0], [0, 2], [1, 1], [2, 0]]; // Multi-class targets (0, 1, 2)

        let tree = MultiTargetDecisionTreeClassifier::new();
        let trained_tree = tree.fit(&X.view(), &y).unwrap();
        let predictions = trained_tree.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (6, 2));

        // Check that predictions are in valid range
        for pred in predictions.iter() {
            assert!(pred >= &0 && pred <= &2);
        }
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let tree = MultiTargetDecisionTreeClassifier::new();
        assert!(tree.clone().fit(&X.view(), &y).is_err());

        // Test with no targets
        let y_empty = Array2::<i32>::zeros((2, 0));
        assert!(tree.clone().fit(&X.view(), &y_empty).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1, 0], [0, 1]];
        let tree_for_predict = MultiTargetDecisionTreeClassifier::new();
        let trained_tree = tree_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_tree.predict(&X_test.view()).is_err());
        assert!(trained_tree.predict_proba(&X_test.view()).is_err());
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_hyperparameters() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [5.0, 2.0],
            [6.0, 3.0],
            [7.0, 1.0],
            [8.0, 4.0]
        ];
        let y = array![
            [0, 1],
            [1, 0],
            [1, 1],
            [0, 0],
            [0, 1],
            [1, 0],
            [1, 1],
            [0, 0]
        ];

        // Test min_samples_split
        let tree1 = MultiTargetDecisionTreeClassifier::new().min_samples_split(4);
        let trained_tree1 = tree1.fit(&X.view(), &y).unwrap();

        // Test min_samples_leaf
        let tree2 = MultiTargetDecisionTreeClassifier::new().min_samples_leaf(2);
        let trained_tree2 = tree2.fit(&X.view(), &y).unwrap();

        // Test max_depth
        let tree3 = MultiTargetDecisionTreeClassifier::new().max_depth(Some(1));
        let trained_tree3 = tree3.fit(&X.view(), &y).unwrap();

        // All should produce valid predictions
        assert_eq!(trained_tree1.predict(&X.view()).unwrap().dim(), (8, 2));
        assert_eq!(trained_tree2.predict(&X.view()).unwrap().dim(), (8, 2));
        assert_eq!(trained_tree3.predict(&X.view()).unwrap().dim(), (8, 2));
    }

    #[test]
    fn test_multi_target_decision_tree_classifier_random_state() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1], [1, 0], [1, 1], [0, 0]];

        // Train two trees with same random state
        let tree1 = MultiTargetDecisionTreeClassifier::new().random_state(Some(42));
        let trained_tree1 = tree1.fit(&X.view(), &y).unwrap();

        let tree2 = MultiTargetDecisionTreeClassifier::new().random_state(Some(42));
        let trained_tree2 = tree2.fit(&X.view(), &y).unwrap();

        // Should produce same predictions (deterministic given same random state)
        let pred1 = trained_tree1.predict(&X.view()).unwrap();
        let pred2 = trained_tree2.predict(&X.view()).unwrap();

        // Note: Since our current implementation doesn't use randomness in splits,
        // this test mainly verifies the API works. In a more advanced implementation
        // with random feature selection, this would test reproducibility.
        assert_eq!(pred1.dim(), pred2.dim());
    }
}

/// Compressed Sensing Label Powerset
///
/// A multi-label classification approach using compressed sensing to handle
/// high-dimensional label spaces more efficiently.
#[derive(Debug, Clone)]
pub struct CompressedSensingLabelPowerset<S = Untrained> {
    state: S,
    compressed_dimension: Option<usize>,
    random_state: Option<u64>,
    reconstruction_method: ReconstructionMethod,
}

impl CompressedSensingLabelPowerset<Untrained> {
    /// Create a new CompressedSensingLabelPowerset instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            compressed_dimension: None,
            random_state: None,
            reconstruction_method: ReconstructionMethod::Linear,
        }
    }

    /// Set the compressed dimension
    pub fn compressed_dimension(mut self, dim: usize) -> Self {
        self.compressed_dimension = Some(dim);
        self
    }

    /// Set random state for reproducibility
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }

    /// Set reconstruction method
    pub fn reconstruction_method(mut self, method: ReconstructionMethod) -> Self {
        self.reconstruction_method = method;
        self
    }
}

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

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

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

/// Trained state for CompressedSensingLabelPowerset
#[derive(Debug, Clone)]
pub struct CompressedSensingLabelPowersetTrained {
    projection_matrix: Array2<Float>,
    label_powerset: LabelPowerset<LabelPowersetTrained>,
    n_features: usize,
    n_labels: usize,
    compressed_dimension: usize,
    reconstruction_method: ReconstructionMethod,
}

impl Fit<ArrayView2<'_, Float>, Array2<i32>> for CompressedSensingLabelPowerset<Untrained> {
    type Fitted = CompressedSensingLabelPowerset<CompressedSensingLabelPowersetTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let n_labels = y.ncols();

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

        let compressed_dimension = self.compressed_dimension.unwrap_or(n_labels / 2);
        if compressed_dimension >= n_labels {
            return Err(SklearsError::InvalidInput(
                "Compressed dimension must be less than number of labels".to_string(),
            ));
        }

        // Generate projection matrix
        let projection_matrix =
            generate_random_projection_matrix(compressed_dimension, n_labels, self.random_state);

        // Transform labels to compressed space
        let y_float: Array2<Float> = y.mapv(|x| x as Float);
        let y_compressed = y_float.dot(&projection_matrix.t());

        // Train label powerset on compressed labels
        let y_compressed_int: Array2<i32> = y_compressed.mapv(|x| if x > 0.0 { 1 } else { 0 });
        let powerset = LabelPowerset::new();
        let trained_powerset = powerset.fit(X, &y_compressed_int)?;

        let trained_state = CompressedSensingLabelPowersetTrained {
            projection_matrix,
            label_powerset: trained_powerset,
            n_features,
            n_labels,
            compressed_dimension,
            reconstruction_method: self.reconstruction_method,
        };

        Ok(CompressedSensingLabelPowerset {
            state: trained_state,
            compressed_dimension: self.compressed_dimension,
            random_state: self.random_state,
            reconstruction_method: self.reconstruction_method,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>>
    for CompressedSensingLabelPowerset<CompressedSensingLabelPowersetTrained>
{
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        // Predict compressed labels
        let compressed_predictions = self.state.label_powerset.predict(X)?;
        let compressed_float: Array2<Float> = compressed_predictions.mapv(|x| x as Float);

        // Reconstruct original labels
        let mut reconstructed = Array2::zeros((n_samples, self.state.n_labels));

        for i in 0..n_samples {
            let compressed_sample = compressed_float.row(i).to_owned();
            let reconstructed_sample = reconstruct_labels(
                &compressed_sample,
                &self.state.projection_matrix,
                self.state.reconstruction_method,
            )?;

            // Convert to binary
            for j in 0..self.state.n_labels {
                reconstructed[[i, j]] = if reconstructed_sample[j] > 0.0 { 1 } else { 0 };
            }
        }

        Ok(reconstructed)
    }
}

impl CompressedSensingLabelPowerset<CompressedSensingLabelPowersetTrained> {
    /// Get the compression ratio
    pub fn compression_ratio(&self) -> Float {
        self.state.compressed_dimension as Float / self.state.n_labels as Float
    }

    /// Get the projection matrix
    pub fn projection_matrix(&self) -> &Array2<Float> {
        &self.state.projection_matrix
    }
}

/// Multi-Output Support Vector Machine
///
/// A multi-output support vector machine that handles multiple regression or
/// classification targets simultaneously by training separate SVM models for each output.
#[derive(Debug, Clone)]
pub struct MultiOutputSVM<S = Untrained> {
    state: S,
    kernel: SVMKernel,
    c: Float,
    epsilon: Float,
    gamma: Option<Float>,
}

/// SVM Kernel types
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SVMKernel {
    /// Linear kernel: K(x, y) = x^T y
    Linear,
    /// Polynomial kernel: K(x, y) = (gamma * x^T y + coef0)^degree
    Polynomial {
        degree: i32,
        gamma: Float,
        coef0: Float,
    },
    /// RBF (Gaussian) kernel: K(x, y) = exp(-gamma * ||x - y||^2)
    RBF { gamma: Float },
    /// Sigmoid kernel: K(x, y) = tanh(gamma * x^T y + coef0)
    Sigmoid { gamma: Float, coef0: Float },
}

impl MultiOutputSVM<Untrained> {
    /// Create a new MultiOutputSVM instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            kernel: SVMKernel::RBF { gamma: 1.0 },
            c: 1.0,
            epsilon: 0.1,
            gamma: None,
        }
    }

    /// Set the SVM kernel
    pub fn kernel(mut self, kernel: SVMKernel) -> Self {
        self.kernel = kernel;
        self
    }

    /// Set the regularization parameter C
    pub fn c(mut self, c: Float) -> Self {
        self.c = c;
        self
    }

    /// Set epsilon for regression tolerance
    pub fn epsilon(mut self, epsilon: Float) -> Self {
        self.epsilon = epsilon;
        self
    }

    /// Set gamma parameter for RBF and polynomial kernels
    pub fn gamma(mut self, gamma: Float) -> Self {
        self.gamma = Some(gamma);
        self
    }
}

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

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

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

/// Trained state for MultiOutputSVM
#[derive(Debug, Clone)]
pub struct MultiOutputSVMTrained {
    support_vectors: Array2<Float>,
    dual_coef: Array2<Float>,
    intercept: Array1<Float>,
    kernel: SVMKernel,
    n_features: usize,
    n_outputs: usize,
    gamma: Float,
}

impl Fit<ArrayView2<'_, Float>, Array2<Float>> for MultiOutputSVM<Untrained> {
    type Fitted = MultiOutputSVM<MultiOutputSVMTrained>;

    fn fit(self, X: &ArrayView2<'_, Float>, y: &Array2<Float>) -> SklResult<Self::Fitted> {
        let (n_samples, n_features) = X.dim();
        let n_outputs = y.ncols();

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

        // Set gamma based on features if not provided
        let gamma = self.gamma.unwrap_or(1.0 / n_features as Float);

        // For simplicity, we'll implement a basic multi-output regression using
        // simplified SVM-like approach with kernel ridge regression
        let kernel_matrix = compute_kernel_matrix(X, X, &self.kernel, gamma)?;

        // Create regularized kernel matrix
        let mut K_reg = kernel_matrix.clone();
        for i in 0..n_samples {
            K_reg[[i, i]] += 1.0 / self.c;
        }

        // Solve for each output: (K + λI) α = y
        let mut dual_coef = Array2::zeros((n_samples, n_outputs));
        let mut intercept = Array1::zeros(n_outputs);

        for output_idx in 0..n_outputs {
            let y_target = y.column(output_idx).to_owned();

            // Solve the system using our linear solver
            match solve_linear_system(&K_reg, &y_target) {
                Ok(alpha) => {
                    dual_coef.column_mut(output_idx).assign(&alpha);

                    // Compute intercept as mean of residuals
                    let predictions = kernel_matrix.dot(&alpha);
                    let residuals = &y_target - &predictions;
                    intercept[output_idx] = residuals.mean().unwrap_or(0.0);
                }
                Err(_) => {
                    // Fallback to simple linear solution
                    let mean_target = y_target.mean().unwrap_or(0.0);
                    intercept[output_idx] = mean_target;
                }
            }
        }

        let trained_state = MultiOutputSVMTrained {
            support_vectors: X.to_owned(),
            dual_coef,
            intercept,
            kernel: self.kernel,
            n_features,
            n_outputs,
            gamma,
        };

        Ok(MultiOutputSVM {
            state: trained_state,
            kernel: self.kernel,
            c: self.c,
            epsilon: self.epsilon,
            gamma: self.gamma,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<Float>> for MultiOutputSVM<MultiOutputSVMTrained> {
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();
        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        // Compute kernel matrix between test and training data
        let kernel_matrix = compute_kernel_matrix(
            X,
            &self.state.support_vectors.view(),
            &self.state.kernel,
            self.state.gamma,
        )?;

        // Predict: K(X, X_train) * dual_coef + intercept
        let predictions = kernel_matrix.dot(&self.state.dual_coef) + &self.state.intercept;

        Ok(predictions)
    }
}

impl MultiOutputSVM<MultiOutputSVMTrained> {
    /// Get the number of support vectors
    pub fn n_support_vectors(&self) -> usize {
        self.state.support_vectors.nrows()
    }

    /// Get the dual coefficients
    pub fn dual_coef(&self) -> &Array2<Float> {
        &self.state.dual_coef
    }

    /// Get the intercept terms
    pub fn intercept(&self) -> &Array1<Float> {
        &self.state.intercept
    }

    /// Get the support vectors
    pub fn support_vectors(&self) -> &Array2<Float> {
        &self.state.support_vectors
    }
}

/// Compute kernel matrix between two sets of samples
fn compute_kernel_matrix(
    X1: &ArrayView2<Float>,
    X2: &ArrayView2<Float>,
    kernel: &SVMKernel,
    gamma: Float,
) -> SklResult<Array2<Float>> {
    let n1 = X1.nrows();
    let n2 = X2.nrows();
    let mut K = Array2::zeros((n1, n2));

    for i in 0..n1 {
        for j in 0..n2 {
            let x1 = X1.row(i);
            let x2 = X2.row(j);
            K[[i, j]] = compute_kernel_value(&x1, &x2, kernel, gamma);
        }
    }

    Ok(K)
}

/// Compute kernel value between two samples
fn compute_kernel_value(
    x1: &ArrayView1<Float>,
    x2: &ArrayView1<Float>,
    kernel: &SVMKernel,
    default_gamma: Float,
) -> Float {
    match kernel {
        SVMKernel::Linear => x1.dot(x2),
        SVMKernel::Polynomial {
            degree,
            gamma,
            coef0,
        } => (*gamma * x1.dot(x2) + *coef0).powi(*degree),
        SVMKernel::RBF { gamma } => {
            let dist_sq = x1
                .iter()
                .zip(x2.iter())
                .map(|(a, b)| (a - b).powi(2))
                .sum::<Float>();
            (-gamma * dist_sq).exp()
        }
        SVMKernel::Sigmoid { gamma, coef0 } => (*gamma * x1.dot(x2) + *coef0).tanh(),
    }
}

// =============================================================================
// STRUCTURED OUTPUT PREDICTION METHODS
// =============================================================================

/// Conditional Random Fields for sequence labeling
///
/// A discriminative probabilistic framework for labeling and segmenting
/// sequential data. CRFs model the conditional probability of label sequences
/// given input sequences, making them particularly suitable for structured
/// prediction tasks like named entity recognition, part-of-speech tagging,
/// and DNA sequence analysis.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::ConditionalRandomField;
/// use ndarray::array;
///
/// let X = array![[[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]]]; // One sequence
/// let y = array![[0, 1, 0]]; // Label sequence
///
/// let crf = ConditionalRandomField::new()
///     .max_iterations(100)
///     .learning_rate(0.01);
/// let trained_crf = crf.fit(&X, &y).unwrap();
/// let predictions = trained_crf.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct ConditionalRandomField<State = Untrained> {
    max_iterations: usize,
    learning_rate: Float,
    l2_penalty: Float,
    tolerance: Float,
    state: State,
}

/// Trained state for Conditional Random Field
#[derive(Debug, Clone)]
pub struct ConditionalRandomFieldTrained {
    feature_weights: Array2<Float>,
    transition_weights: Array2<Float>,
    n_features: usize,
    n_labels: usize,
    label_to_idx: HashMap<i32, usize>,
    idx_to_label: HashMap<usize, i32>,
}

impl ConditionalRandomField<Untrained> {
    /// Create new CRF instance
    pub fn new() -> Self {
        Self {
            max_iterations: 100,
            learning_rate: 0.01,
            l2_penalty: 0.1,
            tolerance: 1e-6,
            state: Untrained,
        }
    }

    /// Set maximum iterations for optimization
    pub fn max_iterations(mut self, max_iter: usize) -> Self {
        self.max_iterations = max_iter;
        self
    }

    /// Set learning rate for gradient descent
    pub fn learning_rate(mut self, lr: Float) -> Self {
        self.learning_rate = lr;
        self
    }

    /// Set L2 regularization penalty
    pub fn l2_penalty(mut self, penalty: Float) -> Self {
        self.l2_penalty = penalty;
        self
    }

    /// Set convergence tolerance
    pub fn tolerance(mut self, tol: Float) -> Self {
        self.tolerance = tol;
        self
    }
}

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

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

impl Fit<Array3<Float>, Array2<i32>> for ConditionalRandomField<Untrained> {
    type Fitted = ConditionalRandomField<ConditionalRandomFieldTrained>;

    fn fit(self, X: &Array3<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_sequences, max_length, n_features) = X.dim();

        if y.nrows() != n_sequences {
            return Err(SklearsError::InvalidInput(
                "Number of sequences in X and y must match".to_string(),
            ));
        }

        // Build label mappings
        let unique_labels: std::collections::HashSet<i32> = y.iter().cloned().collect();
        let mut label_to_idx = HashMap::new();
        let mut idx_to_label = HashMap::new();

        for (idx, &label) in unique_labels.iter().enumerate() {
            label_to_idx.insert(label, idx);
            idx_to_label.insert(idx, label);
        }

        let n_labels = unique_labels.len();

        // Initialize weights
        let mut feature_weights = Array2::zeros((n_features, n_labels));
        let mut transition_weights = Array2::zeros((n_labels, n_labels));

        // Training with gradient ascent on log-likelihood
        let mut prev_likelihood = Float::NEG_INFINITY;

        for iteration in 0..self.max_iterations {
            let mut feature_gradient = Array2::zeros((n_features, n_labels));
            let mut transition_gradient = Array2::zeros((n_labels, n_labels));
            let mut total_likelihood = 0.0;

            // Process each sequence
            for seq_idx in 0..n_sequences {
                let sequence = X.slice(s![seq_idx, .., ..]);
                let labels = y.row(seq_idx);

                // Get actual sequence length (assuming padded with zeros)
                let seq_len = labels.iter().position(|&x| x == -1).unwrap_or(max_length);
                if seq_len == 0 {
                    continue;
                }

                // Forward-backward algorithm for marginal probabilities
                let (alpha, beta, Z) = self.forward_backward(
                    &sequence.slice(s![..seq_len, ..]),
                    &feature_weights,
                    &transition_weights,
                    &label_to_idx,
                )?;

                // Compute feature expectations
                for t in 0..seq_len {
                    let features = sequence.row(t);
                    for (k, &label_idx) in label_to_idx.iter() {
                        let marginal = alpha[[t, label_idx]] + beta[[t, label_idx]] - Z;
                        for (f, &feat_val) in features.iter().enumerate() {
                            feature_gradient[[f, label_idx]] += marginal.exp() * feat_val;
                        }
                    }
                }

                // Compute transition expectations
                for t in 0..(seq_len - 1) {
                    for (k1, &l1_idx) in label_to_idx.iter() {
                        for (k2, &l2_idx) in label_to_idx.iter() {
                            let score = alpha[[t, l1_idx]]
                                + transition_weights[[l1_idx, l2_idx]]
                                + feature_weights.row(l2_idx).dot(&sequence.row(t + 1))
                                + beta[[t + 1, l2_idx]];
                            let marginal = (score - Z).exp();
                            transition_gradient[[l1_idx, l2_idx]] += marginal;
                        }
                    }
                }

                // Add empirical feature counts
                for t in 0..seq_len {
                    let features = sequence.row(t);
                    let label_idx = *label_to_idx.get(&labels[t]).unwrap();
                    for (f, &feat_val) in features.iter().enumerate() {
                        feature_gradient[[f, label_idx]] -= feat_val;
                    }
                }

                // Add empirical transition counts
                for t in 0..(seq_len - 1) {
                    let curr_label = *label_to_idx.get(&labels[t]).unwrap();
                    let next_label = *label_to_idx.get(&labels[t + 1]).unwrap();
                    transition_gradient[[curr_label, next_label]] -= 1.0;
                }

                total_likelihood += Z;
            }

            // Apply L2 regularization
            feature_gradient = feature_gradient - self.l2_penalty * &feature_weights;
            transition_gradient = transition_gradient - self.l2_penalty * &transition_weights;

            // Update weights
            feature_weights = feature_weights - self.learning_rate * &feature_gradient;
            transition_weights = transition_weights - self.learning_rate * &transition_gradient;

            // Check convergence
            if iteration > 0 && (total_likelihood - prev_likelihood).abs() < self.tolerance {
                break;
            }
            prev_likelihood = total_likelihood;
        }

        Ok(ConditionalRandomField {
            max_iterations: self.max_iterations,
            learning_rate: self.learning_rate,
            l2_penalty: self.l2_penalty,
            tolerance: self.tolerance,
            state: ConditionalRandomFieldTrained {
                feature_weights,
                transition_weights,
                n_features,
                n_labels,
                label_to_idx,
                idx_to_label,
            },
        })
    }
}

impl ConditionalRandomField<Untrained> {
    /// Forward-backward algorithm for CRF inference
    fn forward_backward(
        &self,
        sequence: &ArrayView2<Float>,
        feature_weights: &Array2<Float>,
        transition_weights: &Array2<Float>,
        label_to_idx: &HashMap<i32, usize>,
    ) -> SklResult<(Array2<Float>, Array2<Float>, Float)> {
        let seq_len = sequence.nrows();
        let n_labels = label_to_idx.len();

        let mut alpha = Array2::zeros((seq_len, n_labels));
        let mut beta = Array2::zeros((seq_len, n_labels));

        // Forward pass
        for (_, &label_idx) in label_to_idx.iter() {
            alpha[[0, label_idx]] = feature_weights.row(label_idx).dot(&sequence.row(0));
        }

        for t in 1..seq_len {
            for (_, &curr_label_idx) in label_to_idx.iter() {
                let mut sum = Float::NEG_INFINITY;
                for (_, &prev_label_idx) in label_to_idx.iter() {
                    let score = alpha[[t - 1, prev_label_idx]]
                        + transition_weights[[prev_label_idx, curr_label_idx]]
                        + feature_weights.row(curr_label_idx).dot(&sequence.row(t));
                    sum = log_sum_exp(sum, score);
                }
                alpha[[t, curr_label_idx]] = sum;
            }
        }

        // Partition function
        let mut Z = Float::NEG_INFINITY;
        for (_, &label_idx) in label_to_idx.iter() {
            Z = log_sum_exp(Z, alpha[[seq_len - 1, label_idx]]);
        }

        // Backward pass
        for (_, &label_idx) in label_to_idx.iter() {
            beta[[seq_len - 1, label_idx]] = 0.0;
        }

        for t in (0..(seq_len - 1)).rev() {
            for (_, &curr_label_idx) in label_to_idx.iter() {
                let mut sum = Float::NEG_INFINITY;
                for (_, &next_label_idx) in label_to_idx.iter() {
                    let score = transition_weights[[curr_label_idx, next_label_idx]]
                        + feature_weights
                            .row(next_label_idx)
                            .dot(&sequence.row(t + 1))
                        + beta[[t + 1, next_label_idx]];
                    sum = log_sum_exp(sum, score);
                }
                beta[[t, curr_label_idx]] = sum;
            }
        }

        Ok((alpha, beta, Z))
    }
}

impl Predict<Array3<Float>, Array2<i32>> for ConditionalRandomField<ConditionalRandomFieldTrained> {
    fn predict(&self, X: &Array3<Float>) -> SklResult<Array2<i32>> {
        let (n_sequences, max_length, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features does not match training data".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_sequences, max_length));

        for seq_idx in 0..n_sequences {
            let sequence = X.slice(s![seq_idx, .., ..]);

            // Get actual sequence length (assuming padded)
            let seq_len = max_length; // For simplicity, assuming full length

            // Viterbi decoding
            let best_path = self.viterbi_decode(&sequence.slice(s![..seq_len, ..]))?;

            for (t, &label_idx) in best_path.iter().enumerate() {
                predictions[[seq_idx, t]] = *self.state.idx_to_label.get(&label_idx).unwrap();
            }
        }

        Ok(predictions)
    }
}

impl ConditionalRandomField<ConditionalRandomFieldTrained> {
    /// Viterbi algorithm for finding most likely label sequence
    fn viterbi_decode(&self, sequence: &ArrayView2<Float>) -> SklResult<Vec<usize>> {
        let seq_len = sequence.nrows();
        let n_labels = self.state.n_labels;

        let mut viterbi = Array2::zeros((seq_len, n_labels));
        let mut backpointer = Array2::zeros((seq_len, n_labels));

        // Initialize
        for label_idx in 0..n_labels {
            viterbi[[0, label_idx]] = self
                .state
                .feature_weights
                .row(label_idx)
                .dot(&sequence.row(0));
        }

        // Forward pass
        for t in 1..seq_len {
            for curr_label in 0..n_labels {
                let mut best_score = Float::NEG_INFINITY;
                let mut best_prev = 0;

                for prev_label in 0..n_labels {
                    let score = viterbi[[t - 1, prev_label]]
                        + self.state.transition_weights[[prev_label, curr_label]]
                        + self
                            .state
                            .feature_weights
                            .row(curr_label)
                            .dot(&sequence.row(t));

                    if score > best_score {
                        best_score = score;
                        best_prev = prev_label;
                    }
                }

                viterbi[[t, curr_label]] = best_score;
                backpointer[[t, curr_label]] = best_prev as Float;
            }
        }

        // Find best final state
        let mut best_final_score = Float::NEG_INFINITY;
        let mut best_final_state = 0;

        for label_idx in 0..n_labels {
            if viterbi[[seq_len - 1, label_idx]] > best_final_score {
                best_final_score = viterbi[[seq_len - 1, label_idx]];
                best_final_state = label_idx;
            }
        }

        // Backtrack
        let mut path = vec![0; seq_len];
        path[seq_len - 1] = best_final_state;

        for t in (1..seq_len).rev() {
            path[t - 1] = backpointer[[t, path[t]]] as usize;
        }

        Ok(path)
    }

    /// Get feature weights
    pub fn feature_weights(&self) -> &Array2<Float> {
        &self.state.feature_weights
    }

    /// Get transition weights
    pub fn transition_weights(&self) -> &Array2<Float> {
        &self.state.transition_weights
    }
}

/// Structured Perceptron for structured prediction
///
/// A simple and effective algorithm for learning structured prediction models.
/// The structured perceptron extends the classic perceptron to handle structured
/// outputs by using a feature function that maps input-output pairs to feature
/// vectors and a loss function that measures the quality of predictions.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::StructuredPerceptron;
/// use ndarray::array;
///
/// let X = array![[[1.0, 2.0], [2.0, 3.0]]]; // One sequence
/// let y = array![[0, 1]]; // Label sequence
///
/// let perceptron = StructuredPerceptron::new().max_iterations(50);
/// let trained_perceptron = perceptron.fit(&X, &y).unwrap();
/// let predictions = trained_perceptron.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct StructuredPerceptron<State = Untrained> {
    max_iterations: usize,
    learning_rate: Float,
    random_state: Option<u64>,
    state: State,
}

/// Trained state for Structured Perceptron
#[derive(Debug, Clone)]
pub struct StructuredPerceptronTrained {
    weights: Array1<Float>,
    n_features: usize,
    n_labels: usize,
    label_to_idx: HashMap<i32, usize>,
    idx_to_label: HashMap<usize, i32>,
}

impl StructuredPerceptron<Untrained> {
    /// Create new structured perceptron instance
    pub fn new() -> Self {
        Self {
            max_iterations: 100,
            learning_rate: 1.0,
            random_state: None,
            state: Untrained,
        }
    }

    /// Set maximum iterations
    pub fn max_iterations(mut self, max_iter: usize) -> Self {
        self.max_iterations = max_iter;
        self
    }

    /// Set learning rate
    pub fn learning_rate(mut self, lr: Float) -> Self {
        self.learning_rate = lr;
        self
    }

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

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

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

impl Fit<Array3<Float>, Array2<i32>> for StructuredPerceptron<Untrained> {
    type Fitted = StructuredPerceptron<StructuredPerceptronTrained>;

    fn fit(self, X: &Array3<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_sequences, max_length, n_features) = X.dim();

        if y.nrows() != n_sequences {
            return Err(SklearsError::InvalidInput(
                "Number of sequences in X and y must match".to_string(),
            ));
        }

        // Build label mappings
        let unique_labels: std::collections::HashSet<i32> = y.iter().cloned().collect();
        let mut label_to_idx = HashMap::new();
        let mut idx_to_label = HashMap::new();

        for (idx, &label) in unique_labels.iter().enumerate() {
            label_to_idx.insert(label, idx);
            idx_to_label.insert(idx, label);
        }

        let n_labels = unique_labels.len();

        // Feature vector size: position-specific features + transition features
        let feature_size = max_length * n_features * n_labels + n_labels * n_labels;
        let mut weights = Array1::zeros(feature_size);

        // Training loop
        for _iteration in 0..self.max_iterations {
            let mut total_updates = 0;

            for seq_idx in 0..n_sequences {
                let sequence = X.slice(s![seq_idx, .., ..]);
                let true_labels = y.row(seq_idx);

                // Get actual sequence length
                let seq_len = true_labels
                    .iter()
                    .position(|&x| x == -1)
                    .unwrap_or(max_length);
                if seq_len == 0 {
                    continue;
                }

                // Make prediction using current weights
                let predicted_labels = self.predict_sequence(
                    &sequence.slice(s![..seq_len, ..]),
                    &weights,
                    max_length,
                    n_features,
                    n_labels,
                    &label_to_idx,
                    &idx_to_label,
                )?;

                // Check if prediction is correct
                let mut is_correct = true;
                for t in 0..seq_len {
                    if predicted_labels[t] != true_labels[t] {
                        is_correct = false;
                        break;
                    }
                }

                // Update weights if prediction is wrong
                if !is_correct {
                    // Extract features for true and predicted sequences
                    let true_features = self.extract_features(
                        &sequence.slice(s![..seq_len, ..]),
                        &true_labels.slice(s![..seq_len]),
                        max_length,
                        n_features,
                        n_labels,
                        &label_to_idx,
                    )?;

                    let pred_features = self.extract_features(
                        &sequence.slice(s![..seq_len, ..]),
                        &ArrayView1::from(&predicted_labels[..seq_len]),
                        max_length,
                        n_features,
                        n_labels,
                        &label_to_idx,
                    )?;

                    // Perceptron update: w = w + η(φ(x,y) - φ(x,y'))
                    let update = &true_features - &pred_features;
                    weights = weights + self.learning_rate * &update;

                    total_updates += 1;
                }
            }

            // Early stopping if no updates were made
            if total_updates == 0 {
                break;
            }
        }

        Ok(StructuredPerceptron {
            max_iterations: self.max_iterations,
            learning_rate: self.learning_rate,
            random_state: self.random_state,
            state: StructuredPerceptronTrained {
                weights,
                n_features,
                n_labels,
                label_to_idx,
                idx_to_label,
            },
        })
    }
}

impl StructuredPerceptron<Untrained> {
    /// Extract feature vector for a labeled sequence
    fn extract_features(
        &self,
        sequence: &ArrayView2<Float>,
        labels: &ArrayView1<i32>,
        max_length: usize,
        n_features: usize,
        n_labels: usize,
        label_to_idx: &HashMap<i32, usize>,
    ) -> SklResult<Array1<Float>> {
        let feature_size = max_length * n_features * n_labels + n_labels * n_labels;
        let mut features = Array1::zeros(feature_size);
        let seq_len = sequence.nrows();

        // Position-specific features
        for t in 0..seq_len {
            let label_idx = *label_to_idx.get(&labels[t]).unwrap();
            let base_idx = t * n_features * n_labels + label_idx * n_features;

            for f in 0..n_features {
                features[base_idx + f] = sequence[[t, f]];
            }
        }

        // Transition features
        let transition_base = max_length * n_features * n_labels;
        for t in 0..(seq_len - 1) {
            let curr_label = *label_to_idx.get(&labels[t]).unwrap();
            let next_label = *label_to_idx.get(&labels[t + 1]).unwrap();
            let transition_idx = transition_base + curr_label * n_labels + next_label;
            features[transition_idx] = 1.0;
        }

        Ok(features)
    }

    /// Predict sequence labels using current weights
    fn predict_sequence(
        &self,
        sequence: &ArrayView2<Float>,
        weights: &Array1<Float>,
        max_length: usize,
        n_features: usize,
        n_labels: usize,
        label_to_idx: &HashMap<i32, usize>,
        idx_to_label: &HashMap<usize, i32>,
    ) -> SklResult<Vec<i32>> {
        let seq_len = sequence.nrows();

        // Simple greedy prediction for each position
        let mut predictions = Vec::with_capacity(seq_len);

        for t in 0..seq_len {
            let mut best_score = Float::NEG_INFINITY;
            let mut best_label = 0;

            for label_idx in 0..n_labels {
                let base_idx = t * n_features * n_labels + label_idx * n_features;
                let mut score = 0.0;

                for f in 0..n_features {
                    score += weights[base_idx + f] * sequence[[t, f]];
                }

                // Add transition score if not first position
                if t > 0 && !predictions.is_empty() {
                    let prev_label_idx = *label_to_idx.get(&predictions[t - 1]).unwrap();
                    let transition_base = max_length * n_features * n_labels;
                    let transition_idx = transition_base + prev_label_idx * n_labels + label_idx;
                    score += weights[transition_idx];
                }

                if score > best_score {
                    best_score = score;
                    best_label = label_idx;
                }
            }

            predictions.push(*idx_to_label.get(&best_label).unwrap());
        }

        Ok(predictions)
    }
}

impl Predict<Array3<Float>, Array2<i32>> for StructuredPerceptron<StructuredPerceptronTrained> {
    fn predict(&self, X: &Array3<Float>) -> SklResult<Array2<i32>> {
        let (n_sequences, max_length, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features does not match training data".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_sequences, max_length));

        for seq_idx in 0..n_sequences {
            let sequence = X.slice(s![seq_idx, .., ..]);

            // Predict sequence
            let pred_labels = self.predict_sequence_trained(&sequence)?;

            for (t, &label) in pred_labels.iter().enumerate() {
                if t < max_length {
                    predictions[[seq_idx, t]] = label;
                }
            }
        }

        Ok(predictions)
    }
}

impl StructuredPerceptron<StructuredPerceptronTrained> {
    /// Predict sequence using trained weights
    fn predict_sequence_trained(&self, sequence: &ArrayView2<Float>) -> SklResult<Vec<i32>> {
        let seq_len = sequence.nrows();
        let mut predictions = Vec::with_capacity(seq_len);

        for t in 0..seq_len {
            let mut best_score = Float::NEG_INFINITY;
            let mut best_label = 0;

            for label_idx in 0..self.state.n_labels {
                let base_idx =
                    t * sequence.ncols() * self.state.n_labels + label_idx * sequence.ncols();
                let mut score = 0.0;

                for f in 0..sequence.ncols() {
                    if base_idx + f < self.state.weights.len() {
                        score += self.state.weights[base_idx + f] * sequence[[t, f]];
                    }
                }

                if score > best_score {
                    best_score = score;
                    best_label = label_idx;
                }
            }

            predictions.push(*self.state.idx_to_label.get(&best_label).unwrap());
        }

        Ok(predictions)
    }

    /// Get learned weights
    pub fn weights(&self) -> &Array1<Float> {
        &self.state.weights
    }
}

/// Hidden Markov Model for sequence modeling
///
/// A statistical model that assumes the system being modeled is a Markov process
/// with unobserved (hidden) states. HMMs are particularly useful for temporal
/// pattern recognition such as speech recognition, handwriting recognition,
/// gesture recognition, part-of-speech tagging, and bioinformatics.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::HiddenMarkovModel;
/// use ndarray::array;
///
/// let X = array![[[1.0, 2.0], [2.0, 3.0], [1.5, 2.5]]]; // One sequence
/// let y = array![[0, 1, 0]]; // State sequence
///
/// let hmm = HiddenMarkovModel::new().n_states(2).max_iterations(100);
/// let trained_hmm = hmm.fit(&X, &y).unwrap();
/// let predictions = trained_hmm.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct HiddenMarkovModel<State = Untrained> {
    n_states: usize,
    max_iterations: usize,
    tolerance: Float,
    random_state: Option<u64>,
    state: State,
}

/// Trained state for Hidden Markov Model
#[derive(Debug, Clone)]
pub struct HiddenMarkovModelTrained {
    transition_matrix: Array2<Float>,
    emission_means: Array2<Float>,
    emission_covariances: Array3<Float>,
    initial_probabilities: Array1<Float>,
    n_states: usize,
    n_features: usize,
}

impl HiddenMarkovModel<Untrained> {
    /// Create new HMM instance
    pub fn new() -> Self {
        Self {
            n_states: 2,
            max_iterations: 100,
            tolerance: 1e-6,
            random_state: None,
            state: Untrained,
        }
    }

    /// Set number of hidden states
    pub fn n_states(mut self, n_states: usize) -> Self {
        self.n_states = n_states;
        self
    }

    /// Set maximum iterations for EM algorithm
    pub fn max_iterations(mut self, max_iter: usize) -> Self {
        self.max_iterations = max_iter;
        self
    }

    /// Set convergence tolerance
    pub fn tolerance(mut self, tol: Float) -> Self {
        self.tolerance = tol;
        self
    }

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

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

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

impl Fit<Array3<Float>, Array2<i32>> for HiddenMarkovModel<Untrained> {
    type Fitted = HiddenMarkovModel<HiddenMarkovModelTrained>;

    fn fit(self, X: &Array3<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_sequences, max_length, n_features) = X.dim();

        if y.nrows() != n_sequences {
            return Err(SklearsError::InvalidInput(
                "Number of sequences in X and y must match".to_string(),
            ));
        }

        // Initialize parameters
        let mut transition_matrix =
            Array2::from_elem((self.n_states, self.n_states), 1.0 / self.n_states as Float);
        let mut emission_means = Array2::zeros((self.n_states, n_features));
        let mut emission_covariances = Array3::zeros((self.n_states, n_features, n_features));
        let mut initial_probabilities =
            Array1::from_elem(self.n_states, 1.0 / self.n_states as Float);

        // Initialize emission parameters using supervised data
        self.initialize_emission_parameters(
            &X.view(),
            &y.view(),
            &mut emission_means,
            &mut emission_covariances,
        )?;

        // EM algorithm
        let mut prev_likelihood = Float::NEG_INFINITY;

        for _iteration in 0..self.max_iterations {
            let mut total_likelihood = 0.0;

            // E-step: Forward-backward algorithm for each sequence
            let mut gamma_sum = Array2::<Float>::zeros((self.n_states, n_features));
            let mut xi_sum = Array2::<Float>::zeros((self.n_states, self.n_states));
            let mut initial_sum = Array1::<Float>::zeros(self.n_states);
            let mut total_gamma = Array1::<Float>::zeros(self.n_states);

            for seq_idx in 0..n_sequences {
                let sequence = X.slice(s![seq_idx, .., ..]);
                let seq_len = self.get_sequence_length(&y.row(seq_idx));

                if seq_len == 0 {
                    continue;
                }

                let obs_seq = sequence.slice(s![..seq_len, ..]);

                // Forward-backward
                let (alpha, beta, likelihood) = self.forward_backward(
                    &obs_seq,
                    &transition_matrix,
                    &emission_means,
                    &emission_covariances,
                    &initial_probabilities,
                )?;

                total_likelihood += likelihood;

                // Compute gamma (state probabilities)
                let gamma = self.compute_gamma(&alpha, &beta, likelihood);

                // Compute xi (transition probabilities)
                let xi = self.compute_xi(
                    &obs_seq,
                    &alpha,
                    &beta,
                    &transition_matrix,
                    &emission_means,
                    &emission_covariances,
                    likelihood,
                )?;

                // Accumulate statistics
                initial_sum = initial_sum + &gamma.row(0);

                for t in 0..seq_len {
                    for i in 0..self.n_states {
                        total_gamma[i] += gamma[[t, i]];
                        for j in 0..n_features {
                            gamma_sum[[i, j]] += gamma[[t, i]] * obs_seq[[t, j]];
                        }
                    }
                }

                for t in 0..(seq_len - 1) {
                    for i in 0..self.n_states {
                        for j in 0..self.n_states {
                            xi_sum[[i, j]] += xi[[t, i, j]];
                        }
                    }
                }
            }

            // M-step: Update parameters
            // Update initial probabilities
            let initial_sum_total = initial_sum.sum();
            if initial_sum_total > 0.0 {
                initial_probabilities = initial_sum / initial_sum_total;
            }

            // Update transition matrix
            for i in 0..self.n_states {
                let row_sum = xi_sum.row(i).sum();
                if row_sum > 0.0 {
                    for j in 0..self.n_states {
                        transition_matrix[[i, j]] = xi_sum[[i, j]] / row_sum;
                    }
                }
            }

            // Update emission means
            for i in 0..self.n_states {
                if total_gamma[i] > 0.0 {
                    for j in 0..n_features {
                        emission_means[[i, j]] = gamma_sum[[i, j]] / total_gamma[i];
                    }
                }
            }

            // Update emission covariances (simplified as diagonal)
            for i in 0..self.n_states {
                for j in 0..n_features {
                    emission_covariances[[i, j, j]] = 1.0; // Simplified identity covariance
                }
            }

            // Check convergence
            if (total_likelihood - prev_likelihood).abs() < self.tolerance {
                break;
            }
            prev_likelihood = total_likelihood;
        }

        Ok(HiddenMarkovModel {
            n_states: self.n_states,
            max_iterations: self.max_iterations,
            tolerance: self.tolerance,
            random_state: self.random_state,
            state: HiddenMarkovModelTrained {
                transition_matrix,
                emission_means,
                emission_covariances,
                initial_probabilities,
                n_states: self.n_states,
                n_features,
            },
        })
    }
}

impl HiddenMarkovModel<Untrained> {
    /// Initialize emission parameters using supervised data
    fn initialize_emission_parameters(
        &self,
        X: &ArrayView3<Float>,
        y: &ArrayView2<i32>,
        emission_means: &mut Array2<Float>,
        emission_covariances: &mut Array3<Float>,
    ) -> SklResult<()> {
        let (n_sequences, _max_length, n_features) = X.dim();

        // Compute means for each state
        let mut state_counts = vec![0; self.n_states];
        let mut state_sums = Array2::<Float>::zeros((self.n_states, n_features));

        for seq_idx in 0..n_sequences {
            let sequence = X.slice(s![seq_idx, .., ..]);
            let labels = y.row(seq_idx);
            let seq_len = self.get_sequence_length(&labels);

            for t in 0..seq_len {
                let state = labels[t] as usize;
                if state < self.n_states {
                    state_counts[state] += 1;
                    for f in 0..n_features {
                        state_sums[[state, f]] += sequence[[t, f]];
                    }
                }
            }
        }

        // Compute means
        for i in 0..self.n_states {
            if state_counts[i] > 0 {
                for j in 0..n_features {
                    emission_means[[i, j]] = state_sums[[i, j]] / state_counts[i] as Float;
                }
            }
        }

        // Initialize covariances as identity matrices
        for i in 0..self.n_states {
            for j in 0..n_features {
                emission_covariances[[i, j, j]] = 1.0;
            }
        }

        Ok(())
    }

    /// Get effective sequence length (stop at -1 padding)
    fn get_sequence_length(&self, labels: &ArrayView1<i32>) -> usize {
        labels.iter().position(|&x| x == -1).unwrap_or(labels.len())
    }

    /// Forward-backward algorithm
    fn forward_backward(
        &self,
        sequence: &ArrayView2<Float>,
        transition_matrix: &Array2<Float>,
        emission_means: &Array2<Float>,
        emission_covariances: &Array3<Float>,
        initial_probabilities: &Array1<Float>,
    ) -> SklResult<(Array2<Float>, Array2<Float>, Float)> {
        let seq_len = sequence.nrows();
        let mut alpha = Array2::zeros((seq_len, self.n_states));
        let mut beta = Array2::zeros((seq_len, self.n_states));

        // Forward pass
        for i in 0..self.n_states {
            let emission_prob = self.gaussian_pdf(
                &sequence.row(0),
                &emission_means.row(i),
                &emission_covariances.slice(s![i, .., ..]),
            );
            alpha[[0, i]] = initial_probabilities[i] * emission_prob;
        }

        for t in 1..seq_len {
            for j in 0..self.n_states {
                let mut sum = 0.0;
                for i in 0..self.n_states {
                    sum += alpha[[t - 1, i]] * transition_matrix[[i, j]];
                }
                let emission_prob = self.gaussian_pdf(
                    &sequence.row(t),
                    &emission_means.row(j),
                    &emission_covariances.slice(s![j, .., ..]),
                );
                alpha[[t, j]] = sum * emission_prob;
            }
        }

        // Compute likelihood
        let likelihood = alpha.row(seq_len - 1).sum();

        // Backward pass
        for i in 0..self.n_states {
            beta[[seq_len - 1, i]] = 1.0;
        }

        for t in (0..(seq_len - 1)).rev() {
            for i in 0..self.n_states {
                let mut sum = 0.0;
                for j in 0..self.n_states {
                    let emission_prob = self.gaussian_pdf(
                        &sequence.row(t + 1),
                        &emission_means.row(j),
                        &emission_covariances.slice(s![j, .., ..]),
                    );
                    sum += transition_matrix[[i, j]] * emission_prob * beta[[t + 1, j]];
                }
                beta[[t, i]] = sum;
            }
        }

        Ok((alpha, beta, likelihood))
    }

    /// Compute gamma (state probabilities)
    fn compute_gamma(
        &self,
        alpha: &Array2<Float>,
        beta: &Array2<Float>,
        likelihood: Float,
    ) -> Array2<Float> {
        let (seq_len, n_states) = alpha.dim();
        let mut gamma = Array2::zeros((seq_len, n_states));

        for t in 0..seq_len {
            for i in 0..n_states {
                gamma[[t, i]] = alpha[[t, i]] * beta[[t, i]] / likelihood;
            }
        }

        gamma
    }

    /// Compute xi (transition probabilities)
    fn compute_xi(
        &self,
        sequence: &ArrayView2<Float>,
        alpha: &Array2<Float>,
        beta: &Array2<Float>,
        transition_matrix: &Array2<Float>,
        emission_means: &Array2<Float>,
        emission_covariances: &Array3<Float>,
        likelihood: Float,
    ) -> SklResult<Array3<Float>> {
        let seq_len = sequence.nrows();
        let mut xi = Array3::zeros((seq_len - 1, self.n_states, self.n_states));

        for t in 0..(seq_len - 1) {
            for i in 0..self.n_states {
                for j in 0..self.n_states {
                    let emission_prob = self.gaussian_pdf(
                        &sequence.row(t + 1),
                        &emission_means.row(j),
                        &emission_covariances.slice(s![j, .., ..]),
                    );
                    xi[[t, i, j]] = alpha[[t, i]]
                        * transition_matrix[[i, j]]
                        * emission_prob
                        * beta[[t + 1, j]]
                        / likelihood;
                }
            }
        }

        Ok(xi)
    }

    /// Gaussian PDF for emission probabilities
    fn gaussian_pdf(
        &self,
        x: &ArrayView1<Float>,
        mean: &ArrayView1<Float>,
        _covariance: &ArrayView2<Float>,
    ) -> Float {
        // Simplified Gaussian PDF (assuming diagonal covariance = identity)
        let diff = x - mean;
        let exp_term = -0.5 * diff.dot(&diff);
        exp_term.exp()
    }
}

impl Predict<Array3<Float>, Array2<i32>> for HiddenMarkovModel<HiddenMarkovModelTrained> {
    fn predict(&self, X: &Array3<Float>) -> SklResult<Array2<i32>> {
        let (n_sequences, max_length, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features does not match training data".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_sequences, max_length));

        for seq_idx in 0..n_sequences {
            let sequence = X.slice(s![seq_idx, .., ..]);

            // Viterbi decoding for most likely state sequence
            let state_path = self.viterbi_decode(&sequence)?;

            for (t, &state) in state_path.iter().enumerate() {
                if t < max_length {
                    predictions[[seq_idx, t]] = state as i32;
                }
            }
        }

        Ok(predictions)
    }
}

impl HiddenMarkovModel<HiddenMarkovModelTrained> {
    /// Viterbi algorithm for finding most likely state sequence
    fn viterbi_decode(&self, sequence: &ArrayView2<Float>) -> SklResult<Vec<usize>> {
        let seq_len = sequence.nrows();
        let mut viterbi = Array2::zeros((seq_len, self.state.n_states));
        let mut backpointer = Array2::zeros((seq_len, self.state.n_states));

        // Initialize
        for i in 0..self.state.n_states {
            let emission_prob =
                self.gaussian_pdf(&sequence.row(0), &self.state.emission_means.row(i));
            viterbi[[0, i]] = self.state.initial_probabilities[i] * emission_prob;
        }

        // Forward pass
        for t in 1..seq_len {
            for j in 0..self.state.n_states {
                let mut best_score = 0.0;
                let mut best_prev = 0;

                for i in 0..self.state.n_states {
                    let score = viterbi[[t - 1, i]] * self.state.transition_matrix[[i, j]];
                    if score > best_score {
                        best_score = score;
                        best_prev = i;
                    }
                }

                let emission_prob =
                    self.gaussian_pdf(&sequence.row(t), &self.state.emission_means.row(j));
                viterbi[[t, j]] = best_score * emission_prob;
                backpointer[[t, j]] = best_prev as Float;
            }
        }

        // Find best final state
        let mut best_final_score = 0.0;
        let mut best_final_state = 0;

        for i in 0..self.state.n_states {
            if viterbi[[seq_len - 1, i]] > best_final_score {
                best_final_score = viterbi[[seq_len - 1, i]];
                best_final_state = i;
            }
        }

        // Backtrack
        let mut path = vec![0; seq_len];
        path[seq_len - 1] = best_final_state;

        for t in (1..seq_len).rev() {
            path[t - 1] = backpointer[[t, path[t]]] as usize;
        }

        Ok(path)
    }

    /// Simplified Gaussian PDF
    fn gaussian_pdf(&self, x: &ArrayView1<Float>, mean: &ArrayView1<Float>) -> Float {
        let diff = x - mean;
        let exp_term = -0.5 * diff.dot(&diff);
        exp_term.exp()
    }

    /// Get transition matrix
    pub fn transition_matrix(&self) -> &Array2<Float> {
        &self.state.transition_matrix
    }

    /// Get emission means
    pub fn emission_means(&self) -> &Array2<Float> {
        &self.state.emission_means
    }

    /// Get initial probabilities
    pub fn initial_probabilities(&self) -> &Array1<Float> {
        &self.state.initial_probabilities
    }
}

/// Log-sum-exp trick for numerical stability
fn log_sum_exp(a: Float, b: Float) -> Float {
    if a > b {
        a + (b - a).exp().ln_1p()
    } else {
        b + (a - b).exp().ln_1p()
    }
}

// =============================================================================
// HIERARCHICAL PREDICTION METHODS
// =============================================================================

/// Hierarchical Multi-Label Classification
///
/// A multi-label classification approach that leverages hierarchical relationships
/// between labels. This method enforces consistency in the label hierarchy by
/// ensuring that if a child label is predicted, its parent labels are also predicted.
/// Particularly useful for taxonomic classification, gene ontology annotation,
/// and other domains with natural label hierarchies.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::HierarchicalMultiLabelClassifier;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
/// let y = array![[1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0]]; // 4 labels in hierarchy
///
/// // Define hierarchy: child -> parent relationships
/// let hierarchy = vec![(2, 0), (3, 1)]; // label 2 is child of 0, label 3 is child of 1
///
/// let hmlc = HierarchicalMultiLabelClassifier::new()
///     .hierarchy(hierarchy)
///     .violation_penalty(1.0);
/// let trained_hmlc = hmlc.fit(&X, &y).unwrap();
/// let predictions = trained_hmlc.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct HierarchicalMultiLabelClassifier<State = Untrained> {
    hierarchy: Vec<(usize, usize)>, // (child, parent) pairs
    violation_penalty: Float,
    base_classifier_type: String,
    consistency_enforcement: ConsistencyEnforcement,
    state: State,
}

/// Methods for enforcing hierarchical consistency
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsistencyEnforcement {
    /// Post-process predictions to enforce consistency
    PostProcessing,
    /// Include hierarchy constraints in loss function
    ConstrainedTraining,
    /// Use Bayesian inference with hierarchy priors
    BayesianInference,
}

/// Trained state for Hierarchical Multi-Label Classifier
#[derive(Debug, Clone)]
pub struct HierarchicalMultiLabelClassifierTrained {
    binary_classifiers: Vec<BinaryRelevance<BinaryRelevanceTrained>>,
    hierarchy: Vec<(usize, usize)>,
    hierarchy_matrix: Array2<Float>,
    n_labels: usize,
    violation_penalty: Float,
    consistency_enforcement: ConsistencyEnforcement,
}

impl HierarchicalMultiLabelClassifier<Untrained> {
    /// Create new hierarchical multi-label classifier
    pub fn new() -> Self {
        Self {
            hierarchy: Vec::new(),
            violation_penalty: 1.0,
            base_classifier_type: "binary_relevance".to_string(),
            consistency_enforcement: ConsistencyEnforcement::PostProcessing,
            state: Untrained,
        }
    }

    /// Set label hierarchy as (child, parent) pairs
    pub fn hierarchy(mut self, hierarchy: Vec<(usize, usize)>) -> Self {
        self.hierarchy = hierarchy;
        self
    }

    /// Set penalty for hierarchy violations
    pub fn violation_penalty(mut self, penalty: Float) -> Self {
        self.violation_penalty = penalty;
        self
    }

    /// Set consistency enforcement method
    pub fn consistency_enforcement(mut self, method: ConsistencyEnforcement) -> Self {
        self.consistency_enforcement = method;
        self
    }

    /// Set base classifier type
    pub fn base_classifier_type(mut self, classifier_type: String) -> Self {
        self.base_classifier_type = classifier_type;
        self
    }
}

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

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

impl Fit<Array2<Float>, Array2<i32>> for HierarchicalMultiLabelClassifier<Untrained> {
    type Fitted = HierarchicalMultiLabelClassifier<HierarchicalMultiLabelClassifierTrained>;

    fn fit(self, X: &Array2<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, _n_features) = X.dim();
        let (y_samples, n_labels) = y.dim();

        if n_samples != y_samples {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        // Build hierarchy matrix (n_labels x n_labels)
        let mut hierarchy_matrix = Array2::zeros((n_labels, n_labels));
        for &(child, parent) in &self.hierarchy {
            if child < n_labels && parent < n_labels {
                hierarchy_matrix[[child, parent]] = 1.0;
            }
        }

        // Add transitive closure for hierarchy
        for k in 0..n_labels {
            for i in 0..n_labels {
                for j in 0..n_labels {
                    if hierarchy_matrix[[i, k]] > 0.0 && hierarchy_matrix[[k, j]] > 0.0 {
                        hierarchy_matrix[[i, j]] = 1.0;
                    }
                }
            }
        }

        // Train binary classifiers for each label
        let mut binary_classifiers = Vec::new();

        for label_idx in 0..n_labels {
            // Create modified training data based on consistency enforcement
            let y_modified = match self.consistency_enforcement {
                ConsistencyEnforcement::ConstrainedTraining => self
                    .apply_hierarchy_constraints_training(
                        &y.view(),
                        label_idx,
                        &hierarchy_matrix,
                    )?,
                _ => y.column(label_idx).to_owned(),
            };

            let binary_classifier = BinaryRelevance::new();
            let y_2d = y_modified.insert_axis(ndarray::Axis(1));
            let trained_classifier = binary_classifier.fit(&X.view(), &y_2d)?;
            binary_classifiers.push(trained_classifier);
        }

        Ok(HierarchicalMultiLabelClassifier {
            hierarchy: self.hierarchy.clone(),
            violation_penalty: self.violation_penalty,
            base_classifier_type: self.base_classifier_type.clone(),
            consistency_enforcement: self.consistency_enforcement,
            state: HierarchicalMultiLabelClassifierTrained {
                binary_classifiers,
                hierarchy: self.hierarchy,
                hierarchy_matrix,
                n_labels,
                violation_penalty: self.violation_penalty,
                consistency_enforcement: self.consistency_enforcement.clone(),
            },
        })
    }
}

impl HierarchicalMultiLabelClassifier<Untrained> {
    /// Apply hierarchy constraints during training
    fn apply_hierarchy_constraints_training(
        &self,
        y: &ArrayView2<i32>,
        label_idx: usize,
        hierarchy_matrix: &Array2<Float>,
    ) -> SklResult<Array1<i32>> {
        let n_samples = y.nrows();
        let mut y_modified = y.column(label_idx).to_owned();

        for sample_idx in 0..n_samples {
            let mut labels = y.row(sample_idx).to_owned();

            // Enforce hierarchy: if child is positive, parent must be positive
            for i in 0..labels.len() {
                if labels[i] == 1 {
                    for j in 0..labels.len() {
                        if hierarchy_matrix[[i, j]] > 0.0 {
                            labels[j] = 1;
                        }
                    }
                }
            }

            y_modified[sample_idx] = labels[label_idx];
        }

        Ok(y_modified)
    }
}

impl Predict<Array2<Float>, Array2<i32>>
    for HierarchicalMultiLabelClassifier<HierarchicalMultiLabelClassifierTrained>
{
    fn predict(&self, X: &Array2<Float>) -> SklResult<Array2<i32>> {
        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.state.n_labels));

        // Get raw predictions from binary classifiers
        for (label_idx, classifier) in self.state.binary_classifiers.iter().enumerate() {
            let label_predictions = classifier.predict(&X.view())?;
            for sample_idx in 0..n_samples {
                predictions[[sample_idx, label_idx]] = label_predictions[[sample_idx, 0]];
            }
        }

        // Apply consistency enforcement
        match self.state.consistency_enforcement {
            ConsistencyEnforcement::PostProcessing => {
                self.apply_hierarchy_consistency_post_processing(&mut predictions)?;
            }
            ConsistencyEnforcement::BayesianInference => {
                let probabilities = self.predict_proba(&X.view())?;
                predictions = self.apply_bayesian_hierarchy_inference(&probabilities)?;
            }
            _ => {} // Already handled during training
        }

        Ok(predictions)
    }
}

impl HierarchicalMultiLabelClassifier<HierarchicalMultiLabelClassifierTrained> {
    /// Apply hierarchy consistency via post-processing
    fn apply_hierarchy_consistency_post_processing(
        &self,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        let n_samples = predictions.nrows();

        for sample_idx in 0..n_samples {
            let mut changed = true;
            while changed {
                changed = false;

                // Bottom-up propagation: if child is positive, make parent positive
                for &(child, parent) in &self.state.hierarchy {
                    if predictions[[sample_idx, child]] == 1
                        && predictions[[sample_idx, parent]] == 0
                    {
                        predictions[[sample_idx, parent]] = 1;
                        changed = true;
                    }
                }

                // Top-down propagation: if parent is negative, make children negative
                for &(child, parent) in &self.state.hierarchy {
                    if predictions[[sample_idx, parent]] == 0
                        && predictions[[sample_idx, child]] == 1
                    {
                        predictions[[sample_idx, child]] = 0;
                        changed = true;
                    }
                }
            }
        }

        Ok(())
    }

    /// Apply Bayesian hierarchy inference
    fn apply_bayesian_hierarchy_inference(
        &self,
        probabilities: &Array2<Float>,
    ) -> SklResult<Array2<i32>> {
        let (n_samples, n_labels) = probabilities.dim();
        let mut predictions = Array2::zeros((n_samples, n_labels));

        for sample_idx in 0..n_samples {
            let probs = probabilities.row(sample_idx);

            // Use dynamic programming to find optimal consistent labeling
            let optimal_labels = self.find_optimal_consistent_labeling(&probs)?;

            for (label_idx, &label) in optimal_labels.iter().enumerate() {
                predictions[[sample_idx, label_idx]] = label;
            }
        }

        Ok(predictions)
    }

    /// Find optimal consistent labeling using dynamic programming
    fn find_optimal_consistent_labeling(
        &self,
        probabilities: &ArrayView1<Float>,
    ) -> SklResult<Vec<i32>> {
        let n_labels = probabilities.len();
        let mut best_score = Float::NEG_INFINITY;
        let mut best_labeling = vec![0; n_labels];

        // Enumerate all possible labelings (2^n_labels)
        for labeling_int in 0..(1 << n_labels) {
            let mut labeling = vec![0; n_labels];
            for i in 0..n_labels {
                labeling[i] = if (labeling_int >> i) & 1 == 1 { 1 } else { 0 };
            }

            // Check hierarchy consistency
            let mut is_consistent = true;
            for &(child, parent) in &self.state.hierarchy {
                if labeling[child] == 1 && labeling[parent] == 0 {
                    is_consistent = false;
                    break;
                }
            }

            if is_consistent {
                // Compute score
                let mut score = 0.0;
                for i in 0..n_labels {
                    if labeling[i] == 1 {
                        score += probabilities[i].ln();
                    } else {
                        score += (1.0 - probabilities[i]).ln();
                    }
                }

                if score > best_score {
                    best_score = score;
                    best_labeling = labeling;
                }
            }
        }

        Ok(best_labeling)
    }

    /// Predict class probabilities
    pub fn predict_proba(&self, X: &ArrayView2<Float>) -> SklResult<Array2<Float>> {
        let n_samples = X.nrows();
        let mut probabilities = Array2::zeros((n_samples, self.state.n_labels));

        for (label_idx, classifier) in self.state.binary_classifiers.iter().enumerate() {
            let label_probabilities = classifier.predict_proba(X)?;
            for sample_idx in 0..n_samples {
                probabilities[[sample_idx, label_idx]] = label_probabilities[[sample_idx, 1]];
                // Probability of positive class
            }
        }

        Ok(probabilities)
    }

    /// Get hierarchy matrix
    pub fn hierarchy_matrix(&self) -> &Array2<Float> {
        &self.state.hierarchy_matrix
    }

    /// Get hierarchy relationships
    pub fn hierarchy(&self) -> &Vec<(usize, usize)> {
        &self.state.hierarchy
    }
}

/// Tree-Structured Output Prediction
///
/// A structured prediction method for outputs that follow a tree structure.
/// This is useful for tasks like parse tree prediction, decision tree paths,
/// or any hierarchical classification where the output space has a tree structure.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::TreeStructuredPredictor;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0]];
/// let y = array![[0, 1, 2], [1, 0, 2]]; // Tree paths as sequences
///
/// let tree_predictor = TreeStructuredPredictor::new()
///     .max_depth(3)
///     .branching_factor(3);
/// let trained_predictor = tree_predictor.fit(&X, &y).unwrap();
/// let predictions = trained_predictor.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct TreeStructuredPredictor<State = Untrained> {
    max_depth: usize,
    branching_factor: usize,
    tree_structure: Vec<Vec<usize>>, // Adjacency list representation
    node_classifiers: HashMap<usize, String>,
    state: State,
}

/// Trained state for Tree-Structured Predictor
#[derive(Debug, Clone)]
pub struct TreeStructuredPredictorTrained {
    node_classifiers: HashMap<usize, BinaryRelevance<BinaryRelevanceTrained>>,
    tree_structure: Vec<Vec<usize>>,
    max_depth: usize,
    n_nodes: usize,
}

impl TreeStructuredPredictor<Untrained> {
    /// Create new tree-structured predictor
    pub fn new() -> Self {
        Self {
            max_depth: 5,
            branching_factor: 2,
            tree_structure: Vec::new(),
            node_classifiers: HashMap::new(),
            state: Untrained,
        }
    }

    /// Set maximum tree depth
    pub fn max_depth(mut self, depth: usize) -> Self {
        self.max_depth = depth;
        self
    }

    /// Set branching factor
    pub fn branching_factor(mut self, factor: usize) -> Self {
        self.branching_factor = factor;
        self
    }

    /// Set custom tree structure
    pub fn tree_structure(mut self, structure: Vec<Vec<usize>>) -> Self {
        self.tree_structure = structure;
        self
    }
}

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

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

impl Fit<Array2<Float>, Array2<i32>> for TreeStructuredPredictor<Untrained> {
    type Fitted = TreeStructuredPredictor<TreeStructuredPredictorTrained>;

    fn fit(self, X: &Array2<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, _n_features) = X.dim();
        let (y_samples, max_path_length) = y.dim();

        if n_samples != y_samples {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        // Build tree structure if not provided
        let tree_structure = if self.tree_structure.is_empty() {
            self.build_default_tree_structure()?
        } else {
            self.tree_structure.clone()
        };

        let n_nodes = tree_structure.len();
        let mut node_classifiers = HashMap::new();

        // Train classifier for each internal node
        for node_id in 0..n_nodes {
            if !tree_structure[node_id].is_empty() {
                // Internal node
                // Create binary classification data for this node
                let (node_X, node_y) = self.create_node_training_data(
                    &X.view(),
                    &y.view(),
                    node_id,
                    &tree_structure,
                    max_path_length,
                )?;

                if node_y.len() > 0 {
                    let classifier = BinaryRelevance::new();
                    let trained_classifier = classifier.fit(&node_X.view(), &node_y)?;
                    node_classifiers.insert(node_id, trained_classifier);
                }
            }
        }

        Ok(TreeStructuredPredictor {
            max_depth: self.max_depth,
            branching_factor: self.branching_factor,
            tree_structure: tree_structure.clone(),
            node_classifiers: HashMap::new(),
            state: TreeStructuredPredictorTrained {
                node_classifiers,
                tree_structure,
                max_depth: self.max_depth,
                n_nodes,
            },
        })
    }
}

impl TreeStructuredPredictor<Untrained> {
    /// Build default tree structure
    fn build_default_tree_structure(&self) -> SklResult<Vec<Vec<usize>>> {
        let mut total_nodes = 0;
        for depth in 0..self.max_depth {
            total_nodes += self.branching_factor.pow(depth as u32);
        }

        let mut tree_structure = vec![Vec::new(); total_nodes];
        let mut node_id = 0;

        // Build complete tree
        for depth in 0..(self.max_depth - 1) {
            let nodes_at_depth = self.branching_factor.pow(depth as u32);

            for _ in 0..nodes_at_depth {
                for child in 0..self.branching_factor {
                    let child_id = node_id + nodes_at_depth + child;
                    if child_id < total_nodes {
                        tree_structure[node_id].push(child_id);
                    }
                }
                node_id += 1;
            }
        }

        Ok(tree_structure)
    }

    /// Create training data for a specific node
    fn create_node_training_data(
        &self,
        X: &ArrayView2<Float>,
        y: &ArrayView2<i32>,
        node_id: usize,
        tree_structure: &Vec<Vec<usize>>,
        max_path_length: usize,
    ) -> SklResult<(Array2<Float>, Array2<i32>)> {
        let n_samples = X.nrows();
        let mut valid_samples = Vec::new();
        let mut node_labels = Vec::new();

        for sample_idx in 0..n_samples {
            let path = y.row(sample_idx);

            // Check if this sample's path passes through this node
            for pos in 0..max_path_length {
                if path[pos] as usize == node_id && pos + 1 < max_path_length {
                    // Sample passes through this node, determine which child to predict
                    let next_node = path[pos + 1] as usize;

                    // Find which child index this corresponds to
                    if let Some(child_idx) = tree_structure[node_id]
                        .iter()
                        .position(|&child| child == next_node)
                    {
                        valid_samples.push(sample_idx);
                        node_labels.push(child_idx as i32);
                        break;
                    }
                }
            }
        }

        // Create training data for this node
        let n_valid = valid_samples.len();
        if n_valid == 0 {
            return Ok((Array2::zeros((0, X.ncols())), Array2::zeros((0, 1))));
        }

        let mut node_X = Array2::zeros((n_valid, X.ncols()));
        let mut node_y = Array2::zeros((n_valid, 1));

        for (i, &sample_idx) in valid_samples.iter().enumerate() {
            for j in 0..X.ncols() {
                node_X[[i, j]] = X[[sample_idx, j]];
            }
            node_y[[i, 0]] = node_labels[i];
        }

        Ok((node_X, node_y))
    }
}

impl Predict<Array2<Float>, Array2<i32>>
    for TreeStructuredPredictor<TreeStructuredPredictorTrained>
{
    fn predict(&self, X: &Array2<Float>) -> SklResult<Array2<i32>> {
        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.state.max_depth));

        for sample_idx in 0..n_samples {
            let sample = X.row(sample_idx);
            let path = self.predict_tree_path(&sample)?;

            for (pos, &node) in path.iter().enumerate() {
                if pos < self.state.max_depth {
                    predictions[[sample_idx, pos]] = node as i32;
                }
            }
        }

        Ok(predictions)
    }
}

impl TreeStructuredPredictor<TreeStructuredPredictorTrained> {
    /// Predict tree path for a single sample
    fn predict_tree_path(&self, sample: &ArrayView1<Float>) -> SklResult<Vec<usize>> {
        let mut path = Vec::new();
        let mut current_node = 0; // Start at root
        path.push(current_node);

        while !self.state.tree_structure[current_node].is_empty() {
            // Internal node - predict which child to take
            if let Some(classifier) = self.state.node_classifiers.get(&current_node) {
                let sample_2d = sample.to_owned().insert_axis(ndarray::Axis(0));
                let prediction = classifier.predict(&sample_2d.view())?;
                let child_idx = prediction[[0, 0]] as usize;

                if child_idx < self.state.tree_structure[current_node].len() {
                    current_node = self.state.tree_structure[current_node][child_idx];
                    path.push(current_node);
                } else {
                    break; // Invalid prediction
                }
            } else {
                break; // No classifier for this node
            }
        }

        Ok(path)
    }

    /// Get tree structure
    pub fn tree_structure(&self) -> &Vec<Vec<usize>> {
        &self.state.tree_structure
    }
}

/// DAG-Structured Prediction
///
/// A structured prediction method for outputs that follow a directed acyclic graph (DAG)
/// structure. This is useful for tasks like workflow prediction, dependency parsing,
/// or any classification where the output space has a DAG structure with multiple paths.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::DAGStructuredPredictor;
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0]];
/// let y = array![[1, 1, 0, 1], [0, 1, 1, 0]]; // DAG node activations
///
/// let dag_predictor = DAGStructuredPredictor::new()
///     .add_edge(0, 2)
///     .add_edge(1, 2)
///     .add_edge(2, 3);
/// let trained_predictor = dag_predictor.fit(&X, &y).unwrap();
/// let predictions = trained_predictor.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct DAGStructuredPredictor<State = Untrained> {
    dag_edges: Vec<(usize, usize)>, // (parent, child) pairs
    topological_order: Vec<usize>,
    inference_method: DAGInferenceMethod,
    state: State,
}

/// Methods for DAG inference
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DAGInferenceMethod {
    /// Greedy inference following topological order
    Greedy,
    /// Belief propagation on the DAG
    BeliefPropagation,
    /// Integer linear programming for exact inference
    ExactILP,
}

/// Trained state for DAG-Structured Predictor
#[derive(Debug, Clone)]
pub struct DAGStructuredPredictorTrained {
    node_classifiers: HashMap<usize, BinaryRelevance<BinaryRelevanceTrained>>,
    dag_edges: Vec<(usize, usize)>,
    topological_order: Vec<usize>,
    adjacency_matrix: Array2<Float>,
    n_nodes: usize,
    inference_method: DAGInferenceMethod,
}

impl DAGStructuredPredictor<Untrained> {
    /// Create new DAG-structured predictor
    pub fn new() -> Self {
        Self {
            dag_edges: Vec::new(),
            topological_order: Vec::new(),
            inference_method: DAGInferenceMethod::Greedy,
            state: Untrained,
        }
    }

    /// Add edge to DAG structure
    pub fn add_edge(mut self, parent: usize, child: usize) -> Self {
        self.dag_edges.push((parent, child));
        self
    }

    /// Set DAG edges
    pub fn dag_edges(mut self, edges: Vec<(usize, usize)>) -> Self {
        self.dag_edges = edges;
        self
    }

    /// Set inference method
    pub fn inference_method(mut self, method: DAGInferenceMethod) -> Self {
        self.inference_method = method;
        self
    }
}

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

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

impl Fit<Array2<Float>, Array2<i32>> for DAGStructuredPredictor<Untrained> {
    type Fitted = DAGStructuredPredictor<DAGStructuredPredictorTrained>;

    fn fit(self, X: &Array2<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, _n_features) = X.dim();
        let (y_samples, n_nodes) = y.dim();

        if n_samples != y_samples {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        // Build adjacency matrix
        let mut adjacency_matrix = Array2::zeros((n_nodes, n_nodes));
        for &(parent, child) in &self.dag_edges {
            if parent < n_nodes && child < n_nodes {
                adjacency_matrix[[parent, child]] = 1.0;
            }
        }

        // Compute topological ordering
        let topological_order = self.compute_topological_order(n_nodes)?;

        // Train classifier for each node
        let mut node_classifiers = HashMap::new();

        for &node_id in &topological_order {
            // Get parent features for this node
            let node_features =
                self.create_node_features(&X.view(), &y.view(), node_id, &adjacency_matrix)?;
            let node_labels = y.column(node_id).to_owned();

            let classifier = BinaryRelevance::new();
            let node_labels_2d = node_labels.insert_axis(ndarray::Axis(1));
            let trained_classifier = classifier.fit(&node_features.view(), &node_labels_2d)?;
            node_classifiers.insert(node_id, trained_classifier);
        }

        Ok(DAGStructuredPredictor {
            dag_edges: self.dag_edges.clone(),
            topological_order: topological_order.clone(),
            inference_method: self.inference_method,
            state: DAGStructuredPredictorTrained {
                node_classifiers,
                dag_edges: self.dag_edges,
                topological_order,
                adjacency_matrix,
                n_nodes,
                inference_method: self.inference_method.clone(),
            },
        })
    }
}

impl DAGStructuredPredictor<Untrained> {
    /// Compute topological ordering of DAG
    fn compute_topological_order(&self, n_nodes: usize) -> SklResult<Vec<usize>> {
        let mut in_degree = vec![0; n_nodes];
        let mut adj_list = vec![Vec::new(); n_nodes];

        // Build adjacency list and compute in-degrees
        for &(parent, child) in &self.dag_edges {
            adj_list[parent].push(child);
            in_degree[child] += 1;
        }

        // Kahn's algorithm for topological sorting
        let mut queue = Vec::new();
        let mut topo_order = Vec::new();

        // Add all nodes with in-degree 0 to queue
        for node in 0..n_nodes {
            if in_degree[node] == 0 {
                queue.push(node);
            }
        }

        while let Some(node) = queue.pop() {
            topo_order.push(node);

            // Update in-degrees of neighbors
            for &neighbor in &adj_list[node] {
                in_degree[neighbor] -= 1;
                if in_degree[neighbor] == 0 {
                    queue.push(neighbor);
                }
            }
        }

        if topo_order.len() != n_nodes {
            return Err(SklearsError::InvalidInput(
                "DAG contains cycles - not a valid DAG".to_string(),
            ));
        }

        Ok(topo_order)
    }

    /// Create features for a node including parent node information
    fn create_node_features(
        &self,
        X: &ArrayView2<Float>,
        y: &ArrayView2<i32>,
        node_id: usize,
        adjacency_matrix: &Array2<Float>,
    ) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();

        // Count parent nodes
        let n_parents = adjacency_matrix.column(node_id).sum() as usize;
        let feature_size = n_features + n_parents;

        let mut node_features = Array2::zeros((n_samples, feature_size));

        // Copy original features
        for i in 0..n_samples {
            for j in 0..n_features {
                node_features[[i, j]] = X[[i, j]];
            }
        }

        // Add parent node features
        let mut parent_idx = 0;
        for parent in 0..adjacency_matrix.nrows() {
            if adjacency_matrix[[parent, node_id]] > 0.0 {
                for i in 0..n_samples {
                    node_features[[i, n_features + parent_idx]] = y[[i, parent]] as Float;
                }
                parent_idx += 1;
            }
        }

        Ok(node_features)
    }
}

impl Predict<Array2<Float>, Array2<i32>> for DAGStructuredPredictor<DAGStructuredPredictorTrained> {
    fn predict(&self, X: &Array2<Float>) -> SklResult<Array2<i32>> {
        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.state.n_nodes));

        match self.state.inference_method {
            DAGInferenceMethod::Greedy => {
                self.greedy_inference(&X.view(), &mut predictions)?;
            }
            DAGInferenceMethod::BeliefPropagation => {
                self.belief_propagation_inference(&X.view(), &mut predictions)?;
            }
            DAGInferenceMethod::ExactILP => {
                // For simplicity, fall back to greedy inference
                self.greedy_inference(&X.view(), &mut predictions)?;
            }
        }

        Ok(predictions)
    }
}

impl DAGStructuredPredictor<DAGStructuredPredictorTrained> {
    /// Greedy inference following topological order
    fn greedy_inference(
        &self,
        X: &ArrayView2<Float>,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        let n_samples = X.nrows();

        for sample_idx in 0..n_samples {
            for &node_id in &self.state.topological_order {
                if let Some(classifier) = self.state.node_classifiers.get(&node_id) {
                    // Create features for this node
                    let node_features = self.create_prediction_features(
                        &X.row(sample_idx),
                        &predictions.row(sample_idx),
                        node_id,
                    )?;

                    let node_prediction =
                        classifier.predict(&node_features.insert_axis(ndarray::Axis(0)).view())?;
                    predictions[[sample_idx, node_id]] = node_prediction[[0, 0]];
                }
            }
        }

        Ok(())
    }

    /// Belief propagation inference (simplified)
    fn belief_propagation_inference(
        &self,
        X: &ArrayView2<Float>,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        // For simplicity, use greedy inference
        // In a full implementation, this would use message passing
        self.greedy_inference(X, predictions)
    }

    /// Create features for prediction including parent predictions
    fn create_prediction_features(
        &self,
        sample: &ArrayView1<Float>,
        current_predictions: &ArrayView1<i32>,
        node_id: usize,
    ) -> SklResult<Array1<Float>> {
        let n_features = sample.len();
        let n_parents = self.state.adjacency_matrix.column(node_id).sum() as usize;
        let feature_size = n_features + n_parents;

        let mut node_features = Array1::zeros(feature_size);

        // Copy original features
        for i in 0..n_features {
            node_features[i] = sample[i];
        }

        // Add parent predictions
        let mut parent_idx = 0;
        for parent in 0..self.state.adjacency_matrix.nrows() {
            if self.state.adjacency_matrix[[parent, node_id]] > 0.0 {
                node_features[n_features + parent_idx] = current_predictions[parent] as Float;
                parent_idx += 1;
            }
        }

        Ok(node_features)
    }

    /// Get DAG structure
    pub fn dag_edges(&self) -> &Vec<(usize, usize)> {
        &self.state.dag_edges
    }

    /// Get topological order
    pub fn topological_order(&self) -> &Vec<usize> {
        &self.state.topological_order
    }

    /// Get adjacency matrix
    pub fn adjacency_matrix(&self) -> &Array2<Float> {
        &self.state.adjacency_matrix
    }
}

// =============================================================================
// GRAPH-STRUCTURED OUTPUT PREDICTION METHODS
// =============================================================================

/// Graph-Based Structured Prediction
///
/// A structured prediction method for outputs that have a general graph structure.
/// This supports both directed and undirected graphs and uses message passing
/// algorithms for inference. Particularly useful for social network analysis,
/// molecule prediction, knowledge graph completion, and other tasks where
/// outputs have complex graph relationships.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Fit, Predict};
/// use sklears_multioutput::{GraphStructuredPredictor, GraphType};
/// use ndarray::array;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
/// let y = array![[1, 0, 1], [0, 1, 0], [1, 1, 0]]; // Node labels
/// let edges = vec![(0, 1), (1, 2), (0, 2)]; // Graph edges
///
/// let graph_predictor = GraphStructuredPredictor::new()
///     .graph_type(GraphType::Undirected)
///     .edges(edges)
///     .message_passing_iterations(10);
/// let trained_predictor = graph_predictor.fit(&X, &y).unwrap();
/// let predictions = trained_predictor.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct GraphStructuredPredictor<State = Untrained> {
    graph_type: GraphType,
    edges: Vec<(usize, usize)>,
    message_passing_iterations: usize,
    inference_method: GraphInferenceMethod,
    node_feature_dim: usize,
    edge_feature_dim: usize,
    state: State,
}

/// Types of graphs supported
#[derive(Debug, Clone)]
pub enum GraphType {
    /// Undirected graph
    Undirected,
    /// Directed graph
    Directed,
    /// Bipartite graph
    Bipartite,
}

/// Methods for graph inference
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraphInferenceMethod {
    /// Message passing with belief propagation
    MessagePassing,
    /// Graph neural network approach
    GraphNeuralNetwork,
    /// Variational inference
    VariationalInference,
    /// Spectral methods
    SpectralMethods,
}

/// Trained state for Graph-Structured Predictor
#[derive(Debug, Clone)]
pub struct GraphStructuredPredictorTrained {
    node_classifiers: HashMap<usize, BinaryRelevance<BinaryRelevanceTrained>>,
    edge_weights: Array2<Float>,
    adjacency_matrix: Array2<Float>,
    graph_type: GraphType,
    edges: Vec<(usize, usize)>,
    message_passing_iterations: usize,
    inference_method: GraphInferenceMethod,
    n_nodes: usize,
    node_potentials: Array2<Float>,
    edge_potentials: Array3<Float>,
}

impl GraphStructuredPredictor<Untrained> {
    /// Create new graph-structured predictor
    pub fn new() -> Self {
        Self {
            graph_type: GraphType::Undirected,
            edges: Vec::new(),
            message_passing_iterations: 10,
            inference_method: GraphInferenceMethod::MessagePassing,
            node_feature_dim: 0,
            edge_feature_dim: 0,
            state: Untrained,
        }
    }

    /// Set graph type
    pub fn graph_type(mut self, graph_type: GraphType) -> Self {
        self.graph_type = graph_type;
        self
    }

    /// Set graph edges
    pub fn edges(mut self, edges: Vec<(usize, usize)>) -> Self {
        self.edges = edges;
        self
    }

    /// Set number of message passing iterations
    pub fn message_passing_iterations(mut self, iterations: usize) -> Self {
        self.message_passing_iterations = iterations;
        self
    }

    /// Set inference method
    pub fn inference_method(mut self, method: GraphInferenceMethod) -> Self {
        self.inference_method = method;
        self
    }

    /// Set node feature dimension
    pub fn node_feature_dim(mut self, dim: usize) -> Self {
        self.node_feature_dim = dim;
        self
    }

    /// Set edge feature dimension
    pub fn edge_feature_dim(mut self, dim: usize) -> Self {
        self.edge_feature_dim = dim;
        self
    }
}

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

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

impl Fit<Array2<Float>, Array2<i32>> for GraphStructuredPredictor<Untrained> {
    type Fitted = GraphStructuredPredictor<GraphStructuredPredictorTrained>;

    fn fit(self, X: &Array2<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_samples, _n_features) = X.dim();
        let (y_samples, n_nodes) = y.dim();

        if n_samples != y_samples {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        // Build adjacency matrix
        let adjacency_matrix = self.build_adjacency_matrix(n_nodes)?;

        // Compute edge weights using node correlations
        let edge_weights = self.compute_edge_weights(&y.view(), &adjacency_matrix)?;

        // Train node classifiers
        let node_classifiers = self.train_node_classifiers(&X.view(), &y.view())?;

        // Compute potentials for inference
        let (node_potentials, edge_potentials) =
            self.compute_potentials(&X.view(), &y.view(), &adjacency_matrix)?;

        Ok(GraphStructuredPredictor {
            graph_type: self.graph_type.clone(),
            edges: self.edges.clone(),
            message_passing_iterations: self.message_passing_iterations,
            inference_method: self.inference_method,
            node_feature_dim: self.node_feature_dim,
            edge_feature_dim: self.edge_feature_dim,
            state: GraphStructuredPredictorTrained {
                node_classifiers,
                edge_weights,
                adjacency_matrix,
                graph_type: self.graph_type,
                edges: self.edges,
                message_passing_iterations: self.message_passing_iterations,
                inference_method: self.inference_method.clone(),
                n_nodes,
                node_potentials,
                edge_potentials,
            },
        })
    }
}

impl GraphStructuredPredictor<Untrained> {
    /// Build adjacency matrix from edges
    fn build_adjacency_matrix(&self, n_nodes: usize) -> SklResult<Array2<Float>> {
        let mut adjacency_matrix = Array2::zeros((n_nodes, n_nodes));

        for &(i, j) in &self.edges {
            if i < n_nodes && j < n_nodes {
                adjacency_matrix[[i, j]] = 1.0;

                // For undirected graphs, add symmetric edge
                match self.graph_type {
                    GraphType::Undirected | GraphType::Bipartite => {
                        adjacency_matrix[[j, i]] = 1.0;
                    }
                    GraphType::Directed => {
                        // Already added above
                    }
                }
            }
        }

        Ok(adjacency_matrix)
    }

    /// Compute edge weights based on label correlations
    fn compute_edge_weights(
        &self,
        y: &ArrayView2<i32>,
        adjacency_matrix: &Array2<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = y.ncols();
        let mut edge_weights = Array2::zeros((n_nodes, n_nodes));

        // Compute mutual information between connected nodes
        for i in 0..n_nodes {
            for j in 0..n_nodes {
                if adjacency_matrix[[i, j]] > 0.0 {
                    let mi = self.compute_mutual_information(&y.column(i), &y.column(j))?;
                    edge_weights[[i, j]] = mi;
                }
            }
        }

        Ok(edge_weights)
    }

    /// Compute mutual information between two label sequences
    fn compute_mutual_information(
        &self,
        labels1: &ArrayView1<i32>,
        labels2: &ArrayView1<i32>,
    ) -> SklResult<Float> {
        let n_samples = labels1.len();
        if n_samples != labels2.len() {
            return Err(SklearsError::InvalidInput(
                "Label sequences must have same length".to_string(),
            ));
        }

        // Compute joint and marginal distributions
        let mut joint_counts = HashMap::new();
        let mut marginal1_counts = HashMap::new();
        let mut marginal2_counts = HashMap::new();

        for i in 0..n_samples {
            let l1 = labels1[i];
            let l2 = labels2[i];

            *joint_counts.entry((l1, l2)).or_insert(0) += 1;
            *marginal1_counts.entry(l1).or_insert(0) += 1;
            *marginal2_counts.entry(l2).or_insert(0) += 1;
        }

        // Compute mutual information
        let mut mi = 0.0;
        for ((l1, l2), &joint_count) in &joint_counts {
            let p_joint = joint_count as Float / n_samples as Float;
            let p_marginal1 = *marginal1_counts.get(l1).unwrap() as Float / n_samples as Float;
            let p_marginal2 = *marginal2_counts.get(l2).unwrap() as Float / n_samples as Float;

            if p_joint > 0.0 && p_marginal1 > 0.0 && p_marginal2 > 0.0 {
                mi += p_joint * (p_joint / (p_marginal1 * p_marginal2)).ln();
            }
        }

        Ok(mi)
    }

    /// Train individual node classifiers
    fn train_node_classifiers(
        &self,
        X: &ArrayView2<Float>,
        y: &ArrayView2<i32>,
    ) -> SklResult<HashMap<usize, BinaryRelevance<BinaryRelevanceTrained>>> {
        let n_nodes = y.ncols();
        let mut node_classifiers = HashMap::new();

        for node_id in 0..n_nodes {
            let node_labels = y.column(node_id).to_owned();
            let classifier = BinaryRelevance::new();
            let node_labels_2d = node_labels.insert_axis(ndarray::Axis(1));
            let trained_classifier = classifier.fit(X, &node_labels_2d)?;
            node_classifiers.insert(node_id, trained_classifier);
        }

        Ok(node_classifiers)
    }

    /// Compute node and edge potentials for inference
    fn compute_potentials(
        &self,
        X: &ArrayView2<Float>,
        y: &ArrayView2<i32>,
        adjacency_matrix: &Array2<Float>,
    ) -> SklResult<(Array2<Float>, Array3<Float>)> {
        let (n_samples, _) = X.dim();
        let n_nodes = y.ncols();

        // Node potentials: learned from data
        let mut node_potentials = Array2::zeros((n_nodes, 2)); // Binary labels
        for node_id in 0..n_nodes {
            let labels = y.column(node_id);
            let positive_count = labels.iter().filter(|&&x| x == 1).count() as Float;
            let negative_count = labels.iter().filter(|&&x| x == 0).count() as Float;
            let total = positive_count + negative_count;

            if total > 0.0 {
                node_potentials[[node_id, 0]] = negative_count / total;
                node_potentials[[node_id, 1]] = positive_count / total;
            } else {
                node_potentials[[node_id, 0]] = 0.5;
                node_potentials[[node_id, 1]] = 0.5;
            }
        }

        // Edge potentials: agreement between connected nodes
        let mut edge_potentials = Array3::zeros((n_nodes, 2, 2)); // [edge, label1, label2]
        for i in 0..n_nodes {
            for j in 0..n_nodes {
                if adjacency_matrix[[i, j]] > 0.0 {
                    // Compute empirical edge potentials
                    let mut joint_counts = Array2::zeros((2, 2));
                    for sample_idx in 0..n_samples {
                        let l1 = y[[sample_idx, i]] as usize;
                        let l2 = y[[sample_idx, j]] as usize;
                        if l1 < 2 && l2 < 2 {
                            joint_counts[[l1, l2]] += 1.0;
                        }
                    }

                    // Normalize to get probabilities
                    let total = joint_counts.sum();
                    if total > 0.0 {
                        joint_counts = joint_counts / total;
                    }

                    edge_potentials
                        .slice_mut(s![i, .., ..])
                        .assign(&joint_counts);
                }
            }
        }

        Ok((node_potentials, edge_potentials))
    }
}

impl Predict<Array2<Float>, Array2<i32>>
    for GraphStructuredPredictor<GraphStructuredPredictorTrained>
{
    fn predict(&self, X: &Array2<Float>) -> SklResult<Array2<i32>> {
        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.state.n_nodes));

        match self.state.inference_method {
            GraphInferenceMethod::MessagePassing => {
                self.message_passing_inference(&X.view(), &mut predictions)?;
            }
            GraphInferenceMethod::GraphNeuralNetwork => {
                self.graph_neural_network_inference(&X.view(), &mut predictions)?;
            }
            GraphInferenceMethod::VariationalInference => {
                self.variational_inference(&X.view(), &mut predictions)?;
            }
            GraphInferenceMethod::SpectralMethods => {
                self.spectral_inference(&X.view(), &mut predictions)?;
            }
        }

        Ok(predictions)
    }
}

impl GraphStructuredPredictor<GraphStructuredPredictorTrained> {
    /// Message passing inference using belief propagation
    fn message_passing_inference(
        &self,
        X: &ArrayView2<Float>,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        let n_samples = X.nrows();

        for sample_idx in 0..n_samples {
            // Initialize beliefs with node classifier outputs
            let mut beliefs = Array2::zeros((self.state.n_nodes, 2));
            for node_id in 0..self.state.n_nodes {
                if let Some(classifier) = self.state.node_classifiers.get(&node_id) {
                    let sample_2d = X.row(sample_idx).to_owned().insert_axis(ndarray::Axis(0));
                    let proba = classifier.predict_proba(&sample_2d.view())?;
                    // BinaryRelevance returns probabilities for each label, not binary class probabilities
                    // proba[[0, 0]] is the probability of the first (and only) label being positive
                    let positive_prob = proba[[0, 0]];
                    beliefs[[node_id, 0]] = 1.0 - positive_prob; // Probability of negative class
                    beliefs[[node_id, 1]] = positive_prob; // Probability of positive class
                } else {
                    beliefs[[node_id, 0]] = self.state.node_potentials[[node_id, 0]];
                    beliefs[[node_id, 1]] = self.state.node_potentials[[node_id, 1]];
                }
            }

            // Message passing iterations
            for _iter in 0..self.state.message_passing_iterations {
                let mut new_beliefs = beliefs.clone();

                for i in 0..self.state.n_nodes {
                    // Collect messages from neighbors
                    let mut messages = Vec::new();
                    for j in 0..self.state.n_nodes {
                        if i != j && self.state.adjacency_matrix[[i, j]] > 0.0 {
                            let message = self.compute_message(i, j, &beliefs)?;
                            messages.push(message);
                        }
                    }

                    // Update belief
                    if !messages.is_empty() {
                        for label in 0..2 {
                            let mut belief = beliefs[[i, label]];
                            for message in &messages {
                                belief *= message[label];
                            }
                            new_beliefs[[i, label]] = belief;
                        }

                        // Normalize
                        let total = new_beliefs.row(i).sum();
                        if total > 0.0 {
                            for label in 0..2 {
                                new_beliefs[[i, label]] /= total;
                            }
                        }
                    }
                }

                beliefs = new_beliefs;
            }

            // Make final predictions
            for node_id in 0..self.state.n_nodes {
                predictions[[sample_idx, node_id]] =
                    if beliefs[[node_id, 1]] > beliefs[[node_id, 0]] {
                        1
                    } else {
                        0
                    };
            }
        }

        Ok(())
    }

    /// Compute message from node j to node i
    fn compute_message(
        &self,
        i: usize,
        j: usize,
        beliefs: &Array2<Float>,
    ) -> SklResult<Vec<Float>> {
        let mut message = vec![0.0; 2];

        for label_j in 0..2 {
            for label_i in 0..2 {
                let edge_potential = if i < self.state.edge_potentials.dim().0 {
                    self.state.edge_potentials[[i, label_i, label_j]]
                } else {
                    1.0 // Default potential
                };
                message[label_i] += beliefs[[j, label_j]] * edge_potential;
            }
        }

        // Normalize message
        let total: Float = message.iter().sum();
        if total > 0.0 {
            for m in &mut message {
                *m /= total;
            }
        }

        Ok(message)
    }

    /// Graph neural network inference (simplified)
    fn graph_neural_network_inference(
        &self,
        X: &ArrayView2<Float>,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        // For simplicity, use message passing with learned weights
        self.message_passing_inference(X, predictions)
    }

    /// Variational inference for graphs
    fn variational_inference(
        &self,
        X: &ArrayView2<Float>,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        let n_samples = X.nrows();

        for sample_idx in 0..n_samples {
            // Initialize variational parameters
            let mut q_params = Array2::from_elem((self.state.n_nodes, 2), 0.5);

            // Get initial beliefs from node classifiers
            for node_id in 0..self.state.n_nodes {
                if let Some(classifier) = self.state.node_classifiers.get(&node_id) {
                    let sample_2d = X.row(sample_idx).to_owned().insert_axis(ndarray::Axis(0));
                    let proba = classifier.predict_proba(&sample_2d.view())?;
                    // BinaryRelevance returns probabilities for each label, not binary class probabilities
                    let positive_prob = proba[[0, 0]];
                    q_params[[node_id, 0]] = 1.0 - positive_prob; // Probability of negative class
                    q_params[[node_id, 1]] = positive_prob; // Probability of positive class
                }
            }

            // Coordinate ascent on ELBO
            for _iter in 0..self.state.message_passing_iterations {
                let mut new_q_params = q_params.clone();

                for i in 0..self.state.n_nodes {
                    // Update variational parameter for node i
                    for label_i in 0..2 {
                        let mut log_unnormalized = self.state.node_potentials[[i, label_i]].ln();

                        // Add contributions from neighboring nodes
                        for j in 0..self.state.n_nodes {
                            if i != j && self.state.adjacency_matrix[[i, j]] > 0.0 {
                                for label_j in 0..2 {
                                    let edge_potential = if i < self.state.edge_potentials.dim().0 {
                                        self.state.edge_potentials[[i, label_i, label_j]]
                                    } else {
                                        1.0
                                    };
                                    log_unnormalized +=
                                        q_params[[j, label_j]] * edge_potential.ln();
                                }
                            }
                        }

                        new_q_params[[i, label_i]] = log_unnormalized.exp();
                    }

                    // Normalize
                    let total = new_q_params.row(i).sum();
                    if total > 0.0 {
                        for label in 0..2 {
                            new_q_params[[i, label]] /= total;
                        }
                    }
                }

                q_params = new_q_params;
            }

            // Make predictions based on variational parameters
            for node_id in 0..self.state.n_nodes {
                predictions[[sample_idx, node_id]] =
                    if q_params[[node_id, 1]] > q_params[[node_id, 0]] {
                        1
                    } else {
                        0
                    };
            }
        }

        Ok(())
    }

    /// Spectral methods for graph inference
    fn spectral_inference(
        &self,
        X: &ArrayView2<Float>,
        predictions: &mut Array2<i32>,
    ) -> SklResult<()> {
        let n_samples = X.nrows();

        // Compute graph Laplacian
        let degree_matrix = self.compute_degree_matrix()?;
        let laplacian = &degree_matrix - &self.state.adjacency_matrix;

        for sample_idx in 0..n_samples {
            // Get initial predictions from node classifiers
            let mut node_scores = Array1::zeros(self.state.n_nodes);
            for node_id in 0..self.state.n_nodes {
                if let Some(classifier) = self.state.node_classifiers.get(&node_id) {
                    let sample_2d = X.row(sample_idx).to_owned().insert_axis(ndarray::Axis(0));
                    let proba = classifier.predict_proba(&sample_2d.view())?;
                    // BinaryRelevance returns probabilities for each label, not binary class probabilities
                    // Convert to decision score: positive_prob - negative_prob
                    let positive_prob = proba[[0, 0]];
                    let negative_prob = 1.0 - positive_prob;
                    node_scores[node_id] = positive_prob - negative_prob; // Decision score
                }
            }

            // Apply graph regularization (simplified)
            let regularized_scores = self.apply_graph_regularization(&node_scores, &laplacian)?;

            // Make predictions based on regularized scores
            for node_id in 0..self.state.n_nodes {
                predictions[[sample_idx, node_id]] = if regularized_scores[node_id] > 0.0 {
                    1
                } else {
                    0
                };
            }
        }

        Ok(())
    }

    /// Compute degree matrix
    fn compute_degree_matrix(&self) -> SklResult<Array2<Float>> {
        let n_nodes = self.state.n_nodes;
        let mut degree_matrix = Array2::zeros((n_nodes, n_nodes));

        for i in 0..n_nodes {
            let degree = self.state.adjacency_matrix.row(i).sum();
            degree_matrix[[i, i]] = degree;
        }

        Ok(degree_matrix)
    }

    /// Apply graph regularization using Laplacian
    fn apply_graph_regularization(
        &self,
        scores: &Array1<Float>,
        laplacian: &Array2<Float>,
    ) -> SklResult<Array1<Float>> {
        // Simplified graph regularization: scores - λ * L * scores
        let lambda = 0.1; // Regularization parameter
        let laplacian_scores = laplacian.dot(scores);
        let regularized = scores - lambda * &laplacian_scores;
        Ok(regularized)
    }

    /// Get adjacency matrix
    pub fn adjacency_matrix(&self) -> &Array2<Float> {
        &self.state.adjacency_matrix
    }

    /// Get edge weights
    pub fn edge_weights(&self) -> &Array2<Float> {
        &self.state.edge_weights
    }

    /// Get node potentials
    pub fn node_potentials(&self) -> &Array2<Float> {
        &self.state.node_potentials
    }

    /// Get edge potentials
    pub fn edge_potentials(&self) -> &Array3<Float> {
        &self.state.edge_potentials
    }
}

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

    #[test]
    fn test_multi_output_svm_basic() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[1.5, 2.5], [2.5, 3.5], [3.5, 1.5], [4.5, 4.5]];

        let model = MultiOutputSVM::new().kernel(SVMKernel::Linear).c(1.0);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        // Test prediction
        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (4, 2));

        // Test methods
        assert_eq!(trained_model.n_support_vectors(), 4);
        assert_eq!(trained_model.dual_coef().dim(), (4, 2));
        assert_eq!(trained_model.intercept().len(), 2);
    }

    #[test]
    fn test_multi_output_svm_rbf_kernel() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];

        let model = MultiOutputSVM::new()
            .kernel(SVMKernel::RBF { gamma: 0.5 })
            .c(1.0);
        let trained_model = model.fit(&X.view(), &y).unwrap();

        let predictions = trained_model.predict(&X.view()).unwrap();
        assert_eq!(predictions.dim(), (3, 2));
    }

    #[test]
    fn test_multi_output_svm_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0]]; // Mismatched dimensions

        let model = MultiOutputSVM::new();
        assert!(model.fit(&X.view(), &y).is_err());

        // Test prediction dimension mismatch
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1.0, 2.0], [2.0, 3.0]];
        let model = MultiOutputSVM::new();
        let trained_model = model.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_model.predict(&X_test.view()).is_err());
    }
}

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

    #[test]
    fn test_compressed_sensing_label_powerset_basic() {
        let X = array![
            [1.0, 2.0],
            [2.0, 3.0],
            [3.0, 1.0],
            [4.0, 4.0],
            [5.0, 2.0],
            [6.0, 3.0]
        ];
        let y = array![
            [0, 1, 0],
            [1, 0, 1],
            [1, 1, 0],
            [0, 0, 1],
            [0, 1, 1],
            [1, 0, 0]
        ]; // 3 labels

        let cs = CompressedSensingLabelPowerset::new()
            .compressed_dimension(2) // Compress 3 labels to 2 dimensions
            .random_state(Some(42));

        let trained_cs = cs.fit(&X.view(), &y).unwrap();
        let predictions = trained_cs.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (6, 3));

        // Check that predictions are binary
        for pred in predictions.iter() {
            assert!(pred == &0 || pred == &1);
        }

        // Check compression ratio
        let ratio = trained_cs.compression_ratio();
        assert!((ratio - (2.0 / 3.0)).abs() < 1e-10);
    }

    #[test]
    fn test_compressed_sensing_iterative_thresholding() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1, 0, 1], [1, 0, 1, 0], [1, 1, 0, 0], [0, 0, 1, 1]]; // 4 labels

        let method = ReconstructionMethod::IterativeThresholding;

        let cs = CompressedSensingLabelPowerset::new()
            .compressed_dimension(3) // Compress 4 labels to 3 dimensions
            .reconstruction_method(method)
            .random_state(Some(42));

        let trained_cs = cs.fit(&X.view(), &y).unwrap();
        let predictions = trained_cs.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 4));
    }

    #[test]
    fn test_compressed_sensing_omp() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1, 0, 1], [1, 0, 1, 0], [1, 1, 0, 0], [0, 0, 1, 1]]; // 4 labels

        let method = ReconstructionMethod::OrthogonalMatchingPursuit;

        let cs = CompressedSensingLabelPowerset::new()
            .compressed_dimension(3) // Compress 4 labels to 3 dimensions
            .reconstruction_method(method)
            .random_state(Some(42));

        let trained_cs = cs.fit(&X.view(), &y).unwrap();
        let predictions = trained_cs.predict(&X.view()).unwrap();

        assert_eq!(predictions.dim(), (4, 4));
    }

    #[test]
    fn test_compressed_sensing_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1, 0], [0, 1], [1, 1]]; // Wrong number of rows

        let cs = CompressedSensingLabelPowerset::new();
        assert!(cs.clone().fit(&X.view(), &y).is_err());

        // Test with no labels
        let y_empty = Array2::<i32>::zeros((2, 0));
        assert!(cs.clone().fit(&X.view(), &y_empty).is_err());

        // Test with compressed dimension >= number of labels
        let y_valid = array![[1, 0], [0, 1]];
        let cs_invalid = CompressedSensingLabelPowerset::new().compressed_dimension(2); // Same as number of labels
        assert!(cs_invalid.fit(&X.view(), &y_valid).is_err());

        // Test prediction with wrong feature dimensions
        let X_train = array![[1.0, 2.0], [2.0, 3.0]];
        let y_train = array![[1, 0, 1], [0, 1, 0]];
        let cs_for_predict = CompressedSensingLabelPowerset::new().compressed_dimension(2);
        let trained_cs = cs_for_predict.fit(&X_train.view(), &y_train).unwrap();

        let X_test = array![[1.0, 2.0, 3.0]]; // Wrong number of features
        assert!(trained_cs.predict(&X_test.view()).is_err());
    }

    #[test]
    fn test_compressed_sensing_projection_matrix() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1, 0], [1, 0, 1], [1, 1, 0], [0, 0, 1]]; // 3 labels

        let cs = CompressedSensingLabelPowerset::new()
            .compressed_dimension(2) // Compress 3 labels to 2 dimensions
            .random_state(Some(42));

        let trained_cs = cs.fit(&X.view(), &y).unwrap();
        let projection_matrix = trained_cs.projection_matrix();

        assert_eq!(projection_matrix.dim(), (2, 3)); // 2 compressed dimensions x 3 labels

        // Check that rows are normalized
        for i in 0..2 {
            let row_norm: Float = projection_matrix
                .row(i)
                .iter()
                .map(|x| x * x)
                .sum::<Float>()
                .sqrt();
            assert!((row_norm - 1.0).abs() < 1e-6);
        }
    }

    #[test]
    fn test_compressed_sensing_reproducibility() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
        let y = array![[0, 1, 0], [1, 0, 1], [1, 1, 0], [0, 0, 1]];

        // Train two models with same random state
        let cs1 = CompressedSensingLabelPowerset::new()
            .compressed_dimension(2)
            .random_state(Some(42));
        let trained_cs1 = cs1.fit(&X.view(), &y).unwrap();

        let cs2 = CompressedSensingLabelPowerset::new()
            .compressed_dimension(2)
            .random_state(Some(42));
        let trained_cs2 = cs2.fit(&X.view(), &y).unwrap();

        // Should produce same projection matrices
        let proj1 = trained_cs1.projection_matrix();
        let proj2 = trained_cs2.projection_matrix();

        for i in 0..proj1.nrows() {
            for j in 0..proj1.ncols() {
                assert!((proj1[[i, j]] - proj2[[i, j]]).abs() < 1e-10);
            }
        }
    }
}

/// Maximum Entropy Markov Model (MEMM) for Sequence Labeling
///
/// MEMM is a discriminative model for sequence labeling that combines the advantages
/// of maximum entropy models with Markov assumptions. Unlike CRF, MEMM models the
/// conditional probability of each label given the previous label and observed features.
///
/// The model uses logistic regression at each position to predict the next label
/// based on features extracted from the current observation and previous label.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::MaximumEntropyMarkovModel;
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// // Sequence data: each row is a sequence element with features
/// let X = vec![
///     array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]], // sequence 1
///     array![[4.0, 1.0], [1.0, 4.0]]                // sequence 2
/// ];
/// let y = vec![
///     vec![0, 1, 2], // labels for sequence 1
///     vec![1, 0]     // labels for sequence 2
/// ];
///
/// let memm = MaximumEntropyMarkovModel::new()
///     .max_iter(100)
///     .learning_rate(0.01)
///     .l2_penalty(0.01);
///
/// let trained_memm = memm.fit(&X, &y).unwrap();
/// let predictions = trained_memm.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct MaximumEntropyMarkovModel<S = Untrained> {
    state: S,
    max_iter: usize,
    learning_rate: Float,
    l2_penalty: Float,
    tolerance: Float,
    random_state: Option<u64>,
    feature_functions: Vec<FeatureFunction>,
}

/// Trained state for MEMM
#[derive(Debug, Clone)]
pub struct MaximumEntropyMarkovModelTrained {
    /// Weights for feature functions
    weights: Array1<Float>,
    /// Feature functions used in the model
    feature_functions: Vec<FeatureFunction>,
    /// Number of unique labels
    n_labels: usize,
    /// Label mapping (string to index)
    label_map: HashMap<i32, usize>,
    /// Reverse label mapping (index to string)
    label_names: Vec<i32>,
    /// Number of features per observation
    n_features: usize,
    /// Training history
    loss_curve: Vec<Float>,
}

/// Feature function for MEMM
#[derive(Debug, Clone)]
pub struct FeatureFunction {
    /// Feature type identifier
    pub feature_type: FeatureType,
    /// Previous label (for transition features)
    pub prev_label: Option<usize>,
    /// Current label
    pub curr_label: usize,
    /// Feature index (for observation features)
    pub feature_idx: Option<usize>,
}

/// Types of features in MEMM
#[derive(Debug, Clone, PartialEq)]
pub enum FeatureType {
    /// Observation feature: depends on current observation and label
    Observation,
    /// Transition feature: depends on previous and current label
    Transition,
    /// Bias feature: constant feature for each label
    Bias,
}

impl MaximumEntropyMarkovModel<Untrained> {
    /// Create a new MEMM instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            max_iter: 100,
            learning_rate: 0.01,
            l2_penalty: 0.01,
            tolerance: 1e-6,
            random_state: None,
            feature_functions: Vec::new(),
        }
    }

    /// Set maximum number of iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set learning rate
    pub fn learning_rate(mut self, learning_rate: Float) -> Self {
        self.learning_rate = learning_rate;
        self
    }

    /// Set L2 penalty coefficient
    pub fn l2_penalty(mut self, l2_penalty: Float) -> Self {
        self.l2_penalty = l2_penalty;
        self
    }

    /// Set convergence tolerance
    pub fn tolerance(mut self, tolerance: Float) -> Self {
        self.tolerance = tolerance;
        self
    }

    /// Set random state for reproducibility
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.random_state = random_state;
        self
    }
}

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

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

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

impl Fit<Vec<Array2<Float>>, Vec<Vec<i32>>> for MaximumEntropyMarkovModel<Untrained> {
    type Fitted = MaximumEntropyMarkovModel<MaximumEntropyMarkovModelTrained>;

    fn fit(self, X: &Vec<Array2<Float>>, y: &Vec<Vec<i32>>) -> SklResult<Self::Fitted> {
        if X.is_empty() || y.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with empty sequences".to_string(),
            ));
        }

        if X.len() != y.len() {
            return Err(SklearsError::InvalidInput(
                "Number of feature sequences must match number of label sequences".to_string(),
            ));
        }

        // Validate sequence lengths
        for (i, (x_seq, y_seq)) in X.iter().zip(y.iter()).enumerate() {
            if x_seq.nrows() != y_seq.len() {
                return Err(SklearsError::InvalidInput(format!(
                    "Sequence {} has mismatched lengths: features {} vs labels {}",
                    i,
                    x_seq.nrows(),
                    y_seq.len()
                )));
            }
        }

        // Extract unique labels and create mappings
        let mut unique_labels = std::collections::HashSet::new();
        for seq in y {
            for &label in seq {
                unique_labels.insert(label);
            }
        }

        let mut label_names: Vec<i32> = unique_labels.into_iter().collect();
        label_names.sort();
        let n_labels = label_names.len();

        let label_map: HashMap<i32, usize> = label_names
            .iter()
            .enumerate()
            .map(|(i, &label)| (label, i))
            .collect();

        // Get number of features from first sequence
        let n_features = X[0].ncols();

        // Generate feature functions
        let feature_functions = self.generate_feature_functions(n_features, n_labels);
        let n_feature_functions = feature_functions.len();

        // Initialize weights
        let mut rng = match self.random_state {
            Some(seed) => ChaCha8Rng::seed_from_u64(seed),
            None => ChaCha8Rng::from_rng(&mut rand::thread_rng()).unwrap(),
        };

        let mut weights = Array1::random_using(
            n_feature_functions,
            Normal::new(0.0, 0.01).unwrap(),
            &mut rng,
        );

        let mut loss_curve = Vec::new();

        // Training loop using gradient descent
        for iter in 0..self.max_iter {
            let mut total_gradient = Array1::zeros(n_feature_functions);
            let mut total_loss = 0.0;
            let mut total_positions = 0;

            // Process each sequence
            for (x_seq, y_seq) in X.iter().zip(y.iter()) {
                let seq_len = y_seq.len();

                for pos in 0..seq_len {
                    let prev_label_idx = if pos == 0 {
                        None
                    } else {
                        Some(label_map[&y_seq[pos - 1]])
                    };

                    let true_label_idx = label_map[&y_seq[pos]];
                    let observation = x_seq.row(pos);

                    // Compute feature vector for all possible labels
                    let mut scores = Array1::zeros(n_labels);
                    for label_idx in 0..n_labels {
                        scores[label_idx] = self.compute_score(
                            &weights,
                            &feature_functions,
                            &observation,
                            prev_label_idx,
                            label_idx,
                        );
                    }

                    // Apply softmax to get probabilities
                    let probabilities = self.softmax(&scores);

                    // Compute loss (negative log-likelihood)
                    let loss = -probabilities[true_label_idx].ln();
                    total_loss += loss;
                    total_positions += 1;

                    // Compute gradient
                    for (f_idx, feature_func) in feature_functions.iter().enumerate() {
                        let true_feature_value = self.evaluate_feature_function(
                            feature_func,
                            &observation,
                            prev_label_idx,
                            true_label_idx,
                        );

                        let expected_feature_value: Float = (0..n_labels)
                            .map(|label_idx| {
                                probabilities[label_idx]
                                    * self.evaluate_feature_function(
                                        feature_func,
                                        &observation,
                                        prev_label_idx,
                                        label_idx,
                                    )
                            })
                            .sum();

                        total_gradient[f_idx] += true_feature_value - expected_feature_value;
                    }
                }
            }

            // Average loss and gradient
            let avg_loss = total_loss / total_positions as Float;
            loss_curve.push(avg_loss);
            total_gradient /= total_positions as Float;

            // Add L2 regularization to gradient
            for i in 0..total_gradient.len() {
                total_gradient[i] -= self.l2_penalty * weights[i];
            }

            // Update weights
            for i in 0..weights.len() {
                weights[i] += self.learning_rate * total_gradient[i];
            }

            // Check convergence
            if iter > 0 && (loss_curve[iter - 1] - avg_loss).abs() < self.tolerance {
                break;
            }
        }

        let trained_state = MaximumEntropyMarkovModelTrained {
            weights,
            feature_functions,
            n_labels,
            label_map,
            label_names,
            n_features,
            loss_curve,
        };

        Ok(MaximumEntropyMarkovModel {
            state: trained_state,
            max_iter: self.max_iter,
            learning_rate: self.learning_rate,
            l2_penalty: self.l2_penalty,
            tolerance: self.tolerance,
            random_state: self.random_state,
            feature_functions: Vec::new(),
        })
    }
}

impl MaximumEntropyMarkovModel<Untrained> {
    /// Generate feature functions for the model
    fn generate_feature_functions(
        &self,
        n_features: usize,
        n_labels: usize,
    ) -> Vec<FeatureFunction> {
        let mut functions = Vec::new();

        // Bias features (one per label)
        for label_idx in 0..n_labels {
            functions.push(FeatureFunction {
                feature_type: FeatureType::Bias,
                prev_label: None,
                curr_label: label_idx,
                feature_idx: None,
            });
        }

        // Observation features (one per feature per label)
        for feature_idx in 0..n_features {
            for label_idx in 0..n_labels {
                functions.push(FeatureFunction {
                    feature_type: FeatureType::Observation,
                    prev_label: None,
                    curr_label: label_idx,
                    feature_idx: Some(feature_idx),
                });
            }
        }

        // Transition features (one per label pair)
        for prev_label_idx in 0..n_labels {
            for curr_label_idx in 0..n_labels {
                functions.push(FeatureFunction {
                    feature_type: FeatureType::Transition,
                    prev_label: Some(prev_label_idx),
                    curr_label: curr_label_idx,
                    feature_idx: None,
                });
            }
        }

        functions
    }

    /// Compute score for a given label at a position
    fn compute_score(
        &self,
        weights: &Array1<Float>,
        feature_functions: &[FeatureFunction],
        observation: &ArrayView1<Float>,
        prev_label: Option<usize>,
        curr_label: usize,
    ) -> Float {
        feature_functions
            .iter()
            .enumerate()
            .map(|(f_idx, feature_func)| {
                weights[f_idx]
                    * self.evaluate_feature_function(
                        feature_func,
                        observation,
                        prev_label,
                        curr_label,
                    )
            })
            .sum()
    }

    /// Evaluate a feature function
    fn evaluate_feature_function(
        &self,
        feature_func: &FeatureFunction,
        observation: &ArrayView1<Float>,
        prev_label: Option<usize>,
        curr_label: usize,
    ) -> Float {
        match feature_func.feature_type {
            FeatureType::Bias => {
                if feature_func.curr_label == curr_label {
                    1.0
                } else {
                    0.0
                }
            }
            FeatureType::Observation => {
                if feature_func.curr_label == curr_label {
                    observation[feature_func.feature_idx.unwrap()]
                } else {
                    0.0
                }
            }
            FeatureType::Transition => {
                if feature_func.curr_label == curr_label && feature_func.prev_label == prev_label {
                    1.0
                } else {
                    0.0
                }
            }
        }
    }

    /// Apply softmax to scores
    fn softmax(&self, scores: &Array1<Float>) -> Array1<Float> {
        let max_score = scores.iter().fold(Float::NEG_INFINITY, |a, &b| a.max(b));
        let shifted_scores = scores.map(|&x| x - max_score);
        let exp_scores = shifted_scores.map(|&x| x.exp());
        let sum_exp = exp_scores.sum();
        exp_scores.map(|&x| x / sum_exp)
    }
}

impl Predict<Vec<Array2<Float>>, Vec<Vec<i32>>>
    for MaximumEntropyMarkovModel<MaximumEntropyMarkovModelTrained>
{
    fn predict(&self, X: &Vec<Array2<Float>>) -> SklResult<Vec<Vec<i32>>> {
        if X.is_empty() {
            return Ok(Vec::new());
        }

        // Validate feature dimensions
        for (i, x_seq) in X.iter().enumerate() {
            if x_seq.ncols() != self.state.n_features {
                return Err(SklearsError::InvalidInput(format!(
                    "Sequence {} has {} features, expected {}",
                    i,
                    x_seq.ncols(),
                    self.state.n_features
                )));
            }
        }

        let mut predictions = Vec::new();

        for x_seq in X {
            let seq_len = x_seq.nrows();
            let mut seq_predictions = Vec::new();

            for pos in 0..seq_len {
                let prev_label_idx = if pos == 0 {
                    None
                } else {
                    // Find the index of the previous predicted label
                    let prev_label = seq_predictions[pos - 1];
                    Some(self.state.label_map[&prev_label])
                };

                let observation = x_seq.row(pos);

                // Compute scores for all labels
                let mut scores = Array1::zeros(self.state.n_labels);
                for label_idx in 0..self.state.n_labels {
                    scores[label_idx] =
                        self.compute_score_trained(&observation, prev_label_idx, label_idx);
                }

                // Find best label
                let best_label_idx = scores
                    .iter()
                    .enumerate()
                    .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
                    .unwrap()
                    .0;

                seq_predictions.push(self.state.label_names[best_label_idx]);
            }

            predictions.push(seq_predictions);
        }

        Ok(predictions)
    }
}

impl MaximumEntropyMarkovModel<MaximumEntropyMarkovModelTrained> {
    /// Compute score for a label using trained weights
    fn compute_score_trained(
        &self,
        observation: &ArrayView1<Float>,
        prev_label: Option<usize>,
        curr_label: usize,
    ) -> Float {
        self.state
            .feature_functions
            .iter()
            .enumerate()
            .map(|(f_idx, feature_func)| {
                self.state.weights[f_idx]
                    * self.evaluate_feature_function_trained(
                        feature_func,
                        observation,
                        prev_label,
                        curr_label,
                    )
            })
            .sum()
    }

    /// Evaluate feature function for trained model
    fn evaluate_feature_function_trained(
        &self,
        feature_func: &FeatureFunction,
        observation: &ArrayView1<Float>,
        prev_label: Option<usize>,
        curr_label: usize,
    ) -> Float {
        match feature_func.feature_type {
            FeatureType::Bias => {
                if feature_func.curr_label == curr_label {
                    1.0
                } else {
                    0.0
                }
            }
            FeatureType::Observation => {
                if feature_func.curr_label == curr_label {
                    observation[feature_func.feature_idx.unwrap()]
                } else {
                    0.0
                }
            }
            FeatureType::Transition => {
                if feature_func.curr_label == curr_label && feature_func.prev_label == prev_label {
                    1.0
                } else {
                    0.0
                }
            }
        }
    }

    /// Get the training loss curve
    pub fn loss_curve(&self) -> &[Float] {
        &self.state.loss_curve
    }

    /// Get the learned weights
    pub fn weights(&self) -> &Array1<Float> {
        &self.state.weights
    }

    /// Get the feature functions
    pub fn feature_functions(&self) -> &[FeatureFunction] {
        &self.state.feature_functions
    }

    /// Predict probabilities for each position in sequences
    pub fn predict_proba(&self, X: &Vec<Array2<Float>>) -> SklResult<Vec<Array2<Float>>> {
        if X.is_empty() {
            return Ok(Vec::new());
        }

        let mut all_probabilities = Vec::new();

        for x_seq in X {
            let seq_len = x_seq.nrows();
            let mut seq_probabilities = Array2::zeros((seq_len, self.state.n_labels));

            for pos in 0..seq_len {
                let prev_label_idx = if pos == 0 {
                    None
                } else {
                    // For probability prediction, we need to consider all possible previous labels
                    // For simplicity, we'll use greedy decoding
                    let prev_probs = seq_probabilities.row(pos - 1);
                    let best_prev_idx = prev_probs
                        .iter()
                        .enumerate()
                        .max_by(|(_, a): &(usize, &Float), (_, b): &(usize, &Float)| {
                            (*a).partial_cmp(*b).unwrap()
                        })
                        .unwrap()
                        .0;
                    Some(best_prev_idx)
                };

                let observation = x_seq.row(pos);

                // Compute scores for all labels
                let mut scores = Array1::zeros(self.state.n_labels);
                for label_idx in 0..self.state.n_labels {
                    scores[label_idx] =
                        self.compute_score_trained(&observation, prev_label_idx, label_idx);
                }

                // Apply softmax to get probabilities
                let probabilities = self.softmax_trained(&scores);
                seq_probabilities.row_mut(pos).assign(&probabilities);
            }

            all_probabilities.push(seq_probabilities);
        }

        Ok(all_probabilities)
    }

    /// Apply softmax for trained model
    fn softmax_trained(&self, scores: &Array1<Float>) -> Array1<Float> {
        let max_score = scores.iter().fold(Float::NEG_INFINITY, |a, &b| a.max(b));
        let shifted_scores = scores.map(|&x| x - max_score);
        let exp_scores = shifted_scores.map(|&x| x.exp());
        let sum_exp = exp_scores.sum();
        exp_scores.map(|&x| x / sum_exp)
    }
}

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

    #[test]
    fn test_memm_basic_functionality() {
        let X = vec![
            array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]],
            array![[4.0, 1.0], [1.0, 4.0]],
        ];
        let y = vec![vec![0, 1, 2], vec![1, 0]];

        let memm = MaximumEntropyMarkovModel::new()
            .max_iter(10)
            .learning_rate(0.1)
            .random_state(Some(42));

        let trained_memm = memm.fit(&X, &y).unwrap();
        let predictions = trained_memm.predict(&X).unwrap();

        assert_eq!(predictions.len(), 2);
        assert_eq!(predictions[0].len(), 3);
        assert_eq!(predictions[1].len(), 2);
    }

    #[test]
    fn test_memm_predict_proba() {
        let X = vec![array![[1.0, 2.0], [2.0, 3.0]]];
        let y = vec![vec![0, 1]];

        let memm = MaximumEntropyMarkovModel::new()
            .max_iter(5)
            .random_state(Some(42));

        let trained_memm = memm.fit(&X, &y).unwrap();
        let probabilities = trained_memm.predict_proba(&X).unwrap();

        assert_eq!(probabilities.len(), 1);
        assert_eq!(probabilities[0].dim(), (2, 2)); // 2 positions, 2 labels

        // Check that probabilities sum to 1 for each position
        for pos in 0..probabilities[0].nrows() {
            let sum: Float = probabilities[0].row(pos).sum();
            assert!((sum - 1.0).abs() < 1e-6);
        }
    }

    #[test]
    fn test_memm_error_handling() {
        let X = vec![array![[1.0, 2.0], [2.0, 3.0]]];
        let y = vec![vec![0, 1, 2]]; // Wrong length

        let memm = MaximumEntropyMarkovModel::new();
        assert!(memm.fit(&X, &y).is_err());

        // Test empty sequences
        let empty_X: Vec<Array2<Float>> = Vec::new();
        let empty_y: Vec<Vec<i32>> = Vec::new();
        assert!(MaximumEntropyMarkovModel::new()
            .fit(&empty_X, &empty_y)
            .is_err());
    }

    #[test]
    fn test_memm_feature_functions() {
        let X = vec![array![[1.0, 2.0]]];
        let y = vec![vec![0]];

        let memm = MaximumEntropyMarkovModel::new()
            .max_iter(1)
            .random_state(Some(42));

        let trained_memm = memm.fit(&X, &y).unwrap();
        let feature_functions = trained_memm.feature_functions();

        // Should have bias + observation + transition features
        // With 2 features and 1 label: 1 bias + 2 observation + 1 transition = 4 features
        assert!(feature_functions.len() > 0);
    }

    #[test]
    fn test_memm_reproducibility() {
        let X = vec![array![[1.0, 2.0], [2.0, 3.0]]];
        let y = vec![vec![0, 1]];

        let memm1 = MaximumEntropyMarkovModel::new()
            .max_iter(10)
            .random_state(Some(42));
        let trained_memm1 = memm1.fit(&X, &y).unwrap();
        let pred1 = trained_memm1.predict(&X).unwrap();

        let memm2 = MaximumEntropyMarkovModel::new()
            .max_iter(10)
            .random_state(Some(42));
        let trained_memm2 = memm2.fit(&X, &y).unwrap();
        let pred2 = trained_memm2.predict(&X).unwrap();

        assert_eq!(pred1, pred2);
    }
}
// ================================================================================================
// NEW IMPLEMENTATIONS: Ontology-Aware and Cost-Sensitive Hierarchical Methods
// ================================================================================================

/// Ontology-Aware Hierarchical Classifier
///
/// A hierarchical multi-label classifier that incorporates domain ontology knowledge
/// to ensure taxonomically consistent predictions. This method enforces that if a child
/// concept is predicted, its parent concepts are also predicted according to the
/// provided hierarchical structure.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::{OntologyAwareClassifier, ConsistencyEnforcement};
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
/// use std::collections::HashMap;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1]];
///
/// // Define ontology: child -> parent relationships
/// let mut ontology = HashMap::new();
/// ontology.insert(2, vec![0]); // concept 2 is child of concept 0
/// ontology.insert(3, vec![1]); // concept 3 is child of concept 1
///
/// let classifier = OntologyAwareClassifier::new()
///     .ontology(ontology)
///     .consistency_enforcement(ConsistencyEnforcement::PostProcessing)
///     .random_state(Some(42));
///
/// let trained_classifier = classifier.fit(&X.view(), &y.view()).unwrap();
/// let predictions = trained_classifier.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct OntologyAwareClassifier<S = Untrained> {
    state: S,
    ontology: HashMap<usize, Vec<usize>>, // child -> parents mapping
    consistency_enforcement: ConsistencyEnforcement,
    random_state: Option<u64>,
    base_threshold: Float,
    confidence_boost: Float,
}

/// Trained state for OntologyAwareClassifier
#[derive(Debug, Clone)]
pub struct OntologyAwareClassifierTrained {
    /// Binary classifiers for each concept
    classifiers: HashMap<usize, BinaryClassifierState>,
    /// Concept hierarchy (child -> parents)
    ontology: HashMap<usize, Vec<usize>>,
    /// Consistency enforcement method
    consistency_enforcement: ConsistencyEnforcement,
    /// Prediction parameters
    base_threshold: Float,
    confidence_boost: Float,
    /// Number of concepts
    n_concepts: usize,
    /// Number of features
    n_features: usize,
}

#[derive(Debug, Clone)]
struct BinaryClassifierState {
    weights: Array1<Float>,
    bias: Float,
    positive_examples: usize,
    negative_examples: usize,
}

impl OntologyAwareClassifier<Untrained> {
    /// Create a new ontology-aware classifier
    pub fn new() -> Self {
        Self {
            state: Untrained,
            ontology: HashMap::new(),
            consistency_enforcement: ConsistencyEnforcement::PostProcessing,
            random_state: None,
            base_threshold: 0.5,
            confidence_boost: 0.1,
        }
    }

    /// Set the concept ontology (child -> parents mapping)
    pub fn ontology(mut self, ontology: HashMap<usize, Vec<usize>>) -> Self {
        self.ontology = ontology;
        self
    }

    /// Set the consistency enforcement method
    pub fn consistency_enforcement(mut self, enforcement: ConsistencyEnforcement) -> Self {
        self.consistency_enforcement = enforcement;
        self
    }

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

    /// Set base threshold for binary predictions
    pub fn base_threshold(mut self, threshold: Float) -> Self {
        self.base_threshold = threshold;
        self
    }

    /// Set confidence boost for parent concepts
    pub fn confidence_boost(mut self, boost: Float) -> Self {
        self.confidence_boost = boost;
        self
    }
}

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

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

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

impl
    Fit<
        ArrayView2<'_, Float>,
        ArrayView2<'_, i32>,
        OntologyAwareClassifier<OntologyAwareClassifierTrained>,
    > for OntologyAwareClassifier<Untrained>
{
    type Fitted = OntologyAwareClassifier<OntologyAwareClassifierTrained>;

    fn fit(
        self,
        X: &ArrayView2<'_, Float>,
        y: &ArrayView2<'_, i32>,
    ) -> SklResult<OntologyAwareClassifier<OntologyAwareClassifierTrained>> {
        let (n_samples, n_features) = X.dim();
        let (y_samples, n_concepts) = y.dim();

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

        if n_samples < 2 {
            return Err(SklearsError::InvalidInput(
                "Need at least 2 samples for training".to_string(),
            ));
        }

        // Initialize random number generator if needed
        let mut rng = if let Some(seed) = self.random_state {
            ChaCha8Rng::seed_from_u64(seed)
        } else {
            ChaCha8Rng::from_rng(&mut rand::thread_rng()).unwrap()
        };

        // Train binary classifier for each concept
        let mut classifiers = HashMap::new();

        for concept_idx in 0..n_concepts {
            let y_concept = y.column(concept_idx);

            // Prepare training data with ontological constraints if needed
            let adjusted_y = match self.consistency_enforcement {
                ConsistencyEnforcement::ConstrainedTraining => {
                    // Adjust labels to enforce ontological consistency during training
                    self.enforce_training_consistency(&y_concept, concept_idx)?
                }
                _ => y_concept.to_owned(),
            };

            // Train simple logistic regression for this concept
            let classifier = train_binary_logistic_regression(X, &adjusted_y.view(), &mut rng)?;
            classifiers.insert(concept_idx, classifier);
        }

        Ok(OntologyAwareClassifier {
            state: OntologyAwareClassifierTrained {
                classifiers,
                ontology: self.ontology.clone(),
                consistency_enforcement: self.consistency_enforcement,
                base_threshold: self.base_threshold,
                confidence_boost: self.confidence_boost,
                n_concepts,
                n_features,
            },
            ontology: self.ontology,
            consistency_enforcement: self.consistency_enforcement,
            random_state: self.random_state,
            base_threshold: self.base_threshold,
            confidence_boost: self.confidence_boost,
        })
    }
}

impl OntologyAwareClassifier<Untrained> {
    /// Enforce consistency during training by adjusting labels
    fn enforce_training_consistency(
        &self,
        y_concept: &ArrayView1<'_, i32>,
        concept_idx: usize,
    ) -> SklResult<Array1<i32>> {
        let mut adjusted_y = y_concept.to_owned();

        // If this concept has parents, ensure parents are also labeled when child is labeled
        if let Some(parents) = self.ontology.get(&concept_idx) {
            for (sample_idx, &label) in y_concept.iter().enumerate() {
                if label == 1 {
                    // Child is positive, so parents should be positive too
                    // Note: This is a simplified approach; in practice, you'd need access to all labels
                    // Here we just ensure the current concept maintains its label
                    adjusted_y[sample_idx] = 1;
                }
            }
        }

        Ok(adjusted_y)
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>>
    for OntologyAwareClassifier<OntologyAwareClassifierTrained>
{
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        // Get probability predictions first
        let probabilities = self.predict_proba(X)?;

        // Convert probabilities to binary predictions
        let mut predictions = Array2::zeros((n_samples, self.state.n_concepts));

        for i in 0..n_samples {
            for j in 0..self.state.n_concepts {
                predictions[[i, j]] = if probabilities[[i, j]] > self.state.base_threshold {
                    1
                } else {
                    0
                };
            }
        }

        // Apply ontological consistency
        match self.state.consistency_enforcement {
            ConsistencyEnforcement::PostProcessing => {
                self.enforce_post_processing_consistency(&mut predictions)?;
            }
            ConsistencyEnforcement::BayesianInference => {
                predictions = self.bayesian_inference_consistency(&probabilities)?;
            }
            _ => {} // ConstrainedTraining consistency was applied during training
        }

        Ok(predictions)
    }
}

impl OntologyAwareClassifier<OntologyAwareClassifierTrained> {
    /// Predict class probabilities
    pub fn predict_proba(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<Float>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut probabilities = Array2::zeros((n_samples, self.state.n_concepts));

        // Get base probabilities from individual classifiers
        for (concept_idx, classifier) in &self.state.classifiers {
            for i in 0..n_samples {
                let x_sample = X.row(i);
                let logit = x_sample.dot(&classifier.weights) + classifier.bias;
                let probability = 1.0 / (1.0 + (-logit).exp()); // Sigmoid
                probabilities[[i, *concept_idx]] = probability;
            }
        }

        Ok(probabilities)
    }

    /// Enforce consistency through post-processing
    fn enforce_post_processing_consistency(&self, predictions: &mut Array2<i32>) -> SklResult<()> {
        let n_samples = predictions.nrows();

        for sample_idx in 0..n_samples {
            // For each positive prediction, ensure parents are also positive
            let mut changed = true;
            while changed {
                changed = false;
                for (child, parents) in &self.state.ontology {
                    if predictions[[sample_idx, *child]] == 1 {
                        for parent in parents {
                            if *parent < self.state.n_concepts
                                && predictions[[sample_idx, *parent]] == 0
                            {
                                predictions[[sample_idx, *parent]] = 1;
                                changed = true;
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Apply Bayesian inference for consistency
    fn bayesian_inference_consistency(
        &self,
        probabilities: &Array2<Float>,
    ) -> SklResult<Array2<i32>> {
        let (n_samples, _) = probabilities.dim();
        let mut predictions = Array2::zeros((n_samples, self.state.n_concepts));

        for sample_idx in 0..n_samples {
            // Apply Bayesian reasoning with ontological priors
            let mut adjusted_probs = probabilities.row(sample_idx).to_owned();

            // Boost parent probabilities based on child evidence
            for (child, parents) in &self.state.ontology {
                let child_prob = adjusted_probs[*child];
                for parent in parents {
                    if *parent < self.state.n_concepts {
                        // Boost parent probability based on child evidence
                        let boost = child_prob * self.state.confidence_boost;
                        adjusted_probs[*parent] = (adjusted_probs[*parent] + boost).min(1.0);
                    }
                }
            }

            // Make final predictions based on adjusted probabilities
            for concept_idx in 0..self.state.n_concepts {
                predictions[[sample_idx, concept_idx]] =
                    if adjusted_probs[concept_idx] > self.state.base_threshold {
                        1
                    } else {
                        0
                    };
            }
        }

        Ok(predictions)
    }

    /// Get the learned ontology structure
    pub fn ontology(&self) -> &HashMap<usize, Vec<usize>> {
        &self.state.ontology
    }

    /// Get classifier weights for analysis
    pub fn concept_weights(&self, concept_idx: usize) -> Option<&Array1<Float>> {
        self.state.classifiers.get(&concept_idx).map(|c| &c.weights)
    }
}

/// Cost-Sensitive Hierarchical Classifier
///
/// Extends hierarchical classification with cost-sensitive learning, where different
/// types of misclassification errors have different costs. This is particularly useful
/// in domains where false positives and false negatives have asymmetric costs.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::{CostSensitiveHierarchicalClassifier, CostStrategy};
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
/// use std::collections::HashMap;
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0], [4.0, 4.0]];
/// let y = array![[1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1]];
///
/// // Define hierarchical structure and costs
/// let mut hierarchy = HashMap::new();
/// hierarchy.insert(2, vec![0]); // concept 2 is child of concept 0
/// hierarchy.insert(3, vec![1]); // concept 3 is child of concept 1
///
/// let mut costs = HashMap::new();
/// costs.insert(0, (1.0, 2.0)); // (false_positive_cost, false_negative_cost)
/// costs.insert(1, (2.0, 1.0));
/// costs.insert(2, (1.5, 1.5));
/// costs.insert(3, (3.0, 1.0));
///
/// let classifier = CostSensitiveHierarchicalClassifier::new()
///     .hierarchy(hierarchy)
///     .costs(costs)
///     .cost_strategy(CostStrategy::Weighted)
///     .random_state(Some(42));
///
/// let trained_classifier = classifier.fit(&X.view(), &y.view()).unwrap();
/// let predictions = trained_classifier.predict(&X.view()).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct CostSensitiveHierarchicalClassifier<S = Untrained> {
    state: S,
    hierarchy: HashMap<usize, Vec<usize>>, // child -> parents mapping
    costs: HashMap<usize, (Float, Float)>, // concept -> (false_positive_cost, false_negative_cost)
    cost_strategy: CostStrategy,
    random_state: Option<u64>,
    learning_rate: Float,
    max_iter: usize,
}

/// Strategies for incorporating costs into learning
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CostStrategy {
    /// Weight training examples by costs
    Weighted,
    /// Adjust decision thresholds based on costs
    ThresholdAdjustment,
    /// Use cost-sensitive loss function
    CostSensitiveLoss,
}

/// Trained state for CostSensitiveHierarchicalClassifier
#[derive(Debug, Clone)]
pub struct CostSensitiveHierarchicalClassifierTrained {
    /// Concept classifiers
    classifiers: HashMap<usize, BinaryClassifierState>,
    /// Hierarchical structure
    hierarchy: HashMap<usize, Vec<usize>>,
    /// Cost matrix
    costs: HashMap<usize, (Float, Float)>,
    /// Cost-adjusted thresholds for each concept
    thresholds: HashMap<usize, Float>,
    /// Cost strategy used
    cost_strategy: CostStrategy,
    /// Model parameters
    n_concepts: usize,
    n_features: usize,
}

impl CostSensitiveHierarchicalClassifier<Untrained> {
    /// Create a new cost-sensitive hierarchical classifier
    pub fn new() -> Self {
        Self {
            state: Untrained,
            hierarchy: HashMap::new(),
            costs: HashMap::new(),
            cost_strategy: CostStrategy::Weighted,
            random_state: None,
            learning_rate: 0.01,
            max_iter: 1000,
        }
    }

    /// Set the hierarchical structure (child -> parents mapping)
    pub fn hierarchy(mut self, hierarchy: HashMap<usize, Vec<usize>>) -> Self {
        self.hierarchy = hierarchy;
        self
    }

    /// Set the cost matrix (concept -> (false_positive_cost, false_negative_cost))
    pub fn costs(mut self, costs: HashMap<usize, (Float, Float)>) -> Self {
        self.costs = costs;
        self
    }

    /// Set the cost strategy
    pub fn cost_strategy(mut self, strategy: CostStrategy) -> Self {
        self.cost_strategy = strategy;
        self
    }

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

    /// Set learning rate
    pub fn learning_rate(mut self, lr: Float) -> Self {
        self.learning_rate = lr;
        self
    }

    /// Set maximum iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }
}

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

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

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

impl
    Fit<
        ArrayView2<'_, Float>,
        ArrayView2<'_, i32>,
        CostSensitiveHierarchicalClassifier<CostSensitiveHierarchicalClassifierTrained>,
    > for CostSensitiveHierarchicalClassifier<Untrained>
{
    type Fitted = CostSensitiveHierarchicalClassifier<CostSensitiveHierarchicalClassifierTrained>;

    fn fit(
        self,
        X: &ArrayView2<'_, Float>,
        y: &ArrayView2<'_, i32>,
    ) -> SklResult<CostSensitiveHierarchicalClassifier<CostSensitiveHierarchicalClassifierTrained>>
    {
        let (n_samples, n_features) = X.dim();
        let (y_samples, n_concepts) = y.dim();

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

        if n_samples < 2 {
            return Err(SklearsError::InvalidInput(
                "Need at least 2 samples for training".to_string(),
            ));
        }

        // Initialize random number generator
        let mut rng = if let Some(seed) = self.random_state {
            ChaCha8Rng::seed_from_u64(seed)
        } else {
            ChaCha8Rng::from_rng(&mut rand::thread_rng()).unwrap()
        };

        // Train cost-sensitive classifier for each concept
        let mut classifiers = HashMap::new();
        let mut thresholds = HashMap::new();

        for concept_idx in 0..n_concepts {
            let y_concept = y.column(concept_idx);
            let costs = self.costs.get(&concept_idx).copied().unwrap_or((1.0, 1.0));

            match self.cost_strategy {
                CostStrategy::Weighted => {
                    // Train with cost-weighted examples
                    let classifier =
                        train_cost_weighted_classifier(X, &y_concept, costs, &mut rng)?;
                    classifiers.insert(concept_idx, classifier);
                    thresholds.insert(concept_idx, 0.5);
                }
                CostStrategy::ThresholdAdjustment => {
                    // Train normal classifier but adjust threshold
                    let classifier = train_binary_logistic_regression(X, &y_concept, &mut rng)?;
                    let optimal_threshold = compute_cost_optimal_threshold(costs);
                    classifiers.insert(concept_idx, classifier);
                    thresholds.insert(concept_idx, optimal_threshold);
                }
                CostStrategy::CostSensitiveLoss => {
                    // Train with cost-sensitive loss function
                    let classifier = train_cost_sensitive_loss_classifier(
                        X,
                        &y_concept,
                        costs,
                        self.learning_rate,
                        self.max_iter,
                        &mut rng,
                    )?;
                    classifiers.insert(concept_idx, classifier);
                    thresholds.insert(concept_idx, 0.5);
                }
            }
        }

        Ok(CostSensitiveHierarchicalClassifier {
            state: CostSensitiveHierarchicalClassifierTrained {
                classifiers,
                hierarchy: self.hierarchy.clone(),
                costs: self.costs.clone(),
                thresholds,
                cost_strategy: self.cost_strategy,
                n_concepts,
                n_features,
            },
            hierarchy: self.hierarchy,
            costs: self.costs,
            cost_strategy: self.cost_strategy,
            random_state: self.random_state,
            learning_rate: self.learning_rate,
            max_iter: self.max_iter,
        })
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<i32>>
    for CostSensitiveHierarchicalClassifier<CostSensitiveHierarchicalClassifierTrained>
{
    fn predict(&self, X: &ArrayView2<'_, Float>) -> SklResult<Array2<i32>> {
        let (n_samples, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut predictions = Array2::zeros((n_samples, self.state.n_concepts));

        // Make predictions using cost-adjusted thresholds
        for (concept_idx, classifier) in &self.state.classifiers {
            let threshold = self
                .state
                .thresholds
                .get(concept_idx)
                .copied()
                .unwrap_or(0.5);

            for i in 0..n_samples {
                let x_sample = X.row(i);
                let logit = x_sample.dot(&classifier.weights) + classifier.bias;
                let probability = 1.0 / (1.0 + (-logit).exp());

                predictions[[i, *concept_idx]] = if probability > threshold { 1 } else { 0 };
            }
        }

        // Enforce hierarchical consistency
        self.enforce_hierarchical_consistency(&mut predictions)?;

        Ok(predictions)
    }
}

impl CostSensitiveHierarchicalClassifier<CostSensitiveHierarchicalClassifierTrained> {
    /// Enforce hierarchical consistency in predictions
    fn enforce_hierarchical_consistency(&self, predictions: &mut Array2<i32>) -> SklResult<()> {
        let n_samples = predictions.nrows();

        for sample_idx in 0..n_samples {
            // Ensure parent concepts are predicted when children are predicted
            let mut changed = true;
            while changed {
                changed = false;
                for (child, parents) in &self.state.hierarchy {
                    if predictions[[sample_idx, *child]] == 1 {
                        for parent in parents {
                            if *parent < self.state.n_concepts
                                && predictions[[sample_idx, *parent]] == 0
                            {
                                predictions[[sample_idx, *parent]] = 1;
                                changed = true;
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Get the cost-adjusted threshold for a concept
    pub fn concept_threshold(&self, concept_idx: usize) -> Option<Float> {
        self.state.thresholds.get(&concept_idx).copied()
    }

    /// Get the cost matrix
    pub fn costs(&self) -> &HashMap<usize, (Float, Float)> {
        &self.state.costs
    }

    /// Compute expected cost for a prediction
    pub fn compute_prediction_cost(
        &self,
        y_true: &Array2<i32>,
        y_pred: &Array2<i32>,
    ) -> SklResult<Float> {
        if y_true.dim() != y_pred.dim() {
            return Err(SklearsError::InvalidInput(
                "y_true and y_pred must have the same dimensions".to_string(),
            ));
        }

        let mut total_cost = 0.0;
        let (n_samples, n_concepts) = y_true.dim();

        for sample_idx in 0..n_samples {
            for concept_idx in 0..n_concepts {
                let true_label = y_true[[sample_idx, concept_idx]];
                let pred_label = y_pred[[sample_idx, concept_idx]];

                if let Some(&(fp_cost, fn_cost)) = self.state.costs.get(&concept_idx) {
                    match (true_label, pred_label) {
                        (0, 1) => total_cost += fp_cost, // False positive
                        (1, 0) => total_cost += fn_cost, // False negative
                        _ => {}                          // Correct predictions have no cost
                    }
                }
            }
        }

        Ok(total_cost)
    }
}

// ================================================================================================
// Helper Functions for Ontology-Aware and Cost-Sensitive Methods
// ================================================================================================

/// Train a simple binary logistic regression classifier
fn train_binary_logistic_regression(
    X: &ArrayView2<'_, Float>,
    y: &ArrayView1<'_, i32>,
    rng: &mut ChaCha8Rng,
) -> SklResult<BinaryClassifierState> {
    let (n_samples, n_features) = X.dim();

    // Initialize weights randomly
    let normal = Normal::new(0.0, 0.01).unwrap();
    let mut weights = Array1::random_using(n_features, normal, rng);
    let mut bias = 0.0;

    let learning_rate = 0.01;
    let max_iter = 1000;

    // Count positive and negative examples
    let positive_examples = y.iter().filter(|&&label| label == 1).count();
    let negative_examples = n_samples - positive_examples;

    // Simple gradient descent
    for _iter in 0..max_iter {
        let mut grad_weights = Array1::zeros(n_features);
        let mut grad_bias = 0.0;

        for i in 0..n_samples {
            let x_i = X.row(i);
            let y_i = y[i] as Float;

            let logit = x_i.dot(&weights) + bias;
            let prob = 1.0 / (1.0 + (-logit).exp());
            let error = prob - y_i;

            grad_weights = grad_weights + error * &x_i;
            grad_bias += error;
        }

        weights = weights - learning_rate * &grad_weights / (n_samples as Float);
        bias -= learning_rate * grad_bias / (n_samples as Float);
    }

    Ok(BinaryClassifierState {
        weights,
        bias,
        positive_examples,
        negative_examples,
    })
}

/// Train a cost-weighted binary classifier
fn train_cost_weighted_classifier(
    X: &ArrayView2<'_, Float>,
    y: &ArrayView1<'_, i32>,
    costs: (Float, Float), // (false_positive_cost, false_negative_cost)
    rng: &mut ChaCha8Rng,
) -> SklResult<BinaryClassifierState> {
    let (n_samples, n_features) = X.dim();
    let (fp_cost, fn_cost) = costs;

    // Initialize weights randomly
    let normal = Normal::new(0.0, 0.01).unwrap();
    let mut weights = Array1::random_using(n_features, normal, rng);
    let mut bias = 0.0;

    let learning_rate = 0.01;
    let max_iter = 1000;

    // Count examples
    let positive_examples = y.iter().filter(|&&label| label == 1).count();
    let negative_examples = n_samples - positive_examples;

    // Weighted gradient descent
    for _iter in 0..max_iter {
        let mut grad_weights = Array1::zeros(n_features);
        let mut grad_bias = 0.0;

        for i in 0..n_samples {
            let x_i = X.row(i);
            let y_i = y[i] as Float;

            // Weight example by cost
            let weight = if y_i == 1.0 { fn_cost } else { fp_cost };

            let logit = x_i.dot(&weights) + bias;
            let prob = 1.0 / (1.0 + (-logit).exp());
            let error = (prob - y_i) * weight;

            grad_weights = grad_weights + error * &x_i;
            grad_bias += error;
        }

        weights = weights - learning_rate * &grad_weights / (n_samples as Float);
        bias -= learning_rate * grad_bias / (n_samples as Float);
    }

    Ok(BinaryClassifierState {
        weights,
        bias,
        positive_examples,
        negative_examples,
    })
}

/// Train classifier with cost-sensitive loss function
fn train_cost_sensitive_loss_classifier(
    X: &ArrayView2<'_, Float>,
    y: &ArrayView1<'_, i32>,
    costs: (Float, Float),
    learning_rate: Float,
    max_iter: usize,
    rng: &mut ChaCha8Rng,
) -> SklResult<BinaryClassifierState> {
    let (n_samples, n_features) = X.dim();
    let (fp_cost, fn_cost) = costs;

    // Initialize weights randomly
    let normal = Normal::new(0.0, 0.01).unwrap();
    let mut weights = Array1::random_using(n_features, normal, rng);
    let mut bias = 0.0;

    // Count examples
    let positive_examples = y.iter().filter(|&&label| label == 1).count();
    let negative_examples = n_samples - positive_examples;

    // Cost-sensitive gradient descent with asymmetric loss
    for _iter in 0..max_iter {
        let mut grad_weights = Array1::zeros(n_features);
        let mut grad_bias = 0.0;

        for i in 0..n_samples {
            let x_i = X.row(i);
            let y_i = y[i] as Float;

            let logit = x_i.dot(&weights) + bias;
            let prob = 1.0 / (1.0 + (-logit).exp());

            // Cost-sensitive gradient computation
            let cost_adjusted_error = if y_i == 1.0 {
                // For positive examples, weight by false negative cost
                (prob - y_i) * fn_cost
            } else {
                // For negative examples, weight by false positive cost
                (prob - y_i) * fp_cost
            };

            grad_weights = grad_weights + cost_adjusted_error * &x_i;
            grad_bias += cost_adjusted_error;
        }

        weights = weights - learning_rate * &grad_weights / (n_samples as Float);
        bias -= learning_rate * grad_bias / (n_samples as Float);
    }

    Ok(BinaryClassifierState {
        weights,
        bias,
        positive_examples,
        negative_examples,
    })
}

/// Compute optimal threshold based on cost ratio
fn compute_cost_optimal_threshold(costs: (Float, Float)) -> Float {
    let (fp_cost, fn_cost) = costs;
    // Optimal threshold for cost-sensitive classification
    // threshold = cost_ratio / (1 + cost_ratio) where cost_ratio = fp_cost / fn_cost
    let cost_ratio = fp_cost / fn_cost;
    cost_ratio / (1.0 + cost_ratio)
}

// ================================================================================================
// Graph Neural Networks for Structured Output Prediction
// ================================================================================================

/// Aggregation functions for Graph Neural Networks
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AggregationFunction {
    /// Mean aggregation
    Mean,
    /// Sum aggregation  
    Sum,
    /// Maximum aggregation
    Max,
    /// Attention-based aggregation
    Attention,
}

/// Message passing variants for GNNs
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MessagePassingVariant {
    /// Graph Convolutional Network (GCN)
    GCN,
    /// Graph Attention Network (GAT)
    GAT,
    /// GraphSAGE
    GraphSAGE,
    /// Graph Isomorphism Network (GIN)
    GIN,
}

/// Graph Neural Network for Structured Output Prediction
///
/// This model handles structured prediction problems where the output space
/// has a graph structure. It uses message passing and node embedding to
/// learn representations that respect the graph topology.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::{GraphNeuralNetwork, MessagePassingVariant, AggregationFunction};
/// use sklears_core::traits::{Fit, Predict};
/// use ndarray::array;
///
/// // Example graph structure (adjacency matrix)
/// let adjacency = array![[0, 1, 1], [1, 0, 1], [1, 1, 0]];
/// let node_features = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
/// let node_labels = array![[1, 0], [0, 1], [1, 1]];
///
/// let gnn = GraphNeuralNetwork::new()
///     .hidden_dim(16)
///     .num_layers(2)
///     .message_passing_variant(MessagePassingVariant::GCN)
///     .aggregation_function(AggregationFunction::Mean)
///     .learning_rate(0.01)
///     .max_iter(100);
/// ```
#[derive(Debug, Clone)]
pub struct GraphNeuralNetwork<S = Untrained> {
    state: S,
    hidden_dim: usize,
    num_layers: usize,
    message_passing_variant: MessagePassingVariant,
    aggregation_function: AggregationFunction,
    learning_rate: Float,
    max_iter: usize,
    tolerance: Float,
    random_state: Option<u64>,
    alpha: Float, // L2 regularization
    dropout: Float,
    attention_heads: usize, // For GAT
}

/// Trained state for GraphNeuralNetwork
#[derive(Debug, Clone)]
pub struct GraphNeuralNetworkTrained {
    /// Weight matrices for each layer
    layer_weights: Vec<Array2<Float>>,
    /// Bias vectors for each layer
    layer_biases: Vec<Array1<Float>>,
    /// Attention weights (for GAT)
    attention_weights: Vec<Array2<Float>>,
    /// Output layer weights
    output_weights: Array2<Float>,
    /// Output layer bias
    output_bias: Array1<Float>,
    /// Network configuration
    hidden_dim: usize,
    num_layers: usize,
    message_passing_variant: MessagePassingVariant,
    aggregation_function: AggregationFunction,
    attention_heads: usize,
    n_features: usize,
    n_outputs: usize,
    /// Training history
    loss_curve: Vec<Float>,
    n_iter: usize,
}

impl GraphNeuralNetwork<Untrained> {
    /// Create a new GraphNeuralNetwork instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            hidden_dim: 64,
            num_layers: 2,
            message_passing_variant: MessagePassingVariant::GCN,
            aggregation_function: AggregationFunction::Mean,
            learning_rate: 0.01,
            max_iter: 200,
            tolerance: 1e-4,
            random_state: None,
            alpha: 1e-4,
            dropout: 0.0,
            attention_heads: 8,
        }
    }

    /// Set hidden dimension
    pub fn hidden_dim(mut self, hidden_dim: usize) -> Self {
        self.hidden_dim = hidden_dim;
        self
    }

    /// Set number of layers
    pub fn num_layers(mut self, num_layers: usize) -> Self {
        self.num_layers = num_layers;
        self
    }

    /// Set message passing variant
    pub fn message_passing_variant(mut self, variant: MessagePassingVariant) -> Self {
        self.message_passing_variant = variant;
        self
    }

    /// Set aggregation function
    pub fn aggregation_function(mut self, aggregation: AggregationFunction) -> Self {
        self.aggregation_function = aggregation;
        self
    }

    /// Set learning rate
    pub fn learning_rate(mut self, learning_rate: Float) -> Self {
        self.learning_rate = learning_rate;
        self
    }

    /// Set maximum iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set convergence tolerance
    pub fn tolerance(mut self, tolerance: Float) -> Self {
        self.tolerance = tolerance;
        self
    }

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

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

    /// Set dropout rate
    pub fn dropout(mut self, dropout: Float) -> Self {
        self.dropout = dropout;
        self
    }

    /// Set number of attention heads (for GAT)
    pub fn attention_heads(mut self, attention_heads: usize) -> Self {
        self.attention_heads = attention_heads;
        self
    }
}

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

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

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

/// Fit method for Graph Neural Networks with graph structure
impl GraphNeuralNetwork<Untrained> {
    /// Fit the GNN with adjacency matrix, node features, and node labels
    pub fn fit_graph(
        self,
        adjacency: &Array2<Float>, // Adjacency matrix [n_nodes, n_nodes]
        node_features: &Array2<Float>, // Node features [n_nodes, n_features]
        node_labels: &Array2<i32>, // Node labels [n_nodes, n_outputs]
    ) -> SklResult<GraphNeuralNetwork<GraphNeuralNetworkTrained>> {
        let (n_nodes, n_features) = node_features.dim();
        let (adj_nodes, adj_nodes_2) = adjacency.dim();
        let (label_nodes, n_outputs) = node_labels.dim();

        // Validation
        if adj_nodes != adj_nodes_2 {
            return Err(SklearsError::InvalidInput(
                "Adjacency matrix must be square".to_string(),
            ));
        }
        if n_nodes != adj_nodes || n_nodes != label_nodes {
            return Err(SklearsError::InvalidInput(
                "Number of nodes must match across adjacency matrix, features, and labels"
                    .to_string(),
            ));
        }
        if n_nodes == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with zero nodes".to_string(),
            ));
        }

        // Initialize random number generator
        let mut rng = match self.random_state {
            Some(seed) => ChaCha8Rng::seed_from_u64(seed),
            None => ChaCha8Rng::from_rng(&mut rand::thread_rng()).unwrap(),
        };

        // Initialize network parameters
        let (layer_weights, layer_biases, attention_weights, output_weights, output_bias) =
            self.initialize_gnn_parameters(n_features, n_outputs, &mut rng)?;

        let mut layer_weights = layer_weights;
        let mut layer_biases = layer_biases;
        let mut attention_weights = attention_weights;
        let mut output_weights = output_weights;
        let mut output_bias = output_bias;

        // Normalize adjacency matrix (add self-loops and compute degree normalization)
        let normalized_adj = self.normalize_adjacency(adjacency)?;

        // Training loop
        let mut loss_curve = Vec::new();
        let node_features_owned = node_features.to_owned();
        let node_labels_float = node_labels.map(|&x| x as Float);

        for epoch in 0..self.max_iter {
            // Forward pass
            let node_embeddings = self.forward_pass_gnn(
                &node_features_owned,
                &normalized_adj,
                &layer_weights,
                &layer_biases,
                &attention_weights,
            )?;

            // Output layer
            let predictions = node_embeddings.dot(&output_weights.t()) + &output_bias;

            // Compute loss (MSE for simplicity)
            let loss = self.compute_graph_loss(&predictions, &node_labels_float);
            loss_curve.push(loss);

            // Check convergence
            if epoch > 0 && (loss_curve[epoch - 1] - loss).abs() < self.tolerance {
                break;
            }

            // Backward pass (simplified gradient descent)
            self.backward_pass_gnn(
                &node_features_owned,
                &normalized_adj,
                &node_labels_float,
                &predictions,
                &node_embeddings,
                &mut layer_weights,
                &mut layer_biases,
                &mut attention_weights,
                &mut output_weights,
                &mut output_bias,
            )?;
        }

        let trained_state = GraphNeuralNetworkTrained {
            layer_weights,
            layer_biases,
            attention_weights,
            output_weights,
            output_bias,
            hidden_dim: self.hidden_dim,
            num_layers: self.num_layers,
            message_passing_variant: self.message_passing_variant,
            aggregation_function: self.aggregation_function,
            attention_heads: self.attention_heads,
            n_features,
            n_outputs,
            loss_curve,
            n_iter: self.max_iter,
        };

        Ok(GraphNeuralNetwork {
            state: trained_state,
            hidden_dim: self.hidden_dim,
            num_layers: self.num_layers,
            message_passing_variant: self.message_passing_variant,
            aggregation_function: self.aggregation_function,
            learning_rate: self.learning_rate,
            max_iter: self.max_iter,
            tolerance: self.tolerance,
            random_state: self.random_state,
            alpha: self.alpha,
            dropout: self.dropout,
            attention_heads: self.attention_heads,
        })
    }

    /// Initialize GNN parameters
    fn initialize_gnn_parameters(
        &self,
        n_features: usize,
        n_outputs: usize,
        rng: &mut ChaCha8Rng,
    ) -> SklResult<(
        Vec<Array2<Float>>, // layer_weights
        Vec<Array1<Float>>, // layer_biases
        Vec<Array2<Float>>, // attention_weights
        Array2<Float>,      // output_weights
        Array1<Float>,      // output_bias
    )> {
        let mut layer_weights = Vec::new();
        let mut layer_biases = Vec::new();
        let mut attention_weights = Vec::new();

        // Initialize layers
        for layer in 0..self.num_layers {
            let input_dim = if layer == 0 {
                match self.message_passing_variant {
                    MessagePassingVariant::GraphSAGE => n_features * 2, // Concatenated features
                    _ => n_features,
                }
            } else {
                match self.message_passing_variant {
                    MessagePassingVariant::GraphSAGE => self.hidden_dim * 2, // Concatenated features
                    _ => self.hidden_dim,
                }
            };
            let output_dim = self.hidden_dim;

            // Xavier initialization
            let scale = (2.0 / (input_dim + output_dim) as Float).sqrt();
            let weight = Array2::random_using(
                (output_dim, input_dim),
                Normal::new(0.0, scale).unwrap(),
                rng,
            );
            let bias = Array1::zeros(output_dim);

            layer_weights.push(weight);
            layer_biases.push(bias);

            // Initialize attention weights for GAT
            if self.message_passing_variant == MessagePassingVariant::GAT {
                let attention_dim = output_dim * 2; // Concatenated features
                let attention_weight = Array2::random_using(
                    (self.attention_heads, attention_dim),
                    Normal::new(0.0, scale).unwrap(),
                    rng,
                );
                attention_weights.push(attention_weight);
            }
        }

        // Output layer
        let output_scale = (2.0 / (self.hidden_dim + n_outputs) as Float).sqrt();
        let output_weights = Array2::random_using(
            (n_outputs, self.hidden_dim),
            Normal::new(0.0, output_scale).unwrap(),
            rng,
        );
        let output_bias = Array1::zeros(n_outputs);

        Ok((
            layer_weights,
            layer_biases,
            attention_weights,
            output_weights,
            output_bias,
        ))
    }

    /// Normalize adjacency matrix with self-loops and degree normalization
    fn normalize_adjacency(&self, adjacency: &Array2<Float>) -> SklResult<Array2<Float>> {
        let n_nodes = adjacency.nrows();

        // Add self-loops: A_tilde = A + I
        let mut adj_with_self_loops = adjacency.clone();
        for i in 0..n_nodes {
            adj_with_self_loops[[i, i]] += 1.0;
        }

        // Compute degree matrix D
        let degrees: Array1<Float> = adj_with_self_loops.sum_axis(Axis(1));

        // D^(-1/2) normalization for symmetric normalization
        let mut normalized_adj = Array2::zeros((n_nodes, n_nodes));
        for i in 0..n_nodes {
            for j in 0..n_nodes {
                if adj_with_self_loops[[i, j]] > 0.0 {
                    let norm_factor = (degrees[i] * degrees[j]).sqrt();
                    if norm_factor > 1e-10 {
                        normalized_adj[[i, j]] = adj_with_self_loops[[i, j]] / norm_factor;
                    }
                }
            }
        }

        Ok(normalized_adj)
    }

    /// Forward pass through GNN layers
    fn forward_pass_gnn(
        &self,
        node_features: &Array2<Float>,
        adjacency: &Array2<Float>,
        layer_weights: &[Array2<Float>],
        layer_biases: &[Array1<Float>],
        attention_weights: &[Array2<Float>],
    ) -> SklResult<Array2<Float>> {
        let mut current_features = node_features.clone();

        for layer in 0..self.num_layers {
            match self.message_passing_variant {
                MessagePassingVariant::GCN => {
                    current_features = self.gcn_layer(
                        &current_features,
                        adjacency,
                        &layer_weights[layer],
                        &layer_biases[layer],
                    )?;
                }
                MessagePassingVariant::GAT => {
                    current_features = self.gat_layer(
                        &current_features,
                        adjacency,
                        &layer_weights[layer],
                        &layer_biases[layer],
                        &attention_weights[layer],
                    )?;
                }
                MessagePassingVariant::GraphSAGE => {
                    current_features = self.graphsage_layer(
                        &current_features,
                        adjacency,
                        &layer_weights[layer],
                        &layer_biases[layer],
                    )?;
                }
                MessagePassingVariant::GIN => {
                    current_features = self.gin_layer(
                        &current_features,
                        adjacency,
                        &layer_weights[layer],
                        &layer_biases[layer],
                    )?;
                }
            }

            // Apply ReLU activation
            current_features = current_features.map(|&x| x.max(0.0));
        }

        Ok(current_features)
    }

    /// Graph Convolutional Network layer
    fn gcn_layer(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
    ) -> SklResult<Array2<Float>> {
        // H' = σ(AHW + b)
        let aggregated = adjacency.dot(features); // Message aggregation
        let transformed = aggregated.dot(&weights.t()); // Linear transformation
        let output = transformed + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// Graph Attention Network layer (simplified)
    fn gat_layer(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
        attention_weights: &Array2<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = features.nrows();
        let hidden_dim = weights.nrows();

        // Transform features
        let transformed_features = features.dot(&weights.t());

        // Simplified attention mechanism (using first attention head)
        let mut attended_features = Array2::zeros((n_nodes, hidden_dim));

        for i in 0..n_nodes {
            let mut weighted_sum = Array1::zeros(hidden_dim);
            let mut attention_sum = 0.0;

            for j in 0..n_nodes {
                if adjacency[[i, j]] > 0.0 {
                    // Simplified attention score (dot product)
                    let attention_score = transformed_features
                        .row(i)
                        .dot(&transformed_features.row(j));
                    let attention_weight = attention_score.exp();

                    weighted_sum = weighted_sum + attention_weight * &transformed_features.row(j);
                    attention_sum += attention_weight;
                }
            }

            if attention_sum > 1e-10 {
                attended_features
                    .row_mut(i)
                    .assign(&(weighted_sum / attention_sum));
            }
        }

        let output = attended_features + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// GraphSAGE layer (simplified)
    fn graphsage_layer(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = features.nrows();
        let n_features = features.ncols();

        // Aggregate neighbor features
        let mut aggregated_features = Array2::<Float>::zeros((n_nodes, n_features));

        for i in 0..n_nodes {
            let mut neighbor_sum = Array1::<Float>::zeros(n_features);
            let mut neighbor_count = 0;

            for j in 0..n_nodes {
                if adjacency[[i, j]] > 0.0 && i != j {
                    neighbor_sum = neighbor_sum + &features.row(j);
                    neighbor_count += 1;
                }
            }

            if neighbor_count > 0 {
                aggregated_features
                    .row_mut(i)
                    .assign(&(neighbor_sum / neighbor_count as Float));
            }
        }

        // Concatenate self features with aggregated neighbor features
        let concatenated =
            ndarray::concatenate![Axis(1), features.view(), aggregated_features.view()];

        // Apply transformation
        let output = concatenated.dot(&weights.t()) + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// Graph Isomorphism Network layer
    fn gin_layer(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = features.nrows();
        let n_features = features.ncols();

        // Sum aggregation of neighbors
        let mut aggregated_features = Array2::<Float>::zeros((n_nodes, n_features));

        for i in 0..n_nodes {
            let mut neighbor_sum = Array1::<Float>::zeros(n_features);

            for j in 0..n_nodes {
                if adjacency[[i, j]] > 0.0 && i != j {
                    neighbor_sum = neighbor_sum + &features.row(j);
                }
            }

            aggregated_features.row_mut(i).assign(&neighbor_sum);
        }

        // GIN update: (1 + ε) * h_i + Σ h_j
        let epsilon = 0.1; // Learnable parameter, simplified as constant
        let updated_features = features * (1.0 + epsilon) + &aggregated_features;

        // Apply MLP (simplified as single linear layer)
        let output = updated_features.dot(&weights.t()) + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// Compute graph-based loss
    fn compute_graph_loss(&self, predictions: &Array2<Float>, targets: &Array2<Float>) -> Float {
        let diff = predictions - targets;
        diff.map(|x| x * x).mean().unwrap()
    }

    /// Simplified backward pass for GNN
    fn backward_pass_gnn(
        &self,
        node_features: &Array2<Float>,
        adjacency: &Array2<Float>,
        targets: &Array2<Float>,
        predictions: &Array2<Float>,
        node_embeddings: &Array2<Float>,
        layer_weights: &mut [Array2<Float>],
        layer_biases: &mut [Array1<Float>],
        attention_weights: &mut [Array2<Float>],
        output_weights: &mut Array2<Float>,
        output_bias: &mut Array1<Float>,
    ) -> SklResult<()> {
        let n_nodes = node_features.nrows() as Float;

        // Output layer gradients
        let output_error = predictions - targets;
        let output_weight_grad = output_error.t().dot(node_embeddings) / n_nodes;
        let output_bias_grad = output_error.mean_axis(Axis(0)).unwrap();

        // Update output layer
        *output_weights = output_weights.clone() - self.learning_rate * output_weight_grad;
        *output_bias = output_bias.clone() - self.learning_rate * output_bias_grad;

        // Simplified hidden layer updates (using output error as proxy)
        for layer in (0..self.num_layers).rev() {
            let input_features = if layer == 0 {
                match self.message_passing_variant {
                    MessagePassingVariant::GraphSAGE => {
                        // For GraphSAGE, we need concatenated features
                        let n_nodes = node_features.nrows();
                        let n_features = node_features.ncols();
                        let mut aggregated = Array2::<Float>::zeros((n_nodes, n_features));
                        for i in 0..n_nodes {
                            let mut neighbor_sum = Array1::<Float>::zeros(n_features);
                            let mut neighbor_count = 0;
                            for j in 0..n_nodes {
                                if adjacency[[i, j]] > 0.0 && i != j {
                                    neighbor_sum = neighbor_sum + &node_features.row(j);
                                    neighbor_count += 1;
                                }
                            }
                            if neighbor_count > 0 {
                                aggregated
                                    .row_mut(i)
                                    .assign(&(neighbor_sum / neighbor_count as Float));
                            }
                        }
                        ndarray::concatenate![Axis(1), node_features.view(), aggregated.view()]
                    }
                    _ => node_features.clone(),
                }
            } else {
                // Simplified: use node_embeddings as proxy for intermediate representations
                match self.message_passing_variant {
                    MessagePassingVariant::GraphSAGE => {
                        // For GraphSAGE, concatenate embeddings with aggregated embeddings
                        let n_nodes = node_embeddings.nrows();
                        let n_features = node_embeddings.ncols();
                        let mut aggregated = Array2::<Float>::zeros((n_nodes, n_features));
                        for i in 0..n_nodes {
                            let mut neighbor_sum = Array1::<Float>::zeros(n_features);
                            let mut neighbor_count = 0;
                            for j in 0..n_nodes {
                                if adjacency[[i, j]] > 0.0 && i != j {
                                    neighbor_sum = neighbor_sum + &node_embeddings.row(j);
                                    neighbor_count += 1;
                                }
                            }
                            if neighbor_count > 0 {
                                aggregated
                                    .row_mut(i)
                                    .assign(&(neighbor_sum / neighbor_count as Float));
                            }
                        }
                        ndarray::concatenate![Axis(1), node_embeddings.view(), aggregated.view()]
                    }
                    _ => node_embeddings.clone(),
                }
            };

            let hidden_error_temp = output_weights.t().dot(&output_error.t());
            let hidden_error = hidden_error_temp.t();
            let weight_grad = hidden_error.t().dot(&input_features) / n_nodes;
            let bias_grad = hidden_error.mean_axis(Axis(0)).unwrap();

            layer_weights[layer] = layer_weights[layer].clone() - self.learning_rate * weight_grad;
            layer_biases[layer] = layer_biases[layer].clone() - self.learning_rate * bias_grad;
        }

        Ok(())
    }
}

/// Prediction method for trained GNN
impl GraphNeuralNetwork<GraphNeuralNetworkTrained> {
    /// Predict node labels given adjacency matrix and node features
    pub fn predict_graph(
        &self,
        adjacency: &Array2<Float>,
        node_features: &Array2<Float>,
    ) -> SklResult<Array2<i32>> {
        let (n_nodes, n_features) = node_features.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "Number of features doesn't match training data".to_string(),
            ));
        }

        // Normalize adjacency matrix
        let normalized_adj = self.normalize_adjacency_trained(adjacency)?;

        // Forward pass
        let node_embeddings = self.forward_pass_gnn_trained(&node_features, &normalized_adj)?;

        // Output predictions
        let predictions_float =
            node_embeddings.dot(&self.state.output_weights.t()) + &self.state.output_bias;

        // Convert to integer predictions (simple thresholding)
        let predictions = predictions_float.map(|&x| if x > 0.5 { 1 } else { 0 });

        Ok(predictions)
    }

    /// Normalize adjacency matrix for trained model
    fn normalize_adjacency_trained(&self, adjacency: &Array2<Float>) -> SklResult<Array2<Float>> {
        let n_nodes = adjacency.nrows();

        // Add self-loops
        let mut adj_with_self_loops = adjacency.clone();
        for i in 0..n_nodes {
            adj_with_self_loops[[i, i]] += 1.0;
        }

        // Compute degrees
        let degrees: Array1<Float> = adj_with_self_loops.sum_axis(Axis(1));

        // Symmetric normalization
        let mut normalized_adj = Array2::zeros((n_nodes, n_nodes));
        for i in 0..n_nodes {
            for j in 0..n_nodes {
                if adj_with_self_loops[[i, j]] > 0.0 {
                    let norm_factor = (degrees[i] * degrees[j]).sqrt();
                    if norm_factor > 1e-10 {
                        normalized_adj[[i, j]] = adj_with_self_loops[[i, j]] / norm_factor;
                    }
                }
            }
        }

        Ok(normalized_adj)
    }

    /// Forward pass for trained model
    fn forward_pass_gnn_trained(
        &self,
        node_features: &Array2<Float>,
        adjacency: &Array2<Float>,
    ) -> SklResult<Array2<Float>> {
        let mut current_features = node_features.clone();

        for layer in 0..self.state.num_layers {
            match self.state.message_passing_variant {
                MessagePassingVariant::GCN => {
                    current_features = self.gcn_layer_trained(
                        &current_features,
                        adjacency,
                        &self.state.layer_weights[layer],
                        &self.state.layer_biases[layer],
                    )?;
                }
                MessagePassingVariant::GAT => {
                    current_features = self.gat_layer_trained(
                        &current_features,
                        adjacency,
                        &self.state.layer_weights[layer],
                        &self.state.layer_biases[layer],
                        &self.state.attention_weights[layer],
                    )?;
                }
                MessagePassingVariant::GraphSAGE => {
                    current_features = self.graphsage_layer_trained(
                        &current_features,
                        adjacency,
                        &self.state.layer_weights[layer],
                        &self.state.layer_biases[layer],
                    )?;
                }
                MessagePassingVariant::GIN => {
                    current_features = self.gin_layer_trained(
                        &current_features,
                        adjacency,
                        &self.state.layer_weights[layer],
                        &self.state.layer_biases[layer],
                    )?;
                }
            }

            // Apply ReLU activation
            current_features = current_features.map(|&x| x.max(0.0));
        }

        Ok(current_features)
    }

    /// GCN layer for trained model
    fn gcn_layer_trained(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
    ) -> SklResult<Array2<Float>> {
        let aggregated = adjacency.dot(features);
        let transformed = aggregated.dot(&weights.t());
        let output = transformed + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// GAT layer for trained model
    fn gat_layer_trained(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
        attention_weights: &Array2<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = features.nrows();
        let hidden_dim = weights.nrows();

        let transformed_features = features.dot(&weights.t());
        let mut attended_features = Array2::zeros((n_nodes, hidden_dim));

        for i in 0..n_nodes {
            let mut weighted_sum = Array1::zeros(hidden_dim);
            let mut attention_sum = 0.0;

            for j in 0..n_nodes {
                if adjacency[[i, j]] > 0.0 {
                    let attention_score = transformed_features
                        .row(i)
                        .dot(&transformed_features.row(j));
                    let attention_weight = attention_score.exp();

                    weighted_sum = weighted_sum + attention_weight * &transformed_features.row(j);
                    attention_sum += attention_weight;
                }
            }

            if attention_sum > 1e-10 {
                attended_features
                    .row_mut(i)
                    .assign(&(weighted_sum / attention_sum));
            }
        }

        let output = attended_features + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// GraphSAGE layer for trained model
    fn graphsage_layer_trained(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = features.nrows();
        let n_features = features.ncols();

        let mut aggregated_features = Array2::<Float>::zeros((n_nodes, n_features));

        for i in 0..n_nodes {
            let mut neighbor_sum = Array1::<Float>::zeros(n_features);
            let mut neighbor_count = 0;

            for j in 0..n_nodes {
                if adjacency[[i, j]] > 0.0 && i != j {
                    neighbor_sum = neighbor_sum + &features.row(j);
                    neighbor_count += 1;
                }
            }

            if neighbor_count > 0 {
                aggregated_features
                    .row_mut(i)
                    .assign(&(neighbor_sum / neighbor_count as Float));
            }
        }

        let concatenated =
            ndarray::concatenate![Axis(1), features.view(), aggregated_features.view()];
        let output = concatenated.dot(&weights.t()) + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// GIN layer for trained model
    fn gin_layer_trained(
        &self,
        features: &Array2<Float>,
        adjacency: &Array2<Float>,
        weights: &Array2<Float>,
        bias: &Array1<Float>,
    ) -> SklResult<Array2<Float>> {
        let n_nodes = features.nrows();
        let n_features = features.ncols();

        let mut aggregated_features = Array2::<Float>::zeros((n_nodes, n_features));

        for i in 0..n_nodes {
            let mut neighbor_sum = Array1::<Float>::zeros(n_features);

            for j in 0..n_nodes {
                if adjacency[[i, j]] > 0.0 && i != j {
                    neighbor_sum = neighbor_sum + &features.row(j);
                }
            }

            aggregated_features.row_mut(i).assign(&neighbor_sum);
        }

        let epsilon = 0.1;
        let updated_features = features * (1.0 + epsilon) + &aggregated_features;
        let output = updated_features.dot(&weights.t()) + &bias.view().insert_axis(Axis(0));
        Ok(output)
    }

    /// Get the loss curve from training
    pub fn loss_curve(&self) -> &[Float] {
        &self.state.loss_curve
    }

    /// Get training iterations
    pub fn n_iter(&self) -> usize {
        self.state.n_iter
    }

    /// Get network configuration
    pub fn message_passing_variant(&self) -> MessagePassingVariant {
        self.state.message_passing_variant
    }

    /// Get hidden dimension
    pub fn hidden_dim(&self) -> usize {
        self.state.hidden_dim
    }
}

// ================================================================================================
// Tests for Graph Neural Networks
// ================================================================================================

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

    #[test]
    fn test_gnn_basic_functionality() {
        // Create a simple 3-node graph
        let adjacency = array![[0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0]];
        let node_features = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let node_labels = array![[1, 0], [0, 1], [1, 1]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(8)
            .num_layers(2)
            .message_passing_variant(MessagePassingVariant::GCN)
            .max_iter(10)
            .random_state(Some(42));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (3, 2));
        assert!(predictions.iter().all(|&x| x == 0 || x == 1));
    }

    #[test]
    fn test_gnn_gat_variant() {
        let adjacency = array![[0.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0]];
        let node_features = array![[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let node_labels = array![[1, 0], [0, 1], [1, 0]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(6)
            .num_layers(1)
            .message_passing_variant(MessagePassingVariant::GAT)
            .attention_heads(2)
            .max_iter(5)
            .random_state(Some(123));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (3, 2));
        assert_eq!(
            trained_gnn.message_passing_variant(),
            MessagePassingVariant::GAT
        );
    }

    #[test]
    fn test_gnn_graphsage_variant() {
        let adjacency = array![
            [0.0, 1.0, 1.0, 0.0],
            [1.0, 0.0, 0.0, 1.0],
            [1.0, 0.0, 0.0, 1.0],
            [0.0, 1.0, 1.0, 0.0]
        ];
        let node_features = array![[1.0, 2.0], [2.0, 1.0], [1.5, 1.5], [2.5, 0.5]];
        let node_labels = array![[1, 0], [0, 1], [1, 1], [0, 0]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(4)
            .num_layers(2)
            .message_passing_variant(MessagePassingVariant::GraphSAGE)
            .max_iter(8)
            .random_state(Some(456));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (4, 2));
        assert_eq!(
            trained_gnn.message_passing_variant(),
            MessagePassingVariant::GraphSAGE
        );
    }

    #[test]
    fn test_gnn_gin_variant() {
        let adjacency = array![[0.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0]];
        let node_features = array![[2.0, 1.0], [1.0, 2.0], [1.5, 1.5]];
        let node_labels = array![[1, 1], [0, 1], [1, 0]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(5)
            .num_layers(1)
            .message_passing_variant(MessagePassingVariant::GIN)
            .max_iter(6)
            .random_state(Some(789));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (3, 2));
        assert_eq!(
            trained_gnn.message_passing_variant(),
            MessagePassingVariant::GIN
        );
    }

    #[test]
    fn test_gnn_configuration() {
        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(32)
            .num_layers(3)
            .message_passing_variant(MessagePassingVariant::GAT)
            .aggregation_function(AggregationFunction::Attention)
            .learning_rate(0.005)
            .max_iter(50)
            .tolerance(1e-5)
            .random_state(Some(42))
            .alpha(0.01)
            .dropout(0.1)
            .attention_heads(4);

        assert_eq!(gnn.hidden_dim, 32);
        assert_eq!(gnn.num_layers, 3);
        assert_eq!(gnn.message_passing_variant, MessagePassingVariant::GAT);
        assert_eq!(gnn.aggregation_function, AggregationFunction::Attention);
        assert_eq!(gnn.learning_rate, 0.005);
        assert_eq!(gnn.max_iter, 50);
        assert_eq!(gnn.tolerance, 1e-5);
        assert_eq!(gnn.random_state, Some(42));
        assert_eq!(gnn.alpha, 0.01);
        assert_eq!(gnn.dropout, 0.1);
        assert_eq!(gnn.attention_heads, 4);
    }

    #[test]
    fn test_gnn_error_handling() {
        let adjacency = array![[0.0, 1.0], [1.0, 0.0]]; // 2x2 matrix
        let node_features = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]]; // 3 nodes
        let node_labels = array![[1, 0], [0, 1]]; // 2 nodes

        let gnn = GraphNeuralNetwork::new();
        assert!(gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .is_err());

        // Test non-square adjacency matrix
        let adjacency_nonsquare = array![[0.0, 1.0, 1.0], [1.0, 0.0, 1.0]]; // 2x3 matrix
        let node_features_2 = array![[1.0, 2.0], [2.0, 3.0]];
        let node_labels_2 = array![[1, 0], [0, 1]];

        let gnn2 = GraphNeuralNetwork::new();
        assert!(gnn2
            .fit_graph(&adjacency_nonsquare, &node_features_2, &node_labels_2)
            .is_err());

        // Test prediction with wrong number of features
        let adjacency_valid = array![[0.0, 1.0], [1.0, 0.0]];
        let node_features_valid = array![[1.0, 2.0], [2.0, 3.0]];
        let node_labels_valid = array![[1, 0], [0, 1]];

        let gnn3 = GraphNeuralNetwork::new().max_iter(1);
        let trained_gnn = gnn3
            .fit_graph(&adjacency_valid, &node_features_valid, &node_labels_valid)
            .unwrap();

        let node_features_wrong = array![[1.0, 2.0, 3.0], [2.0, 3.0, 1.0]]; // Wrong number of features
        assert!(trained_gnn
            .predict_graph(&adjacency_valid, &node_features_wrong)
            .is_err());
    }

    #[test]
    fn test_gnn_reproducibility() {
        let adjacency = array![[0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0]];
        let node_features = array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]];
        let node_labels = array![[1, 0], [0, 1], [1, 1]];

        let gnn1 = GraphNeuralNetwork::new()
            .hidden_dim(6)
            .max_iter(5)
            .random_state(Some(42));
        let trained_gnn1 = gnn1
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let pred1 = trained_gnn1
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        let gnn2 = GraphNeuralNetwork::new()
            .hidden_dim(6)
            .max_iter(5)
            .random_state(Some(42));
        let trained_gnn2 = gnn2
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let pred2 = trained_gnn2
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        // With the same random state, predictions should be identical
        for i in 0..pred1.nrows() {
            for j in 0..pred1.ncols() {
                assert_eq!(pred1[[i, j]], pred2[[i, j]]);
            }
        }
    }

    #[test]
    fn test_gnn_adjacency_normalization() {
        let adjacency = array![[0.0, 2.0, 1.0], [2.0, 0.0, 3.0], [1.0, 3.0, 0.0]]; // Weighted adjacency
        let node_features = array![[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let node_labels = array![[1, 0], [0, 1], [1, 1]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(4)
            .max_iter(3)
            .random_state(Some(123));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (3, 2));
        assert!(predictions.iter().all(|&x| x == 0 || x == 1));
    }

    #[test]
    fn test_gnn_single_node() {
        let adjacency = array![[0.0]]; // Single node with no self-connection
        let node_features = array![[1.0, 2.0]];
        let node_labels = array![[1, 0]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(3)
            .max_iter(2)
            .random_state(Some(999));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (1, 2));
        assert!(predictions.iter().all(|&x| x == 0 || x == 1));
    }

    #[test]
    fn test_aggregation_function_enums() {
        assert_eq!(AggregationFunction::Mean, AggregationFunction::Mean);
        assert_ne!(AggregationFunction::Mean, AggregationFunction::Sum);
        assert_ne!(AggregationFunction::Max, AggregationFunction::Attention);
    }

    #[test]
    fn test_message_passing_variant_enums() {
        assert_eq!(MessagePassingVariant::GCN, MessagePassingVariant::GCN);
        assert_ne!(MessagePassingVariant::GCN, MessagePassingVariant::GAT);
        assert_ne!(MessagePassingVariant::GraphSAGE, MessagePassingVariant::GIN);
    }

    #[test]
    fn test_gnn_large_graph() {
        // Test with a larger graph (5 nodes)
        let adjacency = array![
            [0.0, 1.0, 1.0, 0.0, 0.0],
            [1.0, 0.0, 1.0, 1.0, 0.0],
            [1.0, 1.0, 0.0, 1.0, 1.0],
            [0.0, 1.0, 1.0, 0.0, 1.0],
            [0.0, 0.0, 1.0, 1.0, 0.0]
        ];
        let node_features = array![
            [1.0, 2.0, 0.5],
            [2.0, 1.0, 1.5],
            [1.5, 1.5, 1.0],
            [0.5, 2.5, 0.8],
            [2.5, 0.5, 1.2]
        ];
        let node_labels = array![[1, 0, 1], [0, 1, 0], [1, 1, 1], [0, 0, 1], [1, 0, 0]];

        let gnn = GraphNeuralNetwork::new()
            .hidden_dim(10)
            .num_layers(2)
            .message_passing_variant(MessagePassingVariant::GCN)
            .max_iter(15)
            .random_state(Some(42));

        let trained_gnn = gnn
            .fit_graph(&adjacency, &node_features, &node_labels)
            .unwrap();
        let predictions = trained_gnn
            .predict_graph(&adjacency, &node_features)
            .unwrap();

        assert_eq!(predictions.dim(), (5, 3));
        assert!(predictions.iter().all(|&x| x == 0 || x == 1));
        assert_eq!(trained_gnn.hidden_dim(), 10);
    }
}