bixverse-rs 0.6.4

A Rust library with various utilities for computational biology and single cell.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
//! Contains R-specific functions for single-cell data processing that need
//! the extendr interface.

use edge_rs::sc::nebula::NebulaParams;
use edge_rs::sc::test::ScTested;
use extendr_api::*;
use std::collections::HashMap;

use crate::ml::clustering::k_means::KMeansParamsWrappers;
use crate::ml::gp::LandmarkGpParams;
use crate::prelude::{BixverseFloat, LanczosParams, VecConvert, VecFloatConvert};
use crate::single_cell::mc_generation::{
    hdwgcna_meta_cells::BootstrappedMetaCellParams, metacells2::params::*,
    seacells::SEACellsParams, super_cells::SuperCellParams,
};
use crate::single_cell::sc_analysis::{
    cellphonedb::CellPhoneDbParams,
    dge_pathway_scores::{AucellParams, parse_auc_type},
    dialogue::{DialogueParams, HlmParams, PmdParams, RefineParams, parse_averaging},
    fast_clusters::FastLouvainParams,
    hotspot::{HotSpotGraphParams, HotSpotParams},
    meld::{MeldParams, parse_lap_type, parse_meld_filter},
    milo_r::MiloRParams,
    nebula::{NebulaScParams, parse_nebula_method},
    nichenet::ligand_regulatory_potential::LigandTargetParams,
    regulon_binarise::BinariseParams,
    scenic::{
        ExtraTreesConfig, GradientBoostingConfig, RandomForestConfig, RegressionLearner,
        ScenicParams,
    },
    vision::SignatureGenes,
};
use crate::single_cell::sc_data::h5ad_io::parse_h5ad_format;
use crate::single_cell::sc_processing::magic::{MagicLayer, MagicParams};
use crate::single_cell::sc_processing::residuals::{
    assert_ascending, validate_clip_range, validate_groups,
};
use crate::single_cell::sc_trajectory::gene_trends::{
    BranchSelectionParams, BranchWeighting, GeneTrendsParams,
};
use crate::single_cell::sc_trajectory::palantir::PalantirParams;
use crate::utils::r_rust_interface::{
    r_list_count, r_list_count_allow_zero, r_list_real, r_list_required_real, r_list_to_map,
};

use crate::single_cell::sc_annotation::{
    sc_type::{CellTypeMarkers, ScTypeCellParams, SctypeRes, parse_score_calibration},
    symphony::SymphonyMapParams,
};
use crate::single_cell::sc_batch_correction::{
    bbknn::BbknnParams, fast_mnn::FastMnnParams, harmony::HarmonyParams,
    harmony_core::HARMONY_KMEANS_ITERS, harmony_v2::HarmonyParamsV2, seurat_cca::SeuratCcaParams,
    seurat_rpca::SeuratRpcaParams,
};
use crate::single_cell::sc_data::h5ad_io::RawDataSlot;
use crate::single_cell::sc_data::{
    bin_merge_io::BinMergeTask, data_io::MinCellQuality, h5_10x_io::parse_tenx_version,
    h5_10x_multifile_io::TenxFileTask, h5ad_io::parse_raw_slot, h5ad_multifile_io::H5adFileTask,
    mtx_multifile_io::MtxFileTask, sc_synthetic_data::CellTypeConfig,
};
use crate::single_cell::sc_processing::analytic_pearson::model::{AprModel, AprParams};
use crate::single_cell::sc_processing::analytic_pearson::stream::AprGroupedFit;
use crate::single_cell::sc_processing::sctransform::model::{SctCovariates, SctModel, SctParams};
use crate::single_cell::sc_processing::sctransform::stream::SctGroupedFit;
use crate::single_cell::sc_processing::{
    cellsweep::{
        CellSweepFit, CellSweepParams, CellSweepSample, EmptyDropletCall, parse_empty_droplet_call,
    },
    doublet_detection::BoostParams,
    hvg::ScranTrendParams,
    knn::KnnParams,
    pca::{PcaSolver, SingleCellPcaParams, parse_pca_solver},
    scdblfinder::ScDblFinderParams,
    scrublet::ScrubletParams,
    utils_doublets::ScDblSimParams,
};

/////////////
// Helpers //
/////////////

/// Convert assignments to R-friendly list format with unassigned cell handling
///
/// Returns -1 for unassigned cells (R convention for missing/unassigned).
///
/// ### Params
///
/// * `assignments` - Vector where
///   `assignments[cell_id] = Some(metacell_id) or None`
/// * `n_cells` - Total number of cells
///
/// ### Returns
///
/// R List with the slots `assignments`, `metacells`, `unassigned`,
/// `n_metacells`, `n_cells` and `n_unassigned`, with -1 marking unassigned
/// cells. `n_metacells` is derived as `max(id) + 1` over the assignments, so
/// trailing metacells that ended up empty are dropped rather than reported at
/// size zero.
pub fn assignments_to_r_list(assignments: &[Option<usize>], n_cells: usize) -> List {
    let r_assignments: Vec<i32> = assignments
        .iter()
        .map(|&x| match x {
            Some(id) => (id + 1) as i32,
            None => -1,
        })
        .collect();

    let n_unassigned = assignments.iter().filter(|x| x.is_none()).count();

    let actual_k = assignments
        .iter()
        .filter_map(|&x| x)
        .max()
        .map(|x| x + 1)
        .unwrap_or(0);

    let mut metacells = vec![Vec::new(); actual_k];

    for (cell_id, &metacell_id) in assignments.iter().enumerate() {
        if let Some(id) = metacell_id {
            metacells[id].push((cell_id + 1) as i32);
        }
    }

    let unassigned: Vec<i32> = assignments
        .iter()
        .enumerate()
        .filter_map(|(cell_id, &x)| {
            if x.is_none() {
                Some((cell_id + 1) as i32)
            } else {
                None
            }
        })
        .collect();

    let metacells_list: List = metacells.into_iter().map(Robj::from).collect();

    list!(
        assignments = r_assignments,
        metacells = metacells_list,
        unassigned = unassigned,
        n_metacells = actual_k,
        n_cells = n_cells,
        n_unassigned = n_unassigned
    )
}

/// Build the R-facing assignment list from metacell membership lists.
///
/// Cells may appear in multiple metacells (overlap is allowed). The per-cell
/// `assignments` field is therefore a list of integer vectors, one per cell,
/// each containing the 1-indexed metacell IDs that cell belongs to. Cells
/// in no metacell get an empty vector and appear in `unassigned`. This
/// helper is needed for the bootstrapped approach of meta cell generation
///
/// ### Params
///
/// * `metacell` - A slice of the cell indices per metacell
/// * `n_cells` - Total number of cells
///
/// ### Returns
///
/// R list in a similar structure as [assignments_to_r_list] with a difference
/// in the assigmnents. These are now a list, not an integer vector!
pub fn metacells_to_r_list(metacells: &[Vec<usize>], n_cells: usize) -> List {
    let mut cell_assignments: Vec<Vec<i32>> = vec![Vec::new(); n_cells];
    for (mc_id, cells) in metacells.iter().enumerate() {
        for &cell_id in cells {
            cell_assignments[cell_id].push((mc_id + 1) as i32);
        }
    }

    let unassigned: Vec<i32> = cell_assignments
        .iter()
        .enumerate()
        .filter_map(|(cell_id, mcs)| mcs.is_empty().then_some((cell_id + 1) as i32))
        .collect();

    let n_unassigned = unassigned.len();
    let n_metacells = metacells.len();

    let metacells_list: List = metacells
        .iter()
        .map(|cells| {
            let r_cells: Vec<i32> = cells.iter().map(|&c| (c + 1) as i32).collect();
            Robj::from(r_cells)
        })
        .collect();

    let assignments_list: List = cell_assignments.into_iter().map(Robj::from).collect();

    list!(
        assignments = assignments_list,
        metacells = metacells_list,
        unassigned = unassigned,
        n_metacells = n_metacells,
        n_cells = n_cells,
        n_unassigned = n_unassigned
    )
}

////////////////////
// Param wrappers //
////////////////////

//////////////
// CellType //
//////////////

impl CellTypeConfig {
    /// Generate the CellTypeConfig from an R list
    ///
    /// If values are not found, will use default values
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list containing the parameters. Should have the
    ///   elements `"marker_genes"`, `"marker_exp_range"`, `"markers_per_cell"`.
    ///
    /// ### Returns
    ///
    /// The `CellTypeConfig` based on the R list.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let marker_genes = map
            .get("marker_genes")
            .and_then(|v| v.as_integer_vector())
            .map(|v| v.iter().map(|x| *x as usize).collect())
            .unwrap_or_default();

        Ok(CellTypeConfig { marker_genes })
    }
}

//////////////////
// Cell quality //
//////////////////

impl MinCellQuality {
    /// Generate the MinCellQuality params from an R list
    ///
    /// or default to sensible defaults
    ///
    /// ### Params
    ///
    /// * `r_list` - R list with the parameters
    ///
    /// ### Returns
    ///
    /// Self with the specified parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let min_qc: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let min_unique_genes = min_qc
            .get("min_unique_genes")
            .and_then(|v| v.as_integer())
            .unwrap_or(100) as usize;

        let min_lib_size = min_qc
            .get("min_lib_size")
            .and_then(|v| v.as_integer())
            .unwrap_or(250) as usize;

        let min_cells = min_qc
            .get("min_cells")
            .and_then(|v| v.as_integer())
            .unwrap_or(10) as usize;

        let target_size = min_qc
            .get("target_size")
            .and_then(|v| v.as_real())
            .unwrap_or(1e5) as f32;

        Ok(MinCellQuality {
            min_unique_genes,
            min_lib_size,
            min_cells,
            target_size,
        })
    }
}

///////////////
// KnnParams //
///////////////

impl KnnParams {
    /// Generate KnnParams from an R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults based on heuristics. Every count is read through
    /// [r_list_count], so `list(k = 50)` works as well as `list(k = 50L)` and a
    /// nonsensical value errors instead of silently reverting to the default.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the kNN parameters.
    ///
    /// ### Returns
    ///
    /// The `KnnParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        // general
        let knn_method = std::string::String::from(
            params_list
                .get("knn_method")
                .and_then(|v| v.as_str())
                .unwrap_or("annoy"),
        );

        let ann_dist = std::string::String::from(
            params_list
                .get("ann_dist")
                .and_then(|v| v.as_str())
                .unwrap_or("cosine"),
        );

        // this allows zeros through deliberately for auto-detection in the
        // doublet detection methods
        let k = r_list_count_allow_zero(&params_list, "k")?.unwrap_or(15);

        // annoy
        let n_tree = r_list_count(&params_list, "n_trees")?.unwrap_or(50);

        let search_budget = r_list_count(&params_list, "search_budget")?;

        // nn descent
        let diversify_prob = params_list
            .get("diversify_prob")
            .and_then(|v| v.as_real())
            .unwrap_or(0.0) as f32;

        let delta = params_list
            .get("delta")
            .and_then(|v| v.as_real())
            .unwrap_or(0.001) as f32;

        let ef_budget = r_list_count(&params_list, "ef_budget")?;
        let extract_knn = params_list
            .get("extract_knn")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // hnsw
        let m = r_list_count(&params_list, "m")?.unwrap_or(16);

        let ef_construction = r_list_count(&params_list, "ef_construction")?.unwrap_or(200);

        let ef_search = r_list_count(&params_list, "ef_search")?.unwrap_or(100);

        // ivf
        let n_list = r_list_count(&params_list, "n_list")?;

        let n_probe = r_list_count(&params_list, "n_probe")?;

        Ok(Self {
            knn_method,
            ann_dist,
            k,
            n_tree,
            search_budget,
            ef_budget,
            extract_knn,
            diversify_prob,
            delta,
            m,
            ef_construction,
            ef_search,
            n_list,
            n_probe,
        })
    }
}

///////////////
// Scran HVG //
///////////////

impl ScranTrendParams {
    /// Generate ScranTrendParams from an R list
    ///
    /// Missing values fall back to scrapper's `fitVarianceTrend` defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the trend parameters.
    ///
    /// ### Returns
    ///
    /// The `ScranTrendParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let flag =
            |key: &str, default: bool| params.get(key).and_then(|v| v.as_bool()).unwrap_or(default);

        Ok(Self {
            mean_filter: flag("mean_filter", defaults.mean_filter),
            minimum_mean: r_list_real(&params, "min_mean")?.unwrap_or(defaults.minimum_mean),
            transform: flag("transform", defaults.transform),
            use_minimum_width: flag("use_min_width", defaults.use_minimum_width),
            minimum_width: r_list_real(&params, "min_width")?.unwrap_or(defaults.minimum_width),
            minimum_window_count: r_list_count(&params, "min_window_count")?
                .unwrap_or(defaults.minimum_window_count),
            span: r_list_real(&params, "span")?.unwrap_or(defaults.span),
        })
    }
}

//////////////
// Scrublet //
//////////////

impl ScrubletParams {
    /// Generate ScrubletParams from an R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults based on Scrublet's original implementation.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Scrublet parameters.
    ///
    /// ### Returns
    ///
    /// The `ScrubletParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let scrublet_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        // General params
        let log_transform = scrublet_list
            .get("log_transform")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let mean_center = scrublet_list
            .get("mean_center")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let normalise_variance = scrublet_list
            .get("normalise_variance")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let target_size = scrublet_list
            .get("target_size")
            .and_then(|v| v.as_real())
            .map(|x| x as f32);

        // HVG detection parameters
        let min_gene_var_pctl = scrublet_list
            .get("min_gene_var_pctl")
            .and_then(|v| v.as_real())
            .unwrap_or(0.85) as f32;

        let hvg_method = std::string::String::from(
            scrublet_list
                .get("hvg_method")
                .and_then(|v| v.as_str())
                .unwrap_or("vst"),
        );

        let loess_span = scrublet_list
            .get("loess_span")
            .and_then(|v| v.as_real())
            .unwrap_or(0.3);

        let clip_max = scrublet_list
            .get("clip_max")
            .and_then(|v| v.as_real())
            .map(|x| x as f32);

        let n_bins = scrublet_list
            .get("n_bins")
            .and_then(|v| v.as_integer())
            .unwrap_or(20) as usize;

        let binning_strategy = std::string::String::from(
            scrublet_list
                .get("binning_strategy")
                .and_then(|v| v.as_str())
                .unwrap_or("equal_width"),
        );

        // PCA parameters
        let no_pcs = scrublet_list
            .get("no_pcs")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;

        let svd_solver = match scrublet_list.get("svd_solver").and_then(|v| v.as_str()) {
            Some(x) => parse_pca_solver(x).ok_or_else(|| format!("Invalid PCA solver: {}", x))?,
            None => PcaSolver::Covariance,
        };

        // Doublet simulation parameters
        let sim_doublet_ratio = scrublet_list
            .get("sim_doublet_ratio")
            .and_then(|v| v.as_real())
            .unwrap_or(2.0) as f32;

        let expected_doublet_rate = scrublet_list
            .get("expected_doublet_rate")
            .and_then(|v| v.as_real())
            .unwrap_or(0.1) as f32;

        let stdev_doublet_rate = scrublet_list
            .get("stdev_doublet_rate")
            .and_then(|v| v.as_real())
            .unwrap_or(0.02) as f32;

        // Doublet calling parameters. `params_scrublet()` emits
        // `n_bins_histogram`; `n_bins_hist` is the Rust field name and stays
        // accepted for hand-built lists. Reading only the latter, as this did,
        // meant the user's bin count never reached the Otsu histogram.
        let n_bins_hist = scrublet_list
            .get("n_bins_histogram")
            .or_else(|| scrublet_list.get("n_bins_hist"))
            .and_then(|v| v.as_integer())
            .unwrap_or(50) as usize;

