manifolds-rs 0.3.3

Embedding methods implemented in Rust: (parametric) UMAP, tSNE, PHATE, Diffusion Map and PacMAP.
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
//! Dimensionality reduction algorithms including UMAP, t-SNE, PHATE, Diffusion
//! Maps and PacMAP.
//!
//! Provides both standard and approximate nearest-neighbour-based graph
//! construction, multiple optimisers, and (optionally) parametric UMAP via a
//! neural network encoder.
//!
//! Additionally, optional GPU-accelerated versions (in terms of kNN search)
//! can be used when the right feature flags are active.

#![allow(clippy::needless_range_loop)] // I like loops ... !
#![warn(missing_docs)]

pub mod data;
pub mod errors;
pub mod prelude;
pub mod training;
pub mod utils;

#[cfg(feature = "parametric")]
pub mod parametric;

use ann_search_rs::cpu::hnsw::{HnswIndex, HnswState};
use ann_search_rs::cpu::nndescent::{ApplySortedUpdates, NNDescent, NNDescentQuery};
use ann_search_rs::utils::dist::parse_ann_dist;
use faer::MatRef;
use rand_distr::{Distribution, StandardNormal};
use std::{default::Default, time::Instant};
use thousands::*;

#[cfg(feature = "parametric")]
use burn::tensor::{backend::AutodiffBackend, Element};
#[cfg(feature = "parametric")]
use num_traits::ToPrimitive;

#[cfg(feature = "gpu")]
use ann_search_rs::gpu::nndescent_gpu::NNDescentGpu;
#[cfg(feature = "gpu")]
use ann_search_rs::gpu::traits_gpu::AnnSearchGpuFloat;
#[cfg(feature = "gpu")]
use cubecl::prelude::*;

use crate::data::graph::*;
use crate::data::init::*;
use crate::data::nearest_neighbours::*;
use crate::data::pacmap_pairs::*;
use crate::data::structures::*;
use crate::prelude::*;
use crate::training::mds_optimiser::*;
use crate::training::pacmap_optimiser::{
    optimise_pacmap, optimise_pacmap_parallel, PacMapOptimiser,
};
use crate::training::tsne_optimiser::*;
use crate::training::umap_optimisers::*;
use crate::utils::diffusions::*;
use crate::utils::math::compute_largest_eigenpairs_lanczos;
use crate::utils::potentials::compute_potential_distances;
use crate::utils::sparse_ops::matrix_power;

#[cfg(feature = "parametric")]
use crate::parametric::model::*;
#[cfg(feature = "parametric")]
use crate::parametric::parametric_train::*;
#[cfg(feature = "fft_tsne")]
use crate::utils::fft::FftwFloat;

///////////
// Types //
///////////

/// Type for the pre-computed kNN
///
/// ### Fields
///
/// * `0` - Should be the indices of the nearest neighbours excluding self
/// * `1` - Should be the distances to the nearest neighbours excluding self
pub type PreComputedKnn<T> = Option<(Vec<Vec<usize>>, Vec<Vec<T>>)>;

/// Result of the tSNE graph
///
/// ### Fields
///
/// * `0` - The coordinate list
/// * `1` - The nearest neighbours
/// * `2` - The distances to the nearest neighbours
///
/// ### Errors
///
/// Potential errors from the generation of the graph
pub type TsneGraph<T> = Result<(CoordinateList<T>, Vec<Vec<usize>>, Vec<Vec<T>>), ManifoldsError>;

//////////
// Umap //
//////////

/// Main Config structure with all of the possible sub configurations
#[derive(Debug, Clone)]
pub struct UmapParams<T> {
    /// How many dimensions to return
    pub n_dim: usize,
    /// Number of neighbours
    pub k: usize,
    /// Which optimiser to use. Defaults to `"adam_parallel"`.
    pub optimiser: String,
    /// (Approximate) Nearest neighbour method. One of `"exhaustive"`, `"ivf"`,
    /// `"hnsw"`, `"nndescent"`, `"annoy"`, `"kmknn"` or `"balltree"`.
    pub ann_type: String,
    /// Which embedding initialisation to use. Defaults to spectral clustering.
    pub initialisation: String,
    /// Optional initialisation range to use
    pub init_range: Option<T>,
    /// Nearest neighbour parameters.
    pub nn_params: NearestNeighbourParams<T>,
    /// Parameters for the UMAP graph generation.
    pub umap_graph_params: UmapGraphParams<T>,
    /// Parameters to use for the UMAP optimiser.
    pub optim_params: UmapOptimParams<T>,
    /// Shall randomised SVC be used for PCA-based embedding
    pub randomised: bool,
}

impl<T> Default for UmapParams<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            k: 15,
            optimiser: "adam_parallel".to_string(),
            ann_type: "kmknn".to_string(),
            initialisation: "spectral".to_string(),
            init_range: None,
            nn_params: NearestNeighbourParams::default(),
            optim_params: UmapOptimParams::default(),
            umap_graph_params: UmapGraphParams::default(),
            randomised: false,
        }
    }
}

impl<T> UmapParams<T>
where
    T: ManifoldsFloat,
{
    /// Generate new UMAP parameters with full control over every field.
    ///
    /// This constructor exposes every field directly. For sensible defaults,
    /// use [`UmapParams::default`] or [`UmapParams::new_default_2d`] instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - How many dimensions to return.
    /// * `k` - How many neighbours to consider.
    /// * `optimiser` - Which optimiser to use, e.g. `"adam_parallel"`.
    /// * `ann_type` - (Approximate) nearest neighbour method. One of
    ///   `"exhaustive"`, `"ivf"`, `"hnsw"`, `"nndescent"`, `"annoy"`,
    ///   `"kmknn"` or `"balltree"`.
    /// * `initialisation` - Which embedding initialisation to use, e.g.
    ///   `"spectral"`.
    /// * `init_range` - Optional initialisation range.
    /// * `nn_params` - Nearest neighbour parameters.
    /// * `optim_params` - Parameters for the UMAP optimiser.
    /// * `umap_graph_params` - Parameters for the UMAP graph generation.
    /// * `randomised` - Whether randomised SVD is used for PCA-based embedding.
    ///
    /// ### Returns
    ///
    /// A fully specified set of UMAP parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        k: usize,
        optimiser: String,
        ann_type: String,
        initialisation: String,
        init_range: Option<T>,
        nn_params: NearestNeighbourParams<T>,
        optim_params: UmapOptimParams<T>,
        umap_graph_params: UmapGraphParams<T>,
        randomised: bool,
    ) -> Self {
        Self {
            n_dim,
            k,
            optimiser,
            ann_type,
            initialisation,
            init_range,
            nn_params,
            optim_params,
            umap_graph_params,
            randomised,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `min_dist` and
    /// `spread`, which feed into the optimiser parameters and control how
    /// tightly points are packed in the embedding.
    ///
    /// ### Params
    ///
    /// * `min_dist` - Minimum distance between data points. Defaults to `0.5`.
    /// * `spread` - Spread parameter. Defaults to `1.0`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation.
    pub fn new_default_2d(min_dist: Option<T>, spread: Option<T>) -> Self {
        let min_dist = min_dist.unwrap_or(T::from_f64(0.5).unwrap());
        let spread = spread.unwrap_or(T::from_f64(1.0).unwrap());

        Self {
            optim_params: UmapOptimParams::from_min_dist_spread(
                min_dist, spread, None, None, None, None, None, None, None,
            ),
            ..Self::default()
        }
    }
}

/// Helper function to generate the UMAP graph
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed k-nearest neighbours and distances. Needs
///   to be a tuple of `(Vec<Vec<usize>>, Vec<Vec<T>>)` with indices and
///   distances excluding self.
/// * `k` - Number of nearest neighbours (typically 15-50).
/// * `ann_type` - (Approximate) Nearest neighbour method: `"exhaustive"`,
///   `"kmknn"`, `"balltree"`, `"annoy"`, `"hnsw"`, or `"nndescent"`. If you
///   provide a weird string, the function will default to `"kmknn"`
/// * `umap_params` - UMAP-specific parameters (bandwidth, local_connectivity,
///   mix_weight)
/// * `nn_params` - Nearest neighbour parameters for nearest neighbour search.
/// * `seed` - Random seed
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Tuple of (graph, knn_indices, knn_dist) for use in optimisation
#[allow(clippy::too_many_arguments)]
pub fn construct_umap_graph<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    k: usize,
    ann_type: String,
    umap_params: &UmapGraphParams<T>,
    nn_params: &NearestNeighbourParams<T>,
    n_epochs: usize,
    seed: usize,
    verbose: usize,
) -> UmapGraphResults<T>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    let (knn_indices, knn_dist) = match precomputed_knn {
        Some((indices, distances)) => {
            if verbosity.normal_verbosity() {
                println!("Using precomputed kNN graph...");
            }
            (indices, distances)
        }
        None => {
            if verbosity.normal_verbosity() {
                println!(
                    "Running (approximate) nearest neighbour search using {}...",
                    ann_type
                );
            }
            let start_knn = Instant::now();
            let result = run_ann_search(data, k, ann_type, nn_params, seed, verbose)?;
            if verbosity.normal_verbosity() {
                println!("kNN search done in: {:.2?}.", start_knn.elapsed());
            }
            result
        }
    };

    if verbosity.normal_verbosity() {
        println!("Constructing fuzzy simplicial set...");
    }

    let start_graph = Instant::now();

    let (sigma, rho) = smooth_knn_dist(
        &knn_dist,
        knn_dist[0].len(),
        umap_params.local_connectivity,
        umap_params.bandwidth,
        64,
    );

    let graph = knn_to_coo(&knn_indices, &knn_dist, &sigma, &rho);
    let graph = symmetrise_graph(graph, umap_params.mix_weight);
    let graph = filter_weak_edges(graph, n_epochs, verbose);

    if verbosity.normal_verbosity() {
        println!(
            "Finalised graph generation in {:.2?}.",
            start_graph.elapsed()
        );
    }

    Ok((graph, knn_indices, knn_dist))
}

/// Run UMAP dimensionality reduction
///
/// Uniform Manifold Approximation and Projection (UMAP) is a manifold learning
/// technique for dimensionality reduction. This implementation follows the
/// standard UMAP algorithm:
///
/// 1. Find k-nearest neighbours using approximate nearest neighbour search
/// 2. Construct fuzzy simplicial set via smooth kNN distances
/// 3. Symmetrise the graph using fuzzy set union
/// 4. Initialise embedding via spectral decomposition
/// 5. Optimise embedding using stochastic gradient descent
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed k-nearest neighbours and distances. Needs
///   to be a tuple of `(Vec<Vec<usize>>, Vec<Vec<T>>)` with indices and
///   distances excluding self.
/// * `umap_params` - The UMAP parameters.
/// * `seed` - Seed for reproducibility.
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding coordinates as `Vec<Vec<T>>` where outer vector has length
/// `n_dim` and inner vectors have length `n_samples`. Each outer element
/// represents one embedding dimension.
pub fn umap<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    umap_params: &UmapParams<T>,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    StandardNormal: Distribution<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    // parse various parameters
    let init_type = parse_initilisation(
        &umap_params.initialisation,
        umap_params.randomised,
        umap_params.init_range,
    )
    .unwrap_or_else(|| {
        println!(
            "Unknown initialisation provided: {:?}. Defaulting to PCA.",
            umap_params.initialisation,
        );
        EmbdInit::PcaInit {
            range: None,
            randomised: true,
        }
    });
    let optimiser = parse_umap_optimiser(&umap_params.optimiser).unwrap_or_default();

    if verbosity.normal_verbosity() {
        println!(
            "Running umap with alpha: {:.2?} and beta: {:.2?}",
            umap_params.optim_params.a, umap_params.optim_params.b
        );
    }

    let (graph, _, _) = construct_umap_graph(
        data,
        precomputed_knn,
        umap_params.k,
        umap_params.ann_type.clone(),
        &umap_params.umap_graph_params,
        &umap_params.nn_params,
        umap_params.optim_params.n_epochs,
        seed,
        verbose,
    )?;

    if verbosity.normal_verbosity() {
        println!(
            "Initialising embedding via {} layout...",
            umap_params.initialisation
        );
    }

    let start_layout = Instant::now();

    let mut embd = initialise_embedding(&init_type, umap_params.n_dim, seed as u64, &graph, data)?;

    let graph_adj = coo_to_adjacency_list(&graph);

    if verbosity.normal_verbosity() {
        println!(
            "Optimising embedding via {} ({} epochs) on {} edges...",
            match optimiser {
                UmapOptimiser::Adam => "Adam",
                UmapOptimiser::Sgd => "SGD",
                UmapOptimiser::AdamParallel => "Adam (multi-threaded)",
            },
            umap_params.optim_params.n_epochs,
            graph.col_indices.len().separate_with_underscores()
        );
    }

    match optimiser {
        UmapOptimiser::Adam => optimise_embedding_adam(
            &mut embd,
            &graph_adj,
            &umap_params.optim_params,
            seed as u64,
            verbose,
        )?,
        UmapOptimiser::Sgd => {
            optimise_embedding_sgd(
                &mut embd,
                &graph_adj,
                &umap_params.optim_params,
                seed as u64,
                verbose,
            )?;
        }
        UmapOptimiser::AdamParallel => {
            optimise_embedding_adam_parallel(
                &mut embd,
                &graph_adj,
                &umap_params.optim_params,
                seed as u64,
                verbose,
            )?;
        }
    }

    let end_layout = start_layout.elapsed();

    if verbosity.normal_verbosity() {
        println!(
            "Initialised and optimised embedding in: {:.2?}.",
            end_layout
        );
        println!("UMAP complete!");
    }

    // transpose: from [n_samples][n_dim] to [n_dim][n_samples]
    let n_samples = embd.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; umap_params.n_dim];

    for sample_idx in 0..n_samples {
        for dim_idx in 0..umap_params.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}

