trustformers-debug 0.1.1

Advanced debugging tools for TrustformeRS models
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
//! Utilities module for common debugging operations and helper functions

use anyhow::Result;
use ndarray::{Array, ArrayD, IxDyn};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant};

use crate::{DebugConfig, DebugSession, QuickDebugLevel, SimplifiedDebugResult};

/// Common debugging utilities and helper functions
pub struct DebugUtils;

impl DebugUtils {
    /// Quick model health check with automatic issue detection
    pub async fn quick_health_check<T>(model: &T) -> Result<HealthCheckResult> {
        let result = crate::quick_debug(model, QuickDebugLevel::Light).await?;
        
        let health_score = match &result {
            SimplifiedDebugResult::Light(health) => health.score,
            SimplifiedDebugResult::Standard { health, .. } => health.score,
            SimplifiedDebugResult::Deep(report) => {
                let summary = report.summary();
                100.0 - (summary.critical_issues as f64 * 20.0 + summary.total_issues as f64 * 5.0)
            },
            SimplifiedDebugResult::Production(anomaly) => {
                100.0 - (anomaly.anomaly_count as f64 * 10.0)
            }
        };

        Ok(HealthCheckResult {
            overall_score: health_score,
            status: Self::score_to_status(health_score),
            issues: result.recommendations(),
            critical_issues: result.has_critical_issues(),
            timestamp: chrono::Utc::now(),
        })
    }

    /// Batch tensor analysis with statistical insights
    pub fn analyze_tensors_batch(tensors: &[ArrayD<f32>]) -> Result<BatchTensorAnalysis> {
        let mut results = Vec::new();
        let mut overall_stats = TensorStatistics::default();

        for (i, tensor) in tensors.iter().enumerate() {
            let stats = Self::compute_tensor_statistics(tensor)?;
            results.push(TensorAnalysisResult {
                tensor_index: i,
                shape: tensor.shape().to_vec(),
                statistics: stats.clone(),
                anomalies: Self::detect_tensor_anomalies(&stats),
            });

            // Accumulate overall statistics
            overall_stats.accumulate(&stats);
        }

        overall_stats.finalize(tensors.len());

        Ok(BatchTensorAnalysis {
            individual_results: results,
            overall_statistics: overall_stats,
            batch_size: tensors.len(),
            analysis_timestamp: chrono::Utc::now(),
        })
    }

    /// Compute comprehensive tensor statistics
    pub fn compute_tensor_statistics(tensor: &ArrayD<f32>) -> Result<TensorStatistics> {
        let values: Vec<f32> = tensor.iter().cloned().collect();
        let n = values.len() as f64;

        if n == 0.0 {
            return Ok(TensorStatistics::default());
        }

        let sum: f64 = values.iter().map(|&x| x as f64).sum::<f64>();
        let mean = sum / n;

        let variance: f64 = values.iter()
            .map(|&x| (x as f64 - mean).powi(2))
            .sum::<f64>() / n;
        let std_dev = variance.sqrt();

        let mut sorted_values = values.clone();
        sorted_values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let min = *sorted_values.first().unwrap_or(&0.0);
        let max = *sorted_values.last().unwrap_or(&0.0);

        let median = if sorted_values.len() % 2 == 0 {
            let mid = sorted_values.len() / 2;
            (sorted_values[mid - 1] + sorted_values[mid]) / 2.0
        } else {
            sorted_values[sorted_values.len() / 2]
        };

        let p25 = Self::percentile(&sorted_values, 0.25);
        let p75 = Self::percentile(&sorted_values, 0.75);

        let nan_count = values.iter().filter(|&&x| x.is_nan()).count();
        let inf_count = values.iter().filter(|&&x| x.is_infinite()).count();
        let zero_count = values.iter().filter(|&&x| x == 0.0).count();

        let skewness = Self::compute_skewness(&values, mean, std_dev);
        let kurtosis = Self::compute_kurtosis(&values, mean, std_dev);

        Ok(TensorStatistics {
            count: n as usize,
            mean: mean as f32,
            std_dev: std_dev as f32,
            min,
            max,
            median,
            p25,
            p75,
            nan_count,
            inf_count,
            zero_count,
            skewness: skewness as f32,
            kurtosis: kurtosis as f32,
        })
    }

    /// Detect anomalies in tensor statistics
    pub fn detect_tensor_anomalies(stats: &TensorStatistics) -> Vec<TensorAnomaly> {
        let mut anomalies = Vec::new();

        // Check for NaN/Inf values
        if stats.nan_count > 0 {
            anomalies.push(TensorAnomaly {
                anomaly_type: AnomalyType::NanValues,
                severity: AnomalySeverity::Critical,
                description: format!("Found {} NaN values", stats.nan_count),
                suggested_fix: "Check input data and model initialization".to_string(),
            });
        }

        if stats.inf_count > 0 {
            anomalies.push(TensorAnomaly {
                anomaly_type: AnomalyType::InfiniteValues,
                severity: AnomalySeverity::Critical,
                description: format!("Found {} infinite values", stats.inf_count),
                suggested_fix: "Reduce learning rate or add gradient clipping".to_string(),
            });
        }

        // Check for extreme skewness
        if stats.skewness.abs() > 3.0 {
            anomalies.push(TensorAnomaly {
                anomaly_type: AnomalyType::ExtremeSkewness,
                severity: AnomalySeverity::Medium,
                description: format!("Extreme skewness: {:.2}", stats.skewness),
                suggested_fix: "Consider data normalization or different initialization".to_string(),
            });
        }

        // Check for extreme kurtosis
        if stats.kurtosis.abs() > 7.0 {
            anomalies.push(TensorAnomaly {
                anomaly_type: AnomalyType::ExtremeKurtosis,
                severity: AnomalySeverity::Medium,
                description: format!("Extreme kurtosis: {:.2}", stats.kurtosis),
                suggested_fix: "Check for outliers or consider robust normalization".to_string(),
            });
        }

        // Check for too many zeros (dead neurons indicator)
        let zero_ratio = stats.zero_count as f32 / stats.count as f32;
        if zero_ratio > 0.5 {
            anomalies.push(TensorAnomaly {
                anomaly_type: AnomalyType::DeadNeurons,
                severity: AnomalySeverity::High,
                description: format!("High zero ratio: {:.1}%", zero_ratio * 100.0),
                suggested_fix: "Check activation functions and learning rate".to_string(),
            });
        }

        // Check for extremely small or large values
        if stats.max > 1e6 || stats.min < -1e6 {
            anomalies.push(TensorAnomaly {
                anomaly_type: AnomalyType::ExtremeValues,
                severity: AnomalySeverity::High,
                description: format!("Extreme values: min={:.2e}, max={:.2e}", stats.min, stats.max),
                suggested_fix: "Consider gradient clipping or normalization".to_string(),
            });
        }

        anomalies
    }

    /// Generate debug report summary
    pub fn generate_debug_summary(config: &DebugConfig, results: &[SimplifiedDebugResult]) -> DebugSummary {
        let mut total_issues = 0;
        let mut critical_issues = 0;
        let mut all_recommendations = Vec::new();

        for result in results {
            if result.has_critical_issues() {
                critical_issues += 1;
            }
            total_issues += 1;
            all_recommendations.extend(result.recommendations());
        }

        // Deduplicate recommendations
        all_recommendations.sort();
        all_recommendations.dedup();

        DebugSummary {
            config_hash: Self::hash_config(config),
            total_debug_runs: results.len(),
            total_issues,
            critical_issues,
            recommendations: all_recommendations,
            timestamp: chrono::Utc::now(),
        }
    }

    /// Export debug session data to various formats
    pub async fn export_debug_data(
        session: &DebugSession, 
        format: ExportFormat, 
        output_path: &str
    ) -> Result<String> {
        let report = session.generate_snapshot().await?;
        
        match format {
            ExportFormat::Json => {
                let json_data = serde_json::to_string_pretty(&report)?;
                tokio::fs::write(output_path, json_data).await?;
            },
            ExportFormat::Csv => {
                let csv_data = Self::report_to_csv(&report)?;
                tokio::fs::write(output_path, csv_data).await?;
            },
            ExportFormat::Html => {
                let html_data = Self::report_to_html(&report)?;
                tokio::fs::write(output_path, html_data).await?;
            },
        }

        Ok(output_path.to_string())
    }

    /// Create a debug session template for common use cases
    pub fn create_debug_template(template_type: DebugTemplate) -> DebugConfig {
        match template_type {
            DebugTemplate::Development => DebugConfig {
                enable_tensor_inspection: true,
                enable_gradient_debugging: true,
                enable_model_diagnostics: true,
                enable_visualization: true,
                enable_memory_profiling: true,
                enable_computation_graph_analysis: true,
                max_tracked_tensors: 1000,
                max_gradient_history: 200,
                sampling_rate: 1.0,
                ..Default::default()
            },
            DebugTemplate::Production => DebugConfig {
                enable_tensor_inspection: false,
                enable_gradient_debugging: false,
                enable_model_diagnostics: false,
                enable_visualization: false,
                enable_memory_profiling: true,
                enable_computation_graph_analysis: false,
                max_tracked_tensors: 50,
                max_gradient_history: 10,
                sampling_rate: 0.1,
                ..Default::default()
            },
            DebugTemplate::Training => DebugConfig {
                enable_tensor_inspection: true,
                enable_gradient_debugging: true,
                enable_model_diagnostics: true,
                enable_visualization: false,
                enable_memory_profiling: true,
                enable_computation_graph_analysis: true,
                max_tracked_tensors: 500,
                max_gradient_history: 100,
                sampling_rate: 0.5,
                ..Default::default()
            },
            DebugTemplate::Research => DebugConfig {
                enable_tensor_inspection: true,
                enable_gradient_debugging: true,
                enable_model_diagnostics: true,
                enable_visualization: true,
                enable_memory_profiling: true,
                enable_computation_graph_analysis: true,
                max_tracked_tensors: 2000,
                max_gradient_history: 500,
                sampling_rate: 1.0,
                ..Default::default()
            },
        }
    }

    // Helper functions
    fn score_to_status(score: f64) -> String {
        match score {
            s if s >= 90.0 => "Excellent".to_string(),
            s if s >= 80.0 => "Good".to_string(),
            s if s >= 70.0 => "Fair".to_string(),
            s if s >= 60.0 => "Poor".to_string(),
            _ => "Critical".to_string(),
        }
    }

    fn percentile(sorted_values: &[f32], p: f64) -> f32 {
        let index = (p * (sorted_values.len() - 1) as f64) as usize;
        sorted_values.get(index).copied().unwrap_or(0.0)
    }

    fn compute_skewness(values: &[f32], mean: f64, std_dev: f64) -> f64 {
        if std_dev == 0.0 {
            return 0.0;
        }
        let n = values.len() as f64;
        let sum: f64 = values.iter()
            .map(|&x| ((x as f64 - mean) / std_dev).powi(3))
            .sum::<f64>();
        sum / n
    }

    fn compute_kurtosis(values: &[f32], mean: f64, std_dev: f64) -> f64 {
        if std_dev == 0.0 {
            return 0.0;
        }
        let n = values.len() as f64;
        let sum: f64 = values.iter()
            .map(|&x| ((x as f64 - mean) / std_dev).powi(4))
            .sum::<f64>();
        (sum / n) - 3.0 // Subtract 3 for excess kurtosis
    }

    fn hash_config(config: &DebugConfig) -> String {
        // Simple hash implementation for config tracking
        format!("{:x}", 
            config.enable_tensor_inspection as u8 |
            (config.enable_gradient_debugging as u8) << 1 |
            (config.enable_model_diagnostics as u8) << 2 |
            (config.enable_visualization as u8) << 3 |
            (config.enable_memory_profiling as u8) << 4
        )
    }

    fn report_to_csv(report: &crate::DebugReport) -> Result<String> {
        let mut csv = String::new();
        csv.push_str("session_id,component,metric,value\n");
        
        csv.push_str(&format!("{},session,id,{}\n", report.session_id, report.session_id));
        
        if let Some(ref tensor_report) = report.tensor_report {
            csv.push_str(&format!("{},tensor,total_tensors,{}\n", 
                report.session_id, tensor_report.total_tensors));
            csv.push_str(&format!("{},tensor,tensors_with_issues,{}\n", 
                report.session_id, tensor_report.tensors_with_issues));
        }

        Ok(csv)
    }

    fn report_to_html(report: &crate::DebugReport) -> Result<String> {
        let mut html = String::new();
        html.push_str("<!DOCTYPE html><html><head><title>Debug Report</title></head><body>");
        html.push_str(&format!("<h1>Debug Report - Session {}</h1>", report.session_id));
        
        if let Some(ref tensor_report) = report.tensor_report {
            html.push_str("<h2>Tensor Analysis</h2>");
            html.push_str(&format!("<p>Total tensors: {}</p>", tensor_report.total_tensors));
            html.push_str(&format!("<p>Tensors with issues: {}</p>", tensor_report.tensors_with_issues));
        }

        html.push_str("</body></html>");
        Ok(html)
    }
}

/// Health check result structure
#[derive(Debug, Serialize, Deserialize)]
pub struct HealthCheckResult {
    pub overall_score: f64,
    pub status: String,
    pub issues: Vec<String>,
    pub critical_issues: bool,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Batch tensor analysis result
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchTensorAnalysis {
    pub individual_results: Vec<TensorAnalysisResult>,
    pub overall_statistics: TensorStatistics,
    pub batch_size: usize,
    pub analysis_timestamp: chrono::DateTime<chrono::Utc>,
}

/// Individual tensor analysis result
#[derive(Debug, Serialize, Deserialize)]
pub struct TensorAnalysisResult {
    pub tensor_index: usize,
    pub shape: Vec<usize>,
    pub statistics: TensorStatistics,
    pub anomalies: Vec<TensorAnomaly>,
}

/// Comprehensive tensor statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TensorStatistics {
    pub count: usize,
    pub mean: f32,
    pub std_dev: f32,
    pub min: f32,
    pub max: f32,
    pub median: f32,
    pub p25: f32,
    pub p75: f32,
    pub nan_count: usize,
    pub inf_count: usize,
    pub zero_count: usize,
    pub skewness: f32,
    pub kurtosis: f32,
}

impl Default for TensorStatistics {
    fn default() -> Self {
        Self {
            count: 0,
            mean: 0.0,
            std_dev: 0.0,
            min: 0.0,
            max: 0.0,
            median: 0.0,
            p25: 0.0,
            p75: 0.0,
            nan_count: 0,
            inf_count: 0,
            zero_count: 0,
            skewness: 0.0,
            kurtosis: 0.0,
        }
    }
}

impl TensorStatistics {
    fn accumulate(&mut self, other: &TensorStatistics) {
        self.count += other.count;
        self.mean += other.mean;
        self.std_dev += other.std_dev;
        self.min = self.min.min(other.min);
        self.max = self.max.max(other.max);
        self.nan_count += other.nan_count;
        self.inf_count += other.inf_count;
        self.zero_count += other.zero_count;
    }

    fn finalize(&mut self, batch_size: usize) {
        if batch_size > 0 {
            self.mean /= batch_size as f32;
            self.std_dev /= batch_size as f32;
        }
    }
}

/// Tensor anomaly detection result
#[derive(Debug, Serialize, Deserialize)]
pub struct TensorAnomaly {
    pub anomaly_type: AnomalyType,
    pub severity: AnomalySeverity,
    pub description: String,
    pub suggested_fix: String,
}

/// Types of tensor anomalies
#[derive(Debug, Serialize, Deserialize)]
pub enum AnomalyType {
    NanValues,
    InfiniteValues,
    ExtremeSkewness,
    ExtremeKurtosis,
    DeadNeurons,
    ExtremeValues,
    Saturation,
    Outliers,
}

/// Severity levels for anomalies
#[derive(Debug, Serialize, Deserialize)]
pub enum AnomalySeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// Debug summary structure
#[derive(Debug, Serialize, Deserialize)]
pub struct DebugSummary {
    pub config_hash: String,
    pub total_debug_runs: usize,
    pub total_issues: usize,
    pub critical_issues: usize,
    pub recommendations: Vec<String>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Export format options
#[derive(Debug, Clone)]
pub enum ExportFormat {
    Json,
    Csv,
    Html,
}

/// Debug template types
#[derive(Debug, Clone)]
pub enum DebugTemplate {
    Development,
    Production,
    Training,
    Research,
}

/// Debugging convenience macros
#[macro_export]
macro_rules! debug_tensor {
    ($session:expr, $tensor:expr, $name:expr) => {
        $session.tensor_inspector_mut().inspect_tensor(
            $tensor, 
            $name, 
            None, 
            Some("debug_macro")
        )
    };
    ($session:expr, $tensor:expr, $name:expr, $layer:expr) => {
        $session.tensor_inspector_mut().inspect_tensor(
            $tensor, 
            $name, 
            Some($layer), 
            Some("debug_macro")
        )
    };
}

#[macro_export]
macro_rules! debug_gradient {
    ($session:expr, $layer:expr, $gradients:expr) => {
        $session.gradient_debugger_mut().record_gradient_flow($layer, $gradients)
    };
}

#[macro_export]
macro_rules! quick_debug_check {
    ($model:expr) => {
        trustformers_debug::debug($model).await
    };
    ($model:expr, $level:expr) => {
        trustformers_debug::quick_debug($model, $level).await
    };
}

/// Performance monitoring utilities
pub struct PerformanceMonitor {
    start_time: Instant,
    checkpoints: HashMap<String, Instant>,
    durations: HashMap<String, Duration>,
}

impl PerformanceMonitor {
    pub fn new() -> Self {
        Self {
            start_time: Instant::now(),
            checkpoints: HashMap::new(),
            durations: HashMap::new(),
        }
    }

    pub fn checkpoint(&mut self, name: &str) {
        self.checkpoints.insert(name.to_string(), Instant::now());
    }

    pub fn end_checkpoint(&mut self, name: &str) -> Option<Duration> {
        if let Some(start) = self.checkpoints.remove(name) {
            let duration = start.elapsed();
            self.durations.insert(name.to_string(), duration);
            Some(duration)
        } else {
            None
        }
    }

    pub fn total_elapsed(&self) -> Duration {
        self.start_time.elapsed()
    }

    pub fn get_durations(&self) -> &HashMap<String, Duration> {
        &self.durations
    }

    pub fn performance_report(&self) -> String {
        let mut report = format!("Performance Report - Total: {:.2}ms\n", 
                               self.total_elapsed().as_millis());
        
        for (name, duration) in &self.durations {
            report.push_str(&format!("  {}: {:.2}ms\n", name, duration.as_millis()));
        }
        
        report
    }
}

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

/// Advanced tensor analysis with ML-specific insights
pub struct AdvancedTensorAnalyzer;

impl AdvancedTensorAnalyzer {
    /// Detect gradient explosion patterns
    pub fn detect_gradient_explosion(gradients: &[ArrayD<f32>], threshold: f32) -> GradientExplosionAnalysis {
        let mut exploding_layers = Vec::new();
        let mut max_gradient_norm = 0.0f32;
        let mut gradient_norms = Vec::new();

        for (layer_idx, gradient) in gradients.iter().enumerate() {
            let l2_norm = Self::compute_l2_norm(gradient);
            gradient_norms.push(l2_norm);
            
            if l2_norm > max_gradient_norm {
                max_gradient_norm = l2_norm;
            }
            
            if l2_norm > threshold {
                exploding_layers.push(ExplodingLayer {
                    layer_index: layer_idx,
                    gradient_norm: l2_norm,
                    severity: Self::classify_explosion_severity(l2_norm, &gradient_norms),
                    recommended_action: Self::recommend_explosion_mitigation(l2_norm),
                });
            }
        }

        let mean_norm = gradient_norms.iter().sum::<f32>() / gradient_norms.len() as f32;
        let std_norm = {
            let variance: f32 = gradient_norms.iter()
                .map(|&x| (x - mean_norm).powi(2))
                .sum::<f32>() / gradient_norms.len() as f32;
            variance.sqrt()
        };

        let explosion_ratio = exploding_layers.len() as f32 / gradients.len() as f32;
        
        GradientExplosionAnalysis {
            has_explosion: !exploding_layers.is_empty(),
            exploding_layers,
            max_gradient_norm,
            mean_gradient_norm: mean_norm,
            std_gradient_norm: std_norm,
            explosion_ratio,
            recommended_clip_value: max_gradient_norm * 0.5,
        }
    }

    /// Analyze model weight distribution patterns
    pub fn analyze_weight_distribution(weights: &[ArrayD<f32>]) -> Result<WeightDistributionAnalysis> {
        let mut layer_analyses = Vec::new();
        let mut all_weights = Vec::new();
        let mut overall_stats = WeightStatistics::default();

        for (layer_idx, weight) in weights.iter().enumerate() {
            let values: Vec<f32> = weight.iter().cloned().collect();
            all_weights.extend_from_slice(&values);

            let stats = Self::compute_advanced_weight_stats(weight)?;
            let health = Self::assess_weight_health(&stats);
            
            let layer_analysis = LayerWeightAnalysis {
                layer_index: layer_idx,
                statistics: stats.clone(),
                health_score: health.score,
                issues: health.issues,
                recommendations: health.recommendations,
            };
            
            overall_stats.accumulate(&stats);
            layer_analyses.push(layer_analysis);
        }

        // Overall analysis
        let overall_mean = all_weights.iter().sum::<f32>() / all_weights.len() as f32;
        let overall_std = {
            let variance = all_weights.iter()
                .map(|&x| (x - overall_mean).powi(2))
                .sum::<f32>() / all_weights.len() as f32;
            variance.sqrt()
        };

        overall_stats.finalize(weights.len());
        
        Ok(WeightDistributionAnalysis {
            layer_analyses,
            overall_statistics: overall_stats.clone(),
            distribution_health: Self::assess_overall_distribution_health(&overall_stats),
            outlier_detection: Self::detect_weight_outliers(weights)?,
        })
    }

    /// Compare model states for debugging
    pub fn compare_model_states(
        state_a: &ModelDebugState,
        state_b: &ModelDebugState,
    ) -> ModelStateComparison {
        let weight_diff = Self::compute_weight_differences(&state_a.weights, &state_b.weights);
        let gradient_diff = Self::compute_gradient_differences(&state_a.gradients, &state_b.gradients);
        
        let significant_changes = weight_diff.iter()
            .enumerate()
            .filter(|(_, &diff)| diff > 0.1)
            .map(|(idx, &diff)| LayerChange {
                layer_index: idx,
                change_type: ChangeType::WeightUpdate,
                magnitude: diff,
                description: format!("Weight change: {:.3}", diff),
            })
            .collect();

        let overall_change_magnitude = weight_diff.iter().sum::<f32>() / weight_diff.len() as f32;
        
        ModelStateComparison {
            weight_differences: weight_diff,
            gradient_differences: gradient_diff,
            significant_changes,
            overall_change_magnitude,
            regression_detected: Self::detect_regression(&state_a.metrics, &state_b.metrics),
        }
    }

    fn compute_l2_norm(tensor: &ArrayD<f32>) -> f32 {
        tensor.iter().map(|&x| x * x).sum::<f32>().sqrt()
    }


    fn assess_distribution_health(weights: &[f32]) -> DistributionHealth {
        let mean = weights.iter().sum::<f32>() / weights.len() as f32;
        let std_dev = {
            let variance = weights.iter()
                .map(|&x| (x - mean).powi(2))
                .sum::<f32>() / weights.len() as f32;
            variance.sqrt()
        };

        let dead_ratio = weights.iter().filter(|&&x| x.abs() < 1e-8).count() as f32 / weights.len() as f32;
        let extreme_ratio = weights.iter().filter(|&&x| x.abs() > 3.0).count() as f32 / weights.len() as f32;

        let score = if dead_ratio > 0.5 || extreme_ratio > 0.1 {
            20.0
        } else if dead_ratio > 0.2 || extreme_ratio > 0.05 {
            40.0
        } else if std_dev > 0.1 && std_dev < 2.0 && dead_ratio < 0.1 {
            80.0
        } else {
            100.0
        };
        
        let status = match score {
            s if s >= 90.0 => DistributionHealthStatus::Excellent,
            s if s >= 70.0 => DistributionHealthStatus::Good,
            s if s >= 50.0 => DistributionHealthStatus::Fair,
            s if s >= 30.0 => DistributionHealthStatus::Poor,
            _ => DistributionHealthStatus::Critical,
        };
        
        DistributionHealth { score, status }
    }

    fn compute_gradient_differences(grads_a: &[ArrayD<f32>], grads_b: &[ArrayD<f32>]) -> Vec<f32> {
        grads_a.iter()
            .zip(grads_b.iter())
            .map(|(a, b)| {
                let diff: f32 = a.iter().zip(b.iter())
                    .map(|(&x, &y)| (x - y).abs())
                    .sum();
                diff / a.len() as f32
            })
            .collect()
    }

    fn detect_regression(metrics_a: &ModelMetrics, metrics_b: &ModelMetrics) -> bool {
        metrics_b.loss > metrics_a.loss * 1.1 || 
        metrics_b.accuracy < metrics_a.accuracy * 0.95
    }
}

/// Model debug state for comparison
#[derive(Debug, Clone)]
pub struct ModelDebugState {
    pub weights: Vec<ArrayD<f32>>,
    pub gradients: Vec<ArrayD<f32>>,
    pub metrics: ModelMetrics,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

/// Model metrics for tracking
#[derive(Debug, Clone)]
pub struct ModelMetrics {
    pub loss: f32,
    pub accuracy: f32,
    pub learning_rate: f32,
    pub epoch: u32,
}

/// Gradient explosion analysis results
#[derive(Debug, Serialize, Deserialize)]
pub struct GradientExplosionAnalysis {
    pub has_explosion: bool,
    pub exploding_layers: Vec<ExplodingLayer>,
    pub max_gradient_norm: f32,
    pub mean_gradient_norm: f32,
    pub std_gradient_norm: f32,
    pub explosion_ratio: f32,
    pub recommended_clip_value: f32,
}

impl AdvancedTensorAnalyzer {
    /// Perform advanced gradient explosion detection with sophisticated algorithms
    pub fn detect_gradient_explosion_advanced(
        gradients: &[ArrayD<f32>],
        threshold_multiplier: f32
    ) -> Result<GradientExplosionAnalysis> {
        let mut gradient_norms = Vec::new();
        let mut exploding_layers = Vec::new();
        
        // Calculate gradient norms for each layer
        for (layer_idx, grad) in gradients.iter().enumerate() {
            let norm = Self::compute_gradient_norm(grad);
            gradient_norms.push(norm);
            
            // Detect exploding gradients using adaptive thresholding
            if Self::is_gradient_exploding(norm, &gradient_norms, threshold_multiplier) {
                exploding_layers.push(ExplodingLayer {
                    layer_index: layer_idx,
                    gradient_norm: norm,
                    severity: Self::classify_explosion_severity(norm, &gradient_norms),
                    recommended_action: Self::recommend_explosion_mitigation(norm),
                });
            }
        }
        
        let max_norm = gradient_norms.iter().copied().fold(0.0, f32::max);
        let mean_norm = gradient_norms.iter().sum::<f32>() / gradient_norms.len() as f32;
        let variance: f32 = gradient_norms.iter()
            .map(|&x| (x - mean_norm).powi(2))
            .sum::<f32>() / gradient_norms.len() as f32;
        let std_norm = variance.sqrt();
        
        // Calculate explosion ratio using statistical analysis
        let explosion_ratio = if mean_norm > 0.0 {
            max_norm / mean_norm
        } else {
            0.0
        };
        
        // Intelligent gradient clipping recommendation
        let recommended_clip_value = Self::compute_optimal_clip_value(&gradient_norms);
        
        Ok(GradientExplosionAnalysis {
            has_explosion: !exploding_layers.is_empty(),
            exploding_layers,
            max_gradient_norm: max_norm,
            mean_gradient_norm: mean_norm,
            std_gradient_norm: std_norm,
            explosion_ratio,
            recommended_clip_value,
        })
    }
    
    /// Analyze weight distribution with advanced statistical methods
    pub fn analyze_weight_distribution_advanced(
        weights: &[ArrayD<f32>]
    ) -> Result<WeightDistributionAnalysis> {
        let mut layer_analyses = Vec::new();
        let mut overall_stats = WeightStatistics::default();
        
        for (layer_idx, weight) in weights.iter().enumerate() {
            let stats = Self::compute_advanced_weight_stats(weight)?;
            let health = Self::assess_weight_health(&stats);
            
            layer_analyses.push(LayerWeightAnalysis {
                layer_index: layer_idx,
                statistics: stats.clone(),
                health_score: health.score,
                issues: health.issues,
                recommendations: health.recommendations,
            });
            
            overall_stats.accumulate(&stats);
        }
        
        overall_stats.finalize(weights.len());
        
        Ok(WeightDistributionAnalysis {
            layer_analyses,
            overall_statistics: overall_stats.clone(),
            distribution_health: Self::assess_overall_distribution_health(&overall_stats),
            outlier_detection: Self::detect_weight_outliers(weights)?,
        })
    }
    
    /// Compare model states with advanced regression detection
    pub fn compare_model_states_advanced(
        state_a: &ModelDebugState,
        state_b: &ModelDebugState
    ) -> Result<AdvancedModelComparison> {
        // Weight comparison with statistical significance testing
        let weight_differences = Self::compute_weight_differences(&state_a.weights, &state_b.weights);
        let weight_drift = Self::calculate_weight_drift(&weight_differences);
        
        // Gradient comparison with flow analysis
        let gradient_differences = Self::compute_gradient_differences(&state_a.gradients, &state_b.gradients);
        let gradient_coherence = Self::analyze_gradient_coherence(&gradient_differences);
        
        // Performance regression analysis
        let performance_change = Self::analyze_performance_change(&state_a.metrics, &state_b.metrics);
        let regression_probability = Self::calculate_regression_probability(&performance_change);
        
        // Advanced change magnitude assessment
        let change_magnitude = Self::assess_change_magnitude(&weight_drift, &gradient_coherence);
        
        Ok(AdvancedModelComparison {
            weight_drift_analysis: weight_drift.clone(),
            gradient_coherence_analysis: gradient_coherence,
            performance_change_analysis: performance_change.clone(),
            regression_probability,
            change_magnitude,
            recommendations: Self::generate_comparison_recommendations(
                &weight_drift, &performance_change, regression_probability
            ),
        })
    }
    