        let manual_threshold = scrublet_list
            .get("manual_threshold")
            .and_then(|v| v.as_real())
            .map(|x| x as f32);

        Ok(Self {
            // norm
            log_transform,
            normalise_variance,
            mean_center,
            target_size,
            // hvg
            min_gene_var_pctl,
            hvg_method,
            loess_span,
            clip_max,
            n_bins,
            binning_strategy,
            // pca
            no_pcs,
            svd_solver,
            // doublet simulation/detection
            sim_doublet_ratio,
            expected_doublet_rate,
            stdev_doublet_rate,
            n_bins_hist,
            manual_threshold,
            // knn
            knn_params,
        })
    }
}

///////////
// Boost //
///////////

impl BoostParams {
    /// Generate BoostParams from an R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults based on the Boost algorithm.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Boost parameters.
    ///
    /// ### Returns
    ///
    /// The `BoostParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let fast_cluster_params = FastLouvainParams::from_r_list(r_list.clone())?;

        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        // norm parameters
        let log_transform = params_list
            .get("log_transform")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let mean_center = params_list
            .get("mean_center")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let normalise_variance = params_list
            .get("normalise_variance")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let target_size = params_list
            .get("target_size")
            .and_then(|v| v.as_real())
            .map(|x| x as f32);

        // hvg
        let min_gene_var_pctl = params_list
            .get("min_gene_var_pctl")
            .and_then(|v| v.as_real())
            .unwrap_or(0.85) as f32;

        let hvg_method = std::string::String::from(
            params_list
                .get("hvg_method")
                .and_then(|v| v.as_str())
                .unwrap_or("vst"),
        );

        let loess_span = params_list
            .get("loess_span")
            .and_then(|v| v.as_real())
            .unwrap_or(0.3);

        let clip_max = params_list
            .get("clip_max")
            .and_then(|v| v.as_real())
            .map(|x| x as f32);

        let n_bins = params_list
            .get("n_bins")
            .and_then(|v| v.as_integer())
            .unwrap_or(20) as usize;

        let binning_strategy = std::string::String::from(
            params_list
                .get("binning_strategy")
                .and_then(|v| v.as_str())
                .unwrap_or("equal_width"),
        );

        // pca
        let no_pcs = params_list
            .get("no_pcs")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;

        let svd_solver = match params_list.get("svd_solver").and_then(|v| v.as_str()) {
            Some(x) => parse_pca_solver(x).ok_or_else(|| format!("Invalid PCA solver: {}", x))?,
            None => PcaSolver::Covariance,
        };

        // doublet detection params
        let boost_rate = params_list
            .get("boost_rate")
            .and_then(|v| v.as_real())
            .unwrap_or(0.25) as f32;

        let replace = params_list
            .get("replace")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let resolution = params_list
            .get("resolution")
            .and_then(|v| v.as_real())
            .unwrap_or(1.0) as f32;

        let louvain_iters = params_list
            .get("louvain_iters")
            .and_then(|v| v.as_integer())
            .unwrap_or(10) as usize;

        let n_iters = params_list
            .get("n_iters")
            .and_then(|v| v.as_integer())
            .unwrap_or(10) as usize;

        let p_thresh = params_list
            .get("p_thresh")
            .and_then(|v| v.as_real())
            .unwrap_or(1e-7) as f32;

        let voter_thresh = params_list
            .get("voter_thresh")
            .and_then(|v| v.as_real())
            .unwrap_or(0.9) as f32;

        let fast_cluster = params_list
            .get("fast_cluster")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let km_type = std::string::String::from(
            params_list
                .get("km_type")
                .and_then(|v| v.as_str())
                .unwrap_or("minibatch"),
        );

        Ok(Self {
            // processing
            log_transform,
            mean_center,
            normalise_variance,
            target_size,
            // hvg
            min_gene_var_pctl,
            hvg_method,
            loess_span,
            clip_max,
            n_bins,
            binning_strategy,
            // pca
            no_pcs,
            svd_solver,
            // boosted
            boost_rate,
            replace,
            resolution,
            louvain_iters,
            n_iters,
            p_thresh,
            voter_thresh,
            // knn
            knn_params,
            // fast cluster related stuff
            fast_cluster,
            fast_cluster_params,
            km_type,
        })
    }
}

///////////////////////
// ScDblFinderParams //
///////////////////////

impl ScDblFinderParams {
    /// Generate ScDblFinderParams from an R list.
    ///
    /// Values not found in the list fall back to the `Default` implementation.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with scDblFinder parameters.
    ///
    /// ### Returns
    ///
    /// `ScDblFinderParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let fast_cluster_params = FastLouvainParams::from_r_list(r_list.clone())?;
        let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let km_type = std::string::String::from(
            map.get("km_type")
                .and_then(|v| v.as_str())
                .unwrap_or("minibatch"),
        );

        Ok(Self {
            // Preprocessing
            log_transform: map
                .get("log_transform")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.log_transform),
            mean_center: map
                .get("mean_center")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.mean_center),
            normalise_variance: map
                .get("normalise_variance")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.normalise_variance),
            target_size: map
                .get("target_size")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
            n_genes: map
                .get("n_genes")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.n_genes as i32) as usize,
            // Simulation
            doublet_ratio: map
                .get("doublet_ratio")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.doublet_ratio as f64) as f32,
            heterotypic_bias: map
                .get("heterotypic_bias")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.heterotypic_bias as f64) as f32,
            sim_params: ScDblSimParams::default(),
            // PCA
            no_pcs: map
                .get("no_pcs")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.no_pcs as i32) as usize,
            svd_solver: match map.get("svd_solver").and_then(|v| v.as_str()) {
                Some(x) => {
                    parse_pca_solver(x).ok_or_else(|| format!("Invalid PCA solver: {}", x))?
                }
                None => defaults.svd_solver,
            },
            // Clustering
            cluster_resolution: map
                .get("cluster_resolution")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.cluster_resolution as f64)
                as f32,
            cluster_iters: map
                .get("cluster_iters")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.cluster_iters as i32) as usize,
            fast_cluster: map
                .get("fast_cluster")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.fast_cluster),
            km_type,
            fast_cluster_params,
            // kNN
            knn_params,
            // Iteration
            n_iterations: map
                .get("n_iterations")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.n_iterations as i32) as usize,
            // Classification
            gbm_n_trees: map
                .get("n_trees")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.gbm_n_trees as i32) as usize,
            max_depth: map
                .get("max_depth")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.max_depth as i32) as usize,
            learning_rate: map
                .get("learning_rate")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.learning_rate as f64) as f32,
            min_samples_leaf: map
                .get("min_samples_leaf")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.min_samples_leaf as i32) as usize,
            subsample_rate: map
                .get("subsample_rate")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.subsample_rate as f64) as f32,
            cv_folds: map
                .get("cv_folds")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.cv_folds as i32) as usize,
            cv_early_stop: map
                .get("cv_early_stop")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.cv_early_stop as i32) as usize,
            se_fraction: map
                .get("se_fraction")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.se_fraction as f64) as f32,
            // Feature engineering
            include_pcs: map
                .get("include_pcs")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.include_pcs as i32) as usize,
            return_features: map
                .get("return_features")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.return_features),
            cxds_genes: map
                .get("cxds_genes")
                .and_then(|v| v.as_integer())
                .map(|x| x as usize),
            // Expected doublet rate
            expected_doublet_rate: map
                .get("expected_doublet_rate")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
            // Thresholding
            manual_threshold: map
                .get("manual_threshold")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
        })
    }
}

///////////////////////
// FastLouvainParams //
///////////////////////

impl FastLouvainParams<f32> {
    /// Generate the [FastLouvainParams] from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults. The nested kNN and k-means blocks are parsed from
    /// the same flat list via `KnnParams::from_r_list` and
    /// `KMeansParamsWrappers::from_r_list`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the fast Louvain parameters.
    ///
    /// ### Return
    ///
    /// The [FastLouvainParams] with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let kmeans_params = KMeansParamsWrappers::from_r_list(r_list.clone())?;
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults: FastLouvainParams<f32> = Self::default();

        // knn
        let same_weight = params
            .get("same_weight")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.same_weight);

        // k means
        let n_centroids = params
            .get("n_centroids")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_centroids);

        let batch_size = params
            .get("batch_size")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.batch_size);

        let drift_threshold: f32 = params
            .get("drift_threshold")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.drift_threshold);

        let lr_alpha: f32 = params
            .get("lr_alpha")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.lr_alpha);

        // louvain
        let louvain_iters = params
            .get("louvain_iters")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.louvain_iters);
        let multi_level_louvain = params
            .get("multi_level_louvain")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.multi_level_louvain);

        // snn
        let full_snn = params
            .get("full_snn")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.full_snn);

        let pruning = params
            .get("pruning")
            .and_then(|v| v.as_real())
            .map(|x| x as f32);

        let snn_similarity = std::string::String::from(
            params
                .get("snn_similarity")
                .and_then(|v| v.as_str())
                .unwrap_or("jaccard"),
        );

        Ok(Self {
            n_centroids,
            kmeans_params,
            batch_size,
            drift_threshold,
            lr_alpha,
            louvain_iters,
            knn_params,
            full_snn,
            pruning,
            snn_similarity,
            multi_level_louvain,
            same_weight,
        })
    }
}

/////////
// PCA //
/////////

impl SingleCellPcaParams {
    /// Generate the [SingleCellPcaParams] from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the BBKNN parameters.
    ///
    /// ### Return
    ///
    /// The [SingleCellPcaParams] with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = SingleCellPcaParams::default();

        let mean_center = params
            .get("mean_center")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.mean_center);

        let normalise_variance = params
            .get("normalise_variance")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.normalise_variance);

        let svd_solver = match params.get("svd_solver").and_then(|v| v.as_str()) {
            Some(x) => parse_pca_solver(x).ok_or_else(|| format!("Invalid PCA solver: {}", x))?,
            None => defaults.svd_solver,
        };

        let clr = params
            .get("clr")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.clr);

        let size_factor = params
            .get("size_factor")
            .and_then(|v| v.as_real())
            .unwrap_or(1e4) as f32;

        Ok(Self {
            mean_center,
            normalise_variance,
            svd_solver,
            clr,
            size_factor,
        })
    }
}

///////////
// BBKNN //
///////////

impl BbknnParams {
    /// Generate the BbknnParams from a R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the BBKNN parameters.
    ///
    /// ### Return
    ///
    /// The `BbknnParams` with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let bbknn_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let neighbours_within_batch = bbknn_list
            .get("neighbours_within_batch")
            .and_then(|v| v.as_integer())
            .unwrap_or(3) as usize;

        let set_op_mix_ratio = bbknn_list
            .get("set_op_mix_ratio")
            .and_then(|v| v.as_real())
            .unwrap_or(1.0) as f32;

        let local_connectivity = bbknn_list
            .get("local_connectivity")
            .and_then(|v| v.as_real())
            .unwrap_or(1.0) as f32;

        let trim = bbknn_list
            .get("trim")
            .and_then(|v| v.as_integer())
            .unwrap_or(10 * neighbours_within_batch as i32) as usize;

        Ok(Self {
            neighbours_within_batch,
            set_op_mix_ratio,
            local_connectivity,
            trim: Some(trim),
            knn_params,
        })
    }
}

/////////////
// FastMNN //
/////////////

impl FastMnnParams {
    /// Generate the FastMnnParams from an R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the fastMNN parameters.
    ///
    /// ### Return
    ///
    /// The `FastMnnParams` with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let pca_params = SingleCellPcaParams::from_r_list(r_list.clone())?;
        let fastmnn_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let ndist = fastmnn_list
            .get("ndist")
            .and_then(|v| v.as_real())
            .unwrap_or(3.0) as f32;
        let cos_norm = fastmnn_list
            .get("cos_norm")
            .and_then(|v| v.as_logical())
            .map(|rb| rb.is_true())
            .unwrap_or(true);
        let no_pcs = fastmnn_list
            .get("no_pcs")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;
        let sparse_svd = fastmnn_list
            .get("sparse_svd")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        Ok(Self {
            ndist,
            no_pcs,
            sparse_svd,
            cos_norm,
            knn_params,
            pca_params,
        })
    }
}

////////////////
// Seurat CCA //
////////////////

impl SeuratCcaParams {
    /// Generate the SeuratCcaParams from an R list
    ///
    /// Should values not be found within the list, the parameters will
    /// default to the values in `SeuratCcaParams::default()` (Seurat v3
    /// defaults).
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Seurat CCA parameters, plus nested
    ///   `knn_params` and PCA fields consumed by [KnnParams::from_r_list]
    ///   and [SingleCellPcaParams::from_r_list].
    ///
    /// ### Returns
    ///
    /// The `SeuratCcaParams` with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let pca_params = SingleCellPcaParams::from_r_list(r_list.clone())?;
        let cca_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let num_cc = cca_list
            .get("num_cc")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;
        let dims = cca_list
            .get("dims")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;
        let k_anchor = cca_list
            .get("k_anchor")
            .and_then(|v| v.as_integer())
            .unwrap_or(5) as usize;
        let k_filter = cca_list
            .get("k_filter")
            .and_then(|v| v.as_integer())
            .unwrap_or(200) as usize;
        let k_score = cca_list
            .get("k_score")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;
        let k_weight = cca_list
            .get("k_weight")
            .and_then(|v| v.as_integer())
            .unwrap_or(100) as usize;
        let n_top_features = cca_list
            .get("n_top_features")
            .and_then(|v| v.as_integer())
            .unwrap_or(200) as usize;
        let l2_norm = cca_list
            .get("l2_norm")
            .and_then(|v| v.as_logical())
            .map(|rb| rb.is_true())
            .unwrap_or(true);
        let sd = cca_list.get("sd").and_then(|v| v.as_real()).unwrap_or(1.0) as f32;

        Ok(Self {
            num_cc,
            dims,
            k_anchor,
            k_filter,
            k_score,
            k_weight,
            n_top_features,
            l2_norm,
            sd,
            knn_params,
            pca_params,
        })
    }
}

/////////////////
// Seurat rPCA //
/////////////////

impl SeuratRpcaParams {
    /// Generate the SeuratRpcaParams from an R list
    ///
    /// Should values not be found within the list, the parameters will
    /// default to the values in `SeuratRpcaParams::default()`. Note that
    /// rPCA does not use `num_cc`, `k_filter`, or `n_top_features` (the
    /// gene-space FilterAnchors step is CCA-only in Seurat).
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Seurat rPCA parameters, plus nested
    ///   `knn_params` and PCA fields consumed by [KnnParams::from_r_list]
    ///   and [SingleCellPcaParams::from_r_list].
    ///
    /// ### Returns
    ///
    /// The `SeuratRpcaParams` with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let pca_params = SingleCellPcaParams::from_r_list(r_list.clone())?;
        let rpca_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let dims = rpca_list
            .get("dims")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;
        let k_anchor = rpca_list
            .get("k_anchor")
            .and_then(|v| v.as_integer())
            .unwrap_or(5) as usize;
        let k_score = rpca_list
            .get("k_score")
            .and_then(|v| v.as_integer())
            .unwrap_or(30) as usize;
        let k_weight = rpca_list
            .get("k_weight")
            .and_then(|v| v.as_integer())
            .unwrap_or(100) as usize;
        let l2_norm = rpca_list
            .get("l2_norm")
            .and_then(|v| v.as_logical())
            .map(|rb| rb.is_true())
            .unwrap_or(true);
        let sd = rpca_list.get("sd").and_then(|v| v.as_real()).unwrap_or(1.0) as f32;