//////////
// tSNE //
//////////

/// Main configuration for t-SNE dimensionality reduction
#[derive(Debug, Clone)]
pub struct TsneParams<T> {
    ///  Number of output dimensions (typically 2)
    pub n_dim: usize,
    /// Perplexity parameter controlling neighbourhood size (typical: 5-50)
    pub perplexity: T,
    /// (Approximate) Nearest neighbour method. One of `"exhaustive"`, `"ivf"`,
    /// `"hnsw"`, `"nndescent"`, `"annoy"`, `"kmknn"` or `"balltree"`.
    pub ann_type: String,
    /// Embedding initialisation method: `"pca"`, `"random"`, or `"spectral"`
    pub initialisation: String,
    /// Optional initialisation range
    pub init_range: Option<T>,
    /// Nearest neighbour parameters
    pub nn_params: NearestNeighbourParams<T>,
    /// tSNE optimisation parameters
    pub optim_params: TsneOptimParams<T>,
    /// Use randomised SVD for PCA initialisation
    pub randomised_init: bool,
}

impl<T> Default for TsneParams<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            perplexity: T::from_f64(30.0).unwrap(),
            ann_type: "kmknn".to_string(),
            initialisation: "pca".to_string(),
            init_range: None,
            nn_params: NearestNeighbourParams::default(),
            optim_params: TsneOptimParams {
                n_epochs: 1000,
                lr: None,
                early_exag_iter: 250,
                early_exag_factor: T::from_f64(12.0).unwrap(),
                late_exag_factor: None,
                theta: T::from_f64(0.5).unwrap(),
                n_interp_points: 3,
            },
            randomised_init: true,
        }
    }
}

impl<T> TsneParams<T>
where
    T: ManifoldsFloat,
{
    /// Create new t-SNE parameters with full control over every field.
    ///
    /// This constructor exposes every field directly, including the
    /// optimiser parameters. For sensible defaults, use
    /// [`TsneParams::default`] or [`TsneParams::new_default_2d`] instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - Number of output dimensions.
    /// * `perplexity` - Perplexity parameter controlling neighbourhood size
    ///   (typical: 5-50).
    /// * `ann_type` - (Approximate) nearest neighbour method. One of
    ///   `"exhaustive"`, `"ivf"`, `"hnsw"`, `"nndescent"`, `"annoy"`,
    ///   `"kmknn"` or `"balltree"`.
    /// * `initialisation` - Embedding initialisation method: `"pca"`,
    ///   `"random"`, or `"spectral"`.
    /// * `init_range` - Optional initialisation range to fix the initial
    ///   embedding between certain values.
    /// * `nn_params` - Nearest neighbour parameters.
    /// * `optim_params` - t-SNE optimisation parameters. These cover the
    ///   learning rate, number of epochs, early/late exaggeration, the
    ///   Barnes-Hut `theta`, and the number of FFT interpolation points.
    /// * `randomised_init` - Whether randomised SVD is used for PCA
    ///   initialisation.
    ///
    /// ### Returns
    ///
    /// A fully specified set of t-SNE parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        perplexity: T,
        ann_type: String,
        initialisation: String,
        init_range: Option<T>,
        nn_params: NearestNeighbourParams<T>,
        optim_params: TsneOptimParams<T>,
        randomised_init: bool,
    ) -> Self {
        Self {
            n_dim,
            perplexity,
            ann_type,
            initialisation,
            init_range,
            nn_params,
            optim_params,
            randomised_init,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `perplexity`, the
    /// characteristic t-SNE knob controlling neighbourhood size.
    ///
    /// ### Params
    ///
    /// * `perplexity` - Perplexity parameter (typical: 5-50). Defaults to
    ///   `30.0`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation.
    pub fn new_default_2d(perplexity: Option<T>) -> Self {
        let perplexity = perplexity.unwrap_or_else(|| T::from_f64(30.0).unwrap());

        Self {
            perplexity,
            ..Self::default()
        }
    }
}

/// Construct affinity graph for t-SNE from high-dimensional data
///
/// Performs the following steps:
///
/// 1. Runs k-nearest neighbour search where k = 3 × perplexity
/// 2. Computes Gaussian affinities P(j|i) via binary search for target entropy
/// 3. Symmetrises to joint probabilities: P_ij = (P(j|i) + P(i|j)) / 2N
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed k-nearest neighbours and distances. Needs
///   to be a tuple of `(Vec<Vec<usize>>, Vec<Vec<T>>)` with indices and
///   distances excluding self.
/// * `perplexity` - Target perplexity (effective number of neighbours,
///   typical: 5-50)
/// * `ann_type` - (Approximate) Nearest neighbour method: `"exhaustive"`,
///   `"kmknn"`, `"balltree"`, `"annoy"`, `"hnsw"`, or `"nndescent"`. If you
///   provide a weird string, the function will default to `"kmknn"`
/// * `nn_params` - Nearest neighbour search parameters
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Tuple of:
///
/// - `CoordinateList<T>` containing symmetric joint probabilities P_ij
/// - `Vec<Vec<usize>>` k-nearest neighbour indices for each point
/// - `Vec<Vec<T>>` k-nearest neighbour distances for each point
///
/// # Notes
///
/// The k value is automatically set to `3 × perplexity`, clamped between 5 and
/// n-1. This is standard practice in t-SNE implementations.
pub fn construct_tsne_graph<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    perplexity: T,
    ann_type: String,
    nn_params: &NearestNeighbourParams<T>,
    seed: usize,
    verbose: usize,
) -> TsneGraph<T>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    let (knn_indices, knn_dist) = match precomputed_knn {
        Some((indices, distances)) => {
            if verbosity.normal_verbosity() {
                println!("Using precomputed kNN graph...");
            }
            (indices, distances)
        }
        None => {
            let k_float = perplexity * T::from_f64(3.0).unwrap();
            let k = k_float.to_usize().unwrap().max(5).min(data.nrows() - 1);

            if verbosity.normal_verbosity() {
                println!("Running kNN search (k={}) using {}...", k, ann_type);
            }

            let start_knn = Instant::now();
            let result = run_ann_search(data, k, ann_type, nn_params, seed, verbose)?;

            if verbosity.normal_verbosity() {
                println!("kNN search done in: {:.2?}.", start_knn.elapsed());
            }

            result
        }
    };

    if verbosity.normal_verbosity() {
        println!("Computing Gaussian affinities and symmetrising...");
    }

    let start_graph = Instant::now();

    let directed_graph = gaussian_knn_affinities(
        &knn_indices,
        &knn_dist,
        perplexity,
        T::from_f64(1e-5).unwrap(),
        200,
        nn_params.dist_metric == "euclidean",
    )?;

    let graph = symmetrise_affinities_tsne(directed_graph);

    if verbosity.normal_verbosity() {
        println!(
            "Finalised graph generation in {:.2?}.",
            start_graph.elapsed()
        );
    }

    Ok((graph, knn_indices, knn_dist))
}

/// Run t-SNE dimensionality reduction
///
/// t-Distributed Stochastic Neighbour Embedding (t-SNE) is a technique for
/// visualising high-dimensional data by reducing it to 2 dimensions. This
/// version supports both Barnes-Hut approximation and FFT-accelerated
/// interpolation for repulsive forces.
///
/// ### Algorithm
///
/// 1. Construct high-dimensional affinity graph via Gaussian kernels
///    - k-NN search with k = 3 × perplexity
///    - Binary search for precision to match target perplexity
///    - Symmetrise to joint probabilities P_ij
/// 2. Initialise low-dimensional embedding (typically via PCA)
/// 3. Optimise embedding via gradient descent
///    - Attractive forces: exact computation from graph
///    - Repulsive forces: Barnes-Hut approximation or FFT-accelerated
///      interpolation.
///    - Early exaggeration (first 250 iterations)
///    - Momentum switching at iteration 250
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed k-nearest neighbours and distances. Needs
///   to be a tuple of `(Vec<Vec<usize>>, Vec<Vec<T>>)` with indices and
///   distances excluding self.
/// * `params` - t-SNE parameters controlling algorithm behaviour
/// * `approx_type` - Type of approximation to use for repulsive forces.
///   Options: `"barnes_hut" | "bh"`, `"fft"`
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding coordinates as `Vec<Vec<T>>` where outer vector has length
/// `n_dim` and inner vectors have length `n_samples`. Each outer element
/// represents one embedding dimension.
///
/// ### References
///
/// - van der Maaten & Hinton (2008): "Visualizing Data using t-SNE"
/// - van der Maaten (2014): "Accelerating t-SNE using Tree-Based Algorithms"
/// - Linderman et al. (2019): " Fast interpolation-based t-SNE for improved
///   visualization of single-cell RNA-seq data"
#[cfg(feature = "fft_tsne")]
pub fn tsne<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    params: &TsneParams<T>,
    approx_type: &str,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat + FftwFloat,
    HnswIndex<T>: HnswState<T>,
    StandardNormal: Distribution<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    if params.n_dim != 2 {
        return Err(ManifoldsError::IncorrectDim {
            n_dim: params.n_dim,
        });
    }

    let verbosity = parse_verbosity_level(verbose);

    // 1. graph construction
    let (graph, _, _) = construct_tsne_graph(
        data,
        precomputed_knn,
        params.perplexity,
        params.ann_type.clone(),
        &params.nn_params,
        seed,
        verbose,
    )?;

    if verbosity.normal_verbosity() {
        println!("Initialising embedding via {}...", &params.initialisation);
    }

    // 2. initialise embedding
    let init_type = parse_initilisation(
        &params.initialisation,
        params.randomised_init,
        params.init_range,
    )
    .unwrap_or_else(|| {
        println!(
            "Unknown initialisation provided: {:?}. Defaulting to PCA.",
            params.initialisation,
        );
        EmbdInit::PcaInit {
            range: Some(T::from_f64(1e-2).unwrap()),
            randomised: true,
        }
    });

    let mut embd = initialise_embedding(&init_type, params.n_dim, seed as u64, &graph, data)?;

    // parse the optimisation type
    let tsne_approx = parse_tsne_optimiser(approx_type).unwrap_or_default();

    // 3. optimise
    let start_optim = Instant::now();
    match tsne_approx {
        TsneOpt::BarnesHut => {
            if verbosity.normal_verbosity() {
                println!(
                    "Optimising via Barnes-Hut t-SNE ({} epochs)...",
                    params.optim_params.n_epochs
                );
            }
            optimise_bh_tsne(&mut embd, &params.optim_params, &graph, verbose);
        }
        #[cfg(feature = "fft_tsne")]
        TsneOpt::Fft => {
            if verbosity.normal_verbosity() {
                println!(
                    "Optimising via FFT Interpolation-based t-SNE ({} epochs)...",
                    params.optim_params.n_epochs
                );
            }
            let _ = optimise_fft_tsne(&mut embd, &params.optim_params, &graph, verbose);
        }
    }

    if verbosity.normal_verbosity() {
        println!("Optimisation complete in {:.2?}.", start_optim.elapsed());
    }

    // 4. transpose output: [n_samples][n_dim] → [n_dim][n_samples]
    let n_samples = embd.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; params.n_dim];

    for sample_idx in 0..n_samples {
        for dim_idx in 0..params.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}

