bixverse-rs 0.3.5

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
//! Contains R-specific functions for single-cell data processing that need
//! the extendr interface.

use extendr_api::*;
use std::collections::HashMap;

use crate::ml::clustering::k_means::KMeansParamsWrappers;
use crate::prelude::{BixverseFloat, 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::{
    fast_clusters::FastLouvainParams,
    hotspot::HotSpotParams,
    meld::{MeldParams, parse_lap_type, parse_meld_filter},
    milo_r::MiloRParams,
    nichenet::ligand_regulatory_potential::LigandTargetParams,
    scenic::{
        ExtraTreesConfig, GradientBoostingConfig, RandomForestConfig, RegressionLearner,
        ScenicParams,
    },
    vision::SignatureGenes,
};
use crate::single_cell::sc_data::h5ad_io::parse_h5ad_format;

use crate::single_cell::sc_annotation::{
    sc_type::{CellTypeMarkers, SctypeRes},
    symphony::SymphonyMapParams,
};
use crate::single_cell::sc_batch_correction::{
    bbknn::BbknnParams, fast_mnn::FastMnnParams, harmony::HarmonyParams,
    harmony_v2::HarmonyParamsV2,
};
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::{
    doublet_detection::BoostParams, knn::KnnParams, pca::SingleCellPcaParams,
    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
/// * `k` - Number of metacells
///
/// ### Returns
///
/// R List with -1 indicating unassigned cells
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.try_into()?;

        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.try_into()?;

        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.
    ///
    /// ### 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.try_into()?;

        // 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"),
        );

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

        // annoy
        let n_tree = params_list
            .get("n_trees")
            .and_then(|v| v.as_integer())
            .unwrap_or(50) as usize;

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

        // 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 = params_list
            .get("ef_budget")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize);

        // hnsw
        let m = params_list
            .get("m")
            .and_then(|v| v.as_integer())
            .unwrap_or(16) as usize;

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

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

        // ivf
        let n_list = params_list
            .get("n_list")
            .and_then(|v| v.as_integer())
            .map(|v| v as usize);

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

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

//////////////
// 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.try_into()?;

        // 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 random_svd = scrublet_list
            .get("random_svd")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        // 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
        let n_bins_hist = 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,
            random_svd,
            // 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.try_into()?;

        // 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 random_svd = params_list
            .get("random_svd")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        // 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,
            random_svd,
            // 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.try_into()?;
        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,
            random_svd: map
                .get("random_svd")
                .and_then(|v| v.as_bool())
                .unwrap_or(defaults.random_svd),
            // 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
            n_trees: map
                .get("n_trees")
                .and_then(|v| v.as_integer())
                .unwrap_or(defaults.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 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 kmeans_params = KMeansParamsWrappers::from_r_list(r_list.clone())?;
        let params: HashMap<&str, Robj> = r_list.try_into()?;
        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.try_into()?;
        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 randomised = params
            .get("randomised")
            .and_then(|v| v.as_bool())
            .unwrap_or(defaults.randomised);

        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,
            randomised,
            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.try_into()?;

        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.try_into()?;

        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 random_svd = fastmnn_list
            .get("random_svd")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let sparse_svd = fastmnn_list
            .get("sparse_svd")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        Ok(Self {
            ndist,
            no_pcs,
            random_svd,
            sparse_svd,
            cos_norm,
            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.try_into()?;

        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
    ///
    /// Should values not be found within the List, the parameters will default
    /// to sensible defaults based on the original SEACells implementation.
    ///
    /// ### 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 knn_params = KnnParams::from_r_list(r_list.clone())?;

        let seacells_list: HashMap<&str, Robj> = r_list.try_into()?;

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

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

        // convergence_epsilon: algorithm converges when RSS change < epsilon * RSS(0)
        // Default: 1e-3 from Python implementation
        let convergence_epsilon = seacells_list
            .get("convergence_epsilon")
            .and_then(|v| v.as_real())
            .unwrap_or(1e-3) as f32;

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

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

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

        let graph_building = seacells_list
            .get("graph_building")
            .and_then(|v| v.as_str())
            .unwrap_or("union")
            .to_string();

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

        let pruning_threshold: f32 = seacells_list
            .get("pruning_threshold")
            .and_then(|v| v.as_real())
            .unwrap_or(1e-7) as f32;

        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,
        })
    }
}

///////////////
// 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.try_into()?;

        // 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.try_into()?;

        // 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.try_into()?;

        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.try_into()?;

        // 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);

        Ok(Self {
            model,
            normalise,
            knn_params,
        })
    }
}

/////////////
// 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(r_list.clone())?;
        let params_list: HashMap<&str, Robj> = r_list.try_into()?;

        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(r_list.clone())?;
        let params_list: HashMap<&str, Robj> = r_list.try_into()?;

        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.try_into()?;
        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.try_into()?;
        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.try_into()?;
        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.try_into()?;
        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.clone().try_into()?;

        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.try_into()?;

        let raw_slot: RawDataSlot = map
            .get("raw_slot")
            .and_then(|v| v.as_str())
            .and_then(parse_raw_slot)
            .unwrap_or_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.try_into()?;

        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.try_into()?;

        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.try_into()?;
        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.try_into()?;
        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,
        })
    }
}

/////////////////////////
// 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.try_into()?;
        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.try_into()?;
        let defaults = Self::default();

        let method = params
            .get("similarity_method")
            .and_then(|v| v.as_str())
            .map(|s| match s.to_lowercase().as_str() {
                "log_pearson" | "logpearson" => SimilarityMethod::LogPearson,
                "pearson" => SimilarityMethod::Pearson,
                "spearman" => SimilarityMethod::Spearman,
                _ => defaults.method,
            })
            .unwrap_or(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.try_into()?;
        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.try_into()?;
        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.try_into()?;
        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.try_into()?;
        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.try_into()?;
        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.try_into()?;

        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.try_into()?;

        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,
        })
    }
}

//////////
// 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.try_into()?;
        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);

        let filter = params
            .get("filter")
            .and_then(|v| v.as_str())
            .and_then(parse_meld_filter)
            .unwrap_or(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 = params
            .get("lap_type")
            .and_then(|v| v.as_str())
            .and_then(parse_lap_type)
            .unwrap_or(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,
        })
    }
}