        Ok(Self {
            dims,
            k_anchor,
            k_score,
            k_weight,
            l2_norm,
            sd,
            knn_params,
            pca_params,
        })
    }
}

///////////
// miloR //
///////////

impl MiloRParams {
    /// Generate MiloRParams from an R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults based on heuristics.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the MiloR parameters
    ///
    /// ### Returns
    ///
    /// The `MiloRParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let prop = params_list
            .get("prop")
            .and_then(|v| v.as_real())
            .unwrap_or(0.2);

        let k_refine = params_list
            .get("k_refine")
            .and_then(|v| v.as_integer())
            .unwrap_or(20) as usize;

        let index_type = std::string::String::from(
            params_list
                .get("index_type")
                .and_then(|v| v.as_str())
                .unwrap_or("annoy"),
        );

        let refinement_strategy = std::string::String::from(
            params_list
                .get("refinement_strategy")
                .and_then(|v| v.as_str())
                .unwrap_or("approximate"),
        );

        Ok(Self {
            prop,
            k_refine,
            refinement_strategy,
            index_type,
            knn_params,
        })
    }
}

//////////////
// SEACells //
//////////////

impl SEACellsParams {
    /// Generate SEACellsParams from an R list
    ///
    /// Any element missing from the list falls back to the matching field of
    /// [SEACellsParams::default], so the two sides cannot drift apart.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the SEACells parameters.
    ///
    /// ### Returns
    ///
    /// The `SEACellsParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let seacells_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let lanczos_params = LanczosParams::from_r_list(&seacells_list)?;

        let n_sea_cells = seacells_list
            .get("n_sea_cells")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_sea_cells);

        let max_fw_iters = seacells_list
            .get("max_fw_iters")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_fw_iters);

        // convergence_epsilon: algorithm converges when RSS change < epsilon * RSS(0)
        let convergence_epsilon = seacells_list
            .get("convergence_epsilon")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.convergence_epsilon);

        let max_iter = seacells_list
            .get("max_iter")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_iter);

        let min_iter = seacells_list
            .get("min_iter")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_iter);

        let greedy_threshold = seacells_list
            .get("greedy_threshold")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.greedy_threshold);

        let graph_building = seacells_list
            .get("graph_building")
            .and_then(|v| v.as_str())
            .map(String::from)
            .unwrap_or(defaults.graph_building);

        let pruning = seacells_list
            .get("pruning")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.pruning);

        let pruning_threshold = seacells_list
            .get("pruning_threshold")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.pruning_threshold);

        let n_landmarks = seacells_list
            .get("n_landmarks")
            .and_then(|v| v.as_integer())
            .map(|x| x as usize);

        Ok(Self {
            // seacell
            n_sea_cells,
            max_fw_iters,
            convergence_epsilon,
            max_iter,
            min_iter,
            greedy_threshold,
            graph_building,
            pruning,
            pruning_threshold,
            n_landmarks,
            // knn
            knn_params,
            // eigensolver
            lanczos_params,
        })
    }
}

///////////////
// MetaCells //
///////////////

impl BootstrappedMetaCellParams {
    /// Generate the MetaCellParams from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list with the parameters.
    ///
    /// ### Return
    ///
    /// The `MetaCellParams` structure.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;
        let meta_cell_params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        // meta cell
        let max_shared = meta_cell_params
            .get("max_shared")
            .and_then(|v| v.as_integer())
            .unwrap_or(15) as usize;
        let target_no_metacells = meta_cell_params
            .get("target_no_metacells")
            .and_then(|v| v.as_integer())
            .unwrap_or(1000) as usize;
        let max_iter = meta_cell_params
            .get("max_iter")
            .and_then(|v| v.as_integer())
            .unwrap_or(5000) as usize;

        Ok(Self {
            max_shared,
            target_no_metacells,
            max_iter,
            knn_params,
        })
    }
}

////////////////
// SuperCells //
////////////////

impl SuperCellParams {
    /// Generate the SuperCellParams from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list with the parameters
    ///
    /// ### Return
    ///
    /// The `SuperCellParams` structure
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        // supercell
        let walk_length = params
            .get("walk_length")
            .and_then(|v| v.as_integer())
            .unwrap_or(3) as usize;

        let graining_factor = params
            .get("graining_factor")
            .and_then(|v| v.as_real())
            .unwrap_or(50.0);

        let use_kernel = params
            .get("use_kernel")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let k_ith = params
            .get("k_ith")
            .and_then(|v| v.as_integer())
            .map(|x| x as usize);
        let max_support = params
            .get("max_support")
            .and_then(|v| v.as_integer())
            .map(|x| x as usize);

        Ok(Self {
            walk_length,
            graining_factor,
            knn_params,
            use_kernel,
            k_ith,
            max_support,
        })
    }
}

////////////
// Vision //
////////////

impl SignatureGenes {
    /// Generate a SignatureGenes from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - An R list that is expected to have `"pos"` and `"neg"` with
    ///   0-index positions of the gene for this gene set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let r_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let positive: Vec<usize> = r_list
            .get("pos")
            .and_then(|v| v.as_integer_vector())
            .unwrap_or_default()
            .iter()
            .map(|x| *x as usize)
            .collect();

        let negative: Vec<usize> = r_list
            .get("neg")
            .and_then(|v| v.as_integer_vector())
            .unwrap_or_default()
            .iter()
            .map(|x| *x as usize)
            .collect();

        Ok(Self { positive, negative })
    }
}

/////////////
// Hotspot //
/////////////

impl HotSpotParams {
    /// Generate HotSpotParams from an R list
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults based on heuristics.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Boost parameters.
    ///
    /// ### Returns
    ///
    /// The `HotSpotParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        // hotspot
        let model = std::string::String::from(
            params_list
                .get("model")
                .and_then(|v| v.as_str())
                .unwrap_or("normal"),
        );

        let normalise = params_list
            .get("normalise")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        // both default to what `Hotspot.create_knn_graph` ships upstream
        let defaults = HotSpotGraphParams::default();
        let weighted_graph = params_list
            .get("weighted_graph")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.weighted_graph);

        let neighborhood_factor = params_list
            .get("neighborhood_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .filter(|v| *v > 0.0)
            .unwrap_or(defaults.neighborhood_factor);

        Ok(Self {
            model,
            normalise,
            knn_params,
            graph_params: HotSpotGraphParams::new(weighted_graph, neighborhood_factor),
        })
    }
}

/////////////
// Harmony //
/////////////

impl HarmonyParams {
    /// Generate HarmonyParams from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to the values defined in `HarmonyParams::default()`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Harmony parameters.
    ///
    /// ### Returns
    ///
    /// The `HarmonyParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let kmeans_params =
            KMeansParamsWrappers::from_r_list_with_iters(r_list.clone(), HARMONY_KMEANS_ITERS)?;
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let k = params_list
            .get("k")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.k);

        let sigma = params_list
            .get("sigma")
            .and_then(|v| v.as_real_vector())
            .map(|v| v.iter().map(|&x| x as f32).collect())
            .unwrap_or(defaults.sigma);

        let theta = params_list
            .get("theta")
            .and_then(|v| v.as_real_vector())
            .map(|v| v.iter().map(|&x| x as f32).collect())
            .unwrap_or(defaults.theta);

        let lambda = params_list
            .get("lambda")
            .and_then(|v| v.as_real_vector())
            .map(|v| v.iter().map(|&x| x as f32).collect())
            .unwrap_or(defaults.lambda);

        let block_size = params_list
            .get("block_size")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.block_size);

        let max_iter_kmeans = params_list
            .get("max_iter_kmeans")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_iter_kmeans);

        let max_iter_harmony = params_list
            .get("max_iter_harmony")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_iter_harmony);

        let epsilon_kmeans = params_list
            .get("epsilon_kmeans")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.epsilon_kmeans);

        let epsilon_harmony = params_list
            .get("epsilon_harmony")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.epsilon_harmony);

        let window_size = params_list
            .get("window_size")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.window_size);

        Ok(Self {
            k,
            sigma,
            theta,
            lambda,
            block_size,
            max_iter_kmeans,
            max_iter_harmony,
            epsilon_kmeans,
            epsilon_harmony,
            window_size,
            kmeans_params,
        })
    }
}

//////////////////
// Harmony (v2) //
//////////////////

impl HarmonyParamsV2 {
    /// Generate HarmonyParamsV2 from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to the values defined in `HarmonyParamsV2::default()`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Harmony parameters.
    ///
    /// ### Returns
    ///
    /// The `HarmonyParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let kmeans_params =
            KMeansParamsWrappers::from_r_list_with_iters(r_list.clone(), HARMONY_KMEANS_ITERS)?;
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let k = params_list
            .get("k")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.k);

        let sigma = params_list
            .get("sigma")
            .and_then(|v| v.as_real_vector())
            .map(|v| v.iter().map(|&x| x as f32).collect())
            .unwrap_or(defaults.sigma);

        let theta = params_list
            .get("theta")
            .and_then(|v| v.as_real_vector())
            .map(|v| v.iter().map(|&x| x as f32).collect())
            .unwrap_or(defaults.theta);

        let lambda = params_list
            .get("lambda")
            .and_then(|v| v.as_real_vector())
            .map(|v| v.iter().map(|&x| x as f32).collect())
            .unwrap_or(defaults.lambda);

        let block_size = params_list
            .get("block_size")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.block_size);

        let max_iter_kmeans = params_list
            .get("max_iter_kmeans")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_iter_kmeans);

        let max_iter_harmony = params_list
            .get("max_iter_harmony")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_iter_harmony);

        let epsilon_kmeans = params_list
            .get("epsilon_kmeans")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.epsilon_kmeans);

        let epsilon_harmony = params_list
            .get("epsilon_harmony")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.epsilon_harmony);

        let window_size = params_list
            .get("window_size")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.window_size);

        let alpha = params_list
            .get("alpha")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.alpha);

        let tau = params_list
            .get("tau")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.tau);

        let batch_proportion_cutoff = params_list
            .get("batch_proportion_cutoff")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.batch_proportion_cutoff);

        let use_dynamic_lambda = params_list
            .get("use_dynamic_lambda")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.use_dynamic_lambda);

        Ok(Self {
            k,
            sigma,
            theta,
            lambda,
            block_size,
            max_iter_kmeans,
            max_iter_harmony,
            epsilon_kmeans,
            epsilon_harmony,
            window_size,
            alpha,
            tau,
            batch_proportion_cutoff,
            use_dynamic_lambda,
            kmeans_params,
        })
    }
}

//////////////
// Symphomy //
//////////////

/////////////////////
// Symphony params //
/////////////////////

impl SymphonyMapParams {
    /// Generate [SymphonyMapParams] from an R list.
    ///
    /// Should values not be found within the list, parameters will default
    /// to sensible defaults based on Symphony R conventions.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Symphony mapping parameters.
    ///
    /// ### Returns
    ///
    /// The [SymphonyMapParams] with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = SymphonyMapParams::default();

        let sigma = params_list
            .get("sigma")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.sigma);
        let lambda = params_list
            .get("lambda")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.lambda);

        Ok(Self { sigma, lambda })
    }
}

////////////////////
// SCENIC - Trees //
////////////////////

impl RandomForestConfig {
    /// Generate RandomForestConfig from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to the values defined in `RandomForestConfig::default()`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the RandomForest parameters.
    ///
    /// ### Returns
    ///
    /// The `RandomForestConfig` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let n_trees = params_list
            .get("n_trees")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_trees);
        let min_samples_leaf = params_list
            .get("min_samples_leaf")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_samples_leaf);
        let n_features_split = params_list
            .get("n_features_split")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_features_split);
        let subsample_rate = params_list
            .get("subsample_rate")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.subsample_rate);
        let bootstrap = params_list
            .get("bootstrap")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.bootstrap);
        let max_depth = params_list
            .get("max_depth")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as usize))
            .unwrap_or(defaults.max_depth);
        let subsample_frac = params_list
            .get("subsample_frac")
            .and_then(|v| v.as_real())
            .map(|v| Some(v as f32))
            .unwrap_or(defaults.subsample_frac);

        Ok(Self {
            n_trees,
            min_samples_leaf,
            n_features_split,
            subsample_rate,
            bootstrap,
            max_depth,
            subsample_frac,
        })
    }
}

impl ExtraTreesConfig {
    /// Generate ExtraTreesConfig from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to the values defined in `ExtraTreesConfig::default()`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the ExtraTrees parameters.
    ///
    /// ### Returns
    ///
    /// The `ExtraTreesConfig` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let n_trees = params_list
            .get("n_trees")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_trees);
        let min_samples_leaf = params_list
            .get("min_samples_leaf")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_samples_leaf);
        let n_features_split = params_list
            .get("n_features_split")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_features_split);
        let n_thresholds = params_list
            .get("n_thresholds")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_thresholds);
        let max_depth = params_list
            .get("max_depth")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as usize))
            .unwrap_or(defaults.max_depth);
        let subsample_frac = params_list
            .get("subsample_frac")
            .and_then(|v| v.as_real())
            .map(|v| Some(v as f32))
            .unwrap_or(defaults.subsample_frac);

        Ok(Self {
            n_trees,
            min_samples_leaf,
            n_features_split,
            n_thresholds,
            max_depth,
            subsample_frac,
        })
    }
}

impl GradientBoostingConfig {
    /// Generate GradientBoostingConfig from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to the values defined in `GradientBoostingConfig::default()`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the GradientBoosting parameters.
    ///
    /// ### Returns
    ///
    /// The `GradientBoostingConfig` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let n_trees_max = params_list
            .get("n_trees_max")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_trees_max);
        let learning_rate = params_list
            .get("learning_rate")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.learning_rate);
        let max_depth = params_list
            .get("max_depth")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_depth);
        let min_samples_leaf = params_list
            .get("min_samples_leaf")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_samples_leaf);
        let early_stop_window = params_list
            .get("early_stop_window")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.early_stop_window);
        let subsample_rate = params_list
            .get("subsample_rate")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.subsample_rate);
        let n_features_split = params_list
            .get("n_features_split")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_features_split);

        Ok(Self {
            n_trees_max,
            learning_rate,
            max_depth,
            min_samples_leaf,
            early_stop_window,
            subsample_rate,
            n_features_split,
        })
    }
}

/////////////////////
// SCENIC - Params //
/////////////////////

impl ScenicParams {
    /// Generate `ScenicParams` from an R list.
    ///
    /// The list is expected to contain fields for all top-level SCENIC
    /// parameters plus the fields required by the chosen regression learner.
    /// Tree configuration parameters are read from the same flat list as the
    /// top-level parameters, following the same convention as `KnnParams` in
    /// other parameter structs.
    ///
    /// The `learner_type` field selects the regression learner:
    /// `"extratrees"` maps to `ExtraTreesConfig`, anything else (including the
    /// default `"randomforest"`) maps to `RandomForestConfig`. Learner
    /// parameters are then parsed from the same list via the respective
    /// `from_r_list` implementation.
    ///
    /// Should values not be found within the list, parameters will default to
    /// the values defined in `ScenicParams::default()`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list with the SCENIC parameters.
    ///
    /// ### Returns
    ///
    /// The `ScenicParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params: HashMap<&str, Robj> = r_list_to_map(r_list.clone())?;