/// Run t-SNE dimensionality reduction
///
/// t-Distributed Stochastic Neighbour Embedding (t-SNE) is a technique for
/// visualising high-dimensional data by reducing it to 2 dimensions. This
/// version supports both Barnes-Hut approximation and FFT-accelerated
/// interpolation for repulsive forces.
///
/// ### Algorithm
///
/// 1. Construct high-dimensional affinity graph via Gaussian kernels
///    - k-NN search with k = 3 × perplexity
///    - Binary search for precision to match target perplexity
///    - Symmetrise to joint probabilities P_ij
/// 2. Initialise low-dimensional embedding (typically via PCA)
/// 3. Optimise embedding via gradient descent
///    - Attractive forces: exact computation from graph
///    - Repulsive forces: Barnes-Hut approximation or FFT-accelerated
///      interpolation.
///    - Early exaggeration (first 250 iterations)
///    - Momentum switching at iteration 250
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed k-nearest neighbours and distances. Needs
///   to be a tuple of `(Vec<Vec<usize>>, Vec<Vec<T>>)` with indices and
///   distances excluding self.
/// * `params` - t-SNE parameters controlling algorithm behaviour
/// * `approx_type` - Type of approximation to use for repulsive forces.
///   Options: `"barnes_hut" | "bh"`, `"fft"`
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding coordinates as `Vec<Vec<T>>` where outer vector has length
/// `n_dim` and inner vectors have length `n_samples`. Each outer element
/// represents one embedding dimension.
///
/// ### References
///
/// - van der Maaten & Hinton (2008): "Visualizing Data using t-SNE"
/// - van der Maaten (2014): "Accelerating t-SNE using Tree-Based Algorithms"
/// - Linderman et al. (2019): " Fast interpolation-based t-SNE for improved
///   visualization of single-cell RNA-seq data"
#[cfg(not(feature = "fft_tsne"))]
pub fn tsne<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    params: &TsneParams<T>,
    approx_type: &str,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    StandardNormal: Distribution<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    if params.n_dim != 2 {
        return Err(ManifoldsError::IncorrectDim {
            n_dim: params.n_dim,
        });
    }
    let verbosity = parse_verbosity_level(verbose);

    // 1. graph construction
    let (graph, _, _) = construct_tsne_graph(
        data,
        precomputed_knn,
        params.perplexity,
        params.ann_type.clone(),
        &params.nn_params,
        seed,
        verbose,
    )?;

    // 2. initialise embedding
    if verbosity.normal_verbosity() {
        println!("Initialising embedding via {}...", &params.initialisation);
    }

    let init_type = parse_initilisation(
        &params.initialisation,
        params.randomised_init,
        params.init_range,
    )
    .unwrap_or_else(|| {
        println!(
            "Unknown initialisation provided: {:?}. Defaulting to PCA.",
            params.initialisation,
        );
        EmbdInit::PcaInit {
            range: Some(T::from_f64(1e-2).unwrap()),
            randomised: true,
        }
    });

    let mut embd = initialise_embedding(&init_type, params.n_dim, seed as u64, &graph, data)?;

    // parse the optimisation type
    let tsne_approx = parse_tsne_optimiser(approx_type).unwrap_or_default();

    // 3. optimise
    let start_optim = Instant::now();
    match tsne_approx {
        TsneOpt::BarnesHut => {
            if verbosity.normal_verbosity() {
                println!(
                    "Optimising via Barnes-Hut t-SNE ({} epochs)...",
                    params.optim_params.n_epochs
                );
            }
            optimise_bh_tsne(&mut embd, &params.optim_params, &graph, verbose);
        }
        #[cfg(not(feature = "fft_tsne"))]
        TsneOpt::Fft => {
            panic!("FFT-accelerated t-SNE not available. Recompile with 'fft_tsne' feature or use 'barnes_hut' approximation.");
        }
    }

    if verbosity.normal_verbosity() {
        println!("Optimisation complete in {:.2?}.", start_optim.elapsed());
    }

    // 4. transpose output: [n_samples][n_dim] → [n_dim][n_samples]
    let n_samples = embd.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; params.n_dim];

    for sample_idx in 0..n_samples {
        for dim_idx in 0..params.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}

///////////
// PHATE //
///////////

/// PHATE parameters
#[derive(Debug, Clone)]
pub struct PhateParams<T> {
    /// Number of output dimensions (default: 2)
    pub n_dim: usize,
    /// Number of neighbours to use
    pub k: usize,
    /// (Approximate) Nearest neighbour method. One of `"exhaustive"`, `"ivf"`,
    /// `"hnsw"`, `"nndescent"`, `"annoy"`, `"kmknn"`, or `"balltree"`.
    pub ann_type: String,
    /// Nearest neighbour search parameters to use
    pub ann_params: NearestNeighbourParams<T>,
    /// Diffusion parameters to use
    pub diffusion_params: PhateDiffusionParams<T>,
    /// Which MDS implementation to use
    pub mds_method: String,
    /// Optional number of iterations for MDS fitting
    pub mds_iter: Option<usize>,
    /// Shall randomised SVD be used for PCA-based initialisation
    pub randomised: bool,
}

impl<T> Default for PhateParams<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        let diffusion_params = PhateDiffusionParams::new(
            Some(T::from_f64(40.0).unwrap()),
            T::from_f64(1.0).unwrap(),
            T::from_f64(1e-4).unwrap(),
            "average".to_string(),
            None,
            "spectral".to_string(),
            None,
            None,
            None,
            T::from_f64(1.0).unwrap(),
        );

        Self {
            n_dim: 2,
            k: 5,
            ann_type: "kmknn".to_string(),
            ann_params: NearestNeighbourParams::default(),
            diffusion_params,
            mds_method: "sgd_dense".to_string(),
            mds_iter: None,
            randomised: true,
        }
    }
}

impl<T> PhateParams<T>
where
    T: ManifoldsFloat,
{
    /// Create new PHATE parameters with full control over every field.
    ///
    /// This constructor exposes every field directly, including the
    /// diffusion parameters. For sensible defaults, use
    /// [`PhateParams::default`] or [`PhateParams::new_default_2d`] instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - Number of output dimensions.
    /// * `k` - Number of nearest neighbours.
    /// * `ann_type` - (Approximate) nearest neighbour method. One of
    ///   `"exhaustive"`, `"ivf"`, `"hnsw"`, `"nndescent"`, `"annoy"`,
    ///   `"kmknn"` or `"balltree"`.
    /// * `ann_params` - Nearest neighbour search parameters.
    /// * `diffusion_params` - Diffusion parameters. These cover the alpha
    ///   decay, kernel bandwidth scaling, graph symmetry, landmarks, SVD
    ///   components, diffusion time selection, and the informational distance
    ///   constant `gamma`.
    /// * `mds_method` - Which MDS implementation to use, e.g. `"sgd_dense"`.
    /// * `mds_iter` - Optional number of iterations for MDS fitting; `None`
    ///   uses the MDS default.
    /// * `randomised` - Whether randomised SVD is used for PCA-based
    ///   initialisation.
    ///
    /// ### Returns
    ///
    /// A fully specified set of PHATE parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        k: usize,
        ann_type: String,
        ann_params: NearestNeighbourParams<T>,
        diffusion_params: PhateDiffusionParams<T>,
        mds_method: String,
        mds_iter: Option<usize>,
        randomised: bool,
    ) -> Self {
        Self {
            n_dim,
            k,
            ann_type,
            ann_params,
            diffusion_params,
            mds_method,
            mds_iter,
            randomised,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `k`, the number of
    /// nearest neighbours used to build the affinity graph.
    ///
    /// ### Params
    ///
    /// * `k` - Number of nearest neighbours. Defaults to `5`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation.
    pub fn new_default_2d(k: Option<usize>) -> Self {
        let k = k.unwrap_or(5);

        Self {
            k,
            ..Self::default()
        }
    }
}

/////////////////////
// PHATE diffusion //
/////////////////////

/// Build the PHATE diffusion operator from high-dimensional data
///
/// Runs kNN search (or uses precomputed results), computes alpha decay
/// affinities, and constructs either a full or landmark diffusion operator
/// depending on `phate_params.n_landmarks`.
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `k` - Number of nearest neighbours for graph construction
/// * `precomputed_knn` - Precomputed kNN indices and distances as
///   `Some((Vec<Vec<usize>>, Vec<Vec<T>>))`, or `None` to run search
///   internally. Indices and distances must exclude self.
/// * `ann_type` - (Approximate) Nearest neighbour method: `"exhaustive"`,
///   `"kmknn"`, `"balltree"`, `"annoy"`, `"hnsw"`, or `"nndescent"`. If you
///   provide a weird string, the function will default to `"kmknn"`
/// * `nn_params` - Nearest neighbour search parameters
/// * `phate_params` - Full PHATE parameter struct (uses `k`, `decay`,
///   `bandwidth_scale`, `thresh`, `symmetrise`, `n_landmarks`,
///   `landmark_mode`)
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// `PhateDiffusion::Full { operator }` when `n_landmarks` is `None` or
/// \>= N, otherwise `PhateDiffusion::Landmark { landmarks }` containing
/// the compressed landmark operator and interpolation matrices.
#[allow(clippy::too_many_arguments)]
pub fn construct_phate_diffusion<T>(
    data: MatRef<T>,
    k: usize,
    precomputed_knn: PreComputedKnn<T>,
    ann_type: &str,
    nn_params: &NearestNeighbourParams<T>,
    phate_params: &PhateParams<T>,
    seed: usize,
    verbose: usize,
) -> Result<PhateDiffusion<T>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    let (knn_indices, knn_dist) = match precomputed_knn {
        Some((indices, distances)) => {
            if verbosity.normal_verbosity() {
                println!("Using precomputed kNN graph...");
            }
            (indices, distances)
        }
        None => {
            if verbosity.normal_verbosity() {
                println!(
                    "Running (approximate) nearest neighbour search using {}...",
                    ann_type
                );
            }
            let start_knn = Instant::now();
            let result = run_ann_search(data, k, ann_type.to_string(), nn_params, seed, verbose)?;
            if verbosity.normal_verbosity() {
                println!("kNN search done in: {:.2?}.", start_knn.elapsed());
            }
            result
        }
    };

    if verbosity.normal_verbosity() {
        println!("Calculating alpha decay affinities");
    }
    let start_alpha_affinities = Instant::now();

    let graph = phate_alpha_decay_affinities(
        &knn_indices,
        &knn_dist,
        phate_params.k,
        phate_params.diffusion_params.decay,
        phate_params.diffusion_params.bandwidth_scale,
        phate_params.diffusion_params.thresh,
        &phate_params.diffusion_params.graph_symmetry,
        nn_params.dist_metric == "euclidean",
    );

    if verbosity.normal_verbosity() {
        println!(
            "Alpha decay affinity calculations done in: {:.2?}.",
            start_alpha_affinities.elapsed()
        );
    }

    let affinity = coo_to_csr(&graph);
    let diffusion_op = build_diffusion_operator(&affinity);

    match phate_params.diffusion_params.n_landmarks {
        None => Ok(PhateDiffusion::Full {
            operator: diffusion_op,
        }),
        Some(n_landmarks) if n_landmarks >= data.nrows() => Ok(PhateDiffusion::Full {
            operator: diffusion_op,
        }),
        Some(n_landmarks) => {
            if verbosity.normal_verbosity() {
                println!(" Building {} landmarks...", n_landmarks);
            }
            let start_landmarks = Instant::now();
            let landmarks = PhateLandmarks::build(
                data,
                &affinity,
                &diffusion_op,
                n_landmarks,
                &phate_params.diffusion_params.landmark_method,
                &nn_params.dist_metric,
                seed,
                Some(100),
                verbose,
            )?;
            if verbosity.normal_verbosity() {
                println!(
                    " Landmarks generated in: {:.2?}.",
                    start_landmarks.elapsed()
                );
            }
            Ok(PhateDiffusion::Landmark { landmarks })
        }
    }
}

