1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115
|
// This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
// Christopher Chang.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "include/plink2_stats.h"
#include "plink2_compress_stream.h"
#include "plink2_data.h"
#include "plink2_misc.h"
#ifdef __cplusplus
namespace plink2 {
#endif
void InitUpdateAlleles(UpdateAllelesInfo* update_alleles_info_ptr) {
update_alleles_info_ptr->flags = kfUpdateAlleles0;
update_alleles_info_ptr->fname = nullptr;
}
void CleanupUpdateAlleles(UpdateAllelesInfo* update_alleles_info_ptr) {
free_cond(update_alleles_info_ptr->fname);
}
void InitUpdateSex(UpdateSexInfo* update_sex_info_ptr) {
update_sex_info_ptr->flags = kfUpdateSex0;
update_sex_info_ptr->col_num = 0;
update_sex_info_ptr->fname = nullptr;
}
void CleanupUpdateSex(UpdateSexInfo* update_sex_info_ptr) {
free_cond(update_sex_info_ptr->fname);
}
void InitSdiff(SdiffInfo* sdiff_info_ptr) {
sdiff_info_ptr->flags = kfSdiff0;
sdiff_info_ptr->dosage_hap_tol = kDosageMissing;
sdiff_info_ptr->fname_id_delim = '\0';
sdiff_info_ptr->other_id_ct = 0;
sdiff_info_ptr->first_id_or_fname = nullptr;
sdiff_info_ptr->other_ids_flattened = nullptr;
}
void CleanupSdiff(SdiffInfo* sdiff_info_ptr) {
free_cond(sdiff_info_ptr->first_id_or_fname);
free_cond(sdiff_info_ptr->other_ids_flattened);
}
void InitFst(FstInfo* fst_info_ptr) {
fst_info_ptr->flags = kfFst0;
fst_info_ptr->blocksize = 0;
fst_info_ptr->pheno_name = nullptr;
fst_info_ptr->first_id_or_fname = nullptr;
fst_info_ptr->other_ids_flattened = nullptr;
}
void CleanupFst(FstInfo* fst_info_ptr) {
free_cond(fst_info_ptr->pheno_name);
free_cond(fst_info_ptr->first_id_or_fname);
free_cond(fst_info_ptr->other_ids_flattened);
}
void InitCheckSex(CheckSexInfo* check_sex_info_ptr) {
check_sex_info_ptr->flags = kfCheckSex0;
check_sex_info_ptr->max_female_xf = -1.0;
check_sex_info_ptr->min_male_xf = -1.0;
check_sex_info_ptr->max_female_ycount = UINT32_MAX;
check_sex_info_ptr->min_male_ycount = UINT32_MAX;
check_sex_info_ptr->max_female_yrate = -1.0;
check_sex_info_ptr->min_male_yrate = -1.0;
}
PglErr UpdateVarBps(const ChrInfo* cip, const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const TwoColParams* params, uint32_t sort_vars_in_cmd, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uint32_t htable_size, uint32_t max_thread_ct, uintptr_t* variant_include, uint32_t* __restrict variant_bps, uint32_t* __restrict variant_ct_ptr, UnsortedVar* vpos_sortstatusp) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
uintptr_t* already_seen;
if (unlikely(bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &already_seen))) {
goto UpdateVarBps_ret_NOMEM;
}
// This could be pointed at a file containing allele codes, so don't limit
// line length to minimum value.
reterr = SizeAndInitTextStream(params->fname, bigstack_left(), MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto UpdateVarBps_ret_TSTREAM_FAIL;
}
reterr = TextSkip(params->skip_ct, &txs);
if (unlikely(reterr)) {
if (reterr == kPglRetEof) {
snprintf(g_logbuf, kLogbufSize, "Error: Fewer lines than expected in %s.\n", params->fname);
goto UpdateVarBps_ret_INCONSISTENT_INPUT_WW;
}
goto UpdateVarBps_ret_TSTREAM_FAIL;
}
line_idx = params->skip_ct;
const uint32_t colid_first = (params->colid < params->colx);
uint32_t variant_ct = *variant_ct_ptr;
uint32_t colmin;
uint32_t coldiff;
if (colid_first) {
colmin = params->colid - 1;
coldiff = params->colx - params->colid;
} else {
colmin = params->colx - 1;
coldiff = params->colid - params->colx;
}
const char skipchar = params->skipchar;
uintptr_t miss_ct = 0;
uint32_t hit_ct = 0;
while (1) {
++line_idx;
const char* line_start = TextGet(&txs);
if (!line_start) {
if (likely(!TextStreamErrcode2(&txs, &reterr))) {
break;
}
goto UpdateVarBps_ret_TSTREAM_FAIL;
}
char cc = *line_start;
if (cc == skipchar) {
continue;
}
const char* colid_ptr;
const char* colbp_ptr;
if (colid_first) {
colid_ptr = NextTokenMult0(line_start, colmin);
colbp_ptr = NextTokenMult(colid_ptr, coldiff);
if (unlikely(!colbp_ptr)) {
goto UpdateVarBps_ret_MISSING_TOKENS;
}
} else {
colbp_ptr = NextTokenMult0(line_start, colmin);
colid_ptr = NextTokenMult(colbp_ptr, coldiff);
if (unlikely(!colid_ptr)) {
goto UpdateVarBps_ret_MISSING_TOKENS;
}
}
const uint32_t varid_slen = strlen_se(colid_ptr);
uint32_t cur_llidx;
uint32_t variant_uidx = VariantIdDupHtableFind(colid_ptr, variant_ids, variant_id_htable, htable_dup_base, varid_slen, htable_size, max_variant_id_slen, &cur_llidx);
if (variant_uidx == UINT32_MAX) {
++miss_ct;
continue;
}
const char* cur_var_id = variant_ids[variant_uidx];
if (unlikely(cur_llidx != UINT32_MAX)) {
// we could check if some copies have been filtered out after hash
// table construction?
snprintf(g_logbuf, kLogbufSize, "Error: --update-map variant ID '%s' appears multiple times in dataset.\n", cur_var_id);
goto UpdateVarBps_ret_INCONSISTENT_INPUT_WW;
}
if (unlikely(IsSet(already_seen, variant_uidx))) {
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-map file.\n", cur_var_id);
goto UpdateVarBps_ret_INCONSISTENT_INPUT_WW;
}
SetBit(variant_uidx, already_seen);
if (!IsSet(variant_include, variant_uidx)) {
continue;
}
int32_t bp_coord;
if (ScanIntAbsDefcap(colbp_ptr, &bp_coord)) {
snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of --update-map file.\n", line_idx);
goto UpdateVarBps_ret_MALFORMED_INPUT;
}
if (bp_coord < 0) {
ClearBit(variant_uidx, variant_include);
--variant_ct;
} else {
variant_bps[variant_uidx] = bp_coord;
}
++hit_ct;
}
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--update-map: %u value%s updated, %" PRIuPTR " variant ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
} else {
snprintf(g_logbuf, kLogbufSize, "--update-map: %u value%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
}
logputsb();
UnsortedVar vpos_sortstatus = (*vpos_sortstatusp) & (~kfUnsortedVarBp);
if (!(vpos_sortstatus & kfUnsortedVarSplitChr)) {
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t last_bp = 0;
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (variant_uidx >= chr_end);
last_bp = 0;
}
const uint32_t cur_bp = variant_bps[variant_uidx];
if (last_bp > cur_bp) {
vpos_sortstatus |= kfUnsortedVarBp;
if (!((*vpos_sortstatusp) & kfUnsortedVarBp)) {
if (sort_vars_in_cmd) {
logerrputs("Note: Base-pair positions are now unsorted.\n");
} else {
logerrputs("Warning: Base-pair positions are now unsorted!\n");
}
}
break;
}
last_bp = cur_bp;
}
if (((*vpos_sortstatusp) & kfUnsortedVarBp) && (!(vpos_sortstatus & kfUnsortedVarBp))) {
logputs("Base-pair positions are now sorted.\n");
}
*vpos_sortstatusp = vpos_sortstatus;
}
}
while (0) {
UpdateVarBps_ret_NOMEM:
reterr = kPglRetNomem;
break;
UpdateVarBps_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-map file", &txs);
break;
UpdateVarBps_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-map file has fewer tokens than expected.\n", line_idx);
UpdateVarBps_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
reterr = kPglRetInconsistentInput;
break;
UpdateVarBps_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
}
CleanupTextStream2("--update-map file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr UpdateVarNames(const uintptr_t* variant_include, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const TwoColParams* params, uint32_t raw_variant_ct, uint32_t htable_size, uint32_t max_thread_ct, char** variant_ids, uint32_t* max_variant_id_slen_ptr) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
const uint32_t orig_max_variant_id_slen = *max_variant_id_slen_ptr;
uint32_t max_variant_id_slen = orig_max_variant_id_slen;
char** variant_ids_copy;
uintptr_t* already_seen;
if (unlikely(bigstack_alloc_cp(raw_variant_ct, &variant_ids_copy) ||
bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &already_seen))) {
goto UpdateVarNames_ret_NOMEM;
}
memcpy(variant_ids_copy, variant_ids, raw_variant_ct * sizeof(intptr_t));
// This could be pointed at a file containing allele codes, so don't limit
// line length to minimum value.
// On the other hand, new variant IDs are allocated off the end of
// bigstack, and that could result in a lot of memory pressure.
reterr = SizeAndInitTextStream(params->fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto UpdateVarNames_ret_TSTREAM_FAIL;
}
reterr = TextSkip(params->skip_ct, &txs);
if (unlikely(reterr)) {
if (reterr == kPglRetEof) {
snprintf(g_logbuf, kLogbufSize, "Error: Fewer lines than expected in %s.\n", params->fname);
goto UpdateVarNames_ret_INCONSISTENT_INPUT_WW;
}
goto UpdateVarNames_ret_TSTREAM_FAIL;
}
line_idx = params->skip_ct;
const uint32_t colold_first = (params->colid < params->colx);
uint32_t colmin;
uint32_t coldiff;
if (colold_first) {
colmin = params->colid - 1;
coldiff = params->colx - params->colid;
} else {
colmin = params->colx - 1;
coldiff = params->colid - params->colx;
}
const char skipchar = params->skipchar;
char* alloc_base = R_CAST(char*, g_bigstack_base);
char* alloc_end = R_CAST(char*, g_bigstack_end);
uintptr_t miss_ct = 0;
uint32_t hit_ct = 0;
while (1) {
++line_idx;
const char* line_start = TextGet(&txs);
if (!line_start) {
// bugfix (7 Jun 2023): this condition was flipped
if (likely(!TextStreamErrcode2(&txs, &reterr))) {
break;
}
goto UpdateVarNames_ret_TSTREAM_FAIL;
}
char cc = *line_start;
if (cc == skipchar) {
continue;
}
const char* colold_ptr;
const char* colnew_ptr;
if (colold_first) {
colold_ptr = NextTokenMult0(line_start, colmin);
colnew_ptr = NextTokenMult(colold_ptr, coldiff);
if (unlikely(!colnew_ptr)) {
goto UpdateVarNames_ret_MISSING_TOKENS;
}
} else {
colnew_ptr = NextTokenMult0(line_start, colmin);
colold_ptr = NextTokenMult(colnew_ptr, coldiff);
if (unlikely(!colold_ptr)) {
goto UpdateVarNames_ret_MISSING_TOKENS;
}
}
const uint32_t colold_slen = strlen_se(colold_ptr);
uint32_t cur_llidx;
uint32_t variant_uidx = VariantIdDupHtableFind(colold_ptr, TO_CONSTCPCONSTP(variant_ids_copy), variant_id_htable, htable_dup_base, colold_slen, htable_size, orig_max_variant_id_slen, &cur_llidx);
if (variant_uidx == UINT32_MAX) {
++miss_ct;
continue;
}
const char* cur_var_id = variant_ids_copy[variant_uidx];
if (unlikely(cur_llidx != UINT32_MAX)) {
// we could check if some copies have been filtered out after hash
// table construction?
snprintf(g_logbuf, kLogbufSize, "Error: --update-name variant ID '%s' appears multiple times in dataset.\n", cur_var_id);
goto UpdateVarNames_ret_INCONSISTENT_INPUT_WW;
}
if (!IsSet(variant_include, variant_uidx)) {
continue;
}
if (unlikely(IsSet(already_seen, variant_uidx))) {
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-name file.\n", cur_var_id);
goto UpdateVarNames_ret_INCONSISTENT_INPUT_WW;
}
SetBit(variant_uidx, already_seen);
++hit_ct;
const uint32_t colnew_slen = strlen_se(colnew_ptr);
if (colnew_slen <= colold_slen) {
const uint32_t colold_blen = colold_slen + 1;
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < colold_blen)) {
goto UpdateVarNames_ret_NOMEM;
}
memcpy(alloc_base, cur_var_id, colold_blen);
variant_ids_copy[variant_uidx] = alloc_base;
alloc_base = &(alloc_base[colold_blen]);
memcpyx(variant_ids[variant_uidx], colnew_ptr, colnew_slen, '\0');
} else {
if (colnew_slen > max_variant_id_slen) {
max_variant_id_slen = colnew_slen;
}
const uint32_t colnew_blen = colnew_slen + 1;
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < colnew_blen)) {
goto UpdateVarNames_ret_NOMEM;
}
alloc_end -= colnew_blen;
memcpyx(alloc_end, colnew_ptr, colnew_slen, '\0');
variant_ids[variant_uidx] = alloc_end;
}
}
BigstackEndSet(alloc_end);
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--update-name: %u value%s updated, %" PRIuPTR " variant ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
} else {
snprintf(g_logbuf, kLogbufSize, "--update-name: %u value%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
}
logputsb();
*max_variant_id_slen_ptr = max_variant_id_slen;
}
while (0) {
UpdateVarNames_ret_NOMEM:
reterr = kPglRetNomem;
break;
UpdateVarNames_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-name file", &txs);
break;
UpdateVarNames_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-name file has fewer tokens than expected.\n", line_idx);
UpdateVarNames_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
reterr = kPglRetInconsistentInput;
break;
}
CleanupTextStream2("--update-name file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
static_assert(kPglMaxAlleleCt <= 65535, "UpdateVarAlleles() must be updated.");
PglErr UpdateVarAlleles(const uintptr_t* variant_include, const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const uintptr_t* allele_idx_offsets, const UpdateAllelesInfo* update_alleles_info_ptr, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uint32_t htable_size, uint32_t max_allele_ct, char input_missing_geno_char, uint32_t max_thread_ct, char** allele_storage_mutable, uint32_t* max_allele_slen_ptr, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
// Set this to 65536 even though kPglMaxAlleleCt is only 255 as of this
// writing, since VCF variants with >255 alleles are out there and we don't
// want to crash when partial-match is a possibility.
const uint32_t max_impl_input_allele_ct = 65536;
uintptr_t line_idx = 0;
FILE* errfile = nullptr;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
const uint32_t max_allele_ctl = BitCtToWordCt(max_allele_ct);
char** input_allele_starts;
uint32_t* input_allele_slens;
const char** orig_alleles_sorted;
uint32_t* sorted_to_orig_idx;
uint16_t* orig_to_input_idx;
uintptr_t* alleles_seen;
uintptr_t* variants_seen;
unsigned char* sort_wkspace;
if (unlikely(bigstack_alloc_cp(max_impl_input_allele_ct, &input_allele_starts) ||
bigstack_alloc_u32(max_impl_input_allele_ct, &input_allele_slens) ||
bigstack_alloc_kcp(max_allele_ct, &orig_alleles_sorted) ||
bigstack_alloc_u32(max_allele_ct, &sorted_to_orig_idx) ||
bigstack_alloc_u16(max_allele_ct, &orig_to_input_idx) ||
bigstack_alloc_w(max_allele_ctl, &alleles_seen) ||
bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &variants_seen) ||
bigstack_alloc_uc(max_allele_ct * sizeof(StrSortIndexedDeref), &sort_wkspace))) {
goto UpdateVarAlleles_ret_NOMEM;
}
reterr = SizeAndInitTextStream(update_alleles_info_ptr->fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto UpdateVarAlleles_ret_TSTREAM_FAIL;
}
const uint32_t allow_mismatch = (update_alleles_info_ptr->flags / kfUpdateAllelesAllowMismatch) & 1;
const uint32_t strict_missing = (update_alleles_info_ptr->flags / kfUpdateAllelesStrictMissing) & 1;
const char* std_input_missing_geno = &(g_one_char_strs[92]);
unsigned char* tmp_alloc_base = g_bigstack_base;
unsigned char* tmp_alloc_end = g_bigstack_end;
uintptr_t miss_ct = 0;
uintptr_t err_ct = 0;
uint32_t hit_ct = 0;
uint32_t is_3col = 2; // 0 = orig format, 1 = 3col, 2 = not determined yet
uint32_t max_allele_slen = *max_allele_slen_ptr;
uint32_t cur_input_allele_ct = 2;
uint32_t cur_allele_ct = 2;
char* line_iter = TextLineEnd(&txs);
++line_idx;
for (; TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
char* varid_start = line_iter;
char* varid_end = CurTokenEnd(varid_start);
uint32_t cur_llidx;
uint32_t variant_uidx = VariantIdDupHtableFind(varid_start, variant_ids, variant_id_htable, htable_dup_base, varid_end - varid_start, htable_size, max_variant_id_slen, &cur_llidx);
if (variant_uidx == UINT32_MAX) {
line_iter = varid_end;
++miss_ct;
continue;
}
const char* varid = variant_ids[variant_uidx];
if (unlikely(cur_llidx != UINT32_MAX)) {
snprintf(g_logbuf, kLogbufSize, "Error: --update-alleles variant ID '%s' appears multiple times in dataset.\n", varid);
goto UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW;
}
if (unlikely(IsSet(variants_seen, variant_uidx))) {
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-alleles file.\n", varid);
goto UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW;
}
SetBit(variant_uidx, variants_seen);
if (!IsSet(variant_include, variant_uidx)) {
line_iter = varid_end;
++miss_ct;
continue;
}
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
char** orig_alleles = &(allele_storage_mutable[allele_idx_offset_base]);
char* col2_start = FirstNonTspace(varid_end);
char* col2_end = FirstSpaceOrEoln(col2_start);
char* col3_start = FirstNonTspace(col2_end);
if (unlikely(IsEolnKns(*col3_start))) {
goto UpdateVarAlleles_ret_MISSING_TOKENS;
}
char* col3_end = FirstSpaceOrEoln(col3_start);
if (is_3col == 2) {
is_3col = (NextToken(col3_end) == nullptr);
}
char* new_alleles_start = col3_start;
if (is_3col) {
cur_input_allele_ct = 0;
for (char* col2_iter = col2_start; ; ) {
char* input_allele_end = AdvToDelimOrEnd(col2_iter, col2_end, ',');
input_allele_starts[cur_input_allele_ct] = col2_iter;
input_allele_slens[cur_input_allele_ct] = input_allele_end - col2_iter;
++cur_input_allele_ct;
// Null-terminate to set up bsearch_strptr_overread().
*input_allele_end = '\0';
if (input_allele_end == col2_end) {
break;
}
if (unlikely(cur_input_allele_ct == max_impl_input_allele_ct)) {
goto UpdateVarAlleles_ret_TOO_MANY_ALLELES;
}
col2_iter = &(input_allele_end[1]);
}
if ((cur_input_allele_ct > cur_allele_ct) && (!allow_mismatch)) {
UpdateVarAlleles_errfile:
if (!err_ct) {
strcpy_k(outname_end, ".allele.no.snp");
if (fopen_checked(outname, FOPEN_WB, &errfile)) {
goto UpdateVarAlleles_ret_OPEN_FAIL;
}
}
// variant ID, expected allele 1, remaining comma-separated expected
// alleles
// not optimized for now, could explicitly manage a write buffer if
// it ever matters
fputs(varid, errfile);
putc_unlocked('\t', errfile);
fwrite(input_allele_starts[0], input_allele_slens[0], 1, errfile);
putc_unlocked('\t', errfile);
if (cur_input_allele_ct == 1) {
putc_unlocked('.', errfile);
} else {
for (uint32_t aidx = 1; ; ) {
fwrite(input_allele_starts[aidx], input_allele_slens[aidx], 1, errfile);
++aidx;
if (aidx == cur_input_allele_ct) {
break;
}
putc_unlocked(',', errfile);
}
}
#ifdef _WIN32
putc_unlocked('\r', errfile);
#endif
if (unlikely(putc_checked('\n', errfile))) {
goto UpdateVarAlleles_ret_WRITE_FAIL;
}
++err_ct;
continue;
}
} else {
// cur_input_allele_ct == 2
new_alleles_start = FirstNonTspace(col3_end);
input_allele_starts[0] = col2_start;
input_allele_starts[1] = col3_start;
input_allele_slens[0] = col2_end - col2_start;
input_allele_slens[1] = col3_end - col3_start;
*col2_end = '\0';
*col3_end = '\0';
}
uint32_t wildcard_idx = UINT32_MAX;
// safe to assume preexisting allele codes are distinct since
// CheckAlleleUniqueness() was run.
if (cur_allele_ct == 2) {
if (strcmp_overread_lt(orig_alleles[0], orig_alleles[1])) {
sorted_to_orig_idx[0] = 0;
sorted_to_orig_idx[1] = 1;
} else {
sorted_to_orig_idx[0] = 1;
sorted_to_orig_idx[1] = 0;
}
orig_alleles_sorted[0] = orig_alleles[sorted_to_orig_idx[0]];
orig_alleles_sorted[1] = orig_alleles[sorted_to_orig_idx[1]];
if (!strict_missing) {
for (uint32_t uii = 0; uii != 2; ++uii) {
if (memequal(orig_alleles_sorted[uii], std_input_missing_geno, 2)) {
wildcard_idx = sorted_to_orig_idx[uii];
break;
}
}
}
} else {
memcpy(orig_alleles_sorted, orig_alleles, cur_allele_ct * sizeof(intptr_t));
SortStrptrArrIndexed2(cur_allele_ct, 0, 1, 0, orig_alleles_sorted, sorted_to_orig_idx, nullptr, sort_wkspace);
}
ZeroWArr(max_allele_ctl, alleles_seen);
for (uint32_t old_idx = 0; old_idx != cur_input_allele_ct; ++old_idx) {
const char* old_allele = input_allele_starts[old_idx];
uint32_t old_slen = input_allele_slens[old_idx];
// standardize missing allele codes
if ((old_slen == 1) && (old_allele[0] == input_missing_geno_char)) {
old_allele = std_input_missing_geno;
}
const int32_t sorted_orig_idx = bsearch_strptr_overread(old_allele, orig_alleles_sorted, cur_allele_ct);
if (sorted_orig_idx != -1) {
const uint32_t orig_idx = sorted_to_orig_idx[sorted_orig_idx];
if (IsSet(alleles_seen, orig_idx)) {
goto UpdateVarAlleles_ret_DUPLICATE_INPUT_ALLELE_CODE;
}
SetBit(orig_idx, alleles_seen);
orig_to_input_idx[orig_idx] = old_idx;
}
}
if ((wildcard_idx != UINT32_MAX) && (alleles_seen[0] == 2 - wildcard_idx) && (cur_input_allele_ct == 2)) {
// Biallelic variant with one missing allele code, only non-missing
// allele has been matched, exactly two input alleles.
// Match the other old input allele with the original missing allele.
alleles_seen[0] = 3;
orig_to_input_idx[wildcard_idx] = 1 - orig_to_input_idx[1 - wildcard_idx];
}
const uint32_t seen_ct = PopcountWords(alleles_seen, max_allele_ctl);
if ((!seen_ct) || ((!allow_mismatch) && (seen_ct < cur_input_allele_ct))) {
goto UpdateVarAlleles_errfile;
}
if (is_3col) {
uint32_t new_input_allele_idx = 0;
for (char* col3_iter = col3_start; ; ) {
char* input_allele_end = AdvToDelimOrEnd(col3_iter, col3_end, ',');
input_allele_starts[new_input_allele_idx] = col3_iter;
input_allele_slens[new_input_allele_idx] = input_allele_end - col3_iter;
// No need to null-terminate this time. (And if we did, we'd need to
// handle the case where *col3_end was '\n'.)
++new_input_allele_idx;
if (input_allele_end == col3_end) {
if (unlikely(new_input_allele_idx != cur_input_allele_ct)) {
snprintf(g_logbuf, kLogbufSize, "Error: Too few new alleles on line %" PRIuPTR " of --update-alleles file.\n", line_idx);
goto UpdateVarAlleles_ret_MALFORMED_INPUT_WW;
}
break;
}
if (unlikely(new_input_allele_idx == cur_input_allele_ct)) {
snprintf(g_logbuf, kLogbufSize, "Error: Too many new alleles on line %" PRIuPTR " of --update-alleles file.\n", line_idx);
goto UpdateVarAlleles_ret_MALFORMED_INPUT_WW;
}
col3_iter = &(input_allele_end[1]);
}
} else {
char* col4_end = FirstSpaceOrEoln(new_alleles_start);
char* col5_start = FirstNonTspace(col4_end);
if (unlikely(IsEolnKns(*col5_start))) {
goto UpdateVarAlleles_ret_MISSING_TOKENS;
}
char* col5_end = FirstSpaceOrEoln(col5_start);
input_allele_starts[0] = new_alleles_start;
input_allele_starts[1] = col5_start;
input_allele_slens[0] = col4_end - new_alleles_start;
input_allele_slens[1] = col5_end - col5_start;
}
uintptr_t aidx_base = 0;
uintptr_t cur_bits = alleles_seen[0];
for (uint32_t seen_idx = 0; seen_idx != seen_ct; ++seen_idx) {
const uint32_t aidx = BitIter1(alleles_seen, &aidx_base, &cur_bits);
const uint32_t new_idx = orig_to_input_idx[aidx];
const char* new_allele_start = input_allele_starts[new_idx];
const uint32_t new_slen = input_allele_slens[new_idx];
if (new_slen == 1) {
char cc = new_allele_start[0];
if (cc == input_missing_geno_char) {
cc = '.';
}
orig_alleles[aidx] = K_CAST(char*, &(g_one_char_strs[ctou32(cc) * 2]));
} else {
// reuse old storage if we can, allocate when we must
if (strlen(orig_alleles[aidx]) < new_slen) {
if (PtrWSubCk(tmp_alloc_base, new_slen + 1, &tmp_alloc_end)) {
goto UpdateVarAlleles_ret_NOMEM;
}
orig_alleles[aidx] = R_CAST(char*, tmp_alloc_end);
}
memcpyx(orig_alleles[aidx], new_allele_start, new_slen, '\0');
}
}
// Confirm there are no duplicate allele codes after the change.
if (cur_allele_ct == 2) {
if (unlikely(strequal_overread(orig_alleles[0], orig_alleles[1]))) {
goto UpdateVarAlleles_ret_DUPLICATE_ALLELE_CODE_AFTER_UPDATE;
}
} else {
memcpy(orig_alleles_sorted, orig_alleles, cur_allele_ct * sizeof(intptr_t));
SortStrptrArrIndexed2(cur_allele_ct, 0, 1, 0, orig_alleles_sorted, sorted_to_orig_idx, nullptr, sort_wkspace);
const char* prev_allele = orig_alleles_sorted[0];
for (uint32_t aidx = 1; aidx != cur_allele_ct; ++aidx) {
const char* cur_allele = orig_alleles_sorted[aidx];
if (unlikely(strequal_overread(prev_allele, cur_allele))) {
goto UpdateVarAlleles_ret_DUPLICATE_ALLELE_CODE_AFTER_UPDATE;
}
prev_allele = cur_allele;
}
// For multiallelic variants, also confirm missing allele code is not
// present.
if (unlikely(bsearch_strptr_overread(std_input_missing_geno, orig_alleles_sorted, cur_allele_ct) != -1)) {
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-alleles file results in a missing allele code in a multiallelic variant.\n", line_idx);
goto UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW;
}
}
++hit_ct;
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto UpdateVarAlleles_ret_TSTREAM_FAIL;
}
*max_allele_slen_ptr = max_allele_slen;
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--update-alleles: %u variant%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
} else {
snprintf(g_logbuf, kLogbufSize, "--update-alleles: %u variant%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
}
logputsb();
if (err_ct) {
logprintfww("%" PRIuPTR " update failure%s logged to %s .\n", err_ct, (err_ct == 1)? "" : "s", outname);
}
BigstackEndSet(tmp_alloc_end);
}
while (0) {
UpdateVarAlleles_ret_NOMEM:
reterr = kPglRetNomem;
break;
UpdateVarAlleles_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
UpdateVarAlleles_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
UpdateVarAlleles_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-alleles file", &txs);
break;
UpdateVarAlleles_ret_MISSING_TOKENS:
logerrprintfww("Error: Line %" PRIuPTR " of --update-alleles file has fewer tokens than expected.\n", line_idx);
reterr = kPglRetMalformedInput;
break;
UpdateVarAlleles_ret_TOO_MANY_ALLELES:
logerrprintfww("Error: Line %" PRIuPTR " of --update-alleles file has too many alleles (this " PROG_NAME_STR " build is limited to %u).\n", line_idx, max_impl_input_allele_ct);
reterr = kPglRetNotYetSupported;
break;
UpdateVarAlleles_ret_DUPLICATE_ALLELE_CODE_AFTER_UPDATE:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-alleles file results in a duplicated allele code.\n", line_idx);
UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
reterr = kPglRetInconsistentInput;
break;
UpdateVarAlleles_ret_DUPLICATE_INPUT_ALLELE_CODE:
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate allele code on line %" PRIuPTR " of --update-alleles file.\n", line_idx);
UpdateVarAlleles_ret_MALFORMED_INPUT_WW:
WordWrapB(0);
logerrputsb();
reterr = kPglRetMalformedInput;
break;
}
fclose_cond(errfile);
CleanupTextStream2("--update-alleles file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr RecoverVarIds(const char* fname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const char* missing_varid, uint32_t raw_variant_ct, uint32_t variant_ct, RecoverVarIdsFlags flags, uint32_t max_thread_ct, char** variant_ids, uint32_t* max_variant_id_slen_ptr, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
char* alloc_end = R_CAST(char*, g_bigstack_end);
uintptr_t line_idx = 0;
FILE* errfile = nullptr;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
// Significant overlap with UpdateVarNames().
const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct;
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
char** variant_ids_copy;
uintptr_t* chr_already_seen;
uintptr_t* already_seen;
uintptr_t* conflict_bitarr;
char** orig_alt_starts = nullptr; // spurious g++ 4.8 warning
if (unlikely(bigstack_alloc_cp(raw_variant_ct, &variant_ids_copy) ||
bigstack_calloc_w(BitCtToWordCt(chr_code_end), &chr_already_seen) ||
bigstack_calloc_w(raw_variant_ctl, &already_seen) ||
bigstack_calloc_w(raw_variant_ctl, &conflict_bitarr) ||
bigstack_alloc_cp(kPglMaxAltAlleleCt, &orig_alt_starts))) {
goto RecoverVarIds_ret_NOMEM;
}
// need this to be able to write original variant IDs in conflict case
memcpy(variant_ids_copy, variant_ids, raw_variant_ct * sizeof(intptr_t));
reterr = SizeAndInitTextStream(fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto RecoverVarIds_ret_TSTREAM_FAIL;
}
char* line_start;
do {
++line_idx;
line_start = TextGet(&txs);
if (unlikely(!line_start)) {
if (!TextStreamErrcode2(&txs, &reterr)) {
logerrputs("Error: Empty --recover-var-ids file.\n");
goto RecoverVarIds_ret_MALFORMED_INPUT;
}
goto RecoverVarIds_ret_TSTREAM_FAIL;
}
} while ((*line_start == '#') && (!tokequal_k(line_start, "#CHROM")));
// simplified copy of plink2_pvar code, probably want to write a library
// function for this
uint32_t col_skips[4];
uint32_t col_types[4];
uint32_t strict_allele_order = 1;
const uint32_t is_bim = !(line_start[0] == '#');
char* line_iter = nullptr;
if (!is_bim) {
// parse header
// [-1] = #CHROM (must be first column)
// [0] = POS
// [1] = ID
// [2] = REF
// [3] = ALT
char* token_end = &(line_start[6]);
uint32_t found_header_bitset = 0;
uint32_t relevant_postchr_col_ct = 0;
char* linebuf_iter;
for (uint32_t col_idx = 1; ; ++col_idx) {
linebuf_iter = FirstNonTspace(token_end);
if (IsEolnKns(*linebuf_iter)) {
break;
}
token_end = CurTokenEnd(linebuf_iter);
const uint32_t token_slen = token_end - linebuf_iter;
uint32_t cur_col_type;
if (token_slen == 3) {
if (memequal_sk(linebuf_iter, "POS")) {
cur_col_type = 0;
} else if (memequal_sk(linebuf_iter, "REF")) {
cur_col_type = 2;
} else if (memequal_sk(linebuf_iter, "ALT")) {
cur_col_type = 3;
} else {
continue;
}
} else if (token_slen == 2) {
if (memequal_sk(linebuf_iter, "ID")) {
cur_col_type = 1;
} else {
continue;
}
} else {
continue;
}
const uint32_t cur_col_type_shifted = 1 << cur_col_type;
if (unlikely(found_header_bitset & cur_col_type_shifted)) {
// known token, so no overflow danger
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '");
write_iter = memcpya(write_iter, linebuf_iter, token_slen);
write_iter = strcpya_k(write_iter, "' on line ");
write_iter = wtoa(line_idx, write_iter);
strcpy_k(write_iter, " of --recover-var-ids file.\n");
goto RecoverVarIds_ret_MALFORMED_INPUT_WW;
}
found_header_bitset |= cur_col_type_shifted;
col_skips[relevant_postchr_col_ct] = col_idx;
col_types[relevant_postchr_col_ct++] = cur_col_type;
}
if (unlikely(relevant_postchr_col_ct != 4)) {
snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of --recover-var-ids file. (POS, ID, REF, and ALT are required.)\n", line_idx);
goto RecoverVarIds_ret_MALFORMED_INPUT_WW;
}
for (uint32_t rpc_col_idx = 3; rpc_col_idx; --rpc_col_idx) {
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1];
}
line_iter = AdvPastDelim(linebuf_iter, '\n');
} else {
// .bim. Interpret as #CHROM ID POS ALT REF if there are exactly 5
// columns, otherwise #CHROM ID CM POS ALT REF.
col_skips[0] = 1;
col_skips[2] = 1;
col_skips[3] = 1;
col_types[0] = 1;
col_types[1] = 0;
col_types[2] = 3;
col_types[3] = 2;
char* linebuf_iter = NextTokenMult(line_start, 4);
if (unlikely(!linebuf_iter)) {
goto RecoverVarIds_ret_MISSING_TOKENS;
}
linebuf_iter = NextToken(linebuf_iter);
if (!linebuf_iter) {
col_skips[1] = 1;
} else {
col_skips[1] = 2;
}
strict_allele_order = (flags / kfRecoverVarIdsStrictBimOrder) & 1;
line_iter = line_start;
--line_idx;
}
// Only nonzero if we're actually replacing existing IDs with the missing
// ID in the conflict case.
uint32_t missing_varid_blen = 0;
if (flags & kfRecoverVarIdsForce) {
if (!missing_varid) {
missing_varid = &(g_one_char_strs[92]); // '.'
}
missing_varid_blen = 1 + strlen(missing_varid);
}
const uint32_t is_rigid = (flags / kfRecoverVarIdsRigid) & 1;
uint32_t max_variant_id_slen = *max_variant_id_slen_ptr;
char* alloc_base = R_CAST(char*, g_bigstack_base);
uint32_t is_unsorted = 0;
uint32_t prev_chr = UINT32_MAX;
uint32_t prev_chr_vidx_end = 0;
uint32_t prev_chr_vidx_start = 0;
uint32_t prev_bp = 0;
uint32_t prev_vidx_start = 0;
uint32_t prev_vidx_end = 0;
uint32_t rm_dup_warning = 0;
uintptr_t record_uidx = ~k0LU; // deliberate overflow
uint32_t cur_allele_ct = 2;
for (; TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n')) {
if ((!(line_idx % 1000000)) && line_idx) {
printf("\r--recover-var-ids: %" PRIuPTR "m lines scanned.", line_idx / 1000000);
fflush(stdout);
}
++line_idx;
line_start = line_iter;
if (unlikely(line_start[0] == '#')) {
putc_unlocked('\n', stdout);
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --recover-var-ids file starts with a '#'. (This is only permitted before the first nonheader line, and if a #CHROM header line is present it must denote the end of the header block.)\n", line_idx);
goto RecoverVarIds_ret_MALFORMED_INPUT_WW;
}
++record_uidx;
line_iter = CurTokenEnd(line_start);
uint32_t cur_chr_code = GetChrCodeCounted(cip, line_iter - line_start, line_start);
if (IsI32Neg(cur_chr_code)) {
continue;
}
// Could add some special handling of chrX/PAR1/PAR2(/XY?) later, if
// that proves to be a pain point; this does operate on VCF input,
// after all. It's a bit annoying to implement, though, so I'm
// excluding it from the first version.
if (cur_chr_code == prev_chr) {
if (!prev_chr_vidx_end) {
continue;
}
} else {
prev_chr = cur_chr_code;
if (!is_unsorted) {
if (IsSet(chr_already_seen, cur_chr_code)) {
is_unsorted = 1;
} else {
SetBit(cur_chr_code, chr_already_seen);
prev_bp = 0;
}
}
if (!IsSet(cip->chr_mask, cur_chr_code)) {
prev_chr_vidx_end = 0;
continue;
}
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[cur_chr_code];
prev_chr_vidx_start = cip->chr_fo_vidx_start[chr_fo_idx];
prev_chr_vidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
prev_vidx_start = prev_chr_vidx_start;
prev_vidx_end = prev_chr_vidx_start;
}
char* token_ptrs[4];
uint32_t token_slens[4];
line_iter = TokenLex(line_iter, col_types, col_skips, 4, token_ptrs, token_slens);
if (unlikely(!line_iter)) {
putc_unlocked('\n', stdout);
goto RecoverVarIds_ret_MISSING_TOKENS;
}
// Usually, everything is sorted by position, so we use exponential
// search over binary search unless we've detected unsorted data.
int32_t cur_bp_signed;
if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp_signed))) {
putc_unlocked('\n', stdout);
snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of --recover-var-ids file.\n", line_idx);
goto RecoverVarIds_ret_MALFORMED_INPUT_WW;
}
if (cur_bp_signed < 0) {
continue;
}
const uint32_t cur_bp = cur_bp_signed;
if (cur_bp < prev_bp) {
is_unsorted = 1;
}
if (!is_unsorted) {
if (is_rigid || (cur_bp > prev_bp)) {
const uint32_t arr_length = prev_chr_vidx_end - prev_vidx_end;
const uint32_t incr = Expsearch0U32(&(variant_bps[prev_vidx_end]), arr_length, cur_bp);
if (incr == arr_length) {
prev_vidx_end = prev_chr_vidx_end;
continue;
}
prev_vidx_start = incr + prev_vidx_end;
}
prev_bp = cur_bp;
} else {
const uint32_t arr_length = prev_chr_vidx_end - prev_chr_vidx_start;
const uint32_t incr = LowerBoundNonemptyU32(&(variant_bps[prev_chr_vidx_start]), arr_length, cur_bp);
if (incr == arr_length) {
continue;
}
prev_vidx_start = incr + prev_chr_vidx_start;
}
prev_vidx_start = AdvBoundedTo1Bit(variant_include, prev_vidx_start, prev_chr_vidx_end);
// variant_bps[prev_vidx_start] is the first element >= cur_bp that
// hasn't been filtered out.
if (variant_bps[prev_vidx_start] != cur_bp) {
prev_vidx_end = prev_vidx_start;
continue;
}
if (is_rigid) {
if (unlikely(record_uidx >= raw_variant_ct)) {
putc_unlocked('\n', stdout);
logerrputs("Error: \"--recover-var-ids rigid\" file does not match the main dataset.\n");
goto RecoverVarIds_ret_INCONSISTENT_INPUT;
}
if (!IsSet(variant_include, record_uidx)) {
continue;
}
if (record_uidx != prev_vidx_start) {
putc_unlocked('\n', stdout);
logerrputs("Error: \"--recover-var-ids rigid\" file does not match the main dataset.\n");
goto RecoverVarIds_ret_INCONSISTENT_INPUT;
}
}
char* orig_alt_start = token_ptrs[3];
const uint32_t orig_alt_slen = token_slens[3];
const uint32_t extra_orig_alt_ct = CountByte(orig_alt_start, ',', orig_alt_slen);
if (unlikely(extra_orig_alt_ct && is_bim)) {
// probably want to enforce this in main .pvar loader too...
putc_unlocked('\n', stdout);
snprintf(g_logbuf, kLogbufSize, "Error: Multiple ALT alleles on line %" PRIuPTR " of headerless --recover-var-ids file.\n", line_idx);
goto RecoverVarIds_ret_MALFORMED_INPUT_WW;
}
// Null-terminate all allele codes so we can use strequal_overread();
// and make sure to reset the final null terminator so that unsafe
// line_iter advancement works.
const char line_iter_char = *line_iter;
char* orig_ref_start = token_ptrs[2];
orig_ref_start[token_slens[2]] = '\0';
{
char* orig_alt_iter = orig_alt_start;
for (uint32_t alt_idx = 0; alt_idx != extra_orig_alt_ct; ++alt_idx) {
orig_alt_starts[alt_idx] = orig_alt_iter;
orig_alt_iter = AdvToDelim(orig_alt_iter, ',');
*orig_alt_iter++ = '\0';
}
orig_alt_starts[extra_orig_alt_ct] = orig_alt_iter;
}
char* orig_alt_end = &(orig_alt_start[orig_alt_slen]);
*orig_alt_end = '\0';
const uint32_t orig_alt_ct = extra_orig_alt_ct + 1;
uint32_t cur_vidx = prev_vidx_start;
// Multiple variants in the current dataset may have this position;
// check them all for allele-code concordance. If there are multiple
// matches, allow this but print a warning suggesting --rm-dup. In the
// usual subcase where there are multiple instances in the original
// file, we'll error out instead unless 'force' was specified.
uint32_t already_matched = 0;
goto RecoverVarIds_first_iter;
for (; (!is_rigid) && (cur_vidx != prev_chr_vidx_end) && (variant_bps[cur_vidx] == cur_bp); cur_vidx = AdvBoundedTo1Bit(variant_include, cur_vidx + 1, prev_chr_vidx_end)) {
RecoverVarIds_first_iter: ;
uintptr_t allele_idx_offset_base = cur_vidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[cur_vidx];
cur_allele_ct = allele_idx_offsets[cur_vidx + 1] - allele_idx_offset_base;
}
if (cur_allele_ct != orig_alt_ct + 1) {
continue;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
const char* ref_allele = cur_alleles[0];
if (strict_allele_order) {
if (!strequal_overread(ref_allele, orig_ref_start)) {
continue;
}
const char* const* cur_alt_alleles = &(cur_alleles[1]);
uint32_t alt_idx = 0;
for (; alt_idx != orig_alt_ct; ++alt_idx) {
if (!strequal_overread(cur_alt_alleles[alt_idx], orig_alt_starts[alt_idx])) {
break;
}
}
if (alt_idx != orig_alt_ct) {
continue;
}
} else {
// cur_allele_ct == 2 guaranteed.
const char* other_allele = cur_alleles[1];
if (!strequal_overread(ref_allele, orig_ref_start)) {
if ((!strequal_overread(ref_allele, orig_alt_start)) || (!strequal_overread(other_allele, orig_ref_start))) {
continue;
}
} else if (!strequal_overread(other_allele, orig_alt_start)) {
continue;
}
}
char* old_id = variant_ids[cur_vidx];
const uint32_t old_id_slen = strlen(old_id);
const char* new_id = token_ptrs[1];
const uint32_t new_id_slen = token_slens[1];
if (IsSet(already_seen, cur_vidx)) {
if ((new_id_slen != old_id_slen) || (!memequal(new_id, old_id, old_id_slen))) {
SetBit(cur_vidx, conflict_bitarr);
rm_dup_warning = 1;
}
continue;
}
// Okay, chr/pos/alleles match, and there's no conflict with a
// previous entry. Update the variant ID.
SetBit(cur_vidx, already_seen);
if (new_id_slen <= old_id_slen) {
const uint32_t old_id_blen = old_id_slen + 1;
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < old_id_blen)) {
goto RecoverVarIds_ret_NOMEM;
}
memcpy(alloc_base, old_id, old_id_blen);
variant_ids_copy[cur_vidx] = alloc_base;
alloc_base = &(alloc_base[old_id_blen]);
memcpyx(old_id, new_id, new_id_slen, '\0');
} else {
if (new_id_slen > max_variant_id_slen) {
max_variant_id_slen = new_id_slen;
}
const uint32_t new_id_blen = new_id_slen + 1;
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < new_id_blen)) {
goto RecoverVarIds_ret_NOMEM;
}
alloc_end -= new_id_blen;
memcpyx(alloc_end, new_id, new_id_slen, '\0');
variant_ids[cur_vidx] = alloc_end;
}
rm_dup_warning |= already_matched;
already_matched = 1;
}
*line_iter = line_iter_char;
prev_vidx_end = cur_vidx;
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto RecoverVarIds_ret_TSTREAM_FAIL;
}
putc_unlocked('\r', stdout);
logprintf("--recover-var-ids: %" PRIuPTR " line%s scanned.\n", line_idx, (line_idx == 1)? "" : "s");
const uint32_t conflict_ct = PopcountWords(conflict_bitarr, raw_variant_ctl);
if (conflict_ct) {
strcpy_k(outname_end, ".recoverid.dup");
if (fopen_checked(outname, FOPEN_WB, &errfile)) {
goto RecoverVarIds_ret_OPEN_FAIL;
}
// Simply a list of affected variant IDs, one per line, sorted
// in order of original-file appearance.
// The reported variant IDs will usually be duplicated, since
// --set-all-var-ids makes them a function of CHROM/POS/REF/ALT, and
// that's what old-variant-ID recovery is based on. (But one could e.g.
// set the IDs to zero-based indexes before calling --recover-var-ids, if
// they wanted every .recoverid.dup entry to be unambiguous.)
char* textbuf = g_textbuf;
char* textbuf_flush = &(textbuf[kMaxMediumLine]);
char* write_iter = textbuf;
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = conflict_bitarr[0];
for (uint32_t conflict_idx = 0; conflict_idx != conflict_ct; ++conflict_idx) {
const uint32_t variant_uidx = BitIter1(conflict_bitarr, &variant_uidx_base, &cur_bits);
write_iter = strcpya(write_iter, variant_ids_copy[variant_uidx]);
AppendBinaryEoln(&write_iter);
if (unlikely(fwrite_ck(textbuf_flush, errfile, &write_iter))) {
goto RecoverVarIds_ret_WRITE_FAIL;
}
if (missing_varid_blen) {
char* cur_id = variant_ids[variant_uidx];
const uint32_t cur_id_slen = strlen(cur_id);
if (missing_varid_blen <= cur_id_slen + 1) {
memcpy(cur_id, missing_varid, missing_varid_blen);
} else {
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < missing_varid_blen)) {
goto RecoverVarIds_ret_NOMEM;
}
alloc_end -= missing_varid_blen;
memcpy(alloc_end, missing_varid, missing_varid_blen);
variant_ids[variant_uidx] = alloc_end;
}
}
}
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &errfile))) {
goto RecoverVarIds_ret_WRITE_FAIL;
}
if (!missing_varid_blen) {
// not really unlikely, conditional on being in this branch...
snprintf(g_logbuf, kLogbufSize, "Error: %u variant%s had conflicting matching-position-and-alleles records in the --recover-var-ids file; affected ID%s been written to %s . (Add the 'force' modifier if you just want to set %s to the missing code.)\n", conflict_ct, (conflict_ct == 1)? "" : "s", (conflict_ct == 1)? "" : "s", outname, (conflict_ct == 1)? "it" : "them");
goto RecoverVarIds_ret_INCONSISTENT_INPUT_WW;
}
logerrprintfww("Warning: %u variant ID%s set to '%s' by \"--recover-var-ids force\". Previous ID%s been written to %s .\n", conflict_ct, (conflict_ct == 1)? "" : "s", missing_varid, (conflict_ct == 1)? " has" : "s have", outname);
}
const uint32_t update_ct = PopcountWords(already_seen, raw_variant_ctl);
const uint32_t unupdated_ct = variant_ct - update_ct;
if (unupdated_ct && (!(flags & kfRecoverVarIdsPartial))) {
snprintf(g_logbuf, kLogbufSize, "Error: %u/%u variant%s had no matching-position-and-alleles records in the --recover-var-ids file. (Add the 'partial' modifier when this is expected.)\n", unupdated_ct, variant_ct, (unupdated_ct == 1)? "" : "s");
goto RecoverVarIds_ret_INCONSISTENT_INPUT_WW;
}
logprintf("--recover-var-ids: %u/%u ID%s updated.\n", update_ct, variant_ct, (update_ct == 1)? "" : "s");
if (rm_dup_warning) {
logerrputs("Warning: Some variants had identical positions and alleles, and therefore were\nassigned the same ID. Consider deduplicating your data with --rm-dup.\n");
}
*max_variant_id_slen_ptr = max_variant_id_slen;
}
while (0) {
RecoverVarIds_ret_NOMEM:
reterr = kPglRetNomem;
break;
RecoverVarIds_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
RecoverVarIds_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
RecoverVarIds_ret_TSTREAM_FAIL:
putc_unlocked('\n', stdout);
TextStreamErrPrint("--recover-var-ids file", &txs);
break;
RecoverVarIds_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --recover-var-ids file has fewer tokens than expected.\n", line_idx);
RecoverVarIds_ret_MALFORMED_INPUT_WW:
WordWrapB(0);
logerrputsb();
RecoverVarIds_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
RecoverVarIds_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
RecoverVarIds_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
CleanupTextStream2("--recover-var-ids file", &txs, &reterr);
fclose_cond(errfile);
// doesn't hurt to ensure all replaced variant_ids[] entries are valid in the
// error case...
BigstackEndSet(alloc_end);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr Plink1ClusterImport(const char* within_fname, const char* catpheno_name, const char* family_missing_catname, const uintptr_t* sample_include, const char* sample_ids, const char* missing_catname, uint32_t raw_sample_ct, uint32_t sample_ct, uintptr_t max_sample_id_blen, uint32_t mwithin_val, uint32_t max_thread_ct, PhenoCol** pheno_cols_ptr, char** pheno_names_ptr, uint32_t* pheno_ct_ptr, uintptr_t* max_pheno_name_blen_ptr) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream within_txs;
PreinitTextStream(&within_txs);
{
if (!sample_ct) {
goto Plink1ClusterImport_ret_1;
}
const char catpheno_name_default[] = "CATPHENO";
uint32_t catpheno_name_blen;
if (!catpheno_name) {
catpheno_name = catpheno_name_default;
catpheno_name_blen = 9;
} else {
catpheno_name_blen = 1 + strlen(catpheno_name);
}
const uintptr_t old_max_pheno_name_blen = *max_pheno_name_blen_ptr;
const uint32_t old_pheno_ct = *pheno_ct_ptr;
const char* old_pheno_names = *pheno_names_ptr;
uintptr_t new_max_pheno_name_blen;
if (old_pheno_names && (catpheno_name_blen <= old_max_pheno_name_blen)) {
new_max_pheno_name_blen = old_max_pheno_name_blen;
for (uint32_t pheno_idx = 0; pheno_idx != old_pheno_ct; ++pheno_idx) {
if (unlikely(memequal(catpheno_name, &(old_pheno_names[pheno_idx * old_max_pheno_name_blen]), catpheno_name_blen))) {
snprintf(g_logbuf, kLogbufSize, "Error: Cannot create a new categorical phenotype named '%s', since another phenotype of the same name already exists.\n", catpheno_name);
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT_WW;
}
}
} else {
new_max_pheno_name_blen = catpheno_name_blen;
}
const uint32_t new_pheno_ct = old_pheno_ct + 1;
uintptr_t new_pheno_names_byte_ct = new_pheno_ct * new_max_pheno_name_blen;
char* pheno_names;
if (unlikely(pgl_malloc(new_pheno_names_byte_ct, &pheno_names))) {
goto Plink1ClusterImport_ret_NOMEM;
}
if (old_pheno_names && (old_max_pheno_name_blen == new_max_pheno_name_blen)) {
memcpy(pheno_names, old_pheno_names, old_pheno_ct * new_max_pheno_name_blen);
} else {
for (uint32_t pheno_idx = 0; pheno_idx != old_pheno_ct; ++pheno_idx) {
strcpy(&(pheno_names[pheno_idx * new_max_pheno_name_blen]), &(old_pheno_names[pheno_idx * old_max_pheno_name_blen]));
}
}
memcpy(&(pheno_names[old_pheno_ct * new_max_pheno_name_blen]), catpheno_name, catpheno_name_blen);
free_cond(old_pheno_names);
*pheno_names_ptr = pheno_names;
PhenoCol* new_pheno_cols = S_CAST(PhenoCol*, realloc(*pheno_cols_ptr, new_pheno_ct * sizeof(PhenoCol)));
if (unlikely(!new_pheno_cols)) {
goto Plink1ClusterImport_ret_NOMEM;
}
*pheno_cols_ptr = new_pheno_cols;
*pheno_ct_ptr = new_pheno_ct;
*max_pheno_name_blen_ptr = new_max_pheno_name_blen;
new_pheno_cols[old_pheno_ct].nonmiss = nullptr;
new_pheno_cols[old_pheno_ct].type_code = S_CAST(PhenoDtype, kPhenoDtypeCat);
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
uintptr_t* cat_nm = nullptr;
uint32_t* cat_idxs = nullptr;
if (!within_fname) {
if (unlikely(bigstack_alloc_w(raw_sample_ctaw, &cat_nm) ||
bigstack_calloc_u32(raw_sample_ct, &cat_idxs))) {
goto Plink1ClusterImport_ret_NOMEM;
}
memcpy(cat_nm, sample_include, raw_sample_ctaw * sizeof(intptr_t));
}
uint32_t* cat_htable;
uint32_t cat_htable_size;
if (unlikely(HtableGoodSizeAlloc(sample_ct + 2, bigstack_left() / 4, &cat_htable, &cat_htable_size))) {
goto Plink1ClusterImport_ret_NOMEM;
}
SetAllU32Arr(cat_htable_size, cat_htable);
const uintptr_t data_vec_ct = Int32CtToVecCt(raw_sample_ct);
const uint32_t missing_catname_slen = strlen(missing_catname);
const uint32_t missing_catname_hval = Hashceil(missing_catname, missing_catname_slen, cat_htable_size);
if (within_fname) {
uintptr_t* already_seen;
uint32_t* sorted_cat_idxs;
char* idbuf;
const char** cur_cat_names;
if (unlikely(bigstack_calloc_w(BitCtToWordCt(sample_ct), &already_seen) ||
bigstack_calloc_u32(sample_ct, &sorted_cat_idxs) ||
bigstack_alloc_c(max_sample_id_blen, &idbuf) ||
bigstack_alloc_kcp(sample_ct + 2, &cur_cat_names))) {
goto Plink1ClusterImport_ret_NOMEM;
}
cat_htable[missing_catname_hval] = 0;
cur_cat_names[0] = missing_catname;
const char na_str[] = "NA";
uint32_t na_hashval = Hashceil(na_str, 2, cat_htable_size);
if (na_hashval == missing_catname_hval) {
if (++na_hashval == cat_htable_size) {
na_hashval = 0;
}
}
cat_htable[na_hashval] = sample_ct + 1;
cur_cat_names[sample_ct + 1] = na_str;
uint32_t* id_map;
char* sorted_idbox;
if (unlikely(CopySortStrboxSubset(sample_include, sample_ids, sample_ct, max_sample_id_blen, 0, 0, &sorted_idbox, &id_map))) {
goto Plink1ClusterImport_ret_NOMEM;
}
reterr = SizeAndInitTextStream(within_fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &within_txs);
if (unlikely(reterr)) {
goto Plink1ClusterImport_ret_TSTREAM_FAIL;
}
char* cat_name_write_start = R_CAST(char*, g_bigstack_base);
char* cat_name_iter = cat_name_write_start;
char* cat_name_write_max = R_CAST(char*, BigstackEndRoundedDown());
uint32_t nonnull_cat_ct = 0;
uintptr_t miss_ct = 0;
uintptr_t duplicate_ct = 0;
for (char* line_iter = &(TextLineEnd(&within_txs)[-1]); ; line_iter = AdvToDelim(line_iter, '\n')) {
// need this since we may clobber \n
Plink1ClusterImport_LINE_ITER_ALREADY_ADVANCED:
++line_iter;
++line_idx;
if (!TextGetUnsafe2(&within_txs, &line_iter)) {
if (likely(!TextStreamErrcode2(&within_txs, &reterr))) {
break;
}
goto Plink1ClusterImport_ret_TSTREAM_FAIL;
}
char* fid_start = line_iter;
char* fid_end = CurTokenEnd(fid_start);
char* iid_start = FirstNonTspace(fid_end);
if (unlikely(IsEolnKns(*iid_start))) {
goto Plink1ClusterImport_ret_MISSING_TOKENS;
}
char* iid_end = CurTokenEnd(iid_start);
const uint32_t fid_slen = fid_end - fid_start;
const uint32_t iid_slen = iid_end - iid_start;
const uint32_t id_blen = fid_slen + iid_slen + 2;
if (id_blen > max_sample_id_blen) {
++miss_ct;
line_iter = iid_end;
continue;
}
char* idbuf_iter = memcpyax(idbuf, fid_start, fid_slen, '\t');
idbuf_iter = memcpya(idbuf_iter, iid_start, iid_slen);
*idbuf_iter = '\0';
uint32_t lb_idx = bsearch_strbox_lb(idbuf, sorted_idbox, id_blen, max_sample_id_blen, sample_ct);
*idbuf_iter = ' ';
const uint32_t ub_idx = bsearch_strbox_lb(idbuf, sorted_idbox, id_blen, max_sample_id_blen, sample_ct);
if (ub_idx == lb_idx) {
++miss_ct;
line_iter = iid_end;
continue;
}
char* main_token_start = NextTokenMult(iid_end, mwithin_val);
if (unlikely(!main_token_start)) {
goto Plink1ClusterImport_ret_MISSING_TOKENS;
}
char* main_token_end = CurTokenEnd(main_token_start);
line_iter = AdvToDelim(line_iter, '\n');
*main_token_end = '\0';
const uint32_t main_token_slen = main_token_end - main_token_start;
if (unlikely(main_token_slen > kMaxIdSlen)) {
logerrputs("Error: Category names are limited to " MAX_ID_SLEN_STR " characters.\n");
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
uint32_t cur_cat_idx = IdHtableAdd(main_token_start, cur_cat_names, main_token_slen, cat_htable_size, nonnull_cat_ct + 1, cat_htable);
if (cur_cat_idx == UINT32_MAX) {
if (unlikely(main_token_slen >= S_CAST(uintptr_t, cat_name_write_max - cat_name_iter))) {
goto Plink1ClusterImport_ret_NOMEM;
}
char* cat_name_start = cat_name_iter;
cat_name_iter = memcpya(cat_name_iter, main_token_start, main_token_slen + 1);
// bugfix (5 May 2021): dropped this increment in mid-Jan refactor
++nonnull_cat_ct;
cur_cat_idx = nonnull_cat_ct;
cur_cat_names[cur_cat_idx] = cat_name_start;
}
// permit duplicates if category is identical
if (IsSet(already_seen, lb_idx)) {
const uint32_t existing_cat_idx = sorted_cat_idxs[lb_idx];
if (unlikely(existing_cat_idx != cur_cat_idx)) {
idbuf[fid_slen] = ' ';
logpreprintfww("Error: Duplicate sample ID \"%s\" with conflicting category assignments in --within file.\n", idbuf);
goto Plink1ClusterImport_ret_MALFORMED_INPUT_2;
}
++duplicate_ct;
} else {
SetBit(lb_idx, already_seen);
for (; lb_idx != ub_idx; ++lb_idx) {
sorted_cat_idxs[lb_idx] = cur_cat_idx;
}
}
goto Plink1ClusterImport_LINE_ITER_ALREADY_ADVANCED;
}
if (unlikely(!nonnull_cat_ct)) {
if (line_idx == miss_ct + 1) {
// could be fancy and only print the last part of this message if
// all FIDs are 0
logerrputs("Error: No sample IDs in --within file are in the main dataset. Compare it with\nyour .fam/.psam file; note that if the latter has no FID column at all, that\ncorresponds to FIDs of '0', not FIDs equal to the IIDs.\n");
} else {
logerrputs("Error: All --within categories are null.\n");
}
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
double dxx;
const uint32_t prepend_c = (ScanadvDouble(cur_cat_names[1], &dxx) != nullptr);
if (prepend_c) {
for (uint32_t catname_idx = 2; catname_idx <= nonnull_cat_ct; ++catname_idx) {
if (unlikely(!ScanadvDouble(cur_cat_names[catname_idx], &dxx))) {
logerrputs("Error: Either all non-null --within categories must be numeric, or none can be.\n");
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
}
logputs("Note: Prepending 'C' to all --within category names.\n");
} else {
for (uint32_t catname_idx = 2; catname_idx <= nonnull_cat_ct; ++catname_idx) {
if (unlikely(ScanadvDouble(cur_cat_names[catname_idx], &dxx))) {
logerrputs("Error: Either all non-null --within categories must be numeric, or none can be.\n");
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
}
}
// see end of e.g. LoadPsam()
BigstackBaseSet(cat_name_write_start);
uint32_t* old_cat_idxs_to_new;
if (unlikely(bigstack_alloc_u32(nonnull_cat_ct + 1, &old_cat_idxs_to_new))) {
goto Plink1ClusterImport_ret_NOMEM;
}
const uintptr_t catname_vec_ct = WordCtToVecCt(nonnull_cat_ct + 1);
const uintptr_t total_catname_blen = (prepend_c * nonnull_cat_ct) + S_CAST(uintptr_t, cat_name_iter - cat_name_write_start);
const uintptr_t catname_storage_vec_ct = DivUp(total_catname_blen, kBytesPerVec);
if (unlikely(vecaligned_malloc((raw_sample_ctaw * kWordsPerVec + data_vec_ct + catname_vec_ct + catname_storage_vec_ct) * kBytesPerVec, &(new_pheno_cols[old_pheno_ct].nonmiss)))) {
goto Plink1ClusterImport_ret_NOMEM;
}
new_pheno_cols[old_pheno_ct].nonnull_category_ct = nonnull_cat_ct;
uintptr_t* catdata_iter = new_pheno_cols[old_pheno_ct].nonmiss;
cat_nm = catdata_iter;
ZeroWArr(raw_sample_ctaw, cat_nm);
catdata_iter = &(catdata_iter[raw_sample_ctaw]);
cat_idxs = R_CAST(uint32_t*, catdata_iter);
ZeroU32Arr(raw_sample_ct, cat_idxs);
new_pheno_cols[old_pheno_ct].data.cat = cat_idxs;
catdata_iter = &(catdata_iter[data_vec_ct * kWordsPerVec]);
const char** cur_name_ptrs = R_CAST(const char**, catdata_iter);
new_pheno_cols[old_pheno_ct].category_names = cur_name_ptrs;
*cur_name_ptrs++ = missing_catname;
char* name_storage_iter = R_CAST(char*, &(catdata_iter[catname_vec_ct * kWordsPerVec]));
cat_name_iter = cat_name_write_start;
for (uint32_t uii = 0; uii != nonnull_cat_ct; ++uii) {
char* cur_name_start = name_storage_iter;
if (prepend_c) {
*name_storage_iter++ = 'C';
}
const uint32_t cur_catname_blen = 1 + strlen(cat_name_iter);
name_storage_iter = memcpya(name_storage_iter, cat_name_iter, cur_catname_blen);
*cur_name_ptrs++ = cur_name_start;
cat_name_iter = &(cat_name_iter[cur_catname_blen]);
}
if (unlikely(SortStrptrArrIndexed(nonnull_cat_ct + 1, 1, 0, 1, new_pheno_cols[old_pheno_ct].category_names, nullptr, old_cat_idxs_to_new))) {
goto Plink1ClusterImport_ret_NOMEM;
}
for (uint32_t sorted_sample_idx = 0; sorted_sample_idx != sample_ct; ++sorted_sample_idx) {
const uint32_t cur_sample_uidx = id_map[sorted_sample_idx];
uint32_t cur_cat_idx = sorted_cat_idxs[sorted_sample_idx];
if (cur_cat_idx > sample_ct) {
cur_cat_idx = 0;
}
if (cur_cat_idx) {
SetBit(cur_sample_uidx, cat_nm);
}
cat_idxs[cur_sample_uidx] = old_cat_idxs_to_new[cur_cat_idx];
}
if (duplicate_ct) {
logprintfww("Note: %" PRIuPTR " duplicate sample ID%s) in --within file.\n", duplicate_ct, (duplicate_ct == 1)? " (with a consistent category assignment" : "s (with consistent category assignments");
}
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--within: %u non-null categor%s present, %" PRIuPTR " sample ID%s skipped.\n", nonnull_cat_ct, (nonnull_cat_ct == 1)? "y" : "ies", miss_ct, (miss_ct == 1)? "" : "s");
WordWrapB(0);
} else {
snprintf(g_logbuf, kLogbufSize, "--within: %u non-null categor%s present.\n", nonnull_cat_ct, (nonnull_cat_ct == 1)? "y" : "ies");
}
logputsb();
} else {
// --family
cat_htable[missing_catname_hval] = 0xfffffffdU;
uintptr_t total_catname_blen = 0; // does not need to include 'NONE'
uint32_t family_missing_catname_slen = 0;
if (family_missing_catname) {
family_missing_catname_slen = strlen(family_missing_catname);
uint32_t family_missing_catname_hval = Hashceil(family_missing_catname, family_missing_catname_slen, cat_htable_size);
if (cat_htable[family_missing_catname_hval] == UINT32_MAX) {
cat_htable[family_missing_catname_hval] = UINT32_MAXM1;
} else if ((missing_catname_slen != family_missing_catname_slen) || (!memequal(family_missing_catname, missing_catname, missing_catname_slen))) {
if (++family_missing_catname_hval == cat_htable_size) {
family_missing_catname_hval = 0;
}
cat_htable[family_missing_catname_hval] = UINT32_MAXM1;
}
}
// guaranteed to have enough space, otherwise HtableGoodSizeAlloc would
// have failed
uint32_t* cat_idx_m1_to_first_sample_uidx = R_CAST(uint32_t*, g_bigstack_base);
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
uint32_t nonnull_cat_ct = 0;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
const char* cur_fid = &(sample_ids[sample_uidx * max_sample_id_blen]);
const char* cur_fid_end = AdvToDelim(cur_fid, '\t');
const uint32_t slen = cur_fid_end - cur_fid;
const uint32_t blen = slen + 1;
for (uint32_t hashval = Hashceil(cur_fid, slen, cat_htable_size); ; ) {
const uint32_t cur_htable_entry = cat_htable[hashval];
if (cur_htable_entry >= 0xfffffffdU) {
if (cur_htable_entry == UINT32_MAX) {
cat_htable[hashval] = sample_uidx;
total_catname_blen += blen;
cat_idx_m1_to_first_sample_uidx[nonnull_cat_ct] = sample_uidx;
cat_idxs[sample_uidx] = ++nonnull_cat_ct;
break;
} else if (cur_htable_entry == UINT32_MAXM1) {
if ((slen == family_missing_catname_slen) && memequal(cur_fid, family_missing_catname, family_missing_catname_slen)) {
ClearBit(sample_uidx, cat_nm);
cat_idxs[sample_uidx] = 0;
break;
}
} else {
if ((slen == missing_catname_slen) && memequal(cur_fid, missing_catname, missing_catname_slen)) {
ClearBit(sample_uidx, cat_nm);
cat_idxs[sample_uidx] = 0;
break;
}
}
} else {
if (memequal(cur_fid, &(sample_ids[cur_htable_entry * max_sample_id_blen]), blen)) {
cat_idxs[sample_uidx] = cat_idxs[cur_htable_entry];
break;
}
}
if (++hashval == cat_htable_size) {
hashval = 0;
}
}
}
if (unlikely(!nonnull_cat_ct)) {
logerrputs("Error: All --family FIDs are null.\n");
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
// add 'C' prefixes?
double dxx;
const uint32_t prepend_c = (ScanadvDouble(&(sample_ids[cat_idx_m1_to_first_sample_uidx[0] * max_sample_id_blen]), &dxx) != nullptr);
if (prepend_c) {
for (uint32_t uii = 1; uii != nonnull_cat_ct; ++uii) {
if (unlikely(!ScanadvDouble(&(sample_ids[cat_idx_m1_to_first_sample_uidx[uii] * max_sample_id_blen]), &dxx))) {
logerrputs("Error: Either all non-null --family FIDs must be numeric, or none can be.\n");
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
}
logputs("Note: Prepending 'C' to all --family category names.\n");
total_catname_blen += nonnull_cat_ct;
} else {
for (uint32_t uii = 1; uii != nonnull_cat_ct; ++uii) {
if (unlikely(ScanadvDouble(&(sample_ids[cat_idx_m1_to_first_sample_uidx[uii] * max_sample_id_blen]), &dxx))) {
logerrputs("Error: Either all non-null --family FIDs must be numeric, or none can be.\n");
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT;
}
}
}
// see end of e.g. LoadPsam()
BigstackFinalizeU32(cat_idx_m1_to_first_sample_uidx, nonnull_cat_ct);
uint32_t* old_cat_idxs_to_new;
if (unlikely(bigstack_alloc_u32(nonnull_cat_ct + 1, &old_cat_idxs_to_new))) {
goto Plink1ClusterImport_ret_NOMEM;
}
const uintptr_t catname_vec_ct = WordCtToVecCt(nonnull_cat_ct + 1);
const uintptr_t catname_storage_vec_ct = DivUp(total_catname_blen, kBytesPerVec);
if (unlikely(vecaligned_malloc((raw_sample_ctaw * kWordsPerVec + data_vec_ct + catname_vec_ct + catname_storage_vec_ct) * kBytesPerVec, &(new_pheno_cols[old_pheno_ct].nonmiss)))) {
goto Plink1ClusterImport_ret_NOMEM;
}
new_pheno_cols[old_pheno_ct].nonnull_category_ct = nonnull_cat_ct;
uintptr_t* catdata_iter = new_pheno_cols[old_pheno_ct].nonmiss;
memcpy(catdata_iter, cat_nm, raw_sample_ctaw * sizeof(intptr_t));
catdata_iter = &(catdata_iter[raw_sample_ctaw]);
uint32_t* cat_idx_dst = R_CAST(uint32_t*, catdata_iter);
new_pheno_cols[old_pheno_ct].data.cat = cat_idx_dst;
catdata_iter = &(catdata_iter[data_vec_ct * kWordsPerVec]);
const char** cur_name_ptrs = R_CAST(const char**, catdata_iter);
new_pheno_cols[old_pheno_ct].category_names = cur_name_ptrs;
*cur_name_ptrs++ = missing_catname;
char* name_storage_iter = R_CAST(char*, &(catdata_iter[catname_vec_ct * kWordsPerVec]));
for (uint32_t uii = 0; uii != nonnull_cat_ct; ++uii) {
char* cur_name_start = name_storage_iter;
if (prepend_c) {
*name_storage_iter++ = 'C';
}
const char* cur_fid = &(sample_ids[cat_idx_m1_to_first_sample_uidx[uii] * max_sample_id_blen]);
const char* cur_fid_end = AdvToDelim(cur_fid, '\t');
name_storage_iter = memcpyax(name_storage_iter, cur_fid, cur_fid_end - cur_fid, '\0');
*cur_name_ptrs++ = cur_name_start;
}
if (unlikely(SortStrptrArrIndexed(nonnull_cat_ct + 1, 1, 0, 1, new_pheno_cols[old_pheno_ct].category_names, nullptr, old_cat_idxs_to_new))) {
goto Plink1ClusterImport_ret_NOMEM;
}
sample_uidx_base = 0;
cur_bits = sample_include[0];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
cat_idx_dst[sample_uidx] = old_cat_idxs_to_new[cat_idxs[sample_uidx]];
}
logprintf("--family: %u non-null categor%s present.\n", nonnull_cat_ct, (nonnull_cat_ct == 1)? "y" : "ies");
}
}
while (0) {
Plink1ClusterImport_ret_NOMEM:
reterr = kPglRetNomem;
break;
Plink1ClusterImport_ret_TSTREAM_FAIL:
TextStreamErrPrint("--within file", &within_txs);
break;
Plink1ClusterImport_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --within file has fewer tokens than expected.\n", line_idx);
Plink1ClusterImport_ret_MALFORMED_INPUT_2:
logerrputsb();
reterr = kPglRetMalformedInput;
break;
Plink1ClusterImport_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
Plink1ClusterImport_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
Plink1ClusterImport_ret_1:
CleanupTextStream2("--within file", &within_txs, &reterr);
BigstackReset(bigstack_mark);
if (reterr) {
if (*pheno_names_ptr) {
free(*pheno_names_ptr);
*pheno_names_ptr = nullptr;
}
CleanupPhenoCols(*pheno_ct_ptr, *pheno_cols_ptr);
*pheno_ct_ptr = 0;
*pheno_cols_ptr = nullptr;
}
return reterr;
}
PglErr PrescanSampleIds(const char* fname, SampleIdInfo* siip) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
reterr = ForceNonFifo(fname);
if (unlikely(reterr)) {
if (reterr == kPglRetOpenFail) {
logerrprintfww(kErrprintfFopen, "--update-ids file", strerror(errno));
} else {
logerrprintfww(kErrprintfRewind, "--update-ids file");
}
goto PrescanSampleIds_ret_1;
}
reterr = InitTextStream(fname, kTextStreamBlenFast, 1, &txs);
if (unlikely(reterr)) {
goto PrescanSampleIds_ret_TSTREAM_FAIL;
}
uint32_t is_header_line;
const char* line_iter;
do {
++line_idx;
line_iter = TextGet(&txs);
if (!line_iter) {
reterr = TextStreamRawErrcode(&txs);
if (likely(reterr == kPglRetEof)) {
// permit empty file here, but signal this to caller
// (reterr == kPglRetSuccess when file is nonempty, so we can detect
// rewind-fail)
goto PrescanSampleIds_ret_1;
}
goto PrescanSampleIds_ret_TSTREAM_FAIL;
}
is_header_line = (*line_iter == '#');
} while (is_header_line && (!tokequal_k(&(line_iter[1]), "OLD_FID")) && (!tokequal_k(&(line_iter[1]), "OLD_IID")));
uint32_t old_fid_present = 0;
uint32_t old_sid_present = 0;
uint32_t new_fid_present = 0;
uint32_t new_sid_present = 0;
if (is_header_line) {
if (line_iter[5] == 'F') {
old_fid_present = 1;
line_iter = FirstNonTspace(&(line_iter[8]));
if (unlikely(!tokequal_k(line_iter, "OLD_IID"))) {
logerrputs("Error: Invalid --update-ids file (second header column must be OLD_IID when\nfirst is #OLD_FID).\n");
goto PrescanSampleIds_ret_MALFORMED_INPUT;
}
}
line_iter = FirstNonTspace(CurTokenEnd(line_iter));
if (tokequal_k(line_iter, "OLD_SID")) {
old_sid_present = 1;
line_iter = FirstNonTspace(&(line_iter[7]));
}
if (tokequal_k(line_iter, "NEW_FID")) {
new_fid_present = 1;
line_iter = FirstNonTspace(&(line_iter[7]));
}
if (unlikely(!tokequal_k(line_iter, "NEW_IID"))) {
logerrputs("Error: Invalid --update-ids file (no NEW_IID column in expected position).\n");
goto PrescanSampleIds_ret_MALFORMED_INPUT;
}
line_iter = FirstNonTspace(&(line_iter[7]));
if (tokequal_k(line_iter, "NEW_SID")) {
new_sid_present = 1;
line_iter = FirstNonTspace(&(line_iter[7]));
}
if (unlikely(!IsSpaceOrEoln(*line_iter))) {
// Unlike --update-parents/--update-sex, there's no clear benefit to
// tolerating extra columns, so let's keep this simple.
logerrputs("Error: Invalid --update-ids file main header line (only permitted columns are\nOLD_FID, OLD_IID, OLD_SID, NEW_FID, NEW_IID, and NEW_SID, in that order).\n");
goto PrescanSampleIds_ret_MALFORMED_INPUT;
}
} else {
const uint32_t token_ct = CountTokens(line_iter);
if (token_ct == 4) {
old_fid_present = 1;
new_fid_present = 1;
} else if (unlikely(token_ct != 2)) {
logerrputs("Error: Invalid --update-ids file (with no #OLD_FID or #OLD_IID header line, 2\nor 4 columns expected).\n");
goto PrescanSampleIds_ret_MALFORMED_INPUT;
}
}
const uint32_t initial_skip_ct = 1 + old_fid_present + old_sid_present;
uintptr_t max_sample_id_blen = 0;
uintptr_t max_sid_blen = 0;
if (is_header_line) {
line_iter = AdvPastDelim(line_iter, '\n');
++line_idx;
}
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
line_iter = NextTokenMult(line_iter, initial_skip_ct);
if (unlikely(!line_iter)) {
goto PrescanSampleIds_ret_MISSING_TOKENS;
}
const char* id_start = line_iter;
line_iter = CurTokenEnd(id_start);
uintptr_t cur_sample_id_blen = 1 + S_CAST(uintptr_t, line_iter - id_start);
if (new_fid_present) {
const char* iid_start = FirstNonTspace(line_iter);
if (unlikely(IsEolnKns(*iid_start))) {
goto PrescanSampleIds_ret_MISSING_TOKENS;
}
line_iter = CurTokenEnd(iid_start);
cur_sample_id_blen += 1 + S_CAST(uintptr_t, line_iter - iid_start);
} else {
// bugfix (23 Sep 2020): forgot to add 2 for implicit FID=0
cur_sample_id_blen += 2;
}
if (cur_sample_id_blen > max_sample_id_blen) {
max_sample_id_blen = cur_sample_id_blen;
}
if (new_sid_present) {
const char* sid_start = FirstNonTspace(line_iter);
if (unlikely(IsEolnKns(*sid_start))) {
goto PrescanSampleIds_ret_MISSING_TOKENS;
}
line_iter = CurTokenEnd(sid_start);
const uintptr_t sid_slen = line_iter - sid_start;
if (sid_slen >= max_sid_blen) {
max_sid_blen = sid_slen + 1;
}
}
if (unlikely(!IsEolnKns(*line_iter))) {
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-ids file has more tokens than expected.\n", line_idx);
goto PrescanSampleIds_ret_MALFORMED_INPUT_WW;
}
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto PrescanSampleIds_ret_TSTREAM_FAIL;
}
reterr = kPglRetSuccess;
siip->max_sample_id_blen = max_sample_id_blen;
if (new_sid_present) {
siip->max_sid_blen = max_sid_blen;
}
}
while (0) {
PrescanSampleIds_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-ids file", &txs);
break;
PrescanSampleIds_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-ids file has fewer tokens than expected.\n", line_idx);
PrescanSampleIds_ret_MALFORMED_INPUT_WW:
WordWrapB(0);
logerrputsb();
PrescanSampleIds_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
}
PrescanSampleIds_ret_1:
CleanupTextStream2("--update-ids file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr PrescanParentalIds(const char* fname, uint32_t max_thread_ct, ParentalIdInfo* parental_id_infop) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
reterr = ForceNonFifo(fname);
if (unlikely(reterr)) {
if (reterr == kPglRetOpenFail) {
logerrprintfww(kErrprintfFopen, "--update-parents file", strerror(errno));
} else {
logerrprintfww(kErrprintfRewind, "--update-parents file");
}
goto PrescanParentalIds_ret_1;
}
// don't use LoadXidHeader since we can ignore sample ID on this pass
// permit very long lines since this can be pointed at .ped files
// possible minor todo: could save longest line length for later reference
reterr = SizeAndInitTextStream(fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto PrescanParentalIds_ret_TSTREAM_FAIL;
}
uint32_t is_header_line;
const char* line_iter;
do {
++line_idx;
line_iter = TextGet(&txs);
if (!line_iter) {
reterr = TextStreamRawErrcode(&txs);
if (likely(reterr == kPglRetEof)) {
// permit empty file here, but signal this to caller
// (reterr == kPglRetSuccess when file is nonempty, so we can detect
// rewind-fail)
goto PrescanParentalIds_ret_1;
}
goto PrescanParentalIds_ret_TSTREAM_FAIL;
}
is_header_line = (*line_iter == '#');
} while (is_header_line && (!tokequal_k(&(line_iter[1]), "FID")) && (!tokequal_k(&(line_iter[1]), "IID")));
uint32_t pat_col_idx;
if (is_header_line) {
// Search for 'PAT' column. Require all-caps.
pat_col_idx = 0;
line_iter = &(line_iter[4]);
while (1) {
++pat_col_idx;
const char* token_start = FirstNonTspace(line_iter);
if (unlikely(IsEolnKns(*token_start))) {
logerrputs("Error: Invalid --update-parents file (no PAT column).\n");
goto PrescanParentalIds_ret_MALFORMED_INPUT;
}
line_iter = CurTokenEnd(token_start);
if (strequal_k(token_start, "PAT", line_iter - token_start)) {
break;
}
}
// Require immediately-following column to be 'MAT'.
const char* token_start = FirstNonTspace(line_iter);
line_iter = FirstSpaceOrEoln(token_start);
if (unlikely(!strequal_k(token_start, "MAT", line_iter - token_start))) {
logerrputs("Error: Invalid --update-parents file (no MAT column immediately following PAT\ncolumn).\n");
goto PrescanParentalIds_ret_MALFORMED_INPUT;
}
line_iter = AdvPastDelim(line_iter, '\n');
++line_idx;
} else {
const uint32_t token_ct = CountTokens(line_iter);
if (unlikely(token_ct < 3)) {
logerrputs("Error: Invalid --update-parents file (3+ columns expected).\n");
goto PrescanParentalIds_ret_MALFORMED_INPUT;
}
pat_col_idx = (token_ct == 3)? 1 : 2;
}
uintptr_t max_paternal_id_blen = 0;
uintptr_t max_maternal_id_blen = 0;
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
line_iter = NextTokenMult(line_iter, pat_col_idx);
if (unlikely(!line_iter)) {
goto PrescanParentalIds_ret_MISSING_TOKENS;
}
const char* pat_start = line_iter;
line_iter = CurTokenEnd(pat_start);
const uintptr_t cur_paternal_id_slen = line_iter - pat_start;
if (cur_paternal_id_slen >= max_paternal_id_blen) {
max_paternal_id_blen = cur_paternal_id_slen + 1;
}
const char* mat_start = FirstNonTspace(line_iter);
if (unlikely(IsEolnKns(*mat_start))) {
goto PrescanParentalIds_ret_MISSING_TOKENS;
}
line_iter = CurTokenEnd(mat_start);
uintptr_t cur_maternal_id_slen = line_iter - mat_start;
if (cur_maternal_id_slen >= max_maternal_id_blen) {
max_maternal_id_blen = cur_maternal_id_slen + 1;
}
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto PrescanParentalIds_ret_TSTREAM_FAIL;
}
reterr = kPglRetSuccess;
parental_id_infop->max_paternal_id_blen = max_paternal_id_blen;
parental_id_infop->max_maternal_id_blen = max_maternal_id_blen;
}
while (0) {
PrescanParentalIds_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-parents file", &txs);
break;
PrescanParentalIds_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-parents file has fewer tokens than expected.\n", line_idx);
WordWrapB(0);
logerrputsb();
PrescanParentalIds_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
}
PrescanParentalIds_ret_1:
CleanupTextStream2("--update-parents file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr UpdateSampleIds(const char* fname, const uintptr_t* sample_include, uint32_t raw_sample_ct, uintptr_t sample_ct, SampleIdInfo* siip) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
if (!sample_ct) {
goto UpdateSampleIds_ret_1;
}
// probable todo: deduplicate shared code with PrescanSampleIds
reterr = InitTextStream(fname, kTextStreamBlenFast, 1, &txs);
if (unlikely(reterr)) {
goto UpdateSampleIds_ret_TSTREAM_FAIL;
}
const char* line_iter;
uint32_t is_header_line;
do {
++line_idx;
line_iter = TextGet(&txs);
if (unlikely(!line_iter)) {
reterr = TextStreamRawErrcode(&txs);
// This function is no longer called when the original file is empty.
goto UpdateSampleIds_ret_TSTREAM_FAIL;
}
is_header_line = (*line_iter == '#');
} while (is_header_line && (!tokequal_k(&(line_iter[1]), "OLD_FID")) && (!tokequal_k(&(line_iter[1]), "OLD_IID")));
uint32_t old_fid_present = 0;
uint32_t old_sid_present = 0;
uint32_t new_fid_present = 0;
uint32_t new_sid_present = 0;
if (is_header_line) {
if (line_iter[5] == 'F') {
old_fid_present = 1;
line_iter = FirstNonTspace(&(line_iter[8]));
if (unlikely(!tokequal_k(line_iter, "OLD_IID"))) {
goto UpdateSampleIds_ret_REWIND_FAIL;
}
}
line_iter = FirstNonTspace(CurTokenEnd(line_iter));
if (tokequal_k(line_iter, "OLD_SID")) {
old_sid_present = 1;
line_iter = FirstNonTspace(&(line_iter[7]));
}
if (tokequal_k(line_iter, "NEW_FID")) {
new_fid_present = 1;
line_iter = FirstNonTspace(&(line_iter[7]));
}
if (unlikely(!tokequal_k(line_iter, "NEW_IID"))) {
goto UpdateSampleIds_ret_REWIND_FAIL;
}
line_iter = FirstNonTspace(&(line_iter[7]));
if (tokequal_k(line_iter, "NEW_SID")) {
new_sid_present = 1;
line_iter = FirstNonTspace(&(line_iter[7]));
}
if (unlikely(!IsSpaceOrEoln(*line_iter))) {
goto UpdateSampleIds_ret_REWIND_FAIL;
}
} else {
const uint32_t token_ct = CountTokens(line_iter);
if (token_ct == 4) {
old_fid_present = 1;
new_fid_present = 1;
} else if (unlikely(token_ct != 2)) {
goto UpdateSampleIds_ret_REWIND_FAIL;
}
}
XidMode xid_mode;
if (old_fid_present) {
xid_mode = old_sid_present? kfXidModeFidIidSid : kfXidModeFidIid;
} else {
xid_mode = old_sid_present? kfXidModeIidSid : kfXidModeIid;
}
if (new_fid_present) {
// bugfix (14 Jan 2021)
siip->flags |= kfSampleIdFidPresent;
}
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
const uintptr_t max_sid_blen = siip->max_sid_blen;
uint32_t* xid_map = nullptr;
char* sorted_xidbox = nullptr;
uintptr_t max_xid_blen;
reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
if (unlikely(reterr)) {
goto UpdateSampleIds_ret_1;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
uintptr_t* already_seen;
char* idbuf;
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &already_seen) ||
bigstack_alloc_c(max_xid_blen, &idbuf))) {
goto UpdateSampleIds_ret_NOMEM;
}
uint32_t hit_ct = 0;
uintptr_t miss_ct = 0;
if (is_header_line) {
line_iter = AdvPastDelim(line_iter, '\n');
++line_idx;
}
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
const char* linebuf_iter = line_iter;
uint32_t xid_idx;
uint32_t xid_idx_end;
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx, &xid_idx_end, idbuf)) {
if (unlikely(!linebuf_iter)) {
goto UpdateSampleIds_ret_REWIND_FAIL;
}
++miss_ct;
continue;
}
uint32_t sample_uidx = xid_map[xid_idx];
if (unlikely(IsSet(already_seen, sample_uidx))) {
// possible todo: tolerate duplicates if payload matches, like
// --update-sex does
logerrprintfww("Error: Sample ID on line %" PRIuPTR " of --update-ids file duplicates one earlier in the file.\n", line_idx);
goto UpdateSampleIds_ret_MALFORMED_INPUT;
}
SetBit(sample_uidx, already_seen);
char* new_sample_id = &(siip->sample_ids[sample_uidx * max_sample_id_blen]);
char* new_sample_id_iter = new_sample_id;
if (new_fid_present) {
const char* sample_id_start = FirstNonTspace(linebuf_iter);
linebuf_iter = CurTokenEnd(sample_id_start);
new_sample_id_iter = memcpya(new_sample_id_iter, sample_id_start, linebuf_iter - sample_id_start);
} else {
*new_sample_id_iter++ = '0';
}
*new_sample_id_iter++ = '\t';
const char* iid_start = FirstNonTspace(linebuf_iter);
linebuf_iter = CurTokenEnd(iid_start);
new_sample_id_iter = memcpyax(new_sample_id_iter, iid_start, linebuf_iter - iid_start, '\0');
char* new_sid = nullptr;
uint32_t new_sid_blen = 0;
if (new_sid_present) {
new_sid = &(siip->sids[sample_uidx * max_sid_blen]);
const char* sid_start = FirstNonTspace(linebuf_iter);
linebuf_iter = CurTokenEnd(sid_start);
const uint32_t new_sid_slen = linebuf_iter - sid_start;
memcpyx(new_sid, sid_start, new_sid_slen, '\0');
new_sid_blen = new_sid_slen + 1;
}
line_iter = linebuf_iter;
hit_ct += xid_idx_end - xid_idx;
if (++xid_idx != xid_idx_end) {
uintptr_t new_sample_id_blen = new_sample_id_iter - new_sample_id;
do {
sample_uidx = xid_map[xid_idx];
memcpy(&(siip->sample_ids[sample_uidx * max_sample_id_blen]), new_sample_id, new_sample_id_blen);
if (new_sid) {
// now possible since NEW_SID may be present without OLD_SID
memcpy(&(siip->sids[sample_uidx * max_sid_blen]), new_sid, new_sid_blen);
}
} while (++xid_idx != xid_idx_end);
}
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto UpdateSampleIds_ret_TSTREAM_FAIL;
}
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--update-ids: %u sample%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
} else {
snprintf(g_logbuf, kLogbufSize, "--update-ids: %u sample%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
}
logputsb();
reterr = CheckXidUniqueness(sample_include, siip, " from --update-ids", sample_ct);
if (unlikely(reterr)) {
goto UpdateSampleIds_ret_1;
}
}
while (0) {
UpdateSampleIds_ret_NOMEM:
reterr = kPglRetNomem;
break;
UpdateSampleIds_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-ids file", &txs);
break;
UpdateSampleIds_ret_REWIND_FAIL:
logerrprintfww(kErrprintfRewind, "--update-ids file");
reterr = kPglRetRewindFail;
break;
UpdateSampleIds_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
}
UpdateSampleIds_ret_1:
CleanupTextStream2("--update-ids file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr UpdateSampleParents(const char* fname, const SampleIdInfo* siip, const uintptr_t* sample_include, uint32_t raw_sample_ct, uintptr_t sample_ct, uint32_t max_thread_ct, ParentalIdInfo* parental_id_infop, uintptr_t* founder_info) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
if (!sample_ct) {
goto UpdateSampleParents_ret_1;
}
// permit very long lines since this can be pointed at .ped files
reterr = SizeAndInitTextStream(fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto UpdateSampleParents_ret_TSTREAM_FAIL;
}
const char* line_iter;
XidMode xid_mode;
{
char* line_start;
reterr = LoadXidHeader("update-parents", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, &line_idx, &txs, &xid_mode, &line_start);
if (unlikely(reterr)) {
if (reterr == kPglRetEof) {
goto UpdateSampleParents_ret_REWIND_FAIL;
}
goto UpdateSampleParents_ret_TSTREAM_XID_FAIL;
}
line_iter = line_start;
}
uint32_t postid_pat_col_idx = 1;
if (*line_iter == '#') {
const uint32_t id_col_ct = GetXidColCt(xid_mode);
const char* token_end = CurTokenEnd(NextTokenMult0(line_iter, id_col_ct - 1));
while (1) {
const char* token_start = FirstNonTspace(token_end);
if (unlikely(IsEolnKns(*token_start))) {
goto UpdateSampleParents_ret_REWIND_FAIL;
}
token_end = CurTokenEnd(token_start);
if (strequal_k(token_start, "PAT", token_end - token_start)) {
break;
}
++postid_pat_col_idx;
}
line_iter = AdvPastDelim(line_iter, '\n');
++line_idx;
} else {
const uint32_t token_ct = CountTokens(line_iter);
if (unlikely(token_ct < 3)) {
goto UpdateSampleParents_ret_REWIND_FAIL;
}
xid_mode = (token_ct == 3)? kfXidModeIid : kfXidModeFidIid;
}
uint32_t* xid_map = nullptr;
char* sorted_xidbox = nullptr;
uintptr_t max_xid_blen;
reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
if (unlikely(reterr)) {
goto UpdateSampleParents_ret_1;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
uintptr_t* already_seen;
char* idbuf;
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &already_seen) ||
bigstack_alloc_c(max_xid_blen, &idbuf))) {
goto UpdateSampleParents_ret_NOMEM;
}
const uintptr_t max_paternal_id_blen = parental_id_infop->max_paternal_id_blen;
const uintptr_t max_maternal_id_blen = parental_id_infop->max_maternal_id_blen;
char* paternal_ids = parental_id_infop->paternal_ids;
char* maternal_ids = parental_id_infop->maternal_ids;
uint32_t hit_ct = 0;
uintptr_t miss_ct = 0;
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
const char* linebuf_iter = line_iter;
uint32_t xid_idx;
uint32_t xid_idx_end;
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx, &xid_idx_end, idbuf)) {
if (unlikely(!linebuf_iter)) {
goto UpdateSampleParents_ret_REWIND_FAIL;
}
++miss_ct;
continue;
}
uint32_t sample_uidx = xid_map[xid_idx];
if (unlikely(IsSet(already_seen, sample_uidx))) {
// possible todo: tolerate duplicates if payload matches, like
// --update-sex does
logerrprintfww("Error: Sample ID on line %" PRIuPTR " of --update-parents file duplicates one earlier in the file.\n", line_idx);
goto UpdateSampleParents_ret_MALFORMED_INPUT;
}
SetBit(sample_uidx, already_seen);
const char* pat_start = NextTokenMult(linebuf_iter, postid_pat_col_idx);
const char* pat_end = CurTokenEnd(pat_start);
const char* mat_start = FirstNonTspace(pat_end);
line_iter = CurTokenEnd(mat_start);
const uint32_t plen = pat_end - pat_start;
const uint32_t mlen = line_iter - mat_start;
const uint32_t is_founder = (plen == 1) && (*pat_start == '0') && (mlen == 1) && (*mat_start == '0');
hit_ct += xid_idx_end - xid_idx;
while (1) {
memcpyx(&(paternal_ids[sample_uidx * max_paternal_id_blen]), pat_start, plen, '\0');
memcpyx(&(maternal_ids[sample_uidx * max_maternal_id_blen]), mat_start, mlen, '\0');
AssignBit(sample_uidx, is_founder, founder_info);
if (++xid_idx == xid_idx_end) {
break;
}
sample_uidx = xid_map[xid_idx];
}
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto UpdateSampleParents_ret_REWIND_FAIL;
}
reterr = kPglRetSuccess;
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--update-parents: %u sample%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
} else {
snprintf(g_logbuf, kLogbufSize, "--update-parents: %u sample%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
}
logputsb();
}
while (0) {
UpdateSampleParents_ret_NOMEM:
reterr = kPglRetNomem;
break;
UpdateSampleParents_ret_TSTREAM_XID_FAIL:
if (!TextStreamErrcode(&txs)) {
break;
}
UpdateSampleParents_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-parents file", &txs);
break;
UpdateSampleParents_ret_REWIND_FAIL:
logerrprintfww(kErrprintfRewind, "--update-parents file");
reterr = kPglRetRewindFail;
break;
UpdateSampleParents_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
}
UpdateSampleParents_ret_1:
CleanupTextStream2("--update-parents file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr UpdateSampleSexes(const uintptr_t* sample_include, const SampleIdInfo* siip, const UpdateSexInfo* update_sex_info_ptr, uint32_t raw_sample_ct, uintptr_t sample_ct, uint32_t max_thread_ct, uintptr_t* sex_nm, uintptr_t* sex_male) {
unsigned char* bigstack_mark = g_bigstack_base;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
if (!sample_ct) {
goto UpdateSampleSexes_ret_1;
}
// permit very long lines since this can be pointed at .ped files
reterr = SizeAndInitTextStream(update_sex_info_ptr->fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto UpdateSampleSexes_ret_TSTREAM_FAIL;
}
// (Much of this boilerplate is shared with e.g. KeepColMatch(); it
// probably belongs in its own function.)
char* line_start;
XidMode xid_mode;
reterr = LoadXidHeader("update-sex", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeaderFixedWidth : kfXidHeaderFixedWidthIgnoreSid, &line_idx, &txs, &xid_mode, &line_start);
if (reterr) {
if (likely(reterr == kPglRetEof)) {
reterr = kPglRetSuccess;
logputs("--update-sex: 0 samples updated.\n");
goto UpdateSampleSexes_ret_1;
}
goto UpdateSampleSexes_ret_TSTREAM_XID_FAIL;
}
const uint32_t id_col_ct = GetXidColCt(xid_mode);
uint32_t col_num = update_sex_info_ptr->col_num;
uint32_t postid_col_idx = 0;
if ((*line_start == '#') && (!col_num)) {
// search for 'SEX' column (any capitalization)
const char* token_end = CurTokenEnd(NextTokenMult0(line_start, id_col_ct - 1));
while (1) {
++postid_col_idx;
const char* linebuf_iter = FirstNonTspace(token_end);
if (unlikely(IsEolnKns(*linebuf_iter))) {
logerrputs("Error: No 'SEX' column in --update-sex file, and no column number specified.\n");
goto UpdateSampleSexes_ret_MALFORMED_INPUT;
}
token_end = CurTokenEnd(linebuf_iter);
if (MatchUpperKLen(linebuf_iter, "SEX", token_end - linebuf_iter)) {
break;
}
}
} else {
if (!col_num) {
if (unlikely(id_col_ct == 3)) {
logerrputs("Error: You must use 'col-num=' to specify the position of the sex column in the\n--update-sex file.\n");
goto UpdateSampleSexes_ret_MALFORMED_INPUT;
}
col_num = 3;
}
if (unlikely(id_col_ct >= col_num)) {
logerrputs("Error: --update-sex 'col-num=' argument too small (it refers to a sample ID\ncolumn).\n");
goto UpdateSampleSexes_ret_MALFORMED_INPUT;
}
postid_col_idx = col_num - id_col_ct;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
uint32_t* xid_map = nullptr;
char* sorted_xidbox = nullptr;
uintptr_t max_xid_blen;
reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
if (unlikely(reterr)) {
goto UpdateSampleSexes_ret_1;
}
uintptr_t* already_seen;
char* idbuf;
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &already_seen) ||
bigstack_alloc_c(max_xid_blen, &idbuf))) {
goto UpdateSampleSexes_ret_NOMEM;
}
const uint32_t male0 = (update_sex_info_ptr->flags / kfUpdateSexMale0) & 1;
uint32_t hit_ct = 0;
uintptr_t miss_ct = 0;
uintptr_t duplicate_ct = 0;
if (*line_start == '#') {
++line_idx;
line_start = TextGet(&txs);
}
for (; line_start; ++line_idx, line_start = TextGet(&txs)) {
const char* linebuf_iter = line_start;
uint32_t xid_idx_start;
uint32_t xid_idx_end;
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx_start, &xid_idx_end, idbuf)) {
if (unlikely(!linebuf_iter)) {
goto UpdateSampleSexes_ret_MISSING_TOKENS;
}
++miss_ct;
continue;
}
const char* sex_start = NextTokenMult(linebuf_iter, postid_col_idx);
if (unlikely(!sex_start)) {
goto UpdateSampleSexes_ret_MISSING_TOKENS;
}
uint32_t sexval = ctou32(*sex_start);
const uint32_t ujj = sexval & 0xdfU;
sexval -= 48;
if (sexval > 2) {
if (ujj == 77) {
// 'M'/'m'
sexval = 1;
} else if (ujj == 70) {
// 'F'/'f'
sexval = 2;
} else if (unlikely((!male0) && (sexval != 30) && (ujj != 85))) {
// allow 'N' = missing to make 1/2/NA work
// allow 'U'/'u' since this is actually being used by Illumina
// GenCall and Affymetrix APT
// don't permit 'n' for now
snprintf(g_logbuf, kLogbufSize, "Error: Invalid sex value on line %" PRIuPTR " of --update-sex file. (Acceptable values: 1/M/m = male, 2/F/f = female, 0/N/U = missing.)\n", line_idx);
goto UpdateSampleSexes_ret_MALFORMED_INPUT_WW;
} else {
// with 'male0', everything else is treated as missing
sexval = 0;
}
} else if (male0) {
if (unlikely(sexval == 2)) {
snprintf(g_logbuf, kLogbufSize, "Error: Invalid sex value on line %" PRIuPTR " of --update-sex file. ('2' is prohibited when the 'male0' modifier is present.)\n", line_idx);
goto UpdateSampleSexes_ret_MALFORMED_INPUT_WW;
}
++sexval;
}
uint32_t sample_uidx = xid_map[xid_idx_start];
if (IsSet(already_seen, sample_uidx)) {
// permit duplicates iff sex value is identical
const uint32_t old_sexval = IsSet(sex_nm, sample_uidx) * (2 - IsSet(sex_male, sample_uidx));
if (unlikely(sexval != old_sexval)) {
snprintf(g_logbuf, kLogbufSize, "Error: Sample ID on line %" PRIuPTR " of --update-sex file duplicates one earlier in the file, and sex values don't match.\n", line_idx);
goto UpdateSampleSexes_ret_MALFORMED_INPUT_WW;
}
++duplicate_ct;
continue;
}
SetBit(sample_uidx, already_seen);
hit_ct += xid_idx_end - xid_idx_start;
for (uint32_t xid_idx = xid_idx_start; ; sample_uidx = xid_map[xid_idx]) {
if (sexval) {
SetBit(sample_uidx, sex_nm);
if (sexval == 1) {
SetBit(sample_uidx, sex_male);
} else {
ClearBit(sample_uidx, sex_male);
}
} else {
ClearBit(sample_uidx, sex_nm);
ClearBit(sample_uidx, sex_male);
}
if (++xid_idx == xid_idx_end) {
break;
}
}
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto UpdateSampleSexes_ret_TSTREAM_FAIL;
}
if (duplicate_ct) {
logprintfww("Note: %" PRIuPTR " duplicate sample ID%s) in --update-sex file.\n", duplicate_ct, (duplicate_ct == 1)? " (with a consistent sex assignment" : "s (with consistent sex assignments");
}
if (miss_ct) {
snprintf(g_logbuf, kLogbufSize, "--update-sex: %u sample%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s");
} else {
snprintf(g_logbuf, kLogbufSize, "--update-sex: %u sample%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s");
}
logputsb();
}
while (0) {
UpdateSampleSexes_ret_TSTREAM_XID_FAIL:
if (!TextStreamErrcode(&txs)) {
break;
}
UpdateSampleSexes_ret_TSTREAM_FAIL:
TextStreamErrPrint("--update-sex file", &txs);
break;
UpdateSampleSexes_ret_NOMEM:
reterr = kPglRetNomem;
break;
UpdateSampleSexes_ret_MALFORMED_INPUT_WW:
WordWrapB(0);
logerrputsb();
UpdateSampleSexes_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
UpdateSampleSexes_ret_MISSING_TOKENS:
logerrprintf("Error: Line %" PRIuPTR " of --update-sex file has fewer tokens than expected.\n", line_idx);
reterr = kPglRetMalformedInput;
break;
}
UpdateSampleSexes_ret_1:
CleanupTextStream2("--update-sex file", &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr SplitCatPheno(const char* split_cat_phenonames_flattened, const uintptr_t* sample_include, uint32_t raw_sample_ct, PhenoTransformFlags pheno_transform_flags, PhenoCol** pheno_cols_ptr, char** pheno_names_ptr, uint32_t* pheno_ct_ptr, uintptr_t* max_pheno_name_blen_ptr, PhenoCol** covar_cols_ptr, char** covar_names_ptr, uint32_t* covar_ct_ptr, uintptr_t* max_covar_name_blen_ptr) {
unsigned char* bigstack_mark = g_bigstack_base;
const char* doomed_pheno_names = nullptr;
PhenoCol* doomed_pheno_cols = nullptr;
uint32_t doomed_pheno_ct = 0;
PglErr reterr = kPglRetSuccess;
{
const uint32_t is_omit = ((pheno_transform_flags & (kfPhenoTransformSplitCatOmitMost | kfPhenoTransformSplitCatOmitLast)) != 0);
const uint32_t omit_most = (pheno_transform_flags / kfPhenoTransformSplitCatOmitMost) & 1;
uint32_t qt_12 = 0;
uint32_t at_least_one_cat_pheno_processed = 0;
for (uint32_t is_covar = 0; is_covar != 2; ++is_covar) {
PhenoCol** xpheno_cols_ptr;
char** xpheno_names_ptr;
uint32_t* xpheno_ct_ptr;
uintptr_t* max_xpheno_name_blen_ptr;
if (!is_covar) {
xpheno_cols_ptr = pheno_cols_ptr;
xpheno_names_ptr = pheno_names_ptr;
xpheno_ct_ptr = pheno_ct_ptr;
max_xpheno_name_blen_ptr = max_pheno_name_blen_ptr;
} else {
if (!split_cat_phenonames_flattened) {
break;
}
BigstackReset(bigstack_mark);
xpheno_cols_ptr = covar_cols_ptr;
xpheno_names_ptr = covar_names_ptr;
xpheno_ct_ptr = covar_ct_ptr;
max_xpheno_name_blen_ptr = max_covar_name_blen_ptr;
qt_12 = !(pheno_transform_flags & kfPhenoTransformSplitCatCovar01);
}
const uint32_t old_pheno_ct = *xpheno_ct_ptr;
if (!old_pheno_ct) {
continue;
}
const uint32_t old_pheno_ctl = BitCtToWordCt(old_pheno_ct);
const uintptr_t old_max_pheno_name_blen = *max_xpheno_name_blen_ptr;
PhenoCol* old_pheno_cols = *xpheno_cols_ptr;
const char* old_pheno_names = *xpheno_names_ptr;
uintptr_t* phenos_to_split;
if (unlikely(bigstack_calloc_w(old_pheno_ctl, &phenos_to_split))) {
goto SplitCatPheno_ret_NOMEM;
}
if (!split_cat_phenonames_flattened) {
for (uint32_t pheno_idx = 0; pheno_idx != old_pheno_ct; ++pheno_idx) {
const PhenoCol* cur_pheno_col = &(old_pheno_cols[pheno_idx]);
if (cur_pheno_col->type_code == kPhenoDtypeCat) {
if (unlikely(strchr(&(old_pheno_names[pheno_idx * old_max_pheno_name_blen]), '='))) {
logerrputs("Error: --split-cat-pheno cannot be used on phenotypes containing the '='\ncharacter.\n");
goto SplitCatPheno_ret_INCONSISTENT_INPUT;
}
SetBit(pheno_idx, phenos_to_split);
}
}
} else {
uint32_t* id_htable;
uint32_t id_htable_size;
if (unlikely(HtableGoodSizeAlloc(old_pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) {
goto SplitCatPheno_ret_NOMEM;
}
// shouldn't be possible for this to fail
PopulateStrboxHtable(old_pheno_names, old_pheno_ct, old_max_pheno_name_blen, id_htable_size, id_htable);
const char* split_cat_phenonames_iter = split_cat_phenonames_flattened;
do {
const uint32_t cur_phenoname_slen = strlen(split_cat_phenonames_iter);
if (cur_phenoname_slen < old_max_pheno_name_blen) {
uint32_t pheno_idx = StrboxHtableFind(split_cat_phenonames_iter, old_pheno_names, id_htable, old_max_pheno_name_blen, cur_phenoname_slen, id_htable_size);
if (pheno_idx != UINT32_MAX) {
if (unlikely(old_pheno_cols[pheno_idx].type_code != kPhenoDtypeCat)) {
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a categorical %s.\n", split_cat_phenonames_iter, is_covar? "covariate" : "phenotype");
goto SplitCatPheno_ret_INCONSISTENT_INPUT_WW;
}
SetBit(pheno_idx, phenos_to_split);
}
}
split_cat_phenonames_iter = &(split_cat_phenonames_iter[cur_phenoname_slen + 1]);
} while (*split_cat_phenonames_iter);
BigstackReset(id_htable);
}
const uint32_t split_pheno_ct = PopcountWords(phenos_to_split, old_pheno_ctl);
if (!split_pheno_ct) {
continue;
}
at_least_one_cat_pheno_processed = 1;
// first pass: determine new memory allocation sizes
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
uintptr_t new_max_pheno_name_blen = old_max_pheno_name_blen;
// excludes null; also excludes one other category if omit-most/omit-last
uint32_t* observed_cat_cts;
uintptr_t** observed_cats;
uintptr_t* sample_include_intersect;
if (unlikely(bigstack_alloc_u32(split_pheno_ct, &observed_cat_cts) ||
bigstack_alloc_wp(split_pheno_ct, &observed_cats) ||
bigstack_alloc_w(raw_sample_ctl, &sample_include_intersect))) {
goto SplitCatPheno_ret_NOMEM;
}
uint32_t* omitted_cat_uidxs = nullptr;
if (is_omit) {
if (unlikely(bigstack_alloc_u32(split_pheno_ct, &omitted_cat_uidxs))) {
goto SplitCatPheno_ret_NOMEM;
}
}
uint32_t* cat_obs_buf = nullptr;
uintptr_t create_pheno_ct = 0;
uintptr_t split_pheno_uidx_base = 0;
uintptr_t phenos_to_split_bits = phenos_to_split[0];
uint32_t max_cat_uidx = 0;
for (uint32_t split_pheno_idx = 0; split_pheno_idx != split_pheno_ct; ++split_pheno_idx) {
const uintptr_t split_pheno_uidx = BitIter1(phenos_to_split, &split_pheno_uidx_base, &phenos_to_split_bits);
const PhenoCol* cur_pheno_col = &(old_pheno_cols[split_pheno_uidx]);
BitvecAndCopy(sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, sample_include_intersect);
const uint32_t cur_cat_ct = cur_pheno_col->nonnull_category_ct + 1;
const uint32_t cur_cat_ctl = BitCtToWordCt(cur_cat_ct);
uintptr_t* cur_observed_cats;
if (unlikely(bigstack_alloc_w(cur_cat_ctl, &cur_observed_cats))) {
goto SplitCatPheno_ret_NOMEM;
}
if (omit_most) {
if (unlikely(bigstack_alloc_u32(cur_cat_ct, &cat_obs_buf))) {
goto SplitCatPheno_ret_NOMEM;
}
}
observed_cats[split_pheno_idx] = cur_observed_cats;
const uint32_t cur_nmiss_ct = PopcountWords(sample_include_intersect, raw_sample_ctl);
uint32_t cur_observed_cat_ct;
if (!omit_most) {
cur_observed_cat_ct = IdentifyRemainingCats(sample_include_intersect, cur_pheno_col, cur_nmiss_ct, cur_observed_cats);
if (is_omit && cur_observed_cat_ct) {
const uint32_t last_cat_uidx = FindLast1BitBefore(cur_observed_cats, cur_cat_ct + 1);
omitted_cat_uidxs[split_pheno_idx] = last_cat_uidx;
ClearBit(last_cat_uidx, cur_observed_cats);
--cur_observed_cat_ct;
}
} else {
const uint32_t largest_cat_uidx = IdentifyRemainingCatsAndMostCommon(sample_include_intersect, cur_pheno_col, cur_nmiss_ct, cur_observed_cats, cat_obs_buf);
cur_observed_cat_ct = PopcountWords(cur_observed_cats, cur_cat_ctl);
if (cur_observed_cat_ct) {
omitted_cat_uidxs[split_pheno_idx] = largest_cat_uidx;
ClearBit(largest_cat_uidx, cur_observed_cats);
--cur_observed_cat_ct;
}
}
if (cur_observed_cat_ct) {
// old phenotype name, '=' character, null terminator
const uintptr_t blen_base = strlen(&(old_pheno_names[split_pheno_uidx * old_max_pheno_name_blen])) + 2;
const char* const* cat_names = cur_pheno_col->category_names;
uintptr_t cat_uidx_base = 0;
uintptr_t cur_observed_cats_bits = cur_observed_cats[0];
uint32_t cat_uidx = 0;
for (uint32_t cat_idx = 0; cat_idx != cur_observed_cat_ct; ++cat_idx) {
cat_uidx = BitIter1(cur_observed_cats, &cat_uidx_base, &cur_observed_cats_bits);
const char* cur_cat_name = cat_names[cat_uidx];
const uint32_t cur_slen = strlen(cur_cat_name);
if (unlikely(memchr(cur_cat_name, '=', cur_slen))) {
logerrputs("Error: --split-cat-pheno category names may not contain the '=' character.\n");
goto SplitCatPheno_ret_INCONSISTENT_INPUT;
}
const uintptr_t total_blen = cur_slen + blen_base;
if (total_blen > new_max_pheno_name_blen) {
new_max_pheno_name_blen = total_blen;
}
}
if (cat_uidx > max_cat_uidx) {
max_cat_uidx = cat_uidx;
}
}
observed_cat_cts[split_pheno_idx] = cur_observed_cat_ct;
create_pheno_ct += cur_observed_cat_ct;
if (cat_obs_buf) {
BigstackReset(cat_obs_buf);
}
}
if (unlikely(new_max_pheno_name_blen > kMaxIdBlen)) {
logerrputs("Error: New --split-cat-pheno phenotype name too long. Shorten your phenotype\nor your category names.\n");
goto SplitCatPheno_ret_INCONSISTENT_INPUT;
}
const uint32_t copy_pheno_ct = old_pheno_ct - split_pheno_ct;
// before new_pheno_ct variable definition due to potential integer
// overflow
if (unlikely(create_pheno_ct + copy_pheno_ct > kMaxPhenoCt)) {
logerrputs("Error: --split-cat-pheno would create too many phenotypes (" PROG_NAME_STR " is limited to\n" MAX_PHENO_CT_STR ").\n");
goto SplitCatPheno_ret_INCONSISTENT_INPUT;
}
const uint32_t new_pheno_ct = create_pheno_ct + copy_pheno_ct;
uintptr_t** write_data_ptrs;
if (unlikely(bigstack_alloc_wp(max_cat_uidx + 1, &write_data_ptrs))) {
goto SplitCatPheno_ret_NOMEM;
}
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
uint32_t new_data_word_ct = raw_sample_ctaw;
if (is_covar) {
new_data_word_ct = DblCtToVecCt(raw_sample_ct) * kWordsPerVec;
}
uintptr_t* omit_dummy = nullptr;
if (is_omit) {
if (unlikely(bigstack_alloc_w(new_data_word_ct, &omit_dummy))) {
goto SplitCatPheno_ret_NOMEM;
}
}
// second pass: allocate memory and actually create the new phenotypes
char* new_pheno_names;
if (unlikely(pgl_malloc(new_pheno_ct * new_max_pheno_name_blen, &new_pheno_names))) {
goto SplitCatPheno_ret_NOMEM;
}
doomed_pheno_names = old_pheno_names;
*xpheno_names_ptr = new_pheno_names;
PhenoCol* new_pheno_cols;
if (unlikely(pgl_malloc(new_pheno_ct * sizeof(PhenoCol), &new_pheno_cols))) {
goto SplitCatPheno_ret_NOMEM;
}
doomed_pheno_cols = old_pheno_cols;
doomed_pheno_ct = old_pheno_ct;
*xpheno_cols_ptr = new_pheno_cols;
*xpheno_ct_ptr = new_pheno_ct;
*max_xpheno_name_blen_ptr = new_max_pheno_name_blen;
uintptr_t pheno_read_idx_base = 0;
uintptr_t phenos_to_split_inv_bits = ~phenos_to_split[0];
for (uint32_t pheno_write_idx = 0; pheno_write_idx != copy_pheno_ct; ++pheno_write_idx) {
const uintptr_t pheno_read_idx = BitIter0(phenos_to_split, &pheno_read_idx_base, &phenos_to_split_inv_bits);
// manually move this data
memcpy(&(new_pheno_cols[pheno_write_idx]), &(doomed_pheno_cols[pheno_read_idx]), sizeof(PhenoCol));
doomed_pheno_cols[pheno_read_idx].nonmiss = nullptr;
strcpy(&(new_pheno_names[pheno_write_idx * new_max_pheno_name_blen]), &(old_pheno_names[pheno_read_idx * old_max_pheno_name_blen]));
}
for (uint32_t pheno_write_idx = copy_pheno_ct; pheno_write_idx != new_pheno_ct; ++pheno_write_idx) {
new_pheno_cols[pheno_write_idx].nonmiss = nullptr;
}
const uintptr_t new_pheno_bytes_req = (raw_sample_ctaw + new_data_word_ct) * sizeof(intptr_t);
uint32_t pheno_write_idx = copy_pheno_ct;
pheno_read_idx_base = 0;
phenos_to_split_bits = phenos_to_split[0];
for (uint32_t split_pheno_idx = 0; split_pheno_idx != split_pheno_ct; ++split_pheno_idx) {
const uintptr_t pheno_read_idx = BitIter1(phenos_to_split, &pheno_read_idx_base, &phenos_to_split_bits);
const uint32_t cur_pheno_write_ct = observed_cat_cts[split_pheno_idx];
if (!cur_pheno_write_ct) {
continue;
}
const uintptr_t* cur_observed_cats = observed_cats[split_pheno_idx];
const PhenoCol* old_pheno_col = &(old_pheno_cols[pheno_read_idx]);
BitvecAndCopy(sample_include, old_pheno_col->nonmiss, raw_sample_ctaw, sample_include_intersect);
const char* old_pheno_name = &(old_pheno_names[pheno_read_idx * old_max_pheno_name_blen]);
const uint32_t old_pheno_name_slen = strlen(old_pheno_name);
const char* const* old_cat_names = old_pheno_col->category_names;
uintptr_t orig_cat_idx_base;
uintptr_t cur_observed_cats_bits;
BitIter1Start(cur_observed_cats, 1, &orig_cat_idx_base, &cur_observed_cats_bits);
for (uint32_t uii = 0; uii != cur_pheno_write_ct; ++uii, ++pheno_write_idx) {
const uintptr_t orig_cat_idx = BitIter1(cur_observed_cats, &orig_cat_idx_base, &cur_observed_cats_bits);
uintptr_t* new_pheno_data_iter;
if (unlikely(vecaligned_malloc(new_pheno_bytes_req, &new_pheno_data_iter))) {
goto SplitCatPheno_ret_NOMEM;
}
char* new_phenoname_write_iter = memcpyax(&(new_pheno_names[pheno_write_idx * new_max_pheno_name_blen]), old_pheno_name, old_pheno_name_slen, '=');
strcpy(new_phenoname_write_iter, old_cat_names[orig_cat_idx]);
PhenoCol* pheno_write_col = &(new_pheno_cols[pheno_write_idx]);
pheno_write_col->nonmiss = new_pheno_data_iter;
pheno_write_col->category_names = nullptr;
pheno_write_col->type_code = S_CAST(PhenoDtype, is_covar);
pheno_write_col->nonnull_category_ct = 0;
memcpy(new_pheno_data_iter, sample_include_intersect, raw_sample_ctaw * sizeof(intptr_t));
new_pheno_data_iter = &(new_pheno_data_iter[raw_sample_ctaw]);
write_data_ptrs[orig_cat_idx] = new_pheno_data_iter;
// assigning to one element of a union and reading from another with
// a different type is undefined behavior in C++11
if (!is_covar) {
pheno_write_col->data.cc = new_pheno_data_iter;
ZeroWArr(raw_sample_ctaw, new_pheno_data_iter);
} else {
double* pheno_qt = R_CAST(double*, new_pheno_data_iter);
pheno_write_col->data.qt = pheno_qt;
if (qt_12) {
for (uint32_t ujj = 0; ujj != raw_sample_ct; ++ujj) {
pheno_qt[ujj] = 1.0;
}
} else {
ZeroDArr(raw_sample_ct, pheno_qt);
}
}
}
if (is_omit) {
write_data_ptrs[omitted_cat_uidxs[split_pheno_idx]] = omit_dummy;
}
const uint32_t cur_nmiss_ct = PopcountWords(sample_include_intersect, raw_sample_ctl);
const uint32_t* cur_cats = old_pheno_col->data.cat;
uintptr_t sample_uidx_base = 0;
uintptr_t sample_include_intersect_bits = sample_include_intersect[0];
if (!is_covar) {
for (uint32_t sample_idx = 0; sample_idx != cur_nmiss_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &sample_include_intersect_bits);
SetBit(sample_uidx, write_data_ptrs[cur_cats[sample_uidx]]);
}
} else {
double** write_qt_ptrs = R_CAST(double**, write_data_ptrs);
const double write_val = u31tod(1 + qt_12);
for (uint32_t sample_idx = 0; sample_idx != cur_nmiss_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &sample_include_intersect_bits);
write_qt_ptrs[cur_cats[sample_uidx]][sample_uidx] = write_val;
}
}
}
// if any preexisting phenotype names contain a single copy of the '='
// character, verify that we didn't create any duplicate IDs
for (uint32_t pheno_idx = 0; pheno_idx != copy_pheno_ct; ++pheno_idx) {
const char* first_eq = strchr(&(new_pheno_names[pheno_idx * new_max_pheno_name_blen]), '=');
if (first_eq && (!strchr(&(first_eq[1]), '='))) {
uint32_t* id_htable;
uint32_t id_htable_size;
if (unlikely(HtableGoodSizeAlloc(new_pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) {
goto SplitCatPheno_ret_NOMEM;
}
uint32_t duplicate_idx = PopulateStrboxHtable(new_pheno_names, new_pheno_ct, new_max_pheno_name_blen, id_htable_size, id_htable);
if (unlikely(duplicate_idx)) {
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate %s '%s' created by --split-cat-pheno.\n", is_covar? "covariate" : "phenotype", &(new_pheno_names[duplicate_idx * new_max_pheno_name_blen]));
goto SplitCatPheno_ret_INCONSISTENT_INPUT_WW;
}
break;
}
}
free_const(doomed_pheno_names);
doomed_pheno_names = nullptr;
CleanupPhenoCols(doomed_pheno_ct, doomed_pheno_cols);
doomed_pheno_cols = nullptr;
logprintfww("--split-cat-pheno: %u categorical %s%s converted to %" PRIuPTR " %s%s.\n", split_pheno_ct, is_covar? "covariate" : "phenotype", (split_pheno_ct == 1)? "" : "s", create_pheno_ct, is_covar? "covariate" : "phenotype", (create_pheno_ct == 1)? "" : "s");
}
if (!at_least_one_cat_pheno_processed) {
logerrprintf("Warning: No categorical phenotypes%s processed by --split-cat-pheno.\n", (split_cat_phenonames_flattened && (!(*covar_ct_ptr)))? "/covariates" : "");
}
}
while (0) {
SplitCatPheno_ret_NOMEM:
reterr = kPglRetNomem;
break;
SplitCatPheno_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
SplitCatPheno_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
BigstackReset(bigstack_mark);
free_cond(doomed_pheno_names);
CleanupPhenoCols(doomed_pheno_ct, doomed_pheno_cols);
if (reterr) {
if (*pheno_names_ptr) {
free(*pheno_names_ptr);
*pheno_names_ptr = nullptr;
}
CleanupPhenoCols(*pheno_ct_ptr, *pheno_cols_ptr);
*pheno_ct_ptr = 0;
*pheno_cols_ptr = nullptr;
if (*covar_names_ptr) {
free(*covar_names_ptr);
*covar_names_ptr = nullptr;
}
CleanupPhenoCols(*covar_ct_ptr, *covar_cols_ptr);
*covar_ct_ptr = 0;
*covar_cols_ptr = nullptr;
}
return reterr;
}
PglErr PhenoVarianceStandardize(const char* vstd_flattened, const uintptr_t* sample_include, const char* pheno_names, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t is_covar, uint32_t is_covar_flag, PhenoCol* pheno_cols) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
{
if (!pheno_ct) {
goto PhenoVarianceStandardize_ret_SKIP;
}
const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct);
uintptr_t* phenos_to_transform;
if (unlikely(bigstack_calloc_w(pheno_ctl, &phenos_to_transform))) {
goto PhenoVarianceStandardize_ret_NOMEM;
}
if (!vstd_flattened) {
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
if (cur_pheno_col->type_code == kPhenoDtypeQt) {
SetBit(pheno_idx, phenos_to_transform);
}
}
} else {
uint32_t* id_htable;
uint32_t id_htable_size;
if (unlikely(HtableGoodSizeAlloc(pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) {
goto PhenoVarianceStandardize_ret_NOMEM;
}
PopulateStrboxHtable(pheno_names, pheno_ct, max_pheno_name_blen, id_htable_size, id_htable);
const char* vstd_phenonames_iter = vstd_flattened;
do {
const uint32_t cur_phenoname_slen = strlen(vstd_phenonames_iter);
if (cur_phenoname_slen < max_pheno_name_blen) {
uint32_t pheno_idx = StrboxHtableFind(vstd_phenonames_iter, pheno_names, id_htable, max_pheno_name_blen, cur_phenoname_slen, id_htable_size);
if (pheno_idx != UINT32_MAX) {
if (unlikely(pheno_cols[pheno_idx].type_code != kPhenoDtypeQt)) {
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a quantitative %s.\n", vstd_phenonames_iter, is_covar? "covariate" : "phenotype");
goto PhenoVarianceStandardize_ret_INCONSISTENT_INPUT_WW;
}
SetBit(pheno_idx, phenos_to_transform);
}
}
vstd_phenonames_iter = &(vstd_phenonames_iter[cur_phenoname_slen + 1]);
} while (*vstd_phenonames_iter);
BigstackReset(id_htable);
}
const uint32_t pheno_transform_ct = PopcountWords(phenos_to_transform, pheno_ctl);
if (!pheno_transform_ct) {
goto PhenoVarianceStandardize_ret_SKIP;
}
double* shifted_pheno_qt;
if (unlikely(bigstack_alloc_d(raw_sample_ct, &shifted_pheno_qt))) {
goto PhenoVarianceStandardize_ret_NOMEM;
}
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
uintptr_t pheno_uidx_base = 0;
uintptr_t phenos_to_transform_bits = phenos_to_transform[0];
for (uint32_t pheno_transform_idx = 0; pheno_transform_idx != pheno_transform_ct; ++pheno_transform_idx) {
const uintptr_t pheno_uidx = BitIter1(phenos_to_transform, &pheno_uidx_base, &phenos_to_transform_bits);
PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]);
uintptr_t* pheno_nm = cur_pheno_col->nonmiss;
BitvecAnd(sample_include, raw_sample_ctaw, pheno_nm);
const uint32_t cur_sample_ct = PopcountWords(pheno_nm, raw_sample_ctaw);
if (cur_sample_ct < 2) {
if (cur_sample_ct) {
logerrprintfww("Warning: Exactly one value present for %s '%s'; standardizing to missing.\n", is_covar? "covariate" : "quantitative phenotype", &(pheno_names[pheno_uidx * max_pheno_name_blen]));
ZeroWArr(raw_sample_ctaw, pheno_nm);
}
continue;
}
double* pheno_qt = cur_pheno_col->data.qt;
double shifted_pheno_sum = 0.0;
double shifted_pheno_ssq = 0.0;
const uint32_t first_sample_uidx = AdvTo1Bit(pheno_nm, 0);
shifted_pheno_qt[first_sample_uidx] = 0.0;
const double pheno_shift = pheno_qt[first_sample_uidx];
uintptr_t sample_uidx_base;
uintptr_t pheno_nm_bits;
BitIter1Start(pheno_nm, first_sample_uidx + 1, &sample_uidx_base, &pheno_nm_bits);
for (uint32_t sample_idx = 1; sample_idx != cur_sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(pheno_nm, &sample_uidx_base, &pheno_nm_bits);
const double cur_shifted_pheno_val = pheno_qt[sample_uidx] - pheno_shift;
shifted_pheno_sum += cur_shifted_pheno_val;
shifted_pheno_ssq += cur_shifted_pheno_val * cur_shifted_pheno_val;
shifted_pheno_qt[sample_uidx] = cur_shifted_pheno_val;
}
const double cur_shifted_mean = shifted_pheno_sum / u31tod(cur_sample_ct);
const double variance_numer = shifted_pheno_ssq - shifted_pheno_sum * cur_shifted_mean;
if (!(variance_numer > 0.0)) {
logerrprintfww("Warning: %s '%s' is constant; standardizing to all-missing.\n", is_covar? "Covariate" : "Quantitative phenotype", &(pheno_names[pheno_uidx * max_pheno_name_blen]));
ZeroWArr(raw_sample_ctaw, pheno_nm);
continue;
}
const double cur_stdev_recip = sqrt(u31tod(cur_sample_ct - 1) / variance_numer);
BitIter1Start(pheno_nm, first_sample_uidx, &sample_uidx_base, &pheno_nm_bits);
for (uint32_t sample_idx = 0; sample_idx != cur_sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(pheno_nm, &sample_uidx_base, &pheno_nm_bits);
pheno_qt[sample_uidx] = (shifted_pheno_qt[sample_uidx] - cur_shifted_mean) * cur_stdev_recip;
}
}
// could reduce the reported number when all values were originally missing
logprintf("--%svariance-standardize: %u %s%s transformed.\n", is_covar_flag? "covar-" : "", pheno_transform_ct, is_covar? "covariate" : "phenotype", (pheno_transform_ct == 1)? "" : "s");
}
while (0) {
PhenoVarianceStandardize_ret_NOMEM:
reterr = kPglRetNomem;
break;
PhenoVarianceStandardize_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
reterr = kPglRetInconsistentInput;
break;
PhenoVarianceStandardize_ret_SKIP:
logprintf("--%svariance-standardize: No %s affected.\n", is_covar_flag? "covar-" : "", is_covar? "covariates" : "quantitative phenotypes");
break;
}
BigstackReset(bigstack_mark);
return reterr;
}
typedef struct DblIndexStruct {
double dxx;
uint32_t uii;
#ifdef __cplusplus
bool operator<(const struct DblIndexStruct& rhs) const {
return dxx < rhs.dxx;
}
#endif
} DblIndex;
PglErr PhenoQuantileNormalize(const char* quantnorm_flattened, const uintptr_t* sample_include, const char* pheno_names, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t is_covar, uint32_t is_subset_flag, PhenoCol* pheno_cols) {
unsigned char* bigstack_mark = g_bigstack_base;
const char* flag_prefix = is_subset_flag? (is_covar? "covar-" : "pheno-") : "";
PglErr reterr = kPglRetSuccess;
{
if ((!pheno_ct) || (!sample_ct)) {
goto PhenoQuantileNormalize_ret_SKIP;
}
// this boilerplate probably belongs in its own function
const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct);
uintptr_t* phenos_to_transform;
if (unlikely(bigstack_calloc_w(pheno_ctl, &phenos_to_transform))) {
goto PhenoQuantileNormalize_ret_NOMEM;
}
if (!quantnorm_flattened) {
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
if (cur_pheno_col->type_code == kPhenoDtypeQt) {
SetBit(pheno_idx, phenos_to_transform);
}
}
} else {
uint32_t* id_htable;
uint32_t id_htable_size;
if (unlikely(HtableGoodSizeAlloc(pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) {
goto PhenoQuantileNormalize_ret_NOMEM;
}
PopulateStrboxHtable(pheno_names, pheno_ct, max_pheno_name_blen, id_htable_size, id_htable);
const char* quantnorm_phenonames_iter = quantnorm_flattened;
do {
const uint32_t cur_phenoname_slen = strlen(quantnorm_phenonames_iter);
if (cur_phenoname_slen < max_pheno_name_blen) {
uint32_t pheno_idx = StrboxHtableFind(quantnorm_phenonames_iter, pheno_names, id_htable, max_pheno_name_blen, cur_phenoname_slen, id_htable_size);
if (pheno_idx != UINT32_MAX) {
if (unlikely(pheno_cols[pheno_idx].type_code != kPhenoDtypeQt)) {
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a quantitative %s.\n", quantnorm_phenonames_iter, is_covar? "covariate" : "phenotype");
goto PhenoQuantileNormalize_ret_INCONSISTENT_INPUT_WW;
}
SetBit(pheno_idx, phenos_to_transform);
}
}
quantnorm_phenonames_iter = &(quantnorm_phenonames_iter[cur_phenoname_slen + 1]);
} while (*quantnorm_phenonames_iter);
BigstackReset(id_htable);
}
const uint32_t pheno_transform_ct = PopcountWords(phenos_to_transform, pheno_ctl);
if (!pheno_transform_ct) {
goto PhenoQuantileNormalize_ret_SKIP;
}
DblIndex* tagged_raw_pheno_vals;
if (unlikely(BIGSTACK_ALLOC_X(DblIndex, sample_ct, &tagged_raw_pheno_vals))) {
goto PhenoQuantileNormalize_ret_NOMEM;
}
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
uintptr_t pheno_uidx_base = 0;
uintptr_t phenos_to_transform_bits = phenos_to_transform[0];
for (uint32_t pheno_transform_idx = 0; pheno_transform_idx != pheno_transform_ct; ++pheno_transform_idx) {
const uintptr_t pheno_uidx = BitIter1(phenos_to_transform, &pheno_uidx_base, &phenos_to_transform_bits);
PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]);
uintptr_t* pheno_nm = cur_pheno_col->nonmiss;
BitvecAnd(sample_include, raw_sample_ctaw, pheno_nm);
const uint32_t cur_sample_ct = PopcountWords(pheno_nm, raw_sample_ctaw);
if (!cur_sample_ct) {
continue;
}
double* pheno_qt = cur_pheno_col->data.qt;
uintptr_t sample_uidx_base = 0;
uintptr_t pheno_nm_bits = pheno_nm[0];
for (uint32_t sample_idx = 0; sample_idx != cur_sample_ct; ++sample_idx) {
// bugfix (1 Sep 2017): this needs to iterate over pheno_nm, not
// sample_include
const uintptr_t sample_uidx = BitIter1(pheno_nm, &sample_uidx_base, &pheno_nm_bits);
tagged_raw_pheno_vals[sample_idx].dxx = pheno_qt[sample_uidx];
tagged_raw_pheno_vals[sample_idx].uii = sample_uidx;
}
STD_SORT_PAR_UNSEQ(cur_sample_ct, double_cmp, tagged_raw_pheno_vals);
const double sample_ct_x2_recip = 1.0 / S_CAST(double, 2 * cur_sample_ct);
for (uint32_t sample_idx_start = 0; sample_idx_start != cur_sample_ct; ) {
const double cur_raw_pheno = tagged_raw_pheno_vals[sample_idx_start].dxx;
uint32_t sample_idx_end = sample_idx_start + 1;
for (; sample_idx_end != cur_sample_ct; ++sample_idx_end) {
if (tagged_raw_pheno_vals[sample_idx_end].dxx != cur_raw_pheno) {
break;
}
}
const double cur_zscore = QuantileToZscore(S_CAST(double, sample_idx_start + sample_idx_end) * sample_ct_x2_recip);
for (; sample_idx_start != sample_idx_end; ++sample_idx_start) {
pheno_qt[tagged_raw_pheno_vals[sample_idx_start].uii] = cur_zscore;
}
}
}
logprintf("--%squantile-normalize: %u %s%s transformed.\n", flag_prefix, pheno_transform_ct, is_covar? "covariate" : "phenotype", (pheno_transform_ct == 1)? "" : "s");
}
while (0) {
PhenoQuantileNormalize_ret_NOMEM:
reterr = kPglRetNomem;
break;
PhenoQuantileNormalize_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
reterr = kPglRetInconsistentInput;
break;
PhenoQuantileNormalize_ret_SKIP:
logprintf("--%squantile-normalize: No %s affected.\n", flag_prefix, is_covar? "covariates" : "quantitative phenotypes");
break;
}
BigstackReset(bigstack_mark);
return reterr;
}
PglErr ProcessBoundaryToken(const char* tok_start, const char* tok_end, const char* token_source_str, uint32_t max_boundary_ct, PglErr err_type, double* prev_boundary_ptr, uint32_t* boundary_ct_ptr, double** freq_bounds_ptr, uint64_t** ddosage_bounds_ptr) {
double cur_boundary;
const char* scan_end = ScanadvDouble(tok_start, &cur_boundary);
if (unlikely((!scan_end) || (scan_end != tok_end))) {
logerrprintf("Error: Invalid token in %s.\n", token_source_str);
return err_type;
}
if (unlikely(cur_boundary <= (*prev_boundary_ptr))) {
logerrputs("Error: Invalid bin boundary sequence (must be strictly increasing, and start\nwith a positive number).\n");
return err_type;
}
uint32_t boundary_ct = *boundary_ct_ptr;
if (unlikely(boundary_ct == max_boundary_ct)) {
#ifdef __LP64__
if (max_boundary_ct == 0x40000000) {
logerrputs("Error: Too many bin boundaries.\n");
return err_type;
}
#endif
return kPglRetNomem;
}
if (freq_bounds_ptr) {
if (unlikely(cur_boundary > 1.0)) {
logerrputs("Error: --freq bin boundary too large (must be <= 1).\n");
return err_type;
}
// strictly-greater-than comparisons
(*freq_bounds_ptr)[boundary_ct] = cur_boundary * (1 - kSmallEpsilon);
} else {
// max 2^31 - 3 variants
if (unlikely(cur_boundary > 4294967290.0)) {
logerrputs("Error: --freq counts bin boundary too large.\n");
return err_type;
}
// due to the use of strictly-greater-than for comparison, we round
// exact multiples of 1/32768 down
const int64_t int_part = S_CAST(int64_t, cur_boundary);
const double cur_boundary_frac_part = cur_boundary - int_part;
const int64_t int_part_scaled = int_part * kDosageMax;
if (cur_boundary_frac_part == 0.0) {
(*ddosage_bounds_ptr)[boundary_ct] = int_part_scaled - 1;
} else {
(*ddosage_bounds_ptr)[boundary_ct] = int_part_scaled + S_CAST(int64_t, cur_boundary_frac_part * (kDosageMax * (1 - kSmallEpsilon)));
}
}
*prev_boundary_ptr = cur_boundary;
*boundary_ct_ptr = boundary_ct + 1;
return kPglRetSuccess;
}
PglErr InitHistogramFromFileOrCommalist(const char* binstr, uint32_t is_fname, double** freq_bounds_ptr, uint64_t** ddosage_bounds_ptr, uint32_t* boundary_ct_ptr, uint32_t** histogram_ptr) {
unsigned char* bigstack_end_mark = g_bigstack_end;
TokenStream tks;
PreinitTokenStream(&tks);
uint32_t max_boundary_ct = 0;
PglErr reterr = kPglRetSuccess;
{
if (is_fname) {
// we want to accept >100000 numbers on a single line. this will reject
// "000...{a million more zeroes}...1"; pretty sure that's okay.
reterr = InitTokenStreamEx(binstr, 1, 1, &tks);
if (unlikely(reterr)) {
goto InitHistogramFromFileOrCommalist_ret_TKSTREAM_FAIL;
}
}
uintptr_t ulii = RoundDownPow2(bigstack_left(), kCacheline);
if (unlikely(ulii < 2 * kCacheline)) {
goto InitHistogramFromFileOrCommalist_ret_NOMEM;
}
// 12 = 8 bytes for boundary value + 4 bytes for histogram entry
ulii = (ulii - 2 * kCacheline) / 12;
#ifdef __LP64__
max_boundary_ct = MINV(ulii, 0x40000000);
#else
max_boundary_ct = ulii;
#endif
if (freq_bounds_ptr) {
*freq_bounds_ptr = R_CAST(double*, g_bigstack_base);
} else {
*ddosage_bounds_ptr = R_CAST(uint64_t*, g_bigstack_base);
}
uint32_t boundary_ct = 0;
double prev_boundary = 0.0;
if (is_fname) {
while (1) {
char* shard_boundaries[2];
reterr = TksNext(&tks, 1, shard_boundaries);
if (reterr) {
break;
}
char* shard_iter = shard_boundaries[0];
char* shard_end = shard_boundaries[1];
while (1) {
shard_iter = FirstPostspaceBounded(shard_iter, shard_end);
if (shard_iter == shard_end) {
break;
}
char* token_end = CurTokenEnd(shard_iter);
reterr = ProcessBoundaryToken(shard_iter, token_end, binstr, max_boundary_ct, kPglRetMalformedInput, &prev_boundary, &boundary_ct, freq_bounds_ptr, ddosage_bounds_ptr);
if (unlikely(reterr)) {
goto InitHistogramFromFileOrCommalist_ret_1;
}
shard_iter = token_end;
}
}
if (unlikely(reterr != kPglRetEof)) {
goto InitHistogramFromFileOrCommalist_ret_TKSTREAM_FAIL;
}
if (CleanupTokenStream3("--freq {ref|alt1}bins-file= file", &tks, &reterr)) {
goto InitHistogramFromFileOrCommalist_ret_1;
}
} else {
const char* binstr_iter = binstr;
while (1) {
const char* tok_end = strchrnul(binstr_iter, ',');
reterr = ProcessBoundaryToken(binstr_iter, tok_end, "--freq {ref,alt1}bins= list", max_boundary_ct, kPglRetInvalidCmdline, &prev_boundary, &boundary_ct, freq_bounds_ptr, ddosage_bounds_ptr);
if (unlikely(reterr)) {
goto InitHistogramFromFileOrCommalist_ret_1;
}
if (!(*tok_end)) {
break;
}
binstr_iter = &(tok_end[1]);
}
}
*boundary_ct_ptr = boundary_ct;
g_bigstack_base += RoundUpPow2(boundary_ct * (8 * k1LU), kCacheline);
*histogram_ptr = S_CAST(uint32_t*, bigstack_alloc_raw_rd((boundary_ct + 1) * sizeof(int32_t)));
ZeroU32Arr(boundary_ct + 1, *histogram_ptr);
}
while (0) {
InitHistogramFromFileOrCommalist_ret_NOMEM:
reterr = kPglRetNomem;
break;
InitHistogramFromFileOrCommalist_ret_TKSTREAM_FAIL:
TokenStreamErrPrint("--freq {ref|alt1}bins-file= file", &tks);
break;
}
InitHistogramFromFileOrCommalist_ret_1:
CleanupTokenStream2("--freq {ref|alt1}bins-file= file", &tks, &reterr);
BigstackEndReset(bigstack_end_mark);
return reterr;
}
PglErr WriteAlleleFreqs(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const uint64_t* founder_allele_ddosages, const double* imp_r2_vals, const char* ref_binstr, const char* alt1_binstr, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, PgenGlobalFlags gflags, FreqRptFlags freq_rpt_flags, uint32_t max_thread_ct, uint32_t nonfounders, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
FILE* outfile = nullptr;
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
{
const uint32_t counts = (freq_rpt_flags / kfAlleleFreqCounts) & 1;
if (counts) {
snprintf(outname_end, kMaxOutfnameExtBlen, ".acount");
} else {
snprintf(outname_end, kMaxOutfnameExtBlen, ".afreq");
}
if (!(freq_rpt_flags & kfAlleleFreqBinsOnly)) {
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + max_allele_ct * (24 * k1LU) + 2 * max_allele_slen;
const uint32_t output_zst = freq_rpt_flags & kfAlleleFreqZs;
if (output_zst) {
snprintf(&(outname_end[6 + counts]), kMaxOutfnameExtBlen - 7, ".zst");
}
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
if (unlikely(reterr)) {
goto WriteAlleleFreqs_ret_1;
}
*cswritep++ = '#';
const uint32_t chr_col = freq_rpt_flags & kfAlleleFreqColChrom;
// includes trailing tab
char* chr_buf;
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
goto WriteAlleleFreqs_ret_NOMEM;
}
if (chr_col) {
cswritep = strcpya_k(cswritep, "CHROM\t");
}
if (freq_rpt_flags & kfAlleleFreqColPos) {
cswritep = strcpya_k(cswritep, "POS\t");
} else {
variant_bps = nullptr;
}
cswritep = strcpya_k(cswritep, "ID");
const uint32_t ref_col = freq_rpt_flags & kfAlleleFreqColRef;
if (ref_col) {
cswritep = strcpya_k(cswritep, "\tREF");
}
const uint32_t alt1_col = freq_rpt_flags & kfAlleleFreqColAlt1;
if (alt1_col) {
cswritep = strcpya_k(cswritep, "\tALT1");
}
const uint32_t alt_col = freq_rpt_flags & kfAlleleFreqColAlt;
if (alt_col) {
cswritep = strcpya_k(cswritep, "\tALT");
}
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, freq_rpt_flags / kfAlleleFreqColMaybeprovref, raw_variant_ct, all_nonref);
if (provref_col) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
const uint32_t reffreq_col = freq_rpt_flags & kfAlleleFreqColReffreq;
if (reffreq_col) {
cswritep = strcpya_k(cswritep, "\tREF_");
if (counts) {
cswritep = strcpya_k(cswritep, "CT");
} else {
cswritep = strcpya_k(cswritep, "FREQ");
}
}
const uint32_t alt1freq_col = freq_rpt_flags & kfAlleleFreqColAlt1freq;
if (alt1freq_col) {
cswritep = strcpya_k(cswritep, "\tALT1_");
if (counts) {
cswritep = strcpya_k(cswritep, "CT");
} else {
cswritep = strcpya_k(cswritep, "FREQ");
}
}
const uint32_t freq_col = freq_rpt_flags & (kfAlleleFreqColFreq | kfAlleleFreqColAltfreq);
const uint32_t commalist_exclude_ref = (freq_rpt_flags & (kfAlleleFreqColAltfreq | kfAlleleFreqColAlteq | kfAlleleFreqColAlteqz | kfAlleleFreqColAltnumeq))? 1 : 0;
const uint32_t eq_col = freq_rpt_flags & (kfAlleleFreqColEq | kfAlleleFreqColEqz | kfAlleleFreqColAlteq | kfAlleleFreqColAlteqz | kfAlleleFreqColNumeq | kfAlleleFreqColAltnumeq);
const uint32_t eq_includez = freq_rpt_flags & (kfAlleleFreqColEqz | kfAlleleFreqColAlteqz);
const uint32_t eq_num = freq_rpt_flags & (kfAlleleFreqColNumeq | kfAlleleFreqColAltnumeq);
if (freq_col || eq_col) {
*cswritep++ = '\t';
if (commalist_exclude_ref) {
cswritep = strcpya_k(cswritep, "ALT_");
}
if (eq_num) {
cswritep = strcpya_k(cswritep, "NUM_");
}
if (counts) {
cswritep = strcpya_k(cswritep, "CTS");
} else {
cswritep = strcpya_k(cswritep, "FREQS");
}
}
const uint32_t imp_r2_col = freq_rpt_flags & (kfAlleleFreqColMachR2 | kfAlleleFreqColMinimac3R2);
if (imp_r2_col) {
// These two columns are currently mutually exclusive.
if (freq_rpt_flags & kfAlleleFreqColMachR2) {
cswritep = strcpya_k(cswritep, "\tMACH_R2");
} else {
cswritep = strcpya_k(cswritep, "\tMINIMAC3_R2");
}
}
const uint32_t nobs_col = freq_rpt_flags & kfAlleleFreqColNobs;
if (nobs_col) {
cswritep = strcpya_k(cswritep, "\tOBS_CT");
}
AppendBinaryEoln(&cswritep);
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t chr_buf_blen = 0;
uint32_t suppress_imp_r2 = 0;
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
uint32_t cur_allele_ct = 2;
printf("--freq%s%s: 0%%", output_zst? " zs" : "", counts? " counts" : "");
fflush(stdout);
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (variant_uidx >= chr_end);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
suppress_imp_r2 = (chr_idx == x_code) || (chr_idx == mt_code);
*chr_name_end = '\t';
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
}
if (chr_col) {
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
}
if (variant_bps) {
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (ref_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[0]);
}
if (alt1_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[1]);
}
if (alt_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) {
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
if (provref_col) {
*cswritep++ = '\t';
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
}
const uint64_t* cur_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]);
uint64_t tot_allele_ddosage = cur_allele_ddosages[0];
for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) {
tot_allele_ddosage += cur_allele_ddosages[allele_idx];
}
double tot_allele_ddosage_recip = 0.0;
if (!counts) {
tot_allele_ddosage_recip = 1.0 / u63tod(tot_allele_ddosage);
}
if (reffreq_col) {
*cswritep++ = '\t';
const uint64_t ref_ddosage = cur_allele_ddosages[0];
if (counts) {
// update (22 Nov 2019): we want --read-freq to be able to exactly
// replicate the original frequency. dosagetoa() is not good
// enough for this purpose.
cswritep = ddosagetoa_full(ref_ddosage, cswritep);
} else {
cswritep = dtoa_g(u63tod(ref_ddosage) * tot_allele_ddosage_recip, cswritep);
}
}
if (alt1freq_col) {
*cswritep++ = '\t';
const uint64_t alt1_ddosage = cur_allele_ddosages[1];
if (counts) {
cswritep = ddosagetoa_full(alt1_ddosage, cswritep);
} else {
cswritep = dtoa_g(u63tod(alt1_ddosage) * tot_allele_ddosage_recip, cswritep);
}
}
if (freq_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = commalist_exclude_ref; allele_idx != cur_allele_ct; ++allele_idx) {
const uint64_t cur_allele_ddosage = cur_allele_ddosages[allele_idx];
if (counts) {
cswritep = ddosagetoa_full(cur_allele_ddosage, cswritep);
} else {
cswritep = dtoa_g(u63tod(cur_allele_ddosage) * tot_allele_ddosage_recip, cswritep);
}
*cswritep++ = ',';
}
--cswritep;
} else if (eq_col) {
*cswritep++ = '\t';
uint32_t at_least_one_entry = 0;
for (uint32_t allele_idx = commalist_exclude_ref; allele_idx != cur_allele_ct; ++allele_idx) {
const uint64_t cur_allele_ddosage = cur_allele_ddosages[allele_idx];
if (eq_includez || cur_allele_ddosage) {
if (eq_num) {
cswritep = u32toa(allele_idx, cswritep);
} else {
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
const char* cur_allele = cur_alleles[allele_idx];
const char* cur_allele_end_or_eq = strchrnul(cur_allele, '=');
if (unlikely(*cur_allele_end_or_eq == '=')) {
logerrputs("Error: --freq's 'eq', 'eqz', 'alteq', and 'alteqz' columns cannot be requested\nwhen an allele code contains a '='.\n");
goto WriteAlleleFreqs_ret_INCONSISTENT_INPUT;
}
cswritep = memcpya(cswritep, cur_allele, cur_allele_end_or_eq - cur_allele);
}
*cswritep++ = '=';
if (counts) {
cswritep = ddosagetoa_full(cur_allele_ddosage, cswritep);
} else {
cswritep = dtoa_g(u63tod(cur_allele_ddosage) * tot_allele_ddosage_recip, cswritep);
}
*cswritep++ = ',';
at_least_one_entry = 1;
}
}
if (at_least_one_entry) {
--cswritep;
} else {
*cswritep++ = '.';
}
}
if (imp_r2_col) {
*cswritep++ = '\t';
if (!suppress_imp_r2) {
cswritep = dtoa_g(imp_r2_vals[variant_uidx], cswritep);
} else {
cswritep = strcpya_k(cswritep, "NA");
}
}
if (nobs_col) {
*cswritep++ = '\t';
cswritep = u32toa(tot_allele_ddosage / kDosageMax, cswritep);
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
putc_unlocked('\r', stdout);
logprintfww("--freq%s%s: Allele %s (%s) written to %s .\n", output_zst? " zs" : "", counts? " counts" : "", counts? "counts" : "frequencies", nonfounders? "all samples" : "founders only", outname);
}
if (ref_binstr || alt1_binstr) {
BigstackReset(bigstack_mark);
double* ref_freq_bounds = nullptr;
uint64_t* ref_ddosage_bounds = nullptr;
uint32_t* ref_histogram = nullptr;
uint32_t ref_boundary_ct = 0;
if (ref_binstr) {
reterr = InitHistogramFromFileOrCommalist(ref_binstr, (freq_rpt_flags / kfAlleleFreqBinsRefFname) & 1, counts? nullptr : (&ref_freq_bounds), counts? (&ref_ddosage_bounds) : nullptr, &ref_boundary_ct, &ref_histogram);
if (unlikely(reterr)) {
goto WriteAlleleFreqs_ret_1;
}
}
double* alt1_freq_bounds = nullptr;
uint64_t* alt1_ddosage_bounds = nullptr;
uint32_t* alt1_histogram = nullptr;
uint32_t alt1_boundary_ct = 0;
if (alt1_binstr) {
reterr = InitHistogramFromFileOrCommalist(alt1_binstr, (freq_rpt_flags / kfAlleleFreqBinsAlt1Fname) & 1, counts? nullptr : (&alt1_freq_bounds), counts? (&alt1_ddosage_bounds) : nullptr, &alt1_boundary_ct, &alt1_histogram);
if (unlikely(reterr)) {
goto WriteAlleleFreqs_ret_1;
}
}
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
if (!counts) {
uint32_t cur_allele_ct = 2;
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const uint64_t* cur_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]);
const uint64_t ref_allele_ddosage = cur_allele_ddosages[0];
const uint64_t alt1_allele_ddosage = cur_allele_ddosages[1];
uint64_t tot_allele_ddosage = ref_allele_ddosage + alt1_allele_ddosage;
for (uint32_t allele_idx = 2; allele_idx != cur_allele_ct; ++allele_idx) {
tot_allele_ddosage += cur_allele_ddosages[allele_idx];
}
const double tot_allele_ddosage_recip = 1.0 / u63tod(tot_allele_ddosage);
if (ref_histogram) {
ref_histogram[LowerBoundNonemptyD(ref_freq_bounds, ref_boundary_ct, ref_allele_ddosage * tot_allele_ddosage_recip)] += 1;
}
if (alt1_histogram) {
alt1_histogram[LowerBoundNonemptyD(alt1_freq_bounds, alt1_boundary_ct, alt1_allele_ddosage * tot_allele_ddosage_recip)] += 1;
}
}
} else {
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
}
const uint64_t* cur_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]);
if (ref_histogram) {
ref_histogram[LowerBoundNonemptyU64(ref_ddosage_bounds, ref_boundary_ct, cur_allele_ddosages[0])] += 1;
}
if (alt1_histogram) {
alt1_histogram[LowerBoundNonemptyU64(alt1_ddosage_bounds, alt1_boundary_ct, cur_allele_ddosages[1])] += 1;
}
}
}
for (uint32_t is_alt1 = 0; is_alt1 != 2; ++is_alt1) {
const uint32_t* cur_histogram = is_alt1? alt1_histogram : ref_histogram;
if (!cur_histogram) {
continue;
}
char* outname_end2 = &(outname_end[6 + counts]);
if (!is_alt1) {
outname_end2 = strcpya_k(outname_end2, ".ref");
} else {
outname_end2 = strcpya_k(outname_end2, ".alt1");
}
snprintf(outname_end2, kMaxOutfnameExtBlen - 12, ".bins");
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
goto WriteAlleleFreqs_ret_OPEN_FAIL;
}
char* textbuf = g_textbuf;
char* textbuf_flush = &(textbuf[kMaxMediumLine]);
char* write_iter = strcpya_k(textbuf, "#BIN_START\tOBS_CT" EOLN_STR);
const uint32_t cur_boundary_ct = is_alt1? alt1_boundary_ct : ref_boundary_ct;
if (!counts) {
const double* cur_freq_bounds = is_alt1? alt1_freq_bounds : ref_freq_bounds;
for (uint32_t bin_idx = 0; bin_idx <= cur_boundary_ct; ++bin_idx) {
if (!bin_idx) {
*write_iter++ = '0';
} else {
write_iter = dtoa_g(cur_freq_bounds[bin_idx - 1] * (1.0 / (1 - kSmallEpsilon)), write_iter);
}
*write_iter++ = '\t';
write_iter = u32toa(cur_histogram[bin_idx], write_iter);
AppendBinaryEoln(&write_iter);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
}
} else {
const uint64_t* cur_ddosage_bounds = is_alt1? alt1_ddosage_bounds : ref_ddosage_bounds;
for (uint32_t bin_idx = 0; bin_idx <= cur_boundary_ct; ++bin_idx) {
if (!bin_idx) {
*write_iter++ = '0';
} else {
write_iter = ddosagetoa(1 + cur_ddosage_bounds[bin_idx - 1], write_iter);
}
*write_iter++ = '\t';
write_iter = u32toa(cur_histogram[bin_idx], write_iter);
AppendBinaryEoln(&write_iter);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
}
}
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
goto WriteAlleleFreqs_ret_WRITE_FAIL;
}
const uint32_t cur_is_file = freq_rpt_flags & (is_alt1? kfAlleleFreqBinsAlt1Fname : kfAlleleFreqBinsRefFname);
logprintfww("--freq%s %sbins%s=: Histogram written to %s .\n", counts? " counts" : "", is_alt1? "alt1" : "ref", cur_is_file? "-file" : "", outname);
}
}
}
while (0) {
WriteAlleleFreqs_ret_NOMEM:
reterr = kPglRetNomem;
break;
WriteAlleleFreqs_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
WriteAlleleFreqs_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
WriteAlleleFreqs_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
WriteAlleleFreqs_ret_1:
CswriteCloseCond(&css, cswritep);
fclose_cond(outfile);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr WriteGenoCounts(const uintptr_t* sample_include, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const STD_ARRAY_PTR_DECL(uint32_t, 3, raw_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, x_male_geno_cts), uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t male_ct, uint32_t nosex_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t x_start, uint32_t max_allele_slen, PgenGlobalFlags gflags, GenoCountsFlags geno_counts_flags, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
{
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
char* chr_buf;
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
goto WriteGenoCounts_ret_NOMEM;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
const uint32_t max_allele_ct = PgrGetMaxAlleleCt(simple_pgrp);
uint32_t* sample_include_cumulative_popcounts = nullptr;
uintptr_t* sex_male_collapsed = nullptr; // chrX
const uintptr_t* sex_nonfemale = sex_male;
uint32_t* sex_nonfemale_cumulative_popcounts = nullptr; // chrY
PgenVariant pgv;
pgv.genovec = nullptr;
pgv.patch_01_set = nullptr;
pgv.patch_01_vals = nullptr;
pgv.patch_10_set = nullptr;
pgv.patch_10_vals = nullptr;
uint32_t* diploid_pair_cts = nullptr;
uint32_t* hap_cts = nullptr;
const uint32_t more_counts_needed = (max_allele_ct > 2) && (geno_counts_flags & (kfGenoCountsColRefalt1 | kfGenoCountsColRefalt | kfGenoCountsColHomalt1 | kfGenoCountsColAltxy | kfGenoCountsColXy | kfGenoCountsColHapalt1 | kfGenoCountsColHapalt | kfGenoCountsColHap | kfGenoCountsColNumeq));
const uint32_t nonfemale_ct = male_ct + nosex_ct;
if (more_counts_needed) {
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
bigstack_alloc_w(sample_ctl, &sex_male_collapsed) ||
bigstack_alloc_u32(raw_sample_ctl, &sex_nonfemale_cumulative_popcounts) ||
bigstack_alloc_w(NypCtToWordCt(raw_sample_ct), &pgv.genovec) ||
bigstack_alloc_w(sample_ctl, &pgv.patch_01_set) ||
bigstack_alloc_ac(sample_ct, &pgv.patch_01_vals) ||
bigstack_alloc_w(sample_ctl, &pgv.patch_10_set) ||
bigstack_alloc_ac(2 * sample_ct, &pgv.patch_10_vals) ||
bigstack_alloc_u32(max_allele_ct * max_allele_ct, &diploid_pair_cts) ||
bigstack_alloc_u32(max_allele_ct, &hap_cts))) {
goto WriteGenoCounts_ret_NOMEM;
}
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed);
if (nosex_ct) {
uintptr_t* nonfemale_tmp;
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &nonfemale_tmp))) {
goto WriteGenoCounts_ret_NOMEM;
}
AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, nonfemale_tmp);
sex_nonfemale = nonfemale_tmp;
}
FillCumulativePopcounts(sex_nonfemale, raw_sample_ctl, sex_nonfemale_cumulative_popcounts);
}
// Will need to remove quadratic dependency on max_allele_ct if
// sizeof(AlleleCode) > 1.
// The actual number of numeq and {alt}xy entries is roughly half of
// allele_ct^2, so 12 * allele_ct^2 allows 20 bytes per entry when both
// fields are present simultaneously, which is more than enough. (The
// surplus and the 512 constant are enough to cover the linearly-growing
// fields.)
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + max_allele_ct * max_allele_ct * 20 + 2 * max_allele_slen;
const uint32_t output_zst = geno_counts_flags & kfGenoCountsZs;
OutnameZstSet(".gcount", output_zst, outname_end);
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
if (unlikely(reterr)) {
goto WriteGenoCounts_ret_1;
}
*cswritep++ = '#';
const uint32_t chr_col = geno_counts_flags & kfGenoCountsColChrom;
// includes trailing tab
if (chr_col) {
cswritep = strcpya_k(cswritep, "CHROM\t");
}
if (geno_counts_flags & kfGenoCountsColPos) {
cswritep = strcpya_k(cswritep, "POS\t");
} else {
variant_bps = nullptr;
}
cswritep = strcpya_k(cswritep, "ID");
const uint32_t ref_col = geno_counts_flags & kfGenoCountsColRef;
if (ref_col) {
cswritep = strcpya_k(cswritep, "\tREF");
}
const uint32_t alt1_col = geno_counts_flags & kfGenoCountsColAlt1;
if (alt1_col) {
cswritep = strcpya_k(cswritep, "\tALT1");
}
const uint32_t alt_col = geno_counts_flags & kfGenoCountsColAlt;
if (alt_col) {
cswritep = strcpya_k(cswritep, "\tALT");
}
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, geno_counts_flags / kfGenoCountsColMaybeprovref, raw_variant_ct, all_nonref);
if (provref_col) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
const uint32_t homref_col = geno_counts_flags & kfGenoCountsColHomref;
if (homref_col) {
cswritep = strcpya_k(cswritep, "\tHOM_REF_CT");
}
const uint32_t refalt1_col = geno_counts_flags & kfGenoCountsColRefalt1;
if (refalt1_col) {
cswritep = strcpya_k(cswritep, "\tHET_REF_ALT1_CT");
}
const uint32_t refalt_col = geno_counts_flags & kfGenoCountsColRefalt;
if (refalt_col) {
cswritep = strcpya_k(cswritep, "\tHET_REF_ALT_CTS");
}
const uint32_t homalt1_col = geno_counts_flags & kfGenoCountsColHomalt1;
if (homalt1_col) {
cswritep = strcpya_k(cswritep, "\tHOM_ALT1_CT");
}
const uint32_t xy_col = geno_counts_flags & (kfGenoCountsColAltxy | kfGenoCountsColXy);
const uint32_t xy_col_altonly = (geno_counts_flags / kfGenoCountsColAltxy) & 1;
if (xy_col) {
*cswritep++ = '\t';
if (xy_col_altonly) {
cswritep = strcpya_k(cswritep, "TWO_ALT_GENO_CTS");
} else {
cswritep = strcpya_k(cswritep, "DIPLOID_GENO_CTS");
}
}
const uint32_t hapref_col = geno_counts_flags & kfGenoCountsColHapref;
if (hapref_col) {
cswritep = strcpya_k(cswritep, "\tHAP_REF_CT");
}
const uint32_t hapalt1_col = geno_counts_flags & kfGenoCountsColHapalt1;
if (hapalt1_col) {
cswritep = strcpya_k(cswritep, "\tHAP_ALT1_CT");
}
const uint32_t hap_col = geno_counts_flags & (kfGenoCountsColHapalt | kfGenoCountsColHap);
const uint32_t hap_col_altonly = (geno_counts_flags / kfGenoCountsColHapalt) & 1;
if (hap_col) {
if (hap_col_altonly) {
cswritep = strcpya_k(cswritep, "\tHAP_ALT_CTS");
} else {
cswritep = strcpya_k(cswritep, "\tHAP_CTS");
}
}
const uint32_t numeq_col = geno_counts_flags & kfGenoCountsColNumeq;
if (numeq_col) {
cswritep = strcpya_k(cswritep, "\tGENO_NUM_CTS");
}
const uint32_t missing_col = geno_counts_flags & kfGenoCountsColMissing;
if (missing_col) {
cswritep = strcpya_k(cswritep, "\tMISSING_CT");
}
const uint32_t nobs_col = geno_counts_flags & kfGenoCountsColNobs;
if (nobs_col) {
cswritep = strcpya_k(cswritep, "\tOBS_CT");
}
AppendBinaryEoln(&cswritep);
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
const uintptr_t* cur_sample_include = nullptr;
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
uint32_t is_autosomal_diploid = 0;
uint32_t is_x = 0;
uint32_t is_y = 0;
uint32_t nobs_base = 0;
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t chr_buf_blen = 0;
uint32_t homref_ct = 0;
uint32_t het_ct = 0;
uint32_t homalt1_ct = 0;
uint32_t hapref_ct = 0;
uint32_t hapalt1_ct = 0;
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
printf("--geno-counts%s: 0%%", output_zst? " zs" : "");
fflush(stdout);
PgrSampleSubsetIndex pssi;
PgrClearSampleSubsetIndex(simple_pgrp, &pssi);
uint32_t allele_ct = 2;
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (variant_uidx >= chr_end);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
*chr_name_end = '\t';
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
is_autosomal_diploid = !IsSet(cip->haploid_mask, chr_idx);
nobs_base = sample_ct;
is_x = (chr_idx == x_code);
is_y = (chr_idx == y_code);
cur_sample_include = sample_include;
const uint32_t* cur_cumulative_popcounts = sample_include_cumulative_popcounts;
if (!is_autosomal_diploid) {
if (is_y) {
cur_sample_include = sex_nonfemale;
cur_cumulative_popcounts = sex_nonfemale_cumulative_popcounts;
nobs_base = nonfemale_ct;
}
}
PgrSetSampleSubsetIndex(cur_cumulative_popcounts, simple_pgrp, &pssi);
homref_ct = 0;
het_ct = 0;
homalt1_ct = 0;
hapref_ct = 0;
hapalt1_ct = 0;
}
if (chr_col) {
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
}
if (variant_bps) {
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (ref_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[0]);
}
if (alt1_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[1]);
}
if (alt_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteGenoCounts_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
if (provref_col) {
*cswritep++ = '\t';
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
}
STD_ARRAY_KREF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx];
uint32_t missing_ct;
if ((allele_ct == 2) || (!more_counts_needed)) {
if (is_autosomal_diploid) {
homref_ct = cur_raw_geno_cts[0];
het_ct = cur_raw_geno_cts[1];
homalt1_ct = cur_raw_geno_cts[2];
missing_ct = nobs_base - homref_ct - het_ct - homalt1_ct;
} else {
if (is_x) {
// bugfix (8 Oct 2017): don't set these in haploid case
homref_ct = cur_raw_geno_cts[0];
het_ct = cur_raw_geno_cts[1];
homalt1_ct = cur_raw_geno_cts[2];
if (x_male_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = x_male_geno_cts[variant_uidx - x_start];
hapref_ct = cur_male_geno_cts[0];
homref_ct -= hapref_ct;
het_ct -= cur_male_geno_cts[1];
hapalt1_ct = cur_male_geno_cts[2];
homalt1_ct -= hapalt1_ct;
}
missing_ct = nobs_base - homref_ct - het_ct - homalt1_ct - hapref_ct - hapalt1_ct;
} else {
// chrY or other pure-haploid; hethap treated as missing
hapref_ct = cur_raw_geno_cts[0];
hapalt1_ct = cur_raw_geno_cts[2];
missing_ct = nobs_base - hapref_ct - hapalt1_ct;
}
}
if (homref_col) {
*cswritep++ = '\t';
cswritep = u32toa(homref_ct, cswritep);
}
if (refalt1_col) {
*cswritep++ = '\t';
cswritep = u32toa(het_ct, cswritep);
}
if (refalt_col) {
*cswritep++ = '\t';
cswritep = u32toa(het_ct, cswritep);
}
if (homalt1_col) {
*cswritep++ = '\t';
cswritep = u32toa(homalt1_ct, cswritep);
}
if (xy_col_altonly) {
*cswritep++ = '\t';
cswritep = u32toa(homalt1_ct, cswritep);
} else if (xy_col) {
*cswritep++ = '\t';
cswritep = u32toa_x(homref_ct, ',', cswritep);
cswritep = u32toa_x(het_ct, ',', cswritep);
cswritep = u32toa(homalt1_ct, cswritep);
}
if (hapref_col) {
*cswritep++ = '\t';
cswritep = u32toa(hapref_ct, cswritep);
}
if (hapalt1_col) {
*cswritep++ = '\t';
cswritep = u32toa(hapalt1_ct, cswritep);
}
if (hap_col) {
*cswritep++ = '\t';
if (!hap_col_altonly) {
cswritep = u32toa_x(hapref_ct, ',', cswritep);
}
cswritep = u32toa(hapalt1_ct, cswritep);
}
if (numeq_col) {
*cswritep++ = '\t';
if (homref_ct) {
cswritep = strcpya_k(cswritep, "0/0=");
cswritep = u32toa_x(homref_ct, ',', cswritep);
}
if (het_ct) {
cswritep = strcpya_k(cswritep, "0/1=");
cswritep = u32toa_x(het_ct, ',', cswritep);
}
if (homalt1_ct) {
cswritep = strcpya_k(cswritep, "1/1=");
cswritep = u32toa_x(homalt1_ct, ',', cswritep);
}
if (hapref_ct) {
cswritep = strcpya_k(cswritep, "0=");
cswritep = u32toa_x(hapref_ct, ',', cswritep);
}
if (hapalt1_ct) {
cswritep = strcpya_k(cswritep, "1=");
cswritep = u32toa_x(hapalt1_ct, ',', cswritep);
}
if (missing_ct != nobs_base) {
--cswritep;
} else {
*cswritep++ = '.';
}
}
} else {
reterr = PgrGetM(cur_sample_include, pssi, nobs_base, variant_uidx, simple_pgrp, &pgv);
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, variant_uidx);
goto WriteGenoCounts_ret_1;
}
// Usually don't care about contents of genovec, patch_01_set, and
// patch_10_set, but chrX is an exception.
// Need to have an alternate strategy once sizeof(AlleleCode) > 1.
ZeroU32Arr(allele_ct * allele_ct, diploid_pair_cts);
diploid_pair_cts[0] = cur_raw_geno_cts[0];
// lo_idx * allele_ct + hi_idx
diploid_pair_cts[1] = cur_raw_geno_cts[1] - pgv.patch_01_ct;
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
diploid_pair_cts[pgv.patch_01_vals[uii]] += 1;
}
const uintptr_t allele_ctp1 = allele_ct + 1;
diploid_pair_cts[allele_ctp1] = cur_raw_geno_cts[2] - pgv.patch_10_ct;
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii];
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1];
diploid_pair_cts[lo_code * allele_ct + hi_code] += 1;
}
if (is_autosomal_diploid) {
homref_ct = cur_raw_geno_cts[0];
homalt1_ct = diploid_pair_cts[allele_ctp1];
missing_ct = nobs_base - cur_raw_geno_cts[0] - cur_raw_geno_cts[1] - cur_raw_geno_cts[2];
hap_cts[0] = 0;
hap_cts[1] = 0;
} else {
if (is_x) {
missing_ct = nobs_base - cur_raw_geno_cts[0] - cur_raw_geno_cts[1] - cur_raw_geno_cts[2];
ZeroU32Arr(allele_ct, hap_cts);
if (x_male_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = x_male_geno_cts[variant_uidx - x_start];
hap_cts[0] = cur_male_geno_cts[0];
diploid_pair_cts[0] -= cur_male_geno_cts[0];
// possible todo: try making two disjoint PgrGetM calls instead.
// don't expect that to be better, though.
uintptr_t sample_widx = 0;
uintptr_t cur_patch_bits = pgv.patch_01_set[0];
uint32_t male_patch_01_ct = 0;
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &cur_patch_bits);
if (sex_male_collapsed[sample_widx] & lowbit) {
diploid_pair_cts[pgv.patch_01_vals[uii]] -= 1;
++male_patch_01_ct;
}
}
missing_ct += male_patch_01_ct;
diploid_pair_cts[1] -= cur_male_geno_cts[1] - male_patch_01_ct;
sample_widx = 0;
cur_patch_bits = pgv.patch_10_set[0];
uint32_t* hap_cts_offset1 = &(hap_cts[1]);
uint32_t male_patch_10_ct = 0;
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &cur_patch_bits);
if (sex_male_collapsed[sample_widx] & lowbit) {
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii];
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1];
diploid_pair_cts[lo_code * allele_ct + hi_code] -= 1;
++male_patch_10_ct;
if (lo_code == hi_code) {
hap_cts_offset1[lo_code] += 1;
}
}
}
missing_ct += male_patch_10_ct;
hap_cts[1] = cur_male_geno_cts[2] - male_patch_10_ct;
diploid_pair_cts[allele_ctp1] -= hap_cts[1];
for (uint32_t aidx = 2; aidx != allele_ct; ++aidx) {
// subtract male rarehoms
missing_ct -= hap_cts[aidx];
}
}
homref_ct = diploid_pair_cts[0];
homalt1_ct = diploid_pair_cts[allele_ctp1];
} else {
// chrY or other pure-haploid; hethap treated as missing
uint32_t nonmissing_ct = 0;
for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) {
const uint32_t cur_ct = diploid_pair_cts[aidx * allele_ctp1];
hap_cts[aidx] = cur_ct;
nonmissing_ct += cur_ct;
}
missing_ct = nobs_base - nonmissing_ct;
}
}
if (homref_col) {
*cswritep++ = '\t';
cswritep = u32toa(homref_ct, cswritep);
}
if (refalt1_col) {
if (is_autosomal_diploid || is_x) {
*cswritep++ = '\t';
cswritep = u32toa(diploid_pair_cts[1], cswritep);
} else {
cswritep = strcpya_k(cswritep, "\t0");
}
}
if (refalt_col) {
*cswritep++ = '\t';
if (is_autosomal_diploid || is_x) {
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) {
cswritep = u32toa_x(diploid_pair_cts[aidx], ',', cswritep);
}
--cswritep;
} else {
// repeat "0,"
cswritep = u16setsa(cswritep, 0x2c30, allele_ct - 2);
*cswritep++ = '0';
}
}
if (homalt1_col) {
*cswritep++ = '\t';
cswritep = u32toa(homalt1_ct, cswritep);
}
if (xy_col) {
*cswritep++ = '\t';
if (is_autosomal_diploid || is_x) {
for (uint32_t aidx_hi = xy_col_altonly; aidx_hi != allele_ct; ++aidx_hi) {
for (uint32_t aidx_lo = xy_col_altonly; aidx_lo <= aidx_hi; ++aidx_lo) {
cswritep = u32toa_x(diploid_pair_cts[aidx_lo * allele_ct + aidx_hi], ',', cswritep);
}
}
--cswritep;
} else {
const uint32_t triangle_base = allele_ct - xy_col_altonly;
cswritep = u16setsa(cswritep, 0x2c30, (triangle_base * (triangle_base + 1) / 2) - 1);
*cswritep++ = '0';
}
}
if (hapref_col) {
*cswritep++ = '\t';
cswritep = u32toa(hap_cts[0], cswritep);
}
if (hapalt1_col) {
*cswritep++ = '\t';
cswritep = u32toa(hap_cts[1], cswritep);
}
if (hap_col) {
*cswritep++ = '\t';
if (!is_autosomal_diploid) {
for (uint32_t aidx = hap_col_altonly; aidx != allele_ct; ++aidx) {
cswritep = u32toa_x(hap_cts[aidx], ',', cswritep);
}
--cswritep;
} else {
cswritep = u16setsa(cswritep, 0x2c30, allele_ct - hap_col_altonly - 1);
*cswritep++ = '0';
}
}
if (numeq_col) {
*cswritep++ = '\t';
if (is_autosomal_diploid || is_x) {
for (uint32_t aidx_hi = 0; aidx_hi != allele_ct; ++aidx_hi) {
for (uint32_t aidx_lo = 0; aidx_lo <= aidx_hi; ++aidx_lo) {
const uint32_t cur_ct = diploid_pair_cts[aidx_lo * allele_ct + aidx_hi];
if (cur_ct) {
cswritep = u32toa_x(aidx_lo, '/', cswritep);
cswritep = u32toa_x(aidx_hi, '=', cswritep);
cswritep = u32toa_x(cur_ct, ',', cswritep);
}
}
}
}
if (!is_autosomal_diploid) {
for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) {
const uint32_t cur_ct = hap_cts[aidx];
if (cur_ct) {
cswritep = u32toa_x(aidx, '=', cswritep);
cswritep = u32toa_x(cur_ct, ',', cswritep);
}
}
}
if (missing_ct != nobs_base) {
--cswritep;
} else {
*cswritep++ = '.';
}
}
}
if (missing_col) {
*cswritep++ = '\t';
cswritep = u32toa(missing_ct, cswritep);
}
if (nobs_col) {
*cswritep++ = '\t';
cswritep = u32toa(nobs_base - missing_ct, cswritep);
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteGenoCounts_ret_WRITE_FAIL;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto WriteGenoCounts_ret_WRITE_FAIL;
}
putc_unlocked('\r', stdout);
logprintfww("--geno-counts%s: Genotype counts written to %s .\n", output_zst? " zs" : "", outname);
}
while (0) {
WriteGenoCounts_ret_NOMEM:
reterr = kPglRetNomem;
break;
WriteGenoCounts_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
}
WriteGenoCounts_ret_1:
CswriteCloseCond(&css, cswritep);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr WriteMissingnessReports(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uint32_t* sample_missing_hc_cts, const uint32_t* sample_missing_dosage_cts, const uint32_t* sample_hethap_cts, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const uint32_t* variant_missing_hc_cts, const uint32_t* variant_missing_dosage_cts, const uint32_t* variant_hethap_cts, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t variant_ct, uintptr_t max_allele_slen, uint32_t y_nosex_missing_stats, PgenGlobalFlags gflags, uint32_t first_hap_uidx, MissingRptFlags missing_rpt_flags, uint32_t max_thread_ct, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
{
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
const uintptr_t* chry_missingstat_include = sex_male;
if (y_nosex_missing_stats) {
uintptr_t* nonfemale_tmp;
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &nonfemale_tmp))) {
goto WriteMissingnessReports_ret_NOMEM;
}
AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, nonfemale_tmp);
chry_missingstat_include = nonfemale_tmp;
}
const uint32_t chry_missingstat_sample_ct = PopcountWords(chry_missingstat_include, raw_sample_ctl);
const uint32_t output_zst = missing_rpt_flags & kfMissingRptZs;
if (!(missing_rpt_flags & kfMissingRptVariantOnly)) {
const uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxMediumLine + pheno_ct * 2;
OutnameZstSet(".smiss", output_zst, outname_end);
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
if (unlikely(reterr)) {
goto WriteMissingnessReports_ret_1;
}
*cswritep++ = '#';
const uint32_t scol_fid = FidColIsRequired(siip, missing_rpt_flags / kfMissingRptScolMaybefid);
if (scol_fid) {
cswritep = strcpya_k(cswritep, "FID\t");
}
cswritep = strcpya_k(cswritep, "IID");
const char* sample_ids = siip->sample_ids;
const char* sids = siip->sids;
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
const uintptr_t max_sid_blen = siip->max_sid_blen;
const uint32_t scol_sid = SidColIsRequired(sids, missing_rpt_flags / kfMissingRptScolMaybesid);
if (scol_sid) {
cswritep = strcpya_k(cswritep, "\tSID");
}
const uint32_t scol_empty_pheno = (missing_rpt_flags & kfMissingRptScolMisspheno1) && (!pheno_ct);
if (scol_empty_pheno) {
cswritep = strcpya_k(cswritep, "\tMISS_PHENO1");
}
const uint32_t scol_phenos = (missing_rpt_flags & (kfMissingRptScolMisspheno1 | kfMissingRptScolMissphenos)) && pheno_ct;
if (scol_phenos) {
if (!(missing_rpt_flags & kfMissingRptScolMissphenos)) {
pheno_ct = 1;
}
for (uintptr_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, &(pheno_names[pheno_idx * max_pheno_name_blen]));
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
}
}
const uint32_t scol_nmiss_dosage = (missing_rpt_flags / kfMissingRptScolNmissDosage) & 1;
if (scol_nmiss_dosage) {
cswritep = strcpya_k(cswritep, "\tMISSING_DOSAGE_CT");
}
const uint32_t scol_nmiss = (missing_rpt_flags / kfMissingRptScolNmiss) & 1;
if (scol_nmiss) {
cswritep = strcpya_k(cswritep, "\tMISSING_CT");
}
const uint32_t scol_nmiss_hh = (missing_rpt_flags / kfMissingRptScolNmissHh) & 1;
if (scol_nmiss_hh) {
cswritep = strcpya_k(cswritep, "\tMISSING_AND_HETHAP_CT");
}
const uint32_t scol_hethap = (missing_rpt_flags / kfMissingRptScolHethap) & 1;
if (scol_hethap) {
cswritep = strcpya_k(cswritep, "\tHETHAP_CT");
}
const uint32_t scol_nobs = (missing_rpt_flags / kfMissingRptScolNobs) & 1;
if (scol_nobs) {
cswritep = strcpya_k(cswritep, "\tOBS_CT");
}
const uint32_t scol_fmiss_dosage = (missing_rpt_flags / kfMissingRptScolFmissDosage) & 1;
if (scol_fmiss_dosage) {
cswritep = strcpya_k(cswritep, "\tF_MISS_DOSAGE");
}
const uint32_t scol_fmiss = (missing_rpt_flags / kfMissingRptScolFmiss) & 1;
if (scol_fmiss) {
cswritep = strcpya_k(cswritep, "\tF_MISS");
}
const uint32_t scol_fmiss_hh = (missing_rpt_flags / kfMissingRptScolFmissHh) & 1;
if (scol_fmiss_hh) {
cswritep = strcpya_k(cswritep, "\tF_MISS_AND_HETHAP");
}
AppendBinaryEoln(&cswritep);
uint32_t variant_ct_y = 0;
uint32_t y_code;
if (XymtExists(cip, kChrOffsetY, &y_code)) {
variant_ct_y = CountChrVariantsUnsafe(variant_include, cip, y_code);
}
const uint32_t variant_ct_nony = variant_ct - variant_ct_y;
char nobs_strs[2][16];
uint32_t nobs_slens[2];
double variant_ct_recips[2];
{
char* write_iter = nobs_strs[0];
*write_iter++ = '\t';
write_iter = u32toa(variant_ct_nony, write_iter);
nobs_slens[0] = write_iter - nobs_strs[0];
variant_ct_recips[0] = 1.0 / u31tod(variant_ct_nony);
write_iter = nobs_strs[1];
*write_iter++ = '\t';
write_iter = u32toa(variant_ct, write_iter);
nobs_slens[1] = write_iter - nobs_strs[1];
}
variant_ct_recips[1] = 1.0 / u31tod(variant_ct);
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
cswritep = AppendXid(sample_ids, sids, scol_fid, scol_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep);
if (scol_phenos) {
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
*cswritep++ = '\t';
// 'Y' - 'N' == 11
*cswritep++ = 'Y' - 11 * IsSet(pheno_cols[pheno_idx].nonmiss, sample_uidx);
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
}
} else {
if (scol_empty_pheno) {
cswritep = strcpya_k(cswritep, "\tY");
}
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
}
if (scol_nmiss_dosage) {
*cswritep++ = '\t';
cswritep = u32toa(sample_missing_dosage_cts[sample_uidx], cswritep);
}
const uint32_t cur_missing_hc_base = sample_missing_hc_cts[sample_uidx];
if (scol_nmiss) {
*cswritep++ = '\t';
cswritep = u32toa(cur_missing_hc_base, cswritep);
}
if (scol_nmiss_hh) {
*cswritep++ = '\t';
cswritep = u32toa(cur_missing_hc_base + sample_hethap_cts[sample_uidx], cswritep);
}
if (scol_hethap) {
*cswritep++ = '\t';
cswritep = u32toa(sample_hethap_cts[sample_uidx], cswritep);
}
const uint32_t chry_included = IsSet(chry_missingstat_include, sample_uidx);
if (scol_nobs) {
cswritep = memcpya(cswritep, nobs_strs[chry_included], nobs_slens[chry_included]);
}
const double cur_variant_ct_recip = variant_ct_recips[chry_included];
if (scol_fmiss_dosage) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(sample_missing_dosage_cts[sample_uidx]) * cur_variant_ct_recip, cswritep);
}
if (scol_fmiss) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(cur_missing_hc_base) * cur_variant_ct_recip, cswritep);
}
if (scol_fmiss_hh) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(cur_missing_hc_base + sample_hethap_cts[sample_uidx]) * cur_variant_ct_recip, cswritep);
}
AppendBinaryEoln(&cswritep);
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
BigstackReset(bigstack_mark);
logprintfww("--missing: Sample missing data report written to %s .\n", outname);
}
if (!(missing_rpt_flags & kfMissingRptSampleOnly)) {
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
char* chr_buf; // includes trailing tab
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
goto WriteMissingnessReports_ret_NOMEM;
}
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + 2 * max_allele_slen;
OutnameZstSet(".vmiss", output_zst, outname_end);
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
if (unlikely(reterr)) {
goto WriteMissingnessReports_ret_1;
}
*cswritep++ = '#';
const uint32_t chr_col = missing_rpt_flags & kfMissingRptVcolChrom;
if (chr_col) {
cswritep = strcpya_k(cswritep, "CHROM\t");
}
if (missing_rpt_flags & kfMissingRptVcolPos) {
cswritep = strcpya_k(cswritep, "POS\t");
} else {
variant_bps = nullptr;
}
cswritep = strcpya_k(cswritep, "ID");
const uint32_t ref_col = missing_rpt_flags & kfMissingRptVcolRef;
if (ref_col) {
cswritep = strcpya_k(cswritep, "\tREF");
}
const uint32_t alt_col = missing_rpt_flags & kfMissingRptVcolAlt;
if (alt_col) {
cswritep = strcpya_k(cswritep, "\tALT");
}
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, missing_rpt_flags / kfMissingRptVcolMaybeprovref, raw_variant_ct, all_nonref);
if (provref_col) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
const uint32_t nmiss_dosage_col = missing_rpt_flags & kfMissingRptVcolNmissDosage;
if (nmiss_dosage_col) {
cswritep = strcpya_k(cswritep, "\tMISSING_DOSAGE_CT");
}
const uint32_t nmiss_col = (missing_rpt_flags / kfMissingRptVcolNmiss) & 1;
if (nmiss_col) {
cswritep = strcpya_k(cswritep, "\tMISSING_CT");
}
const uint32_t nmiss_hh_col = (missing_rpt_flags / kfMissingRptVcolNmissHh) & 1;
if (nmiss_hh_col) {
cswritep = strcpya_k(cswritep, "\tMISSING_AND_HETHAP_CT");
}
const uint32_t hethap_col = (missing_rpt_flags / kfMissingRptVcolHethap) & 1;
if (hethap_col) {
cswritep = strcpya_k(cswritep, "\tHETHAP_CT");
}
const uint32_t nobs_col = (missing_rpt_flags / kfMissingRptVcolNobs) & 1;
if (nobs_col) {
cswritep = strcpya_k(cswritep, "\tOBS_CT");
}
const uint32_t fmiss_dosage_col = missing_rpt_flags & kfMissingRptVcolFmissDosage;
if (fmiss_dosage_col) {
cswritep = strcpya_k(cswritep, "\tF_MISS_DOSAGE");
}
const uint32_t fmiss_col = (missing_rpt_flags / kfMissingRptVcolFmiss) & 1;
if (fmiss_col) {
cswritep = strcpya_k(cswritep, "\tF_MISS");
}
const uint32_t fmiss_hh_col = (missing_rpt_flags / kfMissingRptVcolFmissHh) & 1;
if (fmiss_hh_col) {
cswritep = strcpya_k(cswritep, "\tF_MISS_AND_HETHAP");
}
const uint32_t fhethap_col = (missing_rpt_flags / kfMissingRptVcolFhethap) & 1;
if (fhethap_col) {
cswritep = strcpya_k(cswritep, "\tF_HETHAP");
}
AppendBinaryEoln(&cswritep);
char nobs_str[16];
nobs_str[0] = '\t';
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
uint32_t nobs_slen = 0;
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t chr_buf_blen = 0;
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
uint32_t is_y = 2;
double nobs_recip = 0.0;
fputs("--missing variant report: 0%", stdout);
fflush(stdout);
uint32_t cur_allele_ct = 2;
uint32_t cur_missing_hc_ct = 0;
uint32_t cur_hethap_ct = 0;
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (variant_uidx >= chr_end);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
*chr_name_end = '\t';
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
const uint32_t new_is_y = (chr_idx == y_code);
if (new_is_y != is_y) {
is_y = new_is_y;
const uint32_t cur_nobs = is_y? chry_missingstat_sample_ct : sample_ct;
nobs_recip = 1.0 / u31tod(cur_nobs);
char* nobs_str_end = u32toa(cur_nobs, &(nobs_str[1]));
nobs_slen = nobs_str_end - nobs_str;
}
}
if (chr_col) {
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
}
if (variant_bps) {
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (ref_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[0]);
}
if (alt_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) {
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
if (provref_col) {
*cswritep++ = '\t';
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
}
if (nmiss_dosage_col) {
*cswritep++ = '\t';
cswritep = u32toa(variant_missing_dosage_cts[variant_uidx], cswritep);
}
if (variant_missing_hc_cts) {
cur_missing_hc_ct = variant_missing_hc_cts[variant_uidx];
cur_hethap_ct = 0;
if (variant_uidx >= first_hap_uidx) {
cur_hethap_ct = variant_hethap_cts[variant_uidx - first_hap_uidx];
}
if (nmiss_col) {
*cswritep++ = '\t';
cswritep = u32toa(cur_missing_hc_ct, cswritep);
}
if (nmiss_hh_col) {
*cswritep++ = '\t';
cswritep = u32toa(cur_missing_hc_ct + cur_hethap_ct, cswritep);
}
if (hethap_col) {
*cswritep++ = '\t';
cswritep = u32toa(cur_hethap_ct, cswritep);
}
}
if (nobs_col) {
cswritep = memcpya(cswritep, nobs_str, nobs_slen);
}
if (fmiss_dosage_col) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(variant_missing_dosage_cts[variant_uidx]) * nobs_recip, cswritep);
}
if (fmiss_col) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(cur_missing_hc_ct) * nobs_recip, cswritep);
}
if (fmiss_hh_col) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(cur_missing_hc_ct + cur_hethap_ct) * nobs_recip, cswritep);
}
if (fhethap_col) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(cur_hethap_ct) * nobs_recip, cswritep);
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto WriteMissingnessReports_ret_WRITE_FAIL;
}
putc_unlocked('\r', stdout);
logprintfww("--missing: Variant missing data report written to %s .\n", outname);
}
}
while (0) {
WriteMissingnessReports_ret_NOMEM:
reterr = kPglRetNomem;
break;
WriteMissingnessReports_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
}
WriteMissingnessReports_ret_1:
BigstackReset(bigstack_mark);
CswriteCloseCond(&css, cswritep);
return reterr;
}
PglErr GetMultiallelicMarginalCounts(const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_geno_cts), uint32_t raw_sample_ct, uint32_t autosomal_variant_ct, uint32_t autosomal_xallele_ct, uint32_t hwe_x_ct, uint32_t x_xallele_ct, PgenReader* simple_pgrp, STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts), STD_ARRAY_PTR_DECL(uint32_t, 2, autosomal_xgeno_cts), STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts)) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
{
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
uint32_t* cumulative_popcounts;
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &cumulative_popcounts))) {
goto GetMultiallelicMarginalCounts_ret_NOMEM;
}
FillCumulativePopcounts(founder_info, raw_sample_ctl, cumulative_popcounts);
const uint32_t founder_ct = cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(founder_info[raw_sample_ctl - 1]);
const uint32_t founder_ctl2 = NypCtToWordCt(founder_ct);
const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
const uint32_t max_allele_ct = PgrGetMaxAlleleCt(simple_pgrp);
PgenVariant pgv;
uint32_t* one_cts;
uint32_t* two_cts;
if (unlikely(bigstack_alloc_w(founder_ctl2, &(pgv.genovec)) ||
bigstack_alloc_w(founder_ctl, &(pgv.patch_01_set)) ||
bigstack_alloc_ac(founder_ct, &(pgv.patch_01_vals)) ||
bigstack_alloc_w(founder_ctl, &(pgv.patch_10_set)) ||
bigstack_alloc_ac(2 * founder_ct, &(pgv.patch_10_vals)) ||
bigstack_alloc_u32(max_allele_ct, &one_cts) ||
bigstack_alloc_u32(max_allele_ct, &two_cts))) {
goto GetMultiallelicMarginalCounts_ret_NOMEM;
}
if (autosomal_xallele_ct) {
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(cumulative_popcounts, simple_pgrp, &pssi);
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
uintptr_t xgeno_idx = 0;
for (uint32_t variant_idx = 0; variant_idx != autosomal_variant_ct; ++variant_idx) {
uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
uint32_t chr_idx;
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
chr_idx = cip->chr_file_order[chr_fo_idx];
} while ((variant_uidx >= chr_end) || IsSet(cip->haploid_mask, chr_idx));
BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &cur_bits);
variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
}
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
if (allele_ct > 2) {
reterr = PgrGetM(founder_info, pssi, founder_ct, variant_uidx, simple_pgrp, &pgv);
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, variant_uidx);
goto GetMultiallelicMarginalCounts_ret_1;
}
ZeroTrailingNyps(founder_ct, pgv.genovec);
ZeroU32Arr(allele_ct, one_cts);
ZeroU32Arr(allele_ct, two_cts);
// const uint32_t hom_ref_ct = hwe_geno_cts[variant_uidx][0];
const uint32_t het_ref_ct = hwe_geno_cts[variant_uidx][1];
const uint32_t altxy_ct = hwe_geno_cts[variant_uidx][2];
// two_cts[0] = hom_ref_ct;
// one_cts[0] = het_ref_ct;
one_cts[1] = het_ref_ct - pgv.patch_01_ct;
two_cts[1] = altxy_ct - pgv.patch_10_ct;
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
one_cts[pgv.patch_01_vals[uii]] += 1;
}
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii];
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1];
if (lo_code == hi_code) {
two_cts[lo_code] += 1;
} else {
one_cts[lo_code] += 1;
one_cts[hi_code] += 1;
}
}
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) {
// This is currently inverted, to match how hwe_geno_cts represents
// REF allele counts.
autosomal_xgeno_cts[xgeno_idx][0] = two_cts[aidx];
autosomal_xgeno_cts[xgeno_idx][1] = one_cts[aidx];
++xgeno_idx;
}
}
}
}
if (x_xallele_ct) {
// Related to multiallelic-chrX --geno-counts implementation.
uintptr_t* founder_knownsex;
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &founder_knownsex))) {
goto GetMultiallelicMarginalCounts_ret_NOMEM;
}
BitvecAndCopy(founder_info, sex_nm, raw_sample_ctl, founder_knownsex);
FillCumulativePopcounts(founder_knownsex, raw_sample_ctl, cumulative_popcounts);
const uint32_t founder_x_ct = cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(founder_knownsex[raw_sample_ctl - 1]);
const uint32_t founder_x_ctaw = BitCtToAlignedWordCt(founder_x_ct);
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(cumulative_popcounts, simple_pgrp, &pssi);
uintptr_t* founder_male_collapsed;
uintptr_t* founder_male_interleaved_vec;
if (unlikely(bigstack_alloc_w(founder_x_ctaw, &founder_male_collapsed) ||
bigstack_alloc_w(founder_x_ctaw, &founder_male_interleaved_vec))) {
goto GetMultiallelicMarginalCounts_ret_NOMEM;
}
CopyBitarrSubset(sex_male, founder_knownsex, founder_x_ct, founder_male_collapsed);
const uint32_t founder_x_ctl = BitCtToWordCt(founder_x_ct);
const uint32_t founder_male_ct = PopcountWords(founder_male_collapsed, founder_ctl);
ZeroWArr(founder_x_ctaw - founder_x_ctl, &(founder_male_collapsed[founder_x_ctl]));
FillInterleavedMaskVec(founder_male_collapsed, founder_x_ctaw / kWordsPerVec, founder_male_interleaved_vec);
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code];
const uint32_t x_start = cip->chr_fo_vidx_start[x_chr_fo_idx];
uintptr_t variant_uidx_base;
uintptr_t cur_bits;
BitIter1Start(variant_include, x_start, &variant_uidx_base, &cur_bits);
uintptr_t xgeno_idx = 0;
for (uint32_t variant_idx = 0; variant_idx != hwe_x_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
if (allele_ct > 2) {
reterr = PgrGetM(founder_knownsex, pssi, founder_x_ct, variant_uidx, simple_pgrp, &pgv);
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, variant_uidx);
goto GetMultiallelicMarginalCounts_ret_1;
}
ZeroTrailingNyps(founder_x_ct, pgv.genovec);
ZeroU32Arr(allele_ct, one_cts);
ZeroU32Arr(allele_ct, two_cts);
STD_ARRAY_DECL(uint32_t, 4, genocounts);
GenoarrCountFreqsUnsafe(pgv.genovec, founder_x_ct, genocounts);
// const uint32_t hom_ref_ct = genocounts[0];
const uint32_t het_ref_ct = genocounts[1];
const uint32_t altxy_ct = genocounts[2];
// two_cts[0] = hom_ref_ct;
// one_cts[0] = het_ref_ct;
one_cts[1] = het_ref_ct - pgv.patch_01_ct;
two_cts[1] = altxy_ct - pgv.patch_10_ct;
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
one_cts[pgv.patch_01_vals[uii]] += 1;
}
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii];
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1];
if (lo_code == hi_code) {
two_cts[lo_code] += 1;
} else {
one_cts[lo_code] += 1;
one_cts[hi_code] += 1;
}
}
uintptr_t knownsex_xgeno_idx = xgeno_idx;
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) {
x_knownsex_xgeno_cts[knownsex_xgeno_idx][0] = two_cts[aidx];
x_knownsex_xgeno_cts[knownsex_xgeno_idx][1] = one_cts[aidx];
++knownsex_xgeno_idx;
}
if (x_male_xgeno_cts) {
ZeroU32Arr(allele_ct, one_cts);
ZeroU32Arr(allele_ct, two_cts);
GenoarrCountSubsetFreqs(pgv.genovec, founder_male_interleaved_vec, founder_x_ct, founder_male_ct, genocounts);
const uint32_t male_het_ref_ct = genocounts[1];
const uint32_t male_altxy_ct = genocounts[2];
one_cts[1] = male_het_ref_ct;
two_cts[1] = male_altxy_ct;
uintptr_t sample_widx = 0;
uintptr_t cur_patch_bits = pgv.patch_01_set[0];
uint32_t male_patch_01_ct = 0;
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &cur_patch_bits);
if (founder_male_collapsed[sample_widx] & lowbit) {
++male_patch_01_ct;
one_cts[pgv.patch_01_vals[uii]] += 1;
}
}
one_cts[1] -= male_patch_01_ct;
sample_widx = 0;
cur_patch_bits = pgv.patch_10_set[0];
uint32_t male_patch_10_ct = 0;
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &cur_patch_bits);
if (founder_male_collapsed[sample_widx] & lowbit) {
++male_patch_10_ct;
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii];
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1];
if (lo_code == hi_code) {
two_cts[lo_code] += 1;
} else {
one_cts[lo_code] += 1;
one_cts[hi_code] += 1;
}
}
}
two_cts[1] -= male_patch_10_ct;
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) {
x_male_xgeno_cts[xgeno_idx][0] = two_cts[aidx];
x_male_xgeno_cts[xgeno_idx][1] = one_cts[aidx];
++xgeno_idx;
}
} else {
xgeno_idx = knownsex_xgeno_idx;
}
}
}
}
}
while (0) {
GetMultiallelicMarginalCounts_ret_NOMEM:
reterr = kPglRetNomem;
break;
}
GetMultiallelicMarginalCounts_ret_1:
BigstackReset(bigstack_mark);
return reterr;
}
typedef struct ComputeHweXLnPvalsCtxStruct {
const uintptr_t* variant_include;
const uintptr_t* allele_idx_offsets;
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts);
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts);
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts);
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts);
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts);
uint32_t* variant_uidx_starts;
uintptr_t* extra_aidx_starts;
uint32_t x_start;
uint32_t hwe_x_start;
uint32_t hwe_midp;
uint32_t hwe_x_ct;
double* hwe_x_ln_pvals;
} ComputeHweXLnPvalsCtx;
void ComputeHweXLnPvalsMain(uintptr_t tidx, uintptr_t thread_ct, ComputeHweXLnPvalsCtx* ctx) {
const uintptr_t* variant_include = ctx->variant_include;
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts) = ctx->founder_raw_geno_cts;
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts) = ctx->founder_x_male_geno_cts;
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts) = ctx->founder_x_nosex_geno_cts;
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts) = ctx->x_knownsex_xgeno_cts;
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts) = ctx->x_male_xgeno_cts;
const uint32_t x_start = ctx->x_start;
const uint32_t hwe_x_ct = ctx->hwe_x_ct;
const uint32_t hwe_midp = ctx->hwe_midp;
// this needs to be aligned with ComputeUidxStartPartition()
const uint32_t variant_idx_end = (hwe_x_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct;
uint32_t variant_idx = (hwe_x_ct * S_CAST(uint64_t, tidx)) / thread_ct;
uintptr_t xgeno_idx = ctx->extra_aidx_starts[tidx];
double* hwe_x_ln_pvals_iter = &(ctx->hwe_x_ln_pvals[variant_idx + xgeno_idx]);
uintptr_t variant_uidx_base;
uintptr_t cur_bits;
BitIter1Start(variant_include, ctx->variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_idx_end;
if (!tidx) {
next_print_variant_idx = variant_idx_end / 100;
}
uint32_t male_1copy_ct = 0;
uint32_t male_hethap_ct = 0;
uint32_t male_0copy_ct = 0;
for (; variant_idx != variant_idx_end; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
STD_ARRAY_KREF(uint32_t, 3) cur_raw_geno_cts = founder_raw_geno_cts[variant_uidx];
uint32_t female_2copy_ct = cur_raw_geno_cts[0];
uint32_t female_1copy_ct = cur_raw_geno_cts[1];
uint32_t female_0copy_ct = cur_raw_geno_cts[2];
if (founder_x_male_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = founder_x_male_geno_cts[variant_uidx - x_start];
male_1copy_ct = cur_male_geno_cts[0];
female_2copy_ct -= male_1copy_ct;
male_hethap_ct = cur_male_geno_cts[1];
female_1copy_ct -= male_hethap_ct;
male_0copy_ct = cur_male_geno_cts[2];
female_0copy_ct -= male_0copy_ct;
}
if (founder_x_nosex_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = founder_x_nosex_geno_cts[variant_uidx - x_start];
female_2copy_ct -= cur_nosex_geno_cts[0];
female_1copy_ct -= cur_nosex_geno_cts[1];
female_0copy_ct -= cur_nosex_geno_cts[2];
}
*hwe_x_ln_pvals_iter++ = HweXchrLnP(female_1copy_ct, female_2copy_ct, female_0copy_ct, male_1copy_ct, male_0copy_ct, hwe_midp);
if (allele_idx_offsets) {
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
if (allele_ct != 2) {
const uint32_t female_obs_ct = female_2copy_ct + female_1copy_ct + female_0copy_ct;
const uint32_t male_obs_ct = male_1copy_ct + male_hethap_ct + male_0copy_ct;
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) {
female_2copy_ct = x_knownsex_xgeno_cts[xgeno_idx][0];
female_1copy_ct = x_knownsex_xgeno_cts[xgeno_idx][1];
if (x_male_xgeno_cts) {
male_1copy_ct = x_male_xgeno_cts[xgeno_idx][0];
female_2copy_ct -= male_1copy_ct;
male_hethap_ct = x_male_xgeno_cts[xgeno_idx][1];
female_1copy_ct -= male_hethap_ct;
male_0copy_ct = male_obs_ct - male_1copy_ct - male_hethap_ct;
}
female_0copy_ct = female_obs_ct - female_2copy_ct - female_1copy_ct;
*hwe_x_ln_pvals_iter++ = HweXchrLnP(female_1copy_ct, female_2copy_ct, female_0copy_ct, male_1copy_ct, male_0copy_ct, hwe_midp);
++xgeno_idx;
}
}
}
if (variant_idx >= next_print_variant_idx) {
// only possible for tidx == 0
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_idx_end;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_idx_end)) / 100;
}
}
if (pct > 10) {
putc_unlocked('\b', stdout);
}
}
THREAD_FUNC_DECL ComputeHweXLnPvalsThread(void* raw_arg) {
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
ComputeHweXLnPvalsCtx* ctx = S_CAST(ComputeHweXLnPvalsCtx*, arg->sharedp->context);
ComputeHweXLnPvalsMain(arg->tidx, GetThreadCt(arg->sharedp) + 1, ctx);
THREAD_RETURN;
}
PglErr ComputeHweXLnPvals(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts), uint32_t x_start, uint32_t hwe_x_ct, uintptr_t x_xallele_ct, uint32_t hwe_midp, uint32_t calc_thread_ct, double** hwe_x_ln_pvals_ptr) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
ThreadGroup tg;
PreinitThreads(&tg);
ComputeHweXLnPvalsCtx ctx;
{
assert(hwe_x_ct);
if (unlikely(bigstack_alloc_d(hwe_x_ct + x_xallele_ct, hwe_x_ln_pvals_ptr))) {
goto ComputeHweXLnPvals_ret_NOMEM;
}
bigstack_mark = g_bigstack_base;
ctx.hwe_x_ln_pvals = *hwe_x_ln_pvals_ptr;
if (calc_thread_ct > hwe_x_ct) {
calc_thread_ct = hwe_x_ct;
}
if (unlikely(SetThreadCt0(calc_thread_ct - 1, &tg) ||
bigstack_alloc_u32(calc_thread_ct, &ctx.variant_uidx_starts) ||
bigstack_alloc_w(calc_thread_ct, &ctx.extra_aidx_starts))) {
goto ComputeHweXLnPvals_ret_NOMEM;
}
// possible todo: extra-allele-based load balancer
ComputeUidxStartPartition(variant_include, hwe_x_ct, calc_thread_ct, x_start, ctx.variant_uidx_starts);
ctx.extra_aidx_starts[0] = 0;
uintptr_t extra_aidx = 0;
uint32_t prev_variant_uidx = ctx.variant_uidx_starts[0];
for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
const uint32_t cur_variant_uidx = ctx.variant_uidx_starts[tidx];
extra_aidx += CountExtraAlleles(variant_include, allele_idx_offsets, prev_variant_uidx, cur_variant_uidx, 1);
ctx.extra_aidx_starts[tidx] = extra_aidx;
prev_variant_uidx = cur_variant_uidx;
}
ctx.variant_include = variant_include;
ctx.allele_idx_offsets = allele_idx_offsets;
ctx.founder_raw_geno_cts = founder_raw_geno_cts;
ctx.founder_x_male_geno_cts = founder_x_male_geno_cts;
ctx.founder_x_nosex_geno_cts = founder_x_nosex_geno_cts;
ctx.x_knownsex_xgeno_cts = x_knownsex_xgeno_cts;
ctx.x_male_xgeno_cts = x_male_xgeno_cts;
ctx.x_start = x_start;
ctx.hwe_x_ct = hwe_x_ct;
ctx.hwe_midp = hwe_midp;
logprintf("Computing chrX Hardy-Weinberg %sp-values... ", hwe_midp? "mid" : "");
fputs("0%", stdout);
fflush(stdout);
if (calc_thread_ct > 1) {
SetThreadFuncAndData(ComputeHweXLnPvalsThread, &ctx, &tg);
DeclareLastThreadBlock(&tg);
if (unlikely(SpawnThreads(&tg))) {
goto ComputeHweXLnPvals_ret_THREAD_CREATE_FAIL;
}
}
ComputeHweXLnPvalsMain(calc_thread_ct - 1, calc_thread_ct, &ctx);
JoinThreads0(&tg);
fputs("\b\b", stdout);
logputs("done.\n");
}
while (0) {
ComputeHweXLnPvals_ret_NOMEM:
reterr = kPglRetNomem;
break;
ComputeHweXLnPvals_ret_THREAD_CREATE_FAIL:
reterr = kPglRetThreadCreateFail;
break;
}
CleanupThreads(&tg);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr HardyReport(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, autosomal_xgeno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_x_male_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_x_nosex_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts), const double* hwe_x_ln_pvals, uint32_t variant_ct, uint32_t hwe_x_ct, uint32_t max_allele_slen, PgenGlobalFlags gflags, double output_min_ln, HardyFlags hardy_flags, uint32_t max_thread_ct, uint32_t nonfounders, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
{
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct;
const uint32_t chr_code_endl = BitCtToWordCt(chr_code_end);
const uintptr_t overflow_buf_size = RoundUpPow2(kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + 2 * max_allele_slen, kCacheline);
const uint32_t output_zst = hardy_flags & kfHardyZs;
uintptr_t overflow_buf_alloc = overflow_buf_size;
if (output_zst) {
overflow_buf_alloc += CstreamWkspaceReq(overflow_buf_size);
}
char* overflow_buf;
uintptr_t* chr_skips;
if (unlikely(bigstack_alloc_c(overflow_buf_alloc, &overflow_buf) ||
bigstack_alloc_w(chr_code_endl, &chr_skips))) {
goto HardyReport_ret_NOMEM;
}
// skip chrX, chrY, chrM here
memcpy(chr_skips, cip->haploid_mask, chr_code_endl * sizeof(intptr_t));
const uint32_t chr_skip_ct = PopcountWords(chr_skips, chr_code_endl);
uint32_t variant_skip_ct = 0;
uintptr_t chr_uidx_base = 0;
uintptr_t chr_skips_bits = chr_skips[0];
for (uint32_t chr_skip_idx = 0; chr_skip_idx != chr_skip_ct; ++chr_skip_idx) {
const uintptr_t chr_uidx = BitIter1(chr_skips, &chr_uidx_base, &chr_skips_bits);
if (IsSet(cip->chr_mask, chr_uidx)) {
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_uidx];
variant_skip_ct += PopcountBitRange(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1]);
}
}
if (variant_skip_ct - hwe_x_ct) {
logprintf("--hardy: Skipping %u haploid variant%s.\n", variant_skip_ct - hwe_x_ct, (variant_skip_ct - hwe_x_ct == 1)? "" : "s");
}
variant_ct -= variant_skip_ct;
const uint32_t midp = (hardy_flags / kfHardyMidp) & 1;
const uint32_t redundant = (hardy_flags / kfHardyRedundant) & 1;
const uint32_t chr_col = hardy_flags & kfHardyColChrom;
const uint32_t ref_col = hardy_flags & kfHardyColRef;
const uint32_t alt1_col = hardy_flags & kfHardyColAlt1;
const uint32_t alt_col = hardy_flags & kfHardyColAlt;
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
// customize this, since the standard calculation does not exclude haploid
// chromosomes
uint32_t provref_col = 0;
if (ref_col) {
if (hardy_flags & kfHardyColProvref) {
provref_col = 1;
} else if (!(hardy_flags & kfHardyColMaybeprovref)) {
// do nothing
} else if (!nonref_flags) {
provref_col = all_nonref;
} else {
const uint32_t chr_ct = cip->chr_ct;
for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
if ((!IsSet(cip->chr_mask, chr_idx)) || IsSet(chr_skips, chr_idx)) {
continue;
}
if (!IntersectionRangeIsEmpty(variant_include, nonref_flags, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1])) {
provref_col = 1;
break;
}
}
}
}
const uint32_t report_neglog10p = (hardy_flags / kfHardyLog10) & 1;
const uint32_t ax_col = hardy_flags & kfHardyColAx;
const uint32_t gcounts = hardy_flags & (kfHardyColGcounts | kfHardyColGcount1col);
const uint32_t gcount_1col = hardy_flags & kfHardyColGcount1col;
const char gcount_delim = gcount_1col? ',' : '\t';
const uint32_t hetfreq_cols = hardy_flags & kfHardyColHetfreq;
const uint32_t p_col = hardy_flags & kfHardyColP;
if (variant_ct) {
OutnameZstSet(".hardy", output_zst, outname_end);
reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css);
if (unlikely(reterr)) {
goto HardyReport_ret_1;
}
cswritep = overflow_buf;
*cswritep++ = '#';
// includes trailing tab
char* chr_buf = nullptr;
if (chr_col) {
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
goto HardyReport_ret_NOMEM;
}
cswritep = strcpya_k(cswritep, "CHROM\t");
}
if (hardy_flags & kfHardyColPos) {
cswritep = strcpya_k(cswritep, "POS\t");
} else {
variant_bps = nullptr;
}
cswritep = strcpya_k(cswritep, "ID");
if (ref_col) {
cswritep = strcpya_k(cswritep, "\tREF");
}
if (alt1_col) {
cswritep = strcpya_k(cswritep, "\tALT1");
}
if (alt_col) {
cswritep = strcpya_k(cswritep, "\tALT");
}
if (provref_col) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
cswritep = strcpya_k(cswritep, "\tA1");
if (ax_col) {
cswritep = strcpya_k(cswritep, "\tAX");
}
if (gcounts) {
if (gcount_1col) {
cswritep = strcpya_k(cswritep, "\tGCOUNTS");
} else {
cswritep = strcpya_k(cswritep, "\tHOM_A1_CT\tHET_A1_CT\tTWO_AX_CT");
}
}
if (hetfreq_cols) {
cswritep = strcpya_k(cswritep, "\tO(HET_A1)\tE(HET_A1)");
}
if (p_col) {
*cswritep++ = '\t';
if (report_neglog10p) {
cswritep = strcpya_k(cswritep, "NEG_LOG10_");
}
if (midp) {
cswritep = strcpya_k(cswritep, "MID");
}
*cswritep++ = 'P';
}
AppendBinaryEoln(&cswritep);
uintptr_t variant_uidx_base = 0;
uintptr_t variant_include_bits = variant_include[0];
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t chr_buf_blen = 0;
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
printf("--hardy%s%s: 0%%", output_zst? " zs" : "", midp? " midp" : "");
fflush(stdout);
uintptr_t xgeno_idx = 0;
uint32_t allele_ct = 2;
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
// bugfix (15 May 2018): this needs to happen even if we aren't
// printing #CHROM column
if (variant_uidx >= chr_end) {
uint32_t chr_idx;
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
chr_idx = cip->chr_file_order[chr_fo_idx];
} while ((variant_uidx >= chr_end) || IsSet(chr_skips, chr_idx));
BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &variant_include_bits);
variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
if (chr_col) {
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
*chr_name_end = '\t';
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
}
}
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
const uint32_t print_allele_ct = ((allele_ct == 2) && (!redundant))? 1 : allele_ct;
STD_ARRAY_KREF(uint32_t, 3) cur_geno_cts = hwe_geno_cts[variant_uidx];
uint32_t het_a1_ct = cur_geno_cts[1];
const uint32_t nonmissing_ct = cur_geno_cts[0] + het_a1_ct + cur_geno_cts[2];
for (uint32_t a1_idx = 0; a1_idx != print_allele_ct; ++a1_idx) {
if (chr_col) {
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
}
if (variant_bps) {
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
if (ref_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[0]);
}
if (alt1_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[1]);
}
if (alt_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
if (unlikely(Cswrite(&css, &cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
if (provref_col) {
*cswritep++ = '\t';
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
}
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[a1_idx]);
if (ax_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
if (allele_idx == a1_idx) {
continue;
}
if (unlikely(Cswrite(&css, &cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
uint32_t hom_a1_ct;
uint32_t two_ax_ct;
if (!a1_idx) {
hom_a1_ct = cur_geno_cts[0];
two_ax_ct = cur_geno_cts[2];
} else if (allele_ct == 2) {
// special case, don't read from autosomal_xgeno_cts
hom_a1_ct = cur_geno_cts[2];
two_ax_ct = cur_geno_cts[0];
} else {
STD_ARRAY_KREF(uint32_t, 2) xgeno_cts = autosomal_xgeno_cts[xgeno_idx];
hom_a1_ct = xgeno_cts[0];
het_a1_ct = xgeno_cts[1];
two_ax_ct = nonmissing_ct - hom_a1_ct - het_a1_ct;
++xgeno_idx;
}
if (gcounts) {
*cswritep++ = '\t';
cswritep = u32toa_x(hom_a1_ct, gcount_delim, cswritep);
cswritep = u32toa_x(het_a1_ct, gcount_delim, cswritep);
cswritep = u32toa(two_ax_ct, cswritep);
}
if (hetfreq_cols) {
*cswritep++ = '\t';
const double nonmissing_ct_recip = 1.0 / u31tod(nonmissing_ct);
cswritep = dtoa_g(u31tod(het_a1_ct) * nonmissing_ct_recip, cswritep);
*cswritep++ = '\t';
const double dbl_maj_freq = (hom_a1_ct * 2 + het_a1_ct) * nonmissing_ct_recip;
// (1.0 - maj_freq) is vulnerable to catastrophic cancellation when
// maj_freq is 1
if (hom_a1_ct == nonmissing_ct) {
*cswritep++ = '0';
} else {
const double expected_het_freq = dbl_maj_freq * (1.0 - dbl_maj_freq * 0.5);
cswritep = dtoa_g(expected_het_freq, cswritep);
}
}
if (p_col) {
// possible todo: multithread this
*cswritep++ = '\t';
const double hwe_ln_p = HweLnP(het_a1_ct, hom_a1_ct, two_ax_ct, midp);
if (report_neglog10p) {
const double reported_val = (-kRecipLn10) * hwe_ln_p;
cswritep = dtoa_g(reported_val, cswritep);
} else {
cswritep = lntoa_g(MAXV(hwe_ln_p, output_min_ln), cswritep);
}
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
putc_unlocked('\r', stdout);
logprintfww("--hardy%s%s: Autosomal Hardy-Weinberg report (%s) written to %s .\n", output_zst? " zs" : "", midp? " midp" : "", nonfounders? "all samples" : "founders only", outname);
}
if (hwe_x_ct) {
BigstackReset(chr_skips);
OutnameZstSet(".hardy.x", output_zst, outname_end);
reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css);
if (unlikely(reterr)) {
goto HardyReport_ret_1;
}
cswritep = overflow_buf;
*cswritep++ = '#';
// includes trailing tab
char x_name_buf[8];
uint32_t x_name_blen = 0;
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
if (chr_col) {
cswritep = strcpya_k(cswritep, "CHROM\t");
char* write_iter = chrtoa(cip, x_code, x_name_buf);
*write_iter++ = '\t';
x_name_blen = write_iter - x_name_buf;
}
if (hardy_flags & kfHardyColPos) {
cswritep = strcpya_k(cswritep, "POS\t");
} else {
variant_bps = nullptr;
}
cswritep = strcpya_k(cswritep, "ID");
if (ref_col) {
cswritep = strcpya_k(cswritep, "\tREF");
}
if (alt1_col) {
cswritep = strcpya_k(cswritep, "\tALT1");
}
if (alt_col) {
cswritep = strcpya_k(cswritep, "\tALT");
}
const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code];
const uint32_t x_start = cip->chr_fo_vidx_start[x_chr_fo_idx];
if (ref_col && ((hardy_flags & (kfHardyColMaybeprovref | kfHardyColProvref)) == kfHardyColMaybeprovref) && nonref_flags) {
provref_col = !IntersectionRangeIsEmpty(variant_include, nonref_flags, x_start, cip->chr_fo_vidx_start[x_chr_fo_idx + 1]);
}
if (provref_col) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
cswritep = strcpya_k(cswritep, "\tA1");
if (ax_col) {
cswritep = strcpya_k(cswritep, "\tAX");
}
if (gcounts) {
if (gcount_1col) {
cswritep = strcpya_k(cswritep, "\tGCOUNTS");
} else {
cswritep = strcpya_k(cswritep, "\tFEMALE_HOM_A1_CT\tFEMALE_HET_A1_CT\tFEMALE_TWO_AX_CT\tMALE_A1_CT\tMALE_AX_CT");
}
}
if (hetfreq_cols) {
cswritep = strcpya_k(cswritep, "\tO(FEMALE_HET_A1)\tE(FEMALE_HET_A1)");
}
const uint32_t sexaf_cols = hardy_flags & kfHardyColSexaf;
if (sexaf_cols) {
cswritep = strcpya_k(cswritep, "\tFEMALE_A1_FREQ\tMALE_A1_FREQ");
}
const uint32_t femalep_col = hardy_flags & kfHardyColFemalep;
if (femalep_col) {
cswritep = strcpya_k(cswritep, "\tFEMALE_ONLY_");
if (report_neglog10p) {
cswritep = strcpya_k(cswritep, "NEG_LOG10_");
}
if (midp) {
cswritep = strcpya_k(cswritep, "MID");
}
*cswritep++ = 'P';
}
if (p_col) {
*cswritep++ = '\t';
if (report_neglog10p) {
cswritep = strcpya_k(cswritep, "NEG_LOG10_");
}
if (midp) {
cswritep = strcpya_k(cswritep, "MID");
}
*cswritep++ = 'P';
}
AppendBinaryEoln(&cswritep);
fputs("--hardy: Writing chrX results...", stdout);
fflush(stdout);
uintptr_t variant_uidx_base;
uintptr_t variant_include_bits;
BitIter1Start(variant_include, x_start, &variant_uidx_base, &variant_include_bits);
uintptr_t xgeno_idx = 0;
uint32_t allele_ct = 2;
uint32_t male_a1_ct = 0;
uint32_t male_ax_ct = 0;
for (uint32_t variant_idx = 0; variant_idx != hwe_x_ct; ++variant_idx) {
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
const uint32_t print_allele_ct = ((allele_ct == 2) && (!redundant))? 1 : allele_ct;
STD_ARRAY_KREF(uint32_t, 3) cur_geno_cts = hwe_geno_cts[variant_uidx];
uint32_t female_obs_ct = cur_geno_cts[0] + cur_geno_cts[1] + cur_geno_cts[2];
if (hwe_x_nosex_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = hwe_x_nosex_geno_cts[variant_uidx - x_start];
female_obs_ct -= cur_nosex_geno_cts[0] + cur_nosex_geno_cts[1] + cur_nosex_geno_cts[2];
}
uint32_t male_obs_ct = 0;
if (hwe_x_male_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = hwe_x_male_geno_cts[variant_uidx - x_start];
male_obs_ct = cur_male_geno_cts[0] + cur_male_geno_cts[1] + cur_male_geno_cts[2];
female_obs_ct -= male_obs_ct;
}
for (uint32_t a1_idx = 0; a1_idx != print_allele_ct; ++a1_idx) {
cswritep = memcpya(cswritep, x_name_buf, x_name_blen);
if (variant_bps) {
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
if (ref_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[0]);
}
if (alt1_col) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[1]);
}
if (alt_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
if (unlikely(Cswrite(&css, &cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
if (provref_col) {
*cswritep++ = '\t';
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
}
*cswritep++ = '\t';
cswritep = strcpya(cswritep, cur_alleles[a1_idx]);
if (ax_col) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
if (allele_idx == a1_idx) {
continue;
}
if (unlikely(Cswrite(&css, &cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
}
--cswritep;
}
uint32_t female_hom_a1_ct;
uint32_t female_het_a1_ct;
uint32_t female_two_ax_ct;
if ((!a1_idx) || (allele_ct == 2)) {
female_hom_a1_ct = cur_geno_cts[2 * a1_idx];
female_het_a1_ct = cur_geno_cts[1];
female_two_ax_ct = cur_geno_cts[2 - 2 * a1_idx];
if (hwe_x_male_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = hwe_x_male_geno_cts[variant_uidx - x_start];
male_a1_ct = cur_male_geno_cts[2 * a1_idx];
female_hom_a1_ct -= male_a1_ct;
female_het_a1_ct -= cur_male_geno_cts[1];
male_ax_ct = cur_male_geno_cts[2 - 2 * a1_idx];
female_two_ax_ct -= male_ax_ct;
}
if (hwe_x_nosex_geno_cts) {
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = hwe_x_nosex_geno_cts[variant_uidx - x_start];
female_hom_a1_ct -= cur_nosex_geno_cts[2 * a1_idx];
female_het_a1_ct -= cur_nosex_geno_cts[1];
female_two_ax_ct -= cur_nosex_geno_cts[2 - 2 * a1_idx];
}
} else {
STD_ARRAY_KREF(uint32_t, 2) cur_knownsex_xgeno_cts = x_knownsex_xgeno_cts[xgeno_idx];
female_hom_a1_ct = cur_knownsex_xgeno_cts[0];
female_het_a1_ct = cur_knownsex_xgeno_cts[1];
if (x_male_xgeno_cts) {
STD_ARRAY_KREF(uint32_t, 2) cur_male_xgeno_cts = x_male_xgeno_cts[xgeno_idx];
male_a1_ct = cur_male_xgeno_cts[0];
female_hom_a1_ct -= male_a1_ct;
const uint32_t male_hethap_ct = cur_male_xgeno_cts[1];
female_het_a1_ct -= male_hethap_ct;
male_ax_ct = male_obs_ct - male_a1_ct - male_hethap_ct;
}
female_two_ax_ct = female_obs_ct - female_hom_a1_ct - female_het_a1_ct;
// Correct to increment this before looking up hwe_x_ln_pvals[]
// (and to not increment on a1_idx == 0).
++xgeno_idx;
}
if (gcounts) {
*cswritep++ = '\t';
cswritep = u32toa_x(female_hom_a1_ct, gcount_delim, cswritep);
cswritep = u32toa_x(female_het_a1_ct, gcount_delim, cswritep);
cswritep = u32toa_x(female_two_ax_ct, gcount_delim, cswritep);
cswritep = u32toa_x(male_a1_ct, gcount_delim, cswritep);
cswritep = u32toa(male_ax_ct, cswritep);
}
if (hetfreq_cols || sexaf_cols) {
const double female_obs_ct_recip = 1.0 / u31tod(female_obs_ct);
const double dbl_a1_freq = (female_hom_a1_ct * 2 + female_het_a1_ct) * female_obs_ct_recip;
if (hetfreq_cols) {
*cswritep++ = '\t';
cswritep = dtoa_g(u31tod(female_het_a1_ct) * female_obs_ct_recip, cswritep);
*cswritep++ = '\t';
// (1.0 - a1_freq) is vulnerable to catastrophic cancellation
// when actual a1_freq is 1.
if (female_hom_a1_ct == female_obs_ct) {
*cswritep++ = '0';
} else {
const double expected_het_freq = dbl_a1_freq * (1.0 - 0.5 * dbl_a1_freq);
cswritep = dtoa_g(expected_het_freq, cswritep);
}
}
if (sexaf_cols) {
*cswritep++ = '\t';
cswritep = dtoa_g(dbl_a1_freq * 0.5, cswritep);
*cswritep++ = '\t';
const double male_a1_freq = u31tod(male_a1_ct) / u31tod(male_a1_ct + male_ax_ct);
cswritep = dtoa_g(male_a1_freq, cswritep);
}
}
if (femalep_col) {
*cswritep++ = '\t';
const double female_hwe_ln_p = HweLnP(female_het_a1_ct, female_hom_a1_ct, female_two_ax_ct, midp);
if (report_neglog10p) {
const double reported_val = (-kRecipLn10) * female_hwe_ln_p;
cswritep = dtoa_g(reported_val, cswritep);
} else {
cswritep = lntoa_g(MAXV(female_hwe_ln_p, output_min_ln), cswritep);
}
}
if (p_col) {
*cswritep++ = '\t';
// bugfix (27 Jun 2020): forgot to correct this for multiallelic
// variants
const double ln_pval = hwe_x_ln_pvals[variant_idx + xgeno_idx];
if (report_neglog10p) {
const double reported_val = (-kRecipLn10) * ln_pval;
cswritep = dtoa_g(reported_val, cswritep);
} else {
cswritep = lntoa_g(MAXV(ln_pval, output_min_ln), cswritep);
}
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto HardyReport_ret_WRITE_FAIL;
}
putc_unlocked('\r', stdout);
logprintfww("--hardy%s%s: chrX Hardy-Weinberg report (%s) written to %s .\n", output_zst? " zs" : "", midp? " midp" : "", nonfounders? "all samples" : "founders only", outname);
}
}
while (0) {
HardyReport_ret_NOMEM:
reterr = kPglRetNomem;
break;
HardyReport_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
}
HardyReport_ret_1:
CswriteCloseCond(&css, cswritep);
BigstackReset(bigstack_mark);
return reterr;
}
ENUM_U31_DEF_START()
kSubstCodeNonsnpsymb,
kSubstCodeSymbolic,
kSubstCodeTs,
kSubstCodeTv,
kSubstCodeWeirdSnp,
kSubstCodeCt
ENUM_U31_DEF_END(SubstCode);
SubstCode GetSubstCode(const char* ref, const char* alt) {
if (ref[1] || alt[1]) {
return (alt[0] == '<')? kSubstCodeSymbolic : kSubstCodeNonsnpsymb;
}
const unsigned char ref_upcase = ref[0] & 0xdf;
const unsigned char alt_upcase = alt[0] & 0xdf;
const unsigned char uchar_xor = ref_upcase ^ alt_upcase;
if ((ref_upcase == 'A') || (ref_upcase == 'G')) {
// 1 ^ 7 = 6
if (uchar_xor == 6) {
return kSubstCodeTs;
}
// bcftools sample-stats treats all SNP non-transitions are
// transversions. Don't replicate that.
if ((alt_upcase == 'C') || (alt_upcase == 'T')) {
return kSubstCodeTv;
}
} else if ((ref_upcase == 'C') || (ref_upcase == 'T')) {
// 3 ^ 20 = 23
if (uchar_xor == 23) {
return kSubstCodeTs;
}
if ((alt_upcase == 'A') || (alt_upcase == 'G')) {
return kSubstCodeTv;
}
}
return kSubstCodeWeirdSnp;
}
// Assumes trailing bits have been zeroed or filled.
// Returns UINT32_MAX if no singleton.
uint32_t GetSingletonIdx(const uintptr_t* genovec, uint32_t sample_ct) {
const uint32_t word_ct = NypCtToWordCt(sample_ct);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
uintptr_t geno_word = genovec[widx];
if (!geno_word) {
continue;
}
geno_word = (geno_word ^ (geno_word >> 1)) & kMask5555;
if (!geno_word) {
continue;
}
if ((singleton_idx != UINT32_MAX) || (geno_word & (geno_word - 1))) {
return UINT32_MAX;
}
singleton_idx = widx * kBitsPerWordD2 + (ctzw(geno_word) / 2);
}
return singleton_idx;
}
// If the ALT allele in a chrX biallelic variant is observed in one female and
// one male, bcftools counts it as a singleton for the female. Default to
// replicating this weird behavior.
void UpdateSampleDiploidSingletonCountX(const uintptr_t* sex_male, const uintptr_t* genovec, uint32_t sample_ct, uint32_t* diploid_singleton_cts) {
const uint32_t word_ct = NypCtToWordCt(sample_ct);
const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
uintptr_t geno_word = genovec[widx];
if (!geno_word) {
continue;
}
geno_word = (geno_word ^ (geno_word >> 1)) & kMask5555;
if (!geno_word) {
continue;
}
geno_word = geno_word & (~UnpackHalfwordToWord(sex_male_alias[widx]));
if (!geno_word) {
continue;
}
if ((singleton_idx != UINT32_MAX) || (geno_word & (geno_word - 1))) {
return;
}
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno_word) / 2;
}
if (singleton_idx != UINT32_MAX) {
diploid_singleton_cts[singleton_idx] += 1;
}
}
void UpdateSampleSingletonCountX(const uintptr_t* sex_male, const uintptr_t* genovec, uint32_t sample_ct, uint32_t* singleton_cts) {
const uint32_t word_ct = NypCtToWordCt(sample_ct);
const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
const uintptr_t geno_word = genovec[widx];
if (!geno_word) {
continue;
}
const uintptr_t geno2_word = (~geno_word) & (geno_word >> 1) & kMask5555;
if (geno2_word) {
if ((singleton_idx != UINT32_MAX) || (geno2_word & (geno2_word - 1))) {
return;
}
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno2_word) / 2;
}
uintptr_t geno1_word = geno_word & (~(geno_word >> 1)) & kMask5555;
if (geno1_word) {
geno1_word = geno1_word & (~UnpackHalfwordToWord(sex_male_alias[widx]));
if (geno1_word) {
if ((singleton_idx != UINT32_MAX) || (geno1_word & (geno1_word - 1))) {
return;
}
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno1_word) / 2;
}
}
}
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
}
void UpdateSampleSingletonCountY(const uintptr_t* sex_male, const uintptr_t* genovec, uint32_t sample_ct, uint32_t* singleton_cts) {
const uint32_t word_ct = NypCtToWordCt(sample_ct);
const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
const uintptr_t geno_word = genovec[widx];
if (!geno_word) {
continue;
}
uintptr_t geno2_word = (~geno_word) & (geno_word >> 1) & kMask5555;
if (geno2_word) {
geno2_word = geno2_word & UnpackHalfwordToWord(sex_male_alias[widx]);
if (geno2_word) {
if ((singleton_idx != UINT32_MAX) || (geno2_word & (geno2_word - 1))) {
return;
}
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno2_word) / 2;
}
}
}
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
}
uint32_t GetSingletonIdxSparse(const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len) {
const uint32_t word_ct = NypCtToWordCt(difflist_len);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
uintptr_t raregeno_word = raregeno[widx];
if (!raregeno_word) {
continue;
}
raregeno_word = (raregeno_word ^ (raregeno_word >> 1)) & kMask5555;
if (!raregeno_word) {
continue;
}
if ((singleton_idx != UINT32_MAX) || (raregeno_word & (raregeno_word - 1))) {
return UINT32_MAX;
}
singleton_idx = difflist_sample_ids[widx * kBitsPerWordD2 + (ctzw(raregeno_word) / 2)];
}
return singleton_idx;
}
void UpdateSampleDiploidSingletonCountSparseX(const uintptr_t* sex_male, const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len, uint32_t* diploid_singleton_cts) {
const uint32_t word_ct = NypCtToWordCt(difflist_len);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
uintptr_t raregeno_word = raregeno[widx];
if (!raregeno_word) {
continue;
}
raregeno_word = (raregeno_word ^ (raregeno_word >> 1)) & kMask5555;
if (!raregeno_word) {
continue;
}
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
do {
const uint32_t difflist_idx_lowbits = ctzw(raregeno_word) / 2;
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits];
if (!IsSet(sex_male, sample_idx)) {
if (singleton_idx != UINT32_MAX) {
return;
}
singleton_idx = sample_idx;
}
raregeno_word = raregeno_word & (raregeno_word - 1);
} while (raregeno_word);
}
if (singleton_idx != UINT32_MAX) {
diploid_singleton_cts[singleton_idx] += 1;
}
}
void UpdateSampleSingletonCountSparseX(const uintptr_t* sex_male, const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len, uint32_t* singleton_cts) {
const uint32_t word_ct = NypCtToWordCt(difflist_len);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
const uintptr_t raregeno_word = raregeno[widx];
if (!raregeno_word) {
continue;
}
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
const uintptr_t geno2_word = (~raregeno_word) & (raregeno_word >> 1) & kMask5555;
if (geno2_word) {
if ((singleton_idx != UINT32_MAX) || (geno2_word & (geno2_word - 1))) {
return;
}
singleton_idx = cur_difflist_sample_ids[ctzw(geno2_word) / 2];
}
uintptr_t geno1_word = raregeno_word & (~(raregeno_word >> 1)) & kMask5555;
while (geno1_word) {
const uint32_t difflist_idx_lowbits = ctzw(geno1_word) / 2;
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits];
if (!IsSet(sex_male, sample_idx)) {
if (singleton_idx != UINT32_MAX) {
return;
}
singleton_idx = sample_idx;
}
geno1_word = geno1_word & (geno1_word - 1);
}
}
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
}
void UpdateSampleSingletonCountSparseY(const uintptr_t* sex_male, const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len, uint32_t* singleton_cts) {
const uint32_t word_ct = NypCtToWordCt(difflist_len);
uint32_t singleton_idx = UINT32_MAX;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
uintptr_t raregeno_word = raregeno[widx];
if (!raregeno_word) {
continue;
}
raregeno_word = (~raregeno_word) & (raregeno_word >> 1) & kMask5555;
if (!raregeno_word) {
continue;
}
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
do {
const uint32_t difflist_idx_lowbits = ctzw(raregeno_word) / 2;
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits];
if (IsSet(sex_male, sample_idx)) {
if (singleton_idx != UINT32_MAX) {
return;
}
singleton_idx = sample_idx;
}
raregeno_word = raregeno_word & (raregeno_word - 1);
} while (raregeno_word);
}
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
}
void UpdateDenseSampleCounts3(const uintptr_t* genovec, uint32_t acc2_vec_ct, VecW* acc2_0, uint16_t* remainders) {
const VecW m1 = VCONST_W(kMask5555);
const VecW* genovvec = R_CAST(const VecW*, genovec);
VecW* acc2_2 = &(acc2_0[acc2_vec_ct * 23]);
VecW* acc2_1 = &(acc2_2[acc2_vec_ct * 23]);
for (uint32_t vidx = 0; vidx != acc2_vec_ct; ++vidx) {
// Tried iterating over word-indexes instead (since LEA instruction can
// only multiply by 1/2/4/8, not 16 or 32), but that doesn't help, it just
// makes the code messier.
const VecW vv = genovvec[vidx];
const VecW vv_hi = vecw_srli(vv, 1);
const VecW vv_lo_0 = vecw_and_notfirst(vv, m1);
acc2_0[vidx] += vecw_and_notfirst(vv_hi, vv_lo_0);
acc2_2[vidx] += vv_lo_0 & vv_hi;
acc2_1[vidx] += vecw_and_notfirst(vv_hi, vv) & m1;
}
remainders[0] -= 1;
if (!remainders[0]) {
VecW* acc4_0 = &(acc2_0[acc2_vec_ct]);
Vcount0Incr2To4(acc2_vec_ct, acc2_0, acc4_0);
VecW* acc4_2 = &(acc2_2[acc2_vec_ct]);
Vcount0Incr2To4(acc2_vec_ct, acc2_2, acc4_2);
VecW* acc4_1 = &(acc2_1[acc2_vec_ct]);
Vcount0Incr2To4(acc2_vec_ct, acc2_1, acc4_1);
remainders[1] -= 1;
if (!remainders[1]) {
const uint32_t acc4_vec_ct = acc2_vec_ct * 2;
VecW* acc8_0 = &(acc4_0[acc4_vec_ct]);
Vcount0Incr4To8(acc4_vec_ct, acc4_0, acc8_0);
VecW* acc8_2 = &(acc4_2[acc4_vec_ct]);
Vcount0Incr4To8(acc4_vec_ct, acc4_2, acc8_2);
VecW* acc8_1 = &(acc4_1[acc4_vec_ct]);
Vcount0Incr4To8(acc4_vec_ct, acc4_1, acc8_1);
remainders[2] -= 1;
if (!remainders[2]) {
const uint32_t acc8_vec_ct = acc4_vec_ct * 2;
VecW* acc32_0 = &(acc8_0[acc8_vec_ct]);
Vcount0Incr8To32(acc8_vec_ct, acc8_0, acc32_0);
VecW* acc32_2 = &(acc8_2[acc8_vec_ct]);
Vcount0Incr8To32(acc8_vec_ct, acc8_2, acc32_2);
VecW* acc32_1 = &(acc8_1[acc8_vec_ct]);
Vcount0Incr8To32(acc8_vec_ct, acc8_1, acc32_1);
remainders[2] = 17;
}
remainders[1] = 5;
}
remainders[0] = 3;
}
}
void UpdateDenseSampleCounts2(const uintptr_t* genovec, uint32_t acc2_vec_ct, VecW* acc2_0, uint16_t* remainders) {
const VecW m1 = VCONST_W(kMask5555);
const VecW* genovvec = R_CAST(const VecW*, genovec);
VecW* acc2_2 = &(acc2_0[acc2_vec_ct * 23]);
for (uint32_t vidx = 0; vidx != acc2_vec_ct; ++vidx) {
const VecW vv = genovvec[vidx];
const VecW vv_hi = vecw_srli(vv, 1);
const VecW vv_lo_0 = vecw_and_notfirst(vv, m1);
acc2_0[vidx] += vecw_and_notfirst(vv_hi, vv_lo_0);
acc2_2[vidx] += vv_lo_0 & vv_hi;
}
remainders[0] -= 1;
if (!remainders[0]) {
VecW* acc4_0 = &(acc2_0[acc2_vec_ct]);
Vcount0Incr2To4(acc2_vec_ct, acc2_0, acc4_0);
VecW* acc4_2 = &(acc2_2[acc2_vec_ct]);
Vcount0Incr2To4(acc2_vec_ct, acc2_2, acc4_2);
remainders[1] -= 1;
if (!remainders[1]) {
const uint32_t acc4_vec_ct = acc2_vec_ct * 2;
VecW* acc8_0 = &(acc4_0[acc4_vec_ct]);
Vcount0Incr4To8(acc4_vec_ct, acc4_0, acc8_0);
VecW* acc8_2 = &(acc4_2[acc4_vec_ct]);
Vcount0Incr4To8(acc4_vec_ct, acc4_2, acc8_2);
remainders[2] -= 1;
if (!remainders[2]) {
const uint32_t acc8_vec_ct = acc4_vec_ct * 2;
VecW* acc32_0 = &(acc8_0[acc8_vec_ct]);
Vcount0Incr8To32(acc8_vec_ct, acc8_0, acc32_0);
VecW* acc32_2 = &(acc8_2[acc8_vec_ct]);
Vcount0Incr8To32(acc8_vec_ct, acc8_2, acc32_2);
remainders[2] = 17;
}
remainders[1] = 5;
}
remainders[0] = 3;
}
}
// This shares a lot with LoadSampleMissingCts() in plink2_filter. Might want
// to merge this into a single driver function at some point, similar to how
// LoadAlleleAndGenoCounts() reduces duplication of variant-stat calculation.
typedef struct SampleCountsCtxStruct {
const uintptr_t* variant_include;
const ChrInfo* cip;
const uintptr_t* allele_idx_offsets;
const char* const* allele_storage;
const uintptr_t* sample_include;
uint32_t* sample_include_cumulative_popcounts;
uintptr_t* sex_male_collapsed;
uint32_t sample_ct;
uint32_t male_ct;
uint32_t y_nonmale_needed;
PgenReader** pgr_ptrs;
uintptr_t** genovecs;
uintptr_t** thread_read_mhc;
uintptr_t** raregenos;
uint32_t** difflist_sample_id_bufs;
uint32_t* read_variant_uidx_starts;
uint32_t cur_block_size;
uint64_t err_info;
// top-level: length calc_thread_ct array
// second level: length-20 arrays, corresponding to the 20 chr_type x
// subst_code possibilities
// bottom level: acc2 partial counts, then acc4, then acc8, then acc32 for
// genotype=0. Then the same for genotype=2, and finally (in
// autosomal-diploid/chrX cases) genotype=1.
VecW*** thread_dense_counts;
// top-level: length calc_thread_ct array
// second level: length-40 arrays, corresponding to chr_type x common_geno x
// subst_code possibilities
// bottom level: three vector-aligned length-sample_ct arrays, corresponding
// to the three ((common_geno ^ rare_geno) - 1) possibilities.
uint32_t*** thread_sparse_counts;
uint32_t** thread_sparse_common0_cts;
uint32_t** thread_diploid_singleton_cts;
uint32_t** thread_singleton_cts;
uint16_t** thread_alt_subst_codes;
// Multiallelic complications: geno=2 entries can correspond to het
// altx/alty, and subst_code can vary between alt alleles. We track the
// necessary adjustments with the het_rarealt_cts, het2alt_cts,
// hom_rarealt_cts, and hap_rarealt_cts arrays below.
// - het2alt_cts has 10 vector-aligned length-sample_ct arrays. The first
// five correspond to ALT1 subst_codes, and the last five correspond to the
// actually-observed-ALT subst_codes. The sum of the last five arrays is
// always twice that of the first five arrays, since each allele is counted
// separately.
// - het_rarealt_cts, hom_rarealt_cts and hap_rarealt_cts have 5
// vector-aligned lenght-sample_ct arrays, corresponding to subst_code
// frequency deltas.
uint32_t** thread_het2alt_cts;
int32_t** thread_het_rarealt_cts;
int32_t** thread_hom_rarealt_cts;
int32_t** thread_hap_rarealt_cts;
} SampleCountsCtx;
THREAD_FUNC_DECL SampleCountsThread(void* raw_arg) {
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
const uintptr_t tidx = arg->tidx;
SampleCountsCtx* ctx = S_CAST(SampleCountsCtx*, arg->sharedp->context);
const uintptr_t* variant_include = ctx->variant_include;
const ChrInfo* cip = ctx->cip;
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
const char* const* allele_storage = ctx->allele_storage;
const uintptr_t* sample_include = ctx->sample_include;
PgenReader* pgrp = ctx->pgr_ptrs[tidx];
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
const uintptr_t* sex_male_collapsed = ctx->sex_male_collapsed;
const uintptr_t sample_ct = ctx->sample_ct;
const uint32_t male_ct = ctx->male_ct;
const uint32_t skip_y = (!male_ct) && (!ctx->y_nonmale_needed);
uintptr_t* genovec = ctx->genovecs[tidx];
PgenVariant pgv;
pgv.genovec = genovec;
SetPgvThreadMhcNull(sample_ct, tidx, ctx->thread_read_mhc, &pgv);
uintptr_t* raregeno = ctx->raregenos[tidx];
uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx];
// todo: tune this threshold
const uint32_t max_simple_difflist_len = sample_ct / 32;
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
const uint32_t acc2_vec_ct = NypCtToVecCt(sample_ct);
const uintptr_t dense_counts_vstride = acc2_vec_ct * 23;
const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
VecW** dense_counts = ctx->thread_dense_counts[tidx];
// 4 chr_types, 3 remainders per variant_type
// uint16_t instead of uint8_t to avoid aliasing paranoia
uint16_t dense_remainders[12 * kSubstCodeCt];
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) {
if (dense_counts[dense_vtype]) {
ZeroVecArr(dense_counts_vstride * (2 + (dense_vtype < 2 * kSubstCodeCt)), dense_counts[dense_vtype]);
dense_remainders[3 * dense_vtype] = 3;
dense_remainders[3 * dense_vtype + 1] = 5;
dense_remainders[3 * dense_vtype + 2] = 17;
}
}
const uintptr_t sample_ct_i32av = RoundUpPow2(sample_ct, kInt32PerVec);
uint32_t** sparse_counts = ctx->thread_sparse_counts[tidx];
// 4 chr_types * 2 common_geno
for (uint32_t uii = 0; uii != 8 * kSubstCodeCt; ++uii) {
if (sparse_counts[uii]) {
ZeroU32Arr(3 * sample_ct_i32av, sparse_counts[uii]);
}
}
uint32_t* sparse_common0_cts = ctx->thread_sparse_common0_cts[tidx];
ZeroU32Arr(4 * kSubstCodeCt, sparse_common0_cts);
uint32_t* diploid_singleton_cts = nullptr;
if (ctx->thread_diploid_singleton_cts) {
diploid_singleton_cts = ctx->thread_diploid_singleton_cts[tidx];
ZeroU32Arr(sample_ct_i32av, diploid_singleton_cts);
}
uint32_t* singleton_cts = nullptr;
if (ctx->thread_singleton_cts) {
singleton_cts = ctx->thread_singleton_cts[tidx];
ZeroU32Arr(sample_ct_i32av, singleton_cts);
}
uint16_t* alt_subst_codes = nullptr;
uint32_t* het2alt_minus_cts = nullptr;
uint32_t* het2alt_plus_cts = nullptr;
int32_t* het_rarealt_cts = nullptr;
int32_t* hom_rarealt_cts = nullptr;
int32_t* hap_rarealt_cts = nullptr;
if (ctx->thread_alt_subst_codes) {
alt_subst_codes = ctx->thread_alt_subst_codes[tidx];
het2alt_minus_cts = ctx->thread_het2alt_cts[tidx];
ZeroU32Arr(2 * kSubstCodeCt * sample_ct_i32av, het2alt_minus_cts);
het2alt_plus_cts = &(het2alt_minus_cts[kSubstCodeCt * sample_ct_i32av]);
het_rarealt_cts = ctx->thread_het_rarealt_cts[tidx];
ZeroI32Arr(kSubstCodeCt * sample_ct_i32av, het_rarealt_cts);
hom_rarealt_cts = ctx->thread_hom_rarealt_cts[tidx];
ZeroI32Arr(kSubstCodeCt * sample_ct_i32av, hom_rarealt_cts);
if (ctx->thread_hap_rarealt_cts) {
hap_rarealt_cts = ctx->thread_hap_rarealt_cts[tidx];
ZeroI32Arr(kSubstCodeCt * sample_ct_i32av, hap_rarealt_cts);
}
}
uint32_t cur_allele_ct = 2;
uint64_t new_err_info = 0;
do {
const uint32_t cur_block_size = ctx->cur_block_size;
const uint32_t cur_idx_ct = (((tidx + 1) * cur_block_size) / calc_thread_ct) - ((tidx * cur_block_size) / calc_thread_ct);
uintptr_t variant_uidx_base;
uintptr_t cur_bits;
BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
uint32_t chr_end = 0;
uint32_t chr_type = 0;
uint32_t is_haploid = 0;
uint32_t is_diploid_x = 0;
uint32_t is_y = 0;
for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
is_haploid = IsSet(cip->haploid_mask, chr_idx);
is_diploid_x = 0;
is_y = (chr_idx == y_code);
if (chr_idx == x_code) {
is_diploid_x = !IsSet(cip->haploid_mask, 0);
}
chr_type = 0;
if (is_haploid) {
if (is_diploid_x) {
if (!male_ct) {
// all-unknown-sex override
is_haploid = 0;
is_diploid_x = 0;
} else {
chr_type = 1;
}
} else if (is_y) {
chr_type = 2;
} else {
chr_type = 3;
}
}
}
if (is_y && skip_y) {
continue;
}
uintptr_t allele_idx_offset_base;
if (!allele_idx_offsets) {
allele_idx_offset_base = variant_uidx * 2;
} else {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (cur_allele_ct == 2) {
// Finally, a scenario where exposing this capability really pays off.
uint32_t difflist_common_geno;
uint32_t difflist_len;
const PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_simple_difflist_len, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
if (unlikely(reterr)) {
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
goto SampleCountsThread_err;
}
if (difflist_common_geno == 2) {
// Don't bother with sparse optimization here, should be rare and it
// complicates singleton-counting code
PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, sample_ct, difflist_len, genovec);
difflist_common_geno = UINT32_MAX;
}
uint32_t subst_code = GetSubstCode(cur_alleles[0], cur_alleles[1]);
const uint32_t dense_vtype = chr_type * kSubstCodeCt + subst_code;
if (difflist_common_geno == UINT32_MAX) {
if (chr_type < 2) {
UpdateDenseSampleCounts3(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3]));
} else {
UpdateDenseSampleCounts2(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3]));
}
if (diploid_singleton_cts || singleton_cts) {
ZeroTrailingNyps(sample_ct, genovec);
if (is_haploid) {
if (is_diploid_x) {
if (diploid_singleton_cts) {
UpdateSampleDiploidSingletonCountX(sex_male_collapsed, genovec, sample_ct, diploid_singleton_cts);
}
if (singleton_cts) {
UpdateSampleSingletonCountX(sex_male_collapsed, genovec, sample_ct, singleton_cts);
}
continue;
}
if (!singleton_cts) {
continue;
}
if (is_y) {
UpdateSampleSingletonCountY(sex_male_collapsed, genovec, sample_ct, singleton_cts);
continue;
}
SetHetMissing(sample_ctl2, genovec);
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct);
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
continue;
}
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct);
if (singleton_idx != UINT32_MAX) {
if (diploid_singleton_cts) {
diploid_singleton_cts[singleton_idx] += 1;
}
if (singleton_cts) {
singleton_cts[singleton_idx] += 1;
}
}
}
continue;
}
uint32_t vtrans_type = dense_vtype + chr_type * kSubstCodeCt;
if (!difflist_common_geno) {
sparse_common0_cts[dense_vtype] += 1;
} else {
vtrans_type += kSubstCodeCt;
}
if (!difflist_len) {
continue;
}
uint32_t* cur_sparse_cts = sparse_counts[vtrans_type];
const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2;
// difflist_common_geno_word == 0 if difflist_common_geno == 0,
// ~k0LU if difflist_common_geno == 3.
const uintptr_t difflist_common_geno_word = -S_CAST(uintptr_t, difflist_common_geno & 1);
uint32_t loop_len = kBitsPerWordD2;
for (uint32_t widx = 0; ; ++widx) {
if (widx >= word_ct_m1) {
if (widx > word_ct_m1) {
break;
}
loop_len = ModNz(difflist_len, kBitsPerWordD2);
}
uintptr_t raregeno_xor_word = raregeno[widx] ^ difflist_common_geno_word;
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uintptr_t sample_idx = cur_difflist_sample_ids[uii];
const uint32_t cur_geno_xor = raregeno_xor_word & 3;
cur_sparse_cts[(cur_geno_xor - 1) * sample_ct_i32av + sample_idx] += 1;
raregeno_xor_word = raregeno_xor_word >> 2;
}
}
if (diploid_singleton_cts || singleton_cts) {
ZeroTrailingNyps(difflist_len, raregeno);
if (is_haploid) {
if (is_diploid_x) {
if (diploid_singleton_cts) {
UpdateSampleDiploidSingletonCountSparseX(sex_male_collapsed, raregeno, difflist_sample_ids, difflist_len, diploid_singleton_cts);
}
if (singleton_cts) {
UpdateSampleSingletonCountSparseX(sex_male_collapsed, raregeno, difflist_sample_ids, difflist_len, singleton_cts);
}
continue;
}
if (!singleton_cts) {
continue;
}
if (is_y) {
UpdateSampleSingletonCountSparseY(sex_male_collapsed, raregeno, difflist_sample_ids, difflist_len, singleton_cts);
continue;
}
const uint32_t difflist_word_ct = NypCtToWordCt(difflist_len);
SetHetMissing(difflist_word_ct, raregeno);
const uint32_t singleton_idx = GetSingletonIdxSparse(raregeno, difflist_sample_ids, difflist_len);
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
continue;
}
const uint32_t singleton_idx = GetSingletonIdxSparse(raregeno, difflist_sample_ids, difflist_len);
if (singleton_idx != UINT32_MAX) {
if (diploid_singleton_cts) {
diploid_singleton_cts[singleton_idx] += 1;
}
if (singleton_cts) {
singleton_cts[singleton_idx] += 1;
}
}
}
continue;
}
// Multiallelic case.
const PglErr reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv);
if (unlikely(reterr)) {
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
goto SampleCountsThread_err;
}
const uint32_t subst_code1 = GetSubstCode(cur_alleles[0], cur_alleles[1]);
alt_subst_codes[1] = subst_code1;
uint32_t subst_codes_vary = 0;
for (uint32_t allele_idx = 2; allele_idx != cur_allele_ct; ++allele_idx) {
const uint32_t cur_subst_code = GetSubstCode(cur_alleles[0], cur_alleles[allele_idx]);
alt_subst_codes[allele_idx] = cur_subst_code;
subst_codes_vary |= (cur_subst_code != subst_code1);
}
const uint32_t dense_vtype = chr_type * kSubstCodeCt + subst_code1;
if (chr_type < 2) {
UpdateDenseSampleCounts3(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3]));
} else {
UpdateDenseSampleCounts2(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3]));
}
const uint32_t patch_10_ct = pgv.patch_10_ct;
const uint32_t subst_code1_offset = subst_code1 * sample_ct_i32av;
if (!subst_codes_vary) {
if (patch_10_ct) {
const uintptr_t* patch_10_set = pgv.patch_10_set;
const AlleleCode* patch_10_vals = pgv.patch_10_vals;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_10_set[0];
if (!chr_type) {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
if (a0 != a1) {
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1;
het2alt_plus_cts[subst_code1_offset + sample_idx] += 2;
}
}
} else if (chr_type == 1) {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
if (a0 != a1) {
if (!is_male) {
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1;
het2alt_plus_cts[subst_code1_offset + sample_idx] += 2;
} else {
// het-haploid, treat as missing
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
}
}
}
} else {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
if (a0 != a1) {
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
}
}
}
}
} else { // subst_codes_vary
if (chr_type < 2) {
const uint32_t patch_01_ct = pgv.patch_01_ct;
if (patch_01_ct) {
const uintptr_t* patch_01_set = pgv.patch_01_set;
const AlleleCode* patch_01_vals = pgv.patch_01_vals;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_01_set[0];
if (!chr_type) {
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits);
const uint32_t cur_subst_code = alt_subst_codes[patch_01_vals[uii]];
if (subst_code1 != cur_subst_code) {
het_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
het_rarealt_cts[cur_subst_code * sample_ct_i32av + sample_idx] += 1;
}
}
} else {
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits);
// bugfix (9 Jan 2023): in male case, we will adjust hethap
// to missing later under the assumption that this genotype
// is ref/alt1. So, subst_code doesn't matter.
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx);
if (!is_male) {
const uint32_t cur_subst_code = alt_subst_codes[patch_01_vals[uii]];
if (subst_code1 != cur_subst_code) {
het_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
het_rarealt_cts[cur_subst_code * sample_ct_i32av + sample_idx] += 1;
}
}
}
}
}
}
if (patch_10_ct) {
const uintptr_t* patch_10_set = pgv.patch_10_set;
const AlleleCode* patch_10_vals = pgv.patch_10_vals;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_10_set[0];
if (!chr_type) {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
const uint32_t new_code0 = alt_subst_codes[a0];
if (a0 != a1) {
const uint32_t new_code1 = alt_subst_codes[a1];
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1;
het2alt_plus_cts[new_code0 * sample_ct_i32av + sample_idx] += 1;
het2alt_plus_cts[new_code1 * sample_ct_i32av + sample_idx] += 1;
} else if (new_code0 != subst_code1) {
hom_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
hom_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1;
}
}
} else if (chr_type == 1) {
// ugh
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
const uint32_t new_code0 = alt_subst_codes[a0];
if (a0 != a1) {
if (!is_male) {
const uint32_t new_code1 = alt_subst_codes[a1];
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1;
het2alt_plus_cts[new_code0 * sample_ct_i32av + sample_idx] += 1;
het2alt_plus_cts[new_code1 * sample_ct_i32av + sample_idx] += 1;
} else {
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
}
} else if (new_code0 != subst_code1) {
if (!is_male) {
hom_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
hom_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1;
} else {
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
hap_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1;
}
}
}
} else {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
const uint32_t new_code0 = alt_subst_codes[a0];
if (a0 != a1) {
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
} else if (new_code0 != subst_code1) {
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1;
hap_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1;
}
}
}
}
}
if (diploid_singleton_cts || singleton_cts) {
// this logic is completely unchanged, basic dense case should fall
// through to this?
ZeroTrailingNyps(sample_ct, genovec);
if (is_haploid) {
if (is_diploid_x) {
if (diploid_singleton_cts) {
UpdateSampleDiploidSingletonCountX(sex_male_collapsed, genovec, sample_ct, diploid_singleton_cts);
}
if (singleton_cts) {
UpdateSampleSingletonCountX(sex_male_collapsed, genovec, sample_ct, singleton_cts);
}
continue;
}
if (!singleton_cts) {
continue;
}
if (is_y) {
UpdateSampleSingletonCountY(sex_male_collapsed, genovec, sample_ct, singleton_cts);
continue;
}
SetHetMissing(sample_ctl2, genovec);
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct);
if (singleton_idx != UINT32_MAX) {
singleton_cts[singleton_idx] += 1;
}
continue;
}
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct);
if (singleton_idx != UINT32_MAX) {
if (diploid_singleton_cts) {
diploid_singleton_cts[singleton_idx] += 1;
}
if (singleton_cts) {
singleton_cts[singleton_idx] += 1;
}
}
}
}
} while (!THREAD_BLOCK_FINISH(arg));
{
const uintptr_t acc4_vec_ct = acc2_vec_ct * 2;
const uintptr_t acc8_vec_ct = acc2_vec_ct * 4;
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) {
VecW* acc2_0 = dense_counts[dense_vtype];
if (acc2_0) {
VecW* acc4_0 = &(acc2_0[acc2_vec_ct]);
VcountIncr2To4(acc2_0, acc2_vec_ct, acc4_0);
VecW* acc8_0 = &(acc4_0[acc4_vec_ct]);
VcountIncr4To8(acc4_0, acc4_vec_ct, acc8_0);
VcountIncr8To32(acc8_0, acc8_vec_ct, &(acc8_0[acc8_vec_ct]));
VecW* acc2_2 = &(acc2_0[dense_counts_vstride]);
VecW* acc4_2 = &(acc2_2[acc2_vec_ct]);
VcountIncr2To4(acc2_2, acc2_vec_ct, acc4_2);
VecW* acc8_2 = &(acc4_2[acc4_vec_ct]);
VcountIncr4To8(acc4_2, acc4_vec_ct, acc8_2);
VcountIncr8To32(acc8_2, acc8_vec_ct, &(acc8_2[acc8_vec_ct]));
if (dense_vtype < 2 * kSubstCodeCt) {
VecW* acc2_1 = &(acc2_2[dense_counts_vstride]);
VecW* acc4_1 = &(acc2_1[acc2_vec_ct]);
VcountIncr2To4(acc2_1, acc2_vec_ct, acc4_1);
VecW* acc8_1 = &(acc4_1[acc4_vec_ct]);
VcountIncr4To8(acc4_1, acc4_vec_ct, acc8_1);
VcountIncr8To32(acc8_1, acc8_vec_ct, &(acc8_1[acc8_vec_ct]));
}
}
}
}
while (0) {
SampleCountsThread_err:
UpdateU64IfSmaller(new_err_info, &ctx->err_info);
THREAD_BLOCK_FINISH(arg);
break;
}
THREAD_RETURN;
}
void Unscramble2(uint32_t sample_ct, uint32_t* dst, uint32_t* unscramble_buf) {
const uint32_t acc2_vec_ct = NypCtToWordCt(sample_ct);
memcpy(unscramble_buf, dst, acc2_vec_ct * 16 * kBytesPerVec);
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t scrambled_idx = VcountScramble2(sample_idx);
dst[sample_idx] = unscramble_buf[scrambled_idx];
}
}
// diploid-only if haploid_counts_subst == nullptr
void IncrSubstType(const SampleCountsCtx* ctx, const uint32_t* const* diploid_counts_subst, const uint32_t* const* haploid_counts_subst, uint32_t sample_ct_i32v, uint32_t subst_code, uint32_t* dst) {
{
const uint32_t* dip_src1 = diploid_counts_subst[1];
const uint32_t* dip_src2 = diploid_counts_subst[2];
U32CastVecAdd2(dip_src1, dip_src2, sample_ct_i32v, dst);
if (haploid_counts_subst) {
const uint32_t* hap_src = haploid_counts_subst[1];
if (hap_src) {
U32CastVecAdd(hap_src, sample_ct_i32v, dst);
}
}
}
if (ctx->thread_het2alt_cts) {
const uintptr_t sample_ct_i32av = sample_ct_i32v * kInt32PerVec;
const uint32_t* sub_src = &(ctx->thread_het2alt_cts[0][subst_code * sample_ct_i32av]);
const uint32_t* add_src = &(sub_src[kSubstCodeCt * sample_ct_i32av]);
U32CastVecAddSub(add_src, sub_src, sample_ct_i32v, dst);
}
}
uint32_t* AllocAndCountSubstType(const SampleCountsCtx* ctx, const uint32_t* const* diploid_counts_subst, const uint32_t* const* haploid_counts_subst, uint32_t sample_ct_i32v, uint32_t subst_code) {
uint32_t* dst = S_CAST(uint32_t*, bigstack_alloc(sample_ct_i32v * sizeof(VecU32)));
if (unlikely(!dst)) {
return nullptr;
}
ZeroU32Arr(sample_ct_i32v * kInt32PerVec, dst);
IncrSubstType(ctx, diploid_counts_subst, haploid_counts_subst, sample_ct_i32v, subst_code, dst);
return dst;
}
ENUM_U31_DEF_START()
kSampleCountHom,
kSampleCountHomref,
kSampleCountHomalt,
kSampleCountHomaltSnp,
kSampleCountHet,
kSampleCountRefalt,
kSampleCountHet2alt,
kSampleCountHetSnp,
kSampleCountDiploidTs,
kSampleCountTs,
kSampleCountDiploidTv,
kSampleCountTv,
kSampleCountDiploidNonsnpsymb,
kSampleCountNonsnpsymb,
kSampleCountSymbolic,
kSampleCountNonsnp,
kSampleCountDiploidSingle,
kSampleCountSingle,
kSampleCountHaprefWithFemaleY,
kSampleCountHapref,
kSampleCountHapaltWithFemaleY,
kSampleCountHapalt,
kSampleCountMissingWithFemaleY,
kSampleCountMissing,
kSampleCountTypeCt
ENUM_U31_DEF_END(SampleCountType);
PglErr SampleCounts(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t male_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, SampleCountsFlags flags, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
unsigned char* bigstack_end_mark = g_bigstack_end;
const char sample_counts_headers[kSampleCountTypeCt][30] = {
"HOM_CT",
"HOM_REF_CT",
"HOM_ALT_CT",
"HOM_ALT_SNP_CT",
"HET_CT",
"HET_REF_ALT_CT",
"HET_2ALT_CT",
"HET_SNP_CT",
"DIPLOID_TRANSITION_CT",
"TRANSITION_CT",
"DIPLOID_TRANSVERSION_CT",
"TRANSVERSION_CT",
"DIPLOID_NONSNP_NONSYMBOLIC_CT",
"NONSNP_NONSYMBOLIC_CT",
"SYMBOLIC_CT",
"NONSNP_CT",
"DIPLOID_SINGLETON_CT",
"SINGLETON_CT",
"HAP_REF_INCL_FEMALE_Y_CT",
"HAP_REF_CT",
"HAP_ALT_INCL_FEMALE_Y_CT",
"HAP_ALT_CT",
"MISSING_INCL_FEMALE_Y_CT",
"MISSING_CT"
};
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
ThreadGroup tg;
PreinitThreads(&tg);
SampleCountsCtx ctx;
{
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &ctx.sample_include_cumulative_popcounts))) {
goto SampleCounts_ret_NOMEM;
}
FillCumulativePopcounts(sample_include, raw_sample_ctl, ctx.sample_include_cumulative_popcounts);
// Biallelic variants are handled as follows:
// 1. Define four chromosome types (autosomal-diploid, chrX-diploid, chrY,
// and generic-haploid), and four substitution types (non-SNP,
// SNP-transition, SNP-transversion, non-ACGT 'SNP'). We compute
// per-sample 0/1/2 genotype counts for each (chromosome type,
// substitution type) pair. This is accelerated by distinguishing the
// dense- and sparse-storage cases, and also parallelized across
// variants.
// 2. Given these raw genotype counts, it is straightforward to build all
// of the supported columns, except for SINGLETON_CT. (MISSING_CT can
// be obtained by subtraction from the total number of variants,
// excluding chrY for nonmales.)
// 3. SINGLETON_CT gets its own logic in the main loop.
uint32_t chr_types = 0;
uint32_t diploid_chr_type_ct = 0;
if (IsAutosomalDiploidChrPresent(cip)) {
chr_types = 1;
++diploid_chr_type_ct;
}
uint32_t haploid_chr_type_ct = 0;
uint32_t y_variant_ct = 0;
uint32_t y_nonmale_needed = 0;
{
uint32_t y_code;
if (XymtExists(cip, kChrOffsetY, &y_code)) {
y_variant_ct = CountChrVariantsUnsafe(variant_include, cip, y_code);
}
uintptr_t haploid_mask_lowbit = cip->haploid_mask[0] & 1;
// bugfix (28 Mar 2021): if chrX is present, no autosomal diploid
// chromosomes are present, and there are no males, we need to set the
// low bit of chr_types and increment diploid_chr_type_ct.
uint32_t x_code;
if ((!haploid_mask_lowbit) && XymtExists(cip, kChrOffsetX, &x_code)) {
if (male_ct) {
chr_types |= 2;
++diploid_chr_type_ct;
} else if (!chr_types) {
chr_types = 1;
++diploid_chr_type_ct;
}
}
if (y_variant_ct) {
y_nonmale_needed = ((flags & (kfSampleCountsColHaprefWithFemaleY | kfSampleCountsColHapaltWithFemaleY | kfSampleCountsColMissingWithFemaleY)) != 0);
if (male_ct || y_nonmale_needed) {
chr_types |= 4;
++haploid_chr_type_ct;
}
}
uint32_t mt_code;
if (haploid_mask_lowbit || XymtExists(cip, kChrOffsetMT, &mt_code)) {
chr_types |= 8;
++haploid_chr_type_ct;
}
}
assert(diploid_chr_type_ct + haploid_chr_type_ct);
// probable todo: for sample_ct > raw_sample_ct / 2 or so, may be better to
// perform un-subsetted computation and then subset the results? Benchmark
// this.
const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
if (chr_types & 6) {
if (unlikely(bigstack_alloc_w(sample_ctl, &ctx.sex_male_collapsed))) {
goto SampleCounts_ret_NOMEM;
}
CopyBitarrSubset(sex_male, sample_include, sample_ct, ctx.sex_male_collapsed);
} else {
ctx.sex_male_collapsed = nullptr;
}
// don't subtract 1 after load-balancing is improved?
uint32_t calc_thread_ct = (max_thread_ct > 4)? (max_thread_ct - 1) : max_thread_ct;
if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.raregenos) ||
bigstack_alloc_u32p(calc_thread_ct, &ctx.difflist_sample_id_bufs) ||
bigstack_alloc_vpp(calc_thread_ct, &ctx.thread_dense_counts) ||
bigstack_alloc_u32pp(calc_thread_ct, &ctx.thread_sparse_counts) ||
bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_sparse_common0_cts))) {
goto SampleCounts_ret_NOMEM;
}
const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec);
const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec);
const uintptr_t acc2_vec_ct = NypCtToVecCt(sample_ct);
const uintptr_t dense_counts_vstride = acc2_vec_ct * 23;
// - need (0, 1, 2) genotype counts in diploid-chromosome case, only need
// (0, 1) for haploid
const uintptr_t dense_counts_bottom_vec_ct = kSubstCodeCt * (dense_counts_vstride * (3 * diploid_chr_type_ct + 2 * haploid_chr_type_ct));
const uintptr_t dense_counts_middle_vec_ct = DivUp(4 * kSubstCodeCt, kWordsPerVec);
const uintptr_t sample_ct_i32v = DivUp(sample_ct, kInt32PerVec);
// - x6 for 2 common_geno possibilities (0, 3), 3 common_geno -> rare_geno
// transitions per common_geno
const uintptr_t sparse_counts_bottom_vec_ct = 6 * kSubstCodeCt * sample_ct_i32v * (diploid_chr_type_ct + haploid_chr_type_ct);
const uintptr_t sample_ct_i32av = sample_ct_i32v * kInt32PerVec;
// - x8 for 4 chromosome types, 2 common_geno possibilities
const uintptr_t sparse_counts_middle_vec_ct = DivUp(8 * kSubstCodeCt, kWordsPerVec);
const uintptr_t sparse_common0_vec_ct = DivUp(4 * kSubstCodeCt, kInt32PerVec);
uintptr_t thread_xalloc_vec_ct = raregeno_vec_ct + difflist_sample_id_vec_ct + dense_counts_bottom_vec_ct + dense_counts_middle_vec_ct + sparse_counts_bottom_vec_ct + sparse_counts_middle_vec_ct + sparse_common0_vec_ct;
ctx.thread_diploid_singleton_cts = nullptr;
if (flags & kfSampleCountsColDiploidSingle) {
if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_diploid_singleton_cts))) {
goto SampleCounts_ret_NOMEM;
}
thread_xalloc_vec_ct += sample_ct_i32v;
}
ctx.thread_singleton_cts = nullptr;
if (flags & kfSampleCountsColSingle) {
if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_singleton_cts))) {
goto SampleCounts_ret_NOMEM;
}
thread_xalloc_vec_ct += sample_ct_i32v;
}
// We support multiallelic variants by also tracking a few het_2alt,
// hom_rarealt, and hap_rarealt counts.
ctx.thread_alt_subst_codes = nullptr;
ctx.thread_het2alt_cts = nullptr;
ctx.thread_het_rarealt_cts = nullptr;
ctx.thread_hom_rarealt_cts = nullptr;
ctx.thread_hap_rarealt_cts = nullptr;
const uint32_t mhc_needed = (max_allele_ct > 2);
uintptr_t alt_subst_codes_vec_ct = 0;
uintptr_t het2alt_vec_ct = 0;
uintptr_t het_rarealt_vec_ct = 0;
uintptr_t hom_rarealt_vec_ct = 0;
uintptr_t hap_rarealt_vec_ct = 0;
if (mhc_needed) {
if (unlikely(bigstack_alloc_u16p(calc_thread_ct, &ctx.thread_alt_subst_codes) ||
bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_het2alt_cts) ||
bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_het_rarealt_cts) ||
bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_hom_rarealt_cts))) {
goto SampleCounts_ret_NOMEM;
}
alt_subst_codes_vec_ct = DivUp(kPglMaxAlleleCt, kInt16PerVec);
het2alt_vec_ct = sample_ct_i32v * 2 * kSubstCodeCt;
het_rarealt_vec_ct = sample_ct_i32v * kSubstCodeCt;
hom_rarealt_vec_ct = sample_ct_i32v * kSubstCodeCt;
thread_xalloc_vec_ct += alt_subst_codes_vec_ct + het2alt_vec_ct + het_rarealt_vec_ct + hom_rarealt_vec_ct;
if (chr_types & 14) {
if (unlikely(bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_hap_rarealt_cts))) {
goto SampleCounts_ret_NOMEM;
}
hap_rarealt_vec_ct = sample_ct_i32v * kSubstCodeCt;
thread_xalloc_vec_ct += hap_rarealt_vec_ct;
}
}
const uintptr_t thread_xalloc_cacheline_ct = DivUp(thread_xalloc_vec_ct, kVecsPerCacheline);
// Cacheline-alignment is relevant for per-thread workspaces. We normally
// get that automatically by allocating from the bottom of the arena, but
// in this case it's more convenient to allocate them at the end, which is
// normally only vector-aligned. So we force the end to be
// cacheline-aligned here.
g_bigstack_end = R_CAST(unsigned char*, RoundDownPow2(R_CAST(uintptr_t, g_bigstack_end), kCacheline));
unsigned char* bigstack_mark2 = g_bigstack_base;
STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
ctx.thread_read_mhc = nullptr;
uint32_t read_block_size;
if (unlikely(PgenMtLoadInit(variant_include, raw_sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
goto SampleCounts_ret_NOMEM;
}
if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
goto SampleCounts_ret_NOMEM;
}
ctx.variant_include = variant_include;
ctx.cip = cip;
ctx.allele_idx_offsets = allele_idx_offsets;
ctx.allele_storage = allele_storage;
ctx.sample_include = sample_include;
ctx.sample_ct = sample_ct;
ctx.male_ct = male_ct;
ctx.y_nonmale_needed = y_nonmale_needed;
ctx.err_info = (~0LLU) << 32;
unsigned char* bigstack_end_mark2 = nullptr;
assert(bigstack_left() >= thread_xalloc_cacheline_ct * kCacheline * calc_thread_ct);
for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
unsigned char* cur_alloc = S_CAST(unsigned char*, bigstack_end_alloc_raw(thread_xalloc_cacheline_ct * kCacheline));
ctx.raregenos[tidx] = R_CAST(uintptr_t*, cur_alloc);
cur_alloc = &(cur_alloc[raregeno_vec_ct * kBytesPerVec]);
ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[difflist_sample_id_vec_ct * kBytesPerVec]);
if (mhc_needed) {
ctx.thread_alt_subst_codes[tidx] = R_CAST(uint16_t*, cur_alloc);
cur_alloc = &(cur_alloc[alt_subst_codes_vec_ct * kBytesPerVec]);
}
if (!tidx) {
bigstack_end_mark2 = cur_alloc;
}
ctx.thread_dense_counts[tidx] = R_CAST(VecW**, cur_alloc);
cur_alloc = &(cur_alloc[dense_counts_middle_vec_ct * kBytesPerVec]);
ZeroPtrArr(4 * kSubstCodeCt, ctx.thread_dense_counts[tidx]);
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) {
if (!((chr_types >> cur_chr_type) & 1)) {
continue;
}
const uintptr_t record_byte_ct = (dense_counts_vstride * (2 + (cur_chr_type < 2))) * kBytesPerVec;
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
ctx.thread_dense_counts[tidx][cur_chr_type * kSubstCodeCt + subst_code] = R_CAST(VecW*, cur_alloc);
cur_alloc = &(cur_alloc[record_byte_ct]);
}
}
ctx.thread_sparse_counts[tidx] = R_CAST(uint32_t**, cur_alloc);
cur_alloc = &(cur_alloc[sparse_counts_middle_vec_ct * kBytesPerVec]);
ZeroPtrArr(8 * kSubstCodeCt, ctx.thread_sparse_counts[tidx]);
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) {
if (!((chr_types >> cur_chr_type) & 1)) {
continue;
}
const uintptr_t record_byte_ct = sample_ct_i32v * 3 * kBytesPerVec;
for (uint32_t common_geno_and_subst_code = 0; common_geno_and_subst_code != 2 * kSubstCodeCt; ++common_geno_and_subst_code) {
ctx.thread_sparse_counts[tidx][cur_chr_type * 2 * kSubstCodeCt + common_geno_and_subst_code] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[record_byte_ct]);
}
}
ctx.thread_sparse_common0_cts[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[sparse_common0_vec_ct * kBytesPerVec]);
if (ctx.thread_diploid_singleton_cts) {
ctx.thread_diploid_singleton_cts[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]);
}
if (ctx.thread_singleton_cts) {
ctx.thread_singleton_cts[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]);
}
if (mhc_needed) {
ctx.thread_het2alt_cts[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[het2alt_vec_ct * kBytesPerVec]);
ctx.thread_het_rarealt_cts[tidx] = R_CAST(int32_t*, cur_alloc);
cur_alloc = &(cur_alloc[het_rarealt_vec_ct * kBytesPerVec]);
ctx.thread_hom_rarealt_cts[tidx] = R_CAST(int32_t*, cur_alloc);
cur_alloc = &(cur_alloc[hom_rarealt_vec_ct * kBytesPerVec]);
if (ctx.thread_hap_rarealt_cts) {
ctx.thread_hap_rarealt_cts[tidx] = R_CAST(int32_t*, cur_alloc);
cur_alloc = &(cur_alloc[hap_rarealt_vec_ct * kBytesPerVec]);
}
}
if (!tidx) {
assert(S_CAST(uintptr_t, cur_alloc - g_bigstack_end) == thread_xalloc_vec_ct * kBytesPerVec);
}
}
SetThreadFuncAndData(SampleCountsThread, &ctx, &tg);
logputs("Calculating sample counts... ");
fputs("0%", stdout);
fflush(stdout);
uint32_t pct = 0;
uint32_t parity = 0;
uint32_t read_block_idx = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
for (uint32_t variant_idx = 0; ; ) {
const uint32_t cur_block_size = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
if (unlikely(reterr)) {
goto SampleCounts_ret_PGR_FAIL;
}
if (variant_idx) {
JoinThreads(&tg);
reterr = S_CAST(PglErr, ctx.err_info);
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, ctx.err_info >> 32);
goto SampleCounts_ret_1;
}
}
if (!IsLastBlock(&tg)) {
ctx.cur_block_size = cur_block_size;
ComputeUidxStartPartition(variant_include, cur_block_size, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
if (variant_idx + cur_block_size == variant_ct) {
DeclareLastThreadBlock(&tg);
}
if (unlikely(SpawnThreads(&tg))) {
goto SampleCounts_ret_THREAD_CREATE_FAIL;
}
}
parity = 1 - parity;
if (variant_idx == variant_ct) {
break;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
++read_block_idx;
variant_idx += cur_block_size;
// crucially, this is independent of the PgenReader block_base
// pointers
pgfip->block_base = main_loadbufs[parity];
}
const uintptr_t acc32_voffset = acc2_vec_ct * 7;
const uintptr_t acc32_vec_ct = acc2_vec_ct * 16;
for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
// any reasonable compiler should vectorize the inner loops
// could also multithread this (unscramble first, then split by sample
// ranges), but computation time here should be negligible
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) {
VecW* dst_acc2_0 = ctx.thread_dense_counts[0][dense_vtype];
if (dst_acc2_0) {
const VecW* src_acc2_0 = ctx.thread_dense_counts[tidx][dense_vtype];
const VecU32* src_acc32_0 = R_CAST(const VecU32*, &(src_acc2_0[acc32_voffset]));
VecU32* dst_acc32_0 = R_CAST(VecU32*, &(dst_acc2_0[acc32_voffset]));
U32VecAdd(src_acc32_0, acc32_vec_ct, dst_acc32_0);
const VecU32* src_acc32_2 = &(src_acc32_0[acc2_vec_ct * 23]);
VecU32* dst_acc32_2 = &(dst_acc32_0[acc2_vec_ct * 23]);
U32VecAdd(src_acc32_2, acc32_vec_ct, dst_acc32_2);
if (dense_vtype < 2 * kSubstCodeCt) {
const VecU32* src_acc32_1 = &(src_acc32_2[acc2_vec_ct * 23]);
VecU32* dst_acc32_1 = &(dst_acc32_2[acc2_vec_ct * 23]);
U32VecAdd(src_acc32_1, acc32_vec_ct, dst_acc32_1);
}
}
}
for (uint32_t sparse_vtype = 0; sparse_vtype != 8 * kSubstCodeCt; ++sparse_vtype) {
uint32_t* dst = ctx.thread_sparse_counts[0][sparse_vtype];
if (dst) {
const uint32_t* src = ctx.thread_sparse_counts[tidx][sparse_vtype];
U32CastVecAdd(src, sample_ct_i32v * 3, dst);
}
}
{
const uint32_t* src = ctx.thread_sparse_common0_cts[tidx];
uint32_t* dst = ctx.thread_sparse_common0_cts[0];
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) {
dst[dense_vtype] += src[dense_vtype];
}
}
if (ctx.thread_diploid_singleton_cts) {
const uint32_t* src = ctx.thread_diploid_singleton_cts[tidx];
uint32_t* dst = ctx.thread_diploid_singleton_cts[0];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
if (ctx.thread_singleton_cts) {
const uint32_t* src = ctx.thread_singleton_cts[tidx];
uint32_t* dst = ctx.thread_singleton_cts[0];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
if (mhc_needed) {
{
uint32_t* dst = ctx.thread_het2alt_cts[0];
const uint32_t* src = ctx.thread_het2alt_cts[tidx];
U32CastVecAdd(src, sample_ct_i32v * 2 * kSubstCodeCt, dst);
}
int32_t* dst = ctx.thread_het_rarealt_cts[0];
const int32_t* src = ctx.thread_het_rarealt_cts[tidx];
I32CastVecAdd(src, sample_ct_i32v * kSubstCodeCt, dst);
dst = ctx.thread_hom_rarealt_cts[0];
src = ctx.thread_hom_rarealt_cts[tidx];
I32CastVecAdd(src, sample_ct_i32v * kSubstCodeCt, dst);
if (ctx.thread_hap_rarealt_cts) {
dst = ctx.thread_hap_rarealt_cts[0];
src = ctx.thread_hap_rarealt_cts[tidx];
I32CastVecAdd(src, sample_ct_i32v * kSubstCodeCt, dst);
}
}
}
BigstackDoubleReset(bigstack_mark2, bigstack_end_mark2);
// Now we're ready to derive our final values from the raw count-matrices.
// 1. Unscramble the final dense raw counts.
uint32_t* unscramble_buf;
if (unlikely(bigstack_alloc_u32(acc32_vec_ct * kInt32PerVec, &unscramble_buf))) {
goto SampleCounts_ret_NOMEM;
}
uint32_t* male_u32_mask = nullptr;
uint32_t* haploid_counts[kSubstCodeCt][2];
uint32_t* y_nonmale_counts[2];
uint32_t* diploid_counts[kSubstCodeCt][3];
{
uint32_t* unscrambled_dense_counts[4 * kSubstCodeCt][3];
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) {
const uint32_t vtype_stop = kSubstCodeCt * (cur_chr_type + 1);
if (!((chr_types >> cur_chr_type) & 1)) {
for (uint32_t vtype = kSubstCodeCt * cur_chr_type; vtype != vtype_stop; ++vtype) {
unscrambled_dense_counts[vtype][0] = nullptr;
unscrambled_dense_counts[vtype][1] = nullptr;
unscrambled_dense_counts[vtype][2] = nullptr;
}
continue;
}
for (uint32_t vtype = kSubstCodeCt * cur_chr_type; vtype != vtype_stop; ++vtype) {
VecW* dst_acc2_0 = ctx.thread_dense_counts[0][vtype];
uint32_t* dst_0 = R_CAST(uint32_t*, &(dst_acc2_0[acc32_voffset]));
Unscramble2(sample_ct, dst_0, unscramble_buf);
unscrambled_dense_counts[vtype][0] = dst_0;
uint32_t* dst_2 = &(dst_0[acc2_vec_ct * 23 * kInt32PerVec]);
Unscramble2(sample_ct, dst_2, unscramble_buf);
unscrambled_dense_counts[vtype][2] = dst_2;
if (cur_chr_type < 2) {
uint32_t* dst_1 = &(dst_2[acc2_vec_ct * 23 * kInt32PerVec]);
Unscramble2(sample_ct, dst_1, unscramble_buf);
unscrambled_dense_counts[vtype][1] = dst_1;
} else {
unscrambled_dense_counts[vtype][1] = nullptr;
}
}
}
BigstackReset(bigstack_mark2);
// 2. Patch in the sparse counts.
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) {
if (!((chr_types >> cur_chr_type) & 1)) {
continue;
}
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
const uint32_t dense_vtype = kSubstCodeCt * cur_chr_type + subst_code;
uint32_t* dense0 = unscrambled_dense_counts[dense_vtype][0];
uint32_t* dense1 = unscrambled_dense_counts[dense_vtype][1];
uint32_t* dense2 = unscrambled_dense_counts[dense_vtype][2];
const uint32_t base0 = ctx.thread_sparse_common0_cts[0][dense_vtype];
uint32_t sparse_vtype = dense_vtype + kSubstCodeCt * cur_chr_type;
// 0->1
const uint32_t* src = ctx.thread_sparse_counts[0][sparse_vtype];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
dense0[sample_idx] += base0 - src[sample_idx];
}
if (dense1) {
U32CastVecAdd(src, sample_ct_i32v, dense1);
}
// 0->2
src = &(src[sample_ct_i32av]);
U32CastVecSub(src, sample_ct_i32v, dense0);
U32CastVecAdd(src, sample_ct_i32v, dense2);
// 0->3
src = &(src[sample_ct_i32av]);
U32CastVecSub(src, sample_ct_i32v, dense0);
sparse_vtype += kSubstCodeCt;
src = ctx.thread_sparse_counts[0][sparse_vtype];
// 3->2
U32CastVecAdd(src, sample_ct_i32v, dense2);
// 3->1
src = &(src[sample_ct_i32av]);
if (dense1) {
U32CastVecAdd(src, sample_ct_i32v, dense1);
}
// 3->0
src = &(src[sample_ct_i32av]);
U32CastVecAdd(src, sample_ct_i32v, dense0);
}
}
// 3. Allocate the reported-counts arrays, and fill them in a sensible
// order.
// We start with
// haploid_counts := chrX/chrY male + generic-haploid
// y_nonmale_counts := chrY nonmale 0+2
// diploid_counts := autosomal-diploid + chrX nonmale
// It's safe to move and alter the unscrambled_dense_counts arrays in the
// process, since we only refer to haploid_counts/y_nonmale_counts/
// diploid_counts afterward, but we have to be careful about timing when
// we do that.
for (uint32_t alt_ct = 0; alt_ct != 2; ++alt_ct) {
y_nonmale_counts[alt_ct] = nullptr;
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
haploid_counts[subst_code][alt_ct] = nullptr;
}
}
if (chr_types & 14) {
if (chr_types & 6) {
// possible todo: not important here, but should be interesting to
// benchmark vector-based ways of doing this (including a simple
// 16- or 256-element lookup table)
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &male_u32_mask))) {
goto SampleCounts_ret_NOMEM;
}
const uintptr_t* sex_male_collapsed = ctx.sex_male_collapsed;
uintptr_t sample_idx_base = 0;
uintptr_t cur_bits = sex_male_collapsed[0];
for (uint32_t male_idx = 0; male_idx != male_ct; ++male_idx) {
const uint32_t sample_idx = BitIter1(sex_male_collapsed, &sample_idx_base, &cur_bits);
male_u32_mask[sample_idx] = UINT32_MAX;
}
}
uint32_t* female_y_dst = nullptr;
for (uint32_t alt_ct = 0; alt_ct != 2; ++alt_ct) {
if (y_nonmale_needed) {
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &female_y_dst))) {
goto SampleCounts_ret_NOMEM;
}
y_nonmale_counts[alt_ct] = female_y_dst;
}
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
uint32_t* dst;
if (chr_types & 8) {
dst = unscrambled_dense_counts[3 * kSubstCodeCt + subst_code][alt_ct * 2];
} else {
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
}
haploid_counts[subst_code][alt_ct] = dst;
if (chr_types & 6) {
if (chr_types & 4) {
const uint32_t* src2 = unscrambled_dense_counts[2 * kSubstCodeCt + subst_code][alt_ct * 2];
if (female_y_dst) {
U32CastVecInvmaskedAdd(male_u32_mask, src2, sample_ct_i32v, female_y_dst);
}
if (chr_types & 2) {
const uint32_t* src1 = unscrambled_dense_counts[kSubstCodeCt + subst_code][alt_ct * 2];
U32CastVecMaskedAdd2(male_u32_mask, src1, src2, sample_ct_i32v, dst);
} else {
U32CastVecMaskedAdd(male_u32_mask, src2, sample_ct_i32v, dst);
}
} else {
const uint32_t* src1 = unscrambled_dense_counts[kSubstCodeCt + subst_code][alt_ct * 2];
U32CastVecMaskedAdd(male_u32_mask, src1, sample_ct_i32v, dst);
}
}
}
}
}
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
for (uint32_t alt_ct = 0; alt_ct != 3; ++alt_ct) {
uint32_t* dst;
if (chr_types & 1) {
dst = unscrambled_dense_counts[subst_code][alt_ct];
} else {
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
}
diploid_counts[subst_code][alt_ct] = dst;
if (chr_types & 2) {
// chrX nonmales
const uint32_t* src = unscrambled_dense_counts[subst_code + kSubstCodeCt][alt_ct];
U32CastVecInvmaskedAdd(male_u32_mask, src, sample_ct_i32v, dst);
}
}
}
if (mhc_needed) {
// het_rarealt: modifies diploid alt_ct=1 subst_code distribution
// hom_rarealt: modifies diploid alt_ct=2 subst_code distribution
// hap_rarealt: modifies haploid alt_ct=1 subst_code distribution
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
// let's make sure overflow behavior is defined, so if there's a bug
// earlier on it's less likely to be a nightmare
const uint32_t* src = R_CAST(uint32_t*, &(ctx.thread_het_rarealt_cts[0][subst_code * sample_ct_i32av]));
uint32_t* dst = diploid_counts[subst_code][1];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
const uint32_t* src = R_CAST(uint32_t*, &(ctx.thread_hom_rarealt_cts[0][subst_code * sample_ct_i32av]));
uint32_t* dst = diploid_counts[subst_code][2];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
if (ctx.thread_hap_rarealt_cts) {
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) {
const uint32_t* src = R_CAST(uint32_t*, &(ctx.thread_hap_rarealt_cts[0][subst_code * sample_ct_i32av]));
uint32_t* dst = haploid_counts[subst_code][1];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
}
// het2alt: handled separately
}
}
// Main dependency graph:
// het2alt ALT1= pieces
// |
// v
// het2alt reported sum + refalt -> het
// | |
// | ---> missing
// v |
// homalt + homref -> hom
uint32_t* het2alt_reported_vals = nullptr;
if (mhc_needed) {
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &het2alt_reported_vals))) {
goto SampleCounts_ret_NOMEM;
}
const uint32_t* src0 = ctx.thread_het2alt_cts[0];
const uint32_t* src1 = &(src0[sample_ct_i32av]);
const uint32_t* src2 = &(src1[sample_ct_i32av]);
const uint32_t* src3 = &(src2[sample_ct_i32av]);
const uint32_t* src4 = &(src3[sample_ct_i32av]);
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, het2alt_reported_vals);
}
uint32_t* refalt_vals;
uint32_t* homalt_vals;
uint32_t* homref_vals;
uint32_t* hom_vals;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &refalt_vals) ||
bigstack_alloc_u32(sample_ct_i32av, &homalt_vals) ||
bigstack_alloc_u32(sample_ct_i32av, &homref_vals) ||
bigstack_alloc_u32(sample_ct_i32av, &hom_vals))) {
goto SampleCounts_ret_NOMEM;
}
{
const uint32_t* src0 = diploid_counts[0][1];
const uint32_t* src1 = diploid_counts[1][1];
const uint32_t* src2 = diploid_counts[2][1];
const uint32_t* src3 = diploid_counts[3][1];
const uint32_t* src4 = diploid_counts[4][1];
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, refalt_vals);
}
uint32_t* het_vals;
if (!mhc_needed) {
het_vals = refalt_vals;
} else {
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &het_vals))) {
goto SampleCounts_ret_NOMEM;
}
U32CastVecAssignAdd2(het2alt_reported_vals, refalt_vals, sample_ct_i32v, het_vals);
}
{
const uint32_t* src0 = diploid_counts[0][2];
const uint32_t* src1 = diploid_counts[1][2];
const uint32_t* src2 = diploid_counts[2][2];
const uint32_t* src3 = diploid_counts[3][2];
const uint32_t* src4 = diploid_counts[4][2];
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, homalt_vals);
if (het2alt_reported_vals) {
U32CastVecSub(het2alt_reported_vals, sample_ct_i32v, homalt_vals);
}
src0 = diploid_counts[0][0];
src1 = diploid_counts[1][0];
src2 = diploid_counts[2][0];
src3 = diploid_counts[3][0];
src4 = diploid_counts[4][0];
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, homref_vals);
U32CastVecAssignAdd2(homref_vals, homalt_vals, sample_ct_i32v, hom_vals);
}
uint32_t* hapref_vals;
uint32_t* hapalt_vals;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &hapref_vals) ||
bigstack_alloc_u32(sample_ct_i32av, &hapalt_vals))) {
goto SampleCounts_ret_NOMEM;
}
{
if (chr_types & 14) {
const uint32_t* src0 = haploid_counts[0][0];
const uint32_t* src1 = haploid_counts[1][0];
const uint32_t* src2 = haploid_counts[2][0];
const uint32_t* src3 = haploid_counts[3][0];
const uint32_t* src4 = haploid_counts[4][0];
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, hapref_vals);
src0 = haploid_counts[0][1];
src1 = haploid_counts[1][1];
src2 = haploid_counts[2][1];
src3 = haploid_counts[3][1];
src4 = haploid_counts[4][1];
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, hapalt_vals);
} else {
ZeroU32Arr(sample_ct, hapref_vals);
ZeroU32Arr(sample_ct, hapalt_vals);
}
}
uint32_t* final_counts[kSampleCountTypeCt];
ZeroPtrArr(kSampleCountTypeCt, final_counts);
if (flags & kfSampleCountsColHom) {
final_counts[kSampleCountHom] = hom_vals;
}
if (flags & kfSampleCountsColHomref) {
final_counts[kSampleCountHomref] = homref_vals;
}
if (flags & kfSampleCountsColHomalt) {
final_counts[kSampleCountHomalt] = homalt_vals;
}
if (flags & kfSampleCountsColHomaltSnp) {
uint32_t* dst;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
final_counts[kSampleCountHomaltSnp] = dst;
const uint32_t* src1 = diploid_counts[kSubstCodeTs][2];
const uint32_t* src2 = diploid_counts[kSubstCodeTv][2];
const uint32_t* src3 = diploid_counts[kSubstCodeWeirdSnp][2];
U32CastVecAssignAdd3(src1, src2, src3, sample_ct_i32v, dst);
if (mhc_needed) {
const uint32_t* src_base = ctx.thread_het2alt_cts[0];
src1 = &(src_base[sample_ct_i32av * kSubstCodeTs]);
src2 = &(src_base[sample_ct_i32av * kSubstCodeTv]);
src3 = &(src_base[sample_ct_i32av * kSubstCodeWeirdSnp]);
U32CastVecSub3(src1, src2, src3, sample_ct_i32v, dst);
}
}
if (flags & kfSampleCountsColHet) {
final_counts[kSampleCountHet] = het_vals;
}
if (flags & kfSampleCountsColRefalt) {
final_counts[kSampleCountRefalt] = refalt_vals;
}
if (flags & kfSampleCountsColHet2alt) {
if (het2alt_reported_vals) {
final_counts[kSampleCountHet2alt] = het2alt_reported_vals;
} else {
if (unlikely(bigstack_calloc_u32(sample_ct_i32av, &(final_counts[kSampleCountHet2alt])))) {
goto SampleCounts_ret_NOMEM;
}
}
}
if (flags & kfSampleCountsColHetSnp) {
uint32_t* dst;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
final_counts[kSampleCountHetSnp] = dst;
const uint32_t* src1 = diploid_counts[kSubstCodeTs][1];
const uint32_t* src2 = diploid_counts[kSubstCodeTv][1];
const uint32_t* src3 = diploid_counts[kSubstCodeWeirdSnp][1];
U32CastVecAssignAdd3(src1, src2, src3, sample_ct_i32v, dst);
if (mhc_needed) {
const uint32_t* src_base = &(ctx.thread_het2alt_cts[0][kSubstCodeCt * sample_ct_i32av]);
src1 = &(src_base[kSubstCodeTs * sample_ct_i32av]);
src2 = &(src_base[kSubstCodeTv * sample_ct_i32av]);
src3 = &(src_base[kSubstCodeWeirdSnp * sample_ct_i32av]);
U32CastVecAdd3(src1, src2, src3, sample_ct_i32v, dst);
}
}
if (flags & kfSampleCountsColDiploidTs) {
final_counts[kSampleCountDiploidTs] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTs]), nullptr, sample_ct_i32v, kSubstCodeTs);
if (unlikely(!final_counts[kSampleCountDiploidTs])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColTs) {
final_counts[kSampleCountTs] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTs]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeTs]), sample_ct_i32v, kSubstCodeTs);
if (unlikely(!final_counts[kSampleCountTs])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColDiploidTv) {
final_counts[kSampleCountDiploidTv] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTv]), nullptr, sample_ct_i32v, kSubstCodeTv);
if (unlikely(!final_counts[kSampleCountDiploidTv])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColTv) {
final_counts[kSampleCountTv] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTv]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeTv]), sample_ct_i32v, kSubstCodeTv);
if (unlikely(!final_counts[kSampleCountTv])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColDiploidNonsnpsymb) {
final_counts[kSampleCountDiploidNonsnpsymb] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeNonsnpsymb]), nullptr, sample_ct_i32v, kSubstCodeNonsnpsymb);
if (unlikely(!final_counts[kSampleCountDiploidNonsnpsymb])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColNonsnpsymb) {
final_counts[kSampleCountNonsnpsymb] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeNonsnpsymb]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeNonsnpsymb]), sample_ct_i32v, kSubstCodeNonsnpsymb);
if (unlikely(!final_counts[kSampleCountNonsnpsymb])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColSymbolic) {
final_counts[kSampleCountSymbolic] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeSymbolic]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeSymbolic]), sample_ct_i32v, kSubstCodeSymbolic);
if (unlikely(!final_counts[kSampleCountSymbolic])) {
goto SampleCounts_ret_NOMEM;
}
}
if (flags & kfSampleCountsColNonsnp) {
final_counts[kSampleCountNonsnp] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeNonsnpsymb]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeNonsnpsymb]), sample_ct_i32v, kSubstCodeNonsnpsymb);
if (unlikely(!final_counts[kSampleCountNonsnp])) {
goto SampleCounts_ret_NOMEM;
}
IncrSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeSymbolic]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeSymbolic]), sample_ct_i32v, kSubstCodeSymbolic, final_counts[kSampleCountNonsnp]);
}
if (flags & kfSampleCountsColDiploidSingle) {
final_counts[kSampleCountDiploidSingle] = ctx.thread_diploid_singleton_cts[0];
}
if (flags & kfSampleCountsColSingle) {
final_counts[kSampleCountSingle] = ctx.thread_singleton_cts[0];
}
if (flags & kfSampleCountsColHaprefWithFemaleY) {
uint32_t* dst;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
final_counts[kSampleCountHaprefWithFemaleY] = dst;
memcpy(dst, hapref_vals, sample_ct * sizeof(int32_t));
if (chr_types & 4) {
const uint32_t* src = y_nonmale_counts[0];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
}
if (flags & kfSampleCountsColHapref) {
final_counts[kSampleCountHapref] = hapref_vals;
}
if (flags & kfSampleCountsColHapaltWithFemaleY) {
uint32_t* dst;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
final_counts[kSampleCountHapaltWithFemaleY] = dst;
memcpy(dst, hapalt_vals, sample_ct * sizeof(int32_t));
if (chr_types & 4) {
const uint32_t* src = y_nonmale_counts[1];
U32CastVecAdd(src, sample_ct_i32v, dst);
}
}
if (flags & kfSampleCountsColHapalt) {
final_counts[kSampleCountHapalt] = hapalt_vals;
}
if (flags & kfSampleCountsColMissingWithFemaleY) {
uint32_t* dst;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
final_counts[kSampleCountMissingWithFemaleY] = dst;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
// todo: verify this vectorizes well
dst[sample_idx] = variant_ct - hom_vals[sample_idx] - het_vals[sample_idx] - hapref_vals[sample_idx] - hapalt_vals[sample_idx];
}
if (chr_types & 4) {
const uint32_t* src0 = y_nonmale_counts[0];
const uint32_t* src1 = y_nonmale_counts[1];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
dst[sample_idx] -= src0[sample_idx] + src1[sample_idx];
}
}
}
if (flags & kfSampleCountsColMissing) {
uint32_t* dst;
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) {
goto SampleCounts_ret_NOMEM;
}
final_counts[kSampleCountMissing] = dst;
const uint32_t nony_variant_ct = variant_ct - y_variant_ct;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
dst[sample_idx] = nony_variant_ct - hom_vals[sample_idx] - het_vals[sample_idx] - hapref_vals[sample_idx] - hapalt_vals[sample_idx];
}
if (chr_types & 4) {
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
dst[sample_idx] += male_u32_mask[sample_idx] & y_variant_ct;
}
}
}
// Ready to write to disk.
if (pct > 10) {
putc_unlocked('\b', stdout);
}
fputs("\b\b", stdout);
logputs("done.\n");
BigstackEndReset(bigstack_end_mark2);
const uintptr_t overflow_buf_size = RoundUpPow2(kCompressStreamBlock + 3 * kMaxIdSlen + 512, kCacheline);
const uint32_t output_zst = flags & kfSampleCountsZs;
uintptr_t overflow_buf_alloc = overflow_buf_size;
if (output_zst) {
overflow_buf_alloc += CstreamWkspaceReq(overflow_buf_size);
}
char* overflow_buf;
if (unlikely(bigstack_alloc_c(overflow_buf_alloc, &overflow_buf))) {
goto SampleCounts_ret_NOMEM;
}
OutnameZstSet(".scount", output_zst, outname_end);
reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css);
if (unlikely(reterr)) {
goto SampleCounts_ret_1;
}
cswritep = overflow_buf;
*cswritep++ = '#';
const uint32_t col_fid = FidColIsRequired(siip, flags / kfSampleCountsColMaybefid);
if (col_fid) {
cswritep = strcpya_k(cswritep, "FID\t");
}
cswritep = strcpya_k(cswritep, "IID");
const char* sample_ids = siip->sample_ids;
const char* sids = siip->sids;
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
const uintptr_t max_sid_blen = siip->max_sid_blen;
const uint32_t col_sid = SidColIsRequired(sids, flags / kfSampleCountsColMaybesid);
if (col_sid) {
cswritep = strcpya_k(cswritep, "\tSID");
}
const uint32_t col_sex = (flags / kfSampleCountsColSex) & 1;
if (col_sex) {
cswritep = strcpya_k(cswritep, "\tSEX");
}
uint32_t type_bitarr;
memcpy(&type_bitarr, &flags, 4);
type_bitarr = type_bitarr / kfSampleCountsColHom;
{
uint32_t types_left = type_bitarr;
while (types_left) {
*cswritep++ = '\t';
cswritep = strcpya(cswritep, sample_counts_headers[ctzu32(types_left)]);
types_left = types_left & (types_left - 1);
}
}
AppendBinaryEoln(&cswritep);
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
cswritep = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep);
if (col_sex) {
*cswritep++ = '\t';
if (IsSet(sex_nm, sample_uidx)) {
*cswritep++ = '2' - IsSet(sex_male, sample_uidx);
} else {
cswritep = strcpya_k(cswritep, "NA");
}
}
uint32_t types_left = type_bitarr;
while (types_left) {
const uint32_t type_idx = ctzu32(types_left);
*cswritep++ = '\t';
cswritep = u32toa(final_counts[type_idx][sample_idx], cswritep);
types_left = types_left & (types_left - 1);
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto SampleCounts_ret_WRITE_FAIL;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto SampleCounts_ret_WRITE_FAIL;
}
logprintfww("--sample-counts: Results written to %s .\n", outname);
}
while (0) {
SampleCounts_ret_NOMEM:
reterr = kPglRetNomem;
break;
SampleCounts_ret_PGR_FAIL:
PgenErrPrintN(reterr);
break;
SampleCounts_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
SampleCounts_ret_THREAD_CREATE_FAIL:
reterr = kPglRetThreadCreateFail;
break;
}
SampleCounts_ret_1:
CleanupThreads(&tg);
CswriteCloseCond(&css, cswritep);
BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
pgfip->block_base = nullptr;
return reterr;
}
static const Dosage kGenoToDosage[4] = {0, kDosageMid, kDosageMax, kDosageMissing};
typedef struct SdiffCountsStruct {
uint32_t missing_ct; // never includes halfmiss
uint32_t ibsmiss_ct; // can determine ibs2_ct from this
uint32_t ibsx_cts[2];
uint32_t halfmiss_ct;
uint32_t diff_ct; // never includes halfmiss
} SdiffCounts;
// Simplest case. May multithread this, add biallelic hardcall and other
// optimizations, etc. later.
PglErr SdiffCountsOnly(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uint32_t* __restrict id_pairs, const uintptr_t* __restrict pair_sex_male, const uintptr_t* __restrict variant_include, const ChrInfo* cip, const uintptr_t* __restrict allele_idx_offsets, const SdiffInfo* sdip, uint32_t sample_ct, uint32_t variant_ct, uintptr_t id_pair_ct, PgenReader* simple_pgrp, SdiffCounts* sdiff_counts) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
{
const uint32_t dosage_hap_tol = sdip->dosage_hap_tol;
const uint32_t dosage_needed = (PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent) && (dosage_hap_tol != kDosageMissing);
// values unimportant if dosage_hap_tol == kDosageMissing
const uint32_t dosage_dip_tol = dosage_hap_tol / 2;
uint32_t dosage_sex_tols[2]; // for chrX
dosage_sex_tols[0] = dosage_dip_tol;
dosage_sex_tols[1] = dosage_hap_tol;
const uint32_t ibs_needed = ((sdip->flags & kfSdiffCountsIbsNeeded) != kfSdiff0);
PgenVariant pgv;
if (unlikely(BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, dosage_needed? kfPgenGlobalDosagePresent : kfPgenGlobal0, &pgv))) {
goto SdiffCountsOnly_ret_NOMEM;
}
Dosage* dosage_buf = nullptr;
if (dosage_needed) {
// todo: multidosage
if (unlikely(bigstack_alloc_dosage(sample_ct, &dosage_buf))) {
goto SdiffCountsOnly_ret_NOMEM;
}
}
AlleleCode* allele_code_buf = nullptr;
if (allele_idx_offsets != nullptr) {
if (unlikely(bigstack_alloc_ac(2 * sample_ct, &allele_code_buf))) {
goto SdiffCountsOnly_ret_NOMEM;
}
}
pgv.patch_01_ct = 0;
pgv.patch_10_ct = 0;
pgv.dosage_ct = 0;
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
uint32_t is_autosomal_diploid = 0;
uint32_t is_x = 0;
uint32_t is_y = 0;
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
uint32_t allele_ct = 2;
fputs("--sample-diff counts-only: 0%", stdout);
fflush(stdout);
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (variant_uidx >= chr_end);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
is_autosomal_diploid = !IsSet(cip->haploid_mask, chr_idx);
is_x = (chr_idx == x_code);
is_y = (chr_idx == y_code);
}
if (allele_idx_offsets) {
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
}
if (allele_ct == 2) {
if (!dosage_needed) {
reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec);
} else {
reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
}
} else {
if (!dosage_needed) {
reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
} else {
reterr = PgrGetMD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
}
if ((!pgv.patch_01_ct) && (!pgv.patch_10_ct)) {
// todo: also check for multidosage
allele_ct = 2;
}
}
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, variant_uidx);
goto SdiffCountsOnly_ret_1;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
if (allele_ct == 2) {
if (!pgv.dosage_ct) {
if (AllGenoEqual(pgv.genovec, sample_ct)) {
// don't need to do anything!
continue;
}
const uint32_t* id_pair_iter = id_pairs;
if (is_autosomal_diploid) {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 == hc2) {
if (hc1 == 3) {
sdiff_counts[pair_idx].missing_ct += 1;
sdiff_counts[pair_idx].ibsmiss_ct += 1;
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += 1;
continue;
}
cur_counts->diff_ct += 1;
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1;
}
} else if (is_x) {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 == hc2) {
if (hc1 == 3) {
sdiff_counts[pair_idx].missing_ct += 1;
if (!IsSet(pair_sex_male, pair_idx)) {
sdiff_counts[pair_idx].ibsmiss_ct += 1;
}
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
const uint32_t is_male = IsSet(pair_sex_male, pair_idx);
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += !is_male;
continue;
}
cur_counts->diff_ct += 1;
if (!is_male) {
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1;
}
}
} else {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
// don't need pair_sex_nonfemale here since we prohibit
// unknown-sex pairs when chrY is present
if (is_y && (!IsSet(pair_sex_male, pair_idx))) {
continue;
}
const uint32_t sample_idx1 = id_pairs[2 * pair_idx];
const uint32_t sample_idx2 = id_pairs[2 * pair_idx + 1];
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 == hc2) {
if (hc1 == 3) {
sdiff_counts[pair_idx].missing_ct += 1;
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->halfmiss_ct += 1;
continue;
}
cur_counts->diff_ct += 1;
}
}
} else {
// dosages present
const Dosage* dosage_read_iter = pgv.dosage_main;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
if (!IsSet(pgv.dosage_present, sample_idx)) {
dosage_buf[sample_idx] = kGenoToDosage[GetNyparrEntry(pgv.genovec, sample_idx)];
} else {
dosage_buf[sample_idx] = *dosage_read_iter++;
}
}
const uint32_t* id_pair_iter = id_pairs;
if (is_autosomal_diploid) {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const uint32_t dosage1 = dosage_buf[sample_idx1];
const uint32_t dosage2 = dosage_buf[sample_idx2];
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if (dosage1 == kDosageMissing) {
cur_counts->ibsmiss_ct += 1;
if (dosage2 == kDosageMissing) {
cur_counts->missing_ct += 1;
} else {
cur_counts->halfmiss_ct += 1;
}
continue;
}
if (dosage2 == kDosageMissing) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += 1;
continue;
}
if (abs_i32(dosage1 - dosage2) > dosage_dip_tol) {
cur_counts->diff_ct += 1;
}
if (!ibs_needed) {
continue;
}
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 == hc2) {
continue;
}
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->ibsmiss_ct += 1;
}
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1;
}
} else if (is_x) {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const uint32_t dosage1 = dosage_buf[sample_idx1];
const uint32_t dosage2 = dosage_buf[sample_idx2];
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if (dosage1 == kDosageMissing) {
cur_counts->ibsmiss_ct += 1;
if (dosage2 == kDosageMissing) {
cur_counts->missing_ct += 1;
} else {
cur_counts->halfmiss_ct += 1;
}
continue;
}
if (dosage2 == kDosageMissing) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += 1;
continue;
}
const uint32_t is_male = IsSet(pair_sex_male, pair_idx);
if (abs_i32(dosage1 - dosage2) > dosage_sex_tols[is_male]) {
cur_counts->diff_ct += 1;
}
if ((!ibs_needed) || is_male) {
continue;
}
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 == hc2) {
continue;
}
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->ibsmiss_ct += 1;
}
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1;
}
} else {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
if (is_y && (!IsSet(pair_sex_male, pair_idx))) {
continue;
}
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const uint32_t dosage1 = dosage_buf[sample_idx1];
const uint32_t dosage2 = dosage_buf[sample_idx2];
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if (dosage1 == kDosageMissing) {
cur_counts->ibsmiss_ct += 1;
if (dosage2 == kDosageMissing) {
cur_counts->missing_ct += 1;
} else {
cur_counts->halfmiss_ct += 1;
}
continue;
}
if (dosage2 == kDosageMissing) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += 1;
continue;
}
if (abs_i32(dosage1 - dosage2) > dosage_hap_tol) {
cur_counts->diff_ct += 1;
}
}
}
}
} else {
// multiallelic
if (!pgv.dosage_ct) {
PglMultiallelicSparseToDenseMiss(&pgv, sample_ct, allele_code_buf);
const uint32_t* id_pair_iter = id_pairs;
if (is_autosomal_diploid) {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1];
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1];
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2];
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1];
if ((ac11 == ac21) && (ac12 == ac22)) {
if (ac11 == kMissingAlleleCode) {
sdiff_counts[pair_idx].missing_ct += 1;
sdiff_counts[pair_idx].ibsmiss_ct += 1;
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += 1;
continue;
}
cur_counts->diff_ct += 1;
if (ibs_needed) {
cur_counts->ibsx_cts[(ac11 == ac21) || (ac11 == ac22) || (ac12 == ac21) || (ac12 == ac22)] += 1;
}
}
} else if (is_x) {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1];
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1];
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2];
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1];
if ((ac11 == ac21) && (ac12 == ac22)) {
if (ac11 == kMissingAlleleCode) {
sdiff_counts[pair_idx].missing_ct += 1;
if (!IsSet(pair_sex_male, pair_idx)) {
sdiff_counts[pair_idx].ibsmiss_ct += 1;
}
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
const uint32_t is_male = IsSet(pair_sex_male, pair_idx);
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += !is_male;
continue;
}
cur_counts->diff_ct += 1;
if (ibs_needed && (!is_male)) {
cur_counts->ibsx_cts[(ac11 == ac21) || (ac11 == ac22) || (ac12 == ac21) || (ac12 == ac22)] += 1;
}
}
} else {
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
if (is_y && (!IsSet(pair_sex_male, pair_idx))) {
continue;
}
const uint32_t sample_idx1 = id_pairs[2 * pair_idx];
const uint32_t sample_idx2 = id_pairs[2 * pair_idx + 1];
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1];
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1];
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2];
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1];
if ((ac11 == ac21) && (ac12 == ac22)) {
if (ac11 == kMissingAlleleCode) {
sdiff_counts[pair_idx].missing_ct += 1;
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) {
cur_counts->halfmiss_ct += 1;
}
cur_counts->diff_ct += 1;
}
}
} else {
// multiallelic-dosage; todo
exit(S_CAST(int32_t, kPglRetInternalError));
}
}
}
if (pct > 10) {
putc_unlocked('\b', stdout);
}
fputs("\b\b", stdout);
logputs("done.\n");
}
while (0) {
SdiffCountsOnly_ret_NOMEM:
reterr = kPglRetNomem;
break;
PgenErrPrintN(reterr);
break;
}
SdiffCountsOnly_ret_1:
BigstackReset(bigstack_mark);
return reterr;
}
void AppendSdiffHeaderLine(SdiffFlags flags, uint32_t col_provref, uint32_t col_fid, uint32_t col_sid, uint32_t dosage_reported, char** cswritepp) {
char* cswritep = *cswritepp;
*cswritep++ = '#';
if (flags & kfSdiffColChrom) {
cswritep = strcpya_k(cswritep, "CHROM\t");
}
if (flags & kfSdiffColPos) {
cswritep = strcpya_k(cswritep, "POS\t");
}
cswritep = strcpya_k(cswritep, "ID");
if (flags & kfSdiffColRef) {
cswritep = strcpya_k(cswritep, "\tREF");
}
if (flags & kfSdiffColAlt) {
cswritep = strcpya_k(cswritep, "\tALT");
}
if (col_provref) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
if (flags & kfSdiffColId) {
if (col_fid) {
cswritep = strcpya_k(cswritep, "\tFID1");
}
cswritep = strcpya_k(cswritep, "\tIID1");
if (col_sid) {
cswritep = strcpya_k(cswritep, "\tSID1");
}
if (col_fid) {
cswritep = strcpya_k(cswritep, "\tFID2");
}
cswritep = strcpya_k(cswritep, "\tIID2");
if (col_sid) {
cswritep = strcpya_k(cswritep, "\tSID2");
}
}
if (flags & kfSdiffColGeno) {
if (!dosage_reported) {
cswritep = strcpya_k(cswritep, "\tGT1\tGT2");
} else {
cswritep = strcpya_k(cswritep, "\tDS1\tDS2");
}
}
*cswritepp = cswritep;
AppendBinaryEoln(cswritepp);
}
typedef struct SdiffWriteContextStruct {
char* collapsed_sample_fmtids;
char* chr_buf;
const uint32_t* variant_bps;
const char* const* variant_ids;
SdiffFlags flags;
uintptr_t max_sample_fmtid_blen;
uint32_t chr_buf_blen;
} SdiffWriteContext;
BoolErr AppendSdiffPregenoFields(const SdiffWriteContext* swcp, const char* const* cur_alleles, uint32_t sample_idx1, uint32_t sample_idx2, uint32_t variant_uidx, uint32_t allele_ct, uint32_t col_provref, uint32_t provref, CompressStreamState* cssp, char** cswritepp) {
char* cswritep = *cswritepp;
if (swcp->chr_buf) {
cswritep = memcpya(cswritep, swcp->chr_buf, swcp->chr_buf_blen);
}
if (swcp->variant_bps) {
cswritep = u32toa_x(swcp->variant_bps[variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, swcp->variant_ids[variant_uidx]);
if (swcp->flags & kfSdiffColRef) {
*cswritep++ = '\t';
const char* cur_allele = cur_alleles[0];
const uint32_t allele_slen = strlen(cur_allele);
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) {
// might not need this assignment, but play it safe for now
*cswritepp = cswritep;
return 1;
}
}
if (swcp->flags & kfSdiffColAlt) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
const char* cur_allele = cur_alleles[allele_idx];
const uint32_t allele_slen = strlen(cur_allele);
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) {
*cswritepp = cswritep;
return 1;
}
*cswritep++ = ',';
}
--cswritep;
}
if (col_provref) {
*cswritep++ = '\t';
*cswritep++ = provref? 'Y' : 'N';
}
if (swcp->collapsed_sample_fmtids) {
*cswritep++ = '\t';
cswritep = strcpyax(cswritep, &(swcp->collapsed_sample_fmtids[sample_idx1 * swcp->max_sample_fmtid_blen]), '\t');
cswritep = strcpya(cswritep, &(swcp->collapsed_sample_fmtids[sample_idx2 * swcp->max_sample_fmtid_blen]));
}
*cswritepp = cswritep;
return 0;
}
PglErr SdiffMainBatch(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const SampleIdInfo* siip, const uint32_t* __restrict id_pairs, const uintptr_t* __restrict pair_sex_male, const uintptr_t* __restrict variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* __restrict allele_idx_offsets, const char* const* allele_storage, const SdiffInfo* sdip, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uintptr_t id_pair_ct, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end, SdiffCounts* sdiff_counts) {
unsigned char* bigstack_mark = g_bigstack_base;
char** cswritep_arr = nullptr;
CompressStreamState* css_arr = nullptr;
const SdiffFlags flags = sdip->flags;
const uint32_t is_pairwise = (flags / kfSdiffPairwise) & 1;
const uintptr_t file_ct = is_pairwise? id_pair_ct : 1;
PglErr reterr = kPglRetSuccess;
{
const uint32_t col_fid = FidColIsRequired(siip, flags / kfSdiffColMaybefid);
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfSdiffColMaybesid);
SdiffWriteContext swc;
if (unlikely(CollapsedSampleFmtidInitAlloc(sample_include, siip, sample_ct, col_fid, col_sid, &swc.collapsed_sample_fmtids, &swc.max_sample_fmtid_blen))) {
goto SdiffMainBatch_ret_NOMEM;
}
swc.chr_buf = nullptr;
if (flags & kfSdiffColChrom) {
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
if (unlikely(bigstack_alloc_c(max_chr_blen, &swc.chr_buf))) {
goto SdiffMainBatch_ret_NOMEM;
}
}
if (!(flags & kfSdiffColPos)) {
swc.variant_bps = nullptr;
} else {
swc.variant_bps = variant_bps;
}
swc.variant_ids = variant_ids;
if (unlikely(bigstack_calloc_cp(file_ct, &cswritep_arr) ||
BIGSTACK_ALLOC_X(CompressStreamState, file_ct, &css_arr))) {
goto SdiffMainBatch_ret_NOMEM;
}
swc.flags = flags;
swc.chr_buf_blen = 0;
for (uintptr_t fidx = 0; fidx != id_pair_ct; ++fidx) {
PreinitCstream(&(css_arr[fidx]));
}
const uintptr_t* nonref_flags = PgrGetNonrefFlags(simple_pgrp);
const uint32_t all_nonref = (PgrGetGflags(simple_pgrp) & kfPgenGlobalAllNonref) && (!nonref_flags);
const uint32_t col_provref = (flags & kfSdiffColRef) && ProvrefCol(variant_include, nonref_flags, flags / kfSdiffColMaybeprovref, raw_variant_ct, all_nonref);
const uint32_t output_zst = (flags / kfSdiffZs) & 1;
// ".sdiff" + terminating null = 7 bytes
const uintptr_t fname_extrachar_limit = kPglFnamesize - 7 - (output_zst * 4) - S_CAST(uintptr_t, outname_end - outname);
const char fname_id_delim = sdip->fname_id_delim;
const uint32_t dosage_hap_tol = sdip->dosage_hap_tol;
const uint32_t dosage_reported = (dosage_hap_tol != kDosageMissing);
const uint32_t dosage_needed = (PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent) && dosage_reported;
if (is_pairwise) {
const uint32_t* id_pair_iter = id_pairs;
const uint32_t stream_thread_ct = (max_thread_ct > (2 * id_pair_ct))? ((max_thread_ct - 1) / id_pair_ct) : 1;
*outname_end = '.';
for (uintptr_t fidx = 0; fidx != id_pair_ct; ++fidx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
const char* sample_fmtid1 = &(swc.collapsed_sample_fmtids[sample_idx1 * swc.max_sample_fmtid_blen]);
const char* sample_fmtid2 = &(swc.collapsed_sample_fmtids[sample_idx2 * swc.max_sample_fmtid_blen]);
const uint32_t slen1 = strlen(sample_fmtid1);
const uint32_t slen2 = strlen(sample_fmtid2);
if (unlikely(slen1 + slen2 + 2 > fname_extrachar_limit)) {
logputs("\n");
logerrputs("Error: Sample ID and/or --out argument too long for --sample-diff pairwise\nmode.\n");
goto SdiffMainBatch_ret_INCONSISTENT_INPUT;
}
char* fname_iter = &(outname_end[1]);
// note that this copies tab(s); replace them with fname_id_delim
fname_iter = memcpya(fname_iter, sample_fmtid1, slen1);
char* tab_iter = &(outname_end[2]);
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter));
if (tab_iter) {
*tab_iter++ = fname_id_delim;
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter));
if (tab_iter) {
*tab_iter = fname_id_delim;
}
}
*fname_iter++ = '.';
tab_iter = &(fname_iter[1]);
fname_iter = memcpya(fname_iter, sample_fmtid2, slen2);
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter));
if (tab_iter) {
*tab_iter++ = fname_id_delim;
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter));
if (tab_iter) {
*tab_iter = fname_id_delim;
}
}
fname_iter = strcpya_k(fname_iter, ".sdiff");
if (output_zst) {
fname_iter = strcpya_k(fname_iter, ".zst");
}
*fname_iter = '\0';
reterr = InitCstreamAlloc(outname, 0, output_zst, stream_thread_ct, kCompressStreamBlock + kMaxMediumLine, &(css_arr[fidx]), &(cswritep_arr[fidx]));
if (unlikely(reterr)) {
goto SdiffMainBatch_ret_1;
}
AppendSdiffHeaderLine(flags, col_provref, col_fid, col_sid, dosage_reported, &(cswritep_arr[fidx]));
}
} else {
char* fname_iter = outname_end;
const uint32_t stream_thread_ct = (max_thread_ct > 1)? (max_thread_ct - 1) : 1;
if (flags & kfSdiffOneBase) {
const uint32_t base_sample_idx = id_pairs[0];
const char* sample_fmtid = &(swc.collapsed_sample_fmtids[base_sample_idx * swc.max_sample_fmtid_blen]);
const uint32_t base_slen = strlen(sample_fmtid);
if (unlikely(base_slen >= fname_extrachar_limit)) {
logputs("\n");
logerrputs("Error: Sample ID and/or --out argument too long for --sample-diff base= mode.\n");
goto SdiffMainBatch_ret_INCONSISTENT_INPUT;
}
*fname_iter++ = '.';
char* tab_iter = &(fname_iter[1]);
fname_iter = memcpya(fname_iter, sample_fmtid, base_slen);
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter));
if (tab_iter) {
*tab_iter++ = fname_id_delim;
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter));
if (tab_iter) {
*tab_iter = fname_id_delim;
}
}
}
fname_iter = strcpya_k(fname_iter, ".sdiff");
if (output_zst) {
fname_iter = strcpya_k(fname_iter, ".zst");
}
*fname_iter = '\0';
reterr = InitCstreamAlloc(outname, 0, output_zst, stream_thread_ct, kCompressStreamBlock + kMaxMediumLine, &(css_arr[0]), &(cswritep_arr[0]));
if (unlikely(reterr)) {
goto SdiffMainBatch_ret_1;
}
AppendSdiffHeaderLine(flags, col_provref, col_fid, col_sid, dosage_reported, &(cswritep_arr[0]));
}
if (!(flags & kfSdiffColId)) {
swc.collapsed_sample_fmtids = nullptr;
}
// values unimportant if dosage_hap_tol == kDosageMissing
const uint32_t dosage_dip_tol = dosage_hap_tol / 2;
uint32_t dosage_sex_tols[2]; // for chrX
dosage_sex_tols[0] = dosage_dip_tol;
dosage_sex_tols[1] = dosage_hap_tol;
const uint32_t ibs_needed = ((sdip->flags & kfSdiffCountsIbsNeeded) != kfSdiff0);
PgenVariant pgv;
if (unlikely(BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, dosage_needed? kfPgenGlobalDosagePresent : kfPgenGlobal0, &pgv))) {
goto SdiffMainBatch_ret_NOMEM;
}
Dosage* dosage_buf = nullptr;
if (dosage_needed) {
// todo: multidosage
if (unlikely(bigstack_alloc_dosage(sample_ct, &dosage_buf))) {
goto SdiffMainBatch_ret_NOMEM;
}
}
AlleleCode* allele_code_buf = nullptr;
if (allele_idx_offsets != nullptr) {
if (unlikely(bigstack_alloc_ac(2 * sample_ct, &allele_code_buf))) {
goto SdiffMainBatch_ret_NOMEM;
}
}
pgv.patch_01_ct = 0;
pgv.patch_10_ct = 0;
pgv.dosage_ct = 0;
// assumes little-endian
// diploid GT: \t0/0 \t0/1 \t1/1 \t./.
// diploid DS: \t0 \t1 \t2 \t.
// haploid GT: \t0 \t0/1 \t1 \t.
// haploid DS: \t0 \t0.5 \t1 \t.
// '!' = ascii 33, should never appear in output
const uint32_t gt_text[8] = {0x302f3009, 0x312f3009, 0x312f3109, 0x2e2f2e09, 0x21213009, 0x312f3009, 0x21213109, 0x21212e09};
const uint32_t ds_text[8] = {0x21213009, 0x21213109, 0x21213209, 0x21212e09, 0x21213009, 0x352e3009, 0x21213109, 0x21212e09};
const uint32_t* hc_text = dosage_reported? ds_text : gt_text;
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
const uint32_t include_missing = (flags / kfSdiffIncludeMissing) & 1;
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
uint32_t is_autosomal_diploid = 0;
uint32_t is_x = 0;
uint32_t is_y = 0;
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t pct = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
uint32_t allele_ct = 2;
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
if (variant_uidx >= chr_end) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (variant_uidx >= chr_end);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
is_autosomal_diploid = !IsSet(cip->haploid_mask, chr_idx);
is_x = (chr_idx == x_code);
is_y = (chr_idx == y_code);
if (swc.chr_buf) {
char* chr_name_end = chrtoa(cip, chr_idx, swc.chr_buf);
*chr_name_end = '\t';
swc.chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - swc.chr_buf);
}
}
uintptr_t allele_idx_offset_base = variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
if (allele_ct == 2) {
if (!dosage_needed) {
reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec);
} else {
reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
}
} else {
if (!dosage_needed) {
reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
} else {
reterr = PgrGetMD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv);
}
}
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, variant_uidx);
goto SdiffMainBatch_ret_1;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
const uint32_t provref = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)));
if (allele_ct == 2) {
if (!pgv.dosage_ct) {
if (AllGenoEqual(pgv.genovec, sample_ct)) {
// don't need to do anything!
continue;
}
const uint32_t* id_pair_iter = id_pairs;
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
if (is_y && (!IsSet(pair_sex_male, pair_idx))) {
continue;
}
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 == hc2) {
if (hc1 == 3) {
sdiff_counts[pair_idx].missing_ct += 1;
sdiff_counts[pair_idx].ibsmiss_ct += is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx)));
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
const uint32_t is_diploid_pair = is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx)));
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += is_diploid_pair;
if (!include_missing) {
continue;
}
} else {
cur_counts->diff_ct += 1;
if (is_diploid_pair) {
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1;
}
}
const uintptr_t fidx = is_pairwise? pair_idx : 0;
char* cswritep = cswritep_arr[fidx];
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (unlikely(AppendSdiffPregenoFields(&swc, cur_alleles, sample_idx1, sample_idx2, variant_uidx, allele_ct, col_provref, provref, &(css_arr[fidx]), &cswritep))) {
// might not need this assignment, but play it safe for now
cswritep_arr[fidx] = cswritep;
goto SdiffMainBatch_ret_WRITE_FAIL;
}
if (flags & kfSdiffColGeno) {
if (is_diploid_pair) {
cswritep = memcpya(cswritep, &(hc_text[hc1]), 4);
cswritep -= 2 * dosage_reported;
cswritep = memcpya(cswritep, &(hc_text[hc2]), 4);
cswritep -= 2 * dosage_reported;
} else {
cswritep = memcpya(cswritep, &(hc_text[hc1 + 4]), 4);
cswritep -= 2 * (hc1 != 1);
cswritep = memcpya(cswritep, &(hc_text[hc2 + 4]), 4);
cswritep -= 2 * (hc2 != 1);
}
}
AppendBinaryEoln(&cswritep);
cswritep_arr[fidx] = cswritep;
if (unlikely(Cswrite(&(css_arr[fidx]), &(cswritep_arr[fidx])))) {
cswritep_arr[fidx] = cswritep;
goto SdiffMainBatch_ret_WRITE_FAIL;
}
}
} else {
// dosages present
const Dosage* dosage_read_iter = pgv.dosage_main;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
if (!IsSet(pgv.dosage_present, sample_idx)) {
dosage_buf[sample_idx] = kGenoToDosage[GetNyparrEntry(pgv.genovec, sample_idx)];
} else {
dosage_buf[sample_idx] = *dosage_read_iter++;
}
}
const uint32_t* id_pair_iter = id_pairs;
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
if (is_y && (!IsSet(pair_sex_male, pair_idx))) {
continue;
}
const uint32_t dosage1 = dosage_buf[sample_idx1];
const uint32_t dosage2 = dosage_buf[sample_idx2];
if (dosage1 == dosage2) {
if (dosage1 == kDosageMissing) {
sdiff_counts[pair_idx].missing_ct += 1;
sdiff_counts[pair_idx].ibsmiss_ct += is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx)));
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
const uint32_t is_diploid_pair = is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx)));
if ((dosage1 == kDosageMissing) || (dosage2 == kDosageMissing)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += is_diploid_pair;
if (!include_missing) {
continue;
}
} else {
if (ibs_needed && is_diploid_pair) {
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1);
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2);
if (hc1 != hc2) {
if ((hc1 == 3) || (hc2 == 3)) {
cur_counts->ibsmiss_ct += 1;
}
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1;
}
}
if (abs_i32(dosage1 - dosage2) <= dosage_sex_tols[!is_diploid_pair]) {
continue;
}
cur_counts->diff_ct += 1;
}
const uintptr_t fidx = is_pairwise? pair_idx : 0;
char* cswritep = cswritep_arr[fidx];
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (unlikely(AppendSdiffPregenoFields(&swc, cur_alleles, sample_idx1, sample_idx2, variant_uidx, allele_ct, col_provref, provref, &(css_arr[fidx]), &cswritep))) {
cswritep_arr[fidx] = cswritep;
goto SdiffMainBatch_ret_WRITE_FAIL;
}
if (flags & kfSdiffColGeno) {
*cswritep++ = '\t';
if (dosage1 == kDosageMissing) {
*cswritep++ = '.';
} else if (is_diploid_pair) {
cswritep = PrintSmallDosage(dosage1, cswritep);
} else {
cswritep = PrintHaploidDosage(dosage1, cswritep);
}
*cswritep++ = '\t';
if (dosage2 == kDosageMissing) {
*cswritep++ = '.';
} else if (is_diploid_pair) {
cswritep = PrintSmallDosage(dosage2, cswritep);
} else {
cswritep = PrintHaploidDosage(dosage2, cswritep);
}
}
AppendBinaryEoln(&cswritep);
cswritep_arr[fidx] = cswritep;
if (unlikely(Cswrite(&(css_arr[fidx]), &(cswritep_arr[fidx])))) {
cswritep_arr[fidx] = cswritep;
goto SdiffMainBatch_ret_WRITE_FAIL;
}
}
}
} else {
// multiallelic
if (!pgv.dosage_ct) {
PglMultiallelicSparseToDenseMiss(&pgv, sample_ct, allele_code_buf);
const uint32_t* id_pair_iter = id_pairs;
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
if (is_y && (!IsSet(pair_sex_male, pair_idx))) {
continue;
}
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1];
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1];
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2];
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1];
if ((ac11 == ac21) && (ac12 == ac22)) {
if (ac11 == kMissingAlleleCode) {
sdiff_counts[pair_idx].missing_ct += 1;
sdiff_counts[pair_idx].ibsmiss_ct += is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx)));
}
continue;
}
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
const uint32_t is_diploid_pair = is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx)));
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) {
cur_counts->halfmiss_ct += 1;
cur_counts->ibsmiss_ct += is_diploid_pair;
if (!include_missing) {
continue;
}
} else {
cur_counts->diff_ct += 1;
if (ibs_needed && is_diploid_pair) {
cur_counts->ibsx_cts[(ac11 == ac21) || (ac11 == ac22) || (ac12 == ac21) || (ac12 == ac22)] += 1;
}
}
const uintptr_t fidx = is_pairwise? pair_idx : 0;
char* cswritep = cswritep_arr[fidx];
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (unlikely(AppendSdiffPregenoFields(&swc, cur_alleles, sample_idx1, sample_idx2, variant_uidx, allele_ct, col_provref, provref, &(css_arr[fidx]), &cswritep))) {
// might not need this assignment, but play it safe for now
cswritep_arr[fidx] = cswritep;
goto SdiffMainBatch_ret_WRITE_FAIL;
}
if (flags & kfSdiffColGeno) {
*cswritep++ = '\t';
if (is_diploid_pair) {
if (!dosage_reported) {
if (ac11 == kMissingAlleleCode) {
cswritep = strcpya_k(cswritep, "./.");
} else {
cswritep = u32toa_x(ac11, '/', cswritep);
cswritep = u32toa(ac12, cswritep);
}
*cswritep++ = '\t';
if (ac21 == kMissingAlleleCode) {
cswritep = strcpya_k(cswritep, "./.");
} else {
cswritep = u32toa_x(ac21, '/', cswritep);
cswritep = u32toa(ac22, cswritep);
}
} else {
cswritep = PrintMultiallelicHcAsDs(ac11, ac12, allele_ct, cswritep);
*cswritep++ = '\t';
cswritep = PrintMultiallelicHcAsDs(ac21, ac22, allele_ct, cswritep);
}
} else {
if (!dosage_reported) {
if (ac11 == kMissingAlleleCode) {
*cswritep++ = '.';
} else {
cswritep = u32toa(ac11, cswritep);
if (ac11 != ac12) {
*cswritep++ = '/';
cswritep = u32toa(ac12, cswritep);
}
}
*cswritep++ = '\t';
if (ac21 == kMissingAlleleCode) {
*cswritep++ = '.';
} else {
cswritep = u32toa(ac21, cswritep);
if (ac21 != ac22) {
*cswritep++ = '/';
cswritep = u32toa(ac22, cswritep);
}
}
} else {
cswritep = PrintMultiallelicHcAsHaploidDs(ac11, ac12, allele_ct, cswritep);
*cswritep++ = '\t';
cswritep = PrintMultiallelicHcAsHaploidDs(ac21, ac22, allele_ct, cswritep);
}
}
}
AppendBinaryEoln(&cswritep);
cswritep_arr[fidx] = cswritep;
if (unlikely(Cswrite(&(css_arr[fidx]), &(cswritep_arr[fidx])))) {
cswritep_arr[fidx] = cswritep;
goto SdiffMainBatch_ret_WRITE_FAIL;
}
}
} else {
// multiallelic-dosage; todo
exit(S_CAST(int32_t, kPglRetInternalError));
}
}
}
for (uintptr_t fidx = 0; fidx != file_ct; ++fidx) {
if (unlikely(CswriteCloseNull(&(css_arr[fidx]), cswritep_arr[fidx]))) {
goto SdiffMainBatch_ret_WRITE_FAIL;
}
}
if (pct > 10) {
fputs("\b \b", stdout);
}
fputs("\b\b", stdout);
}
while (0) {
SdiffMainBatch_ret_NOMEM:
reterr = kPglRetNomem;
break;
SdiffMainBatch_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
SdiffMainBatch_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
SdiffMainBatch_ret_1:
if (css_arr) {
for (uintptr_t fidx = 0; fidx != file_ct; ++fidx) {
CswriteCloseCond(&(css_arr[fidx]), cswritep_arr[fidx]);
}
}
BigstackReset(bigstack_mark);
return reterr;
}
CONSTI32(kSdiffBatchMax, (kMaxOpenFiles - 32) & (~(kBitsPerWord - 1)));
static_assert((kSdiffBatchMax % kBitsPerWord) == 0, "kSdiffBatchMax must be a multiple of kBitsPerWord.");
static_assert(kSdiffBatchMax > 0, "kSdiffBatchMax must be positive.");
PglErr Sdiff(const uintptr_t* orig_sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const SdiffInfo* sdip, uint32_t raw_sample_ct, uint32_t orig_sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t iid_sid, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
unsigned char* bigstack_end_mark = g_bigstack_end;
uintptr_t line_idx = 0;
TextStream txs; // file=
PreinitTextStream(&txs);
FILE* outfile = nullptr;
PglErr reterr = kPglRetSuccess;
{
// Determine xid_mode.
const SdiffFlags flags = sdip->flags;
const uint32_t other_id_ct = sdip->other_id_ct;
char* line_start = nullptr;
char* line_iter = nullptr;
XidMode xid_mode;
if (other_id_ct) {
// todo: make this its own function if we use the same logic elsewhere
// For sanity's sake, require all sample IDs provided on command line
// to contain the same number of delimiters.
const char* first_delim_ptr = strchr(sdip->first_id_or_fname, '\t');
if (!first_delim_ptr) {
xid_mode = kfXidModeIid;
} else {
const char* second_delim_ptr = strchr(&(first_delim_ptr[1]), '\t');
if (!second_delim_ptr) {
if (iid_sid) {
xid_mode = kfXidModeIidSid;
} else {
xid_mode = kfXidModeFidIid;
}
} else {
if (unlikely(strchr(&(second_delim_ptr[1]), '\t'))) {
logerrputs("Error: Too many instances of id-delim= character in --sample-diff sample ID.\n");
goto Sdiff_ret_INVALID_CMDLINE;
}
xid_mode = kfXidModeFidIidSid;
}
}
} else {
reterr = InitTextStream(sdip->first_id_or_fname, kTextStreamBlenFast, MAXV(max_thread_ct - 1, 1), &txs);
if (unlikely(reterr)) {
goto Sdiff_ret_TSTREAM_FAIL;
}
reterr = LoadXidHeaderPair("sample-diff", iid_sid, &line_idx, &txs, &xid_mode, &line_start, &line_iter);
if (unlikely(reterr)) {
if (reterr == kPglRetEof) {
logerrputs("Error: Empty --sample-diff file.\n");
reterr = kPglRetInconsistentInput;
}
goto Sdiff_ret_TSTREAM_XID_FAIL;
}
}
unsigned char* bigstack_mark2 = g_bigstack_base;
// May as well have --strict-sid0 or lack of it apply to base=/ids= too.
if ((xid_mode & kfXidModeFlagSid) && (!siip->sids) && (!(siip->flags & kfSampleIdStrictSid0))) {
xid_mode ^= kfXidModeFlagSid | kfXidModeFlagSkipSid;
}
char* sorted_xidbox;
uint32_t* xid_map;
uintptr_t max_xid_blen;
reterr = SortedXidboxInitAlloc(orig_sample_include, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
if (unlikely(reterr)) {
goto Sdiff_ret_1;
}
char* idbuf;
if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) {
goto Sdiff_ret_NOMEM;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
// Now we can parse the sample IDs from the file or command line properly.
uintptr_t* sample_include;
uint32_t* sample_include_cumulative_popcounts;
uint32_t* id_pairs;
uintptr_t id_pair_ct;
uint32_t sample_ct;
if (other_id_ct) {
sample_ct = other_id_ct + 1;
uint32_t* sample_idxs;
if (unlikely(bigstack_end_alloc_u32(sample_ct, &sample_idxs))) {
goto Sdiff_ret_NOMEM;
}
const char* first_id = sdip->first_id_or_fname;
const char* dummy_iter = first_id;
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &dummy_iter, &(sample_idxs[0]), idbuf))) {
logerrprintfww("Error: --sample-diff sample ID '%s' not found.\n", first_id);
goto Sdiff_ret_INCONSISTENT_INPUT;
}
const char* other_ids_iter = sdip->other_ids_flattened;
for (uint32_t id_idx = 1; id_idx != sample_ct; ++id_idx) {
const char* other_id = other_ids_iter;
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &other_ids_iter, &(sample_idxs[id_idx]), idbuf))) {
logerrprintfww("Error: --sample-diff sample ID '%s' not found.\n", other_id);
goto Sdiff_ret_INCONSISTENT_INPUT;
}
++other_ids_iter;
}
BigstackReset(bigstack_mark2);
if (flags & kfSdiffOneBase) {
id_pair_ct = other_id_ct;
} else {
id_pair_ct = (S_CAST(uintptr_t, other_id_ct) * sample_ct) / 2;
}
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &sample_include) ||
bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
bigstack_alloc_u32(id_pair_ct * 2, &id_pairs))) {
goto Sdiff_ret_NOMEM;
}
for (uint32_t id_idx = 0; id_idx != sample_ct; ++id_idx) {
const uint32_t sample_uidx = sample_idxs[id_idx];
if (IsSet(sample_include, sample_uidx)) {
logerrputs("Error: Duplicate ID in --sample-diff list.\n");
goto Sdiff_ret_INVALID_CMDLINE;
}
SetBit(sample_uidx, sample_include);
}
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
UidxsToIdxs(sample_include, sample_include_cumulative_popcounts, sample_ct, sample_idxs);
if (flags & kfSdiffOneBase) {
const uint32_t sample_idx_base = sample_idxs[0];
for (uint32_t id_idx = 1; id_idx != sample_ct; ++id_idx) {
id_pairs[2 * id_idx - 2] = sample_idx_base;
id_pairs[2 * id_idx - 1] = sample_idxs[id_idx];
}
} else {
uint32_t* id_pairs_iter = id_pairs;
for (uint32_t id_idx2 = 1; id_idx2 != sample_ct; ++id_idx2) {
const uint32_t sample_idx2 = sample_idxs[id_idx2];
for (uint32_t id_idx1 = 0; id_idx1 != id_idx2; ++id_idx1) {
*id_pairs_iter++ = sample_idxs[id_idx1];
*id_pairs_iter++ = sample_idx2;
}
}
}
BigstackEndReset(bigstack_end_mark);
} else {
uint32_t* sample_pair_uidxs_end = R_CAST(uint32_t*, bigstack_end_mark);
uint32_t* sample_pair_uidxs_iter = sample_pair_uidxs_end;
uint32_t* sample_pair_uidxs_oom = R_CAST(uint32_t*, g_bigstack_base);
if (*line_start == '#') {
line_iter = AdvPastDelim(line_iter, '\n');
++line_idx;
} else {
line_iter = line_start;
}
for (; TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
const char* linebuf_iter = line_iter;
uint32_t sample_uidx1;
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx1, idbuf))) {
if (!idbuf[0]) {
logerrprintfww("Error: --sample-diff sample ID (on line %" PRIuPTR " of file) not found.\n", line_idx);
} else {
TabsToSpaces(idbuf);
logerrprintfww("Error: --sample-diff sample ID '%s' (on line %" PRIuPTR " of file) not found.\n", idbuf, line_idx);
}
goto Sdiff_ret_INCONSISTENT_INPUT;
}
linebuf_iter = FirstNonTspace(linebuf_iter);
if (unlikely(IsEolnKns(*linebuf_iter))) {
goto Sdiff_ret_MISSING_TOKENS;
}
uint32_t sample_uidx2;
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx2, idbuf))) {
if (!idbuf[0]) {
logerrprintfww("Error: --sample-diff sample ID (on line %" PRIuPTR " of file) not found.\n", line_idx);
} else {
TabsToSpaces(idbuf);
logerrprintfww("Error: --sample-diff sample ID '%s' (on line %" PRIuPTR " of file) not found.\n", idbuf, line_idx);
}
goto Sdiff_ret_INCONSISTENT_INPUT;
}
if (unlikely(sample_uidx1 == sample_uidx2)) {
TabsToSpaces(idbuf);
logerrprintfww("Error: Duplicate sample ID \"%s\" on line %" PRIuPTR " of --sample-diff file.\n", idbuf, line_idx);
goto Sdiff_ret_MALFORMED_INPUT;
}
if (unlikely(sample_pair_uidxs_iter == sample_pair_uidxs_oom)) {
goto Sdiff_ret_NOMEM;
}
*(--sample_pair_uidxs_iter) = sample_uidx1;
*(--sample_pair_uidxs_iter) = sample_uidx2;
line_iter = K_CAST(char*, linebuf_iter);
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto Sdiff_ret_TSTREAM_FAIL;
}
const uintptr_t id_ct = sample_pair_uidxs_end - sample_pair_uidxs_iter;
if (unlikely(!id_ct)) {
logerrputs("Error: Empty --sample-diff file.\n");
goto Sdiff_ret_MALFORMED_INPUT;
}
BigstackEndSet(sample_pair_uidxs_iter);
BigstackReset(bigstack_mark2);
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &sample_include) ||
bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
bigstack_alloc_u32(id_ct, &id_pairs))) {
goto Sdiff_ret_NOMEM;
}
sample_pair_uidxs_iter = sample_pair_uidxs_end;
for (uintptr_t ulii = 0; ulii != id_ct; ++ulii) {
const uint32_t sample_uidx = *(--sample_pair_uidxs_iter);
SetBit(sample_uidx, sample_include);
id_pairs[ulii] = sample_uidx;
}
BigstackEndReset(bigstack_end_mark);
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
sample_ct = sample_include_cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(sample_include[raw_sample_ctl - 1]);
// Don't strictly enforce pair-uniqueness for now, but do perform a basic
// sanity check.
if (id_ct > S_CAST(uintptr_t, sample_ct) * (sample_ct - 1)) {
logerrputs("Error: Duplicate ID pairs in --sample-diff file.\n");
goto Sdiff_ret_MALFORMED_INPUT;
}
UidxsToIdxs(sample_include, sample_include_cumulative_popcounts, id_ct, id_pairs);
id_pair_ct = id_ct / 2;
}
SdiffCounts* sdiff_counts;
if (unlikely(BIGSTACK_ALLOC_X(SdiffCounts, id_pair_ct, &sdiff_counts))) {
goto Sdiff_ret_NOMEM;
}
memset(sdiff_counts, 0, id_pair_ct * sizeof(SdiffCounts));
uintptr_t* pair_sex_male = nullptr;
uint32_t x_ct = 0;
uint32_t y_ct = 0;
{
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
if ((!IsI32Neg(x_code)) && IsSet(cip->chr_mask, x_code)) {
x_ct = CountChrVariantsUnsafe(variant_include, cip, x_code);
}
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
if ((!IsI32Neg(y_code)) && IsSet(cip->chr_mask, y_code)) {
y_ct = CountChrVariantsUnsafe(variant_include, cip, y_code);
}
}
if (x_ct || y_ct) {
const uintptr_t id_pair_ctl = BitCtToWordCt(id_pair_ct);
const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
uintptr_t* sex_nm_collapsed;
uintptr_t* sex_male_collapsed;
if (unlikely(bigstack_alloc_w(id_pair_ctl, &pair_sex_male) ||
bigstack_alloc_w(sample_ctl, &sex_nm_collapsed) ||
bigstack_alloc_w(sample_ctl, &sex_male_collapsed))) {
goto Sdiff_ret_NOMEM;
}
CopyBitarrSubset(sex_nm, sample_include, sample_ct, sex_nm_collapsed);
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed);
const uint32_t* id_pairs_iter = id_pairs;
const uintptr_t word_ct_m1 = id_pair_ctl - 1;
uint32_t loop_len = kBitsPerWord;
for (uintptr_t widx = 0; ; ++widx) {
if (widx >= word_ct_m1) {
if (widx > word_ct_m1) {
break;
}
loop_len = ModNz(id_pair_ct, kBitsPerWord);
}
uintptr_t cur_word = 0;
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uint32_t sample_idx1 = *id_pairs_iter++;
const uint32_t sample_idx2 = *id_pairs_iter++;
const uint32_t sex_nm1 = IsSet(sex_nm_collapsed, sample_idx1);
const uint32_t sex_nm_xor = sex_nm1 ^ IsSet(sex_nm_collapsed, sample_idx2);
const uintptr_t sex_male1 = IsSet(sex_male_collapsed, sample_idx1);
const uintptr_t sex_male_xor = sex_male1 ^ IsSet(sex_male_collapsed, sample_idx2);
if (sex_nm_xor) {
// Exactly one sex is missing.
cur_word |= sex_male_xor << uii;
} else if (unlikely(!sex_nm1)) {
logerrputs("Error: --sample-diff requires at least one sample in each pair to have known\nsex when chrX or chrY is present.\n");
goto Sdiff_ret_INCONSISTENT_INPUT;
} else if (unlikely(sex_male_xor)) {
logerrputs("Error: --sample-diff cannot perform male-female comparisons when chrX or chrY\nis present. (Consider \"--not-chr X,Y\".)\n");
goto Sdiff_ret_INCONSISTENT_INPUT;
} else {
cur_word |= sex_male1 << uii;
}
}
pair_sex_male[widx] = cur_word;
}
BigstackReset(sex_nm_collapsed);
}
// Main loops.
if (flags & kfSdiffCountsOnly) {
reterr = SdiffCountsOnly(sample_include, sample_include_cumulative_popcounts, id_pairs, pair_sex_male, variant_include, cip, allele_idx_offsets, sdip, sample_ct, variant_ct, id_pair_ct, simple_pgrp, sdiff_counts);
if (unlikely(reterr)) {
goto Sdiff_ret_1;
}
} else {
const uint32_t is_pairwise = (flags / kfSdiffPairwise) & 1;
uintptr_t batch_ct = 1;
if (is_pairwise && (id_pair_ct > kSdiffBatchMax)) {
batch_ct = 1 + ((id_pair_ct - 1) / kSdiffBatchMax);
}
for (uintptr_t batch_idx = 0; batch_idx != batch_ct; ++batch_idx) {
const uintptr_t id_pair_idx_start = batch_idx * kSdiffBatchMax;
uintptr_t id_pair_idx_end = id_pair_ct;
if (batch_ct == 1) {
printf("--sample-diff%s: 0%%", is_pairwise? " pairwise" : "");
} else {
if (batch_idx != batch_ct - 1) {
id_pair_idx_end = id_pair_idx_start + kSdiffBatchMax;
}
printf("\r--sample-diff pairwise batch %" PRIuPTR "/%" PRIuPTR ": 0%%", batch_idx + 1, batch_ct);
}
fflush(stdout);
reterr = SdiffMainBatch(sample_include, sample_include_cumulative_popcounts, siip, &(id_pairs[2 * id_pair_idx_start]), &(pair_sex_male[id_pair_idx_start / kBitsPerWord]), variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, sdip, sample_ct, raw_variant_ct, variant_ct, id_pair_idx_end - id_pair_idx_start, max_thread_ct, simple_pgrp, outname, outname_end, &(sdiff_counts[id_pair_idx_start]));
if (unlikely(reterr)) {
goto Sdiff_ret_1;
}
}
fputs("done.\n", stdout);
if (is_pairwise) {
*outname_end = '\0';
logprintfww("--sample-diff pairwise: Discordances written to %s.[ID1].[ID2].sdiff%s (%" PRIuPTR " file%s).\n", outname, (flags & kfSdiffZs)? ".zst" : "", id_pair_ct, (id_pair_ct == 1)? "" : "s");
} else {
logprintfww("--sample-diff: Discordances written to %s .\n", outname);
}
}
// Final count-summary.
const uint32_t col_fid = FidColIsRequired(siip, flags / kfSdiffCountsColMaybefid);
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfSdiffCountsColMaybesid);
char* collapsed_sample_fmtids;
uintptr_t max_sample_fmtid_blen;
if (unlikely(CollapsedSampleFmtidInitAlloc(sample_include, siip, sample_ct, col_fid, col_sid, &collapsed_sample_fmtids, &max_sample_fmtid_blen))) {
goto Sdiff_ret_NOMEM;
}
uint32_t autosomal_diploid_ct;
uint32_t nonsex_haploid_ct;
if (!IsSet(cip->chr_mask, 0)) {
const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
const uint32_t chr_idx_end = cip->max_code + 1 + cip->name_ct;
nonsex_haploid_ct = 0;
for (uint32_t chr_idx = 1; ; ++chr_idx) {
// usually just MT
chr_idx = AdvBoundedTo1Bit(cip->haploid_mask, chr_idx, chr_idx_end);
if (chr_idx == chr_idx_end) {
break;
}
if ((!IsSet(cip->chr_mask, chr_idx)) || (chr_idx == x_code) || (chr_idx == y_code)) {
continue;
}
nonsex_haploid_ct += CountChrVariantsUnsafe(variant_include, cip, chr_idx);
}
autosomal_diploid_ct = variant_ct - x_ct - y_ct - nonsex_haploid_ct;
} else {
autosomal_diploid_ct = 0;
nonsex_haploid_ct = variant_ct - x_ct - y_ct;
}
snprintf(outname_end, kMaxOutfnameExtBlen, ".sdiff.summary");
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
goto Sdiff_ret_OPEN_FAIL;
}
char* textbuf = g_textbuf;
char* textbuf_flush = &(textbuf[kMaxMediumLine]);
char* write_iter = textbuf;
*write_iter++ = '#';
if (col_fid) {
write_iter = strcpya_k(write_iter, "FID1\t");
}
write_iter = strcpya_k(write_iter, "IID1");
if (col_sid) {
write_iter = strcpya_k(write_iter, "\tSID1");
}
if (col_fid) {
write_iter = strcpya_k(write_iter, "\tFID2");
}
write_iter = strcpya_k(write_iter, "\tIID2");
if (col_sid) {
write_iter = strcpya_k(write_iter, "\tSID2");
}
if (flags & kfSdiffCountsColNobs) {
write_iter = strcpya_k(write_iter, "\tOBS_CT");
}
if (flags & kfSdiffCountsColNobsIbs) {
write_iter = strcpya_k(write_iter, "\tIBS_OBS_CT");
}
if (flags & kfSdiffCountsColIbs0) {
write_iter = strcpya_k(write_iter, "\tIBS0_CT");
}
if (flags & kfSdiffCountsColIbs1) {
write_iter = strcpya_k(write_iter, "\tIBS1_CT");
}
if (flags & kfSdiffCountsColIbs2) {
write_iter = strcpya_k(write_iter, "\tIBS2_CT");
}
if (flags & kfSdiffCountsColHalfmiss) {
write_iter = strcpya_k(write_iter, "\tHALFMISS_CT");
}
if (flags & kfSdiffCountsColDiff) {
write_iter = strcpya_k(write_iter, "\tDIFF_CT");
}
AppendBinaryEoln(&write_iter);
const uint32_t obs_ct_base = autosomal_diploid_ct + x_ct + nonsex_haploid_ct;
const uint32_t* id_pair_iter = id_pairs;
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) {
const uint32_t sample_idx1 = *id_pair_iter++;
const uint32_t sample_idx2 = *id_pair_iter++;
write_iter = strcpyax(write_iter, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx1]), '\t');
write_iter = strcpya(write_iter, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx2]));
const SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]);
if (flags & kfSdiffCountsColNobs) {
uint32_t obs_ct = obs_ct_base;
if (y_ct && IsSet(pair_sex_male, pair_idx)) {
obs_ct += y_ct;
}
if (!(flags & kfSdiffIncludeMissing)) {
obs_ct -= cur_counts->missing_ct + cur_counts->halfmiss_ct;
}
*write_iter++ = '\t';
write_iter = u32toa(obs_ct, write_iter);
}
if (flags & kfSdiffCountsIbsNeeded) {
uint32_t ibs_obs_ct = autosomal_diploid_ct - cur_counts->ibsmiss_ct;
if (x_ct && (!IsSet(pair_sex_male, pair_idx))) {
ibs_obs_ct += x_ct;
}
if (flags & kfSdiffCountsColNobsIbs) {
*write_iter++ = '\t';
write_iter = u32toa(ibs_obs_ct, write_iter);
}
if (flags & kfSdiffCountsColIbs0) {
*write_iter++ = '\t';
write_iter = u32toa(cur_counts->ibsx_cts[0], write_iter);
}
if (flags & kfSdiffCountsColIbs1) {
*write_iter++ = '\t';
write_iter = u32toa(cur_counts->ibsx_cts[1], write_iter);
}
if (flags & kfSdiffCountsColIbs2) {
*write_iter++ = '\t';
write_iter = u32toa(ibs_obs_ct - cur_counts->ibsx_cts[0] - cur_counts->ibsx_cts[1], write_iter);
}
}
if (flags & kfSdiffCountsColHalfmiss) {
*write_iter++ = '\t';
write_iter = u32toa(cur_counts->halfmiss_ct, write_iter);
}
if (flags & kfSdiffCountsColDiff) {
uint32_t diff_ct = cur_counts->diff_ct;
if (flags & kfSdiffIncludeMissing) {
diff_ct += cur_counts->halfmiss_ct;
}
*write_iter++ = '\t';
write_iter = u32toa(diff_ct, write_iter);
}
AppendBinaryEoln(&write_iter);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto Sdiff_ret_WRITE_FAIL;
}
}
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
goto Sdiff_ret_WRITE_FAIL;
}
logprintfww("--sample-diff: Discordance count summary written to %s .\n", outname);
}
while (0) {
Sdiff_ret_NOMEM:
reterr = kPglRetNomem;
break;
Sdiff_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
Sdiff_ret_TSTREAM_XID_FAIL:
if (!TextStreamErrcode(&txs)) {
break;
}
Sdiff_ret_TSTREAM_FAIL:
TextStreamErrPrint("--sample-diff file", &txs);
break;
Sdiff_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
Sdiff_ret_INVALID_CMDLINE:
reterr = kPglRetInvalidCmdline;
break;
Sdiff_ret_MISSING_TOKENS:
logerrprintf("Error: Line %" PRIuPTR " of --sample-diff file has fewer tokens than expected.\n", line_idx);
Sdiff_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
Sdiff_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
Sdiff_ret_1:
fclose_cond(outfile);
CleanupTextStream2("--sample-diff file", &txs, &reterr);
BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
return reterr;
}
PglErr WriteSnplist(const uintptr_t* variant_include, const char* const* variant_ids, uint32_t variant_ct, uint32_t output_zst, uint32_t allow_dups, uint32_t max_thread_ct, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
{
if (!allow_dups) {
uint32_t dup_found;
reterr = CheckIdUniqueness(g_bigstack_base, g_bigstack_end, variant_include, variant_ids, variant_ct, max_thread_ct, &dup_found);
if (unlikely(reterr)) {
goto WriteSnplist_ret_1;
}
if (dup_found) {
// I estimate that this corresponds to a pipeline bug (or, at minimum,
// inefficiency) >90% of the time.
// --extract[-intersect] could be modified in a similar manner, but my
// working hypothesis is that interception of suspect --write-snplist
// operations is enough to stop most duplicate-related --extract
// misuses.
logerrputs("Error: --write-snplist normally shouldn't be used with duplicate variant IDs.\n(--set-all-var-ids helps with ID deduplication, and --rm-dup addresses actual\nduplicate data.) However, if you've already accounted for them, you can\nsuppress this error with the 'allow-dups' modifier.\n");
goto WriteSnplist_ret_INCONSISTENT_INPUT;
}
}
OutnameZstSet(".snplist", output_zst, outname_end);
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, kCompressStreamBlock + kMaxIdSlen + 2, &css, &cswritep);
if (unlikely(reterr)) {
goto WriteSnplist_ret_1;
}
uintptr_t variant_uidx_base = 0;
uintptr_t cur_bits = variant_include[0];
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto WriteSnplist_ret_WRITE_FAIL;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto WriteSnplist_ret_WRITE_FAIL;
}
logprintfww("--write-snplist%s%s: Variant IDs written to %s .\n", output_zst? " zs" : "", allow_dups? " allow-dups" : "", outname);
}
while (0) {
WriteSnplist_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
WriteSnplist_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
WriteSnplist_ret_1:
CswriteCloseCond(&css, cswritep);
BigstackReset(bigstack_mark);
return reterr;
}
// similar to write_psam().
PglErr WriteCovar(const uintptr_t* sample_include, const PedigreeIdInfo* piip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const PhenoCol* covar_cols, const char* covar_names, const uint32_t* new_sample_idx_to_old, const char* output_missing_pheno, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t covar_ct, uintptr_t max_covar_name_blen, WriteCovarFlags write_covar_flags, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
FILE* outfile = nullptr;
PglErr reterr = kPglRetSuccess;
{
snprintf(outname_end, kMaxOutfnameExtBlen, ".cov");
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
goto WriteCovar_ret_OPEN_FAIL;
}
const uint32_t omp_slen = strlen(output_missing_pheno);
char* textbuf = g_textbuf;
char* textbuf_flush = &(textbuf[kMaxMediumLine]);
const uint32_t write_fid = FidColIsRequired(&piip->sii, write_covar_flags / kfWriteCovarColMaybefid);
const char* sample_ids = piip->sii.sample_ids;
const char* sids = piip->sii.sids;
const char* paternal_ids = piip->parental_id_info.paternal_ids;
const char* maternal_ids = piip->parental_id_info.maternal_ids;
const uintptr_t max_sample_id_blen = piip->sii.max_sample_id_blen;
const uintptr_t max_sid_blen = piip->sii.max_sid_blen;
const uintptr_t max_paternal_id_blen = piip->parental_id_info.max_paternal_id_blen;
const uintptr_t max_maternal_id_blen = piip->parental_id_info.max_maternal_id_blen;
const uint32_t write_sid = SidColIsRequired(sids, write_covar_flags / kfWriteCovarColMaybesid);
const uint32_t write_parents = ParentalColsAreRequired(piip, write_covar_flags / kfWriteCovarColMaybeparents);
const uint32_t write_sex = (write_covar_flags / kfWriteCovarColSex) & 1;
const uint32_t write_empty_pheno = (write_covar_flags & kfWriteCovarColPheno1) && (!pheno_ct);
const uint32_t write_phenos = (write_covar_flags & (kfWriteCovarColPheno1 | kfWriteCovarColPhenos)) && pheno_ct;
if (write_phenos && (!(write_covar_flags & kfWriteCovarColPhenos))) {
pheno_ct = 1;
}
char* write_iter = textbuf;
*write_iter++ = '#';
if (write_fid) {
write_iter = strcpya_k(write_iter, "FID\t");
}
write_iter = strcpya_k(write_iter, "IID");
if (write_sid) {
write_iter = strcpya_k(write_iter, "\tSID");
}
if (write_parents) {
write_iter = strcpya_k(write_iter, "\tPAT\tMAT");
}
if (write_sex) {
write_iter = strcpya_k(write_iter, "\tSEX");
}
if (write_phenos || write_empty_pheno || write_sex) {
// verify that no names are duplicated
uint32_t* covar_name_htable;
uint32_t covar_name_htable_size;
if (unlikely(HtableGoodSizeAlloc(covar_ct + write_sex, bigstack_left(), &covar_name_htable, &covar_name_htable_size))) {
goto WriteCovar_ret_NOMEM;
}
// shouldn't be possible for this to fail
PopulateStrboxHtable(covar_names, covar_ct, max_covar_name_blen, covar_name_htable_size, covar_name_htable);
uint32_t max_xcovar_name_blen = max_covar_name_blen;
if (write_sex) {
// add "SEX"
if (unlikely(StrboxHtableAdd("SEX", covar_names, max_covar_name_blen, strlen("SEX"), covar_name_htable_size, covar_ct, covar_name_htable) != UINT32_MAX)) {
logerrputs("Error: .cov file cannot have both a regular SEX column and a covariate named\n'SEX'. Exclude or rename one of these columns.\n");
goto WriteCovar_ret_INCONSISTENT_INPUT;
}
if (max_xcovar_name_blen < 4) {
max_xcovar_name_blen = 4;
}
}
if (write_phenos) {
const char* pheno_name_iter = pheno_names;
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
*write_iter++ = '\t';
const uint32_t cur_pheno_name_slen = strlen(pheno_name_iter);
if (cur_pheno_name_slen < max_xcovar_name_blen) {
// can't just use StrboxHtableFind() since "SEX" may not be stored
// in covar_names[]
const uint32_t cur_pheno_name_blen = cur_pheno_name_slen + 1;
for (uint32_t hashval = Hashceil(pheno_name_iter, cur_pheno_name_slen, covar_name_htable_size); ; ) {
const uint32_t cur_htable_idval = covar_name_htable[hashval];
if (cur_htable_idval >= covar_ct) {
if (cur_htable_idval == UINT32_MAX) {
break;
}
if (unlikely(strequal_k_unsafe(pheno_name_iter, "SEX"))) {
logerrputs(write_sex? "Error: .cov file cannot have both a regular SEX column and a phenotype named\n'SEX'. Exclude or rename one of these columns.\n" : "Error: .cov file cannot have a phenotype and a covariate with the same name.\n");
goto WriteCovar_ret_INCONSISTENT_INPUT;
}
} else {
if (unlikely(memequal(pheno_name_iter, &(covar_names[cur_htable_idval * max_covar_name_blen]), cur_pheno_name_blen))) {
logerrputs("Error: .cov file cannot have a phenotype and a covariate with the same name.\n");
goto WriteCovar_ret_INCONSISTENT_INPUT;
}
}
if (++hashval == covar_name_htable_size) {
hashval = 0;
}
}
}
write_iter = memcpya(write_iter, pheno_name_iter, cur_pheno_name_slen);
pheno_name_iter = &(pheno_name_iter[max_pheno_name_blen]);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteCovar_ret_WRITE_FAIL;
}
}
} else if (write_empty_pheno) {
if (max_covar_name_blen > 6) {
for (uint32_t hashval = Hashceil("PHENO1", 6, covar_name_htable_size); ; ) {
const uint32_t cur_htable_idval = covar_name_htable[hashval];
if (cur_htable_idval >= covar_ct) {
if (cur_htable_idval == UINT32_MAX) {
break;
}
} else {
if (unlikely(strequal_k_unsafe(&(covar_names[cur_htable_idval * max_covar_name_blen]), "PHENO1"))) {
logerrputs("Error: .cov file cannot have a phenotype and a covariate with the same name.\n");
goto WriteCovar_ret_INCONSISTENT_INPUT;
}
}
if (++hashval == covar_name_htable_size) {
hashval = 0;
}
}
}
write_iter = strcpya_k(write_iter, "\tPHENO1");
}
}
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
*write_iter++ = '\t';
const char* cur_covar_name = &(covar_names[covar_idx * max_covar_name_blen]);
const uint32_t cur_covar_name_slen = strlen(cur_covar_name);
write_iter = memcpya(write_iter, cur_covar_name, cur_covar_name_slen);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteCovar_ret_WRITE_FAIL;
}
}
AppendBinaryEoln(&write_iter);
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
uint32_t sample_uidx2 = 0;
// not really necessary to make sample_uidx increment dependent on
// new_sample_idx_to_old == nullptr
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
uintptr_t sample_uidx;
if (!new_sample_idx_to_old) {
sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
} else {
do {
sample_uidx = new_sample_idx_to_old[sample_uidx2++];
} while (!IsSet(sample_include, sample_uidx));
}
write_iter = AppendXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter);
if (write_parents) {
*write_iter++ = '\t';
write_iter = strcpyax(write_iter, &(paternal_ids[max_paternal_id_blen * sample_uidx]), '\t');
write_iter = strcpya(write_iter, &(maternal_ids[max_maternal_id_blen * sample_uidx]));
}
if (write_sex) {
*write_iter++ = '\t';
if (IsSet(sex_nm, sample_uidx)) {
*write_iter++ = '2' - IsSet(sex_male, sample_uidx);
} else {
// this is better than '0' since it allows the raw column to be used
// as --covar input
// (can't do this for .fam export, though: not worth the
// compatibility issues)
write_iter = strcpya_k(write_iter, "NA");
}
}
if (write_phenos) {
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
*write_iter++ = '\t';
write_iter = AppendPhenoStr(&(pheno_cols[pheno_idx]), output_missing_pheno, omp_slen, sample_uidx, write_iter);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteCovar_ret_WRITE_FAIL;
}
}
} else {
if (write_empty_pheno) {
*write_iter++ = '\t';
write_iter = memcpya(write_iter, output_missing_pheno, omp_slen);
}
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteCovar_ret_WRITE_FAIL;
}
}
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
*write_iter++ = '\t';
write_iter = AppendPhenoStr(&(covar_cols[covar_idx]), output_missing_pheno, omp_slen, sample_uidx, write_iter);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto WriteCovar_ret_WRITE_FAIL;
}
}
AppendBinaryEoln(&write_iter);
}
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
goto WriteCovar_ret_WRITE_FAIL;
}
logprintfww("Covariates written to %s .\n", outname);
}
while (0) {
WriteCovar_ret_NOMEM:
reterr = kPglRetNomem;
break;
WriteCovar_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
WriteCovar_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
WriteCovar_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
fclose_cond(outfile);
BigstackReset(bigstack_mark);
return reterr;
}
// This is almost a subset of SampleCounts().
typedef struct HetCtxStruct {
const uintptr_t* variant_subset;
const uintptr_t* allele_idx_offsets;
const uintptr_t* sample_include;
const uint32_t* sample_include_cumulative_popcounts;
const uintptr_t* founder_info_collapsed; // only non-null if small-sample
const uintptr_t* founder_info_interleaved_vec;
const double* allele_freqs; // nullptr if small-sample
uint32_t sample_ct;
uint32_t founder_ct;
PgenReader** pgr_ptrs;
uintptr_t** genovecs;
uintptr_t** thread_read_mhc;
uintptr_t** raregenos;
uint32_t** difflist_sample_id_bufs;
uint32_t** allele_nobs_bufs;
VecW** scrambled_ohet_bufs;
uint32_t* read_variant_uidx_starts;
uint32_t cur_block_size;
uint64_t err_info;
double* thread_ehet_base;
uint32_t* thread_nobs_base;
uint32_t* thread_monomorphic_ct;
uint32_t** thread_ohets;
double** thread_ehet_incrs;
int32_t** thread_nobs_incrs;
} HetCtx;
THREAD_FUNC_DECL HetThread(void* raw_arg) {
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
const uintptr_t tidx = arg->tidx;
HetCtx* ctx = S_CAST(HetCtx*, arg->sharedp->context);
const uintptr_t* variant_subset = ctx->variant_subset;
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
const double* allele_freqs = ctx->allele_freqs;
const uintptr_t* sample_include = ctx->sample_include;
PgenReader* pgrp = ctx->pgr_ptrs[tidx];
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
const uintptr_t* founder_info_collapsed = ctx->founder_info_collapsed;
const uintptr_t* founder_info_interleaved_vec = ctx->founder_info_interleaved_vec;
const uint32_t sample_ct = ctx->sample_ct;
const uint32_t founder_ct = ctx->founder_ct;
const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
uintptr_t* genovec = ctx->genovecs[tidx];
PgenVariant pgv;
pgv.genovec = genovec;
SetPgvThreadMhcNull(sample_ct, tidx, ctx->thread_read_mhc, &pgv);
uintptr_t* raregeno = ctx->raregenos[tidx];
uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx];
uint32_t* allele_nobs = nullptr;
if (ctx->thread_read_mhc) {
allele_nobs = ctx->allele_nobs_bufs[tidx];
}
// todo: tune this threshold
const uint32_t max_simple_difflist_len = sample_ct / 32;
double ehet_base = 0.0;
uint32_t nobs_base = 0;
uint32_t monomorphic_ct = 0;
uint32_t* ohets = ctx->thread_ohets[tidx];
double* ehet_incrs = ctx->thread_ehet_incrs[tidx];
int32_t* nobs_incrs = ctx->thread_nobs_incrs[tidx];
ZeroU32Arr(RoundUpPow2(sample_ct, kInt32PerVec), ohets);
ZeroDArr(sample_ct, ehet_incrs);
ZeroI32Arr(RoundUpPow2(sample_ct, kInt32PerVec), nobs_incrs);
const uint32_t acc2_vec_ct = NypCtToVecCt(sample_ct);
const uintptr_t dense_counts_vstride = acc2_vec_ct * 23;
VecW* scrambled_ohets = ctx->scrambled_ohet_bufs[tidx];
uint32_t dense_ct_rem3 = 3;
uint32_t dense_ct_rem15d3 = 5;
uint32_t dense_ct_rem255d15 = 17;
ZeroVecArr(dense_counts_vstride, scrambled_ohets);
const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
double ehet = 0.0;
uint32_t cur_allele_ct = 2;
uint64_t new_err_info = 0;
do {
const uint32_t cur_block_size = ctx->cur_block_size;
const uint32_t cur_idx_ct = (((tidx + 1) * cur_block_size) / calc_thread_ct) - ((tidx * cur_block_size) / calc_thread_ct);
uintptr_t variant_uidx_base;
uintptr_t cur_bits;
BitIter1Start(variant_subset, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits);
for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) {
const uint32_t variant_uidx = BitIter1(variant_subset, &variant_uidx_base, &cur_bits);
uintptr_t allele_idx_offset_base;
if (!allele_idx_offsets) {
allele_idx_offset_base = variant_uidx * 2;
} else {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
if (cur_allele_ct == 2) {
if (allele_freqs) {
const double ref_freq = allele_freqs[allele_idx_offset_base - variant_uidx];
ehet = 2 * ref_freq * (1 - ref_freq);
if (ehet < kSmallishEpsilon) {
++monomorphic_ct;
continue;
}
}
uint32_t difflist_common_geno;
uint32_t difflist_len;
const PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_simple_difflist_len, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
if (unlikely(reterr)) {
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
goto HetThread_err;
}
if (difflist_common_geno != UINT32_MAX) {
ZeroTrailingNyps(difflist_len, raregeno);
const uint32_t word_ct = NypCtToWordCt(difflist_len);
if (!allele_freqs) {
STD_ARRAY_DECL(uint32_t, 4, genocounts);
genocounts[0] = 0;
genocounts[1] = 0;
genocounts[2] = 0;
genocounts[3] = 0;
if (word_ct) {
const uint32_t word_ct_m1 = word_ct - 1;
uint32_t loop_len = kBitsPerWordD2;
for (uint32_t widx = 0; ; ++widx) {
if (widx >= word_ct_m1) {
if (widx > word_ct_m1) {
break;
}
loop_len = ModNz(difflist_len, kBitsPerWordD2);
}
const uint32_t difflist_idx_base = widx * kBitsPerWordD2;
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[difflist_idx_base]);
uintptr_t raregeno_word = raregeno[widx];
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uint32_t sample_idx = cur_difflist_sample_ids[uii];
genocounts[raregeno_word & 3] += IsSet(founder_info_collapsed, sample_idx);
raregeno_word >>= 2;
}
}
}
genocounts[difflist_common_geno] += founder_ct - difflist_len;
const uint32_t numer1 = 2 * genocounts[0] + genocounts[1];
const uint32_t numer2 = genocounts[1] + 2 * genocounts[2];
if ((!numer1) || (!numer2)) {
++monomorphic_ct;
continue;
}
const uint32_t denom = numer1 + numer2;
ehet = 2 * S_CAST(double, numer1) * S_CAST(double, numer2) / ((S_CAST(double, denom)) * S_CAST(double, denom - 1));
}
if (difflist_common_geno != 3) {
ehet_base += ehet;
++nobs_base;
for (uint32_t widx = 0; widx != word_ct; ++widx) {
const uintptr_t raregeno_word = raregeno[widx];
const uint32_t difflist_idx_base = widx * kBitsPerWordD2;
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[difflist_idx_base]);
uintptr_t het_word = (raregeno_word & kMask5555) & (~(raregeno_word >> 1));
while (het_word) {
const uint32_t difflist_idx_lowbits = ctzw(het_word) / 2;
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits];
ohets[sample_idx] += 1;
het_word &= het_word - 1;
}
uintptr_t missing_word = (raregeno_word & kMask5555) & (raregeno_word >> 1);
while (missing_word) {
const uint32_t difflist_idx_lowbits = ctzw(missing_word) / 2;
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits];
ehet_incrs[sample_idx] -= ehet;
nobs_incrs[sample_idx] -= 1;
missing_word &= missing_word - 1;
}
}
} else {
if (!word_ct) {
++monomorphic_ct;
continue;
}
const uint32_t word_ct_m1 = word_ct - 1;
uint32_t loop_len = kBitsPerWordD2;
for (uint32_t widx = 0; ; ++widx) {
if (widx >= word_ct_m1) {
if (widx > word_ct_m1) {
break;
}
loop_len = ModNz(difflist_len, kBitsPerWordD2);
}
uintptr_t raregeno_word = raregeno[widx];
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uint32_t sample_idx = cur_difflist_sample_ids[uii];
ohets[sample_idx] += raregeno_word & 1;
ehet_incrs[sample_idx] += ehet;
nobs_incrs[sample_idx] += 1;
raregeno_word >>= 2;
}
}
}
continue;
}
ZeroTrailingNyps(sample_ct, genovec);
if (!allele_freqs) {
STD_ARRAY_DECL(uint32_t, 4, genocounts);
GenoarrCountSubsetFreqs(genovec, founder_info_interleaved_vec, sample_ct, founder_ct, genocounts);
const uint32_t numer1 = 2 * genocounts[0] + genocounts[1];
const uint32_t numer2 = genocounts[1] + 2 * genocounts[2];
if ((!numer1) || (!numer2)) {
++monomorphic_ct;
continue;
}
const uint32_t denom = numer1 + numer2;
ehet = 2 * S_CAST(double, numer1) * S_CAST(double, numer2) / ((S_CAST(double, denom)) * S_CAST(double, denom - 1));
}
} else {
// multiallelic
if (allele_freqs) {
const double* cur_allele_freqs = &(allele_freqs[allele_idx_offset_base - variant_uidx]);
const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1;
double freq_sum = 0.0;
double freq_ssq = 0.0;
for (uint32_t aidx = 0; aidx != cur_allele_ct_m1; ++aidx) {
const double cur_freq = cur_allele_freqs[aidx];
freq_sum += cur_freq;
freq_ssq += cur_freq * cur_freq;
}
const double last_allele_freq = 1.0 - freq_sum;
ehet = 1.0 - freq_ssq - last_allele_freq * last_allele_freq;
if (ehet < kSmallishEpsilon) {
++monomorphic_ct;
continue;
}
}
const PglErr reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv);
if (unlikely(reterr)) {
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
goto HetThread_err;
}
const uint32_t patch_10_ct = pgv.patch_10_ct;
const AlleleCode* patch_10_vals = pgv.patch_10_vals;
if (!allele_freqs) {
STD_ARRAY_DECL(uint32_t, 4, genocounts);
GenoarrCountSubsetFreqs(genovec, founder_info_interleaved_vec, sample_ct, founder_ct, genocounts);
allele_nobs[0] = 2 * genocounts[0] + genocounts[1];
allele_nobs[1] = genocounts[1] + 2 * genocounts[2];
const uint32_t denom = allele_nobs[0] + allele_nobs[1];
if (!denom) {
++monomorphic_ct;
continue;
}
ZeroU32Arr(cur_allele_ct - 2, &(allele_nobs[2]));
const uint32_t patch_01_ct = pgv.patch_01_ct;
if (patch_01_ct) {
const uintptr_t* patch_01_set = pgv.patch_01_set;
const AlleleCode* patch_01_vals = pgv.patch_01_vals;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_01_set[0];
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits);
allele_nobs[patch_01_vals[uii]] += IsSet(founder_info_collapsed, sample_idx);
}
allele_nobs[1] -= PopcountWordsIntersect(founder_info_collapsed, patch_01_set, sample_ctl);
}
if (patch_10_ct) {
const uintptr_t* patch_10_set = pgv.patch_10_set;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_10_set[0];
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
if (IsSet(founder_info_collapsed, sample_idx)) {
allele_nobs[patch_10_vals[2 * uii]] += 1;
allele_nobs[patch_10_vals[2 * uii + 1]] += 1;
}
}
allele_nobs[1] -= 2 * PopcountWordsIntersect(founder_info_collapsed, patch_10_set, sample_ctl);
}
uint64_t allele_nobs_ssq = 0;
for (uint32_t uii = 0; uii != cur_allele_ct; ++uii) {
const uintptr_t cur_allele_nobs = allele_nobs[uii];
allele_nobs_ssq += S_CAST(uint64_t, cur_allele_nobs) * cur_allele_nobs;
}
const double denom_d = S_CAST(double, denom);
ehet = (1.0 - (S_CAST(double, allele_nobs_ssq) / (denom_d * denom_d))) * (denom_d / S_CAST(double, denom - 1));
}
if (patch_10_ct) {
// For every altx/alty genotype where x and y are different, change
// the genovec entry from 2 to 1.
const uintptr_t* patch_10_set = pgv.patch_10_set;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_10_set[0];
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const AlleleCode a0 = patch_10_vals[uii * 2];
const AlleleCode a1 = patch_10_vals[uii * 2 + 1];
if (a0 != a1) {
const uintptr_t widx = sample_idx / kBitsPerWordD2;
const uint32_t bit_shift_ct = 2 * (sample_idx % kBitsPerWordD2);
genovec[widx] ^= (3 * k1LU) << bit_shift_ct;
}
}
}
}
ehet_base += ehet;
++nobs_base;
// See e.g. UpdateDenseSampleCounts2().
const VecW m1 = VCONST_W(kMask5555);
const VecW* genovvec = R_CAST(const VecW*, genovec);
for (uint32_t vidx = 0; vidx != acc2_vec_ct; ++vidx) {
const VecW vv = genovvec[vidx];
const VecW vv_shifted = vecw_srli(vv, 1);
const VecW vv_lo_only = vv & m1;
scrambled_ohets[vidx] += vecw_and_notfirst(vv_shifted, vv_lo_only);
}
--dense_ct_rem3;
if (!dense_ct_rem3) {
VecW* acc4 = &(scrambled_ohets[acc2_vec_ct]);
Vcount0Incr2To4(acc2_vec_ct, scrambled_ohets, acc4);
--dense_ct_rem15d3;
if (!dense_ct_rem15d3) {
const uint32_t acc4_vec_ct = acc2_vec_ct * 2;
VecW* acc8 = &(acc4[acc4_vec_ct]);
Vcount0Incr4To8(acc4_vec_ct, acc4, acc8);
--dense_ct_rem255d15;
if (!dense_ct_rem255d15) {
const uint32_t acc8_vec_ct = acc4_vec_ct * 2;
VecW* acc32 = &(acc8[acc8_vec_ct]);
Vcount0Incr8To32(acc8_vec_ct, acc8, acc32);
dense_ct_rem255d15 = 17;
}
dense_ct_rem15d3 = 5;
}
dense_ct_rem3 = 3;
}
for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
const uintptr_t geno_word = genovec[widx];
uintptr_t missing_word = geno_word & (geno_word >> 1) & kMask5555;
if (!missing_word) {
continue;
}
uint32_t sample_idx_base = widx * kBitsPerWordD2;
double* cur_ehet_incrs = &(ehet_incrs[sample_idx_base]);
int32_t* cur_nobs_incrs = &(nobs_incrs[sample_idx_base]);
do {
const uint32_t sample_idx_lowbits = ctzw(missing_word) / 2;
cur_ehet_incrs[sample_idx_lowbits] -= ehet;
cur_nobs_incrs[sample_idx_lowbits] -= 1;
missing_word &= missing_word - 1;
} while (missing_word);
}
}
} while (!THREAD_BLOCK_FINISH(arg));
{
ctx->thread_ehet_base[tidx] = ehet_base;
ctx->thread_nobs_base[tidx] = nobs_base;
ctx->thread_monomorphic_ct[tidx] = monomorphic_ct;
VecW* acc4 = &(scrambled_ohets[acc2_vec_ct]);
VcountIncr2To4(scrambled_ohets, acc2_vec_ct, acc4);
const uint32_t acc4_vec_ct = acc2_vec_ct * 2;
VecW* acc8 = &(acc4[acc4_vec_ct]);
VcountIncr4To8(acc4, acc4_vec_ct, acc8);
const uint32_t acc8_vec_ct = acc4_vec_ct * 2;
VecW* acc32 = &(acc8[acc8_vec_ct]);
VcountIncr8To32(acc8, acc8_vec_ct, acc32);
uint32_t* acc32_alias = R_CAST(uint32_t*, acc32);
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t scrambled_idx = VcountScramble2(sample_idx);
ohets[sample_idx] += acc32_alias[scrambled_idx];
}
}
while (0) {
HetThread_err:
UpdateU64IfSmaller(new_err_info, &ctx->err_info);
THREAD_BLOCK_FINISH(arg);
break;
}
THREAD_RETURN;
}
PglErr HetCalcMain(const uintptr_t* sample_include, const uintptr_t* variant_subset, const uintptr_t* allele_idx_offsets, const double* allele_freqs, const uintptr_t* founder_info, const char* calcstr, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t founder_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t small_sample, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, uint32_t** ohets_ptr, double** ehet_incrs_ptr, int32_t** nobs_incrs_ptr, double* ehet_base_ptr, int32_t* nobs_base_ptr) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
ThreadGroup tg;
PreinitThreads(&tg);
HetCtx ctx;
{
// return values
if (unlikely(bigstack_alloc_u32(sample_ct, ohets_ptr) ||
bigstack_alloc_d(sample_ct, ehet_incrs_ptr) ||
bigstack_alloc_i32(sample_ct, nobs_incrs_ptr))) {
goto HetCalcMain_ret_NOMEM;
}
bigstack_mark = g_bigstack_base;
ctx.variant_subset = variant_subset;
ctx.allele_idx_offsets = allele_idx_offsets;
ctx.sample_include = sample_include;
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
uint32_t* sample_include_cumulative_popcounts;
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts))) {
goto HetCalcMain_ret_NOMEM;
}
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
ctx.founder_info_collapsed = nullptr;
ctx.founder_info_interleaved_vec = nullptr;
ctx.allele_freqs = allele_freqs;
if (small_sample) {
const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
uintptr_t* founder_info_collapsed;
uintptr_t* founder_info_interleaved_vec;
if (unlikely(bigstack_alloc_w(sample_ctaw, &founder_info_collapsed) ||
bigstack_alloc_w(sample_ctaw, &founder_info_interleaved_vec))) {
goto HetCalcMain_ret_NOMEM;
}
CopyBitarrSubset(founder_info, sample_include, sample_ct, founder_info_collapsed);
const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
ZeroWArr(sample_ctaw - sample_ctl, &(founder_info_collapsed[sample_ctl]));
FillInterleavedMaskVec(founder_info_collapsed, sample_ctaw / kWordsPerVec, founder_info_interleaved_vec);
ctx.founder_info_collapsed = founder_info_collapsed;
ctx.founder_info_interleaved_vec = founder_info_interleaved_vec;
ctx.allele_freqs = nullptr;
}
ctx.sample_ct = sample_ct;
ctx.founder_ct = founder_ct;
uint32_t calc_thread_ct = max_thread_ct;
if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.raregenos) ||
bigstack_alloc_u32p(calc_thread_ct, &ctx.difflist_sample_id_bufs) ||
bigstack_alloc_vp(calc_thread_ct, &ctx.scrambled_ohet_bufs) ||
bigstack_alloc_d(calc_thread_ct, &ctx.thread_ehet_base) ||
bigstack_alloc_u32(calc_thread_ct, &ctx.thread_nobs_base) ||
bigstack_alloc_u32(calc_thread_ct, &ctx.thread_monomorphic_ct) ||
bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_ohets) ||
bigstack_alloc_dp(calc_thread_ct, &ctx.thread_ehet_incrs) ||
bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_nobs_incrs))) {
goto HetCalcMain_ret_NOMEM;
}
const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec);
const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec);
const uint32_t mhc_needed = (max_allele_ct > 2);
uintptr_t allele_nobs_vec_ct = 0;
ctx.allele_nobs_bufs = nullptr;
if (mhc_needed) {
if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.allele_nobs_bufs))) {
goto HetCalcMain_ret_NOMEM;
}
allele_nobs_vec_ct = DivUp(max_allele_ct, kInt32PerVec);
}
const uintptr_t acc2_vec_ct = NypCtToVecCt(sample_ct);
const uintptr_t scrambled_ohet_vec_ct = acc2_vec_ct * 23;
const uintptr_t sample_ct_i32v = DivUp(sample_ct, kInt32PerVec);
const uintptr_t sample_ct_dv = DivUp(sample_ct * sizeof(double), kBytesPerVec);
const uintptr_t thread_xalloc_vec_ct = raregeno_vec_ct + difflist_sample_id_vec_ct + allele_nobs_vec_ct + scrambled_ohet_vec_ct + 2 * sample_ct_i32v + sample_ct_dv;
const uintptr_t thread_xalloc_cacheline_ct = DivUp(thread_xalloc_vec_ct, kVecsPerCacheline);
STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
ctx.thread_read_mhc = nullptr;
uint32_t read_block_size;
if (unlikely(PgenMtLoadInit(ctx.variant_subset, raw_sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
goto HetCalcMain_ret_NOMEM;
}
if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
goto HetCalcMain_ret_NOMEM;
}
ctx.err_info = (~0LLU) << 32;
assert(bigstack_left() >= thread_xalloc_cacheline_ct * kCacheline * calc_thread_ct);
for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
unsigned char* cur_alloc = S_CAST(unsigned char*, bigstack_alloc_raw(thread_xalloc_cacheline_ct * kCacheline));
ctx.raregenos[tidx] = R_CAST(uintptr_t*, cur_alloc);
cur_alloc = &(cur_alloc[raregeno_vec_ct * kBytesPerVec]);
ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[difflist_sample_id_vec_ct * kBytesPerVec]);
if (mhc_needed) {
ctx.allele_nobs_bufs[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[allele_nobs_vec_ct * kBytesPerVec]);
}
ctx.scrambled_ohet_bufs[tidx] = R_CAST(VecW*, cur_alloc);
cur_alloc = &(cur_alloc[scrambled_ohet_vec_ct * kBytesPerVec]);
if (!tidx) {
ctx.thread_ohets[0] = *ohets_ptr;
ctx.thread_ehet_incrs[0] = *ehet_incrs_ptr;
ctx.thread_nobs_incrs[0] = *nobs_incrs_ptr;
} else {
ctx.thread_ohets[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]);
ctx.thread_ehet_incrs[tidx] = R_CAST(double*, cur_alloc);
cur_alloc = &(cur_alloc[sample_ct_dv * kBytesPerVec]);
ctx.thread_nobs_incrs[tidx] = R_CAST(int32_t*, cur_alloc);
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]);
assert(cur_alloc <= g_bigstack_base);
}
}
SetThreadFuncAndData(HetThread, &ctx, &tg);
logprintf("%s: ", calcstr);
fputs("0%", stdout);
fflush(stdout);
uint32_t pct = 0;
uint32_t parity = 0;
uint32_t read_block_idx = 0;
uint32_t next_print_variant_idx = variant_ct / 100;
for (uint32_t variant_idx = 0; ; ) {
const uint32_t cur_block_size = MultireadNonempty(ctx.variant_subset, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
if (unlikely(reterr)) {
goto HetCalcMain_ret_PGR_FAIL;
}
if (variant_idx) {
JoinThreads(&tg);
reterr = S_CAST(PglErr, ctx.err_info);
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, ctx.err_info >> 32);
goto HetCalcMain_ret_1;
}
}
if (!IsLastBlock(&tg)) {
ctx.cur_block_size = cur_block_size;
ComputeUidxStartPartition(ctx.variant_subset, cur_block_size, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
if (variant_idx + cur_block_size == variant_ct) {
DeclareLastThreadBlock(&tg);
}
if (unlikely(SpawnThreads(&tg))) {
goto HetCalcMain_ret_THREAD_CREATE_FAIL;
}
}
parity = 1 - parity;
if (variant_idx == variant_ct) {
break;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
}
++read_block_idx;
variant_idx += cur_block_size;
pgfip->block_base = main_loadbufs[parity];
}
double ehet_base = ctx.thread_ehet_base[0];
uint32_t nobs_base = ctx.thread_nobs_base[0];
uint32_t monomorphic_ct = ctx.thread_monomorphic_ct[0];
uint32_t* ohets = *ohets_ptr;
double* ehet_incrs = *ehet_incrs_ptr;
int32_t* nobs_incrs = *nobs_incrs_ptr;
for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
ehet_base += ctx.thread_ehet_base[tidx];
nobs_base += ctx.thread_nobs_base[tidx];
monomorphic_ct += ctx.thread_monomorphic_ct[tidx];
U32CastVecAdd(ctx.thread_ohets[tidx], sample_ct_i32v, ohets);
const double* src = ctx.thread_ehet_incrs[tidx];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
ehet_incrs[sample_idx] += src[sample_idx];
}
I32CastVecAdd(ctx.thread_nobs_incrs[tidx], sample_ct_i32v, nobs_incrs);
}
if (pct > 10) {
putc_unlocked('\b', stdout);
}
fputs("\b\b", stdout);
logputs("done.\n");
if (monomorphic_ct) {
logerrprintfww("Warning: %u variant%s skipped because %s monomorphic.%s\n", monomorphic_ct, (monomorphic_ct == 1)? "" : "s", (monomorphic_ct == 1)? "it was" : "they were", small_sample? "" : " You may want to use --read-freq to provide more accurate allele frequency estimates.");
}
*ehet_base_ptr = ehet_base;
*nobs_base_ptr = nobs_base;
}
while (0) {
HetCalcMain_ret_NOMEM:
reterr = kPglRetNomem;
break;
HetCalcMain_ret_PGR_FAIL:
PgenErrPrintN(reterr);
break;
HetCalcMain_ret_THREAD_CREATE_FAIL:
reterr = kPglRetThreadCreateFail;
break;
}
HetCalcMain_ret_1:
CleanupThreads(&tg);
BigstackReset(bigstack_mark);
pgfip->block_base = nullptr;
return reterr;
}
PglErr HetReport(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const double* allele_freqs, const uintptr_t* founder_info, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t founder_ct, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t max_allele_ct, HetFlags flags, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
char* cswritep = nullptr;
CompressStreamState css;
PglErr reterr = kPglRetSuccess;
PreinitCstream(&css);
{
if (IsSet(cip->haploid_mask, 0)) {
logerrputs("Error: --het cannot be used on haploid genomes.\n");
goto HetReport_ret_INCONSISTENT_INPUT;
}
const uint32_t small_sample = (flags / kfHetSmallSample) & 1;
if (small_sample && (!founder_ct)) {
logerrputs("Error: '--het small-sample' requires founders. (--make-founders may come in\nhandy here.\n)");
goto HetReport_ret_INCONSISTENT_INPUT;
}
const uintptr_t* autosomal_variant_include = orig_variant_include;
uint32_t autosomal_variant_ct = orig_variant_ct;
reterr = ConditionalAllocateNonAutosomalVariants(cip, "--het", raw_variant_ct, &autosomal_variant_include, &autosomal_variant_ct);
if (!autosomal_variant_ct) {
goto HetReport_ret_NO_VARIATION;
}
const uint32_t output_zst = flags & kfHetZs;
OutnameZstSet(".het", output_zst, outname_end);
reterr = InitCstreamAlloc(outname, 0, output_zst, 1, 2 * kCompressStreamBlock, &css, &cswritep);
if (unlikely(reterr)) {
goto HetReport_ret_1;
}
*cswritep++ = '#';
const uint32_t col_fid = FidColIsRequired(siip, flags / kfHetColMaybefid);
if (col_fid) {
cswritep = strcpya_k(cswritep, "FID\t");
}
cswritep = strcpya_k(cswritep, "IID");
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfHetColMaybesid);
if (col_sid) {
cswritep = strcpya_k(cswritep, "\tSID");
}
const uint32_t col_hom = (flags / kfHetColHom) & 1;
if (col_hom) {
cswritep = strcpya_k(cswritep, "\tO(HOM)\tE(HOM)");
}
const uint32_t col_het = (flags / kfHetColHet) & 1;
if (col_het) {
cswritep = strcpya_k(cswritep, "\tO(HET)\tE(HET)");
}
const uint32_t col_nobs = (flags / kfHetColNobs) & 1;
if (col_nobs) {
cswritep = strcpya_k(cswritep, "\tOBS_CT");
}
const uint32_t col_f = (flags / kfHetColF) & 1;
if (col_f) {
cswritep = strcpya_k(cswritep, "\tF");
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto HetReport_ret_WRITE_FAIL;
}
uint32_t* ohets;
double* ehet_incrs;
int32_t* nobs_incrs;
double ehet_base;
int32_t nobs_base;
reterr = HetCalcMain(sample_include, autosomal_variant_include, allele_idx_offsets, allele_freqs, founder_info, "--het", raw_sample_ct, sample_ct, founder_ct, raw_variant_ct, autosomal_variant_ct, max_allele_ct, small_sample, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, &ohets, &ehet_incrs, &nobs_incrs, &ehet_base, &nobs_base);
if (unlikely(reterr)) {
goto HetReport_ret_1;
}
const char* sample_ids = siip->sample_ids;
const char* sids = siip->sids;
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
const uintptr_t max_sid_blen = siip->max_sid_blen;
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
cswritep = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep);
const uint32_t ohet = ohets[sample_idx];
const double ehet = ehet_base + ehet_incrs[sample_idx];
const uint32_t nobs = nobs_base + nobs_incrs[sample_idx];
if (col_hom) {
*cswritep++ = '\t';
cswritep = u32toa_x(nobs - ohet, '\t', cswritep);
cswritep = dtoa_g(u31tod(nobs) - ehet, cswritep);
}
if (col_het) {
*cswritep++ = '\t';
cswritep = u32toa_x(ohet, '\t', cswritep);
cswritep = dtoa_g(ehet, cswritep);
}
if (col_nobs) {
*cswritep++ = '\t';
cswritep = u32toa(nobs, cswritep);
}
if (col_f) {
*cswritep++ = '\t';
cswritep = dtoa_g(1.0 - u31tod(ohet) / ehet, cswritep);
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(&css, &cswritep))) {
goto HetReport_ret_WRITE_FAIL;
}
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto HetReport_ret_WRITE_FAIL;
}
logprintfww("--het: Results written to %s .\n", outname);
}
while (0) {
HetReport_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
HetReport_ret_NO_VARIATION:
logerrputs("Error: --het requires at least one polymorphic autosomal variant.\n");
HetReport_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
HetReport_ret_1:
CswriteCloseCond(&css, cswritep);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr CheckOrImputeSex(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const double* allele_freqs, const CheckSexInfo* csip, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t max_allele_ct, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, uintptr_t* sex_nm, uintptr_t* sex_male, PgenFileInfo* pgfip, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
FILE* outfile = nullptr;
PglErr reterr = kPglRetSuccess;
{
const CheckSexFlags flags = csip->flags;
const char* flagstr = (flags & kfCheckSexImpute)? "--impute-sex" : "--check-sex";
if (IsSet(cip->haploid_mask, 0)) {
snprintf(g_logbuf, kLogbufSize, "Error: %s cannot be used on haploid genomes.\n", flagstr);
goto CheckOrImputeSex_ret_INCONSISTENT_INPUT_2;
}
double* xfs = nullptr;
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
double max_female_xf = csip->max_female_xf;
double min_male_xf = csip->min_male_xf;
uint32_t used_variant_ct_x = 0;
uint32_t x_code;
if ((flags & kfCheckSexUseX) && XymtExists(cip, kChrOffsetX, &x_code)) {
used_variant_ct_x = CountChrVariantsUnsafe(orig_variant_include, cip, x_code);
if (used_variant_ct_x) {
if (max_female_xf == -1.0) {
max_female_xf = PrevFloat64(min_male_xf);
} else if (min_male_xf == -1.0) {
min_male_xf = NextFloat64(max_female_xf);
}
uintptr_t* variant_include_x;
if (unlikely(bigstack_alloc_d(sample_ct, &xfs) ||
bigstack_alloc_w(raw_variant_ctl, &variant_include_x))) {
goto CheckOrImputeSex_ret_NOMEM;
}
const uint32_t x_fo_idx = cip->chr_idx_to_foidx[x_code];
const uint32_t x_start = cip->chr_fo_vidx_start[x_fo_idx];
const uint32_t x_end = cip->chr_fo_vidx_start[x_fo_idx + 1];
const uint32_t x_start_widx = x_start / kBitsPerWord;
const uint32_t x_end_widx = (x_end + kBitsPerWord - 1) / kBitsPerWord;
memcpy(&(variant_include_x[x_start_widx]), &(orig_variant_include[x_start_widx]), (x_end_widx - x_start_widx) * sizeof(intptr_t));
if (x_start) {
ClearBitsNz(0, x_start, variant_include_x);
}
// bugfix (17 Dec 2024): trailing bits must also be zeroed out
const uint32_t raw_variant_ct_rounded_up = RoundUpPow2(raw_variant_ct, kBitsPerWord);
if (x_end < raw_variant_ct_rounded_up) {
ClearBitsNz(x_end, raw_variant_ct_rounded_up, variant_include_x);
}
// Don't actually need nobs.
uint32_t* ohets;
double* ehet_incrs;
int32_t* nobs_incrs;
double ehet_base;
int32_t nobs_base;
reterr = HetCalcMain(sample_include, variant_include_x, allele_idx_offsets, allele_freqs, nullptr, (flags & kfCheckSexImpute)? "--impute-sex chrX" : "--check-sex chrX", raw_sample_ct, sample_ct, sample_ct, raw_variant_ct, used_variant_ct_x, max_allele_ct, 0, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, &ohets, &ehet_incrs, &nobs_incrs, &ehet_base, &nobs_base);
if (unlikely(reterr)) {
goto CheckOrImputeSex_ret_1;
}
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t ohet = ohets[sample_idx];
const double ehet = ehet_base + ehet_incrs[sample_idx];
xfs[sample_idx] = 1.0 - u31tod(ohet) / ehet;
}
BigstackReset(variant_include_x);
}
}
uint32_t* y_valid_geno_cts = nullptr;
uint32_t max_female_ycount = csip->max_female_ycount;
uint32_t min_male_ycount = csip->min_male_ycount;
uint32_t used_variant_ct_y = 0;
uint32_t y_code = 0;
if ((flags & kfCheckSexUseY) && XymtExists(cip, kChrOffsetY, &y_code)) {
used_variant_ct_y = CountChrVariantsUnsafe(orig_variant_include, cip, y_code);
if (used_variant_ct_y) {
if (max_female_ycount == UINT32_MAX) {
if (min_male_ycount != UINT32_MAX) {
max_female_ycount = min_male_ycount - 1;
} else {
// No ycount condition specified. yrate condition will be merged
// correctly if we initialize max_female_ycount=UINT32_MAX,
// min_male_ycount=0.
min_male_ycount = 0;
}
} else if (min_male_ycount == UINT32_MAX) {
min_male_ycount = max_female_ycount + 1;
}
{
const double max_female_yrate = csip->max_female_yrate;
const double min_male_yrate = csip->min_male_yrate;
if (max_female_yrate != -1.0) {
const uint32_t uii = S_CAST(int32_t, max_female_yrate * used_variant_ct_y);
if (uii < max_female_ycount) {
max_female_ycount = uii;
}
}
if (min_male_yrate != -1.0) {
const uint32_t uii = used_variant_ct_y - S_CAST(int32_t, (1.0 - min_male_yrate) * used_variant_ct_y);
if (uii > min_male_ycount) {
min_male_ycount = uii;
}
}
}
uintptr_t* variant_include_y;
uint32_t* sample_missing_hc_cts;
uint32_t* sample_hethap_cts;
if (unlikely(bigstack_alloc_u32(sample_ct, &y_valid_geno_cts) ||
bigstack_alloc_w(raw_variant_ctl, &variant_include_y) ||
bigstack_alloc_u32(raw_sample_ct, &sample_missing_hc_cts) ||
bigstack_alloc_u32(raw_sample_ct, &sample_hethap_cts))) {
goto CheckOrImputeSex_ret_NOMEM;
}
const uint32_t y_fo_idx = cip->chr_idx_to_foidx[y_code];
const uint32_t y_start = cip->chr_fo_vidx_start[y_fo_idx];
const uint32_t y_end = cip->chr_fo_vidx_start[y_fo_idx + 1];
const uint32_t y_start_widx = y_start / kBitsPerWord;
const uint32_t y_end_widx = (y_end + kBitsPerWord - 1) / kBitsPerWord;
memcpy(&(variant_include_y[y_start_widx]), &(orig_variant_include[y_start_widx]), (y_end_widx - y_start_widx) * sizeof(intptr_t));
if (y_start) {
ClearBitsNz(0, y_start, variant_include_y);
}
const uint32_t raw_variant_ct_rounded_up = RoundUpPow2(raw_variant_ct, kBitsPerWord);
if (y_end < raw_variant_ct_rounded_up) {
ClearBitsNz(y_end, raw_variant_ct_rounded_up, variant_include_y);
}
logprintf("%s: ", flagstr);
reterr = LoadSampleMissingCts(sample_include, sample_include, variant_include_y, cip, "chrY valid genotype call", raw_variant_ct, used_variant_ct_y, raw_sample_ct, 0, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, sample_missing_hc_cts, nullptr, sample_hethap_cts);
if (unlikely(reterr)) {
goto CheckOrImputeSex_ret_1;
}
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
y_valid_geno_cts[sample_idx] = used_variant_ct_y - sample_missing_hc_cts[sample_uidx] - sample_hethap_cts[sample_uidx];
}
BigstackReset(variant_include_y);
}
}
if (unlikely((!used_variant_ct_x) && (!used_variant_ct_y))) {
snprintf(g_logbuf, kLogbufSize, "Error: %s: No usable variants.\n", flagstr);
goto CheckOrImputeSex_ret_INCONSISTENT_INPUT_2;
}
uintptr_t* imputed_sex_nm;
uintptr_t* imputed_sex_male;
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &imputed_sex_nm) ||
bigstack_calloc_w(raw_sample_ctl, &imputed_sex_male))) {
goto CheckOrImputeSex_ret_NOMEM;
}
snprintf(outname_end, kMaxOutfnameExtBlen, ".sexcheck");
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
goto CheckOrImputeSex_ret_OPEN_FAIL;
}
char* textbuf_flush = &(g_textbuf[kMaxMediumLine]);
char* write_iter = g_textbuf;
*write_iter++ = '#';
const uint32_t col_fid = FidColIsRequired(siip, flags / kfCheckSexColMaybefid);
if (col_fid) {
write_iter = strcpya_k(write_iter, "FID\t");
}
write_iter = strcpya_k(write_iter, "IID");
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfCheckSexColMaybesid);
if (col_sid) {
write_iter = strcpya_k(write_iter, "\tSID");
}
const uint32_t col_pedsex = (flags / kfCheckSexColPedsex) & 1;
if (col_pedsex) {
write_iter = strcpya_k(write_iter, "\tPEDSEX");
}
write_iter = strcpya_k(write_iter, "\tSNPSEX");
const uint32_t col_status = (flags / kfCheckSexColStatus) & 1;
if (col_status) {
write_iter = strcpya_k(write_iter, "\tSTATUS");
}
const uint32_t col_xf = used_variant_ct_x && (flags & kfCheckSexColXF);
if (col_xf) {
write_iter = strcpya_k(write_iter, "\tF");
}
const uint32_t col_ycount = used_variant_ct_y && (flags & kfCheckSexColYcount);
if (col_ycount) {
write_iter = strcpya_k(write_iter, "\tYCOUNT");
}
const uint32_t col_yrate = used_variant_ct_y && (flags & kfCheckSexColYrate);
if (col_yrate) {
write_iter = strcpya_k(write_iter, "\tYRATE");
}
const uint32_t col_yobs = used_variant_ct_y && (flags & kfCheckSexColYobs);
if (col_yobs) {
write_iter = strcpya_k(write_iter, "\tYOBS");
}
AppendBinaryEoln(&write_iter);
const double y_denom = used_variant_ct_y? (1.0 / u31tod(used_variant_ct_y)) : 0.0;
const char* sample_ids = siip->sample_ids;
const char* sids = siip->sids;
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
const uintptr_t max_sid_blen = siip->max_sid_blen;
uintptr_t sample_uidx_base = 0;
uintptr_t cur_bits = sample_include[0];
double cur_xf = 0.0;
uint32_t cur_ycount = 0;
uint32_t problem_ct = 0;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
write_iter = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter);
const uint32_t ped_nm = IsSet(sex_nm, sample_uidx);
const uint32_t ped_male = IsSet(sex_male, sample_uidx);
if (col_pedsex) {
*write_iter++ = '\t';
if (ped_nm) {
*write_iter++ = '2' - ped_male;
} else {
write_iter = strcpya_k(write_iter, "NA");
}
}
uint32_t not_male = 0;
uint32_t not_female = 0;
if (xfs) {
cur_xf = xfs[sample_idx];
if (cur_xf <= max_female_xf) {
not_male = 1;
} else if (cur_xf >= min_male_xf) {
not_female = 1;
} else {
not_male = 1;
not_female = 1;
}
}
if (y_valid_geno_cts) {
cur_ycount = y_valid_geno_cts[sample_idx];
if (cur_ycount <= max_female_ycount) {
not_male = 1;
} else if (cur_ycount >= min_male_ycount) {
not_female = 1;
} else {
not_male = 1;
not_female = 1;
}
}
*write_iter++ = '\t';
uint32_t is_problem;
if (not_male) {
if (not_female) {
write_iter = strcpya_k(write_iter, "NA");
is_problem = 1;
} else {
*write_iter++ = '2';
SetBit(sample_uidx, imputed_sex_nm);
is_problem = (!ped_nm) || ped_male;
}
} else {
*write_iter++ = '1';
SetBit(sample_uidx, imputed_sex_nm);
SetBit(sample_uidx, imputed_sex_male);
is_problem = (!ped_nm) || (!ped_male);
}
problem_ct += is_problem;
if (col_status) {
if (is_problem) {
write_iter = strcpya_k(write_iter, "\tPROBLEM");
} else {
write_iter = strcpya_k(write_iter, "\tOK");
}
}
if (col_xf) {
*write_iter++ = '\t';
write_iter = dtoa_g(cur_xf, write_iter);
}
if (col_ycount) {
*write_iter++ = '\t';
write_iter = u32toa(cur_ycount, write_iter);
}
if (col_yrate) {
*write_iter++ = '\t';
write_iter = dtoa_g(u31tod(cur_ycount) * y_denom, write_iter);
}
if (col_yobs) {
*write_iter++ = '\t';
write_iter = u32toa(used_variant_ct_y, write_iter);
}
AppendBinaryEoln(&write_iter);
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
goto CheckOrImputeSex_ret_WRITE_FAIL;
}
}
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
goto CheckOrImputeSex_ret_WRITE_FAIL;
}
write_iter = strcpya(g_logbuf, flagstr);
write_iter = strcpya_k(write_iter, ": ");
if (used_variant_ct_x) {
write_iter = u32toa(used_variant_ct_x, write_iter);
write_iter = strcpya_k(write_iter, " chrX variant");
if (used_variant_ct_x != 1) {
*write_iter++ = 's';
}
if (used_variant_ct_y) {
write_iter = strcpya_k(write_iter, " and ");
write_iter = u32toa(used_variant_ct_y, write_iter);
write_iter = strcpya_k(write_iter, " variant");
if (used_variant_ct_y != 1) {
*write_iter++ = 's';
}
}
} else {
write_iter = u32toa(used_variant_ct_y, write_iter);
write_iter = strcpya_k(write_iter, " variant");
if (used_variant_ct_y != 1) {
*write_iter++ = 's';
}
}
write_iter = strcpya_k(write_iter, " scanned, ");
if (flags & kfCheckSexImpute) {
memcpy(sex_nm, imputed_sex_nm, raw_sample_ctl * sizeof(intptr_t));
memcpy(sex_male, imputed_sex_male, raw_sample_ctl * sizeof(intptr_t));
const uint32_t imputed_nm_ct = PopcountWords(imputed_sex_nm, raw_sample_ctl);
const uint32_t imputed_male_ct = PopcountWords(imputed_sex_male, raw_sample_ctl);
write_iter = u32toa_x(imputed_nm_ct, '/', write_iter);
write_iter = u32toa(sample_ct, write_iter);
write_iter = strcpya_k(write_iter, " sex");
if (sample_ct != 1) {
write_iter = strcpya_k(write_iter, "es");
}
write_iter = strcpya_k(write_iter, " imputed (");
write_iter = u32toa(imputed_nm_ct - imputed_male_ct, write_iter);
write_iter = strcpya_k(write_iter, " female, ");
write_iter = u32toa(imputed_male_ct, write_iter);
write_iter = strcpya_k(write_iter, " male)");
} else {
write_iter = u32toa(problem_ct, write_iter);
write_iter = strcpya_k(write_iter, " problem");
if (problem_ct != 1) {
*write_iter++ = 's';
}
write_iter = strcpya_k(write_iter, " detected");
}
write_iter = strcpya_k(write_iter, ". Report written to ");
write_iter = memcpya(write_iter, outname, &(outname_end[strlen(".sexcheck")]) - outname);
strcpy_k(write_iter, " .\n");
WordWrapB(0);
logputsb();
}
while (0) {
CheckOrImputeSex_ret_NOMEM:
reterr = kPglRetNomem;
break;
CheckOrImputeSex_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
CheckOrImputeSex_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
CheckOrImputeSex_ret_INCONSISTENT_INPUT_2:
logerrputsb();
reterr = kPglRetInconsistentInput;
break;
}
CheckOrImputeSex_ret_1:
fclose_cond(outfile);
BigstackReset(bigstack_mark);
return reterr;
}
typedef struct FstCtxStruct {
const uintptr_t* cur_variant_include;
const uintptr_t* allele_idx_offsets;
const uintptr_t* sample_include;
const uint32_t* sample_include_cumulative_popcounts;
// sex_male_collapsed == nullptr unless chrX /w males
const uintptr_t* sex_male_collapsed;
const uint32_t* sample_to_pop_idx;
uint32_t* diploid_pop_sizes;
const uint32_t* haploid_pop_sizes;
uint32_t sample_ct;
uint32_t pop_ct;
PgenReader** pgr_ptrs;
uintptr_t** genovecs;
uintptr_t** thread_read_mhc;
uintptr_t** raregenos;
uint32_t** difflist_sample_id_bufs;
uint32_t** pop_geno_bufs;
uint32_t* read_variant_uidx_starts;
uint32_t cur_block_variant_ct; // .pgen iteration, not jackknife
uint64_t err_info;
// worker threads compute intermediate stats; parent thread computes final
// Fst estimates (to avoid O(pop_ct^2) space problem) and executes
// block-jackknife.
uint32_t* pop_nm_sample_cts[2];
uint32_t* pop_allele_obs_cts[2]; // major dimension = pop, minor = allele
// Hudson only
double* half_within[2];
// W-C only
uint32_t* pop_allele_het_cts[2];
} FstCtx;
THREAD_FUNC_DECL FstThread(void* raw_arg) {
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
const uintptr_t tidx = arg->tidx;
FstCtx* ctx = S_CAST(FstCtx*, arg->sharedp->context);
const uintptr_t* variant_include = ctx->cur_variant_include;
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
const uintptr_t* sample_include = ctx->sample_include;
PgenReader* pgrp = ctx->pgr_ptrs[tidx];
PgrSampleSubsetIndex pssi;
PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
// sex_male nullptr iff not chrX /w males
const uintptr_t* sex_male = ctx->sex_male_collapsed;
const uint32_t* sample_to_pop_idx = ctx->sample_to_pop_idx;
const uint32_t* diploid_pop_sizes = ctx->diploid_pop_sizes;
const uint32_t* haploid_pop_sizes = ctx->haploid_pop_sizes;
const uint32_t sample_ct = ctx->sample_ct;
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
const uint32_t sample_ctl2_m1 = sample_ctl2 - 1;
const uint32_t haploid_present = (sex_male != nullptr);
const uintptr_t pop_ct = ctx->pop_ct;
const uintptr_t pop_ct_x4 = pop_ct * 4;
uintptr_t* genovec = ctx->genovecs[tidx];
PgenVariant pgv;
pgv.genovec = genovec;
SetPgvThreadMhcNull(sample_ct, tidx, ctx->thread_read_mhc, &pgv);
uintptr_t* raregeno = ctx->raregenos[tidx];
uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx];
uint32_t* pop_geno_buf = ctx->pop_geno_bufs[tidx];
const uintptr_t pop_geno_buf_size = pop_ct_x4 << haploid_present;
// todo: tune this threshold
const uint32_t max_simple_difflist_len = sample_ct / 32;
const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
uint32_t allele_ct = 2;
uint32_t parity = 0;
uint64_t new_err_info = 0;
do {
uint32_t cur_idx_ct;
uintptr_t variant_uidx_base;
uintptr_t variant_include_bits;
uint32_t* pop_nm_sample_cts_iter;
uint32_t* pop_allele_obs_cts_iter;
double* half_within_iter;
uint32_t* pop_allele_het_cts_iter;
{
const uint32_t cur_block_variant_ct = ctx->cur_block_variant_ct;
const uint32_t first_variant_bidx = (tidx * cur_block_variant_ct) / calc_thread_ct;
cur_idx_ct = (((tidx + 1) * cur_block_variant_ct) / calc_thread_ct) - first_variant_bidx;
const uint32_t variant_uidx_start = ctx->read_variant_uidx_starts[tidx];
BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &variant_include_bits);
const uintptr_t allele_bidx = first_variant_bidx * 2 + CountExtraAlleles(variant_include, allele_idx_offsets, ctx->read_variant_uidx_starts[0], variant_uidx_start, 0);
// non-null iff Weir-Cockerham method, or OBS_CT .fst.var col requested
pop_nm_sample_cts_iter = ctx->pop_nm_sample_cts[parity];
if (pop_nm_sample_cts_iter) {
pop_nm_sample_cts_iter = &(pop_nm_sample_cts_iter[pop_ct * first_variant_bidx]);
}
pop_allele_obs_cts_iter = ctx->pop_allele_obs_cts[parity];
pop_allele_obs_cts_iter = &(pop_allele_obs_cts_iter[pop_ct * allele_bidx]);
// non-null iff Hudson
half_within_iter = ctx->half_within[parity];
if (half_within_iter) {
half_within_iter = &(half_within_iter[pop_ct * first_variant_bidx]);
}
// non-null iff W-C
pop_allele_het_cts_iter = ctx->pop_allele_het_cts[parity];
if (pop_allele_het_cts_iter) {
pop_allele_het_cts_iter = &(pop_allele_het_cts_iter[pop_ct * allele_bidx]);
}
}
for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) {
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
if (allele_idx_offsets) {
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
}
ZeroU32Arr(pop_geno_buf_size, pop_geno_buf);
uint32_t difflist_common_geno = UINT32_MAX;
if (allele_ct == 2) {
uint32_t difflist_len;
const PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_simple_difflist_len, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
if (unlikely(reterr)) {
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
goto FstThread_err;
}
if (difflist_common_geno != UINT32_MAX) {
const uint32_t word_ct = NypCtToWordCt(difflist_len);
if (word_ct) {
const uint32_t word_ct_m1 = word_ct - 1;
uint32_t loop_len = kBitsPerWordD2;
for (uint32_t widx = 0; ; ++widx) {
if (widx >= word_ct_m1) {
if (widx > word_ct_m1) {
break;
}
loop_len = ModNz(difflist_len, kBitsPerWordD2);
}
const uint32_t difflist_idx_base = widx * kBitsPerWordD2;
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[difflist_idx_base]);
uintptr_t raregeno_word = raregeno[widx];
if (!haploid_present) {
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uint32_t sample_idx = cur_difflist_sample_ids[uii];
const uintptr_t cur_geno = raregeno_word & 3;
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx];
pop_geno_buf[pop_idx * 4 + cur_geno] += 1;
raregeno_word >>= 2;
}
} else {
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uint32_t sample_idx = cur_difflist_sample_ids[uii];
uintptr_t cur_geno = raregeno_word & 3;
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx];
const uintptr_t male_mask = -IsSet(sex_male, sample_idx);
pop_geno_buf[pop_idx * 4 + cur_geno + (male_mask & pop_ct_x4)] += 1;
raregeno_word >>= 2;
}
}
}
}
if (difflist_common_geno != 3) {
const uint32_t other_hom_geno = 2 - difflist_common_geno;
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
const uint32_t diploid_pop_size = diploid_pop_sizes[pop_idx];
uint32_t* cur_pop_geno_buf = &(pop_geno_buf[pop_idx * 4]);
cur_pop_geno_buf[difflist_common_geno] = diploid_pop_size - cur_pop_geno_buf[1] - cur_pop_geno_buf[other_hom_geno] - cur_pop_geno_buf[3];
}
if (haploid_present) {
uint32_t* haploid_pop_geno_buf = &(pop_geno_buf[pop_ct_x4]);
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
const uint32_t haploid_pop_size = haploid_pop_sizes[pop_idx];
uint32_t* cur_pop_geno_buf = &(haploid_pop_geno_buf[pop_idx * 4]);
cur_pop_geno_buf[difflist_common_geno] = haploid_pop_size - cur_pop_geno_buf[1] - cur_pop_geno_buf[other_hom_geno] - cur_pop_geno_buf[3];
}
}
}
}
} else {
const PglErr reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv);
if (unlikely(reterr)) {
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
goto FstThread_err;
}
}
if (difflist_common_geno == UINT32_MAX) {
uint32_t loop_len = kBitsPerWordD2;
for (uint32_t widx = 0; ; ++widx) {
if (widx >= sample_ctl2_m1) {
if (widx > sample_ctl2_m1) {
break;
}
loop_len = ModNz(sample_ct, kBitsPerWordD2);
}
const uint32_t* cur_pop_idxs = &(sample_to_pop_idx[widx * kBitsPerWordD2]);
uintptr_t geno_word = genovec[widx];
if (!haploid_present) {
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uintptr_t cur_geno = geno_word & 3;
const uintptr_t pop_idx = cur_pop_idxs[uii];
pop_geno_buf[pop_idx * 4 + cur_geno] += 1;
geno_word >>= 2;
}
} else {
uintptr_t male_hw = R_CAST(const Halfword*, sex_male)[widx];
for (uint32_t uii = 0; uii != loop_len; ++uii) {
const uintptr_t cur_geno = geno_word & 3;
const uintptr_t pop_idx = cur_pop_idxs[uii];
const uintptr_t male_mask = -(male_hw & k1LU);
pop_geno_buf[pop_idx * 4 + cur_geno + (male_mask & pop_ct_x4)] += 1;
geno_word >>= 2;
male_hw >>= 1;
}
}
}
}
if (pop_nm_sample_cts_iter) {
const uint32_t* pop_geno_buf_iter = pop_geno_buf;
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
pop_nm_sample_cts_iter[pop_idx] = pop_geno_buf_iter[0] + pop_geno_buf_iter[1] + pop_geno_buf_iter[2];
pop_geno_buf_iter = &(pop_geno_buf_iter[4]);
}
if (haploid_present) {
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
pop_nm_sample_cts_iter[pop_idx] += pop_geno_buf_iter[0] + pop_geno_buf_iter[2];
pop_geno_buf_iter = &(pop_geno_buf_iter[4]);
}
}
}
ZeroU32Arr(pop_ct * allele_ct, pop_allele_obs_cts_iter);
if (pop_allele_het_cts_iter) {
ZeroU32Arr(pop_ct * allele_ct, pop_allele_het_cts_iter);
}
if (allele_ct != 2) {
if (pgv.patch_01_ct) {
const uint32_t patch_01_ct = pgv.patch_01_ct;
const uintptr_t* patch_01_set = pgv.patch_01_set;
const AlleleCode* patch_01_vals = pgv.patch_01_vals;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_01_set[0];
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
const uint32_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits);
if (sex_male && IsSet(sex_male, sample_idx)) {
// already counted as missing
continue;
}
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx];
pop_geno_buf[pop_idx * 4 + 1] -= 1;
pop_allele_obs_cts_iter[pop_idx] += 1;
const AlleleCode ac = patch_01_vals[uii];
pop_allele_obs_cts_iter[ac * pop_ct + pop_idx] += 1;
if (pop_allele_het_cts_iter) {
pop_allele_het_cts_iter[pop_idx] += 1;
pop_allele_het_cts_iter[ac * pop_ct + pop_idx] += 1;
}
}
}
if (pgv.patch_10_ct) {
const uint32_t patch_10_ct = pgv.patch_10_ct;
const uintptr_t* patch_10_set = pgv.patch_10_set;
const AlleleCode* patch_10_vals = pgv.patch_10_vals;
uintptr_t sample_idx_base = 0;
uintptr_t sample_idx_bits = patch_10_set[0];
if (!haploid_present) {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uint32_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx];
pop_geno_buf[pop_idx * 4 + 2] -= 1;
const AlleleCode ac0 = patch_10_vals[uii * 2];
const AlleleCode ac1 = patch_10_vals[uii * 2 + 1];
pop_allele_obs_cts_iter[pop_idx + ac0 * pop_ct] += 1;
pop_allele_obs_cts_iter[pop_idx + ac1 * pop_ct] += 1;
if (pop_allele_het_cts_iter && (ac0 != ac1)) {
pop_allele_het_cts_iter[pop_idx + ac0 * pop_ct] += 1;
pop_allele_het_cts_iter[pop_idx + ac1 * pop_ct] += 1;
}
}
} else {
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
const uint32_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits);
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx];
const uintptr_t is_male = IsSet(sex_male, sample_idx);
pop_geno_buf[pop_idx * 4 + 2 + ((-is_male) & pop_ct_x4)] -= 1;
const AlleleCode ac0 = patch_10_vals[uii * 2];
const AlleleCode ac1 = patch_10_vals[uii * 2 + 1];
if (ac0 == ac1) {
pop_allele_obs_cts_iter[pop_idx + ac0 * pop_ct] += 2 - is_male;
} else {
if (is_male) {
if (pop_nm_sample_cts_iter) {
pop_nm_sample_cts_iter[pop_idx] -= 1;
}
continue;
}
pop_allele_obs_cts_iter[pop_idx + ac0 * pop_ct] += 1;
pop_allele_obs_cts_iter[pop_idx + ac1 * pop_ct] += 1;
// guaranteed to be performing Hudson computation if we're
// here, so no need to check pop_allele_het_cts_iter
}
}
}
}
}
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
const uint32_t hom_ref_ct = pop_geno_buf[pop_idx * 4];
const uint32_t het_ref_alt1_ct = pop_geno_buf[pop_idx * 4 + 1];
const uint32_t hom_alt1_ct = pop_geno_buf[pop_idx * 4 + 2];
pop_allele_obs_cts_iter[pop_idx] += hom_ref_ct * 2 + het_ref_alt1_ct;
pop_allele_obs_cts_iter[pop_idx + pop_ct] += hom_alt1_ct * 2 + het_ref_alt1_ct;
if (pop_allele_het_cts_iter) {
pop_allele_het_cts_iter[pop_idx] += het_ref_alt1_ct;
pop_allele_het_cts_iter[pop_idx + pop_ct] += het_ref_alt1_ct;
}
}
if (haploid_present) {
const uint32_t* haploid_pop_geno_buf_iter = &(pop_geno_buf[pop_ct_x4]);
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
const uint32_t hap_ref_ct = haploid_pop_geno_buf_iter[0];
const uint32_t hap_alt1_ct = haploid_pop_geno_buf_iter[2];
pop_allele_obs_cts_iter[pop_idx] += hap_ref_ct;
pop_allele_obs_cts_iter[pop_idx + pop_ct] += hap_alt1_ct;
haploid_pop_geno_buf_iter = &(haploid_pop_geno_buf_iter[4]);
}
}
if (half_within_iter) {
// Hudson
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
uintptr_t n_hap = 0;
uint64_t ssq = 0;
for (uintptr_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
const uintptr_t allele_obs_ct = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx];
n_hap += allele_obs_ct;
ssq += S_CAST(uint64_t, allele_obs_ct) * allele_obs_ct;
}
const uint64_t n_pairs_x2 = S_CAST(uint64_t, n_hap) * (n_hap - 1);
const uint64_t n_same = (ssq - n_hap) / 2;
const uint64_t n_diff = n_pairs_x2 / 2 - n_same;
*half_within_iter++ = u63tod(n_diff) / u63tod(n_pairs_x2);
}
} else {
// Weir-Cockerham
pop_allele_het_cts_iter = &(pop_allele_het_cts_iter[pop_ct * allele_ct]);
}
if (pop_nm_sample_cts_iter) {
pop_nm_sample_cts_iter = &(pop_nm_sample_cts_iter[pop_ct]);
}
pop_allele_obs_cts_iter = &(pop_allele_obs_cts_iter[pop_ct * allele_ct]);
}
parity = 1 - parity;
while (0) {
FstThread_err:
UpdateU64IfSmaller(new_err_info, &ctx->err_info);
}
} while (!THREAD_BLOCK_FINISH(arg));
THREAD_RETURN;
}
const char g_cc_cat_names[2][8] = {"CONTROL", "CASE"};
CONSTI32(kFstReportVariantsBatchMax, kMaxOpenFiles - 12);
PglErr FstReport(const uintptr_t* orig_sample_include, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const FstInfo* fst_infop, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t max_allele_ct, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) {
unsigned char* bigstack_mark = g_bigstack_base;
unsigned char* bigstack_end_mark = g_bigstack_end;
uint32_t max_variant_file_ct = 0;
FILE* s_outfile = nullptr;
char** v_cswritep_arr = nullptr;
CompressStreamState* v_css_arr = nullptr;
PglErr reterr = kPglRetSuccess;
TextStream txs; // file=
PreinitTextStream(&txs);
ThreadGroup tg;
PreinitThreads(&tg);
FstCtx ctx;
{
if (IsSet(cip->haploid_mask, 0)) {
logerrputs("Error: --fst cannot be used on haploid genomes.\n");
goto FstReport_ret_INCONSISTENT_INPUT;
}
const char* pheno_name = fst_infop->pheno_name;
const PhenoCol* pheno_col;
{
const uint32_t pheno_blen = strlen(pheno_name) + 1;
if (pheno_blen > max_pheno_name_blen) {
goto FstReport_ret_PHENO_NOT_FOUND;
}
for (uintptr_t pheno_idx = 0; ; ++pheno_idx) {
if (pheno_idx == pheno_ct) {
goto FstReport_ret_PHENO_NOT_FOUND;
}
if (memequal(pheno_name, &(pheno_names[pheno_idx * max_pheno_name_blen]), pheno_blen)) {
pheno_col = &(pheno_cols[pheno_idx]);
break;
}
}
}
if (pheno_col->type_code == kPhenoDtypeQt) {
logerrprintfww("Error: --fst phenotype '%s' is quantitative (binary or categorical required).\n", pheno_name);
goto FstReport_ret_INCONSISTENT_INPUT;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
if (pheno_col->type_code != kPhenoDtypeCat) {
assert(pheno_col->type_code == kPhenoDtypeCc);
// this may belong in plink2_cmdline
PhenoCol* synthetic_pheno_col;
uint32_t* cat_tmp;
const char** category_names;
if (unlikely(BIGSTACK_ALLOC_X(PhenoCol, 1, &synthetic_pheno_col) ||
bigstack_end_calloc_u32(raw_sample_ct, &cat_tmp) ||
bigstack_end_alloc_kcp(3, &category_names))) {
goto FstReport_ret_NOMEM;
}
const uintptr_t* raw_pheno_nm = pheno_col->nonmiss;
const uintptr_t* pheno_cc = pheno_col->data.cc;
for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) {
if (!IsSet(raw_pheno_nm, sample_uidx)) {
continue;
}
// 'CASE' is lexicographically before 'CONTROL'
cat_tmp[sample_uidx] = 2 - IsSet(pheno_cc, sample_uidx);
}
category_names[0] = nullptr;
category_names[1] = g_cc_cat_names[1];
category_names[2] = g_cc_cat_names[0];
synthetic_pheno_col->category_names = category_names;
synthetic_pheno_col->nonmiss = pheno_col->nonmiss;
synthetic_pheno_col->data.cat = cat_tmp;
synthetic_pheno_col->type_code = kPhenoDtypeCat;
synthetic_pheno_col->nonnull_category_ct = 2;
pheno_col = synthetic_pheno_col;
}
ctx.allele_idx_offsets = allele_idx_offsets;
uintptr_t* sample_include;
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include))) {
goto FstReport_ret_NOMEM;
}
BitvecAndCopy(orig_sample_include, pheno_col->nonmiss, raw_sample_ctl, sample_include);
uint32_t sample_ct = PopcountWords(sample_include, raw_sample_ctl);
const FstFlags flags = fst_infop->flags;
const uint32_t is_wc = (flags / kfFstMethodWc) & 1;
uintptr_t pop_pair_ct = 0;
uint32_t* pop_pairs = nullptr;
const char** pop_names;
uintptr_t pop_ct;
{
const uint32_t nonnull_category_ct = pheno_col->nonnull_category_ct;
const uint32_t raw_cat_ctl = 1 + (nonnull_category_ct / kBitsPerWord);
uintptr_t* cats_seen;
if (unlikely(bigstack_end_alloc_w(raw_cat_ctl, &cats_seen))) {
goto FstReport_ret_NOMEM;
}
pop_ct = IdentifyRemainingCats(sample_include, pheno_col, sample_ct, cats_seen);
assert(!(cats_seen[0] & 1));
if (pop_ct < 2) {
logerrputs("Error: --fst requires two or more populations.\n");
goto FstReport_ret_INCONSISTENT_INPUT;
}
const uint32_t* old_cats = pheno_col->data.cat;
if (flags & (kfFstOneBasePop | kfFstExplicitPopIds)) {
const char** nonnull_category_names = &(pheno_col->category_names[1]);
const char* first_id = fst_infop->first_id_or_fname;
const uint32_t first_cat_idx = 1 + bsearch_strptr_natural(first_id, nonnull_category_names, nonnull_category_ct);
if (unlikely(!IsSet(cats_seen, first_cat_idx))) {
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, first_id);
goto FstReport_ret_INCONSISTENT_INPUT;
}
const char* other_ids = fst_infop->other_ids_flattened;
if (!other_ids) {
// base= with single argument
const uintptr_t other_pop_ct = pop_ct - 1;
if (unlikely(bigstack_alloc_u32(2 * other_pop_ct, &pop_pairs))) {
goto FstReport_ret_NOMEM;
}
pop_pair_ct = other_pop_ct;
uint32_t* pop_pairs_iter = pop_pairs;
uintptr_t cats_seen_base = 0;
uintptr_t cats_seen_bits = cats_seen[0];
uintptr_t ulii = 0;
for (; ulii != other_pop_ct; ++ulii) {
const uint32_t other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits);
if (other_cat_idx == first_cat_idx) {
break;
}
*pop_pairs_iter++ = other_cat_idx;
*pop_pairs_iter++ = first_cat_idx;
}
for (; ulii != other_pop_ct; ++ulii) {
const uint32_t other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits);
*pop_pairs_iter++ = first_cat_idx;
*pop_pairs_iter++ = other_cat_idx;
}
} else {
// either base= or id= with multiple arguments
uintptr_t* pop_include;
if (unlikely(bigstack_end_calloc_w(raw_cat_ctl, &pop_include))) {
goto FstReport_ret_NOMEM;
}
SetBit(first_cat_idx, pop_include);
const char* other_ids_iter = other_ids;
do {
const uint32_t cat_idx = 1 + bsearch_strptr_natural(other_ids_iter, nonnull_category_names, nonnull_category_ct);
if (unlikely(!IsSet(cats_seen, cat_idx))) {
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, other_ids_iter);
goto FstReport_ret_INCONSISTENT_INPUT;
}
if (unlikely(IsSet(pop_include, cat_idx))) {
logerrprintfww("Error: Duplicate --fst population ID '%s'.\n", other_ids_iter);
goto FstReport_ret_INVALID_CMDLINE;
}
SetBit(cat_idx, pop_include);
other_ids_iter = strnul(other_ids_iter);
++other_ids_iter;
} while (*other_ids_iter);
const uintptr_t named_pop_ct = PopcountWords(pop_include, raw_cat_ctl);
if (named_pop_ct != pop_ct) {
// Safe to ignore unnamed populations.
pop_ct = named_pop_ct;
memcpy(cats_seen, pop_include, raw_cat_ctl * sizeof(intptr_t));
sample_ct = RemoveExcludedCats(old_cats, cats_seen, raw_sample_ct, sample_ct, sample_include);
}
if (flags & kfFstOneBasePop) {
pop_pair_ct = named_pop_ct - 1;
if (unlikely(bigstack_alloc_u32(2 * pop_pair_ct, &pop_pairs))) {
goto FstReport_ret_NOMEM;
}
uint32_t* pop_pairs_iter = pop_pairs;
uint32_t uii = 0;
uintptr_t cats_seen_base = 0;
uintptr_t cats_seen_bits = cats_seen[0];
for (; uii != named_pop_ct; ++uii) {
uint32_t other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits);
if (first_cat_idx == other_cat_idx) {
while (1) {
++uii;
if (uii == named_pop_ct) {
break;
}
other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits);
*pop_pairs_iter++ = first_cat_idx;
*pop_pairs_iter++ = other_cat_idx;
}
break;
}
*pop_pairs_iter++ = other_cat_idx;
*pop_pairs_iter++ = first_cat_idx;
}
} else {
// ids=
SetBit(first_cat_idx, cats_seen);
const uint64_t named_pop_ct_m1 = named_pop_ct - k1LU;
const uint64_t pop_pair_ct_u64 = (named_pop_ct * named_pop_ct_m1) / 2;
if (unlikely(bigstack_alloc64_u32(2 * pop_pair_ct_u64, &pop_pairs))) {
goto FstReport_ret_NOMEM;
}
pop_pair_ct = pop_pair_ct_u64;
uint32_t* pop_pairs_iter = pop_pairs;
uintptr_t cats_seen_base1 = 0;
uintptr_t cats_seen_bits1 = cats_seen[0];
for (uintptr_t ulii = 0; ulii != named_pop_ct_m1; ++ulii) {
const uint32_t cat_idx1 = BitIter1(cats_seen, &cats_seen_base1, &cats_seen_bits1);
uintptr_t cats_seen_base2 = cats_seen_base1;
uintptr_t cats_seen_bits2 = cats_seen_bits1;
for (uintptr_t uljj = ulii; uljj != named_pop_ct_m1; ++uljj) {
const uint32_t cat_idx2 = BitIter1(cats_seen, &cats_seen_base2, &cats_seen_bits2);
*pop_pairs_iter++ = cat_idx1;
*pop_pairs_iter++ = cat_idx2;
}
}
}
}
} else if (flags & kfFstPopPairFile) {
const uint64_t possible_pair_ct_u64 = S_CAST(uint64_t, nonnull_category_ct) * (nonnull_category_ct + 1LLU) / 2;
const uint64_t possible_pair_ctl_u64 = DivUpU64(possible_pair_ct_u64, kBitsPerWord);
uintptr_t* selected_pairs;
uintptr_t* pop_include;
if (unlikely(bigstack_end_calloc64_w(possible_pair_ctl_u64, &selected_pairs) ||
bigstack_end_calloc_w(raw_cat_ctl, &pop_include))) {
goto FstReport_ret_NOMEM;
}
unsigned char* bigstack_end_mark2 = g_bigstack_end;
const char* in_fname = fst_infop->first_id_or_fname;
reterr = InitTextStreamEx(in_fname, 1, kMaxLongLine, kTextStreamBlenFast, 1, &txs);
if (unlikely(reterr)) {
goto FstReport_ret_TSTREAM_FAIL;
}
const char** nonnull_category_names = &(pheno_col->category_names[1]);
uintptr_t duplicate_ct = 0;
uintptr_t line_idx = 0;
while (1) {
++line_idx;
char* first_token_start = TextGet(&txs);
if (!first_token_start) {
if (likely(!TextStreamErrcode2(&txs, &reterr))) {
break;
}
goto FstReport_ret_TSTREAM_FAIL;
}
char* first_token_end = CurTokenEnd(first_token_start);
char* second_token_start = FirstNonTspace(first_token_end);
if (unlikely(IsEolnKns(*second_token_start))) {
logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, in_fname);
goto FstReport_ret_MALFORMED_INPUT;
}
char* second_token_end = CurTokenEnd(second_token_start);
*first_token_end = '\0';
const uintptr_t cat_idx1 = 1 + bsearch_strptr_natural(first_token_start, nonnull_category_names, nonnull_category_ct);
if (unlikely(!IsSet(cats_seen, cat_idx1))) {
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, first_token_start);
goto FstReport_ret_INCONSISTENT_INPUT;
}
*second_token_end = '\0';
const uintptr_t cat_idx2 = 1 + bsearch_strptr_natural(second_token_start, nonnull_category_names, nonnull_category_ct);
if (unlikely(!IsSet(cats_seen, cat_idx2))) {
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, second_token_start);
goto FstReport_ret_INCONSISTENT_INPUT;
}
uintptr_t bit_idx;
if (cat_idx1 < cat_idx2) {
bit_idx = ((cat_idx2 * (cat_idx2 - 1)) / 2) + cat_idx1;
} else if (likely(cat_idx2 < cat_idx1)) {
bit_idx = ((cat_idx1 * (cat_idx1 - 1)) / 2) + cat_idx2;
} else {
logerrprintfww("Error: Both populations on line %" PRIuPTR " of %s are the same.\n", line_idx, in_fname);
goto FstReport_ret_MALFORMED_INPUT;
}
SetBit(cat_idx1, pop_include);
SetBit(cat_idx2, pop_include);
duplicate_ct += IsSet(selected_pairs, bit_idx);
SetBit(bit_idx, selected_pairs);
}
if (unlikely(CleanupTextStream2("--fst file", &txs, &reterr))) {
goto FstReport_ret_1;
}
const uintptr_t named_pop_ct = PopcountWords(pop_include, raw_cat_ctl);
if (named_pop_ct != pop_ct) {
pop_ct = named_pop_ct;
memcpy(cats_seen, pop_include, raw_cat_ctl * sizeof(intptr_t));
sample_ct = RemoveExcludedCats(old_cats, cats_seen, raw_sample_ct, sample_ct, sample_include);
}
BigstackEndReset(bigstack_end_mark2);
pop_pair_ct = PopcountWords(selected_pairs, possible_pair_ctl_u64);
if (unlikely(!pop_pair_ct)) {
logerrprintfww("Error: %s is empty.\n", in_fname);
goto FstReport_ret_INCONSISTENT_INPUT;
}
logprintfww("--fst: %" PRIuPTR "%s population pair%s loaded from %s.\n", pop_pair_ct, duplicate_ct? " distinct" : "", (pop_pair_ct == 1)? "" : "s", in_fname);
if (duplicate_ct) {
logerrprintf("Warning: %" PRIuPTR " duplicate pair%s in --fst file.\n", duplicate_ct, (duplicate_ct == 1)? "" : "s");
}
if (unlikely(bigstack_alloc_u32(2 * pop_pair_ct, &pop_pairs))) {
goto FstReport_ret_NOMEM;
}
uint32_t* pop_pairs_iter = pop_pairs;
uintptr_t selected_pairs_base = 0;
uintptr_t selected_pairs_bits = selected_pairs[0];
uintptr_t cur_tri = 0;
uintptr_t idx_hi = 1;
for (uintptr_t ulii = 0; ulii != pop_pair_ct; ++ulii) {
const uintptr_t selected_pairs_uidx = BitIter1(selected_pairs, &selected_pairs_base, &selected_pairs_bits);
uintptr_t idx_lo = selected_pairs_uidx - cur_tri;
while (idx_lo >= idx_hi) {
idx_lo -= idx_hi;
cur_tri += idx_hi;
++idx_hi;
}
*pop_pairs_iter++ = idx_lo;
*pop_pairs_iter++ = idx_hi;
}
}
uint32_t* sample_include_cumulative_popcounts;
uint32_t* sample_to_pop_idx;
uint32_t* diploid_pop_sizes;
uint32_t* old_cat_idx_to_new;
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
bigstack_alloc_u32(sample_ct, &sample_to_pop_idx) ||
bigstack_calloc_u32(pop_ct, &diploid_pop_sizes) ||
bigstack_alloc_kcp(pop_ct, &pop_names) ||
bigstack_end_alloc_u32(1 + nonnull_category_ct, &old_cat_idx_to_new))) {
goto FstReport_ret_NOMEM;
}
ctx.sample_include = sample_include;
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
uintptr_t cat_uidx_base = 0;
uintptr_t cats_seen_bits = cats_seen[0];
for (uintptr_t cat_idx = 0; cat_idx != pop_ct; ++cat_idx) {
const uintptr_t cat_uidx = BitIter1(cats_seen, &cat_uidx_base, &cats_seen_bits);
old_cat_idx_to_new[cat_uidx] = cat_idx;
pop_names[cat_idx] = pheno_col->category_names[cat_uidx];
}
uintptr_t sample_uidx_base = 0;
uintptr_t sample_include_bits = sample_include[0];
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
const uint32_t pop_idx = old_cat_idx_to_new[old_cats[sample_uidx]];
sample_to_pop_idx[sample_idx] = pop_idx;
diploid_pop_sizes[pop_idx] += 1;
}
ctx.sample_to_pop_idx = sample_to_pop_idx;
ctx.diploid_pop_sizes = diploid_pop_sizes;
ctx.sample_ct = sample_ct;
ctx.pop_ct = pop_ct;
if (!(flags & (kfFstOneBasePop | kfFstExplicitPopIds | kfFstPopPairFile))) {
const uint64_t pop_pair_ct_u64 = (S_CAST(uint64_t, pop_ct) * (pop_ct - k1LU)) / 2;
if (unlikely(bigstack_alloc64_u32(2 * pop_pair_ct_u64, &pop_pairs))) {
goto FstReport_ret_NOMEM;
}
pop_pair_ct = pop_pair_ct_u64;
uint32_t* pop_pairs_iter = pop_pairs;
const uint32_t pop_ct_m1 = pop_ct - 1;
for (uint32_t first_pop_idx = 0; first_pop_idx != pop_ct_m1; ++first_pop_idx) {
for (uint32_t second_pop_idx = first_pop_idx + 1; second_pop_idx != pop_ct; ++second_pop_idx) {
*pop_pairs_iter++ = first_pop_idx;
*pop_pairs_iter++ = second_pop_idx;
}
}
} else {
const uintptr_t pop_pair_ct_x2 = pop_pair_ct * 2;
for (uintptr_t ulii = 0; ulii != pop_pair_ct_x2; ++ulii) {
pop_pairs[ulii] = old_cat_idx_to_new[pop_pairs[ulii]];
}
}
BigstackEndReset(bigstack_end_mark);
}
logprintf("--fst: Analyzing %u samples across %" PRIuPTR " populations.\n", sample_ct, pop_ct);
if (unlikely(bigstack_alloc_wp(max_thread_ct, &ctx.raregenos) ||
bigstack_alloc_u32p(max_thread_ct, &ctx.difflist_sample_id_bufs) ||
bigstack_alloc_u32p(max_thread_ct, &ctx.pop_geno_bufs))) {
goto FstReport_ret_NOMEM;
}
const uint32_t report_variants = (flags / kfFstReportVariants) & 1;
if (report_variants) {
max_variant_file_ct = MINV(pop_pair_ct, kFstReportVariantsBatchMax);
if (unlikely(bigstack_calloc_cp(max_variant_file_ct, &v_cswritep_arr) ||
BIGSTACK_ALLOC_X(CompressStreamState, max_variant_file_ct, &v_css_arr))) {
goto FstReport_ret_NOMEM;
}
for (uintptr_t fidx = 0; fidx != max_variant_file_ct; ++fidx) {
PreinitCstream(&(v_css_arr[fidx]));
}
}
const uint32_t v_output_zst = (flags / kfFstZs) & 1;
const uint32_t chrom_vcol = (flags / kfFstVcolChrom) & 1;
char* chr_buf = nullptr;
if (chrom_vcol) {
uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
goto FstReport_ret_NOMEM;
}
}
const uint32_t pos_vcol = (flags / kfFstVcolPos) & 1;
const uint32_t ref_vcol = (flags / kfFstVcolRef) & 1;
const uint32_t alt_vcol = (flags / kfFstVcolAlt) & 1;
const uint32_t alleles_needed = ref_vcol || alt_vcol;
const uintptr_t* nonref_flags = pgfip->nonref_flags;
const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
const uint32_t nobs_vcol = (flags / kfFstVcolNobs) & 1;
const uint32_t nallele_vcol = (flags / kfFstVcolNallele) & 1;
const uint32_t fstfrac_vcol = (flags / kfFstVcolFstfrac) & 1;
const uint32_t fst_vcol = (flags / kfFstVcolFst) & 1;
const uint32_t jackknife_blocksize = fst_infop->blocksize;
const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec);
const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec);
const uint32_t mhc_needed = (max_allele_ct > 2);
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
unsigned char* bigstack_mark2 = g_bigstack_base;
uint32_t allele_ct = 2;
for (uint32_t is_x = 0; is_x != 2; ++is_x) {
const uintptr_t* cur_variant_include = orig_variant_include;
char* outname_end2 = outname_end;
uint32_t cur_variant_ct;
if (!is_x) {
cur_variant_ct = orig_variant_ct;
reterr = ConditionalAllocateNonAutosomalVariants(cip, nullptr, raw_variant_ct, &cur_variant_include, &cur_variant_ct);
if (unlikely(reterr)) {
goto FstReport_ret_1;
}
ctx.sex_male_collapsed = nullptr;
ctx.haploid_pop_sizes = nullptr;
} else {
if (is_wc) {
break;
}
outname_end2 = strcpya_k(outname_end2, ".x");
cur_variant_ct = 0;
uint32_t x_code;
if (XymtExists(cip, kChrOffsetX, &x_code)) {
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[x_code];
const uint32_t start_idx = cip->chr_fo_vidx_start[chr_fo_idx];
const uint32_t end_idx = cip->chr_fo_vidx_start[chr_fo_idx + 1];
cur_variant_ct = PopcountBitRange(orig_variant_include, start_idx, end_idx);
if (cur_variant_ct && (cur_variant_ct != orig_variant_ct)) {
// may want this in a plink2_common function
uintptr_t* tmp_variant_include;
if (unlikely(bigstack_alloc_w(raw_variant_ctl, &tmp_variant_include))) {
goto FstReport_ret_NOMEM;
}
const uint32_t start_widx = start_idx / kBitsPerWord;
const uint32_t end_widx = DivUp(end_idx, kBitsPerWord);
ZeroWArr(start_widx, tmp_variant_include);
memcpy(&(tmp_variant_include[start_widx]), &(orig_variant_include[start_widx]), (end_widx - start_widx) * sizeof(intptr_t));
ZeroWArr(raw_variant_ctl - end_widx, &(tmp_variant_include[end_widx]));
const uint32_t start_remainder = start_idx % kBitsPerWord;
tmp_variant_include[start_widx] &= (~k0LU) << start_remainder;
const uint32_t end_remainder = end_idx % kBitsPerWord;
if (end_remainder) {
tmp_variant_include[end_widx - 1] &= (k1LU << end_remainder) - 1;
}
cur_variant_include = tmp_variant_include;
}
const uint32_t haploid_present = !IntersectionIsEmpty(sample_include, sex_male, raw_sample_ctl);
if (haploid_present) {
const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
uintptr_t* sex_male_collapsed;
uint32_t* haploid_pop_sizes;
if (unlikely(bigstack_alloc_w(sample_ctl, &sex_male_collapsed) ||
bigstack_calloc_u32(pop_ct, &haploid_pop_sizes))) {
goto FstReport_ret_NOMEM;
}
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed);
const uint32_t* sample_to_pop_idx = ctx.sample_to_pop_idx;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t pop_idx = sample_to_pop_idx[sample_idx];
haploid_pop_sizes[pop_idx] += IsSet(sex_male_collapsed, sample_idx);
}
// This assumes is_x happens after !is_x.
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) {
ctx.diploid_pop_sizes[pop_idx] -= haploid_pop_sizes[pop_idx];
}
ctx.sex_male_collapsed = sex_male_collapsed;
ctx.haploid_pop_sizes = haploid_pop_sizes;
}
}
}
if (!cur_variant_ct) {
continue;
}
const uint32_t provref_vcol = ref_vcol && ProvrefCol(cur_variant_include, nonref_flags, flags / kfFstVcolMaybeprovref, raw_variant_ct, all_nonref);
ctx.cur_variant_include = cur_variant_include;
const uintptr_t pop_geno_vec_ct = DivUp(pop_ct * (4 << (ctx.sex_male_collapsed != nullptr)), kInt32PerVec);
const uintptr_t thread_xalloc_vec_ct = raregeno_vec_ct + difflist_sample_id_vec_ct + pop_geno_vec_ct;
const uintptr_t thread_xalloc_cacheline_ct = DivUp(thread_xalloc_vec_ct, kVecsPerCacheline);
const uintptr_t per_allele_xalloc_byte_ct = pop_ct * sizeof(int32_t) * 2 * (1 + is_wc);
uintptr_t per_variant_xalloc_byte_ct = per_allele_xalloc_byte_ct;
if (nobs_vcol || is_wc) {
per_variant_xalloc_byte_ct += pop_ct * sizeof(int32_t) * 2;
} else {
ctx.pop_nm_sample_cts[0] = nullptr;
ctx.pop_nm_sample_cts[1] = nullptr;
}
if (!is_wc) {
// half_within
per_variant_xalloc_byte_ct += pop_ct * sizeof(double) * 2;
ctx.pop_allele_het_cts[0] = nullptr;
ctx.pop_allele_het_cts[1] = nullptr;
} else {
// pop_allele_het_cts already included in (1 + is_wc) term above
ctx.half_within[0] = nullptr;
ctx.half_within[1] = nullptr;
}
uint32_t calc_thread_ct = max_thread_ct;
strcpy_k(outname_end2, ".fst.summary");
if (unlikely(fopen_checked(outname, FOPEN_WB, &s_outfile))) {
goto FstReport_ret_OPEN_FAIL;
}
char* s_write_iter = g_textbuf;
char* s_textbuf_flush = &(s_write_iter[kMaxMediumLine]);
s_write_iter = strcpya_k(s_write_iter, "#POP1\tPOP2\t");
const uint32_t nobs_scol = (flags / kfFstColNobs) & 1;
if (nobs_scol) {
s_write_iter = strcpya_k(s_write_iter, "OBS_CT\t");
}
if (!is_wc) {
s_write_iter = strcpya_k(s_write_iter, "HUDSON_FST");
} else {
s_write_iter = strcpya_k(s_write_iter, "WC_FST");
}
if (jackknife_blocksize) {
s_write_iter = strcpya_k(s_write_iter, "\tSE");
}
AppendBinaryEoln(&s_write_iter);
uintptr_t pop_pair_batch_size = pop_pair_ct;
uintptr_t pass_ct = 1;
if (report_variants && (pop_pair_ct > kFstReportVariantsBatchMax)) {
pop_pair_batch_size = kFstReportVariantsBatchMax;
pass_ct = DivUp(pop_pair_ct, kFstReportVariantsBatchMax);
}
double* fst_numer_sums;
double* fst_denom_sums;
uint32_t* fst_nobs;
if (unlikely(bigstack_alloc_d(pop_pair_batch_size, &fst_numer_sums) ||
bigstack_alloc_d(pop_pair_batch_size, &fst_denom_sums) ||
bigstack_alloc_u32(pop_pair_batch_size, &fst_nobs))) {
goto FstReport_ret_NOMEM;
}
uint32_t jackknife_block_max = 0;
if (jackknife_blocksize) {
if (cur_variant_ct <= jackknife_blocksize) {
logerrprintf("Warning: Too few %s variants for --fst blocksize=%u to be useful.\n", is_x? "chrX" : "autosomal", jackknife_blocksize);
}
jackknife_block_max = DivUp(cur_variant_ct, jackknife_blocksize);
}
// <output prefix, including .x>.<popID1>.<popID2>.fst.var[.zst]
const uint32_t pop_name_capacity = kPglFnamesize - 11 - (4 * v_output_zst) - S_CAST(uintptr_t, outname_end2 - outname);
unsigned char* bigstack_mark3 = g_bigstack_base;
for (uintptr_t pass_idx = 0; pass_idx != pass_ct; ++pass_idx) {
const uintptr_t pop_pair_start_idx = pass_idx * pop_pair_batch_size;
if (pass_idx == pass_ct - 1) {
pop_pair_batch_size = pop_pair_ct - pop_pair_start_idx;
}
const uint32_t* cur_pop_pairs = &(pop_pairs[2 * pop_pair_start_idx]);
if (report_variants) {
if (pop_pair_batch_size > pop_pair_ct - pop_pair_start_idx) {
pop_pair_batch_size = pop_pair_ct - pop_pair_start_idx;
}
for (uintptr_t fidx = 0; fidx != pop_pair_batch_size; ++fidx) {
{
const uint32_t pop_idx1 = cur_pop_pairs[2 * fidx];
const uint32_t pop_idx2 = cur_pop_pairs[2 * fidx + 1];
char* fname_iter = outname_end2;
const uint32_t slen1 = strlen(pop_names[pop_idx1]);
const uint32_t slen2 = strlen(pop_names[pop_idx2]);
if (unlikely(slen1 + slen2 > pop_name_capacity)) {
logerrputs("Error: Population name and/or --out argument too long.\n");
goto FstReport_ret_INCONSISTENT_INPUT;
}
*fname_iter++ = '.';
fname_iter = memcpyax(fname_iter, pop_names[pop_idx1], slen1, '.');
fname_iter = memcpya(fname_iter, pop_names[pop_idx2], slen2);
OutnameZstSet(".fst.var", v_output_zst, fname_iter);
}
reterr = InitCstreamAlloc(outname, 0, v_output_zst, 1, 2 * kCompressStreamBlock, &(v_css_arr[fidx]), &(v_cswritep_arr[fidx]));
if (unlikely(reterr)) {
goto FstReport_ret_1;
}
char* cswritep = v_cswritep_arr[fidx];
*cswritep++ = '#';
if (chrom_vcol) {
cswritep = strcpya_k(cswritep, "CHROM\t");
}
if (pos_vcol) {
cswritep = strcpya_k(cswritep, "POS\t");
}
cswritep = strcpya_k(cswritep, "ID");
if (ref_vcol) {
cswritep = strcpya_k(cswritep, "\tREF");
}
if (alt_vcol) {
cswritep = strcpya_k(cswritep, "\tALT");
}
if (provref_vcol) {
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
}
if (nobs_vcol) {
cswritep = strcpya_k(cswritep, "\tOBS_CT");
}
if (nallele_vcol) {
cswritep = strcpya_k(cswritep, "\tPOP1_ALLELE_CT\tPOP2_ALLELE_CT");
}
if (fstfrac_vcol) {
cswritep = strcpya_k(cswritep, "\tFST_NUMER\tFST_DENOM");
}
if (fst_vcol) {
if (!is_wc) {
cswritep = strcpya_k(cswritep, "\tHUDSON_FST");
} else {
cswritep = strcpya_k(cswritep, "\tWC_FST");
}
}
AppendBinaryEoln(&cswritep);
v_cswritep_arr[fidx] = cswritep;
}
}
ZeroDArr(pop_pair_batch_size, fst_numer_sums);
ZeroDArr(pop_pair_batch_size, fst_denom_sums);
ZeroU32Arr(pop_pair_batch_size, fst_nobs);
double* jackknife_fst_numers = nullptr;
double* jackknife_fst_denoms = nullptr;
uint32_t* jackknife_next_block_starts = nullptr;
// In the jackknife case, fst_{numer,denom}_sums are only for the
// current block while the calculation is in progress; we save them off
// to jackknife_fst_{numers,denoms} when each block is complete.
if (jackknife_blocksize) {
// leading dimension = pop-pair index
// strictly speaking, pop_pair_batch_size should be reduced if this
// would be too large, but that should never come up with any sane
// blocksize= choice
if (unlikely(bigstack_alloc_d(jackknife_block_max * pop_pair_batch_size, &jackknife_fst_numers) ||
bigstack_alloc_d(jackknife_block_max * pop_pair_batch_size, &jackknife_fst_denoms) ||
bigstack_alloc_u32(pop_pair_batch_size, &jackknife_next_block_starts))) {
goto FstReport_ret_NOMEM;
}
for (uintptr_t ulii = 0; ulii != pop_pair_batch_size; ++ulii) {
jackknife_next_block_starts[ulii] = jackknife_blocksize;
}
}
uintptr_t bytes_avail = bigstack_left();
// defend against adverse rounding
if (unlikely(bytes_avail < 6 * kCacheline)) {
goto FstReport_ret_NOMEM;
}
bytes_avail -= 6 * kCacheline;
STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
ctx.thread_read_mhc = nullptr;
uint32_t read_block_size;
uintptr_t max_alt_allele_block_size;
if (unlikely(PgenMtLoadInit(cur_variant_include, sample_ct, cur_variant_ct, bytes_avail, pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, per_variant_xalloc_byte_ct, per_allele_xalloc_byte_ct, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, &max_alt_allele_block_size, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
goto FstReport_ret_NOMEM;
}
if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
goto FstReport_ret_NOMEM;
}
ctx.err_info = (~0LLU) << 32;
for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
unsigned char* cur_alloc = S_CAST(unsigned char*, bigstack_alloc_raw(thread_xalloc_cacheline_ct * kCacheline));
ctx.raregenos[tidx] = R_CAST(uintptr_t*, cur_alloc);
cur_alloc = &(cur_alloc[raregeno_vec_ct * kBytesPerVec]);
ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[difflist_sample_id_vec_ct * kBytesPerVec]);
ctx.pop_geno_bufs[tidx] = R_CAST(uint32_t*, cur_alloc);
cur_alloc = &(cur_alloc[pop_geno_vec_ct * kBytesPerVec]);
}
if (nobs_vcol || is_wc) {
const uintptr_t geno_obs_alloc = RoundUpPow2(pop_ct * sizeof(int32_t) * read_block_size, kCacheline);
ctx.pop_nm_sample_cts[0] = S_CAST(uint32_t*, bigstack_alloc_raw(geno_obs_alloc));
ctx.pop_nm_sample_cts[1] = S_CAST(uint32_t*, bigstack_alloc_raw(geno_obs_alloc));
}
const uintptr_t max_allele_block_size = read_block_size + max_alt_allele_block_size;
const uintptr_t allele_pop_alloc = RoundUpPow2(pop_ct * max_allele_block_size * sizeof(int32_t), kCacheline);
ctx.pop_allele_obs_cts[0] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc));
ctx.pop_allele_obs_cts[1] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc));
if (!is_wc) {
const uintptr_t half_within_alloc = RoundUpPow2(pop_ct * sizeof(double) * read_block_size, kCacheline);
ctx.half_within[0] = S_CAST(double*, bigstack_alloc_raw(half_within_alloc));
ctx.half_within[1] = S_CAST(double*, bigstack_alloc_raw(half_within_alloc));
} else {
ctx.pop_allele_het_cts[0] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc));
ctx.pop_allele_het_cts[1] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc));
}
SetThreadFuncAndData(FstThread, &ctx, &tg);
if (pop_pair_ct == pop_pair_batch_size) {
logprintf("%s --fst: ", is_x? "chrX" : "Autosomal");
} else {
logprintf("%s --fst pass %u/%u: ", is_x? "chrX" : "Autosomal", pass_idx + 1, pass_ct);
}
fputs("0%", stdout);
fflush(stdout);
uint32_t pct = 0;
uintptr_t write_variant_uidx_base = 0;
uintptr_t write_variant_bits = cur_variant_include[0];
uint32_t parity = 0;
uint32_t read_block_idx = 0;
uint32_t chr_fo_idx = UINT32_MAX;
uint32_t chr_end = 0;
uint32_t chr_buf_blen = 0;
uint32_t prev_block_variant_ct = 0;
uint32_t next_print_variant_idx = cur_variant_ct / 100;
for (uint32_t variant_idx = 0; ; ) {
const uint32_t cur_block_variant_ct = MultireadNonempty(cur_variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
if (unlikely(reterr)) {
goto FstReport_ret_PGR_FAIL;
}
if (variant_idx) {
JoinThreads(&tg);
reterr = S_CAST(PglErr, ctx.err_info);
if (unlikely(reterr)) {
PgenErrPrintNV(reterr, ctx.err_info >> 32);
goto FstReport_ret_1;
}
}
if (!IsLastBlock(&tg)) {
ctx.cur_block_variant_ct = cur_block_variant_ct;
ComputeUidxStartPartition(cur_variant_include, cur_block_variant_ct, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
if (variant_idx + cur_block_variant_ct == cur_variant_ct) {
DeclareLastThreadBlock(&tg);
}
if (unlikely(SpawnThreads(&tg))) {
goto FstReport_ret_THREAD_CREATE_FAIL;
}
}
parity = 1 - parity;
if (variant_idx) {
// process *previous* block results
const uint32_t* pop_nm_sample_cts_iter = ctx.pop_nm_sample_cts[parity];
const uint32_t* pop_allele_obs_cts_iter = ctx.pop_allele_obs_cts[parity];
const double* half_within_iter = ctx.half_within[parity];
const uint32_t* pop_allele_het_cts_iter = ctx.pop_allele_het_cts[parity];
for (uint32_t variant_bidx = 0; variant_bidx != prev_block_variant_ct; ++variant_bidx) {
const uint32_t write_variant_uidx = BitIter1(cur_variant_include, &write_variant_uidx_base, &write_variant_bits);
if (chr_buf && (write_variant_uidx >= chr_end)) {
do {
++chr_fo_idx;
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
} while (write_variant_uidx >= chr_end);
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
*chr_name_end = '\t';
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
}
uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offset_base;
}
for (uintptr_t pop_pair_bidx = 0; pop_pair_bidx != pop_pair_batch_size; ++pop_pair_bidx) {
const uint32_t pop_idx1 = cur_pop_pairs[2 * pop_pair_bidx];
const uint32_t pop_idx2 = cur_pop_pairs[2 * pop_pair_bidx + 1];
// See allel/stats/fst.py under
// https://github.com/cggh/scikit-allel for a more readable
// form of these computations.
double fst_numer = 0.0;
double fst_denom = 0.0;
uintptr_t pop1_n_hap = 0;
uintptr_t pop2_n_hap = 0;
if (!is_wc) {
// Hudson
uint64_t n_same = 0;
for (uintptr_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
const uintptr_t ct1 = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx1];
const uintptr_t ct2 = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx2];
pop1_n_hap += ct1;
pop2_n_hap += ct2;
n_same += S_CAST(uint64_t, ct1) * ct2;
}
const uint64_t n_pairs = S_CAST(uint64_t, pop1_n_hap) * pop2_n_hap;
const uint64_t n_diff = n_pairs - n_same;
if (n_diff) {
const double within = half_within_iter[pop_idx1] + half_within_iter[pop_idx2];
fst_denom = u63tod(n_diff) / u63tod(n_pairs);
fst_numer = fst_denom - within;
}
} else {
// Weir-Cockerham
const uintptr_t pop1_size = pop_nm_sample_cts_iter[pop_idx1];
const uintptr_t pop2_size = pop_nm_sample_cts_iter[pop_idx2];
pop1_n_hap = pop1_size * 2;
pop2_n_hap = pop2_size * 2;
const uintptr_t n_total = pop1_size + pop2_size;
const double n_total_d = u31tod(n_total);
const double n_total_recip = 1.0 / n_total_d;
const double n_bar = n_total_d * 0.5;
const double n_bar_m1_recip = 1.0 / (n_bar - 1);
const double n_bar_div_n_c = n_bar / (n_total_d - u63tod(pop1_size * pop1_size + pop2_size * pop2_size) * n_total_recip);
const double pop1_size_d = u31tod(pop1_size);
const double pop2_size_d = u31tod(pop2_size);
const double pop1_size_recip = 1.0 / pop1_size_d;
const double pop2_size_recip = 1.0 / pop2_size_d;
double a_sum = 0.0;
double b_sum = 0.0;
double c_sum = 0.0;
const uintptr_t wc_allele_ct = (allele_ct == 2)? 1 : allele_ct;
for (uintptr_t allele_idx = 0; allele_idx != wc_allele_ct; ++allele_idx) {
const uint32_t pop1_cur_allele_ct = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx1];
const uint32_t pop2_cur_allele_ct = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx2];
const uint32_t total_allele_ct = pop1_cur_allele_ct + pop2_cur_allele_ct;
if (!total_allele_ct) {
continue;
}
if (total_allele_ct == 2 * n_total) {
// guaranteed to have no variation; don't want to deal
// with rounding errors, etc.
break;
}
const double pop1_cur_allele_ct_d = u31tod(pop1_cur_allele_ct);
const double pop2_cur_allele_ct_d = u31tod(pop2_cur_allele_ct);
const double pop1_afreq = pop1_cur_allele_ct_d * pop1_size_recip * 0.5;
const double pop2_afreq = pop2_cur_allele_ct_d * pop2_size_recip * 0.5;
const double p_bar = (pop1_cur_allele_ct_d + pop2_cur_allele_ct_d) * 0.5 * n_total_recip;
const double s_squared_pop1_term = pop1_afreq - p_bar;
const double s_squared_pop2_term = pop2_afreq - p_bar;
const double s_squared = (pop1_size_d * s_squared_pop1_term * s_squared_pop1_term + pop2_size_d * s_squared_pop2_term * s_squared_pop2_term) * n_total_recip * 2;
const double h_bar = u31tod(pop_allele_het_cts_iter[allele_idx * pop_ct + pop_idx1] + pop_allele_het_cts_iter[allele_idx * pop_ct + pop_idx2]) * n_total_recip;
const double p_bar_times_1_minus_p_bar = p_bar * (1 - p_bar);
a_sum += n_bar_div_n_c * (s_squared - (p_bar_times_1_minus_p_bar - 0.5 * s_squared - 0.25 * h_bar) * n_bar_m1_recip);
b_sum += n_bar * n_bar_m1_recip * (p_bar_times_1_minus_p_bar - 0.5 * s_squared - (0.5 - 0.5 * n_total_recip) * h_bar);
c_sum += h_bar * 0.5;
}
fst_numer = a_sum;
fst_denom = a_sum + b_sum + c_sum;
}
if ((fst_denom != 0.0) && (fst_numer == fst_numer)) {
fst_numer_sums[pop_pair_bidx] += fst_numer;
fst_denom_sums[pop_pair_bidx] += fst_denom;
const uint32_t new_nobs = fst_nobs[pop_pair_bidx] + 1;
fst_nobs[pop_pair_bidx] = new_nobs;
if (jackknife_next_block_starts && (new_nobs == jackknife_next_block_starts[pop_pair_bidx])) {
const uintptr_t idx_2d = pop_pair_bidx * jackknife_block_max + (new_nobs / jackknife_blocksize) - 1;
const double cur_block_fst_numer_sum = fst_numer_sums[pop_pair_bidx];
const double cur_block_fst_denom_sum = fst_denom_sums[pop_pair_bidx];
jackknife_fst_numers[idx_2d] = cur_block_fst_numer_sum;
jackknife_fst_denoms[idx_2d] = cur_block_fst_denom_sum;
fst_numer_sums[pop_pair_bidx] = 0.0;
fst_denom_sums[pop_pair_bidx] = 0.0;
jackknife_next_block_starts[pop_pair_bidx] = new_nobs + jackknife_blocksize;
}
}
if (!report_variants) {
continue;
}
CompressStreamState* cssp = &(v_css_arr[pop_pair_bidx]);
char* cswritep = v_cswritep_arr[pop_pair_bidx];
// first several columns are practically identical to e.g.
// AppendSdiffPregenoFields(); probably want a library
// function for this
if (chrom_vcol) {
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
}
if (pos_vcol) {
cswritep = u32toa_x(variant_bps[write_variant_uidx], '\t', cswritep);
}
cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]);
if (alleles_needed) {
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (ref_vcol) {
*cswritep++ = '\t';
const char* cur_allele = cur_alleles[0];
const uint32_t allele_slen = strlen(cur_allele);
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) {
v_cswritep_arr[pop_pair_bidx] = cswritep;
goto FstReport_ret_WRITE_FAIL;
}
}
if (alt_vcol) {
*cswritep++ = '\t';
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
const char* cur_allele = cur_alleles[allele_idx];
const uint32_t allele_slen = strlen(cur_allele);
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) {
v_cswritep_arr[pop_pair_bidx] = cswritep;
goto FstReport_ret_WRITE_FAIL;
}
*cswritep++ = ',';
}
--cswritep;
}
if (provref_vcol) {
*cswritep++ = '\t';
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, write_variant_uidx)))? 'Y' : 'N';
}
}
if (nobs_vcol) {
*cswritep++ = '\t';
cswritep = u32toa(pop_nm_sample_cts_iter[pop_idx1] + pop_nm_sample_cts_iter[pop_idx2], cswritep);
}
if (nallele_vcol) {
*cswritep++ = '\t';
cswritep = u32toa_x(pop1_n_hap, '\t', cswritep);
cswritep = u32toa(pop2_n_hap, cswritep);
}
if (fstfrac_vcol) {
*cswritep++ = '\t';
cswritep = dtoa_g(fst_numer, cswritep);
*cswritep++ = '\t';
cswritep = dtoa_g(fst_denom, cswritep);
}
if (fst_vcol) {
*cswritep++ = '\t';
cswritep = dtoa_g(fst_numer / fst_denom, cswritep);
}
AppendBinaryEoln(&cswritep);
if (unlikely(Cswrite(cssp, &cswritep))) {
goto FstReport_ret_WRITE_FAIL;
}
v_cswritep_arr[pop_pair_bidx] = cswritep;
}
if (pop_nm_sample_cts_iter) {
pop_nm_sample_cts_iter = &(pop_nm_sample_cts_iter[pop_ct]);
}
pop_allele_obs_cts_iter = &(pop_allele_obs_cts_iter[pop_ct * allele_ct]);
if (half_within_iter) {
half_within_iter = &(half_within_iter[pop_ct]);
} else {
pop_allele_het_cts_iter = &(pop_allele_het_cts_iter[pop_ct * allele_ct]);
}
}
}
if (variant_idx == cur_variant_ct) {
break;
}
if (variant_idx >= next_print_variant_idx) {
if (pct > 10) {
putc_unlocked('\b', stdout);
}
pct = (variant_idx * 100LLU) / cur_variant_ct;
printf("\b\b%u%%", pct++);
fflush(stdout);
next_print_variant_idx = (pct * S_CAST(uint64_t, cur_variant_ct)) / 100;
}
++read_block_idx;
prev_block_variant_ct = cur_block_variant_ct;
variant_idx += cur_block_variant_ct;
pgfip->block_base = main_loadbufs[parity];
}
for (uintptr_t pop_pair_bidx = 0; pop_pair_bidx != pop_pair_batch_size; ++pop_pair_bidx) {
const uint32_t pop_idx1 = cur_pop_pairs[2 * pop_pair_bidx];
const uint32_t pop_idx2 = cur_pop_pairs[2 * pop_pair_bidx + 1];
const uint32_t nobs = fst_nobs[pop_pair_bidx];
double fst_numer_sum = fst_numer_sums[pop_pair_bidx];
double fst_denom_sum = fst_denom_sums[pop_pair_bidx];
double fst_se = 0.0;
if (jackknife_fst_numers) {
double* block_fst_numers = &(jackknife_fst_numers[pop_pair_bidx * jackknife_block_max]);
double* block_fst_denoms = &(jackknife_fst_denoms[pop_pair_bidx * jackknife_block_max]);
if (nobs > jackknife_blocksize) {
const uint32_t n_block = DivUp(nobs, jackknife_blocksize);
uint32_t prev_block_ct = n_block;
uint32_t last_block_size = jackknife_blocksize;
if (nobs != n_block * jackknife_blocksize) {
--prev_block_ct;
block_fst_numers[prev_block_ct] = fst_numer_sum;
block_fst_denoms[prev_block_ct] = fst_denom_sum;
last_block_size = nobs - (prev_block_ct * jackknife_blocksize);
}
for (uint32_t block_idx = 0; block_idx != prev_block_ct; ++block_idx) {
fst_numer_sum += block_fst_numers[block_idx];
fst_denom_sum += block_fst_denoms[block_idx];
}
const double nobs_d = u31tod(nobs);
const double nobs_recip = 1.0 / nobs_d;
// https://reich.hms.harvard.edu/sites/reich.hms.harvard.edu/files/inline-files/wjack.pdf
const double theta_hat = fst_numer_sum / fst_denom_sum;
// first pass: compute theta_jack
double theta_jack = 0.0;
double cur_block_size_d = u31tod(jackknife_blocksize);
for (uint32_t block_idx = 0; ; ++block_idx) {
if (block_idx >= prev_block_ct) {
if (block_idx > prev_block_ct) {
break;
}
cur_block_size_d = u31tod(last_block_size);
}
// we can avoid computing some of these values twice, but this
// isn't a bottleneck
const double theta_with_j_removed = (fst_numer_sum - block_fst_numers[block_idx]) / (fst_denom_sum - block_fst_denoms[block_idx]);
theta_jack += (theta_hat - theta_with_j_removed) + cur_block_size_d * theta_with_j_removed * nobs_recip;
}
// second pass: compute variance estimate
double main_sum = 0.0;
double hh = nobs_d / u31tod(jackknife_blocksize);
for (uint32_t block_idx = 0; ; ++block_idx) {
if (block_idx >= prev_block_ct) {
if (block_idx > prev_block_ct) {
break;
}
hh = nobs_d / u31tod(last_block_size);
}
const double h_minus_1 = hh - 1.0;
const double theta_with_j_removed = (fst_numer_sum - block_fst_numers[block_idx]) / (fst_denom_sum - block_fst_denoms[block_idx]);
const double tau_j = hh * theta_hat - h_minus_1 * theta_with_j_removed;
const double tau_j_minus_theta_jack = tau_j - theta_jack;
main_sum += tau_j_minus_theta_jack * tau_j_minus_theta_jack / h_minus_1;
}
const double variance_estimate = main_sum / u31tod(n_block);
fst_se = sqrt(variance_estimate);
} else {
if (nobs == jackknife_blocksize) {
fst_numer_sum += block_fst_numers[0];
fst_denom_sum += block_fst_denoms[0];
}
fst_se = 0.0 / 0.0;
}
}
s_write_iter = strcpyax(s_write_iter, pop_names[pop_idx1], '\t');
s_write_iter = strcpyax(s_write_iter, pop_names[pop_idx2], '\t');
if (nobs_scol) {
s_write_iter = u32toa_x(nobs, '\t', s_write_iter);
}
s_write_iter = dtoa_g(fst_numer_sum / fst_denom_sum, s_write_iter);
if (jackknife_blocksize) {
*s_write_iter++ = '\t';
s_write_iter = dtoa_g(fst_se, s_write_iter);
}
AppendBinaryEoln(&s_write_iter);
if (unlikely(fwrite_ck(s_textbuf_flush, s_outfile, &s_write_iter))) {
goto FstReport_ret_WRITE_FAIL;
}
}
if (report_variants) {
for (uintptr_t fidx = 0; fidx != pop_pair_batch_size; ++fidx) {
if (unlikely(CswriteCloseNull(&(v_css_arr[fidx]), v_cswritep_arr[fidx]))) {
goto FstReport_ret_WRITE_FAIL;
}
}
}
if (pct > 10) {
putc_unlocked('\b', stdout);
}
fputs("\b\b", stdout);
logputs("done.\n");
BigstackReset(bigstack_mark3);
}
if (report_variants) {
logprintf("%s --fst: %u .fst.var%s file%s written.\n", is_x? "chrX" : "Autosomal", pop_pair_ct, v_output_zst? ".zst" : "", (pop_pair_ct == 1)? "" : "s");
strcpy_k(outname_end2, ".fst.summary");
}
if (unlikely(fclose_flush_null(s_textbuf_flush, s_write_iter, &s_outfile))) {
goto FstReport_ret_WRITE_FAIL;
}
logprintfww("%s --fst: Summary written to %s .\n", is_x? "chrX" : "Autosomal", outname);
BigstackReset(bigstack_mark2);
}
}
while (0) {
FstReport_ret_NOMEM:
reterr = kPglRetNomem;
break;
FstReport_ret_PGR_FAIL:
PgenErrPrintN(reterr);
break;
FstReport_ret_OPEN_FAIL:
reterr = kPglRetOpenFail;
break;
FstReport_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
FstReport_ret_INVALID_CMDLINE:
reterr = kPglRetInvalidCmdline;
break;
FstReport_ret_TSTREAM_FAIL:
TextStreamErrPrint("--fst file", &txs);
break;
FstReport_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
FstReport_ret_PHENO_NOT_FOUND:
logerrprintfww("Error: --fst phenotype '%s' not loaded.\n", fst_infop->pheno_name);
FstReport_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
FstReport_ret_THREAD_CREATE_FAIL:
reterr = kPglRetThreadCreateFail;
break;
}
FstReport_ret_1:
if (v_css_arr) {
for (uintptr_t fidx = 0; fidx != max_variant_file_ct; ++fidx) {
CswriteCloseCond(&(v_css_arr[fidx]), v_cswritep_arr[fidx]);
}
}
CleanupThreads(&tg);
fclose_cond(s_outfile);
CleanupTextStream2("--fst file", &txs, &reterr);
BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
pgfip->block_base = nullptr;
return reterr;
}
typedef struct AlleleUniquenessCheckerStruct {
const uintptr_t* variant_include;
const uintptr_t* allele_idx_offsets;
const char* const* allele_storage;
uint32_t* variant_uidx_starts;
const char*** allele_sortbufs;
uint32_t variant_ct;
uint32_t dup_vidx; // UINT32_MAX if no variant found with duplicate alleles
} AlleleUniquenessChecker;
void CheckAlleleUniquenessMain(uint32_t tidx, uint32_t thread_ct, AlleleUniquenessChecker* ctx) {
const uintptr_t* variant_include = ctx->variant_include;
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
const char* const* allele_storage = ctx->allele_storage;
const char** allele_sortbuf = ctx->allele_sortbufs? ctx->allele_sortbufs[tidx] : nullptr;
const uint32_t variant_ct = ctx->variant_ct;
const uint32_t variant_uidx_start = ctx->variant_uidx_starts[tidx];
const uint32_t variant_idx_start = (variant_ct * S_CAST(uint64_t, tidx)) / thread_ct;
const uint32_t variant_idx_end = (variant_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct;
uint32_t cur_allele_ct = 2;
uintptr_t variant_uidx_base;
uintptr_t cur_bits;
BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits);
for (uint32_t variant_idx = variant_idx_start; variant_idx != variant_idx_end; ++variant_idx) {
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
uintptr_t allele_idx_offset_base = 2 * variant_uidx;
if (allele_idx_offsets) {
allele_idx_offset_base = allele_idx_offsets[variant_uidx];
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
}
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
if (cur_allele_ct == 2) {
if (unlikely(strequal_overread(cur_alleles[0], cur_alleles[1]))) {
UpdateU32IfSmaller(variant_uidx, &(ctx->dup_vidx));
return;
}
} else {
memcpy(allele_sortbuf, cur_alleles, cur_allele_ct * sizeof(intptr_t));
StrptrArrSortOverread(cur_allele_ct, allele_sortbuf);
const char* prev_allele = allele_sortbuf[0];
for (uint32_t aidx = 1; aidx != cur_allele_ct; ++aidx) {
const char* cur_allele = allele_sortbuf[aidx];
if (unlikely(strequal_overread(prev_allele, cur_allele))) {
UpdateU32IfSmaller(variant_uidx, &(ctx->dup_vidx));
return;
}
cur_allele = prev_allele;
}
}
}
}
THREAD_FUNC_DECL CheckAlleleUniquenessThread(void* raw_arg) {
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
const uint32_t tidx = arg->tidx;
const uint32_t thread_ct = GetThreadCt(arg->sharedp) + 1;
AlleleUniquenessChecker* ctx = S_CAST(AlleleUniquenessChecker*, arg->sharedp->context);
CheckAlleleUniquenessMain(tidx, thread_ct, ctx);
THREAD_RETURN;
}
PglErr CheckAlleleUniqueness(const uintptr_t* variant_include, const ChrInfo* cip, const ChrIdx* chr_idxs, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_thread_ct) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
ThreadGroup tg;
PreinitThreads(&tg);
AlleleUniquenessChecker ctx;
{
const uint32_t thread_ct = ClipU32(variant_ct / 65536, 1, max_thread_ct);
if (unlikely(SetThreadCt0(thread_ct - 1, &tg) ||
bigstack_alloc_u32(thread_ct, &ctx.variant_uidx_starts))) {
goto CheckAlleleUniqueness_ret_NOMEM;
}
if (max_allele_ct == 2) {
ctx.allele_sortbufs = nullptr;
} else {
if (unlikely(bigstack_alloc_kcpp(thread_ct, &ctx.allele_sortbufs))) {
goto CheckAlleleUniqueness_ret_NOMEM;
}
for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) {
if (unlikely(bigstack_alloc_kcp(max_allele_ct, &(ctx.allele_sortbufs[tidx])))) {
goto CheckAlleleUniqueness_ret_NOMEM;
}
}
}
ctx.variant_include = variant_include;
ctx.allele_idx_offsets = allele_idx_offsets;
ctx.allele_storage = allele_storage;
ctx.variant_ct = variant_ct;
ctx.dup_vidx = UINT32_MAX;
FillU32SubsetStarts(variant_include, thread_ct, 0, variant_ct, ctx.variant_uidx_starts);
if (thread_ct > 1) {
SetThreadFuncAndData(CheckAlleleUniquenessThread, &ctx, &tg);
DeclareLastThreadBlock(&tg);
if (unlikely(SpawnThreads(&tg))) {
goto CheckAlleleUniqueness_ret_THREAD_CREATE_FAIL;
}
}
CheckAlleleUniquenessMain(thread_ct - 1, thread_ct, &ctx);
JoinThreads0(&tg);
const uint32_t dup_vidx = ctx.dup_vidx;
if (unlikely(dup_vidx != UINT32_MAX)) {
// Not a big deal, but best to make this still work when split
// chromosomes are present.
const uint32_t chr_idx = chr_idxs? chr_idxs[dup_vidx] : GetVariantChr(cip, dup_vidx);
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate allele code in variant '");
write_iter = strcpya(write_iter, variant_ids[dup_vidx]);
write_iter = strcpya_k(write_iter, "' at position ");
write_iter = chrtoa(cip, chr_idx, write_iter);
*write_iter++ = ':';
write_iter = u32toa(variant_bps[dup_vidx], write_iter);
strcpy_k(write_iter, ".\n");
WordWrapB(0);
logerrputsb();
reterr = kPglRetInconsistentInput;
}
}
while (0) {
CheckAlleleUniqueness_ret_NOMEM:
reterr = kPglRetNomem;
break;
CheckAlleleUniqueness_ret_THREAD_CREATE_FAIL:
reterr = kPglRetThreadCreateFail;
break;
}
CleanupThreads(&tg);
BigstackReset(bigstack_mark);
return reterr;
}
#ifdef __cplusplus
} // namespace plink2
#endif
|