        let min_counts = params
            .get("min_counts")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_counts);

        let min_cells = params
            .get("min_cells")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.min_cells);

        let gene_batch_strategy = params
            .get("gene_batch_strategy")
            .and_then(|v| v.as_str())
            .map(String::from)
            .unwrap_or(defaults.gene_batch_strategy);

        let gene_batch_size = params
            .get("gene_batch_size")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as usize))
            .unwrap_or(defaults.gene_batch_size);

        let n_pcs = params
            .get("n_pcs")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_pcs);

        let n_subsample = params
            .get("n_subsample")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_subsample);

        let learner_type = params
            .get("learner_type")
            .and_then(|v| v.as_str())
            .unwrap_or("randomforest");

        let regression_learner = match learner_type.to_lowercase().as_str() {
            "extratrees" => {
                RegressionLearner::ExtraTrees(ExtraTreesConfig::from_r_list(r_list.clone())?)
            }
            "grnboost2" => RegressionLearner::GradientBoosting(
                GradientBoostingConfig::from_r_list(r_list.clone())?,
            ),
            _ => RegressionLearner::RandomForest(RandomForestConfig::from_r_list(r_list.clone())?),
        };

        Ok(Self {
            min_counts,
            min_cells,
            regression_learner,
            gene_batch_strategy,
            gene_batch_size,
            n_pcs,
            n_subsample,
        })
    }
}

//////////////////
// H5adFileTask //
//////////////////

impl H5adFileTask {
    /// Generate an H5adFileTask from an R list
    ///
    /// Expects: exp_id, h5_path, cs_type, no_cells, no_genes,
    /// gene_local_to_universe (integer vector, NA for unmapped genes,
    /// 0-indexed).
    pub fn from_r_list(r_list: List) -> extendr_api::Result<Self> {
        let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let raw_slot: RawDataSlot = match map.get("raw_slot").and_then(|v| v.as_str()) {
            Some(s) => {
                parse_raw_slot(s).ok_or_else(|| Error::Other(format!("Invalid raw slot: {}", s)))?
            }
            None => RawDataSlot::default(),
        };

        let exp_id = map
            .get("exp_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("exp_id missing or not a string".into()))?
            .to_string();

        let h5_path = map
            .get("h5_path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("h5_path missing or not a string".into()))?
            .to_string();

        let cs_type_str = map
            .get("cs_type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("cs_type missing or not a string".into()))?;
        let cs_type = parse_h5ad_format(cs_type_str)
            .ok_or_else(|| Error::Other("cs_type must be 'csr' or 'csc'".into()))?;

        let no_cells = map
            .get("no_cells")
            .and_then(|v| v.as_integer())
            .ok_or_else(|| Error::Other("no_cells missing or not an integer".into()))?
            as usize;

        let no_genes = map
            .get("no_genes")
            .and_then(|v| v.as_integer())
            .ok_or_else(|| Error::Other("no_genes missing or not an integer".into()))?
            as usize;

        let mapping_raw: Vec<i32> = map
            .get("gene_local_to_universe")
            .ok_or_else(|| Error::Other("gene_local_to_universe missing".into()))?
            .as_integer_slice()
            .ok_or_else(|| Error::Other("gene_local_to_universe must be an integer vector".into()))?
            .to_vec();

        // R NA_integer_ is i32::MIN
        let gene_local_to_universe: Vec<Option<usize>> = mapping_raw
            .into_iter()
            .map(|v| {
                if v == i32::MIN {
                    None
                } else {
                    Some(v as usize)
                }
            })
            .collect();

        Ok(Self {
            exp_id,
            h5_path,
            cs_type,
            no_cells,
            no_genes,
            gene_local_to_universe,
            raw_slot,
        })
    }
}

//////////////////
// BinMergeTask //
//////////////////

impl BinMergeTask {
    /// Generate a BinMergeTask from an R list
    ///
    /// Expects: exp_id, bin_cells_path, cells_to_keep (0-indexed integer
    /// vector), gene_local_to_universe (integer vector, NA for unmapped
    /// genes, 0-indexed).
    pub fn from_r_list(r_list: List) -> extendr_api::Result<Self> {
        let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let exp_id = map
            .get("exp_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("exp_id missing or not a string".into()))?
            .to_string();

        let bin_cells_path = map
            .get("bin_cells_path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("bin_cells_path missing or not a string".into()))?
            .to_string();

        let cells_to_keep: Vec<usize> = map
            .get("cells_to_keep")
            .ok_or_else(|| Error::Other("cells_to_keep missing".into()))?
            .as_integer_slice()
            .ok_or_else(|| Error::Other("cells_to_keep must be an integer vector".into()))?
            .iter()
            .map(|&x| x as usize)
            .collect();

        let mapping_raw: Vec<i32> = map
            .get("gene_local_to_universe")
            .ok_or_else(|| Error::Other("gene_local_to_universe missing".into()))?
            .as_integer_slice()
            .ok_or_else(|| Error::Other("gene_local_to_universe must be an integer vector".into()))?
            .to_vec();

        // R NA_integer_ is i32::MIN
        let gene_local_to_universe: Vec<Option<u32>> = mapping_raw
            .into_iter()
            .map(|v| if v == i32::MIN { None } else { Some(v as u32) })
            .collect();

        Ok(Self {
            exp_id,
            bin_cells_path,
            cells_to_keep,
            gene_local_to_universe,
        })
    }
}

/////////////////
// MtxFileTask //
/////////////////

impl MtxFileTask {
    /// Generate an MtxFileTask from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list to converted to [MtxFileTask].
    ///
    /// ### Returns
    ///
    /// Self.
    pub fn from_r_list(r_list: List) -> extendr_api::Result<Self> {
        let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let exp_id = map
            .get("exp_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("exp_id missing or not a string".into()))?
            .to_string();

        let mtx_path = map
            .get("mtx_path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("mtx_path missing or not a string".into()))?
            .to_string();

        let cells_as_rows = map
            .get("cells_as_rows")
            .and_then(|v| v.as_bool())
            .ok_or_else(|| Error::Other("cells_as_rows missing or not a boolean".into()))?;

        let mapping_raw: Vec<i32> = map
            .get("gene_local_to_universe")
            .ok_or_else(|| Error::Other("gene_local_to_universe missing".into()))?
            .as_integer_slice()
            .ok_or_else(|| Error::Other("gene_local_to_universe must be an integer vector".into()))?
            .to_vec();

        let gene_local_to_universe: Vec<Option<usize>> = mapping_raw
            .into_iter()
            .map(|v| {
                if v == i32::MIN {
                    None
                } else {
                    Some(v as usize)
                }
            })
            .collect();

        Ok(Self {
            exp_id,
            mtx_path,
            gene_local_to_universe,
            cells_as_rows,
        })
    }
}

//////////////////
// TenxFileTask //
//////////////////

impl TenxFileTask {
    /// Generate a TenxFileTask from an R list
    ///
    /// Expects: exp_id, h5_path, version ("v2"/"v3"), no_cells, no_genes,
    /// gene_local_to_universe (integer vector, NA for unmapped / non-gene
    /// features, 0-indexed), feature_type (optional string).
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list to convert to [TenxFileTask].
    ///
    /// ### Returns
    ///
    /// Self.
    pub fn from_r_list(r_list: List) -> extendr_api::Result<Self> {
        let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let exp_id = map
            .get("exp_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("exp_id missing or not a string".into()))?
            .to_string();
        let h5_path = map
            .get("h5_path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("h5_path missing or not a string".into()))?
            .to_string();
        let version_str = map
            .get("version")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("version missing or not a string".into()))?;
        let version = parse_tenx_version(version_str)
            .ok_or_else(|| Error::Other("version must be 'v2' or 'v3'".into()))?;
        let no_cells = map
            .get("no_cells")
            .and_then(|v| v.as_integer())
            .ok_or_else(|| Error::Other("no_cells missing or not an integer".into()))?
            as usize;
        let no_genes = map
            .get("no_genes")
            .and_then(|v| v.as_integer())
            .ok_or_else(|| Error::Other("no_genes missing or not an integer".into()))?
            as usize;
        let mapping_raw: Vec<i32> = map
            .get("gene_local_to_universe")
            .ok_or_else(|| Error::Other("gene_local_to_universe missing".into()))?
            .as_integer_slice()
            .ok_or_else(|| Error::Other("gene_local_to_universe must be an integer vector".into()))?
            .to_vec();
        let gene_local_to_universe: Vec<Option<usize>> = mapping_raw
            .into_iter()
            .map(|v| {
                if v == i32::MIN {
                    None
                } else {
                    Some(v as usize)
                }
            })
            .collect();
        let feature_type = map
            .get("feature_type")
            .and_then(|v| v.as_str())
            .map(|v| v.to_string());
        Ok(Self {
            exp_id,
            h5_path,
            version,
            no_cells,
            no_genes,
            gene_local_to_universe,
            feature_type,
        })
    }
}

//////////////
// NicheNet //
//////////////

impl<T> LigandTargetParams<T>
where
    T: BixverseFloat,
{
    /// Generate the [LigandTargetParams] from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list to convert to [LigandTargetParams].
    ///
    /// ### Returns
    ///
    /// Self.
    pub fn from_r_list(r_list: List) -> extendr_api::Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = LigandTargetParams::default();

        let lr_sig_hub = params
            .get("lr_sig_hub")
            .and_then(|x| x.as_real())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(defaults.lr_sig_hub);
        let gr_hub = params
            .get("gr_hub")
            .and_then(|x| x.as_real())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(defaults.gr_hub);
        let ltf_cutoff = params
            .get("ltf_cutoff")
            .and_then(|x| x.as_real())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(defaults.ltf_cutoff);
        let damping_factor = params
            .get("damping_factor")
            .and_then(|x| x.as_real())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(defaults.damping_factor);
        let tol = params
            .get("tol")
            .and_then(|x| x.as_real())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(defaults.tol);
        let max_iter = params
            .get("max_iter")
            .and_then(|x| x.as_integer())
            .map(|x| x as usize)
            .unwrap_or(defaults.max_iter);
        let topology_correction = params
            .get("topology_correction")
            .and_then(|x| x.as_bool())
            .unwrap_or(defaults.topology_correction);
        let secondary_targets = params
            .get("secondary_targets")
            .and_then(|x| x.as_bool())
            .unwrap_or(defaults.secondary_targets);

        Ok(Self {
            lr_sig_hub,
            gr_hub,
            ltf_cutoff,
            damping_factor,
            max_iter,
            tol,
            secondary_targets,
            topology_correction,
        })
    }
}

/////////////////
// CellPhoneDB //
/////////////////

impl<T> CellPhoneDbParams<T>
where
    T: BixverseFloat,
{
    /// Generate the [CellPhoneDbParams] from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list to convert to [CellPhoneDbParams].
    ///
    /// ### Returns
    ///
    /// Self.
    pub fn from_r_list(r_list: List) -> extendr_api::Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = CellPhoneDbParams::default();

        let n_perm = params
            .get("n_perm")
            .and_then(|x| x.as_integer())
            .map(|x| x as usize)
            .unwrap_or(defaults.n_perm);
        let threshold = params
            .get("threshold")
            .and_then(|x| x.as_real())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(defaults.threshold);
        let seed = params
            .get("seed")
            .and_then(|x| x.as_integer())
            .map(|x| x as usize)
            .unwrap_or(defaults.seed);
        let perm_batch = params
            .get("perm_batch")
            .and_then(|x| x.as_integer())
            .map(|x| x as usize)
            .or(defaults.perm_batch);

        Ok(Self {
            n_perm,
            threshold,
            seed,
            perm_batch,
        })
    }
}

/////////////////////////
// MetaCells2 - Params //
/////////////////////////

//////////////////
// SelectParams //
//////////////////

impl SelectParams {
    /// Generate SelectParams from an R list, falling back to defaults.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let downsample_min_samples = params
            .get("downsample_min_samples")
            .and_then(|v| v.as_integer())
            .map(|v| v as u32)
            .unwrap_or(defaults.downsample_min_samples);

        let downsample_min_cell_quantile = params
            .get("downsample_min_cell_quantile")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.downsample_min_cell_quantile);

        let downsample_max_cell_quantile = params
            .get("downsample_max_cell_quantile")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.downsample_max_cell_quantile);

        let min_gene_total = params
            .get("min_gene_total")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as u32))
            .unwrap_or(defaults.min_gene_total);

        let min_gene_top3 = params
            .get("min_gene_top3")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as u32))
            .unwrap_or(defaults.min_gene_top3);

        let min_gene_relative_variance = params
            .get("min_gene_relative_variance")
            .and_then(|v| v.as_real())
            .map(|v| Some(v as f32))
            .unwrap_or(defaults.min_gene_relative_variance);

        let min_genes = params
            .get("min_genes")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_genes);

        let relative_variance_window_size = params
            .get("relative_variance_window_size")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.relative_variance_window_size);

        Ok(Self {
            downsample_min_samples,
            downsample_min_cell_quantile,
            downsample_max_cell_quantile,
            min_gene_total,
            min_gene_top3,
            min_gene_relative_variance,
            min_genes,
            relative_variance_window_size,
            lateral_gene_mask: defaults.lateral_gene_mask,
        })
    }
}

//////////////////////
// SimilarityParams //
//////////////////////

impl SimilarityParams {
    /// Generate SimilarityParams from an R list, falling back to defaults.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let method = match params.get("similarity_method").and_then(|v| v.as_str()) {
            Some(s) => match s.to_lowercase().as_str() {
                "log_pearson" | "logpearson" => SimilarityMethod::LogPearson,
                "pearson" => SimilarityMethod::Pearson,
                "spearman" => SimilarityMethod::Spearman,
                other => {
                    return Err(Error::Other(format!(
                        "Invalid similarity method: {}",
                        other
                    )));
                }
            },
            None => defaults.method,
        };

        let value_regularisation = params
            .get("value_regularisation")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.value_regularisation);

        Ok(Self {
            method,
            value_regularisation,
        })
    }
}

////////////////////
// MC2KnnParams   //
////////////////////

impl MC2KnnParams {
    /// Generate MC2KnnParams from an R list, falling back to defaults.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let balanced_ranks_factor = params
            .get("balanced_ranks_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.balanced_ranks_factor);

        let incoming_degree_factor = params
            .get("incoming_degree_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.incoming_degree_factor);

        let outgoing_degree_factor = params
            .get("outgoing_degree_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.outgoing_degree_factor);

        let min_outgoing_degree = params
            .get("min_outgoing_degree")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_outgoing_degree);

        let k_size_factor = params
            .get("k_size_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.k_size_factor);

        let k_umis_quantile = params
            .get("k_umis_quantile")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.k_umis_quantile);

        let min_knn_k = params
            .get("min_knn_k")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as usize))
            .unwrap_or(defaults.min_knn_k);

        let knn_k_override = params
            .get("knn_k_override")
            .and_then(|v| v.as_integer())
            .map(|v| Some(v as usize))
            .unwrap_or(defaults.knn_k_override);

        Ok(Self {
            balanced_ranks_factor,
            incoming_degree_factor,
            outgoing_degree_factor,
            min_outgoing_degree,
            k_size_factor,
            k_umis_quantile,
            min_knn_k,
            knn_k_override,
        })
    }
}

/////////////////////
// PartitionParams //
/////////////////////

impl PartitionParams {
    /// Generate PartitionParams from an R list, falling back to defaults.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let cooldown_pass = params
            .get("cooldown_pass")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.cooldown_pass);

        let cooldown_node = params
            .get("cooldown_node")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.cooldown_node);

        let cooldown_phase = params
            .get("cooldown_phase")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.cooldown_phase);

        let min_split_size_factor = params
            .get("min_split_size_factor")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.min_split_size_factor);

        let max_merge_size_factor = params
            .get("max_merge_size_factor")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.max_merge_size_factor);

        let max_split_min_cut_strength = params
            .get("max_split_min_cut_strength")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.max_split_min_cut_strength);

        let min_cut_seed_cells = params
            .get("min_cut_seed_cells")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_cut_seed_cells);

        let min_seed_size_quantile = params
            .get("min_seed_size_quantile")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.min_seed_size_quantile);

        let max_seed_size_quantile = params
            .get("max_seed_size_quantile")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.max_seed_size_quantile);

        Ok(Self {
            cooldown_pass,
            cooldown_node,
            cooldown_phase,
            min_split_size_factor,
            max_merge_size_factor,
            max_split_min_cut_strength,
            min_cut_seed_cells,
            min_seed_size_quantile,
            max_seed_size_quantile,
        })
    }
}