/// Run PHATE dimensionality reduction
///
/// Potential of Heat-diffusion for Affinity-based Transition Embedding
/// (PHATE) learns a low-dimensional embedding that preserves the
/// diffusion geometry of the data.
///
/// ### Algorithm
///
/// 1. Build affinity graph via alpha decay kernel on kNN distances
/// 2. Construct row-stochastic diffusion operator P = D^{-1} K
/// 3. Determine diffusion time t (knee of Von Neumann entropy, or fixed)
/// 4. Compute diffusion potential: log transformation of P^t by default
/// 5. Embed via MDS on pairwise potential distances
///
/// Steps 2–4 optionally operate on a compressed landmark representation
/// (N × L instead of N × N) when `phate_params.n_landmarks` is set.
/// Pairwise distances and MDS (step 5) always run in the full N × N space;
/// however, to avoid holding the full N x N matrix in memory, you can
/// use a streaming version of MDS that computes the distances on the fly.
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed kNN indices and distances as
///   `Some((Vec<Vec<usize>>, Vec<Vec<T>>))`, or `None` to run search
///   internally. Indices and distances must exclude self.
/// * `phate_params` - PHATE parameters. See `PhateParams` for full
///   documentation of each field.
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding coordinates as `Vec<Vec<T>>` where the outer vector has
/// length `n_dim` and each inner vector has length `n_samples`. Each
/// outer element represents one embedding dimension.
///
/// ### References
///
/// - Moon et al. (2019): "Visualizing Structure and Transitions in
///   High-Dimensional Biological Data" (Nature Biotechnology)
pub fn phate<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    phate_params: PhateParams<T>,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
    StandardNormal: Distribution<T>,
{
    let start_phate = Instant::now();
    let verbosity = parse_verbosity_level(verbose);

    let phate_diffusion = construct_phate_diffusion(
        data,
        phate_params.k,
        precomputed_knn,
        &phate_params.ann_type,
        &phate_params.ann_params,
        &phate_params,
        seed,
        verbose,
    )?;

    let start_t = Instant::now();
    let t = match phate_params.diffusion_params.t {
        PhateTime::Auto { t_max } => {
            if verbosity.normal_verbosity() {
                println!("Finding optimal t (t_max={})...", t_max);
            }
            match &phate_diffusion {
                PhateDiffusion::Landmark { landmarks } => landmarks.find_optimal_t(t_max),
                PhateDiffusion::Full { operator } => {
                    let entropy = landmark_von_neumann_entropy(operator, t_max)?;
                    Ok(find_knee_point(&entropy))
                }
            }
        }
        PhateTime::Fixed(t) => Ok(t),
    }?;
    if verbosity.normal_verbosity() {
        println!("Identified t = {} in {:.2?}.", t, start_t.elapsed());
    }

    let mds_method = parse_mds_method(&phate_params.mds_method).unwrap_or_default();
    let dist = parse_ann_dist(&phate_params.ann_params.dist_metric).unwrap_or_default();
    let mds_params = MdsOptimParams::new(
        data.nrows(),
        phate_params.randomised,
        phate_params.mds_iter,
        None,
    );

    let start_embed = Instant::now();

    let embedding = match phate_diffusion {
        PhateDiffusion::Full { operator } => {
            if verbosity.normal_verbosity() {
                println!("Powering diffusion operator...");
            }
            let powered = matrix_power(&operator, t)?;
            let potential = calculate_potential(&powered, 1, phate_params.diffusion_params.gamma)?;

            if verbosity.normal_verbosity() {
                println!(
                    "Potential shape: {} × {} - calculated in {:.2?}.",
                    potential.shape().0,
                    potential.shape().1,
                    start_embed.elapsed()
                );
            }

            let res = match mds_method {
                MdsMethod::ClassicMds => {
                    if verbosity.normal_verbosity() {
                        println!("Computing pairwise distances, running classic MDS...");
                    }
                    let distances = compute_potential_distances(&potential, &dist);
                    classic_mds(&distances, phate_params.n_dim, mds_params.randomised, seed)
                }
                MdsMethod::SgdDense => {
                    if verbosity.normal_verbosity() {
                        println!("Computing pairwise distances, running SGD-MDS...");
                    }
                    let distances = compute_potential_distances(&potential, &dist);
                    sgd_mds(
                        &distances,
                        phate_params.n_dim,
                        &mds_params,
                        None,
                        seed,
                        verbose,
                    )
                }
            }?;

            res
        }
        PhateDiffusion::Landmark { landmarks } => {
            if verbosity.normal_verbosity() {
                println!(
                    "Powering landmark operator ({} landmarks)...",
                    landmarks.get_n_landmarks()
                );
            }
            let landmark_powered = landmarks.power(t)?;
            let landmark_potential =
                calculate_potential(&landmark_powered, 1, phate_params.diffusion_params.gamma)?;

            if verbosity.normal_verbosity() {
                println!(
                    "Landmark potential shape: {} × {} - calculated in {:.2?}.",
                    landmark_potential.shape().0,
                    landmark_potential.shape().1,
                    start_embed.elapsed()
                );
                println!("Computing landmark pairwise distances...");
            }

            let landmark_distances = compute_potential_distances(&landmark_potential, &dist);

            let landmark_mds_params = MdsOptimParams::new(
                landmarks.get_n_landmarks(),
                phate_params.randomised,
                None,
                None,
            );

            if verbosity.normal_verbosity() {
                println!("Running MDS on landmarks...");
            }

            let landmark_embedding = match mds_method {
                MdsMethod::ClassicMds => classic_mds(
                    &landmark_distances,
                    phate_params.n_dim,
                    landmark_mds_params.randomised,
                    seed,
                ),
                _ => sgd_mds(
                    &landmark_distances,
                    phate_params.n_dim,
                    &landmark_mds_params,
                    None,
                    seed,
                    verbose,
                ),
            }?;

            if verbosity.normal_verbosity() {
                println!("Interpolating to full N points via Nyström...");
            }
            landmarks.interpolate_embedding(&landmark_embedding)
        }
    };

    if verbosity.normal_verbosity() {
        println!("Ran MDS in {:.2?}.", start_embed.elapsed());
        println!("Finished running PHATE in {:.2?}.", start_phate.elapsed());
    }

    let n_samples = embedding.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; phate_params.n_dim];
    for i in 0..n_samples {
        for d in 0..phate_params.n_dim {
            transposed[d][i] = embedding[i][d];
        }
    }

    Ok(transposed)
}

////////////
// PaCMAP //
////////////

////////////
// Params //
////////////

/// Parameters for PaCMAP dimensionality reduction.
#[derive(Debug, Clone)]
pub struct PacmapParams<T> {
    /// Output dimensionality. Default 2.
    pub n_dim: usize,
    /// Number of near neighbours. Default 10 (paper default; lower than UMAP's
    /// 15 since PaCMAP is less sensitive to k).
    pub k: usize,
    /// (Approximate) Nearest neighbour method. One of `"exhaustive"`, `"ivf"`,
    /// `"hnsw"`, `"nndescent"`, `"annoy"`, `"kmknn"` or `"balltree"`.
    pub ann_type: String,
    /// Which optimiser to use. Options are `"adam"` and `"adam_parallel"`
    pub optimiser_type: String,
    /// Mid-near pairs per point. Default 2.
    pub n_mid_near: usize,
    /// Further (random) pairs per point. Default 2.
    pub n_further: usize,
    /// Start index into kNN list for mid-near candidate window. Default 4
    /// (skip the 4 nearest).
    pub mn_candidate_start: usize,
    /// End index into kNN list for mid-near candidate window. Default 50.
    /// Requires k >= this value.
    pub mn_candidate_end: usize,
    /// Embedding initialisation. Default `"pca"`. PCA is strongly recommended
    /// for PaCMAP as random init degrades global structure.
    pub initialisation: String,
    /// Nearest neighbour search parameters.
    pub nn_params: NearestNeighbourParams<T>,
    /// Optimiser parameters.
    pub optim_params: PacmapOptimParams<T>,
}

impl<T> Default for PacmapParams<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            k: 50,
            ann_type: "kmknn".to_string(),
            optimiser_type: "adam_parallel".to_string(),
            n_mid_near: 2,
            n_further: 2,
            mn_candidate_start: 4,
            mn_candidate_end: 50,
            initialisation: "pca".to_string(),
            nn_params: NearestNeighbourParams::default(),
            optim_params: PacmapOptimParams::default(),
        }
    }
}

impl<T> PacmapParams<T>
where
    T: ManifoldsFloat,
{
    /// Generate a new instance of the PaCMAP parameters with full control over
    /// every field.
    ///
    /// For sensible defaults, use [`PacmapParams::default`] or
    /// [`PacmapParams::new_default_2d`] instead.
    ///
    /// Note: `k` is clamped to at least `mn_candidate_end`, since the mid-near
    /// candidate window indexes into the kNN list and must not run past its
    /// end.
    ///
    /// ### Params
    ///
    /// * `n_dim` - Number of dimensions for the embedding.
    /// * `k` - Number of near neighbours. Clamped to at least
    ///   `mn_candidate_end`.
    /// * `ann_type` - (Approximate) nearest neighbour method. One of
    ///   `"exhaustive"`, `"ivf"`, `"hnsw"`, `"nndescent"`, `"annoy"`,
    ///   `"kmknn"` or `"balltree"`.
    /// * `optimiser_type` - Which optimiser to use. Options are `"adam"` and
    ///   `"adam_parallel"`.
    /// * `n_mid_near` - Mid-near pairs per point.
    /// * `n_further` - Further (random) pairs per point.
    /// * `mn_candidate_start` - Start index into the kNN list for the mid-near
    ///   candidate window.
    /// * `mn_candidate_end` - End index into the kNN list for the mid-near
    ///   candidate window. Requires `k >= this value`.
    /// * `initialisation` - Embedding initialisation. PCA is strongly
    ///   recommended for PaCMAP as random init degrades global structure.
    /// * `nn_params` - Nearest neighbour search parameters.
    /// * `optim_params` - Optimiser parameters.
    ///
    /// ### Returns
    ///
    /// A fully specified set of PaCMAP parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        k: usize,
        ann_type: String,
        optimiser_type: String,
        n_mid_near: usize,
        n_further: usize,
        mn_candidate_start: usize,
        mn_candidate_end: usize,
        initialisation: String,
        nn_params: NearestNeighbourParams<T>,
        optim_params: PacmapOptimParams<T>,
    ) -> Self {
        let k = k.max(mn_candidate_end);

        Self {
            n_dim,
            k,
            ann_type,
            optimiser_type,
            n_mid_near,
            n_further,
            mn_candidate_start,
            mn_candidate_end,
            initialisation,
            nn_params,
            optim_params,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `k`, the number of
    /// near neighbours. Note that `k` is clamped to at least
    /// `mn_candidate_end` (default `50`).
    ///
    /// ### Params
    ///
    /// * `k` - Number of near neighbours. Defaults to `50`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation.
    pub fn new_default_2d(k: Option<usize>) -> Self {
        let default = Self::default();
        let k = k.unwrap_or(default.k).max(default.mn_candidate_end);

        Self { k, ..default }
    }
}

//////////
// Main //
//////////

/// Run PaCMAP dimensionality reduction.
///
/// Pairwise Controlled Manifold Approximation (PaCMAP) is a dimensionality
/// reduction method that explicitly balances local and global structure
/// preservation via three pair types and a phased optimisation schedule.
///
/// 1. Find k-nearest neighbours
/// 2. Construct near, mid-near, and further pairs
/// 3. Initialise embedding (PCA strongly recommended)
/// 4. Optimise via three-phase Adam with pair-type weight schedule
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features).
/// * `precomputed_knn` - Optional precomputed kNN. Must have been computed
///   with k >= `params.mn_candidate_end` to support mid-near sampling.
/// * `params` - PaCMAP parameters.
/// * `seed` - Seed for reproducibility.
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding as `Vec<Vec<T>>` with shape `[n_dim][n_samples]`.
pub fn pacmap<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    params_pacmap: &PacmapParams<T>,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    StandardNormal: Distribution<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let n_samples = data.nrows();

    let verbosity = parse_verbosity_level(verbose);

    let (knn_indices, _) = match precomputed_knn {
        Some((indices, distances)) => {
            if verbosity.normal_verbosity() {
                println!("Using precomputed kNN graph...");
            }
            (indices, distances)
        }
        None => {
            if verbosity.normal_verbosity() {
                println!(
                    "Running (approximate) nearest neighbour search using {} (k={})...",
                    params_pacmap.ann_type, params_pacmap.k
                );
            }
            let start_knn = Instant::now();
            let result = run_ann_search(
                data,
                params_pacmap.k,
                params_pacmap.ann_type.clone(),
                &params_pacmap.nn_params,
                seed,
                verbose,
            )?;
            if verbosity.normal_verbosity() {
                println!("kNN search done in: {:.2?}.", start_knn.elapsed());
            }
            result
        }
    };

    if verbosity.normal_verbosity() {
        println!("Constructing PaCMAP pairs...");
    }

    let start_pairs = Instant::now();

    let pairs: PacmapPairs = construct_pacmap_pairs(
        &knn_indices,
        params_pacmap.n_mid_near,
        params_pacmap.n_further,
        params_pacmap.mn_candidate_start,
        params_pacmap.mn_candidate_end,
        seed as u64,
    );

    let end_pairs = start_pairs.elapsed();

    if verbosity.normal_verbosity() {
        println!(
            "Pairs generated in {:.2?}: {} near, {} mid-near, {} further.",
            end_pairs,
            pairs.near.len().separate_with_underscores(),
            pairs.mid_near.len().separate_with_underscores(),
            pairs.further.len().separate_with_underscores()
        );
    }

    let init_type =
        parse_initilisation(&params_pacmap.initialisation, true, None).unwrap_or_else(|| {
            println!(
                "Unknown initialisation provided: {:?}. Defaulting to PCA.",
                params_pacmap.initialisation,
            );
            EmbdInit::PcaInit {
                range: None,
                randomised: true,
            }
        });

    if verbosity.normal_verbosity() {
        println!(
            "Initialising embedding via {} layout...",
            params_pacmap.initialisation
        );
    }

    let dummy_graph = knn_to_coo_unweighted(&knn_indices);
    let mut embd = initialise_embedding(
        &init_type,
        params_pacmap.n_dim,
        seed as u64,
        &dummy_graph,
        data,
    )?;

    let optimiser = parse_pacmap_optimiser(&params_pacmap.optimiser_type).unwrap_or_default();

    let start_optim = Instant::now();

    match optimiser {
        PacMapOptimiser::AdamParallel => {
            let _ =
                optimise_pacmap_parallel(&mut embd, &pairs, &params_pacmap.optim_params, verbose);
        }
        PacMapOptimiser::Adam => {
            let _ = optimise_pacmap(&mut embd, &pairs, &params_pacmap.optim_params, verbose);
        }
    }

    let end_optim = start_optim.elapsed();

    if verbosity.normal_verbosity() {
        println!("Optimisation done in {:.2?}.", end_optim);
        println!("PaCMAP complete!");
    }

    // transpose from [n_samples][n_dim] to [n_dim][n_samples]
    let mut transposed = vec![vec![T::zero(); n_samples]; params_pacmap.n_dim];
    for sample_idx in 0..n_samples {
        for dim_idx in 0..params_pacmap.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}