    // Helper methods for advanced analysis
    fn compute_gradient_norm(gradient: &ArrayD<f32>) -> f32 {
        gradient.iter().map(|&x| x * x).sum::<f32>().sqrt()
    }
    
    fn is_gradient_exploding(norm: f32, all_norms: &[f32], threshold_multiplier: f32) -> bool {
        if all_norms.is_empty() {
            return false;
        }
        
        let mean = all_norms.iter().sum::<f32>() / all_norms.len() as f32;
        let variance: f32 = all_norms.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / all_norms.len() as f32;
        let std_dev = variance.sqrt();
        
        // Use statistical threshold: mean + threshold_multiplier * std_dev
        norm > mean + threshold_multiplier * std_dev && norm > 1.0
    }
    
    fn classify_explosion_severity(norm: f32, all_norms: &[f32]) -> ExplosionSeverity {
        let mean = all_norms.iter().sum::<f32>() / all_norms.len() as f32;
        let ratio = if mean > 0.0 { norm / mean } else { 0.0 };
        
        match ratio {
            r if r > 10.0 => ExplosionSeverity::Critical,
            r if r > 5.0 => ExplosionSeverity::High,
            r if r > 2.0 => ExplosionSeverity::Medium,
            _ => ExplosionSeverity::Low,
        }
    }
    
    fn recommend_explosion_mitigation(norm: f32) -> String {
        match norm {
            n if n > 10.0 => "Apply aggressive gradient clipping (0.1-0.5) and reduce learning rate by 50%".to_string(),
            n if n > 5.0 => "Apply moderate gradient clipping (0.5-1.0) and reduce learning rate by 25%".to_string(),
            n if n > 2.0 => "Apply light gradient clipping (1.0-2.0) and monitor closely".to_string(),
            _ => "Monitor gradient norms for trends".to_string(),
        }
    }
    
    fn compute_optimal_clip_value(gradient_norms: &[f32]) -> f32 {
        if gradient_norms.is_empty() {
            return 1.0;
        }
        
        let mut sorted_norms = gradient_norms.to_vec();
        sorted_norms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        
        // Use 95th percentile as clipping value for robustness
        let percentile_95_idx = (sorted_norms.len() as f32 * 0.95) as usize;
        sorted_norms.get(percentile_95_idx).copied().unwrap_or(1.0)
    }
    
    fn compute_advanced_weight_stats(weights: &ArrayD<f32>) -> Result<WeightStatistics> {
        let values: Vec<f32> = weights.iter().cloned().collect();
        
        if values.is_empty() {
            return Ok(WeightStatistics::default());
        }
        
        let n = values.len() as f64;
        let sum: f64 = values.iter().map(|&x| x as f64).sum();
        let mean = sum / n;
        
        let variance: f64 = values.iter()
            .map(|&x| (x as f64 - mean).powi(2))
            .sum::<f64>() / n;
        let std_dev = variance.sqrt();
        
        // Advanced statistics
        let skewness = Self::compute_skewness(&values, mean, std_dev);
        let kurtosis = Self::compute_kurtosis(&values, mean, std_dev);
        let entropy = Self::compute_entropy(&values);
        
        Ok(WeightStatistics {
            mean: mean as f32,
            std_dev: std_dev as f32,
            skewness,
            kurtosis,
            entropy,
            min: values.iter().copied().fold(f32::INFINITY, f32::min),
            max: values.iter().copied().fold(f32::NEG_INFINITY, f32::max),
            zero_fraction: values.iter().filter(|&&x| x.abs() < 1e-8).count() as f32 / values.len() as f32,
        })
    }
    
    fn compute_skewness(values: &[f32], mean: f64, std_dev: f64) -> f32 {
        if std_dev == 0.0 {
            return 0.0;
        }
        
        let n = values.len() as f64;
        let skew: f64 = values.iter()
            .map(|&x| ((x as f64 - mean) / std_dev).powi(3))
            .sum::<f64>() / n;
        
        skew as f32
    }
    
    fn compute_kurtosis(values: &[f32], mean: f64, std_dev: f64) -> f32 {
        if std_dev == 0.0 {
            return 0.0;
        }
        
        let n = values.len() as f64;
        let kurt: f64 = values.iter()
            .map(|&x| ((x as f64 - mean) / std_dev).powi(4))
            .sum::<f64>() / n - 3.0; // Excess kurtosis
        
        kurt as f32
    }
    
    fn compute_entropy(values: &[f32]) -> f32 {
        // Simplified entropy calculation using binning
        let mut bins = vec![0; 50]; // Use 50 bins
        let min_val = values.iter().copied().fold(f32::INFINITY, f32::min);
        let max_val = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        
        if max_val <= min_val {
            return 0.0;
        }
        
        let bin_width = (max_val - min_val) / 50.0;
        
        for &value in values {
            let bin_idx = ((value - min_val) / bin_width).floor() as usize;
            let bin_idx = bin_idx.min(49); // Ensure we don't exceed bounds
            bins[bin_idx] += 1;
        }
        
        let n = values.len() as f32;
        let entropy: f32 = bins.iter()
            .filter(|&&count| count > 0)
            .map(|&count| {
                let p = count as f32 / n;
                -p * p.log2()
            })
            .sum();
        
        entropy
    }
    
    fn assess_weight_health(stats: &WeightStatistics) -> WeightHealth {
        let mut issues = Vec::new();
        let mut recommendations = Vec::new();
        let mut score: f32 = 100.0;
        
        // Check for common weight issues
        if stats.zero_fraction > 0.5 {
            issues.push("High sparsity detected".to_string());
            recommendations.push("Consider reducing regularization or adjusting initialization".to_string());
            score -= 20.0;
        }
        
        if stats.std_dev < 0.01 {
            issues.push("Low weight variance - potential underfitting".to_string());
            recommendations.push("Increase model capacity or reduce regularization".to_string());
            score -= 15.0;
        }
        
        if stats.std_dev > 1.0 {
            issues.push("High weight variance - potential instability".to_string());
            recommendations.push("Add weight regularization or reduce learning rate".to_string());
            score -= 15.0;
        }
        
        if stats.skewness.abs() > 2.0 {
            issues.push("Highly skewed weight distribution".to_string());
            recommendations.push("Check for gradient flow issues or adjust initialization".to_string());
            score -= 10.0;
        }
        
        if stats.kurtosis > 5.0 {
            issues.push("Heavy-tailed weight distribution".to_string());
            recommendations.push("Monitor for outliers and consider gradient clipping".to_string());
            score -= 10.0;
        }
        
        WeightHealth {
            score: score.max(0.0),
            issues,
            recommendations,
        }
    }
    
    fn assess_overall_distribution_health(stats: &WeightStatistics) -> DistributionHealth {
        let score = 100.0
            - (stats.zero_fraction * 30.0) // Penalize high sparsity
            - (stats.skewness.abs() * 10.0) // Penalize skewness
            - ((stats.kurtosis - 3.0).abs() * 5.0); // Penalize non-normal kurtosis
        
        let status = match score {
            s if s >= 80.0 => DistributionHealthStatus::Excellent,
            s if s >= 60.0 => DistributionHealthStatus::Good,
            s if s >= 40.0 => DistributionHealthStatus::Fair,
            s if s >= 20.0 => DistributionHealthStatus::Poor,
            _ => DistributionHealthStatus::Critical,
        };
        
        DistributionHealth {
            score: score.max(0.0),
            status,
        }
    }
    
    fn detect_weight_outliers(weights: &[ArrayD<f32>]) -> Result<Vec<WeightOutlier>> {
        let mut outliers = Vec::new();
        
        for (layer_idx, weight) in weights.iter().enumerate() {
            let values: Vec<f32> = weight.iter().cloned().collect();
            let mean = values.iter().sum::<f32>() / values.len() as f32;
            let variance = values.iter()
                .map(|&x| (x - mean).powi(2))
                .sum::<f32>() / values.len() as f32;
            let std_dev = variance.sqrt();
            
            // Detect outliers using 3-sigma rule
            let threshold = 3.0 * std_dev;
            
            for (idx, &value) in values.iter().enumerate() {
                if (value - mean).abs() > threshold {
                    outliers.push(WeightOutlier {
                        layer_index: layer_idx,
                        weight_index: idx,
                        value,
                        z_score: (value - mean) / std_dev,
                        severity: if (value - mean).abs() > 4.0 * std_dev {
                            OutlierSeverity::High
                        } else {
                            OutlierSeverity::Medium
                        },
                    });
                }
            }
        }
        
        Ok(outliers)
    }
    
    fn compute_weight_differences(weights_a: &[ArrayD<f32>], weights_b: &[ArrayD<f32>]) -> Vec<f32> {
        weights_a.iter()
            .zip(weights_b.iter())
            .map(|(a, b)| {
                let diff: f32 = a.iter().zip(b.iter())
                    .map(|(&x, &y)| (x - y).abs())
                    .sum();
                diff / a.len() as f32
            })
            .collect()
    }
    
    fn calculate_weight_drift(differences: &[f32]) -> WeightDriftAnalysis {
        let mean_drift = differences.iter().sum::<f32>() / differences.len() as f32;
        let max_drift = differences.iter().copied().fold(0.0, f32::max);
        
        let drift_severity = match mean_drift {
            d if d > 0.1 => DriftSeverity::High,
            d if d > 0.05 => DriftSeverity::Medium,
            d if d > 0.01 => DriftSeverity::Low,
            _ => DriftSeverity::Minimal,
        };
        
        WeightDriftAnalysis {
            mean_drift,
            max_drift,
            severity: drift_severity,
            affected_layers: differences.iter()
                .enumerate()
                .filter(|(_, &diff)| diff > mean_drift * 2.0)
                .map(|(idx, _)| idx)
                .collect(),
        }
    }
    
    fn analyze_gradient_coherence(differences: &[f32]) -> GradientCoherenceAnalysis {
        let coherence_score = 1.0 - (differences.iter().sum::<f32>() / differences.len() as f32);
        
        GradientCoherenceAnalysis {
            coherence_score,
            inconsistent_layers: differences.iter()
                .enumerate()
                .filter(|(_, &diff)| diff > 0.1)
                .map(|(idx, _)| idx)
                .collect(),
        }
    }
    
    fn analyze_performance_change(metrics_a: &ModelMetrics, metrics_b: &ModelMetrics) -> PerformanceChangeAnalysis {
        let loss_change = ((metrics_b.loss - metrics_a.loss) / metrics_a.loss) * 100.0;
        let accuracy_change = ((metrics_b.accuracy - metrics_a.accuracy) / metrics_a.accuracy) * 100.0;
        
        PerformanceChangeAnalysis {
            loss_change_percent: loss_change,
            accuracy_change_percent: accuracy_change,
            is_improvement: loss_change < 0.0 && accuracy_change > 0.0,
            is_regression: loss_change > 5.0 || accuracy_change < -2.0,
        }
    }
    
    fn calculate_regression_probability(performance_change: &PerformanceChangeAnalysis) -> f32 {
        let mut probability: f32 = 0.0;
        
        if performance_change.loss_change_percent > 10.0 {
            probability += 0.4;
        } else if performance_change.loss_change_percent > 5.0 {
            probability += 0.2;
        }
        
        if performance_change.accuracy_change_percent < -5.0 {
            probability += 0.4;
        } else if performance_change.accuracy_change_percent < -2.0 {
            probability += 0.2;
        }
        
        probability.min(1.0)
    }
    
    fn assess_change_magnitude(
        weight_drift: &WeightDriftAnalysis, 
        gradient_coherence: &GradientCoherenceAnalysis
    ) -> ChangeMagnitude {
        let weight_score = match weight_drift.severity {
            DriftSeverity::High => 3,
            DriftSeverity::Medium => 2,
            DriftSeverity::Low => 1,
            DriftSeverity::Minimal => 0,
        };
        
        let coherence_score = if gradient_coherence.coherence_score < 0.7 { 2 } else { 0 };
        
        match weight_score + coherence_score {
            5.. => ChangeMagnitude::Major,
            3..=4 => ChangeMagnitude::Moderate,
            1..=2 => ChangeMagnitude::Minor,
            _ => ChangeMagnitude::Negligible,
        }
    }
    
    fn generate_comparison_recommendations(
        weight_drift: &WeightDriftAnalysis,
        performance_change: &PerformanceChangeAnalysis,
        regression_probability: f32
    ) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        if regression_probability > 0.5 {
            recommendations.push("High regression probability detected - consider reverting changes".to_string());
        }
        
        match weight_drift.severity {
            DriftSeverity::High => {
                recommendations.push("Significant weight drift detected - investigate learning rate and optimization settings".to_string());
            },
            DriftSeverity::Medium => {
                recommendations.push("Moderate weight changes observed - monitor training stability".to_string());
            },
            _ => {}
        }
        
        if performance_change.loss_change_percent > 10.0 {
            recommendations.push("Large loss increase - check for overfitting or data distribution changes".to_string());
        }
        
        if performance_change.accuracy_change_percent < -5.0 {
            recommendations.push("Significant accuracy drop - validate model architecture and training data".to_string());
        }
        