////////////////////
// DeviantsParams //
////////////////////

impl DeviantsParams {
    /// Generate DeviantsParams from an R list, falling back to defaults.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let min_gene_fold_factor = params
            .get("min_gene_fold_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.min_gene_fold_factor);

        let max_gene_fraction = params
            .get("max_gene_fraction")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.max_gene_fraction);

        let max_cell_fraction = params
            .get("max_cell_fraction")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.max_cell_fraction);

        let gap_skip_cells = params
            .get("gap_skip_cells")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.gap_skip_cells);

        let max_gap_cells_count = params
            .get("max_gap_cells_count")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.max_gap_cells_count);

        let max_gap_cells_fraction = params
            .get("max_gap_cells_fraction")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.max_gap_cells_fraction);

        let min_compare_umis = params
            .get("min_compare_umis")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.min_compare_umis);

        let cells_regularisation_quantile = params
            .get("cells_regularisation_quantile")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.cells_regularisation_quantile);

        Ok(Self {
            min_gene_fold_factor,
            max_gene_fraction,
            max_cell_fraction,
            gap_skip_cells,
            max_gap_cells_count,
            max_gap_cells_fraction,
            min_compare_umis,
            cells_regularisation_quantile,
        })
    }
}

////////////////////
// DissolveParams //
////////////////////

impl DissolveParams {
    /// Generate DissolveParams from an R list, falling back to defaults.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let min_robust_size_factor = params
            .get("min_robust_size_factor")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.min_robust_size_factor);

        let min_convincing_gene_fold_factor = params
            .get("min_convincing_gene_fold_factor")
            .and_then(|v| v.as_real())
            .map(|v| Some(v as f32))
            .unwrap_or(defaults.min_convincing_gene_fold_factor);

        Ok(Self {
            min_robust_size_factor,
            min_convincing_gene_fold_factor,
        })
    }
}

/////////////////////
// MetacellsParams //
/////////////////////

impl MetacellsParams {
    /// Generate MetacellsParams from a flat R list, recursively filling each
    /// sub-struct from the same list. Falls back to defaults for any missing
    /// field.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let select = SelectParams::from_r_list(r_list.clone())?;
        let similarity = SimilarityParams::from_r_list(r_list.clone())?;
        let knn = MC2KnnParams::from_r_list(r_list.clone())?;
        let partition = PartitionParams::from_r_list(r_list.clone())?;
        let deviants = DeviantsParams::from_r_list(r_list.clone())?;
        let dissolve = DissolveParams::from_r_list(r_list.clone())?;

        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let target_metacell_size = params
            .get("target_metacell_size")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.target_metacell_size);

        let min_metacell_size = params
            .get("min_metacell_size")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.min_metacell_size);

        // u64 — read as real to dodge R's i32 limit.
        let target_metacell_umis = params
            .get("target_metacell_umis")
            .and_then(|v| v.as_real())
            .map(|v| v as u64)
            .unwrap_or(defaults.target_metacell_umis);

        let must_complete_cover = params
            .get("must_complete_cover")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.must_complete_cover);

        let random_seed = params
            .get("random_seed")
            .and_then(|v| v.as_real())
            .map(|v| v as u64)
            .unwrap_or(defaults.random_seed);

        Ok(Self {
            select,
            similarity,
            knn,
            partition,
            deviants,
            dissolve,
            target_metacell_size,
            min_metacell_size,
            target_metacell_umis,
            must_complete_cover,
            random_seed,
        })
    }
}

////////////
// ScType //
////////////

impl CellTypeMarkers {
    /// Generate a [CellTypeMarkers] from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list from which to parse the cell markers
    ///
    /// ### Returns
    ///
    /// The [CellTypeMarkers] or Error
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let data: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let cell_type = data
            .get("cell_type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Other("cell_type missing or not a string".into()))?
            .to_string();

        let positive_indices: Vec<usize> = data
            .get("positive_indices")
            .and_then(|v| v.as_integer_vector())
            .map(|v| v.r_int_convert())
            .unwrap_or_default();

        let negative_indices: Vec<usize> = data
            .get("negative_indices")
            .and_then(|v| v.as_integer_vector())
            .map(|v| v.r_int_convert())
            .unwrap_or_default();

        Ok(Self {
            cell_type,
            positive_indices,
            negative_indices,
        })
    }
}

impl SctypeRes {
    /// Generate a [SctypeRes] from an R list
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list from which to parse the ScType results
    ///
    /// ### Returns
    ///
    /// The [SctypeRes] or Error
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let data: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let cell_types = data
            .get("cell_types")
            .and_then(|v| v.as_string_vector())
            .ok_or_else(|| Error::Other("cell_types missing or not a string vector".into()))?;

        let scores = data
            .get("scores")
            .and_then(|v| v.as_real_vector())
            .ok_or_else(|| Error::Other("scores missing or not a real vector".into()))?
            .r_float_convert();

        let n_cells: usize = data
            .get("n_cells")
            .and_then(|v| v.as_real())
            .map(|v| v as usize)
            .ok_or_else(|| Error::Other("n_cells missing or not an integer".into()))?;

        let n_cell_types: usize = data
            .get("n_cell_types")
            .and_then(|v| v.as_real())
            .map(|v| v as usize)
            .ok_or_else(|| Error::Other("n_cell_types missing or not an integer".into()))?;

        Ok(Self {
            cell_types,
            scores,
            n_cells,
            n_cell_types,
        })
    }
}

impl ScTypeCellParams {
    /// Generate the [ScTypeCellParams] from an R list
    ///
    /// Missing fields fall back to the defaults rather than erroring. An
    /// unrecognised calibration string is an error, since silently scoring on
    /// raw values would hide the mistake.
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list from which to parse the parameters
    ///
    /// ### Returns
    ///
    /// The [ScTypeCellParams] or Error
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let data: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let calibration =
            match data.get("calibration").and_then(|v| v.as_str()) {
                Some(s) => Some(parse_score_calibration(s).ok_or_else(|| {
                    Error::Other(format!("Invalid ScType score calibration: {}", s))
                })?),
                None => None,
            };

        Ok(Self::new(
            data.get("alpha")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
            data.get("iterations")
                .and_then(|v| v.as_integer())
                .map(|x| x as usize),
            data.get("tolerance")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
            calibration,
            data.get("score_floor")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
            data.get("purity_threshold")
                .and_then(|v| v.as_real())
                .map(|x| x as f32),
        ))
    }
}

//////////
// MELD //
//////////

impl MeldParams {
    /// Generate MeldParams from an R list, falling back to defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list from which to parse the arguments
    ///
    /// ### Returns
    ///
    /// The populated [MeldParams]
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let beta = params
            .get("beta")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.beta);

        let offset = params
            .get("offset")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.offset);

        let order = params
            .get("order")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.order);

        // An unrecognised string errors rather than falling back, matching
        // `ScTypeCellParams`: silently filtering with something other than what
        // was asked for hides the typo.
        let filter = match params.get("filter").and_then(|v| v.as_str()) {
            Some(s) => parse_meld_filter(s)
                .ok_or_else(|| Error::Other(format!("Invalid MELD filter: {}", s)))?,
            None => defaults.filter,
        };

        let chebyshev_order = params
            .get("chebyshev_order")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize)
            .unwrap_or(defaults.chebyshev_order);

        let lap_type = match params.get("lap_type").and_then(|v| v.as_str()) {
            Some(s) => parse_lap_type(s)
                .ok_or_else(|| Error::Other(format!("Invalid MELD Laplacian type: {}", s)))?,
            None => defaults.lap_type,
        };

        let normalise_indicators = params
            .get("normalise_indicators")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.normalise_indicators);

        Ok(Self {
            beta,
            offset,
            order,
            filter,
            chebyshev_order,
            lap_type,
            normalise_indicators,
            knn_params,
        })
    }
}

impl AucellParams {
    /// Generate AucellParams from an R list, falling back to defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list from which to parse the arguments
    ///
    /// ### Returns
    ///
    /// The populated [AucellParams]
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let auc_type = match params.get("auc_type").and_then(|v| v.as_str()) {
            Some(s) => {
                parse_auc_type(s).ok_or_else(|| Error::Other(format!("Invalid AUC type: {}", s)))?
            }
            None => defaults.auc_type,
        };

        let max_rank = params
            .get("max_rank")
            .and_then(|v| v.as_real())
            .map(|v| v as usize)
            .or(defaults.max_rank);

        let standardise = params
            .get("standardise")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.standardise);

        Ok(Self {
            auc_type,
            max_rank,
            standardise,
        })
    }
}

impl BinariseParams {
    /// Generate BinariseParams from an R list, falling back to defaults.
    ///
    /// ### Params
    ///
    /// * `r_list` - The R list from which to parse the arguments
    ///
    /// ### Returns
    ///
    /// The populated [BinariseParams]
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        let bw_adjust = params
            .get("bw_adjust")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.bw_adjust);

        let n_grid = params
            .get("n_grid")
            .and_then(|v| v.as_real())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_grid);

        let n_bins = params
            .get("n_bins")
            .and_then(|v| v.as_real())
            .map(|v| v as usize)
            .unwrap_or(defaults.n_bins);

        Ok(Self {
            bw_adjust,
            n_grid,
            n_bins,
        })
    }
}

//////////////
// Palantir //
//////////////

impl PalantirParams {
    /// Generate PalantirParams from an R list
    ///
    /// Any element missing from the list falls back to the matching field of
    /// [PalantirParams::default], so the two sides cannot drift apart. The
    /// nested kNN block is parsed by [KnnParams::from_r_list].
    ///
    /// Counts go through [r_list_count], which accepts both `10` and `10L` and
    /// errors on a value that is present but unusable. Previously a stray
    /// `knn = -5L` quietly became 30.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the Palantir parameters.
    ///
    /// ### Returns
    ///
    /// The `PalantirParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let knn_params = KnnParams::from_r_list(r_list.clone())?;

        let palantir_list: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let lanczos_params = LanczosParams::from_r_list(&palantir_list)?;

        let n_dcs = r_list_count(&palantir_list, "n_dcs")?.unwrap_or(defaults.n_dcs);

        let n_eigs = r_list_count(&palantir_list, "n_eigs")?;

        let knn = r_list_count(&palantir_list, "knn")?.unwrap_or(defaults.knn);

        let num_waypoints =
            r_list_count(&palantir_list, "num_waypoints")?.unwrap_or(defaults.num_waypoints);

        let scale_components = palantir_list
            .get("scale_components")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.scale_components);

        let use_early_cell_as_start = palantir_list
            .get("use_early_cell_as_start")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.use_early_cell_as_start);

        let max_iterations =
            r_list_count(&palantir_list, "max_iterations")?.unwrap_or(defaults.max_iterations);

        let branch_prob_threshold = palantir_list
            .get("branch_prob_threshold")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.branch_prob_threshold);

        Ok(Self {
            n_dcs,
            n_eigs,
            knn,
            num_waypoints,
            scale_components,
            use_early_cell_as_start,
            max_iterations,
            branch_prob_threshold,
            knn_params,
            lanczos_params,
        })
    }
}

///////////
// MAGIC //
///////////

impl MagicParams {
    /// Generate MagicParams from an R list
    ///
    /// Missing elements fall back to [MagicParams::default]. `layer` accepts
    /// `"norm"` or `"raw"`; anything else takes the default rather than
    /// erroring, matching how the other parsers here treat an unusable value.
    ///
    /// `n_steps` goes through [r_list_count_allow_zero] because zero is
    /// meaningful: it returns the un-imputed matrix.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the MAGIC parameters.
    ///
    /// ### Returns
    ///
    /// The `MagicParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let n_steps = r_list_count_allow_zero(&params, "n_steps")?.unwrap_or(defaults.n_steps);

        let clip_threshold = params
            .get("clip_threshold")
            .and_then(|v| v.as_real())
            .map(|v| v as f32)
            .unwrap_or(defaults.clip_threshold);

        let gene_batch_size =
            r_list_count(&params, "gene_batch_size")?.unwrap_or(defaults.gene_batch_size);

        let layer = params
            .get("layer")
            .and_then(|v| v.as_str())
            .and_then(parse_magic_layer)
            .unwrap_or(defaults.layer);

        let allow_large = params
            .get("allow_large")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.allow_large);

        Ok(Self {
            n_steps,
            clip_threshold,
            gene_batch_size,
            layer,
            allow_large,
        })
    }
}

/// Parse the R-side layer string into a [MagicLayer].
///
/// ### Params
///
/// * `s` - The layer name, `"norm"` or `"raw"`, case-insensitive.
///
/// ### Returns
///
/// The matching layer, or `None` if the string is not recognised.
pub fn parse_magic_layer(s: &str) -> Option<MagicLayer> {
    match s.to_lowercase().as_str() {
        "norm" | "normalised" | "normalized" => Some(MagicLayer::Norm),
        "raw" | "counts" => Some(MagicLayer::Raw),
        _ => None,
    }
}

/////////////////
// Gene trends //
/////////////////

impl BranchSelectionParams {
    /// Generate BranchSelectionParams from an R list
    ///
    /// Missing elements fall back to [BranchSelectionParams::default], which
    /// carries the reference's `q = eps = 1e-2` and a resolution of 500.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the branch selection parameters.
    ///
    /// ### Returns
    ///
    /// The `BranchSelectionParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let q = params
            .get("q")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.q);

        let eps = params
            .get("eps")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.eps);

        let resolution = r_list_count(&params, "resolution")?.unwrap_or(defaults.resolution);

        Ok(Self { q, eps, resolution })
    }
}

impl LandmarkGpParams {
    /// Generate LandmarkGpParams from an R list
    ///
    /// Missing elements fall back to [LandmarkGpParams::default], which carries
    /// mellon's `length_scale = sigma = 1.0`. Those defaults are a strong
    /// smoothing prior; see the module documentation of
    /// [crate::single_cell::sc_trajectory::gene_trends].
    ///
    /// ### Params
    ///
    /// * `params` - Parsed R list contents, already flattened to a map. Shares
    ///   the list with [GeneTrendsParams], so the keys sit at the same level
    ///   rather than in a nested block.
    ///
    /// ### Returns
    ///
    /// The `LandmarkGpParams` with all parameters set.
    pub fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self> {
        let defaults = Self::default();

        let length_scale = params
            .get("length_scale")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.length_scale);

        let sigma = params
            .get("sigma")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.sigma);

        let jitter = params
            .get("jitter")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.jitter);

        let max_jitter_retries = r_list_count_allow_zero(params, "max_jitter_retries")?
            .unwrap_or(defaults.max_jitter_retries);

        // Zero is legal here and means "use the default", which is what
        // `fit_landmark_gp` does with it.
        let chunk_size =
            r_list_count_allow_zero(params, "chunk_size")?.unwrap_or(defaults.chunk_size);

        Ok(Self {
            length_scale,
            sigma,
            jitter,
            max_jitter_retries,
            chunk_size,
        })
    }
}

impl GeneTrendsParams {
    /// Generate GeneTrendsParams from an R list
    ///
    /// The Gaussian process hyperparameters live in the same flat list and are
    /// parsed by [LandmarkGpParams::from_r_map]. `weighting` accepts
    /// `"hard_mask"` or `"fate_probability"`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the gene trend parameters.
    ///
    /// ### Returns
    ///
    /// The `GeneTrendsParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let defaults = Self::default();
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let gp = LandmarkGpParams::from_r_map(&params)?;