////////////////////
// Diffusion maps //
////////////////////

/// Parameters for classical diffusion maps (Coifman & Lafon, 2006).
#[derive(Debug, Clone)]
pub struct DiffusionMapsParams<T> {
    /// Output embedding dimensionality (default: 2)
    pub n_dim: usize,
    /// Number of nearest neighbours used to build the graph
    pub k: usize,
    /// ANN algorithm name (see `NearestNeighbourParams`)
    pub ann_type: String,
    /// Nearest neighbour search parameters
    pub ann_params: NearestNeighbourParams<T>,
    /// Multiplicative factor applied to the adaptive kernel bandwidth
    pub bandwidth_scale: T,
    /// Sparsity threshold applied to kernel entries
    pub thresh: T,
    /// Graph symmetrisation: `"add"`, `"multiply"`, `"mnn"` or `"none"`
    pub graph_symmetry: String,
    /// Anisotropic density-correction exponent in [0, 1]. 0 gives the
    /// normalised graph Laplacian, 0.5 the Fokker-Planck operator, 1 the
    /// Laplace-Beltrami operator.
    pub alpha_norm: T,
    /// Diffusion time: `Auto` picks the VNE knee, `Fixed(t)` uses `t` directly.
    pub t: PhateTime,
    /// Landmark count. `None` or `>= n` runs full DM.
    pub n_landmarks: Option<usize>,
    /// `"random"`, `"spectral"` or `"density"`
    pub landmark_method: String,
    /// Components for spectral landmark selection (ignored otherwise)
    pub n_svd: Option<usize>,
}

impl<T> Default for DiffusionMapsParams<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            k: 5,
            ann_type: "kmknn".to_string(),
            ann_params: NearestNeighbourParams::default(),
            bandwidth_scale: T::from_f64(1.0).unwrap(),
            thresh: T::from_f64(1e-4).unwrap(),
            graph_symmetry: "add".to_string(),
            alpha_norm: T::from_f64(1.0).unwrap(),
            t: parse_phate_time(None, PHATE_MAX_T),
            n_landmarks: None,
            landmark_method: "spectral".to_string(),
            n_svd: None,
        }
    }
}

impl<T> DiffusionMapsParams<T>
where
    T: ManifoldsFloat,
{
    /// Construct a new `DiffusionMapsParams` with full control over every
    /// field.
    ///
    /// For sensible defaults, use [`DiffusionMapsParams::default`] or
    /// [`DiffusionMapsParams::new_default_2d`] instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - Output embedding dimensionality.
    /// * `k` - Number of nearest neighbours for graph construction.
    /// * `ann_type` - ANN algorithm: `"exhaustive"`, `"kmknn"`, `"balltree"`,
    ///   `"annoy"`, `"hnsw"`, or `"nndescent"`.
    /// * `ann_params` - Nearest neighbour search parameters.
    /// * `bandwidth_scale` - Multiplicative factor on the adaptive kernel
    ///   bandwidth.
    /// * `thresh` - Kernel entries below this value are set to zero.
    /// * `graph_symmetry` - Symmetrisation method: `"add"`, `"multiply"`,
    ///   `"mnn"` or `"none"`.
    /// * `alpha_norm` - Anisotropic normalisation exponent in [0, 1]. 0 gives
    ///   the normalised graph Laplacian, 0.5 the Fokker-Planck operator, 1 the
    ///   Laplace-Beltrami operator.
    /// * `t` - Diffusion time: `Auto` picks the VNE knee, `Fixed(t)` uses `t`
    ///   directly.
    /// * `n_landmarks` - Number of landmarks. `None` or `>= n` runs full DM.
    /// * `landmark_method` - `"random"`, `"spectral"`, or `"density"`.
    /// * `n_svd` - SVD components for spectral landmark selection. Ignored
    ///   otherwise.
    ///
    /// ### Returns
    ///
    /// A fully specified set of diffusion maps parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        k: usize,
        ann_type: String,
        ann_params: NearestNeighbourParams<T>,
        bandwidth_scale: T,
        thresh: T,
        graph_symmetry: String,
        alpha_norm: T,
        t: PhateTime,
        n_landmarks: Option<usize>,
        landmark_method: String,
        n_svd: Option<usize>,
    ) -> Self {
        Self {
            n_dim,
            k,
            ann_type,
            ann_params,
            bandwidth_scale,
            thresh,
            graph_symmetry,
            alpha_norm,
            t,
            n_landmarks,
            landmark_method,
            n_svd,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `k`, the number of
    /// nearest neighbours used to build the graph.
    ///
    /// ### Params
    ///
    /// * `k` - Number of nearest neighbours. Defaults to `5`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation.
    pub fn new_default_2d(k: Option<usize>) -> Self {
        let k = k.unwrap_or(5);

        Self {
            k,
            ..Self::default()
        }
    }
}

/// Full or landmark diffusion maps operator.
///
/// `Full` is used when no landmarks are requested or when the landmark count
/// meets or exceeds the data size. `Landmark` delegates eigendecomposition and
/// Nystroem extension to `DiffusionMapsLandmarks`.
pub enum DiffusionMapsOperator<T>
where
    T: ManifoldsFloat,
{
    /// Full N×N symmetric diffusion operator.
    Full {
        /// Symmetric diffusion operator P_sym = D^{-1/2} K D^{-1/2}
        p_sym: CompressedSparseData<T>,
        /// Square-root of node degrees; used to recover right eigenvectors
        /// of the row-stochastic operator from the symmetric ones
        sqrt_degrees: Vec<T>,
    },
    /// Landmark-based operator for large data sets.
    Landmark {
        /// Landmark operator ready for eigendecomposition and Nystroem extension
        landmarks: DiffusionMapsLandmarks<T>,
    },
}

/// Build the diffusion maps operator from raw data.
///
/// Runs kNN search, builds a Gaussian kernel via alpha-decay, applies
/// anisotropic normalisation, then returns either a full or landmark operator
/// depending on `dm_params.n_landmarks`. Falls back to full if
/// `n_landmarks >= n`.
///
/// ### Params
///
/// * `data` - Input data matrix (N × features)
/// * `k` - Number of nearest neighbours
/// * `precomputed_knn` - Optional precomputed kNN; skips search if provided
/// * `ann_type` - ANN algorithm name
/// * `nn_params` - Nearest neighbour search parameters
/// * `dm_params` - Diffusion maps parameters
/// * `seed` - RNG seed
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// `DiffusionMapsOperator` (full or landmark)
#[allow(clippy::too_many_arguments)]
pub fn construct_diffusion_maps_operator<T>(
    data: MatRef<T>,
    k: usize,
    precomputed_knn: PreComputedKnn<T>,
    ann_type: &str,
    nn_params: &NearestNeighbourParams<T>,
    dm_params: &DiffusionMapsParams<T>,
    seed: usize,
    verbose: usize,
) -> Result<DiffusionMapsOperator<T>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let use_full = match dm_params.n_landmarks {
        None => true,
        Some(n) => n >= data.nrows(),
    };

    let verbosity = parse_verbosity_level(verbose);

    let needs_affinity =
        use_full || matches!(dm_params.landmark_method.as_str(), "spectral" | "density");

    let affinity = if needs_affinity {
        let (knn_indices, knn_dist) = match precomputed_knn {
            Some((indices, distances)) => {
                if verbosity.normal_verbosity() {
                    println!("Using precomputed kNN graph...");
                }
                (indices, distances)
            }
            None => {
                if verbosity.normal_verbosity() {
                    println!(
                        "Running (approximate) nearest neighbour search using {}...",
                        ann_type
                    );
                }
                let start_knn = Instant::now();
                let res = run_ann_search(data, k, ann_type.to_string(), nn_params, seed, verbose)?;
                if verbosity.normal_verbosity() {
                    println!("kNN search done in {:.2?}.", start_knn.elapsed());
                }
                res
            }
        };

        if verbosity.normal_verbosity() {
            println!("Building Gaussian kernel affinities");
        }
        let graph = phate_alpha_decay_affinities(
            &knn_indices,
            &knn_dist,
            dm_params.k,
            Some(T::from_f64(2.0).unwrap()),
            dm_params.bandwidth_scale,
            dm_params.thresh,
            &dm_params.graph_symmetry,
            nn_params.dist_metric == "euclidean",
        );
        Some(coo_to_csr(&graph))
    } else {
        if verbosity.normal_verbosity() {
            println!("Skipping full affinity (random landmarks).");
        }
        None
    };

    if use_full {
        let kernel = affinity.unwrap();
        let kernel_norm = apply_anisotropic_normalisation(&kernel, dm_params.alpha_norm)?;
        let (p_sym, sqrt_degrees) = build_symmetric_diffusion_operator(&kernel_norm)?;
        return Ok(DiffusionMapsOperator::Full {
            p_sym,
            sqrt_degrees,
        });
    }

    let n_landmarks = dm_params.n_landmarks.unwrap();
    if verbosity.normal_verbosity() {
        println!(" Building {} landmarks...", n_landmarks);
    }
    let start_l = Instant::now();
    let landmarks = DiffusionMapsLandmarks::build(
        data,
        affinity.as_ref(),
        n_landmarks,
        &dm_params.landmark_method,
        &nn_params.dist_metric,
        dm_params.alpha_norm,
        dm_params.k,
        dm_params.bandwidth_scale,
        dm_params.thresh,
        &dm_params.graph_symmetry,
        seed,
        dm_params.n_svd,
        verbose,
    )?;
    if verbosity.normal_verbosity() {
        println!(" Landmarks built in {:.2?}.", start_l.elapsed());
    }
    Ok(DiffusionMapsOperator::Landmark { landmarks })
}

