Skip to content

Reading files

Source code in polars_bio/io.py
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
class IOOperations:
    @staticmethod
    def read_fasta(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
    ) -> pl.DataFrame:
        """

        Read a FASTA file into a DataFrame.

        Parameters:
            path: The path to the FASTA file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the FASTA file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

        !!! Example
            ```shell
            wget https://www.ebi.ac.uk/ena/browser/api/fasta/BK006935.2?download=true -O /tmp/test.fasta
            ```

            ```python
            import polars_bio as pb
            pb.read_fasta("/tmp/test.fasta").limit(1)
            ```
            ```shell
             shape: (1, 3)
            ┌─────────────────────────┬─────────────────────────────────┬─────────────────────────────────┐
            │ name                    ┆ description                     ┆ sequence                        │
            │ ---                     ┆ ---                             ┆ ---                             │
            │ str                     ┆ str                             ┆ str                             │
            ╞═════════════════════════╪═════════════════════════════════╪═════════════════════════════════╡
            │ ENA|BK006935|BK006935.2 ┆ TPA_inf: Saccharomyces cerevis… ┆ CCACACCACACCCACACACCCACACACCAC… │
            └─────────────────────────┴─────────────────────────────────┴─────────────────────────────────┘
            ```
        """
        return IOOperations.scan_fasta(
            path,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
        ).collect()

    @staticmethod
    def scan_fasta(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
    ) -> pl.LazyFrame:
        """

        Lazily read a FASTA file into a LazyFrame.

        Parameters:
            path: The path to the FASTA file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the FASTA file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

        !!! Example
            ```shell
            wget https://www.ebi.ac.uk/ena/browser/api/fasta/BK006935.2?download=true -O /tmp/test.fasta
            ```

            ```python
            import polars_bio as pb
            pb.scan_fasta("/tmp/test.fasta").limit(1).collect()
            ```
            ```shell
             shape: (1, 3)
            ┌─────────────────────────┬─────────────────────────────────┬─────────────────────────────────┐
            │ name                    ┆ description                     ┆ sequence                        │
            │ ---                     ┆ ---                             ┆ ---                             │
            │ str                     ┆ str                             ┆ str                             │
            ╞═════════════════════════╪═════════════════════════════════╪═════════════════════════════════╡
            │ ENA|BK006935|BK006935.2 ┆ TPA_inf: Saccharomyces cerevis… ┆ CCACACCACACCCACACACCCACACACCAC… │
            └─────────────────────────┴─────────────────────────────────┴─────────────────────────────────┘
            ```
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )
        fasta_read_options = FastaReadOptions(
            object_storage_options=object_storage_options
        )
        read_options = ReadOptions(fasta_read_options=fasta_read_options)
        return _read_file(path, InputFormat.Fasta, read_options, projection_pushdown)

    @staticmethod
    def read_vcf(
        path: str,
        info_fields: Union[list[str], None] = None,
        format_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        samples: Union[list[str], None] = None,
    ) -> pl.DataFrame:
        """
        Read a text VCF file into a DataFrame.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a VCF TBI/CSI
            index is present. See [File formats support](/polars-bio/features/#file-formats-support),
            [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

        Parameters:
            path: The path to the VCF file.
            info_fields: List of INFO field names to include. If *None*, all INFO fields from the VCF header are included by default. Use this to limit fields for better performance.
            format_fields: List of FORMAT field names to include (per-sample genotype data). If *None*, all FORMAT fields are included by default. For **single-sample** VCFs, FORMAT fields are top-level columns (e.g., `GT`, `DP`). For **multi-sample** VCFs, FORMAT data is exposed as a nested `genotypes` column (`struct<GT: list, DP: list, ...>`) with sample names in `meta["header"]["sample_names"]`.
            samples: Optional list of sample names to include from the VCF header. Matching is exact and case-sensitive. Missing sample names are skipped with a warning. The output follows the requested sample order.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the VCF file. If not specified, it will be detected automatically..
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using VCF TBI/CSI index files for efficient region-based filtering. Index files are auto-discovered (for example, `file.vcf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

        !!! Example "Reading VCF with INFO and FORMAT fields"
            ```python
            import polars_bio as pb

            # Read VCF with both INFO and FORMAT fields
            df = pb.read_vcf(
                "sample.vcf.gz",
                info_fields=["END"],              # INFO field
                format_fields=["GT", "DP", "GQ"]  # FORMAT fields
            )

            # Single-sample VCF: FORMAT fields are top-level columns (GT, DP, GQ)
            print(df.select(["chrom", "start", "ref", "alt", "END", "GT", "DP", "GQ"]))
            # Output:
            # shape: (10, 8)
            # ┌───────┬───────┬─────┬─────┬──────┬─────┬─────┬─────┐
            # │ chrom ┆ start ┆ ref ┆ alt ┆ END  ┆ GT  ┆ DP  ┆ GQ  │
            # │ str   ┆ u32   ┆ str ┆ str ┆ i32  ┆ str ┆ i32 ┆ i32 │
            # ╞═══════╪═══════╪═════╪═════╪══════╪═════╪═════╪═════╡
            # │ 1     ┆ 10009 ┆ A   ┆ .   ┆ null ┆ 0/0 ┆ 10  ┆ 27  │
            # │ 1     ┆ 10015 ┆ A   ┆ .   ┆ null ┆ 0/0 ┆ 17  ┆ 35  │
            # └───────┴───────┴─────┴─────┴──────┴─────┴─────┴─────┘

            # Multi-sample VCF: FORMAT data is nested in "genotypes"
            df = pb.read_vcf("multisample.vcf", format_fields=["GT", "DP"])
            print(df.select(["chrom", "start", "genotypes"]))
            ```
        """
        lf = IOOperations.scan_vcf(
            path=path,
            info_fields=info_fields,
            format_fields=format_fields,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
            samples=samples,
        )
        # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        # Set metadata on the collected DataFrame
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_vcf(
        path: str,
        info_fields: Union[list[str], None] = None,
        format_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        samples: Union[list[str], None] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a text VCF file into a LazyFrame.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a VCF TBI/CSI
            index is present. See [File formats support](/polars-bio/features/#file-formats-support),
            [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

        Parameters:
            path: The path to the VCF file.
            info_fields: List of INFO field names to include. If *None*, all INFO fields from the VCF header are included by default. Use this to limit fields for better performance.
            format_fields: List of FORMAT field names to include (per-sample genotype data). If *None*, all FORMAT fields are included by default. For **single-sample** VCFs, FORMAT fields are top-level columns (e.g., `GT`, `DP`). For **multi-sample** VCFs, FORMAT data is exposed as a nested `genotypes` column (`struct<GT: list, DP: list, ...>`) with sample names in `meta["header"]["sample_names"]`.
            samples: Optional list of sample names to include from the VCF header. Matching is exact and case-sensitive. Missing sample names are skipped with a warning. The output follows the requested sample order.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the VCF file. If not specified, it will be detected automatically..
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using VCF TBI/CSI index files for efficient region-based filtering. Index files are auto-discovered (for example, `file.vcf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

        !!! Example "Lazy scanning VCF with INFO and FORMAT fields"
            ```python
            import polars_bio as pb

            # Lazily scan VCF with both INFO and FORMAT fields
            lf = pb.scan_vcf(
                "sample.vcf.gz",
                info_fields=["END"],              # INFO field
                format_fields=["GT", "DP", "GQ"]  # FORMAT fields
            )

            # Apply filters and collect only what's needed
            df = lf.filter(pl.col("DP") > 20).select(
                ["chrom", "start", "ref", "alt", "GT", "DP", "GQ"]
            ).collect()

            # Single-sample VCF: FORMAT fields are top-level columns (GT, DP, GQ)
            # Multi-sample VCF: FORMAT data is nested in "genotypes"
            ```
        """
        _validate_variant_input_path(path, "vcf")
        return IOOperations._scan_variant(
            path=path,
            info_fields=info_fields,
            format_fields=format_fields,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
            samples=samples,
            genotype_output="string",
            source_format="vcf",
        )

    @staticmethod
    def read_bcf(
        path: str,
        info_fields: Union[list[str], None] = None,
        format_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        samples: Union[list[str], None] = None,
        genotype_output: str = "string",
    ) -> pl.DataFrame:
        """Read a BCF file into a DataFrame.

        Parameters:
            path: The path to the BCF file. The path must end in `.bcf`.
            info_fields: INFO fields to include. If *None*, all header-defined INFO fields are included.
            format_fields: FORMAT fields to include. Single-sample fields are top-level columns; multisample fields are nested in `genotypes`.
            samples: Optional sample names to include, in requested order.
            chunk_size: Object-store chunk size in MB.
            concurrent_fetches: Number of concurrent object-store fetches.
            allow_anonymous: Allow anonymous object-store access.
            enable_request_payer: Enable AWS request-payer access.
            max_retries: Maximum number of object-store retries.
            timeout: Object-store timeout in seconds.
            compression_type: Compression override. The default detects BCF automatically.
            projection_pushdown: Push column projection into the BCF reader.
            predicate_pushdown: Use a neighboring `.bcf.csi` index for genomic predicate pushdown when available.
            use_zero_based: Select 0-based half-open (`True`) or 1-based closed (`False`) coordinates. *None* uses global configuration.
            genotype_output: GT representation. `"string"` (default) returns VCF-style calls such as `"0/1"`. `"dosage"` returns the number of ALT alleles per sample as nullable `Int8` (normally 0, 1, or 2 for diploid calls); any missing allele yields null. Dosage requires GT to be the only selected FORMAT field and requires biallelic records. When `format_fields` is *None*, all header-defined FORMAT fields are selected, so pass `format_fields=["GT"]` when the header declares additional fields. Multiallelic records are rejected.

        !!! note
            BCF is input-only. Use `write_vcf` or `sink_vcf` to write text VCF.
        """
        lf = IOOperations.scan_bcf(
            path=path,
            info_fields=info_fields,
            format_fields=format_fields,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
            samples=samples,
            genotype_output=genotype_output,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_bcf(
        path: str,
        info_fields: Union[list[str], None] = None,
        format_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        samples: Union[list[str], None] = None,
        genotype_output: str = "string",
    ) -> pl.LazyFrame:
        """Lazily read a BCF file into a LazyFrame.

        BCF CSI range pushdown, projection pushdown, and configured input
        partition parallelism are preserved. `genotype_output="string"` returns
        VCF-style GT calls and remains the default. `genotype_output="dosage"`
        returns the number of ALT alleles per sample as nullable `Int8` (normally
        0, 1, or 2 for diploid calls); any missing allele yields null. Dosage
        requires GT to be the only selected FORMAT field and requires biallelic
        records. When `format_fields` is `None`, all header-defined FORMAT
        fields are selected, so pass `format_fields=["GT"]` when the header
        declares additional fields. Multiallelic records are rejected.
        """
        _validate_bcf_genotype_output(genotype_output, format_fields)
        _validate_variant_input_path(path, "bcf")
        return IOOperations._scan_variant(
            path=path,
            info_fields=info_fields,
            format_fields=format_fields,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
            samples=samples,
            genotype_output=genotype_output,
            source_format="bcf",
        )

    @staticmethod
    def _scan_variant(
        path: str,
        info_fields: Union[list[str], None],
        format_fields: Union[list[str], None],
        chunk_size: int,
        concurrent_fetches: int,
        allow_anonymous: bool,
        enable_request_payer: bool,
        max_retries: int,
        timeout: int,
        compression_type: str,
        projection_pushdown: bool,
        predicate_pushdown: bool,
        use_zero_based: Optional[bool],
        samples: Union[list[str], None],
        genotype_output: str,
        source_format: str,
    ) -> pl.LazyFrame:
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        # Upstream VCF reader projects all INFO fields by default when info_fields is None.
        initial_info_fields = info_fields

        zero_based = _resolve_zero_based(use_zero_based)
        vcf_read_options = VcfReadOptions(
            info_fields=initial_info_fields,
            format_fields=format_fields,
            samples=samples,
            object_storage_options=object_storage_options,
            zero_based=zero_based,
            genotype_output=genotype_output,
        )
        read_options = ReadOptions(vcf_read_options=vcf_read_options)
        lf = _read_file(
            path,
            InputFormat.Vcf,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )
        lf.config_meta.set(source_format=source_format)
        return lf

    @staticmethod
    def read_vcf_zarr(
        path: str,
        info_fields: Union[list[str], None] = None,
        format_fields: Union[list[str], None] = None,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        samples: Union[list[str], None] = None,
        genotype_encoding_raw: bool = True,
    ) -> pl.DataFrame:
        """
        Read a local VCF Zarr store into a DataFrame.

        Parameters:
            path: The path to the VCF Zarr store directory.
            info_fields: Optional list of INFO field names to include. If None, local INFO arrays are discovered automatically. Use [] to disable INFO fields.
            format_fields: Optional list of FORMAT field names to include. If None, local FORMAT arrays are discovered automatically. Use [] to disable FORMAT fields.
            projection_pushdown: Enable column projection pushdown at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown at the DataFusion level.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None, uses the global configuration.
            samples: Optional list of sample names to include.
            genotype_encoding_raw: If True, output GT as raw typed allele calls. If False, output VCF-style GT strings.
        """
        lf = IOOperations.scan_vcf_zarr(
            path=path,
            info_fields=info_fields,
            format_fields=format_fields,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
            samples=samples,
            genotype_encoding_raw=genotype_encoding_raw,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_vcf_zarr(
        path: str,
        info_fields: Union[list[str], None] = None,
        format_fields: Union[list[str], None] = None,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        samples: Union[list[str], None] = None,
        genotype_encoding_raw: bool = True,
    ) -> pl.LazyFrame:
        """
        Lazily read a local VCF Zarr store into a LazyFrame.

        Parameters:
            path: The path to the VCF Zarr store directory.
            info_fields: Optional list of INFO field names to include. If None, local INFO arrays are discovered automatically. Use [] to disable INFO fields.
            format_fields: Optional list of FORMAT field names to include. If None, local FORMAT arrays are discovered automatically. Use [] to disable FORMAT fields.
            projection_pushdown: Enable column projection pushdown at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown at the DataFusion level.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None, uses the global configuration.
            samples: Optional list of sample names to include.
            genotype_encoding_raw: If True, output GT as raw typed allele calls. If False, output VCF-style GT strings.
        """
        zero_based = _resolve_zero_based(use_zero_based)
        vcf_zarr_read_options = VcfZarrReadOptions(
            info_fields=info_fields,
            format_fields=format_fields,
            samples=samples,
            zero_based=zero_based,
            genotype_encoding_raw=genotype_encoding_raw,
        )
        read_options = ReadOptions(vcf_zarr_read_options=vcf_zarr_read_options)
        return _read_file(
            path,
            InputFormat.VcfZarr,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_gff(
        path: str,
        attr_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a GFF file into a DataFrame.

        Parameters:
            path: The path to the GFF file.
            attr_fields: List of attribute field names to extract as separate columns. If *None*, attributes will be kept as a nested structure. Use this to extract specific attributes like 'ID', 'gene_name', 'gene_type', etc. as direct columns for easier access.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the GFF file. If not specified, it will be detected automatically..
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gff.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        lf = IOOperations.scan_gff(
            path,
            attr_fields,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
        )
        # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        # Set metadata on the collected DataFrame
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_gff(
        path: str,
        attr_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a GFF file into a LazyFrame.

        Parameters:
            path: The path to the GFF file.
            attr_fields: List of attribute field names to extract as separate columns. If *None*, attributes will be kept as a nested structure. Use this to extract specific attributes like 'ID', 'gene_name', 'gene_type', etc. as direct columns for easier access.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the GFF file. If not specified, it will be detected automatically.
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gff.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        gff_read_options = GffReadOptions(
            attr_fields=attr_fields,
            object_storage_options=object_storage_options,
            zero_based=zero_based,
        )
        read_options = ReadOptions(gff_read_options=gff_read_options)
        _store_py_object_storage_options(read_options, object_storage_options)
        return _read_file(
            path,
            InputFormat.Gff,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_gtf(
        path: str,
        attr_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a GTF file into a DataFrame.

        GTF (Gene Transfer Format) shares the same 9-column structure as GFF but uses
        different attribute syntax (``key "value"`` vs GFF's ``key=value``).

        Parameters:
            path: The path to the GTF file.
            attr_fields: List of attribute field names to extract as separate columns.
                If *None*, attributes will be kept as a nested structure.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the GTF file. If not specified, it will be detected automatically.
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gtf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        lf = IOOperations.scan_gtf(
            path,
            attr_fields,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_gtf(
        path: str,
        attr_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a GTF file into a LazyFrame.

        GTF (Gene Transfer Format) shares the same 9-column structure as GFF but uses
        different attribute syntax (``key "value"`` vs GFF's ``key=value``).

        Parameters:
            path: The path to the GTF file.
            attr_fields: List of attribute field names to extract as separate columns.
                If *None*, attributes will be kept as a nested structure.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the GTF file. If not specified, it will be detected automatically.
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gtf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        gtf_read_options = GtfReadOptions(
            attr_fields=attr_fields,
            object_storage_options=object_storage_options,
            zero_based=zero_based,
        )
        read_options = ReadOptions(gtf_read_options=gtf_read_options)
        _store_py_object_storage_options(read_options, object_storage_options)
        return _read_file(
            path,
            InputFormat.Gtf,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_bam(
        path: str,
        tag_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        infer_tag_types: bool = True,
        infer_tag_sample_size: int = 100,
        tag_type_hints: Optional[list[str]] = None,
    ) -> pl.DataFrame:
        """
        Read a BAM file into a DataFrame.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a BAI/CSI index
            is present. See [File formats support](/polars-bio/features/#file-formats-support),
            [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

        Parameters:
            path: The path to the BAM file.
            tag_fields: List of BAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large-scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using index files (BAI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.bam.bai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
            infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
            infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
            tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        lf = IOOperations.scan_bam(
            path,
            tag_fields,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
            infer_tag_types,
            infer_tag_sample_size,
            tag_type_hints,
        )
        # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        # Set metadata on the collected DataFrame
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_bam(
        path: str,
        tag_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        infer_tag_types: bool = True,
        infer_tag_sample_size: int = 100,
        tag_type_hints: Optional[list[str]] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a BAM file into a LazyFrame.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a BAI/CSI index
            is present. See [File formats support](/polars-bio/features/#file-formats-support),
            [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

        Parameters:
            path: The path to the BAM file.
            tag_fields: List of BAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            predicate_pushdown: Enable predicate pushdown using index files (BAI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.bam.bai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
            infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
            infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
            tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type="auto",
        )

        zero_based = _resolve_zero_based(use_zero_based)
        if tag_type_hints is not None:
            _validate_tag_type_hints(tag_type_hints)
            tag_type_hints = _normalize_read_tag_type_hints(tag_type_hints)
        bam_read_options = BamReadOptions(
            object_storage_options=object_storage_options,
            zero_based=zero_based,
            tag_fields=tag_fields,
            infer_tag_types=infer_tag_types,
            infer_tag_sample_size=infer_tag_sample_size,
            tag_type_hints=tag_type_hints,
        )
        read_options = ReadOptions(bam_read_options=bam_read_options)
        return _read_file(
            path,
            InputFormat.Bam,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_cram(
        path: str,
        reference_path: str = None,
        tag_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        infer_tag_types: bool = True,
        infer_tag_sample_size: int = 100,
        tag_type_hints: Optional[list[str]] = None,
    ) -> pl.DataFrame:
        """
        Read a CRAM file into a DataFrame.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a CRAI index
            is present. See [File formats support](/polars-bio/features/#file-formats-support),
            [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

        Parameters:
            path: The path to the CRAM file (local or cloud storage: S3, GCS, Azure Blob).
            reference_path: Optional path to external FASTA reference file (**local path only**, cloud storage not supported). If not provided, the CRAM file must contain embedded reference sequences. The FASTA file must have an accompanying index file (.fai) in the same directory. Create the index using: `samtools faidx reference.fasta`
            tag_fields: List of CRAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
            predicate_pushdown: Enable predicate pushdown using index files (CRAI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.cram.crai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
            infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
            infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
            tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

        !!! warning "Known Limitation: MD and NM Tags"
            Due to a limitation in the underlying noodles-cram library, **MD (mismatch descriptor) and NM (edit distance) tags are not accessible** from CRAM files, even when stored in the file. These tags can be seen with samtools but are not exposed through the noodles-cram record.data() interface.

            Other optional tags (RG, MQ, AM, OQ, etc.) work correctly. This issue is tracked at: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

            **Workaround**: Use BAM format if MD/NM tags are required for your analysis.

        !!! example "Using External Reference"
            ```python
            import polars_bio as pb

            # Read CRAM with external reference
            df = pb.read_cram(
                "/path/to/file.cram",
                reference_path="/path/to/reference.fasta"
            )
            ```

        !!! example "Public CRAM File Example"
            Download and read a public CRAM file from 42basepairs:
            ```bash
            # Download the CRAM file and reference
            wget https://42basepairs.com/download/s3/gatk-test-data/wgs_cram/NA12878_20k_hg38/NA12878.cram
            wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta

            # Create FASTA index (required)
            samtools faidx Homo_sapiens_assembly38.fasta
            ```

            ```python
            import polars_bio as pb

            # Read first 5 reads from the CRAM file
            df = pb.scan_cram(
                "NA12878.cram",
                reference_path="Homo_sapiens_assembly38.fasta"
            ).limit(5).collect()

            print(df.select(["name", "chrom", "start", "end", "cigar"]))
            ```

        !!! example "Creating CRAM with Embedded Reference"
            To create a CRAM file with embedded reference using samtools:
            ```bash
            samtools view -C -o output.cram --output-fmt-option embed_ref=1 input.bam
            ```

        Returns:
            A Polars DataFrame with the following schema:
                - name: Read name (String)
                - chrom: Chromosome/contig name (String)
                - start: Alignment start position, 1-based (UInt32)
                - end: Alignment end position, 1-based (UInt32)
                - flags: SAM flags (UInt32)
                - cigar: CIGAR string (String)
                - mapping_quality: Mapping quality (UInt32)
                - mate_chrom: Mate chromosome/contig name (String)
                - mate_start: Mate alignment start position, 1-based (UInt32)
                - sequence: Read sequence (String)
                - quality_scores: Base quality scores (String)
        """
        lf = IOOperations.scan_cram(
            path,
            reference_path,
            tag_fields,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
            infer_tag_types,
            infer_tag_sample_size,
            tag_type_hints,
        )
        # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        # Set metadata on the collected DataFrame
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_cram(
        path: str,
        reference_path: str = None,
        tag_fields: Union[list[str], None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        infer_tag_types: bool = True,
        infer_tag_sample_size: int = 100,
        tag_type_hints: Optional[list[str]] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a CRAM file into a LazyFrame.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a CRAI index
            is present. See [File formats support](/polars-bio/features/#file-formats-support),
            [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

        Parameters:
            path: The path to the CRAM file (local or cloud storage: S3, GCS, Azure Blob).
            reference_path: Optional path to external FASTA reference file (**local path only**, cloud storage not supported). If not provided, the CRAM file must contain embedded reference sequences. The FASTA file must have an accompanying index file (.fai) in the same directory. Create the index using: `samtools faidx reference.fasta`
            tag_fields: List of CRAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
            predicate_pushdown: Enable predicate pushdown using index files (CRAI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.cram.crai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
            infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
            infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
            tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

        !!! warning "Known Limitation: MD and NM Tags"
            Due to a limitation in the underlying noodles-cram library, **MD (mismatch descriptor) and NM (edit distance) tags are not accessible** from CRAM files, even when stored in the file. These tags can be seen with samtools but are not exposed through the noodles-cram record.data() interface.

            Other optional tags (RG, MQ, AM, OQ, etc.) work correctly. This issue is tracked at: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

            **Workaround**: Use BAM format if MD/NM tags are required for your analysis.

        !!! example "Using External Reference"
            ```python
            import polars_bio as pb

            # Lazy scan CRAM with external reference
            lf = pb.scan_cram(
                "/path/to/file.cram",
                reference_path="/path/to/reference.fasta"
            )

            # Apply transformations and collect
            df = lf.filter(pl.col("chrom") == "chr1").collect()
            ```

        !!! example "Public CRAM File Example"
            Download and read a public CRAM file from 42basepairs:
            ```bash
            # Download the CRAM file and reference
            wget https://42basepairs.com/download/s3/gatk-test-data/wgs_cram/NA12878_20k_hg38/NA12878.cram
            wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta

            # Create FASTA index (required)
            samtools faidx Homo_sapiens_assembly38.fasta
            ```

            ```python
            import polars_bio as pb
            import polars as pl

            # Lazy scan and filter for chromosome 20 reads
            df = pb.scan_cram(
                "NA12878.cram",
                reference_path="Homo_sapiens_assembly38.fasta"
            ).filter(
                pl.col("chrom") == "chr20"
            ).select(
                ["name", "chrom", "start", "end", "mapping_quality"]
            ).limit(10).collect()

            print(df)
            ```

        !!! example "Creating CRAM with Embedded Reference"
            To create a CRAM file with embedded reference using samtools:
            ```bash
            samtools view -C -o output.cram --output-fmt-option embed_ref=1 input.bam
            ```

        Returns:
            A Polars LazyFrame with the following schema:
                - name: Read name (String)
                - chrom: Chromosome/contig name (String)
                - start: Alignment start position, 1-based (UInt32)
                - end: Alignment end position, 1-based (UInt32)
                - flags: SAM flags (UInt32)
                - cigar: CIGAR string (String)
                - mapping_quality: Mapping quality (UInt32)
                - mate_chrom: Mate chromosome/contig name (String)
                - mate_start: Mate alignment start position, 1-based (UInt32)
                - sequence: Read sequence (String)
                - quality_scores: Base quality scores (String)
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type="auto",
        )

        zero_based = _resolve_zero_based(use_zero_based)
        if tag_type_hints is not None:
            _validate_tag_type_hints(tag_type_hints)
            tag_type_hints = _normalize_read_tag_type_hints(tag_type_hints)
        cram_read_options = CramReadOptions(
            reference_path=reference_path,
            object_storage_options=object_storage_options,
            zero_based=zero_based,
            tag_fields=tag_fields,
            infer_tag_types=infer_tag_types,
            infer_tag_sample_size=infer_tag_sample_size,
            tag_type_hints=tag_type_hints,
        )
        read_options = ReadOptions(cram_read_options=cram_read_options)
        return _read_file(
            path,
            InputFormat.Cram,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def describe_bam(
        path: str,
        sample_size: int = 100,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Get schema information for a BAM file with automatic tag discovery.

        Samples the first N records to discover all available tags and their types.
        Returns detailed schema information including column names, data types,
        nullability, category (standard/tag), SAM type, and descriptions.

        Parameters:
            path: The path to the BAM file.
            sample_size: Number of records to sample for tag discovery (default: 100).
                Use higher values for more comprehensive tag discovery.
            chunk_size: The size in MB of a chunk when reading from object storage.
            concurrent_fetches: The number of concurrent fetches when reading from object storage.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file.
            timeout: The timeout in seconds for reading the file.
            compression_type: The compression type of the file. If "auto" (default), compression is detected automatically.
            use_zero_based: If True, output 0-based coordinates. If False, 1-based coordinates.

        Returns:
            DataFrame with columns:
            - column_name: Name of the column/field
            - data_type: Arrow data type (e.g., "Utf8", "Int32")
            - nullable: Whether the field can be null
            - category: "core" for fixed columns, "tag" for optional SAM tags
            - sam_type: SAM type code (e.g., "Z", "i") for tags, null for core columns
            - description: Human-readable description of the field

        Example:
            ```python
            import polars_bio as pb

            # Auto-discover all tags present in the file
            schema = pb.describe_bam("file.bam", sample_size=100)
            print(schema)
            # Output:
            # shape: (15, 6)
            # ┌─────────────┬───────────┬──────────┬──────────┬──────────┬──────────────────────┐
            # │ column_name ┆ data_type ┆ nullable ┆ category ┆ sam_type ┆ description          │
            # │ ---         ┆ ---       ┆ ---      ┆ ---      ┆ ---      ┆ ---                  │
            # │ str         ┆ str       ┆ bool     ┆ str      ┆ str      ┆ str                  │
            # ╞═════════════╪═══════════╪══════════╪══════════╪══════════╪══════════════════════╡
            # │ name        ┆ Utf8      ┆ true     ┆ core     ┆ null     ┆ Query name           │
            # │ chrom       ┆ Utf8      ┆ true     ┆ core     ┆ null     ┆ Reference name       │
            # │ ...         ┆ ...       ┆ ...      ┆ ...      ┆ ...      ┆ ...                  │
            # │ NM          ┆ Int32     ┆ true     ┆ tag      ┆ i        ┆ Edit distance        │
            # │ AS          ┆ Int32     ┆ true     ┆ tag      ┆ i        ┆ Alignment score      │
            # └─────────────┴───────────┴──────────┴──────────┴──────────┴──────────────────────┘
            ```
        """
        # Build object storage options
        object_storage_options = PyObjectStorageOptions(
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        # Resolve zero_based setting
        zero_based = _resolve_zero_based(use_zero_based)

        # Call Rust function with tag auto-discovery (tag_fields=None)
        df = py_describe_bam(
            ctx,  # PyBioSessionContext
            path,
            object_storage_options,
            zero_based,
            None,  # tag_fields=None enables auto-discovery
            sample_size,
        )

        # Convert DataFusion DataFrame to Polars DataFrame
        return pl.from_arrow(df.to_arrow_table())

    @staticmethod
    def describe_cram(
        path: str,
        reference_path: str = None,
        sample_size: int = 100,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Get schema information for a CRAM file with automatic tag discovery.

        Samples the first N records to discover all available tags and their types.
        Returns detailed schema information including column names, data types,
        nullability, category (core/tag), SAM type, and descriptions.

        Parameters:
            path: The path to the CRAM file.
            reference_path: Optional path to external FASTA reference file.
            sample_size: Number of records to sample for tag discovery (default: 100).
            chunk_size: The size in MB of a chunk when reading from object storage.
            concurrent_fetches: The number of concurrent fetches when reading from object storage.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file.
            timeout: The timeout in seconds for reading the file.
            compression_type: The compression type of the file. If "auto" (default), compression is detected automatically.
            use_zero_based: If True, output 0-based coordinates. If False, 1-based coordinates.

        Returns:
            DataFrame with columns:
            - column_name: Name of the column/field
            - data_type: Arrow data type (e.g., "Utf8", "Int32")
            - nullable: Whether the field can be null
            - category: "core" for fixed columns, "tag" for optional SAM tags
            - sam_type: SAM type code (e.g., "Z", "i") for tags, null for core columns
            - description: Human-readable description of the field

        !!! warning "Known Limitation: MD and NM Tags"
            Due to a limitation in the underlying noodles-cram library, **MD (mismatch descriptor) and NM (edit distance) tags are not discoverable** from CRAM files, even when stored. Automatic tag discovery will not include MD/NM tags. Other optional tags (RG, MQ, AM, OQ, etc.) are discovered correctly. See: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

        Example:
            ```python
            import polars_bio as pb

            # Auto-discover all tags present in the file
            schema = pb.describe_cram("file.cram", sample_size=100)
            print(schema)

            # Filter to see only tag columns
            tags = schema.filter(schema["category"] == "tag")
            print(tags["column_name"])
            ```
        """
        # Build object storage options
        object_storage_options = PyObjectStorageOptions(
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        # Resolve zero_based setting
        zero_based = _resolve_zero_based(use_zero_based)

        # Call Rust function with tag auto-discovery (tag_fields=None)
        df = py_describe_cram(
            ctx,
            path,
            reference_path,
            object_storage_options,
            zero_based,
            None,  # tag_fields=None enables auto-discovery
            sample_size,
        )

        # Convert DataFusion DataFrame to Polars DataFrame
        return pl.from_arrow(df.to_arrow_table())

    @staticmethod
    def read_fastq(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
    ) -> pl.DataFrame:
        """
        Read a FASTQ file into a DataFrame.

        !!! hint "Parallelism & Compression"
            See [File formats support](/polars-bio/features/#file-formats-support),
            [Compression](/polars-bio/features/#compression),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details on parallel reads and supported compression types.

        Parameters:
            path: The path to the FASTQ file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the FASTQ file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        """
        return IOOperations.scan_fastq(
            path,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
        ).collect()

    @staticmethod
    def scan_fastq(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
    ) -> pl.LazyFrame:
        """
        Lazily read a FASTQ file into a LazyFrame.

        !!! hint "Parallelism & Compression"
            See [File formats support](/polars-bio/features/#file-formats-support),
            [Compression](/polars-bio/features/#compression),
            and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details on parallel reads and supported compression types.

        Parameters:
            path: The path to the FASTQ file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the FASTQ file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        fastq_read_options = FastqReadOptions(
            object_storage_options=object_storage_options,
        )
        read_options = ReadOptions(fastq_read_options=fastq_read_options)
        return _read_file(path, InputFormat.Fastq, read_options, projection_pushdown)

    @staticmethod
    def read_pairs(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a Pairs (Hi-C) file into a DataFrame.

        The Pairs format (4DN project) stores chromatin contact data with columns:
        readID, chr1, pos1, chr2, pos2, strand1, strand2.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a TBI index
            is present. See [File formats support](/polars-bio/features/#file-formats-support)
            and [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown) for details.

        Parameters:
            path: The path to the Pairs file (.pairs, .pairs.gz, .pairs.bgz).
            chunk_size: The size in MB of a chunk when reading from an object store.
            concurrent_fetches: The number of concurrent fetches when reading from an object store.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type. If not specified, it will be detected automatically.
            projection_pushdown: Enable column projection pushdown to optimize query performance.
            predicate_pushdown: Enable predicate pushdown using index files (TBI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.pairs.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        lf = IOOperations.scan_pairs(
            path,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_pairs(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a Pairs (Hi-C) file into a LazyFrame.

        The Pairs format (4DN project) stores chromatin contact data with columns:
        readID, chr1, pos1, chr2, pos2, strand1, strand2.

        !!! hint "Parallelism & Indexed Reads"
            Indexed parallel reads and predicate pushdown are automatic when a TBI index
            is present. See [File formats support](/polars-bio/features/#file-formats-support)
            and [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown) for details.

        Parameters:
            path: The path to the Pairs file (.pairs, .pairs.gz, .pairs.bgz).
            chunk_size: The size in MB of a chunk when reading from an object store.
            concurrent_fetches: The number of concurrent fetches when reading from an object store.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type. If not specified, it will be detected automatically.
            projection_pushdown: Enable column projection pushdown to optimize query performance.
            predicate_pushdown: Enable predicate pushdown using index files (TBI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.pairs.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates are filtered client-side. Correctness is always guaranteed.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        pairs_read_options = PairsReadOptions(
            object_storage_options=object_storage_options,
            zero_based=zero_based,
        )
        read_options = ReadOptions(pairs_read_options=pairs_read_options)
        return _read_file(
            path,
            InputFormat.Pairs,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_bgen(
        path: str,
        genotype_output: str = "probability",
        probability_layout: str = "nested",
        samples: Union[list[str], None] = None,
        genotype_fields: Union[list[str], None] = None,
        sample_path: Union[str, None] = None,
        bgi_path: Union[str, None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a BGEN file into a DataFrame.

        One row is one BGEN variant. Encoded alleles stay ordered in `alleles`
        and are not given reference/alternate semantics.

        Parameters:
            path: The path to the BGEN file. The path must end in `.bgen`.
            genotype_output: Genotype representation. `"probability"` (default) keeps every format-defined state in `genotypes.GP`. `"dosage"` emits `genotypes.DS`, the expected copy count of `alleles[1]`, and rejects multiallelic variants.
            probability_layout: How probability states are stored. `"nested"` (default) gives each sample a variable-length list and reads every BGEN file. `"fixed"` gives each sample a fixed-width list, dropping the per-sample offsets that are about a quarter of the emitted probability bytes for a diploid biallelic cohort; it requires every variant to store the same number of states and rejects a file that mixes them. Ignored when `genotype_output="dosage"`.
            samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in file order.
            genotype_fields: Children of the `genotypes` struct to emit, from the output mode's value child — `"DS"` for dosage, `"GP"` for probability — and `"PLOIDY"`, in the requested order. If *None*, all of them are emitted. `"PLOIDY"` is a byte per genotype, 2.53 GB on a whole 1000 Genomes chromosome 22, and a NumPy view of the result keeps the whole struct alive, so pass `["DS"]` when only the dosages are wanted.
            sample_path: An explicit Oxford `.sample` companion. Used only when the BGEN has no embedded sample identifiers.
            bgi_path: An explicit `.bgi` index. A neighbouring `file.bgen.bgi` is discovered automatically.
            chunk_size: The size in MB of a chunk when reading from an object store.
            concurrent_fetches: The number of concurrent fetches when reading from an object store.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression override. BGEN block compression is read from the file header.
            projection_pushdown: Enable column projection pushdown. Metadata-only scans do not read or decompress probability blocks.
            predicate_pushdown: Use a `.bgi` index for `chrom`, `rsid`, `id`, `start`, and `end` predicate pushdown when one is available.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

        !!! note
            BGEN is input-only.
        """
        lf = IOOperations.scan_bgen(
            path=path,
            genotype_output=genotype_output,
            probability_layout=probability_layout,
            samples=samples,
            genotype_fields=genotype_fields,
            sample_path=sample_path,
            bgi_path=bgi_path,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_bgen(
        path: str,
        genotype_output: str = "probability",
        probability_layout: str = "nested",
        samples: Union[list[str], None] = None,
        genotype_fields: Union[list[str], None] = None,
        sample_path: Union[str, None] = None,
        bgi_path: Union[str, None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a BGEN file into a LazyFrame.

        BGI range pushdown, projection pushdown, and configured input partition
        parallelism are preserved. See `read_bgen` for the parameters.
        """
        _validate_bgen_genotype_output(genotype_output)
        _validate_bgen_probability_layout(probability_layout)
        _validate_bgen_genotype_fields(genotype_fields)
        _validate_bgen_input_path(path)
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        bgen_read_options = BgenReadOptions(
            object_storage_options=object_storage_options,
            genotype_output=genotype_output,
            probability_layout=probability_layout,
            samples=samples,
            genotype_fields=genotype_fields,
            sample_path=sample_path,
            bgi_path=bgi_path,
            zero_based=zero_based,
        )
        read_options = ReadOptions(bgen_read_options=bgen_read_options)
        return _read_file(
            path,
            InputFormat.Bgen,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_pgen(
        path: str,
        genotype_fields: Sequence[str] = ("GT",),
        samples: Union[list[str], None] = None,
        missing_sample_policy: str = "error",
        psam_id_mode: str = "iid",
        pvar_path: Union[str, None] = None,
        psam_path: Union[str, None] = None,
        pgi_path: Union[str, None] = None,
        max_range_gap: Union[int, None] = None,
        max_range_bytes: Union[int, None] = None,
        batch_soft_byte_limit: Union[int, None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a PLINK 2 PGEN fileset into a DataFrame.

        One row is one PVAR variant. The `.pvar` and `.psam` companions are
        discovered from the `.pgen` basename.

        Parameters:
            path: The path to the PGEN file. The path must end in `.pgen`. A neighbouring `.pvar` (or `.pvar.zst`) and `.psam` are discovered automatically.
            genotype_fields: Genotype children to emit, from `"GT"`, `"ALT_COUNT"`, `"PHASED"`, `"DS"`, `"DS_STORED"`, and `"HDS"`, in the requested order. Defaults to `("GT",)`. Note this narrows the provider default, which emits all of them. `"ALT_COUNT"` is the hardcall ALT allele count as `int8`, one byte per genotype rather than the four `"DS"` uses; prefer it when the fileset stores only hardcalls.
            samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in PSAM order.
            missing_sample_policy: `"error"` (default) rejects a requested sample name absent from the PSAM; `"ignore"` omits it from the selection.
            psam_id_mode: How selectable sample names are built from PSAM identifiers. `"iid"` (default) uses IID alone and rejects duplicates; `"fid_iid"` uses `FID:IID`; `"fid_iid_sid"` uses `FID:IID:SID`. A PSAM without FID or SID columns defaults those parts to `"0"`.
            pvar_path: An explicit `.pvar` companion. A neighbouring `.pvar` then `.pvar.zst` is discovered otherwise.
            psam_path: An explicit `.psam` companion. The shared-basename `.psam` is used otherwise.
            pgi_path: An explicit `.pgi` index, for a PGEN that uses an external index.
            max_range_gap: The largest run of unselected bytes bridged when coalescing reads, in bytes. The provider default is 0, which never bridges a gap and issues one read per contiguous run of selected variants. Raising it trades wasted bytes for fewer requests, which matters most on object storage. If *None*, the provider default is used.
            max_range_bytes: The largest coalesced read, in bytes. If *None*, the provider default is used.
            batch_soft_byte_limit: A soft target for genotype bytes in one RecordBatch. If *None*, the provider default is used.
            chunk_size: The size in MB of a chunk when reading from an object store.
            concurrent_fetches: The number of concurrent fetches when reading from an object store.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression override. PGEN record compression is read from the file header.
            projection_pushdown: Enable column projection pushdown. Metadata-only scans do not read genotype records.
            predicate_pushdown: Push `chrom`, `id`, `start`, and `end` predicates into variant selection.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

        !!! note
            PGEN is input-only.
        """
        lf = IOOperations.scan_pgen(
            path=path,
            genotype_fields=genotype_fields,
            samples=samples,
            missing_sample_policy=missing_sample_policy,
            psam_id_mode=psam_id_mode,
            pvar_path=pvar_path,
            psam_path=psam_path,
            pgi_path=pgi_path,
            max_range_gap=max_range_gap,
            max_range_bytes=max_range_bytes,
            batch_soft_byte_limit=batch_soft_byte_limit,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_pgen(
        path: str,
        genotype_fields: Sequence[str] = ("GT",),
        samples: Union[list[str], None] = None,
        missing_sample_policy: str = "error",
        psam_id_mode: str = "iid",
        pvar_path: Union[str, None] = None,
        psam_path: Union[str, None] = None,
        pgi_path: Union[str, None] = None,
        max_range_gap: Union[int, None] = None,
        max_range_bytes: Union[int, None] = None,
        batch_soft_byte_limit: Union[int, None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a PLINK 2 PGEN fileset into a LazyFrame.

        Projection pushdown and configured input partition parallelism are
        preserved. See `read_pgen` for the parameters.
        """
        _validate_pgen_input_path(path)
        _validate_pgen_genotype_fields(genotype_fields)
        _validate_pgen_psam_id_mode(psam_id_mode)
        _validate_pgen_missing_sample_policy(missing_sample_policy)
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        pgen_read_options = PgenReadOptions(
            object_storage_options=object_storage_options,
            genotype_fields=list(genotype_fields),
            zero_based=zero_based,
            samples=samples,
            missing_sample_policy=missing_sample_policy,
            psam_id_mode=psam_id_mode,
            pvar_path=pvar_path,
            psam_path=psam_path,
            pgi_path=pgi_path,
            max_range_gap=max_range_gap,
            max_range_bytes=max_range_bytes,
            batch_soft_byte_limit=batch_soft_byte_limit,
        )
        read_options = ReadOptions(pgen_read_options=pgen_read_options)
        return _read_file(
            path,
            InputFormat.Pgen,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_pgen_matrix(
        path: str,
        field: str = "ALT_COUNT",
        samples: Union[list[str], None] = None,
        missing: Union[int, float, None] = None,
        missing_sample_policy: str = "error",
        psam_id_mode: str = "iid",
        pvar_path: Union[str, None] = None,
        psam_path: Union[str, None] = None,
        pgi_path: Union[str, None] = None,
        max_range_gap: Union[int, None] = None,
        max_range_bytes: Union[int, None] = None,
        batch_soft_byte_limit: Union[int, None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        use_zero_based: Optional[bool] = None,
        copy_threads: Union[int, None] = None,
    ) -> "PgenMatrix":
        """
        Read one genotype field of a PGEN fileset into a dense NumPy matrix.

        The whole-cohort matrix is what association testing, PCA, and relatedness
        pipelines consume, and going through a DataFrame to get one costs a
        second full copy of every value: the scan builds Arrow batches, and
        something then has to consolidate them into a contiguous array. The
        decoder here writes genotypes at their final address instead, so they
        are written once.

        On chromosome 22 of 1000 Genomes (993,881 variants x 2,548 samples) the
        `DS` matrix takes **1.29 s** and 12.6 GB, against 3.2 s and 22.3 GB
        through `read_pgen`. `ALT_COUNT` takes 0.70 s. Both are faster than
        PLINK 2's own `pgenlib` at one thread, and roughly three times faster
        again given eight partitions.

        Parameters:
            path: The path to the PGEN file. The path must end in `.pgen`.
            field: The genotype field to materialize: `"ALT_COUNT"` (`int8` hardcall ALT allele count) or `"DS"` (`float32` ALT dosage). Fields with more than one value per sample — `"GT"`, `"HDS"` — have no dense matrix form, and `"DS_STORED"` has no decoder on this path; read those with `read_pgen`.
            samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in PSAM order. The matrix has one column per selected sample.
            missing: The value written where a genotype is missing. Defaults to `-9` for `"ALT_COUNT"`, matching PLINK's sentinel, and to NaN for the float fields.
            missing_sample_policy: `"error"` (default) rejects a requested sample name absent from the PSAM; `"ignore"` omits it.
            psam_id_mode: How selectable sample names are built from PSAM identifiers. See `read_pgen`.
            pvar_path: An explicit `.pvar` companion.
            psam_path: An explicit `.psam` companion.
            pgi_path: An explicit `.pgi` index.
            max_range_gap: The largest run of unselected bytes bridged when coalescing reads.
            max_range_bytes: The largest coalesced read, in bytes.
            batch_soft_byte_limit: A soft target for genotype bytes in one RecordBatch.
            chunk_size: The size in MB of a chunk when reading from an object store.
            concurrent_fetches: The number of concurrent fetches when reading from an object store.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression override.
            use_zero_based: If True, report 0-based positions. If False, 1-based. If None (default), uses the global configuration.
            copy_threads: How many threads decode into the result. They write disjoint row ranges, so they never contend. If *None* (default), this follows `datafusion.execution.target_partitions`, so a single-partition read stays single-threaded end to end.

        Returns:
            A `PgenMatrix` of `values` (a C-contiguous `(variants, samples)`
            array), `positions` (one per row), and `sample_names` (one per
            column).

        !!! note
            Rows are in PVAR order at every partition count: each variant is
            written at its own row index rather than in the order it finished
            decoding. This differs from `read_pgen`, whose row order may
            interleave above one partition.

        Example:
            ```python
            import polars_bio as pb

            matrix = pb.read_pgen_matrix("cohort.pgen", field="ALT_COUNT")
            matrix.values.shape       # (variants, samples)
            matrix.values.mean(axis=1)  # per-variant ALT frequency * 2
            ```
        """
        # Imported here rather than at module scope: NumPy is not a polars-bio
        # dependency, and only this function needs it.
        try:
            import numpy as np
        except ImportError as error:  # pragma: no cover - environment-dependent
            raise ImportError(
                "read_pgen_matrix returns NumPy arrays and needs NumPy installed"
            ) from error

        dtypes = {
            "ALT_COUNT": np.int8,
            "DS": np.float32,
        }
        if field not in dtypes:
            raise ValueError(
                f"read_pgen_matrix supports {sorted(dtypes)}, not {field!r}. "
                "Fields with more than one value per sample have no dense matrix "
                "form, and DS_STORED has no decoder on this path; read them with "
                "read_pgen."
            )
        dtype = np.dtype(dtypes[field])
        if missing is None:
            missing = -9 if dtype == np.int8 else np.nan
        elif field == "ALT_COUNT":
            # The sentinel crosses into Rust as an f64 and is written with
            # `as i8`, which saturates out-of-range values and turns NaN into
            # 0 — silently indistinguishable from a homozygous-reference call.
            # Reject what that cast would corrupt rather than write it.
            sentinel = float(missing)
            if (
                not np.isfinite(sentinel)
                or sentinel != int(sentinel)
                or not -128 <= sentinel <= 127
            ):
                raise ValueError(
                    f"missing={missing!r} is not representable as the int8 "
                    "ALT_COUNT matrix stores; pass a whole number in "
                    "[-128, 127] (PLINK's own sentinel is -9)"
                )

        # Built directly rather than through `scan_pgen`, because this path does
        # not register a table: the reader opens the fileset itself and answers
        # shape, names and positions from it, so the PVAR is parsed once.
        decode_options = PgenReadOptions(
            object_storage_options=PyObjectStorageOptions(
                allow_anonymous=allow_anonymous,
                enable_request_payer=enable_request_payer,
                chunk_size=chunk_size,
                concurrent_fetches=concurrent_fetches,
                max_retries=max_retries,
                timeout=timeout,
                compression_type=compression_type,
            ),
            genotype_fields=[field],
            zero_based=_resolve_zero_based(use_zero_based),
            samples=samples,
            missing_sample_policy=missing_sample_policy,
            psam_id_mode=psam_id_mode,
            pvar_path=pvar_path,
            psam_path=psam_path,
            pgi_path=pgi_path,
            max_range_gap=max_range_gap,
            max_range_bytes=max_range_bytes,
            batch_soft_byte_limit=batch_soft_byte_limit,
        )

        from polars_bio.context import get_option
        from polars_bio.polars_bio import PgenMatrixReader

        reader = PgenMatrixReader(path, decode_options)
        variants, columns = reader.shape()

        if copy_threads is None:
            try:
                copy_threads = int(get_option("datafusion.execution.target_partitions"))
            except (TypeError, ValueError):
                copy_threads = 1
        copy_threads = max(1, int(copy_threads))

        values = np.empty((variants, columns), dtype=dtype)
        # The array itself is handed over, not its address: the reader checks
        # dtype, C-contiguity, writability and length at the boundary, which is
        # the only place a caller cannot route around.
        reader.read_into(field, values, copy_threads, float(missing))

        positions = np.asarray(reader.positions(), dtype=np.int64)
        if positions.shape[0] != variants:
            raise RuntimeError(
                f"PGEN reported {variants} variants but {positions.shape[0]} positions"
            )
        return PgenMatrix(
            values=values, positions=positions, sample_names=list(reader.sample_names())
        )

    @staticmethod
    def read_bgen_matrix(
        path: str,
        samples: Union[list[str], None] = None,
        missing: Union[float, None] = None,
        sample_path: Union[str, None] = None,
        bgi_path: Union[str, None] = None,
        threads: Union[int, None] = None,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        use_zero_based: Optional[bool] = None,
    ) -> PgenMatrix:
        """
        Read a BGEN's ALT dosages into a dense NumPy matrix.

        The counterpart of `read_pgen_matrix`. `scan_bgen` returns Arrow batches
        that a caller wanting one array must then consolidate, and on a whole
        chromosome that consolidation is a serial pass over 10 GB — it does not
        parallelise, so it becomes the ceiling as partitions are added. This
        decodes each variant at its final address instead, which on chromosome
        22 scales 6.0x from one thread to eight against the Arrow path's 4.2x.

        Dosage only: BGEN probabilities are variable width and have no single
        dense shape. Use `scan_bgen(genotype_output="probability")` for those.

        Parameters:
            path: The path to the BGEN file. The path must end in `.bgen`.
            samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in file order.
            missing: Written where a sample has no called genotype. Defaults to `NaN`.
            sample_path: An explicit Oxford `.sample` companion, used only when the BGEN has no embedded sample identifiers.
            bgi_path: An explicit `.bgi` index. A neighbouring `file.bgen.bgi` is discovered automatically.
            threads: Decoder threads. Defaults to the configured `datafusion.execution.target_partitions`.
            use_zero_based: Output coordinate convention for the returned positions.

        Example:
            ```python
            import polars_bio as pb

            matrix = pb.read_bgen_matrix("chr22.bgen")
            matrix.values.shape          # (variants, samples), float32
            matrix.values.mean(axis=1)   # per-variant mean dosage
            ```
        """
        # Imported here rather than at module scope: NumPy is not a polars-bio
        # dependency, and only the matrix readers need it.
        try:
            import numpy as np
        except ImportError as error:  # pragma: no cover - environment-dependent
            raise ImportError(
                "read_bgen_matrix returns NumPy arrays and needs NumPy installed"
            ) from error

        _validate_bgen_input_path(path)
        dtype = np.dtype(np.float32)
        if missing is None:
            missing = np.nan

        decode_options = BgenReadOptions(
            object_storage_options=PyObjectStorageOptions(
                allow_anonymous=allow_anonymous,
                enable_request_payer=enable_request_payer,
                chunk_size=chunk_size,
                concurrent_fetches=concurrent_fetches,
                max_retries=max_retries,
                timeout=timeout,
                compression_type=compression_type,
            ),
            genotype_output="dosage",
            probability_layout="nested",
            samples=samples,
            genotype_fields=["DS"],
            sample_path=sample_path,
            bgi_path=bgi_path,
            zero_based=_resolve_zero_based(use_zero_based),
        )

        from polars_bio.context import get_option
        from polars_bio.polars_bio import BgenMatrixReader

        reader = BgenMatrixReader(path, decode_options)
        variants, columns = reader.shape()

        if threads is None:
            try:
                threads = int(get_option("datafusion.execution.target_partitions"))
            except (TypeError, ValueError):
                threads = 1
        threads = max(1, int(threads))

        values = np.empty((variants, columns), dtype=dtype)
        # As in `read_pgen_matrix`: the array goes across, not its address, and
        # the reader validates it before decoding.
        reader.read_into(values, threads, float(missing))

        positions = np.asarray(reader.positions(), dtype=np.int64)
        if positions.shape[0] != variants:
            raise RuntimeError(
                f"BGEN reported {variants} variants but {positions.shape[0]} positions"
            )
        return PgenMatrix(
            values=values, positions=positions, sample_names=list(reader.sample_names())
        )

    @staticmethod
    def read_bed(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a BED file into a DataFrame.

        Parameters:
            path: The path to the BED file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the BED file. If not specified, it will be detected automatically based on the file extension. BGZF compressions is supported ('bgz').
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! Note
            Only **BED4** format is supported. It extends the basic BED format (BED3) by adding a name field, resulting in four columns: chromosome, start position, end position, and name.
            Also unlike other text formats, **GZIP** compression is not supported.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        lf = IOOperations.scan_bed(
            path,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
            use_zero_based,
        )
        # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        # Set metadata on the collected DataFrame
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_bed(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a BED file into a LazyFrame.

        Parameters:
            path: The path to the BED file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries:  The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the BED file. If not specified, it will be detected automatically based on the file extension. BGZF compressions is supported ('bgz').
            projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
            use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

        !!! Note
            Only **BED4** format is supported. It extends the basic BED format (BED3) by adding a name field, resulting in four columns: chromosome, start position, end position, and name.
            Also unlike other text formats, **GZIP** compression is not supported.

        !!! note
            By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        bed_read_options = BedReadOptions(
            object_storage_options=object_storage_options,
            zero_based=zero_based,
        )
        read_options = ReadOptions(bed_read_options=bed_read_options)
        return _read_file(
            path,
            InputFormat.Bed,
            read_options,
            projection_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_bigwig(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a BigWig file into a DataFrame.

        BigWig rows are exposed as ``chrom``, ``start``, ``end``, and ``value``.

        Parameters:
            path: The path to the BigWig file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the BigWig file. If not specified, it will be detected automatically based on the file extension.
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
            predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
            use_zero_based: Coordinate system override. BigWig is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
        """
        lf = IOOperations.scan_bigwig(
            path,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_bigwig(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a BigWig file into a LazyFrame.

        BigWig is natively 0-based half-open. Set ``use_zero_based=False`` to emit
        1-based closed coordinates.

        Parameters:
            path: The path to the BigWig file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the BigWig file. If not specified, it will be detected automatically based on the file extension.
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
            predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
            use_zero_based: Coordinate system override. BigWig is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        bigwig_read_options = BigWigReadOptions(
            object_storage_options=object_storage_options,
            zero_based=zero_based,
        )
        read_options = ReadOptions(bigwig_read_options=bigwig_read_options)
        return _read_file(
            path,
            InputFormat.BigWig,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_bigbed(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        schema: str = "auto",
    ) -> pl.DataFrame:
        """
        Read a BigBed file into a DataFrame.

        ``schema="auto"`` uses supported autoSQL fields when available.
        ``schema="rest"`` exposes the raw trailing fields in ``rest``.

        Parameters:
            path: The path to the BigBed file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the BigBed file. If not specified, it will be detected automatically based on the file extension.
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
            predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
            use_zero_based: Coordinate system override. BigBed is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
            schema: Schema mode. ``"auto"`` exposes the supported autoSQL fields when available; ``"rest"`` exposes the raw trailing fields in a single ``rest`` column.
        """
        lf = IOOperations.scan_bigbed(
            path,
            chunk_size,
            concurrent_fetches,
            allow_anonymous,
            enable_request_payer,
            max_retries,
            timeout,
            compression_type,
            projection_pushdown,
            predicate_pushdown,
            use_zero_based,
            schema,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_bigbed(
        path: str,
        chunk_size: int = 8,
        concurrent_fetches: int = 1,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        max_retries: int = 5,
        timeout: int = 300,
        compression_type: str = "auto",
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        schema: str = "auto",
    ) -> pl.LazyFrame:
        """
        Lazily read a BigBed file into a LazyFrame.

        BigBed is natively 0-based half-open. Set ``use_zero_based=False`` to emit
        1-based closed coordinates.

        Parameters:
            path: The path to the BigBed file.
            chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
            concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
            allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
            enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            max_retries: The maximum number of retries for reading the file from object storage.
            timeout: The timeout in seconds for reading the file from object storage.
            compression_type: The compression type of the BigBed file. If not specified, it will be detected automatically based on the file extension.
            projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
            predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
            use_zero_based: Coordinate system override. BigBed is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
            schema: Schema mode. ``"auto"`` exposes the supported autoSQL fields when available; ``"rest"`` exposes the raw trailing fields in a single ``rest`` column.
        """
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        )

        zero_based = _resolve_zero_based(use_zero_based)
        bigbed_read_options = BigBedReadOptions(
            object_storage_options=object_storage_options,
            zero_based=zero_based,
            schema=_normalize_bigbed_schema_mode(schema),
        )
        read_options = ReadOptions(bigbed_read_options=bigbed_read_options)
        return _read_file(
            path,
            InputFormat.BigBed,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def read_cool(
        path: str,
        resolution: Optional[int] = None,
        join_bins: bool = True,
        include_weights: bool = False,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Read a Cooler (`.cool`/`.mcool`) Hi-C contact matrix into a DataFrame.

        See `scan_cool` for parameter semantics.

        Parameters:
            path: The path to the `.cool`/`.mcool` file, or a cooler URI (`file.mcool::/resolutions/10000`).
            resolution: Bin size selecting an `.mcool` data collection. Optional for `.cool` files and single-resolution `.mcool` files.
            join_bins: If *True* (default), join pixels with bin coordinates (`chrom1`, `start1`, `end1`, `chrom2`, `start2`, `end2`, `count`); if *False*, return the raw COO triple (`bin1_id`, `bin2_id`, `count`).
            include_weights: If *True*, expose balancing weights as `weight1`/`weight2` (requires a balanced cooler).
            projection_pushdown: Enable column projection pushdown optimization.
            predicate_pushdown: Enable predicate pushdown on the first-axis genomic columns (`chrom1`, `start1`, `end1`) so range filters prune pixel row ranges through the cooler indexes.
            use_zero_based: Coordinate system override. Cooler is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
        """
        lf = IOOperations.scan_cool(
            path,
            resolution=resolution,
            join_bins=join_bins,
            include_weights=include_weights,
            projection_pushdown=projection_pushdown,
            predicate_pushdown=predicate_pushdown,
            use_zero_based=use_zero_based,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_cool(
        path: str,
        resolution: Optional[int] = None,
        join_bins: bool = True,
        include_weights: bool = False,
        projection_pushdown: bool = True,
        predicate_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a Cooler (`.cool`/`.mcool`) Hi-C contact matrix into a LazyFrame.

        One row per stored pixel (upper-triangle contact), joined with bin
        coordinates by default. `.mcool` files store one data collection per
        resolution: select one with ``resolution`` or the cooler URI syntax
        ``file.mcool::/resolutions/10000``; an `.mcool` with several
        resolutions and no selection raises an error listing the available
        ones. Only local filesystem paths are supported.

        Cooler is natively 0-based half-open. Set ``use_zero_based=False`` to
        emit 1-based closed coordinates.

        Parameters:
            path: The path to the `.cool`/`.mcool` file, or a cooler URI (`file.mcool::/resolutions/10000`).
            resolution: Bin size selecting an `.mcool` data collection. Optional for `.cool` files and single-resolution `.mcool` files.
            join_bins: If *True* (default), join pixels with bin coordinates (`chrom1`, `start1`, `end1`, `chrom2`, `start2`, `end2`, `count`); if *False*, return the raw COO triple (`bin1_id`, `bin2_id`, `count`).
            include_weights: If *True*, expose balancing weights as `weight1`/`weight2` (requires a balanced cooler).
            projection_pushdown: Enable column projection pushdown optimization. Only HDF5 datasets required by the requested columns are read, and `count(*)` is served from the cooler index without touching pixel data.
            predicate_pushdown: Enable predicate pushdown on the first-axis genomic columns (`chrom1`, `start1`, `end1`) so range filters prune pixel row ranges through the cooler indexes.
            use_zero_based: Coordinate system override. Cooler is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.

        !!! Example
            ```python
            import polars as pl
            import polars_bio as pb

            pb.scan_cool("contacts.mcool", resolution=10000).filter(
                pl.col("chrom1") == "chr1"
            ).collect()
            ```
        """
        zero_based = _resolve_zero_based(use_zero_based)
        cool_read_options = CoolReadOptions(
            resolution=resolution,
            join_bins=join_bins,
            include_weights=include_weights,
            zero_based=zero_based,
        )
        read_options = ReadOptions(cool_read_options=cool_read_options)
        return _read_file(
            path,
            InputFormat.Cool,
            read_options,
            projection_pushdown,
            predicate_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def describe_cool(path: str) -> pl.DataFrame:
        """
        Describe the data collections of a Cooler (`.cool`/`.mcool`) file.

        Returns one row per stored data collection (one for `.cool`, one per
        resolution for `.mcool`) with `group_path`, `resolution` (bin size),
        `bin_type`, `format_version`, `assembly`, `nbins`, `nnz`, `sum`, and
        `nchroms`, read from file metadata without scanning pixel data. `sum`
        is Int64/UInt64 for integer-count collections and Float64 for
        float-count collections. Files mixing those storage classes use an
        exact Decimal column (or an exact string for values outside Arrow's
        Decimal128 range), preserving wide integer totals alongside fractions.

        Parameters:
            path: The path to the `.cool`/`.mcool` file, or a cooler URI
                (`file.mcool::/resolutions/10000`) to describe a single data
                collection.
        """
        return py_describe_cool(ctx, path).to_polars()

    @staticmethod
    def read_table(path: str, schema: Dict = None, **kwargs) -> pl.DataFrame:
        """
         Read a tab-delimited (i.e. BED) file into a Polars DataFrame.
         Tries to be compatible with Bioframe's [read_table](https://bioframe.readthedocs.io/en/latest/guide-io.html)
         but faster. Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).

        Parameters:
            path: The path to the file.
            schema: Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).
        """
        return IOOperations.scan_table(path, schema, **kwargs).collect()

    @staticmethod
    def scan_table(path: str, schema: Dict = None, **kwargs) -> pl.LazyFrame:
        """
         Lazily read a tab-delimited (i.e. BED) file into a Polars LazyFrame.
         Tries to be compatible with Bioframe's [read_table](https://bioframe.readthedocs.io/en/latest/guide-io.html)
         but faster and lazy. Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).

        Parameters:
            path: The path to the file.
            schema: Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).
        """
        df = pl.scan_csv(path, separator="\t", has_header=False, **kwargs)
        if schema is not None:
            columns = SCHEMAS[schema]
            if len(columns) != len(df.collect_schema()):
                raise ValueError(
                    f"Schema incompatible with the input. Expected {len(columns)} columns in a schema, got {len(df.collect_schema())} in the input data file. Please provide a valid schema."
                )
            for i, c in enumerate(columns):
                df = df.rename({f"column_{i + 1}": c})
        return df

    @staticmethod
    def describe_vcf(
        path: str,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        compression_type: str = "auto",
    ) -> pl.DataFrame:
        """
        Describe a text VCF INFO and FORMAT schema.

        Parameters:
            path: The path to the text VCF file.
            allow_anonymous: Whether to allow anonymous access to object storage (GCS and S3 supported).
            enable_request_payer: Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            compression_type: The compression type of the VCF file. If not specified, it will be detected automatically..
        """
        _validate_variant_input_path(path, "vcf", operation="describe")
        return IOOperations._describe_variant(
            path,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            compression_type=compression_type,
        )

    @staticmethod
    def describe_bcf(
        path: str,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        compression_type: str = "auto",
    ) -> pl.DataFrame:
        """Describe a BCF INFO and FORMAT schema.

        Parameters:
            path: The path to the BCF file. The path must end in `.bcf`.
            allow_anonymous: Whether to allow anonymous access to object storage (GCS and S3 supported).
            enable_request_payer: Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
            compression_type: The compression override. The default detects BCF automatically.
        """
        _validate_variant_input_path(path, "bcf", operation="describe")
        return IOOperations._describe_variant(
            path,
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            compression_type=compression_type,
        )

    @staticmethod
    def _describe_variant(
        path: str,
        allow_anonymous: bool,
        enable_request_payer: bool,
        compression_type: str,
    ) -> pl.DataFrame:
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=8,
            concurrent_fetches=1,
            max_retries=1,
            timeout=10,
            compression_type=compression_type,
        )
        return py_describe_vcf(ctx, path, object_storage_options).to_polars()

    @staticmethod
    def describe_bgen(
        path: str,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        compression_type: str = "auto",
        sample_path: Union[str, None] = None,
        bgi_path: Union[str, None] = None,
    ) -> pl.DataFrame:
        """
        Describe the schema a BGEN file produces.

        BGEN has no INFO/FORMAT header, so instead of a field dictionary this
        returns one row per emitted column, plus the file-level properties the
        provider records in the Arrow schema metadata: the BGEN layout, whether
        a `.bgi` index was used, whether sample identifiers were generated, and
        the coordinate system.

        Parameters:
            path: The path to the BGEN file. The path must end in `.bgen`.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            compression_type: The compression override.
            sample_path: An explicit Oxford `.sample` companion, used only when the BGEN has no embedded sample identifiers.
            bgi_path: An explicit `.bgi` index. Pass it for an index stored away from the file, so the reported `index` property reflects the index a read would actually use.

        !!! note
            The reported schema is the one the default `probability_layout="nested"`
            produces, because that layout describes every BGEN file. Reading with
            `probability_layout="fixed"` gives `genotypes.GP` a fixed-width state
            list instead.
        """
        _validate_bgen_input_path(path, operation="describe")
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=8,
            concurrent_fetches=1,
            max_retries=1,
            timeout=10,
            compression_type=compression_type,
        )
        bgen_read_options = BgenReadOptions(
            object_storage_options=object_storage_options,
            genotype_output="probability",
            probability_layout="nested",
            samples=None,
            sample_path=sample_path,
            bgi_path=bgi_path,
            zero_based=_resolve_zero_based(None),
        )
        # Registering under the derived name would deregister and replace a
        # table the caller already registered for the same file, so describe
        # uses a private name and removes it again.
        describe_name = f"_pb_bgen_describe_{uuid4().hex}"
        table = py_register_table(
            ctx,
            path,
            describe_name,
            InputFormat.Bgen,
            ReadOptions(bgen_read_options=bgen_read_options),
        )
        try:
            schema = py_get_table_schema(ctx, table.name)
        finally:
            ctx.deregister_table(table.name)
        metadata = {
            (key.decode() if isinstance(key, bytes) else key): (
                value.decode() if isinstance(value, bytes) else value
            )
            for key, value in (schema.metadata or {}).items()
        }
        described = pl.DataFrame(
            {
                "name": [field.name for field in schema],
                "type": [str(field.type) for field in schema],
            }
        )
        properties = {
            "layout": metadata.get("bio.bgen.layout"),
            "index": metadata.get("bio.bgen.index"),
            "sample_names_synthetic": metadata.get("bio.bgen.sample_names.synthetic"),
            "coordinate_system_zero_based": metadata.get(
                "bio.coordinate_system_zero_based"
            ),
        }
        return described.with_columns(
            [pl.lit(value).alias(name) for name, value in properties.items()]
        )

    @staticmethod
    def describe_pgen(
        path: str,
        allow_anonymous: bool = True,
        enable_request_payer: bool = False,
        compression_type: str = "auto",
        pvar_path: Union[str, None] = None,
        psam_path: Union[str, None] = None,
        pgi_path: Union[str, None] = None,
    ) -> pl.DataFrame:
        """
        Describe the schema a PLINK 2 PGEN fileset produces.

        PGEN has no embedded header, so instead of a field dictionary this
        returns one row per emitted column, plus the file-level properties the
        provider records in the Arrow schema metadata: the storage mode,
        whether the index is embedded or external, the specification baseline,
        and the coordinate system.

        Parameters:
            path: The path to the PGEN file. The path must end in `.pgen`.
            allow_anonymous: Whether to allow anonymous access to object storage.
            enable_request_payer: Whether to enable request payer for object storage.
            compression_type: The compression override.
            pvar_path: An explicit `.pvar` companion.
            psam_path: An explicit `.psam` companion.
            pgi_path: An explicit `.pgi` index, for a PGEN that uses an external index. Without it, such a fileset cannot be opened here at all.

        !!! note
            The reported schema is the one the default `genotype_fields=("GT",)`
            produces. Selecting other genotype fields changes the children of
            the `genotypes` struct.
        """
        _validate_pgen_input_path(path, operation="describe")
        object_storage_options = PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=8,
            concurrent_fetches=1,
            max_retries=1,
            timeout=10,
            compression_type=compression_type,
        )
        pgen_read_options = PgenReadOptions(
            object_storage_options=object_storage_options,
            genotype_fields=["GT"],
            pvar_path=pvar_path,
            psam_path=psam_path,
            pgi_path=pgi_path,
            zero_based=_resolve_zero_based(None),
        )
        # Registering under the derived name would deregister and replace a
        # table the caller already registered for the same file, so describe
        # uses a private name and removes it again.
        describe_name = f"_pb_pgen_describe_{uuid4().hex}"
        table = py_register_table(
            ctx,
            path,
            describe_name,
            InputFormat.Pgen,
            ReadOptions(pgen_read_options=pgen_read_options),
        )
        try:
            schema = py_get_table_schema(ctx, table.name)
        finally:
            ctx.deregister_table(table.name)
        metadata = {
            (key.decode() if isinstance(key, bytes) else key): (
                value.decode() if isinstance(value, bytes) else value
            )
            for key, value in (schema.metadata or {}).items()
        }
        described = pl.DataFrame(
            {
                "name": [field.name for field in schema],
                "type": [str(field.type) for field in schema],
            }
        )
        properties = {
            "storage_mode": metadata.get("bio.pgen.storage_mode"),
            "index": metadata.get("bio.pgen.index"),
            "specification_baseline": metadata.get("bio.pgen.specification_baseline"),
            "coordinate_system_zero_based": metadata.get(
                "bio.coordinate_system_zero_based"
            ),
        }
        return described.with_columns(
            [pl.lit(value).alias(name) for name, value in properties.items()]
        )

    @staticmethod
    def describe_vcf_zarr(path: str) -> pl.DataFrame:
        """
        Describe VCF Zarr INFO and FORMAT schema.

        Parameters:
            path: The path to the local VCF Zarr store directory.
        """
        return py_describe_vcf_zarr(ctx, path).to_polars()

    @staticmethod
    def from_polars(name: str, df: Union[pl.DataFrame, pl.LazyFrame]) -> None:
        """
        Register a Polars DataFrame as a DataFusion table.

        Parameters:
            name: The name of the table.
            df: The Polars DataFrame.
        """
        reader = (
            df.to_arrow()
            if isinstance(df, pl.DataFrame)
            else df.collect().to_arrow().to_reader()
        )
        py_from_polars(ctx, name, reader)

    @staticmethod
    def write_vcf(
        df: Union[pl.DataFrame, pl.LazyFrame],
        path: str,
    ) -> int:
        """
        Write a DataFrame to VCF format.

        Coordinate system is automatically read from DataFrame metadata (set during
        read_vcf). Compression is auto-detected from the file extension.

        Parameters:
            df: The DataFrame or LazyFrame to write.
            path: The output file path. Compression is auto-detected from extension
                  (.vcf.bgz for BGZF, .vcf.gz for GZIP, .vcf for uncompressed).

        Returns:
            The number of rows written.

        !!! Example "Writing VCF files"
            ```python
            import polars_bio as pb

            # Read a VCF file
            df = pb.read_vcf("input.vcf")

            # Write to uncompressed VCF
            pb.write_vcf(df, "output.vcf")

            # Write to BGZF-compressed VCF
            pb.write_vcf(df, "output.vcf.bgz")

            # Write to GZIP-compressed VCF
            pb.write_vcf(df, "output.vcf.gz")
            ```
        """
        return _write_file(df, path, OutputFormat.Vcf)

    @staticmethod
    def sink_vcf(
        lf: pl.LazyFrame,
        path: str,
    ) -> None:
        """
        Streaming write a LazyFrame to VCF format.

        This method executes the LazyFrame immediately and writes the results
        to the specified path. Unlike `write_vcf`, it doesn't return the row count.

        Coordinate system is automatically read from LazyFrame metadata (set during
        scan_vcf). Compression is auto-detected from the file extension.

        Parameters:
            lf: The LazyFrame to write.
            path: The output file path. Compression is auto-detected from extension
                  (.vcf.bgz for BGZF, .vcf.gz for GZIP, .vcf for uncompressed).

        !!! Example "Streaming write VCF"
            ```python
            import polars_bio as pb

            # Lazy read and filter, then sink to VCF
            lf = pb.scan_vcf("large_input.vcf").filter(pl.col("qual") > 30)
            pb.sink_vcf(lf, "filtered_output.vcf.bgz")
            ```
        """
        _write_file(lf, path, OutputFormat.Vcf)

    @staticmethod
    def write_fasta(
        df: Union[pl.DataFrame, pl.LazyFrame],
        path: str,
    ) -> int:
        """
        Write a DataFrame to FASTA format.

        Compression is auto-detected from the file extension.

        Parameters:
            df: The DataFrame or LazyFrame to write. Must have columns:
                - name: Sequence name/identifier
                - sequence: DNA/RNA sequence
                Optional: description (added after name on header line)
            path: The output file path. Compression is auto-detected from extension
                  (.fasta.bgz for BGZF, .fasta.gz/.fa.gz for GZIP, .fasta/.fa for uncompressed).

        Returns:
            The number of rows written.

        !!! Example "Writing FASTA files"
            ```python
            import polars_bio as pb

            # Read a FASTA file
            df = pb.read_fasta("input.fasta")

            # Write to uncompressed FASTA
            pb.write_fasta(df, "output.fasta")

            # Write to GZIP-compressed FASTA
            pb.write_fasta(df, "output.fasta.gz")
            ```
        """
        return _write_file(df, path, OutputFormat.Fasta)

    @staticmethod
    def sink_fasta(
        lf: pl.LazyFrame,
        path: str,
    ) -> None:
        """
        Streaming write a LazyFrame to FASTA format.

        Compression is auto-detected from the file extension.

        Parameters:
            lf: The LazyFrame to write.
            path: The output file path. Compression is auto-detected from extension
                  (.fasta.bgz for BGZF, .fasta.gz/.fa.gz for GZIP, .fasta/.fa for uncompressed).

        !!! Example "Streaming write FASTA"
            ```python
            import polars_bio as pb

            # Lazy read, filter, then sink
            lf = pb.scan_fasta("large_input.fasta.gz")
            pb.sink_fasta(lf.limit(1000), "sample_output.fasta")
            ```
        """
        _write_file(lf, path, OutputFormat.Fasta)

    @staticmethod
    def write_fastq(
        df: Union[pl.DataFrame, pl.LazyFrame],
        path: str,
    ) -> int:
        """
        Write a DataFrame to FASTQ format.

        Compression is auto-detected from the file extension.

        Parameters:
            df: The DataFrame or LazyFrame to write. Must have columns:
                - name: Read name/identifier
                - sequence: DNA sequence
                - quality_scores: Quality scores string
                Optional: description (added after name on header line)
            path: The output file path. Compression is auto-detected from extension
                  (.fastq.bgz for BGZF, .fastq.gz for GZIP, .fastq for uncompressed).

        Returns:
            The number of rows written.

        !!! Example "Writing FASTQ files"
            ```python
            import polars_bio as pb

            # Read a FASTQ file
            df = pb.read_fastq("input.fastq")

            # Write to uncompressed FASTQ
            pb.write_fastq(df, "output.fastq")

            # Write to GZIP-compressed FASTQ
            pb.write_fastq(df, "output.fastq.gz")
            ```
        """
        return _write_file(df, path, OutputFormat.Fastq)

    @staticmethod
    def sink_fastq(
        lf: pl.LazyFrame,
        path: str,
    ) -> None:
        """
        Streaming write a LazyFrame to FASTQ format.

        Compression is auto-detected from the file extension.

        Parameters:
            lf: The LazyFrame to write.
            path: The output file path. Compression is auto-detected from extension
                  (.fastq.bgz for BGZF, .fastq.gz for GZIP, .fastq for uncompressed).

        !!! Example "Streaming write FASTQ"
            ```python
            import polars_bio as pb

            # Lazy read, filter by quality, then sink
            lf = pb.scan_fastq("large_input.fastq.gz")
            pb.sink_fastq(lf.limit(1000), "sample_output.fastq")
            ```
        """
        _write_file(lf, path, OutputFormat.Fastq)

    @staticmethod
    def write_bam(
        df: Union[pl.DataFrame, pl.LazyFrame],
        path: str,
        sort_on_write: bool = False,
        tag_type_overrides: Optional[dict[str, str]] = None,
    ) -> int:
        """
        Write a DataFrame to BAM/SAM format.

        Compression is auto-detected from file extension:
        - .sam → Uncompressed SAM (plain text)
        - .bam → BGZF-compressed BAM

        For CRAM format, use `write_cram()` instead.

        Parameters:
            df: DataFrame or LazyFrame with 11 core BAM columns + optional tag columns
            path: Output file path (.bam or .sam)
            sort_on_write: If True, sort records by (chrom, start) and set header SO:coordinate.
                If False (default), set header SO:unsorted.
            tag_type_overrides: Optional exact SAM tag type specifications for ambiguous
                or newly created tag columns, e.g. {"tp": "A", "XH": "H", "ML": "B:C"}.
                Overrides take precedence over preserved source metadata and Arrow dtype inference.

        Returns:
            Number of rows written

        !!! Example "Write BAM files"
            ```python
            import polars_bio as pb
            df = pb.read_bam("input.bam", tag_fields=["NM", "AS"])
            pb.write_bam(df, "output.bam")
            pb.write_bam(df, "output.sam")
            ```
        """
        return _write_bam_file(
            df,
            path,
            OutputFormat.Bam,
            None,
            sort_on_write=sort_on_write,
            tag_type_overrides=tag_type_overrides,
        )

    @staticmethod
    def sink_bam(
        lf: pl.LazyFrame,
        path: str,
        sort_on_write: bool = False,
        tag_type_overrides: Optional[dict[str, str]] = None,
    ) -> None:
        """
        Streaming write a LazyFrame to BAM/SAM format.

        For CRAM format, use `sink_cram()` instead.

        Parameters:
            lf: LazyFrame to write
            path: Output file path (.bam or .sam)
            sort_on_write: If True, sort records by (chrom, start) and set header SO:coordinate.
                If False (default), set header SO:unsorted.
            tag_type_overrides: Optional exact SAM tag type specifications for ambiguous
                or newly created tag columns, e.g. {"tp": "A", "XH": "H", "ML": "B:C"}.
                Overrides take precedence over preserved source metadata and Arrow dtype inference.

        !!! Example "Streaming write BAM"
            ```python
            import polars_bio as pb
            lf = pb.scan_bam("input.bam").filter(pl.col("mapping_quality") > 20)
            pb.sink_bam(lf, "filtered.bam")
            ```
        """
        _write_bam_file(
            lf,
            path,
            OutputFormat.Bam,
            None,
            sort_on_write=sort_on_write,
            tag_type_overrides=tag_type_overrides,
        )

    @staticmethod
    def read_sam(
        path: str,
        tag_fields: Union[list[str], None] = None,
        projection_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        infer_tag_types: bool = True,
        infer_tag_sample_size: int = 100,
        tag_type_hints: Optional[list[str]] = None,
    ) -> pl.DataFrame:
        """
        Read a SAM file into a DataFrame.

        SAM (Sequence Alignment/Map) is the plain-text counterpart of BAM.
        This function reuses the BAM reader, which auto-detects the format
        from the file extension.

        Parameters:
            path: The path to the SAM file.
            tag_fields: List of SAM tag names to include as columns (e.g., ["NM", "MD", "AS"]).
                If None, no optional tags are parsed (default).
            projection_pushdown: Enable column projection pushdown to optimize query performance.
            use_zero_based: If True, output 0-based half-open coordinates.
                If False, output 1-based closed coordinates.
                If None (default), uses the global configuration.
            infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags.
            infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
            tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

        !!! note
            By default, coordinates are output in **1-based closed** format.
        """
        lf = IOOperations.scan_sam(
            path,
            tag_fields,
            projection_pushdown,
            use_zero_based,
            infer_tag_types,
            infer_tag_sample_size,
            tag_type_hints,
        )
        zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
        df = lf.collect()
        if zero_based is not None:
            set_coordinate_system(df, zero_based)
        return df

    @staticmethod
    def scan_sam(
        path: str,
        tag_fields: Union[list[str], None] = None,
        projection_pushdown: bool = True,
        use_zero_based: Optional[bool] = None,
        infer_tag_types: bool = True,
        infer_tag_sample_size: int = 100,
        tag_type_hints: Optional[list[str]] = None,
    ) -> pl.LazyFrame:
        """
        Lazily read a SAM file into a LazyFrame.

        SAM (Sequence Alignment/Map) is the plain-text counterpart of BAM.
        This function reuses the BAM reader, which auto-detects the format
        from the file extension.

        Parameters:
            path: The path to the SAM file.
            tag_fields: List of SAM tag names to include as columns (e.g., ["NM", "MD", "AS"]).
                If None, no optional tags are parsed (default).
            projection_pushdown: Enable column projection pushdown to optimize query performance.
            use_zero_based: If True, output 0-based half-open coordinates.
                If False, output 1-based closed coordinates.
                If None (default), uses the global configuration.
            infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags.
            infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
            tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

        !!! note
            By default, coordinates are output in **1-based closed** format.
        """
        zero_based = _resolve_zero_based(use_zero_based)
        if tag_type_hints is not None:
            _validate_tag_type_hints(tag_type_hints)
            tag_type_hints = _normalize_read_tag_type_hints(tag_type_hints)
        bam_read_options = BamReadOptions(
            zero_based=zero_based,
            tag_fields=tag_fields,
            infer_tag_types=infer_tag_types,
            infer_tag_sample_size=infer_tag_sample_size,
            tag_type_hints=tag_type_hints,
        )
        read_options = ReadOptions(bam_read_options=bam_read_options)
        return _read_file(
            path,
            InputFormat.Sam,
            read_options,
            projection_pushdown,
            zero_based=zero_based,
        )

    @staticmethod
    def describe_sam(
        path: str,
        sample_size: int = 100,
        use_zero_based: Optional[bool] = None,
    ) -> pl.DataFrame:
        """
        Get schema information for a SAM file with automatic tag discovery.

        Samples the first N records to discover all available tags and their types.
        Reuses the BAM describe logic, which auto-detects SAM from the file extension.

        Parameters:
            path: The path to the SAM file.
            sample_size: Number of records to sample for tag discovery (default: 100).
            use_zero_based: If True, output 0-based coordinates. If False, 1-based coordinates.

        Returns:
            DataFrame with columns: column_name, data_type, nullable, category, sam_type, description
        """
        zero_based = _resolve_zero_based(use_zero_based)

        df = py_describe_bam(
            ctx,
            path,
            None,
            zero_based,
            None,
            sample_size,
        )

        return pl.from_arrow(df.to_arrow_table())

    @staticmethod
    def write_sam(
        df: Union[pl.DataFrame, pl.LazyFrame],
        path: str,
        sort_on_write: bool = False,
        tag_type_overrides: Optional[dict[str, str]] = None,
    ) -> int:
        """
        Write a DataFrame to SAM format (plain text).

        Parameters:
            df: DataFrame or LazyFrame with 11 core BAM/SAM columns + optional tag columns
            path: Output file path (.sam)
            sort_on_write: If True, sort records by (chrom, start) and set header SO:coordinate.
                If False (default), set header SO:unsorted.
            tag_type_overrides: Optional exact SAM tag type specifications for ambiguous
                or newly created tag columns, e.g. {"tp": "A", "XH": "H", "ML": "B:C"}.
                Overrides take precedence over preserved source metadata and Arrow dtype inference.

        Returns:
            Number of rows written

        !!! Example "Write SAM files"
            ```python
            import polars_bio as pb
            df = pb.read_bam("input.bam", tag_fields=["NM", "AS"])
            pb.write_sam(df, "output.sam")
            ```
        """
        return _write_bam_file(
            df,
            path,
            OutputFormat.Sam,
            None,
            sort_on_write=sort_on_write,
            tag_type_overrides=tag_type_overrides,
        )

    @staticmethod
    def sink_sam(
        lf: pl.LazyFrame,
        path: str,
        sort_on_write: bool = False,
        tag_type_overrides: Optional[dict[str, str]] = None,
    ) -> None:
        """
        Streaming write a LazyFrame to SAM format (plain text).

        Parameters:
            lf: LazyFrame to write
            path: Output file path (.sam)
            sort_on_write: If True, sort records by (chrom, start) and set header SO:coordinate.
                If False (default), set header SO:unsorted.
            tag_type_overrides: Optional exact SAM tag type specifications for ambiguous
                or newly created tag columns, e.g. {"tp": "A", "XH": "H", "ML": "B:C"}.
                Overrides take precedence over preserved source metadata and Arrow dtype inference.

        !!! Example "Streaming write SAM"
            ```python
            import polars_bio as pb
            lf = pb.scan_bam("input.bam").filter(pl.col("mapping_quality") > 20)
            pb.sink_sam(lf, "filtered.sam")
            ```
        """
        _write_bam_file(
            lf,
            path,
            OutputFormat.Sam,
            None,
            sort_on_write=sort_on_write,
            tag_type_overrides=tag_type_overrides,
        )

    @staticmethod
    def write_cram(
        df: Union[pl.DataFrame, pl.LazyFrame],
        path: str,
        reference_path: str,
        sort_on_write: bool = False,
    ) -> int:
        """
        Write a DataFrame to CRAM format.

        CRAM uses reference-based compression, storing only differences from the
        reference sequence. This achieves 30-60% better compression than BAM.

        Parameters:
            df: DataFrame or LazyFrame with 11 core BAM columns + optional tag columns
            path: Output CRAM file path
            reference_path: Path to reference FASTA file (required). The reference must
                contain all sequences referenced by the alignment data.
            sort_on_write: If True, sort records by (chrom, start) and set header SO:coordinate.
                If False (default), set header SO:unsorted.

        Returns:
            Number of rows written

        !!! warning "Known Limitation: MD and NM Tags"
            Due to a limitation in the underlying noodles-cram library, **MD and NM tags cannot be read back from CRAM files** after writing, even though they are written to the file. If you need MD/NM tags for downstream analysis, use BAM format instead. Other optional tags (RG, MQ, AM, OQ, AS, etc.) work correctly. See: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

        !!! Example "Write CRAM files"
            ```python
            import polars_bio as pb

            df = pb.read_bam("input.bam", tag_fields=["NM", "AS"])

            # Write CRAM with reference (required)
            pb.write_cram(df, "output.cram", reference_path="reference.fasta")

            # For sorted output
            pb.write_cram(df, "output.cram", reference_path="reference.fasta", sort_on_write=True)
            ```
        """
        return _write_bam_file(
            df, path, OutputFormat.Cram, reference_path, sort_on_write=sort_on_write
        )

    @staticmethod
    def sink_cram(
        lf: pl.LazyFrame,
        path: str,
        reference_path: str,
        sort_on_write: bool = False,
    ) -> None:
        """
        Streaming write a LazyFrame to CRAM format.

        CRAM uses reference-based compression, storing only differences from the
        reference sequence. This method streams data without materializing all
        rows in memory.

        Parameters:
            lf: LazyFrame to write
            path: Output CRAM file path
            reference_path: Path to reference FASTA file (required). The reference must
                contain all sequences referenced by the alignment data.
            sort_on_write: If True, sort records by (chrom, start) and set header SO:coordinate.
                If False (default), set header SO:unsorted.

        !!! warning "Known Limitation: MD and NM Tags"
            Due to a limitation in the underlying noodles-cram library, **MD and NM tags cannot be read back from CRAM files** after writing, even though they are written to the file. If you need MD/NM tags for downstream analysis, use BAM format instead. Other optional tags (RG, MQ, AM, OQ, AS, etc.) work correctly. See: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

        !!! Example "Streaming write CRAM"
            ```python
            import polars_bio as pb
            import polars as pl

            lf = pb.scan_bam("large_input.bam")
            lf = lf.filter(pl.col("mapping_quality") > 30)

            # Write CRAM with reference (required)
            pb.sink_cram(lf, "filtered.cram", reference_path="reference.fasta")

            # For sorted output
            pb.sink_cram(lf, "filtered.cram", reference_path="reference.fasta", sort_on_write=True)
            ```
        """
        _write_bam_file(
            lf, path, OutputFormat.Cram, reference_path, sort_on_write=sort_on_write
        )

read_bcf(path, info_fields=None, format_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, samples=None, genotype_output='string') staticmethod

Read a BCF file into a DataFrame.

Parameters:

Name Type Description Default
path str

The path to the BCF file. The path must end in .bcf.

required
info_fields Union[list[str], None]

INFO fields to include. If None, all header-defined INFO fields are included.

None
format_fields Union[list[str], None]

FORMAT fields to include. Single-sample fields are top-level columns; multisample fields are nested in genotypes.

None
samples Union[list[str], None]

Optional sample names to include, in requested order.

None
chunk_size int

Object-store chunk size in MB.

8
concurrent_fetches int

Number of concurrent object-store fetches.

1
allow_anonymous bool

Allow anonymous object-store access.

True
enable_request_payer bool

Enable AWS request-payer access.

False
max_retries int

Maximum number of object-store retries.

5
timeout int

Object-store timeout in seconds.

300
compression_type str

Compression override. The default detects BCF automatically.

'auto'
projection_pushdown bool

Push column projection into the BCF reader.

True
predicate_pushdown bool

Use a neighboring .bcf.csi index for genomic predicate pushdown when available.

True
use_zero_based Optional[bool]

Select 0-based half-open (True) or 1-based closed (False) coordinates. None uses global configuration.

None
genotype_output str

GT representation. "string" (default) returns VCF-style calls such as "0/1". "dosage" returns the number of ALT alleles per sample as nullable Int8 (normally 0, 1, or 2 for diploid calls); any missing allele yields null. Dosage requires GT to be the only selected FORMAT field and requires biallelic records. When format_fields is None, all header-defined FORMAT fields are selected, so pass format_fields=["GT"] when the header declares additional fields. Multiallelic records are rejected.

'string'

Note

BCF is input-only. Use write_vcf or sink_vcf to write text VCF.

Source code in polars_bio/io.py
@staticmethod
def read_bcf(
    path: str,
    info_fields: Union[list[str], None] = None,
    format_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    samples: Union[list[str], None] = None,
    genotype_output: str = "string",
) -> pl.DataFrame:
    """Read a BCF file into a DataFrame.

    Parameters:
        path: The path to the BCF file. The path must end in `.bcf`.
        info_fields: INFO fields to include. If *None*, all header-defined INFO fields are included.
        format_fields: FORMAT fields to include. Single-sample fields are top-level columns; multisample fields are nested in `genotypes`.
        samples: Optional sample names to include, in requested order.
        chunk_size: Object-store chunk size in MB.
        concurrent_fetches: Number of concurrent object-store fetches.
        allow_anonymous: Allow anonymous object-store access.
        enable_request_payer: Enable AWS request-payer access.
        max_retries: Maximum number of object-store retries.
        timeout: Object-store timeout in seconds.
        compression_type: Compression override. The default detects BCF automatically.
        projection_pushdown: Push column projection into the BCF reader.
        predicate_pushdown: Use a neighboring `.bcf.csi` index for genomic predicate pushdown when available.
        use_zero_based: Select 0-based half-open (`True`) or 1-based closed (`False`) coordinates. *None* uses global configuration.
        genotype_output: GT representation. `"string"` (default) returns VCF-style calls such as `"0/1"`. `"dosage"` returns the number of ALT alleles per sample as nullable `Int8` (normally 0, 1, or 2 for diploid calls); any missing allele yields null. Dosage requires GT to be the only selected FORMAT field and requires biallelic records. When `format_fields` is *None*, all header-defined FORMAT fields are selected, so pass `format_fields=["GT"]` when the header declares additional fields. Multiallelic records are rejected.

    !!! note
        BCF is input-only. Use `write_vcf` or `sink_vcf` to write text VCF.
    """
    lf = IOOperations.scan_bcf(
        path=path,
        info_fields=info_fields,
        format_fields=format_fields,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
        samples=samples,
        genotype_output=genotype_output,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_bgen(path, genotype_output='probability', probability_layout='nested', samples=None, genotype_fields=None, sample_path=None, bgi_path=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a BGEN file into a DataFrame.

One row is one BGEN variant. Encoded alleles stay ordered in alleles and are not given reference/alternate semantics.

Parameters:

Name Type Description Default
path str

The path to the BGEN file. The path must end in .bgen.

required
genotype_output str

Genotype representation. "probability" (default) keeps every format-defined state in genotypes.GP. "dosage" emits genotypes.DS, the expected copy count of alleles[1], and rejects multiallelic variants.

'probability'
probability_layout str

How probability states are stored. "nested" (default) gives each sample a variable-length list and reads every BGEN file. "fixed" gives each sample a fixed-width list, dropping the per-sample offsets that are about a quarter of the emitted probability bytes for a diploid biallelic cohort; it requires every variant to store the same number of states and rejects a file that mixes them. Ignored when genotype_output="dosage".

'nested'
samples Union[list[str], None]

Sample identifiers to emit, in requested order. If None, all samples are emitted in file order.

None
genotype_fields Union[list[str], None]

Children of the genotypes struct to emit, from the output mode's value child — "DS" for dosage, "GP" for probability — and "PLOIDY", in the requested order. If None, all of them are emitted. "PLOIDY" is a byte per genotype, 2.53 GB on a whole 1000 Genomes chromosome 22, and a NumPy view of the result keeps the whole struct alive, so pass ["DS"] when only the dosages are wanted.

None
sample_path Union[str, None]

An explicit Oxford .sample companion. Used only when the BGEN has no embedded sample identifiers.

None
bgi_path Union[str, None]

An explicit .bgi index. A neighbouring file.bgen.bgi is discovered automatically.

None
chunk_size int

The size in MB of a chunk when reading from an object store.

8
concurrent_fetches int

The number of concurrent fetches when reading from an object store.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression override. BGEN block compression is read from the file header.

'auto'
projection_pushdown bool

Enable column projection pushdown. Metadata-only scans do not read or decompress probability blocks.

True
predicate_pushdown bool

Use a .bgi index for chrom, rsid, id, start, and end predicate pushdown when one is available.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

None

Note

BGEN is input-only.

Source code in polars_bio/io.py
@staticmethod
def read_bgen(
    path: str,
    genotype_output: str = "probability",
    probability_layout: str = "nested",
    samples: Union[list[str], None] = None,
    genotype_fields: Union[list[str], None] = None,
    sample_path: Union[str, None] = None,
    bgi_path: Union[str, None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a BGEN file into a DataFrame.

    One row is one BGEN variant. Encoded alleles stay ordered in `alleles`
    and are not given reference/alternate semantics.

    Parameters:
        path: The path to the BGEN file. The path must end in `.bgen`.
        genotype_output: Genotype representation. `"probability"` (default) keeps every format-defined state in `genotypes.GP`. `"dosage"` emits `genotypes.DS`, the expected copy count of `alleles[1]`, and rejects multiallelic variants.
        probability_layout: How probability states are stored. `"nested"` (default) gives each sample a variable-length list and reads every BGEN file. `"fixed"` gives each sample a fixed-width list, dropping the per-sample offsets that are about a quarter of the emitted probability bytes for a diploid biallelic cohort; it requires every variant to store the same number of states and rejects a file that mixes them. Ignored when `genotype_output="dosage"`.
        samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in file order.
        genotype_fields: Children of the `genotypes` struct to emit, from the output mode's value child — `"DS"` for dosage, `"GP"` for probability — and `"PLOIDY"`, in the requested order. If *None*, all of them are emitted. `"PLOIDY"` is a byte per genotype, 2.53 GB on a whole 1000 Genomes chromosome 22, and a NumPy view of the result keeps the whole struct alive, so pass `["DS"]` when only the dosages are wanted.
        sample_path: An explicit Oxford `.sample` companion. Used only when the BGEN has no embedded sample identifiers.
        bgi_path: An explicit `.bgi` index. A neighbouring `file.bgen.bgi` is discovered automatically.
        chunk_size: The size in MB of a chunk when reading from an object store.
        concurrent_fetches: The number of concurrent fetches when reading from an object store.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression override. BGEN block compression is read from the file header.
        projection_pushdown: Enable column projection pushdown. Metadata-only scans do not read or decompress probability blocks.
        predicate_pushdown: Use a `.bgi` index for `chrom`, `rsid`, `id`, `start`, and `end` predicate pushdown when one is available.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

    !!! note
        BGEN is input-only.
    """
    lf = IOOperations.scan_bgen(
        path=path,
        genotype_output=genotype_output,
        probability_layout=probability_layout,
        samples=samples,
        genotype_fields=genotype_fields,
        sample_path=sample_path,
        bgi_path=bgi_path,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_bgen_matrix(path, samples=None, missing=None, sample_path=None, bgi_path=None, threads=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', use_zero_based=None) staticmethod

Read a BGEN's ALT dosages into a dense NumPy matrix.

The counterpart of read_pgen_matrix. scan_bgen returns Arrow batches that a caller wanting one array must then consolidate, and on a whole chromosome that consolidation is a serial pass over 10 GB — it does not parallelise, so it becomes the ceiling as partitions are added. This decodes each variant at its final address instead, which on chromosome 22 scales 6.0x from one thread to eight against the Arrow path's 4.2x.

Dosage only: BGEN probabilities are variable width and have no single dense shape. Use scan_bgen(genotype_output="probability") for those.

Parameters:

Name Type Description Default
path str

The path to the BGEN file. The path must end in .bgen.

required
samples Union[list[str], None]

Sample identifiers to emit, in requested order. If None, all samples are emitted in file order.

None
missing Union[float, None]

Written where a sample has no called genotype. Defaults to NaN.

None
sample_path Union[str, None]

An explicit Oxford .sample companion, used only when the BGEN has no embedded sample identifiers.

None
bgi_path Union[str, None]

An explicit .bgi index. A neighbouring file.bgen.bgi is discovered automatically.

None
threads Union[int, None]

Decoder threads. Defaults to the configured datafusion.execution.target_partitions.

None
use_zero_based Optional[bool]

Output coordinate convention for the returned positions.

None
Example
import polars_bio as pb

matrix = pb.read_bgen_matrix("chr22.bgen")
matrix.values.shape          # (variants, samples), float32
matrix.values.mean(axis=1)   # per-variant mean dosage
Source code in polars_bio/io.py
@staticmethod
def read_bgen_matrix(
    path: str,
    samples: Union[list[str], None] = None,
    missing: Union[float, None] = None,
    sample_path: Union[str, None] = None,
    bgi_path: Union[str, None] = None,
    threads: Union[int, None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    use_zero_based: Optional[bool] = None,
) -> PgenMatrix:
    """
    Read a BGEN's ALT dosages into a dense NumPy matrix.

    The counterpart of `read_pgen_matrix`. `scan_bgen` returns Arrow batches
    that a caller wanting one array must then consolidate, and on a whole
    chromosome that consolidation is a serial pass over 10 GB — it does not
    parallelise, so it becomes the ceiling as partitions are added. This
    decodes each variant at its final address instead, which on chromosome
    22 scales 6.0x from one thread to eight against the Arrow path's 4.2x.

    Dosage only: BGEN probabilities are variable width and have no single
    dense shape. Use `scan_bgen(genotype_output="probability")` for those.

    Parameters:
        path: The path to the BGEN file. The path must end in `.bgen`.
        samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in file order.
        missing: Written where a sample has no called genotype. Defaults to `NaN`.
        sample_path: An explicit Oxford `.sample` companion, used only when the BGEN has no embedded sample identifiers.
        bgi_path: An explicit `.bgi` index. A neighbouring `file.bgen.bgi` is discovered automatically.
        threads: Decoder threads. Defaults to the configured `datafusion.execution.target_partitions`.
        use_zero_based: Output coordinate convention for the returned positions.

    Example:
        ```python
        import polars_bio as pb

        matrix = pb.read_bgen_matrix("chr22.bgen")
        matrix.values.shape          # (variants, samples), float32
        matrix.values.mean(axis=1)   # per-variant mean dosage
        ```
    """
    # Imported here rather than at module scope: NumPy is not a polars-bio
    # dependency, and only the matrix readers need it.
    try:
        import numpy as np
    except ImportError as error:  # pragma: no cover - environment-dependent
        raise ImportError(
            "read_bgen_matrix returns NumPy arrays and needs NumPy installed"
        ) from error

    _validate_bgen_input_path(path)
    dtype = np.dtype(np.float32)
    if missing is None:
        missing = np.nan

    decode_options = BgenReadOptions(
        object_storage_options=PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        ),
        genotype_output="dosage",
        probability_layout="nested",
        samples=samples,
        genotype_fields=["DS"],
        sample_path=sample_path,
        bgi_path=bgi_path,
        zero_based=_resolve_zero_based(use_zero_based),
    )

    from polars_bio.context import get_option
    from polars_bio.polars_bio import BgenMatrixReader

    reader = BgenMatrixReader(path, decode_options)
    variants, columns = reader.shape()

    if threads is None:
        try:
            threads = int(get_option("datafusion.execution.target_partitions"))
        except (TypeError, ValueError):
            threads = 1
    threads = max(1, int(threads))

    values = np.empty((variants, columns), dtype=dtype)
    # As in `read_pgen_matrix`: the array goes across, not its address, and
    # the reader validates it before decoding.
    reader.read_into(values, threads, float(missing))

    positions = np.asarray(reader.positions(), dtype=np.int64)
    if positions.shape[0] != variants:
        raise RuntimeError(
            f"BGEN reported {variants} variants but {positions.shape[0]} positions"
        )
    return PgenMatrix(
        values=values, positions=positions, sample_names=list(reader.sample_names())
    )

read_pgen(path, genotype_fields=('GT',), samples=None, missing_sample_policy='error', psam_id_mode='iid', pvar_path=None, psam_path=None, pgi_path=None, max_range_gap=None, max_range_bytes=None, batch_soft_byte_limit=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a PLINK 2 PGEN fileset into a DataFrame.

One row is one PVAR variant. The .pvar and .psam companions are discovered from the .pgen basename.

Parameters:

Name Type Description Default
path str

The path to the PGEN file. The path must end in .pgen. A neighbouring .pvar (or .pvar.zst) and .psam are discovered automatically.

required
genotype_fields Sequence[str]

Genotype children to emit, from "GT", "ALT_COUNT", "PHASED", "DS", "DS_STORED", and "HDS", in the requested order. Defaults to ("GT",). Note this narrows the provider default, which emits all of them. "ALT_COUNT" is the hardcall ALT allele count as int8, one byte per genotype rather than the four "DS" uses; prefer it when the fileset stores only hardcalls.

('GT',)
samples Union[list[str], None]

Sample identifiers to emit, in requested order. If None, all samples are emitted in PSAM order.

None
missing_sample_policy str

"error" (default) rejects a requested sample name absent from the PSAM; "ignore" omits it from the selection.

'error'
psam_id_mode str

How selectable sample names are built from PSAM identifiers. "iid" (default) uses IID alone and rejects duplicates; "fid_iid" uses FID:IID; "fid_iid_sid" uses FID:IID:SID. A PSAM without FID or SID columns defaults those parts to "0".

'iid'
pvar_path Union[str, None]

An explicit .pvar companion. A neighbouring .pvar then .pvar.zst is discovered otherwise.

None
psam_path Union[str, None]

An explicit .psam companion. The shared-basename .psam is used otherwise.

None
pgi_path Union[str, None]

An explicit .pgi index, for a PGEN that uses an external index.

None
max_range_gap Union[int, None]

The largest run of unselected bytes bridged when coalescing reads, in bytes. The provider default is 0, which never bridges a gap and issues one read per contiguous run of selected variants. Raising it trades wasted bytes for fewer requests, which matters most on object storage. If None, the provider default is used.

None
max_range_bytes Union[int, None]

The largest coalesced read, in bytes. If None, the provider default is used.

None
batch_soft_byte_limit Union[int, None]

A soft target for genotype bytes in one RecordBatch. If None, the provider default is used.

None
chunk_size int

The size in MB of a chunk when reading from an object store.

8
concurrent_fetches int

The number of concurrent fetches when reading from an object store.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression override. PGEN record compression is read from the file header.

'auto'
projection_pushdown bool

Enable column projection pushdown. Metadata-only scans do not read genotype records.

True
predicate_pushdown bool

Push chrom, id, start, and end predicates into variant selection.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

None

Note

PGEN is input-only.

Source code in polars_bio/io.py
@staticmethod
def read_pgen(
    path: str,
    genotype_fields: Sequence[str] = ("GT",),
    samples: Union[list[str], None] = None,
    missing_sample_policy: str = "error",
    psam_id_mode: str = "iid",
    pvar_path: Union[str, None] = None,
    psam_path: Union[str, None] = None,
    pgi_path: Union[str, None] = None,
    max_range_gap: Union[int, None] = None,
    max_range_bytes: Union[int, None] = None,
    batch_soft_byte_limit: Union[int, None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a PLINK 2 PGEN fileset into a DataFrame.

    One row is one PVAR variant. The `.pvar` and `.psam` companions are
    discovered from the `.pgen` basename.

    Parameters:
        path: The path to the PGEN file. The path must end in `.pgen`. A neighbouring `.pvar` (or `.pvar.zst`) and `.psam` are discovered automatically.
        genotype_fields: Genotype children to emit, from `"GT"`, `"ALT_COUNT"`, `"PHASED"`, `"DS"`, `"DS_STORED"`, and `"HDS"`, in the requested order. Defaults to `("GT",)`. Note this narrows the provider default, which emits all of them. `"ALT_COUNT"` is the hardcall ALT allele count as `int8`, one byte per genotype rather than the four `"DS"` uses; prefer it when the fileset stores only hardcalls.
        samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in PSAM order.
        missing_sample_policy: `"error"` (default) rejects a requested sample name absent from the PSAM; `"ignore"` omits it from the selection.
        psam_id_mode: How selectable sample names are built from PSAM identifiers. `"iid"` (default) uses IID alone and rejects duplicates; `"fid_iid"` uses `FID:IID`; `"fid_iid_sid"` uses `FID:IID:SID`. A PSAM without FID or SID columns defaults those parts to `"0"`.
        pvar_path: An explicit `.pvar` companion. A neighbouring `.pvar` then `.pvar.zst` is discovered otherwise.
        psam_path: An explicit `.psam` companion. The shared-basename `.psam` is used otherwise.
        pgi_path: An explicit `.pgi` index, for a PGEN that uses an external index.
        max_range_gap: The largest run of unselected bytes bridged when coalescing reads, in bytes. The provider default is 0, which never bridges a gap and issues one read per contiguous run of selected variants. Raising it trades wasted bytes for fewer requests, which matters most on object storage. If *None*, the provider default is used.
        max_range_bytes: The largest coalesced read, in bytes. If *None*, the provider default is used.
        batch_soft_byte_limit: A soft target for genotype bytes in one RecordBatch. If *None*, the provider default is used.
        chunk_size: The size in MB of a chunk when reading from an object store.
        concurrent_fetches: The number of concurrent fetches when reading from an object store.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression override. PGEN record compression is read from the file header.
        projection_pushdown: Enable column projection pushdown. Metadata-only scans do not read genotype records.
        predicate_pushdown: Push `chrom`, `id`, `start`, and `end` predicates into variant selection.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

    !!! note
        PGEN is input-only.
    """
    lf = IOOperations.scan_pgen(
        path=path,
        genotype_fields=genotype_fields,
        samples=samples,
        missing_sample_policy=missing_sample_policy,
        psam_id_mode=psam_id_mode,
        pvar_path=pvar_path,
        psam_path=psam_path,
        pgi_path=pgi_path,
        max_range_gap=max_range_gap,
        max_range_bytes=max_range_bytes,
        batch_soft_byte_limit=batch_soft_byte_limit,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_pgen_matrix(path, field='ALT_COUNT', samples=None, missing=None, missing_sample_policy='error', psam_id_mode='iid', pvar_path=None, psam_path=None, pgi_path=None, max_range_gap=None, max_range_bytes=None, batch_soft_byte_limit=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', use_zero_based=None, copy_threads=None) staticmethod

Read one genotype field of a PGEN fileset into a dense NumPy matrix.

The whole-cohort matrix is what association testing, PCA, and relatedness pipelines consume, and going through a DataFrame to get one costs a second full copy of every value: the scan builds Arrow batches, and something then has to consolidate them into a contiguous array. The decoder here writes genotypes at their final address instead, so they are written once.

On chromosome 22 of 1000 Genomes (993,881 variants x 2,548 samples) the DS matrix takes 1.29 s and 12.6 GB, against 3.2 s and 22.3 GB through read_pgen. ALT_COUNT takes 0.70 s. Both are faster than PLINK 2's own pgenlib at one thread, and roughly three times faster again given eight partitions.

Parameters:

Name Type Description Default
path str

The path to the PGEN file. The path must end in .pgen.

required
field str

The genotype field to materialize: "ALT_COUNT" (int8 hardcall ALT allele count) or "DS" (float32 ALT dosage). Fields with more than one value per sample — "GT", "HDS" — have no dense matrix form, and "DS_STORED" has no decoder on this path; read those with read_pgen.

'ALT_COUNT'
samples Union[list[str], None]

Sample identifiers to emit, in requested order. If None, all samples are emitted in PSAM order. The matrix has one column per selected sample.

None
missing Union[int, float, None]

The value written where a genotype is missing. Defaults to -9 for "ALT_COUNT", matching PLINK's sentinel, and to NaN for the float fields.

None
missing_sample_policy str

"error" (default) rejects a requested sample name absent from the PSAM; "ignore" omits it.

'error'
psam_id_mode str

How selectable sample names are built from PSAM identifiers. See read_pgen.

'iid'
pvar_path Union[str, None]

An explicit .pvar companion.

None
psam_path Union[str, None]

An explicit .psam companion.

None
pgi_path Union[str, None]

An explicit .pgi index.

None
max_range_gap Union[int, None]

The largest run of unselected bytes bridged when coalescing reads.

None
max_range_bytes Union[int, None]

The largest coalesced read, in bytes.

None
batch_soft_byte_limit Union[int, None]

A soft target for genotype bytes in one RecordBatch.

None
chunk_size int

The size in MB of a chunk when reading from an object store.

8
concurrent_fetches int

The number of concurrent fetches when reading from an object store.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression override.

'auto'
use_zero_based Optional[bool]

If True, report 0-based positions. If False, 1-based. If None (default), uses the global configuration.

None
copy_threads Union[int, None]

How many threads decode into the result. They write disjoint row ranges, so they never contend. If None (default), this follows datafusion.execution.target_partitions, so a single-partition read stays single-threaded end to end.

None

Returns:

Type Description
PgenMatrix

A PgenMatrix of values (a C-contiguous (variants, samples)

PgenMatrix

array), positions (one per row), and sample_names (one per

PgenMatrix

column).

Note

Rows are in PVAR order at every partition count: each variant is written at its own row index rather than in the order it finished decoding. This differs from read_pgen, whose row order may interleave above one partition.

Example
import polars_bio as pb

matrix = pb.read_pgen_matrix("cohort.pgen", field="ALT_COUNT")
matrix.values.shape       # (variants, samples)
matrix.values.mean(axis=1)  # per-variant ALT frequency * 2
Source code in polars_bio/io.py
@staticmethod
def read_pgen_matrix(
    path: str,
    field: str = "ALT_COUNT",
    samples: Union[list[str], None] = None,
    missing: Union[int, float, None] = None,
    missing_sample_policy: str = "error",
    psam_id_mode: str = "iid",
    pvar_path: Union[str, None] = None,
    psam_path: Union[str, None] = None,
    pgi_path: Union[str, None] = None,
    max_range_gap: Union[int, None] = None,
    max_range_bytes: Union[int, None] = None,
    batch_soft_byte_limit: Union[int, None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    use_zero_based: Optional[bool] = None,
    copy_threads: Union[int, None] = None,
) -> "PgenMatrix":
    """
    Read one genotype field of a PGEN fileset into a dense NumPy matrix.

    The whole-cohort matrix is what association testing, PCA, and relatedness
    pipelines consume, and going through a DataFrame to get one costs a
    second full copy of every value: the scan builds Arrow batches, and
    something then has to consolidate them into a contiguous array. The
    decoder here writes genotypes at their final address instead, so they
    are written once.

    On chromosome 22 of 1000 Genomes (993,881 variants x 2,548 samples) the
    `DS` matrix takes **1.29 s** and 12.6 GB, against 3.2 s and 22.3 GB
    through `read_pgen`. `ALT_COUNT` takes 0.70 s. Both are faster than
    PLINK 2's own `pgenlib` at one thread, and roughly three times faster
    again given eight partitions.

    Parameters:
        path: The path to the PGEN file. The path must end in `.pgen`.
        field: The genotype field to materialize: `"ALT_COUNT"` (`int8` hardcall ALT allele count) or `"DS"` (`float32` ALT dosage). Fields with more than one value per sample — `"GT"`, `"HDS"` — have no dense matrix form, and `"DS_STORED"` has no decoder on this path; read those with `read_pgen`.
        samples: Sample identifiers to emit, in requested order. If *None*, all samples are emitted in PSAM order. The matrix has one column per selected sample.
        missing: The value written where a genotype is missing. Defaults to `-9` for `"ALT_COUNT"`, matching PLINK's sentinel, and to NaN for the float fields.
        missing_sample_policy: `"error"` (default) rejects a requested sample name absent from the PSAM; `"ignore"` omits it.
        psam_id_mode: How selectable sample names are built from PSAM identifiers. See `read_pgen`.
        pvar_path: An explicit `.pvar` companion.
        psam_path: An explicit `.psam` companion.
        pgi_path: An explicit `.pgi` index.
        max_range_gap: The largest run of unselected bytes bridged when coalescing reads.
        max_range_bytes: The largest coalesced read, in bytes.
        batch_soft_byte_limit: A soft target for genotype bytes in one RecordBatch.
        chunk_size: The size in MB of a chunk when reading from an object store.
        concurrent_fetches: The number of concurrent fetches when reading from an object store.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression override.
        use_zero_based: If True, report 0-based positions. If False, 1-based. If None (default), uses the global configuration.
        copy_threads: How many threads decode into the result. They write disjoint row ranges, so they never contend. If *None* (default), this follows `datafusion.execution.target_partitions`, so a single-partition read stays single-threaded end to end.

    Returns:
        A `PgenMatrix` of `values` (a C-contiguous `(variants, samples)`
        array), `positions` (one per row), and `sample_names` (one per
        column).

    !!! note
        Rows are in PVAR order at every partition count: each variant is
        written at its own row index rather than in the order it finished
        decoding. This differs from `read_pgen`, whose row order may
        interleave above one partition.

    Example:
        ```python
        import polars_bio as pb

        matrix = pb.read_pgen_matrix("cohort.pgen", field="ALT_COUNT")
        matrix.values.shape       # (variants, samples)
        matrix.values.mean(axis=1)  # per-variant ALT frequency * 2
        ```
    """
    # Imported here rather than at module scope: NumPy is not a polars-bio
    # dependency, and only this function needs it.
    try:
        import numpy as np
    except ImportError as error:  # pragma: no cover - environment-dependent
        raise ImportError(
            "read_pgen_matrix returns NumPy arrays and needs NumPy installed"
        ) from error

    dtypes = {
        "ALT_COUNT": np.int8,
        "DS": np.float32,
    }
    if field not in dtypes:
        raise ValueError(
            f"read_pgen_matrix supports {sorted(dtypes)}, not {field!r}. "
            "Fields with more than one value per sample have no dense matrix "
            "form, and DS_STORED has no decoder on this path; read them with "
            "read_pgen."
        )
    dtype = np.dtype(dtypes[field])
    if missing is None:
        missing = -9 if dtype == np.int8 else np.nan
    elif field == "ALT_COUNT":
        # The sentinel crosses into Rust as an f64 and is written with
        # `as i8`, which saturates out-of-range values and turns NaN into
        # 0 — silently indistinguishable from a homozygous-reference call.
        # Reject what that cast would corrupt rather than write it.
        sentinel = float(missing)
        if (
            not np.isfinite(sentinel)
            or sentinel != int(sentinel)
            or not -128 <= sentinel <= 127
        ):
            raise ValueError(
                f"missing={missing!r} is not representable as the int8 "
                "ALT_COUNT matrix stores; pass a whole number in "
                "[-128, 127] (PLINK's own sentinel is -9)"
            )

    # Built directly rather than through `scan_pgen`, because this path does
    # not register a table: the reader opens the fileset itself and answers
    # shape, names and positions from it, so the PVAR is parsed once.
    decode_options = PgenReadOptions(
        object_storage_options=PyObjectStorageOptions(
            allow_anonymous=allow_anonymous,
            enable_request_payer=enable_request_payer,
            chunk_size=chunk_size,
            concurrent_fetches=concurrent_fetches,
            max_retries=max_retries,
            timeout=timeout,
            compression_type=compression_type,
        ),
        genotype_fields=[field],
        zero_based=_resolve_zero_based(use_zero_based),
        samples=samples,
        missing_sample_policy=missing_sample_policy,
        psam_id_mode=psam_id_mode,
        pvar_path=pvar_path,
        psam_path=psam_path,
        pgi_path=pgi_path,
        max_range_gap=max_range_gap,
        max_range_bytes=max_range_bytes,
        batch_soft_byte_limit=batch_soft_byte_limit,
    )

    from polars_bio.context import get_option
    from polars_bio.polars_bio import PgenMatrixReader

    reader = PgenMatrixReader(path, decode_options)
    variants, columns = reader.shape()

    if copy_threads is None:
        try:
            copy_threads = int(get_option("datafusion.execution.target_partitions"))
        except (TypeError, ValueError):
            copy_threads = 1
    copy_threads = max(1, int(copy_threads))

    values = np.empty((variants, columns), dtype=dtype)
    # The array itself is handed over, not its address: the reader checks
    # dtype, C-contiguity, writability and length at the boundary, which is
    # the only place a caller cannot route around.
    reader.read_into(field, values, copy_threads, float(missing))

    positions = np.asarray(reader.positions(), dtype=np.int64)
    if positions.shape[0] != variants:
        raise RuntimeError(
            f"PGEN reported {variants} variants but {positions.shape[0]} positions"
        )
    return PgenMatrix(
        values=values, positions=positions, sample_names=list(reader.sample_names())
    )

read_vcf(path, info_fields=None, format_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, samples=None) staticmethod

Read a text VCF file into a DataFrame.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a VCF TBI/CSI index is present. See File formats support, Indexed reads, and Automatic parallel partitioning for details.

Parameters:

Name Type Description Default
path str

The path to the VCF file.

required
info_fields Union[list[str], None]

List of INFO field names to include. If None, all INFO fields from the VCF header are included by default. Use this to limit fields for better performance.

None
format_fields Union[list[str], None]

List of FORMAT field names to include (per-sample genotype data). If None, all FORMAT fields are included by default. For single-sample VCFs, FORMAT fields are top-level columns (e.g., GT, DP). For multi-sample VCFs, FORMAT data is exposed as a nested genotypes column (struct<GT: list, DP: list, ...>) with sample names in meta["header"]["sample_names"].

None
samples Union[list[str], None]

Optional list of sample names to include from the VCF header. Matching is exact and case-sensitive. Missing sample names are skipped with a warning. The output follows the requested sample order.

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the VCF file. If not specified, it will be detected automatically..

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using VCF TBI/CSI index files for efficient region-based filtering. Index files are auto-discovered (for example, file.vcf.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Reading VCF with INFO and FORMAT fields

import polars_bio as pb

# Read VCF with both INFO and FORMAT fields
df = pb.read_vcf(
    "sample.vcf.gz",
    info_fields=["END"],              # INFO field
    format_fields=["GT", "DP", "GQ"]  # FORMAT fields
)

# Single-sample VCF: FORMAT fields are top-level columns (GT, DP, GQ)
print(df.select(["chrom", "start", "ref", "alt", "END", "GT", "DP", "GQ"]))
# Output:
# shape: (10, 8)
# ┌───────┬───────┬─────┬─────┬──────┬─────┬─────┬─────┐
# │ chrom ┆ start ┆ ref ┆ alt ┆ END  ┆ GT  ┆ DP  ┆ GQ  │
# │ str   ┆ u32   ┆ str ┆ str ┆ i32  ┆ str ┆ i32 ┆ i32 │
# ╞═══════╪═══════╪═════╪═════╪══════╪═════╪═════╪═════╡
# │ 1     ┆ 10009 ┆ A   ┆ .   ┆ null ┆ 0/0 ┆ 10  ┆ 27  │
# │ 1     ┆ 10015 ┆ A   ┆ .   ┆ null ┆ 0/0 ┆ 17  ┆ 35  │
# └───────┴───────┴─────┴─────┴──────┴─────┴─────┴─────┘

# Multi-sample VCF: FORMAT data is nested in "genotypes"
df = pb.read_vcf("multisample.vcf", format_fields=["GT", "DP"])
print(df.select(["chrom", "start", "genotypes"]))
Source code in polars_bio/io.py
@staticmethod
def read_vcf(
    path: str,
    info_fields: Union[list[str], None] = None,
    format_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    samples: Union[list[str], None] = None,
) -> pl.DataFrame:
    """
    Read a text VCF file into a DataFrame.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a VCF TBI/CSI
        index is present. See [File formats support](/polars-bio/features/#file-formats-support),
        [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

    Parameters:
        path: The path to the VCF file.
        info_fields: List of INFO field names to include. If *None*, all INFO fields from the VCF header are included by default. Use this to limit fields for better performance.
        format_fields: List of FORMAT field names to include (per-sample genotype data). If *None*, all FORMAT fields are included by default. For **single-sample** VCFs, FORMAT fields are top-level columns (e.g., `GT`, `DP`). For **multi-sample** VCFs, FORMAT data is exposed as a nested `genotypes` column (`struct<GT: list, DP: list, ...>`) with sample names in `meta["header"]["sample_names"]`.
        samples: Optional list of sample names to include from the VCF header. Matching is exact and case-sensitive. Missing sample names are skipped with a warning. The output follows the requested sample order.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the VCF file. If not specified, it will be detected automatically..
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using VCF TBI/CSI index files for efficient region-based filtering. Index files are auto-discovered (for example, `file.vcf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

    !!! Example "Reading VCF with INFO and FORMAT fields"
        ```python
        import polars_bio as pb

        # Read VCF with both INFO and FORMAT fields
        df = pb.read_vcf(
            "sample.vcf.gz",
            info_fields=["END"],              # INFO field
            format_fields=["GT", "DP", "GQ"]  # FORMAT fields
        )

        # Single-sample VCF: FORMAT fields are top-level columns (GT, DP, GQ)
        print(df.select(["chrom", "start", "ref", "alt", "END", "GT", "DP", "GQ"]))
        # Output:
        # shape: (10, 8)
        # ┌───────┬───────┬─────┬─────┬──────┬─────┬─────┬─────┐
        # │ chrom ┆ start ┆ ref ┆ alt ┆ END  ┆ GT  ┆ DP  ┆ GQ  │
        # │ str   ┆ u32   ┆ str ┆ str ┆ i32  ┆ str ┆ i32 ┆ i32 │
        # ╞═══════╪═══════╪═════╪═════╪══════╪═════╪═════╪═════╡
        # │ 1     ┆ 10009 ┆ A   ┆ .   ┆ null ┆ 0/0 ┆ 10  ┆ 27  │
        # │ 1     ┆ 10015 ┆ A   ┆ .   ┆ null ┆ 0/0 ┆ 17  ┆ 35  │
        # └───────┴───────┴─────┴─────┴──────┴─────┴─────┴─────┘

        # Multi-sample VCF: FORMAT data is nested in "genotypes"
        df = pb.read_vcf("multisample.vcf", format_fields=["GT", "DP"])
        print(df.select(["chrom", "start", "genotypes"]))
        ```
    """
    lf = IOOperations.scan_vcf(
        path=path,
        info_fields=info_fields,
        format_fields=format_fields,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
        samples=samples,
    )
    # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    # Set metadata on the collected DataFrame
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_vcf_zarr(path, info_fields=None, format_fields=None, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, samples=None, genotype_encoding_raw=True) staticmethod

Read a local VCF Zarr store into a DataFrame.

Parameters:

Name Type Description Default
path str

The path to the VCF Zarr store directory.

required
info_fields Union[list[str], None]

Optional list of INFO field names to include. If None, local INFO arrays are discovered automatically. Use [] to disable INFO fields.

None
format_fields Union[list[str], None]

Optional list of FORMAT field names to include. If None, local FORMAT arrays are discovered automatically. Use [] to disable FORMAT fields.

None
projection_pushdown bool

Enable column projection pushdown at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown at the DataFusion level.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None, uses the global configuration.

None
samples Union[list[str], None]

Optional list of sample names to include.

None
genotype_encoding_raw bool

If True, output GT as raw typed allele calls. If False, output VCF-style GT strings.

True
Source code in polars_bio/io.py
@staticmethod
def read_vcf_zarr(
    path: str,
    info_fields: Union[list[str], None] = None,
    format_fields: Union[list[str], None] = None,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    samples: Union[list[str], None] = None,
    genotype_encoding_raw: bool = True,
) -> pl.DataFrame:
    """
    Read a local VCF Zarr store into a DataFrame.

    Parameters:
        path: The path to the VCF Zarr store directory.
        info_fields: Optional list of INFO field names to include. If None, local INFO arrays are discovered automatically. Use [] to disable INFO fields.
        format_fields: Optional list of FORMAT field names to include. If None, local FORMAT arrays are discovered automatically. Use [] to disable FORMAT fields.
        projection_pushdown: Enable column projection pushdown at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown at the DataFusion level.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None, uses the global configuration.
        samples: Optional list of sample names to include.
        genotype_encoding_raw: If True, output GT as raw typed allele calls. If False, output VCF-style GT strings.
    """
    lf = IOOperations.scan_vcf_zarr(
        path=path,
        info_fields=info_fields,
        format_fields=format_fields,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
        samples=samples,
        genotype_encoding_raw=genotype_encoding_raw,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_bam(path, tag_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, infer_tag_types=True, infer_tag_sample_size=100, tag_type_hints=None) staticmethod

Read a BAM file into a DataFrame.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a BAI/CSI index is present. See File formats support, Indexed reads, and Automatic parallel partitioning for details.

Parameters:

Name Type Description Default
path str

The path to the BAM file.

required
tag_fields Union[list[str], None]

List of BAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large-scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using index files (BAI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.bam.bai). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None
infer_tag_types bool

If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.

True
infer_tag_sample_size int

Number of records to sample for tag type inference (default: 100).

100
tag_type_hints Optional[list[str]]

Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def read_bam(
    path: str,
    tag_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    infer_tag_types: bool = True,
    infer_tag_sample_size: int = 100,
    tag_type_hints: Optional[list[str]] = None,
) -> pl.DataFrame:
    """
    Read a BAM file into a DataFrame.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a BAI/CSI index
        is present. See [File formats support](/polars-bio/features/#file-formats-support),
        [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

    Parameters:
        path: The path to the BAM file.
        tag_fields: List of BAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large-scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using index files (BAI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.bam.bai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
        infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
        infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
        tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    lf = IOOperations.scan_bam(
        path,
        tag_fields,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
        infer_tag_types,
        infer_tag_sample_size,
        tag_type_hints,
    )
    # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    # Set metadata on the collected DataFrame
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_cram(path, reference_path=None, tag_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, infer_tag_types=True, infer_tag_sample_size=100, tag_type_hints=None) staticmethod

Read a CRAM file into a DataFrame.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a CRAI index is present. See File formats support, Indexed reads, and Automatic parallel partitioning for details.

Parameters:

Name Type Description Default
path str

The path to the CRAM file (local or cloud storage: S3, GCS, Azure Blob).

required
reference_path str

Optional path to external FASTA reference file (local path only, cloud storage not supported). If not provided, the CRAM file must contain embedded reference sequences. The FASTA file must have an accompanying index file (.fai) in the same directory. Create the index using: samtools faidx reference.fasta

None
tag_fields Union[list[str], None]

List of CRAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True
predicate_pushdown bool

Enable predicate pushdown using index files (CRAI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.cram.crai). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None
infer_tag_types bool

If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.

True
infer_tag_sample_size int

Number of records to sample for tag type inference (default: 100).

100
tag_type_hints Optional[list[str]]

Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Known Limitation: MD and NM Tags

Due to a limitation in the underlying noodles-cram library, MD (mismatch descriptor) and NM (edit distance) tags are not accessible from CRAM files, even when stored in the file. These tags can be seen with samtools but are not exposed through the noodles-cram record.data() interface.

Other optional tags (RG, MQ, AM, OQ, etc.) work correctly. This issue is tracked at: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

Workaround: Use BAM format if MD/NM tags are required for your analysis.

Using External Reference

import polars_bio as pb

# Read CRAM with external reference
df = pb.read_cram(
    "/path/to/file.cram",
    reference_path="/path/to/reference.fasta"
)

Public CRAM File Example

Download and read a public CRAM file from 42basepairs:

# Download the CRAM file and reference
wget https://42basepairs.com/download/s3/gatk-test-data/wgs_cram/NA12878_20k_hg38/NA12878.cram
wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta

# Create FASTA index (required)
samtools faidx Homo_sapiens_assembly38.fasta

import polars_bio as pb

# Read first 5 reads from the CRAM file
df = pb.scan_cram(
    "NA12878.cram",
    reference_path="Homo_sapiens_assembly38.fasta"
).limit(5).collect()

print(df.select(["name", "chrom", "start", "end", "cigar"]))

Creating CRAM with Embedded Reference

To create a CRAM file with embedded reference using samtools:

samtools view -C -o output.cram --output-fmt-option embed_ref=1 input.bam

Returns:

Type Description
DataFrame

A Polars DataFrame with the following schema: - name: Read name (String) - chrom: Chromosome/contig name (String) - start: Alignment start position, 1-based (UInt32) - end: Alignment end position, 1-based (UInt32) - flags: SAM flags (UInt32) - cigar: CIGAR string (String) - mapping_quality: Mapping quality (UInt32) - mate_chrom: Mate chromosome/contig name (String) - mate_start: Mate alignment start position, 1-based (UInt32) - sequence: Read sequence (String) - quality_scores: Base quality scores (String)

Source code in polars_bio/io.py
@staticmethod
def read_cram(
    path: str,
    reference_path: str = None,
    tag_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    infer_tag_types: bool = True,
    infer_tag_sample_size: int = 100,
    tag_type_hints: Optional[list[str]] = None,
) -> pl.DataFrame:
    """
    Read a CRAM file into a DataFrame.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a CRAI index
        is present. See [File formats support](/polars-bio/features/#file-formats-support),
        [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

    Parameters:
        path: The path to the CRAM file (local or cloud storage: S3, GCS, Azure Blob).
        reference_path: Optional path to external FASTA reference file (**local path only**, cloud storage not supported). If not provided, the CRAM file must contain embedded reference sequences. The FASTA file must have an accompanying index file (.fai) in the same directory. Create the index using: `samtools faidx reference.fasta`
        tag_fields: List of CRAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
        predicate_pushdown: Enable predicate pushdown using index files (CRAI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.cram.crai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
        infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
        infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
        tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

    !!! warning "Known Limitation: MD and NM Tags"
        Due to a limitation in the underlying noodles-cram library, **MD (mismatch descriptor) and NM (edit distance) tags are not accessible** from CRAM files, even when stored in the file. These tags can be seen with samtools but are not exposed through the noodles-cram record.data() interface.

        Other optional tags (RG, MQ, AM, OQ, etc.) work correctly. This issue is tracked at: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

        **Workaround**: Use BAM format if MD/NM tags are required for your analysis.

    !!! example "Using External Reference"
        ```python
        import polars_bio as pb

        # Read CRAM with external reference
        df = pb.read_cram(
            "/path/to/file.cram",
            reference_path="/path/to/reference.fasta"
        )
        ```

    !!! example "Public CRAM File Example"
        Download and read a public CRAM file from 42basepairs:
        ```bash
        # Download the CRAM file and reference
        wget https://42basepairs.com/download/s3/gatk-test-data/wgs_cram/NA12878_20k_hg38/NA12878.cram
        wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta

        # Create FASTA index (required)
        samtools faidx Homo_sapiens_assembly38.fasta
        ```

        ```python
        import polars_bio as pb

        # Read first 5 reads from the CRAM file
        df = pb.scan_cram(
            "NA12878.cram",
            reference_path="Homo_sapiens_assembly38.fasta"
        ).limit(5).collect()

        print(df.select(["name", "chrom", "start", "end", "cigar"]))
        ```

    !!! example "Creating CRAM with Embedded Reference"
        To create a CRAM file with embedded reference using samtools:
        ```bash
        samtools view -C -o output.cram --output-fmt-option embed_ref=1 input.bam
        ```

    Returns:
        A Polars DataFrame with the following schema:
            - name: Read name (String)
            - chrom: Chromosome/contig name (String)
            - start: Alignment start position, 1-based (UInt32)
            - end: Alignment end position, 1-based (UInt32)
            - flags: SAM flags (UInt32)
            - cigar: CIGAR string (String)
            - mapping_quality: Mapping quality (UInt32)
            - mate_chrom: Mate chromosome/contig name (String)
            - mate_start: Mate alignment start position, 1-based (UInt32)
            - sequence: Read sequence (String)
            - quality_scores: Base quality scores (String)
    """
    lf = IOOperations.scan_cram(
        path,
        reference_path,
        tag_fields,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
        infer_tag_types,
        infer_tag_sample_size,
        tag_type_hints,
    )
    # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    # Set metadata on the collected DataFrame
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_sam(path, tag_fields=None, projection_pushdown=True, use_zero_based=None, infer_tag_types=True, infer_tag_sample_size=100, tag_type_hints=None) staticmethod

Read a SAM file into a DataFrame.

SAM (Sequence Alignment/Map) is the plain-text counterpart of BAM. This function reuses the BAM reader, which auto-detects the format from the file extension.

Parameters:

Name Type Description Default
path str

The path to the SAM file.

required
tag_fields Union[list[str], None]

List of SAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default).

None
projection_pushdown bool

Enable column projection pushdown to optimize query performance.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

None
infer_tag_types bool

If True (default), sample the file to auto-detect types for custom/unknown tags.

True
infer_tag_sample_size int

Number of records to sample for tag type inference (default: 100).

100
tag_type_hints Optional[list[str]]

Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

None

Note

By default, coordinates are output in 1-based closed format.

Source code in polars_bio/io.py
@staticmethod
def read_sam(
    path: str,
    tag_fields: Union[list[str], None] = None,
    projection_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    infer_tag_types: bool = True,
    infer_tag_sample_size: int = 100,
    tag_type_hints: Optional[list[str]] = None,
) -> pl.DataFrame:
    """
    Read a SAM file into a DataFrame.

    SAM (Sequence Alignment/Map) is the plain-text counterpart of BAM.
    This function reuses the BAM reader, which auto-detects the format
    from the file extension.

    Parameters:
        path: The path to the SAM file.
        tag_fields: List of SAM tag names to include as columns (e.g., ["NM", "MD", "AS"]).
            If None, no optional tags are parsed (default).
        projection_pushdown: Enable column projection pushdown to optimize query performance.
        use_zero_based: If True, output 0-based half-open coordinates.
            If False, output 1-based closed coordinates.
            If None (default), uses the global configuration.
        infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags.
        infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
        tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

    !!! note
        By default, coordinates are output in **1-based closed** format.
    """
    lf = IOOperations.scan_sam(
        path,
        tag_fields,
        projection_pushdown,
        use_zero_based,
        infer_tag_types,
        infer_tag_sample_size,
        tag_type_hints,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_fastq(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True) staticmethod

Read a FASTQ file into a DataFrame.

Parallelism & Compression

See File formats support, Compression, and Automatic parallel partitioning for details on parallel reads and supported compression types.

Parameters:

Name Type Description Default
path str

The path to the FASTQ file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the FASTQ file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
Source code in polars_bio/io.py
@staticmethod
def read_fastq(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
) -> pl.DataFrame:
    """
    Read a FASTQ file into a DataFrame.

    !!! hint "Parallelism & Compression"
        See [File formats support](/polars-bio/features/#file-formats-support),
        [Compression](/polars-bio/features/#compression),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details on parallel reads and supported compression types.

    Parameters:
        path: The path to the FASTQ file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the FASTQ file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
    """
    return IOOperations.scan_fastq(
        path,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
    ).collect()

read_fasta(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True) staticmethod

Read a FASTA file into a DataFrame.

Parameters:

Name Type Description Default
path str

The path to the FASTA file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the FASTA file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').

'auto'
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True

Example

wget https://www.ebi.ac.uk/ena/browser/api/fasta/BK006935.2?download=true -O /tmp/test.fasta

import polars_bio as pb
pb.read_fasta("/tmp/test.fasta").limit(1)
 shape: (1, 3)
┌─────────────────────────┬─────────────────────────────────┬─────────────────────────────────┐
 name                     description                      sequence                         ---                      ---                              ---                              str                      str                              str                             ╞═════════════════════════╪═════════════════════════════════╪═════════════════════════════════╡
 ENA|BK006935|BK006935.2  TPA_inf: Saccharomyces cerevis…  CCACACCACACCCACACACCCACACACCAC… └─────────────────────────┴─────────────────────────────────┴─────────────────────────────────┘

Source code in polars_bio/io.py
@staticmethod
def read_fasta(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
) -> pl.DataFrame:
    """

    Read a FASTA file into a DataFrame.

    Parameters:
        path: The path to the FASTA file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the FASTA file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

    !!! Example
        ```shell
        wget https://www.ebi.ac.uk/ena/browser/api/fasta/BK006935.2?download=true -O /tmp/test.fasta
        ```

        ```python
        import polars_bio as pb
        pb.read_fasta("/tmp/test.fasta").limit(1)
        ```
        ```shell
         shape: (1, 3)
        ┌─────────────────────────┬─────────────────────────────────┬─────────────────────────────────┐
        │ name                    ┆ description                     ┆ sequence                        │
        │ ---                     ┆ ---                             ┆ ---                             │
        │ str                     ┆ str                             ┆ str                             │
        ╞═════════════════════════╪═════════════════════════════════╪═════════════════════════════════╡
        │ ENA|BK006935|BK006935.2 ┆ TPA_inf: Saccharomyces cerevis… ┆ CCACACCACACCCACACACCCACACACCAC… │
        └─────────────────────────┴─────────────────────────────────┴─────────────────────────────────┘
        ```
    """
    return IOOperations.scan_fasta(
        path,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
    ).collect()

read_gff(path, attr_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a GFF file into a DataFrame.

Parameters:

Name Type Description Default
path str

The path to the GFF file.

required
attr_fields Union[list[str], None]

List of attribute field names to extract as separate columns. If None, attributes will be kept as a nested structure. Use this to extract specific attributes like 'ID', 'gene_name', 'gene_type', etc. as direct columns for easier access.

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the GFF file. If not specified, it will be detected automatically..

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.gff.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def read_gff(
    path: str,
    attr_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a GFF file into a DataFrame.

    Parameters:
        path: The path to the GFF file.
        attr_fields: List of attribute field names to extract as separate columns. If *None*, attributes will be kept as a nested structure. Use this to extract specific attributes like 'ID', 'gene_name', 'gene_type', etc. as direct columns for easier access.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the GFF file. If not specified, it will be detected automatically..
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gff.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    lf = IOOperations.scan_gff(
        path,
        attr_fields,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
    )
    # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    # Set metadata on the collected DataFrame
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_gtf(path, attr_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a GTF file into a DataFrame.

GTF (Gene Transfer Format) shares the same 9-column structure as GFF but uses different attribute syntax (key "value" vs GFF's key=value).

Parameters:

Name Type Description Default
path str

The path to the GTF file.

required
attr_fields Union[list[str], None]

List of attribute field names to extract as separate columns. If None, attributes will be kept as a nested structure.

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the GTF file. If not specified, it will be detected automatically.

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.gtf.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def read_gtf(
    path: str,
    attr_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a GTF file into a DataFrame.

    GTF (Gene Transfer Format) shares the same 9-column structure as GFF but uses
    different attribute syntax (``key "value"`` vs GFF's ``key=value``).

    Parameters:
        path: The path to the GTF file.
        attr_fields: List of attribute field names to extract as separate columns.
            If *None*, attributes will be kept as a nested structure.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the GTF file. If not specified, it will be detected automatically.
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gtf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    lf = IOOperations.scan_gtf(
        path,
        attr_fields,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_bed(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, use_zero_based=None) staticmethod

Read a BED file into a DataFrame.

Parameters:

Name Type Description Default
path str

The path to the BED file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the BED file. If not specified, it will be detected automatically based on the file extension. BGZF compressions is supported ('bgz').

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

Only BED4 format is supported. It extends the basic BED format (BED3) by adding a name field, resulting in four columns: chromosome, start position, end position, and name. Also unlike other text formats, GZIP compression is not supported.

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def read_bed(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a BED file into a DataFrame.

    Parameters:
        path: The path to the BED file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the BED file. If not specified, it will be detected automatically based on the file extension. BGZF compressions is supported ('bgz').
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! Note
        Only **BED4** format is supported. It extends the basic BED format (BED3) by adding a name field, resulting in four columns: chromosome, start position, end position, and name.
        Also unlike other text formats, **GZIP** compression is not supported.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    lf = IOOperations.scan_bed(
        path,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
        use_zero_based,
    )
    # Get metadata before collecting (polars-config-meta doesn't preserve through collect)
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    # Set metadata on the collected DataFrame
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_pairs(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a Pairs (Hi-C) file into a DataFrame.

The Pairs format (4DN project) stores chromatin contact data with columns: readID, chr1, pos1, chr2, pos2, strand1, strand2.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a TBI index is present. See File formats support and Indexed reads for details.

Parameters:

Name Type Description Default
path str

The path to the Pairs file (.pairs, .pairs.gz, .pairs.bgz).

required
chunk_size int

The size in MB of a chunk when reading from an object store.

8
concurrent_fetches int

The number of concurrent fetches when reading from an object store.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type. If not specified, it will be detected automatically.

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance.

True
predicate_pushdown bool

Enable predicate pushdown using index files (TBI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.pairs.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def read_pairs(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a Pairs (Hi-C) file into a DataFrame.

    The Pairs format (4DN project) stores chromatin contact data with columns:
    readID, chr1, pos1, chr2, pos2, strand1, strand2.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a TBI index
        is present. See [File formats support](/polars-bio/features/#file-formats-support)
        and [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown) for details.

    Parameters:
        path: The path to the Pairs file (.pairs, .pairs.gz, .pairs.bgz).
        chunk_size: The size in MB of a chunk when reading from an object store.
        concurrent_fetches: The number of concurrent fetches when reading from an object store.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type. If not specified, it will be detected automatically.
        projection_pushdown: Enable column projection pushdown to optimize query performance.
        predicate_pushdown: Enable predicate pushdown using index files (TBI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.pairs.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    lf = IOOperations.scan_pairs(
        path,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_bigwig(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a BigWig file into a DataFrame.

BigWig rows are exposed as chrom, start, end, and value.

Parameters:

Name Type Description Default
path str

The path to the BigWig file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the BigWig file. If not specified, it will be detected automatically based on the file extension.

'auto'
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True
predicate_pushdown bool

Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.

True
use_zero_based Optional[bool]

Coordinate system override. BigWig is natively 0-based half-open; set to False to emit 1-based closed coordinates, or None to use the global default.

None
Source code in polars_bio/io.py
@staticmethod
def read_bigwig(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a BigWig file into a DataFrame.

    BigWig rows are exposed as ``chrom``, ``start``, ``end``, and ``value``.

    Parameters:
        path: The path to the BigWig file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the BigWig file. If not specified, it will be detected automatically based on the file extension.
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
        predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
        use_zero_based: Coordinate system override. BigWig is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
    """
    lf = IOOperations.scan_bigwig(
        path,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_bigbed(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, schema='auto') staticmethod

Read a BigBed file into a DataFrame.

schema="auto" uses supported autoSQL fields when available. schema="rest" exposes the raw trailing fields in rest.

Parameters:

Name Type Description Default
path str

The path to the BigBed file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the BigBed file. If not specified, it will be detected automatically based on the file extension.

'auto'
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True
predicate_pushdown bool

Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.

True
use_zero_based Optional[bool]

Coordinate system override. BigBed is natively 0-based half-open; set to False to emit 1-based closed coordinates, or None to use the global default.

None
schema str

Schema mode. "auto" exposes the supported autoSQL fields when available; "rest" exposes the raw trailing fields in a single rest column.

'auto'
Source code in polars_bio/io.py
@staticmethod
def read_bigbed(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    schema: str = "auto",
) -> pl.DataFrame:
    """
    Read a BigBed file into a DataFrame.

    ``schema="auto"`` uses supported autoSQL fields when available.
    ``schema="rest"`` exposes the raw trailing fields in ``rest``.

    Parameters:
        path: The path to the BigBed file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the BigBed file. If not specified, it will be detected automatically based on the file extension.
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
        predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
        use_zero_based: Coordinate system override. BigBed is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
        schema: Schema mode. ``"auto"`` exposes the supported autoSQL fields when available; ``"rest"`` exposes the raw trailing fields in a single ``rest`` column.
    """
    lf = IOOperations.scan_bigbed(
        path,
        chunk_size,
        concurrent_fetches,
        allow_anonymous,
        enable_request_payer,
        max_retries,
        timeout,
        compression_type,
        projection_pushdown,
        predicate_pushdown,
        use_zero_based,
        schema,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_cool(path, resolution=None, join_bins=True, include_weights=False, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Read a Cooler (.cool/.mcool) Hi-C contact matrix into a DataFrame.

See scan_cool for parameter semantics.

Parameters:

Name Type Description Default
path str

The path to the .cool/.mcool file, or a cooler URI (file.mcool::/resolutions/10000).

required
resolution Optional[int]

Bin size selecting an .mcool data collection. Optional for .cool files and single-resolution .mcool files.

None
join_bins bool

If True (default), join pixels with bin coordinates (chrom1, start1, end1, chrom2, start2, end2, count); if False, return the raw COO triple (bin1_id, bin2_id, count).

True
include_weights bool

If True, expose balancing weights as weight1/weight2 (requires a balanced cooler).

False
projection_pushdown bool

Enable column projection pushdown optimization.

True
predicate_pushdown bool

Enable predicate pushdown on the first-axis genomic columns (chrom1, start1, end1) so range filters prune pixel row ranges through the cooler indexes.

True
use_zero_based Optional[bool]

Coordinate system override. Cooler is natively 0-based half-open; set to False to emit 1-based closed coordinates, or None to use the global default.

None
Source code in polars_bio/io.py
@staticmethod
def read_cool(
    path: str,
    resolution: Optional[int] = None,
    join_bins: bool = True,
    include_weights: bool = False,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Read a Cooler (`.cool`/`.mcool`) Hi-C contact matrix into a DataFrame.

    See `scan_cool` for parameter semantics.

    Parameters:
        path: The path to the `.cool`/`.mcool` file, or a cooler URI (`file.mcool::/resolutions/10000`).
        resolution: Bin size selecting an `.mcool` data collection. Optional for `.cool` files and single-resolution `.mcool` files.
        join_bins: If *True* (default), join pixels with bin coordinates (`chrom1`, `start1`, `end1`, `chrom2`, `start2`, `end2`, `count`); if *False*, return the raw COO triple (`bin1_id`, `bin2_id`, `count`).
        include_weights: If *True*, expose balancing weights as `weight1`/`weight2` (requires a balanced cooler).
        projection_pushdown: Enable column projection pushdown optimization.
        predicate_pushdown: Enable predicate pushdown on the first-axis genomic columns (`chrom1`, `start1`, `end1`) so range filters prune pixel row ranges through the cooler indexes.
        use_zero_based: Coordinate system override. Cooler is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
    """
    lf = IOOperations.scan_cool(
        path,
        resolution=resolution,
        join_bins=join_bins,
        include_weights=include_weights,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
    )
    zero_based = lf.config_meta.get_metadata().get("coordinate_system_zero_based")
    df = lf.collect()
    if zero_based is not None:
        set_coordinate_system(df, zero_based)
    return df

read_table(path, schema=None, **kwargs) staticmethod

Read a tab-delimited (i.e. BED) file into a Polars DataFrame. Tries to be compatible with Bioframe's read_table but faster. Schema should follow the Bioframe's schema format.

Parameters:

Name Type Description Default
path str

The path to the file.

required
schema Dict

Schema should follow the Bioframe's schema format.

None
Source code in polars_bio/io.py
@staticmethod
def read_table(path: str, schema: Dict = None, **kwargs) -> pl.DataFrame:
    """
     Read a tab-delimited (i.e. BED) file into a Polars DataFrame.
     Tries to be compatible with Bioframe's [read_table](https://bioframe.readthedocs.io/en/latest/guide-io.html)
     but faster. Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).

    Parameters:
        path: The path to the file.
        schema: Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).
    """
    return IOOperations.scan_table(path, schema, **kwargs).collect()

scan_bcf(path, info_fields=None, format_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, samples=None, genotype_output='string') staticmethod

Lazily read a BCF file into a LazyFrame.

BCF CSI range pushdown, projection pushdown, and configured input partition parallelism are preserved. genotype_output="string" returns VCF-style GT calls and remains the default. genotype_output="dosage" returns the number of ALT alleles per sample as nullable Int8 (normally 0, 1, or 2 for diploid calls); any missing allele yields null. Dosage requires GT to be the only selected FORMAT field and requires biallelic records. When format_fields is None, all header-defined FORMAT fields are selected, so pass format_fields=["GT"] when the header declares additional fields. Multiallelic records are rejected.

Source code in polars_bio/io.py
@staticmethod
def scan_bcf(
    path: str,
    info_fields: Union[list[str], None] = None,
    format_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    samples: Union[list[str], None] = None,
    genotype_output: str = "string",
) -> pl.LazyFrame:
    """Lazily read a BCF file into a LazyFrame.

    BCF CSI range pushdown, projection pushdown, and configured input
    partition parallelism are preserved. `genotype_output="string"` returns
    VCF-style GT calls and remains the default. `genotype_output="dosage"`
    returns the number of ALT alleles per sample as nullable `Int8` (normally
    0, 1, or 2 for diploid calls); any missing allele yields null. Dosage
    requires GT to be the only selected FORMAT field and requires biallelic
    records. When `format_fields` is `None`, all header-defined FORMAT
    fields are selected, so pass `format_fields=["GT"]` when the header
    declares additional fields. Multiallelic records are rejected.
    """
    _validate_bcf_genotype_output(genotype_output, format_fields)
    _validate_variant_input_path(path, "bcf")
    return IOOperations._scan_variant(
        path=path,
        info_fields=info_fields,
        format_fields=format_fields,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
        samples=samples,
        genotype_output=genotype_output,
        source_format="bcf",
    )

scan_bgen(path, genotype_output='probability', probability_layout='nested', samples=None, genotype_fields=None, sample_path=None, bgi_path=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a BGEN file into a LazyFrame.

BGI range pushdown, projection pushdown, and configured input partition parallelism are preserved. See read_bgen for the parameters.

Source code in polars_bio/io.py
@staticmethod
def scan_bgen(
    path: str,
    genotype_output: str = "probability",
    probability_layout: str = "nested",
    samples: Union[list[str], None] = None,
    genotype_fields: Union[list[str], None] = None,
    sample_path: Union[str, None] = None,
    bgi_path: Union[str, None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a BGEN file into a LazyFrame.

    BGI range pushdown, projection pushdown, and configured input partition
    parallelism are preserved. See `read_bgen` for the parameters.
    """
    _validate_bgen_genotype_output(genotype_output)
    _validate_bgen_probability_layout(probability_layout)
    _validate_bgen_genotype_fields(genotype_fields)
    _validate_bgen_input_path(path)
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    bgen_read_options = BgenReadOptions(
        object_storage_options=object_storage_options,
        genotype_output=genotype_output,
        probability_layout=probability_layout,
        samples=samples,
        genotype_fields=genotype_fields,
        sample_path=sample_path,
        bgi_path=bgi_path,
        zero_based=zero_based,
    )
    read_options = ReadOptions(bgen_read_options=bgen_read_options)
    return _read_file(
        path,
        InputFormat.Bgen,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_pgen(path, genotype_fields=('GT',), samples=None, missing_sample_policy='error', psam_id_mode='iid', pvar_path=None, psam_path=None, pgi_path=None, max_range_gap=None, max_range_bytes=None, batch_soft_byte_limit=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a PLINK 2 PGEN fileset into a LazyFrame.

Projection pushdown and configured input partition parallelism are preserved. See read_pgen for the parameters.

Source code in polars_bio/io.py
@staticmethod
def scan_pgen(
    path: str,
    genotype_fields: Sequence[str] = ("GT",),
    samples: Union[list[str], None] = None,
    missing_sample_policy: str = "error",
    psam_id_mode: str = "iid",
    pvar_path: Union[str, None] = None,
    psam_path: Union[str, None] = None,
    pgi_path: Union[str, None] = None,
    max_range_gap: Union[int, None] = None,
    max_range_bytes: Union[int, None] = None,
    batch_soft_byte_limit: Union[int, None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a PLINK 2 PGEN fileset into a LazyFrame.

    Projection pushdown and configured input partition parallelism are
    preserved. See `read_pgen` for the parameters.
    """
    _validate_pgen_input_path(path)
    _validate_pgen_genotype_fields(genotype_fields)
    _validate_pgen_psam_id_mode(psam_id_mode)
    _validate_pgen_missing_sample_policy(missing_sample_policy)
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    pgen_read_options = PgenReadOptions(
        object_storage_options=object_storage_options,
        genotype_fields=list(genotype_fields),
        zero_based=zero_based,
        samples=samples,
        missing_sample_policy=missing_sample_policy,
        psam_id_mode=psam_id_mode,
        pvar_path=pvar_path,
        psam_path=psam_path,
        pgi_path=pgi_path,
        max_range_gap=max_range_gap,
        max_range_bytes=max_range_bytes,
        batch_soft_byte_limit=batch_soft_byte_limit,
    )
    read_options = ReadOptions(pgen_read_options=pgen_read_options)
    return _read_file(
        path,
        InputFormat.Pgen,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_vcf(path, info_fields=None, format_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, samples=None) staticmethod

Lazily read a text VCF file into a LazyFrame.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a VCF TBI/CSI index is present. See File formats support, Indexed reads, and Automatic parallel partitioning for details.

Parameters:

Name Type Description Default
path str

The path to the VCF file.

required
info_fields Union[list[str], None]

List of INFO field names to include. If None, all INFO fields from the VCF header are included by default. Use this to limit fields for better performance.

None
format_fields Union[list[str], None]

List of FORMAT field names to include (per-sample genotype data). If None, all FORMAT fields are included by default. For single-sample VCFs, FORMAT fields are top-level columns (e.g., GT, DP). For multi-sample VCFs, FORMAT data is exposed as a nested genotypes column (struct<GT: list, DP: list, ...>) with sample names in meta["header"]["sample_names"].

None
samples Union[list[str], None]

Optional list of sample names to include from the VCF header. Matching is exact and case-sensitive. Missing sample names are skipped with a warning. The output follows the requested sample order.

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the VCF file. If not specified, it will be detected automatically..

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using VCF TBI/CSI index files for efficient region-based filtering. Index files are auto-discovered (for example, file.vcf.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Lazy scanning VCF with INFO and FORMAT fields

import polars_bio as pb

# Lazily scan VCF with both INFO and FORMAT fields
lf = pb.scan_vcf(
    "sample.vcf.gz",
    info_fields=["END"],              # INFO field
    format_fields=["GT", "DP", "GQ"]  # FORMAT fields
)

# Apply filters and collect only what's needed
df = lf.filter(pl.col("DP") > 20).select(
    ["chrom", "start", "ref", "alt", "GT", "DP", "GQ"]
).collect()

# Single-sample VCF: FORMAT fields are top-level columns (GT, DP, GQ)
# Multi-sample VCF: FORMAT data is nested in "genotypes"
Source code in polars_bio/io.py
@staticmethod
def scan_vcf(
    path: str,
    info_fields: Union[list[str], None] = None,
    format_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    samples: Union[list[str], None] = None,
) -> pl.LazyFrame:
    """
    Lazily read a text VCF file into a LazyFrame.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a VCF TBI/CSI
        index is present. See [File formats support](/polars-bio/features/#file-formats-support),
        [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

    Parameters:
        path: The path to the VCF file.
        info_fields: List of INFO field names to include. If *None*, all INFO fields from the VCF header are included by default. Use this to limit fields for better performance.
        format_fields: List of FORMAT field names to include (per-sample genotype data). If *None*, all FORMAT fields are included by default. For **single-sample** VCFs, FORMAT fields are top-level columns (e.g., `GT`, `DP`). For **multi-sample** VCFs, FORMAT data is exposed as a nested `genotypes` column (`struct<GT: list, DP: list, ...>`) with sample names in `meta["header"]["sample_names"]`.
        samples: Optional list of sample names to include from the VCF header. Matching is exact and case-sensitive. Missing sample names are skipped with a warning. The output follows the requested sample order.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the VCF file. If not specified, it will be detected automatically..
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using VCF TBI/CSI index files for efficient region-based filtering. Index files are auto-discovered (for example, `file.vcf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

    !!! Example "Lazy scanning VCF with INFO and FORMAT fields"
        ```python
        import polars_bio as pb

        # Lazily scan VCF with both INFO and FORMAT fields
        lf = pb.scan_vcf(
            "sample.vcf.gz",
            info_fields=["END"],              # INFO field
            format_fields=["GT", "DP", "GQ"]  # FORMAT fields
        )

        # Apply filters and collect only what's needed
        df = lf.filter(pl.col("DP") > 20).select(
            ["chrom", "start", "ref", "alt", "GT", "DP", "GQ"]
        ).collect()

        # Single-sample VCF: FORMAT fields are top-level columns (GT, DP, GQ)
        # Multi-sample VCF: FORMAT data is nested in "genotypes"
        ```
    """
    _validate_variant_input_path(path, "vcf")
    return IOOperations._scan_variant(
        path=path,
        info_fields=info_fields,
        format_fields=format_fields,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
        projection_pushdown=projection_pushdown,
        predicate_pushdown=predicate_pushdown,
        use_zero_based=use_zero_based,
        samples=samples,
        genotype_output="string",
        source_format="vcf",
    )

scan_vcf_zarr(path, info_fields=None, format_fields=None, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, samples=None, genotype_encoding_raw=True) staticmethod

Lazily read a local VCF Zarr store into a LazyFrame.

Parameters:

Name Type Description Default
path str

The path to the VCF Zarr store directory.

required
info_fields Union[list[str], None]

Optional list of INFO field names to include. If None, local INFO arrays are discovered automatically. Use [] to disable INFO fields.

None
format_fields Union[list[str], None]

Optional list of FORMAT field names to include. If None, local FORMAT arrays are discovered automatically. Use [] to disable FORMAT fields.

None
projection_pushdown bool

Enable column projection pushdown at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown at the DataFusion level.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None, uses the global configuration.

None
samples Union[list[str], None]

Optional list of sample names to include.

None
genotype_encoding_raw bool

If True, output GT as raw typed allele calls. If False, output VCF-style GT strings.

True
Source code in polars_bio/io.py
@staticmethod
def scan_vcf_zarr(
    path: str,
    info_fields: Union[list[str], None] = None,
    format_fields: Union[list[str], None] = None,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    samples: Union[list[str], None] = None,
    genotype_encoding_raw: bool = True,
) -> pl.LazyFrame:
    """
    Lazily read a local VCF Zarr store into a LazyFrame.

    Parameters:
        path: The path to the VCF Zarr store directory.
        info_fields: Optional list of INFO field names to include. If None, local INFO arrays are discovered automatically. Use [] to disable INFO fields.
        format_fields: Optional list of FORMAT field names to include. If None, local FORMAT arrays are discovered automatically. Use [] to disable FORMAT fields.
        projection_pushdown: Enable column projection pushdown at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown at the DataFusion level.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None, uses the global configuration.
        samples: Optional list of sample names to include.
        genotype_encoding_raw: If True, output GT as raw typed allele calls. If False, output VCF-style GT strings.
    """
    zero_based = _resolve_zero_based(use_zero_based)
    vcf_zarr_read_options = VcfZarrReadOptions(
        info_fields=info_fields,
        format_fields=format_fields,
        samples=samples,
        zero_based=zero_based,
        genotype_encoding_raw=genotype_encoding_raw,
    )
    read_options = ReadOptions(vcf_zarr_read_options=vcf_zarr_read_options)
    return _read_file(
        path,
        InputFormat.VcfZarr,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_bam(path, tag_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, infer_tag_types=True, infer_tag_sample_size=100, tag_type_hints=None) staticmethod

Lazily read a BAM file into a LazyFrame.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a BAI/CSI index is present. See File formats support, Indexed reads, and Automatic parallel partitioning for details.

Parameters:

Name Type Description Default
path str

The path to the BAM file.

required
tag_fields Union[list[str], None]

List of BAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using index files (BAI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.bam.bai). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None
infer_tag_types bool

If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.

True
infer_tag_sample_size int

Number of records to sample for tag type inference (default: 100).

100
tag_type_hints Optional[list[str]]

Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def scan_bam(
    path: str,
    tag_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    infer_tag_types: bool = True,
    infer_tag_sample_size: int = 100,
    tag_type_hints: Optional[list[str]] = None,
) -> pl.LazyFrame:
    """
    Lazily read a BAM file into a LazyFrame.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a BAI/CSI index
        is present. See [File formats support](/polars-bio/features/#file-formats-support),
        [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

    Parameters:
        path: The path to the BAM file.
        tag_fields: List of BAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using index files (BAI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.bam.bai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
        infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
        infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
        tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type="auto",
    )

    zero_based = _resolve_zero_based(use_zero_based)
    if tag_type_hints is not None:
        _validate_tag_type_hints(tag_type_hints)
        tag_type_hints = _normalize_read_tag_type_hints(tag_type_hints)
    bam_read_options = BamReadOptions(
        object_storage_options=object_storage_options,
        zero_based=zero_based,
        tag_fields=tag_fields,
        infer_tag_types=infer_tag_types,
        infer_tag_sample_size=infer_tag_sample_size,
        tag_type_hints=tag_type_hints,
    )
    read_options = ReadOptions(bam_read_options=bam_read_options)
    return _read_file(
        path,
        InputFormat.Bam,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_cram(path, reference_path=None, tag_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, infer_tag_types=True, infer_tag_sample_size=100, tag_type_hints=None) staticmethod

Lazily read a CRAM file into a LazyFrame.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a CRAI index is present. See File formats support, Indexed reads, and Automatic parallel partitioning for details.

Parameters:

Name Type Description Default
path str

The path to the CRAM file (local or cloud storage: S3, GCS, Azure Blob).

required
reference_path str

Optional path to external FASTA reference file (local path only, cloud storage not supported). If not provided, the CRAM file must contain embedded reference sequences. The FASTA file must have an accompanying index file (.fai) in the same directory. Create the index using: samtools faidx reference.fasta

None
tag_fields Union[list[str], None]

List of CRAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True
predicate_pushdown bool

Enable predicate pushdown using index files (CRAI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.cram.crai). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None
infer_tag_types bool

If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.

True
infer_tag_sample_size int

Number of records to sample for tag type inference (default: 100).

100
tag_type_hints Optional[list[str]]

Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Known Limitation: MD and NM Tags

Due to a limitation in the underlying noodles-cram library, MD (mismatch descriptor) and NM (edit distance) tags are not accessible from CRAM files, even when stored in the file. These tags can be seen with samtools but are not exposed through the noodles-cram record.data() interface.

Other optional tags (RG, MQ, AM, OQ, etc.) work correctly. This issue is tracked at: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

Workaround: Use BAM format if MD/NM tags are required for your analysis.

Using External Reference

import polars_bio as pb

# Lazy scan CRAM with external reference
lf = pb.scan_cram(
    "/path/to/file.cram",
    reference_path="/path/to/reference.fasta"
)

# Apply transformations and collect
df = lf.filter(pl.col("chrom") == "chr1").collect()

Public CRAM File Example

Download and read a public CRAM file from 42basepairs:

# Download the CRAM file and reference
wget https://42basepairs.com/download/s3/gatk-test-data/wgs_cram/NA12878_20k_hg38/NA12878.cram
wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta

# Create FASTA index (required)
samtools faidx Homo_sapiens_assembly38.fasta

import polars_bio as pb
import polars as pl

# Lazy scan and filter for chromosome 20 reads
df = pb.scan_cram(
    "NA12878.cram",
    reference_path="Homo_sapiens_assembly38.fasta"
).filter(
    pl.col("chrom") == "chr20"
).select(
    ["name", "chrom", "start", "end", "mapping_quality"]
).limit(10).collect()

print(df)

Creating CRAM with Embedded Reference

To create a CRAM file with embedded reference using samtools:

samtools view -C -o output.cram --output-fmt-option embed_ref=1 input.bam

Returns:

Type Description
LazyFrame

A Polars LazyFrame with the following schema: - name: Read name (String) - chrom: Chromosome/contig name (String) - start: Alignment start position, 1-based (UInt32) - end: Alignment end position, 1-based (UInt32) - flags: SAM flags (UInt32) - cigar: CIGAR string (String) - mapping_quality: Mapping quality (UInt32) - mate_chrom: Mate chromosome/contig name (String) - mate_start: Mate alignment start position, 1-based (UInt32) - sequence: Read sequence (String) - quality_scores: Base quality scores (String)

Source code in polars_bio/io.py
@staticmethod
def scan_cram(
    path: str,
    reference_path: str = None,
    tag_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    infer_tag_types: bool = True,
    infer_tag_sample_size: int = 100,
    tag_type_hints: Optional[list[str]] = None,
) -> pl.LazyFrame:
    """
    Lazily read a CRAM file into a LazyFrame.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a CRAI index
        is present. See [File formats support](/polars-bio/features/#file-formats-support),
        [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details.

    Parameters:
        path: The path to the CRAM file (local or cloud storage: S3, GCS, Azure Blob).
        reference_path: Optional path to external FASTA reference file (**local path only**, cloud storage not supported). If not provided, the CRAM file must contain embedded reference sequences. The FASTA file must have an accompanying index file (.fai) in the same directory. Create the index using: `samtools faidx reference.fasta`
        tag_fields: List of CRAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default). Common tags include: NM (edit distance), MD (mismatch string), AS (alignment score), XS (secondary alignment score), RG (read group), CB (cell barcode), UB (UMI barcode).
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
        predicate_pushdown: Enable predicate pushdown using index files (CRAI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.cram.crai`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.
        infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags. This prevents integer tags from being decoded as ASCII characters.
        infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
        tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Used as fallback when inference is disabled or a tag is not found in sampled records. Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.

    !!! warning "Known Limitation: MD and NM Tags"
        Due to a limitation in the underlying noodles-cram library, **MD (mismatch descriptor) and NM (edit distance) tags are not accessible** from CRAM files, even when stored in the file. These tags can be seen with samtools but are not exposed through the noodles-cram record.data() interface.

        Other optional tags (RG, MQ, AM, OQ, etc.) work correctly. This issue is tracked at: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

        **Workaround**: Use BAM format if MD/NM tags are required for your analysis.

    !!! example "Using External Reference"
        ```python
        import polars_bio as pb

        # Lazy scan CRAM with external reference
        lf = pb.scan_cram(
            "/path/to/file.cram",
            reference_path="/path/to/reference.fasta"
        )

        # Apply transformations and collect
        df = lf.filter(pl.col("chrom") == "chr1").collect()
        ```

    !!! example "Public CRAM File Example"
        Download and read a public CRAM file from 42basepairs:
        ```bash
        # Download the CRAM file and reference
        wget https://42basepairs.com/download/s3/gatk-test-data/wgs_cram/NA12878_20k_hg38/NA12878.cram
        wget https://storage.googleapis.com/genomics-public-data/resources/broad/hg38/v0/Homo_sapiens_assembly38.fasta

        # Create FASTA index (required)
        samtools faidx Homo_sapiens_assembly38.fasta
        ```

        ```python
        import polars_bio as pb
        import polars as pl

        # Lazy scan and filter for chromosome 20 reads
        df = pb.scan_cram(
            "NA12878.cram",
            reference_path="Homo_sapiens_assembly38.fasta"
        ).filter(
            pl.col("chrom") == "chr20"
        ).select(
            ["name", "chrom", "start", "end", "mapping_quality"]
        ).limit(10).collect()

        print(df)
        ```

    !!! example "Creating CRAM with Embedded Reference"
        To create a CRAM file with embedded reference using samtools:
        ```bash
        samtools view -C -o output.cram --output-fmt-option embed_ref=1 input.bam
        ```

    Returns:
        A Polars LazyFrame with the following schema:
            - name: Read name (String)
            - chrom: Chromosome/contig name (String)
            - start: Alignment start position, 1-based (UInt32)
            - end: Alignment end position, 1-based (UInt32)
            - flags: SAM flags (UInt32)
            - cigar: CIGAR string (String)
            - mapping_quality: Mapping quality (UInt32)
            - mate_chrom: Mate chromosome/contig name (String)
            - mate_start: Mate alignment start position, 1-based (UInt32)
            - sequence: Read sequence (String)
            - quality_scores: Base quality scores (String)
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type="auto",
    )

    zero_based = _resolve_zero_based(use_zero_based)
    if tag_type_hints is not None:
        _validate_tag_type_hints(tag_type_hints)
        tag_type_hints = _normalize_read_tag_type_hints(tag_type_hints)
    cram_read_options = CramReadOptions(
        reference_path=reference_path,
        object_storage_options=object_storage_options,
        zero_based=zero_based,
        tag_fields=tag_fields,
        infer_tag_types=infer_tag_types,
        infer_tag_sample_size=infer_tag_sample_size,
        tag_type_hints=tag_type_hints,
    )
    read_options = ReadOptions(cram_read_options=cram_read_options)
    return _read_file(
        path,
        InputFormat.Cram,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_sam(path, tag_fields=None, projection_pushdown=True, use_zero_based=None, infer_tag_types=True, infer_tag_sample_size=100, tag_type_hints=None) staticmethod

Lazily read a SAM file into a LazyFrame.

SAM (Sequence Alignment/Map) is the plain-text counterpart of BAM. This function reuses the BAM reader, which auto-detects the format from the file extension.

Parameters:

Name Type Description Default
path str

The path to the SAM file.

required
tag_fields Union[list[str], None]

List of SAM tag names to include as columns (e.g., ["NM", "MD", "AS"]). If None, no optional tags are parsed (default).

None
projection_pushdown bool

Enable column projection pushdown to optimize query performance.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration.

None
infer_tag_types bool

If True (default), sample the file to auto-detect types for custom/unknown tags.

True
infer_tag_sample_size int

Number of records to sample for tag type inference (default: 100).

100
tag_type_hints Optional[list[str]]

Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

None

Note

By default, coordinates are output in 1-based closed format.

Source code in polars_bio/io.py
@staticmethod
def scan_sam(
    path: str,
    tag_fields: Union[list[str], None] = None,
    projection_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    infer_tag_types: bool = True,
    infer_tag_sample_size: int = 100,
    tag_type_hints: Optional[list[str]] = None,
) -> pl.LazyFrame:
    """
    Lazily read a SAM file into a LazyFrame.

    SAM (Sequence Alignment/Map) is the plain-text counterpart of BAM.
    This function reuses the BAM reader, which auto-detects the format
    from the file extension.

    Parameters:
        path: The path to the SAM file.
        tag_fields: List of SAM tag names to include as columns (e.g., ["NM", "MD", "AS"]).
            If None, no optional tags are parsed (default).
        projection_pushdown: Enable column projection pushdown to optimize query performance.
        use_zero_based: If True, output 0-based half-open coordinates.
            If False, output 1-based closed coordinates.
            If None (default), uses the global configuration.
        infer_tag_types: If True (default), sample the file to auto-detect types for custom/unknown tags.
        infer_tag_sample_size: Number of records to sample for tag type inference (default: 100).
        tag_type_hints: Explicit SAM-style type hints for tags (e.g., ["pt:i", "ML:B:C", "FZ:B:S"]). Supported forms: TAG:TYPE, TAG:B, or TAG:B:SUBTYPE where TYPE is one of A, c, C, s, S, i, I, f, Z, H and SUBTYPE is one of c, C, s, S, i, I, f.

    !!! note
        By default, coordinates are output in **1-based closed** format.
    """
    zero_based = _resolve_zero_based(use_zero_based)
    if tag_type_hints is not None:
        _validate_tag_type_hints(tag_type_hints)
        tag_type_hints = _normalize_read_tag_type_hints(tag_type_hints)
    bam_read_options = BamReadOptions(
        zero_based=zero_based,
        tag_fields=tag_fields,
        infer_tag_types=infer_tag_types,
        infer_tag_sample_size=infer_tag_sample_size,
        tag_type_hints=tag_type_hints,
    )
    read_options = ReadOptions(bam_read_options=bam_read_options)
    return _read_file(
        path,
        InputFormat.Sam,
        read_options,
        projection_pushdown,
        zero_based=zero_based,
    )

scan_fastq(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True) staticmethod

Lazily read a FASTQ file into a LazyFrame.

Parallelism & Compression

See File formats support, Compression, and Automatic parallel partitioning for details on parallel reads and supported compression types.

Parameters:

Name Type Description Default
path str

The path to the FASTQ file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the FASTQ file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
Source code in polars_bio/io.py
@staticmethod
def scan_fastq(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
) -> pl.LazyFrame:
    """
    Lazily read a FASTQ file into a LazyFrame.

    !!! hint "Parallelism & Compression"
        See [File formats support](/polars-bio/features/#file-formats-support),
        [Compression](/polars-bio/features/#compression),
        and [Automatic parallel partitioning](/polars-bio/features/#automatic-parallel-partitioning) for details on parallel reads and supported compression types.

    Parameters:
        path: The path to the FASTQ file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the FASTQ file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    fastq_read_options = FastqReadOptions(
        object_storage_options=object_storage_options,
    )
    read_options = ReadOptions(fastq_read_options=fastq_read_options)
    return _read_file(path, InputFormat.Fastq, read_options, projection_pushdown)

scan_fasta(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True) staticmethod

Lazily read a FASTA file into a LazyFrame.

Parameters:

Name Type Description Default
path str

The path to the FASTA file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the FASTA file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True

Example

wget https://www.ebi.ac.uk/ena/browser/api/fasta/BK006935.2?download=true -O /tmp/test.fasta

import polars_bio as pb
pb.scan_fasta("/tmp/test.fasta").limit(1).collect()
 shape: (1, 3)
┌─────────────────────────┬─────────────────────────────────┬─────────────────────────────────┐
 name                     description                      sequence                         ---                      ---                              ---                              str                      str                              str                             ╞═════════════════════════╪═════════════════════════════════╪═════════════════════════════════╡
 ENA|BK006935|BK006935.2  TPA_inf: Saccharomyces cerevis…  CCACACCACACCCACACACCCACACACCAC… └─────────────────────────┴─────────────────────────────────┴─────────────────────────────────┘

Source code in polars_bio/io.py
@staticmethod
def scan_fasta(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
) -> pl.LazyFrame:
    """

    Lazily read a FASTA file into a LazyFrame.

    Parameters:
        path: The path to the FASTA file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the FASTA file. If not specified, it will be detected automatically based on the file extension. BGZF and GZIP compressions are supported ('bgz', 'gz').
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

    !!! Example
        ```shell
        wget https://www.ebi.ac.uk/ena/browser/api/fasta/BK006935.2?download=true -O /tmp/test.fasta
        ```

        ```python
        import polars_bio as pb
        pb.scan_fasta("/tmp/test.fasta").limit(1).collect()
        ```
        ```shell
         shape: (1, 3)
        ┌─────────────────────────┬─────────────────────────────────┬─────────────────────────────────┐
        │ name                    ┆ description                     ┆ sequence                        │
        │ ---                     ┆ ---                             ┆ ---                             │
        │ str                     ┆ str                             ┆ str                             │
        ╞═════════════════════════╪═════════════════════════════════╪═════════════════════════════════╡
        │ ENA|BK006935|BK006935.2 ┆ TPA_inf: Saccharomyces cerevis… ┆ CCACACCACACCCACACACCCACACACCAC… │
        └─────────────────────────┴─────────────────────────────────┴─────────────────────────────────┘
        ```
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )
    fasta_read_options = FastaReadOptions(
        object_storage_options=object_storage_options
    )
    read_options = ReadOptions(fasta_read_options=fasta_read_options)
    return _read_file(path, InputFormat.Fasta, read_options, projection_pushdown)

scan_gff(path, attr_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a GFF file into a LazyFrame.

Parameters:

Name Type Description Default
path str

The path to the GFF file.

required
attr_fields Union[list[str], None]

List of attribute field names to extract as separate columns. If None, attributes will be kept as a nested structure. Use this to extract specific attributes like 'ID', 'gene_name', 'gene_type', etc. as direct columns for easier access.

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the GFF file. If not specified, it will be detected automatically.

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.gff.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def scan_gff(
    path: str,
    attr_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a GFF file into a LazyFrame.

    Parameters:
        path: The path to the GFF file.
        attr_fields: List of attribute field names to extract as separate columns. If *None*, attributes will be kept as a nested structure. Use this to extract specific attributes like 'ID', 'gene_name', 'gene_type', etc. as direct columns for easier access.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the GFF file. If not specified, it will be detected automatically.
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gff.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    gff_read_options = GffReadOptions(
        attr_fields=attr_fields,
        object_storage_options=object_storage_options,
        zero_based=zero_based,
    )
    read_options = ReadOptions(gff_read_options=gff_read_options)
    _store_py_object_storage_options(read_options, object_storage_options)
    return _read_file(
        path,
        InputFormat.Gff,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_gtf(path, attr_fields=None, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a GTF file into a LazyFrame.

GTF (Gene Transfer Format) shares the same 9-column structure as GFF but uses different attribute syntax (key "value" vs GFF's key=value).

Parameters:

Name Type Description Default
path str

The path to the GTF file.

required
attr_fields Union[list[str], None]

List of attribute field names to extract as separate columns. If None, attributes will be kept as a nested structure.

None
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the GTF file. If not specified, it will be detected automatically.

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
predicate_pushdown bool

Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.gtf.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like .str.contains() or OR logic are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def scan_gtf(
    path: str,
    attr_fields: Union[list[str], None] = None,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a GTF file into a LazyFrame.

    GTF (Gene Transfer Format) shares the same 9-column structure as GFF but uses
    different attribute syntax (``key "value"`` vs GFF's ``key=value``).

    Parameters:
        path: The path to the GTF file.
        attr_fields: List of attribute field names to extract as separate columns.
            If *None*, attributes will be kept as a nested structure.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large-scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the GTF file. If not specified, it will be detected automatically.
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        predicate_pushdown: Enable predicate pushdown using index files (TBI/CSI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.gtf.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates like `.str.contains()` or OR logic are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    gtf_read_options = GtfReadOptions(
        attr_fields=attr_fields,
        object_storage_options=object_storage_options,
        zero_based=zero_based,
    )
    read_options = ReadOptions(gtf_read_options=gtf_read_options)
    _store_py_object_storage_options(read_options, object_storage_options)
    return _read_file(
        path,
        InputFormat.Gtf,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_bed(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, use_zero_based=None) staticmethod

Lazily read a BED file into a LazyFrame.

Parameters:

Name Type Description Default
path str

The path to the BED file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the BED file. If not specified, it will be detected automatically based on the file extension. BGZF compressions is supported ('bgz').

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

Only BED4 format is supported. It extends the basic BED format (BED3) by adding a name field, resulting in four columns: chromosome, start position, end position, and name. Also unlike other text formats, GZIP compression is not supported.

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def scan_bed(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a BED file into a LazyFrame.

    Parameters:
        path: The path to the BED file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries:  The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the BED file. If not specified, it will be detected automatically based on the file extension. BGZF compressions is supported ('bgz').
        projection_pushdown: Enable column projection pushdown to optimize query performance by only reading the necessary columns at the DataFusion level.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! Note
        Only **BED4** format is supported. It extends the basic BED format (BED3) by adding a name field, resulting in four columns: chromosome, start position, end position, and name.
        Also unlike other text formats, **GZIP** compression is not supported.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    bed_read_options = BedReadOptions(
        object_storage_options=object_storage_options,
        zero_based=zero_based,
    )
    read_options = ReadOptions(bed_read_options=bed_read_options)
    return _read_file(
        path,
        InputFormat.Bed,
        read_options,
        projection_pushdown,
        zero_based=zero_based,
    )

scan_pairs(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a Pairs (Hi-C) file into a LazyFrame.

The Pairs format (4DN project) stores chromatin contact data with columns: readID, chr1, pos1, chr2, pos2, strand1, strand2.

Parallelism & Indexed Reads

Indexed parallel reads and predicate pushdown are automatic when a TBI index is present. See File formats support and Indexed reads for details.

Parameters:

Name Type Description Default
path str

The path to the Pairs file (.pairs, .pairs.gz, .pairs.bgz).

required
chunk_size int

The size in MB of a chunk when reading from an object store.

8
concurrent_fetches int

The number of concurrent fetches when reading from an object store.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type. If not specified, it will be detected automatically.

'auto'
projection_pushdown bool

Enable column projection pushdown to optimize query performance.

True
predicate_pushdown bool

Enable predicate pushdown using index files (TBI) for efficient region-based filtering. Index files are auto-discovered (e.g., file.pairs.gz.tbi). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates are filtered client-side. Correctness is always guaranteed.

True
use_zero_based Optional[bool]

If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration datafusion.bio.coordinate_system_zero_based.

None

Note

By default, coordinates are output in 1-based closed format. Use use_zero_based=True or set pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True) for 0-based half-open coordinates.

Source code in polars_bio/io.py
@staticmethod
def scan_pairs(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a Pairs (Hi-C) file into a LazyFrame.

    The Pairs format (4DN project) stores chromatin contact data with columns:
    readID, chr1, pos1, chr2, pos2, strand1, strand2.

    !!! hint "Parallelism & Indexed Reads"
        Indexed parallel reads and predicate pushdown are automatic when a TBI index
        is present. See [File formats support](/polars-bio/features/#file-formats-support)
        and [Indexed reads](/polars-bio/features/#indexed-reads-predicate-pushdown) for details.

    Parameters:
        path: The path to the Pairs file (.pairs, .pairs.gz, .pairs.bgz).
        chunk_size: The size in MB of a chunk when reading from an object store.
        concurrent_fetches: The number of concurrent fetches when reading from an object store.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type. If not specified, it will be detected automatically.
        projection_pushdown: Enable column projection pushdown to optimize query performance.
        predicate_pushdown: Enable predicate pushdown using index files (TBI) for efficient region-based filtering. Index files are auto-discovered (e.g., `file.pairs.gz.tbi`). Only simple predicates are pushed down (equality, comparisons, IN); complex predicates are filtered client-side. Correctness is always guaranteed.
        use_zero_based: If True, output 0-based half-open coordinates. If False, output 1-based closed coordinates. If None (default), uses the global configuration `datafusion.bio.coordinate_system_zero_based`.

    !!! note
        By default, coordinates are output in **1-based closed** format. Use `use_zero_based=True` or set `pb.set_option(pb.POLARS_BIO_COORDINATE_SYSTEM_ZERO_BASED, True)` for 0-based half-open coordinates.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    pairs_read_options = PairsReadOptions(
        object_storage_options=object_storage_options,
        zero_based=zero_based,
    )
    read_options = ReadOptions(pairs_read_options=pairs_read_options)
    return _read_file(
        path,
        InputFormat.Pairs,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_bigwig(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a BigWig file into a LazyFrame.

BigWig is natively 0-based half-open. Set use_zero_based=False to emit 1-based closed coordinates.

Parameters:

Name Type Description Default
path str

The path to the BigWig file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the BigWig file. If not specified, it will be detected automatically based on the file extension.

'auto'
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True
predicate_pushdown bool

Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.

True
use_zero_based Optional[bool]

Coordinate system override. BigWig is natively 0-based half-open; set to False to emit 1-based closed coordinates, or None to use the global default.

None
Source code in polars_bio/io.py
@staticmethod
def scan_bigwig(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a BigWig file into a LazyFrame.

    BigWig is natively 0-based half-open. Set ``use_zero_based=False`` to emit
    1-based closed coordinates.

    Parameters:
        path: The path to the BigWig file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the BigWig file. If not specified, it will be detected automatically based on the file extension.
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
        predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
        use_zero_based: Coordinate system override. BigWig is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    bigwig_read_options = BigWigReadOptions(
        object_storage_options=object_storage_options,
        zero_based=zero_based,
    )
    read_options = ReadOptions(bigwig_read_options=bigwig_read_options)
    return _read_file(
        path,
        InputFormat.BigWig,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_bigbed(path, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', projection_pushdown=True, predicate_pushdown=True, use_zero_based=None, schema='auto') staticmethod

Lazily read a BigBed file into a LazyFrame.

BigBed is natively 0-based half-open. Set use_zero_based=False to emit 1-based closed coordinates.

Parameters:

Name Type Description Default
path str

The path to the BigBed file.

required
chunk_size int

The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.

8
concurrent_fetches int

[GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.

1
allow_anonymous bool

[GCS, AWS S3] Whether to allow anonymous access to object storage.

True
enable_request_payer bool

[AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
max_retries int

The maximum number of retries for reading the file from object storage.

5
timeout int

The timeout in seconds for reading the file from object storage.

300
compression_type str

The compression type of the BigBed file. If not specified, it will be detected automatically based on the file extension.

'auto'
projection_pushdown bool

Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.

True
predicate_pushdown bool

Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.

True
use_zero_based Optional[bool]

Coordinate system override. BigBed is natively 0-based half-open; set to False to emit 1-based closed coordinates, or None to use the global default.

None
schema str

Schema mode. "auto" exposes the supported autoSQL fields when available; "rest" exposes the raw trailing fields in a single rest column.

'auto'
Source code in polars_bio/io.py
@staticmethod
def scan_bigbed(
    path: str,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
    schema: str = "auto",
) -> pl.LazyFrame:
    """
    Lazily read a BigBed file into a LazyFrame.

    BigBed is natively 0-based half-open. Set ``use_zero_based=False`` to emit
    1-based closed coordinates.

    Parameters:
        path: The path to the BigBed file.
        chunk_size: The size in MB of a chunk when reading from an object store. The default is 8 MB. For large scale operations, it is recommended to increase this value to 64.
        concurrent_fetches: [GCS] The number of concurrent fetches when reading from an object store. The default is 1. For large scale operations, it is recommended to increase this value to 8 or even more.
        allow_anonymous: [GCS, AWS S3] Whether to allow anonymous access to object storage.
        enable_request_payer: [AWS S3] Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        max_retries: The maximum number of retries for reading the file from object storage.
        timeout: The timeout in seconds for reading the file from object storage.
        compression_type: The compression type of the BigBed file. If not specified, it will be detected automatically based on the file extension.
        projection_pushdown: Enable column projection pushdown optimization. When True, only requested columns are processed at the DataFusion execution level, improving performance and reducing memory usage.
        predicate_pushdown: Enable predicate pushdown on the genomic coordinate columns so range filters are evaluated at the DataFusion execution level.
        use_zero_based: Coordinate system override. BigBed is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.
        schema: Schema mode. ``"auto"`` exposes the supported autoSQL fields when available; ``"rest"`` exposes the raw trailing fields in a single ``rest`` column.
    """
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    zero_based = _resolve_zero_based(use_zero_based)
    bigbed_read_options = BigBedReadOptions(
        object_storage_options=object_storage_options,
        zero_based=zero_based,
        schema=_normalize_bigbed_schema_mode(schema),
    )
    read_options = ReadOptions(bigbed_read_options=bigbed_read_options)
    return _read_file(
        path,
        InputFormat.BigBed,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_cool(path, resolution=None, join_bins=True, include_weights=False, projection_pushdown=True, predicate_pushdown=True, use_zero_based=None) staticmethod

Lazily read a Cooler (.cool/.mcool) Hi-C contact matrix into a LazyFrame.

One row per stored pixel (upper-triangle contact), joined with bin coordinates by default. .mcool files store one data collection per resolution: select one with resolution or the cooler URI syntax file.mcool::/resolutions/10000; an .mcool with several resolutions and no selection raises an error listing the available ones. Only local filesystem paths are supported.

Cooler is natively 0-based half-open. Set use_zero_based=False to emit 1-based closed coordinates.

Parameters:

Name Type Description Default
path str

The path to the .cool/.mcool file, or a cooler URI (file.mcool::/resolutions/10000).

required
resolution Optional[int]

Bin size selecting an .mcool data collection. Optional for .cool files and single-resolution .mcool files.

None
join_bins bool

If True (default), join pixels with bin coordinates (chrom1, start1, end1, chrom2, start2, end2, count); if False, return the raw COO triple (bin1_id, bin2_id, count).

True
include_weights bool

If True, expose balancing weights as weight1/weight2 (requires a balanced cooler).

False
projection_pushdown bool

Enable column projection pushdown optimization. Only HDF5 datasets required by the requested columns are read, and count(*) is served from the cooler index without touching pixel data.

True
predicate_pushdown bool

Enable predicate pushdown on the first-axis genomic columns (chrom1, start1, end1) so range filters prune pixel row ranges through the cooler indexes.

True
use_zero_based Optional[bool]

Coordinate system override. Cooler is natively 0-based half-open; set to False to emit 1-based closed coordinates, or None to use the global default.

None

Example

import polars as pl
import polars_bio as pb

pb.scan_cool("contacts.mcool", resolution=10000).filter(
    pl.col("chrom1") == "chr1"
).collect()
Source code in polars_bio/io.py
@staticmethod
def scan_cool(
    path: str,
    resolution: Optional[int] = None,
    join_bins: bool = True,
    include_weights: bool = False,
    projection_pushdown: bool = True,
    predicate_pushdown: bool = True,
    use_zero_based: Optional[bool] = None,
) -> pl.LazyFrame:
    """
    Lazily read a Cooler (`.cool`/`.mcool`) Hi-C contact matrix into a LazyFrame.

    One row per stored pixel (upper-triangle contact), joined with bin
    coordinates by default. `.mcool` files store one data collection per
    resolution: select one with ``resolution`` or the cooler URI syntax
    ``file.mcool::/resolutions/10000``; an `.mcool` with several
    resolutions and no selection raises an error listing the available
    ones. Only local filesystem paths are supported.

    Cooler is natively 0-based half-open. Set ``use_zero_based=False`` to
    emit 1-based closed coordinates.

    Parameters:
        path: The path to the `.cool`/`.mcool` file, or a cooler URI (`file.mcool::/resolutions/10000`).
        resolution: Bin size selecting an `.mcool` data collection. Optional for `.cool` files and single-resolution `.mcool` files.
        join_bins: If *True* (default), join pixels with bin coordinates (`chrom1`, `start1`, `end1`, `chrom2`, `start2`, `end2`, `count`); if *False*, return the raw COO triple (`bin1_id`, `bin2_id`, `count`).
        include_weights: If *True*, expose balancing weights as `weight1`/`weight2` (requires a balanced cooler).
        projection_pushdown: Enable column projection pushdown optimization. Only HDF5 datasets required by the requested columns are read, and `count(*)` is served from the cooler index without touching pixel data.
        predicate_pushdown: Enable predicate pushdown on the first-axis genomic columns (`chrom1`, `start1`, `end1`) so range filters prune pixel row ranges through the cooler indexes.
        use_zero_based: Coordinate system override. Cooler is natively 0-based half-open; set to *False* to emit 1-based closed coordinates, or *None* to use the global default.

    !!! Example
        ```python
        import polars as pl
        import polars_bio as pb

        pb.scan_cool("contacts.mcool", resolution=10000).filter(
            pl.col("chrom1") == "chr1"
        ).collect()
        ```
    """
    zero_based = _resolve_zero_based(use_zero_based)
    cool_read_options = CoolReadOptions(
        resolution=resolution,
        join_bins=join_bins,
        include_weights=include_weights,
        zero_based=zero_based,
    )
    read_options = ReadOptions(cool_read_options=cool_read_options)
    return _read_file(
        path,
        InputFormat.Cool,
        read_options,
        projection_pushdown,
        predicate_pushdown,
        zero_based=zero_based,
    )

scan_table(path, schema=None, **kwargs) staticmethod

Lazily read a tab-delimited (i.e. BED) file into a Polars LazyFrame. Tries to be compatible with Bioframe's read_table but faster and lazy. Schema should follow the Bioframe's schema format.

Parameters:

Name Type Description Default
path str

The path to the file.

required
schema Dict

Schema should follow the Bioframe's schema format.

None
Source code in polars_bio/io.py
@staticmethod
def scan_table(path: str, schema: Dict = None, **kwargs) -> pl.LazyFrame:
    """
     Lazily read a tab-delimited (i.e. BED) file into a Polars LazyFrame.
     Tries to be compatible with Bioframe's [read_table](https://bioframe.readthedocs.io/en/latest/guide-io.html)
     but faster and lazy. Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).

    Parameters:
        path: The path to the file.
        schema: Schema should follow the Bioframe's schema [format](https://github.com/open2c/bioframe/blob/2b685eebef393c2c9e6220dcf550b3630d87518e/bioframe/io/schemas.py#L174).
    """
    df = pl.scan_csv(path, separator="\t", has_header=False, **kwargs)
    if schema is not None:
        columns = SCHEMAS[schema]
        if len(columns) != len(df.collect_schema()):
            raise ValueError(
                f"Schema incompatible with the input. Expected {len(columns)} columns in a schema, got {len(df.collect_schema())} in the input data file. Please provide a valid schema."
            )
        for i, c in enumerate(columns):
            df = df.rename({f"column_{i + 1}": c})
    return df

describe_bcf(path, allow_anonymous=True, enable_request_payer=False, compression_type='auto') staticmethod

Describe a BCF INFO and FORMAT schema.

Parameters:

Name Type Description Default
path str

The path to the BCF file. The path must end in .bcf.

required
allow_anonymous bool

Whether to allow anonymous access to object storage (GCS and S3 supported).

True
enable_request_payer bool

Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
compression_type str

The compression override. The default detects BCF automatically.

'auto'
Source code in polars_bio/io.py
@staticmethod
def describe_bcf(
    path: str,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    compression_type: str = "auto",
) -> pl.DataFrame:
    """Describe a BCF INFO and FORMAT schema.

    Parameters:
        path: The path to the BCF file. The path must end in `.bcf`.
        allow_anonymous: Whether to allow anonymous access to object storage (GCS and S3 supported).
        enable_request_payer: Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        compression_type: The compression override. The default detects BCF automatically.
    """
    _validate_variant_input_path(path, "bcf", operation="describe")
    return IOOperations._describe_variant(
        path,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        compression_type=compression_type,
    )

describe_bgen(path, allow_anonymous=True, enable_request_payer=False, compression_type='auto', sample_path=None, bgi_path=None) staticmethod

Describe the schema a BGEN file produces.

BGEN has no INFO/FORMAT header, so instead of a field dictionary this returns one row per emitted column, plus the file-level properties the provider records in the Arrow schema metadata: the BGEN layout, whether a .bgi index was used, whether sample identifiers were generated, and the coordinate system.

Parameters:

Name Type Description Default
path str

The path to the BGEN file. The path must end in .bgen.

required
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
compression_type str

The compression override.

'auto'
sample_path Union[str, None]

An explicit Oxford .sample companion, used only when the BGEN has no embedded sample identifiers.

None
bgi_path Union[str, None]

An explicit .bgi index. Pass it for an index stored away from the file, so the reported index property reflects the index a read would actually use.

None

Note

The reported schema is the one the default probability_layout="nested" produces, because that layout describes every BGEN file. Reading with probability_layout="fixed" gives genotypes.GP a fixed-width state list instead.

Source code in polars_bio/io.py
@staticmethod
def describe_bgen(
    path: str,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    compression_type: str = "auto",
    sample_path: Union[str, None] = None,
    bgi_path: Union[str, None] = None,
) -> pl.DataFrame:
    """
    Describe the schema a BGEN file produces.

    BGEN has no INFO/FORMAT header, so instead of a field dictionary this
    returns one row per emitted column, plus the file-level properties the
    provider records in the Arrow schema metadata: the BGEN layout, whether
    a `.bgi` index was used, whether sample identifiers were generated, and
    the coordinate system.

    Parameters:
        path: The path to the BGEN file. The path must end in `.bgen`.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        compression_type: The compression override.
        sample_path: An explicit Oxford `.sample` companion, used only when the BGEN has no embedded sample identifiers.
        bgi_path: An explicit `.bgi` index. Pass it for an index stored away from the file, so the reported `index` property reflects the index a read would actually use.

    !!! note
        The reported schema is the one the default `probability_layout="nested"`
        produces, because that layout describes every BGEN file. Reading with
        `probability_layout="fixed"` gives `genotypes.GP` a fixed-width state
        list instead.
    """
    _validate_bgen_input_path(path, operation="describe")
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=8,
        concurrent_fetches=1,
        max_retries=1,
        timeout=10,
        compression_type=compression_type,
    )
    bgen_read_options = BgenReadOptions(
        object_storage_options=object_storage_options,
        genotype_output="probability",
        probability_layout="nested",
        samples=None,
        sample_path=sample_path,
        bgi_path=bgi_path,
        zero_based=_resolve_zero_based(None),
    )
    # Registering under the derived name would deregister and replace a
    # table the caller already registered for the same file, so describe
    # uses a private name and removes it again.
    describe_name = f"_pb_bgen_describe_{uuid4().hex}"
    table = py_register_table(
        ctx,
        path,
        describe_name,
        InputFormat.Bgen,
        ReadOptions(bgen_read_options=bgen_read_options),
    )
    try:
        schema = py_get_table_schema(ctx, table.name)
    finally:
        ctx.deregister_table(table.name)
    metadata = {
        (key.decode() if isinstance(key, bytes) else key): (
            value.decode() if isinstance(value, bytes) else value
        )
        for key, value in (schema.metadata or {}).items()
    }
    described = pl.DataFrame(
        {
            "name": [field.name for field in schema],
            "type": [str(field.type) for field in schema],
        }
    )
    properties = {
        "layout": metadata.get("bio.bgen.layout"),
        "index": metadata.get("bio.bgen.index"),
        "sample_names_synthetic": metadata.get("bio.bgen.sample_names.synthetic"),
        "coordinate_system_zero_based": metadata.get(
            "bio.coordinate_system_zero_based"
        ),
    }
    return described.with_columns(
        [pl.lit(value).alias(name) for name, value in properties.items()]
    )

describe_pgen(path, allow_anonymous=True, enable_request_payer=False, compression_type='auto', pvar_path=None, psam_path=None, pgi_path=None) staticmethod

Describe the schema a PLINK 2 PGEN fileset produces.

PGEN has no embedded header, so instead of a field dictionary this returns one row per emitted column, plus the file-level properties the provider records in the Arrow schema metadata: the storage mode, whether the index is embedded or external, the specification baseline, and the coordinate system.

Parameters:

Name Type Description Default
path str

The path to the PGEN file. The path must end in .pgen.

required
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
compression_type str

The compression override.

'auto'
pvar_path Union[str, None]

An explicit .pvar companion.

None
psam_path Union[str, None]

An explicit .psam companion.

None
pgi_path Union[str, None]

An explicit .pgi index, for a PGEN that uses an external index. Without it, such a fileset cannot be opened here at all.

None

Note

The reported schema is the one the default genotype_fields=("GT",) produces. Selecting other genotype fields changes the children of the genotypes struct.

Source code in polars_bio/io.py
@staticmethod
def describe_pgen(
    path: str,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    compression_type: str = "auto",
    pvar_path: Union[str, None] = None,
    psam_path: Union[str, None] = None,
    pgi_path: Union[str, None] = None,
) -> pl.DataFrame:
    """
    Describe the schema a PLINK 2 PGEN fileset produces.

    PGEN has no embedded header, so instead of a field dictionary this
    returns one row per emitted column, plus the file-level properties the
    provider records in the Arrow schema metadata: the storage mode,
    whether the index is embedded or external, the specification baseline,
    and the coordinate system.

    Parameters:
        path: The path to the PGEN file. The path must end in `.pgen`.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        compression_type: The compression override.
        pvar_path: An explicit `.pvar` companion.
        psam_path: An explicit `.psam` companion.
        pgi_path: An explicit `.pgi` index, for a PGEN that uses an external index. Without it, such a fileset cannot be opened here at all.

    !!! note
        The reported schema is the one the default `genotype_fields=("GT",)`
        produces. Selecting other genotype fields changes the children of
        the `genotypes` struct.
    """
    _validate_pgen_input_path(path, operation="describe")
    object_storage_options = PyObjectStorageOptions(
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        chunk_size=8,
        concurrent_fetches=1,
        max_retries=1,
        timeout=10,
        compression_type=compression_type,
    )
    pgen_read_options = PgenReadOptions(
        object_storage_options=object_storage_options,
        genotype_fields=["GT"],
        pvar_path=pvar_path,
        psam_path=psam_path,
        pgi_path=pgi_path,
        zero_based=_resolve_zero_based(None),
    )
    # Registering under the derived name would deregister and replace a
    # table the caller already registered for the same file, so describe
    # uses a private name and removes it again.
    describe_name = f"_pb_pgen_describe_{uuid4().hex}"
    table = py_register_table(
        ctx,
        path,
        describe_name,
        InputFormat.Pgen,
        ReadOptions(pgen_read_options=pgen_read_options),
    )
    try:
        schema = py_get_table_schema(ctx, table.name)
    finally:
        ctx.deregister_table(table.name)
    metadata = {
        (key.decode() if isinstance(key, bytes) else key): (
            value.decode() if isinstance(value, bytes) else value
        )
        for key, value in (schema.metadata or {}).items()
    }
    described = pl.DataFrame(
        {
            "name": [field.name for field in schema],
            "type": [str(field.type) for field in schema],
        }
    )
    properties = {
        "storage_mode": metadata.get("bio.pgen.storage_mode"),
        "index": metadata.get("bio.pgen.index"),
        "specification_baseline": metadata.get("bio.pgen.specification_baseline"),
        "coordinate_system_zero_based": metadata.get(
            "bio.coordinate_system_zero_based"
        ),
    }
    return described.with_columns(
        [pl.lit(value).alias(name) for name, value in properties.items()]
    )

describe_vcf(path, allow_anonymous=True, enable_request_payer=False, compression_type='auto') staticmethod

Describe a text VCF INFO and FORMAT schema.

Parameters:

Name Type Description Default
path str

The path to the text VCF file.

required
allow_anonymous bool

Whether to allow anonymous access to object storage (GCS and S3 supported).

True
enable_request_payer bool

Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.

False
compression_type str

The compression type of the VCF file. If not specified, it will be detected automatically..

'auto'
Source code in polars_bio/io.py
@staticmethod
def describe_vcf(
    path: str,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    compression_type: str = "auto",
) -> pl.DataFrame:
    """
    Describe a text VCF INFO and FORMAT schema.

    Parameters:
        path: The path to the text VCF file.
        allow_anonymous: Whether to allow anonymous access to object storage (GCS and S3 supported).
        enable_request_payer: Whether to enable request payer for object storage. This is useful for reading files from AWS S3 buckets that require request payer.
        compression_type: The compression type of the VCF file. If not specified, it will be detected automatically..
    """
    _validate_variant_input_path(path, "vcf", operation="describe")
    return IOOperations._describe_variant(
        path,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        compression_type=compression_type,
    )

describe_vcf_zarr(path) staticmethod

Describe VCF Zarr INFO and FORMAT schema.

Parameters:

Name Type Description Default
path str

The path to the local VCF Zarr store directory.

required
Source code in polars_bio/io.py
@staticmethod
def describe_vcf_zarr(path: str) -> pl.DataFrame:
    """
    Describe VCF Zarr INFO and FORMAT schema.

    Parameters:
        path: The path to the local VCF Zarr store directory.
    """
    return py_describe_vcf_zarr(ctx, path).to_polars()

describe_bam(path, sample_size=100, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', use_zero_based=None) staticmethod

Get schema information for a BAM file with automatic tag discovery.

Samples the first N records to discover all available tags and their types. Returns detailed schema information including column names, data types, nullability, category (standard/tag), SAM type, and descriptions.

Parameters:

Name Type Description Default
path str

The path to the BAM file.

required
sample_size int

Number of records to sample for tag discovery (default: 100). Use higher values for more comprehensive tag discovery.

100
chunk_size int

The size in MB of a chunk when reading from object storage.

8
concurrent_fetches int

The number of concurrent fetches when reading from object storage.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file.

5
timeout int

The timeout in seconds for reading the file.

300
compression_type str

The compression type of the file. If "auto" (default), compression is detected automatically.

'auto'
use_zero_based Optional[bool]

If True, output 0-based coordinates. If False, 1-based coordinates.

None

Returns:

Type Description
DataFrame

DataFrame with columns:

DataFrame
  • column_name: Name of the column/field
DataFrame
  • data_type: Arrow data type (e.g., "Utf8", "Int32")
DataFrame
  • nullable: Whether the field can be null
DataFrame
  • category: "core" for fixed columns, "tag" for optional SAM tags
DataFrame
  • sam_type: SAM type code (e.g., "Z", "i") for tags, null for core columns
DataFrame
  • description: Human-readable description of the field
Example
import polars_bio as pb

# Auto-discover all tags present in the file
schema = pb.describe_bam("file.bam", sample_size=100)
print(schema)
# Output:
# shape: (15, 6)
# ┌─────────────┬───────────┬──────────┬──────────┬──────────┬──────────────────────┐
# │ column_name ┆ data_type ┆ nullable ┆ category ┆ sam_type ┆ description          │
# │ ---         ┆ ---       ┆ ---      ┆ ---      ┆ ---      ┆ ---                  │
# │ str         ┆ str       ┆ bool     ┆ str      ┆ str      ┆ str                  │
# ╞═════════════╪═══════════╪══════════╪══════════╪══════════╪══════════════════════╡
# │ name        ┆ Utf8      ┆ true     ┆ core     ┆ null     ┆ Query name           │
# │ chrom       ┆ Utf8      ┆ true     ┆ core     ┆ null     ┆ Reference name       │
# │ ...         ┆ ...       ┆ ...      ┆ ...      ┆ ...      ┆ ...                  │
# │ NM          ┆ Int32     ┆ true     ┆ tag      ┆ i        ┆ Edit distance        │
# │ AS          ┆ Int32     ┆ true     ┆ tag      ┆ i        ┆ Alignment score      │
# └─────────────┴───────────┴──────────┴──────────┴──────────┴──────────────────────┘
Source code in polars_bio/io.py
@staticmethod
def describe_bam(
    path: str,
    sample_size: int = 100,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Get schema information for a BAM file with automatic tag discovery.

    Samples the first N records to discover all available tags and their types.
    Returns detailed schema information including column names, data types,
    nullability, category (standard/tag), SAM type, and descriptions.

    Parameters:
        path: The path to the BAM file.
        sample_size: Number of records to sample for tag discovery (default: 100).
            Use higher values for more comprehensive tag discovery.
        chunk_size: The size in MB of a chunk when reading from object storage.
        concurrent_fetches: The number of concurrent fetches when reading from object storage.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file.
        timeout: The timeout in seconds for reading the file.
        compression_type: The compression type of the file. If "auto" (default), compression is detected automatically.
        use_zero_based: If True, output 0-based coordinates. If False, 1-based coordinates.

    Returns:
        DataFrame with columns:
        - column_name: Name of the column/field
        - data_type: Arrow data type (e.g., "Utf8", "Int32")
        - nullable: Whether the field can be null
        - category: "core" for fixed columns, "tag" for optional SAM tags
        - sam_type: SAM type code (e.g., "Z", "i") for tags, null for core columns
        - description: Human-readable description of the field

    Example:
        ```python
        import polars_bio as pb

        # Auto-discover all tags present in the file
        schema = pb.describe_bam("file.bam", sample_size=100)
        print(schema)
        # Output:
        # shape: (15, 6)
        # ┌─────────────┬───────────┬──────────┬──────────┬──────────┬──────────────────────┐
        # │ column_name ┆ data_type ┆ nullable ┆ category ┆ sam_type ┆ description          │
        # │ ---         ┆ ---       ┆ ---      ┆ ---      ┆ ---      ┆ ---                  │
        # │ str         ┆ str       ┆ bool     ┆ str      ┆ str      ┆ str                  │
        # ╞═════════════╪═══════════╪══════════╪══════════╪══════════╪══════════════════════╡
        # │ name        ┆ Utf8      ┆ true     ┆ core     ┆ null     ┆ Query name           │
        # │ chrom       ┆ Utf8      ┆ true     ┆ core     ┆ null     ┆ Reference name       │
        # │ ...         ┆ ...       ┆ ...      ┆ ...      ┆ ...      ┆ ...                  │
        # │ NM          ┆ Int32     ┆ true     ┆ tag      ┆ i        ┆ Edit distance        │
        # │ AS          ┆ Int32     ┆ true     ┆ tag      ┆ i        ┆ Alignment score      │
        # └─────────────┴───────────┴──────────┴──────────┴──────────┴──────────────────────┘
        ```
    """
    # Build object storage options
    object_storage_options = PyObjectStorageOptions(
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    # Resolve zero_based setting
    zero_based = _resolve_zero_based(use_zero_based)

    # Call Rust function with tag auto-discovery (tag_fields=None)
    df = py_describe_bam(
        ctx,  # PyBioSessionContext
        path,
        object_storage_options,
        zero_based,
        None,  # tag_fields=None enables auto-discovery
        sample_size,
    )

    # Convert DataFusion DataFrame to Polars DataFrame
    return pl.from_arrow(df.to_arrow_table())

describe_sam(path, sample_size=100, use_zero_based=None) staticmethod

Get schema information for a SAM file with automatic tag discovery.

Samples the first N records to discover all available tags and their types. Reuses the BAM describe logic, which auto-detects SAM from the file extension.

Parameters:

Name Type Description Default
path str

The path to the SAM file.

required
sample_size int

Number of records to sample for tag discovery (default: 100).

100
use_zero_based Optional[bool]

If True, output 0-based coordinates. If False, 1-based coordinates.

None

Returns:

Type Description
DataFrame

DataFrame with columns: column_name, data_type, nullable, category, sam_type, description

Source code in polars_bio/io.py
@staticmethod
def describe_sam(
    path: str,
    sample_size: int = 100,
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Get schema information for a SAM file with automatic tag discovery.

    Samples the first N records to discover all available tags and their types.
    Reuses the BAM describe logic, which auto-detects SAM from the file extension.

    Parameters:
        path: The path to the SAM file.
        sample_size: Number of records to sample for tag discovery (default: 100).
        use_zero_based: If True, output 0-based coordinates. If False, 1-based coordinates.

    Returns:
        DataFrame with columns: column_name, data_type, nullable, category, sam_type, description
    """
    zero_based = _resolve_zero_based(use_zero_based)

    df = py_describe_bam(
        ctx,
        path,
        None,
        zero_based,
        None,
        sample_size,
    )

    return pl.from_arrow(df.to_arrow_table())

describe_cram(path, reference_path=None, sample_size=100, chunk_size=8, concurrent_fetches=1, allow_anonymous=True, enable_request_payer=False, max_retries=5, timeout=300, compression_type='auto', use_zero_based=None) staticmethod

Get schema information for a CRAM file with automatic tag discovery.

Samples the first N records to discover all available tags and their types. Returns detailed schema information including column names, data types, nullability, category (core/tag), SAM type, and descriptions.

Parameters:

Name Type Description Default
path str

The path to the CRAM file.

required
reference_path str

Optional path to external FASTA reference file.

None
sample_size int

Number of records to sample for tag discovery (default: 100).

100
chunk_size int

The size in MB of a chunk when reading from object storage.

8
concurrent_fetches int

The number of concurrent fetches when reading from object storage.

1
allow_anonymous bool

Whether to allow anonymous access to object storage.

True
enable_request_payer bool

Whether to enable request payer for object storage.

False
max_retries int

The maximum number of retries for reading the file.

5
timeout int

The timeout in seconds for reading the file.

300
compression_type str

The compression type of the file. If "auto" (default), compression is detected automatically.

'auto'
use_zero_based Optional[bool]

If True, output 0-based coordinates. If False, 1-based coordinates.

None

Returns:

Type Description
DataFrame

DataFrame with columns:

DataFrame
  • column_name: Name of the column/field
DataFrame
  • data_type: Arrow data type (e.g., "Utf8", "Int32")
DataFrame
  • nullable: Whether the field can be null
DataFrame
  • category: "core" for fixed columns, "tag" for optional SAM tags
DataFrame
  • sam_type: SAM type code (e.g., "Z", "i") for tags, null for core columns
DataFrame
  • description: Human-readable description of the field

Known Limitation: MD and NM Tags

Due to a limitation in the underlying noodles-cram library, MD (mismatch descriptor) and NM (edit distance) tags are not discoverable from CRAM files, even when stored. Automatic tag discovery will not include MD/NM tags. Other optional tags (RG, MQ, AM, OQ, etc.) are discovered correctly. See: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

Example
import polars_bio as pb

# Auto-discover all tags present in the file
schema = pb.describe_cram("file.cram", sample_size=100)
print(schema)

# Filter to see only tag columns
tags = schema.filter(schema["category"] == "tag")
print(tags["column_name"])
Source code in polars_bio/io.py
@staticmethod
def describe_cram(
    path: str,
    reference_path: str = None,
    sample_size: int = 100,
    chunk_size: int = 8,
    concurrent_fetches: int = 1,
    allow_anonymous: bool = True,
    enable_request_payer: bool = False,
    max_retries: int = 5,
    timeout: int = 300,
    compression_type: str = "auto",
    use_zero_based: Optional[bool] = None,
) -> pl.DataFrame:
    """
    Get schema information for a CRAM file with automatic tag discovery.

    Samples the first N records to discover all available tags and their types.
    Returns detailed schema information including column names, data types,
    nullability, category (core/tag), SAM type, and descriptions.

    Parameters:
        path: The path to the CRAM file.
        reference_path: Optional path to external FASTA reference file.
        sample_size: Number of records to sample for tag discovery (default: 100).
        chunk_size: The size in MB of a chunk when reading from object storage.
        concurrent_fetches: The number of concurrent fetches when reading from object storage.
        allow_anonymous: Whether to allow anonymous access to object storage.
        enable_request_payer: Whether to enable request payer for object storage.
        max_retries: The maximum number of retries for reading the file.
        timeout: The timeout in seconds for reading the file.
        compression_type: The compression type of the file. If "auto" (default), compression is detected automatically.
        use_zero_based: If True, output 0-based coordinates. If False, 1-based coordinates.

    Returns:
        DataFrame with columns:
        - column_name: Name of the column/field
        - data_type: Arrow data type (e.g., "Utf8", "Int32")
        - nullable: Whether the field can be null
        - category: "core" for fixed columns, "tag" for optional SAM tags
        - sam_type: SAM type code (e.g., "Z", "i") for tags, null for core columns
        - description: Human-readable description of the field

    !!! warning "Known Limitation: MD and NM Tags"
        Due to a limitation in the underlying noodles-cram library, **MD (mismatch descriptor) and NM (edit distance) tags are not discoverable** from CRAM files, even when stored. Automatic tag discovery will not include MD/NM tags. Other optional tags (RG, MQ, AM, OQ, etc.) are discovered correctly. See: https://github.com/biodatageeks/datafusion-bio-formats/issues/54

    Example:
        ```python
        import polars_bio as pb

        # Auto-discover all tags present in the file
        schema = pb.describe_cram("file.cram", sample_size=100)
        print(schema)

        # Filter to see only tag columns
        tags = schema.filter(schema["category"] == "tag")
        print(tags["column_name"])
        ```
    """
    # Build object storage options
    object_storage_options = PyObjectStorageOptions(
        chunk_size=chunk_size,
        concurrent_fetches=concurrent_fetches,
        allow_anonymous=allow_anonymous,
        enable_request_payer=enable_request_payer,
        max_retries=max_retries,
        timeout=timeout,
        compression_type=compression_type,
    )

    # Resolve zero_based setting
    zero_based = _resolve_zero_based(use_zero_based)

    # Call Rust function with tag auto-discovery (tag_fields=None)
    df = py_describe_cram(
        ctx,
        path,
        reference_path,
        object_storage_options,
        zero_based,
        None,  # tag_fields=None enables auto-discovery
        sample_size,
    )

    # Convert DataFusion DataFrame to Polars DataFrame
    return pl.from_arrow(df.to_arrow_table())

describe_cool(path) staticmethod

Describe the data collections of a Cooler (.cool/.mcool) file.

Returns one row per stored data collection (one for .cool, one per resolution for .mcool) with group_path, resolution (bin size), bin_type, format_version, assembly, nbins, nnz, sum, and nchroms, read from file metadata without scanning pixel data. sum is Int64/UInt64 for integer-count collections and Float64 for float-count collections. Files mixing those storage classes use an exact Decimal column (or an exact string for values outside Arrow's Decimal128 range), preserving wide integer totals alongside fractions.

Parameters:

Name Type Description Default
path str

The path to the .cool/.mcool file, or a cooler URI (file.mcool::/resolutions/10000) to describe a single data collection.

required
Source code in polars_bio/io.py
@staticmethod
def describe_cool(path: str) -> pl.DataFrame:
    """
    Describe the data collections of a Cooler (`.cool`/`.mcool`) file.

    Returns one row per stored data collection (one for `.cool`, one per
    resolution for `.mcool`) with `group_path`, `resolution` (bin size),
    `bin_type`, `format_version`, `assembly`, `nbins`, `nnz`, `sum`, and
    `nchroms`, read from file metadata without scanning pixel data. `sum`
    is Int64/UInt64 for integer-count collections and Float64 for
    float-count collections. Files mixing those storage classes use an
    exact Decimal column (or an exact string for values outside Arrow's
    Decimal128 range), preserving wide integer totals alongside fractions.

    Parameters:
        path: The path to the `.cool`/`.mcool` file, or a cooler URI
            (`file.mcool::/resolutions/10000`) to describe a single data
            collection.
    """
    return py_describe_cool(ctx, path).to_polars()

from_polars(name, df) staticmethod

Register a Polars DataFrame as a DataFusion table.

Parameters:

Name Type Description Default
name str

The name of the table.

required
df Union[DataFrame, LazyFrame]

The Polars DataFrame.

required
Source code in polars_bio/io.py
@staticmethod
def from_polars(name: str, df: Union[pl.DataFrame, pl.LazyFrame]) -> None:
    """
    Register a Polars DataFrame as a DataFusion table.

    Parameters:
        name: The name of the table.
        df: The Polars DataFrame.
    """
    reader = (
        df.to_arrow()
        if isinstance(df, pl.DataFrame)
        else df.collect().to_arrow().to_reader()
    )
    py_from_polars(ctx, name, reader)