        let resolution = r_list_count(&params, "resolution")?.unwrap_or(defaults.resolution);

        let weighting = params
            .get("weighting")
            .and_then(|v| v.as_str())
            .and_then(parse_branch_weighting)
            .unwrap_or(defaults.weighting);

        Ok(Self {
            resolution,
            weighting,
            gp,
        })
    }
}

/// Parse the R-side weighting string into a [BranchWeighting].
///
/// ### Params
///
/// * `s` - The weighting name, `"hard_mask"` or `"fate_probability"`,
///   case-insensitive.
///
/// ### Returns
///
/// The matching weighting, or `None` if the string is not recognised.
pub fn parse_branch_weighting(s: &str) -> Option<BranchWeighting> {
    match s.to_lowercase().as_str() {
        "hard_mask" | "hardmask" | "mask" => Some(BranchWeighting::HardMask),
        "fate_probability" | "fateprobability" | "fate_prob" => {
            Some(BranchWeighting::FateProbability)
        }
        _ => None,
    }
}

//////////////
// DIALOGUE //
//////////////

impl PmdParams {
    /// Generate PmdParams from a flattened R list.
    ///
    /// Missing elements fall back to [PmdParams::default], which carries
    /// upstream's `DLG.get.param` values. Shares the list with [HlmParams] and
    /// [RefineParams], so the keys sit at the same level rather than in a
    /// nested block.
    ///
    /// ### Params
    ///
    /// * `params` - Parsed R list contents, already flattened to a map.
    ///
    /// ### Returns
    ///
    /// The `PmdParams` with all parameters set.
    pub fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self> {
        let defaults = Self::default();

        let k = r_list_count(params, "k")?.unwrap_or(defaults.k);

        let n_permutations =
            r_list_count(params, "n_permutations")?.unwrap_or(defaults.n_permutations);

        let extra_sparse = params
            .get("extra_sparse")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.extra_sparse);

        // Zero is legal and lets every sample into the ANOVA, however few cells
        // it contributed.
        let abn_c = r_list_count_allow_zero(params, "abn_c")?.unwrap_or(defaults.abn_c);

        let p_anova = params
            .get("p_anova")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.p_anova);

        let centre = params
            .get("centre")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.centre);

        let cap = params
            .get("cap")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.cap);

        let spatial = params
            .get("spatial")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.spatial);

        let n_genes = r_list_count(params, "n_genes")?.unwrap_or(defaults.n_genes);

        let min_ci = params
            .get("min_ci")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.min_ci);

        // An unrecognised string errors rather than falling back: collapsing
        // with something other than what was asked for hides the typo.
        let averaging = match params.get("averaging").and_then(|v| v.as_str()) {
            Some(s) => parse_averaging(s)
                .ok_or_else(|| Error::Other(format!("Invalid DIALOGUE averaging: {}", s)))?,
            None => defaults.averaging,
        };

        let mcp_assignment_p = params
            .get("mcp_assignment_p")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.mcp_assignment_p);

        // u64 — read as real to dodge R's i32 limit.
        let seed = params
            .get("seed")
            .and_then(|v| v.as_real())
            .map(|v| v as u64)
            .unwrap_or(defaults.seed);

        Ok(Self {
            k,
            n_permutations,
            extra_sparse,
            abn_c,
            p_anova,
            centre,
            cap,
            spatial,
            n_genes,
            min_ci,
            averaging,
            mcp_assignment_p,
            seed,
        })
    }
}

impl HlmParams {
    /// Generate HlmParams from a flattened R list.
    ///
    /// Missing elements fall back to [HlmParams::default]. Shares the list with
    /// [PmdParams] and [RefineParams].
    ///
    /// ### Params
    ///
    /// * `params` - Parsed R list contents, already flattened to a map.
    ///
    /// ### Returns
    ///
    /// The `HlmParams` with all parameters set.
    pub fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self> {
        let defaults = Self::default();

        // Zero is legal and drops the per-sample cell count requirement.
        let min_cells_per_sample = r_list_count_allow_zero(params, "min_cells_per_sample")?
            .unwrap_or(defaults.min_cells_per_sample);

        let use_tme_qc = params
            .get("use_tme_qc")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.use_tme_qc);

        let use_cell_quality = params
            .get("use_cell_quality")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.use_cell_quality);

        let satterthwaite = params
            .get("satterthwaite")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.satterthwaite);

        Ok(Self {
            min_cells_per_sample,
            use_tme_qc,
            use_cell_quality,
            satterthwaite,
        })
    }
}

impl RefineParams {
    /// Generate RefineParams from a flattened R list.
    ///
    /// Missing elements fall back to [RefineParams::default]. Shares the list
    /// with [PmdParams] and [HlmParams].
    ///
    /// ### Params
    ///
    /// * `params` - Parsed R list contents, already flattened to a map.
    ///
    /// ### Returns
    ///
    /// The `RefineParams` with all parameters set.
    pub fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self> {
        let defaults = Self::default();

        let support_p = params
            .get("support_p")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.support_p);

        let min_support_fraction = params
            .get("min_support_fraction")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.min_support_fraction);

        // Zero is legal and lets any non-empty stratum through.
        let min_stratum =
            r_list_count_allow_zero(params, "min_stratum")?.unwrap_or(defaults.min_stratum);

        let early_stop_cor = params
            .get("early_stop_cor")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.early_stop_cor);

        let permissive_p = params
            .get("permissive_p")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.permissive_p);

        let strict_p = params
            .get("strict_p")
            .and_then(|v| v.as_real())
            .unwrap_or(defaults.strict_p);

        Ok(Self {
            support_p,
            min_support_fraction,
            min_stratum,
            early_stop_cor,
            permissive_p,
            strict_p,
        })
    }
}

impl DialogueParams {
    /// Generate DialogueParams from a flat R list.
    ///
    /// The three stage blocks share one list, so the keys sit at the same level
    /// rather than in nested blocks. The list is flattened once and handed to
    /// [PmdParams::from_r_map], [HlmParams::from_r_map] and
    /// [RefineParams::from_r_map]. Nothing is validated here:
    /// [DialogueParams::validate] needs the cell type count, which the list does
    /// not carry, and `dialogue_run` calls it.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the DIALOGUE parameters.
    ///
    /// ### Returns
    ///
    /// The `DialogueParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        Ok(Self {
            pmd: PmdParams::from_r_map(&params)?,
            hlm: HlmParams::from_r_map(&params)?,
            refine: RefineParams::from_r_map(&params)?,
        })
    }
}

////////////
// NEBULA //
////////////

/// R-list parsing for [NebulaParams].
///
/// A trait rather than an inherent impl because [NebulaParams] is defined in
/// `edge-rs`.
pub trait NebulaParamsFromR: Sized {
    /// Parse the [NebulaParams] from a list
    ///
    /// ### Params
    ///
    /// * `params` - The flattened R list to parse
    ///
    /// ### Returns
    ///
    /// The [NebulaParams] populated by the R list, defaulting to the `nebula`
    /// package's own values.
    fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self>;
}

/// [NebulaParamsFromR] implementation
impl NebulaParamsFromR for NebulaParams {
    fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self> {
        let defaults = Self::default();

        let real = |key: &str, fallback: f64| -> f64 {
            params
                .get(key)
                .and_then(|v| v.as_real())
                .unwrap_or(fallback)
        };

        let method = match params.get("nebula_method").and_then(|v| v.as_str()) {
            Some(s) => parse_nebula_method(s)
                .ok_or_else(|| Error::Other(format!("Invalid NEBULA method: {}", s)))?,
            None => defaults.method,
        };

        Ok(Self {
            min: (
                real("min_sigma", defaults.min.0),
                real("min_phi", defaults.min.1),
            ),
            max: (
                real("max_sigma", defaults.max.0),
                real("max_phi", defaults.max.1),
            ),
            method,
            cutoff_cell: real("cutoff_cell", defaults.cutoff_cell),
            kappa: real("kappa", defaults.kappa),
            cpc: real("cpc", defaults.cpc),
            mincp: r_list_count(params, "mincp")?.unwrap_or(defaults.mincp),
            min_subjects: r_list_count_allow_zero(params, "min_subjects")?
                .unwrap_or(defaults.min_subjects),
            reml: params
                .get("reml")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.reml),
            eps: real("eps", defaults.eps),
        })
    }
}

/// R-list parsing for [ScTested].
///
/// A trait rather than an inherent impl because [ScTested] is defined in
/// `edge-rs`.
pub trait ScTestedFromR: Sized {
    /// Parse the [ScTested] from a list
    ///
    /// Expects either `coef`, a zero-based coefficient index, or `contrast`, one
    /// weight per coefficient. There is no default: which effect to report is
    /// the question the caller came to ask.
    ///
    /// ### Params
    ///
    /// * `params` - The flattened R list to parse
    ///
    /// ### Returns
    ///
    /// The [ScTested], or an error if neither key is present.
    fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self>;
}

/// [ScTestedFromR] implementation
impl ScTestedFromR for ScTested {
    fn from_r_map(params: &HashMap<&str, Robj>) -> Result<Self> {
        if let Some(contrast) = params.get("contrast").and_then(|v| v.as_real_vector()) {
            return Ok(ScTested::Contrast(contrast));
        }
        match r_list_count_allow_zero(params, "coef")? {
            Some(coef) => Ok(ScTested::Coef(coef)),
            None => Err(Error::Other(
                "NEBULA needs either `coef` or `contrast` to know what to test".into(),
            )),
        }
    }
}

impl NebulaScParams {
    /// Generate NebulaScParams from an R list
    ///
    /// The upstream NEBULA knobs fall back to the `nebula` package's own
    /// defaults. `coef` or `contrast` is required.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the NEBULA parameters.
    ///
    /// ### Returns
    ///
    /// The `NebulaScParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        Ok(Self {
            nebula: NebulaParams::from_r_map(&params)?,
            gene_batch_size: r_list_count(&params, "gene_batch_size")?
                .unwrap_or(defaults.gene_batch_size),
            shrink_dispersion: params
                .get("shrink_dispersion")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.shrink_dispersion),
            tested: ScTested::from_r_map(&params)?,
        })
    }
}

///////////////
// CellSweep //
///////////////

impl CellSweepParams {
    /// Generate CellSweepParams from an R list
    ///
    /// Anything missing from the list falls back to the reference
    /// implementation's default.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the CellSweep parameters.
    ///
    /// ### Returns
    ///
    /// The `CellSweepParams` with all parameters set.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = Self::default();

        Ok(Self {
            freeze_empties: params
                .get("freeze_empties")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.freeze_empties),
            freeze_ambient_profile: params
                .get("freeze_ambient_profile")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.freeze_ambient_profile),
            init_alpha: params
                .get("init_alpha")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.init_alpha),
            init_beta: params
                .get("init_beta")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.init_beta),
            alpha_cap: params
                .get("alpha_cap")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.alpha_cap),
            repulsion_strength: params
                .get("repulsion_strength")
                .and_then(|v| v.as_real())
                .map(|v| v as f32)
                .unwrap_or(defaults.repulsion_strength),
            max_frac_gene_repulsion: params
                .get("max_frac_gene_repulsion")
                .and_then(|v| v.as_real())
                .map(|v| v as f32)
                .unwrap_or(defaults.max_frac_gene_repulsion),
            celltype_lambda: params
                .get("celltype_lambda")
                .and_then(|v| v.as_real())
                .map(|v| v as f32)
                .unwrap_or(defaults.celltype_lambda),
            ambient_lambda: params
                .get("ambient_lambda")
                .and_then(|v| v.as_real())
                .map(|v| v as f32)
                .unwrap_or(defaults.ambient_lambda),
            bulk_lambda: params
                .get("bulk_lambda")
                .and_then(|v| v.as_real())
                .map(|v| v as f32)
                .unwrap_or(defaults.bulk_lambda),
            eps: params
                .get("eps")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.eps),
            log_eps: params
                .get("log_eps")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.log_eps),
            max_iter: r_list_count(&params, "max_iter")?.unwrap_or(defaults.max_iter),
            del0_ll_tol: params
                .get("del0_ll_tol")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.del0_ll_tol),
            min_ll_tol: params
                .get("min_ll_tol")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.min_ll_tol),
            tol_p: params
                .get("tol_p")
                .and_then(|v| v.as_real())
                .map(|v| v as f32)
                .unwrap_or(defaults.tol_p),
            tol_f: params
                .get("tol_f")
                .and_then(|v| v.as_real())
                .unwrap_or(defaults.tol_f),
            norm_from_rounded: params
                .get("norm_from_rounded")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.norm_from_rounded),
            seed: r_list_count(&params, "seed")?.unwrap_or(defaults.seed as usize) as u64,
        })
    }
}

/// Resolve the empty droplet calling strategy from an R list.
///
/// The method name and its numeric argument arrive as separate list entries,
/// so the variant is parsed first and then filled in. An unrecognised method
/// errors rather than falling back, and so does a method whose argument is
/// missing: a silent zero cutoff would call nothing empty and the model would
/// then fail much further downstream.
///
/// ### Params
///
/// * `r_list` - List with `method` plus, where the method needs one,
///   `umi_cutoff` or `expected_cells`.
///
/// ### Returns
///
/// The resolved `EmptyDropletCall`.
pub fn empty_droplet_call_from_r_list(r_list: List) -> Result<EmptyDropletCall> {
    let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

    let method = params
        .get("method")
        .and_then(|v| v.as_str())
        .ok_or_else(|| Error::Other("Empty droplet params need a 'method' entry.".to_string()))?;

    let call = parse_empty_droplet_call(method).ok_or_else(|| {
        Error::Other(format!(
            "'{method}' is not a known empty droplet method. Use one of 'supplied', 'umi_cutoff', 'expected_cells', 'knee'."
        ))
    })?;

    Ok(match call {
        EmptyDropletCall::UmiCutoff(_) => {
            let cutoff = r_list_count(&params, "umi_cutoff")?.ok_or_else(|| {
                Error::Other("method = 'umi_cutoff' needs a 'umi_cutoff' entry.".to_string())
            })?;
            EmptyDropletCall::UmiCutoff(cutoff as u32)
        }
        EmptyDropletCall::ExpectedCells(_) => {
            let expected = r_list_count(&params, "expected_cells")?.ok_or_else(|| {
                Error::Other(
                    "method = 'expected_cells' needs an 'expected_cells' entry.".to_string(),
                )
            })?;
            EmptyDropletCall::ExpectedCells(expected)
        }
        other => other,
    })
}