/// Run diffusion maps end-to-end.
///
/// 1. kNN graph on the raw data
/// 2. Gaussian kernel via alpha-decay with decay = 2 (adaptive bandwidth)
/// 3. Anisotropic (alpha) normalisation for density correction
/// 4. Symmetric diffusion operator P_sym = D^{-1/2} K D^{-1/2}
/// 5. Top (n_dim + 1) eigenpairs of P_sym via Lanczos
/// 6. Drop the trivial eigenvalue (= 1) and scale each non-trivial eigenvector
///    phi_k by lambda_k^t
///
/// With landmarks, steps 4–6 run on the L×L operator and are Nystroem-extended
/// back to N points.
///
/// ### Params
///
/// * `data` - Input data matrix (N × features)
/// * `precomputed_knn` - Optional precomputed kNN; skips search if provided.
///   Must have been computed with k >= `dm_params.k`.
/// * `dm_params` - Diffusion maps parameters
/// * `seed` - RNG seed
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding as `Vec<Vec<T>>` with shape `[n_dim][n_samples]`
pub fn diffusion_maps<T>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    dm_params: DiffusionMapsParams<T>,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    let start_dm = Instant::now();

    let verbosity = parse_verbosity_level(verbose);

    let op = construct_diffusion_maps_operator(
        data,
        dm_params.k,
        precomputed_knn,
        &dm_params.ann_type,
        &dm_params.ann_params,
        &dm_params,
        seed,
        verbose,
    )?;

    let embedding: Vec<Vec<T>> = match op {
        DiffusionMapsOperator::Full {
            p_sym,
            sqrt_degrees,
        } => {
            let t = match dm_params.t {
                PhateTime::Auto { t_max } => {
                    if verbosity.normal_verbosity() {
                        println!("Finding optimal t (t_max={})...", t_max);
                    }
                    let entropy = landmark_von_neumann_entropy(&p_sym, t_max)?;
                    find_knee_point(&entropy)
                }
                PhateTime::Fixed(t) => t,
            };
            if verbosity.normal_verbosity() {
                println!("Using t = {}.", t);
                println!(
                    "Computing top {} eigenpairs of P_sym...",
                    dm_params.n_dim + 1
                );
            }
            let start_eig = Instant::now();
            let n_ask = (dm_params.n_dim + 5).min(sqrt_degrees.len() - 1);
            let (evals, evecs) = compute_largest_eigenpairs_lanczos(&p_sym, n_ask, seed as u64)?;

            if verbosity.normal_verbosity() {
                println!("Eigendecomposition done in {:.2?}.", start_eig.elapsed());
            }

            let n = sqrt_degrees.len();
            let mut embedding = vec![vec![T::zero(); dm_params.n_dim]; n];
            for comp_idx in 1..=dm_params.n_dim {
                let lambda = T::from_f32(evals[comp_idx]).unwrap();
                let lambda_t = lambda.powi(t as i32);

                let mut max_abs = 0.0f32;
                let mut sign = 1.0f32;
                for i in 0..n {
                    let v = evecs[i][comp_idx];
                    if v.abs() > max_abs {
                        max_abs = v.abs();
                        sign = if v >= 0.0 { 1.0 } else { -1.0 };
                    }
                }
                for i in 0..n {
                    let u = T::from_f32(evecs[i][comp_idx] * sign).unwrap();
                    embedding[i][comp_idx - 1] = lambda_t * u / sqrt_degrees[i];
                }
            }
            embedding
        }
        DiffusionMapsOperator::Landmark { landmarks } => {
            let t = match dm_params.t {
                PhateTime::Auto { t_max } => {
                    if verbosity.normal_verbosity() {
                        println!("Finding optimal t on landmarks (t_max={})...", t_max);
                    }
                    landmarks.find_optimal_t(t_max)?
                }
                PhateTime::Fixed(t) => t,
            };
            if verbosity.detailed_verbosity() {
                println!(
                    "Using t = {}. Eigendecomposing {}x{} landmark operator...",
                    t,
                    landmarks.get_n_landmarks(),
                    landmarks.get_n_landmarks()
                );
            }
            let start_eig = Instant::now();
            let (evals, evecs) = landmarks.eigendecompose(dm_params.n_dim, seed as u64)?;

            if verbosity.detailed_verbosity() {
                println!("Eigendecomposition done in {:.2?}.", start_eig.elapsed());
            }
            if verbosity.normal_verbosity() {
                println!("Nystroem-extending to full data...");
            }
            let (landmark_embedding, lambdas) =
                landmarks.compute_landmark_embedding(&evals, &evecs, dm_params.n_dim, t);
            landmarks.nystrom_extend(&landmark_embedding, &lambdas)
        }
    };

    if verbosity.normal_verbosity() {
        println!("Diffusion maps finished in {:.2?}.", start_dm.elapsed());
    }

    let n = embedding.len();
    let mut transposed = vec![vec![T::zero(); n]; dm_params.n_dim];
    for i in 0..n {
        for d in 0..dm_params.n_dim {
            transposed[d][i] = embedding[i][d];
        }
    }

    Ok(transposed)
}

/////////////////////
// Parametric UMAP //
/////////////////////

#[cfg(feature = "parametric")]
/// Stores the parameters for parametric UMAP via neural nets
#[derive(Debug, Clone)]
pub struct ParametricUmapParams<T> {
    /// How many dimensions to return
    pub n_dim: usize,
    /// Number of neighbours
    pub k: usize,
    /// Which of the possible approximate nearest neighbour searches to use.
    /// Defaults to `"hnsw"`.
    pub ann_type: String,
    /// Vector of usizes for the hidden layers in the MLP.
    pub hidden_layers: Vec<usize>,
    /// Nearest neighbour parameters.
    pub nn_params: NearestNeighbourParams<T>,
    /// The graph parameters for the generation of the graph structure.
    pub umap_graph_params: UmapGraphParams<T>,
    /// Train parameters for the neural network.
    pub train_param: TrainParametricParams<T>,
}

#[cfg(feature = "parametric")]
impl<T> Default for ParametricUmapParams<T>
where
    T: ManifoldsFloat + Element,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            k: 15,
            ann_type: "hnsw".to_string(),
            hidden_layers: vec![128, 128, 128],
            nn_params: NearestNeighbourParams::default(),
            umap_graph_params: UmapGraphParams::default(),
            train_param: TrainParametricParams::default(),
        }
    }
}

#[cfg(feature = "parametric")]
impl<T> ParametricUmapParams<T>
where
    T: ManifoldsFloat + Element,
{
    /// Generate new parametric UMAP parameters with full control over every
    /// field.
    ///
    /// For sensible defaults, use [`ParametricUmapParams::default`] or
    /// [`ParametricUmapParams::new_default_2d`] instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - Number of embedding dimensions.
    /// * `k` - Number of nearest neighbours.
    /// * `ann_type` - (Approximate) nearest neighbour method. One of
    ///   `"exhaustive"`, `"ivf"`, `"hnsw"`, `"nndescent"`, `"annoy"`,
    ///   `"kmknn"` or `"balltree"`.
    /// * `hidden_layers` - Hidden layer sizes for the MLP encoder.
    /// * `nn_params` - Nearest neighbour parameters.
    /// * `umap_graph_params` - UMAP graph generation parameters.
    /// * `train_param` - Training parameters for the neural network.
    ///
    /// ### Returns
    ///
    /// A fully specified set of parametric UMAP parameters.
    pub fn new(
        n_dim: usize,
        k: usize,
        ann_type: String,
        hidden_layers: Vec<usize>,
        nn_params: NearestNeighbourParams<T>,
        umap_graph_params: UmapGraphParams<T>,
        train_param: TrainParametricParams<T>,
    ) -> Self {
        Self {
            n_dim,
            k,
            ann_type,
            hidden_layers,
            nn_params,
            umap_graph_params,
            train_param,
        }
    }

    /// Default parameters for standard 2D parametric UMAP.
    ///
    /// Returns the default parameters but lets you tune `min_dist`, `spread`
    /// and `corr_weight`, which feed into the training parameters.
    ///
    /// ### Params
    ///
    /// * `min_dist` - Minimum distance between embedded points. Defaults to
    ///   `0.1`.
    /// * `spread` - Effective scale of embedded points. Defaults to `1.0`.
    /// * `corr_weight` - Correlation loss weight. Defaults to `0.0`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation.
    pub fn new_default_2d(min_dist: Option<T>, spread: Option<T>, corr_weight: Option<T>) -> Self {
        let min_dist = min_dist.unwrap_or(T::from_f64(0.1).unwrap());
        let spread = spread.unwrap_or(T::from_f64(1.0).unwrap());
        let corr_weight = corr_weight.unwrap_or(T::from_f64(0.0).unwrap());

        Self {
            train_param: TrainParametricParams::from_min_dist_spread(
                min_dist,
                spread,
                corr_weight,
                None,
                None,
                None,
                None,
            ),
            ..Self::default()
        }
    }
}

#[cfg(feature = "parametric")]
/// Run parametric UMAP dimensionality reduction
///
/// Parametric UMAP learns a neural network encoder that maps high-dimensional
/// data to a low-dimensional embedding space. Unlike standard UMAP, this
/// approach provides an explicit parametric mapping that can be applied to
/// new data points without retraining.
///
/// The algorithm follows these steps:
///
/// 1. Find k-nearest neighbours using approximate nearest neighbour search
/// 2. Construct fuzzy simplicial set via smooth kNN distances
/// 3. Symmetrise the graph using fuzzy set union
/// 4. Train an MLP encoder to preserve the graph structure using UMAP loss
/// 5. Return embeddings by passing all data through the trained encoder
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed k-nearest neighbours and distances. Needs
///   to be a tuple of `(Vec<Vec<usize>>, Vec<Vec<T>>)` with indices and
///   distances excluding self.
/// * `umap_params` - Configuration parameters for parametric UMAP
/// * `device` - Burn backend device for neural network training
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding coordinates as `Vec<Vec<T>>` where outer vector has length
/// `n_dim` and inner vectors have length `n_samples`. Each outer element
/// represents one embedding dimension.
pub fn parametric_umap<T, B>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    umap_params: &ParametricUmapParams<T>,
    device: &B::Device,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat + Element,
    B: AutodiffBackend,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    // parse various parameters
    let nn_params = umap_params.nn_params.clone();

    let verbosity = parse_verbosity_level(verbose);

    if verbosity.normal_verbosity() {
        println!(
            "Running parametric umap with alpha: {:.2?} and beta: {:.2?}",
            ToPrimitive::to_f32(&umap_params.train_param.a).unwrap(),
            ToPrimitive::to_f32(&umap_params.train_param.b).unwrap()
        );
    }

    let (graph, _, _) = construct_umap_graph(
        data,
        precomputed_knn,
        umap_params.k,
        umap_params.ann_type.clone(),
        &umap_params.umap_graph_params,
        &nn_params,
        umap_params.train_param.n_epochs,
        seed,
        verbose,
    )?;

    let model_params = UmapMlpConfig::from_params(
        data.ncols(),
        umap_params.hidden_layers.clone(),
        umap_params.n_dim,
    );

    let (embd, _) = train_parametric_umap::<B, T>(
        data,
        graph,
        &model_params,
        &umap_params.train_param,
        device,
        seed,
        verbosity.normal_verbosity(),
    );

    Ok(embd)
}

#[cfg(feature = "parametric")]
/// Train the parametric UMAP model and return it
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `umap_params` - Configuration parameters for parametric UMAP
/// * `device` - Burn backend device for neural network training
/// * `seed` - Random seed for reproducibility
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// Parametric UMAP learns a neural network encoder that maps high-dimensional
/// data to a low-dimensional embedding space. Unlike standard UMAP, this
/// approach provides an explicit parametric mapping that can be applied to
/// new data points without retraining.
///
/// The algorithm follows these steps:
///
/// 1. Find k-nearest neighbours using approximate nearest neighbour search
/// 2. Construct fuzzy simplicial set via smooth kNN distances
/// 3. Symmetrise the graph using fuzzy set union
/// 4. Train an MLP encoder to preserve the graph structure using UMAP loss
/// 5. Returns the trained MLP encoder that can be used now also on new data
///
/// ### Returns
///
/// Returns a tuple of embedding and the `TrainedUmapModel` for further usage.
pub fn train_parametric_umap_model<T, B>(
    data: MatRef<T>,
    umap_params: &ParametricUmapParams<T>,
    device: &B::Device,
    seed: usize,
    verbose: usize,
) -> ParametricUmapResults<B, T>
where
    T: ManifoldsFloat + Element,
    B: AutodiffBackend,
    HnswIndex<T>: HnswState<T>,
    NNDescent<T>: ApplySortedUpdates<T> + NNDescentQuery<T>,
{
    // parse various parameters
    let nn_params = umap_params.nn_params.clone();
    let verbosity = parse_verbosity_level(verbose);

    if verbosity.normal_verbosity() {
        println!(
            "Training parametric umap model with alpha: {:.2?} and beta: {:.2?}",
            ToPrimitive::to_f32(&umap_params.train_param.a).unwrap(),
            ToPrimitive::to_f32(&umap_params.train_param.b).unwrap()
        );
    }

    let (graph, _, _) = construct_umap_graph(
        data,
        None,
        umap_params.k,
        umap_params.ann_type.clone(),
        &umap_params.umap_graph_params,
        &nn_params,
        umap_params.train_param.n_epochs,
        seed,
        verbose,
    )?;

    let model_params = UmapMlpConfig::from_params(
        data.ncols(),
        umap_params.hidden_layers.clone(),
        umap_params.n_dim,
    );

    let (embd, trained_model) = train_parametric_umap::<B, T>(
        data,
        graph,
        &model_params,
        &umap_params.train_param,
        device,
        seed,
        verbosity.normal_verbosity(),
    );

    Ok((embd, trained_model))
}

