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
|
/*
* Copyright 2011, Ben Langmead <langmea@cs.jhu.edu>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 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.
*
* Bowtie 2 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 Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <dirent.h>
#include <fstream>
#include <getopt.h>
#include <iostream>
#include <limits>
#include <math.h>
#include <stdexcept>
#include <stdlib.h>
#include <string>
#include <thread>
#include <time.h>
#include <utility>
#ifndef _WIN32
#include <signal.h>
#endif
#include "alphabet.h"
#include "assert_helpers.h"
#include "endian_swap.h"
#include "bt2_idx.h"
#include "formats.h"
#include "sequence_io.h"
#include "tokenize.h"
#include "aln_sink.h"
#include "pat.h"
#include "threading.h"
#include "ds.h"
#include "aligner_metrics.h"
#include "sam.h"
#include "aligner_seed.h"
#include "aligner_seed_policy.h"
#include "aligner_driver.h"
#include "aligner_sw.h"
#include "aligner_sw_driver.h"
#include "aligner_cache.h"
#include "util.h"
#include "pe.h"
#include "simple_func.h"
#include "presets.h"
#include "opts.h"
#include "outq.h"
#include "aligner_seed2.h"
#include "bt2_search.h"
using namespace std;
static int FNAME_SIZE;
static std::atomic<int> thread_counter;
static EList<string> mates1; // mated reads (first mate)
static EList<string> mates2; // mated reads (second mate)
static EList<string> mates12; // mated reads (1st/2nd interleaved in 1 file)
static string adjIdxBase;
int gVerbose; // be talkative
static bool startVerbose; // be talkative at startup
int gQuiet; // print nothing but the alignments
static int sanityCheck; // enable expensive sanity checks
static int format; // default read format is FASTQ
static bool interleaved; // reads are interleaved
static string origString; // reference text, or filename(s)
static int seed; // srandom() seed
static int timing; // whether to report basic timing data
static int metricsIval; // interval between alignment metrics messages (0 = no messages)
static string metricsFile;// output file to put alignment metrics in
static bool metricsStderr;// output file to put alignment metrics in
static bool metricsPerRead; // report a metrics tuple for every read
static bool allHits; // for multihits, report just one
static bool deterministicSeeds; // for low quality seeds, enable subsampling
static bool showVersion; // just print version and quit?
static int ipause; // pause before maching?
static uint64_t qUpto; // max # of queries to read
static int gTrim5; // amount to trim from 5' end
static int gTrim3; // amount to trim from 3' end
static pair<short, size_t> trimTo; // trim reads exceeding given length from either 3' or 5'-end
static int offRate; // keep default offRate
static bool solexaQuals; // quality strings are solexa quals, not phred, and subtract 64 (not 33)
static bool phred64Quals; // quality chars are phred, but must subtract 64 (not 33)
static bool integerQuals; // quality strings are space-separated strings of integers, not ASCII
static int nthreads; // number of pthreads operating concurrently
static int thread_ceiling;// maximum number of threads user wants bowtie to use
static string thread_stealing_dir; // keep track of pids in this directory
static bool thread_stealing;// true iff thread stealing is in use
static int outType; // style of output
static bool noRefNames; // true -> print reference indexes; not names
static uint32_t lowseeds; // size of seed range above which a seed is considered low quality, and thus discarded (0 disables the cut)
static uint32_t lowseedsDivider; // how much should I divide the lowseeds parameter by, if 0 use abs value
static uint32_t khits; // number of hits per read; >1 is much slower
static uint32_t mhits; // don't report any hits if there are > mhits
static int partitionSz; // output a partitioning key in first field
static int readsPerBatch; // # reads to read from input file at once
static bool fileParallel; // separate threads read separate input files in parallel
static bool useShmem; // use shared memory to hold the index
static bool useMm; // use memory-mapped files to hold the index
static bool mmSweep; // sweep through memory-mapped files immediately after mapping
int gMinInsert; // minimum insert size
int gMaxInsert; // maximum insert size
bool gMate1fw; // -1 mate aligns in fw orientation on fw strand
bool gMate2fw; // -2 mate aligns in rc orientation on fw strand
bool gFlippedMatesOK; // allow mates to be in wrong order
bool gDovetailMatesOK; // allow one mate to extend off the end of the other
bool gContainMatesOK; // allow one mate to contain the other in PE alignment
bool gOlapMatesOK; // allow mates to overlap in PE alignment
bool gExpandToFrag; // incr max frag length to =larger mate len if necessary
bool gReportDiscordant; // find and report discordant paired-end alignments
bool gReportMixed; // find and report unpaired alignments for paired reads
static uint32_t cacheLimit; // ranges w/ size > limit will be cached
static uint32_t cacheSize; // # words per range cache
static uint32_t skipReads; // # reads/read pairs to skip
bool gNofw; // don't align fw orientation of read
bool gNorc; // don't align rc orientation of read
static uint32_t fastaContLen;
static uint32_t fastaContFreq;
static bool hadoopOut; // print Hadoop status and summary messages
static bool fullRef;
static bool samTruncQname; // whether to truncate QNAME to 255 chars
static bool samAppendComment; // append FASTA/FASTQ comment to SAM record
static bool samOmitSecSeqQual; // omit SEQ/QUAL for 2ndary alignments?
static bool samNoUnal; // don't print records for unaligned reads
static bool samNoHead; // don't print any header lines in SAM output
static bool samNoSQ; // don't print @SQ header lines
static bool sam_print_as;
static bool sam_print_xs; // XS:i
static bool sam_print_xss; // Xs:i and Ys:i
static bool sam_print_yn; // YN:i and Yn:i
static bool sam_print_xn;
static bool sam_print_x0;
static bool sam_print_x1;
static bool sam_print_xm;
static bool sam_print_xo;
static bool sam_print_xg;
static bool sam_print_nm;
static bool sam_print_md;
static bool sam_print_yf;
static bool sam_print_yi;
static bool sam_print_ym;
static bool sam_print_yp;
static bool sam_print_yt;
static bool sam_print_ys;
static bool sam_print_zs;
static bool sam_print_xr;
static bool sam_print_xt;
static bool sam_print_xd;
static bool sam_print_xu;
static bool sam_print_yl;
static bool sam_print_ye;
static bool sam_print_yu;
static bool sam_print_xp;
static bool sam_print_yr;
static bool sam_print_zb;
static bool sam_print_zr;
static bool sam_print_zf;
static bool sam_print_zm;
static bool sam_print_zi;
static bool sam_print_zp;
static bool sam_print_zu;
static bool sam_print_zt;
static EList<string> sam_opt_flags;
static bool preserve_tags; // Only applies when aligning BAM files
static bool align_paired_reads; // Process only the paired reads in BAM file
static bool bwaSwLike;
static bool gSeedLenIsSet;
static float bwaSwLikeC;
static float bwaSwLikeT;
static bool qcFilter;
bool gReportOverhangs; // false -> filter out alignments that fall off the end of a reference sequence
static string rgid; // ID: setting for @RG header line
static string rgs; // SAM outputs for @RG header line
static string rgs_optflag; // SAM optional flag to add corresponding to @RG ID
static bool msample; // whether to report a random alignment when maxed-out via -m/-M
int gGapBarrier; // # diags on top/bot only to be entered diagonally
int gDefaultSeedLen;
static EList<string> qualities;
static EList<string> qualities1;
static EList<string> qualities2;
static string polstr; // temporary holder for policy string
static bool msNoCache; // true -> disable local cache
static int bonusMatchType; // how to reward matches
static int bonusMatch; // constant reward if bonusMatchType=constant
static int penMmcType; // how to penalize mismatches
static int penMmcMax; // max mm penalty
static int penMmcMin; // min mm penalty
static int penNType; // how to penalize Ns in the read
static int penN; // constant if N pelanty is a constant
static bool penNCatPair; // concatenate mates before N filtering?
static bool localAlign; // do local alignment in DP steps
static bool noisyHpolymer; // set to true if gap penalties should be reduced to be consistent with a sequencer that under- and overcalls homopolymers
static int penRdGapConst; // constant cost of extending a gap in the read
static int penRfGapConst; // constant cost of extending a gap in the reference
static int penRdGapLinear; // coeff of linear term for cost of gap extension in read
static int penRfGapLinear; // coeff of linear term for cost of gap extension in ref
static SimpleFunc scoreMin; // minimum valid score as function of read len
static SimpleFunc nCeil; // max # Ns allowed as function of read len
static SimpleFunc msIval; // interval between seeds as function of read len
static double descConsExp; // how to adjust score minimum as we descent further into index-assisted alignment
static bool descPrioritizeRoots; // whether to prioritize search roots with scores
static size_t descLanding; // don't place a search root if it's within this many positions of end
static SimpleFunc descentTotSz; // maximum space a DescentDriver can use in bytes
static SimpleFunc descentTotFmops; // maximum # FM ops a DescentDriver can perform
static int multiseedMms; // mismatches permitted in a multiseed seed
static int multiseedLen; // length of multiseed seeds
static size_t multiseedOff; // offset to begin extracting seeds
static uint32_t seedCacheLocalMB; // # MB to use for non-shared seed alignment cacheing
static uint32_t seedCacheCurrentMB; // # MB to use for current-read seed hit cacheing
static uint32_t exactCacheCurrentMB; // # MB to use for current-read seed hit cacheing
static size_t maxhalf; // max width on one side of DP table
static bool seedSumm; // print summary information about seed hits, not alignments
static bool scUnMapped; // consider soft-clipped bases unmapped when calculating TLEN
static bool doUngapped; // do ungapped alignment
static bool xeq; // use X/= instead of M in CIGAR string
static size_t maxIters; // stop after this many extend loop iterations
static size_t maxUg; // stop after this many ungap extends
static size_t maxDp; // stop after this many DPs
static size_t maxItersIncr; // amt to add to maxIters for each -k > 1
static size_t maxEeStreak; // stop after this many end-to-end fails in a row
static size_t maxUgStreak; // stop after this many ungap fails in a row
static size_t maxDpStreak; // stop after this many dp fails in a row
static size_t maxStreakIncr; // amt to add to streak for each -k > 1
static size_t maxMateStreak; // stop seed range after this many mate-find fails
static bool doExtend; // extend seed hits
static bool enable8; // use 8-bit SSE where possible?
static size_t cminlen; // longer reads use checkpointing
static size_t cpow2; // checkpoint interval log2
static bool doTri; // do triangular mini-fills?
static string defaultPreset; // default preset; applied immediately
static bool ignoreQuals; // all mms incur same penalty, regardless of qual
static string wrapper; // type of wrapper script, so we can print correct usage
static EList<string> queries; // list of query files
static string outfile; // write SAM output to this file
static int mapqv; // MAPQ calculation version
static int tighten; // -M tighten mode (0=none, 1=best, 2=secbest+1)
static bool doExactUpFront; // do exact search up front if seeds seem good enough
static bool do1mmUpFront; // do 1mm search up front if seeds seem good enough
static size_t do1mmMinLen; // length below which we disable 1mm e2e search
static size_t seedBoostThresh; // if average non-zero position has more than this many elements
static size_t nSeedRounds; // # seed rounds
static bool reorder; // true -> reorder SAM recs in -p mode
static float sampleFrac; // only align random fraction of input reads
static bool arbitraryRandom; // pseudo-randoms no longer a function of read properties
static bool bowtie2p5;
static string logDps; // log seed-extend dynamic programming problems
static string logDpsOpp; // log mate-search dynamic programming problems
static string bt2index; // read Bowtie 2 index from files with this prefix
static EList<pair<int, string> > extra_opts;
static size_t extra_opts_cur;
#ifdef USE_SRA
static EList<string> sra_accs;
#endif
#define DMAX std::numeric_limits<double>::max()
static void set_format(int ¤t_format, file_format format) {
if (current_format == UNKNOWN)
current_format = format;
else {
std::cerr << file_format_names[current_format] << " and "
<< file_format_names[format] << " formats are "
<< "mutually exclusive." << std::endl;
exit(1);
}
}
int set_default_thread_count() {
int num_threads = 1;
const char *omp_num_threads = NULL;
if ((omp_num_threads = getenv("OMP_NUM_THREADS")) != NULL) {
try {
num_threads = std::stoi(omp_num_threads);
} catch (std::invalid_argument const &ex) {
std::cerr << "Error: " << ex.what() << std::endl;
exit(EXIT_FAILURE);
} catch (std::out_of_range const &ex) {
std::cerr << "Error: " << ex.what() << std::endl;
exit(EXIT_FAILURE);
}
}
return num_threads;
}
static void resetOptions() {
mates1.clear();
mates2.clear();
mates12.clear();
adjIdxBase = "";
gVerbose = 0;
startVerbose = 0;
gQuiet = false;
sanityCheck = 0; // enable expensive sanity checks
format = UNKNOWN; // default read format is FASTQ
interleaved = false; // reads are not interleaved by default
origString = ""; // reference text, or filename(s)
seed = 0; // srandom() seed
timing = 0; // whether to report basic timing data
metricsIval = 1; // interval between alignment metrics messages (0 = no messages)
metricsFile = ""; // output file to put alignment metrics in
metricsStderr = false; // print metrics to stderr (in addition to --metrics-file if it's specified
metricsPerRead = false; // report a metrics tuple for every read?
allHits = false; // for multihits, report just one
deterministicSeeds = false; // for low quality seeds, enable subsampling
showVersion = false; // just print version and quit?
ipause = 0; // pause before maching?
qUpto = 0xffffffffffffffff; // max # of queries to read
gTrim5 = 0; // amount to trim from 5' end
gTrim3 = 0; // amount to trim from 3' end
trimTo = pair<short, size_t>(5, 0); // default: don't do any trimming
offRate = -1; // keep default offRate
solexaQuals = false; // quality strings are solexa quals, not phred, and subtract 64 (not 33)
phred64Quals = false; // quality chars are phred, but must subtract 64 (not 33)
integerQuals = false; // quality strings are space-separated strings of integers, not ASCII
nthreads = set_default_thread_count(); // number of pthreads operating concurrently
thread_ceiling = 0; // max # threads user asked for
thread_stealing_dir = ""; // keep track of pids in this directory
thread_stealing = false; // true iff thread stealing is in use
FNAME_SIZE = 4096;
outType = OUTPUT_SAM; // style of output
noRefNames = false; // true -> print reference indexes; not names
lowseeds = 0; // size of seed range above which a seed is considered low quality, and thus discarded (0 disables the cut)
lowseedsDivider = 0; // how much should I divide the lowseeds parameter by, if 0 use the abs value
khits = 1; // number of hits per read; >1 is much slower
mhits = 50; // stop after finding this many alignments+1
partitionSz = 0; // output a partitioning key in first field
readsPerBatch = 16; // # reads to read from input file at once
fileParallel = false; // separate threads read separate input files in parallel
useShmem = false; // use shared memory to hold the index
useMm = false; // use memory-mapped files to hold the index
mmSweep = false; // sweep through memory-mapped files immediately after mapping
gMinInsert = 0; // minimum insert size
gMaxInsert = 500; // maximum insert size
gMate1fw = true; // -1 mate aligns in fw orientation on fw strand
gMate2fw = false; // -2 mate aligns in rc orientation on fw strand
gFlippedMatesOK = false; // allow mates to be in wrong order
gDovetailMatesOK = false; // allow one mate to extend off the end of the other
gContainMatesOK = true; // allow one mate to contain the other in PE alignment
gOlapMatesOK = true; // allow mates to overlap in PE alignment
gExpandToFrag = true; // incr max frag length to =larger mate len if necessary
gReportDiscordant = true; // find and report discordant paired-end alignments
gReportMixed = true; // find and report unpaired alignments for paired reads
cacheLimit = 5; // ranges w/ size > limit will be cached
cacheSize = 0; // # words per range cache
skipReads = 0; // # reads/read pairs to skip
gNofw = false; // don't align fw orientation of read
gNorc = false; // don't align rc orientation of read
fastaContLen = 0;
fastaContFreq = 0;
hadoopOut = false; // print Hadoop status and summary messages
fullRef = false; // print entire reference name instead of just up to 1st space
samTruncQname = true; // whether to truncate QNAME to 255 chars
samAppendComment = false; // append FASTA/Q comment to SAM record
samOmitSecSeqQual = false; // omit SEQ/QUAL for 2ndary alignments?
samNoUnal = false; // omit SAM records for unaligned reads
samNoHead = false; // don't print any header lines in SAM output
samNoSQ = false; // don't print @SQ header lines
sam_print_as = true;
sam_print_xs = true;
sam_print_xss = false; // Xs:i and Ys:i
sam_print_yn = false; // YN:i and Yn:i
sam_print_xn = true;
sam_print_x0 = true;
sam_print_x1 = true;
sam_print_xm = true;
sam_print_xo = true;
sam_print_xg = true;
sam_print_nm = true;
sam_print_md = true;
sam_print_yf = true;
sam_print_yi = false;
sam_print_ym = false;
sam_print_yp = false;
sam_print_yt = true;
sam_print_ys = true;
sam_print_zs = false;
sam_print_xr = false;
sam_print_xt = false;
sam_print_xd = false;
sam_print_xu = false;
sam_print_yl = false;
sam_print_ye = false;
sam_print_yu = false;
sam_print_xp = false;
sam_print_yr = false;
sam_print_zb = false;
sam_print_zr = false;
sam_print_zf = false;
sam_print_zm = false;
sam_print_zi = false;
sam_print_zp = false;
sam_print_zu = false;
sam_print_zt = false;
preserve_tags = false;
align_paired_reads = false;
bwaSwLike = false;
gSeedLenIsSet = false;
bwaSwLikeC = 5.5f;
bwaSwLikeT = 20.0f;
gDefaultSeedLen = DEFAULT_SEEDLEN;
qcFilter = false; // don't believe upstream qc by default
rgid = ""; // SAM outputs for @RG header line
rgs = ""; // SAM outputs for @RG header line
rgs_optflag = ""; // SAM optional flag to add corresponding to @RG ID
msample = true;
gGapBarrier = 4; // disallow gaps within this many chars of either end of alignment
qualities.clear();
qualities1.clear();
qualities2.clear();
polstr.clear();
msNoCache = true; // true -> disable local cache
bonusMatchType = DEFAULT_MATCH_BONUS_TYPE;
bonusMatch = DEFAULT_MATCH_BONUS;
penMmcType = DEFAULT_MM_PENALTY_TYPE;
penMmcMax = DEFAULT_MM_PENALTY_MAX;
penMmcMin = DEFAULT_MM_PENALTY_MIN;
penNType = DEFAULT_N_PENALTY_TYPE;
penN = DEFAULT_N_PENALTY;
penNCatPair = DEFAULT_N_CAT_PAIR; // concatenate mates before N filtering?
localAlign = false; // do local alignment in DP steps
noisyHpolymer = false;
penRdGapConst = DEFAULT_READ_GAP_CONST;
penRfGapConst = DEFAULT_REF_GAP_CONST;
penRdGapLinear = DEFAULT_READ_GAP_LINEAR;
penRfGapLinear = DEFAULT_REF_GAP_LINEAR;
scoreMin.init (SIMPLE_FUNC_LINEAR, DEFAULT_MIN_CONST, DEFAULT_MIN_LINEAR);
nCeil.init (SIMPLE_FUNC_LINEAR, 0.0f, DMAX, 2.0f, 0.1f);
msIval.init (SIMPLE_FUNC_LINEAR, 1.0f, DMAX, DEFAULT_IVAL_B, DEFAULT_IVAL_A);
descConsExp = 2.0;
descPrioritizeRoots = false;
descLanding = 20;
descentTotSz.init(SIMPLE_FUNC_LINEAR, 1024.0, DMAX, 0.0, 1024.0);
descentTotFmops.init(SIMPLE_FUNC_LINEAR, 100.0, DMAX, 0.0, 10.0);
multiseedMms = DEFAULT_SEEDMMS;
multiseedLen = gDefaultSeedLen;
multiseedOff = 0;
seedCacheLocalMB = 32; // # MB to use for non-shared seed alignment cacheing
seedCacheCurrentMB = 20; // # MB to use for current-read seed hit cacheing
exactCacheCurrentMB = 20; // # MB to use for current-read seed hit cacheing
maxhalf = 15; // max width on one side of DP table
seedSumm = false; // print summary information about seed hits, not alignments
scUnMapped = false; // consider soft clipped bases unmapped when calculating TLEN
xeq = false; // use =/X instead of M in CIGAR string
doUngapped = true; // do ungapped alignment
maxIters = 400; // max iterations of extend loop
maxUg = 300; // stop after this many ungap extends
maxDp = 300; // stop after this many dp extends
maxItersIncr = 20; // amt to add to maxIters for each -k > 1
maxEeStreak = 15; // stop after this many end-to-end fails in a row
maxUgStreak = 15; // stop after this many ungap fails in a row
maxDpStreak = 15; // stop after this many dp fails in a row
maxStreakIncr = 10; // amt to add to streak for each -k > 1
maxMateStreak = 10; // in PE: abort seed range after N mate-find fails
doExtend = true; // do seed extensions
enable8 = true; // use 8-bit SSE where possible?
cminlen = 2000; // longer reads use checkpointing
cpow2 = 4; // checkpoint interval log2
doTri = false; // do triangular mini-fills?
defaultPreset = "sensitive%LOCAL%"; // default preset; applied immediately
extra_opts.clear();
extra_opts_cur = 0;
bt2index.clear(); // read Bowtie 2 index from files with this prefix
ignoreQuals = false; // all mms incur same penalty, regardless of qual
wrapper.clear(); // type of wrapper script, so we can print correct usage
queries.clear(); // list of query files
outfile.clear(); // write SAM output to this file
mapqv = 2; // MAPQ calculation version
tighten = 3; // -M tightening mode
doExactUpFront = true; // do exact search up front if seeds seem good enough
do1mmUpFront = true; // do 1mm search up front if seeds seem good enough
seedBoostThresh = 300; // if average non-zero position has more than this many elements
nSeedRounds = 2; // # rounds of seed searches to do for repetitive reads
do1mmMinLen = 60; // length below which we disable 1mm search
reorder = false; // reorder SAM records with -p > 1
sampleFrac = 1.1f; // align all reads
arbitraryRandom = false; // let pseudo-random seeds be a function of read properties
bowtie2p5 = false;
logDps.clear(); // log seed-extend dynamic programming problems
logDpsOpp.clear(); // log mate-search dynamic programming problems
#ifdef USE_SRA
sra_accs.clear();
#endif
}
static const char *short_options = "bfF:qbzhcu:rv:s:adP:t3:5:w:p:k:l:M:1:2:I:X:CQ:N:i:L:U:x:S:g:O:D:R:";
static struct option long_options[] = {
{(char*)"verbose", no_argument, 0, ARG_VERBOSE},
{(char*)"startverbose", no_argument, 0, ARG_STARTVERBOSE},
{(char*)"quiet", no_argument, 0, ARG_QUIET},
{(char*)"sanity", no_argument, 0, ARG_SANITY},
{(char*)"pause", no_argument, &ipause, 1},
{(char*)"orig", required_argument, 0, ARG_ORIG},
{(char*)"all", no_argument, 0, 'a'},
{(char*)"solexa-quals", no_argument, 0, ARG_SOLEXA_QUALS},
{(char*)"integer-quals", no_argument, 0, ARG_INTEGER_QUALS},
{(char*)"int-quals", no_argument, 0, ARG_INTEGER_QUALS},
{(char*)"metrics", required_argument, 0, ARG_METRIC_IVAL},
{(char*)"metrics-file", required_argument, 0, ARG_METRIC_FILE},
{(char*)"metrics-stderr", no_argument, 0, ARG_METRIC_STDERR},
{(char*)"metrics-per-read", no_argument, 0, ARG_METRIC_PER_READ},
{(char*)"met-read", no_argument, 0, ARG_METRIC_PER_READ},
{(char*)"met", required_argument, 0, ARG_METRIC_IVAL},
{(char*)"met-file", required_argument, 0, ARG_METRIC_FILE},
{(char*)"met-stderr", no_argument, 0, ARG_METRIC_STDERR},
{(char*)"time", no_argument, 0, 't'},
{(char*)"trim3", required_argument, 0, '3'},
{(char*)"trim5", required_argument, 0, '5'},
{(char*)"seed", required_argument, 0, ARG_SEED},
{(char*)"qupto", required_argument, 0, 'u'},
{(char*)"upto", required_argument, 0, 'u'},
{(char*)"version", no_argument, 0, ARG_VERSION},
{(char*)"reads-per-batch", required_argument, 0, ARG_READS_PER_BATCH},
{(char*)"filepar", no_argument, 0, ARG_FILEPAR},
{(char*)"help", no_argument, 0, 'h'},
{(char*)"threads", required_argument, 0, 'p'},
{(char*)"khits", required_argument, 0, 'k'},
{(char*)"lowseeds", required_argument, 0, 'l'},
{(char*)"minins", required_argument, 0, 'I'},
{(char*)"maxins", required_argument, 0, 'X'},
{(char*)"quals", required_argument, 0, 'Q'},
{(char*)"Q1", required_argument, 0, ARG_QUALS1},
{(char*)"Q2", required_argument, 0, ARG_QUALS2},
{(char*)"refidx", no_argument, 0, ARG_REFIDX},
{(char*)"partition", required_argument, 0, ARG_PARTITION},
{(char*)"ff", no_argument, 0, ARG_FF},
{(char*)"fr", no_argument, 0, ARG_FR},
{(char*)"rf", no_argument, 0, ARG_RF},
{(char*)"cachelim", required_argument, 0, ARG_CACHE_LIM},
{(char*)"cachesz", required_argument, 0, ARG_CACHE_SZ},
{(char*)"nofw", no_argument, 0, ARG_NO_FW},
{(char*)"norc", no_argument, 0, ARG_NO_RC},
{(char*)"skip", required_argument, 0, 's'},
{(char*)"12", required_argument, 0, ARG_ONETWO},
{(char*)"tab5", required_argument, 0, ARG_TAB5},
{(char*)"tab6", required_argument, 0, ARG_TAB6},
{(char*)"interleaved", required_argument, 0, ARG_INTERLEAVED},
{(char*)"phred33-quals", no_argument, 0, ARG_PHRED33},
{(char*)"phred64-quals", no_argument, 0, ARG_PHRED64},
{(char*)"phred33", no_argument, 0, ARG_PHRED33},
{(char*)"phred64", no_argument, 0, ARG_PHRED64},
{(char*)"solexa1.3-quals", no_argument, 0, ARG_PHRED64},
{(char*)"mm", no_argument, 0, ARG_MM},
{(char*)"shmem", no_argument, 0, ARG_SHMEM},
{(char*)"mmsweep", no_argument, 0, ARG_MMSWEEP},
{(char*)"hadoopout", no_argument, 0, ARG_HADOOPOUT},
{(char*)"fullref", no_argument, 0, ARG_FULLREF},
{(char*)"usage", no_argument, 0, ARG_USAGE},
{(char*)"sam-no-qname-trunc", no_argument, 0, ARG_SAM_NO_QNAME_TRUNC},
{(char*)"sam-omit-sec-seq", no_argument, 0, ARG_SAM_OMIT_SEC_SEQ},
{(char*)"omit-sec-seq", no_argument, 0, ARG_SAM_OMIT_SEC_SEQ},
{(char*)"sam-no-head", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"sam-nohead", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"sam-noHD", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"sam-no-hd", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"sam-nosq", no_argument, 0, ARG_SAM_NOSQ},
{(char*)"sam-no-sq", no_argument, 0, ARG_SAM_NOSQ},
{(char*)"sam-noSQ", no_argument, 0, ARG_SAM_NOSQ},
{(char*)"no-head", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"no-hd", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"no-sq", no_argument, 0, ARG_SAM_NOSQ},
{(char*)"no-HD", no_argument, 0, ARG_SAM_NOHEAD},
{(char*)"no-SQ", no_argument, 0, ARG_SAM_NOSQ},
{(char*)"no-unal", no_argument, 0, ARG_SAM_NO_UNAL},
{(char*)"sam-RG", required_argument, 0, ARG_SAM_RG},
{(char*)"sam-rg", required_argument, 0, ARG_SAM_RG},
{(char*)"sam-rg-id", required_argument, 0, ARG_SAM_RGID},
{(char*)"RG", required_argument, 0, ARG_SAM_RG},
{(char*)"rg", required_argument, 0, ARG_SAM_RG},
{(char*)"rg-id", required_argument, 0, ARG_SAM_RGID},
{(char*)"snpphred", required_argument, 0, ARG_SNPPHRED},
{(char*)"snpfrac", required_argument, 0, ARG_SNPFRAC},
{(char*)"gbar", required_argument, 0, ARG_GAP_BAR},
{(char*)"qseq", no_argument, 0, ARG_QSEQ},
{(char*)"policy", required_argument, 0, ARG_ALIGN_POLICY},
{(char*)"preset", required_argument, 0, 'P'},
{(char*)"seed-summ", no_argument, 0, ARG_SEED_SUMM},
{(char*)"seed-summary", no_argument, 0, ARG_SEED_SUMM},
{(char*)"overhang", no_argument, 0, ARG_OVERHANG},
{(char*)"no-cache", no_argument, 0, ARG_NO_CACHE},
{(char*)"cache", no_argument, 0, ARG_USE_CACHE},
{(char*)"454", no_argument, 0, ARG_NOISY_HPOLY},
{(char*)"ion-torrent", no_argument, 0, ARG_NOISY_HPOLY},
{(char*)"no-mixed", no_argument, 0, ARG_NO_MIXED},
{(char*)"no-discordant", no_argument, 0, ARG_NO_DISCORDANT},
{(char*)"local", no_argument, 0, ARG_LOCAL},
{(char*)"end-to-end", no_argument, 0, ARG_END_TO_END},
{(char*)"ungapped", no_argument, 0, ARG_UNGAPPED},
{(char*)"no-ungapped", no_argument, 0, ARG_UNGAPPED_NO},
{(char*)"sse8", no_argument, 0, ARG_SSE8},
{(char*)"no-sse8", no_argument, 0, ARG_SSE8_NO},
{(char*)"scan-narrowed", no_argument, 0, ARG_SCAN_NARROWED},
{(char*)"qc-filter", no_argument, 0, ARG_QC_FILTER},
{(char*)"bwa-sw-like", no_argument, 0, ARG_BWA_SW_LIKE},
{(char*)"multiseed", required_argument, 0, ARG_MULTISEED_IVAL},
{(char*)"ma", required_argument, 0, ARG_SCORE_MA},
{(char*)"mp", required_argument, 0, ARG_SCORE_MMP},
{(char*)"np", required_argument, 0, ARG_SCORE_NP},
{(char*)"rdg", required_argument, 0, ARG_SCORE_RDG},
{(char*)"rfg", required_argument, 0, ARG_SCORE_RFG},
{(char*)"score-min", required_argument, 0, ARG_SCORE_MIN},
{(char*)"min-score", required_argument, 0, ARG_SCORE_MIN},
{(char*)"n-ceil", required_argument, 0, ARG_N_CEIL},
{(char*)"dpad", required_argument, 0, ARG_DPAD},
{(char*)"mapq-print-inputs", no_argument, 0, ARG_SAM_PRINT_YI},
{(char*)"very-fast", no_argument, 0, ARG_PRESET_VERY_FAST},
{(char*)"fast", no_argument, 0, ARG_PRESET_FAST},
{(char*)"sensitive", no_argument, 0, ARG_PRESET_SENSITIVE},
{(char*)"very-sensitive", no_argument, 0, ARG_PRESET_VERY_SENSITIVE},
{(char*)"very-fast-local", no_argument, 0, ARG_PRESET_VERY_FAST_LOCAL},
{(char*)"fast-local", no_argument, 0, ARG_PRESET_FAST_LOCAL},
{(char*)"sensitive-local", no_argument, 0, ARG_PRESET_SENSITIVE_LOCAL},
{(char*)"very-sensitive-local", no_argument, 0, ARG_PRESET_VERY_SENSITIVE_LOCAL},
{(char*)"seedlen", required_argument, 0, 'L'},
{(char*)"seedmms", required_argument, 0, 'N'},
{(char*)"seedival", required_argument, 0, 'i'},
{(char*)"ignore-quals", no_argument, 0, ARG_IGNORE_QUALS},
{(char*)"index", required_argument, 0, 'x'},
{(char*)"arg-desc", no_argument, 0, ARG_DESC},
{(char*)"wrapper", required_argument, 0, ARG_WRAPPER},
{(char*)"unpaired", required_argument, 0, 'U'},
{(char*)"output", required_argument, 0, 'S'},
{(char*)"mapq-v", required_argument, 0, ARG_MAPQ_V},
{(char*)"dovetail", no_argument, 0, ARG_DOVETAIL},
{(char*)"no-dovetail", no_argument, 0, ARG_NO_DOVETAIL},
{(char*)"contain", no_argument, 0, ARG_CONTAIN},
{(char*)"no-contain", no_argument, 0, ARG_NO_CONTAIN},
{(char*)"overlap", no_argument, 0, ARG_OVERLAP},
{(char*)"no-overlap", no_argument, 0, ARG_NO_OVERLAP},
{(char*)"tighten", required_argument, 0, ARG_TIGHTEN},
{(char*)"exact-upfront", no_argument, 0, ARG_EXACT_UPFRONT},
{(char*)"1mm-upfront", no_argument, 0, ARG_1MM_UPFRONT},
{(char*)"no-exact-upfront", no_argument, 0, ARG_EXACT_UPFRONT_NO},
{(char*)"no-1mm-upfront", no_argument, 0, ARG_1MM_UPFRONT_NO},
{(char*)"1mm-minlen", required_argument, 0, ARG_1MM_MINLEN},
{(char*)"deterministic-seeds", no_argument, 0, 'd'},
{(char*)"no-deterministic-seeds", no_argument, 0, ARG_DET_SEEDS_NO},
{(char*)"seed-off", required_argument, 0, 'O'},
{(char*)"seed-boost", required_argument, 0, ARG_SEED_BOOST_THRESH},
{(char*)"read-times", no_argument, 0, ARG_READ_TIMES},
{(char*)"show-rand-seed", no_argument, 0, ARG_SHOW_RAND_SEED},
{(char*)"dp-fail-streak", required_argument, 0, ARG_DP_FAIL_STREAK_THRESH},
{(char*)"ee-fail-streak", required_argument, 0, ARG_EE_FAIL_STREAK_THRESH},
{(char*)"ug-fail-streak", required_argument, 0, ARG_UG_FAIL_STREAK_THRESH},
{(char*)"fail-streak", required_argument, 0, 'D'},
{(char*)"dp-fails", required_argument, 0, ARG_DP_FAIL_THRESH},
{(char*)"ug-fails", required_argument, 0, ARG_UG_FAIL_THRESH},
{(char*)"extends", required_argument, 0, ARG_EXTEND_ITERS},
{(char*)"no-extend", no_argument, 0, ARG_NO_EXTEND},
{(char*)"mapq-extra", no_argument, 0, ARG_MAPQ_EX},
{(char*)"seed-rounds", required_argument, 0, 'R'},
{(char*)"reorder", no_argument, 0, ARG_REORDER},
{(char*)"passthrough", no_argument, 0, ARG_READ_PASSTHRU},
{(char*)"sample", required_argument, 0, ARG_SAMPLE},
{(char*)"cp-min", required_argument, 0, ARG_CP_MIN},
{(char*)"cp-ival", required_argument, 0, ARG_CP_IVAL},
{(char*)"tri", no_argument, 0, ARG_TRI},
{(char*)"nondeterministic", no_argument, 0, ARG_NON_DETERMINISTIC},
{(char*)"non-deterministic", no_argument, 0, ARG_NON_DETERMINISTIC},
{(char*)"local-seed-cache-sz", required_argument, 0, ARG_LOCAL_SEED_CACHE_SZ},
{(char*)"seed-cache-sz", required_argument, 0, ARG_CURRENT_SEED_CACHE_SZ},
{(char*)"no-unal", no_argument, 0, ARG_SAM_NO_UNAL},
{(char*)"test-25", no_argument, 0, ARG_TEST_25},
// TODO: following should be a function of read length?
{(char*)"desc-kb", required_argument, 0, ARG_DESC_KB},
{(char*)"desc-landing", required_argument, 0, ARG_DESC_LANDING},
{(char*)"desc-exp", required_argument, 0, ARG_DESC_EXP},
{(char*)"desc-prioritize", no_argument, 0, ARG_DESC_PRIORITIZE},
{(char*)"desc-fmops", required_argument, 0, ARG_DESC_FMOPS},
{(char*)"log-dp", required_argument, 0, ARG_LOG_DP},
{(char*)"log-dp-opp", required_argument, 0, ARG_LOG_DP_OPP},
{(char*)"soft-clipped-unmapped-tlen", no_argument, 0, ARG_SC_UNMAPPED},
{(char*)"xeq", no_argument, 0, ARG_XEQ},
{(char*)"thread-ceiling", required_argument, 0, ARG_THREAD_CEILING},
{(char*)"thread-piddir", required_argument, 0, ARG_THREAD_PIDDIR},
{(char*)"trim-to", required_argument, 0, ARG_TRIM_TO},
{(char*)"preserve-tags", no_argument, 0, ARG_PRESERVE_TAGS},
{(char*)"align-paired-reads", no_argument, 0, ARG_ALIGN_PAIRED_READS},
#ifdef USE_SRA
{(char*)"sra-acc", required_argument, 0, ARG_SRA_ACC},
#endif
{(char*)"sam-append-comment", no_argument, 0, ARG_SAM_APPEND_COMMENT},
{(char*)"sam-opt-config", required_argument, 0, ARG_SAM_OPT_CONFIG},
{(char*)0, 0, 0, 0} // terminator
};
/**
* Print out a concise description of what options are taken and whether they
* take an argument.
*/
static void printArgDesc(ostream& out) {
// struct option {
// const char *name;
// int has_arg;
// int *flag;
// int val;
// };
size_t i = 0;
while(long_options[i].name != 0) {
out << long_options[i].name << "\t"
<< (long_options[i].has_arg == no_argument ? 0 : 1)
<< endl;
i++;
}
size_t solen = strlen(short_options);
for(i = 0; i < solen; i++) {
// Has an option? Does if next char is :
if(i == solen-1) {
assert_neq(':', short_options[i]);
cout << (char)short_options[i] << "\t" << 0 << endl;
} else {
if(short_options[i+1] == ':') {
// Option with argument
cout << (char)short_options[i] << "\t" << 1 << endl;
i++; // skip the ':'
} else {
// Option with no argument
cout << (char)short_options[i] << "\t" << 0 << endl;
}
}
}
}
/**
* Print a summary usage message to the provided output stream.
*/
static void printUsage(ostream& out) {
out << "Bowtie 2 version " << string(BOWTIE2_VERSION).c_str() << " by Ben Langmead (langmea@cs.jhu.edu, www.cs.jhu.edu/~langmea)" << endl;
string tool_name = "bowtie2-align";
if(wrapper == "basic-0") {
tool_name = "bowtie2";
}
out << "Usage: " << endl
#ifdef USE_SRA
<< " " << tool_name.c_str() << " [options]* -x <bt2-idx> {-1 <m1> -2 <m2> | -U <r> | --interleaved <i> | --sra-acc <acc> | -b <bam>} [-S <sam>]" << endl
#else
<< " " << tool_name.c_str() << " [options]* -x <bt2-idx> {-1 <m1> -2 <m2> | -U <r> | --interleaved <i> | -b <bam>} [-S <sam>]" << endl
#endif
<< endl
<< " <bt2-idx> Index filename prefix (minus trailing .X." + gEbwt_ext + ")." << endl
<< " NOTE: Bowtie 1 and Bowtie 2 indexes are not compatible." << endl
<< " <m1> Files with #1 mates, paired with files in <m2>." << endl;
if(wrapper == "basic-0") {
out << " Could be gzip'ed (extension: .gz) or bzip2'ed (extension: .bz2)." << endl;
}
out << " <m2> Files with #2 mates, paired with files in <m1>." << endl;
if(wrapper == "basic-0") {
out << " Could be gzip'ed (extension: .gz) or bzip2'ed (extension: .bz2)." << endl;
}
out << " <r> Files with unpaired reads." << endl;
if(wrapper == "basic-0") {
out << " Could be gzip'ed (extension: .gz) or bzip2'ed (extension: .bz2)." << endl;
}
out << " <i> Files with interleaved paired-end FASTQ/FASTA reads" << endl;
if(wrapper == "basic-0") {
out << " Could be gzip'ed (extension: .gz) or bzip2'ed (extension: .bz2)." << endl;
}
#ifdef USE_SRA
out << " <acc> Files are SRA accessions. Accessions not found in local storage will\n"
<< " be fetched from NCBI." << endl;
#endif
out << " <bam> Files are unaligned BAM sorted by read name." << endl;
out << " <sam> File for SAM output (default: stdout)" << endl
<< endl
<< " <m1>, <m2>, <r> can be comma-separated lists (no whitespace) and can be" << endl
<< " specified many times. E.g. '-U file1.fq,file2.fq -U file3.fq'." << endl
// Wrapper script should write <bam> line next
<< endl
<< "Options (defaults in parentheses):" << endl
<< endl
<< " Input:" << endl
<< " -q query input files are FASTQ .fq/.fastq (default)" << endl
<< " --tab5 query input files are TAB5 .tab5" << endl
<< " --tab6 query input files are TAB6 .tab6" << endl
<< " --qseq query input files are in Illumina's qseq format" << endl
<< " -f query input files are (multi-)FASTA .fa/.mfa" << endl
<< " -r query input files are raw one-sequence-per-line" << endl
<< " -F k:<int>,i:<int> query input files are continuous FASTA where reads" << endl
<< " are substrings (k-mers) extracted from the FASTA file" << endl
<< " and aligned at offsets 1, 1+i, 1+2i ... end of reference" << endl
<< " -c <m1>, <m2>, <r> are sequences themselves, not files" << endl
<< " -s/--skip <int> skip the first <int> reads/pairs in the input (none)" << endl
<< " -u/--upto <int> stop after first <int> reads/pairs (no limit)" << endl
<< " -5/--trim5 <int> trim <int> bases from 5'/left end of reads (0)" << endl
<< " -3/--trim3 <int> trim <int> bases from 3'/right end of reads (0)" << endl
<< " --trim-to [3:|5:]<int> trim reads exceeding <int> bases from either 3' or 5' end" << endl
<< " If the read end is not specified then it defaults to 3 (0)" << endl
<< " --phred33 qualities are Phred+33 (default)" << endl
<< " --phred64 qualities are Phred+64" << endl
<< " --int-quals qualities encoded as space-delimited integers" << endl
<< endl
<< " Presets: Same as:" << endl
<< " For --end-to-end:" << endl
<< " --very-fast -D 5 -R 1 -N 0 -L 22 -i S,0,2.50" << endl
<< " --fast -D 10 -R 2 -N 0 -L 22 -i S,0,2.50" << endl
<< " --sensitive -D 15 -R 2 -N 0 -L 22 -i S,1,1.15 (default)" << endl
<< " --very-sensitive -D 20 -R 3 -N 0 -L 20 -i S,1,0.50" << endl
<< endl
<< " For --local:" << endl
<< " --very-fast-local -D 5 -R 1 -N 0 -L 25 -i S,1,2.00" << endl
<< " --fast-local -D 10 -R 2 -N 0 -L 22 -i S,1,1.75" << endl
<< " --sensitive-local -D 15 -R 2 -N 0 -L 20 -i S,1,0.75 (default)" << endl
<< " --very-sensitive-local -D 20 -R 3 -N 0 -L 20 -i S,1,0.50" << endl
<< endl
<< " Alignment:" << endl
<< " -N <int> max # mismatches in seed alignment; can be 0 or 1 (0)" << endl
<< " -L <int> length of seed substrings; must be >3, <32 (22)" << endl
<< " -i <func> interval between seed substrings w/r/t read len (S,1,1.15)" << endl
<< " --n-ceil <func> func for max # non-A/C/G/Ts permitted in aln (L,0,0.15)" << endl
<< " --dpad <int> include <int> extra ref chars on sides of DP table (15)" << endl
<< " --gbar <int> disallow gaps within <int> nucs of read extremes (4)" << endl
<< " --ignore-quals treat all quality values as 30 on Phred scale (off)" << endl
<< " --nofw do not align forward (original) version of read (off)" << endl
<< " --norc do not align reverse-complement version of read (off)" << endl
<< " --no-1mm-upfront do not allow 1 mismatch alignments before attempting to" << endl
<< " scan for the optimal seeded alignments"
<< endl
<< " --end-to-end entire read must align; no clipping (on)" << endl
<< " OR" << endl
<< " --local local alignment; ends might be soft clipped (off)" << endl
<< endl
<< " Scoring:" << endl
<< " --ma <int> match bonus (0 for --end-to-end, 2 for --local) " << endl
<< " --mp <int> max penalty for mismatch; lower qual = lower penalty (6)" << endl
<< " --np <int> penalty for non-A/C/G/Ts in read/ref (1)" << endl
<< " --rdg <int>,<int> read gap open, extend penalties (5,3)" << endl
<< " --rfg <int>,<int> reference gap open, extend penalties (5,3)" << endl
<< " --score-min <func> min acceptable alignment score w/r/t read length" << endl
<< " (G,20,8 for local, L,-0.6,-0.6 for end-to-end)" << endl
<< endl
<< " Reporting:" << endl
<< " (default) look for multiple alignments, report best, with MAPQ" << endl
<< " OR" << endl
<< " -k <int> report up to <int> alns per read; MAPQ not meaningful" << endl
<< " OR" << endl
<< " -a/--all report all alignments; very slow without -l, MAPQ not meaningful" << endl
<< endl
<< " Effort:" << endl
<< " -l/--lowseeds <n> ignore any low quality seeds with ranges over threshold" << endl
<< " (0=no cut, if percentage, mili or nano, relative to idx size)" << endl
<< " -D <int> give up extending after <int> failed extends in a row (15)" << endl
<< " -R <int> for reads w/ repetitive seeds, try <int> sets of seeds (2)" << endl
<< " -d/--deterministic-seeds" << endl
<< " Consider all seeds in order (no subsampling, best with -a)" << endl
<< endl
<< " Paired-end:" << endl
<< " -I/--minins <int> minimum fragment length (0)" << endl
<< " -X/--maxins <int> maximum fragment length (500)" << endl
<< " --fr/--rf/--ff -1, -2 mates align fw/rev, rev/fw, fw/fw (--fr)" << endl
<< " --no-mixed suppress unpaired alignments for paired reads" << endl
<< " --no-discordant suppress discordant alignments for paired reads" << endl
<< " --dovetail concordant when mates extend past each other" << endl
<< " --no-contain not concordant when one mate alignment contains other" << endl
<< " --no-overlap not concordant when mates overlap at all" << endl
<< endl
<< " BAM:" << endl
<< " --align-paired-reads" << endl
<< " Bowtie2 will, by default, attempt to align unpaired BAM reads." << endl
<< " Use this option to align paired-end reads instead." << endl
<< " --preserve-tags Preserve tags from the original BAM record by" << endl
<< " appending them to the end of the corresponding SAM output." << endl
<< endl
<< " Output:" << endl;
//if(wrapper == "basic-0") {
// out << " --bam output directly to BAM (by piping through 'samtools view')" << endl;
//}
out << " -t/--time print wall-clock time taken by search phases" << endl;
if(wrapper == "basic-0") {
out << " --un <path> write unpaired reads that didn't align to <path>" << endl
<< " --al <path> write unpaired reads that aligned at least once to <path>" << endl
<< " --un-conc <path> write pairs that didn't align concordantly to <path>" << endl
<< " --al-conc <path> write pairs that aligned concordantly at least once to <path>" << endl
<< " (Note: for --un, --al, --un-conc, or --al-conc, add '-gz' to the option name, e.g." << endl
<< " --un-gz <path>, to gzip compress output, or add '-bz2' to bzip2 compress output.)" << endl;
}
out << " --quiet print nothing to stderr except serious errors" << endl
// << " --refidx refer to ref. seqs by 0-based index rather than name" << endl
<< " --met-file <path> send metrics to file at <path> (off)" << endl
<< " --met-stderr send metrics to stderr (off)" << endl
<< " --met <int> report internal counters & metrics every <int> secs (1)" << endl
// Following is supported in the wrapper instead
<< " --no-unal suppress SAM records for unaligned reads" << endl
<< " --no-head suppress header lines, i.e. lines starting with @" << endl
<< " --no-sq suppress @SQ header lines" << endl
<< " --rg-id <text> set read group id, reflected in @RG line and RG:Z: opt field" << endl
<< " --rg <text> add <text> (\"lab:value\") to @RG line of SAM header." << endl
<< " Note: @RG line only printed when --rg-id is set." << endl
<< " --omit-sec-seq put '*' in SEQ and QUAL fields for secondary alignments." << endl
<< " --sam-no-qname-trunc" << endl
<< " Suppress standard behavior of truncating readname at first whitespace " << endl
<< " at the expense of generating non-standard SAM." << endl
<< " --xeq Use '='/'X', instead of 'M,' to specify matches/mismatches in SAM record." << endl
<< " --soft-clipped-unmapped-tlen" << endl
<< " Exclude soft-clipped bases when reporting TLEN." << endl
<< " --sam-append-comment" << endl
<< " Append FASTA/FASTQ comment to SAM record." << endl
<< " --sam-opt-config <config>" << endl
<< " Use <config>, example '-MD,YP,-AS', to toggle SAM Optional fields." << endl
<< endl
<< " Performance:" << endl
// << " -o/--offrate <int> override offrate of index; must be >= index's offrate" << endl
<< " -p/--threads <int> number of alignment threads to launch (1)" << endl
<< " --reorder force SAM output order to match order of input reads" << endl
#ifdef BOWTIE_MM
<< " --mm use memory-mapped I/O for index; many 'bowtie's can share" << endl
#endif
#ifdef BOWTIE_SHARED_MEM
//<< " --shmem use shared mem for index; many 'bowtie's can share" << endl
#endif
<< endl
<< " Other:" << endl
<< " --qc-filter filter out reads that are bad according to QSEQ filter" << endl
<< " --seed <int> seed for random number generator (0)" << endl
<< " --non-deterministic" << endl
<< " seed rand. gen. arbitrarily instead of using read attributes" << endl
// << " --verbose verbose output for debugging" << endl
<< " --version print version information and quit" << endl
<< " -h/--help print this usage message" << endl;
if(wrapper.empty()) {
cerr << endl
<< "*** Warning ***" << endl
<< "'bowtie2-align' was run directly. It is recommended that you run the wrapper script 'bowtie2' instead." << endl
<< endl;
}
}
/**
* Parse an int out of optarg and enforce that it be at least 'lower';
* if it is less than 'lower', than output the given error message and
* exit with an error and a usage message.
*/
static int parseInt(int lower, int upper, const char *errmsg, const char *arg) {
long l;
char *endPtr= NULL;
l = strtol(arg, &endPtr, 10);
if (endPtr != NULL) {
if (l < lower || l > upper) {
cerr << errmsg << endl;
printUsage(cerr);
throw 1;
}
return (int32_t)l;
}
cerr << errmsg << endl;
printUsage(cerr);
throw 1;
return -1;
}
/**
* Upper is maximum int by default.
*/
static int parseInt(int lower, const char *errmsg, const char *arg) {
return parseInt(lower, std::numeric_limits<int>::max(), errmsg, arg);
}
/**
* Parse a T string 'str'.
*/
template<typename T>
T parse(const char *s) {
T tmp;
stringstream ss(s);
ss >> tmp;
return tmp;
}
/**
* Parse a T string 'str',
* provide first char after the parse (\0 if all string consumed)
*/
template<typename T>
T parse(const char *s, char &remainder) {
T tmp;
stringstream ss(s);
ss >> tmp;
ss >> remainder;
return tmp;
}
/**
* Parse a pair of Ts from a string, 'str', delimited with 'delim'.
*/
template<typename T>
pair<T, T> parsePair(const char *str, char delim) {
string s(str);
EList<string> ss;
tokenize(s, delim, ss);
pair<T, T> ret;
ret.first = parse<T>(ss[0].c_str());
ret.second = parse<T>(ss[1].c_str());
return ret;
}
/**
* Parse a pair of Ts from a string, 'str', delimited with 'delim'.
*/
template<typename T>
void parseTuple(const char *str, char delim, EList<T>& ret) {
string s(str);
EList<string> ss;
tokenize(s, delim, ss);
for(size_t i = 0; i < ss.size(); i++) {
ret.push_back(parse<T>(ss[i].c_str()));
}
}
static string applyPreset(const string& sorig, Presets& presets) {
string s = sorig;
size_t found = s.find("%LOCAL%");
if(found != string::npos) {
s.replace(found, strlen("%LOCAL%"), localAlign ? "-local" : "");
}
if(gVerbose) {
cerr << "Applying preset: '" << s.c_str() << "' using preset menu '"
<< presets.name() << "'" << endl;
}
string pol;
presets.apply(s, pol, extra_opts);
return pol;
}
static bool saw_M;
static bool saw_a;
static bool saw_k;
static bool saw_trim3;
static bool saw_trim5;
static bool saw_trim_to;
static bool saw_bam;
static bool saw_preserve_tags;
static bool saw_align_paired_reads;
static EList<string> presetList;
/**
* TODO: Argument parsing is very, very flawed. The biggest problem is that
* there are two separate worlds of arguments, the ones set via polstr, and
* the ones set directly in variables. This makes for nasty interactions,
* e.g., with the -M option being resolved at an awkward time relative to
* the -k and -a options.
*/
static void parseOption(int next_option, const char *arg) {
switch (next_option) {
case ARG_TEST_25: bowtie2p5 = true; break;
case ARG_DESC_KB: descentTotSz = SimpleFunc::parse(arg, 0.0, 1024.0, 1024.0, DMAX); break;
case ARG_DESC_FMOPS: descentTotFmops = SimpleFunc::parse(arg, 0.0, 10.0, 100.0, DMAX); break;
case ARG_LOG_DP: logDps = arg; break;
case ARG_LOG_DP_OPP: logDpsOpp = arg; break;
case ARG_DESC_LANDING: {
descLanding = parse<int>(arg);
if(descLanding < 1) {
cerr << "Error: --desc-landing must be greater than or equal to 1" << endl;
throw 1;
}
break;
}
case ARG_DESC_EXP: {
descConsExp = parse<double>(arg);
if(descConsExp < 0.0) {
cerr << "Error: --desc-exp must be greater than or equal to 0" << endl;
throw 1;
}
break;
}
case ARG_DESC_PRIORITIZE: descPrioritizeRoots = true; break;
case '1': tokenize(arg, ",", mates1); break;
case '2': tokenize(arg, ",", mates2); break;
case ARG_ONETWO: tokenize(arg, ",", mates12); set_format(format, TAB_MATE5); break;
case ARG_TAB5: tokenize(arg, ",", mates12); set_format(format, TAB_MATE5); break;
case ARG_TAB6: tokenize(arg, ",", mates12); set_format(format, TAB_MATE6); break;
case ARG_INTERLEAVED: {
tokenize(arg, ",", mates12);
interleaved = true;
break;
}
case 'b': {
set_format(format, BAM);
saw_bam = true;
break;
}
case 'f': {
if (format != FASTA_CONT)
set_format(format, FASTA);
break;
}
case 'F': {
if (format == FASTA) {
format = UNKNOWN;
}
set_format(format, FASTA_CONT);
pair<uint32_t, uint32_t> p = parsePair<uint32_t>(arg, ',');
fastaContLen = p.first;
fastaContFreq = p.second;
break;
}
case ARG_BWA_SW_LIKE: {
bwaSwLikeC = 5.5f;
bwaSwLikeT = 30;
bwaSwLike = true;
localAlign = true;
// -a INT Score of a match [1]
// -b INT Mismatch penalty [3]
// -q INT Gap open penalty [5]
// -r INT Gap extension penalty. The penalty for a contiguous
// gap of size k is q+k*r. [2]
polstr += ";MA=1;MMP=C3;RDG=5,2;RFG=5,2";
break;
}
case 'q': set_format(format, FASTQ); break;
case 'r': set_format(format, RAW); break;
case 'c': set_format(format, CMDLINE); break;
case ARG_QSEQ: set_format(format, QSEQ); break;
case 'I':
gMinInsert = parseInt(0, "-I arg must be positive", arg);
break;
case 'X':
gMaxInsert = parseInt(1, "-X arg must be at least 1", arg);
break;
case ARG_NO_DISCORDANT: gReportDiscordant = false; break;
case ARG_NO_MIXED: gReportMixed = false; break;
case 's':
skipReads = (uint32_t)parseInt(0, "-s arg must be positive", arg);
break;
case ARG_FF: gMate1fw = true; gMate2fw = true; break;
case ARG_RF: gMate1fw = false; gMate2fw = true; break;
case ARG_FR: gMate1fw = true; gMate2fw = false; break;
case ARG_SHMEM: useShmem = true; break;
case ARG_SEED_SUMM: seedSumm = true; break;
case ARG_SC_UNMAPPED: scUnMapped = true; break;
case ARG_XEQ: xeq = true; break;
case ARG_PRESERVE_TAGS: {
preserve_tags = true;
saw_preserve_tags = true;
break;
}
case ARG_ALIGN_PAIRED_READS: {
align_paired_reads = true;
saw_align_paired_reads = true;
break;
}
case ARG_MM: {
#ifdef BOWTIE_MM
useMm = true;
break;
#else
cerr << "Memory-mapped I/O mode is disabled because bowtie was not compiled with" << endl
<< "BOWTIE_MM defined. Memory-mapped I/O is not supported under Windows. If you" << endl
<< "would like to use memory-mapped I/O on a platform that supports it, please" << endl
<< "refrain from specifying BOWTIE_MM=0 when compiling Bowtie." << endl;
throw 1;
#endif
}
case ARG_MMSWEEP: mmSweep = true; break;
case ARG_HADOOPOUT: hadoopOut = true; break;
case ARG_SOLEXA_QUALS: solexaQuals = true; break;
case ARG_INTEGER_QUALS: integerQuals = true; break;
case ARG_PHRED64: phred64Quals = true; break;
case ARG_PHRED33: solexaQuals = false; phred64Quals = false; break;
case ARG_OVERHANG: gReportOverhangs = true; break;
case ARG_NO_CACHE: msNoCache = true; break;
case ARG_USE_CACHE: msNoCache = false; break;
case ARG_LOCAL_SEED_CACHE_SZ:
seedCacheLocalMB = (uint32_t)parseInt(1, "--local-seed-cache-sz arg must be at least 1", arg);
break;
case ARG_CURRENT_SEED_CACHE_SZ:
seedCacheCurrentMB = (uint32_t)parseInt(1, "--seed-cache-sz arg must be at least 1", arg);
break;
case ARG_REFIDX: noRefNames = true; break;
case ARG_FULLREF: fullRef = true; break;
case ARG_GAP_BAR:
gGapBarrier = parseInt(1, "--gbar must be no less than 1", arg);
break;
case ARG_SEED:
seed = parseInt(0, "--seed arg must be at least 0", arg);
break;
case ARG_NON_DETERMINISTIC:
arbitraryRandom = true;
break;
case 'u':
qUpto = (uint32_t)parseInt(1, "-u/--qupto arg must be at least 1", arg);
break;
case 'Q':
tokenize(arg, ",", qualities);
integerQuals = true;
break;
case ARG_QUALS1:
tokenize(arg, ",", qualities1);
integerQuals = true;
break;
case ARG_QUALS2:
tokenize(arg, ",", qualities2);
integerQuals = true;
break;
case ARG_CACHE_LIM:
cacheLimit = (uint32_t)parseInt(1, "--cachelim arg must be at least 1", arg);
break;
case ARG_CACHE_SZ:
cacheSize = (uint32_t)parseInt(1, "--cachesz arg must be at least 1", arg);
cacheSize *= (1024 * 1024); // convert from MB to B
break;
case ARG_WRAPPER: wrapper = arg; break;
case 'p':
nthreads = parseInt(1, "-p/--threads arg must be at least 1", arg);
break;
case ARG_THREAD_CEILING:
thread_ceiling = parseInt(0, "--thread-ceiling must be at least 0", arg);
break;
case ARG_THREAD_PIDDIR:
thread_stealing_dir = arg;
break;
case ARG_FILEPAR:
fileParallel = true;
break;
case '3': gTrim3 = parseInt(0, "-3/--trim3 arg must be at least 0", arg); break;
case '5': gTrim5 = parseInt(0, "-5/--trim5 arg must be at least 0", arg); break;
case ARG_TRIM_TO: {
if (strlen(arg) > 1 && arg[1] != ':') {
trimTo.first = 3;
trimTo.second = parseInt(0, "--trim-to: the number of bases to trim must be at least 0", arg);
break;
}
pair<int, int> res = parsePair<int>(arg, ':');
if (res.first != 3 && res.first != 5) {
cerr << "--trim-to: trim position must be either 3 or 5" << endl;
printUsage(cerr);
throw 1;
}
if(res.second < 0) {
cerr << "--trim-to: the number bases to trim must be at least 0" << endl;
printUsage(cerr);
throw 1;
}
trimTo = static_cast<pair<short, size_t> >(res);
break;
}
case 'h': printUsage(cout); throw 0; break;
case ARG_USAGE: printUsage(cout); throw 0; break;
//
// NOTE that unlike in Bowtie 1, -M, -a and -k are mutually
// exclusive here.
//
case 'M': {
msample = true;
mhits = parse<uint32_t>(arg);
if(saw_a || saw_k) {
cerr << "Warning: -M, -k and -a are mutually exclusive. "
<< "-M will override" << endl;
khits = 1;
}
assert_eq(1, khits);
saw_M = true;
cerr << "Warning: -M is deprecated. Use -D and -R to adjust " <<
"effort instead." << endl;
break;
}
case ARG_EXTEND_ITERS: {
maxIters = parse<size_t>(arg);
break;
}
case ARG_NO_EXTEND: {
doExtend = false;
break;
}
case 'R': { polstr += ";ROUNDS="; polstr += arg; break; }
case 'D': { polstr += ";DPS="; polstr += arg; break; }
case ARG_DP_MATE_STREAK_THRESH: {
maxMateStreak = parse<size_t>(arg);
break;
}
case ARG_DP_FAIL_STREAK_THRESH: {
maxDpStreak = parse<size_t>(arg);
break;
}
case ARG_EE_FAIL_STREAK_THRESH: {
maxEeStreak = parse<size_t>(arg);
break;
}
case ARG_UG_FAIL_STREAK_THRESH: {
maxUgStreak = parse<size_t>(arg);
break;
}
case ARG_DP_FAIL_THRESH: {
maxDp = parse<size_t>(arg);
break;
}
case ARG_UG_FAIL_THRESH: {
maxUg = parse<size_t>(arg);
break;
}
case ARG_SEED_BOOST_THRESH: {
seedBoostThresh = parse<size_t>(arg);
break;
}
case 'a': {
msample = false;
allHits = true;
mhits = 0; // disable -M
if(saw_M || saw_k) {
cerr << "Warning: -M, -k and -a are mutually exclusive. "
<< "-a will override" << endl;
}
saw_a = true;
break;
}
case 'k': {
msample = false;
khits = (uint32_t)parseInt(1, "-k arg must be at least 1", arg);
mhits = 0; // disable -M
if(saw_M || saw_a) {
cerr << "Warning: -M, -k and -a are mutually exclusive. "
<< "-k will override" << endl;
}
saw_k = true;
break;
}
case 'l': {
char remainder = 0;
lowseedsDivider = 0;
lowseeds = parse<size_t>(arg, remainder);
if (remainder=='%') {
// User requested percentage of DB
lowseedsDivider = 100;
} else if (remainder=='m') {
// User requested mili of DB
lowseedsDivider = 1000;
} else if (remainder=='n') {
// User requested nano of DB
lowseedsDivider = 1000000;
} else if (remainder==0) {
// We got an absolute value
lowseedsDivider = 0;
} else {
cerr << "Warning: -l argument had training chars "
<< "that were not parsed" << endl;
}
break;
}
case 'd': deterministicSeeds = true; break;
case ARG_DET_SEEDS_NO: deterministicSeeds = false; break;
case ARG_VERBOSE: gVerbose = 1; break;
case ARG_STARTVERBOSE: startVerbose = true; break;
case ARG_QUIET: gQuiet = true; break;
case ARG_SANITY: sanityCheck = true; break;
case 't': timing = true; break;
case ARG_METRIC_IVAL: {
metricsIval = parseInt(1, "--metrics arg must be at least 1", arg);
break;
}
case ARG_METRIC_FILE: metricsFile = arg; break;
case ARG_METRIC_STDERR: metricsStderr = true; break;
case ARG_METRIC_PER_READ: metricsPerRead = true; break;
case ARG_NO_FW: gNofw = true; break;
case ARG_NO_RC: gNorc = true; break;
case ARG_SAM_NO_QNAME_TRUNC: samTruncQname = false; break;
case ARG_SAM_APPEND_COMMENT: samAppendComment = true; break;
case ARG_SAM_OMIT_SEC_SEQ: samOmitSecSeqQual = true; break;
case ARG_SAM_NO_UNAL: samNoUnal = true; break;
case ARG_SAM_NOHEAD: samNoHead = true; break;
case ARG_SAM_NOSQ: samNoSQ = true; break;
case ARG_SAM_PRINT_YI: sam_print_yi = true; break;
case ARG_REORDER: reorder = true; break;
case ARG_MAPQ_EX: {
sam_print_zt = true;
break;
}
case ARG_SHOW_RAND_SEED: {
sam_print_zs = true;
break;
}
case ARG_SAMPLE:
sampleFrac = parse<float>(arg);
break;
case ARG_CP_MIN:
cminlen = parse<size_t>(arg);
break;
case ARG_CP_IVAL:
cpow2 = parse<size_t>(arg);
break;
case ARG_TRI:
doTri = true;
break;
case ARG_READ_PASSTHRU: {
sam_print_xr = true;
break;
}
case ARG_READ_TIMES: {
sam_print_xt = true;
sam_print_xd = true;
sam_print_xu = true;
sam_print_yl = true;
sam_print_ye = true;
sam_print_yu = true;
sam_print_yr = true;
sam_print_zb = true;
sam_print_zr = true;
sam_print_zf = true;
sam_print_zm = true;
sam_print_zi = true;
break;
}
case ARG_SAM_RG: {
string argstr = arg;
if(argstr.substr(0, 3) == "ID:") {
rgid = "\t";
rgid += argstr;
rgs_optflag = "RG:Z:" + argstr.substr(3);
} else {
rgs += '\t';
rgs += argstr;
}
break;
}
case ARG_SAM_RGID: {
string argstr = arg;
rgid = "\t";
rgid = "\tID:" + argstr;
rgs_optflag = "RG:Z:" + argstr;
break;
}
case ARG_PARTITION: partitionSz = parse<int>(arg); break;
case ARG_READS_PER_BATCH:
readsPerBatch = parseInt(1, "--reads-per-batch arg must be at least 1", arg);
break;
case ARG_DPAD:
maxhalf = parseInt(0, "--dpad must be no less than 0", arg);
break;
case ARG_ORIG:
if(arg == NULL || strlen(arg) == 0) {
cerr << "--orig arg must be followed by a string" << endl;
printUsage(cerr);
throw 1;
}
origString = arg;
break;
case ARG_LOCAL: {
localAlign = true;
gDefaultSeedLen = DEFAULT_LOCAL_SEEDLEN;
break;
}
case ARG_END_TO_END: localAlign = false; break;
case ARG_SSE8: enable8 = true; break;
case ARG_SSE8_NO: enable8 = false; break;
case ARG_UNGAPPED: doUngapped = true; break;
case ARG_UNGAPPED_NO: doUngapped = false; break;
case ARG_NO_DOVETAIL: gDovetailMatesOK = false; break;
case ARG_NO_CONTAIN: gContainMatesOK = false; break;
case ARG_NO_OVERLAP: gOlapMatesOK = false; break;
case ARG_DOVETAIL: gDovetailMatesOK = true; break;
case ARG_CONTAIN: gContainMatesOK = true; break;
case ARG_OVERLAP: gOlapMatesOK = true; break;
case ARG_QC_FILTER: qcFilter = true; break;
case ARG_IGNORE_QUALS: ignoreQuals = true; break;
case ARG_MAPQ_V: mapqv = parse<int>(arg); break;
case ARG_TIGHTEN: tighten = parse<int>(arg); break;
case ARG_EXACT_UPFRONT: doExactUpFront = true; break;
case ARG_1MM_UPFRONT: do1mmUpFront = true; break;
case ARG_EXACT_UPFRONT_NO: doExactUpFront = false; break;
case ARG_1MM_UPFRONT_NO: do1mmUpFront = false; break;
case ARG_1MM_MINLEN: do1mmMinLen = parse<size_t>(arg); break;
case ARG_NOISY_HPOLY: noisyHpolymer = true; break;
case 'x': bt2index = arg; break;
case ARG_PRESET_VERY_FAST_LOCAL: localAlign = true;
case ARG_PRESET_VERY_FAST: {
presetList.push_back("very-fast%LOCAL%"); break;
}
case ARG_PRESET_FAST_LOCAL: localAlign = true;
case ARG_PRESET_FAST: {
presetList.push_back("fast%LOCAL%"); break;
}
case ARG_PRESET_SENSITIVE_LOCAL: localAlign = true;
case ARG_PRESET_SENSITIVE: {
presetList.push_back("sensitive%LOCAL%"); break;
}
case ARG_PRESET_VERY_SENSITIVE_LOCAL: localAlign = true;
case ARG_PRESET_VERY_SENSITIVE: {
presetList.push_back("very-sensitive%LOCAL%"); break;
}
case 'P': { presetList.push_back(arg); break; }
case ARG_ALIGN_POLICY: {
if(strlen(arg) > 0) {
polstr += ";"; polstr += arg;
}
break;
}
case 'N': {
int64_t len = parse<size_t>(arg);
if (len < 0 || len > 1) {
cerr << "Error: -N argument must be within the interval [0,1]; was " << arg << endl;
throw 1;
}
polstr += ";SEED=";
polstr += arg;
break;
}
case 'L': {
int64_t len = parse<size_t>(arg);
if(len < 1 || len > 32) {
cerr << "Error: -L argument must be within the interval [1,32]; was " << arg << endl;
throw 1;
}
polstr += ";SEEDLEN=";
polstr += arg;
break;
}
case 'O':
multiseedOff = parse<size_t>(arg);
break;
case 'i': {
EList<string> args;
tokenize(arg, ",", args);
if(args.size() > 3 || args.size() == 0) {
cerr << "Error: expected 3 or fewer comma-separated "
<< "arguments to -i option, got "
<< args.size() << endl;
throw 1;
}
// Interval-settings arguments
polstr += (";IVAL=" + args[0]); // Function type
if(args.size() > 1) {
polstr += ("," + args[1]); // Constant term
}
if(args.size() > 2) {
polstr += ("," + args[2]); // Coefficient
}
break;
}
case ARG_MULTISEED_IVAL: {
polstr += ";";
// Split argument by comma
EList<string> args;
tokenize(arg, ",", args);
if(args.size() > 5 || args.size() == 0) {
cerr << "Error: expected 5 or fewer comma-separated "
<< "arguments to --multiseed option, got "
<< args.size() << endl;
throw 1;
}
// Seed mm and length arguments
polstr += "SEED=";
polstr += (args[0]); // # mismatches
if(args.size() > 1) polstr += (";SEEDLEN=" + args[1]); // length
if(args.size() > 2) polstr += (";IVAL=" + args[2]); // Func type
if(args.size() > 3) polstr += ("," + args[ 3]); // Constant term
if(args.size() > 4) polstr += ("," + args[ 4]); // Coefficient
break;
}
case ARG_N_CEIL: {
// Split argument by comma
EList<string> args;
tokenize(arg, ",", args);
if(args.size() > 3) {
cerr << "Error: expected 3 or fewer comma-separated "
<< "arguments to --n-ceil option, got "
<< args.size() << endl;
throw 1;
}
if(args.size() == 0) {
cerr << "Error: expected at least one argument to --n-ceil option" << endl;
throw 1;
}
polstr += ";NCEIL=";
if(args.size() == 3) {
polstr += (args[0] + "," + args[1] + "," + args[2]);
} else {
polstr += ("L," + args[0]);
if(args.size() > 1) {
polstr += ("," + (args[1]));
}
}
break;
}
case ARG_SCORE_MA: polstr += ";MA="; polstr += arg; break;
case ARG_SCORE_MMP: {
EList<string> args;
tokenize(arg, ",", args);
if(args.size() > 2 || args.size() == 0) {
cerr << "Error: expected 1 or 2 comma-separated "
<< "arguments to --mmp option, got " << args.size() << endl;
throw 1;
}
if(args.size() >= 1) {
polstr += ";MMP=Q,";
polstr += args[0];
if(args.size() >= 2) {
polstr += ",";
polstr += args[1];
}
}
break;
}
case ARG_SCORE_NP: polstr += ";NP=C"; polstr += arg; break;
case ARG_SCORE_RDG: polstr += ";RDG="; polstr += arg; break;
case ARG_SCORE_RFG: polstr += ";RFG="; polstr += arg; break;
case ARG_SCORE_MIN: {
polstr += ";";
EList<string> args;
tokenize(arg, ",", args);
if(args.size() > 3 || args.size() == 0) {
cerr << "Error: expected 3 or fewer comma-separated "
<< "arguments to --n-ceil option, got "
<< args.size() << endl;
throw 1;
}
polstr += ("MIN=" + args[0]);
if(args.size() > 1) {
polstr += ("," + args[1]);
}
if(args.size() > 2) {
polstr += ("," + args[2]);
}
break;
}
case ARG_SAM_OPT_CONFIG: {
// string no_defaults("-as,-xs,-xn,-x0,-x1,-xm,-xo,-xg,-nm,-md,-yf,-yt,-ys");
// string defaults("as,xs,xn,x0,x1,xm,xo,xg,nm,md,yf,yt,ys");
// if (strncmp(arg, "-default", 8) == 0) {
// no_defaults += arg;
// }
tokenize(arg, ",", sam_opt_flags);
break;
}
case ARG_DESC: printArgDesc(cout); throw 0;
case 'S': outfile = arg; break;
case 'U': {
EList<string> args;
tokenize(arg, ",", args);
for(size_t i = 0; i < args.size(); i++) {
queries.push_back(args[i]);
}
break;
}
#ifdef USE_SRA
case ARG_SRA_ACC: {
tokenize(arg, ",", sra_accs);
set_format(format, SRA_FASTA);
break;
}
#endif
case ARG_VERSION: showVersion = 1; break;
default:
printUsage(cerr);
throw 1;
}
}
/**
* Read command-line arguments
*/
static void parseOptions(int argc, const char **argv) {
int option_index = 0;
int next_option;
saw_M = false;
saw_a = false;
saw_k = false;
saw_trim3 = false;
saw_trim5 = false;
saw_trim_to = false;
saw_bam = false;
saw_preserve_tags = false;
saw_align_paired_reads = false;
presetList.clear();
if(startVerbose) { cerr << "Parsing options: "; logTime(cerr, true); }
while(true) {
next_option = getopt_long(
argc, const_cast<char**>(argv),
short_options, long_options, &option_index);
const char * arg = optarg;
if(next_option == EOF) {
if(extra_opts_cur < extra_opts.size()) {
next_option = extra_opts[extra_opts_cur].first;
arg = extra_opts[extra_opts_cur].second.c_str();
extra_opts_cur++;
} else {
break;
}
}
parseOption(next_option, arg);
}
if (!localAlign && scUnMapped) {
cerr << "ERROR: --soft-clipped-unmapped-tlen can only be set for local alignments." << endl;
exit(1);
}
if ((saw_trim3 || saw_trim5) && saw_trim_to) {
cerr << "ERROR: --trim5/--trim3 and --trim-to are mutually exclusive "
<< "options." << endl;
exit(1);
}
if (!saw_bam && saw_preserve_tags) {
cerr << "--preserve_tags can only be used when aligning BAM reads." << endl;
exit(1);
}
if (!saw_bam && saw_align_paired_reads) {
cerr << "--align-paired-reads can only be used when aligning BAM reads." << endl;
exit(1);
}
// Now parse all the presets. Might want to pick which presets version to
// use according to other parameters.
unique_ptr<Presets> presets(new PresetsV0());
// Apply default preset
if (presetList.empty())
polstr = applyPreset(defaultPreset, *presets.get()) + polstr;
else {
for (size_t i = presetList.size(); i != 0; i--)
polstr = applyPreset(presetList[i-1], *presets.get()) + polstr;
}
for(size_t i = 0; i < extra_opts.size(); i++) {
next_option = extra_opts[extra_opts_cur].first;
const char *arg = extra_opts[extra_opts_cur].second.c_str();
parseOption(next_option, arg);
}
// Remove initial semicolons
while(!polstr.empty() && polstr[0] == ';') {
polstr = polstr.substr(1);
}
if(gVerbose) {
cerr << "Final policy string: '" << polstr.c_str() << "'" << endl;
}
size_t failStreakTmp = 0;
SeedAlignmentPolicy::parseString(
polstr,
localAlign,
noisyHpolymer,
ignoreQuals,
bonusMatchType,
bonusMatch,
penMmcType,
penMmcMax,
penMmcMin,
penNType,
penN,
penRdGapConst,
penRfGapConst,
penRdGapLinear,
penRfGapLinear,
scoreMin,
nCeil,
penNCatPair,
multiseedMms,
multiseedLen,
msIval,
failStreakTmp,
nSeedRounds);
if(failStreakTmp > 0) {
maxEeStreak = failStreakTmp;
maxUgStreak = failStreakTmp;
maxDpStreak = failStreakTmp;
}
if(saw_a || saw_k) {
msample = false;
mhits = 0;
} else {
assert_gt(mhits, 0);
msample = true;
}
if (deterministicSeeds) {
if ( doExactUpFront || do1mmUpFront || (mhits!=0) ) {
cerr << "Warning: -d cannot be used with --exact-upfront, --1mm-upfront or -m." << endl;
throw 1;
}
if ( !allHits ) {
cerr << "Error: -d can only be used with -a." << endl;
throw 1;
}
}
if (format == UNKNOWN)
set_format(format, FASTQ);
if(mates1.size() != mates2.size()) {
cerr << "Error: " << mates1.size() << " mate files/sequences were specified with -1, but " << mates2.size() << endl
<< "mate files/sequences were specified with -2. The same number of mate files/" << endl
<< "sequences must be specified with -1 and -2." << endl;
throw 1;
}
if(interleaved && (format != FASTA && format != FASTQ && format != BAM)) {
cerr << "Error: --interleaved only works in combination with FASTA (-f) and FASTQ (-q) formats." << endl;
throw 1;
}
if (samAppendComment && (format != FASTA && format != FASTQ)) {
cerr << "Error --sam-append-comment only works with FASTA (-f) and FASTQ (-q) formats. " << endl;
throw 1;
}
if(qualities.size() && format != FASTA) {
cerr << "Error: one or more quality files were specified with -Q but -f was not" << endl
<< "enabled. -Q works only in combination with -f and -C." << endl;
throw 1;
}
if(qualities1.size() && format != FASTA) {
cerr << "Error: one or more quality files were specified with --Q1 but -f was not" << endl
<< "enabled. --Q1 works only in combination with -f and -C." << endl;
throw 1;
}
if(qualities2.size() && format != FASTA) {
cerr << "Error: one or more quality files were specified with --Q2 but -f was not" << endl
<< "enabled. --Q2 works only in combination with -f and -C." << endl;
throw 1;
}
if(qualities1.size() > 0 && mates1.size() != qualities1.size()) {
cerr << "Error: " << mates1.size() << " mate files/sequences were specified with -1, but " << qualities1.size() << endl
<< "quality files were specified with --Q1. The same number of mate and quality" << endl
<< "files must sequences must be specified with -1 and --Q1." << endl;
throw 1;
}
if(qualities2.size() > 0 && mates2.size() != qualities2.size()) {
cerr << "Error: " << mates2.size() << " mate files/sequences were specified with -2, but " << qualities2.size() << endl
<< "quality files were specified with --Q2. The same number of mate and quality" << endl
<< "files must sequences must be specified with -2 and --Q2." << endl;
throw 1;
}
if(!rgs.empty() && rgid.empty()) {
cerr << "Warning: --rg was specified without --rg-id also "
<< "being specified. @RG line is not printed unless --rg-id "
<< "is specified." << endl;
}
// Check for duplicate mate input files
if(format != CMDLINE) {
for(size_t i = 0; i < mates1.size(); i++) {
for(size_t j = 0; j < mates2.size(); j++) {
if(mates1[i] == mates2[j] && !gQuiet) {
cerr << "Warning: Same mate file \"" << mates1[i].c_str() << "\" appears as argument to both -1 and -2" << endl;
}
}
}
}
// If both -s and -u are used, we need to adjust qUpto accordingly
// since it uses rdid to know if we've reached the -u limit (and
// rdids are all shifted up by skipReads characters)
if(qUpto + skipReads > qUpto) {
qUpto += skipReads;
}
if(useShmem && useMm && !gQuiet) {
cerr << "Warning: --shmem overrides --mm..." << endl;
useMm = false;
}
if(gGapBarrier < 1) {
cerr << "Warning: --gbar was set less than 1 (=" << gGapBarrier
<< "); setting to 1 instead" << endl;
gGapBarrier = 1;
}
if(bonusMatch > 0 && !scoreMin.alwaysPositive()) {
cerr << "Error: the match penalty is greater than 0 (" << bonusMatch
<< ") but the --score-min function can be less than or equal to "
<< "zero. Either let the match penalty be 0 or make --score-min "
<< "always positive." << endl;
throw 1;
}
if(multiseedMms >= multiseedLen) {
assert_gt(multiseedLen, 0);
cerr << "Warning: seed mismatches (" << multiseedMms
<< ") is less than seed length (" << multiseedLen
<< "); setting mismatches to " << (multiseedMms-1)
<< " instead" << endl;
multiseedMms = multiseedLen-1;
}
sam_print_zm = sam_print_zm && bowtie2p5;
#ifndef NDEBUG
if(!gQuiet) {
cerr << "Warning: Running in debug mode. Please use debug mode only "
<< "for diagnosing errors, and not for typical use of Bowtie 2."
<< endl;
}
#endif
}
static const char *argv0 = NULL;
#if 0
/// Create a PatternSourcePerThread for the current thread according
/// to the global params and return a pointer to it
static PatternSourcePerThreadFactory*
createPatsrcFactory(
PatternComposer& patcomp,
const PatternParams& pp,
int tid)
{
PatternSourcePerThreadFactory *patsrcFact;
patsrcFact = new PatternSourcePerThreadFactory(patcomp, pp, tid);
assert(patsrcFact != NULL);
return patsrcFact;
}
#endif
#define PTHREAD_ATTRS (PTHREAD_CREATE_JOINABLE | PTHREAD_CREATE_DETACHED)
static PatternSourceReadAheadFactory* multiseed_readahead_factory;
static Ebwt* multiseed_ebwtFw;
static Ebwt* multiseed_ebwtBw;
static Scoring* multiseed_sc;
static BitPairReference* multiseed_refs;
static AlignmentCache* multiseed_ca; // seed cache
static AlnSink* multiseed_msink;
static OutFileBuf* multiseed_metricsOfb;
/**
* Metrics for measuring the work done by the outer read alignment
* loop.
*/
struct OuterLoopMetrics {
OuterLoopMetrics() {
reset();
}
/**
* Set all counters to 0.
*/
void reset() {
reads = bases = srreads = srbases =
freads = fbases = ureads = ubases = 0;
}
/**
* Sum the counters in m in with the conters in this object. This
* is the only safe way to update an OuterLoopMetrics that's shared
* by multiple threads.
*/
void merge(const OuterLoopMetrics& m) {
reads += m.reads;
bases += m.bases;
srreads += m.srreads;
srbases += m.srbases;
freads += m.freads;
fbases += m.fbases;
ureads += m.ureads;
ubases += m.ubases;
}
uint64_t reads; // total reads
uint64_t bases; // total bases
uint64_t srreads; // same-read reads
uint64_t srbases; // same-read bases
uint64_t freads; // filtered reads
uint64_t fbases; // filtered bases
uint64_t ureads; // unfiltered reads
uint64_t ubases; // unfiltered bases
MUTEX_T mutex_m;
};
/**
* Collection of all relevant performance metrics when aligning in
* multiseed mode.
*/
struct PerfMetrics {
PerfMetrics() : first(true) { reset(); }
/**
* Set all counters to 0.
*/
void reset() {
olm.reset();
sdm.reset();
wlm.reset();
swmSeed.reset();
swmMate.reset();
rpm.reset();
dpSse8Seed.reset(); // 8-bit SSE seed extensions
dpSse8Mate.reset(); // 8-bit SSE mate finds
dpSse16Seed.reset(); // 16-bit SSE seed extensions
dpSse16Mate.reset(); // 16-bit SSE mate finds
nbtfiltst = 0;
nbtfiltsc = 0;
nbtfiltdo = 0;
olmu.reset();
sdmu.reset();
wlmu.reset();
swmuSeed.reset();
swmuMate.reset();
rpmu.reset();
dpSse8uSeed.reset(); // 8-bit SSE seed extensions
dpSse8uMate.reset(); // 8-bit SSE mate finds
dpSse16uSeed.reset(); // 16-bit SSE seed extensions
dpSse16uMate.reset(); // 16-bit SSE mate finds
nbtfiltst_u = 0;
nbtfiltsc_u = 0;
nbtfiltdo_u = 0;
}
/**
* Merge a set of specific metrics into this object.
*/
void merge(
const OuterLoopMetrics *ol,
const SeedSearchMetrics *sd,
const WalkMetrics *wl,
const SwMetrics *swSeed,
const SwMetrics *swMate,
const ReportingMetrics *rm,
const SSEMetrics *dpSse8Ex,
const SSEMetrics *dpSse8Ma,
const SSEMetrics *dpSse16Ex,
const SSEMetrics *dpSse16Ma,
uint64_t nbtfiltst_,
uint64_t nbtfiltsc_,
uint64_t nbtfiltdo_)
{
ThreadSafe ts(mutex_m);
if(ol != NULL) {
olmu.merge(*ol);
}
if(sd != NULL) {
sdmu.merge(*sd);
}
if(wl != NULL) {
wlmu.merge(*wl);
}
if(swSeed != NULL) {
swmuSeed.merge(*swSeed);
}
if(swMate != NULL) {
swmuMate.merge(*swMate);
}
if(rm != NULL) {
rpmu.merge(*rm);
}
if(dpSse8Ex != NULL) {
dpSse8uSeed.merge(*dpSse8Ex);
}
if(dpSse8Ma != NULL) {
dpSse8uMate.merge(*dpSse8Ma);
}
if(dpSse16Ex != NULL) {
dpSse16uSeed.merge(*dpSse16Ex);
}
if(dpSse16Ma != NULL) {
dpSse16uMate.merge(*dpSse16Ma);
}
nbtfiltst_u += nbtfiltst_;
nbtfiltsc_u += nbtfiltsc_;
nbtfiltdo_u += nbtfiltdo_;
}
/**
* Reports a matrix of results, incl. column labels, to an OutFileBuf.
* Optionally also sends results to stderr (unbuffered). Can optionally
* print a per-read record with the read name at the beginning.
*/
void reportInterval(
OutFileBuf* o, // file to send output to
bool metricsStderr, // additionally output to stderr?
bool total, // true -> report total, otherwise incremental
const BTString *name) // non-NULL name pointer if is per-read record
{
ThreadSafe ts(mutex_m);
ostringstream stderrSs;
time_t curtime = time(0);
char buf[1024];
if(first) {
const char *str =
/* 1 */ "Time" "\t"
/* 2 */ "Read" "\t"
/* 3 */ "Base" "\t"
/* 4 */ "SameRead" "\t"
/* 5 */ "SameReadBase" "\t"
/* 6 */ "UnfilteredRead" "\t"
/* 7 */ "UnfilteredBase" "\t"
/* 8 */ "Paired" "\t"
/* 9 */ "Unpaired" "\t"
/* 10 */ "AlConUni" "\t"
/* 11 */ "AlConRep" "\t"
/* 12 */ "AlConFail" "\t"
/* 13 */ "AlDis" "\t"
/* 14 */ "AlConFailUni" "\t"
/* 15 */ "AlConFailRep" "\t"
/* 16 */ "AlConFailFail" "\t"
/* 17 */ "AlConRepUni" "\t"
/* 18 */ "AlConRepRep" "\t"
/* 19 */ "AlConRepFail" "\t"
/* 20 */ "AlUnpUni" "\t"
/* 21 */ "AlUnpRep" "\t"
/* 22 */ "AlUnpFail" "\t"
/* 23 */ "SeedSearch" "\t"
/* 24 */ "NRange" "\t"
/* 25 */ "NElt" "\t"
/* 26 */ "IntraSCacheHit" "\t"
/* 27 */ "InterSCacheHit" "\t"
/* 28 */ "OutOfMemory" "\t"
/* 29 */ "AlBWOp" "\t"
/* 30 */ "AlBWBranch" "\t"
/* 31 */ "ResBWOp" "\t"
/* 32 */ "ResBWBranch" "\t"
/* 33 */ "ResResolve" "\t"
/* 34 */ "ResReport" "\t"
/* 35 */ "RedundantSHit" "\t"
/* 36 */ "BestMinEdit0" "\t"
/* 37 */ "BestMinEdit1" "\t"
/* 38 */ "BestMinEdit2" "\t"
/* 39 */ "ExactAttempts" "\t"
/* 40 */ "ExactSucc" "\t"
/* 41 */ "ExactRanges" "\t"
/* 42 */ "ExactRows" "\t"
/* 43 */ "ExactOOMs" "\t"
/* 44 */ "1mmAttempts" "\t"
/* 45 */ "1mmSucc" "\t"
/* 46 */ "1mmRanges" "\t"
/* 47 */ "1mmRows" "\t"
/* 48 */ "1mmOOMs" "\t"
/* 49 */ "UngappedSucc" "\t"
/* 50 */ "UngappedFail" "\t"
/* 51 */ "UngappedNoDec" "\t"
/* 52 */ "DPExLt10Gaps" "\t"
/* 53 */ "DPExLt5Gaps" "\t"
/* 54 */ "DPExLt3Gaps" "\t"
/* 55 */ "DPMateLt10Gaps" "\t"
/* 56 */ "DPMateLt5Gaps" "\t"
/* 57 */ "DPMateLt3Gaps" "\t"
/* 58 */ "DP16ExDps" "\t"
/* 59 */ "DP16ExDpSat" "\t"
/* 60 */ "DP16ExDpFail" "\t"
/* 61 */ "DP16ExDpSucc" "\t"
/* 62 */ "DP16ExCol" "\t"
/* 63 */ "DP16ExCell" "\t"
/* 64 */ "DP16ExInner" "\t"
/* 65 */ "DP16ExFixup" "\t"
/* 66 */ "DP16ExGathSol" "\t"
/* 67 */ "DP16ExBt" "\t"
/* 68 */ "DP16ExBtFail" "\t"
/* 69 */ "DP16ExBtSucc" "\t"
/* 70 */ "DP16ExBtCell" "\t"
/* 71 */ "DP16ExCoreRej" "\t"
/* 72 */ "DP16ExNRej" "\t"
/* 73 */ "DP8ExDps" "\t"
/* 74 */ "DP8ExDpSat" "\t"
/* 75 */ "DP8ExDpFail" "\t"
/* 76 */ "DP8ExDpSucc" "\t"
/* 77 */ "DP8ExCol" "\t"
/* 78 */ "DP8ExCell" "\t"
/* 79 */ "DP8ExInner" "\t"
/* 80 */ "DP8ExFixup" "\t"
/* 81 */ "DP8ExGathSol" "\t"
/* 82 */ "DP8ExBt" "\t"
/* 83 */ "DP8ExBtFail" "\t"
/* 84 */ "DP8ExBtSucc" "\t"
/* 85 */ "DP8ExBtCell" "\t"
/* 86 */ "DP8ExCoreRej" "\t"
/* 87 */ "DP8ExNRej" "\t"
/* 88 */ "DP16MateDps" "\t"
/* 89 */ "DP16MateDpSat" "\t"
/* 90 */ "DP16MateDpFail" "\t"
/* 91 */ "DP16MateDpSucc" "\t"
/* 92 */ "DP16MateCol" "\t"
/* 93 */ "DP16MateCell" "\t"
/* 94 */ "DP16MateInner" "\t"
/* 95 */ "DP16MateFixup" "\t"
/* 96 */ "DP16MateGathSol" "\t"
/* 97 */ "DP16MateBt" "\t"
/* 98 */ "DP16MateBtFail" "\t"
/* 99 */ "DP16MateBtSucc" "\t"
/* 100 */ "DP16MateBtCell" "\t"
/* 101 */ "DP16MateCoreRej" "\t"
/* 102 */ "DP16MateNRej" "\t"
/* 103 */ "DP8MateDps" "\t"
/* 104 */ "DP8MateDpSat" "\t"
/* 105 */ "DP8MateDpFail" "\t"
/* 106 */ "DP8MateDpSucc" "\t"
/* 107 */ "DP8MateCol" "\t"
/* 108 */ "DP8MateCell" "\t"
/* 109 */ "DP8MateInner" "\t"
/* 110 */ "DP8MateFixup" "\t"
/* 111 */ "DP8MateGathSol" "\t"
/* 112 */ "DP8MateBt" "\t"
/* 113 */ "DP8MateBtFail" "\t"
/* 114 */ "DP8MateBtSucc" "\t"
/* 115 */ "DP8MateBtCell" "\t"
/* 116 */ "DP8MateCoreRej" "\t"
/* 117 */ "DP8MateNRej" "\t"
/* 118 */ "DPBtFiltStart" "\t"
/* 119 */ "DPBtFiltScore" "\t"
/* 120 */ "DpBtFiltDom" "\t"
#ifdef USE_MEM_TALLY
/* 121 */ "MemPeak" "\t"
/* 122 */ "UncatMemPeak" "\t" // 0
/* 123 */ "EbwtMemPeak" "\t" // EBWT_CAT
/* 124 */ "CacheMemPeak" "\t" // CA_CAT
/* 125 */ "ResolveMemPeak" "\t" // GW_CAT
/* 126 */ "AlignMemPeak" "\t" // AL_CAT
/* 127 */ "DPMemPeak" "\t" // DP_CAT
/* 128 */ "MiscMemPeak" "\t" // MISC_CAT
/* 129 */ "DebugMemPeak" "\t" // DEBUG_CAT
#endif
"\n";
if(name != NULL) {
if(o != NULL) o->writeChars("Name\t");
if(metricsStderr) stderrSs << "Name\t";
}
if(o != NULL) o->writeChars(str);
if(metricsStderr) stderrSs << str;
first = false;
}
if(total) mergeIncrementals();
// 0. Read name, if needed
if(name != NULL) {
if(o != NULL) {
o->writeChars(name->toZBuf());
o->write('\t');
}
if(metricsStderr) {
stderrSs << (*name) << '\t';
}
}
// 1. Current time in secs
itoa10<time_t>(curtime, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const OuterLoopMetrics& ol = total ? olm : olmu;
// 2. Reads
itoa10<uint64_t>(ol.reads, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 3. Bases
itoa10<uint64_t>(ol.bases, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 4. Same-read reads
itoa10<uint64_t>(ol.srreads, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 5. Same-read bases
itoa10<uint64_t>(ol.srbases, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 6. Unfiltered reads
itoa10<uint64_t>(ol.ureads, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 7. Unfiltered bases
itoa10<uint64_t>(ol.ubases, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const ReportingMetrics& rp = total ? rpm : rpmu;
// 8. Paired reads
itoa10<uint64_t>(rp.npaired, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 9. Unpaired reads
itoa10<uint64_t>(rp.nunpaired, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 10. Pairs with unique concordant alignments
itoa10<uint64_t>(rp.nconcord_uni, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 11. Pairs with repetitive concordant alignments
itoa10<uint64_t>(rp.nconcord_rep, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 12. Pairs with 0 concordant alignments
itoa10<uint64_t>(rp.nconcord_0, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 13. Pairs with 1 discordant alignment
itoa10<uint64_t>(rp.ndiscord, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 14. Mates from unaligned pairs that align uniquely
itoa10<uint64_t>(rp.nunp_0_uni, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 15. Mates from unaligned pairs that align repetitively
itoa10<uint64_t>(rp.nunp_0_rep, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 16. Mates from unaligned pairs that fail to align
itoa10<uint64_t>(rp.nunp_0_0, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 17. Mates from repetitive pairs that align uniquely
itoa10<uint64_t>(rp.nunp_rep_uni, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 18. Mates from repetitive pairs that align repetitively
itoa10<uint64_t>(rp.nunp_rep_rep, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 19. Mates from repetitive pairs that fail to align
itoa10<uint64_t>(rp.nunp_rep_0, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 20. Unpaired reads that align uniquely
itoa10<uint64_t>(rp.nunp_uni, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 21. Unpaired reads that align repetitively
itoa10<uint64_t>(rp.nunp_rep, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 22. Unpaired reads that fail to align
itoa10<uint64_t>(rp.nunp_0, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const SeedSearchMetrics& sd = total ? sdm : sdmu;
// 23. Seed searches
itoa10<uint64_t>(sd.seedsearch, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 24. Seed ranges found
itoa10<uint64_t>(sd.nrange, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 25. Seed elements found
itoa10<uint64_t>(sd.nelt, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 26. Hits in 'current' cache
itoa10<uint64_t>(sd.intrahit, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 27. Hits in 'local' cache
itoa10<uint64_t>(sd.interhit, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 28. Out of memory
itoa10<uint64_t>(sd.ooms, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 29. Burrows-Wheeler ops in aligner
itoa10<uint64_t>(sd.bwops, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 30. Burrows-Wheeler branches (edits) in aligner
itoa10<uint64_t>(sd.bweds, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const WalkMetrics& wl = total ? wlm : wlmu;
// 31. Burrows-Wheeler ops in resolver
itoa10<uint64_t>(wl.bwops, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 32. Burrows-Wheeler branches in resolver
itoa10<uint64_t>(wl.branches, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 33. Burrows-Wheeler offset resolutions
itoa10<uint64_t>(wl.resolves, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 34. Offset reports
itoa10<uint64_t>(wl.reports, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 35. Redundant seed hit
itoa10<uint64_t>(total ? swmSeed.rshit : swmuSeed.rshit, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 36. # times the best (out of fw/rc) minimum # edits was 0
itoa10<uint64_t>(total ? sdm.bestmin0 : sdmu.bestmin0, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 37. # times the best (out of fw/rc) minimum # edits was 1
itoa10<uint64_t>(total ? sdm.bestmin1 : sdmu.bestmin1, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 38. # times the best (out of fw/rc) minimum # edits was 2
itoa10<uint64_t>(total ? sdm.bestmin2 : sdmu.bestmin2, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 39. Exact aligner attempts
itoa10<uint64_t>(total ? swmSeed.exatts : swmuSeed.exatts, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 40. Exact aligner successes
itoa10<uint64_t>(total ? swmSeed.exsucc : swmuSeed.exsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 41. Exact aligner ranges
itoa10<uint64_t>(total ? swmSeed.exranges : swmuSeed.exranges, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 42. Exact aligner rows
itoa10<uint64_t>(total ? swmSeed.exrows : swmuSeed.exrows, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 43. Exact aligner OOMs
itoa10<uint64_t>(total ? swmSeed.exooms : swmuSeed.exooms, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 44. 1mm aligner attempts
itoa10<uint64_t>(total ? swmSeed.mm1atts : swmuSeed.mm1atts, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 45. 1mm aligner successes
itoa10<uint64_t>(total ? swmSeed.mm1succ : swmuSeed.mm1succ, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 46. 1mm aligner ranges
itoa10<uint64_t>(total ? swmSeed.mm1ranges : swmuSeed.mm1ranges, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 47. 1mm aligner rows
itoa10<uint64_t>(total ? swmSeed.mm1rows : swmuSeed.mm1rows, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 48. 1mm aligner OOMs
itoa10<uint64_t>(total ? swmSeed.mm1ooms : swmuSeed.mm1ooms, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 49 Ungapped aligner success
itoa10<uint64_t>(total ? swmSeed.ungapsucc : swmuSeed.ungapsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 50. Ungapped aligner fail
itoa10<uint64_t>(total ? swmSeed.ungapfail : swmuSeed.ungapfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 51. Ungapped aligner no decision
itoa10<uint64_t>(total ? swmSeed.ungapnodec : swmuSeed.ungapnodec, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 52. # seed-extend DPs with < 10 gaps
itoa10<uint64_t>(total ? swmSeed.sws10 : swmuSeed.sws10, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 53. # seed-extend DPs with < 5 gaps
itoa10<uint64_t>(total ? swmSeed.sws5 : swmuSeed.sws5, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 54. # seed-extend DPs with < 3 gaps
itoa10<uint64_t>(total ? swmSeed.sws3 : swmuSeed.sws3, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 55. # seed-extend DPs with < 10 gaps
itoa10<uint64_t>(total ? swmMate.sws10 : swmuMate.sws10, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 56. # seed-extend DPs with < 5 gaps
itoa10<uint64_t>(total ? swmMate.sws5 : swmuMate.sws5, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 57. # seed-extend DPs with < 3 gaps
itoa10<uint64_t>(total ? swmMate.sws3 : swmuMate.sws3, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const SSEMetrics& dpSse16s = total ? dpSse16Seed : dpSse16uSeed;
// 58. 16-bit SSE seed-extend DPs tried
itoa10<uint64_t>(dpSse16s.dp, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 59. 16-bit SSE seed-extend DPs saturated
itoa10<uint64_t>(dpSse16s.dpsat, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 60. 16-bit SSE seed-extend DPs failed
itoa10<uint64_t>(dpSse16s.dpfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 61. 16-bit SSE seed-extend DPs succeeded
itoa10<uint64_t>(dpSse16s.dpsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 62. 16-bit SSE seed-extend DP columns completed
itoa10<uint64_t>(dpSse16s.col, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 63. 16-bit SSE seed-extend DP cells completed
itoa10<uint64_t>(dpSse16s.cell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 64. 16-bit SSE seed-extend DP inner loop iters completed
itoa10<uint64_t>(dpSse16s.inner, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 65. 16-bit SSE seed-extend DP fixup loop iters completed
itoa10<uint64_t>(dpSse16s.fixup, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 66. 16-bit SSE seed-extend DP gather, cells with potential solutions
itoa10<uint64_t>(dpSse16s.gathsol, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 67. 16-bit SSE seed-extend DP backtrace attempts
itoa10<uint64_t>(dpSse16s.bt, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 68. 16-bit SSE seed-extend DP failed backtrace attempts
itoa10<uint64_t>(dpSse16s.btfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 69. 16-bit SSE seed-extend DP succesful backtrace attempts
itoa10<uint64_t>(dpSse16s.btsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 70. 16-bit SSE seed-extend DP backtrace cells
itoa10<uint64_t>(dpSse16s.btcell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 71. 16-bit SSE seed-extend DP core-diag rejections
itoa10<uint64_t>(dpSse16s.corerej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 72. 16-bit SSE seed-extend DP N rejections
itoa10<uint64_t>(dpSse16s.nrej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const SSEMetrics& dpSse8s = total ? dpSse8Seed : dpSse8uSeed;
// 73. 8-bit SSE seed-extend DPs tried
itoa10<uint64_t>(dpSse8s.dp, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 74. 8-bit SSE seed-extend DPs saturated
itoa10<uint64_t>(dpSse8s.dpsat, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 75. 8-bit SSE seed-extend DPs failed
itoa10<uint64_t>(dpSse8s.dpfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 76. 8-bit SSE seed-extend DPs succeeded
itoa10<uint64_t>(dpSse8s.dpsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 77. 8-bit SSE seed-extend DP columns completed
itoa10<uint64_t>(dpSse8s.col, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 78. 8-bit SSE seed-extend DP cells completed
itoa10<uint64_t>(dpSse8s.cell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 79. 8-bit SSE seed-extend DP inner loop iters completed
itoa10<uint64_t>(dpSse8s.inner, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 80. 8-bit SSE seed-extend DP fixup loop iters completed
itoa10<uint64_t>(dpSse8s.fixup, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 81. 16-bit SSE seed-extend DP gather, cells with potential solutions
itoa10<uint64_t>(dpSse8s.gathsol, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 82. 16-bit SSE seed-extend DP backtrace attempts
itoa10<uint64_t>(dpSse8s.bt, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 83. 16-bit SSE seed-extend DP failed backtrace attempts
itoa10<uint64_t>(dpSse8s.btfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 84. 16-bit SSE seed-extend DP succesful backtrace attempts
itoa10<uint64_t>(dpSse8s.btsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 85. 16-bit SSE seed-extend DP backtrace cells
itoa10<uint64_t>(dpSse8s.btcell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 86. 16-bit SSE seed-extend DP core-diag rejections
itoa10<uint64_t>(dpSse8s.corerej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 87. 16-bit SSE seed-extend DP N rejections
itoa10<uint64_t>(dpSse8s.nrej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const SSEMetrics& dpSse16m = total ? dpSse16Mate : dpSse16uMate;
// 88. 16-bit SSE mate-finding DPs tried
itoa10<uint64_t>(dpSse16m.dp, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 89. 16-bit SSE mate-finding DPs saturated
itoa10<uint64_t>(dpSse16m.dpsat, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 90. 16-bit SSE mate-finding DPs failed
itoa10<uint64_t>(dpSse16m.dpfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 91. 16-bit SSE mate-finding DPs succeeded
itoa10<uint64_t>(dpSse16m.dpsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 92. 16-bit SSE mate-finding DP columns completed
itoa10<uint64_t>(dpSse16m.col, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 93. 16-bit SSE mate-finding DP cells completed
itoa10<uint64_t>(dpSse16m.cell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 94. 16-bit SSE mate-finding DP inner loop iters completed
itoa10<uint64_t>(dpSse16m.inner, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 95. 16-bit SSE mate-finding DP fixup loop iters completed
itoa10<uint64_t>(dpSse16m.fixup, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 96. 16-bit SSE mate-finding DP gather, cells with potential solutions
itoa10<uint64_t>(dpSse16m.gathsol, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 97. 16-bit SSE mate-finding DP backtrace attempts
itoa10<uint64_t>(dpSse16m.bt, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 98. 16-bit SSE mate-finding DP failed backtrace attempts
itoa10<uint64_t>(dpSse16m.btfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 99. 16-bit SSE mate-finding DP succesful backtrace attempts
itoa10<uint64_t>(dpSse16m.btsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 100. 16-bit SSE mate-finding DP backtrace cells
itoa10<uint64_t>(dpSse16m.btcell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 101. 16-bit SSE mate-finding DP core-diag rejections
itoa10<uint64_t>(dpSse16m.corerej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 102. 16-bit SSE mate-finding DP N rejections
itoa10<uint64_t>(dpSse16m.nrej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
const SSEMetrics& dpSse8m = total ? dpSse8Mate : dpSse8uMate;
// 103. 8-bit SSE mate-finding DPs tried
itoa10<uint64_t>(dpSse8m.dp, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 104. 8-bit SSE mate-finding DPs saturated
itoa10<uint64_t>(dpSse8m.dpsat, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 105. 8-bit SSE mate-finding DPs failed
itoa10<uint64_t>(dpSse8m.dpfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 106. 8-bit SSE mate-finding DPs succeeded
itoa10<uint64_t>(dpSse8m.dpsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 107. 8-bit SSE mate-finding DP columns completed
itoa10<uint64_t>(dpSse8m.col, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 108. 8-bit SSE mate-finding DP cells completed
itoa10<uint64_t>(dpSse8m.cell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 109. 8-bit SSE mate-finding DP inner loop iters completed
itoa10<uint64_t>(dpSse8m.inner, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 110. 8-bit SSE mate-finding DP fixup loop iters completed
itoa10<uint64_t>(dpSse8m.fixup, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 111. 16-bit SSE mate-finding DP gather, cells with potential solutions
itoa10<uint64_t>(dpSse8m.gathsol, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 112. 16-bit SSE mate-finding DP backtrace attempts
itoa10<uint64_t>(dpSse8m.bt, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 113. 16-bit SSE mate-finding DP failed backtrace attempts
itoa10<uint64_t>(dpSse8m.btfail, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 114. 16-bit SSE mate-finding DP succesful backtrace attempts
itoa10<uint64_t>(dpSse8m.btsucc, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 115. 16-bit SSE mate-finding DP backtrace cells
itoa10<uint64_t>(dpSse8m.btcell, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 116. 16-bit SSE mate-finding DP core rejections
itoa10<uint64_t>(dpSse8m.corerej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 117. 16-bit SSE mate-finding N rejections
itoa10<uint64_t>(dpSse8m.nrej, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 118. Backtrace candidates filtered due to starting cell
itoa10<uint64_t>(total ? nbtfiltst : nbtfiltst_u, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 119. Backtrace candidates filtered due to low score
itoa10<uint64_t>(total ? nbtfiltsc : nbtfiltsc_u, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 120. Backtrace candidates filtered due to domination
itoa10<uint64_t>(total ? nbtfiltdo : nbtfiltdo_u, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
#ifdef USE_MEM_TALLY
// 121. Overall memory peak
itoa10<size_t>(gMemTally.peak() >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 122. Uncategorized memory peak
itoa10<size_t>(gMemTally.peak(0) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 123. Ebwt memory peak
itoa10<size_t>(gMemTally.peak(EBWT_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 124. Cache memory peak
itoa10<size_t>(gMemTally.peak(CA_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 125. Resolver memory peak
itoa10<size_t>(gMemTally.peak(GW_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 126. Seed aligner memory peak
itoa10<size_t>(gMemTally.peak(AL_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 127. Dynamic programming aligner memory peak
itoa10<size_t>(gMemTally.peak(DP_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 128. Miscellaneous memory peak
itoa10<size_t>(gMemTally.peak(MISC_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf << '\t';
if(o != NULL) { o->writeChars(buf); o->write('\t'); }
// 129. Debug memory peak
itoa10<size_t>(gMemTally.peak(DEBUG_CAT) >> 20, buf);
if(metricsStderr) stderrSs << buf;
if(o != NULL) { o->writeChars(buf); }
#endif
if(o != NULL) { o->write('\n'); }
if(metricsStderr) cerr << stderrSs.str().c_str() << endl;
if(!total) mergeIncrementals();
}
void mergeIncrementals() {
olm.merge(olmu);
sdm.merge(sdmu);
wlm.merge(wlmu);
swmSeed.merge(swmuSeed);
swmMate.merge(swmuMate);
dpSse8Seed.merge(dpSse8uSeed);
dpSse8Mate.merge(dpSse8uMate);
dpSse16Seed.merge(dpSse16uSeed);
dpSse16Mate.merge(dpSse16uMate);
nbtfiltst_u += nbtfiltst;
nbtfiltsc_u += nbtfiltsc;
nbtfiltdo_u += nbtfiltdo;
olmu.reset();
sdmu.reset();
wlmu.reset();
swmuSeed.reset();
swmuMate.reset();
rpmu.reset();
dpSse8uSeed.reset();
dpSse8uMate.reset();
dpSse16uSeed.reset();
dpSse16uMate.reset();
nbtfiltst_u = 0;
nbtfiltsc_u = 0;
nbtfiltdo_u = 0;
}
// Total over the whole job
OuterLoopMetrics olm; // overall metrics
SeedSearchMetrics sdm; // metrics related to seed alignment
WalkMetrics wlm; // metrics related to walking left (i.e. resolving reference offsets)
SwMetrics swmSeed; // metrics related to DP seed-extend alignment
SwMetrics swmMate; // metrics related to DP mate-finding alignment
ReportingMetrics rpm; // metrics related to reporting
SSEMetrics dpSse8Seed; // 8-bit SSE seed extensions
SSEMetrics dpSse8Mate; // 8-bit SSE mate finds
SSEMetrics dpSse16Seed; // 16-bit SSE seed extensions
SSEMetrics dpSse16Mate; // 16-bit SSE mate finds
uint64_t nbtfiltst;
uint64_t nbtfiltsc;
uint64_t nbtfiltdo;
// Just since the last update
OuterLoopMetrics olmu; // overall metrics
SeedSearchMetrics sdmu; // metrics related to seed alignment
WalkMetrics wlmu; // metrics related to walking left (i.e. resolving reference offsets)
SwMetrics swmuSeed; // metrics related to DP seed-extend alignment
SwMetrics swmuMate; // metrics related to DP mate-finding alignment
ReportingMetrics rpmu; // metrics related to reporting
SSEMetrics dpSse8uSeed; // 8-bit SSE seed extensions
SSEMetrics dpSse8uMate; // 8-bit SSE mate finds
SSEMetrics dpSse16uSeed; // 16-bit SSE seed extensions
SSEMetrics dpSse16uMate; // 16-bit SSE mate finds
uint64_t nbtfiltst_u;
uint64_t nbtfiltsc_u;
uint64_t nbtfiltdo_u;
MUTEX_T mutex_m; // lock for when one ob
bool first; // yet to print first line?
time_t lastElapsed; // used in reportInterval to measure time since last call
};
static PerfMetrics metrics;
// Cyclic rotations
#define ROTL(n, x) (((x) << (n)) | ((x) >> (32-n)))
#define ROTR(n, x) (((x) >> (n)) | ((x) << (32-n)))
static inline void printMmsSkipMsg(
const PatternSourcePerThread& ps,
bool paired,
bool mate1,
int seedmms)
{
ostringstream os;
if(paired) {
os << "Warning: skipping mate #" << (mate1 ? '1' : '2')
<< " of read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "' because length (" << (mate1 ? ps.read_a().patFw.length() : ps.read_b().patFw.length())
<< ") <= # seed mismatches (" << seedmms << ")" << endl;
} else {
os << "Warning: skipping read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "' because length (" << (mate1 ? ps.read_a().patFw.length() : ps.read_b().patFw.length())
<< ") <= # seed mismatches (" << seedmms << ")" << endl;
}
cerr << os.str().c_str();
}
static inline void printLenSkipMsg(
const PatternSourcePerThread& ps,
bool paired,
bool mate1)
{
ostringstream os;
if(paired) {
os << "Warning: skipping mate #" << (mate1 ? '1' : '2')
<< " of read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "' because it was < 2 characters long" << endl;
} else {
os << "Warning: skipping read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "' because it was < 2 characters long" << endl;
}
cerr << os.str().c_str();
}
static inline void printLocalScoreMsg(
const PatternSourcePerThread& ps,
bool paired,
bool mate1)
{
ostringstream os;
if(paired) {
os << "Warning: minimum score function gave negative number in "
<< "--local mode for mate #" << (mate1 ? '1' : '2')
<< " of read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "; setting to 0 instead" << endl;
} else {
os << "Warning: minimum score function gave negative number in "
<< "--local mode for read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "; setting to 0 instead" << endl;
}
cerr << os.str().c_str();
}
static inline void printEEScoreMsg(
const PatternSourcePerThread& ps,
bool paired,
bool mate1)
{
ostringstream os;
if(paired) {
os << "Warning: minimum score function gave positive number in "
<< "--end-to-end mode for mate #" << (mate1 ? '1' : '2')
<< " of read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "; setting to 0 instead" << endl;
} else {
os << "Warning: minimum score function gave positive number in "
<< "--end-to-end mode for read '" << (mate1 ? ps.read_a().name : ps.read_b().name)
<< "; setting to 0 instead" << endl;
}
cerr << os.str().c_str();
}
/**
* Initialize the minsc and maxpen arrays given information about the reads,
* the alignment policy and the scoring scheme.
*/
static void setupMinScores(
const PatternSourcePerThread& ps,
bool paired,
bool localAlign,
const Scoring& sc,
const size_t *rdlens,
TAlScore *minsc,
TAlScore *maxpen)
{
if(bwaSwLike) {
// From BWA-SW manual: "Given an l-long query, the
// threshold for a hit to be retained is
// a*max{T,c*log(l)}." We try to recreate that here.
float a = (float)sc.match(30);
float T = bwaSwLikeT, c = bwaSwLikeC;
minsc[0] = (TAlScore)max<float>(a*T, a*c*log(rdlens[0]));
if(paired) {
minsc[1] = (TAlScore)max<float>(a*T, a*c*log(rdlens[1]));
}
} else {
minsc[0] = scoreMin.f<TAlScore>(rdlens[0]);
if(paired) minsc[1] = scoreMin.f<TAlScore>(rdlens[1]);
if(localAlign) {
if(minsc[0] < 0) {
if(!gQuiet) printLocalScoreMsg(ps, paired, true);
minsc[0] = 0;
}
if(paired && minsc[1] < 0) {
if(!gQuiet) printLocalScoreMsg(ps, paired, false);
minsc[1] = 0;
}
} else {
if(minsc[0] > 0) {
if(!gQuiet) printEEScoreMsg(ps, paired, true);
minsc[0] = 0;
}
if(paired && minsc[1] > 0) {
if(!gQuiet) printEEScoreMsg(ps, paired, false);
minsc[1] = 0;
}
}
}
// Given minsc, calculate maxpen
if(localAlign) {
TAlScore perfect0 = sc.perfectScore(rdlens[0]);
assert_geq(perfect0, minsc[0]);
maxpen[0] = perfect0 - minsc[0];
if(paired) {
TAlScore perfect1 = sc.perfectScore(rdlens[1]);
assert_geq(perfect1, minsc[1]);
maxpen[1] = perfect1 - minsc[1];
} else {
maxpen[1] = std::numeric_limits<TAlScore>::min();
}
} else {
assert_leq(minsc[0], 0);
maxpen[0] = -minsc[0];
if(paired) {
assert_leq(minsc[1], 0);
maxpen[1] = -minsc[1];
} else {
maxpen[1] = std::numeric_limits<TAlScore>::min();
}
}
}
#define MERGE_METRICS(met) { \
msink.mergeMetrics(rpm); \
met.merge( \
&olm, \
&sdm, \
&wlm, \
&swmSeed, \
&swmMate, \
&rpm, \
&sseU8ExtendMet, \
&sseU8MateMet, \
&sseI16ExtendMet, \
&sseI16MateMet, \
nbtfiltst, \
nbtfiltsc, \
nbtfiltdo); \
olm.reset(); \
sdm.reset(); \
wlm.reset(); \
swmSeed.reset(); \
swmMate.reset(); \
rpm.reset(); \
sseU8ExtendMet.reset(); \
sseU8MateMet.reset(); \
sseI16ExtendMet.reset(); \
sseI16MateMet.reset(); \
}
#define MERGE_SW(x) { \
x.merge( \
sseU8ExtendMet, \
sseU8MateMet, \
sseI16ExtendMet, \
sseI16MateMet, \
nbtfiltst, \
nbtfiltsc, \
nbtfiltdo); \
x.resetCounters(); \
}
#ifdef PER_THREAD_TIMING
/// Based on http://stackoverflow.com/questions/16862620/numa-get-current-node-core
void get_cpu_and_node(int& cpu, int& node) {
unsigned long a,d,c;
__asm__ volatile("rdtscp" : "=a" (a), "=d" (d), "=c" (c));
node = (c & 0xFFF000)>>12;
cpu = c & 0xFFF;
}
#endif
class ThreadCounter {
public:
ThreadCounter() {
thread_counter.fetch_add(1);
}
~ThreadCounter() {
thread_counter.fetch_sub(1);
}
};
/**
* Called once per thread. Sets up per-thread pointers to the shared global
* data structures, creates per-thread structures, then enters the alignment
* loop. The general flow of the alignment loop is:
*
* - If it's been a while and we're the master thread, report some alignment
* metrics
* - Get the next read/pair
* - Check if this read/pair is identical to the previous
* + If identical, check whether we can skip any or all alignment stages. If
* we can skip all stages, report the result immediately and move to next
* read/pair
* + If not identical, continue
* -
*/
//void multiseedSearchWorker::operator()() const {
static void multiseedSearchWorker(void *vp) {
//int tid = *((int*)vp);
thread_tracking_pair *p = (thread_tracking_pair*) vp;
int tid = p->tid;
assert(multiseed_ebwtFw != NULL);
assert(multiseedMms == 0 || multiseed_ebwtBw != NULL);
PatternSourceReadAheadFactory& readahead_factory = *multiseed_readahead_factory;
const Ebwt& ebwtFw = *multiseed_ebwtFw;
const Ebwt* ebwtBw = multiseed_ebwtBw;
const Scoring& sc = *multiseed_sc;
const BitPairReference& ref = *multiseed_refs;
AlnSink& msink = *multiseed_msink;
OutFileBuf* metricsOfb = multiseed_metricsOfb;
const size_t lowseeds_ncut = (lowseeds>0) ?
((lowseedsDivider!=0) ? ((msink.num_refnames() * lowseeds + (lowseedsDivider-1))/lowseedsDivider) // round up, avoid 0
: lowseeds
) :
std::numeric_limits<size_t>::max(); // never filter by size
{
#ifdef PER_THREAD_TIMING
uint64_t ncpu_changeovers = 0;
uint64_t nnuma_changeovers = 0;
int current_cpu = 0, current_node = 0;
get_cpu_and_node(current_cpu, current_node);
std::stringstream ss;
std::string msg;
ss << "thread: " << tid << " time: ";
msg = ss.str();
Timer timer(std::cout, msg.c_str());
#endif
// Sinks: these are so that we can print tables encoding counts for
// events of interest on a per-read, per-seed, per-join, or per-SW
// level. These in turn can be used to diagnose performance
// problems, or generally characterize performance.
//const BitPairReference& refs = *multiseed_refs;
// Thread-local cache for seed alignments
PtrWrap<AlignmentCache> scLocal;
if(!msNoCache) {
scLocal.init(new AlignmentCache(seedCacheLocalMB * 1024 * 1024, false));
}
AlignmentCache scCurrent(seedCacheCurrentMB * 1024 * 1024, false);
// Thread-local cache for current seed alignments
// Interfaces for alignment and seed caches
AlignmentCacheIface ca(
&scCurrent,
scLocal.get(),
msNoCache ? NULL : multiseed_ca);
// Instantiate an object for holding reporting-related parameters.
ReportingParams rp(
(allHits ? std::numeric_limits<THitInt>::max() : khits), // -k
mhits, // -m/-M
0, // penalty gap (not used now)
msample, // true -> -M was specified, otherwise assume -m
gReportDiscordant, // report discordang paired-end alignments?
gReportMixed); // report unpaired alignments for paired reads?
// Instantiate a mapping quality calculator
unique_ptr<Mapq> bmapq(new_mapq(mapqv, scoreMin, sc));
// Make a per-thread wrapper for the global MHitSink object.
AlnSinkWrap msinkwrap(
msink, // global sink
rp, // reporting parameters
*bmapq, // MAPQ calculator
(size_t)tid); // thread id
// Write dynamic-programming problem descriptions here
ofstream *dpLog = NULL, *dpLogOpp = NULL;
if(!logDps.empty()) {
dpLog = new ofstream(logDps.c_str(), ofstream::out);
dpLog->sync_with_stdio(false);
}
if(!logDpsOpp.empty()) {
dpLogOpp = new ofstream(logDpsOpp.c_str(), ofstream::out);
dpLogOpp->sync_with_stdio(false);
}
SeedAligner al;
SwDriver sd(exactCacheCurrentMB * 1024 * 1024);
SwAligner sw(dpLog), osw(dpLogOpp);
SeedResults shs[2];
OuterLoopMetrics olm;
SeedSearchMetrics sdm;
WalkMetrics wlm;
SwMetrics swmSeed, swmMate;
ReportingMetrics rpm;
RandomSource rnd, rndArb;
SSEMetrics sseU8ExtendMet;
SSEMetrics sseU8MateMet;
SSEMetrics sseI16ExtendMet;
SSEMetrics sseI16MateMet;
uint64_t nbtfiltst = 0; // TODO: find a new home for these
uint64_t nbtfiltsc = 0; // TODO: find a new home for these
uint64_t nbtfiltdo = 0; // TODO: find a new home for these
ASSERT_ONLY(BTDnaString tmp);
int pepolFlag;
if(gMate1fw && gMate2fw) {
pepolFlag = PE_POLICY_FF;
} else if(gMate1fw && !gMate2fw) {
pepolFlag = PE_POLICY_FR;
} else if(!gMate1fw && gMate2fw) {
pepolFlag = PE_POLICY_RF;
} else {
pepolFlag = PE_POLICY_RR;
}
assert_geq(gMaxInsert, gMinInsert);
assert_geq(gMinInsert, 0);
PairedEndPolicy pepol(
pepolFlag,
gMaxInsert,
gMinInsert,
localAlign,
gFlippedMatesOK,
gDovetailMatesOK,
gContainMatesOK,
gOlapMatesOK,
gExpandToFrag);
PerfMetrics metricsPt; // per-thread metrics object; for read-level metrics
BTString nametmp;
EList<Seed> seeds1, seeds2;
EList<Seed> *seeds[2] = { &seeds1, &seeds2 };
PerReadMetrics prm;
// Used by thread with threadid == 1 to measure time elapsed
time_t iTime = time(0);
// Keep track of whether last search was exhaustive for mates 1 and 2
bool exhaustive[2] = { false, false };
// Keep track of whether mates 1/2 were filtered out last time through
bool filt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out due Ns last time
bool nfilt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out due to not having
// enough characters to rise about the score threshold.
bool scfilt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out due to not having
// more characters than the number of mismatches permitted in a seed.
bool lenfilt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out by upstream qc
bool qcfilt[2] = { true, true };
rndArb.init((uint32_t)time(0));
int mergei = 0;
int mergeival = 16;
bool done = false;
while(!done) {
PatternSourceReadAhead psrah(readahead_factory);
PatternSourcePerThread* const ps = psrah.ptr();
bool firstPS = true;
do {
pair<bool, bool> ret = firstPS ?
psrah.readResult() : // nextReadPair was already called in the psrah constructor
ps->nextReadPair();
firstPS = false;
bool success = ret.first;
done = ret.second;
if(!success && done) {
break;
} else if(!success) {
continue;
}
TReadId rdid = ps->read_a().rdid;
bool sample = true;
if(arbitraryRandom) {
ps->read_a().seed = rndArb.nextU32();
ps->read_b().seed = rndArb.nextU32();
}
if(sampleFrac < 1.0f) {
rnd.init(ROTL(ps->read_a().seed, 2));
sample = rnd.nextFloat() < sampleFrac;
}
if(rdid >= skipReads && rdid < qUpto && sample) {
// Align this read/pair
bool retry = true;
//
// Check if there is metrics reporting for us to do.
//
if(metricsIval > 0 &&
(metricsOfb != NULL || metricsStderr) &&
!metricsPerRead &&
++mergei == mergeival)
{
// Do a periodic merge. Update global metrics, in a
// synchronized manner if needed.
MERGE_METRICS(metrics);
mergei = 0;
// Check if a progress message should be printed
if(tid == 0) {
// Only thread 1 prints progress messages
time_t curTime = time(0);
if(curTime - iTime >= metricsIval) {
metrics.reportInterval(metricsOfb, metricsStderr, false, NULL);
iTime = curTime;
}
}
}
prm.reset(); // per-read metrics
prm.doFmString = false;
if(sam_print_xt) {
gettimeofday(&prm.tv_beg, &prm.tz_beg);
}
#ifdef PER_THREAD_TIMING
int cpu = 0, node = 0;
get_cpu_and_node(cpu, node);
if(cpu != current_cpu) {
ncpu_changeovers++;
current_cpu = cpu;
}
if(node != current_node) {
nnuma_changeovers++;
current_node = node;
}
#endif
// Try to align this read
while(retry) {
retry = false;
ca.nextRead(); // clear the cache
olm.reads++;
assert(!ca.aligning());
bool paired = !ps->read_b().empty();
const size_t rdlen1 = ps->read_a().length();
const size_t rdlen2 = paired ? ps->read_b().length() : 0;
olm.bases += (rdlen1 + rdlen2);
msinkwrap.nextRead(
&ps->read_a(),
paired ? &ps->read_b() : NULL,
rdid,
sc.qualitiesMatter());
assert(msinkwrap.inited());
size_t rdlens[2] = { rdlen1, rdlen2 };
size_t rdrows[2] = { rdlen1, rdlen2 };
// Calculate the minimum valid score threshold for the read
TAlScore minsc[2];
minsc[0] = minsc[1] = std::numeric_limits<TAlScore>::max();
if(bwaSwLike) {
// From BWA-SW manual: "Given an l-long query, the
// threshold for a hit to be retained is
// a*max{T,c*log(l)}." We try to recreate that here.
float a = (float)sc.match(30);
float T = bwaSwLikeT, c = bwaSwLikeC;
minsc[0] = (TAlScore)max<float>(a*T, a*c*log(rdlens[0]));
if(paired) {
minsc[1] = (TAlScore)max<float>(a*T, a*c*log(rdlens[1]));
}
} else {
minsc[0] = scoreMin.f<TAlScore>(rdlens[0]);
if(paired) minsc[1] = scoreMin.f<TAlScore>(rdlens[1]);
if(localAlign) {
if(minsc[0] < 0) {
if(!gQuiet) printLocalScoreMsg(*ps, paired, true);
minsc[0] = 0;
}
if(paired && minsc[1] < 0) {
if(!gQuiet) printLocalScoreMsg(*ps, paired, false);
minsc[1] = 0;
}
} else {
if(minsc[0] > 0) {
if(!gQuiet) printEEScoreMsg(*ps, paired, true);
minsc[0] = 0;
}
if(paired && minsc[1] > 0) {
if(!gQuiet) printEEScoreMsg(*ps, paired, false);
minsc[1] = 0;
}
}
}
// N filter; does the read have too many Ns?
size_t readns[2] = {0, 0};
sc.nFilterPair(
&ps->read_a().patFw,
paired ? &ps->read_b().patFw : NULL,
readns[0],
readns[1],
nfilt[0],
nfilt[1]);
// Score filter; does the read enough character to rise above
// the score threshold?
scfilt[0] = sc.scoreFilter(minsc[0], rdlens[0]);
scfilt[1] = sc.scoreFilter(minsc[1], rdlens[1]);
lenfilt[0] = lenfilt[1] = true;
if(rdlens[0] <= (size_t)multiseedMms || rdlens[0] < 2) {
if(!gQuiet) printMmsSkipMsg(*ps, paired, true, multiseedMms);
lenfilt[0] = false;
}
if((rdlens[1] <= (size_t)multiseedMms || rdlens[1] < 2) && paired) {
if(!gQuiet) printMmsSkipMsg(*ps, paired, false, multiseedMms);
lenfilt[1] = false;
}
if(rdlens[0] < 2) {
if(!gQuiet) printLenSkipMsg(*ps, paired, true);
lenfilt[0] = false;
}
if(rdlens[1] < 2 && paired) {
if(!gQuiet) printLenSkipMsg(*ps, paired, false);
lenfilt[1] = false;
}
qcfilt[0] = qcfilt[1] = true;
if(qcFilter) {
qcfilt[0] = (ps->read_a().filter != '0');
qcfilt[1] = (ps->read_b().filter != '0');
}
filt[0] = (nfilt[0] && scfilt[0] && lenfilt[0] && qcfilt[0]);
filt[1] = (nfilt[1] && scfilt[1] && lenfilt[1] && qcfilt[1]);
prm.nFilt += (filt[0] ? 0 : 1) + (filt[1] ? 0 : 1);
Read* rds[2] = { &ps->read_a(), &ps->read_b() };
// For each mate...
assert(msinkwrap.empty());
sd.nextRead(paired, rdrows[0], rdrows[1]); // SwDriver
size_t minedfw[2] = { 0, 0 };
size_t minedrc[2] = { 0, 0 };
// Calcualte nofw / no rc
bool nofw[2] = { false, false };
bool norc[2] = { false, false };
nofw[0] = paired ? (gMate1fw ? gNofw : gNorc) : gNofw;
norc[0] = paired ? (gMate1fw ? gNorc : gNofw) : gNorc;
nofw[1] = paired ? (gMate2fw ? gNofw : gNorc) : gNofw;
norc[1] = paired ? (gMate2fw ? gNorc : gNofw) : gNorc;
// Calculate nceil
int nceil[2] = { 0, 0 };
nceil[0] = nCeil.f<int>((double)rdlens[0]);
nceil[0] = min(nceil[0], (int)rdlens[0]);
if(paired) {
nceil[1] = nCeil.f<int>((double)rdlens[1]);
nceil[1] = min(nceil[1], (int)rdlens[1]);
}
exhaustive[0] = exhaustive[1] = false;
size_t matemap[2] = { 0, 1 };
bool pairPostFilt = filt[0] && filt[1];
if(pairPostFilt) {
rnd.init(ps->read_a().seed ^ ps->read_b().seed);
} else {
rnd.init(ps->read_a().seed);
}
// Calculate interval length for both mates
int interval[2] = { 0, 0 };
for(size_t mate = 0; mate < (paired ? 2:1); mate++) {
interval[mate] = msIval.f<int>((double)rdlens[mate]);
if(filt[0] && filt[1]) {
// Boost interval length by 20% for paired-end reads
interval[mate] = (int)(interval[mate] * 1.2 + 0.5);
}
interval[mate] = max(interval[mate], 1);
}
// Calculate streak length
size_t streak[2] = { maxDpStreak, maxDpStreak };
size_t mtStreak[2] = { maxMateStreak, maxMateStreak };
size_t mxDp[2] = { maxDp, maxDp };
size_t mxUg[2] = { maxUg, maxUg };
size_t mxIter[2] = { maxIters, maxIters };
if(allHits) {
streak[0] = streak[1] = std::numeric_limits<size_t>::max();
mtStreak[0] = mtStreak[1] = std::numeric_limits<size_t>::max();
mxDp[0] = mxDp[1] = std::numeric_limits<size_t>::max();
mxUg[0] = mxUg[1] = std::numeric_limits<size_t>::max();
mxIter[0] = mxIter[1] = std::numeric_limits<size_t>::max();
} else if(khits > 1) {
for(size_t mate = 0; mate < 2; mate++) {
streak[mate] += (khits-1) * maxStreakIncr;
mtStreak[mate] += (khits-1) * maxStreakIncr;
mxDp[mate] += (khits-1) * maxItersIncr;
mxUg[mate] += (khits-1) * maxItersIncr;
mxIter[mate] += (khits-1) * maxItersIncr;
}
}
if(filt[0] && filt[1]) {
streak[0] = (size_t)ceil((double)streak[0] / 2.0);
streak[1] = (size_t)ceil((double)streak[1] / 2.0);
assert_gt(streak[1], 0);
}
prm.maxDPFails = streak[0];
assert_gt(streak[0], 0);
// Calculate # seed rounds for each mate
size_t nrounds[2] = { nSeedRounds, nSeedRounds };
if(filt[0] && filt[1]) {
nrounds[0] = (size_t)ceil((double)nrounds[0] / 2.0);
nrounds[1] = (size_t)ceil((double)nrounds[1] / 2.0);
assert_gt(nrounds[1], 0);
}
assert_gt(nrounds[0], 0);
// Increment counters according to what got filtered
for(size_t mate = 0; mate < (paired ? 2:1); mate++) {
if(!filt[mate]) {
// Mate was rejected by N filter
olm.freads++; // reads filtered out
olm.fbases += rdlens[mate]; // bases filtered out
} else {
shs[mate].clear();
shs[mate].nextRead(mate == 0 ? ps->read_a() : ps->read_b());
assert(shs[mate].empty());
olm.ureads++; // reads passing filter
olm.ubases += rdlens[mate]; // bases passing filter
}
}
size_t eePeEeltLimit = std::numeric_limits<size_t>::max();
// Whether we're done with mate1 / mate2
bool done[2] = { !filt[0], !filt[1] };
size_t nelt[2] = {0, 0};
// Find end-to-end exact alignments for each read
if(doExactUpFront) {
for(size_t matei = 0; matei < (paired ? 2:1); matei++) {
size_t mate = matemap[matei];
if(!filt[mate] || done[mate] || msinkwrap.state().doneWithMate(mate == 0)) {
continue;
}
swmSeed.exatts++;
nelt[mate] = al.exactSweep(
ebwtFw, // index
*rds[mate], // read
sc, // scoring scheme
nofw[mate], // nofw?
norc[mate], // norc?
2, // max # edits we care about
minedfw[mate], // minimum # edits for fw mate
minedrc[mate], // minimum # edits for rc mate
true, // report 0mm hits
shs[mate], // put end-to-end results here
sdm); // metrics
size_t bestmin = min(minedfw[mate], minedrc[mate]);
if(bestmin == 0) {
sdm.bestmin0++;
} else if(bestmin == 1) {
sdm.bestmin1++;
} else {
assert_eq(2, bestmin);
sdm.bestmin2++;
}
}
matemap[0] = 0; matemap[1] = 1;
if(nelt[0] > 0 && nelt[1] > 0 && nelt[0] > nelt[1]) {
// Do the mate with fewer exact hits first
// TODO: Consider mates & orientations separately?
matemap[0] = 1; matemap[1] = 0;
}
for(size_t matei = 0; matei < (seedSumm ? 0:2); matei++) {
size_t mate = matemap[matei];
if(nelt[mate] == 0 || nelt[mate] > eePeEeltLimit) {
shs[mate].clearExactE2eHits();
continue;
}
if(msinkwrap.state().doneWithMate(mate == 0)) {
shs[mate].clearExactE2eHits();
done[mate] = true;
continue;
}
assert(filt[mate]);
assert(matei == 0 || paired);
assert(!msinkwrap.maxed());
assert(msinkwrap.repOk());
int ret = 0;
if(paired) {
// Paired-end dynamic programming driver
ret = sd.extendSeedsPaired(
*rds[mate], // mate to align as anchor
*rds[mate ^ 1], // mate to align as opp.
mate == 0, // anchor is mate 1?
!filt[mate ^ 1],// opposite mate filtered out?
shs[mate], // seed hits for anchor
ebwtFw, // bowtie index
ebwtBw, // rev bowtie index
ref, // packed reference strings
sw, // dyn prog aligner, anchor
osw, // dyn prog aligner, opposite
sc, // scoring scheme
pepol, // paired-end policy
-1, // # mms allowed in a seed
0, // length of a seed
0, // interval between seeds
minsc[mate], // min score for anchor
minsc[mate^1], // min score for opp.
nceil[mate], // N ceil for anchor
nceil[mate^1], // N ceil for opp.
nofw[mate], // don't align forward read
norc[mate], // don't align revcomp read
maxhalf, // max width on one DP side
doUngapped, // do ungapped alignment
mxIter[mate], // max extend loop iters
mxUg[mate], // max # ungapped extends
mxDp[mate], // max # DPs
streak[mate], // stop after streak of this many end-to-end fails
streak[mate], // stop after streak of this many ungap fails
streak[mate], // stop after streak of this many dp fails
mtStreak[mate], // max mate fails per seed range
doExtend, // extend seed hits
enable8, // use 8-bit SSE where possible
cminlen, // checkpoint if read is longer
cpow2, // checkpointer interval, log2
doTri, // triangular mini-fills?
tighten, // -M score tightening mode
deterministicSeeds, // Should I disable the random seed selection?
ca, // seed alignment cache
rnd, // pseudo-random source
wlm, // group walk left metrics
swmSeed, // DP metrics, seed extend
swmMate, // DP metrics, mate finding
prm, // per-read metrics
&msinkwrap, // for organizing hits
true, // seek mate immediately
true, // report hits once found
gReportDiscordant,// look for discordant alns?
gReportMixed, // look for unpaired alns?
exhaustive[mate]);
// Might be done, but just with this mate
} else {
// Unpaired dynamic programming driver
ret = sd.extendSeeds(
*rds[mate], // read
mate == 0, // mate #1?
shs[mate], // seed hits
ebwtFw, // bowtie index
ebwtBw, // rev bowtie index
ref, // packed reference strings
sw, // dynamic prog aligner
sc, // scoring scheme
-1, // # mms allowed in a seed
0, // length of a seed
0, // interval between seeds
minsc[mate], // minimum score for valid
nceil[mate], // N ceil for anchor
maxhalf, // max width on one DP side
doUngapped, // do ungapped alignment
mxIter[mate], // max extend loop iters
mxUg[mate], // max # ungapped extends
mxDp[mate], // max # DPs
streak[mate], // stop after streak of this many end-to-end fails
streak[mate], // stop after streak of this many ungap fails
doExtend, // extend seed hits
enable8, // use 8-bit SSE where possible
cminlen, // checkpoint if read is longer
cpow2, // checkpointer interval, log2
doTri, // triangular mini-fills
tighten, // -M score tightening mode
deterministicSeeds, // Should I disable the random seed selection?
ca, // seed alignment cache
rnd, // pseudo-random source
wlm, // group walk left metrics
swmSeed, // DP metrics, seed extend
prm, // per-read metrics
&msinkwrap, // for organizing hits
true, // report hits once found
exhaustive[mate]);
}
assert_gt(ret, 0);
MERGE_SW(sw);
MERGE_SW(osw);
// Clear out the exact hits so that we don't try to
// extend them again later!
shs[mate].clearExactE2eHits();
if(ret == EXTEND_EXHAUSTED_CANDIDATES) {
// Not done yet
} else if(ret == EXTEND_POLICY_FULFILLED) {
// Policy is satisfied for this mate at least
if(msinkwrap.state().doneWithMate(mate == 0)) {
done[mate] = true;
}
if(msinkwrap.state().doneWithMate(mate == 1)) {
done[mate^1] = true;
}
} else if(ret == EXTEND_PERFECT_SCORE) {
// We exhausted this mode at least
done[mate] = true;
} else if(ret == EXTEND_EXCEEDED_HARD_LIMIT) {
// We exceeded a per-read limit
done[mate] = true;
} else if(ret == EXTEND_EXCEEDED_SOFT_LIMIT) {
// Not done yet
} else {
//
cerr << "Bad return value: " << ret << endl;
throw 1;
}
if(!done[mate]) {
TAlScore perfectScore = sc.perfectScore(rdlens[mate]);
if(!done[mate] && minsc[mate] == perfectScore) {
done[mate] = true;
}
}
}
}
// 1-mismatch
if(do1mmUpFront && !seedSumm) {
for(size_t matei = 0; matei < (paired ? 2:1); matei++) {
size_t mate = matemap[matei];
if(!filt[mate] || done[mate] || nelt[mate] > eePeEeltLimit) {
// Done with this mate
shs[mate].clear1mmE2eHits();
nelt[mate] = 0;
continue;
}
nelt[mate] = 0;
assert(!msinkwrap.maxed());
assert(msinkwrap.repOk());
//rnd.init(ROTL(rds[mate]->seed, 10));
assert(shs[mate].empty());
assert(shs[mate].repOk(&ca.current()));
bool yfw = minedfw[mate] <= 1 && !nofw[mate];
bool yrc = minedrc[mate] <= 1 && !norc[mate];
if(yfw || yrc) {
// Clear out the exact hits
swmSeed.mm1atts++;
al.oneMmSearch(
&ebwtFw, // BWT index
ebwtBw, // BWT' index
*rds[mate], // read
sc, // scoring scheme
minsc[mate], // minimum score
!yfw, // don't align forward read
!yrc, // don't align revcomp read
localAlign, // must be legal local alns?
false, // do exact match
true, // do 1mm
shs[mate], // seed hits (hits installed here)
sdm); // metrics
nelt[mate] = shs[mate].num1mmE2eHits();
}
}
// Possibly reorder the mates
matemap[0] = 0; matemap[1] = 1;
if(nelt[0] > 0 && nelt[1] > 0 && nelt[0] > nelt[1]) {
// Do the mate with fewer exact hits first
// TODO: Consider mates & orientations separately?
matemap[0] = 1; matemap[1] = 0;
}
for(size_t matei = 0; matei < (seedSumm ? 0:2); matei++) {
size_t mate = matemap[matei];
if(nelt[mate] == 0 || nelt[mate] > eePeEeltLimit) {
continue;
}
if(msinkwrap.state().doneWithMate(mate == 0)) {
done[mate] = true;
continue;
}
int ret = 0;
if(paired) {
// Paired-end dynamic programming driver
ret = sd.extendSeedsPaired(
*rds[mate], // mate to align as anchor
*rds[mate ^ 1], // mate to align as opp.
mate == 0, // anchor is mate 1?
!filt[mate ^ 1],// opposite mate filtered out?
shs[mate], // seed hits for anchor
ebwtFw, // bowtie index
ebwtBw, // rev bowtie index
ref, // packed reference strings
sw, // dyn prog aligner, anchor
osw, // dyn prog aligner, opposite
sc, // scoring scheme
pepol, // paired-end policy
-1, // # mms allowed in a seed
0, // length of a seed
0, // interval between seeds
minsc[mate], // min score for anchor
minsc[mate^1], // min score for opp.
nceil[mate], // N ceil for anchor
nceil[mate^1], // N ceil for opp.
nofw[mate], // don't align forward read
norc[mate], // don't align revcomp read
maxhalf, // max width on one DP side
doUngapped, // do ungapped alignment
mxIter[mate], // max extend loop iters
mxUg[mate], // max # ungapped extends
mxDp[mate], // max # DPs
streak[mate], // stop after streak of this many end-to-end fails
streak[mate], // stop after streak of this many ungap fails
streak[mate], // stop after streak of this many dp fails
mtStreak[mate], // max mate fails per seed range
doExtend, // extend seed hits
enable8, // use 8-bit SSE where possible
cminlen, // checkpoint if read is longer
cpow2, // checkpointer interval, log2
doTri, // triangular mini-fills?
tighten, // -M score tightening mode
deterministicSeeds, // Should I disable the random seed selection?
ca, // seed alignment cache
rnd, // pseudo-random source
wlm, // group walk left metrics
swmSeed, // DP metrics, seed extend
swmMate, // DP metrics, mate finding
prm, // per-read metrics
&msinkwrap, // for organizing hits
true, // seek mate immediately
true, // report hits once found
gReportDiscordant,// look for discordant alns?
gReportMixed, // look for unpaired alns?
exhaustive[mate]);
// Might be done, but just with this mate
} else {
// Unpaired dynamic programming driver
ret = sd.extendSeeds(
*rds[mate], // read
mate == 0, // mate #1?
shs[mate], // seed hits
ebwtFw, // bowtie index
ebwtBw, // rev bowtie index
ref, // packed reference strings
sw, // dynamic prog aligner
sc, // scoring scheme
-1, // # mms allowed in a seed
0, // length of a seed
0, // interval between seeds
minsc[mate], // minimum score for valid
nceil[mate], // N ceil for anchor
maxhalf, // max width on one DP side
doUngapped, // do ungapped alignment
mxIter[mate], // max extend loop iters
mxUg[mate], // max # ungapped extends
mxDp[mate], // max # DPs
streak[mate], // stop after streak of this many end-to-end fails
streak[mate], // stop after streak of this many ungap fails
doExtend, // extend seed hits
enable8, // use 8-bit SSE where possible
cminlen, // checkpoint if read is longer
cpow2, // checkpointer interval, log2
doTri, // triangular mini-fills?
tighten, // -M score tightening mode
deterministicSeeds, // Should I disable the random seed selection?
ca, // seed alignment cache
rnd, // pseudo-random source
wlm, // group walk left metrics
swmSeed, // DP metrics, seed extend
prm, // per-read metrics
&msinkwrap, // for organizing hits
true, // report hits once found
exhaustive[mate]);
}
assert_gt(ret, 0);
MERGE_SW(sw);
MERGE_SW(osw);
// Clear out the 1mm hits so that we don't try to
// extend them again later!
shs[mate].clear1mmE2eHits();
if(ret == EXTEND_EXHAUSTED_CANDIDATES) {
// Not done yet
} else if(ret == EXTEND_POLICY_FULFILLED) {
// Policy is satisfied for this mate at least
if(msinkwrap.state().doneWithMate(mate == 0)) {
done[mate] = true;
}
if(msinkwrap.state().doneWithMate(mate == 1)) {
done[mate^1] = true;
}
} else if(ret == EXTEND_PERFECT_SCORE) {
// We exhausted this mode at least
done[mate] = true;
} else if(ret == EXTEND_EXCEEDED_HARD_LIMIT) {
// We exceeded a per-read limit
done[mate] = true;
} else if(ret == EXTEND_EXCEEDED_SOFT_LIMIT) {
// Not done yet
} else {
//
cerr << "Bad return value: " << ret << endl;
throw 1;
}
if(!done[mate]) {
TAlScore perfectScore = sc.perfectScore(rdlens[mate]);
if(!done[mate] && minsc[mate] == perfectScore) {
done[mate] = true;
}
}
}
}
int seedlens[2] = { multiseedLen, multiseedLen };
nrounds[0] = min<size_t>(nrounds[0], interval[0]);
nrounds[1] = min<size_t>(nrounds[1], interval[1]);
Constraint gc = Constraint::penaltyFuncBased(scoreMin);
size_t seedsTried = 0;
size_t seedsTriedMS[] = {0, 0, 0, 0};
size_t nUniqueSeeds = 0, nRepeatSeeds = 0, seedHitTot = 0;
size_t nUniqueSeedsMS[] = {0, 0, 0, 0};
size_t nRepeatSeedsMS[] = {0, 0, 0, 0};
size_t seedHitTotMS[] = {0, 0, 0, 0};
for(size_t roundi = 0; roundi < nSeedRounds; roundi++) {
ca.nextRead(); // Clear cache in preparation for new search
shs[0].clearSeeds();
shs[1].clearSeeds();
assert(shs[0].empty());
assert(shs[1].empty());
assert(shs[0].repOk(&ca.current()));
assert(shs[1].repOk(&ca.current()));
//if(roundi > 0) {
// if(seedlens[0] > 8) seedlens[0]--;
// if(seedlens[1] > 8) seedlens[1]--;
//}
for(size_t matei = 0; matei < (paired ? 2:1); matei++) {
size_t mate = matemap[matei];
if(done[mate] || msinkwrap.state().doneWithMate(mate == 0)) {
// Done with this mate
done[mate] = true;
continue;
}
if(roundi >= nrounds[mate]) {
// Not doing this round for this mate
continue;
}
// Figure out the seed offset
if(interval[mate] <= (int)roundi) {
// Can't do this round, seeds already packed as
// tight as possible
continue;
}
size_t offset = (interval[mate] * roundi) / nrounds[mate];
assert(roundi == 0 || offset > 0);
assert(!msinkwrap.maxed());
assert(msinkwrap.repOk());
//rnd.init(ROTL(rds[mate]->seed, 10));
assert(shs[mate].repOk(&ca.current()));
swmSeed.sdatts++;
// Set up seeds
seeds[mate]->clear();
Seed::mmSeeds(
multiseedMms, // max # mms per seed
seedlens[mate], // length of a multiseed seed
*seeds[mate], // seeds
gc); // global constraint
// Check whether the offset would drive the first seed
// off the end
if(offset > 0 && (*seeds[mate])[0].len + offset > rds[mate]->length()) {
continue;
}
// Instantiate the seeds
std::pair<int, int> instFw, instRc;
std::pair<int, int> inst = al.instantiateSeeds(
*seeds[mate], // search seeds
offset, // offset to begin extracting
interval[mate], // interval between seeds
*rds[mate], // read to align
sc, // scoring scheme
nofw[mate], // don't align forward read
norc[mate], // don't align revcomp read
ca, // holds some seed hits from previous reads
shs[mate], // holds all the seed hits
sdm, // metrics
instFw,
instRc);
assert(shs[mate].repOk(&ca.current()));
if(inst.first + inst.second == 0) {
// No seed hits! Done with this mate.
assert(shs[mate].empty());
done[mate] = true;
break;
}
seedsTried += (inst.first + inst.second);
seedsTriedMS[mate * 2 + 0] = instFw.first + instFw.second;
seedsTriedMS[mate * 2 + 1] = instRc.first + instRc.second;
// Align seeds
al.searchAllSeeds(
*seeds[mate], // search seeds
&ebwtFw, // BWT index
ebwtBw, // BWT' index
*rds[mate], // read
sc, // scoring scheme
lowseeds_ncut, // cut no seed quality
ca, // alignment cache
shs[mate], // store seed hits here
sdm, // metrics
prm); // per-read metrics
assert(shs[mate].repOk(&ca.current()));
if(shs[mate].empty()) {
// No seed alignments! Done with this mate.
done[mate] = true;
break;
}
}
// shs contain what we need to know to update our seed
// summaries for this seeding
for(size_t mate = 0; mate < 2; mate++) {
if(!shs[mate].empty()) {
nUniqueSeeds += shs[mate].numUniqueSeeds();
nUniqueSeedsMS[mate * 2 + 0] += shs[mate].numUniqueSeedsStrand(true);
nUniqueSeedsMS[mate * 2 + 1] += shs[mate].numUniqueSeedsStrand(false);
nRepeatSeeds += shs[mate].numRepeatSeeds();
nRepeatSeedsMS[mate * 2 + 0] += shs[mate].numRepeatSeedsStrand(true);
nRepeatSeedsMS[mate * 2 + 1] += shs[mate].numRepeatSeedsStrand(false);
seedHitTot += shs[mate].numElts();
seedHitTotMS[mate * 2 + 0] += shs[mate].numEltsFw();
seedHitTotMS[mate * 2 + 1] += shs[mate].numEltsRc();
}
}
double uniqFactor[2] = { 0.0f, 0.0f };
for(size_t i = 0; i < 2; i++) {
if(!shs[i].empty()) {
swmSeed.sdsucc++;
uniqFactor[i] = shs[i].uniquenessFactor();
}
}
// Possibly reorder the mates
matemap[0] = 0; matemap[1] = 1;
if(!shs[0].empty() && !shs[1].empty() && uniqFactor[1] > uniqFactor[0]) {
// Do the mate with fewer exact hits first
// TODO: Consider mates & orientations separately?
matemap[0] = 1; matemap[1] = 0;
}
for(size_t matei = 0; matei < (paired ? 2:1); matei++) {
size_t mate = matemap[matei];
if(done[mate] || msinkwrap.state().doneWithMate(mate == 0)) {
// Done with this mate
done[mate] = true;
continue;
}
assert(!msinkwrap.maxed());
assert(msinkwrap.repOk());
//rnd.init(ROTL(rds[mate]->seed, 10));
assert(shs[mate].repOk(&ca.current()));
if(!seedSumm) {
// If there aren't any seed hits...
if(shs[mate].empty()) {
continue; // on to the next mate
}
// Sort seed hits into ranks
shs[mate].rankSeedHits(rnd, msinkwrap.allHits());
int ret = 0;
if(paired) {
// Paired-end dynamic programming driver
ret = sd.extendSeedsPaired(
*rds[mate], // mate to align as anchor
*rds[mate ^ 1], // mate to align as opp.
mate == 0, // anchor is mate 1?
!filt[mate ^ 1],// opposite mate filtered out?
shs[mate], // seed hits for anchor
ebwtFw, // bowtie index
ebwtBw, // rev bowtie index
ref, // packed reference strings
sw, // dyn prog aligner, anchor
osw, // dyn prog aligner, opposite
sc, // scoring scheme
pepol, // paired-end policy
multiseedMms, // # mms allowed in a seed
seedlens[mate], // length of a seed
interval[mate], // interval between seeds
minsc[mate], // min score for anchor
minsc[mate^1], // min score for opp.
nceil[mate], // N ceil for anchor
nceil[mate^1], // N ceil for opp.
nofw[mate], // don't align forward read
norc[mate], // don't align revcomp read
maxhalf, // max width on one DP side
doUngapped, // do ungapped alignment
mxIter[mate], // max extend loop iters
mxUg[mate], // max # ungapped extends
mxDp[mate], // max # DPs
streak[mate], // stop after streak of this many end-to-end fails
streak[mate], // stop after streak of this many ungap fails
streak[mate], // stop after streak of this many dp fails
mtStreak[mate], // max mate fails per seed range
doExtend, // extend seed hits
enable8, // use 8-bit SSE where possible
cminlen, // checkpoint if read is longer
cpow2, // checkpointer interval, log2
doTri, // triangular mini-fills?
tighten, // -M score tightening mode
deterministicSeeds, // Should I disable the random seed selection?
ca, // seed alignment cache
rnd, // pseudo-random source
wlm, // group walk left metrics
swmSeed, // DP metrics, seed extend
swmMate, // DP metrics, mate finding
prm, // per-read metrics
&msinkwrap, // for organizing hits
true, // seek mate immediately
true, // report hits once found
gReportDiscordant,// look for discordant alns?
gReportMixed, // look for unpaired alns?
exhaustive[mate]);
// Might be done, but just with this mate
} else {
// Unpaired dynamic programming driver
ret = sd.extendSeeds(
*rds[mate], // read
mate == 0, // mate #1?
shs[mate], // seed hits
ebwtFw, // bowtie index
ebwtBw, // rev bowtie index
ref, // packed reference strings
sw, // dynamic prog aligner
sc, // scoring scheme
multiseedMms, // # mms allowed in a seed
seedlens[mate], // length of a seed
interval[mate], // interval between seeds
minsc[mate], // minimum score for valid
nceil[mate], // N ceil for anchor
maxhalf, // max width on one DP side
doUngapped, // do ungapped alignment
mxIter[mate], // max extend loop iters
mxUg[mate], // max # ungapped extends
mxDp[mate], // max # DPs
streak[mate], // stop after streak of this many end-to-end fails
streak[mate], // stop after streak of this many ungap fails
doExtend, // extend seed hits
enable8, // use 8-bit SSE where possible
cminlen, // checkpoint if read is longer
cpow2, // checkpointer interval, log2
doTri, // triangular mini-fills?
tighten, // -M score tightening mode
deterministicSeeds, // Should I disable the random seed selection?
ca, // seed alignment cache
rnd, // pseudo-random source
wlm, // group walk left metrics
swmSeed, // DP metrics, seed extend
prm, // per-read metrics
&msinkwrap, // for organizing hits
true, // report hits once found
exhaustive[mate]);
}
assert_gt(ret, 0);
MERGE_SW(sw);
MERGE_SW(osw);
if(ret == EXTEND_EXHAUSTED_CANDIDATES) {
// Not done yet
} else if(ret == EXTEND_POLICY_FULFILLED) {
// Policy is satisfied for this mate at least
if(msinkwrap.state().doneWithMate(mate == 0)) {
done[mate] = true;
}
if(msinkwrap.state().doneWithMate(mate == 1)) {
done[mate^1] = true;
}
} else if(ret == EXTEND_PERFECT_SCORE) {
// We exhausted this made at least
done[mate] = true;
} else if(ret == EXTEND_EXCEEDED_HARD_LIMIT) {
// We exceeded a per-read limit
done[mate] = true;
} else if(ret == EXTEND_EXCEEDED_SOFT_LIMIT) {
// Not done yet
} else {
//
cerr << "Bad return value: " << ret << endl;
throw 1;
}
} // if(!seedSumm)
} // for(size_t matei = 0; matei < 2; matei++)
// We don't necessarily have to continue investigating both
// mates. We continue on a mate only if its average
// interval length is high (> 1000)
for(size_t mate = 0; mate < 2; mate++) {
if(!done[mate] && shs[mate].averageHitsPerSeed() < seedBoostThresh) {
done[mate] = true;
}
}
} // end loop over reseeding rounds
if(seedsTried > 0) {
prm.seedPctUnique = (float)nUniqueSeeds / seedsTried;
prm.seedPctRep = (float)nRepeatSeeds / seedsTried;
prm.seedHitAvg = (float)seedHitTot / seedsTried;
} else {
prm.seedPctUnique = -1.0f;
prm.seedPctRep = -1.0f;
prm.seedHitAvg = -1.0f;
}
for(int i = 0; i < 4; i++) {
if(seedsTriedMS[i] > 0) {
prm.seedPctUniqueMS[i] = (float)nUniqueSeedsMS[i] / seedsTriedMS[i];
prm.seedPctRepMS[i] = (float)nRepeatSeedsMS[i] / seedsTriedMS[i];
prm.seedHitAvgMS[i] = (float)seedHitTotMS[i] / seedsTriedMS[i];
} else {
prm.seedPctUniqueMS[i] = -1.0f;
prm.seedPctRepMS[i] = -1.0f;
prm.seedHitAvgMS[i] = -1.0f;
}
}
size_t totnucs = 0;
for(size_t mate = 0; mate < (paired ? 2:1); mate++) {
if(filt[mate]) {
size_t len = rdlens[mate];
if(!nofw[mate] && !norc[mate]) {
len *= 2;
}
totnucs += len;
}
}
prm.seedsPerNuc = totnucs > 0 ? ((float)seedsTried / totnucs) : -1;
for(int i = 0; i < 4; i++) {
prm.seedsPerNucMS[i] = totnucs > 0 ? ((float)seedsTriedMS[i] / totnucs) : -1;
}
for(size_t i = 0; i < 2; i++) {
assert_leq(prm.nExIters, mxIter[i]);
assert_leq(prm.nExDps, mxDp[i]);
assert_leq(prm.nMateDps, mxDp[i]);
assert_leq(prm.nExUgs, mxUg[i]);
assert_leq(prm.nMateUgs, mxUg[i]);
assert_leq(prm.nDpFail, streak[i]);
assert_leq(prm.nUgFail, streak[i]);
assert_leq(prm.nEeFail, streak[i]);
}
// Commit and report paired-end/unpaired alignments
//uint32_t sd = rds[0]->seed ^ rds[1]->seed;
//rnd.init(ROTL(sd, 20));
msinkwrap.finishRead(
&shs[0], // seed results for mate 1
&shs[1], // seed results for mate 2
exhaustive[0], // exhausted seed hits for mate 1?
exhaustive[1], // exhausted seed hits for mate 2?
nfilt[0],
nfilt[1],
scfilt[0],
scfilt[1],
lenfilt[0],
lenfilt[1],
qcfilt[0],
qcfilt[1],
rnd, // pseudo-random generator
rpm, // reporting metrics
prm, // per-read metrics
sc, // scoring scheme
!seedSumm, // suppress seed summaries?
seedSumm, // suppress alignments?
scUnMapped, // Consider soft-clipped bases unmapped when calculating TLEN
xeq);
assert(!retry || msinkwrap.empty());
} // while(retry)
} // if(rdid >= skipReads && rdid < qUpto)
else if(rdid >= qUpto) {
done = true;
break;
}
if(metricsPerRead) {
MERGE_METRICS(metricsPt);
nametmp = ps->read_a().name;
metricsPt.reportInterval(
metricsOfb, metricsStderr, true, &nametmp);
metricsPt.reset();
}
} while (ps->nextReadPairReady()); // must read the whole cached buffer
} // while(true)
// One last metrics merge
MERGE_METRICS(metrics);
if(dpLog != NULL) dpLog->close();
if(dpLogOpp != NULL) dpLogOpp->close();
#ifdef PER_THREAD_TIMING
ss.str("");
ss.clear();
ss << "thread: " << tid << " cpu_changeovers: " << ncpu_changeovers << std::endl
<< "thread: " << tid << " node_changeovers: " << nnuma_changeovers << std::endl;
std::cout << ss.str();
#endif
}
p->done->fetch_add(1);
return;
}
//void multiseedSearchWorker_2p5::operator()() const {
static void multiseedSearchWorker_2p5(void *vp) {
//int tid = *((int*)vp);
thread_tracking_pair *p = (thread_tracking_pair*) vp;
int tid = p->tid;
assert(multiseed_ebwtFw != NULL);
assert(multiseedMms == 0 || multiseed_ebwtBw != NULL);
PatternSourceReadAheadFactory& readahead_factory = *multiseed_readahead_factory;
const Ebwt& ebwtFw = *multiseed_ebwtFw;
const Ebwt& ebwtBw = *multiseed_ebwtBw;
const Scoring& sc = *multiseed_sc;
const BitPairReference& ref = *multiseed_refs;
AlnSink& msink = *multiseed_msink;
OutFileBuf* metricsOfb = multiseed_metricsOfb;
// Sinks: these are so that we can print tables encoding counts for
// events of interest on a per-read, per-seed, per-join, or per-SW
// level. These in turn can be used to diagnose performance
// problems, or generally characterize performance.
ThreadCounter tc;
// Instantiate an object for holding reporting-related parameters.
ReportingParams rp(
(allHits ? std::numeric_limits<THitInt>::max() : khits), // -k
mhits, // -m/-M
0, // penalty gap (not used now)
msample, // true -> -M was specified, otherwise assume -m
gReportDiscordant, // report discordang paired-end alignments?
gReportMixed); // report unpaired alignments for paired reads?
// Instantiate a mapping quality calculator
unique_ptr<Mapq> bmapq(new_mapq(mapqv, scoreMin, sc));
// Make a per-thread wrapper for the global MHitSink object.
AlnSinkWrap msinkwrap(
msink, // global sink
rp, // reporting parameters
*bmapq, // MAPQ calculator
(size_t)tid); // thread id
OuterLoopMetrics olm;
SeedSearchMetrics sdm;
WalkMetrics wlm;
SwMetrics swmSeed, swmMate;
DescentMetrics descm;
ReportingMetrics rpm;
RandomSource rnd, rndArb;
SSEMetrics sseU8ExtendMet;
SSEMetrics sseU8MateMet;
SSEMetrics sseI16ExtendMet;
SSEMetrics sseI16MateMet;
uint64_t nbtfiltst = 0; // TODO: find a new home for these
uint64_t nbtfiltsc = 0; // TODO: find a new home for these
uint64_t nbtfiltdo = 0; // TODO: find a new home for these
ASSERT_ONLY(BTDnaString tmp);
int pepolFlag;
if(gMate1fw && gMate2fw) {
pepolFlag = PE_POLICY_FF;
} else if(gMate1fw && !gMate2fw) {
pepolFlag = PE_POLICY_FR;
} else if(!gMate1fw && gMate2fw) {
pepolFlag = PE_POLICY_RF;
} else {
pepolFlag = PE_POLICY_RR;
}
assert_geq(gMaxInsert, gMinInsert);
assert_geq(gMinInsert, 0);
PairedEndPolicy pepol(
pepolFlag,
gMaxInsert,
gMinInsert,
localAlign,
gFlippedMatesOK,
gDovetailMatesOK,
gContainMatesOK,
gOlapMatesOK,
gExpandToFrag);
AlignerDriver ald(
descConsExp, // exponent for interpolating maximum penalty
descPrioritizeRoots, // whether to select roots with scores and weights
msIval, // interval length, as function of read length
descLanding, // landing length
gVerbose, // verbose?
descentTotSz, // limit on total bytes of best-first search data
descentTotFmops); // limit on total number of FM index ops in BFS
PerfMetrics metricsPt; // per-thread metrics object; for read-level metrics
BTString nametmp;
PerReadMetrics prm;
// Used by thread with threadid == 1 to measure time elapsed
time_t iTime = time(0);
// Keep track of whether last search was exhaustive for mates 1 and 2
bool exhaustive[2] = { false, false };
// Keep track of whether mates 1/2 were filtered out last time through
bool filt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out due Ns last time
bool nfilt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out due to not having
// enough characters to rise about the score threshold.
bool scfilt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out due to not having
// more characters than the number of mismatches permitted in a seed.
bool lenfilt[2] = { true, true };
// Keep track of whether mates 1/2 were filtered out by upstream qc
bool qcfilt[2] = { true, true };
rndArb.init((uint32_t)time(0));
int mergei = 0;
int mergeival = 16;
while(true) {
PatternSourceReadAhead psrah(readahead_factory);
PatternSourcePerThread* const ps = psrah.ptr();
do {
pair<bool, bool> ret = ps->nextReadPair();
bool success = ret.first;
bool done = ret.second;
if(!success && done) {
break;
} else if(!success) {
continue;
}
TReadId rdid = ps->read_a().rdid;
bool sample = true;
if(arbitraryRandom) {
ps->read_a().seed = rndArb.nextU32();
ps->read_b().seed = rndArb.nextU32();
}
if(sampleFrac < 1.0f) {
rnd.init(ROTL(ps->read_a().seed, 2));
sample = rnd.nextFloat() < sampleFrac;
}
if(rdid >= skipReads && rdid < qUpto && sample) {
//
// Check if there is metrics reporting for us to do.
//
if(metricsIval > 0 &&
(metricsOfb != NULL || metricsStderr) &&
!metricsPerRead &&
++mergei == mergeival)
{
// Do a periodic merge. Update global metrics, in a
// synchronized manner if needed.
MERGE_METRICS(metrics);
mergei = 0;
// Check if a progress message should be printed
if(tid == 0) {
// Only thread 1 prints progress messages
time_t curTime = time(0);
if(curTime - iTime >= metricsIval) {
metrics.reportInterval(metricsOfb, metricsStderr, false, NULL);
iTime = curTime;
}
}
}
prm.reset(); // per-read metrics
prm.doFmString = sam_print_zm;
// If we're reporting how long each read takes, get the initial time
// measurement here
if(sam_print_xt) {
gettimeofday(&prm.tv_beg, &prm.tz_beg);
}
// Try to align this read
olm.reads++;
bool paired = !ps->read_b().empty();
const size_t rdlen1 = ps->read_a().length();
const size_t rdlen2 = paired ? ps->read_b().length() : 0;
olm.bases += (rdlen1 + rdlen2);
// Check if read is identical to previous read
rnd.init(ROTL(ps->read_a().seed, 5));
msinkwrap.nextRead(
&ps->read_a(),
paired ? &ps->read_b() : NULL,
rdid,
sc.qualitiesMatter());
assert(msinkwrap.inited());
size_t rdlens[2] = { rdlen1, rdlen2 };
// Calculate the minimum valid score threshold for the read
TAlScore minsc[2], maxpen[2];
minsc[0] = minsc[1] = std::numeric_limits<TAlScore>::max();
setupMinScores(*ps, paired, localAlign, sc, rdlens, minsc, maxpen);
// N filter; does the read have too many Ns?
size_t readns[2] = {0, 0};
sc.nFilterPair(
&ps->read_a().patFw,
paired ? &ps->read_b().patFw : NULL,
readns[0],
readns[1],
nfilt[0],
nfilt[1]);
// Score filter; does the read enough character to rise above
// the score threshold?
scfilt[0] = sc.scoreFilter(minsc[0], rdlens[0]);
scfilt[1] = sc.scoreFilter(minsc[1], rdlens[1]);
lenfilt[0] = lenfilt[1] = true;
if(rdlens[0] <= (size_t)multiseedMms || rdlens[0] < 2) {
if(!gQuiet) printMmsSkipMsg(*ps, paired, true, multiseedMms);
lenfilt[0] = false;
}
if((rdlens[1] <= (size_t)multiseedMms || rdlens[1] < 2) && paired) {
if(!gQuiet) printMmsSkipMsg(*ps, paired, false, multiseedMms);
lenfilt[1] = false;
}
if(rdlens[0] < 2) {
if(!gQuiet) printLenSkipMsg(*ps, paired, true);
lenfilt[0] = false;
}
if(rdlens[1] < 2 && paired) {
if(!gQuiet) printLenSkipMsg(*ps, paired, false);
lenfilt[1] = false;
}
qcfilt[0] = qcfilt[1] = true;
if(qcFilter) {
qcfilt[0] = (ps->read_a().filter != '0');
qcfilt[1] = (ps->read_b().filter != '0');
}
filt[0] = (nfilt[0] && scfilt[0] && lenfilt[0] && qcfilt[0]);
filt[1] = (nfilt[1] && scfilt[1] && lenfilt[1] && qcfilt[1]);
prm.nFilt += (filt[0] ? 0 : 1) + (filt[1] ? 0 : 1);
Read* rds[2] = { &ps->read_a(), &ps->read_b() };
assert(msinkwrap.empty());
// Calcualte nofw / no rc
bool nofw[2] = { false, false };
bool norc[2] = { false, false };
nofw[0] = paired ? (gMate1fw ? gNofw : gNorc) : gNofw;
norc[0] = paired ? (gMate1fw ? gNorc : gNofw) : gNorc;
nofw[1] = paired ? (gMate2fw ? gNofw : gNorc) : gNofw;
norc[1] = paired ? (gMate2fw ? gNorc : gNofw) : gNorc;
// Calculate nceil
int nceil[2] = { 0, 0 };
nceil[0] = nCeil.f<int>((double)rdlens[0]);
nceil[0] = min(nceil[0], (int)rdlens[0]);
if(paired) {
nceil[1] = nCeil.f<int>((double)rdlens[1]);
nceil[1] = min(nceil[1], (int)rdlens[1]);
}
exhaustive[0] = exhaustive[1] = false;
bool pairPostFilt = filt[0] && filt[1];
if(pairPostFilt) {
rnd.init(ROTL((rds[0]->seed ^ rds[1]->seed), 10));
}
// Calculate streak length
size_t streak[2] = { maxDpStreak, maxDpStreak };
size_t mtStreak[2] = { maxMateStreak, maxMateStreak };
size_t mxDp[2] = { maxDp, maxDp };
size_t mxUg[2] = { maxUg, maxUg };
size_t mxIter[2] = { maxIters, maxIters };
if(allHits) {
streak[0] = streak[1] = std::numeric_limits<size_t>::max();
mtStreak[0] = mtStreak[1] = std::numeric_limits<size_t>::max();
mxDp[0] = mxDp[1] = std::numeric_limits<size_t>::max();
mxUg[0] = mxUg[1] = std::numeric_limits<size_t>::max();
mxIter[0] = mxIter[1] = std::numeric_limits<size_t>::max();
} else if(khits > 1) {
for(size_t mate = 0; mate < 2; mate++) {
streak[mate] += (khits-1) * maxStreakIncr;
mtStreak[mate] += (khits-1) * maxStreakIncr;
mxDp[mate] += (khits-1) * maxItersIncr;
mxUg[mate] += (khits-1) * maxItersIncr;
mxIter[mate] += (khits-1) * maxItersIncr;
}
}
// If paired-end and neither mate filtered...
if(filt[0] && filt[1]) {
// Reduce streaks for either mate
streak[0] = (size_t)ceil((double)streak[0] / 2.0);
streak[1] = (size_t)ceil((double)streak[1] / 2.0);
assert_gt(streak[1], 0);
}
assert_gt(streak[0], 0);
prm.maxDPFails = streak[0];
// Increment counters according to what got filtered
for(size_t mate = 0; mate < (paired ? 2:1); mate++) {
if(!filt[mate]) {
// Mate was rejected by N filter
olm.freads++; // reads filtered out
olm.fbases += rdlens[mate]; // bases filtered out
} else {
olm.ureads++; // reads passing filter
olm.ubases += rdlens[mate]; // bases passing filter
}
}
if(filt[0]) {
ald.initRead(ps->read_a(), nofw[0], norc[0], minsc[0], maxpen[0], filt[1] ? &ps->read_b() : NULL);
} else if(filt[1]) {
ald.initRead(ps->read_b(), nofw[1], norc[1], minsc[1], maxpen[1], NULL);
}
if(filt[0] || filt[1]) {
ald.go(sc, ebwtFw, ebwtBw, ref, descm, wlm, prm, rnd, msinkwrap);
}
// Commit and report paired-end/unpaired alignments
uint32_t sd = rds[0]->seed ^ rds[1]->seed;
rnd.init(ROTL(sd, 20));
msinkwrap.finishRead(
NULL, // seed results for mate 1
NULL, // seed results for mate 2
exhaustive[0], // exhausted seed results for 1?
exhaustive[1], // exhausted seed results for 2?
nfilt[0],
nfilt[1],
scfilt[0],
scfilt[1],
lenfilt[0],
lenfilt[1],
qcfilt[0],
qcfilt[1],
rnd, // pseudo-random generator
rpm, // reporting metrics
prm, // per-read metrics
sc, // scoring scheme
!seedSumm, // suppress seed summaries?
seedSumm, // suppress alignments?
scUnMapped, // Consider soft-clipped bases unmapped when calculating TLEN
xeq);
} // if(rdid >= skipReads && rdid < qUpto)
else if(rdid >= qUpto) {
break;
}
if(metricsPerRead) {
MERGE_METRICS(metricsPt);
nametmp = ps->read_a().name;
metricsPt.reportInterval(
metricsOfb, metricsStderr, true, &nametmp);
metricsPt.reset();
}
} while (ps->nextReadPairReady()); // must read the whole cached buffer
} // while(true)
// One last metrics merge
MERGE_METRICS(metrics);
p->done->fetch_add(1);
return;
}
#ifndef _WIN32
/**
* Print friendly-ish message pertaining to failed system call.
*/
static void errno_message() {
int errnum = errno;
cerr << "errno is " << errnum << endl;
perror("perror error: ");
}
/**
* Delete PID file. Raise error if the file doesn't exist or if
* we fail to delete it.
*/
void del_pid(const char* dirname,int pid) {
char* fname = (char*)calloc(FNAME_SIZE, sizeof(char));
if(fname == NULL) {
errno_message();
cerr << "del_pid: could not allocate buffer" << endl;
throw 1;
}
snprintf(fname, FNAME_SIZE, "%s/%d", dirname, pid);
if(unlink(fname) != 0) {
if(errno != ENOENT) {
errno_message();
cerr << "del_pid: could not delete PID file " << fname << endl;
free(fname);
throw 1;
} else {
// Probably just a race between processes
}
}
free(fname);
}
/**
* Write PID file.
*/
static void write_pid(const char* dirname,int pid) {
struct stat dinfo;
if(stat(dirname, &dinfo) != 0) {
if(mkdir(dirname, 0755) != 0) {
if(errno != EEXIST) {
errno_message();
cerr << "write_pid: could not create PID directory " << dirname << endl;
throw 1;
}
}
}
char* fname = (char*)calloc(FNAME_SIZE, sizeof(char));
if(fname == NULL) {
errno_message();
cerr << "write_pid: could not allocate buffer" << endl;
throw 1;
}
snprintf(fname, FNAME_SIZE, "%s/%d", dirname, pid);
FILE *f = fopen(fname, "w");
if(f == NULL) {
errno_message();
cerr << "write_pid: could not open PID file " << fname << endl;
throw 1;
}
if(fclose(f) != 0) {
errno_message();
cerr << "write_pid: could not close PID file " << fname << endl;
throw 1;
}
free(fname);
}
/**
* Read all the PID files in the given PID directory. If the
* process corresponding to a PID file seems to have expired,
* delete the PID file. Return the lowest PID encountered for
* a still-valid process.
*/
static int read_dir(const char* dirname, int* num_pids) {
DIR *dir;
struct dirent *ent;
char* fname = (char*)calloc(FNAME_SIZE, sizeof(char));
if(fname == NULL) {
errno_message();
cerr << "read_dir: could not allocate buffer" << endl;
throw 1;
}
dir = opendir(dirname);
if(dir == NULL) {
errno_message();
cerr << "read_dir: could not open directory " << dirname << endl;
free(fname);
throw 1;
}
int lowest_pid = -1;
while(true) {
errno = 0;
ent = readdir(dir);
if(ent == NULL) {
if(errno != 0) {
errno_message();
cerr << "read_dir: could not read directory " << dirname << endl;
free(fname);
throw 1;
}
break;
}
if(ent->d_name[0] == '.') {
continue;
}
int pid = atoi(ent->d_name);
if(kill(pid, 0) != 0) {
if(errno == ESRCH) {
del_pid(dirname, pid);
continue;
} else {
errno_message();
cerr << "read_dir: could not interrogate pid " << pid << endl;
free(fname);
throw 1;
}
}
(*num_pids)++;
if(pid < lowest_pid || lowest_pid == -1) {
lowest_pid = pid;
}
}
if(closedir(dir) != 0) {
errno_message();
cerr << "read_dir: could not close directory " << dir << endl;
free(fname);
throw 1;
}
free(fname);
return lowest_pid;
}
template<typename T>
static void steal_threads(int pid, int orig_nthreads, EList<int>& tids, EList<T*>& threads)
{
int ncpu = thread_ceiling;
if(thread_ceiling <= nthreads) {
return;
}
int num_pids = 0;
int lowest_pid = read_dir(thread_stealing_dir.c_str(), &num_pids);
if(lowest_pid != pid) {
return;
}
int in_use = ((num_pids-1) * orig_nthreads) + nthreads;
if(in_use < ncpu) {
nthreads++;
tids.push_back(nthreads);
threads.push_back(new T(multiseedSearchWorker, (void*)&tids.back()));
cerr << "pid " << pid << " started new worker # " << nthreads << endl;
}
}
template<typename T>
static void thread_monitor(int pid, int orig_threads, EList<int>& tids, EList<T*>& threads)
{
for(int j = 0; j < 10; j++) {
sleep(1);
}
int steal_ctr = 1;
while(thread_counter > 0) {
steal_threads(pid, orig_threads, tids, threads);
steal_ctr++;
for(int j = 0; j < 10; j++) {
sleep(1);
}
}
}
#endif
/**
* Called once per alignment job. Sets up global pointers to the
* shared global data structures, creates per-thread structures, then
* enters the search loop.
*/
static void multiseedSearch(
Scoring& sc,
const PatternParams& pp,
PatternComposer& patsrc, // pattern source
AlnSink& msink, // hit sink
Ebwt& ebwtFw, // index of original text
Ebwt* ebwtBw, // index of mirror text
OutFileBuf *metricsOfb)
{
multiseed_msink = &msink;
multiseed_ebwtFw = &ebwtFw;
multiseed_ebwtBw = ebwtBw;
multiseed_sc = ≻
multiseed_metricsOfb = metricsOfb;
Timer *_t = new Timer(cerr, "Time loading reference: ", timing);
unique_ptr<BitPairReference> refs(
new BitPairReference(
adjIdxBase,
false,
sanityCheck,
NULL,
NULL,
false,
useMm,
useShmem,
mmSweep,
gVerbose,
startVerbose)
);
delete _t;
if(!refs->loaded()) throw 1;
multiseed_refs = refs.get();
#ifndef _WIN32
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &set, NULL);
#endif
EList<int> tids;
EList<std::thread*> threads(nthreads);
EList<thread_tracking_pair> tps;
// The condition_variable synchronization can be problematic
// in certain situations.
// Disabling it and using the polling-based lock-free mechanism can help there
// The (relative) polling cost is much higher for low thread count, so use that as a treshold
bool readahead_useCVLocks = nthreads<=16; // Note: We may want to consider other factors, too
// Important: Need at least nthreads+1 elements, more is OK
PatternSourceReadAheadFactory readahead_factory(patsrc,pp,4*nthreads+1,readahead_useCVLocks);
multiseed_readahead_factory = &readahead_factory;
tps.resize(std::max(nthreads, thread_ceiling));
threads.reserveExact(std::max(nthreads, thread_ceiling));
tids.reserveExact(std::max(nthreads, thread_ceiling));
{
// Load the other half of the index into memory
assert(!ebwtFw.isInMemory());
Timer _t(cerr, "Time loading forward index: ", timing);
ebwtFw.loadIntoMemory(
0, // colorspace?
-1, // not the reverse index
true, // load SA samp? (yes, need forward index's SA samp)
true, // load ftab (in forward index)
true, // load rstarts (in forward index)
!noRefNames, // load names?
startVerbose);
}
if(multiseedMms > 0 || do1mmUpFront) {
// Load the other half of the index into memory
assert(!ebwtBw->isInMemory());
Timer _t(cerr, "Time loading mirror index: ", timing);
ebwtBw->loadIntoMemory(
0, // colorspace?
// It's bidirectional search, so we need the reverse to be
// constructed as the reverse of the concatenated strings.
1,
false, // don't load SA samp in reverse index
true, // yes, need ftab in reverse index
false, // don't load rstarts in reverse index
!noRefNames, // load names?
startVerbose);
}
// Start the metrics thread
std::atomic<int> all_threads_done;
all_threads_done = 0;
{
Timer _t(cerr, "Multiseed full-index search: ", timing);
#ifndef _WIN32
int pid = 0;
if(thread_stealing) {
pid = getpid();
write_pid(thread_stealing_dir.c_str(), pid);
thread_counter = 0;
}
#endif
for(int i = 0; i < nthreads; i++) {
tids.push_back(i);
tps[i].tid = i;
tps[i].done = &all_threads_done;
if(bowtie2p5) {
threads.push_back(new std::thread(multiseedSearchWorker_2p5, (void*)&tps[i]));
} else {
threads.push_back(new std::thread(multiseedSearchWorker, (void*)&tps[i]));
}
threads[i]->detach();
SLEEP(10);
}
#ifndef _WIN32
if(thread_stealing) {
int orig_threads = nthreads;
thread_monitor(pid, orig_threads, tids, threads);
}
#endif
while(all_threads_done < nthreads) {
SLEEP(10);
}
for (int i = 0; i < nthreads; ++i) {
delete threads[i];
}
#ifndef _WIN32
if(thread_stealing) {
del_pid(thread_stealing_dir.c_str(), pid);
}
#endif
}
if(!metricsPerRead && (metricsOfb != NULL || metricsStderr)) {
metrics.reportInterval(metricsOfb, metricsStderr, true, NULL);
}
}
static string argstr;
template<typename TStr>
static void driver(
const char * type,
const string& bt2indexBase,
const string& outfile)
{
if(gVerbose || startVerbose) {
cerr << "Entered driver(): "; logTime(cerr, true);
}
// Vector of the reference sequences; used for sanity-checking
EList<SString<char> > names, os;
EList<size_t> nameLens, seqLens;
// Read reference sequences from the command-line or from a FASTA file
if(!origString.empty()) {
// Read fasta file(s)
EList<string> origFiles;
tokenize(origString, ",", origFiles);
parseFastas(origFiles, names, nameLens, os, seqLens);
}
PatternParams pp(
format, // file format
interleaved, // some or all of the reads are interleaved
fileParallel, // true -> wrap files with separate PairedPatternSources
seed, // pseudo-random seed
readsPerBatch, // # reads in a light parsing batch
solexaQuals, // true -> qualities are on solexa64 scale
phred64Quals, // true -> qualities are on phred64 scale
integerQuals, // true -> qualities are space-separated numbers
gTrim5, // amt to hard clip from 5' end
gTrim3, // amt to hard clip from 3' end
trimTo, // trim reads exceeding given length from either 3' or 5'-end
fastaContLen, // length of sampled reads for FastaContinuous...
fastaContFreq, // frequency of sampled reads for FastaContinuous...
skipReads, // skip the first 'skip' patterns
qUpto, // max number of queries to read
nthreads, //number of threads for locking
outType != OUTPUT_SAM, // whether to fix mate names
preserve_tags, // keep existing tags when aligning BAM files
align_paired_reads // Align only the paired reads in BAM file
);
if(gVerbose || startVerbose) {
cerr << "Creating PatternSource: "; logTime(cerr, true);
}
PatternComposer *patsrc = PatternComposer::setupPatternComposer(
queries, // singles, from argv
mates1, // mate1's, from -1 arg
mates2, // mate2's, from -2 arg
mates12, // both mates on each line, from --12 arg
qualities, // qualities associated with singles
qualities1, // qualities associated with m1
qualities2, // qualities associated with m2
#ifdef USE_SRA
sra_accs, // SRA accessions
#endif
pp, // read read-in parameters
gVerbose || startVerbose); // be talkative
// Open hit output file
if(gVerbose || startVerbose) {
cerr << "Opening hit output file: "; logTime(cerr, true);
}
OutFileBuf *fout;
if(!outfile.empty()) {
fout = new OutFileBuf(outfile.c_str(), false);
} else {
fout = new OutFileBuf();
}
// Initialize Ebwt object and read in header
if(gVerbose || startVerbose) {
cerr << "About to initialize fw Ebwt: "; logTime(cerr, true);
}
adjIdxBase = adjustEbwtBase(argv0, bt2indexBase, gVerbose);
Ebwt ebwt(
adjIdxBase,
0, // index is colorspace
-1, // fw index
true, // index is for the forward direction
/* overriding: */ offRate,
0, // amount to add to index offrate or <= 0 to do nothing
useMm, // whether to use memory-mapped files
useShmem, // whether to use shared memory
mmSweep, // sweep memory-mapped files
!noRefNames, // load names?
true, // load SA sample?
true, // load ftab?
true, // load rstarts?
gVerbose, // whether to be talkative
startVerbose, // talkative during initialization
false /*passMemExc*/,
sanityCheck);
if(sanityCheck && !os.empty()) {
// Sanity check number of patterns and pattern lengths in Ebwt
// against original strings
assert_eq(os.size(), ebwt.nPat());
for(size_t i = 0; i < os.size(); i++) {
assert_eq(os[i].length(), ebwt.plen()[i]);
}
}
// Sanity-check the restored version of the Ebwt
if(sanityCheck && !os.empty()) {
ebwt.loadIntoMemory(
0,
-1, // fw index
true, // load SA sample
true, // load ftab
true, // load rstarts
!noRefNames,
startVerbose);
ebwt.checkOrigs(os, false, false);
ebwt.evictFromMemory();
}
OutputQueue oq(
*fout, // out file buffer
reorder && (nthreads > 1 || thread_stealing), // whether to reorder
nthreads, // # threads
nthreads > 1 || thread_stealing, // whether to be thread-safe
readsPerBatch, // size of output buffer of reads
skipReads); // first read will have this rdid
{
Timer _t(cerr, "Time searching: ", timing);
// Set up pexnalities
if(bonusMatch > 0 && !localAlign) {
cerr << "Warning: Match bonus always = 0 in --end-to-end mode; ignoring user setting" << endl;
bonusMatch = 0;
}
Scoring sc(
bonusMatch, // constant reward for match
penMmcType, // how to penalize mismatches
penMmcMax, // max mm pelanty
penMmcMin, // min mm pelanty
scoreMin, // min score as function of read len
nCeil, // max # Ns as function of read len
penNType, // how to penalize Ns in the read
penN, // constant if N pelanty is a constant
penNCatPair, // whether to concat mates before N filtering
penRdGapConst, // constant coeff for read gap cost
penRfGapConst, // constant coeff for ref gap cost
penRdGapLinear, // linear coeff for read gap cost
penRfGapLinear, // linear coeff for ref gap cost
gGapBarrier); // # rows at top/bot only entered diagonally
EList<size_t> reflens;
for(size_t i = 0; i < ebwt.nPat(); i++) {
reflens.push_back(ebwt.plen()[i]);
}
EList<string> refnames;
readEbwtRefnames(adjIdxBase, refnames);
SamConfig samc(
refnames, // reference sequence names
reflens, // reference sequence lengths
samTruncQname, // whether to truncate QNAME to 255 chars
samAppendComment, // append FASTA/FASTQ comment to SAM record
samOmitSecSeqQual, // omit SEQ/QUAL for 2ndary alignments?
samNoUnal, // omit unaligned-read records?
string("bowtie2"), // program id
string("bowtie2"), // program name
string(BOWTIE2_VERSION), // program version
argstr, // command-line
rgs_optflag, // read-group string
sam_print_as,
sam_print_xs,
sam_print_xss,
sam_print_yn,
sam_print_xn,
sam_print_x0,
sam_print_x1,
sam_print_xm,
sam_print_xo,
sam_print_xg,
sam_print_nm,
sam_print_md,
sam_print_yf,
sam_print_yi,
sam_print_ym,
sam_print_yp,
sam_print_yt,
sam_print_ys,
sam_print_zs,
sam_print_xr,
sam_print_xt,
sam_print_xd,
sam_print_xu,
sam_print_yl,
sam_print_ye,
sam_print_yu,
sam_print_xp,
sam_print_yr,
sam_print_zb,
sam_print_zr,
sam_print_zf,
sam_print_zm,
sam_print_zi,
sam_print_zp,
sam_print_zu,
sam_print_zt);
if (sam_opt_flags.size() > 0) {
for (size_t i = 0; i < sam_opt_flags.size(); i++) {
samc.toggleOptFlagByName(sam_opt_flags[i]);
}
}
// Set up hit sink; if sanityCheck && !os.empty() is true,
// then instruct the sink to "retain" hits in a vector in
// memory so that we can easily sanity check them later on
AlnSink *mssink = NULL;
switch(outType) {
case OUTPUT_SAM: {
mssink = new AlnSinkSam(
oq, // output queue
samc, // settings & routines for SAM output
refnames, // reference names
gQuiet); // don't print alignment summary at end
if(!samNoHead) {
bool printHd = true, printSq = true;
BTString buf;
samc.printHeader(buf, rgid, rgs, printHd, !samNoSQ, printSq);
fout->writeString(buf);
}
break;
}
default:
cerr << "Invalid output type: " << outType << endl;
throw 1;
}
if(gVerbose || startVerbose) {
cerr << "Dispatching to search driver: "; logTime(cerr, true);
}
// Set up global constraint
OutFileBuf *metricsOfb = NULL;
if(!metricsFile.empty() && metricsIval > 0) {
metricsOfb = new OutFileBuf(metricsFile);
}
// Do the search for all input reads
assert(patsrc != NULL);
assert(mssink != NULL);
if(multiseedMms > 0 || do1mmUpFront) {
if(gVerbose || startVerbose) {
cerr << "About to initialize rev Ebwt: "; logTime(cerr, true);
}
// We need the mirror index if mismatches are allowed
Ebwt ebwtBw = Ebwt(
adjIdxBase + ".rev",
0, // index is colorspace
1, // TODO: maybe not
false, // index is for the reverse direction
/* overriding: */ offRate,
0, // amount to add to index offrate or <= 0 to do nothing
useMm, // whether to use memory-mapped files
useShmem, // whether to use shared memory
mmSweep, // sweep memory-mapped files
!noRefNames, // load names?
true, // load SA sample?
true, // load ftab?
true, // load rstarts?
gVerbose, // whether to be talkative
startVerbose, // talkative during initialization
false /*passMemExc*/,
sanityCheck);
multiseedSearch(
sc, // scoring scheme
pp, // pattern params
*patsrc, // pattern source
*mssink, // hit sink
ebwt, // BWT
&ebwtBw, // BWT'
metricsOfb);
} else {
multiseedSearch(
sc, // scoring scheme
pp, // pattern params
*patsrc, // pattern source
*mssink, // hit sink
ebwt, // BWT
NULL, // BWT'
metricsOfb);
}
// Evict any loaded indexes from memory
if(ebwt.isInMemory()) {
ebwt.evictFromMemory();
}
if(!gQuiet && !seedSumm) {
size_t repThresh = mhits;
if(repThresh == 0) {
repThresh = std::numeric_limits<size_t>::max();
}
mssink->finish(
repThresh,
gReportDiscordant,
gReportMixed,
hadoopOut);
}
oq.flush(true);
assert_eq(oq.numStarted(), oq.numFinished());
assert_eq(oq.numStarted(), oq.numFlushed());
delete patsrc;
delete mssink;
delete metricsOfb;
if(fout != NULL) {
delete fout;
}
}
}
// C++ name mangling is disabled for the bowtie() function to make it
// easier to use Bowtie as a library.
extern "C" {
/**
* Main bowtie entry function. Parses argc/argv style command-line
* options, sets global configuration variables, and calls the driver()
* function.
*/
int bowtie(int argc, const char **argv) {
try {
#ifdef WITH_AFFINITY
//CWILKS: adjust this depending on # of hyperthreads per core
pinning_observer pinner( 2 /* the number of hyper threads on each core */ );
pinner.observe( true );
#endif
// Reset all global state, including getopt state
opterr = optind = 1;
resetOptions();
for(int i = 0; i < argc; i++) {
argstr += argv[i];
if(i < argc-1) argstr += " ";
}
if(startVerbose) { cerr << "Entered main(): "; logTime(cerr, true); }
parseOptions(argc, argv);
argv0 = argv[0];
if(showVersion) {
cout << argv0 << " version " << BOWTIE2_VERSION << endl;
if(sizeof(void*) == 4) {
cout << "32-bit" << endl;
} else if(sizeof(void*) == 8) {
cout << "64-bit" << endl;
} else {
cout << "Neither 32- nor 64-bit: sizeof(void*) = " << sizeof(void*) << endl;
}
// cout << "Built on " << BUILD_HOST << endl;
// cout << BUILD_TIME << endl;
// cout << "Compiler: " << COMPILER_VERSION << endl;
// cout << "Options: " << COMPILER_OPTIONS << endl;
// cout << "Sizeof {int, long, long long, void*, size_t, off_t}: {"
// << sizeof(int)
// << ", " << sizeof(long) << ", " << sizeof(long long)
// << ", " << sizeof(void *) << ", " << sizeof(size_t)
// << ", " << sizeof(off_t) << "}" << endl;
return 0;
}
{
Timer _t(cerr, "Overall time: ", timing);
if(startVerbose) {
cerr << "Parsing index and read arguments: "; logTime(cerr, true);
}
// Get index basename (but only if it wasn't specified via --index)
if(bt2index.empty()) {
cerr << "No index, query, or output file specified!" << endl;
printUsage(cerr);
return 1;
}
#ifndef _WIN32
thread_stealing = thread_ceiling > nthreads;
#endif
if(thread_stealing && thread_stealing_dir.empty()) {
cerr << "When --thread-ceiling is specified, must also specify --thread-piddir" << endl;
printUsage(cerr);
return 1;
}
// Get query filename
bool got_reads = !queries.empty() || !mates1.empty() || !mates12.empty();
#ifdef USE_SRA
got_reads = got_reads || !sra_accs.empty();
#endif
if(optind >= argc) {
if(!got_reads) {
printUsage(cerr);
cerr << "***" << endl
#ifdef USE_SRA
<< "Error: Must specify at least one read input with -U/-1/-2/--sra-acc" << endl;
#else
<< "Error: Must specify at least one read input with -U/-1/-2" << endl;
#endif
return 1;
}
} else if(!got_reads) {
// Tokenize the list of query files
tokenize(argv[optind++], ",", queries);
if(queries.empty()) {
cerr << "Tokenized query file list was empty!" << endl;
printUsage(cerr);
return 1;
}
}
// Get output filename
if(optind < argc && outfile.empty()) {
outfile = argv[optind++];
cerr << "Warning: Output file '" << outfile.c_str()
<< "' was specified without -S. This will not work in "
<< "future Bowtie 2 versions. Please use -S instead."
<< endl;
}
// Extra parametesr?
if(optind < argc) {
cerr << "Extra parameter(s) specified: ";
for(int i = optind; i < argc; i++) {
cerr << "\"" << argv[i] << "\"";
if(i < argc-1) cerr << ", ";
}
cerr << endl;
if(mates1.size() > 0) {
cerr << "Note that if <mates> files are specified using -1/-2, a <singles> file cannot" << endl
<< "also be specified. Please run bowtie separately for mates and singles." << endl;
}
throw 1;
}
// Optionally summarize
if(gVerbose) {
cout << "Input " + gEbwt_ext +" file: \"" << bt2index.c_str() << "\"" << endl;
cout << "Query inputs (DNA, " << file_format_names[format].c_str() << "):" << endl;
for(size_t i = 0; i < queries.size(); i++) {
cout << " " << queries[i].c_str() << endl;
}
cout << "Quality inputs:" << endl;
for(size_t i = 0; i < qualities.size(); i++) {
cout << " " << qualities[i].c_str() << endl;
}
cout << "Output file: \"" << outfile.c_str() << "\"" << endl;
cout << "Local endianness: " << (currentlyBigEndian()? "big":"little") << endl;
cout << "Sanity checking: " << (sanityCheck? "enabled":"disabled") << endl;
#ifdef NDEBUG
cout << "Assertions: disabled" << endl;
#else
cout << "Assertions: enabled" << endl;
#endif
}
if(ipause) {
cout << "Press key to continue..." << endl;
getchar();
}
driver<SString<char> >("DNA", bt2index, outfile);
}
#ifdef WITH_AFFINITY
// Always disable observation before observers destruction
//tracker.observe( false );
pinner.observe( false );
#endif
return 0;
} catch(std::exception& e) {
cerr << "Error: Encountered exception: '" << e.what() << "'" << endl;
cerr << "Command: ";
for(int i = 0; i < argc; i++) cerr << argv[i] << " ";
cerr << endl;
return 1;
} catch(int e) {
if(e != 0) {
cerr << "Error: Encountered internal Bowtie 2 exception (#" << e << ")" << endl;
cerr << "Command: ";
for(int i = 0; i < argc; i++) cerr << argv[i] << " ";
cerr << endl;
}
return e;
}
} // bowtie()
} // extern "C"
|