/// Generate a CellSweepSample from an R list
///
/// Expects `sample_id`, `real_cells` and `empty_cells` (both 0-indexed
/// integer vectors of store indices), `celltype_idx` (0-indexed integer
/// vector, one entry per `real_cells` entry) and `n_celltypes`.
///
/// `n_celltypes` is taken from the list rather than derived from the labels:
/// it has to match the factor levels the caller will map `z_hat` back onto, and
/// a level that happens to be unused in one sample would otherwise silently
/// shift every code above it.
///
/// ### Params
///
/// * `r_list` - The list describing one sample.
///
/// ### Returns
///
/// The `CellSweepSample`.
pub fn cellsweep_sample_from_r_list(r_list: List) -> Result<CellSweepSample> {
    let map: HashMap<&str, Robj> = r_list_to_map(r_list)?;

    let sample_id = map
        .get("sample_id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| Error::Other("sample_id missing or not a string".into()))?
        .to_string();

    let indices = |key: &str| -> Result<Vec<usize>> {
        Ok(map
            .get(key)
            .ok_or_else(|| Error::Other(format!("{key} missing")))?
            .as_integer_slice()
            .ok_or_else(|| Error::Other(format!("{key} must be an integer vector")))?
            .iter()
            .map(|&x| x as usize)
            .collect())
    };

    Ok(CellSweepSample {
        sample_id,
        real_cells: indices("real_cells")?,
        empty_cells: indices("empty_cells")?,
        celltype_idx: indices("celltype_idx")?,
        n_celltypes: r_list_count(&map, "n_celltypes")?
            .ok_or_else(|| Error::Other("n_celltypes missing".into()))?,
    })
}

impl CellSweepFit {
    /// Serialise one sample's fit into an R list.
    ///
    /// The cell-type profiles come back as a flat vector plus the cell-type
    /// count rather than as a matrix, so the caller decides whether to
    /// materialise an `n_celltypes x n_genes` matrix at all.
    ///
    /// ### Params
    ///
    /// * `sample_id` - Identifier of the sample this fit belongs to.
    ///
    /// ### Returns
    ///
    /// A list with `sample_id`, `alpha`, `z_hat` (1-based), `beta`,
    /// `ambient`, `celltype_profiles`, `n_celltypes`, `log_likelihood`,
    /// `n_iter` and `converged`.
    pub fn to_r_list(&self, sample_id: &str) -> List {
        let n_genes = self.ambient.len().max(1);

        list!(
            sample_id = sample_id,
            alpha = self.alpha.clone(),
            z_hat = self
                .z_hat
                .iter()
                .map(|&k| (k + 1) as i32)
                .collect::<Vec<i32>>(),
            beta = self.beta,
            ambient = self.ambient.iter().map(|&v| v as f64).collect::<Vec<f64>>(),
            celltype_profiles = self
                .celltype_profiles
                .iter()
                .map(|&v| v as f64)
                .collect::<Vec<f64>>(),
            n_celltypes = (self.celltype_profiles.len() / n_genes) as i32,
            log_likelihood = self.log_likelihood,
            n_iter = self.n_iter as i32,
            converged = self.converged
        )
    }
}

//////////////////
// scTransform //
//////////////////

impl SctParams {
    /// Generate the [SctParams] from an R list.
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults, which are sctransform's own with
    /// `vst.flavor = "v2"` applied.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the scTransform parameters.
    ///
    /// ### Return
    ///
    /// The [SctParams] with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = SctParams::default();

        // Counts and reals both go through the coercing readers: R writes `2000`
        // as a double and `2000L` as an integer, and the plain accessors match
        // one storage mode each, so a caller writing either form the accessor
        // does not expect would silently get the default instead.
        let n_genes = r_list_count(&params, "n_genes")?.unwrap_or(defaults.n_genes);
        let n_cells = r_list_count(&params, "n_cells")?.unwrap_or(defaults.n_cells);
        let min_cells = r_list_count(&params, "min_cells")?.unwrap_or(defaults.min_cells);

        let bw_adjust = r_list_real(&params, "bw_adjust")?.unwrap_or(defaults.bw_adjust);
        let gmean_eps = r_list_real(&params, "gmean_eps")?.unwrap_or(defaults.gmean_eps);
        let outlier_th = r_list_real(&params, "outlier_th")?.unwrap_or(defaults.outlier_th);
        let poisson_diff_theta =
            r_list_real(&params, "poisson_diff_theta")?.unwrap_or(defaults.poisson_diff_theta);

        // Both ends or neither: half a clipping range is meaningless, so a list
        // carrying only one is treated as carrying none.
        let clip_range = match (
            r_list_real(&params, "clip_min")?,
            r_list_real(&params, "clip_max")?,
        ) {
            (Some(lo), Some(hi)) => {
                validate_clip_range((lo, hi)).map_err(|e| Error::Other(e.to_string()))?;
                Some((lo, hi))
            }
            _ => defaults.clip_range,
        };

        Ok(Self {
            n_genes,
            n_cells,
            min_cells,
            bw_adjust,
            gmean_eps,
            outlier_th,
            poisson_diff_theta,
            clip_range,
        })
    }
}

impl SctModel {
    /// Serialise the [SctModel] into an R list.
    ///
    /// Round trips through [`SctModel::from_r_list`], so the R side can hold a
    /// fitted model between calls and hand it back for the residual PCA rather
    /// than refitting.
    ///
    /// `theta` is infinite for a Poisson gene, which R represents faithfully as
    /// `Inf`, so no sentinel is needed on either side and no separate flag has
    /// to travel with it.
    ///
    /// ### Return
    ///
    /// A list with the per-gene parameters and the scalars that go with them.
    pub fn to_r_list(&self) -> List {
        let genes: Vec<i32> = self.genes.iter().map(|&g| g as i32).collect();

        list!(
            genes = genes,
            theta = self.theta.clone(),
            coefficients = self.coefficients.clone(),
            n_coef = self.n_coef as i32,
            covariate_names = self.covariate_names.clone(),
            log_umi_coef = self.log_umi_coef,
            min_variance = self.min_variance,
            clip_min = self.clip_range.0,
            clip_max = self.clip_range.1,
        )
    }

    /// Rebuild an [SctModel] from the list [`SctModel::to_r_list`] produced.
    ///
    /// ### Params
    ///
    /// * `r_list` - The serialised model.
    ///
    /// ### Return
    ///
    /// The [SctModel], or an error naming the first field that is missing or
    /// the wrong length. Unlike the parameter structs there are no defaults
    /// here: a partially reconstructed model would silently produce wrong
    /// residuals.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let required = |name: &'static str| -> Result<&Robj> {
            params
                .get(name)
                .ok_or_else(|| Error::Other(format!("scTransform model is missing '{name}'")))
        };

        let genes: Vec<usize> = required("genes")?
            .as_integer_slice()
            .ok_or_else(|| Error::Other("scTransform model 'genes' is not integer".to_string()))?
            .iter()
            .map(|&g| g as usize)
            .collect();

        let theta = required("theta")?
            .as_real_vector()
            .ok_or_else(|| Error::Other("scTransform model 'theta' is not numeric".to_string()))?;

        let coefficients = required("coefficients")?.as_real_vector().ok_or_else(|| {
            Error::Other("scTransform model 'coefficients' is not numeric".to_string())
        })?;

        let n_coef = required("n_coef")?.as_integer().ok_or_else(|| {
            Error::Other("scTransform model 'n_coef' is not an integer".to_string())
        })? as usize;

        let covariate_names: Vec<String> = required("covariate_names")?
            .as_str_vector()
            .map(|v| v.into_iter().map(String::from).collect())
            .unwrap_or_default();

        // Without at least the intercept the design is empty and every
        // downstream `n_coef - 1` underflows.
        if n_coef == 0 {
            return Err(Error::Other(
                "scTransform model 'n_coef' must be at least 1 (the intercept)".to_string(),
            ));
        }

        let n = genes.len();
        for (name, len, want) in [
            ("theta", theta.len(), n),
            ("coefficients", coefficients.len(), n * n_coef),
            ("covariate_names", covariate_names.len(), n_coef - 1),
        ] {
            if len != want {
                return Err(Error::Other(format!(
                    "scTransform model '{name}' has {len} entries, expected {want}"
                )));
            }
        }

        // Gene lookups on a model are binary searches, so an axis that came back
        // in HVG-selection order would silently return wrong positions rather
        // than `None`.
        assert_ascending(&genes, "scTransform model genes")
            .map_err(|e| Error::Other(e.to_string()))?;

        let what = "scTransform model";
        let clip_range = (
            r_list_required_real(&params, "clip_min", what)?,
            r_list_required_real(&params, "clip_max", what)?,
        );
        validate_clip_range(clip_range).map_err(|e| Error::Other(e.to_string()))?;

        Ok(Self {
            genes,
            theta,
            coefficients,
            n_coef,
            covariate_names,
            log_umi_coef: r_list_required_real(&params, "log_umi_coef", what)?,
            min_variance: r_list_required_real(&params, "min_variance", what)?,
            clip_range,
        })
    }
}

impl SctCovariates {
    /// Serialise the [SctCovariates] into an R list.
    ///
    /// ### Return
    ///
    /// One named element per covariate, each a numeric vector of length
    /// `n_cells`. That is the shape [`SctCovariates::from_r_list`] reads, so the
    /// two are inverses, and it is the shape a data.frame column arrives in
    /// anyway.
    pub fn to_r_list(&self) -> List {
        let k = self.n_covariates();
        if k == 0 {
            return List::new(0);
        }
        let n_cells = self.values.len() / k;

        let columns: Vec<Robj> = (0..k)
            .map(|j| {
                let column: Vec<f64> = (0..n_cells).map(|c| self.row(c)[j]).collect();
                Robj::from(column)
            })
            .collect();

        let mut out = List::from_values(columns);
        out.set_names(self.names.iter().map(|s| s.as_str()))
            .expect("one name per covariate column by construction");
        out
    }

    /// Rebuild the [SctCovariates] from one column per covariate.
    ///
    /// The R side holds cell-level covariates as a data.frame, so columns are
    /// the natural thing to hand over: a named list of numeric vectors, each of
    /// length `n_cells`. The row-major flattening the model wants happens here
    /// via [`SctCovariates::from_columns`] rather than in R.
    ///
    /// An empty or absent list gives the empty covariate set, which is the
    /// common case and the one the residual arithmetic has a fast path for.
    ///
    /// ### Params
    ///
    /// * `r_list` - Named list of numeric vectors, one per covariate.
    ///
    /// ### Return
    ///
    /// The [SctCovariates], or an error when a column is not numeric or the
    /// columns disagree in length.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let mut columns: Vec<(String, Vec<f64>)> = Vec::with_capacity(r_list.len());

        for (name, value) in r_list.iter() {
            // A data.frame column is as likely to arrive as an integer as a
            // double (`as.integer`, a count, a dummy-coded factor), and
            // `as_real_vector` matches REALSXP alone.
            let values = value
                .as_real_vector()
                .or_else(|| {
                    value
                        .as_integer_slice()
                        .map(|s| s.iter().map(|&x| x as f64).collect())
                })
                .ok_or_else(|| {
                    Error::Other(format!(
                        "scTransform covariate '{name}' must be a numeric or integer vector"
                    ))
                })?;

            // `NA` arrives as NaN and would otherwise propagate silently through
            // the design into every fitted coefficient.
            if let Some(pos) = values.iter().position(|v| !v.is_finite()) {
                return Err(Error::Other(format!(
                    "scTransform covariate '{name}' has a missing or non-finite value at position {}",
                    pos + 1
                )));
            }

            columns.push((name.to_string(), values));
        }

        if columns.is_empty() {
            return Ok(Self::default());
        }

        Self::from_columns(&columns).map_err(|e| Error::Other(e.to_string()))
    }
}

impl SctGroupedFit {
    /// Serialise the [SctGroupedFit] into an R list.
    ///
    /// The models go out as a list of the lists [`SctModel::to_r_list`]
    /// produces, so a round trip is per model and nothing new has to be parsed.
    /// `genes` is the shared axis, already the intersection across groups, and
    /// is what an HVG set and a residual PCA are indexed against.
    ///
    /// ### Return
    ///
    /// A list with the per-group models, the shared gene axis and the group
    /// map.
    pub fn to_r_list(&self) -> List {
        let models = List::from_values(self.models.iter().map(|m| m.to_r_list()));
        let genes: Vec<i32> = self.genes.iter().map(|&g| g as i32).collect();
        let group_of_cell: Vec<i32> = self.group_of_cell.iter().map(|&g| g as i32).collect();

        list!(
            models = models,
            genes = genes,
            group_of_cell = group_of_cell,
            n_groups = self.models.len() as i32,
        )
    }

    /// Rebuild an [SctGroupedFit] from the list [`SctGroupedFit::to_r_list`]
    /// produced.
    ///
    /// `passes` comes back empty. It is a diagnostic of the fitting sweep and
    /// nothing downstream of the fit reads it, so it is not serialised and
    /// cannot be recovered. Everything the residual source needs, the models,
    /// the shared gene axis and the group map, round trips.
    ///
    /// ### Params
    ///
    /// * `r_list` - The serialised grouped fit.
    ///
    /// ### Return
    ///
    /// The [SctGroupedFit], or an error naming the first field that is missing,
    /// the wrong type, or inconsistent with the others.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let (models, genes, group_of_cell) =
            grouped_fit_parts(r_list, "scTransform grouped fit", SctModel::from_r_list)?;

        assert_ascending(&genes, "scTransform grouped fit genes")
            .map_err(|e| Error::Other(e.to_string()))?;

        Ok(Self {
            models,
            genes,
            passes: Vec::new(),
            group_of_cell,
        })
    }
}

/// Pull the shared parts of a serialised grouped fit back out of an R list.
///
/// Both grouped fits carry the same three things under the same names: a list
/// of per-model lists, a group id per selected cell, and `n_groups`. Only the
/// per-model parser and the presence of a shared gene axis differ, so the
/// common validation lives here rather than twice.
///
/// The checks mirror what the residual sources do at construction: a dense
/// group map covering `0..n_groups` and one model per group. Catching it here
/// means the error names the serialised field rather than surfacing later as a
/// mismatch inside `SctResiduals::new`.
///
/// ### Params
///
/// * `r_list` - The serialised grouped fit.
/// * `what` - Label for the error messages.
/// * `parse_model` - Per-model parser, `SctModel::from_r_list` or
///   `AprModel::from_r_list`.
///
/// ### Returns
///
/// The models, the gene axis (empty when the fit does not carry one) and the
/// group map, or an error naming the first field that does not hold up.
fn grouped_fit_parts<M>(
    r_list: List,
    what: &'static str,
    parse_model: impl Fn(List) -> Result<M>,
) -> Result<(Vec<M>, Vec<usize>, Vec<u32>)> {
    let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

    let required = |name: &'static str| -> Result<&Robj> {
        params
            .get(name)
            .ok_or_else(|| Error::Other(format!("{what} is missing '{name}'")))
    };

    let models_robj = required("models")?;
    let models_list = models_robj
        .as_list()
        .ok_or_else(|| Error::Other(format!("{what} 'models' is not a list")))?;

    let models: Vec<M> = models_list
        .values()
        .enumerate()
        .map(|(group, model)| {
            let model = model
                .as_list()
                .ok_or_else(|| Error::Other(format!("{what} model {group} is not a list")))?;
            parse_model(model)
        })
        .collect::<Result<Vec<M>>>()?;

    if models.is_empty() {
        return Err(Error::Other(format!("{what} carries no models")));
    }

    let group_of_cell: Vec<u32> = required("group_of_cell")?
        .as_integer_slice()
        .ok_or_else(|| Error::Other(format!("{what} 'group_of_cell' is not integer")))?
        .iter()
        .map(|&g| {
            u32::try_from(g)
                .map_err(|_| Error::Other(format!("{what} 'group_of_cell' has a negative entry")))
        })
        .collect::<Result<Vec<u32>>>()?;

    // Dense coverage of `0..n_groups`, the same invariant the residual sources
    // check. An empty group would leave a model no cell ever selects.
    let n_groups = validate_groups(&group_of_cell, group_of_cell.len())
        .map_err(|e| Error::Other(e.to_string()))?;

    if n_groups != models.len() {
        return Err(Error::Other(format!(
            "{what} has {} models but the group map implies {n_groups}",
            models.len()
        )));
    }

    // `genes` is absent on the analytic Pearson fit, whose shared axis is
    // derived in `AprResiduals::new` from the per-model sets.
    let genes: Vec<usize> = match params.get("genes") {
        Some(robj) if !robj.is_null() => robj
            .as_integer_slice()
            .ok_or_else(|| Error::Other(format!("{what} 'genes' is not integer")))?
            .iter()
            .map(|&g| {
                usize::try_from(g)
                    .map_err(|_| Error::Other(format!("{what} 'genes' has a negative entry")))
            })
            .collect::<Result<Vec<usize>>>()?,
        _ => Vec::new(),
    };

    Ok((models, genes, group_of_cell))
}