/////////
// GPU //
/////////

//////////////
// UMAP GPU //
//////////////

/// UMAP parameters for GPU-accelerated nearest neighbour search
#[cfg(feature = "gpu")]
#[derive(Debug, Clone)]
pub struct UmapParamsGpu<T> {
    /// How many dimensions to return
    pub n_dim: usize,
    /// Number of neighbours
    pub k: usize,
    /// Which optimiser to use. Defaults to `"adam_parallel"`.
    pub optimiser: String,
    /// Which GPU nearest neighbour search to use. One of `"exhaustive_gpu"`,
    /// `"ivf_gpu"` or `"nndescent_gpu"`. Defaults to `"ivf_gpu"`.
    pub ann_type: String,
    /// Which embedding initialisation to use. Defaults to spectral clustering.
    pub initialisation: String,
    /// Optional initialisation range
    pub init_range: Option<T>,
    /// GPU nearest neighbour parameters
    pub nn_params: NearestNeighbourParamsGpu<T>,
    /// Parameters for UMAP graph generation
    pub umap_graph_params: UmapGraphParams<T>,
    /// Parameters for the UMAP optimiser
    pub optim_params: UmapOptimParams<T>,
    /// Use randomised SVD for PCA-based initialisation
    pub randomised: bool,
}

#[cfg(feature = "gpu")]
impl<T> Default for UmapParamsGpu<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            k: 15,
            optimiser: "adam_parallel".to_string(),
            ann_type: "ivf_gpu".to_string(),
            initialisation: "spectral".to_string(),
            init_range: None,
            nn_params: NearestNeighbourParamsGpu::default(),
            umap_graph_params: UmapGraphParams::default(),
            optim_params: UmapOptimParams::default(),
            randomised: false,
        }
    }
}

#[cfg(feature = "gpu")]
impl<T> UmapParamsGpu<T>
where
    T: ManifoldsFloat,
{
    /// Generate new GPU UMAP parameters with full control over every field.
    ///
    /// This constructor exposes every field directly. For sensible defaults,
    /// use [`UmapParamsGpu::default`] or [`UmapParamsGpu::new_default_2d`]
    /// instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - How many dimensions to return.
    /// * `k` - How many neighbours to consider.
    /// * `optimiser` - Which optimiser to use, e.g. `"adam_parallel"`.
    /// * `ann_type` - Which GPU ANN search to use. One of `"exhaustive_gpu"`,
    ///   `"ivf_gpu"` or `"nndescent_gpu"`.
    /// * `initialisation` - Which embedding initialisation to use, e.g.
    ///   `"spectral"`.
    /// * `init_range` - Optional initialisation range.
    /// * `nn_params` - GPU nearest neighbour parameters.
    /// * `umap_graph_params` - Parameters for the UMAP graph generation.
    /// * `optim_params` - Parameters for the UMAP optimiser.
    /// * `randomised` - Whether randomised SVD is used for PCA-based
    ///   initialisation.
    ///
    /// ### Returns
    ///
    /// A fully specified set of GPU UMAP parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        k: usize,
        optimiser: String,
        ann_type: String,
        initialisation: String,
        init_range: Option<T>,
        nn_params: NearestNeighbourParamsGpu<T>,
        umap_graph_params: UmapGraphParams<T>,
        optim_params: UmapOptimParams<T>,
        randomised: bool,
    ) -> Self {
        Self {
            n_dim,
            k,
            optimiser,
            ann_type,
            initialisation,
            init_range,
            nn_params,
            umap_graph_params,
            optim_params,
            randomised,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `min_dist` and
    /// `spread`, which feed into the optimiser parameters and control how
    /// tightly points are packed in the embedding.
    ///
    /// ### Params
    ///
    /// * `min_dist` - Minimum distance between data points. Defaults to `0.5`.
    /// * `spread` - Spread parameter. Defaults to `1.0`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation with GPU
    /// kNN search.
    pub fn new_default_2d(min_dist: Option<T>, spread: Option<T>) -> Self {
        let min_dist = min_dist.unwrap_or(T::from_f64(0.5).unwrap());
        let spread = spread.unwrap_or(T::from_f64(1.0).unwrap());

        Self {
            optim_params: UmapOptimParams::from_min_dist_spread(
                min_dist, spread, None, None, None, None, None, None, None,
            ),
            ..Self::default()
        }
    }
}

/// Construct the UMAP graph using GPU-accelerated nearest neighbour search
///
/// Identical to `construct_umap_graph` except the kNN search runs on a GPU
/// device via `run_ann_search_gpu`. All downstream graph construction
/// (smooth kNN distances, symmetrisation, edge filtering) remains on CPU.
///
/// ### Params
///
/// * `data` - Input data matrix (samples x features)
/// * `precomputed_knn` - Optional precomputed kNN (indices, distances)
///   excluding self.
/// * `k` - Number of nearest neighbours.
/// * `ann_type` - GPU ANN method: `"exhaustive_gpu"`, `"ivf_gpu"` or
///   `"nndescent_gpu"`.
/// * `umap_params` - UMAP graph parameters (bandwidth, local_connectivity,
///   mix_weight).
/// * `nn_params` - GPU nearest neighbour search parameters.
/// * `n_epochs` - Number of optimisation epochs (used for edge filtering).
/// * `device` - The GPU device to use.
/// * `seed` - Random seed.
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Tuple of (graph, knn_indices, knn_dist).
#[cfg(feature = "gpu")]
#[allow(clippy::too_many_arguments)]
pub fn construct_umap_graph_gpu<T, R>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    k: usize,
    ann_type: String,
    umap_params: &UmapGraphParams<T>,
    nn_params: &NearestNeighbourParamsGpu<T>,
    n_epochs: usize,
    device: R::Device,
    seed: usize,
    verbose: usize,
) -> UmapGraphResults<T>
where
    T: ManifoldsFloat + AnnSearchGpuFloat,
    R: Runtime,
    NNDescentGpu<T, R>: NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    let (knn_indices, knn_dist) = match precomputed_knn {
        Some((indices, distances)) => {
            if verbosity.normal_verbosity() {
                println!("Using precomputed kNN graph...");
            }
            (indices, distances)
        }
        None => {
            if verbosity.normal_verbosity() {
                println!("Running GPU nearest neighbour search using {}...", ann_type);
            }
            let start_knn = Instant::now();
            let result =
                run_ann_search_gpu::<T, R>(data, k, ann_type, nn_params, device, seed, verbose)?;
            if verbosity.normal_verbosity() {
                println!("GPU kNN search done in: {:.2?}.", start_knn.elapsed());
            }
            result
        }
    };

    if verbosity.normal_verbosity() {
        println!("Constructing fuzzy simplicial set...");
    }

    let start_graph = Instant::now();

    let (sigma, rho) = smooth_knn_dist(
        &knn_dist,
        knn_dist[0].len(),
        umap_params.local_connectivity,
        umap_params.bandwidth,
        64,
    );

    let graph = knn_to_coo(&knn_indices, &knn_dist, &sigma, &rho);
    let graph = symmetrise_graph(graph, umap_params.mix_weight);
    let graph = filter_weak_edges(graph, n_epochs, verbose);

    if verbosity.normal_verbosity() {
        println!(
            "Finalised graph generation in {:.2?}.",
            start_graph.elapsed()
        );
    }

    Ok((graph, knn_indices, knn_dist))
}

/// Run UMAP with GPU-accelerated nearest neighbour search
///
/// Identical to `umap` except the kNN graph is constructed on the GPU.
/// Embedding initialisation and optimisation remain on the CPU (the parallel
/// Adam optimiser is already extremely fast for the 2D embedding updates).
///
/// ### Params
///
/// * `data` - Input data matrix (samples x features)
/// * `precomputed_knn` - Optional precomputed kNN (indices, distances)
///   excluding self.
/// * `umap_params` - GPU UMAP parameters.
/// * `device` - The GPU device to use.
/// * `seed` - Random seed.
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding coordinates as `Vec<Vec<T>>` where outer vector has length
/// `n_dim` and inner vectors have length `n_samples`.
#[cfg(feature = "gpu")]
pub fn umap_gpu<T, R>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    umap_params: &UmapParamsGpu<T>,
    device: R::Device,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat + AnnSearchGpuFloat,
    R: Runtime,
    StandardNormal: Distribution<T>,
    NNDescentGpu<T, R>: NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    let init_type = parse_initilisation(
        &umap_params.initialisation,
        umap_params.randomised,
        umap_params.init_range,
    )
    .unwrap_or_else(|| {
        println!(
            "Unknown initialisation provided: {:?}. Defaulting to PCA.",
            umap_params.initialisation,
        );
        EmbdInit::PcaInit {
            range: None,
            randomised: true,
        }
    });
    let optimiser = parse_umap_optimiser(&umap_params.optimiser).unwrap_or_default();

    if verbosity.normal_verbosity() {
        println!(
            "Running umap (GPU kNN) with alpha: {:.2?} and beta: {:.2?}",
            umap_params.optim_params.a, umap_params.optim_params.b
        );
    }

    let (graph, _, _) = construct_umap_graph_gpu::<T, R>(
        data,
        precomputed_knn,
        umap_params.k,
        umap_params.ann_type.clone(),
        &umap_params.umap_graph_params,
        &umap_params.nn_params,
        umap_params.optim_params.n_epochs,
        device,
        seed,
        verbose,
    )?;

    if verbosity.normal_verbosity() {
        println!(
            "Initialising embedding via {} layout...",
            umap_params.initialisation
        );
    }

    let start_layout = Instant::now();

    let mut embd = initialise_embedding(&init_type, umap_params.n_dim, seed as u64, &graph, data)?;

    let graph_adj = coo_to_adjacency_list(&graph);

    if verbosity.normal_verbosity() {
        println!(
            "Optimising embedding via {} ({} epochs) on {} edges...",
            match optimiser {
                UmapOptimiser::Adam => "Adam",
                UmapOptimiser::Sgd => "SGD",
                UmapOptimiser::AdamParallel => "Adam (multi-threaded)",
            },
            umap_params.optim_params.n_epochs,
            graph.col_indices.len().separate_with_underscores()
        );
    }

    match optimiser {
        UmapOptimiser::Adam => optimise_embedding_adam(
            &mut embd,
            &graph_adj,
            &umap_params.optim_params,
            seed as u64,
            verbose,
        )?,
        UmapOptimiser::Sgd => {
            optimise_embedding_sgd(
                &mut embd,
                &graph_adj,
                &umap_params.optim_params,
                seed as u64,
                verbose,
            )?;
        }
        UmapOptimiser::AdamParallel => {
            optimise_embedding_adam_parallel(
                &mut embd,
                &graph_adj,
                &umap_params.optim_params,
                seed as u64,
                verbose,
            )?;
        }
    }

    if verbosity.normal_verbosity() {
        println!(
            "Initialised and optimised embedding in: {:.2?}.",
            start_layout.elapsed()
        );
        println!("UMAP (GPU) complete!");
    }

    let n_samples = embd.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; umap_params.n_dim];

    for sample_idx in 0..n_samples {
        for dim_idx in 0..umap_params.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}

//////////////
// tSNE GPU //
//////////////

/// t-SNE parameters for GPU-accelerated nearest neighbour search
#[cfg(feature = "gpu")]
#[derive(Debug, Clone)]
pub struct TsneParamsGpu<T> {
    /// Number of output dimensions (typically 2)
    pub n_dim: usize,
    /// Perplexity parameter controlling neighbourhood size (typical: 5-50)
    pub perplexity: T,
    /// Which GPU ANN search to use. One of `"exhaustive_gpu"`, `"ivf_gpu"` or
    /// `"nndescent_gpu"`. Defaults to `"ivf_gpu"`.
    pub ann_type: String,
    /// Embedding initialisation method: `"pca"`, `"random"`, or `"spectral"`
    pub initialisation: String,
    /// Optional initialisation range
    pub init_range: Option<T>,
    /// GPU nearest neighbour parameters
    pub nn_params: NearestNeighbourParamsGpu<T>,
    /// tSNE optimisation parameters
    pub optim_params: TsneOptimParams<T>,
    /// Use randomised SVD for PCA initialisation
    pub randomised_init: bool,
}