        recommendations
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ExplodingLayer {
    pub layer_index: usize,
    pub gradient_norm: f32,
    pub severity: ExplosionSeverity,
    pub recommended_action: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ExplosionSeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// Weight distribution analysis  
#[derive(Debug, Serialize, Deserialize)]
pub struct WeightDistributionAnalysis {
    pub layer_analyses: Vec<LayerWeightAnalysis>,
    pub overall_statistics: WeightStatistics,
    pub distribution_health: DistributionHealth,
    pub outlier_detection: Vec<WeightOutlier>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerWeightAnalysis {
    pub layer_index: usize,
    pub statistics: WeightStatistics,
    pub health_score: f32,
    pub issues: Vec<String>,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WeightStatistics {
    pub mean: f32,
    pub std_dev: f32,
    pub skewness: f32,
    pub kurtosis: f32,
    pub entropy: f32,
    pub min: f32,
    pub max: f32,
    pub zero_fraction: f32,
}

impl WeightStatistics {
    pub fn accumulate(&mut self, other: &WeightStatistics) {
        // Simple accumulation for overall statistics
        self.mean += other.mean;
        self.std_dev += other.std_dev;
        self.skewness += other.skewness;
        self.kurtosis += other.kurtosis;
        self.entropy += other.entropy;
        self.min = self.min.min(other.min);
        self.max = self.max.max(other.max);
        self.zero_fraction += other.zero_fraction;
    }
    
    pub fn finalize(&mut self, count: usize) {
        if count > 0 {
            let count_f32 = count as f32;
            self.mean /= count_f32;
            self.std_dev /= count_f32;
            self.skewness /= count_f32;
            self.kurtosis /= count_f32;
            self.entropy /= count_f32;
            self.zero_fraction /= count_f32;
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WeightHealth {
    pub score: f32,
    pub issues: Vec<String>,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DistributionHealth {
    pub score: f32,
    pub status: DistributionHealthStatus,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum DistributionHealthStatus {
    Excellent,
    Good,
    Fair,
    Poor,
    Critical,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WeightOutlier {
    pub layer_index: usize,
    pub weight_index: usize,
    pub value: f32,
    pub z_score: f32,
    pub severity: OutlierSeverity,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum OutlierSeverity {
    Medium,
    High,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AdvancedModelComparison {
    pub weight_drift_analysis: WeightDriftAnalysis,
    pub gradient_coherence_analysis: GradientCoherenceAnalysis,
    pub performance_change_analysis: PerformanceChangeAnalysis,
    pub regression_probability: f32,
    pub change_magnitude: ChangeMagnitude,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WeightDriftAnalysis {
    pub mean_drift: f32,
    pub max_drift: f32,
    pub severity: DriftSeverity,
    pub affected_layers: Vec<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DriftSeverity {
    Minimal,
    Low,
    Medium,
    High,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GradientCoherenceAnalysis {
    pub coherence_score: f32,
    pub inconsistent_layers: Vec<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceChangeAnalysis {
    pub loss_change_percent: f32,
    pub accuracy_change_percent: f32,
    pub is_improvement: bool,
    pub is_regression: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ChangeMagnitude {
    Negligible,
    Minor,
    Moderate,
    Major,
}

/// ML-specific metrics analyzer for learning dynamics and attention analysis
pub struct MLMetricsAnalyzer;

impl MLMetricsAnalyzer {
    /// Analyze learning dynamics and convergence patterns
    pub fn analyze_learning_dynamics(training_history: &[TrainingStep]) -> Result<LearningDynamicsAnalysis> {
        if training_history.is_empty() {
            return Ok(LearningDynamicsAnalysis::default());
        }

        let losses: Vec<f32> = training_history.iter().map(|step| step.loss).collect();
        let accuracies: Vec<f32> = training_history.iter().map(|step| step.accuracy).collect();
        
        let loss_trend = Self::compute_trend(&losses);
        let accuracy_trend = Self::compute_trend(&accuracies);
        
        // Convergence analysis
        let convergence_probability = Self::calculate_convergence_probability(&losses, &accuracies);
        
        // Overfitting detection
        let overfitting_risk = Self::detect_overfitting_risk(&losses, &accuracies);
        
        // Plateau detection
        let plateau_detected = Self::detect_plateau(&losses);
        
        Ok(LearningDynamicsAnalysis {
            loss_trend,
            accuracy_trend,
            convergence_probability,
            overfitting_risk,
            plateau_detected,
            learning_rate_recommendations: Self::generate_lr_recommendations(&losses),
        })
    }
    
    /// Analyze attention patterns in transformer models
    pub fn analyze_attention_patterns(
        attention_weights: &[ArrayD<f32>], // [batch, heads, seq_len, seq_len]
    ) -> Result<AttentionAnalysis> {
        let mut head_analyses = Vec::new();
        let num_heads = attention_weights.len();
        
        for (head_idx, attention) in attention_weights.iter().enumerate() {
            let head_analysis = Self::analyze_single_attention_head(attention)?;
            head_analyses.push(AttentionHeadAnalysis {
                head_index: head_idx,
                specialization_type: Self::classify_head_specialization(&head_analysis),
                attention_entropy: head_analysis.entropy,
                pattern_strength: head_analysis.pattern_strength,
                locality_score: head_analysis.locality_score,
            });
        }
        
        let attention_health = Self::assess_attention_health(&head_analyses);
        
        let redundancy_score = Self::calculate_head_redundancy(&head_analyses);
        let optimization_suggestions = Self::generate_attention_optimizations(&head_analyses);
        
        Ok(AttentionAnalysis {
            head_analyses,
            attention_health,
            redundancy_score,
            optimization_suggestions,
        })
    }
    
    /// Analyze model efficiency across multiple dimensions
    pub fn analyze_model_efficiency(
        model_stats: &ModelStats,
        performance_metrics: &PerformanceMetrics,
    ) -> Result<ModelEfficiencyAnalysis> {
        let parameter_efficiency = Self::calculate_parameter_efficiency(
            model_stats.total_parameters,
            performance_metrics.accuracy,
        );
        
        let computational_efficiency = Self::calculate_computational_efficiency(
            model_stats.flops,
            performance_metrics.accuracy,
            performance_metrics.inference_time,
        );
        
        let memory_efficiency = Self::calculate_memory_efficiency(
            model_stats.memory_usage,
            performance_metrics.accuracy,
        );
        
        let bottlenecks = Self::identify_efficiency_bottlenecks(
            parameter_efficiency,
            computational_efficiency,
            memory_efficiency,
        );
        
        let optimization_recommendations = Self::generate_efficiency_recommendations(&bottlenecks);
        
        Ok(ModelEfficiencyAnalysis {
            parameter_efficiency,
            computational_efficiency,
            memory_efficiency,
            overall_efficiency_score: (parameter_efficiency + computational_efficiency + memory_efficiency) / 3.0,
            bottlenecks,
            optimization_recommendations,
        })
    }
    
    // Helper methods for learning dynamics analysis
    fn compute_trend(values: &[f32]) -> TrendDirection {
        if values.len() < 2 {
            return TrendDirection::Stable;
        }
        
        let start = values[0];
        let end = values[values.len() - 1];
        let change = (end - start) / start;
        
        match change {
            c if c > 0.05 => TrendDirection::Increasing,
            c if c < -0.05 => TrendDirection::Decreasing,
            _ => TrendDirection::Stable,
        }
    }
    
    fn calculate_convergence_probability(losses: &[f32], accuracies: &[f32]) -> f32 {
        let loss_variance = Self::calculate_variance(losses);
        let accuracy_variance = Self::calculate_variance(accuracies);
        
        // Lower variance indicates higher convergence probability
        let loss_convergence = (1.0 - loss_variance.min(1.0)).max(0.0);
        let accuracy_convergence = (1.0 - accuracy_variance.min(1.0)).max(0.0);
        
        (loss_convergence + accuracy_convergence) / 2.0
    }
    
    fn detect_overfitting_risk(losses: &[f32], accuracies: &[f32]) -> OverfittingRisk {
        // Simplified overfitting detection based on trends
        let loss_trend = Self::compute_trend(losses);
        let accuracy_trend = Self::compute_trend(accuracies);
        
        match (loss_trend, accuracy_trend) {
            (TrendDirection::Increasing, TrendDirection::Decreasing) => OverfittingRisk::High,
            (TrendDirection::Increasing, TrendDirection::Stable) => OverfittingRisk::Medium,
            (TrendDirection::Stable, TrendDirection::Decreasing) => OverfittingRisk::Medium,
            _ => OverfittingRisk::Low,
        }
    }
    
    fn detect_plateau(losses: &[f32]) -> bool {
        if losses.len() < 10 {
            return false;
        }
        
        let recent_losses = &losses[losses.len() - 10..];
        let variance = Self::calculate_variance(recent_losses);
        
        variance < 0.001 // Very low variance indicates plateau
    }
    
    fn generate_lr_recommendations(losses: &[f32]) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        if losses.len() < 2 {
            return recommendations;
        }
        
        let trend = Self::compute_trend(losses);
        
        match trend {
            TrendDirection::Increasing => {
                recommendations.push("Loss is increasing - consider reducing learning rate".to_string());
                recommendations.push("Check for gradient explosion or data issues".to_string());
            },
            TrendDirection::Stable => {
                recommendations.push("Loss has plateaued - consider learning rate scheduling".to_string());
                recommendations.push("Try warmup restarts or cyclical learning rates".to_string());
            },
            TrendDirection::Decreasing => {
                recommendations.push("Good convergence - maintain current learning rate".to_string());
            },
        }
        
        recommendations
    }
    
    fn calculate_variance(values: &[f32]) -> f32 {
        if values.is_empty() {
            return 0.0;
        }
        
        let mean = values.iter().sum::<f32>() / values.len() as f32;
        let variance = values.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / values.len() as f32;
        
        variance
    }
    
    // Helper methods for attention analysis
    fn analyze_single_attention_head(attention: &ArrayD<f32>) -> Result<SingleHeadAnalysis> {
        let values: Vec<f32> = attention.iter().cloned().collect();
        
        let entropy = Self::calculate_attention_entropy(&values);
        let pattern_strength = Self::calculate_pattern_strength(&values);
        let locality_score = Self::calculate_locality_score(&values);
        
        Ok(SingleHeadAnalysis {
            entropy,
            pattern_strength,
            locality_score,
        })
    }
    
    fn calculate_attention_entropy(values: &[f32]) -> f32 {
        // Simplified entropy calculation
        let sum: f32 = values.iter().sum();
        if sum == 0.0 {
            return 0.0;
        }
        
        let entropy: f32 = values.iter()
            .filter(|&&x| x > 0.0)
            .map(|&x| {
                let p = x / sum;
                -p * p.log2()
            })
            .sum();
        
        entropy
    }
    
    fn calculate_pattern_strength(values: &[f32]) -> f32 {
        // Measure how structured the attention pattern is
        let max_val = values.iter().copied().fold(0.0, f32::max);
        let mean_val = values.iter().sum::<f32>() / values.len() as f32;
        
        if mean_val > 0.0 {
            max_val / mean_val
        } else {
            0.0
        }
    }
    
    fn calculate_locality_score(values: &[f32]) -> f32 {
        // Simplified locality score - measures how local the attention is
        // Higher score = more local attention
        let seq_len = (values.len() as f32).sqrt() as usize;
        if seq_len == 0 {
            return 0.0;
        }
        
        let mut local_sum = 0.0;
        let mut total_sum = 0.0;
        
        for i in 0..seq_len {
            for j in 0..seq_len {
                let idx = i * seq_len + j;
                if idx < values.len() {
                    let value = values[idx];
                    total_sum += value;
                    
                    // Consider attention as local if within distance of 3
                    if (i as i32 - j as i32).abs() <= 3 {
                        local_sum += value;
                    }
                }
            }
        }
        
        if total_sum > 0.0 {
            local_sum / total_sum
        } else {
            0.0
        }
    }
    
    fn classify_head_specialization(analysis: &SingleHeadAnalysis) -> HeadSpecializationType {
        match (analysis.entropy, analysis.locality_score, analysis.pattern_strength) {
            (e, l, _) if e < 2.0 && l > 0.7 => HeadSpecializationType::Local,
            (e, l, _) if e > 4.0 && l < 0.3 => HeadSpecializationType::Global,
            (_, _, p) if p > 5.0 => HeadSpecializationType::Structured,
            _ => HeadSpecializationType::General,
        }
    }
    
    fn assess_attention_health(head_analyses: &[AttentionHeadAnalysis]) -> AttentionHealth {
        let avg_entropy = head_analyses.iter()
            .map(|h| h.attention_entropy)
            .sum::<f32>() / head_analyses.len() as f32;
        
        let specialization_diversity = Self::calculate_specialization_diversity(head_analyses);
        
        let health_score = (avg_entropy / 5.0).min(1.0) * 50.0 + specialization_diversity * 50.0;
        
        AttentionHealth {
            overall_score: health_score,
            entropy_score: avg_entropy,
            diversity_score: specialization_diversity,
        }
    }
    
    fn calculate_specialization_diversity(head_analyses: &[AttentionHeadAnalysis]) -> f32 {
        use std::collections::HashSet;
        
        let unique_types: HashSet<_> = head_analyses.iter()
            .map(|h| std::mem::discriminant(&h.specialization_type))
            .collect();
        
        unique_types.len() as f32 / 4.0 // 4 possible specialization types
    }
    
    fn calculate_head_redundancy(head_analyses: &[AttentionHeadAnalysis]) -> f32 {
        // Simplified redundancy calculation
        let mut redundancy_score = 0.0;
        let num_heads = head_analyses.len();
        
        if num_heads < 2 {
            return 0.0;
        }
        
        for i in 0..num_heads {
            for j in (i + 1)..num_heads {
                let similarity = Self::calculate_head_similarity(&head_analyses[i], &head_analyses[j]);
                if similarity > 0.8 {
                    redundancy_score += 1.0;
                }
            }
        }
        
        redundancy_score / ((num_heads * (num_heads - 1)) / 2) as f32
    }
    
    fn calculate_head_similarity(head1: &AttentionHeadAnalysis, head2: &AttentionHeadAnalysis) -> f32 {
        let entropy_similarity = 1.0 - (head1.attention_entropy - head2.attention_entropy).abs() / 5.0;
        let locality_similarity = 1.0 - (head1.locality_score - head2.locality_score).abs();
        let pattern_similarity = 1.0 - (head1.pattern_strength - head2.pattern_strength).abs() / 10.0;
        
        (entropy_similarity + locality_similarity + pattern_similarity) / 3.0
    }
    
    fn generate_attention_optimizations(head_analyses: &[AttentionHeadAnalysis]) -> Vec<String> {
        let mut suggestions = Vec::new();
        
        let redundancy_score = Self::calculate_head_redundancy(head_analyses);
        
        if redundancy_score > 0.5 {
            suggestions.push("High head redundancy detected - consider head pruning".to_string());
        }
        
        let local_heads = head_analyses.iter()
            .filter(|h| matches!(h.specialization_type, HeadSpecializationType::Local))
            .count();
        
        if local_heads == 0 {
            suggestions.push("No local attention heads found - consider adding positional encodings".to_string());
        }
        
        suggestions
    }
    
    // Helper methods for efficiency analysis
    fn calculate_parameter_efficiency(total_params: usize, accuracy: f32) -> f32 {
        if total_params == 0 {
            return 0.0;
        }
        
        // Parameters per accuracy point (lower is better, so invert)
        let params_per_accuracy = total_params as f32 / accuracy;
        1.0 / (1.0 + params_per_accuracy / 1000000.0) // Normalize to 0-1 scale
    }
    
    fn calculate_computational_efficiency(flops: u64, accuracy: f32, inference_time: f32) -> f32 {
        if flops == 0 || inference_time == 0.0 {
            return 0.0;
        }
        
        let flops_per_accuracy = flops as f32 / accuracy;
        let time_per_accuracy = inference_time / accuracy;
        
        // Combine FLOPS and time efficiency
        let flop_efficiency = 1.0 / (1.0 + flops_per_accuracy / 1e9);
        let time_efficiency = 1.0 / (1.0 + time_per_accuracy);
        
        (flop_efficiency + time_efficiency) / 2.0
    }
    
    fn calculate_memory_efficiency(memory_usage: usize, accuracy: f32) -> f32 {
        if memory_usage == 0 {
            return 0.0;
        }
        
        let memory_per_accuracy = memory_usage as f32 / accuracy;
        1.0 / (1.0 + memory_per_accuracy / 1000000.0) // Normalize to 0-1 scale
    }
    
    fn identify_efficiency_bottlenecks(
        param_eff: f32,
        comp_eff: f32,
        mem_eff: f32,
    ) -> Vec<EfficiencyBottleneck> {
        let mut bottlenecks = Vec::new();
        
        if param_eff < 0.3 {
            bottlenecks.push(EfficiencyBottleneck::Parameters);
        }
        
        if comp_eff < 0.3 {
            bottlenecks.push(EfficiencyBottleneck::Computation);
        }
        
        if mem_eff < 0.3 {
            bottlenecks.push(EfficiencyBottleneck::Memory);
        }
        
        bottlenecks
    }
    
    fn generate_efficiency_recommendations(bottlenecks: &[EfficiencyBottleneck]) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        for bottleneck in bottlenecks {
            match bottleneck {
                EfficiencyBottleneck::Parameters => {
                    recommendations.push("Consider parameter pruning or knowledge distillation".to_string());
                    recommendations.push("Evaluate if model architecture can be simplified".to_string());
                },
                EfficiencyBottleneck::Computation => {
                    recommendations.push("Consider operation fusion or quantization".to_string());
                    recommendations.push("Optimize attention mechanisms or use linear attention".to_string());
                },
                EfficiencyBottleneck::Memory => {
                    recommendations.push("Consider gradient checkpointing or activation compression".to_string());
                    recommendations.push("Evaluate memory-efficient attention implementations".to_string());
                },
            }
        }
        
        recommendations
    }
}

// Additional data structures for ML metrics analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct TrainingStep {
    pub epoch: u32,
    pub step: u32,
    pub loss: f32,
    pub accuracy: f32,
    pub learning_rate: f32,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct LearningDynamicsAnalysis {
    pub loss_trend: TrendDirection,
    pub accuracy_trend: TrendDirection,
    pub convergence_probability: f32,
    pub overfitting_risk: OverfittingRisk,
    pub plateau_detected: bool,
    pub learning_rate_recommendations: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum TrendDirection {
    Increasing,
    Decreasing,
    Stable,
}

impl Default for TrendDirection {
    fn default() -> Self {
        TrendDirection::Stable
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub enum OverfittingRisk {
    Low,
    Medium,
    High,
}

impl Default for OverfittingRisk {
    fn default() -> Self {
        OverfittingRisk::Low
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AttentionAnalysis {
    pub head_analyses: Vec<AttentionHeadAnalysis>,
    pub attention_health: AttentionHealth,
    pub redundancy_score: f32,
    pub optimization_suggestions: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AttentionHeadAnalysis {
    pub head_index: usize,
    pub specialization_type: HeadSpecializationType,
    pub attention_entropy: f32,
    pub pattern_strength: f32,
    pub locality_score: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum HeadSpecializationType {
    Local,
    Global,
    Structured,
    General,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AttentionHealth {
    pub overall_score: f32,
    pub entropy_score: f32,
    pub diversity_score: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SingleHeadAnalysis {
    pub entropy: f32,
    pub pattern_strength: f32,
    pub locality_score: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModelStats {
    pub total_parameters: usize,
    pub flops: u64,
    pub memory_usage: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    pub accuracy: f32,
    pub inference_time: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModelEfficiencyAnalysis {
    pub parameter_efficiency: f32,
    pub computational_efficiency: f32,
    pub memory_efficiency: f32,
    pub overall_efficiency_score: f32,
    pub bottlenecks: Vec<EfficiencyBottleneck>,
    pub optimization_recommendations: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum EfficiencyBottleneck {
    Parameters,
    Computation,
    Memory,
}

/// Model state comparison
#[derive(Debug, Serialize, Deserialize)]
pub struct ModelStateComparison {
    pub weight_differences: Vec<f32>,
    pub gradient_differences: Vec<f32>,
    pub significant_changes: Vec<LayerChange>,
    pub overall_change_magnitude: f32,
    pub regression_detected: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerChange {
    pub layer_index: usize,
    pub change_type: ChangeType,
    pub magnitude: f32,
    pub description: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ChangeType {
    WeightUpdate,
    GradientChange,
    ActivationShift,
}

/// Advanced spectral analysis utilities for deep mathematical insights into model behavior
pub struct SpectralAnalyzer;

impl SpectralAnalyzer {
    /// Perform comprehensive spectral analysis of weight matrices
    pub fn analyze_weight_spectrum(weights: &[ArrayD<f32>]) -> Result<SpectralAnalysisResult> {
        let mut layer_results = Vec::new();
        
        for (layer_idx, weight_matrix) in weights.iter().enumerate() {
            let layer_analysis = Self::analyze_single_matrix_spectrum(weight_matrix)?;
            layer_results.push(LayerSpectralAnalysis {
                layer_index: layer_idx,
                eigenvalue_analysis: layer_analysis.eigenvalue_analysis,
                singular_value_analysis: layer_analysis.singular_value_analysis,
                condition_number: layer_analysis.condition_number,
                effective_rank: layer_analysis.effective_rank,
                spectral_norm: layer_analysis.spectral_norm,
                nuclear_norm: layer_analysis.nuclear_norm,
                stability_analysis: layer_analysis.stability_analysis,
            });
        }
        
        let recommendations = Self::generate_spectral_recommendations(&layer_results);
        let global_analysis = Self::compute_global_spectral_properties(&layer_results);
        
        Ok(SpectralAnalysisResult {
            layer_analyses: layer_results,
            global_properties: global_analysis,
            recommendations,
        })
    }
    
    /// Analyze eigenvalue spectrum of a single weight matrix
    fn analyze_single_matrix_spectrum(matrix: &ArrayD<f32>) -> Result<SingleMatrixSpectralAnalysis> {
        let shape = matrix.shape();
        if shape.len() != 2 {
            return Err(anyhow::anyhow!("Matrix must be 2D for spectral analysis"));
        }
        
        let (rows, cols) = (shape[0], shape[1]);
        let min_dim = rows.min(cols);
        
        // For computational efficiency, limit analysis to reasonable matrix sizes
        if min_dim > 1000 {
            return Self::analyze_large_matrix_approximate(matrix);
        }
        
        // Convert to square matrix for eigenvalue analysis (A^T A)
        let gram_matrix = Self::compute_gram_matrix(matrix)?;
        let eigenvalues = Self::compute_eigenvalues(&gram_matrix)?;
        
        // Singular value analysis
        let singular_values = Self::compute_singular_values(matrix)?;
        
        // Compute derived metrics
        let condition_number = Self::compute_condition_number(&singular_values);
        let effective_rank = Self::compute_effective_rank(&singular_values);
        let spectral_norm = singular_values.first().copied().unwrap_or(0.0);
        let nuclear_norm = singular_values.iter().sum::<f32>();
        
        // Stability analysis
        let stability_analysis = Self::analyze_numerical_stability(&eigenvalues, &singular_values);
        
        Ok(SingleMatrixSpectralAnalysis {
            eigenvalue_analysis: EigenvalueAnalysis {
                eigenvalues: eigenvalues.clone(),
                dominant_eigenvalue: eigenvalues.first().copied().unwrap_or(0.0),
                eigenvalue_spread: Self::compute_eigenvalue_spread(&eigenvalues),
                spectral_radius: eigenvalues.iter().map(|&x| x.abs()).fold(0.0, f32::max),
            },
            singular_value_analysis: SingularValueAnalysis {
                singular_values: singular_values.clone(),
                rank_estimate: Self::estimate_numerical_rank(&singular_values),
                decay_rate: Self::compute_decay_rate(&singular_values),
            },
            condition_number,
            effective_rank,
            spectral_norm,
            nuclear_norm,
            stability_analysis,
        })
    }
    
    /// Approximate analysis for large matrices using random sampling
    fn analyze_large_matrix_approximate(matrix: &ArrayD<f32>) -> Result<SingleMatrixSpectralAnalysis> {
        // For large matrices, use approximate methods
        let approx_singular_values = Self::approximate_singular_values(matrix, 50)?;
        let condition_number = Self::compute_condition_number(&approx_singular_values);
        let effective_rank = Self::compute_effective_rank(&approx_singular_values);
        
        Ok(SingleMatrixSpectralAnalysis {
            eigenvalue_analysis: EigenvalueAnalysis {
                eigenvalues: approx_singular_values.iter().map(|&x| x * x).collect(),
                dominant_eigenvalue: approx_singular_values.first().copied().unwrap_or(0.0).powi(2),
                eigenvalue_spread: Self::compute_eigenvalue_spread(&approx_singular_values.iter().map(|&x| x * x).collect::<Vec<_>>()),
                spectral_radius: approx_singular_values.first().copied().unwrap_or(0.0),
            },
            singular_value_analysis: SingularValueAnalysis {
                singular_values: approx_singular_values.clone(),
                rank_estimate: Self::estimate_numerical_rank(&approx_singular_values),
                decay_rate: Self::compute_decay_rate(&approx_singular_values),
            },
            condition_number,
            effective_rank,
            spectral_norm: approx_singular_values.first().copied().unwrap_or(0.0),
            nuclear_norm: approx_singular_values.iter().sum::<f32>(),
            stability_analysis: Self::analyze_numerical_stability(
                &approx_singular_values.iter().map(|&x| x * x).collect::<Vec<_>>(),
                &approx_singular_values
            ),
        })
    }
    
    /// Compute Gram matrix A^T A for eigenvalue analysis
    fn compute_gram_matrix(matrix: &ArrayD<f32>) -> Result<Vec<Vec<f32>>> {
        let shape = matrix.shape();
        let (rows, cols) = (shape[0], shape[1]);
        let mut gram = vec![vec![0.0; cols]; cols];
        
        for i in 0..cols {
            for j in 0..cols {
                let mut sum = 0.0;
                for k in 0..rows {
                    sum += matrix[[k, i]] * matrix[[k, j]];
                }
                gram[i][j] = sum;
            }
        }
        
        Ok(gram)
    }
    
    /// Simplified eigenvalue computation using power iteration for dominant eigenvalue
    fn compute_eigenvalues(matrix: &[Vec<f32>]) -> Result<Vec<f32>> {
        let n = matrix.len();
        if n == 0 {
            return Ok(Vec::new());
        }
        
        // For simplicity, compute only the dominant eigenvalue using power iteration
        let mut eigenvalues = Vec::new();
        let dominant = Self::power_iteration(matrix)?;
        eigenvalues.push(dominant);
        
        // Estimate other eigenvalues using Gershgorin circles (approximate)
        for i in 0..n.min(10) { // Limit to first 10 for efficiency
            let mut center = matrix[i][i];
            let mut radius = 0.0;
            for j in 0..n {
                if i != j {
                    radius += matrix[i][j].abs();
                }
            }
            
            // Add estimated eigenvalue from Gershgorin circle
            if eigenvalues.len() < 10 {
                eigenvalues.push(center + radius * 0.5); // Simplified estimate
            }
        }
        
        eigenvalues.sort_by(|a, b| b.abs().partial_cmp(&a.abs()).unwrap_or(std::cmp::Ordering::Equal));
        Ok(eigenvalues)
    }
    
    /// Power iteration to find dominant eigenvalue
    fn power_iteration(matrix: &[Vec<f32>]) -> Result<f32> {
        let n = matrix.len();
        if n == 0 {
            return Ok(0.0);
        }
        
        let mut x = vec![1.0; n];
        let max_iterations = 100;
        let tolerance = 1e-6;
        
        for _ in 0..max_iterations {
            let mut x_new = vec![0.0; n];
            
            // Matrix-vector multiplication
            for i in 0..n {
                for j in 0..n {
                    x_new[i] += matrix[i][j] * x[j];
                }
            }
            
            // Normalize
            let norm = x_new.iter().map(|&x| x * x).sum::<f32>().sqrt();
            if norm < tolerance {
                return Ok(0.0);
            }
            
            for val in &mut x_new {
                *val /= norm;
            }
            
            // Check convergence
            let diff: f32 = x.iter().zip(&x_new).map(|(&a, &b)| (a - b).abs()).sum();
            if diff < tolerance {
                break;
            }
            
            x = x_new;
        }
        
        // Compute Rayleigh quotient for eigenvalue estimate
        let mut numerator = 0.0;
        let mut denominator = 0.0;
        
        for i in 0..n {
            let mut ax_i = 0.0;
            for j in 0..n {
                ax_i += matrix[i][j] * x[j];
            }
            numerator += x[i] * ax_i;
            denominator += x[i] * x[i];
        }
        
        Ok(if denominator > tolerance { numerator / denominator } else { 0.0 })
    }
    
    /// Approximate singular values using random projection
    fn approximate_singular_values(matrix: &ArrayD<f32>, num_singular_values: usize) -> Result<Vec<f32>> {
        let shape = matrix.shape();
        let (rows, cols) = (shape[0], shape[1]);
        let min_dim = rows.min(cols);
        let k = num_singular_values.min(min_dim);
        
        // Simplified approximation - use norm of random projections
        let mut singular_values = Vec::new();
        
        for _ in 0..k {
            // Random vector
            let mut random_vec = vec![0.0; cols];
            for val in &mut random_vec {
                *val = rand::random::<f32>() - 0.5; // Simple random initialization
            }
            
            // Matrix-vector multiplication
            let mut result = vec![0.0; rows];
            for i in 0..rows {
                for j in 0..cols {
                    result[i] += matrix[[i, j]] * random_vec[j];
                }
            }
            
            // Compute norm
            let norm = result.iter().map(|&x| x * x).sum::<f32>().sqrt();
            singular_values.push(norm);
        }
        
        singular_values.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
        Ok(singular_values)
    }
    
    /// Compute singular values using simplified SVD approximation
    fn compute_singular_values(matrix: &ArrayD<f32>) -> Result<Vec<f32>> {
        // For efficiency, use approximate method for larger matrices
        let shape = matrix.shape();
        let (rows, cols) = (shape[0], shape[1]);
        
        if rows.min(cols) > 100 {
            return Self::approximate_singular_values(matrix, 50);
        }
        
        // For smaller matrices, compute more accurately
        let mut values = Vec::new();
        let min_dim = rows.min(cols);
        
        // Simple approximation using matrix norms
        for i in 0..min_dim.min(20) {
            let mut row_norm = 0.0;
            let mut col_norm = 0.0;
            
            if i < rows {
                for j in 0..cols {
                    row_norm += matrix[[i, j]].abs();
                }
            }
            
            if i < cols {
                for j in 0..rows {
                    col_norm += matrix[[j, i]].abs();
                }
            }
            
            values.push((row_norm * col_norm).sqrt());
        }
        
        values.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
        Ok(values)
    }
    
    /// Compute condition number
    fn compute_condition_number(singular_values: &[f32]) -> f32 {
        if singular_values.is_empty() {
            return f32::INFINITY;
        }
        
        let max_sv = singular_values.first().copied().unwrap_or(0.0);
        let min_sv = singular_values.last().copied().unwrap_or(0.0);
        
        if min_sv > 1e-10 {
            max_sv / min_sv
        } else {
            f32::INFINITY
        }
    }
    
    /// Compute effective rank based on singular value decay
    fn compute_effective_rank(singular_values: &[f32]) -> f32 {
        if singular_values.is_empty() {
            return 0.0;
        }
        
        let max_sv = singular_values.first().copied().unwrap_or(0.0);
        if max_sv == 0.0 {
            return 0.0;
        }
        
        let threshold = max_sv * 0.01; // 1% threshold
        singular_values.iter().take_while(|&&sv| sv > threshold).count() as f32
    }
    
    /// Compute eigenvalue spread
    fn compute_eigenvalue_spread(eigenvalues: &[f32]) -> f32 {
        if eigenvalues.len() < 2 {
            return 0.0;
        }
        
        let max_ev = eigenvalues.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        let min_ev = eigenvalues.iter().copied().fold(f32::INFINITY, f32::min);
        
        max_ev - min_ev
    }
    
    /// Estimate numerical rank
    fn estimate_numerical_rank(singular_values: &[f32]) -> usize {
        if singular_values.is_empty() {
            return 0;
        }
        
        let max_sv = singular_values.first().copied().unwrap_or(0.0);
        let threshold = max_sv * 1e-10; // Numerical tolerance
        
        singular_values.iter().take_while(|&&sv| sv > threshold).count()
    }
    
    /// Compute decay rate of singular values
    fn compute_decay_rate(singular_values: &[f32]) -> f32 {
        if singular_values.len() < 2 {
            return 0.0;
        }
        
        let mut decay_sum = 0.0;
        let mut count = 0;
        
        for i in 0..(singular_values.len() - 1) {
            if singular_values[i] > 0.0 && singular_values[i + 1] > 0.0 {
                decay_sum += (singular_values[i + 1] / singular_values[i]).ln().abs();
                count += 1;
            }
        }
        
        if count > 0 {
            decay_sum / count as f32
        } else {
            0.0
        }
    }
    
    /// Analyze numerical stability
    fn analyze_numerical_stability(eigenvalues: &[f32], singular_values: &[f32]) -> StabilityAnalysis {
        let condition_number = Self::compute_condition_number(singular_values);
        
        let stability_score = match condition_number {
            x if x.is_infinite() => 0.0,
            x if x > 1e12 => 0.1,
            x if x > 1e8 => 0.3,
            x if x > 1e4 => 0.6,
            _ => 1.0,
        };
        
        let issues = Self::identify_stability_issues(eigenvalues, singular_values, condition_number);
        let recommendations = Self::generate_stability_recommendations(&issues);
        
        StabilityAnalysis {
            stability_score,
            condition_number,
            issues,
            recommendations,
        }
    }
    
    /// Identify stability issues
    fn identify_stability_issues(
        eigenvalues: &[f32],
        singular_values: &[f32],
        condition_number: f32,
    ) -> Vec<StabilityIssue> {
        let mut issues = Vec::new();
        
        if condition_number > 1e8 {
            issues.push(StabilityIssue::IllConditioned);
        }
        
        if singular_values.iter().any(|&sv| sv < 1e-10) {
            issues.push(StabilityIssue::NearSingular);
        }
        
        if eigenvalues.iter().any(|&ev| ev.abs() > 1e6) {
            issues.push(StabilityIssue::LargeEigenvalues);
        }
        
        let effective_rank = Self::compute_effective_rank(singular_values);
        if effective_rank < singular_values.len() as f32 * 0.1 {
            issues.push(StabilityIssue::LowRank);
        }
        
        issues
    }
    
    /// Generate stability recommendations
    fn generate_stability_recommendations(issues: &[StabilityIssue]) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        for issue in issues {
            match issue {
                StabilityIssue::IllConditioned => {
                    recommendations.push("Matrix is ill-conditioned - consider regularization or preconditioning".to_string());
                },
                StabilityIssue::NearSingular => {
                    recommendations.push("Matrix is near-singular - check for redundant parameters or add regularization".to_string());
                },
                StabilityIssue::LargeEigenvalues => {
                    recommendations.push("Large eigenvalues detected - consider spectral normalization or gradient clipping".to_string());
                },
                StabilityIssue::LowRank => {
                    recommendations.push("Low effective rank detected - model may be under-parameterized".to_string());
                },
            }
        }
        
        recommendations
    }
    
    /// Compute global spectral properties across all layers
    fn compute_global_spectral_properties(layer_analyses: &[LayerSpectralAnalysis]) -> GlobalSpectralProperties {
        if layer_analyses.is_empty() {
            return GlobalSpectralProperties::default();
        }
        
        let avg_condition_number = layer_analyses.iter()
            .map(|a| a.condition_number)
            .filter(|&x| !x.is_infinite())
            .sum::<f32>() / layer_analyses.len() as f32;
        
        let avg_effective_rank = layer_analyses.iter()
            .map(|a| a.effective_rank)
            .sum::<f32>() / layer_analyses.len() as f32;
        
        let max_spectral_norm = layer_analyses.iter()
            .map(|a| a.spectral_norm)
            .fold(0.0, f32::max);
        
        let stability_distribution = Self::compute_stability_distribution(layer_analyses);
        
        GlobalSpectralProperties {
            average_condition_number: avg_condition_number,
            average_effective_rank: avg_effective_rank,
            max_spectral_norm,
            stability_distribution,
            global_stability_score: Self::compute_global_stability_score(layer_analyses),
        }
    }
    
    /// Compute stability distribution across layers
    fn compute_stability_distribution(layer_analyses: &[LayerSpectralAnalysis]) -> StabilityDistribution {
        let mut stable_count = 0;
        let mut unstable_count = 0;
        let mut critical_count = 0;
        
        for analysis in layer_analyses {
            match analysis.stability_analysis.stability_score {
                score if score > 0.8 => stable_count += 1,
                score if score > 0.3 => unstable_count += 1,
                _ => critical_count += 1,
            }
        }
        
        StabilityDistribution {
            stable_layers: stable_count,
            unstable_layers: unstable_count,
            critical_layers: critical_count,
        }
    }
    
    /// Compute global stability score
    fn compute_global_stability_score(layer_analyses: &[LayerSpectralAnalysis]) -> f32 {
        if layer_analyses.is_empty() {
            return 0.0;
        }
        
        layer_analyses.iter()
            .map(|a| a.stability_analysis.stability_score)
            .sum::<f32>() / layer_analyses.len() as f32
    }
    
    /// Generate spectral analysis recommendations
    fn generate_spectral_recommendations(layer_analyses: &[LayerSpectralAnalysis]) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        let avg_condition = layer_analyses.iter()
            .map(|a| a.condition_number)
            .filter(|&x| !x.is_infinite())
            .sum::<f32>() / layer_analyses.len() as f32;
        
        if avg_condition > 1e6 {
            recommendations.push("High average condition number - consider spectral normalization across layers".to_string());
        }
        
        let low_rank_layers = layer_analyses.iter()
            .filter(|a| a.effective_rank < 10.0)
            .count();
        
        if low_rank_layers > layer_analyses.len() / 2 {
            recommendations.push("Many layers have low effective rank - consider increasing model capacity".to_string());
        }
        
        let unstable_layers = layer_analyses.iter()
            .filter(|a| a.stability_analysis.stability_score < 0.5)
            .count();
        
        if unstable_layers > layer_analyses.len() / 4 {
            recommendations.push("Multiple layers show numerical instability - review initialization and normalization".to_string());
        }
        
        recommendations
    }
}

/// Information-theoretic analysis utilities for understanding information flow in neural networks
pub struct InformationTheoreticAnalyzer;

impl InformationTheoreticAnalyzer {
    /// Analyze information flow between layers
    pub fn analyze_information_flow(
        layer_activations: &[ArrayD<f32>],
        layer_weights: &[ArrayD<f32>],
    ) -> Result<InformationFlowAnalysis> {
        let mut layer_info_analyses = Vec::new();
        
        for (layer_idx, (activation, weight)) in layer_activations.iter().zip(layer_weights.iter()).enumerate() {
            let layer_analysis = Self::analyze_single_layer_information(activation, weight)?;
            layer_info_analyses.push(LayerInformationAnalysis {
                layer_index: layer_idx,
                entropy: layer_analysis.entropy,
                mutual_information: layer_analysis.mutual_information,
                information_bottleneck_score: layer_analysis.information_bottleneck_score,
                compression_ratio: layer_analysis.compression_ratio,
            });
        }
        
        let bottleneck_layers = Self::identify_information_bottlenecks(&layer_info_analyses);
        let flow_recommendations = Self::generate_information_flow_recommendations(&layer_info_analyses);
        let global_information_flow = Self::compute_global_information_properties(&layer_info_analyses);
        
        Ok(InformationFlowAnalysis {
            layer_analyses: layer_info_analyses,
            global_flow: global_information_flow,
            bottleneck_layers,
            flow_recommendations,
        })
    }
    
    /// Analyze information properties of a single layer
    fn analyze_single_layer_information(
        activation: &ArrayD<f32>,
        weight: &ArrayD<f32>,
    ) -> Result<SingleLayerInformation> {
        let entropy = Self::compute_differential_entropy(activation)?;
        let mutual_information = Self::estimate_mutual_information(activation, weight)?;
        let information_bottleneck_score = Self::compute_information_bottleneck_score(activation)?;
        let compression_ratio = Self::compute_compression_ratio(activation, weight)?;
        
        Ok(SingleLayerInformation {
            entropy,
            mutual_information,
            information_bottleneck_score,
            compression_ratio,
        })
    }
    
    /// Compute differential entropy of activations
    fn compute_differential_entropy(activations: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = activations.iter().cloned().collect();
        
        if values.is_empty() {
            return Ok(0.0);
        }
        
        // Use histogram-based entropy estimation
        let num_bins = (values.len() as f32).sqrt().ceil() as usize;
        let num_bins = num_bins.max(10).min(100); // Reasonable bounds
        
        let min_val = values.iter().copied().fold(f32::INFINITY, f32::min);
        let max_val = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        
        if max_val <= min_val {
            return Ok(0.0);
        }
        
        let bin_width = (max_val - min_val) / num_bins as f32;
        let mut histogram = vec![0; num_bins];
        
        for &value in &values {
            let bin_idx = ((value - min_val) / bin_width).floor() as usize;
            let bin_idx = bin_idx.min(num_bins - 1);
            histogram[bin_idx] += 1;
        }
        
        let n = values.len() as f32;
        let entropy: f32 = histogram.iter()
            .filter(|&&count| count > 0)
            .map(|&count| {
                let p = count as f32 / n;
                -p * p.log2()
            })
            .sum();
        
        // Differential entropy approximation
        Ok(entropy + (bin_width.abs() + 1e-10).log2())
    }
    
    /// Estimate mutual information between activations and weights
    fn estimate_mutual_information(
        activations: &ArrayD<f32>,
        weights: &ArrayD<f32>,
    ) -> Result<f32> {
        // Simplified mutual information estimation using correlation
        let act_values: Vec<f32> = activations.iter().cloned().collect();
        let weight_values: Vec<f32> = weights.iter().cloned().collect();
        
        if act_values.is_empty() || weight_values.is_empty() {
            return Ok(0.0);
        }
        
        // For efficiency, sample from both if they're different sizes
        let sample_size = act_values.len().min(weight_values.len()).min(10000);
        
        let mut act_sample = Vec::new();
        let mut weight_sample = Vec::new();
        
        for i in 0..sample_size {
            let act_idx = (i * act_values.len()) / sample_size;
            let weight_idx = (i * weight_values.len()) / sample_size;
            act_sample.push(act_values[act_idx]);
            weight_sample.push(weight_values[weight_idx]);
        }
        
        // Compute correlation-based mutual information estimate
        let correlation = Self::compute_correlation(&act_sample, &weight_sample);
        let mutual_info = -0.5 * (1.0 - correlation.abs()).ln().max(0.0);
        
        Ok(mutual_info)
    }
    
    /// Compute information bottleneck score
    fn compute_information_bottleneck_score(activations: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = activations.iter().cloned().collect();
        
        if values.is_empty() {
            return Ok(0.0);
        }
        
        // Information bottleneck score based on activation compression
        let entropy = Self::compute_differential_entropy(activations)?;
        let capacity = (values.len() as f32).log2();
        
        // Score represents how much information is preserved vs compressed
        let bottleneck_score = if capacity > 0.0 {
            (entropy / capacity).min(1.0)
        } else {
            0.0
        };
        
        Ok(bottleneck_score)
    }
    
    /// Compute compression ratio between input and output
    fn compute_compression_ratio(
        activations: &ArrayD<f32>,
        weights: &ArrayD<f32>,
    ) -> Result<f32> {
        let input_entropy = Self::compute_differential_entropy(weights)?;
        let output_entropy = Self::compute_differential_entropy(activations)?;
        
        if input_entropy > 0.0 {
            Ok(output_entropy / input_entropy)
        } else {
            Ok(1.0)
        }
    }
    
    /// Compute correlation between two vectors
    fn compute_correlation(x: &[f32], y: &[f32]) -> f32 {
        if x.len() != y.len() || x.is_empty() {
            return 0.0;
        }
        
        let n = x.len() as f32;
        let mean_x = x.iter().sum::<f32>() / n;
        let mean_y = y.iter().sum::<f32>() / n;
        
        let mut numerator = 0.0;
        let mut sum_sq_x = 0.0;
        let mut sum_sq_y = 0.0;
        
        for (&xi, &yi) in x.iter().zip(y.iter()) {
            let dx = xi - mean_x;
            let dy = yi - mean_y;
            numerator += dx * dy;
            sum_sq_x += dx * dx;
            sum_sq_y += dy * dy;
        }
        
        let denominator = (sum_sq_x * sum_sq_y).sqrt();
        
        if denominator > 1e-10 {
            numerator / denominator
        } else {
            0.0
        }
    }
    
    /// Compute global information flow properties
    fn compute_global_information_properties(
        layer_analyses: &[LayerInformationAnalysis],
    ) -> GlobalInformationFlow {
        if layer_analyses.is_empty() {
            return GlobalInformationFlow::default();
        }
        
        let total_entropy = layer_analyses.iter()
            .map(|a| a.entropy)
            .sum::<f32>();
        
        let avg_mutual_information = layer_analyses.iter()
            .map(|a| a.mutual_information)
            .sum::<f32>() / layer_analyses.len() as f32;
        
        let information_flow_efficiency = Self::compute_information_flow_efficiency(layer_analyses);
        
        GlobalInformationFlow {
            total_entropy,
            average_mutual_information: avg_mutual_information,
            flow_efficiency: information_flow_efficiency,
            entropy_trend: Self::compute_entropy_trend(layer_analyses),
        }
    }
    
    /// Compute information flow efficiency
    fn compute_information_flow_efficiency(layer_analyses: &[LayerInformationAnalysis]) -> f32 {
        if layer_analyses.len() < 2 {
            return 1.0;
        }
        
        let mut efficiency_sum = 0.0;
        
        for i in 0..(layer_analyses.len() - 1) {
            let current_entropy = layer_analyses[i].entropy;
            let next_entropy = layer_analyses[i + 1].entropy;
            
            if current_entropy > 0.0 {
                let efficiency = (next_entropy / current_entropy).min(1.0);
                efficiency_sum += efficiency;
            }
        }
        
        efficiency_sum / (layer_analyses.len() - 1) as f32
    }
    
    /// Compute entropy trend across layers
    fn compute_entropy_trend(layer_analyses: &[LayerInformationAnalysis]) -> EntropyTrend {
        if layer_analyses.len() < 2 {
            return EntropyTrend::Stable;
        }
        
        let first_entropy = layer_analyses.first().unwrap().entropy;
        let last_entropy = layer_analyses.last().unwrap().entropy;
        
        let change_ratio = if first_entropy > 0.0 {
            (last_entropy - first_entropy) / first_entropy
        } else {
            0.0
        };
        
        match change_ratio {
            x if x > 0.1 => EntropyTrend::Increasing,
            x if x < -0.1 => EntropyTrend::Decreasing,
            _ => EntropyTrend::Stable,
        }
    }
    
    /// Identify information bottleneck layers
    fn identify_information_bottlenecks(
        layer_analyses: &[LayerInformationAnalysis],
    ) -> Vec<usize> {
        layer_analyses.iter()
            .enumerate()
            .filter(|(_, analysis)| analysis.information_bottleneck_score < 0.3)
            .map(|(idx, _)| idx)
            .collect()
    }
    
    /// Generate information flow recommendations
    fn generate_information_flow_recommendations(
        layer_analyses: &[LayerInformationAnalysis],
    ) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        let bottleneck_count = Self::identify_information_bottlenecks(layer_analyses).len();
        
        if bottleneck_count > layer_analyses.len() / 3 {
            recommendations.push("Multiple information bottlenecks detected - consider increasing layer capacity".to_string());
        }
        
        let low_mi_layers = layer_analyses.iter()
            .filter(|a| a.mutual_information < 0.1)
            .count();
        
        if low_mi_layers > layer_analyses.len() / 2 {
            recommendations.push("Low mutual information across layers - review weight initialization and activations".to_string());
        }
        
        let avg_compression = layer_analyses.iter()
            .map(|a| a.compression_ratio)
            .sum::<f32>() / layer_analyses.len() as f32;
        
        if avg_compression > 2.0 {
            recommendations.push("High compression ratios detected - model may be over-compressing information".to_string());
        } else if avg_compression < 0.5 {
            recommendations.push("Low compression ratios detected - model may not be learning efficient representations".to_string());
        }
        
        recommendations
    }
}

// Data structures for spectral analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct SpectralAnalysisResult {
    pub layer_analyses: Vec<LayerSpectralAnalysis>,
    pub global_properties: GlobalSpectralProperties,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerSpectralAnalysis {
    pub layer_index: usize,
    pub eigenvalue_analysis: EigenvalueAnalysis,
    pub singular_value_analysis: SingularValueAnalysis,
    pub condition_number: f32,
    pub effective_rank: f32,
    pub spectral_norm: f32,
    pub nuclear_norm: f32,
    pub stability_analysis: StabilityAnalysis,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SingleMatrixSpectralAnalysis {
    pub eigenvalue_analysis: EigenvalueAnalysis,
    pub singular_value_analysis: SingularValueAnalysis,
    pub condition_number: f32,
    pub effective_rank: f32,
    pub spectral_norm: f32,
    pub nuclear_norm: f32,
    pub stability_analysis: StabilityAnalysis,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EigenvalueAnalysis {
    pub eigenvalues: Vec<f32>,
    pub dominant_eigenvalue: f32,
    pub eigenvalue_spread: f32,
    pub spectral_radius: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SingularValueAnalysis {
    pub singular_values: Vec<f32>,
    pub rank_estimate: usize,
    pub decay_rate: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StabilityAnalysis {
    pub stability_score: f32,
    pub condition_number: f32,
    pub issues: Vec<StabilityIssue>,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum StabilityIssue {
    IllConditioned,
    NearSingular,
    LargeEigenvalues,
    LowRank,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GlobalSpectralProperties {
    pub average_condition_number: f32,
    pub average_effective_rank: f32,
    pub max_spectral_norm: f32,
    pub stability_distribution: StabilityDistribution,
    pub global_stability_score: f32,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct StabilityDistribution {
    pub stable_layers: usize,
    pub unstable_layers: usize,
    pub critical_layers: usize,
}

// Data structures for information-theoretic analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct InformationFlowAnalysis {
    pub layer_analyses: Vec<LayerInformationAnalysis>,
    pub global_flow: GlobalInformationFlow,
    pub bottleneck_layers: Vec<usize>,
    pub flow_recommendations: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerInformationAnalysis {
    pub layer_index: usize,
    pub entropy: f32,
    pub mutual_information: f32,
    pub information_bottleneck_score: f32,
    pub compression_ratio: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SingleLayerInformation {
    pub entropy: f32,
    pub mutual_information: f32,
    pub information_bottleneck_score: f32,
    pub compression_ratio: f32,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GlobalInformationFlow {
    pub total_entropy: f32,
    pub average_mutual_information: f32,
    pub flow_efficiency: f32,
    pub entropy_trend: EntropyTrend,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum EntropyTrend {
    Increasing,
    Decreasing,
    Stable,
}

impl Default for EntropyTrend {
    fn default() -> Self {
        EntropyTrend::Stable
    }
}

/// Model complexity analysis utilities for comprehensive model assessment
pub struct ModelComplexityAnalyzer;

impl ModelComplexityAnalyzer {
    /// Comprehensive model complexity analysis
    pub fn analyze_model_complexity(
        weights: &[ArrayD<f32>],
        architecture_info: &ModelArchitectureInfo,
    ) -> Result<ModelComplexityAnalysis> {
        let mut layer_complexities = Vec::new();
        let mut total_parameters = 0;
        let mut total_flops = 0;
        
        for (layer_idx, weight) in weights.iter().enumerate() {
            let layer_complexity = Self::analyze_layer_complexity(weight, layer_idx)?;
            total_parameters += layer_complexity.parameter_count;
            total_flops += layer_complexity.computational_complexity;
            layer_complexities.push(layer_complexity);
        }
        
        let effective_model_rank = Self::compute_model_effective_rank(&layer_complexities);
        let model_capacity = Self::compute_model_capacity(&layer_complexities, total_parameters);
        let complexity_distribution = Self::analyze_complexity_distribution(&layer_complexities);
        let efficiency_metrics = Self::compute_efficiency_metrics(&layer_complexities, architecture_info);
        let bottleneck_analysis = Self::identify_complexity_bottlenecks(&layer_complexities);
        let optimization_recommendations = Self::generate_complexity_recommendations(&layer_complexities, &efficiency_metrics);
        
        Ok(ModelComplexityAnalysis {
            layer_complexities,
            total_parameters,
            total_flops,
            effective_model_rank,
            model_capacity,
            complexity_distribution,
            efficiency_metrics,
            bottleneck_analysis,
            optimization_recommendations,
        })
    }
    
    /// Analyze complexity of a single layer
    fn analyze_layer_complexity(weight: &ArrayD<f32>, layer_idx: usize) -> Result<LayerComplexityAnalysis> {
        let shape = weight.shape();
        let parameter_count = weight.len();
        
        // Compute effective rank and condition number
        let effective_rank = Self::compute_layer_effective_rank(weight)?;
        let condition_number = Self::compute_layer_condition_number(weight)?;
        
        // Computational complexity estimation
        let computational_complexity = Self::estimate_computational_complexity(shape, layer_idx);
        
        // Memory complexity
        let memory_complexity = Self::compute_memory_complexity(weight);
        
        // Complexity ratio analysis
        let complexity_ratio = Self::compute_complexity_ratio(effective_rank, parameter_count as f32);
        
        // Redundancy analysis
        let redundancy_score = Self::compute_redundancy_score(effective_rank, parameter_count);
        
        // Expressiveness analysis
        let expressiveness_score = Self::compute_expressiveness_score(weight)?;
        
        Ok(LayerComplexityAnalysis {
            layer_index: layer_idx,
            parameter_count,
            effective_rank,
            condition_number,
            computational_complexity,
            memory_complexity,
            complexity_ratio,
            redundancy_score,
            expressiveness_score,
            complexity_class: Self::classify_layer_complexity(effective_rank, parameter_count, condition_number),
        })
    }
    
    /// Compute effective rank for a single layer
    fn compute_layer_effective_rank(weight: &ArrayD<f32>) -> Result<f32> {
        let shape = weight.shape();
        if shape.len() != 2 {
            return Ok(shape.iter().product::<usize>() as f32); // For non-matrix tensors
        }
        
        // Simplified effective rank computation using Frobenius norm approximation
        let values: Vec<f32> = weight.iter().cloned().collect();
        let frobenius_norm = values.iter().map(|&x| x * x).sum::<f32>().sqrt();
        let spectral_norm = values.iter().map(|&x| x.abs()).fold(0.0, f32::max);
        
        if spectral_norm > 1e-10 {
            let ratio = frobenius_norm / spectral_norm;
            Ok(ratio.min(shape[0].min(shape[1]) as f32))
        } else {
            Ok(0.0)
        }
    }
    
    /// Compute condition number for a single layer
    fn compute_layer_condition_number(weight: &ArrayD<f32>) -> Result<f32> {
        let shape = weight.shape();
        if shape.len() != 2 {
            return Ok(1.0); // For non-matrix tensors, assume well-conditioned
        }
        
        // Simplified condition number estimation
        let values: Vec<f32> = weight.iter().cloned().collect();
        let max_val = values.iter().copied().fold(0.0, f32::max);
        let min_val = values.iter().filter(|&&x| x.abs() > 1e-10).map(|&x| x.abs()).fold(f32::INFINITY, f32::min);
        
        if min_val > 1e-10 {
            Ok(max_val / min_val)
        } else {
            Ok(f32::INFINITY)
        }
    }
    
    /// Estimate computational complexity (FLOPs) for the layer
    fn estimate_computational_complexity(shape: &[usize], layer_idx: usize) -> u64 {
        match shape.len() {
            2 => {
                // Dense layer: input_dim * output_dim
                (shape[0] as u64) * (shape[1] as u64) * 2 // Multiply + Add
            },
            4 => {
                // Convolutional layer: output_channels * input_channels * kernel_h * kernel_w * output_h * output_w
                // Simplified estimation
                let total_weights = shape.iter().product::<usize>() as u64;
                total_weights * 100 // Rough estimate for conv operations
            },
            _ => {
                // Other layer types
                shape.iter().product::<usize>() as u64
            }
        }
    }
    
    /// Compute memory complexity
    fn compute_memory_complexity(weight: &ArrayD<f32>) -> MemoryComplexity {
        let parameter_count = weight.len();
        let memory_bytes = parameter_count * std::mem::size_of::<f32>();
        
        MemoryComplexity {
            parameter_memory: memory_bytes,
            activation_memory: memory_bytes * 2, // Rough estimate for forward + backward
            gradient_memory: memory_bytes,
            total_memory: memory_bytes * 4, // Parameters + activations + gradients + buffers
        }
    }
    
    /// Compute complexity ratio (effective rank / total parameters)
    fn compute_complexity_ratio(effective_rank: f32, total_params: f32) -> f32 {
        if total_params > 0.0 {
            effective_rank / total_params
        } else {
            0.0
        }
    }
    
    /// Compute redundancy score
    fn compute_redundancy_score(effective_rank: f32, parameter_count: usize) -> f32 {
        let theoretical_rank = (parameter_count as f32).sqrt(); // Rough theoretical maximum
        if theoretical_rank > 0.0 {
            1.0 - (effective_rank / theoretical_rank).min(1.0)
        } else {
            0.0
        }
    }
    
    /// Compute expressiveness score
    fn compute_expressiveness_score(weight: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = weight.iter().cloned().collect();
        
        if values.is_empty() {
            return Ok(0.0);
        }
        
        // Compute entropy-based expressiveness
        let mut histogram = vec![0; 50];
        let min_val = values.iter().copied().fold(f32::INFINITY, f32::min);
        let max_val = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        
        if max_val <= min_val {
            return Ok(0.0);
        }
        
        let bin_width = (max_val - min_val) / 50.0;
        
        for &value in &values {
            let bin_idx = ((value - min_val) / bin_width).floor() as usize;
            let bin_idx = bin_idx.min(49);
            histogram[bin_idx] += 1;
        }
        
        let n = values.len() as f32;
        let entropy: f32 = histogram.iter()
            .filter(|&&count| count > 0)
            .map(|&count| {
                let p = count as f32 / n;
                -p * p.log2()
            })
            .sum();
        
        // Normalize entropy to 0-1 scale
        Ok((entropy / 50.0_f32.log2()).min(1.0))
    }
    
    /// Classify layer complexity
    fn classify_layer_complexity(effective_rank: f32, parameter_count: usize, condition_number: f32) -> ComplexityClass {
        let complexity_ratio = effective_rank / parameter_count as f32;
        
        match (complexity_ratio, condition_number) {
            (r, c) if r > 0.8 && c < 100.0 => ComplexityClass::HighExpressiveWellConditioned,
            (r, c) if r > 0.8 && c >= 100.0 => ComplexityClass::HighExpressiveIllConditioned,
            (r, c) if r > 0.4 && c < 100.0 => ComplexityClass::ModerateExpressiveWellConditioned,
            (r, c) if r > 0.4 && c >= 100.0 => ComplexityClass::ModerateExpressiveIllConditioned,
            (r, c) if r > 0.1 && c < 100.0 => ComplexityClass::LowExpressiveWellConditioned,
            (r, c) if r > 0.1 && c >= 100.0 => ComplexityClass::LowExpressiveIllConditioned,
            _ => ComplexityClass::Degenerate,
        }
    }
    
    /// Compute model-wide effective rank
    fn compute_model_effective_rank(layer_complexities: &[LayerComplexityAnalysis]) -> f32 {
        if layer_complexities.is_empty() {
            return 0.0;
        }
        
        // Weighted average of layer effective ranks
        let total_params: usize = layer_complexities.iter().map(|l| l.parameter_count).sum();
        
        if total_params == 0 {
            return 0.0;
        }
        
        layer_complexities.iter()
            .map(|l| l.effective_rank * (l.parameter_count as f32 / total_params as f32))
            .sum()
    }
    
    /// Compute model capacity
    fn compute_model_capacity(layer_complexities: &[LayerComplexityAnalysis], total_parameters: usize) -> ModelCapacity {
        let effective_parameters: f32 = layer_complexities.iter()
            .map(|l| l.effective_rank * l.parameter_count as f32 / l.parameter_count as f32)
            .sum();
        
        let utilization_ratio = if total_parameters > 0 {
            effective_parameters / total_parameters as f32
        } else {
            0.0
        };
        
        let avg_expressiveness = layer_complexities.iter()
            .map(|l| l.expressiveness_score)
            .sum::<f32>() / layer_complexities.len() as f32;
        
        ModelCapacity {
            theoretical_capacity: total_parameters as f32,
            effective_capacity: effective_parameters,
            utilization_ratio,
            expressiveness_score: avg_expressiveness,
        }
    }
    
    /// Analyze complexity distribution across layers
    fn analyze_complexity_distribution(layer_complexities: &[LayerComplexityAnalysis]) -> ComplexityDistribution {
        let total_layers = layer_complexities.len();
        
        let mut high_complexity = 0;
        let mut medium_complexity = 0;
        let mut low_complexity = 0;
        let mut degenerate = 0;
        
        for layer in layer_complexities {
            match layer.complexity_class {
                ComplexityClass::HighExpressiveWellConditioned | 
                ComplexityClass::HighExpressiveIllConditioned => high_complexity += 1,
                ComplexityClass::ModerateExpressiveWellConditioned | 
                ComplexityClass::ModerateExpressiveIllConditioned => medium_complexity += 1,
                ComplexityClass::LowExpressiveWellConditioned | 
                ComplexityClass::LowExpressiveIllConditioned => low_complexity += 1,
                ComplexityClass::Degenerate => degenerate += 1,
            }
        }
        
        ComplexityDistribution {
            high_complexity_layers: high_complexity,
            medium_complexity_layers: medium_complexity,
            low_complexity_layers: low_complexity,
            degenerate_layers: degenerate,
            distribution_balance: Self::compute_distribution_balance(high_complexity, medium_complexity, low_complexity, degenerate),
        }
    }
    
    /// Compute distribution balance score
    fn compute_distribution_balance(high: usize, medium: usize, low: usize, degenerate: usize) -> f32 {
        let total = high + medium + low + degenerate;
        if total == 0 {
            return 0.0;
        }
        
        // Ideal distribution is more high and medium complexity layers
        let ideal_score = (high as f32 * 1.0 + medium as f32 * 0.8 + low as f32 * 0.4 + degenerate as f32 * 0.0) / total as f32;
        ideal_score
    }
    
    /// Compute efficiency metrics
    fn compute_efficiency_metrics(
        layer_complexities: &[LayerComplexityAnalysis],
        architecture_info: &ModelArchitectureInfo,
    ) -> EfficiencyMetrics {
        let total_params: usize = layer_complexities.iter().map(|l| l.parameter_count).sum();
        let total_flops: u64 = layer_complexities.iter().map(|l| l.computational_complexity).sum();
        
        let parameter_efficiency = if architecture_info.target_accuracy > 0.0 {
            architecture_info.target_accuracy / (total_params as f32 / 1_000_000.0) // Accuracy per million parameters
        } else {
            0.0
        };
        
        let computational_efficiency = if architecture_info.target_accuracy > 0.0 {
            architecture_info.target_accuracy / (total_flops as f32 / 1_000_000_000.0) // Accuracy per billion FLOPs
        } else {
            0.0
        };
        
        let memory_efficiency = if architecture_info.memory_budget > 0 {
            let total_memory: usize = layer_complexities.iter()
                .map(|l| l.memory_complexity.total_memory)
                .sum();
            architecture_info.memory_budget as f32 / total_memory as f32
        } else {
            1.0
        };
        
        EfficiencyMetrics {
            parameter_efficiency,
            computational_efficiency,
            memory_efficiency,
            overall_efficiency: (parameter_efficiency + computational_efficiency + memory_efficiency) / 3.0,
        }
    }
    
    /// Identify complexity bottlenecks
    fn identify_complexity_bottlenecks(layer_complexities: &[LayerComplexityAnalysis]) -> BottleneckAnalysis {
        let mut parameter_bottlenecks = Vec::new();
        let mut computational_bottlenecks = Vec::new();
        let mut memory_bottlenecks = Vec::new();
        let mut conditioning_bottlenecks = Vec::new();
        
        // Find layers with disproportionate resource usage
        let total_params: usize = layer_complexities.iter().map(|l| l.parameter_count).sum();
        let total_flops: u64 = layer_complexities.iter().map(|l| l.computational_complexity).sum();
        let total_memory: usize = layer_complexities.iter()
            .map(|l| l.memory_complexity.total_memory)
            .sum();
        
        for layer in layer_complexities {
            // Parameter bottlenecks (layers using >20% of total parameters)
            if layer.parameter_count as f32 / total_params as f32 > 0.2 {
                parameter_bottlenecks.push(layer.layer_index);
            }
            
            // Computational bottlenecks (layers using >20% of total FLOPs)
            if layer.computational_complexity as f32 / total_flops as f32 > 0.2 {
                computational_bottlenecks.push(layer.layer_index);
            }
            
            // Memory bottlenecks (layers using >20% of total memory)
            if layer.memory_complexity.total_memory as f32 / total_memory as f32 > 0.2 {
                memory_bottlenecks.push(layer.layer_index);
            }
            
            // Conditioning bottlenecks (ill-conditioned layers)
            if layer.condition_number > 1000.0 {
                conditioning_bottlenecks.push(layer.layer_index);
            }
        }
        
        let bottleneck_severity = Self::compute_bottleneck_severity(&parameter_bottlenecks, &computational_bottlenecks, &memory_bottlenecks, &conditioning_bottlenecks);
        
        BottleneckAnalysis {
            parameter_bottlenecks,
            computational_bottlenecks,
            memory_bottlenecks,
            conditioning_bottlenecks,
            bottleneck_severity,
        }
    }
    
    /// Compute bottleneck severity
    fn compute_bottleneck_severity(
        param_bottlenecks: &[usize],
        comp_bottlenecks: &[usize],
        mem_bottlenecks: &[usize],
        cond_bottlenecks: &[usize],
    ) -> BottleneckSeverity {
        let total_bottlenecks = param_bottlenecks.len() + comp_bottlenecks.len() + mem_bottlenecks.len() + cond_bottlenecks.len();
        
        match total_bottlenecks {
            0 => BottleneckSeverity::None,
            1..=2 => BottleneckSeverity::Low,
            3..=5 => BottleneckSeverity::Medium,
            6..=10 => BottleneckSeverity::High,
            _ => BottleneckSeverity::Critical,
        }
    }
    
    /// Generate complexity optimization recommendations
    fn generate_complexity_recommendations(
        layer_complexities: &[LayerComplexityAnalysis],
        efficiency_metrics: &EfficiencyMetrics,
    ) -> Vec<ComplexityRecommendation> {
        let mut recommendations = Vec::new();
        
        // Check for low effective rank layers
        for layer in layer_complexities {
            if layer.redundancy_score > 0.7 {
                recommendations.push(ComplexityRecommendation {
                    layer_index: Some(layer.layer_index),
                    recommendation_type: ComplexityRecommendationType::ReduceRedundancy,
                    description: format!("Layer {} has high redundancy ({}). Consider rank reduction or pruning.", 
                                       layer.layer_index, layer.redundancy_score),
                    expected_impact: if layer.redundancy_score > 0.9 { 
                        RecommendationImpact::High 
                    } else { 
                        RecommendationImpact::Medium 
                    },
                    implementation_difficulty: RecommendationDifficulty::Medium,
                });
            }
            
            if layer.condition_number > 1000.0 {
                recommendations.push(ComplexityRecommendation {
                    layer_index: Some(layer.layer_index),
                    recommendation_type: ComplexityRecommendationType::ImproveConditioning,
                    description: format!("Layer {} is ill-conditioned (condition number: {}). Consider regularization or normalization.", 
                                       layer.layer_index, layer.condition_number),
                    expected_impact: RecommendationImpact::High,
                    implementation_difficulty: RecommendationDifficulty::Low,
                });
            }
            
            if layer.expressiveness_score < 0.3 {
                recommendations.push(ComplexityRecommendation {
                    layer_index: Some(layer.layer_index),
                    recommendation_type: ComplexityRecommendationType::IncreaseExpressiveness,
                    description: format!("Layer {} has low expressiveness ({}). Consider different initialization or activation functions.", 
                                       layer.layer_index, layer.expressiveness_score),
                    expected_impact: RecommendationImpact::Medium,
                    implementation_difficulty: RecommendationDifficulty::Low,
                });
            }
        }
        
        // Global recommendations
        if efficiency_metrics.parameter_efficiency < 0.5 {
            recommendations.push(ComplexityRecommendation {
                layer_index: None,
                recommendation_type: ComplexityRecommendationType::OverallOptimization,
                description: "Low parameter efficiency detected. Consider knowledge distillation or architectural optimization.".to_string(),
                expected_impact: RecommendationImpact::High,
                implementation_difficulty: RecommendationDifficulty::High,
            });
        }
        
        if efficiency_metrics.computational_efficiency < 0.5 {
            recommendations.push(ComplexityRecommendation {
                layer_index: None,
                recommendation_type: ComplexityRecommendationType::OverallOptimization,
                description: "Low computational efficiency detected. Consider operation fusion or quantization.".to_string(),
                expected_impact: RecommendationImpact::High,
                implementation_difficulty: RecommendationDifficulty::Medium,
            });
        }
        
        recommendations
    }
}

// Data structures for model complexity analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct ModelComplexityAnalysis {
    pub layer_complexities: Vec<LayerComplexityAnalysis>,
    pub total_parameters: usize,
    pub total_flops: u64,
    pub effective_model_rank: f32,
    pub model_capacity: ModelCapacity,
    pub complexity_distribution: ComplexityDistribution,
    pub efficiency_metrics: EfficiencyMetrics,
    pub bottleneck_analysis: BottleneckAnalysis,
    pub optimization_recommendations: Vec<ComplexityRecommendation>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerComplexityAnalysis {
    pub layer_index: usize,
    pub parameter_count: usize,
    pub effective_rank: f32,
    pub condition_number: f32,
    pub computational_complexity: u64,
    pub memory_complexity: MemoryComplexity,
    pub complexity_ratio: f32,
    pub redundancy_score: f32,
    pub expressiveness_score: f32,
    pub complexity_class: ComplexityClass,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModelArchitectureInfo {
    pub target_accuracy: f32,
    pub memory_budget: usize,
    pub latency_budget: f32,
    pub model_type: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MemoryComplexity {
    pub parameter_memory: usize,
    pub activation_memory: usize,
    pub gradient_memory: usize,
    pub total_memory: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ComplexityClass {
    HighExpressiveWellConditioned,
    HighExpressiveIllConditioned,
    ModerateExpressiveWellConditioned,
    ModerateExpressiveIllConditioned,
    LowExpressiveWellConditioned,
    LowExpressiveIllConditioned,
    Degenerate,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModelCapacity {
    pub theoretical_capacity: f32,
    pub effective_capacity: f32,
    pub utilization_ratio: f32,
    pub expressiveness_score: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ComplexityDistribution {
    pub high_complexity_layers: usize,
    pub medium_complexity_layers: usize,
    pub low_complexity_layers: usize,
    pub degenerate_layers: usize,
    pub distribution_balance: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EfficiencyMetrics {
    pub parameter_efficiency: f32,
    pub computational_efficiency: f32,
    pub memory_efficiency: f32,
    pub overall_efficiency: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct BottleneckAnalysis {
    pub parameter_bottlenecks: Vec<usize>,
    pub computational_bottlenecks: Vec<usize>,
    pub memory_bottlenecks: Vec<usize>,
    pub conditioning_bottlenecks: Vec<usize>,
    pub bottleneck_severity: BottleneckSeverity,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum BottleneckSeverity {
    None,
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ComplexityRecommendation {
    pub layer_index: Option<usize>,
    pub recommendation_type: ComplexityRecommendationType,
    pub description: String,
    pub expected_impact: RecommendationImpact,
    pub implementation_difficulty: RecommendationDifficulty,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ComplexityRecommendationType {
    ReduceRedundancy,
    ImproveConditioning,
    IncreaseExpressiveness,
    OptimizeMemory,
    OptimizeComputation,
    OverallOptimization,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RecommendationImpact {
    Low,
    Medium,
    High,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RecommendationDifficulty {
    Low,
    Medium,
    High,
}

/// Advanced gradient flow analysis utilities for sophisticated flow pattern detection
pub struct AdvancedGradientFlowAnalyzer;

impl AdvancedGradientFlowAnalyzer {
    /// Comprehensive gradient flow analysis with directional derivatives and flow patterns
    pub fn analyze_gradient_flow(
        gradients: &[ArrayD<f32>],
        model_structure: &ModelStructureInfo,
    ) -> Result<AdvancedGradientFlowAnalysis> {
        let mut layer_flow_analyses = Vec::new();
        
        for (layer_idx, gradient) in gradients.iter().enumerate() {
            let layer_analysis = Self::analyze_layer_gradient_flow(gradient, layer_idx)?;
            layer_flow_analyses.push(layer_analysis);
        }
        
        let directional_derivatives = Self::compute_directional_derivatives(&gradients)?;
        let flow_patterns = Self::analyze_flow_patterns(&gradients)?;
        let gradient_topology = Self::analyze_gradient_topology(&gradients)?;
        let flow_dynamics = Self::analyze_flow_dynamics(&gradients)?;
        let convergence_analysis = Self::analyze_flow_convergence(&layer_flow_analyses);
        
        // Compute recommendations before moving values
        let flow_recommendations = Self::generate_flow_recommendations(&layer_flow_analyses, &flow_patterns);
        
        Ok(AdvancedGradientFlowAnalysis {
            layer_analyses: layer_flow_analyses,
            directional_derivatives,
            flow_patterns,
            gradient_topology,
            flow_dynamics,
            convergence_analysis,
            flow_recommendations,
        })
    }
    
    /// Analyze gradient flow for a single layer
    fn analyze_layer_gradient_flow(gradient: &ArrayD<f32>, layer_idx: usize) -> Result<LayerGradientFlowAnalysis> {
        let gradient_magnitude = Self::compute_gradient_magnitude(gradient);
        let flow_direction = Self::compute_flow_direction(gradient)?;
        let flow_divergence = Self::compute_flow_divergence(gradient)?;
        let flow_curl = Self::compute_flow_curl(gradient)?;
        let flow_coherence = Self::compute_flow_coherence(gradient)?;
        let flow_stability = Self::compute_flow_stability(gradient)?;
        
        Ok(LayerGradientFlowAnalysis {
            layer_index: layer_idx,
            gradient_magnitude,
            flow_direction,
            flow_divergence,
            flow_curl,
            flow_coherence,
            flow_stability,
            flow_classification: Self::classify_flow_type(flow_divergence, flow_curl, flow_coherence),
        })
    }
    
    /// Compute gradient magnitude
    fn compute_gradient_magnitude(gradient: &ArrayD<f32>) -> f32 {
        gradient.iter().map(|&x| x * x).sum::<f32>().sqrt()
    }
    
    /// Compute flow direction (normalized gradient)
    fn compute_flow_direction(gradient: &ArrayD<f32>) -> Result<FlowDirection> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        if values.is_empty() {
            return Ok(FlowDirection::default());
        }
        
        let magnitude = values.iter().map(|&x| x * x).sum::<f32>().sqrt();
        
        if magnitude < 1e-10 {
            return Ok(FlowDirection::default());
        }
        
        // Compute principal direction using SVD approximation
        let dominant_direction = Self::compute_dominant_direction(&values)?;
        let direction_strength = magnitude / values.len() as f32;
        let direction_consistency = Self::compute_direction_consistency(&values, &dominant_direction);
        
        Ok(FlowDirection {
            dominant_direction,
            direction_strength,
            direction_consistency,
            magnitude,
        })
    }
    
    /// Compute dominant direction using simplified PCA
    fn compute_dominant_direction(values: &[f32]) -> Result<Vec<f32>> {
        if values.is_empty() {
            return Ok(Vec::new());
        }
        
        // For simplicity, use the normalized gradient as the dominant direction
        let magnitude = values.iter().map(|&x| x * x).sum::<f32>().sqrt();
        
        if magnitude < 1e-10 {
            return Ok(vec![0.0; values.len().min(3)]); // Return zero vector of max size 3
        }
        
        let normalized: Vec<f32> = values.iter()
            .take(3) // Limit to 3 dimensions for visualization
            .map(|&x| x / magnitude)
            .collect();
        
        Ok(normalized)
    }
    
    /// Compute direction consistency
    fn compute_direction_consistency(values: &[f32], dominant_direction: &[f32]) -> f32 {
        if values.is_empty() || dominant_direction.is_empty() {
            return 0.0;
        }
        
        let magnitude = values.iter().map(|&x| x * x).sum::<f32>().sqrt();
        if magnitude < 1e-10 {
            return 0.0;
        }
        
        // Compute dot product with dominant direction
        let dot_product: f32 = values.iter()
            .zip(dominant_direction.iter())
            .map(|(&v, &d)| v * d / magnitude)
            .sum();
        
        dot_product.abs()
    }
    
    /// Compute flow divergence (gradient of gradient magnitude)
    fn compute_flow_divergence(gradient: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        if values.len() < 2 {
            return Ok(0.0);
        }
        
        // Simplified divergence computation using finite differences
        let mut divergence = 0.0;
        let step_size = 1.0 / values.len() as f32;
        
        for i in 0..(values.len() - 1) {
            let gradient_diff = values[i + 1] - values[i];
            divergence += gradient_diff / step_size;
        }
        
        Ok(divergence / (values.len() - 1) as f32)
    }
    
    /// Compute flow curl (rotational component)
    fn compute_flow_curl(gradient: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        if values.len() < 3 {
            return Ok(0.0);
        }
        
        // Simplified 2D curl computation
        let mut curl = 0.0;
        let step_size = 1.0 / values.len() as f32;
        
        for i in 0..(values.len() - 2) {
            // Approximate curl using finite differences
            let dy_dx = (values[i + 1] - values[i]) / step_size;
            let dx_dy = (values[i + 2] - values[i + 1]) / step_size;
            curl += dx_dy - dy_dx;
        }
        
        Ok(curl / (values.len() - 2) as f32)
    }
    
    /// Compute flow coherence (uniformity of flow)
    fn compute_flow_coherence(gradient: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        if values.len() < 2 {
            return Ok(1.0);
        }
        
        let mean = values.iter().sum::<f32>() / values.len() as f32;
        let variance = values.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / values.len() as f32;
        
        let std_dev = variance.sqrt();
        let mean_abs = mean.abs();
        
        // Coherence as signal-to-noise ratio
        if std_dev > 1e-10 {
            Ok((mean_abs / std_dev).min(1.0))
        } else {
            Ok(1.0)
        }
    }
    
    /// Compute flow stability
    fn compute_flow_stability(gradient: &ArrayD<f32>) -> Result<FlowStability> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        if values.len() < 3 {
            return Ok(FlowStability::default());
        }
        
        // Compute local stability indicators
        let mut local_variations = Vec::new();
        for i in 1..(values.len() - 1) {
            let variation = (values[i + 1] - 2.0 * values[i] + values[i - 1]).abs();
            local_variations.push(variation);
        }
        
        let stability_score = if !local_variations.is_empty() {
            let max_variation = local_variations.iter().copied().fold(0.0, f32::max);
            let mean_variation = local_variations.iter().sum::<f32>() / local_variations.len() as f32;
            
            // Stability inversely related to variation
            1.0 / (1.0 + mean_variation)
        } else {
            1.0
        };
        
        let stability_classification = match stability_score {
            s if s > 0.8 => StabilityClass::Stable,
            s if s > 0.6 => StabilityClass::ModeratelyStable,
            s if s > 0.4 => StabilityClass::Unstable,
            _ => StabilityClass::HighlyUnstable,
        };
        
        Ok(FlowStability {
            stability_score,
            local_variations,
            stability_classification,
        })
    }
    
    /// Classify flow type based on flow characteristics
    fn classify_flow_type(divergence: f32, curl: f32, coherence: f32) -> FlowType {
        match (divergence.abs(), curl.abs(), coherence) {
            (d, c, coh) if d > 0.5 && c < 0.1 && coh > 0.7 => FlowType::Divergent,
            (d, c, coh) if d < 0.1 && c > 0.5 && coh > 0.7 => FlowType::Rotational,
            (d, c, coh) if d < 0.1 && c < 0.1 && coh > 0.8 => FlowType::Laminar,
            (d, c, coh) if coh < 0.3 => FlowType::Turbulent,
            _ => FlowType::Mixed,
        }
    }
    
    /// Compute directional derivatives
    fn compute_directional_derivatives(gradients: &[ArrayD<f32>]) -> Result<DirectionalDerivatives> {
        if gradients.is_empty() {
            return Ok(DirectionalDerivatives::default());
        }
        
        let mut layer_derivatives = Vec::new();
        
        for (i, gradient) in gradients.iter().enumerate() {
            let values: Vec<f32> = gradient.iter().cloned().collect();
            
            if values.len() < 2 {
                continue;
            }
            
            // Compute directional derivative in primary gradient direction
            let primary_derivative = Self::compute_primary_directional_derivative(&values)?;
            let secondary_derivative = Self::compute_secondary_directional_derivative(&values)?;
            let cross_derivative = Self::compute_cross_directional_derivative(&values)?;
            
            layer_derivatives.push(LayerDirectionalDerivatives {
                layer_index: i,
                primary_derivative,
                secondary_derivative,
                cross_derivative,
                derivative_magnitude: (primary_derivative.powi(2) + secondary_derivative.powi(2)).sqrt(),
            });
        }
        
        let flow_acceleration = Self::compute_flow_acceleration(&layer_derivatives);
        let flow_jerk = Self::compute_flow_jerk(&layer_derivatives);
        
        // Compute patterns before moving values
        let derivative_patterns = Self::analyze_derivative_patterns(&layer_derivatives);
        
        Ok(DirectionalDerivatives {
            layer_derivatives,
            flow_acceleration,
            flow_jerk,
            derivative_patterns,
        })
    }
    
    /// Compute primary directional derivative
    fn compute_primary_directional_derivative(values: &[f32]) -> Result<f32> {
        if values.len() < 2 {
            return Ok(0.0);
        }
        
        // First-order finite difference
        let mut derivatives = Vec::new();
        for i in 0..(values.len() - 1) {
            derivatives.push(values[i + 1] - values[i]);
        }
        
        // Return average derivative
        Ok(derivatives.iter().sum::<f32>() / derivatives.len() as f32)
    }
    
    /// Compute secondary directional derivative
    fn compute_secondary_directional_derivative(values: &[f32]) -> Result<f32> {
        if values.len() < 3 {
            return Ok(0.0);
        }
        
        // Second-order finite difference
        let mut second_derivatives = Vec::new();
        for i in 0..(values.len() - 2) {
            let second_deriv = values[i + 2] - 2.0 * values[i + 1] + values[i];
            second_derivatives.push(second_deriv);
        }
        
        Ok(second_derivatives.iter().sum::<f32>() / second_derivatives.len() as f32)
    }
    
    /// Compute cross directional derivative
    fn compute_cross_directional_derivative(values: &[f32]) -> Result<f32> {
        if values.len() < 4 {
            return Ok(0.0);
        }
        
        // Mixed partial derivative approximation
        let mut cross_derivatives = Vec::new();
        for i in 0..(values.len() - 3) {
            let cross_deriv = values[i + 3] - values[i + 2] - values[i + 1] + values[i];
            cross_derivatives.push(cross_deriv);
        }
        
        Ok(cross_derivatives.iter().sum::<f32>() / cross_derivatives.len() as f32)
    }
    
    /// Compute flow acceleration (rate of change of gradient flow)
    fn compute_flow_acceleration(layer_derivatives: &[LayerDirectionalDerivatives]) -> f32 {
        if layer_derivatives.len() < 2 {
            return 0.0;
        }
        
        let mut accelerations = Vec::new();
        for i in 0..(layer_derivatives.len() - 1) {
            let accel = layer_derivatives[i + 1].derivative_magnitude - layer_derivatives[i].derivative_magnitude;
            accelerations.push(accel);
        }
        
        accelerations.iter().sum::<f32>() / accelerations.len() as f32
    }
    
    /// Compute flow jerk (rate of change of acceleration)
    fn compute_flow_jerk(layer_derivatives: &[LayerDirectionalDerivatives]) -> f32 {
        if layer_derivatives.len() < 3 {
            return 0.0;
        }
        
        let mut jerks = Vec::new();
        for i in 0..(layer_derivatives.len() - 2) {
            let jerk = layer_derivatives[i + 2].derivative_magnitude 
                     - 2.0 * layer_derivatives[i + 1].derivative_magnitude 
                     + layer_derivatives[i].derivative_magnitude;
            jerks.push(jerk);
        }
        
        jerks.iter().sum::<f32>() / jerks.len() as f32
    }
    
    /// Analyze derivative patterns
    fn analyze_derivative_patterns(layer_derivatives: &[LayerDirectionalDerivatives]) -> DerivativePatterns {
        if layer_derivatives.is_empty() {
            return DerivativePatterns::default();
        }
        
        let primary_trend = Self::compute_derivative_trend(&layer_derivatives.iter().map(|d| d.primary_derivative).collect::<Vec<_>>());
        let secondary_trend = Self::compute_derivative_trend(&layer_derivatives.iter().map(|d| d.secondary_derivative).collect::<Vec<_>>());
        
        let oscillation_frequency = Self::compute_oscillation_frequency(layer_derivatives);
        let dominant_frequency = Self::compute_dominant_frequency(layer_derivatives);
        
        DerivativePatterns {
            primary_trend,
            secondary_trend,
            oscillation_frequency,
            dominant_frequency,
            pattern_stability: Self::compute_pattern_stability(layer_derivatives),
        }
    }
    
    /// Compute derivative trend
    fn compute_derivative_trend(derivatives: &[f32]) -> DerivativeTrend {
        if derivatives.len() < 2 {
            return DerivativeTrend::Stable;
        }
        
        let start = derivatives[0];
        let end = derivatives[derivatives.len() - 1];
        let change = (end - start) / start.abs().max(1e-10);
        
        match change {
            c if c > 0.1 => DerivativeTrend::Increasing,
            c if c < -0.1 => DerivativeTrend::Decreasing,
            _ => DerivativeTrend::Stable,
        }
    }
    
    /// Compute oscillation frequency
    fn compute_oscillation_frequency(layer_derivatives: &[LayerDirectionalDerivatives]) -> f32 {
        if layer_derivatives.len() < 3 {
            return 0.0;
        }
        
        let mut zero_crossings = 0;
        let derivatives: Vec<f32> = layer_derivatives.iter().map(|d| d.primary_derivative).collect();
        
        for i in 0..(derivatives.len() - 1) {
            if derivatives[i] * derivatives[i + 1] < 0.0 {
                zero_crossings += 1;
            }
        }
        
        // Frequency as zero crossings per layer
        zero_crossings as f32 / (derivatives.len() - 1) as f32
    }
    
    /// Compute dominant frequency
    fn compute_dominant_frequency(layer_derivatives: &[LayerDirectionalDerivatives]) -> f32 {
        // Simplified frequency analysis using peak counting
        if layer_derivatives.len() < 3 {
            return 0.0;
        }
        
        let magnitudes: Vec<f32> = layer_derivatives.iter().map(|d| d.derivative_magnitude).collect();
        let mut peaks = 0;
        
        for i in 1..(magnitudes.len() - 1) {
            if magnitudes[i] > magnitudes[i - 1] && magnitudes[i] > magnitudes[i + 1] {
                peaks += 1;
            }
        }
        
        peaks as f32 / (magnitudes.len() - 2) as f32
    }
    
    /// Compute pattern stability
    fn compute_pattern_stability(layer_derivatives: &[LayerDirectionalDerivatives]) -> f32 {
        if layer_derivatives.is_empty() {
            return 0.0;
        }
        
        let magnitudes: Vec<f32> = layer_derivatives.iter().map(|d| d.derivative_magnitude).collect();
        let mean = magnitudes.iter().sum::<f32>() / magnitudes.len() as f32;
        let variance = magnitudes.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / magnitudes.len() as f32;
        
        // Stability inversely related to variance
        1.0 / (1.0 + variance)
    }
    
    /// Analyze flow patterns
    fn analyze_flow_patterns(gradients: &[ArrayD<f32>]) -> Result<FlowPatterns> {
        let convergence_zones = Self::identify_convergence_zones(gradients)?;
        let divergence_zones = Self::identify_divergence_zones(gradients)?;
        let vortex_structures = Self::identify_vortex_structures(gradients)?;
        let flow_boundaries = Self::identify_flow_boundaries(gradients)?;
        
        Ok(FlowPatterns {
            convergence_zones,
            divergence_zones,
            vortex_structures,
            flow_boundaries,
            pattern_complexity: Self::compute_pattern_complexity(gradients)?,
        })
    }
    
    /// Identify convergence zones
    fn identify_convergence_zones(gradients: &[ArrayD<f32>]) -> Result<Vec<ConvergenceZone>> {
        let mut zones = Vec::new();
        
        for (i, gradient) in gradients.iter().enumerate() {
            let divergence = Self::compute_flow_divergence(gradient)?;
            
            if divergence < -0.1 { // Negative divergence indicates convergence
                zones.push(ConvergenceZone {
                    layer_index: i,
                    convergence_strength: -divergence,
                    zone_stability: Self::compute_zone_stability(gradient)?,
                });
            }
        }
        
        Ok(zones)
    }
    
    /// Identify divergence zones
    fn identify_divergence_zones(gradients: &[ArrayD<f32>]) -> Result<Vec<DivergenceZone>> {
        let mut zones = Vec::new();
        
        for (i, gradient) in gradients.iter().enumerate() {
            let divergence = Self::compute_flow_divergence(gradient)?;
            
            if divergence > 0.1 { // Positive divergence
                zones.push(DivergenceZone {
                    layer_index: i,
                    divergence_strength: divergence,
                    expansion_rate: Self::compute_expansion_rate(gradient)?,
                });
            }
        }
        
        Ok(zones)
    }
    
    /// Identify vortex structures
    fn identify_vortex_structures(gradients: &[ArrayD<f32>]) -> Result<Vec<VortexStructure>> {
        let mut vortices = Vec::new();
        
        for (i, gradient) in gradients.iter().enumerate() {
            let curl = Self::compute_flow_curl(gradient)?;
            
            if curl.abs() > 0.1 { // Significant rotational component
                vortices.push(VortexStructure {
                    layer_index: i,
                    vorticity_strength: curl.abs(),
                    rotation_direction: if curl > 0.0 { 
                        RotationDirection::Counterclockwise 
                    } else { 
                        RotationDirection::Clockwise 
                    },
                    core_stability: Self::compute_vortex_stability(gradient)?,
                });
            }
        }
        
        Ok(vortices)
    }
    
    /// Identify flow boundaries
    fn identify_flow_boundaries(gradients: &[ArrayD<f32>]) -> Result<Vec<FlowBoundary>> {
        let mut boundaries = Vec::new();
        
        for i in 0..(gradients.len() - 1) {
            let boundary_strength = Self::compute_boundary_strength(&gradients[i], &gradients[i + 1])?;
            
            if boundary_strength > 0.5 {
                boundaries.push(FlowBoundary {
                    between_layers: (i, i + 1),
                    boundary_strength,
                    boundary_type: Self::classify_boundary_type(&gradients[i], &gradients[i + 1])?,
                });
            }
        }
        
        Ok(boundaries)
    }
    
    /// Compute zone stability
    fn compute_zone_stability(gradient: &ArrayD<f32>) -> Result<f32> {
        let coherence = Self::compute_flow_coherence(gradient)?;
        let stability = Self::compute_flow_stability(gradient)?;
        Ok((coherence + stability.stability_score) / 2.0)
    }
    
    /// Compute expansion rate
    fn compute_expansion_rate(gradient: &ArrayD<f32>) -> Result<f32> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        if values.len() < 2 {
            return Ok(0.0);
        }
        
        // Rate of change of magnitude
        let mut rates = Vec::new();
        for i in 0..(values.len() - 1) {
            rates.push((values[i + 1].abs() - values[i].abs()).abs());
        }
        
        Ok(rates.iter().sum::<f32>() / rates.len() as f32)
    }
    
    /// Compute vortex stability
    fn compute_vortex_stability(gradient: &ArrayD<f32>) -> Result<f32> {
        let curl = Self::compute_flow_curl(gradient)?;
        let coherence = Self::compute_flow_coherence(gradient)?;
        
        // Vortex stability based on curl consistency and coherence
        Ok(coherence * (1.0 - (curl.abs() - 0.5).abs()).max(0.0))
    }
    
    /// Compute boundary strength between two layers
    fn compute_boundary_strength(grad1: &ArrayD<f32>, grad2: &ArrayD<f32>) -> Result<f32> {
        let values1: Vec<f32> = grad1.iter().cloned().collect();
        let values2: Vec<f32> = grad2.iter().cloned().collect();
        
        let min_len = values1.len().min(values2.len());
        
        if min_len == 0 {
            return Ok(0.0);
        }
        
        let mut differences = Vec::new();
        for i in 0..min_len {
            differences.push((values1[i] - values2[i]).abs());
        }
        
        let max_diff = differences.iter().copied().fold(0.0, f32::max);
        let mean_diff = differences.iter().sum::<f32>() / differences.len() as f32;
        
        // Normalized boundary strength
        Ok(mean_diff / (max_diff + 1e-10))
    }
    
    /// Classify boundary type
    fn classify_boundary_type(grad1: &ArrayD<f32>, grad2: &ArrayD<f32>) -> Result<BoundaryType> {
        let mag1 = Self::compute_gradient_magnitude(grad1);
        let mag2 = Self::compute_gradient_magnitude(grad2);
        
        let ratio = if mag1 > 1e-10 { mag2 / mag1 } else { 1.0 };
        
        Ok(match ratio {
            r if r > 2.0 => BoundaryType::Amplification,
            r if r < 0.5 => BoundaryType::Attenuation,
            _ => BoundaryType::Transition,
        })
    }
    
    /// Compute pattern complexity
    fn compute_pattern_complexity(gradients: &[ArrayD<f32>]) -> Result<f32> {
        if gradients.is_empty() {
            return Ok(0.0);
        }
        
        let mut complexity_measures = Vec::new();
        
        for gradient in gradients {
            let curl = Self::compute_flow_curl(gradient)?;
            let divergence = Self::compute_flow_divergence(gradient)?;
            let coherence = Self::compute_flow_coherence(gradient)?;
            
            // Complexity based on flow characteristics
            let local_complexity = curl.abs() + divergence.abs() + (1.0 - coherence);
            complexity_measures.push(local_complexity);
        }
        
        Ok(complexity_measures.iter().sum::<f32>() / complexity_measures.len() as f32)
    }
    
    /// Analyze gradient topology
    fn analyze_gradient_topology(gradients: &[ArrayD<f32>]) -> Result<GradientTopology> {
        let critical_points = Self::identify_critical_points(gradients)?;
        let saddle_points = Self::identify_saddle_points(gradients)?;
        let flow_separatrices = Self::identify_flow_separatrices(gradients)?;
        let topology_classification = Self::classify_topology(gradients)?;
        
        Ok(GradientTopology {
            critical_points,
            saddle_points,
            flow_separatrices,
            topology_classification,
            topological_invariants: Self::compute_topological_invariants(gradients)?,
        })
    }
    
    /// Identify critical points (where gradient is zero or near zero)
    fn identify_critical_points(gradients: &[ArrayD<f32>]) -> Result<Vec<CriticalPoint>> {
        let mut points = Vec::new();
        
        for (i, gradient) in gradients.iter().enumerate() {
            let magnitude = Self::compute_gradient_magnitude(gradient);
            
            if magnitude < 0.01 { // Near-zero gradient
                let point_type = Self::classify_critical_point(gradient)?;
                points.push(CriticalPoint {
                    layer_index: i,
                    point_type,
                    stability_index: Self::compute_critical_point_stability(gradient)?,
                });
            }
        }
        
        Ok(points)
    }
    
    /// Classify critical point type
    fn classify_critical_point(gradient: &ArrayD<f32>) -> Result<CriticalPointType> {
        let divergence = Self::compute_flow_divergence(gradient)?;
        let curl = Self::compute_flow_curl(gradient)?;
        
        Ok(match (divergence, curl) {
            (d, c) if d > 0.1 && c.abs() < 0.05 => CriticalPointType::Source,
            (d, c) if d < -0.1 && c.abs() < 0.05 => CriticalPointType::Sink,
            (d, c) if d.abs() < 0.05 && c.abs() > 0.1 => CriticalPointType::Vortex,
            _ => CriticalPointType::Saddle,
        })
    }
    
    /// Compute critical point stability
    fn compute_critical_point_stability(gradient: &ArrayD<f32>) -> Result<f32> {
        let stability = Self::compute_flow_stability(gradient)?;
        Ok(stability.stability_score)
    }
    
    /// Identify saddle points
    fn identify_saddle_points(gradients: &[ArrayD<f32>]) -> Result<Vec<SaddlePoint>> {
        let mut saddles = Vec::new();
        
        for (i, gradient) in gradients.iter().enumerate() {
            let point_type = Self::classify_critical_point(gradient)?;
            
            if matches!(point_type, CriticalPointType::Saddle) {
                saddles.push(SaddlePoint {
                    layer_index: i,
                    saddle_strength: Self::compute_saddle_strength(gradient)?,
                    manifold_dimensions: Self::estimate_manifold_dimensions(gradient)?,
                });
            }
        }
        
        Ok(saddles)
    }
    
    /// Compute saddle strength
    fn compute_saddle_strength(gradient: &ArrayD<f32>) -> Result<f32> {
        let divergence = Self::compute_flow_divergence(gradient)?;
        let curl = Self::compute_flow_curl(gradient)?;
        
        // Saddle strength based on mixed characteristics
        Ok((divergence.abs() + curl.abs()) / 2.0)
    }
    
    /// Estimate manifold dimensions
    fn estimate_manifold_dimensions(gradient: &ArrayD<f32>) -> Result<usize> {
        let values: Vec<f32> = gradient.iter().cloned().collect();
        
        // Simplified dimension estimation based on effective rank
        let effective_rank = values.len().min(10); // Cap at 10 for simplicity
        Ok(effective_rank)
    }
    
    /// Identify flow separatrices
    fn identify_flow_separatrices(gradients: &[ArrayD<f32>]) -> Result<Vec<FlowSeparatrix>> {
        let mut separatrices = Vec::new();
        
        for i in 0..(gradients.len() - 1) {
            let boundary_strength = Self::compute_boundary_strength(&gradients[i], &gradients[i + 1])?;
            
            if boundary_strength > 0.7 { // Strong flow separation
                separatrices.push(FlowSeparatrix {
                    between_layers: (i, i + 1),
                    separation_strength: boundary_strength,
                    separatrix_type: Self::classify_separatrix_type(&gradients[i], &gradients[i + 1])?,
                });
            }
        }
        
        Ok(separatrices)
    }
    
    /// Classify separatrix type
    fn classify_separatrix_type(grad1: &ArrayD<f32>, grad2: &ArrayD<f32>) -> Result<SeparatrixType> {
        let divergence1 = Self::compute_flow_divergence(grad1)?;
        let divergence2 = Self::compute_flow_divergence(grad2)?;
        
        Ok(match (divergence1, divergence2) {
            (d1, d2) if d1 * d2 < 0.0 => SeparatrixType::Heteroclinic,
            (d1, d2) if (d1 - d2).abs() > 0.5 => SeparatrixType::Shock,
            _ => SeparatrixType::Simple,
        })
    }
    
    /// Classify overall topology
    fn classify_topology(gradients: &[ArrayD<f32>]) -> Result<TopologyClass> {
        if gradients.is_empty() {
            return Ok(TopologyClass::Simple);
        }
        
        let critical_points = Self::identify_critical_points(gradients)?;
        let saddle_points = Self::identify_saddle_points(gradients)?;
        
        let complexity = critical_points.len() + saddle_points.len() * 2;
        
        Ok(match complexity {
            0..=2 => TopologyClass::Simple,
            3..=5 => TopologyClass::Moderate,
            6..=10 => TopologyClass::Complex,
            _ => TopologyClass::Chaotic,
        })
    }
    
    /// Compute topological invariants
    fn compute_topological_invariants(gradients: &[ArrayD<f32>]) -> Result<TopologicalInvariants> {
        let euler_characteristic = Self::compute_euler_characteristic(gradients)?;
        let genus = Self::estimate_genus(gradients)?;
        let betti_numbers = Self::compute_betti_numbers(gradients)?;
        
        Ok(TopologicalInvariants {
            euler_characteristic,
            genus,
            betti_numbers,
        })
    }
    
    /// Compute Euler characteristic (simplified)
    fn compute_euler_characteristic(gradients: &[ArrayD<f32>]) -> Result<i32> {
        let critical_points = Self::identify_critical_points(gradients)?;
        
        // Simplified Euler characteristic based on critical points
        Ok(critical_points.len() as i32)
    }
    
    /// Estimate genus (simplified)
    fn estimate_genus(gradients: &[ArrayD<f32>]) -> Result<usize> {
        let saddle_points = Self::identify_saddle_points(gradients)?;
        
        // Simplified genus estimation
        Ok(saddle_points.len().saturating_sub(1))
    }
    
    /// Compute Betti numbers (simplified)
    fn compute_betti_numbers(gradients: &[ArrayD<f32>]) -> Result<Vec<usize>> {
        // Simplified Betti number computation
        let connected_components = 1; // Assume single connected component
        let loops = Self::identify_saddle_points(gradients)?.len();
        let voids = 0; // Assume no voids in 2D/3D analysis
        
        Ok(vec![connected_components, loops, voids])
    }
    
    /// Analyze flow dynamics
    fn analyze_flow_dynamics(gradients: &[ArrayD<f32>]) -> Result<FlowDynamics> {
        let temporal_evolution = Self::analyze_temporal_evolution(gradients)?;
        let phase_space_analysis = Self::analyze_phase_space(gradients)?;
        let lyapunov_exponents = Self::estimate_lyapunov_exponents(gradients)?;
        let attractor_analysis = Self::analyze_attractors(gradients)?;
        
        Ok(FlowDynamics {
            temporal_evolution,
            phase_space_analysis,
            lyapunov_exponents,
            attractor_analysis,
            dynamics_classification: Self::classify_dynamics(gradients)?,
        })
    }
    
    /// Analyze temporal evolution
    fn analyze_temporal_evolution(gradients: &[ArrayD<f32>]) -> Result<TemporalEvolution> {
        let magnitudes: Vec<f32> = gradients.iter().map(|g| Self::compute_gradient_magnitude(g)).collect();
        
        let evolution_trend = Self::compute_derivative_trend(&magnitudes);
        let evolution_rate = Self::compute_evolution_rate(&magnitudes);
        let stability_over_time = Self::compute_temporal_stability(&magnitudes);
        
        Ok(TemporalEvolution {
            evolution_trend,
            evolution_rate,
            stability_over_time,
            periodic_components: Self::detect_periodic_components(&magnitudes),
        })
    }
    
    /// Compute evolution rate
    fn compute_evolution_rate(magnitudes: &[f32]) -> f32 {
        if magnitudes.len() < 2 {
            return 0.0;
        }
        
        let mut rates = Vec::new();
        for i in 0..(magnitudes.len() - 1) {
            rates.push((magnitudes[i + 1] - magnitudes[i]).abs());
        }
        
        rates.iter().sum::<f32>() / rates.len() as f32
    }
    
    /// Compute temporal stability
    fn compute_temporal_stability(magnitudes: &[f32]) -> f32 {
        if magnitudes.is_empty() {
            return 0.0;
        }
        
        let mean = magnitudes.iter().sum::<f32>() / magnitudes.len() as f32;
        let variance = magnitudes.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / magnitudes.len() as f32;
        
        // Stability inversely related to variance
        1.0 / (1.0 + variance)
    }
    
    /// Detect periodic components
    fn detect_periodic_components(magnitudes: &[f32]) -> Vec<f32> {
        // Simplified period detection using autocorrelation
        let mut periods = Vec::new();
        
        for lag in 2..magnitudes.len().min(10) {
            let correlation = Self::compute_autocorrelation(magnitudes, lag);
            if correlation > 0.7 {
                periods.push(lag as f32);
            }
        }
        
        periods
    }
    
    /// Compute autocorrelation
    fn compute_autocorrelation(data: &[f32], lag: usize) -> f32 {
        if data.len() <= lag {
            return 0.0;
        }
        
        let n = data.len() - lag;
        let mean = data.iter().sum::<f32>() / data.len() as f32;
        
        let mut numerator = 0.0;
        let mut denominator = 0.0;
        
        for i in 0..n {
            let x = data[i] - mean;
            let y = data[i + lag] - mean;
            numerator += x * y;
            denominator += x * x;
        }
        
        if denominator > 1e-10 {
            numerator / denominator
        } else {
            0.0
        }
    }
    
    /// Analyze phase space
    fn analyze_phase_space(gradients: &[ArrayD<f32>]) -> Result<PhaseSpaceAnalysis> {
        let magnitudes: Vec<f32> = gradients.iter().map(|g| Self::compute_gradient_magnitude(g)).collect();
        
        let phase_portrait = Self::construct_phase_portrait(&magnitudes);
        let attractor_dimension = Self::estimate_attractor_dimension(&magnitudes);
        let phase_space_volume = Self::compute_phase_space_volume(&magnitudes);
        
        Ok(PhaseSpaceAnalysis {
            phase_portrait,
            attractor_dimension,
            phase_space_volume,
            embedding_dimension: Self::estimate_embedding_dimension(&magnitudes),
        })
    }
    
    /// Construct phase portrait
    fn construct_phase_portrait(magnitudes: &[f32]) -> Vec<(f32, f32)> {
        let mut portrait = Vec::new();
        
        for i in 0..(magnitudes.len() - 1) {
            portrait.push((magnitudes[i], magnitudes[i + 1]));
        }
        
        portrait
    }
    
    /// Estimate attractor dimension
    fn estimate_attractor_dimension(magnitudes: &[f32]) -> f32 {
        // Simplified dimension estimation using correlation dimension
        if magnitudes.len() < 3 {
            return 1.0;
        }
        
        // Box-counting dimension approximation
        let unique_values: std::collections::HashSet<_> = magnitudes.iter()
            .map(|&x| (x * 100.0) as i32) // Discretize for counting
            .collect();
        
        (unique_values.len() as f32).log2()
    }
    
    /// Compute phase space volume
    fn compute_phase_space_volume(magnitudes: &[f32]) -> f32 {
        if magnitudes.is_empty() {
            return 0.0;
        }
        
        let min_val = magnitudes.iter().copied().fold(f32::INFINITY, f32::min);
        let max_val = magnitudes.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        
        (max_val - min_val).max(0.0)
    }
    
    /// Estimate embedding dimension
    fn estimate_embedding_dimension(magnitudes: &[f32]) -> usize {
        // Using Takens' theorem approximation
        magnitudes.len().min(10)
    }
    
    /// Estimate Lyapunov exponents
    fn estimate_lyapunov_exponents(gradients: &[ArrayD<f32>]) -> Result<Vec<f32>> {
        let magnitudes: Vec<f32> = gradients.iter().map(|g| Self::compute_gradient_magnitude(g)).collect();
        
        if magnitudes.len() < 3 {
            return Ok(vec![0.0]);
        }
        
        // Simplified Lyapunov exponent estimation
        let mut exponents = Vec::new();
        
        for i in 1..(magnitudes.len() - 1) {
            let divergence_rate = (magnitudes[i + 1] / magnitudes[i]).ln();
            exponents.push(divergence_rate);
        }
        
        // Return the dominant (largest) exponent
        Ok(vec![exponents.iter().copied().fold(f32::NEG_INFINITY, f32::max)])
    }
    
    /// Analyze attractors
    fn analyze_attractors(gradients: &[ArrayD<f32>]) -> Result<AttractorAnalysis> {
        let magnitudes: Vec<f32> = gradients.iter().map(|g| Self::compute_gradient_magnitude(g)).collect();
        
        let attractor_type = Self::classify_attractor_type(&magnitudes);
        let basin_of_attraction = Self::estimate_basin_size(&magnitudes);
        let attractor_stability = Self::compute_attractor_stability(&magnitudes);
        
        Ok(AttractorAnalysis {
            attractor_type,
            basin_of_attraction,
            attractor_stability,
            strange_attractor_indicators: Self::detect_strange_attractor(&magnitudes),
        })
    }
    
    /// Classify attractor type
    fn classify_attractor_type(magnitudes: &[f32]) -> AttractorType {
        let stability = Self::compute_temporal_stability(magnitudes);
        let evolution_rate = Self::compute_evolution_rate(magnitudes);
        
        match (stability, evolution_rate) {
            (s, r) if s > 0.9 && r < 0.01 => AttractorType::FixedPoint,
            (s, r) if s > 0.7 && r < 0.1 => AttractorType::LimitCycle,
            (s, r) if s > 0.5 => AttractorType::Torus,
            _ => AttractorType::Strange,
        }
    }
    
    /// Estimate basin of attraction size
    fn estimate_basin_size(magnitudes: &[f32]) -> f32 {
        if magnitudes.is_empty() {
            return 0.0;
        }
        
        let min_val = magnitudes.iter().copied().fold(f32::INFINITY, f32::min);
        let max_val = magnitudes.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        
        (max_val - min_val).max(0.0)
    }
    
    /// Compute attractor stability
    fn compute_attractor_stability(magnitudes: &[f32]) -> f32 {
        Self::compute_temporal_stability(magnitudes)
    }
    
    /// Detect strange attractor indicators
    fn detect_strange_attractor(magnitudes: &[f32]) -> Vec<String> {
        let mut indicators = Vec::new();
        
        let stability = Self::compute_temporal_stability(magnitudes);
        if stability < 0.3 {
            indicators.push("Low temporal stability".to_string());
        }
        
        let evolution_rate = Self::compute_evolution_rate(magnitudes);
        if evolution_rate > 0.5 {
            indicators.push("High evolution rate".to_string());
        }
        
        // Check for sensitive dependence on initial conditions
        let autocorr = Self::compute_autocorrelation(magnitudes, 1);
        if autocorr < 0.1 {
            indicators.push("Sensitive dependence on initial conditions".to_string());
        }
        
        indicators
    }
    
    /// Classify dynamics
    fn classify_dynamics(gradients: &[ArrayD<f32>]) -> Result<DynamicsClass> {
        let lyapunov = Self::estimate_lyapunov_exponents(gradients)?;
        let attractor_analysis = Self::analyze_attractors(gradients)?;
        
        Ok(match (lyapunov.first().copied().unwrap_or(0.0), attractor_analysis.attractor_type) {
            (l, AttractorType::FixedPoint) if l < 0.0 => DynamicsClass::Stable,
            (l, AttractorType::LimitCycle) if l.abs() < 0.1 => DynamicsClass::Periodic,
            (l, AttractorType::Torus) => DynamicsClass::Quasiperiodic,
            (l, _) if l > 0.1 => DynamicsClass::Chaotic,
            _ => DynamicsClass::Complex,
        })
    }
    
    /// Analyze flow convergence
    fn analyze_flow_convergence(layer_analyses: &[LayerGradientFlowAnalysis]) -> FlowConvergenceAnalysis {
        if layer_analyses.is_empty() {
            return FlowConvergenceAnalysis::default();
        }
        
        let convergence_rate = Self::compute_convergence_rate(layer_analyses);
        let convergence_quality = Self::compute_convergence_quality(layer_analyses);
        let oscillation_damping = Self::compute_oscillation_damping(layer_analyses);
        
        FlowConvergenceAnalysis {
            convergence_rate,
            convergence_quality,
            oscillation_damping,
            convergence_indicators: Self::compute_convergence_indicators(layer_analyses),
        }
    }
    
    /// Compute convergence rate
    fn compute_convergence_rate(layer_analyses: &[LayerGradientFlowAnalysis]) -> f32 {
        if layer_analyses.len() < 2 {
            return 0.0;
        }
        
        let magnitudes: Vec<f32> = layer_analyses.iter().map(|l| l.gradient_magnitude).collect();
        
        // Exponential decay rate
        let mut decay_rates = Vec::new();
        for i in 0..(magnitudes.len() - 1) {
            if magnitudes[i] > 1e-10 {
                let rate = (magnitudes[i + 1] / magnitudes[i]).ln();
                decay_rates.push(rate);
            }
        }
        
        if decay_rates.is_empty() {
            0.0
        } else {
            -decay_rates.iter().sum::<f32>() / decay_rates.len() as f32
        }
    }
    
    /// Compute convergence quality
    fn compute_convergence_quality(layer_analyses: &[LayerGradientFlowAnalysis]) -> f32 {
        if layer_analyses.is_empty() {
            return 0.0;
        }
        
        let coherences: Vec<f32> = layer_analyses.iter().map(|l| l.flow_coherence).collect();
        let stabilities: Vec<f32> = layer_analyses.iter().map(|l| l.flow_stability.stability_score).collect();
        
        let avg_coherence = coherences.iter().sum::<f32>() / coherences.len() as f32;
        let avg_stability = stabilities.iter().sum::<f32>() / stabilities.len() as f32;
        
        (avg_coherence + avg_stability) / 2.0
    }
    
    /// Compute oscillation damping
    fn compute_oscillation_damping(layer_analyses: &[LayerGradientFlowAnalysis]) -> f32 {
        if layer_analyses.len() < 3 {
            return 1.0;
        }
        
        let magnitudes: Vec<f32> = layer_analyses.iter().map(|l| l.gradient_magnitude).collect();
        
        // Measure reduction in oscillations
        let mut oscillation_amplitude = Vec::new();
        for i in 1..(magnitudes.len() - 1) {
            let amplitude = (magnitudes[i] - (magnitudes[i - 1] + magnitudes[i + 1]) / 2.0).abs();
            oscillation_amplitude.push(amplitude);
        }
        
        if oscillation_amplitude.len() < 2 {
            return 1.0;
        }
        
        let first_half = &oscillation_amplitude[0..oscillation_amplitude.len() / 2];
        let second_half = &oscillation_amplitude[oscillation_amplitude.len() / 2..];
        
        let first_avg = first_half.iter().sum::<f32>() / first_half.len() as f32;
        let second_avg = second_half.iter().sum::<f32>() / second_half.len() as f32;
        
        if first_avg > 1e-10 {
            1.0 - (second_avg / first_avg).min(1.0)
        } else {
            1.0
        }
    }
    
    /// Compute convergence indicators
    fn compute_convergence_indicators(layer_analyses: &[LayerGradientFlowAnalysis]) -> ConvergenceIndicators {
        let magnitudes: Vec<f32> = layer_analyses.iter().map(|l| l.gradient_magnitude).collect();
        
        let is_monotonic = Self::check_monotonic_decrease(&magnitudes);
        let has_reached_plateau = Self::check_plateau_reached(&magnitudes);
        let oscillation_frequency = Self::compute_oscillation_frequency_from_magnitudes(&magnitudes);
        
        ConvergenceIndicators {
            is_monotonic,
            has_reached_plateau,
            oscillation_frequency,
            convergence_confidence: Self::compute_convergence_confidence(&magnitudes),
        }
    }
    
    /// Check if magnitudes decrease monotonically
    fn check_monotonic_decrease(magnitudes: &[f32]) -> bool {
        magnitudes.windows(2).all(|w| w[1] <= w[0])
    }
    
    /// Check if plateau is reached
    fn check_plateau_reached(magnitudes: &[f32]) -> bool {
        if magnitudes.len() < 5 {
            return false;
        }
        
        let last_5 = &magnitudes[magnitudes.len() - 5..];
        let variance = Self::compute_temporal_stability(last_5);
        
        variance > 0.95 // High stability indicates plateau
    }
    
    /// Compute oscillation frequency from magnitudes
    fn compute_oscillation_frequency_from_magnitudes(magnitudes: &[f32]) -> f32 {
        Self::compute_oscillation_frequency(&magnitudes.iter().enumerate().map(|(i, &mag)| LayerDirectionalDerivatives {
            layer_index: i,
            primary_derivative: mag,
            secondary_derivative: 0.0,
            cross_derivative: 0.0,
            derivative_magnitude: mag,
        }).collect::<Vec<_>>())
    }
    
    /// Compute convergence confidence
    fn compute_convergence_confidence(magnitudes: &[f32]) -> f32 {
        let stability = Self::compute_temporal_stability(magnitudes);
        let trend_consistency = if magnitudes.len() >= 2 {
            let last_val = magnitudes[magnitudes.len() - 1];
            let first_val = magnitudes[0];
            if first_val > 1e-10 {
                1.0 - (last_val / first_val).min(1.0)
            } else {
                0.0
            }
        } else {
            0.0
        };
        
        (stability + trend_consistency) / 2.0
    }
    
    /// Generate flow recommendations
    fn generate_flow_recommendations(
        layer_analyses: &[LayerGradientFlowAnalysis],
        flow_patterns: &FlowPatterns,
    ) -> Vec<FlowRecommendation> {
        let mut recommendations = Vec::new();
        
        // Check for flow issues
        for layer in layer_analyses {
            if layer.flow_coherence < 0.3 {
                recommendations.push(FlowRecommendation {
                    layer_index: Some(layer.layer_index),
                    recommendation_type: FlowRecommendationType::ImproveCoherence,
                    description: format!("Layer {} has low flow coherence ({}). Consider gradient normalization or learning rate adjustment.", 
                                       layer.layer_index, layer.flow_coherence),
                    urgency: RecommendationUrgency::High,
                    expected_benefit: "Improved training stability and convergence".to_string(),
                });
            }
            
            if layer.flow_stability.stability_score < 0.4 {
                recommendations.push(FlowRecommendation {
                    layer_index: Some(layer.layer_index),
                    recommendation_type: FlowRecommendationType::StabilizeFlow,
                    description: format!("Layer {} shows flow instability ({}). Consider regularization or architecture modifications.", 
                                       layer.layer_index, layer.flow_stability.stability_score),
                    urgency: RecommendationUrgency::High,
                    expected_benefit: "Reduced training variance and improved robustness".to_string(),
                });
            }
            
            if matches!(layer.flow_classification, FlowType::Turbulent) {
                recommendations.push(FlowRecommendation {
                    layer_index: Some(layer.layer_index),
                    recommendation_type: FlowRecommendationType::ReduceTurbulence,
                    description: format!("Layer {} exhibits turbulent flow. Consider batch normalization or skip connections.", 
                                       layer.layer_index),
                    urgency: RecommendationUrgency::Medium,
                    expected_benefit: "Smoother gradient flow and faster convergence".to_string(),
                });
            }
        }
        
        // Global pattern recommendations
        if flow_patterns.pattern_complexity > 1.0 {
            recommendations.push(FlowRecommendation {
                layer_index: None,
                recommendation_type: FlowRecommendationType::SimplifyFlow,
                description: "High flow pattern complexity detected. Consider architectural simplification or regularization.".to_string(),
                urgency: RecommendationUrgency::Medium,
                expected_benefit: "More predictable training dynamics and improved interpretability".to_string(),
            });
        }
        
        if flow_patterns.vortex_structures.len() > layer_analyses.len() / 3 {
            recommendations.push(FlowRecommendation {
                layer_index: None,
                recommendation_type: FlowRecommendationType::ReduceVorticity,
                description: "Multiple vortex structures detected. Consider residual connections or attention mechanisms.".to_string(),
                urgency: RecommendationUrgency::Low,
                expected_benefit: "Reduced gradient circulation and improved information flow".to_string(),
            });
        }
        
        recommendations
    }
}

// Data structures for advanced gradient flow analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct AdvancedGradientFlowAnalysis {
    pub layer_analyses: Vec<LayerGradientFlowAnalysis>,
    pub directional_derivatives: DirectionalDerivatives,
    pub flow_patterns: FlowPatterns,
    pub gradient_topology: GradientTopology,
    pub flow_dynamics: FlowDynamics,
    pub convergence_analysis: FlowConvergenceAnalysis,
    pub flow_recommendations: Vec<FlowRecommendation>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ModelStructureInfo {
    pub num_layers: usize,
    pub layer_types: Vec<String>,
    pub architecture_type: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerGradientFlowAnalysis {
    pub layer_index: usize,
    pub gradient_magnitude: f32,
    pub flow_direction: FlowDirection,
    pub flow_divergence: f32,
    pub flow_curl: f32,
    pub flow_coherence: f32,
    pub flow_stability: FlowStability,
    pub flow_classification: FlowType,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FlowDirection {
    pub dominant_direction: Vec<f32>,
    pub direction_strength: f32,
    pub direction_consistency: f32,
    pub magnitude: f32,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FlowStability {
    pub stability_score: f32,
    pub local_variations: Vec<f32>,
    pub stability_classification: StabilityClass,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub enum StabilityClass {
    #[default]
    Stable,
    ModeratelyStable,
    Unstable,
    HighlyUnstable,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum FlowType {
    Laminar,
    Turbulent,
    Divergent,
    Rotational,
    Mixed,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct DirectionalDerivatives {
    pub layer_derivatives: Vec<LayerDirectionalDerivatives>,
    pub flow_acceleration: f32,
    pub flow_jerk: f32,
    pub derivative_patterns: DerivativePatterns,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerDirectionalDerivatives {
    pub layer_index: usize,
    pub primary_derivative: f32,
    pub secondary_derivative: f32,
    pub cross_derivative: f32,
    pub derivative_magnitude: f32,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct DerivativePatterns {
    pub primary_trend: DerivativeTrend,
    pub secondary_trend: DerivativeTrend,
    pub oscillation_frequency: f32,
    pub dominant_frequency: f32,
    pub pattern_stability: f32,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub enum DerivativeTrend {
    Increasing,
    Decreasing,
    #[default]
    Stable,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlowPatterns {
    pub convergence_zones: Vec<ConvergenceZone>,
    pub divergence_zones: Vec<DivergenceZone>,
    pub vortex_structures: Vec<VortexStructure>,
    pub flow_boundaries: Vec<FlowBoundary>,
    pub pattern_complexity: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ConvergenceZone {
    pub layer_index: usize,
    pub convergence_strength: f32,
    pub zone_stability: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DivergenceZone {
    pub layer_index: usize,
    pub divergence_strength: f32,
    pub expansion_rate: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct VortexStructure {
    pub layer_index: usize,
    pub vorticity_strength: f32,
    pub rotation_direction: RotationDirection,
    pub core_stability: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RotationDirection {
    Clockwise,
    Counterclockwise,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlowBoundary {
    pub between_layers: (usize, usize),
    pub boundary_strength: f32,
    pub boundary_type: BoundaryType,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum BoundaryType {
    Amplification,
    Attenuation,
    Transition,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GradientTopology {
    pub critical_points: Vec<CriticalPoint>,
    pub saddle_points: Vec<SaddlePoint>,
    pub flow_separatrices: Vec<FlowSeparatrix>,
    pub topology_classification: TopologyClass,
    pub topological_invariants: TopologicalInvariants,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CriticalPoint {
    pub layer_index: usize,
    pub point_type: CriticalPointType,
    pub stability_index: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum CriticalPointType {
    Source,
    Sink,
    Vortex,
    Saddle,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SaddlePoint {
    pub layer_index: usize,
    pub saddle_strength: f32,
    pub manifold_dimensions: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlowSeparatrix {
    pub between_layers: (usize, usize),
    pub separation_strength: f32,
    pub separatrix_type: SeparatrixType,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum SeparatrixType {
    Heteroclinic,
    Shock,
    Simple,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum TopologyClass {
    Simple,
    Moderate,
    Complex,
    Chaotic,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TopologicalInvariants {
    pub euler_characteristic: i32,
    pub genus: usize,
    pub betti_numbers: Vec<usize>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlowDynamics {
    pub temporal_evolution: TemporalEvolution,
    pub phase_space_analysis: PhaseSpaceAnalysis,
    pub lyapunov_exponents: Vec<f32>,
    pub attractor_analysis: AttractorAnalysis,
    pub dynamics_classification: DynamicsClass,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TemporalEvolution {
    pub evolution_trend: DerivativeTrend,
    pub evolution_rate: f32,
    pub stability_over_time: f32,
    pub periodic_components: Vec<f32>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PhaseSpaceAnalysis {
    pub phase_portrait: Vec<(f32, f32)>,
    pub attractor_dimension: f32,
    pub phase_space_volume: f32,
    pub embedding_dimension: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AttractorAnalysis {
    pub attractor_type: AttractorType,
    pub basin_of_attraction: f32,
    pub attractor_stability: f32,
    pub strange_attractor_indicators: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum AttractorType {
    FixedPoint,
    LimitCycle,
    Torus,
    Strange,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum DynamicsClass {
    Stable,
    Periodic,
    Quasiperiodic,
    Chaotic,
    Complex,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FlowConvergenceAnalysis {
    pub convergence_rate: f32,
    pub convergence_quality: f32,
    pub oscillation_damping: f32,
    pub convergence_indicators: ConvergenceIndicators,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ConvergenceIndicators {
    pub is_monotonic: bool,
    pub has_reached_plateau: bool,
    pub oscillation_frequency: f32,
    pub convergence_confidence: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FlowRecommendation {
    pub layer_index: Option<usize>,
    pub recommendation_type: FlowRecommendationType,
    pub description: String,
    pub urgency: RecommendationUrgency,
    pub expected_benefit: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum FlowRecommendationType {
    ImproveCoherence,
    StabilizeFlow,
    ReduceTurbulence,
    SimplifyFlow,
    ReduceVorticity,
    OptimizeConvergence,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RecommendationUrgency {
    Low,
    Medium,
    High,
    Critical,
}

/// Advanced Model Comparison Framework for debugging different model states
pub struct ModelComparisonAnalyzer;

impl ModelComparisonAnalyzer {
    /// Compare two model states and identify key differences
    pub fn compare_model_states<T>(
        model_a: &T, 
        model_b: &T, 
        comparison_type: ComparisonType
    ) -> Result<ModelComparisonReport> {
        let mut comparison = ModelComparisonReport {
            comparison_id: uuid::Uuid::new_v4().to_string(),
            comparison_type,
            timestamp: chrono::Utc::now(),
            overall_similarity: 0.0,
            weight_differences: Vec::new(),
            architecture_differences: Vec::new(),
            performance_differences: Vec::new(),
            recommendations: Vec::new(),
        };

        // Analyze architectural differences (placeholder for trait-based implementation)
        comparison.architecture_differences = Self::analyze_architecture_differences();
        
        // Calculate overall similarity score
        comparison.overall_similarity = Self::calculate_overall_similarity(&comparison);
        
        // Generate recommendations based on differences
        comparison.recommendations = Self::generate_comparison_recommendations(&comparison);

        Ok(comparison)
    }

    /// Analyze training convergence patterns across multiple epochs
    pub fn analyze_training_convergence(
        loss_history: &[f32],
        accuracy_history: &[f32],
        learning_rates: &[f32]
    ) -> Result<TrainingConvergenceAnalysis> {
        let convergence_analysis = TrainingConvergenceAnalysis {
            analysis_id: uuid::Uuid::new_v4().to_string(),
            total_epochs: loss_history.len(),
            convergence_status: Self::determine_convergence_status(loss_history),
            loss_trend: Self::analyze_trend(loss_history),
            accuracy_trend: Self::analyze_trend(accuracy_history),
            learning_rate_impact: Self::analyze_lr_impact(learning_rates, loss_history),
            plateau_detection: Self::detect_training_plateaus(loss_history, accuracy_history),
            early_stopping_recommendation: Self::recommend_early_stopping(loss_history, accuracy_history),
            optimization_suggestions: Self::generate_optimization_suggestions(loss_history, accuracy_history, learning_rates),
            estimated_remaining_epochs: Self::estimate_remaining_epochs(loss_history, accuracy_history),
        };

        Ok(convergence_analysis)
    }

    /// Optimize memory usage during debugging sessions
    pub fn optimize_debug_memory_usage(session_config: &DebugConfig) -> Result<MemoryOptimizationReport> {
        let mut memory_optimizer = MemoryOptimizationReport {
            optimization_id: uuid::Uuid::new_v4().to_string(),
            current_memory_usage: Self::estimate_current_memory_usage(session_config),
            optimized_memory_usage: 0,
            memory_savings: 0,
            optimization_strategies: Vec::new(),
            performance_impact: PerformanceImpact::Minimal,
            recommended_actions: Vec::new(),
        };

        // Analyze memory usage patterns
        let strategies = Self::identify_memory_optimization_strategies(session_config);
        memory_optimizer.optimization_strategies = strategies;

        // Calculate potential savings
        memory_optimizer.optimized_memory_usage = Self::calculate_optimized_memory(&memory_optimizer);
        memory_optimizer.memory_savings = memory_optimizer.current_memory_usage - memory_optimizer.optimized_memory_usage;

        // Generate recommendations
        memory_optimizer.recommended_actions = Self::generate_memory_recommendations(&memory_optimizer);

        Ok(memory_optimizer)
    }

    /// Create automated debugging workflows for common issues
    pub fn create_automated_workflow(workflow_type: AutomatedWorkflowType) -> Result<DebuggingWorkflow> {
        let workflow = match workflow_type {
            AutomatedWorkflowType::GradientExplosion => Self::create_gradient_explosion_workflow(),
            AutomatedWorkflowType::TrainingStagnation => Self::create_training_stagnation_workflow(),
            AutomatedWorkflowType::MemoryLeakDetection => Self::create_memory_leak_workflow(),
            AutomatedWorkflowType::PerformanceBottleneck => Self::create_performance_bottleneck_workflow(),
            AutomatedWorkflowType::ComprehensiveHealthCheck => Self::create_comprehensive_health_workflow(),
        };

        Ok(workflow)
    }

    // Private helper methods for model comparison
    fn analyze_architecture_differences() -> Vec<ArchitectureDifference> {
        vec![
            ArchitectureDifference {
                component: "attention_heads".to_string(),
                difference_type: DifferenceType::ParameterCount,
                description: "Different number of attention heads detected".to_string(),
                impact_level: ImpactLevel::Medium,
            }
        ]
    }

    fn calculate_overall_similarity(comparison: &ModelComparisonReport) -> f32 {
        // Sophisticated similarity calculation based on multiple factors
        let architecture_similarity = 0.85; // Placeholder
        let weight_similarity = 0.92; // Placeholder
        let performance_similarity = 0.78; // Placeholder
        
        (architecture_similarity + weight_similarity + performance_similarity) / 3.0
    }

    fn generate_comparison_recommendations(comparison: &ModelComparisonReport) -> Vec<ComparisonRecommendation> {
        let mut recommendations = Vec::new();
        
        if comparison.overall_similarity < 0.8 {
            recommendations.push(ComparisonRecommendation {
                recommendation_type: RecommendationType::Investigation,
                description: "Significant differences detected between models - investigate training procedures".to_string(),
                priority: RecommendationPriority::High,
                estimated_impact: "May indicate model divergence or different training regimes".to_string(),
            });
        }

        recommendations
    }

    // Training convergence analysis helpers
    fn determine_convergence_status(loss_history: &[f32]) -> ConvergenceStatus {
        if loss_history.len() < 10 {
            return ConvergenceStatus::InsufficientData;
        }

        let recent_losses = &loss_history[loss_history.len()-10..];
        let loss_variance = Self::calculate_variance(recent_losses);
        
        if loss_variance < 0.01 {
            ConvergenceStatus::Converged
        } else if Self::is_decreasing_trend(recent_losses) {
            ConvergenceStatus::Converging
        } else {
            ConvergenceStatus::Diverging
        }
    }

    fn analyze_trend(values: &[f32]) -> TrendAnalysis {
        if values.len() < 2 {
            return TrendAnalysis {
                trend_type: TrendType::Unknown,
                trend_strength: 0.0,
                confidence: 0.0,
                slope: 0.0,
            };
        }

        let slope = Self::calculate_slope(values);
        let trend_type = if slope > 0.01 {
            TrendType::Increasing
        } else if slope < -0.01 {
            TrendType::Decreasing
        } else {
            TrendType::Stable
        };

        TrendAnalysis {
            trend_type,
            trend_strength: slope.abs(),
            confidence: Self::calculate_trend_confidence(values),
            slope,
        }
    }

    fn analyze_lr_impact(learning_rates: &[f32], loss_history: &[f32]) -> LearningRateImpact {
        LearningRateImpact {
            correlation_with_loss: Self::calculate_correlation(learning_rates, loss_history),
            optimal_lr_estimate: Self::estimate_optimal_lr(learning_rates, loss_history),
            lr_schedule_recommendation: LRScheduleRecommendation::ExponentialDecay,
            sensitivity_analysis: Self::analyze_lr_sensitivity(learning_rates, loss_history),
        }
    }

    fn detect_training_plateaus(loss_history: &[f32], accuracy_history: &[f32]) -> PlateauDetection {
        PlateauDetection {
            has_loss_plateau: Self::detect_plateau_in_series(loss_history),
            has_accuracy_plateau: Self::detect_plateau_in_series(accuracy_history),
            plateau_start_epoch: Self::find_plateau_start(loss_history),
            plateau_duration: Self::calculate_plateau_duration(loss_history),
            plateau_severity: PlateauSeverity::Moderate,
        }
    }

    fn recommend_early_stopping(loss_history: &[f32], accuracy_history: &[f32]) -> EarlyStoppingRecommendation {
        EarlyStoppingRecommendation {
            should_stop: Self::should_recommend_early_stopping(loss_history, accuracy_history),
            recommended_patience: 10,
            confidence: Self::calculate_early_stopping_confidence(loss_history, accuracy_history),
            reasoning: "Training appears to have plateaued based on loss and accuracy trends".to_string(),
        }
    }

    fn generate_optimization_suggestions(
        loss_history: &[f32], 
        accuracy_history: &[f32], 
        learning_rates: &[f32]
    ) -> Vec<OptimizationSuggestion> {
        let mut suggestions = Vec::new();
        
        if Self::detect_plateau_in_series(loss_history) {
            suggestions.push(OptimizationSuggestion {
                suggestion_type: OptimizationType::LearningRate,
                description: "Consider reducing learning rate to escape plateau".to_string(),
                expected_benefit: "May help model converge to better local minimum".to_string(),
                implementation_difficulty: ImplementationDifficulty::Easy,
            });
        }

        suggestions
    }

    fn estimate_remaining_epochs(loss_history: &[f32], accuracy_history: &[f32]) -> u32 {
        // Simple heuristic based on convergence rate
        if Self::is_decreasing_trend(loss_history) {
            let convergence_rate = Self::estimate_convergence_rate(loss_history);
            if convergence_rate > 0.0 {
                return (0.01 / convergence_rate) as u32; // Estimate epochs to reach 1% of current loss
            }
        }
        50 // Default estimate
    }

    // Memory optimization helpers
    fn estimate_current_memory_usage(config: &DebugConfig) -> u64 {
        // Estimate based on debug configuration
        let base_usage = 100_000_000; // 100MB base
        let tensor_usage = if config.enable_tensor_inspection { 500_000_000 } else { 0 }; // 500MB for tensors
        let gradient_usage = if config.enable_gradient_debugging { 300_000_000 } else { 0 }; // 300MB for gradients
        
        base_usage + tensor_usage + gradient_usage
    }

    fn identify_memory_optimization_strategies(config: &DebugConfig) -> Vec<MemoryOptimizationStrategy> {
        let mut strategies = Vec::new();
        
        if config.enable_tensor_inspection {
            strategies.push(MemoryOptimizationStrategy {
                strategy_type: OptimizationStrategyType::SelectiveTensorInspection,
                description: "Only inspect critical tensors instead of all tensors".to_string(),
                memory_savings_estimate: 200_000_000, // 200MB
                performance_impact: PerformanceImpact::Minimal,
            });
        }

        strategies
    }

    fn calculate_optimized_memory(optimizer: &MemoryOptimizationReport) -> u64 {
        let total_savings: u64 = optimizer.optimization_strategies
            .iter()
            .map(|s| s.memory_savings_estimate)
            .sum();
        
        optimizer.current_memory_usage.saturating_sub(total_savings)
    }

    fn generate_memory_recommendations(optimizer: &MemoryOptimizationReport) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        if optimizer.memory_savings > 100_000_000 { // 100MB savings possible
            recommendations.push("Enable selective debugging to reduce memory footprint".to_string());
        }
        
        if optimizer.current_memory_usage > 1_000_000_000 { // 1GB current usage
            recommendations.push("Consider using lazy evaluation for large tensors".to_string());
        }

        recommendations
    }

    // Automated workflow creation
    fn create_gradient_explosion_workflow() -> DebuggingWorkflow {
        DebuggingWorkflow {
            workflow_id: uuid::Uuid::new_v4().to_string(),
            workflow_type: AutomatedWorkflowType::GradientExplosion,
            steps: vec![
                WorkflowStep {
                    step_id: 1,
                    description: "Monitor gradient norms across all layers".to_string(),
                    action: WorkflowAction::EnableGradientMonitoring,
                    expected_duration: Duration::from_secs(5),
                },
                WorkflowStep {
                    step_id: 2,
                    description: "Check for gradient explosion patterns".to_string(),
                    action: WorkflowAction::AnalyzeGradients,
                    expected_duration: Duration::from_secs(10),
                },
                WorkflowStep {
                    step_id: 3,
                    description: "Generate gradient clipping recommendations".to_string(),
                    action: WorkflowAction::GenerateRecommendations,
                    expected_duration: Duration::from_secs(3),
                },
            ],
            estimated_total_duration: Duration::from_secs(18),
            automation_level: AutomationLevel::FullyAutomated,
        }
    }

    fn create_training_stagnation_workflow() -> DebuggingWorkflow {
        DebuggingWorkflow {
            workflow_id: uuid::Uuid::new_v4().to_string(),
            workflow_type: AutomatedWorkflowType::TrainingStagnation,
            steps: vec![
                WorkflowStep {
                    step_id: 1,
                    description: "Analyze loss curve trends".to_string(),
                    action: WorkflowAction::AnalyzeLossHistory,
                    expected_duration: Duration::from_secs(5),
                },
                WorkflowStep {
                    step_id: 2,
                    description: "Check for training plateaus".to_string(),
                    action: WorkflowAction::DetectPlateaus,
                    expected_duration: Duration::from_secs(8),
                },
                WorkflowStep {
                    step_id: 3,
                    description: "Recommend optimization strategies".to_string(),
                    action: WorkflowAction::GenerateOptimizationSuggestions,
                    expected_duration: Duration::from_secs(5),
                },
            ],
            estimated_total_duration: Duration::from_secs(18),
            automation_level: AutomationLevel::SemiAutomated,
        }
    }

    fn create_memory_leak_workflow() -> DebuggingWorkflow {
        DebuggingWorkflow {
            workflow_id: uuid::Uuid::new_v4().to_string(),
            workflow_type: AutomatedWorkflowType::MemoryLeakDetection,
            steps: vec![
                WorkflowStep {
                    step_id: 1,
                    description: "Monitor memory usage patterns".to_string(),
                    action: WorkflowAction::MonitorMemory,
                    expected_duration: Duration::from_secs(30),
                },
                WorkflowStep {
                    step_id: 2,
                    description: "Detect memory leak patterns".to_string(),
                    action: WorkflowAction::AnalyzeMemoryLeaks,
                    expected_duration: Duration::from_secs(15),
                },
                WorkflowStep {
                    step_id: 3,
                    description: "Generate cleanup recommendations".to_string(),
                    action: WorkflowAction::GenerateCleanupRecommendations,
                    expected_duration: Duration::from_secs(5),
                },
            ],
            estimated_total_duration: Duration::from_secs(50),
            automation_level: AutomationLevel::FullyAutomated,
        }
    }

    fn create_performance_bottleneck_workflow() -> DebuggingWorkflow {
        DebuggingWorkflow {
            workflow_id: uuid::Uuid::new_v4().to_string(),
            workflow_type: AutomatedWorkflowType::PerformanceBottleneck,
            steps: vec![
                WorkflowStep {
                    step_id: 1,
                    description: "Profile model performance".to_string(),
                    action: WorkflowAction::ProfilePerformance,
                    expected_duration: Duration::from_secs(20),
                },
                WorkflowStep {
                    step_id: 2,
                    description: "Identify bottleneck layers".to_string(),
                    action: WorkflowAction::IdentifyBottlenecks,
                    expected_duration: Duration::from_secs(10),
                },
                WorkflowStep {
                    step_id: 3,
                    description: "Suggest performance optimizations".to_string(),
                    action: WorkflowAction::GeneratePerformanceOptimizations,
                    expected_duration: Duration::from_secs(8),
                },
            ],
            estimated_total_duration: Duration::from_secs(38),
            automation_level: AutomationLevel::SemiAutomated,
        }
    }

    fn create_comprehensive_health_workflow() -> DebuggingWorkflow {
        DebuggingWorkflow {
            workflow_id: uuid::Uuid::new_v4().to_string(),
            workflow_type: AutomatedWorkflowType::ComprehensiveHealthCheck,
            steps: vec![
                WorkflowStep {
                    step_id: 1,
                    description: "Run complete model health assessment".to_string(),
                    action: WorkflowAction::ComprehensiveHealthCheck,
                    expected_duration: Duration::from_secs(45),
                },
                WorkflowStep {
                    step_id: 2,
                    description: "Analyze all subsystem health".to_string(),
                    action: WorkflowAction::AnalyzeSubsystemHealth,
                    expected_duration: Duration::from_secs(30),
                },
                WorkflowStep {
                    step_id: 3,
                    description: "Generate comprehensive report".to_string(),
                    action: WorkflowAction::GenerateComprehensiveReport,
                    expected_duration: Duration::from_secs(15),
                },
            ],
            estimated_total_duration: Duration::from_secs(90),
            automation_level: AutomationLevel::FullyAutomated,
        }
    }

    // Mathematical helper functions
    fn calculate_variance(values: &[f32]) -> f32 {
        if values.is_empty() {
            return 0.0;
        }
        
        let mean = values.iter().sum::<f32>() / values.len() as f32;
        let variance = values.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / values.len() as f32;
        
        variance
    }

    fn is_decreasing_trend(values: &[f32]) -> bool {
        if values.len() < 2 {
            return false;
        }
        
        let slope = Self::calculate_slope(values);
        slope < -0.001 // Small negative threshold
    }

    fn calculate_slope(values: &[f32]) -> f32 {
        if values.len() < 2 {
            return 0.0;
        }
        
        let n = values.len() as f32;
        let x_mean = (n - 1.0) / 2.0; // Since indices are 0, 1, 2, ..., n-1
        let y_mean = values.iter().sum::<f32>() / n;
        
        let numerator: f32 = values.iter().enumerate()
            .map(|(i, &y)| (i as f32 - x_mean) * (y - y_mean))
            .sum();
        
        let denominator: f32 = (0..values.len())
            .map(|i| (i as f32 - x_mean).powi(2))
            .sum();
        
        if denominator != 0.0 {
            numerator / denominator
        } else {
            0.0
        }
    }

    fn calculate_trend_confidence(values: &[f32]) -> f32 {
        // Simple R-squared calculation for trend confidence
        if values.len() < 3 {
            return 0.0;
        }
        
        let slope = Self::calculate_slope(values);
        let y_mean = values.iter().sum::<f32>() / values.len() as f32;
        
        let ss_res: f32 = values.iter().enumerate()
            .map(|(i, &y)| {
                let y_pred = slope * i as f32 + (y_mean - slope * (values.len() - 1) as f32 / 2.0);
                (y - y_pred).powi(2)
            })
            .sum();
        
        let ss_tot: f32 = values.iter()
            .map(|&y| (y - y_mean).powi(2))
            .sum();
        
        if ss_tot != 0.0 {
            1.0 - (ss_res / ss_tot)
        } else {
            0.0
        }
    }

    fn calculate_correlation(x_values: &[f32], y_values: &[f32]) -> f32 {
        if x_values.len() != y_values.len() || x_values.is_empty() {
            return 0.0;
        }
        
        let n = x_values.len() as f32;
        let x_mean = x_values.iter().sum::<f32>() / n;
        let y_mean = y_values.iter().sum::<f32>() / n;
        
        let numerator: f32 = x_values.iter().zip(y_values.iter())
            .map(|(&x, &y)| (x - x_mean) * (y - y_mean))
            .sum();
        
        let x_variance: f32 = x_values.iter()
            .map(|&x| (x - x_mean).powi(2))
            .sum();
        
        let y_variance: f32 = y_values.iter()
            .map(|&y| (y - y_mean).powi(2))
            .sum();
        
        let denominator = (x_variance * y_variance).sqrt();
        
        if denominator != 0.0 {
            numerator / denominator
        } else {
            0.0
        }
    }

    fn estimate_optimal_lr(learning_rates: &[f32], loss_history: &[f32]) -> f32 {
        // Simple heuristic: find LR with steepest loss decrease
        if learning_rates.is_empty() || loss_history.len() < 2 {
            return 0.001; // Default
        }
        
        // For simplicity, return the median learning rate
        let mut sorted_lrs = learning_rates.to_vec();
        sorted_lrs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        sorted_lrs[sorted_lrs.len() / 2]
    }

    fn analyze_lr_sensitivity(learning_rates: &[f32], loss_history: &[f32]) -> f32 {
        // Calculate how sensitive loss is to learning rate changes
        Self::calculate_correlation(learning_rates, loss_history).abs()
    }

    fn detect_plateau_in_series(values: &[f32]) -> bool {
        if values.len() < 10 {
            return false;
        }
        
        let recent_values = &values[values.len()-10..];
        let variance = Self::calculate_variance(recent_values);
        variance < 0.001 // Very small variance indicates plateau
    }

    fn find_plateau_start(values: &[f32]) -> Option<usize> {
        // Simple heuristic: find where variance becomes very small
        const WINDOW_SIZE: usize = 10;
        
        if values.len() < WINDOW_SIZE {
            return None;
        }
        
        for i in 0..(values.len() - WINDOW_SIZE + 1) {
            let window = &values[i..i + WINDOW_SIZE];
            if Self::calculate_variance(window) < 0.001 {
                return Some(i);
            }
        }
        
        None
    }

    fn calculate_plateau_duration(values: &[f32]) -> u32 {
        if let Some(start) = Self::find_plateau_start(values) {
            (values.len() - start) as u32
        } else {
            0
        }
    }

    fn should_recommend_early_stopping(loss_history: &[f32], accuracy_history: &[f32]) -> bool {
        Self::detect_plateau_in_series(loss_history) && Self::detect_plateau_in_series(accuracy_history)
    }

    fn calculate_early_stopping_confidence(loss_history: &[f32], accuracy_history: &[f32]) -> f32 {
        let loss_plateau_strength = if Self::detect_plateau_in_series(loss_history) { 0.5 } else { 0.0 };
        let accuracy_plateau_strength = if Self::detect_plateau_in_series(accuracy_history) { 0.5 } else { 0.0 };
        
        loss_plateau_strength + accuracy_plateau_strength
    }

    fn estimate_convergence_rate(loss_history: &[f32]) -> f32 {
        if loss_history.len() < 2 {
            return 0.0;
        }
        
        let recent_slope = Self::calculate_slope(loss_history).abs();
        recent_slope
    }
}

// Supporting data structures for the new capabilities

#[derive(Debug, Serialize, Deserialize)]
pub struct ModelComparisonReport {
    pub comparison_id: String,
    pub comparison_type: ComparisonType,
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub overall_similarity: f32,
    pub weight_differences: Vec<WeightDifference>,
    pub architecture_differences: Vec<ArchitectureDifference>,
    pub performance_differences: Vec<PerformanceDifference>,
    pub recommendations: Vec<ComparisonRecommendation>,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ComparisonType {
    BeforeAfterTraining,
    DifferentArchitectures,
    CheckpointComparison,
    AblationStudy,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WeightDifference {
    pub layer_name: String,
    pub difference_magnitude: f32,
    pub difference_type: WeightDifferenceType,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum WeightDifferenceType {
    Drift,
    Scale,
    Distribution,
    Sparsity,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ArchitectureDifference {
    pub component: String,
    pub difference_type: DifferenceType,
    pub description: String,
    pub impact_level: ImpactLevel,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum DifferenceType {
    ParameterCount,
    LayerStructure,
    ActivationFunction,
    Normalization,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ImpactLevel {
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PerformanceDifference {
    pub metric_name: String,
    pub value_a: f32,
    pub value_b: f32,
    pub relative_difference: f32,
    pub significance: SignificanceLevel,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum SignificanceLevel {
    NotSignificant,
    Marginal,
    Significant,
    HighlySignificant,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ComparisonRecommendation {
    pub recommendation_type: RecommendationType,
    pub description: String,
    pub priority: RecommendationPriority,
    pub estimated_impact: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RecommendationType {
    Investigation,
    Optimization,
    Validation,
    Monitoring,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum RecommendationPriority {
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TrainingConvergenceAnalysis {
    pub analysis_id: String,
    pub total_epochs: usize,
    pub convergence_status: ConvergenceStatus,
    pub loss_trend: TrendAnalysis,
    pub accuracy_trend: TrendAnalysis,
    pub learning_rate_impact: LearningRateImpact,
    pub plateau_detection: PlateauDetection,
    pub early_stopping_recommendation: EarlyStoppingRecommendation,
    pub optimization_suggestions: Vec<OptimizationSuggestion>,
    pub estimated_remaining_epochs: u32,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum ConvergenceStatus {
    Converged,
    Converging,
    Diverging,
    Oscillating,
    InsufficientData,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TrendAnalysis {
    pub trend_type: TrendType,
    pub trend_strength: f32,
    pub confidence: f32,
    pub slope: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum TrendType {
    Increasing,
    Decreasing,
    Stable,
    Oscillating,
    Unknown,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LearningRateImpact {
    pub correlation_with_loss: f32,
    pub optimal_lr_estimate: f32,
    pub lr_schedule_recommendation: LRScheduleRecommendation,
    pub sensitivity_analysis: f32,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum LRScheduleRecommendation {
    Constant,
    LinearDecay,
    ExponentialDecay,
    CosineAnnealing,
    ReduceOnPlateau,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PlateauDetection {
    pub has_loss_plateau: bool,
    pub has_accuracy_plateau: bool,
    pub plateau_start_epoch: Option<usize>,
    pub plateau_duration: u32,
    pub plateau_severity: PlateauSeverity,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum PlateauSeverity {
    Mild,
    Moderate,
    Severe,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EarlyStoppingRecommendation {
    pub should_stop: bool,
    pub recommended_patience: u32,
    pub confidence: f32,
    pub reasoning: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct OptimizationSuggestion {
    pub suggestion_type: OptimizationType,
    pub description: String,
    pub expected_benefit: String,
    pub implementation_difficulty: ImplementationDifficulty,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum OptimizationType {
    LearningRate,
    BatchSize,
    Architecture,
    Regularization,
    DataAugmentation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ImplementationDifficulty {
    Easy,
    Medium,
    Hard,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MemoryOptimizationReport {
    pub optimization_id: String,
    pub current_memory_usage: u64,
    pub optimized_memory_usage: u64,
    pub memory_savings: u64,
    pub optimization_strategies: Vec<MemoryOptimizationStrategy>,
    pub performance_impact: PerformanceImpact,
    pub recommended_actions: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MemoryOptimizationStrategy {
    pub strategy_type: OptimizationStrategyType,
    pub description: String,
    pub memory_savings_estimate: u64,
    pub performance_impact: PerformanceImpact,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum OptimizationStrategyType {
    SelectiveTensorInspection,
    LazyEvaluation,
    MemoryPooling,
    GradientCheckpointing,
    BatchSizeReduction,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum PerformanceImpact {
    Minimal,
    Low,
    Medium,
    High,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DebuggingWorkflow {
    pub workflow_id: String,
    pub workflow_type: AutomatedWorkflowType,
    pub steps: Vec<WorkflowStep>,
    pub estimated_total_duration: Duration,
    pub automation_level: AutomationLevel,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum AutomatedWorkflowType {
    GradientExplosion,
    TrainingStagnation,
    MemoryLeakDetection,
    PerformanceBottleneck,
    ComprehensiveHealthCheck,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct WorkflowStep {
    pub step_id: u32,
    pub description: String,
    pub action: WorkflowAction,
    pub expected_duration: Duration,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum WorkflowAction {
    EnableGradientMonitoring,
    AnalyzeGradients,
    GenerateRecommendations,
    AnalyzeLossHistory,
    DetectPlateaus,
    GenerateOptimizationSuggestions,
    MonitorMemory,
    AnalyzeMemoryLeaks,
    GenerateCleanupRecommendations,
    ProfilePerformance,
    IdentifyBottlenecks,
    GeneratePerformanceOptimizations,
    ComprehensiveHealthCheck,
    AnalyzeSubsystemHealth,
    GenerateComprehensiveReport,
}

#[derive(Debug, Serialize, Deserialize)]
pub enum AutomationLevel {
    Manual,
    SemiAutomated,
    FullyAutomated,
}

// ================================================================================================
// REAL-TIME STREAMING ANALYTICS FOR LIVE TRAINING MONITORING
// ================================================================================================

/// Real-time streaming analytics framework for live training monitoring
/// Provides continuous monitoring and analysis of training metrics with minimal overhead
#[derive(Debug)]
pub struct RealTimeStreamingAnalytics {
    pub config: StreamingConfig,
    metrics_buffer: Vec<TrainingMetrics>,
    alerts: Vec<StreamingAlert>,
    analysis_history: Vec<StreamingAnalysis>,
    last_update: std::time::Instant,
}

/// Configuration for real-time streaming analytics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingConfig {
    pub enable_streaming: bool,
    pub buffer_size: usize,
    pub analysis_interval: Duration,
    pub alert_thresholds: AlertThresholds,
    pub enable_anomaly_detection: bool,
    pub enable_trend_analysis: bool,
}

impl Default for StreamingConfig {
    fn default() -> Self {
        Self {
            enable_streaming: true,
            buffer_size: 1000,
            analysis_interval: Duration::from_secs(10),
            alert_thresholds: AlertThresholds::default(),
            enable_anomaly_detection: true,
            enable_trend_analysis: true,
        }
    }
}

/// Real-time training metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingMetrics {
    pub timestamp: std::time::SystemTime,
    pub epoch: u32,
    pub step: u64,
    pub loss: f32,
    pub learning_rate: f32,
    pub accuracy: Option<f32>,
    pub gpu_memory_usage: f32,
    pub cpu_utilization: f32,
    pub gradient_norm: f32,
    pub throughput: f32, // samples per second
}

/// Alert thresholds for streaming analytics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    pub loss_spike_threshold: f32,
    pub gradient_explosion_threshold: f32,
    pub memory_usage_threshold: f32,
    pub cpu_utilization_threshold: f32,
    pub throughput_drop_threshold: f32,
}

impl Default for AlertThresholds {
    fn default() -> Self {
        Self {
            loss_spike_threshold: 2.0, // 2x increase in loss
            gradient_explosion_threshold: 100.0,
            memory_usage_threshold: 0.9, // 90% memory usage
            cpu_utilization_threshold: 0.95, // 95% CPU usage
            throughput_drop_threshold: 0.5, // 50% throughput drop
        }
    }
}

/// Real-time streaming alert
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingAlert {
    pub alert_id: String,
    pub timestamp: std::time::SystemTime,
    pub severity: AlertSeverity,
    pub alert_type: StreamingAlertType,
    pub message: String,
    pub metrics_snapshot: TrainingMetrics,
    pub recommended_actions: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlertSeverity {
    Info,
    Warning,
    Critical,
    Emergency,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StreamingAlertType {
    LossSpike,
    GradientExplosion,
    MemoryExhaustion,
    CpuThrottling,
    ThroughputDegradation,
    TrainingStagnation,
    NumericalInstability,
}

/// Real-time streaming analysis result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingAnalysis {
    pub analysis_id: String,
    pub timestamp: std::time::SystemTime,
    pub metrics_window: Duration,
    pub trend_analysis: StreamingTrendAnalysis,
    pub anomaly_score: f32,
    pub performance_indicators: PerformanceIndicators,
    pub training_health: TrainingHealthScore,
    pub predictions: TrainingPredictions,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingTrendAnalysis {
    pub loss_trend: StreamingTrendDirection,
    pub loss_volatility: f32,
    pub learning_rate_effectiveness: f32,
    pub gradient_stability: f32,
    pub throughput_trend: StreamingTrendDirection,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StreamingTrendDirection {
    Improving,
    Stable,
    Degrading,
    Volatile,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceIndicators {
    pub current_efficiency: f32,
    pub resource_utilization_score: f32,
    pub training_momentum: f32,
    pub convergence_probability: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingHealthScore {
    pub overall_health: f32, // 0.0 to 1.0
    pub gradient_health: f32,
    pub loss_health: f32,
    pub resource_health: f32,
    pub stability_health: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingPredictions {
    pub estimated_convergence_time: Option<Duration>,
    pub predicted_final_loss: Option<f32>,
    pub recommended_early_stop: bool,
    pub optimization_suggestions: Vec<String>,
}

impl RealTimeStreamingAnalytics {
    /// Create a new real-time streaming analytics instance
    pub fn new(config: StreamingConfig) -> Self {
        Self {
            config,
            metrics_buffer: Vec::new(),
            alerts: Vec::new(),
            analysis_history: Vec::new(),
            last_update: std::time::Instant::now(),
        }
    }

    /// Add new training metrics to the streaming buffer
    pub fn add_metrics(&mut self, metrics: TrainingMetrics) -> Result<()> {
        self.metrics_buffer.push(metrics.clone());
        
        // Maintain buffer size
        if self.metrics_buffer.len() > self.config.buffer_size {
            self.metrics_buffer.remove(0);
        }
        
        // Check for immediate alerts
        self.check_immediate_alerts(&metrics)?;
        
        // Perform analysis if interval has passed
        if self.last_update.elapsed() >= self.config.analysis_interval {
            self.perform_streaming_analysis()?;
            self.last_update = std::time::Instant::now();
        }
        
        Ok(())
    }

    /// Check for immediate alerts based on current metrics
    fn check_immediate_alerts(&mut self, metrics: &TrainingMetrics) -> Result<()> {
        let thresholds = &self.config.alert_thresholds;
        
        // Check for gradient explosion
        if metrics.gradient_norm > thresholds.gradient_explosion_threshold {
            let alert = StreamingAlert {
                alert_id: format!("alert_{}", uuid::Uuid::new_v4()),
                timestamp: std::time::SystemTime::now(),
                severity: AlertSeverity::Critical,
                alert_type: StreamingAlertType::GradientExplosion,
                message: format!("Gradient explosion detected! Norm: {:.2}", metrics.gradient_norm),
                metrics_snapshot: metrics.clone(),
                recommended_actions: vec![
                    "Apply gradient clipping".to_string(),
                    "Reduce learning rate".to_string(),
                    "Check model architecture".to_string(),
                ],
            };
            self.alerts.push(alert);
        }
        
        // Check for memory exhaustion
        if metrics.gpu_memory_usage > thresholds.memory_usage_threshold {
            let alert = StreamingAlert {
                alert_id: format!("alert_{}", uuid::Uuid::new_v4()),
                timestamp: std::time::SystemTime::now(),
                severity: AlertSeverity::Warning,
                alert_type: StreamingAlertType::MemoryExhaustion,
                message: format!("High GPU memory usage: {:.1}%", metrics.gpu_memory_usage * 100.0),
                metrics_snapshot: metrics.clone(),
                recommended_actions: vec![
                    "Reduce batch size".to_string(),
                    "Enable gradient checkpointing".to_string(),
                    "Consider model parallelism".to_string(),
                ],
            };
            self.alerts.push(alert);
        }
        
        // Check for loss spike
        if let Some(previous_metrics) = self.metrics_buffer.last() {
            let loss_ratio = metrics.loss / previous_metrics.loss;
            if loss_ratio > thresholds.loss_spike_threshold {
                let alert = StreamingAlert {
                    alert_id: format!("alert_{}", uuid::Uuid::new_v4()),
                    timestamp: std::time::SystemTime::now(),
                    severity: AlertSeverity::Warning,
                    alert_type: StreamingAlertType::LossSpike,
                    message: format!("Loss spike detected! Increase: {:.1}x", loss_ratio),
                    metrics_snapshot: metrics.clone(),
                    recommended_actions: vec![
                        "Check for data corruption".to_string(),
                        "Verify model stability".to_string(),
                        "Consider learning rate reduction".to_string(),
                    ],
                };
                self.alerts.push(alert);
            }
        }
        
        Ok(())
    }

    /// Perform comprehensive streaming analysis
    fn perform_streaming_analysis(&mut self) -> Result<()> {
        if self.metrics_buffer.len() < 2 {
            return Ok(());
        }
        
        let analysis = StreamingAnalysis {
            analysis_id: format!("analysis_{}", uuid::Uuid::new_v4()),
            timestamp: std::time::SystemTime::now(),
            metrics_window: self.config.analysis_interval,
            trend_analysis: self.analyze_trends()?,
            anomaly_score: self.calculate_anomaly_score()?,
            performance_indicators: self.calculate_performance_indicators()?,
            training_health: self.calculate_training_health()?,
            predictions: self.generate_predictions()?,
        };
        
        self.analysis_history.push(analysis);
        
        // Maintain analysis history size
        if self.analysis_history.len() > 100 {
            self.analysis_history.remove(0);
        }
        
        Ok(())
    }

    /// Analyze trends in the metrics buffer
    fn analyze_trends(&self) -> Result<StreamingTrendAnalysis> {
        if self.metrics_buffer.len() < 10 {
            return Ok(StreamingTrendAnalysis {
                loss_trend: StreamingTrendDirection::Stable,
                loss_volatility: 0.0,
                learning_rate_effectiveness: 0.5,
                gradient_stability: 0.5,
                throughput_trend: StreamingTrendDirection::Stable,
            });
        }
        
        let recent_metrics = &self.metrics_buffer[self.metrics_buffer.len() - 10..];
        
        // Analyze loss trend
        let loss_values: Vec<f32> = recent_metrics.iter().map(|m| m.loss).collect();
        let loss_trend = self.determine_trend_direction(&loss_values);
        let loss_volatility = self.calculate_volatility(&loss_values);
        
        // Analyze throughput trend
        let throughput_values: Vec<f32> = recent_metrics.iter().map(|m| m.throughput).collect();
        let throughput_trend = self.determine_trend_direction(&throughput_values);
        
        // Calculate gradient stability
        let gradient_values: Vec<f32> = recent_metrics.iter().map(|m| m.gradient_norm).collect();
        let gradient_stability = 1.0 - self.calculate_volatility(&gradient_values);
        
        // Estimate learning rate effectiveness
        let lr_effectiveness = self.estimate_lr_effectiveness(recent_metrics);
        
        Ok(StreamingTrendAnalysis {
            loss_trend,
            loss_volatility,
            learning_rate_effectiveness: lr_effectiveness,
            gradient_stability,
            throughput_trend,
        })
    }

    /// Determine trend direction from a series of values
    fn determine_trend_direction(&self, values: &[f32]) -> StreamingTrendDirection {
        if values.len() < 3 {
            return StreamingTrendDirection::Stable;
        }
        
        let first_half = &values[..values.len() / 2];
        let second_half = &values[values.len() / 2..];
        
        let first_avg: f32 = first_half.iter().sum::<f32>() / first_half.len() as f32;
        let second_avg: f32 = second_half.iter().sum::<f32>() / second_half.len() as f32;
        
        let change_ratio = (second_avg - first_avg) / first_avg.abs();
        
        if change_ratio.abs() < 0.05 {
            StreamingTrendDirection::Stable
        } else if change_ratio < -0.1 {
            StreamingTrendDirection::Improving // For loss, decreasing is improving
        } else if change_ratio > 0.1 {
            StreamingTrendDirection::Degrading
        } else {
            StreamingTrendDirection::Volatile
        }
    }

    /// Calculate volatility (coefficient of variation)
    fn calculate_volatility(&self, values: &[f32]) -> f32 {
        if values.len() < 2 {
            return 0.0;
        }
        
        let mean: f32 = values.iter().sum::<f32>() / values.len() as f32;
        let variance: f32 = values.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / values.len() as f32;
        
        let std_dev = variance.sqrt();
        
        if mean.abs() < 1e-8 {
            0.0
        } else {
            std_dev / mean.abs()
        }
    }

    /// Estimate learning rate effectiveness
    fn estimate_lr_effectiveness(&self, metrics: &[TrainingMetrics]) -> f32 {
        if metrics.len() < 5 {
            return 0.5;
        }
        
        let mut effectiveness_scores = Vec::new();
        
        for window in metrics.windows(3) {
            let loss_improvement = (window[0].loss - window[2].loss) / window[0].loss;
            let lr_magnitude = window[1].learning_rate;
            
            // Higher LR should lead to more improvement, but too high can cause instability
            let score = if loss_improvement > 0.0 && lr_magnitude > 0.0 {
                (loss_improvement * 10.0).min(1.0) // Cap at 1.0
            } else {
                0.0
            };
            
            effectiveness_scores.push(score);
        }
        
        effectiveness_scores.iter().sum::<f32>() / effectiveness_scores.len() as f32
    }

    /// Calculate anomaly score for current state
    fn calculate_anomaly_score(&self) -> Result<f32> {
        if self.metrics_buffer.len() < 10 {
            return Ok(0.0);
        }
        
        let recent_metrics = self.metrics_buffer.last().unwrap();
        let historical_metrics = &self.metrics_buffer[..self.metrics_buffer.len() - 1];
        
        let mut anomaly_components = Vec::new();
        
        // Loss anomaly
        let historical_losses: Vec<f32> = historical_metrics.iter().map(|m| m.loss).collect();
        let loss_mean: f32 = historical_losses.iter().sum::<f32>() / historical_losses.len() as f32;
        let loss_std = self.calculate_standard_deviation(&historical_losses, loss_mean);
        let loss_z_score = if loss_std > 0.0 {
            (recent_metrics.loss - loss_mean) / loss_std
        } else {
            0.0
        };
        anomaly_components.push(loss_z_score.abs());
        
        // Gradient norm anomaly
        let historical_gradients: Vec<f32> = historical_metrics.iter().map(|m| m.gradient_norm).collect();
        let grad_mean: f32 = historical_gradients.iter().sum::<f32>() / historical_gradients.len() as f32;
        let grad_std = self.calculate_standard_deviation(&historical_gradients, grad_mean);
        let grad_z_score = if grad_std > 0.0 {
            (recent_metrics.gradient_norm - grad_mean) / grad_std
        } else {
            0.0
        };
        anomaly_components.push(grad_z_score.abs());
        
        // Throughput anomaly
        let historical_throughput: Vec<f32> = historical_metrics.iter().map(|m| m.throughput).collect();
        let throughput_mean: f32 = historical_throughput.iter().sum::<f32>() / historical_throughput.len() as f32;
        let throughput_std = self.calculate_standard_deviation(&historical_throughput, throughput_mean);
        let throughput_z_score = if throughput_std > 0.0 {
            (recent_metrics.throughput - throughput_mean) / throughput_std
        } else {
            0.0
        };
        anomaly_components.push(throughput_z_score.abs());
        
        // Combine anomaly scores (max of 3.0 z-score indicates strong anomaly)
        let total_anomaly: f32 = anomaly_components.iter().sum();
        let normalized_anomaly = (total_anomaly / 9.0).min(1.0); // Normalize to 0-1
        
        Ok(normalized_anomaly)
    }

    /// Calculate standard deviation
    fn calculate_standard_deviation(&self, values: &[f32], mean: f32) -> f32 {
        if values.len() < 2 {
            return 0.0;
        }
        
        let variance: f32 = values.iter()
            .map(|&x| (x - mean).powi(2))
            .sum::<f32>() / values.len() as f32;
        
        variance.sqrt()
    }

    /// Calculate performance indicators
    fn calculate_performance_indicators(&self) -> Result<PerformanceIndicators> {
        if self.metrics_buffer.is_empty() {
            return Ok(PerformanceIndicators {
                current_efficiency: 0.0,
                resource_utilization_score: 0.0,
                training_momentum: 0.0,
                convergence_probability: 0.0,
            });
        }
        
        let recent_metrics = self.metrics_buffer.last().unwrap();
        
        // Current efficiency (samples per second per GPU memory usage)
        let current_efficiency = if recent_metrics.gpu_memory_usage > 0.0 {
            recent_metrics.throughput / recent_metrics.gpu_memory_usage
        } else {
            0.0
        };
        
        // Resource utilization score (balanced CPU and GPU usage)
        let resource_utilization_score = (recent_metrics.cpu_utilization + recent_metrics.gpu_memory_usage) / 2.0;
        
        // Training momentum (improvement rate over recent steps)
        let training_momentum = if self.metrics_buffer.len() >= 5 {
            let recent_five = &self.metrics_buffer[self.metrics_buffer.len() - 5..];
            let initial_loss = recent_five[0].loss;
            let final_loss = recent_five[4].loss;
            
            if initial_loss > 0.0 {
                ((initial_loss - final_loss) / initial_loss).max(0.0)
            } else {
                0.0
            }
        } else {
            0.0
        };
        
        // Convergence probability (based on loss stability and gradient magnitude)
        let convergence_probability = if self.metrics_buffer.len() >= 10 {
            let recent_losses: Vec<f32> = self.metrics_buffer.iter()
                .rev()
                .take(10)
                .map(|m| m.loss)
                .collect();
            
            let loss_volatility = self.calculate_volatility(&recent_losses);
            let avg_gradient = self.metrics_buffer.iter()
                .rev()
                .take(10)
                .map(|m| m.gradient_norm)
                .sum::<f32>() / 10.0;
            
            // Higher probability if loss is stable and gradients are small
            let stability_score = (1.0 - loss_volatility).max(0.0);
            let gradient_score = (1.0 / (1.0 + avg_gradient / 10.0)).max(0.0);
            
            (stability_score + gradient_score) / 2.0
        } else {
            0.0
        };
        
        Ok(PerformanceIndicators {
            current_efficiency,
            resource_utilization_score,
            training_momentum,
            convergence_probability,
        })
    }

    /// Calculate training health score
    fn calculate_training_health(&self) -> Result<TrainingHealthScore> {
        if self.metrics_buffer.is_empty() {
            return Ok(TrainingHealthScore {
                overall_health: 0.0,
                gradient_health: 0.0,
                loss_health: 0.0,
                resource_health: 0.0,
                stability_health: 0.0,
            });
        }
        
        let recent_metrics = self.metrics_buffer.last().unwrap();
        
        // Gradient health (1.0 if gradients are in reasonable range)
        let gradient_health = if recent_metrics.gradient_norm > 0.0 && recent_metrics.gradient_norm < 10.0 {
            1.0 - (recent_metrics.gradient_norm - 1.0).abs() / 9.0
        } else if recent_metrics.gradient_norm >= 10.0 {
            0.0 // Exploding gradients
        } else {
            0.1 // Vanishing gradients
        };
        
        // Loss health (based on whether loss is decreasing and stable)
        let loss_health = if self.metrics_buffer.len() >= 5 {
            let recent_losses: Vec<f32> = self.metrics_buffer.iter()
                .rev()
                .take(5)
                .map(|m| m.loss)
                .collect();
            
            let is_decreasing = recent_losses[0] < recent_losses[4];
            let volatility = self.calculate_volatility(&recent_losses);
            
            if is_decreasing && volatility < 0.1 {
                1.0
            } else if is_decreasing {
                0.7
            } else if volatility < 0.1 {
                0.5
            } else {
                0.2
            }
        } else {
            0.5
        };
        
        // Resource health (memory and CPU usage in reasonable ranges)
        let memory_health = if recent_metrics.gpu_memory_usage < 0.8 {
            1.0
        } else if recent_metrics.gpu_memory_usage < 0.9 {
            0.7
        } else {
            0.3
        };
        
        let cpu_health = if recent_metrics.cpu_utilization < 0.8 {
            1.0
        } else if recent_metrics.cpu_utilization < 0.95 {
            0.7
        } else {
            0.3
        };
        
        let resource_health = (memory_health + cpu_health) / 2.0;
        
        // Stability health (based on metrics volatility)
        let stability_health = if self.metrics_buffer.len() >= 10 {
            let recent_losses: Vec<f32> = self.metrics_buffer.iter()
                .rev()
                .take(10)
                .map(|m| m.loss)
                .collect();
            let recent_gradients: Vec<f32> = self.metrics_buffer.iter()
                .rev()
                .take(10)
                .map(|m| m.gradient_norm)
                .collect();
            
            let loss_volatility = self.calculate_volatility(&recent_losses);
            let gradient_volatility = self.calculate_volatility(&recent_gradients);
            
            let avg_volatility = (loss_volatility + gradient_volatility) / 2.0;
            (1.0 - avg_volatility).max(0.0)
        } else {
            0.5
        };
        
        // Overall health (weighted average)
        let overall_health = (gradient_health * 0.3 + loss_health * 0.3 + 
                            resource_health * 0.2 + stability_health * 0.2);
        
        Ok(TrainingHealthScore {
            overall_health,
            gradient_health,
            loss_health,
            resource_health,
            stability_health,
        })
    }

    /// Generate training predictions
    fn generate_predictions(&self) -> Result<TrainingPredictions> {
        if self.metrics_buffer.len() < 10 {
            return Ok(TrainingPredictions {
                estimated_convergence_time: None,
                predicted_final_loss: None,
                recommended_early_stop: false,
                optimization_suggestions: vec!["Collect more data for predictions".to_string()],
            });
        }
        
        let mut suggestions = Vec::new();
        
        // Analyze recent trends for predictions
        let recent_losses: Vec<f32> = self.metrics_buffer.iter()
            .rev()
            .take(20)
            .map(|m| m.loss)
            .collect();
        
        let loss_improvement_rate = if recent_losses.len() >= 2 {
            (recent_losses[19] - recent_losses[0]) / 19.0 // Change per step
        } else {
            0.0
        };
        
        // Estimate convergence time
        let estimated_convergence_time = if loss_improvement_rate < -1e-6 {
            let current_loss = recent_losses[0];
            let target_loss = current_loss * 0.1; // Assume convergence at 10% of current loss
            let steps_needed = ((current_loss - target_loss) / -loss_improvement_rate) as u64;
            Some(Duration::from_secs(steps_needed * 10)) // Assume 10 seconds per step
        } else {
            None
        };
        
        // Predict final loss (extrapolate current trend)
        let predicted_final_loss = if loss_improvement_rate < 0.0 {
            let current_loss = recent_losses[0];
            Some((current_loss + loss_improvement_rate * 1000.0).max(0.0)) // Extrapolate 1000 steps
        } else {
            None
        };
        
        // Recommend early stopping
        let loss_volatility = self.calculate_volatility(&recent_losses);
        let recommended_early_stop = loss_volatility < 0.01 && loss_improvement_rate.abs() < 1e-6;
        
        // Generate optimization suggestions
        let recent_metrics = self.metrics_buffer.last().unwrap();
        
        if recent_metrics.gradient_norm > 5.0 {
            suggestions.push("Apply gradient clipping to stabilize training".to_string());
        }
        
        if recent_metrics.gpu_memory_usage > 0.9 {
            suggestions.push("Reduce batch size to prevent memory issues".to_string());
        }
        
        if loss_improvement_rate > -1e-6 {
            suggestions.push("Consider reducing learning rate for better convergence".to_string());
        }
        
        if recent_metrics.throughput < 100.0 {
            suggestions.push("Optimize data loading pipeline to improve throughput".to_string());
        }
        
        Ok(TrainingPredictions {
            estimated_convergence_time,
            predicted_final_loss,
            recommended_early_stop,
            optimization_suggestions: suggestions,
        })
    }

    /// Get recent alerts
    pub fn get_recent_alerts(&self, max_alerts: usize) -> Vec<&StreamingAlert> {
        self.alerts.iter()
            .rev()
            .take(max_alerts)
            .collect()
    }

    /// Get latest analysis
    pub fn get_latest_analysis(&self) -> Option<&StreamingAnalysis> {
        self.analysis_history.last()
    }

    /// Get streaming analytics summary
    pub fn get_summary(&self) -> StreamingAnalyticsSummary {
        let latest_analysis = self.get_latest_analysis();
        let critical_alerts = self.alerts.iter()
            .filter(|a| matches!(a.severity, AlertSeverity::Critical | AlertSeverity::Emergency))
            .count();
        
        StreamingAnalyticsSummary {
            total_metrics_processed: self.metrics_buffer.len(),
            total_alerts_generated: self.alerts.len(),
            critical_alerts_count: critical_alerts,
            latest_training_health: latest_analysis.map(|a| a.training_health.overall_health).unwrap_or(0.0),
            anomaly_score: latest_analysis.map(|a| a.anomaly_score).unwrap_or(0.0),
            convergence_probability: latest_analysis
                .map(|a| a.performance_indicators.convergence_probability)
                .unwrap_or(0.0),
        }
    }
}

/// Summary of streaming analytics
#[derive(Debug, Serialize, Deserialize)]
pub struct StreamingAnalyticsSummary {
    pub total_metrics_processed: usize,
    pub total_alerts_generated: usize,
    pub critical_alerts_count: usize,
    pub latest_training_health: f32,
    pub anomaly_score: f32,
    pub convergence_probability: f32,
}

// ================================================================================================
// ENHANCED GPU MEMORY DEBUGGING WITH CUDA-SPECIFIC OPTIMIZATIONS
// ================================================================================================

/// Enhanced GPU memory debugger with CUDA-specific optimizations
/// Provides detailed GPU memory analysis, leak detection, and optimization recommendations
#[derive(Debug)]
pub struct EnhancedGpuMemoryDebugger {
    pub config: GpuMemoryDebugConfig,
    memory_snapshots: Vec<GpuMemorySnapshot>,
    allocation_tracker: HashMap<String, GpuAllocation>,
    leak_detector: GpuLeakDetector,
    optimization_engine: GpuOptimizationEngine,
}

/// Configuration for enhanced GPU memory debugging
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuMemoryDebugConfig {
    pub enable_cuda_profiling: bool,
    pub enable_leak_detection: bool,
    pub enable_fragmentation_analysis: bool,
    pub enable_optimization_suggestions: bool,
    pub snapshot_interval: Duration,
    pub max_snapshots: usize,
    pub leak_detection_threshold: usize, // MB
}

impl Default for GpuMemoryDebugConfig {
    fn default() -> Self {
        Self {
            enable_cuda_profiling: true,
            enable_leak_detection: true,
            enable_fragmentation_analysis: true,
            enable_optimization_suggestions: true,
            snapshot_interval: Duration::from_secs(30),
            max_snapshots: 100,
            leak_detection_threshold: 100, // 100 MB
        }
    }
}

/// GPU memory snapshot with detailed allocation information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuMemorySnapshot {
    pub timestamp: std::time::SystemTime,
    pub device_id: u32,
    pub total_memory: u64,        // bytes
    pub used_memory: u64,         // bytes
    pub free_memory: u64,         // bytes
    pub cached_memory: u64,       // bytes
    pub allocated_blocks: Vec<MemoryBlock>,
    pub fragmentation_score: f32, // 0.0 to 1.0
    pub cuda_context_info: Option<CudaContextInfo>,
}

/// Memory block information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryBlock {
    pub block_id: String,
    pub address: u64,
    pub size: u64,
    pub allocation_type: AllocationType,
    pub allocation_time: std::time::SystemTime,
    pub stack_trace: Option<String>,
    pub tensor_info: Option<TensorInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AllocationType {
    Tensor,
    Gradient,
    Optimizer,
    Cache,
    Temporary,
    Unknown,
}

/// Tensor information for memory blocks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TensorInfo {
    pub shape: Vec<usize>,
    pub dtype: String,
    pub requires_grad: bool,
    pub tensor_name: Option<String>,
}

/// CUDA context information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CudaContextInfo {
    pub cuda_version: String,
    pub driver_version: String,
    pub compute_capability: String,
    pub multiprocessor_count: u32,
    pub max_threads_per_block: u32,
    pub max_block_dimension: Vec<u32>,
    pub max_grid_dimension: Vec<u32>,
    pub memory_clock_rate: u32,
    pub memory_bus_width: u32,
}

/// GPU allocation tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuAllocation {
    pub allocation_id: String,
    pub size: u64,
    pub allocation_time: std::time::SystemTime,
    pub last_access_time: std::time::SystemTime,
    pub access_count: u64,
    pub allocation_type: AllocationType,
    pub stack_trace: Option<String>,
}

/// GPU memory leak detector
#[derive(Debug)]
pub struct GpuLeakDetector {
    baseline_memory: u64,
    suspicious_allocations: Vec<String>,
    leak_patterns: Vec<LeakPattern>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LeakPattern {
    pub pattern_type: LeakPatternType,
    pub description: String,
    pub detection_confidence: f32,
    pub suggested_fixes: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LeakPatternType {
    GradientAccumulation,
    CacheGrowth,
    TensorRetention,
    OptimizerState,
    GraphConstruction,
}

/// GPU optimization engine
#[derive(Debug)]
pub struct GpuOptimizationEngine {
    optimization_history: Vec<GpuOptimization>,
    current_recommendations: Vec<GpuOptimizationRecommendation>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuOptimization {
    pub optimization_id: String,
    pub optimization_type: GpuOptimizationType,
    pub description: String,
    pub estimated_memory_savings: u64,
    pub estimated_performance_impact: f32, // -1.0 to 1.0
    pub implementation_complexity: ImplementationDifficulty,
    pub implementation_steps: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GpuOptimizationType {
    MemoryDefragmentation,
    AllocationPooling,
    GradientCheckpointing,
    ModelParallelism,
    TensorFusion,
    CacheOptimization,
    BatchSizeReduction,
    MixedPrecision,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuOptimizationRecommendation {
    pub recommendation_id: String,
    pub priority: OptimizationPriority,
    pub optimization: GpuOptimization,
    pub current_impact: f32,
    pub confidence_score: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OptimizationPriority {
    Critical,
    High,
    Medium,
    Low,
}

impl EnhancedGpuMemoryDebugger {
    /// Create a new enhanced GPU memory debugger
    pub fn new(config: GpuMemoryDebugConfig) -> Self {
        Self {
            config,
            memory_snapshots: Vec::new(),
            allocation_tracker: HashMap::new(),
            leak_detector: GpuLeakDetector {
                baseline_memory: 0,
                suspicious_allocations: Vec::new(),
                leak_patterns: Vec::new(),
            },
            optimization_engine: GpuOptimizationEngine {
                optimization_history: Vec::new(),
                current_recommendations: Vec::new(),
            },
        }
    }

    /// Take a memory snapshot and analyze GPU state
    pub fn take_snapshot(&mut self, device_id: u32) -> Result<GpuMemorySnapshot> {
        let snapshot = GpuMemorySnapshot {
            timestamp: std::time::SystemTime::now(),
            device_id,
            total_memory: self.get_total_memory(device_id)?,
            used_memory: self.get_used_memory(device_id)?,
            free_memory: self.get_free_memory(device_id)?,
            cached_memory: self.get_cached_memory(device_id)?,
            allocated_blocks: self.get_allocated_blocks(device_id)?,
            fragmentation_score: self.calculate_fragmentation_score(device_id)?,
            cuda_context_info: self.get_cuda_context_info(device_id)?,
        };
        
        self.memory_snapshots.push(snapshot.clone());
        
        // Maintain snapshot history
        if self.memory_snapshots.len() > self.config.max_snapshots {
            self.memory_snapshots.remove(0);
        }
        
        // Analyze for leaks and optimizations
        if self.config.enable_leak_detection {
            self.detect_memory_leaks(&snapshot)?;
        }
        
        if self.config.enable_optimization_suggestions {
            self.generate_optimization_recommendations(&snapshot)?;
        }
        
        Ok(snapshot)
    }

    /// Simulate getting total GPU memory (in real implementation, use CUDA APIs)
    fn get_total_memory(&self, _device_id: u32) -> Result<u64> {
        // In real implementation, use cudaMemGetInfo or similar
        Ok(8_589_934_592) // 8 GB
    }

    /// Simulate getting used GPU memory
    fn get_used_memory(&self, _device_id: u32) -> Result<u64> {
        // In real implementation, use CUDA memory APIs
        Ok(3_221_225_472) // ~3 GB
    }

    /// Simulate getting free GPU memory
    fn get_free_memory(&self, device_id: u32) -> Result<u64> {
        let total = self.get_total_memory(device_id)?;
        let used = self.get_used_memory(device_id)?;
        Ok(total - used)
    }

    /// Simulate getting cached memory
    fn get_cached_memory(&self, _device_id: u32) -> Result<u64> {
        // In real implementation, use PyTorch cache APIs or similar
        Ok(536_870_912) // 512 MB
    }

    /// Get allocated memory blocks
    fn get_allocated_blocks(&self, _device_id: u32) -> Result<Vec<MemoryBlock>> {
        // In real implementation, use memory profiling APIs
        let mut blocks = Vec::new();
        
        // Simulate some allocated blocks
        for i in 0..10 {
            blocks.push(MemoryBlock {
                block_id: format!("block_{}", i),
                address: 0x7f0000000000 + (i as u64 * 1024 * 1024),
                size: 1024 * 1024 * (i as u64 + 1), // Variable sizes
                allocation_type: match i % 3 {
                    0 => AllocationType::Tensor,
                    1 => AllocationType::Gradient,
                    _ => AllocationType::Optimizer,
                },
                allocation_time: std::time::SystemTime::now(),
                stack_trace: Some(format!("stack_trace_{}", i)),
                tensor_info: Some(TensorInfo {
                    shape: vec![32, 768, 768],
                    dtype: "float32".to_string(),
                    requires_grad: i % 2 == 0,
                    tensor_name: Some(format!("tensor_{}", i)),
                }),
            });
        }
        
        Ok(blocks)
    }

    /// Calculate memory fragmentation score
    fn calculate_fragmentation_score(&self, device_id: u32) -> Result<f32> {
        let free_memory = self.get_free_memory(device_id)?;
        let total_memory = self.get_total_memory(device_id)?;
        
        if total_memory == 0 {
            return Ok(0.0);
        }
        
        // Simulate fragmentation calculation
        // In real implementation, analyze free block sizes and distribution
        let utilization = 1.0 - (free_memory as f32 / total_memory as f32);
        
        // Higher utilization typically means higher fragmentation
        let fragmentation = if utilization > 0.8 {
            utilization * 0.7 // High utilization leads to fragmentation
        } else {
            utilization * 0.3 // Low utilization, low fragmentation
        };
        
        Ok(fragmentation.min(1.0))
    }

    /// Get CUDA context information
    fn get_cuda_context_info(&self, _device_id: u32) -> Result<Option<CudaContextInfo>> {
        // In real implementation, use CUDA runtime APIs
        if !self.config.enable_cuda_profiling {
            return Ok(None);
        }
        
        Ok(Some(CudaContextInfo {
            cuda_version: "11.8".to_string(),
            driver_version: "520.61.05".to_string(),
            compute_capability: "8.6".to_string(),
            multiprocessor_count: 84,
            max_threads_per_block: 1024,
            max_block_dimension: vec![1024, 1024, 64],
            max_grid_dimension: vec![2147483647, 65535, 65535],
            memory_clock_rate: 1215000,
            memory_bus_width: 384,
        }))
    }

    /// Detect memory leaks in the current snapshot
    fn detect_memory_leaks(&mut self, snapshot: &GpuMemorySnapshot) -> Result<()> {
        if self.leak_detector.baseline_memory == 0 {
            self.leak_detector.baseline_memory = snapshot.used_memory;
            return Ok(());
        }
        
        let memory_growth = snapshot.used_memory as i64 - self.leak_detector.baseline_memory as i64;
        
        if memory_growth > (self.config.leak_detection_threshold as i64 * 1024 * 1024) {
            // Analyze allocation patterns to identify potential leaks
            self.analyze_leak_patterns(snapshot)?;
        }
        
        Ok(())
    }

    /// Analyze patterns that might indicate memory leaks
    fn analyze_leak_patterns(&mut self, snapshot: &GpuMemorySnapshot) -> Result<()> {
        let mut new_patterns = Vec::new();
        
        // Check for gradient accumulation leaks
        let gradient_blocks: Vec<&MemoryBlock> = snapshot.allocated_blocks.iter()
            .filter(|b| matches!(b.allocation_type, AllocationType::Gradient))
            .collect();
        
        if gradient_blocks.len() > 100 {
            new_patterns.push(LeakPattern {
                pattern_type: LeakPatternType::GradientAccumulation,
                description: "Excessive gradient tensors detected".to_string(),
                detection_confidence: 0.8,
                suggested_fixes: vec![
                    "Call optimizer.zero_grad() after each backward pass".to_string(),
                    "Use gradient checkpointing to reduce memory usage".to_string(),
                    "Consider gradient accumulation with smaller effective batch size".to_string(),
                ],
            });
        }
        
        // Check for cache growth
        if snapshot.cached_memory > 2_147_483_648 { // 2 GB
            new_patterns.push(LeakPattern {
                pattern_type: LeakPatternType::CacheGrowth,
                description: "GPU cache memory growing beyond reasonable limits".to_string(),
                detection_confidence: 0.9,
                suggested_fixes: vec![
                    "Call torch.cuda.empty_cache() periodically".to_string(),
                    "Reduce model parallelism or batch size".to_string(),
                    "Use memory-mapped datasets to reduce caching".to_string(),
                ],
            });
        }
        
        // Check for tensor retention
        let old_tensors: Vec<&MemoryBlock> = snapshot.allocated_blocks.iter()
            .filter(|b| {
                matches!(b.allocation_type, AllocationType::Tensor) &&
                b.allocation_time.elapsed().unwrap_or(Duration::from_secs(0)) > Duration::from_secs(300)
            })
            .collect();
        
        if old_tensors.len() > 50 {
            new_patterns.push(LeakPattern {
                pattern_type: LeakPatternType::TensorRetention,
                description: "Many long-lived tensors detected".to_string(),
                detection_confidence: 0.7,
                suggested_fixes: vec![
                    "Explicitly delete intermediate tensors".to_string(),
                    "Use context managers for temporary computations".to_string(),
                    "Avoid storing tensors in global variables".to_string(),
                ],
            });
        }
        
        self.leak_detector.leak_patterns.extend(new_patterns);
        
        Ok(())
    }

    /// Generate optimization recommendations based on current memory state
    fn generate_optimization_recommendations(&mut self, snapshot: &GpuMemorySnapshot) -> Result<()> {
        let mut recommendations = Vec::new();
        
        // Memory usage is high
        if snapshot.used_memory as f32 / snapshot.total_memory as f32 > 0.9 {
            recommendations.push(GpuOptimizationRecommendation {
                recommendation_id: format!("opt_{}", uuid::Uuid::new_v4()),
                priority: OptimizationPriority::Critical,
                optimization: GpuOptimization {
                    optimization_id: format!("opt_{}", uuid::Uuid::new_v4()),
                    optimization_type: GpuOptimizationType::MemoryDefragmentation,
                    description: "Memory usage is critically high - defragmentation needed".to_string(),
                    estimated_memory_savings: snapshot.total_memory / 10, // 10% savings
                    estimated_performance_impact: -0.1, // Slight performance cost
                    implementation_complexity: ImplementationDifficulty::Easy,
                    implementation_steps: vec![
                        "Call torch.cuda.empty_cache()".to_string(),
                        "Restart CUDA context if necessary".to_string(),
                        "Consider reducing batch size".to_string(),
                    ],
                },
                current_impact: 0.9,
                confidence_score: 0.95,
            });
        }
        
        // High fragmentation
        if snapshot.fragmentation_score > 0.6 {
            recommendations.push(GpuOptimizationRecommendation {
                recommendation_id: format!("opt_{}", uuid::Uuid::new_v4()),
                priority: OptimizationPriority::High,
                optimization: GpuOptimization {
                    optimization_id: format!("opt_{}", uuid::Uuid::new_v4()),
                    optimization_type: GpuOptimizationType::AllocationPooling,
                    description: "High memory fragmentation detected".to_string(),
                    estimated_memory_savings: snapshot.cached_memory / 2,
                    estimated_performance_impact: 0.2, // Performance improvement
                    implementation_complexity: ImplementationDifficulty::Medium,
                    implementation_steps: vec![
                        "Implement memory pooling for allocations".to_string(),
                        "Pre-allocate memory blocks of common sizes".to_string(),
                        "Use memory-efficient data structures".to_string(),
                    ],
                },
                current_impact: snapshot.fragmentation_score,
                confidence_score: 0.8,
            });
        }
        
        // Many gradient allocations
        let gradient_count = snapshot.allocated_blocks.iter()
            .filter(|b| matches!(b.allocation_type, AllocationType::Gradient))
            .count();
        
        if gradient_count > 50 {
            recommendations.push(GpuOptimizationRecommendation {
                recommendation_id: format!("opt_{}", uuid::Uuid::new_v4()),
                priority: OptimizationPriority::Medium,
                optimization: GpuOptimization {
                    optimization_id: format!("opt_{}", uuid::Uuid::new_v4()),
                    optimization_type: GpuOptimizationType::GradientCheckpointing,
                    description: "Excessive gradient memory usage detected".to_string(),
                    estimated_memory_savings: snapshot.used_memory / 3, // ~33% savings
                    estimated_performance_impact: -0.2, // Some performance cost
                    implementation_complexity: ImplementationDifficulty::Hard,
                    implementation_steps: vec![
                        "Implement gradient checkpointing for transformer layers".to_string(),
                        "Use activation checkpointing for memory-intensive operations".to_string(),
                        "Configure checkpointing frequency based on memory constraints".to_string(),
                    ],
                },
                current_impact: gradient_count as f32 / 100.0,
                confidence_score: 0.75,
            });
        }
        
        self.optimization_engine.current_recommendations = recommendations;
        
        Ok(())
    }

    /// Get GPU memory analysis report
    pub fn get_memory_analysis(&self) -> GpuMemoryAnalysis {
        let latest_snapshot = self.memory_snapshots.last();
        
        GpuMemoryAnalysis {
            total_snapshots: self.memory_snapshots.len(),
            latest_memory_usage: latest_snapshot.map(|s| s.used_memory).unwrap_or(0),
            latest_fragmentation: latest_snapshot.map(|s| s.fragmentation_score).unwrap_or(0.0),
            detected_leaks: self.leak_detector.leak_patterns.len(),
            active_recommendations: self.optimization_engine.current_recommendations.len(),
            memory_trend: self.calculate_memory_trend(),
            optimization_potential: self.calculate_optimization_potential(),
        }
    }

    /// Calculate memory usage trend
    fn calculate_memory_trend(&self) -> MemoryTrend {
        if self.memory_snapshots.len() < 5 {
            return MemoryTrend::Stable;
        }
        
        let recent_snapshots = &self.memory_snapshots[self.memory_snapshots.len() - 5..];
        let first_usage = recent_snapshots[0].used_memory as f32;
        let last_usage = recent_snapshots[4].used_memory as f32;
        
        let change_ratio = (last_usage - first_usage) / first_usage;
        
        if change_ratio > 0.1 {
            MemoryTrend::Increasing
        } else if change_ratio < -0.1 {
            MemoryTrend::Decreasing
        } else {
            MemoryTrend::Stable
        }
    }

    /// Calculate optimization potential score
    fn calculate_optimization_potential(&self) -> f32 {
        let critical_recommendations = self.optimization_engine.current_recommendations.iter()
            .filter(|r| matches!(r.priority, OptimizationPriority::Critical))
            .count();
        
        let high_recommendations = self.optimization_engine.current_recommendations.iter()
            .filter(|r| matches!(r.priority, OptimizationPriority::High))
            .count();
        
        let total_estimated_savings: u64 = self.optimization_engine.current_recommendations.iter()
            .map(|r| r.optimization.estimated_memory_savings)
            .sum();
        
        let latest_total_memory = self.memory_snapshots.last()
            .map(|s| s.total_memory)
            .unwrap_or(1);
        
        let savings_ratio = total_estimated_savings as f32 / latest_total_memory as f32;
        
        // Combine factors: urgency of recommendations and potential savings
        let urgency_score = (critical_recommendations * 3 + high_recommendations * 2) as f32 / 10.0;
        let savings_score = savings_ratio * 2.0; // Scale up savings importance
        
        ((urgency_score + savings_score) / 2.0).min(1.0)
    }

    /// Get optimization recommendations
    pub fn get_recommendations(&self) -> &[GpuOptimizationRecommendation] {
        &self.optimization_engine.current_recommendations
    }

    /// Get detected leak patterns
    pub fn get_leak_patterns(&self) -> &[LeakPattern] {
        &self.leak_detector.leak_patterns
    }
}

/// GPU memory analysis summary
#[derive(Debug, Serialize, Deserialize)]
pub struct GpuMemoryAnalysis {
    pub total_snapshots: usize,
    pub latest_memory_usage: u64,
    pub latest_fragmentation: f32,
    pub detected_leaks: usize,
    pub active_recommendations: usize,
    pub memory_trend: MemoryTrend,
    pub optimization_potential: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MemoryTrend {
    Increasing,
    Stable,
    Decreasing,
}