/////////////////////////////////
// Analytic Pearson residuals //
/////////////////////////////////

impl AprParams {
    /// Generate the [AprParams] from an R list.
    ///
    /// Missing values fall back to the defaults of Lause, Berens & Kobak:
    /// `theta = 100` and clipping at `+/- sqrt(n_cells)`.
    ///
    /// ### Params
    ///
    /// * `r_list` - The list with the analytic Pearson parameters.
    ///
    /// ### Return
    ///
    /// The [AprParams] with all of the parameters.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
        let defaults = AprParams::default();

        // Both readers accept either R storage mode; see `r_list_real`.
        let theta = r_list_real(&params, "theta")?.unwrap_or(defaults.theta);
        let min_cells =
            r_list_count_allow_zero(&params, "min_cells")?.unwrap_or(defaults.min_cells);

        // Both ends or neither: half a clipping range is meaningless, so a list
        // carrying only one is treated as carrying none.
        let clip_range = match (
            r_list_real(&params, "clip_min")?,
            r_list_real(&params, "clip_max")?,
        ) {
            (Some(lo), Some(hi)) => Some((lo, hi)),
            _ => defaults.clip_range,
        };

        let parsed = Self {
            theta,
            min_cells,
            clip_range,
        };
        // Catches a non-positive theta and an inverted or NaN clipping range
        // here, at the boundary, rather than letting `clamp` abort in a worker.
        parsed.validate().map_err(|e| Error::Other(e.to_string()))?;

        Ok(parsed)
    }
}

impl AprModel {
    /// Serialise the [AprModel] into an R list.
    ///
    /// ### Return
    ///
    /// A list with the gene axis, the marginals and the two scalars.
    pub fn to_r_list(&self) -> List {
        let genes: Vec<i32> = self.genes.iter().map(|&g| g as i32).collect();

        list!(
            genes = genes,
            gene_sums = self.gene_sums.clone(),
            total = self.total,
            theta = self.theta,
            clip_min = self.clip_range.0,
            clip_max = self.clip_range.1,
        )
    }

    /// Rebuild an [AprModel] from the list [`AprModel::to_r_list`] produced.
    ///
    /// ### Params
    ///
    /// * `r_list` - The serialised model.
    ///
    /// ### Return
    ///
    /// The [AprModel], or an error naming the first field that is missing or
    /// the wrong length. No defaults: a partially reconstructed model would
    /// silently produce wrong residuals.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;

        let required = |name: &'static str| -> Result<&Robj> {
            params
                .get(name)
                .ok_or_else(|| Error::Other(format!("Analytic Pearson model is missing '{name}'")))
        };

        let genes: Vec<usize> = required("genes")?
            .as_integer_slice()
            .ok_or_else(|| {
                Error::Other("Analytic Pearson model 'genes' is not integer".to_string())
            })?
            .iter()
            .map(|&g| g as usize)
            .collect();

        let gene_sums = required("gene_sums")?.as_real_vector().ok_or_else(|| {
            Error::Other("Analytic Pearson model 'gene_sums' is not numeric".to_string())
        })?;

        if gene_sums.len() != genes.len() {
            return Err(Error::Other(format!(
                "Analytic Pearson model 'gene_sums' has {} entries, expected {}",
                gene_sums.len(),
                genes.len()
            )));
        }

        // Gene lookups are binary searches, so an unsorted axis silently returns
        // the wrong position rather than `None`.
        assert_ascending(&genes, "Analytic Pearson model genes")
            .map_err(|e| Error::Other(e.to_string()))?;

        let what = "Analytic Pearson model";
        let model = Self {
            genes,
            gene_sums,
            total: r_list_required_real(&params, "total", what)?,
            theta: r_list_required_real(&params, "theta", what)?,
            clip_range: (
                r_list_required_real(&params, "clip_min", what)?,
                r_list_required_real(&params, "clip_max", what)?,
            ),
        };

        validate_clip_range(model.clip_range).map_err(|e| Error::Other(e.to_string()))?;
        // A zero total gives `p_gene = 0/0 = NaN` and an all-NaN residual
        // matrix, which the variance sweep would otherwise have to catch.
        if model.total <= 0.0 || model.total.is_nan() {
            return Err(Error::Other(format!(
                "{what} 'total' must be positive, got {}",
                model.total
            )));
        }
        if model.theta <= 0.0 || model.theta.is_nan() {
            return Err(Error::Other(format!(
                "{what} 'theta' must be positive, got {}",
                model.theta
            )));
        }

        Ok(model)
    }
}

impl AprGroupedFit {
    /// Serialise the [AprGroupedFit] into an R list.
    ///
    /// The per-cell totals travel with the models because they are part of the
    /// model, not a property of the store: they are sums over each group's own
    /// retained gene set, which the R side cannot recover from the library
    /// sizes.
    ///
    /// ### Return
    ///
    /// A list with the per-group models, the per-cell totals and the group map.
    pub fn to_r_list(&self) -> List {
        let models = List::from_values(self.models.iter().map(|m| m.to_r_list()));
        let group_of_cell: Vec<i32> = self.group_of_cell.iter().map(|&g| g as i32).collect();

        list!(
            models = models,
            cell_totals = self.cell_totals.clone(),
            group_of_cell = group_of_cell,
            n_groups = self.models.len() as i32,
        )
    }

    /// Rebuild an [AprGroupedFit] from the list [`AprGroupedFit::to_r_list`]
    /// produced.
    ///
    /// There is no shared gene axis to carry: [`AprResiduals::new`] derives it
    /// from the per-model sets, so the round trip is the models, the per-cell
    /// totals and the group map.
    ///
    /// ### Params
    ///
    /// * `r_list` - The serialised grouped fit.
    ///
    /// ### Return
    ///
    /// The [AprGroupedFit], or an error naming the first field that is missing,
    /// the wrong type, or inconsistent with the others.
    pub fn from_r_list(r_list: List) -> Result<Self> {
        let cell_totals = r_list_to_map(r_list.clone())?
            .get("cell_totals")
            .ok_or_else(|| {
                Error::Other("Analytic Pearson grouped fit is missing 'cell_totals'".to_string())
            })?
            .as_real_vector()
            .ok_or_else(|| {
                Error::Other(
                    "Analytic Pearson grouped fit 'cell_totals' is not numeric".to_string(),
                )
            })?;

        let (models, _genes, group_of_cell) = grouped_fit_parts(
            r_list,
            "Analytic Pearson grouped fit",
            AprModel::from_r_list,
        )?;

        // The totals are per selected cell, so they and the group map are two
        // views of the same axis and a disagreement means one of them belongs
        // to a different fit.
        if cell_totals.len() != group_of_cell.len() {
            return Err(Error::Other(format!(
                "Analytic Pearson grouped fit 'cell_totals' has {} entries but \
                 'group_of_cell' has {}",
                cell_totals.len(),
                group_of_cell.len()
            )));
        }

        Ok(Self {
            models,
            cell_totals,
            group_of_cell,
        })
    }
}

////////////
// Bonsai //
////////////

#[cfg(feature = "bonsai")]
mod bonsai_wrappers {
    use bonsai_rs::bonsai::StartTree;
    use bonsai_rs::sanity_sc_rs::config::VarianceRule;
    use bonsai_rs::search::nni::NniSearch;
    use bonsai_rs::search::spr::SprSearch;
    use bonsai_rs::tree::NO_NODE;
    use extendr_api::*;
    use std::collections::HashMap;

    use crate::single_cell::sc_analysis::bonsai::{
        BonsaiScParams, BonsaiScResult, parse_bonsai_layout,
    };
    use crate::utils::r_rust_interface::r_list_to_map;

    impl BonsaiScParams {
        /// Generate the [BonsaiScParams] from a flat R list.
        ///
        /// Missing elements fall back to [BonsaiScParams::default]. A string
        /// that names no known option is an error rather than a fallback.
        ///
        /// ### Params
        ///
        /// * `r_list` - Flat list with any of `variance_rule`,
        ///   `fixed_variance`, `variance_bins`, `variance_min`,
        ///   `variance_max`, `min_signal_to_noise`, `start`, `spr_search`,
        ///   `nni_search`, `seed`, `reroot`, `layout` and `hyperbolic`.
        ///
        /// ### Returns
        ///
        /// The [BonsaiScParams] with all of the parameters.
        pub fn from_r_list(r_list: List) -> Result<Self> {
            let params: HashMap<&str, Robj> = r_list_to_map(r_list)?;
            let mut out = Self::default();

            let real = |k: &str| params.get(k).and_then(|v| v.as_real());
            let text = |k: &str| params.get(k).and_then(|v| v.as_str());
            let unknown = |k: &str, v: &str| Error::Other(format!("Invalid Bonsai {k}: {v}"));

            if let Some(v) = text("variance_rule") {
                out.sanity.variance_rule = match v.to_lowercase().as_str() {
                    "fixed" => VarianceRule::Fixed(real("fixed_variance").ok_or_else(|| {
                        Error::Other(
                            "Bonsai variance_rule 'fixed' needs fixed_variance".to_string(),
                        )
                    })?),
                    s => parse_variance_rule(s).ok_or_else(|| unknown("variance_rule", v))?,
                };
            }
            if let Some(v) = params.get("variance_bins").and_then(|v| v.as_integer()) {
                out.sanity.variance_bins = v as usize;
            }
            if let Some(v) = real("variance_min") {
                out.sanity.variance_min = v;
            }
            if let Some(v) = real("variance_max") {
                out.sanity.variance_max = v;
            }
            if let Some(v) = real("min_signal_to_noise") {
                out.bonsai.ingest.min_signal_to_noise = v;
            }
            if let Some(v) = text("start") {
                out.bonsai.start = parse_start_tree(v).ok_or_else(|| unknown("start", v))?;
            }
            if let Some(v) = text("spr_search") {
                out.bonsai.spr.search =
                    parse_spr_search(v).ok_or_else(|| unknown("spr_search", v))?;
            }
            if let Some(v) = text("nni_search") {
                out.bonsai.nni.search =
                    parse_nni_search(v).ok_or_else(|| unknown("nni_search", v))?;
            }
            if let Some(v) = params.get("seed").and_then(|v| v.as_integer()) {
                out.bonsai.linkage.seed = v as usize;
                out.bonsai.spr.seed = v as u64;
                out.bonsai.nni.seed = v as u64;
            }
            if let Some(v) = params.get("reroot").and_then(|v| v.as_bool()) {
                out.bonsai.reroot = v;
            }
            if let Some(v) = text("layout") {
                out.layout = parse_bonsai_layout(v).ok_or_else(|| unknown("layout", v))?;
            }
            if let Some(v) = params.get("hyperbolic").and_then(|v| v.as_bool()) {
                out.hyperbolic = v;
            }

            Ok(out)
        }
    }

    /// Parse a Sanity variance rule other than `"fixed"`, which needs a value.
    ///
    /// ### Params
    ///
    /// * `s` - `"marginalise"`, `"posterior_mean"` or `"max_posterior"`
    ///
    /// ### Returns
    ///
    /// The rule, or `None` if the name is not recognised.
    pub fn parse_variance_rule(s: &str) -> Option<VarianceRule> {
        match s {
            "marginalise" => Some(VarianceRule::Marginalise),
            "posterior_mean" => Some(VarianceRule::PosteriorMean),
            "max_posterior" => Some(VarianceRule::MaxPosterior),
            _ => None,
        }
    }

    /// Parse the Bonsai start tree.
    ///
    /// ### Params
    ///
    /// * `s` - `"linkage"` or `"greedy_merge"`, case-insensitive
    ///
    /// ### Returns
    ///
    /// The start tree, or `None` if the name is not recognised.
    pub fn parse_start_tree(s: &str) -> Option<StartTree> {
        match s.to_lowercase().as_str() {
            "linkage" => Some(StartTree::Linkage),
            "greedy_merge" => Some(StartTree::GreedyMerge),
            _ => None,
        }
    }

    /// Parse the SPR search mode.
    ///
    /// ### Params
    ///
    /// * `s` - `"approximate"` (upstream's default approximations) or
    ///   `"exact"`, case-insensitive
    ///
    /// ### Returns
    ///
    /// The search mode, or `None` if the name is not recognised.
    pub fn parse_spr_search(s: &str) -> Option<SprSearch> {
        match s.to_lowercase().as_str() {
            "approximate" => Some(SprSearch::default()),
            "exact" => Some(SprSearch::Exact),
            _ => None,
        }
    }

    /// Parse the NNI search mode.
    ///
    /// ### Params
    ///
    /// * `s` - `"approximate"` (upstream's default approximations) or
    ///   `"exact"`, case-insensitive
    ///
    /// ### Returns
    ///
    /// The search mode, or `None` if the name is not recognised.
    pub fn parse_nni_search(s: &str) -> Option<NniSearch> {
        match s.to_lowercase().as_str() {
            "approximate" => Some(NniSearch::default()),
            "exact" => Some(NniSearch::Exact),
            _ => None,
        }
    }

    /// Convert a parent array to R integers, the root as `-1`.
    ///
    /// ### Params
    ///
    /// * `parent` - Parent per node, [NO_NODE] for the root
    ///
    /// ### Returns
    ///
    /// 0-indexed parents with `-1` for the root.
    pub fn parents_to_r(parent: &[u32]) -> Vec<i32> {
        parent
            .iter()
            .map(|&p| if p == NO_NODE { -1 } else { p as i32 })
            .collect()
    }

    /// Convert R parents back, `-1` (or any negative) as the root.
    ///
    /// ### Params
    ///
    /// * `parent` - 0-indexed parents, negative for the root
    ///
    /// ### Returns
    ///
    /// Parent per node, [NO_NODE] for the root.
    pub fn parents_from_r(parent: &[i32]) -> Vec<u32> {
        parent
            .iter()
            .map(|&p| if p < 0 { NO_NODE } else { p as u32 })
            .collect()
    }

    /// Serialise a Bonsai result for R.
    ///
    /// ### Params
    ///
    /// * `res` - The result
    ///
    /// ### Returns
    ///
    /// R list with `parent` (0-indexed, `-1` for the root), `branch`, `x`,
    /// `y`, `n_leaves`, `loglik`, `steps` (a list of `step` names, their
    /// `loglik` and `seconds`), `timings` (a list of `stage` and `seconds`) and
    /// `genes_used` (0-indexed).
    pub fn bonsai_sc_to_r_list(res: BonsaiScResult) -> List {
        let mut step = Vec::with_capacity(res.steps.len());
        let mut step_loglik = Vec::with_capacity(res.steps.len());
        let mut step_seconds = Vec::with_capacity(res.steps.len());
        for (name, loglik, secs) in res.steps {
            step.push(name);
            step_loglik.push(loglik);
            step_seconds.push(secs);
        }
        let (stage, stage_seconds): (Vec<String>, Vec<f64>) = res.timings.into_iter().unzip();
        list!(
            parent = parents_to_r(&res.parent),
            branch = res.branch,
            x = res.x,
            y = res.y,
            n_leaves = res.n_leaves as i32,
            loglik = res.loglik,
            steps = list!(step = step, loglik = step_loglik, seconds = step_seconds),
            timings = list!(stage = stage, seconds = stage_seconds),
            genes_used = res
                .genes_used
                .iter()
                .map(|&g| g as i32)
                .collect::<Vec<i32>>()
        )
    }
}

#[cfg(feature = "bonsai")]
pub use bonsai_wrappers::*;