#[cfg(feature = "gpu")]
impl<T> Default for TsneParamsGpu<T>
where
    T: ManifoldsFloat,
{
    fn default() -> Self {
        Self {
            n_dim: 2,
            perplexity: T::from_f64(30.0).unwrap(),
            ann_type: "ivf_gpu".to_string(),
            initialisation: "pca".to_string(),
            init_range: None,
            nn_params: NearestNeighbourParamsGpu::default(),
            optim_params: TsneOptimParams {
                n_epochs: 1000,
                lr: None,
                early_exag_iter: 250,
                early_exag_factor: T::from_f64(12.0).unwrap(),
                late_exag_factor: None,
                theta: T::from_f64(0.5).unwrap(),
                n_interp_points: 3,
            },
            randomised_init: true,
        }
    }
}

#[cfg(feature = "gpu")]
impl<T> TsneParamsGpu<T>
where
    T: ManifoldsFloat,
{
    /// Create new GPU t-SNE parameters with full control over every field.
    ///
    /// This constructor exposes every field directly, including the
    /// optimiser parameters. For sensible defaults, use
    /// [`TsneParamsGpu::default`] or [`TsneParamsGpu::new_default_2d`] instead.
    ///
    /// ### Params
    ///
    /// * `n_dim` - Number of output dimensions.
    /// * `perplexity` - Perplexity parameter controlling neighbourhood size
    ///   (typical: 5-50).
    /// * `ann_type` - GPU ANN algorithm. One of `"exhaustive_gpu"`,
    ///   `"ivf_gpu"` or `"nndescent_gpu"`.
    /// * `initialisation` - Embedding initialisation method: `"pca"`,
    ///   `"random"`, or `"spectral"`.
    /// * `init_range` - Optional initialisation range.
    /// * `nn_params` - GPU nearest neighbour parameters.
    /// * `optim_params` - t-SNE optimisation parameters. These cover the
    ///   learning rate, number of epochs, early/late exaggeration, the
    ///   Barnes-Hut `theta`, and the number of FFT interpolation points.
    /// * `randomised_init` - Whether randomised SVD is used for PCA
    ///   initialisation.
    ///
    /// ### Returns
    ///
    /// A fully specified set of GPU t-SNE parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        n_dim: usize,
        perplexity: T,
        ann_type: String,
        initialisation: String,
        init_range: Option<T>,
        nn_params: NearestNeighbourParamsGpu<T>,
        optim_params: TsneOptimParams<T>,
        randomised_init: bool,
    ) -> Self {
        Self {
            n_dim,
            perplexity,
            ann_type,
            initialisation,
            init_range,
            nn_params,
            optim_params,
            randomised_init,
        }
    }

    /// Default parameters for standard 2D visualisation.
    ///
    /// Returns the default parameters but lets you tune `perplexity`, the
    /// characteristic t-SNE knob controlling neighbourhood size.
    ///
    /// ### Params
    ///
    /// * `perplexity` - Perplexity parameter (typical: 5-50). Defaults to
    ///   `30.0`.
    ///
    /// ### Returns
    ///
    /// Hopefully sensible standard parameters for 2D visualisation with GPU
    /// kNN search.
    pub fn new_default_2d(perplexity: Option<T>) -> Self {
        let perplexity = perplexity.unwrap_or_else(|| T::from_f64(30.0).unwrap());

        Self {
            perplexity,
            ..Self::default()
        }
    }
}

/// Construct affinity graph for t-SNE using GPU-accelerated kNN search
///
/// Identical to `construct_tsne_graph` except the kNN runs on the GPU.
/// Gaussian affinity computation and symmetrisation remain on CPU.
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Precomputed kNN (indices, distances) excluding self
/// * `perplexity` - Target perplexity
/// * `ann_type` - GPU ANN method: `"exhaustive_gpu"`, `"ivf_gpu"` or
///   `"nndescent_gpu"`
/// * `nn_params` - GPU nearest neighbour search parameters
/// * `device` - GPU device to use
/// * `seed` - Random seed
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Tuple of (symmetric affinity graph, knn_indices, knn_dist)
#[cfg(feature = "gpu")]
#[allow(clippy::too_many_arguments)]
pub fn construct_tsne_graph_gpu<T, R>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    perplexity: T,
    ann_type: String,
    nn_params: &NearestNeighbourParamsGpu<T>,
    device: R::Device,
    seed: usize,
    verbose: usize,
) -> TsneGraph<T>
where
    T: ManifoldsFloat + AnnSearchGpuFloat,
    R: Runtime,
    NNDescentGpu<T, R>: NNDescentQuery<T>,
{
    let verbosity = parse_verbosity_level(verbose);

    let (knn_indices, knn_dist) = match precomputed_knn {
        Some((indices, distances)) => {
            if verbosity.normal_verbosity() {
                println!("Using precomputed kNN graph...");
            }
            (indices, distances)
        }
        None => {
            let k_float = perplexity * T::from_f64(3.0).unwrap();
            let k = k_float.to_usize().unwrap().max(5).min(data.nrows() - 1);

            if verbosity.normal_verbosity() {
                println!("Running GPU kNN search (k={}) using {}...", k, ann_type);
            }

            let start_knn = Instant::now();
            let result =
                run_ann_search_gpu::<T, R>(data, k, ann_type, nn_params, device, seed, verbose)?;

            if verbosity.normal_verbosity() {
                println!("GPU kNN search done in: {:.2?}.", start_knn.elapsed());
            }

            result
        }
    };

    if verbosity.normal_verbosity() {
        println!("Computing Gaussian affinities and symmetrising...");
    }

    let start_graph = Instant::now();

    let directed_graph = gaussian_knn_affinities(
        &knn_indices,
        &knn_dist,
        perplexity,
        T::from_f64(1e-5).unwrap(),
        200,
        nn_params.dist_metric == "euclidean",
    )?;

    let graph = symmetrise_affinities_tsne(directed_graph);

    if verbosity.normal_verbosity() {
        println!(
            "Finalised graph generation in {:.2?}.",
            start_graph.elapsed()
        );
    }

    Ok((graph, knn_indices, knn_dist))
}

/// Run t-SNE with GPU-accelerated nearest neighbour search (FFT build)
///
/// Identical to `tsne` except the kNN graph is constructed on the GPU.
/// Optimisation (Barnes-Hut or FFT) stays on CPU.
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Optional precomputed kNN, indices and distances
///   excluding self
/// * `params` - GPU t-SNE parameters
/// * `approx_type` - Repulsive-force approximation: `"barnes_hut" | "bh"` or
///   `"fft"`
/// * `device` - GPU device to use
/// * `seed` - Random seed
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding as `Vec<Vec<T>>` with shape `[n_dim][n_samples]`.
#[cfg(all(feature = "gpu", feature = "fft_tsne"))]
pub fn tsne_gpu<T, R>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    params: &TsneParamsGpu<T>,
    approx_type: &str,
    device: R::Device,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat + AnnSearchGpuFloat + FftwFloat,
    R: Runtime,
    StandardNormal: Distribution<T>,
    NNDescentGpu<T, R>: NNDescentQuery<T>,
{
    if params.n_dim != 2 {
        return Err(ManifoldsError::IncorrectDim {
            n_dim: params.n_dim,
        });
    }

    let verbosity = parse_verbosity_level(verbose);

    let (graph, _, _) = construct_tsne_graph_gpu::<T, R>(
        data,
        precomputed_knn,
        params.perplexity,
        params.ann_type.clone(),
        &params.nn_params,
        device,
        seed,
        verbose,
    )?;

    if verbosity.normal_verbosity() {
        println!("Initialising embedding via {}...", &params.initialisation);
    }

    let init_type = parse_initilisation(
        &params.initialisation,
        params.randomised_init,
        params.init_range,
    )
    .unwrap_or_else(|| {
        println!(
            "Unknown initialisation provided: {:?}. Defaulting to PCA.",
            params.initialisation,
        );
        EmbdInit::PcaInit {
            range: Some(T::from_f64(1e-2).unwrap()),
            randomised: true,
        }
    });

    let mut embd = initialise_embedding(&init_type, params.n_dim, seed as u64, &graph, data)?;

    let tsne_approx = parse_tsne_optimiser(approx_type).unwrap_or_default();

    let start_optim = Instant::now();
    match tsne_approx {
        TsneOpt::BarnesHut => {
            if verbosity.normal_verbosity() {
                println!(
                    "Optimising via Barnes-Hut t-SNE ({} epochs)...",
                    params.optim_params.n_epochs
                );
            }
            optimise_bh_tsne(&mut embd, &params.optim_params, &graph, verbose);
        }
        TsneOpt::Fft => {
            if verbosity.normal_verbosity() {
                println!(
                    "Optimising via FFT Interpolation-based t-SNE ({} epochs)...",
                    params.optim_params.n_epochs
                );
            }
            optimise_fft_tsne(&mut embd, &params.optim_params, &graph, verbose)?;
        }
    }

    if verbosity.normal_verbosity() {
        println!("Optimisation complete in {:.2?}.", start_optim.elapsed());
    }

    let n_samples = embd.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; params.n_dim];

    for sample_idx in 0..n_samples {
        for dim_idx in 0..params.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}

/// Run t-SNE with GPU-accelerated nearest neighbour search (non-FFT build)
///
/// Identical to `tsne` except the kNN graph is constructed on the GPU.
/// Barnes-Hut optimisation stays on CPU. Calling with `approx_type = "fft"`
/// panics; recompile with the `fft_tsne` feature for FFT support.
///
/// ### Params
///
/// * `data` - Input data matrix (samples × features)
/// * `precomputed_knn` - Optional precomputed kNN, indices and distances
///   excluding self
/// * `params` - GPU t-SNE parameters
/// * `approx_type` - Repulsive-force approximation: `"barnes_hut" | "bh"`
/// * `device` - GPU device to use
/// * `seed` - Random seed
/// * `verbose` - If `0` -> silent or `1` for normal verbosity, `2` for detailed
///   verbosity.
///
/// ### Returns
///
/// Embedding as `Vec<Vec<T>>` with shape `[n_dim][n_samples]`.
#[cfg(all(feature = "gpu", not(feature = "fft_tsne")))]
pub fn tsne_gpu<T, R>(
    data: MatRef<T>,
    precomputed_knn: PreComputedKnn<T>,
    params: &TsneParamsGpu<T>,
    approx_type: &str,
    device: R::Device,
    seed: usize,
    verbose: usize,
) -> Result<Vec<Vec<T>>, ManifoldsError>
where
    T: ManifoldsFloat + AnnSearchGpuFloat,
    R: Runtime,
    StandardNormal: Distribution<T>,
    NNDescentGpu<T, R>: NNDescentQuery<T>,
{
    if params.n_dim != 2 {
        return Err(ManifoldsError::IncorrectDim {
            n_dim: params.n_dim,
        });
    }

    let verbosity = parse_verbosity_level(verbose);

    let (graph, _, _) = construct_tsne_graph_gpu::<T, R>(
        data,
        precomputed_knn,
        params.perplexity,
        params.ann_type.clone(),
        &params.nn_params,
        device,
        seed,
        verbose,
    )?;

    if verbosity.normal_verbosity() {
        println!("Initialising embedding via {}...", &params.initialisation);
    }

    let init_type = parse_initilisation(
        &params.initialisation,
        params.randomised_init,
        params.init_range,
    )
    .unwrap_or_else(|| {
        println!(
            "Unknown initialisation provided: {:?}. Defaulting to PCA.",
            params.initialisation,
        );
        EmbdInit::PcaInit {
            range: Some(T::from_f64(1e-2).unwrap()),
            randomised: true,
        }
    });

    let mut embd = initialise_embedding(&init_type, params.n_dim, seed as u64, &graph, data)?;

    let tsne_approx = parse_tsne_optimiser(approx_type).unwrap_or_default();

    let start_optim = Instant::now();
    match tsne_approx {
        TsneOpt::BarnesHut => {
            if verbosity.normal_verbosity() {
                println!(
                    "Optimising via Barnes-Hut t-SNE ({} epochs)...",
                    params.optim_params.n_epochs
                );
            }
            optimise_bh_tsne(&mut embd, &params.optim_params, &graph, verbose);
        }
        TsneOpt::Fft => {
            panic!("FFT-accelerated t-SNE not available. Recompile with 'fft_tsne' feature or use 'barnes_hut' approximation.");
        }
    }

    if verbosity.normal_verbosity() {
        println!("Optimisation complete in {:.2?}.", start_optim.elapsed());
    }

    let n_samples = embd.len();
    let mut transposed = vec![vec![T::zero(); n_samples]; params.n_dim];

    for sample_idx in 0..n_samples {
        for dim_idx in 0..params.n_dim {
            transposed[dim_idx][sample_idx] = embd[sample_idx][dim_idx];
        }
    }

    Ok(transposed)
}