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
|
/*++
Module Name:
IntersectingPairedEndAligner.cpp
Abstract:
A paired-end aligner based on set intersections to narrow down possible candidate locations.
Authors:
Bill Bolosky, February, 2013
Environment:
User mode service.
Revision History:
--*/
#include "stdafx.h"
#include "IntersectingPairedEndAligner.h"
#include "SeedSequencer.h"
#include "mapq.h"
#include "exit.h"
#include "Error.h"
#include "BigAlloc.h"
#include "AlignerOptions.h"
#ifdef _DEBUG
extern volatile bool _DumpAlignments; // From BaseAligner.cpp
#endif // _DEBUG
IntersectingPairedEndAligner::IntersectingPairedEndAligner(
GenomeIndex *index_,
unsigned maxReadSize_,
unsigned maxHits_,
unsigned maxK_,
unsigned maxKForIndels_,
unsigned numSeedsFromCommandLine_,
double seedCoverage_,
int minSpacing_, // Minimum distance to allow between the two ends.
unsigned maxSpacing_, // Maximum distance to allow between the two ends.
unsigned maxBigHits_,
unsigned extraSearchDepth_,
unsigned maxCandidatePoolSize,
int maxSecondaryAlignmentsPerContig_,
BigAllocator *allocator,
DisabledOptimizations disabledOptimizations_,
bool useAffineGap_,
bool ignoreAlignmentAdjustmentsForOm_,
bool altAwareness_,
unsigned maxScoreGapToPreferNonAltAlignment_,
unsigned matchReward_,
unsigned subPenalty_,
unsigned gapOpenPenalty_,
unsigned gapExtendPenalty_,
bool useSoftClip_) :
index(index_), maxReadSize(maxReadSize_), maxHits(maxHits_), maxK(maxK_), maxKForIndels(maxKForIndels_), numSeedsFromCommandLine(__min(MAX_MAX_SEEDS,numSeedsFromCommandLine_)), minSpacing(minSpacing_), maxSpacing(maxSpacing_),
landauVishkin(NULL), reverseLandauVishkin(NULL), maxBigHits(maxBigHits_), seedCoverage(seedCoverage_),
extraSearchDepth(extraSearchDepth_), nLocationsScoredLandauVishkin(0), nLocationsScoredAffineGap(0), disabledOptimizations(disabledOptimizations_),
useAffineGap(useAffineGap_), maxSecondaryAlignmentsPerContig(maxSecondaryAlignmentsPerContig_), alignmentAdjuster(index->getGenome()), ignoreAlignmentAdjustmentsForOm(ignoreAlignmentAdjustmentsForOm_), altAwareness(altAwareness_),
maxScoreGapToPreferNonAltAlignment(maxScoreGapToPreferNonAltAlignment_), matchReward(matchReward_), subPenalty(subPenalty_), gapOpenPenalty(gapOpenPenalty_), gapExtendPenalty(gapExtendPenalty_), useSoftClip(useSoftClip_),
stopOnFirstHit(false)
{
doesGenomeIndexHave64BitLocations = index->doesGenomeIndexHave64BitLocations();
unsigned maxSeedsToUse;
if (0 != numSeedsFromCommandLine) {
maxSeedsToUse = numSeedsFromCommandLine;
} else {
maxSeedsToUse = (unsigned)(maxReadSize * seedCoverage / index->getSeedLength());
}
allocateDynamicMemory(allocator, maxReadSize, maxBigHits, maxSeedsToUse, MAX_K, extraSearchDepth, maxCandidatePoolSize, maxSecondaryAlignmentsPerContig);
rcTranslationTable['A'] = 'T';
rcTranslationTable['G'] = 'C';
rcTranslationTable['C'] = 'G';
rcTranslationTable['T'] = 'A';
rcTranslationTable['N'] = 'N';
for (unsigned i = 0; i < 256; i++) {
nTable[i] = 0;
}
nTable['N'] = 1;
seedLen = index->getSeedLength();
genome = index->getGenome();
genomeSize = genome->getCountOfBases();
if (disabledOptimizations.noMaxKForIndel) {
maxK = maxKForIndels;
}
}
IntersectingPairedEndAligner::~IntersectingPairedEndAligner()
{
}
size_t
IntersectingPairedEndAligner::getBigAllocatorReservation(GenomeIndex * index, unsigned maxBigHitsToConsider, unsigned maxReadSize, unsigned seedLen, unsigned numSeedsFromCommandLine,
double seedCoverage, unsigned maxEditDistanceToConsider, unsigned maxExtraSearchDepth, unsigned maxCandidatePoolSize,
int maxSecondaryAlignmentsPerContig)
{
unsigned maxSeedsToUse;
if (0 != numSeedsFromCommandLine) {
maxSeedsToUse = numSeedsFromCommandLine;
} else {
maxSeedsToUse = (unsigned)(maxReadSize * seedCoverage / index->getSeedLength());
}
CountingBigAllocator countingAllocator;
{
IntersectingPairedEndAligner aligner; // This has to be in a nested scope so its destructor is called before that of the countingAllocator
aligner.index = index;
aligner.doesGenomeIndexHave64BitLocations = index->doesGenomeIndexHave64BitLocations();
aligner.allocateDynamicMemory(&countingAllocator, maxReadSize, maxBigHitsToConsider, maxSeedsToUse, maxEditDistanceToConsider, maxExtraSearchDepth, maxCandidatePoolSize,
maxSecondaryAlignmentsPerContig);
return sizeof(aligner) + countingAllocator.getMemoryUsed();
}
}
void
IntersectingPairedEndAligner::allocateDynamicMemory(BigAllocator *allocator, unsigned maxReadSize, unsigned maxBigHitsToConsider, unsigned maxSeedsToUse,
unsigned maxEditDistanceToConsider, unsigned maxExtraSearchDepth, unsigned maxCandidatePoolSize,
int maxSecondaryAlignmentsPerContig)
{
seedUsed = (BYTE *) allocator->allocate(100 + ((size_t)maxReadSize + 7) / 8);
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
rcReadData[whichRead] = (char *)allocator->allocate(maxReadSize);
rcReadQuality[whichRead] = (char *)allocator->allocate(maxReadSize);
for (Direction dir = 0; dir < NUM_DIRECTIONS; dir++) {
reversedRead[whichRead][dir] = (char *)allocator->allocate(maxReadSize);
hashTableHitSets[whichRead][dir] =(HashTableHitSet *)allocator->allocate(sizeof(HashTableHitSet)); /*new HashTableHitSet();*/
hashTableHitSets[whichRead][dir]->firstInit(maxSeedsToUse, maxMergeDistance, allocator, doesGenomeIndexHave64BitLocations);
}
}
scoringCandidatePoolSize = min(maxCandidatePoolSize, maxBigHitsToConsider * maxSeedsToUse * NUM_READS_PER_PAIR);
scoringCandidates = (ScoringCandidate **) allocator->allocate(sizeof(ScoringCandidate *) * ((size_t)maxEditDistanceToConsider + maxExtraSearchDepth + 1)); //+1 is for 0.
scoringCandidatePool = (ScoringCandidate *)allocator->allocate(sizeof(ScoringCandidate) * scoringCandidatePoolSize);
for (unsigned i = 0; i < NUM_READS_PER_PAIR; i++) {
scoringMateCandidates[i] = (ScoringMateCandidate *) allocator->allocate(sizeof(ScoringMateCandidate) * scoringCandidatePoolSize / NUM_READS_PER_PAIR);
}
mergeAnchorPoolSize = scoringCandidatePoolSize;
mergeAnchorPool = (MergeAnchor *)allocator->allocate(sizeof(MergeAnchor) * mergeAnchorPoolSize);
if (maxSecondaryAlignmentsPerContig > 0) {
size_t size = sizeof(*hitsPerContigCounts) * index->getGenome()->getNumContigs();
hitsPerContigCounts = (HitsPerContigCounts *)allocator->allocate(size);
memset(hitsPerContigCounts, 0, size);
contigCountEpoch = 0;
} else {
hitsPerContigCounts = NULL;
}
}
bool
IntersectingPairedEndAligner::align(
Read *read0,
Read *read1,
PairedAlignmentResult* result,
PairedAlignmentResult* firstALTResult,
int maxEditDistanceForSecondaryResults,
_int64 secondaryResultBufferSize,
_int64 *nSecondaryResults,
PairedAlignmentResult *secondaryResults, // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by align()
_int64 singleSecondaryBufferSize,
_int64 maxSecondaryResultsToReturn,
_int64 *nSingleEndSecondaryResultsForFirstRead,
_int64 *nSingleEndSecondaryResultsForSecondRead,
SingleAlignmentResult *singleEndSecondaryResults, // Single-end secondary alignments for when the paired-end alignment didn't work properly
_int64 maxLVCandidatesForAffineGapBufferSize,
_int64 *nLVCandidatesForAffineGap,
PairedAlignmentResult *lvCandidatesForAffineGap, // Landau-Vishkin candidates that need to be rescored using affine gap
_int64 maxSingleCandidatesForAffineGapBufferSize,
_int64 *nSingleCandidatesForAffineGapFirstRead,
_int64 *nSingleCandidatesForAffineGapSecondRead,
SingleAlignmentResult *singleCandidatesForAffineGap,
int maxK_
)
{
maxK = maxK_;
if (!useAffineGap) {
//
// Version with no affine gap scoring
//
return alignLandauVishkin(read0, read1, result, firstALTResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize,
nSecondaryResults, secondaryResults, singleSecondaryBufferSize, maxSecondaryResultsToReturn, nSingleEndSecondaryResultsForFirstRead, nSingleEndSecondaryResultsForSecondRead,
singleEndSecondaryResults, maxLVCandidatesForAffineGapBufferSize, nLVCandidatesForAffineGap, lvCandidatesForAffineGap);
} else {
//
// Perform seeding, set intersection, LV alignment and identify promising candidates for affine gap scoring
//
bool fitInSecondaryBuffer = alignLandauVishkin(read0, read1, result, firstALTResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize,
nSecondaryResults, secondaryResults, singleSecondaryBufferSize, maxSecondaryResultsToReturn, nSingleEndSecondaryResultsForFirstRead, nSingleEndSecondaryResultsForSecondRead,
singleEndSecondaryResults, maxLVCandidatesForAffineGapBufferSize, nLVCandidatesForAffineGap, lvCandidatesForAffineGap);
if (*nLVCandidatesForAffineGap > maxLVCandidatesForAffineGapBufferSize) {
*nLVCandidatesForAffineGap = maxLVCandidatesForAffineGapBufferSize + 1;
return false;
}
if (!fitInSecondaryBuffer) {
return false;
}
//
// Try to align unaligned read/mate using a Hamming distance based scoring scheme that clips poorly matching start or ends
// of read/mate.
//
if (useSoftClip && (result->status[0] == NotFound || result->status[1] == NotFound)) {
fitInSecondaryBuffer = alignHamming(read0, read1, result, firstALTResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize,
nSecondaryResults, secondaryResults, singleSecondaryBufferSize, maxSecondaryResultsToReturn, nSingleEndSecondaryResultsForFirstRead, nSingleEndSecondaryResultsForSecondRead,
singleEndSecondaryResults, maxLVCandidatesForAffineGapBufferSize, nLVCandidatesForAffineGap, lvCandidatesForAffineGap);
if (*nLVCandidatesForAffineGap > maxLVCandidatesForAffineGapBufferSize) {
*nLVCandidatesForAffineGap = maxLVCandidatesForAffineGapBufferSize + 1;
return false;
}
if (!fitInSecondaryBuffer) {
return false;
}
}
//
// Perform affine gap scoring for promising candidates to get best scoring hit
//
fitInSecondaryBuffer = alignAffineGap(read0, read1, result, firstALTResult, maxEditDistanceForSecondaryResults, secondaryResultBufferSize,
nSecondaryResults, secondaryResults, singleSecondaryBufferSize, maxSecondaryResultsToReturn, nSingleEndSecondaryResultsForFirstRead, nSingleEndSecondaryResultsForSecondRead,
singleEndSecondaryResults, maxLVCandidatesForAffineGapBufferSize, nLVCandidatesForAffineGap, lvCandidatesForAffineGap);
if (!fitInSecondaryBuffer) {
return false;
}
return true;
}
}
bool
IntersectingPairedEndAligner::alignLandauVishkin(
Read* read0,
Read* read1,
PairedAlignmentResult* result,
PairedAlignmentResult* firstALTResult,
int maxEditDistanceForSecondaryResults,
_int64 secondaryResultBufferSize,
_int64* nSecondaryResults,
PairedAlignmentResult* secondaryResults, // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by align()
_int64 singleSecondaryBufferSize,
_int64 maxSecondaryResultsToReturn,
_int64* nSingleEndSecondaryResultsForFirstRead,
_int64* nSingleEndSecondaryResultsForSecondRead,
SingleAlignmentResult* singleEndSecondaryResults, // Single-end secondary alignments for when the paired-end alignment didn't work properly
_int64 maxLVCandidatesForAffineGapBufferSize,
_int64* nLVCandidatesForAffineGap,
PairedAlignmentResult* lvCandidatesForAffineGap
)
{
#if INSTRUMENTATION_FOR_PAPER
_int64 startTime = timeInNanos();
_int64 nScored = 0;
_int64 setIntersectionSize = 0;
bool bestCandidateScoredFirst = false;
#endif // INSTRUMENTATION_FOR_PAPER
firstALTResult->status[0] = firstALTResult->status[1] = NotFound;
firstALTResult->refSpan[0] = firstALTResult->refSpan[1] = 0;
result->nLVCalls = 0;
result->nSmallHits = 0;
result->clippingForReadAdjustment[0] = result->clippingForReadAdjustment[1] = 0;
result->usedAffineGapScoring[0] = result->usedAffineGapScoring[1] = false;
result->basesClippedBefore[0] = result->basesClippedBefore[1] = 0;
result->basesClippedAfter[0] = result->basesClippedAfter[1] = 0;
result->agScore[0] = result->agScore[1] = 0;
result->usedGaplessClipping[0] = result->usedGaplessClipping[1] = false;
result->refSpan[0] = result->refSpan[1] = 0;
result->liftover[0] = result->liftover[1] = false;
*nSecondaryResults = 0;
*nSingleEndSecondaryResultsForFirstRead = 0;
*nSingleEndSecondaryResultsForSecondRead = 0;
*nLVCandidatesForAffineGap = 0;
int maxSeeds;
if (numSeedsFromCommandLine != 0) {
maxSeeds = (int)numSeedsFromCommandLine;
}
else {
maxSeeds = (int)(max(read0->getDataLength(), read1->getDataLength()) * seedCoverage / index->getSeedLength());
}
#ifdef _DEBUG
if (_DumpAlignments) {
printf("\nIntersectingAligner aligning reads '%.*s' and '%.*s' with data '%.*s' and '%.*s'\n", read0->getIdLength(), read0->getId(), read1->getIdLength(), read1->getId(), read0->getDataLength(), read0->getData(), read1->getDataLength(), read1->getData());
}
#endif // _DEBUG
lowestFreeScoringCandidatePoolEntry = 0;
for (int k = 0; k <= maxK + extraSearchDepth; k++) {
scoringCandidates[k] = NULL;
}
for (unsigned i = 0; i < NUM_SET_PAIRS; i++) {
lowestFreeScoringMateCandidate[i] = 0;
}
firstFreeMergeAnchor = 0;
Read rcReads[NUM_READS_PER_PAIR];
ScoreSet scoresForAllAlignments;
ScoreSet scoresForNonAltAlignments;
unsigned popularSeedsSkipped[NUM_READS_PER_PAIR];
reads[0][FORWARD] = read0;
reads[1][FORWARD] = read1;
//
// Don't bother if one or both reads are too short. The minimum read length here is the seed length, but usually there's a longer
// minimum enforced by our caller
//
if (read0->getDataLength() < seedLen || read1->getDataLength() < seedLen) {
return true;
}
//
// Build the RC reads.
//
unsigned countOfNs = 0;
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
Read* read = reads[whichRead][FORWARD];
readLen[whichRead] = read->getDataLength();
popularSeedsSkipped[whichRead] = 0;
countOfHashTableLookups[whichRead] = 0;
#if 0
hitLocations[whichRead]->clear();
mateHitLocations[whichRead]->clear();
#endif // 0
for (Direction dir = FORWARD; dir < NUM_DIRECTIONS; dir++) {
totalHashTableHits[whichRead][dir] = 0;
largestHashTableHit[whichRead][dir] = 0;
hashTableHitSets[whichRead][dir]->init();
}
if (readLen[whichRead] > maxReadSize) {
WriteErrorMessage("IntersectingPairedEndAligner:: got too big read (%d > %d)\n"
"Change MAX_READ_LENTH at the beginning of Read.h and recompile.\n", readLen[whichRead], maxReadSize);
soft_exit(1);
}
for (unsigned i = 0; i < reads[whichRead][FORWARD]->getDataLength(); i++) {
rcReadData[whichRead][i] = rcTranslationTable[read->getData()[readLen[whichRead] - i - 1]];
rcReadQuality[whichRead][i] = read->getQuality()[readLen[whichRead] - i - 1];
countOfNs += nTable[read->getData()[i]];
}
reads[whichRead][RC] = &rcReads[whichRead];
reads[whichRead][RC]->init(read->getId(), read->getIdLength(), rcReadData[whichRead], rcReadQuality[whichRead], read->getDataLength(), read->getFASTQComment(), read->getFASTQCommentLength());
}
if ((int)countOfNs > maxK) {
return true;
}
//
// Build the reverse data for both reads in both directions for the backwards LV to use.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
for (Direction dir = 0; dir < NUM_DIRECTIONS; dir++) {
Read* read = reads[whichRead][dir];
for (unsigned i = 0; i < read->getDataLength(); i++) {
reversedRead[whichRead][dir][i] = read->getData()[read->getDataLength() - i - 1];
}
}
}
unsigned thisPassSeedsNotSkipped[NUM_READS_PER_PAIR][NUM_DIRECTIONS] = { {0,0}, {0,0} };
//
// Initialize the member variables that are effectively stack locals, but are in the object
// to avoid having to pass them to score.
//
localBestPairProbability[0] = 0;
localBestPairProbability[1] = 0;
//
// Phase 1: do the hash table lookups for each of the seeds for each of the reads and add them to the hit sets.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
int nextSeedToTest = 0;
unsigned wrapCount = 0;
int nPossibleSeeds = (int)readLen[whichRead] - seedLen + 1;
memset(seedUsed, 0, (__max(readLen[0], readLen[1]) + 7) / 8);
bool beginsDisjointHitSet[NUM_DIRECTIONS] = { true, true };
while (countOfHashTableLookups[whichRead] < nPossibleSeeds && countOfHashTableLookups[whichRead] < maxSeeds) {
if (nextSeedToTest >= nPossibleSeeds) {
wrapCount++;
beginsDisjointHitSet[FORWARD] = beginsDisjointHitSet[RC] = true;
if (wrapCount >= seedLen) {
//
// There aren't enough valid seeds in this read to reach our target.
//
break;
}
nextSeedToTest = GetWrappedNextSeedToTest(seedLen, wrapCount);
}
while (nextSeedToTest < nPossibleSeeds && IsSeedUsed(nextSeedToTest)) {
//
// This seed is already used. Try the next one.
//
nextSeedToTest++;
}
if (nextSeedToTest >= nPossibleSeeds) {
//
// Unusable seeds have pushed us past the end of the read. Go back around the outer loop so we wrap properly.
//
continue;
}
SetSeedUsed(nextSeedToTest);
if (!Seed::DoesTextRepresentASeed(reads[whichRead][FORWARD]->getData() + nextSeedToTest, seedLen)) {
//
// It's got Ns in it, so just skip it.
//
nextSeedToTest++;
continue;
}
Seed seed(reads[whichRead][FORWARD]->getData() + nextSeedToTest, seedLen);
//
// Find all instances of this seed in the genome.
//
_int64 nHits[NUM_DIRECTIONS];
const GenomeLocation* hits[NUM_DIRECTIONS];
const unsigned* hits32[NUM_DIRECTIONS];
if (doesGenomeIndexHave64BitLocations) {
index->lookupSeed(seed, &nHits[FORWARD], &hits[FORWARD], &nHits[RC], &hits[RC],
hashTableHitSets[whichRead][FORWARD]->getNextSingletonLocation(), hashTableHitSets[whichRead][RC]->getNextSingletonLocation());
} else {
index->lookupSeed32(seed, &nHits[FORWARD], &hits32[FORWARD], &nHits[RC], &hits32[RC]);
}
countOfHashTableLookups[whichRead]++;
for (Direction dir = FORWARD; dir < NUM_DIRECTIONS; dir++) {
int offset;
if (dir == FORWARD) {
offset = nextSeedToTest;
} else {
offset = readLen[whichRead] - seedLen - nextSeedToTest;
}
if (nHits[dir] < maxBigHits) {
totalHashTableHits[whichRead][dir] += nHits[dir];
if (doesGenomeIndexHave64BitLocations) {
hashTableHitSets[whichRead][dir]->recordLookup(offset, nHits[dir], hits[dir], beginsDisjointHitSet[dir]);
} else {
hashTableHitSets[whichRead][dir]->recordLookup(offset, nHits[dir], hits32[dir], beginsDisjointHitSet[dir]);
}
beginsDisjointHitSet[dir] = false;
} else {
popularSeedsSkipped[whichRead]++;
}
} // for each direction
//
// If we don't have enough seeds left to reach the end of the read, space out the seeds more-or-less evenly.
//
if ((maxSeeds - countOfHashTableLookups[whichRead] + 1) * (int)seedLen + nextSeedToTest < nPossibleSeeds) {
_ASSERT((nPossibleSeeds - nextSeedToTest - 1) / (maxSeeds - countOfHashTableLookups[whichRead] + 1) >= (int)seedLen);
nextSeedToTest += (nPossibleSeeds - nextSeedToTest - 1) / (maxSeeds - countOfHashTableLookups[whichRead] + 1);
_ASSERT(nextSeedToTest < nPossibleSeeds); // We haven't run off the end of the read.
} else {
nextSeedToTest += seedLen;
}
} // while we need to lookup seeds for this read
} // for each read
#if INSTRUMENTATION_FOR_PAPER
int hashTableHits[NUM_READS_PER_PAIR] = { hashTableHitSets[0][FORWARD]->getNumDistinctHitLocations(0) + hashTableHitSets[0][RC]->getNumDistinctHitLocations(0),
hashTableHitSets[1][FORWARD]->getNumDistinctHitLocations(0) + hashTableHitSets[1][RC]->getNumDistinctHitLocations(0) };
int log2HashTableHits[NUM_READS_PER_PAIR] = { __min(cheezyLogBase2(hashTableHits[0]), MAX_HIT_SIZE_LOG_2),__min(cheezyLogBase2(hashTableHits[1]), MAX_HIT_SIZE_LOG_2) };
// = { __min(cheezyLogBase2(totalHashTableHits[0][FORWARD] + totalHashTableHits[0][RC]), MAX_HIT_SIZE_LOG_2), __min(cheezyLogBase2(totalHashTableHits[1][FORWARD] + totalHashTableHits[1][RC]), MAX_HIT_SIZE_LOG_2) };
#endif // INSTRUMENTATION_FOR_PAPER
readWithMoreHits = totalHashTableHits[0][FORWARD] + totalHashTableHits[0][RC] > totalHashTableHits[1][FORWARD] + totalHashTableHits[1][RC] ? 0 : 1;
readWithFewerHits = 1 - readWithMoreHits;
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Read 0 has %lld hits, read 1 has %lld hits\n", totalHashTableHits[0][FORWARD] + totalHashTableHits[0][RC], totalHashTableHits[1][FORWARD] + totalHashTableHits[1][RC]);
}
#endif // _DEBUG
Direction setPairDirection[NUM_SET_PAIRS][NUM_READS_PER_PAIR] = {{FORWARD, RC}, {RC, FORWARD}};
//
// Phase 2: find all possible candidates and add them to candidate lists (for the reads with fewer and more hits).
//
int maxUsedBestPossibleScoreList = 0;
for (unsigned whichSetPair = 0; whichSetPair < NUM_SET_PAIRS; whichSetPair++) {
HashTableHitSet *setPair[NUM_READS_PER_PAIR];
if (whichSetPair == 0) {
setPair[0] = hashTableHitSets[0][FORWARD];
setPair[1] = hashTableHitSets[1][RC];
} else {
setPair[0] = hashTableHitSets[0][RC];
setPair[1] = hashTableHitSets[1][FORWARD];
}
unsigned lastSeedOffsetForReadWithFewerHits;
GenomeLocation lastGenomeLocationForReadWithFewerHits;
GenomeLocation lastGenomeLocationForReadWithMoreHits;
unsigned lastSeedOffsetForReadWithMoreHits;
bool outOfMoreHitsLocations = false;
//
// Seed the intersection state by doing a first lookup.
//
if (setPair[readWithFewerHits]->getFirstHit(&lastGenomeLocationForReadWithFewerHits, &lastSeedOffsetForReadWithFewerHits)) {
//
// No hits in this direction.
//
continue; // The outer loop over set pairs.
}
lastGenomeLocationForReadWithMoreHits = InvalidGenomeLocation;
//
// Loop over the candidates in for the read with more hits. At the top of the loop, we have a candidate but don't know if it has
// a mate. Each pass through the loop considers a single hit on the read with fewer hits.
//
for (;;) {
//
// Loop invariant: lastGenomeLocationForReadWithFewerHits is the highest genome offset that has not been considered.
// lastGenomeLocationForReadWithMoreHits is also the highest genome offset on that side that has not been
// considered (or is InvalidGenomeLocation), but higher ones within the appropriate range might already be in scoringMateCandidates.
// We go once through this loop for each. Because the index is ordered high to low, we also go in that direction.
//
if (lastGenomeLocationForReadWithMoreHits > lastGenomeLocationForReadWithFewerHits + maxSpacing) {
//
// The more hits side is too high to be a mate candidate for the fewer hits side. Move it down to the largest
// location that's not too high.
//
if (!setPair[readWithMoreHits]->getNextHitLessThanOrEqualTo(lastGenomeLocationForReadWithFewerHits + maxSpacing,
&lastGenomeLocationForReadWithMoreHits, &lastSeedOffsetForReadWithMoreHits)) {
break; // End of all of the mates. We're done with this set pair.
}
}
if ((lastGenomeLocationForReadWithMoreHits + maxSpacing < lastGenomeLocationForReadWithFewerHits || outOfMoreHitsLocations) &&
(0 == lowestFreeScoringMateCandidate[whichSetPair] ||
!genomeLocationIsWithin(scoringMateCandidates[whichSetPair][lowestFreeScoringMateCandidate[whichSetPair]-1].readWithMoreHitsGenomeLocation, lastGenomeLocationForReadWithFewerHits, maxSpacing))) {
//
// No mates for the hit on the read with fewer hits. Skip to the next candidate.
//
if (outOfMoreHitsLocations) {
//
// Nothing left on the more hits side, we're done with this set pair.
//
break;
}
if (!setPair[readWithFewerHits]->getNextHitLessThanOrEqualTo(lastGenomeLocationForReadWithMoreHits + maxSpacing, &lastGenomeLocationForReadWithFewerHits,
&lastSeedOffsetForReadWithFewerHits)) {
//
// No more candidates on the read with fewer hits side. We're done with this set pair.
//
break;
}
continue;
}
//
// Add all of the mate candidates for the fewer side hit.
//
GenomeLocation previousMoreHitsLocation = lastGenomeLocationForReadWithMoreHits;
while (lastGenomeLocationForReadWithMoreHits + maxSpacing >= lastGenomeLocationForReadWithFewerHits && !outOfMoreHitsLocations) {
unsigned bestPossibleScoreForReadWithMoreHits;
if (disabledOptimizations.noTruncation) {
bestPossibleScoreForReadWithMoreHits = 0;
} else {
bestPossibleScoreForReadWithMoreHits = setPair[readWithMoreHits]->computeBestPossibleScoreForCurrentHit();
}
if (lowestFreeScoringMateCandidate[whichSetPair] >= scoringCandidatePoolSize / NUM_READS_PER_PAIR) {
WriteErrorMessage("Ran out of scoring candidate pool entries. Perhaps trying with a larger value of -mcp will help.\n");
soft_exit(1);
}
scoringMateCandidates[whichSetPair][lowestFreeScoringMateCandidate[whichSetPair]].init(
lastGenomeLocationForReadWithMoreHits, bestPossibleScoreForReadWithMoreHits,
lastSeedOffsetForReadWithMoreHits, &disabledOptimizations, maxKForIndels);
#ifdef _DEBUG
if (_DumpAlignments) {
printf("SetPair %d, added more hits candidate %d at genome location %s:%llu, bestPossibleScore %d, seedOffset %d\n",
whichSetPair, lowestFreeScoringMateCandidate[whichSetPair],
genome->getContigAtLocation(lastGenomeLocationForReadWithMoreHits)->name,
lastGenomeLocationForReadWithMoreHits - genome->getContigAtLocation(lastGenomeLocationForReadWithMoreHits)->beginningLocation,
bestPossibleScoreForReadWithMoreHits,
lastSeedOffsetForReadWithMoreHits);
}
#endif // _DEBUG
lowestFreeScoringMateCandidate[whichSetPair]++;
previousMoreHitsLocation = lastGenomeLocationForReadWithMoreHits;
if (!setPair[readWithMoreHits]->getNextLowerHit(&lastGenomeLocationForReadWithMoreHits, &lastSeedOffsetForReadWithMoreHits)) {
lastGenomeLocationForReadWithMoreHits = 0;
outOfMoreHitsLocations = true;
break; // out of the loop looking for candidates on the more hits side.
}
}
//
// And finally add the hit from the fewer hit side. To compute its best possible score, we need to look at all of the mates; we couldn't do it in the
// loop immediately above because some of them might have already been in the mate list from a different, nearby fewer hit location.
//
int bestPossibleScoreForReadWithFewerHits;
if (disabledOptimizations.noTruncation) {
bestPossibleScoreForReadWithFewerHits = 0;
} else {
bestPossibleScoreForReadWithFewerHits = setPair[readWithFewerHits]->computeBestPossibleScoreForCurrentHit();
}
int lowestBestPossibleScoreOfAnyPossibleMate = maxK + extraSearchDepth;
for (int i = lowestFreeScoringMateCandidate[whichSetPair] - 1; i >= 0; i--) {
if (scoringMateCandidates[whichSetPair][i].readWithMoreHitsGenomeLocation > lastGenomeLocationForReadWithFewerHits + maxSpacing) {
break;
}
lowestBestPossibleScoreOfAnyPossibleMate = __min(lowestBestPossibleScoreOfAnyPossibleMate, scoringMateCandidates[whichSetPair][i].bestPossibleScore);
}
if (lowestBestPossibleScoreOfAnyPossibleMate + bestPossibleScoreForReadWithFewerHits <= maxK + extraSearchDepth) {
//
// There's a set of ends that we can't prove doesn't have too large of a score. Allocate a fewer hit candidate and stick it in the
// correct weight list.
//
if (lowestFreeScoringCandidatePoolEntry >= scoringCandidatePoolSize) {
WriteErrorMessage("Ran out of scoring candidate pool entries. Perhaps rerunning with a larger value of -mcp will help.\n");
soft_exit(1);
}
//
// If we have noOrderedEvaluation set, just stick everything on list 0, regardless of what it really is. This will cause us to
// evaluate the candidates in more-or-less inverse genome order.
//
int bestPossibleScore = disabledOptimizations.noOrderedEvaluation ? 0 : lowestBestPossibleScoreOfAnyPossibleMate + bestPossibleScoreForReadWithFewerHits;
scoringCandidatePool[lowestFreeScoringCandidatePoolEntry].init(lastGenomeLocationForReadWithFewerHits, whichSetPair, lowestFreeScoringMateCandidate[whichSetPair] - 1,
lastSeedOffsetForReadWithFewerHits, bestPossibleScoreForReadWithFewerHits,
scoringCandidates[bestPossibleScore]);
scoringCandidates[bestPossibleScore] = &scoringCandidatePool[lowestFreeScoringCandidatePoolEntry];
#if INSTRUMENTATION_FOR_PAPER
setIntersectionSize++;
#endif // INSTRUMENTATION_FOR_PAPER
#ifdef _DEBUG
if (_DumpAlignments) {
printf("SetPair %d, added fewer hits candidate %d at genome location %s:%llu, bestPossibleScore %d, seedOffset %d\n",
whichSetPair, lowestFreeScoringCandidatePoolEntry,
genome->getContigAtLocation(lastGenomeLocationForReadWithFewerHits)->name, lastGenomeLocationForReadWithFewerHits - genome->getContigAtLocation(lastGenomeLocationForReadWithFewerHits)->beginningLocation,
lowestBestPossibleScoreOfAnyPossibleMate + bestPossibleScoreForReadWithFewerHits,
lastSeedOffsetForReadWithFewerHits);
}
#endif // _DEBUG
lowestFreeScoringCandidatePoolEntry++;
maxUsedBestPossibleScoreList = max(maxUsedBestPossibleScoreList, bestPossibleScore);
}
if (!setPair[readWithFewerHits]->getNextLowerHit(&lastGenomeLocationForReadWithFewerHits, &lastSeedOffsetForReadWithFewerHits)) {
break;
}
} // forever (the loop that does the intersection walk)
} // For each set pair
//
// Phase 2a: mark any scoring candidates that are near enough to one another to be indels so that we can increase the score limit
// when considering them.
//
for (int whichSetPair = 0; whichSetPair < NUM_SET_PAIRS; whichSetPair++) {
//
// For every candidate, we're trying to find the candidate that's the farthest away from it in genome
// space that's still within maxDistForIndels and then mark that distance in the candidate. We do that
// by keeping two indices into the array, a bottom and top (relative to the array; the actual genome
// locations go the other way). Each pass through the loop we move one or the other. We move up top if
// bottom is one less or they're within maxDistForIndels of one another. Otherwise we move up bottom.
//
int bottom = 0;
int top = 1;
while (top < (int)lowestFreeScoringMateCandidate[whichSetPair]) {
_ASSERT(bottom < top);
_ASSERT(scoringMateCandidates[whichSetPair][bottom].readWithMoreHitsGenomeLocation > scoringMateCandidates[whichSetPair][top].readWithMoreHitsGenomeLocation); // Remember, they're in backward order.
GenomeDistance spread = DistanceBetweenGenomeLocations(scoringMateCandidates[whichSetPair][bottom].readWithMoreHitsGenomeLocation, scoringMateCandidates[whichSetPair][top].readWithMoreHitsGenomeLocation);
if (spread < maxKForIndels) {
scoringMateCandidates[whichSetPair][bottom].largestBigIndelDetected = __max(spread, scoringMateCandidates[whichSetPair][bottom].largestBigIndelDetected);
scoringMateCandidates[whichSetPair][top].largestBigIndelDetected = __max(spread, scoringMateCandidates[whichSetPair][top].largestBigIndelDetected);
#if _DEBUG
if (_DumpAlignments) {
fprintf(stderr, "Set largest big indel detected to %lld, %lld for set pair %d mate candidates %d and %d\n",
scoringMateCandidates[whichSetPair][bottom].largestBigIndelDetected, scoringMateCandidates[whichSetPair][top].largestBigIndelDetected,
whichSetPair, bottom, top);
}
#endif // DEBUG
top++;
} else if (bottom < top - 1) {
//
// Move up bottom since it will still be less than top.
//
bottom++;
} else {
//
// They're next to each other and still too far apart. Move up both.
//
bottom++;
top++;
}
} // While we're still considering candidates in one set pair.
} // for each set pair
//
// Now do the fewer end candidates. This works the same way as the loop above (except they're not segregated by set pair).
//
{ // a scope for us to declare locals in.
int bottom = 0;
int top = 1;
while (top < (int)lowestFreeScoringCandidatePoolEntry) {
_ASSERT(bottom < top);
if (scoringCandidatePool[bottom].whichSetPair != scoringCandidatePool[top].whichSetPair) {
bottom = top;
top = top + 1;
continue;
}
_ASSERT(scoringCandidatePool[bottom].readWithFewerHitsGenomeLocation > scoringCandidatePool[top].readWithFewerHitsGenomeLocation); // They're in backward order
GenomeDistance spread = DistanceBetweenGenomeLocations(scoringCandidatePool[bottom].readWithFewerHitsGenomeLocation, scoringCandidatePool[top].readWithFewerHitsGenomeLocation);
if (spread < maxKForIndels) {
// Casting spread to int is OK because it only gets there if it's less than maxKForIndels in the loop at the beginning of 2a
scoringCandidatePool[bottom].largestBigIndelDetected = __max((int)spread, scoringCandidatePool[bottom].largestBigIndelDetected);
scoringCandidatePool[top].largestBigIndelDetected = __max((int)spread, scoringCandidatePool[top].largestBigIndelDetected);
#if _DEBUG
if (_DumpAlignments) {
fprintf(stderr, "Set largest big indel to %d, %d for fewer end candidates %d and %d\n",
scoringCandidatePool[bottom].largestBigIndelDetected, scoringCandidatePool[top].largestBigIndelDetected, bottom, top);
}
#endif // DEBUG
top++;
} else if (bottom < top - 1) {
bottom++;
} else {
bottom++;
top++;
}
} // While we're still looking.
} // Scope for fewer candidate possible indel detection.
//
// Phase 3: score and merge the candidates we've found using Laundau-Vishkin (edit distance, not affine gap).
//
int currentBestPossibleScoreList = 0;
//
// Loop until we've scored all of the candidates, or proven that what's left must have too high of a score to be interesting.
//
//
while (currentBestPossibleScoreList <= maxUsedBestPossibleScoreList &&
currentBestPossibleScoreList <= extraSearchDepth + min(maxK, max( // Never look for worse than our worst interesting score
min(scoresForAllAlignments.bestPairScore, scoresForNonAltAlignments.bestPairScore - maxScoreGapToPreferNonAltAlignment), // Worst we care about for ALT
min(scoresForAllAlignments.bestPairScore + maxScoreGapToPreferNonAltAlignment, scoresForNonAltAlignments.bestPairScore)))) // And for non-ALT
{
if (scoringCandidates[currentBestPossibleScoreList] == NULL) {
//
// No more candidates on this list. Skip to the next one.
//
currentBestPossibleScoreList++;
continue;
}
//
// Grab the first candidate on the highest list and score it.
//
ScoringCandidate *candidate = scoringCandidates[currentBestPossibleScoreList];
int fewerEndScore;
double fewerEndMatchProbability;
int fewerEndGenomeLocationOffset;
bool nonALTAlignment = (!altAwareness) || !genome->isGenomeLocationALT(candidate->readWithFewerHitsGenomeLocation);
int scoreLimit = computeScoreLimit(nonALTAlignment, &scoresForAllAlignments, &scoresForNonAltAlignments, candidate->largestBigIndelDetected);
if (currentBestPossibleScoreList > scoreLimit) {
//
// Remove us from the head of the list and proceed to the next candidate to score. We can get here because now we know ALT/non-ALT, which have different limits.
//
scoringCandidates[currentBestPossibleScoreList] = candidate->scoreListNext;
continue;
}
scoreLocation(readWithFewerHits, setPairDirection[candidate->whichSetPair][readWithFewerHits], candidate->readWithFewerHitsGenomeLocation,
candidate->seedOffset, scoreLimit, &fewerEndScore, &fewerEndMatchProbability, &fewerEndGenomeLocationOffset, &candidate->usedAffineGapScoring,
&candidate->basesClippedBefore, &candidate->basesClippedAfter, &candidate->agScore, &candidate->lvIndels, &candidate->usedGaplessClipping, &candidate->refSpan);
#if INSTRUMENTATION_FOR_PAPER
nScored++;
#endif // INSTRUMENTATION_FOR_PAPER
candidate->matchProbability = fewerEndMatchProbability;
_ASSERT(ScoreAboveLimit == fewerEndScore || fewerEndScore >= candidate->bestPossibleScore);
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Scored fewer end candidate %d, set pair %d, read %d, location %s:%llu, seed offset %d, score limit %d, score %d, offset %d, agScore %d, matchProb %e\n",
(int)(candidate - scoringCandidatePool),
candidate->whichSetPair, readWithFewerHits,
genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation)->name,
candidate->readWithFewerHitsGenomeLocation - genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation)->beginningLocation,
candidate->seedOffset,
scoreLimit, fewerEndScore, fewerEndGenomeLocationOffset, candidate->agScore, fewerEndMatchProbability);
}
#endif // DEBUG
if (fewerEndScore != ScoreAboveLimit) {
//
// Find and score mates. The index in scoringMateCandidateIndex is the lowest mate (i.e., the highest index number).
//
unsigned mateIndex = candidate->scoringMateCandidateIndex;
for (;;) {
ScoringMateCandidate *mate = &scoringMateCandidates[candidate->whichSetPair][mateIndex];
scoreLimit = computeScoreLimit(nonALTAlignment, &scoresForAllAlignments, &scoresForNonAltAlignments, __max(mate->largestBigIndelDetected, __min(candidate->largestBigIndelDetected, fewerEndScore)));
_ASSERT(genomeLocationIsWithin(mate->readWithMoreHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation, maxSpacing));
//
// Exclude it if it's strictly smaller than minSpacing; hence, minSpacing - 1.
//
if (!genomeLocationIsWithin(mate->readWithMoreHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation, minSpacing - 1) && ((mate->bestPossibleScore <= scoreLimit - fewerEndScore))) {
//
// It's within the range and not necessarily too poor of a match. Consider it.
//
//
// If we haven't yet scored this mate, or we've scored it and not gotten an answer, but had a lower score limit than we'd
// use now, score it.
//
int mateScoreLimit = scoreLimit - fewerEndScore;
if (mate->score == ScoringMateCandidate::LocationNotYetScored || (mate->score == ScoreAboveLimit && mate->scoreLimit < scoreLimit - fewerEndScore)) {
scoreLocation(readWithMoreHits, setPairDirection[candidate->whichSetPair][readWithMoreHits], GenomeLocationAsInt64(mate->readWithMoreHitsGenomeLocation),
mate->seedOffset, mateScoreLimit, &mate->score, &mate->matchProbability,
&mate->genomeOffset, &mate->usedAffineGapScoring, &mate->basesClippedBefore, &mate->basesClippedAfter, &mate->agScore, &mate->lvIndels, &mate->usedGaplessClipping, &mate->refSpan);
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Scored mate candidate %d, set pair %d, read %d, location %s:%llu, seed offset %d, score limit %d, score %d, offset %d, agScore %d, matchProb %e\n",
(int)(mate - scoringMateCandidates[candidate->whichSetPair]), candidate->whichSetPair, readWithMoreHits,
genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation)->name,
mate->readWithMoreHitsGenomeLocation - genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation)->beginningLocation,
mate->seedOffset, mateScoreLimit, mate->score, mate->genomeOffset, mate->agScore, mate->matchProbability);
}
#endif // _DEBUG
#if INSTRUMENTATION_FOR_PAPER
nScored++;
#endif // INSTRUMENTATION_FOR_PAPER
_ASSERT(ScoreAboveLimit == mate->score || mate->score >= mate->bestPossibleScore);
mate->scoreLimit = scoreLimit - fewerEndScore;
}
if (mate->score != ScoreAboveLimit && (fewerEndScore + mate->score <= scoreLimit)) { // We need to check to see that we're below scoreLimit because we may have scored this earlier when scoreLimit was higher.
double pairProbability = mate->matchProbability * fewerEndMatchProbability;
int pairScore = mate->score + fewerEndScore;
int pairAGScore = mate->agScore + candidate->agScore;
//
// See if this should be ignored as a merge, or if we need to back out a previously scored location
// because it's a worse version of this location.
//
MergeAnchor *mergeAnchor = candidate->mergeAnchor;
if (NULL == mergeAnchor) {
//
// Look up and down the array of candidates to see if we have possible merge candidates.
//
for (ScoringCandidate *mergeCandidate = candidate - 1;
mergeCandidate >= scoringCandidatePool &&
genomeLocationIsWithin(mergeCandidate->readWithFewerHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset, 50) &&
mergeCandidate->whichSetPair == candidate->whichSetPair;
mergeCandidate--) {
if (mergeCandidate->mergeAnchor != NULL) {
candidate->mergeAnchor = mergeAnchor = mergeCandidate->mergeAnchor;
break;
}
}
if (NULL == mergeAnchor) {
for (ScoringCandidate *mergeCandidate = candidate + 1;
mergeCandidate < scoringCandidatePool + lowestFreeScoringCandidatePoolEntry &&
genomeLocationIsWithin(mergeCandidate->readWithFewerHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset, 50) &&
mergeCandidate->whichSetPair == candidate->whichSetPair;
mergeCandidate++) {
if (mergeCandidate->mergeAnchor != NULL) {
candidate->mergeAnchor = mergeAnchor = mergeCandidate->mergeAnchor;
break;
}
}
}
}
bool eliminatedByMerge; // Did we merge away this result. If this is false, we may still have merged away a previous result.
double oldPairProbability;
bool mergeReplacement = false; // Did we replace the anchor with the new candidate ?
if (NULL == mergeAnchor) {
if (firstFreeMergeAnchor >= mergeAnchorPoolSize) {
WriteErrorMessage("Ran out of merge anchor pool entries. Perhaps rerunning with a larger value of -mcp will help\n");
soft_exit(1);
}
mergeAnchor = &mergeAnchorPool[firstFreeMergeAnchor];
firstFreeMergeAnchor++;
mergeAnchor->init(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset,
pairProbability, pairScore, pairAGScore);
eliminatedByMerge = false;
oldPairProbability = 0;
candidate->mergeAnchor = mergeAnchor;
} else {
eliminatedByMerge = mergeAnchor->checkMerge(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset,
pairProbability, pairScore, pairAGScore, &oldPairProbability, &mergeReplacement);
}
if (!eliminatedByMerge) {
//
// Back out the probability of the old match that we're merged with, if any. The max
// is necessary because a + b - b is not necessarily a in floating point. If there
// was no merge, the oldPairProbability is 0.
//
scoresForAllAlignments.updateProbabilityOfAllPairs(oldPairProbability);
if (nonALTAlignment) {
scoresForNonAltAlignments.updateProbabilityOfAllPairs(oldPairProbability);
}
if (pairProbability > scoresForAllAlignments.probabilityOfBestPair && maxEditDistanceForSecondaryResults != -1 && maxEditDistanceForSecondaryResults >= scoresForAllAlignments.bestPairScore - pairScore) {
//
// Move the old best to be a secondary alignment. This won't happen on the first time we get a valid alignment,
// because bestPairScore is initialized to be very large.
//
//
if (*nSecondaryResults >= secondaryResultBufferSize) {
*nSecondaryResults = secondaryResultBufferSize + 1;
return false;
}
PairedAlignmentResult *secondaryResult = &secondaryResults[*nSecondaryResults];
secondaryResult->alignedAsPair = true;
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
secondaryResult->direction[r] = scoresForAllAlignments.bestResultDirection[r];
secondaryResult->location[r] = scoresForAllAlignments.bestResultGenomeLocation[r];
secondaryResult->origLocation[r] = scoresForAllAlignments.bestResultOrigGenomeLocation[r];
secondaryResult->mapq[r] = 0;
secondaryResult->score[r] = scoresForAllAlignments.bestResultScore[r];
secondaryResult->status[r] = MultipleHits;
secondaryResult->usedAffineGapScoring[r] = scoresForAllAlignments.bestResultUsedAffineGapScoring[r];
secondaryResult->basesClippedBefore[r] = scoresForAllAlignments.bestResultBasesClippedBefore[r];
secondaryResult->basesClippedAfter[r] = scoresForAllAlignments.bestResultBasesClippedAfter[r];
secondaryResult->agScore[r] = scoresForAllAlignments.bestResultAGScore[r];
secondaryResult->seedOffset[r] = scoresForAllAlignments.bestResultSeedOffset[r];
secondaryResult->popularSeedsSkipped[r] = popularSeedsSkipped[r];
secondaryResult->lvIndels[r] = scoresForAllAlignments.bestResultLVIndels[r];
secondaryResult->matchProbability[r] = scoresForAllAlignments.bestResultMatchProbability[r];
secondaryResult->usedGaplessClipping[r] = scoresForAllAlignments.bestResultUsedGaplessClipping[r];
secondaryResult->refSpan[r] = scoresForAllAlignments.bestResultRefSpan[r];
}
(*nSecondaryResults)++;
} // If we're saving the old best score as a secondary result
if (!mergeReplacement && (pairProbability > scoresForAllAlignments.probabilityOfBestPair) && (maxLVCandidatesForAffineGapBufferSize > 0) && (extraSearchDepth >= scoresForAllAlignments.bestPairScore - pairScore)) {
//
// This is close enough that scoring it with affine gap scoring might make it be the best result. Save it for possible consideration in phase 4.
//
if (*nLVCandidatesForAffineGap >= maxLVCandidatesForAffineGapBufferSize) {
*nLVCandidatesForAffineGap = maxLVCandidatesForAffineGapBufferSize + 1;
return false;
}
PairedAlignmentResult *agResult = &lvCandidatesForAffineGap[*nLVCandidatesForAffineGap];
agResult->alignedAsPair = true;
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
agResult->direction[r] = scoresForAllAlignments.bestResultDirection[r];
agResult->location[r] = scoresForAllAlignments.bestResultGenomeLocation[r];
agResult->origLocation[r] = scoresForAllAlignments.bestResultOrigGenomeLocation[r];
agResult->mapq[r] = 0;
agResult->score[r] = scoresForAllAlignments.bestResultScore[r];
agResult->status[r] = MultipleHits;
agResult->usedAffineGapScoring[r] = scoresForAllAlignments.bestResultUsedAffineGapScoring[r];
agResult->basesClippedBefore[r] = scoresForAllAlignments.bestResultBasesClippedBefore[r];
agResult->basesClippedAfter[r] = scoresForAllAlignments.bestResultBasesClippedAfter[r];
agResult->agScore[r] = scoresForAllAlignments.bestResultAGScore[r];
agResult->seedOffset[r] = scoresForAllAlignments.bestResultSeedOffset[r];
agResult->popularSeedsSkipped[r] = popularSeedsSkipped[r];
agResult->lvIndels[r] = scoresForAllAlignments.bestResultLVIndels[r];
agResult->matchProbability[r] = scoresForAllAlignments.bestResultMatchProbability[r];
agResult->usedGaplessClipping[r] = scoresForAllAlignments.bestResultUsedGaplessClipping[r];
agResult->refSpan[r] = scoresForAllAlignments.bestResultRefSpan[r];
}
(*nLVCandidatesForAffineGap)++;
} // if not eliminatedByMerge
if (nonALTAlignment) {
scoresForNonAltAlignments.updateBestHitIfNeeded(pairScore, pairAGScore, pairProbability, fewerEndScore, readWithMoreHits, fewerEndGenomeLocationOffset, candidate, mate);
}
bool updatedBestScore = scoresForAllAlignments.updateBestHitIfNeeded(pairScore, pairAGScore, pairProbability, fewerEndScore, readWithMoreHits, fewerEndGenomeLocationOffset, candidate, mate);
#if INSTRUMENTATION_FOR_PAPER
if (updatedBestScore) {
bestCandidateScoredFirst = nScored == 2;
}
#endif // INSTRUMENTATION_FOR_PAPER
// scoreLimit = computeScoreLimit(nonALTAlignment, &scoresForAllAlignments, &scoresForNonAltAlignments);
if ((!updatedBestScore) && maxEditDistanceForSecondaryResults != -1 && (pairScore <= (maxK + extraSearchDepth)) && maxEditDistanceForSecondaryResults >= pairScore - scoresForAllAlignments.bestPairScore) {
//
// A secondary result to save.
//
if (*nSecondaryResults >= secondaryResultBufferSize) {
*nSecondaryResults = secondaryResultBufferSize + 1;
return false;
}
PairedAlignmentResult *result = &secondaryResults[*nSecondaryResults];
result->alignedAsPair = true;
result->direction[readWithMoreHits] = setPairDirection[candidate->whichSetPair][readWithMoreHits];
result->direction[readWithFewerHits] = setPairDirection[candidate->whichSetPair][readWithFewerHits];
result->location[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation + mate->genomeOffset;
result->location[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset;
result->origLocation[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation;
result->origLocation[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation;
result->mapq[0] = result->mapq[1] = 0;
result->score[readWithMoreHits] = mate->score;
result->score[readWithFewerHits] = fewerEndScore;
result->status[readWithFewerHits] = result->status[readWithMoreHits] = MultipleHits;
result->usedAffineGapScoring[readWithMoreHits] = mate->usedAffineGapScoring;
result->usedAffineGapScoring[readWithFewerHits] = candidate->usedAffineGapScoring;
result->usedGaplessClipping[readWithMoreHits] = mate->usedGaplessClipping;
result->usedGaplessClipping[readWithFewerHits] = candidate->usedGaplessClipping;
result->basesClippedBefore[readWithFewerHits] = candidate->basesClippedBefore;
result->basesClippedAfter[readWithFewerHits] = candidate->basesClippedAfter;
result->basesClippedBefore[readWithMoreHits] = mate->basesClippedBefore;
result->basesClippedAfter[readWithMoreHits] = mate->basesClippedAfter;
result->agScore[readWithMoreHits] = mate->agScore;
result->agScore[readWithFewerHits] = candidate->agScore;
result->seedOffset[readWithMoreHits] = mate->seedOffset;
result->seedOffset[readWithFewerHits] = candidate->seedOffset;
result->lvIndels[readWithMoreHits] = mate->lvIndels;
result->lvIndels[readWithFewerHits] = candidate->lvIndels;
result->matchProbability[readWithMoreHits] = mate->matchProbability;
result->matchProbability[readWithFewerHits] = candidate->matchProbability;
result->popularSeedsSkipped[readWithMoreHits] = popularSeedsSkipped[readWithMoreHits];
result->popularSeedsSkipped[readWithFewerHits] = popularSeedsSkipped[readWithFewerHits];
(*nSecondaryResults)++;
}
if ((!updatedBestScore) && maxLVCandidatesForAffineGapBufferSize > 0 && (pairScore <= (maxK + extraSearchDepth)) && (extraSearchDepth >= pairScore - scoresForAllAlignments.bestPairScore)) {
if (*nLVCandidatesForAffineGap >= maxLVCandidatesForAffineGapBufferSize) {
*nLVCandidatesForAffineGap = maxLVCandidatesForAffineGapBufferSize + 1;
return false;
}
PairedAlignmentResult *result = &lvCandidatesForAffineGap[*nLVCandidatesForAffineGap];
result->alignedAsPair = true;
result->direction[readWithMoreHits] = setPairDirection[candidate->whichSetPair][readWithMoreHits];
result->direction[readWithFewerHits] = setPairDirection[candidate->whichSetPair][readWithFewerHits];
result->location[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation + mate->genomeOffset;
result->location[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset;
result->origLocation[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation;
result->origLocation[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation;
result->mapq[0] = result->mapq[1] = 0;
result->score[readWithMoreHits] = mate->score;
result->score[readWithFewerHits] = fewerEndScore;
result->status[readWithFewerHits] = result->status[readWithMoreHits] = MultipleHits;
result->usedAffineGapScoring[readWithMoreHits] = mate->usedAffineGapScoring;
result->usedAffineGapScoring[readWithFewerHits] = candidate->usedAffineGapScoring;
result->usedGaplessClipping[readWithMoreHits] = mate->usedGaplessClipping;
result->usedGaplessClipping[readWithFewerHits] = candidate->usedGaplessClipping;
result->basesClippedBefore[readWithFewerHits] = candidate->basesClippedBefore;
result->basesClippedAfter[readWithFewerHits] = candidate->basesClippedAfter;
result->basesClippedBefore[readWithMoreHits] = mate->basesClippedBefore;
result->basesClippedAfter[readWithMoreHits] = mate->basesClippedAfter;
result->agScore[readWithMoreHits] = mate->agScore;
result->agScore[readWithFewerHits] = candidate->agScore;
result->seedOffset[readWithMoreHits] = mate->seedOffset;
result->seedOffset[readWithFewerHits] = candidate->seedOffset;
result->lvIndels[readWithMoreHits] = mate->lvIndels;
result->lvIndels[readWithFewerHits] = candidate->lvIndels;
result->matchProbability[readWithMoreHits] = mate->matchProbability;
result->matchProbability[readWithFewerHits] = candidate->matchProbability;
result->popularSeedsSkipped[readWithMoreHits] = popularSeedsSkipped[readWithMoreHits];
result->popularSeedsSkipped[readWithFewerHits] = popularSeedsSkipped[readWithFewerHits];
(*nLVCandidatesForAffineGap)++;
}
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Added %e (= %e * %e) @ (%s:%llu, %s:%llu), giving new probability of all pairs %e, score %d = %d + %d, agScore %d = %d + %d%s\n",
pairProbability, mate->matchProbability , fewerEndMatchProbability,
genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation.location + fewerEndGenomeLocationOffset)->name,
(candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset) - genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation.location + fewerEndGenomeLocationOffset)->beginningLocation,
genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset)->name,
(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset) - genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation.location + mate->genomeOffset)->beginningLocation,
scoresForNonAltAlignments.probabilityOfAllPairs,
pairScore, fewerEndScore, mate->score, candidate->agScore + mate->agScore, candidate->agScore, mate->agScore, updatedBestScore ? " New best hit" : "");
}
#endif // _DEBUG
if ((altAwareness ? scoresForNonAltAlignments.probabilityOfAllPairs : scoresForAllAlignments.probabilityOfAllPairs) >= 4.9 && -1 == maxEditDistanceForSecondaryResults) {
//
// Nothing will rescue us from a 0 MAPQ, so just stop looking.
//
goto doneScoring;
}
}
}// if the mate has a non -1 score
}
if (mateIndex == 0 || !genomeLocationIsWithin(scoringMateCandidates[candidate->whichSetPair][mateIndex-1].readWithMoreHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation, maxSpacing)) {
//
// Out of mate candidates.
//
break;
}
mateIndex--;
}
}
//
// Remove us from the head of the list and proceed to the next candidate to score.
//
scoringCandidates[currentBestPossibleScoreList] = candidate->scoreListNext;
}
doneScoring:
ScoreSet* scoreSetToEmit;
if ((!altAwareness) || scoresForNonAltAlignments.bestPairScore > scoresForAllAlignments.bestPairScore + maxScoreGapToPreferNonAltAlignment) {
scoreSetToEmit = &scoresForAllAlignments;
} else {
scoreSetToEmit = &scoresForNonAltAlignments;
}
if (scoreSetToEmit->bestPairScore == TooBigScoreValue) {
//
// Found nothing.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
result->location[whichRead] = InvalidGenomeLocation;
result->origLocation[whichRead] = InvalidGenomeLocation;
result->mapq[whichRead] = 0;
result->score[whichRead] = ScoreAboveLimit;
result->status[whichRead] = NotFound;
result->clippingForReadAdjustment[whichRead] = 0;
result->usedAffineGapScoring[whichRead] = false;
result->usedGaplessClipping[whichRead] = false;
result->basesClippedBefore[whichRead] = 0;
result->basesClippedAfter[whichRead] = 0;
result->agScore[whichRead] = ScoreAboveLimit;
result->seedOffset[whichRead] = 0;
result->lvIndels[whichRead] = 0;
result->popularSeedsSkipped[whichRead] = popularSeedsSkipped[whichRead];
result->matchProbability[whichRead] = 0.0;
firstALTResult->status[whichRead] = NotFound;
#ifdef _DEBUG
if (_DumpAlignments) {
printf("No sufficiently good pairs found.\n");
}
#endif // DEBUG
}
result->probabilityAllPairs = 0.0;
} else {
scoreSetToEmit->fillInResult(result, popularSeedsSkipped);
if (altAwareness && scoreSetToEmit == &scoresForNonAltAlignments &&
(scoresForAllAlignments.bestResultGenomeLocation[0] != scoresForNonAltAlignments.bestResultGenomeLocation[0] ||
scoresForAllAlignments.bestResultGenomeLocation[1] != scoresForNonAltAlignments.bestResultGenomeLocation[1]))
{
_ASSERT(genome->isGenomeLocationALT(scoresForAllAlignments.bestResultGenomeLocation[0]));
scoresForAllAlignments.fillInResult(firstALTResult, popularSeedsSkipped);
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++)
{
firstALTResult->supplementary[whichRead] = true;
}
} else {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++)
{
firstALTResult->status[whichRead] = NotFound;
}
}
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Returned %s:%llu %s %s:%llu %s with MAPQ %d and %d, probability of all pairs %e, probability of best pair %e, pair score %d\n",
genome->getContigAtLocation(result->location[0])->name, result->location[0] - genome->getContigAtLocation(result->location[0])->beginningLocation,
result->direction[0] == RC ? "RC" : "",
genome->getContigAtLocation(result->location[1])->name, result->location[1] - genome->getContigAtLocation(result->location[1])->beginningLocation,
result->direction[1] == RC ? "RC" : "", result->mapq[0], result->mapq[1], scoreSetToEmit->probabilityOfAllPairs, scoreSetToEmit->probabilityOfBestPair,
scoreSetToEmit->bestPairScore);
if (firstALTResult->status[0] != NotFound) {
printf("Returned first ALT Result %s:%llu %s %s:%llu %s with MAPQ %d and %d, probability of all pairs %e, probability of best pair %e, pair score %d\n",
genome->getContigAtLocation(firstALTResult->location[0])->name, firstALTResult->location[0] - genome->getContigAtLocation(firstALTResult->location[0])->beginningLocation,
firstALTResult->direction[0] == RC ? "RC" : "",
genome->getContigAtLocation(firstALTResult->location[1])->name, firstALTResult->location[1] - genome->getContigAtLocation(firstALTResult->location[1])->beginningLocation,
firstALTResult->direction[1] == RC ? "RC" : "", firstALTResult->mapq[0], firstALTResult->mapq[1], scoresForAllAlignments.probabilityOfAllPairs, scoresForAllAlignments.probabilityOfBestPair,
scoresForAllAlignments.bestPairScore);
} // If we're also returning an ALT result
}
#endif // DEBUG
}
//
// Get rid of any secondary results that are too far away from the best score. (NB: the rest of the code in align() is very similar to BaseAligner::finalizeSecondaryResults. Sorry)
//
Read *inputReads[2] = { read0, read1 };
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
result->scorePriorToClipping[whichRead] = result->score[whichRead];
}
if (!ignoreAlignmentAdjustmentsForOm) {
//
// Start by adjusting the alignments.
//
alignmentAdjuster.AdjustAlignments(inputReads, result);
if (result->status[0] != NotFound && result->status[1] != NotFound && !ignoreAlignmentAdjustmentsForOm) {
scoreSetToEmit->bestPairScore = result->score[0] + result->score[1];
}
for (int i = 0; i < *nSecondaryResults; i++) {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
secondaryResults[i].scorePriorToClipping[whichRead] = secondaryResults[i].score[whichRead];
}
alignmentAdjuster.AdjustAlignments(inputReads, &secondaryResults[i]);
if (secondaryResults[i].status[0] != NotFound && secondaryResults[i].status[1] != NotFound && !ignoreAlignmentAdjustmentsForOm) {
scoreSetToEmit->bestPairScore = __min(scoreSetToEmit->bestPairScore, secondaryResults[i].score[0] + secondaryResults[i].score[1]);
}
}
} else {
for (int i = 0; i < *nSecondaryResults; i++) {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
secondaryResults[i].scorePriorToClipping[whichRead] = secondaryResults[i].score[whichRead];
}
}
}
int i = 0;
while (i < *nSecondaryResults) {
if ((int)(secondaryResults[i].score[0] + secondaryResults[i].score[1]) >(int)scoreSetToEmit->bestPairScore + maxEditDistanceForSecondaryResults ||
secondaryResults[i].status[0] == NotFound || secondaryResults[i].status[1] == NotFound) {
secondaryResults[i] = secondaryResults[(*nSecondaryResults) - 1];
(*nSecondaryResults)--;
} else {
i++;
}
}
//
// Now check to see if there are too many for any particular contig.
//
if (maxSecondaryAlignmentsPerContig > 0 && result->status[0] != NotFound) {
//
// Run through the results and count the number of results per contig, to see if any of them are too big.
// First, record the primary result.
//
bool anyContigHasTooManyResults = false;
contigCountEpoch++;
int primaryContigNum = genome->getContigNumAtLocation(result->location[0]);
hitsPerContigCounts[primaryContigNum].hits = 1;
hitsPerContigCounts[primaryContigNum].epoch = contigCountEpoch;
for (i = 0; i < *nSecondaryResults; i++) {
int contigNum = genome->getContigNumAtLocation(secondaryResults[i].location[0]); // We know they're on the same contig, so either will do
if (hitsPerContigCounts[contigNum].epoch != contigCountEpoch) {
hitsPerContigCounts[contigNum].epoch = contigCountEpoch;
hitsPerContigCounts[contigNum].hits = 0;
}
hitsPerContigCounts[contigNum].hits++;
if (hitsPerContigCounts[contigNum].hits > maxSecondaryAlignmentsPerContig) {
anyContigHasTooManyResults = true;
break;
}
}
if (anyContigHasTooManyResults) {
//
// Just sort them all, in order of contig then hit depth.
//
qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), PairedAlignmentResult::compareByContigAndScore);
//
// Now run through and eliminate any contigs with too many hits. We can't use the same trick at the first loop above, because the
// counting here relies on the results being sorted. So, instead, we just copy them as we go.
//
int currentContigNum = -1;
int currentContigCount = 0;
int destResult = 0;
for (int sourceResult = 0; sourceResult < *nSecondaryResults; sourceResult++) {
int contigNum = genome->getContigNumAtLocation(secondaryResults[sourceResult].location[0]);
if (contigNum != currentContigNum) {
currentContigNum = contigNum;
currentContigCount = (contigNum == primaryContigNum) ? 1 : 0;
}
currentContigCount++;
if (currentContigCount <= maxSecondaryAlignmentsPerContig) {
//
// Keep it. If we don't get here, then we don't copy the result and
// don't increment destResult. And yes, this will sometimes copy a
// result over itself. That's harmless.
//
secondaryResults[destResult] = secondaryResults[sourceResult];
destResult++;
}
} // for each source result
*nSecondaryResults = destResult;
}
} // if we're limiting by contig
if (*nSecondaryResults > maxSecondaryResultsToReturn) {
qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), PairedAlignmentResult::compareByScore);
*nSecondaryResults = maxSecondaryResultsToReturn; // Just truncate it
}
#if INSTRUMENTATION_FOR_PAPER
_int64 runTime = timeInNanos() - startTime;
if (runTime >= 0) { // Really don't understand why timeInNanos() sometimes produces garbage, but it does.
InterlockedAdd64AndReturnNewValue(&g_alignmentCountByHitCountsOfEachSeed[log2HashTableHits[0]][log2HashTableHits[1]], 1);
InterlockedAdd64AndReturnNewValue(&g_alignmentTimeByHitCountsOfEachSeed[log2HashTableHits[0]][log2HashTableHits[1]], runTime);
InterlockedAdd64AndReturnNewValue(&g_scoreCountByHitCountsOfEachSeed[log2HashTableHits[0]][log2HashTableHits[1]], nScored);
InterlockedAdd64AndReturnNewValue(&g_setIntersectionSizeByHitCountsOfEachSeed[log2HashTableHits[0]][log2HashTableHits[1]], setIntersectionSize);
if (__min(hashTableHits[0], hashTableHits[1]) > 0) {
InterlockedAdd64AndReturnNewValue(&g_100xtotalRatioOfSetIntersectionSizeToSmallerSeedHitCountByCountsOfEachSeed[log2HashTableHits[0]][log2HashTableHits[1]],
(100 * setIntersectionSize) / __min(hashTableHits[0], hashTableHits[1]));
}
InterlockedAdd64AndReturnNewValue(&g_totalSizeOfSmallerHitSet, __min(hashTableHits[0], hashTableHits[1]));
InterlockedAdd64AndReturnNewValue(&g_totalSizeOfSetIntersection, setIntersectionSize);
}
if (nScored > 2) {
InterlockedAdd64AndReturnNewValue(&g_alignmentsWithMoreThanOneCandidate, 1);
if (bestCandidateScoredFirst) {
InterlockedAdd64AndReturnNewValue(&g_alignmentsWithMoreThanOneCandidateWhereTheBestCandidateIsScoredFirst, 1);
}
}
#endif // INSTRUMENTATION_FOR_PAPER
return true;
}
//
// This code borrows heavily from alignLandauVishkin. TODO: Refactor
//
bool
IntersectingPairedEndAligner::alignHamming(
Read * read0,
Read * read1,
PairedAlignmentResult * result,
PairedAlignmentResult * firstALTResult,
int maxEditDistanceForSecondaryResults,
_int64 secondaryResultBufferSize,
_int64 * nSecondaryResults,
PairedAlignmentResult * secondaryResults, // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by align()
_int64 singleSecondaryBufferSize,
_int64 maxSecondaryResultsToReturn,
_int64 * nSingleEndSecondaryResultsForFirstRead,
_int64 * nSingleEndSecondaryResultsForSecondRead,
SingleAlignmentResult * singleEndSecondaryResults, // Single-end secondary alignments for when the paired-end alignment didn't work properly
_int64 maxLVCandidatesForAffineGapBufferSize,
_int64 * nLVCandidatesForAffineGap,
PairedAlignmentResult * lvCandidatesForAffineGap
)
{
firstALTResult->status[0] = firstALTResult->status[1] = NotFound;
result->nLVCalls = 0;
result->nSmallHits = 0;
result->clippingForReadAdjustment[0] = result->clippingForReadAdjustment[1] = 0;
result->usedAffineGapScoring[0] = result->usedAffineGapScoring[1] = false;
result->basesClippedBefore[0] = result->basesClippedBefore[1] = 0;
result->basesClippedAfter[0] = result->basesClippedAfter[1] = 0;
result->agScore[0] = result->agScore[1] = 0;
result->usedGaplessClipping[0] = result->usedGaplessClipping[1] = false;
*nSecondaryResults = 0;
*nSingleEndSecondaryResultsForFirstRead = 0;
*nSingleEndSecondaryResultsForSecondRead = 0;
*nLVCandidatesForAffineGap = 0;
int maxSeeds;
if (numSeedsFromCommandLine != 0) {
maxSeeds = (int)numSeedsFromCommandLine;
}
else {
maxSeeds = (int)(max(read0->getDataLength(), read1->getDataLength()) * seedCoverage / index->getSeedLength());
}
#ifdef _DEBUG
if (_DumpAlignments) {
printf("\nHamming: IntersectingAligner aligning reads '%*.s' and '%.*s' with data '%.*s' and '%.*s'\n", read0->getIdLength(), read0->getId(), read1->getIdLength(), read1->getId(), read0->getDataLength(), read0->getData(), read1->getDataLength(), read1->getData());
}
#endif // _DEBUG
lowestFreeScoringCandidatePoolEntry = 0;
for (int k = 0; k <= maxK + extraSearchDepth; k++) {
scoringCandidates[k] = NULL;
}
for (unsigned i = 0; i < NUM_SET_PAIRS; i++) {
lowestFreeScoringMateCandidate[i] = 0;
}
firstFreeMergeAnchor = 0;
Read rcReads[NUM_READS_PER_PAIR];
ScoreSet scoresForAllAlignments;
ScoreSet scoresForNonAltAlignments;
unsigned popularSeedsSkipped[NUM_READS_PER_PAIR];
reads[0][FORWARD] = read0;
reads[1][FORWARD] = read1;
//
// Don't bother if one or both reads are too short. The minimum read length here is the seed length, but usually there's a longer
// minimum enforced by our caller
//
if (read0->getDataLength() < seedLen || read1->getDataLength() < seedLen) {
return true;
}
//
// Build the RC reads.
//
unsigned countOfNs = 0;
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
Read* read = reads[whichRead][FORWARD];
readLen[whichRead] = read->getDataLength();
popularSeedsSkipped[whichRead] = 0;
countOfHashTableLookups[whichRead] = 0;
#if 0
hitLocations[whichRead]->clear();
mateHitLocations[whichRead]->clear();
#endif // 0
for (Direction dir = FORWARD; dir < NUM_DIRECTIONS; dir++) {
totalHashTableHits[whichRead][dir] = 0;
largestHashTableHit[whichRead][dir] = 0;
hashTableHitSets[whichRead][dir]->init();
}
if (readLen[whichRead] > maxReadSize) {
WriteErrorMessage("IntersectingPairedEndAligner:: got too big read (%d > %d)\n"
"Change MAX_READ_LENTH at the beginning of Read.h and recompile.\n", readLen[whichRead], maxReadSize);
soft_exit(1);
}
for (unsigned i = 0; i < reads[whichRead][FORWARD]->getDataLength(); i++) {
rcReadData[whichRead][i] = rcTranslationTable[read->getData()[readLen[whichRead] - i - 1]];
rcReadQuality[whichRead][i] = read->getQuality()[readLen[whichRead] - i - 1];
countOfNs += nTable[read->getData()[i]];
}
reads[whichRead][RC] = &rcReads[whichRead];
reads[whichRead][RC]->init(read->getId(), read->getIdLength(), rcReadData[whichRead], rcReadQuality[whichRead], read->getDataLength(), read->getFASTQComment(), read->getFASTQCommentLength());
}
if ((int)countOfNs > maxK) {
return true;
}
//
// Build the reverse data for both reads in both directions for the backwards LV to use.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
for (Direction dir = 0; dir < NUM_DIRECTIONS; dir++) {
Read* read = reads[whichRead][dir];
for (unsigned i = 0; i < read->getDataLength(); i++) {
reversedRead[whichRead][dir][i] = read->getData()[read->getDataLength() - i - 1];
}
}
}
unsigned thisPassSeedsNotSkipped[NUM_READS_PER_PAIR][NUM_DIRECTIONS] = { {0,0}, {0,0} };
//
// Initialize the member variables that are effectively stack locals, but are in the object
// to avoid having to pass them to score.
//
localBestPairProbability[0] = 0;
localBestPairProbability[1] = 0;
//
// Phase 1: do the hash table lookups for each of the seeds for each of the reads and add them to the hit sets.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
int nextSeedToTest = 0;
unsigned wrapCount = 0;
int nPossibleSeeds = (int)readLen[whichRead] - seedLen + 1;
memset(seedUsed, 0, (__max(readLen[0], readLen[1]) + 7) / 8);
bool beginsDisjointHitSet[NUM_DIRECTIONS] = { true, true };
while (countOfHashTableLookups[whichRead] < nPossibleSeeds && countOfHashTableLookups[whichRead] < maxSeeds) {
if (nextSeedToTest >= nPossibleSeeds) {
wrapCount++;
beginsDisjointHitSet[FORWARD] = beginsDisjointHitSet[RC] = true;
if (wrapCount >= seedLen) {
//
// There aren't enough valid seeds in this read to reach our target.
//
break;
}
nextSeedToTest = GetWrappedNextSeedToTest(seedLen, wrapCount);
}
while (nextSeedToTest < nPossibleSeeds && IsSeedUsed(nextSeedToTest)) {
//
// This seed is already used. Try the next one.
//
nextSeedToTest++;
}
if (nextSeedToTest >= nPossibleSeeds) {
//
// Unusable seeds have pushed us past the end of the read. Go back around the outer loop so we wrap properly.
//
continue;
}
SetSeedUsed(nextSeedToTest);
if (!Seed::DoesTextRepresentASeed(reads[whichRead][FORWARD]->getData() + nextSeedToTest, seedLen)) {
//
// It's got Ns in it, so just skip it.
//
nextSeedToTest++;
continue;
}
Seed seed(reads[whichRead][FORWARD]->getData() + nextSeedToTest, seedLen);
//
// Find all instances of this seed in the genome.
//
_int64 nHits[NUM_DIRECTIONS];
const GenomeLocation* hits[NUM_DIRECTIONS];
const unsigned* hits32[NUM_DIRECTIONS];
if (doesGenomeIndexHave64BitLocations) {
index->lookupSeed(seed, &nHits[FORWARD], &hits[FORWARD], &nHits[RC], &hits[RC],
hashTableHitSets[whichRead][FORWARD]->getNextSingletonLocation(), hashTableHitSets[whichRead][RC]->getNextSingletonLocation());
} else {
index->lookupSeed32(seed, &nHits[FORWARD], &hits32[FORWARD], &nHits[RC], &hits32[RC]);
}
countOfHashTableLookups[whichRead]++;
for (Direction dir = FORWARD; dir < NUM_DIRECTIONS; dir++) {
int offset;
if (dir == FORWARD) {
offset = nextSeedToTest;
} else {
offset = readLen[whichRead] - seedLen - nextSeedToTest;
}
if (nHits[dir] < maxBigHits) {
totalHashTableHits[whichRead][dir] += nHits[dir];
if (doesGenomeIndexHave64BitLocations) {
hashTableHitSets[whichRead][dir]->recordLookup(offset, nHits[dir], hits[dir], beginsDisjointHitSet[dir]);
} else {
hashTableHitSets[whichRead][dir]->recordLookup(offset, nHits[dir], hits32[dir], beginsDisjointHitSet[dir]);
}
beginsDisjointHitSet[dir] = false;
} else {
popularSeedsSkipped[whichRead]++;
}
} // for each direction
//
// If we don't have enough seeds left to reach the end of the read, space out the seeds more-or-less evenly.
//
if ((maxSeeds - countOfHashTableLookups[whichRead] + 1) * (int)seedLen + nextSeedToTest < nPossibleSeeds) {
_ASSERT((nPossibleSeeds - nextSeedToTest - 1) / (maxSeeds - countOfHashTableLookups[whichRead] + 1) >= (int)seedLen);
nextSeedToTest += (nPossibleSeeds - nextSeedToTest - 1) / (maxSeeds - countOfHashTableLookups[whichRead] + 1);
_ASSERT(nextSeedToTest < nPossibleSeeds); // We haven't run off the end of the read.
} else {
nextSeedToTest += seedLen;
}
} // while we need to lookup seeds for this read
} // for each read
readWithMoreHits = totalHashTableHits[0][FORWARD] + totalHashTableHits[0][RC] > totalHashTableHits[1][FORWARD] + totalHashTableHits[1][RC] ? 0 : 1;
readWithFewerHits = 1 - readWithMoreHits;
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: Read 0 has %lld hits, read 1 has %lld hits\n", totalHashTableHits[0][FORWARD] + totalHashTableHits[0][RC], totalHashTableHits[1][FORWARD] + totalHashTableHits[1][RC]);
}
#endif // _DEBUG
Direction setPairDirection[NUM_SET_PAIRS][NUM_READS_PER_PAIR] = { {FORWARD, RC}, {RC, FORWARD} };
//
// Phase 2: find all possible candidates and add them to candidate lists (for the reads with fewer and more hits).
//
int maxUsedBestPossibleScoreList = 0;
for (unsigned whichSetPair = 0; whichSetPair < NUM_SET_PAIRS; whichSetPair++) {
HashTableHitSet* setPair[NUM_READS_PER_PAIR];
if (whichSetPair == 0) {
setPair[0] = hashTableHitSets[0][FORWARD];
setPair[1] = hashTableHitSets[1][RC];
} else {
setPair[0] = hashTableHitSets[0][RC];
setPair[1] = hashTableHitSets[1][FORWARD];
}
unsigned lastSeedOffsetForReadWithFewerHits;
GenomeLocation lastGenomeLocationForReadWithFewerHits;
GenomeLocation lastGenomeLocationForReadWithMoreHits;
unsigned lastSeedOffsetForReadWithMoreHits;
bool outOfMoreHitsLocations = false;
//
// Seed the intersection state by doing a first lookup.
//
if (setPair[readWithFewerHits]->getFirstHit(&lastGenomeLocationForReadWithFewerHits, &lastSeedOffsetForReadWithFewerHits)) {
//
// No hits in this direction.
//
continue; // The outer loop over set pairs.
}
lastGenomeLocationForReadWithMoreHits = InvalidGenomeLocation;
//
// Loop over the candidates in for the read with more hits. At the top of the loop, we have a candidate but don't know if it has
// a mate. Each pass through the loop considers a single hit on the read with fewer hits.
//
for (;;) {
//
// Loop invariant: lastGenomeLocationForReadWithFewerHits is the highest genome offset that has not been considered.
// lastGenomeLocationForReadWithMoreHits is also the highest genome offset on that side that has not been
// considered (or is InvalidGenomeLocation), but higher ones within the appropriate range might already be in scoringMateCandidates.
// We go once through this loop for each
//
if (lastGenomeLocationForReadWithMoreHits > lastGenomeLocationForReadWithFewerHits + maxSpacing) {
//
// The more hits side is too high to be a mate candidate for the fewer hits side. Move it down to the largest
// location that's not too high.
//
if (!setPair[readWithMoreHits]->getNextHitLessThanOrEqualTo(lastGenomeLocationForReadWithFewerHits + maxSpacing,
&lastGenomeLocationForReadWithMoreHits, &lastSeedOffsetForReadWithMoreHits)) {
break; // End of all of the mates. We're done with this set pair.
}
}
if ((lastGenomeLocationForReadWithMoreHits + maxSpacing < lastGenomeLocationForReadWithFewerHits || outOfMoreHitsLocations) &&
(0 == lowestFreeScoringMateCandidate[whichSetPair] ||
!genomeLocationIsWithin(scoringMateCandidates[whichSetPair][lowestFreeScoringMateCandidate[whichSetPair] - 1].readWithMoreHitsGenomeLocation, lastGenomeLocationForReadWithFewerHits, maxSpacing))) {
//
// No mates for the hit on the read with fewer hits. Skip to the next candidate.
//
if (outOfMoreHitsLocations) {
//
// Nothing left on the more hits side, we're done with this set pair.
//
break;
}
if (!setPair[readWithFewerHits]->getNextHitLessThanOrEqualTo(lastGenomeLocationForReadWithMoreHits + maxSpacing, &lastGenomeLocationForReadWithFewerHits,
&lastSeedOffsetForReadWithFewerHits)) {
//
// No more candidates on the read with fewer hits side. We're done with this set pair.
//
break;
}
continue;
}
//
// Add all of the mate candidates for the fewer side hit.
//
GenomeLocation previousMoreHitsLocation = lastGenomeLocationForReadWithMoreHits;
while (lastGenomeLocationForReadWithMoreHits + maxSpacing >= lastGenomeLocationForReadWithFewerHits && !outOfMoreHitsLocations) {
unsigned bestPossibleScoreForReadWithMoreHits;
if (disabledOptimizations.noTruncation) {
bestPossibleScoreForReadWithMoreHits = 0;
} else {
bestPossibleScoreForReadWithMoreHits = setPair[readWithMoreHits]->computeBestPossibleScoreForCurrentHit();
}
if (lowestFreeScoringMateCandidate[whichSetPair] >= scoringCandidatePoolSize / NUM_READS_PER_PAIR) {
WriteErrorMessage("Ran out of scoring candidate pool entries. Perhaps trying with a larger value of -mcp will help.\n");
soft_exit(1);
}
scoringMateCandidates[whichSetPair][lowestFreeScoringMateCandidate[whichSetPair]].init(
lastGenomeLocationForReadWithMoreHits, bestPossibleScoreForReadWithMoreHits,
lastSeedOffsetForReadWithMoreHits, &disabledOptimizations, maxKForIndels);
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: SetPair %d, added more hits candidate %d at genome location %s:%llu, bestPossibleScore %d, seedOffset %d\n",
whichSetPair, lowestFreeScoringMateCandidate[whichSetPair],
genome->getContigAtLocation(lastGenomeLocationForReadWithMoreHits)->name,
lastGenomeLocationForReadWithMoreHits - genome->getContigAtLocation(lastGenomeLocationForReadWithMoreHits)->beginningLocation,
bestPossibleScoreForReadWithMoreHits,
lastSeedOffsetForReadWithMoreHits);
}
#endif // _DEBUG
lowestFreeScoringMateCandidate[whichSetPair]++;
previousMoreHitsLocation = lastGenomeLocationForReadWithMoreHits;
if (!setPair[readWithMoreHits]->getNextLowerHit(&lastGenomeLocationForReadWithMoreHits, &lastSeedOffsetForReadWithMoreHits)) {
lastGenomeLocationForReadWithMoreHits = 0;
outOfMoreHitsLocations = true;
break; // out of the loop looking for candidates on the more hits side.
}
}
//
// And finally add the hit from the fewer hit side. To compute its best possible score, we need to look at all of the mates; we couldn't do it in the
// loop immediately above because some of them might have already been in the mate list from a different, nearby fewer hit location.
//
int bestPossibleScoreForReadWithFewerHits;
if (disabledOptimizations.noTruncation) {
bestPossibleScoreForReadWithFewerHits = 0;
} else {
bestPossibleScoreForReadWithFewerHits = setPair[readWithFewerHits]->computeBestPossibleScoreForCurrentHit();
}
int lowestBestPossibleScoreOfAnyPossibleMate = maxK + extraSearchDepth;
for (int i = lowestFreeScoringMateCandidate[whichSetPair] - 1; i >= 0; i--) {
if (scoringMateCandidates[whichSetPair][i].readWithMoreHitsGenomeLocation > lastGenomeLocationForReadWithFewerHits + maxSpacing) {
break;
}
lowestBestPossibleScoreOfAnyPossibleMate = __min(lowestBestPossibleScoreOfAnyPossibleMate, scoringMateCandidates[whichSetPair][i].bestPossibleScore);
}
if (lowestBestPossibleScoreOfAnyPossibleMate + bestPossibleScoreForReadWithFewerHits <= maxK + extraSearchDepth) {
//
// There's a set of ends that we can't prove doesn't have too large of a score. Allocate a fewer hit candidate and stick it in the
// correct weight list.
//
if (lowestFreeScoringCandidatePoolEntry >= scoringCandidatePoolSize) {
WriteErrorMessage("Ran out of scoring candidate pool entries. Perhaps rerunning with a larger value of -mcp will help.\n");
soft_exit(1);
}
//
// If we have noOrderedEvaluation set, just stick everything on list 0, regardless of what it really is. This will cause us to
// evaluate the candidates in more-or-less inverse genome order.
//
int bestPossibleScore = disabledOptimizations.noOrderedEvaluation ? 0 : lowestBestPossibleScoreOfAnyPossibleMate + bestPossibleScoreForReadWithFewerHits;
scoringCandidatePool[lowestFreeScoringCandidatePoolEntry].init(lastGenomeLocationForReadWithFewerHits, whichSetPair, lowestFreeScoringMateCandidate[whichSetPair] - 1,
lastSeedOffsetForReadWithFewerHits, bestPossibleScoreForReadWithFewerHits,
scoringCandidates[bestPossibleScore]);
scoringCandidates[bestPossibleScore] = &scoringCandidatePool[lowestFreeScoringCandidatePoolEntry];
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: SetPair %d, added fewer hits candidate %d at genome location %s:%llu, bestPossibleScore %d, seedOffset %d\n",
whichSetPair, lowestFreeScoringCandidatePoolEntry,
genome->getContigAtLocation(lastGenomeLocationForReadWithFewerHits)->name, lastGenomeLocationForReadWithFewerHits - genome->getContigAtLocation(lastGenomeLocationForReadWithFewerHits)->beginningLocation,
lowestBestPossibleScoreOfAnyPossibleMate + bestPossibleScoreForReadWithFewerHits,
lastSeedOffsetForReadWithFewerHits);
}
#endif // _DEBUG
lowestFreeScoringCandidatePoolEntry++;
maxUsedBestPossibleScoreList = max(maxUsedBestPossibleScoreList, bestPossibleScore);
}
if (!setPair[readWithFewerHits]->getNextLowerHit(&lastGenomeLocationForReadWithFewerHits, &lastSeedOffsetForReadWithFewerHits)) {
break;
}
} // forever (the loop that does the intersection walk)
} // For each set pair
//
// Phase 3: score and merge the candidates we've found using Hamming (no indels, just count the differing bases).
//
int currentBestPossibleScoreList = 0;
//
// Loop until we've scored all of the candidates, or proven that what's left must have too high of a score to be interesting.
//
//
while (currentBestPossibleScoreList <= maxUsedBestPossibleScoreList &&
currentBestPossibleScoreList <= extraSearchDepth + min(maxK, max( // Never look for worse than our worst interesting score
min(scoresForAllAlignments.bestPairScore, scoresForNonAltAlignments.bestPairScore - maxScoreGapToPreferNonAltAlignment), // Worst we care about for ALT
min(scoresForAllAlignments.bestPairScore + maxScoreGapToPreferNonAltAlignment, scoresForNonAltAlignments.bestPairScore)))) // And for non-ALT
{
if (scoringCandidates[currentBestPossibleScoreList] == NULL) {
//
// No more candidates on this list. Skip to the next one.
//
currentBestPossibleScoreList++;
continue;
}
//
// Grab the first candidate on the highest list and score it.
//
ScoringCandidate* candidate = scoringCandidates[currentBestPossibleScoreList];
int fewerEndScore, fewerEndScoreGapless;
double fewerEndMatchProbability;
int fewerEndGenomeLocationOffset;
bool nonALTAlignment = (!altAwareness) || !genome->isGenomeLocationALT(candidate->readWithFewerHitsGenomeLocation);
int scoreLimit = computeScoreLimit(nonALTAlignment, &scoresForAllAlignments, &scoresForNonAltAlignments, 0);
if (currentBestPossibleScoreList > scoreLimit) {
//
// Remove us from the head of the list and proceed to the next candidate to score. We can get here because now we know ALT/non-ALT, which have different limits.
//
scoringCandidates[currentBestPossibleScoreList] = candidate->scoreListNext;
continue;
}
scoreLocationWithHammingDistance(readWithFewerHits, setPairDirection[candidate->whichSetPair][readWithFewerHits], candidate->readWithFewerHitsGenomeLocation,
candidate->seedOffset, scoreLimit, &fewerEndScore, &fewerEndMatchProbability, &fewerEndGenomeLocationOffset, &candidate->usedAffineGapScoring,
&candidate->basesClippedBefore, &candidate->basesClippedAfter, &candidate->agScore, &candidate->usedGaplessClipping, &fewerEndScoreGapless);
candidate->matchProbability = fewerEndMatchProbability;
_ASSERT(candidate->usedGaplessClipping || ScoreAboveLimit == fewerEndScore || fewerEndScore >= candidate->bestPossibleScore);
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: Scored fewer end candidate %d, set pair %d, read %d, location %s:%llu, seed offset %d, score limit %d, score %d, offset %d, agScore %d, matchProb %e\n",
(int)(candidate - scoringCandidatePool),
candidate->whichSetPair, readWithFewerHits,
genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation)->name,
candidate->readWithFewerHitsGenomeLocation - genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation)->beginningLocation,
candidate->seedOffset,
scoreLimit, fewerEndScore, fewerEndGenomeLocationOffset, candidate->agScore, fewerEndMatchProbability);
}
#endif // DEBUG
if (fewerEndScore != ScoreAboveLimit) {
//
// Find and score mates. The index in scoringMateCandidateIndex is the lowest mate (i.e., the highest index number).
//
unsigned mateIndex = candidate->scoringMateCandidateIndex;
for (;;) {
ScoringMateCandidate* mate = &scoringMateCandidates[candidate->whichSetPair][mateIndex];
_ASSERT(genomeLocationIsWithin(mate->readWithMoreHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation, maxSpacing));
//
// Exclude it if it's strictly smaller than minSpacing; hence, minSpacing -1.
//
if (!genomeLocationIsWithin(mate->readWithMoreHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation, minSpacing - 1) && ((mate->bestPossibleScore <= scoreLimit - fewerEndScore) || (candidate->usedGaplessClipping))) {
//
// It's within the range and not necessarily too poor of a match. Consider it.
//
//
// If we haven't yet scored this mate, or we've scored it and not gotten an answer, but had a lower score limit than we'd
// use now, score it.
//
//
// If we found a good match using the Hamming distance method, don't update scoreLimit.
// This is because the reported score can be very large after clipping
//
int mateScoreLimit = candidate->usedGaplessClipping ? scoreLimit : scoreLimit - fewerEndScore;
int mateScoreGapless;
if (mate->score == ScoringMateCandidate::LocationNotYetScored || (mate->score == ScoreAboveLimit && mate->scoreLimit < scoreLimit - fewerEndScore) || (candidate->usedGaplessClipping)) {
scoreLocationWithHammingDistance(readWithMoreHits, setPairDirection[candidate->whichSetPair][readWithMoreHits], GenomeLocationAsInt64(mate->readWithMoreHitsGenomeLocation),
mate->seedOffset, mateScoreLimit, &mate->score, &mate->matchProbability,
&mate->genomeOffset, &mate->usedAffineGapScoring, &mate->basesClippedBefore, &mate->basesClippedAfter, &mate->agScore, &mate->usedGaplessClipping, &mateScoreGapless);
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: Scored mate candidate %d, set pair %d, read %d, location %s:%llu, seed offset %d, score limit %d, score %d, offset %d, agScore %d, matchProb %e\n",
(int)(mate - scoringMateCandidates[candidate->whichSetPair]), candidate->whichSetPair, readWithMoreHits,
genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation)->name,
mate->readWithMoreHitsGenomeLocation - genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation)->beginningLocation,
mate->seedOffset, mateScoreLimit, mate->score, mate->genomeOffset, mate->agScore, mate->matchProbability);
}
#endif // _DEBUG
_ASSERT(mate->usedGaplessClipping || ScoreAboveLimit == mate->score || mate->score >= mate->bestPossibleScore);
// Don't update scoreLimit for mate if the candidate was matched using the gapless clipping scoring method
// This is because gapless alignments may have large soft clips
mate->scoreLimit = candidate->usedGaplessClipping ? scoreLimit : scoreLimit - fewerEndScore;
}
if (mate->score != ScoreAboveLimit && ((fewerEndScore + mate->score <= scoreLimit) || candidate->usedGaplessClipping || mate->usedGaplessClipping)) { // We need to check to see that we're below scoreLimit because we may have scored this earlier when scoreLimit was higher.
double pairProbability = mate->matchProbability * fewerEndMatchProbability;
int pairScore = mate->score + fewerEndScore;
int pairAGScore = mate->agScore + candidate->agScore;
//
// See if this should be ignored as a merge, or if we need to back out a previously scored location
// because it's a worse version of this location.
//
MergeAnchor* mergeAnchor = candidate->mergeAnchor;
if (NULL == mergeAnchor) {
//
// Look up and down the array of candidates to see if we have possible merge candidates.
//
for (ScoringCandidate* mergeCandidate = candidate - 1;
mergeCandidate >= scoringCandidatePool &&
genomeLocationIsWithin(mergeCandidate->readWithFewerHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset, 50) &&
mergeCandidate->whichSetPair == candidate->whichSetPair;
mergeCandidate--) {
if (mergeCandidate->mergeAnchor != NULL) {
candidate->mergeAnchor = mergeAnchor = mergeCandidate->mergeAnchor;
break;
}
}
if (NULL == mergeAnchor) {
for (ScoringCandidate* mergeCandidate = candidate + 1;
mergeCandidate < scoringCandidatePool + lowestFreeScoringCandidatePoolEntry &&
genomeLocationIsWithin(mergeCandidate->readWithFewerHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset, 50) &&
mergeCandidate->whichSetPair == candidate->whichSetPair;
mergeCandidate++) {
if (mergeCandidate->mergeAnchor != NULL) {
candidate->mergeAnchor = mergeAnchor = mergeCandidate->mergeAnchor;
break;
}
}
}
}
bool eliminatedByMerge; // Did we merge away this result. If this is false, we may still have merged away a previous result.
double oldPairProbability;
bool mergeReplacement = false; // Did we replace the anchor with the new candidate ?
if (NULL == mergeAnchor) {
if (firstFreeMergeAnchor >= mergeAnchorPoolSize) {
WriteErrorMessage("Ran out of merge anchor pool entries. Perhaps rerunning with a larger value of -mcp will help\n");
soft_exit(1);
}
mergeAnchor = &mergeAnchorPool[firstFreeMergeAnchor];
firstFreeMergeAnchor++;
mergeAnchor->init(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset,
pairProbability, pairScore, pairAGScore);
eliminatedByMerge = false;
oldPairProbability = 0;
candidate->mergeAnchor = mergeAnchor;
}
else {
eliminatedByMerge = mergeAnchor->checkMerge(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset, candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset,
pairProbability, pairScore, pairAGScore, &oldPairProbability, &mergeReplacement);
}
if (!eliminatedByMerge) {
//
// Back out the probability of the old match that we're merged with, if any. The max
// is necessary because a + b - b is not necessarily a in floating point. If there
// was no merge, the oldPairProbability is 0.
//
scoresForAllAlignments.updateProbabilityOfAllPairs(oldPairProbability);
if (nonALTAlignment) {
scoresForNonAltAlignments.updateProbabilityOfAllPairs(oldPairProbability);
}
if (pairProbability > scoresForAllAlignments.probabilityOfBestPair && maxEditDistanceForSecondaryResults != -1 && (pairScore <= scoresForAllAlignments.bestPairScore) && (maxEditDistanceForSecondaryResults >= scoresForAllAlignments.bestPairScore - pairScore)) {
//
// Move the old best to be a secondary alignment. This won't happen on the first time we get a valid alignment,
// because bestPairScore is initialized to be very large.
//
//
if (*nSecondaryResults >= secondaryResultBufferSize) {
*nSecondaryResults = secondaryResultBufferSize + 1;
return false;
}
PairedAlignmentResult* secondaryResult = &secondaryResults[*nSecondaryResults];
secondaryResult->alignedAsPair = true;
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
secondaryResult->direction[r] = scoresForAllAlignments.bestResultDirection[r];
secondaryResult->location[r] = scoresForAllAlignments.bestResultGenomeLocation[r];
secondaryResult->origLocation[r] = scoresForAllAlignments.bestResultOrigGenomeLocation[r];
secondaryResult->mapq[r] = 0;
secondaryResult->score[r] = scoresForAllAlignments.bestResultScore[r];
secondaryResult->status[r] = MultipleHits;
secondaryResult->usedAffineGapScoring[r] = scoresForAllAlignments.bestResultUsedAffineGapScoring[r];
secondaryResult->basesClippedBefore[r] = scoresForAllAlignments.bestResultBasesClippedBefore[r];
secondaryResult->basesClippedAfter[r] = scoresForAllAlignments.bestResultBasesClippedAfter[r];
secondaryResult->agScore[r] = scoresForAllAlignments.bestResultAGScore[r];
secondaryResult->seedOffset[r] = scoresForAllAlignments.bestResultSeedOffset[r];
secondaryResult->popularSeedsSkipped[r] = popularSeedsSkipped[r];
secondaryResult->lvIndels[r] = scoresForAllAlignments.bestResultLVIndels[r];
secondaryResult->matchProbability[r] = scoresForAllAlignments.bestResultMatchProbability[r];
secondaryResult->usedGaplessClipping[r] = scoresForAllAlignments.bestResultUsedGaplessClipping[r];
secondaryResult->refSpan[r] = scoresForAllAlignments.bestResultRefSpan[r];
}
(*nSecondaryResults)++;
} // If we're saving the old best score as a secondary result
if (!mergeReplacement && (pairProbability > scoresForAllAlignments.probabilityOfBestPair) && (maxLVCandidatesForAffineGapBufferSize > 0) &&
(pairScore <= scoresForAllAlignments.bestPairScore) && (extraSearchDepth >= scoresForAllAlignments.bestPairScore - pairScore))
{
//
// This is close enough that scoring it with affine gap scoring might make it be the best result. Save it for possible consideration in phase 4.
//
if (*nLVCandidatesForAffineGap >= maxLVCandidatesForAffineGapBufferSize) {
*nLVCandidatesForAffineGap = maxLVCandidatesForAffineGapBufferSize + 1;
return false;
}
PairedAlignmentResult* agResult = &lvCandidatesForAffineGap[*nLVCandidatesForAffineGap];
agResult->alignedAsPair = true;
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
agResult->direction[r] = scoresForAllAlignments.bestResultDirection[r];
agResult->location[r] = scoresForAllAlignments.bestResultGenomeLocation[r];
agResult->origLocation[r] = scoresForAllAlignments.bestResultOrigGenomeLocation[r];
agResult->mapq[r] = 0;
agResult->score[r] = scoresForAllAlignments.bestResultScore[r];
agResult->status[r] = MultipleHits;
agResult->usedAffineGapScoring[r] = scoresForAllAlignments.bestResultUsedAffineGapScoring[r];
agResult->basesClippedBefore[r] = scoresForAllAlignments.bestResultBasesClippedBefore[r];
agResult->basesClippedAfter[r] = scoresForAllAlignments.bestResultBasesClippedAfter[r];
agResult->agScore[r] = scoresForAllAlignments.bestResultAGScore[r];
agResult->seedOffset[r] = scoresForAllAlignments.bestResultSeedOffset[r];
agResult->popularSeedsSkipped[r] = popularSeedsSkipped[r];
agResult->lvIndels[r] = scoresForAllAlignments.bestResultLVIndels[r];
agResult->matchProbability[r] = scoresForAllAlignments.bestResultMatchProbability[r];
agResult->usedGaplessClipping[r] = scoresForAllAlignments.bestResultUsedGaplessClipping[r];
agResult->refSpan[r] = scoresForAllAlignments.bestResultRefSpan[r];
}
(*nLVCandidatesForAffineGap)++;
}
if (nonALTAlignment) {
scoresForNonAltAlignments.updateBestHitIfNeeded(pairScore, pairAGScore, pairProbability, fewerEndScore, readWithMoreHits, fewerEndGenomeLocationOffset, candidate, mate);
}
bool updatedBestScore = scoresForAllAlignments.updateBestHitIfNeeded(pairScore, pairAGScore, pairProbability, fewerEndScore, readWithMoreHits, fewerEndGenomeLocationOffset, candidate, mate);
// scoreLimit = computeScoreLimit(nonALTAlignment, &scoresForAllAlignments, &scoresForNonAltAlignments);
if ((!updatedBestScore) && maxEditDistanceForSecondaryResults != -1 && (pairScore >= scoresForAllAlignments.bestPairScore) && (maxEditDistanceForSecondaryResults >= pairScore - scoresForAllAlignments.bestPairScore)) {
//
// A secondary result to save.
//
if (*nSecondaryResults >= secondaryResultBufferSize) {
*nSecondaryResults = secondaryResultBufferSize + 1;
return false;
}
PairedAlignmentResult* result = &secondaryResults[*nSecondaryResults];
result->alignedAsPair = true;
result->direction[readWithMoreHits] = setPairDirection[candidate->whichSetPair][readWithMoreHits];
result->direction[readWithFewerHits] = setPairDirection[candidate->whichSetPair][readWithFewerHits];
result->location[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation + mate->genomeOffset;
result->location[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset;
result->origLocation[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation;
result->origLocation[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation;
result->mapq[0] = result->mapq[1] = 0;
result->score[readWithMoreHits] = mate->score;
result->score[readWithFewerHits] = fewerEndScore;
result->status[readWithFewerHits] = result->status[readWithMoreHits] = MultipleHits;
result->usedAffineGapScoring[readWithMoreHits] = mate->usedAffineGapScoring;
result->usedAffineGapScoring[readWithFewerHits] = candidate->usedAffineGapScoring;
result->usedGaplessClipping[readWithMoreHits] = mate->usedGaplessClipping;
result->usedGaplessClipping[readWithFewerHits] = candidate->usedGaplessClipping;
result->basesClippedBefore[readWithFewerHits] = candidate->basesClippedBefore;
result->basesClippedAfter[readWithFewerHits] = candidate->basesClippedAfter;
result->basesClippedBefore[readWithMoreHits] = mate->basesClippedBefore;
result->basesClippedAfter[readWithMoreHits] = mate->basesClippedAfter;
result->agScore[readWithMoreHits] = mate->agScore;
result->agScore[readWithFewerHits] = candidate->agScore;
result->seedOffset[readWithMoreHits] = mate->seedOffset;
result->seedOffset[readWithFewerHits] = candidate->seedOffset;
result->lvIndels[readWithMoreHits] = mate->lvIndels;
result->lvIndels[readWithFewerHits] = candidate->lvIndels;
result->matchProbability[readWithMoreHits] = mate->matchProbability;
result->matchProbability[readWithFewerHits] = candidate->matchProbability;
result->popularSeedsSkipped[readWithMoreHits] = popularSeedsSkipped[readWithMoreHits];
result->popularSeedsSkipped[readWithFewerHits] = popularSeedsSkipped[readWithFewerHits];
(*nSecondaryResults)++;
}
if ((!updatedBestScore) && maxLVCandidatesForAffineGapBufferSize > 0 && (pairScore >= scoresForAllAlignments.bestPairScore) && (extraSearchDepth >= pairScore - scoresForAllAlignments.bestPairScore)) {
if (*nLVCandidatesForAffineGap >= maxLVCandidatesForAffineGapBufferSize) {
*nLVCandidatesForAffineGap = maxLVCandidatesForAffineGapBufferSize + 1;
return false;
}
PairedAlignmentResult* result = &lvCandidatesForAffineGap[*nLVCandidatesForAffineGap];
result->alignedAsPair = true;
result->direction[readWithMoreHits] = setPairDirection[candidate->whichSetPair][readWithMoreHits];
result->direction[readWithFewerHits] = setPairDirection[candidate->whichSetPair][readWithFewerHits];
result->location[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation + mate->genomeOffset;
result->location[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset;
result->origLocation[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation;
result->origLocation[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation;
result->mapq[0] = result->mapq[1] = 0;
result->score[readWithMoreHits] = mate->score;
result->score[readWithFewerHits] = fewerEndScore;
result->status[readWithFewerHits] = result->status[readWithMoreHits] = MultipleHits;
result->usedAffineGapScoring[readWithMoreHits] = mate->usedAffineGapScoring;
result->usedAffineGapScoring[readWithFewerHits] = candidate->usedAffineGapScoring;
result->usedGaplessClipping[readWithMoreHits] = mate->usedGaplessClipping;
result->usedGaplessClipping[readWithFewerHits] = candidate->usedGaplessClipping;
result->basesClippedBefore[readWithFewerHits] = candidate->basesClippedBefore;
result->basesClippedAfter[readWithFewerHits] = candidate->basesClippedAfter;
result->basesClippedBefore[readWithMoreHits] = mate->basesClippedBefore;
result->basesClippedAfter[readWithMoreHits] = mate->basesClippedAfter;
result->agScore[readWithMoreHits] = mate->agScore;
result->agScore[readWithFewerHits] = candidate->agScore;
result->seedOffset[readWithMoreHits] = mate->seedOffset;
result->seedOffset[readWithFewerHits] = candidate->seedOffset;
result->lvIndels[readWithMoreHits] = mate->lvIndels;
result->lvIndels[readWithFewerHits] = candidate->lvIndels;
result->matchProbability[readWithMoreHits] = mate->matchProbability;
result->matchProbability[readWithFewerHits] = candidate->matchProbability;
result->popularSeedsSkipped[readWithMoreHits] = popularSeedsSkipped[readWithMoreHits];
result->popularSeedsSkipped[readWithFewerHits] = popularSeedsSkipped[readWithFewerHits];
(*nLVCandidatesForAffineGap)++;
}
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: Added %e (= %e * %e) @ (%s:%llu, %s:%llu), giving new probability of all pairs %e, score %d = %d + %d, agScore %d = %d + %d%s\n",
pairProbability, mate->matchProbability, fewerEndMatchProbability,
genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation.location + fewerEndGenomeLocationOffset)->name,
(candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset) - genome->getContigAtLocation(candidate->readWithFewerHitsGenomeLocation.location + fewerEndGenomeLocationOffset)->beginningLocation,
genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset)->name,
(mate->readWithMoreHitsGenomeLocation + mate->genomeOffset) - genome->getContigAtLocation(mate->readWithMoreHitsGenomeLocation.location + mate->genomeOffset)->beginningLocation,
scoresForNonAltAlignments.probabilityOfAllPairs,
pairScore, fewerEndScore, mate->score, candidate->agScore + mate->agScore, candidate->agScore, mate->agScore, updatedBestScore ? " New best hit" : "");
}
#endif // _DEBUG
if ((altAwareness ? scoresForNonAltAlignments.probabilityOfAllPairs : scoresForAllAlignments.probabilityOfAllPairs) >= 4.9 && -1 == maxEditDistanceForSecondaryResults) {
//
// Nothing will rescue us from a 0 MAPQ, so just stop looking.
//
goto doneScoring;
}
}
}// if the mate has a non -1 score
}
if (mateIndex == 0 || !genomeLocationIsWithin(scoringMateCandidates[candidate->whichSetPair][mateIndex - 1].readWithMoreHitsGenomeLocation, candidate->readWithFewerHitsGenomeLocation, maxSpacing)) {
//
// Out of mate candidates.
//
break;
}
mateIndex--;
}
}
//
// Remove us from the head of the list and proceed to the next candidate to score.
//
scoringCandidates[currentBestPossibleScoreList] = candidate->scoreListNext;
}
doneScoring:
ScoreSet* scoreSetToEmit;
if ((!altAwareness) || scoresForNonAltAlignments.bestPairScore > scoresForAllAlignments.bestPairScore + maxScoreGapToPreferNonAltAlignment) {
scoreSetToEmit = &scoresForAllAlignments;
} else {
scoreSetToEmit = &scoresForNonAltAlignments;
}
if (scoreSetToEmit->bestPairScore == TooBigScoreValue) {
//
// Found nothing.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
result->location[whichRead] = InvalidGenomeLocation;
result->origLocation[whichRead] = InvalidGenomeLocation;
result->mapq[whichRead] = 0;
result->score[whichRead] = ScoreAboveLimit;
result->status[whichRead] = NotFound;
result->clippingForReadAdjustment[whichRead] = 0;
result->usedAffineGapScoring[whichRead] = false;
result->usedGaplessClipping[whichRead] = false;
result->basesClippedBefore[whichRead] = 0;
result->basesClippedAfter[whichRead] = 0;
result->agScore[whichRead] = ScoreAboveLimit;
result->seedOffset[whichRead] = 0;
result->lvIndels[whichRead] = 0;
result->popularSeedsSkipped[whichRead] = popularSeedsSkipped[whichRead];
result->matchProbability[whichRead] = 0.0;
firstALTResult->status[whichRead] = NotFound;
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: No sufficiently good pairs found.\n");
}
#endif // DEBUG
}
result->probabilityAllPairs = 0.0;
} else {
scoreSetToEmit->fillInResult(result, popularSeedsSkipped);
if (altAwareness && scoreSetToEmit == &scoresForNonAltAlignments &&
(scoresForAllAlignments.bestResultGenomeLocation[0] != scoresForNonAltAlignments.bestResultGenomeLocation[0] ||
scoresForAllAlignments.bestResultGenomeLocation[1] != scoresForNonAltAlignments.bestResultGenomeLocation[1]))
{
_ASSERT(genome->isGenomeLocationALT(scoresForAllAlignments.bestResultGenomeLocation[0]));
scoresForAllAlignments.fillInResult(firstALTResult, popularSeedsSkipped);
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++)
{
firstALTResult->supplementary[whichRead] = true;
}
} else {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++)
{
firstALTResult->status[whichRead] = NotFound;
}
}
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Hamming: Returned %s:%llu %s %s:%llu %s with MAPQ %d and %d, probability of all pairs %e, probability of best pair %e, pair score %d\n",
genome->getContigAtLocation(result->location[0])->name, result->location[0] - genome->getContigAtLocation(result->location[0])->beginningLocation,
result->direction[0] == RC ? "RC" : "",
genome->getContigAtLocation(result->location[1])->name, result->location[1] - genome->getContigAtLocation(result->location[1])->beginningLocation,
result->direction[1] == RC ? "RC" : "", result->mapq[0], result->mapq[1], scoreSetToEmit->probabilityOfAllPairs, scoreSetToEmit->probabilityOfBestPair,
scoreSetToEmit->bestPairScore);
if (firstALTResult->status[0] != NotFound) {
printf("Hamming: Returned first ALT Result %s:%llu %s %s:%llu %s with MAPQ %d and %d, probability of all pairs %e, probability of best pair %e, pair score %d\n",
genome->getContigAtLocation(firstALTResult->location[0])->name, firstALTResult->location[0] - genome->getContigAtLocation(firstALTResult->location[0])->beginningLocation,
firstALTResult->direction[0] == RC ? "RC" : "",
genome->getContigAtLocation(firstALTResult->location[1])->name, firstALTResult->location[1] - genome->getContigAtLocation(firstALTResult->location[1])->beginningLocation,
firstALTResult->direction[1] == RC ? "RC" : "", firstALTResult->mapq[0], firstALTResult->mapq[1], scoresForAllAlignments.probabilityOfAllPairs, scoresForAllAlignments.probabilityOfBestPair,
scoresForAllAlignments.bestPairScore);
} // If we're also returning an ALT result
}
#endif // DEBUG
}
//
// Get rid of any secondary results that are too far away from the best score. (NB: the rest of the code in align() is very similar to BaseAligner::finalizeSecondaryResults. Sorry)
//
Read* inputReads[2] = { read0, read1 };
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
result->scorePriorToClipping[whichRead] = result->score[whichRead];
}
if (!ignoreAlignmentAdjustmentsForOm) {
//
// Start by adjusting the alignments.
//
alignmentAdjuster.AdjustAlignments(inputReads, result);
if (result->status[0] != NotFound && result->status[1] != NotFound && !ignoreAlignmentAdjustmentsForOm) {
scoreSetToEmit->bestPairScore = result->score[0] + result->score[1];
}
for (int i = 0; i < *nSecondaryResults; i++) {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
secondaryResults[i].scorePriorToClipping[whichRead] = secondaryResults[i].score[whichRead];
}
alignmentAdjuster.AdjustAlignments(inputReads, &secondaryResults[i]);
if (secondaryResults[i].status[0] != NotFound && secondaryResults[i].status[1] != NotFound && !ignoreAlignmentAdjustmentsForOm) {
scoreSetToEmit->bestPairScore = __min(scoreSetToEmit->bestPairScore, secondaryResults[i].score[0] + secondaryResults[i].score[1]);
}
}
} else {
for (int i = 0; i < *nSecondaryResults; i++) {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
secondaryResults[i].scorePriorToClipping[whichRead] = secondaryResults[i].score[whichRead];
}
}
}
int i = 0;
while (i < *nSecondaryResults) {
if ((int)(secondaryResults[i].score[0] + secondaryResults[i].score[1]) > (int)scoreSetToEmit->bestPairScore + maxEditDistanceForSecondaryResults ||
secondaryResults[i].status[0] == NotFound || secondaryResults[i].status[1] == NotFound) {
secondaryResults[i] = secondaryResults[(*nSecondaryResults) - 1];
(*nSecondaryResults)--;
} else {
i++;
}
}
//
// Now check to see if there are too many for any particular contig.
//
if (maxSecondaryAlignmentsPerContig > 0 && result->status[0] != NotFound) {
//
// Run through the results and count the number of results per contig, to see if any of them are too big.
// First, record the primary result.
//
bool anyContigHasTooManyResults = false;
contigCountEpoch++;
int primaryContigNum = genome->getContigNumAtLocation(result->location[0]);
hitsPerContigCounts[primaryContigNum].hits = 1;
hitsPerContigCounts[primaryContigNum].epoch = contigCountEpoch;
for (i = 0; i < *nSecondaryResults; i++) {
int contigNum = genome->getContigNumAtLocation(secondaryResults[i].location[0]); // We know they're on the same contig, so either will do
if (hitsPerContigCounts[contigNum].epoch != contigCountEpoch) {
hitsPerContigCounts[contigNum].epoch = contigCountEpoch;
hitsPerContigCounts[contigNum].hits = 0;
}
hitsPerContigCounts[contigNum].hits++;
if (hitsPerContigCounts[contigNum].hits > maxSecondaryAlignmentsPerContig) {
anyContigHasTooManyResults = true;
break;
}
}
if (anyContigHasTooManyResults) {
//
// Just sort them all, in order of contig then hit depth.
//
qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), PairedAlignmentResult::compareByContigAndScore);
//
// Now run through and eliminate any contigs with too many hits. We can't use the same trick at the first loop above, because the
// counting here relies on the results being sorted. So, instead, we just copy them as we go.
//
int currentContigNum = -1;
int currentContigCount = 0;
int destResult = 0;
for (int sourceResult = 0; sourceResult < *nSecondaryResults; sourceResult++) {
int contigNum = genome->getContigNumAtLocation(secondaryResults[sourceResult].location[0]);
if (contigNum != currentContigNum) {
currentContigNum = contigNum;
currentContigCount = (contigNum == primaryContigNum) ? 1 : 0;
}
currentContigCount++;
if (currentContigCount <= maxSecondaryAlignmentsPerContig) {
//
// Keep it. If we don't get here, then we don't copy the result and
// don't increment destResult. And yes, this will sometimes copy a
// result over itself. That's harmless.
//
secondaryResults[destResult] = secondaryResults[sourceResult];
destResult++;
}
} // for each source result
*nSecondaryResults = destResult;
}
} // if we're limiting by contig
if (*nSecondaryResults > maxSecondaryResultsToReturn) {
qsort(secondaryResults, *nSecondaryResults, sizeof(*secondaryResults), PairedAlignmentResult::compareByScore);
*nSecondaryResults = maxSecondaryResultsToReturn; // Just truncate it
}
return true;
}
bool
IntersectingPairedEndAligner::alignAffineGap(
Read *read0,
Read *read1,
PairedAlignmentResult* result,
PairedAlignmentResult* firstALTResult,
int maxEditDistanceForSecondaryResults,
_int64 secondaryResultBufferSize,
_int64 *nSecondaryResults,
PairedAlignmentResult *secondaryResults, // The caller passes in a buffer of secondaryResultBufferSize and it's filled in by align()
_int64 singleSecondaryBufferSize,
_int64 maxSecondaryResultsToReturn,
_int64 *nSingleEndSecondaryResultsForFirstRead,
_int64 *nSingleEndSecondaryResultsForSecondRead,
SingleAlignmentResult *singleEndSecondaryResults, // Single-end secondary alignments for when the paired-end alignment didn't work properly
_int64 maxLVCandidatesForAffineGapBufferSize,
_int64 *nLVCandidatesForAffineGap,
PairedAlignmentResult *lvCandidatesForAffineGap
)
{
//
// Phase 4: Re-score candidates that need to be using affine gap scoring, and change the result if necessary.
//
if (result->status[0] == NotFound || result->status[1] == NotFound) {
return true;
}
//
// We rebuild the RC reads and extract the reference again before scoring candidates using affine gap
//
Read rcReads[NUM_READS_PER_PAIR];
reads[0][FORWARD] = read0;
reads[1][FORWARD] = read1;
//
// Don't bother if one or both reads are too short. The minimum read length here is the seed length, but usually there's a longer
// minimum enforced by our caller
//
if (read0->getDataLength() < seedLen || read1->getDataLength() < seedLen) {
return true;
}
//
// Build the RC reads.
//
unsigned countOfNs = 0;
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
Read *read = reads[whichRead][FORWARD];
readLen[whichRead] = read->getDataLength();
for (unsigned i = 0; i < reads[whichRead][FORWARD]->getDataLength(); i++) {
rcReadData[whichRead][i] = rcTranslationTable[read->getData()[readLen[whichRead] - i - 1]];
rcReadQuality[whichRead][i] = read->getQuality()[readLen[whichRead] - i - 1];
countOfNs += nTable[read->getData()[i]];
}
reads[whichRead][RC] = &rcReads[whichRead];
reads[whichRead][RC]->init(read->getId(), read->getIdLength(), rcReadData[whichRead], rcReadQuality[whichRead], read->getDataLength(), read->getFASTQComment(), read->getFASTQCommentLength());
}
if ((int)countOfNs > maxK) {
return true;
}
//
// Build the reverse data for both reads in both directions for the backwards LV to use.
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
for (Direction dir = 0; dir < NUM_DIRECTIONS; dir++) {
Read *read = reads[whichRead][dir];
for (unsigned i = 0; i < read->getDataLength(); i++) {
reversedRead[whichRead][dir][i] = read->getData()[read->getDataLength() - i - 1];
}
}
}
_ASSERT(maxLVCandidatesForAffineGapBufferSize > 0);
int maxKForSameAlignment = gapOpenPenalty / (subPenalty - gapExtendPenalty);
int bestPairScore = result->score[0] + result->score[1];
int scoreLimit, scoreLimitALT;
//
// We can maybe comment below after incorporating Bill's optimization for large indels, if there are not too many large indels
// near the start or ends of reads
//
if (result->usedGaplessClipping[0] || result->usedGaplessClipping[1]) {
scoreLimit = scoreLimitALT = MAX_K - 1;
} else {
scoreLimit = scoreLimitALT = maxK + extraSearchDepth;
}
int genomeOffset[NUM_READS_PER_PAIR] = { 0, 0 };
int genomeSpan[NUM_READS_PER_PAIR] = { 0, 0 };
bool skipAffineGap[NUM_READS_PER_PAIR] = { false, false };
//
// Keep track of old bestPairProbability as this is used in updating the new match probability after affine gap scoring
//
double oldPairProbabilityBestResult = result->matchProbability[0] * result->matchProbability[1];
double oldPairProbabilityBestResultALT = (firstALTResult->status[0] != NotFound) ? firstALTResult->matchProbability[0] * firstALTResult->matchProbability[1] : 0.0;
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
if (result->usedGaplessClipping[r] || result->score[r] > maxKForSameAlignment) {
//
// Use affine gap scoring to determine if bases need to be clipped
//
result->usedAffineGapScoring[r] = true;
if (!result->usedGaplessClipping[r]) {
scoreLimit = __max(scoreLimit, result->score[r]);
}
scoreLocationWithAffineGap(r, result->direction[r], result->origLocation[r],
result->seedOffset[r], scoreLimit, &result->score[r], &result->matchProbability[r],
&genomeOffset[r], &result->basesClippedBefore[r], &result->basesClippedAfter[r], &result->agScore[r], &result->refSpan[r]);
if (result->score[r] != ScoreAboveLimit) {
result->location[r] = result->origLocation[r] + genomeOffset[r];
scoreLimit -= result->score[r];
} else {
result->status[r] = NotFound;
}
//
// Use affine gap scoring for ALT result if it was computed in Phase 3
//
if (firstALTResult->status[r] != NotFound) {
if (firstALTResult->usedGaplessClipping[r] || firstALTResult->score[r] > maxKForSameAlignment) { // affine gap may produce a better alignment
firstALTResult->usedAffineGapScoring[r] = true;
if (!firstALTResult->usedGaplessClipping[r]) {
scoreLimitALT = __max(scoreLimitALT, firstALTResult->score[r]);
}
scoreLocationWithAffineGap(r, firstALTResult->direction[r], firstALTResult->origLocation[r],
firstALTResult->seedOffset[r], scoreLimitALT, &firstALTResult->score[r], &firstALTResult->matchProbability[r],
&genomeOffset[r], &firstALTResult->basesClippedBefore[r], &firstALTResult->basesClippedAfter[r], &firstALTResult->agScore[r], &firstALTResult->refSpan[r]);
if (firstALTResult->score[r] != ScoreAboveLimit) {
firstALTResult->location[r] = firstALTResult->origLocation[r] + genomeOffset[r];
scoreLimitALT -= firstALTResult->score[r];
} else {
firstALTResult->status[r] = NotFound;
}
#if _DEBUG
if (_DumpAlignments) {
fprintf(stderr, "Affine gap scored read %d at %s:%llu ALT score %d, agScore %d mapq %d\n",
r, genome->getContigAtLocation(firstALTResult->location[r])->name, firstALTResult->location[r] - genome->getContigAtLocation(firstALTResult->location[r])->beginningLocation,
firstALTResult->score[r], firstALTResult->agScore[r], firstALTResult->mapq[r]
);
}
#endif // _DEBUG
}
}
} else {
//
// Skip affine gap scoring for reads we know that LV and affine gap will agree on the alignment (and we're not evaluating without this optimization)
//
result->usedAffineGapScoring[r] = false;
skipAffineGap[r] = true;
}
}
if (result->status[0] == NotFound || result->status[1] == NotFound || (result->score[0] > MAX_K - 1) || (result->score[1] > MAX_K - 1)) {
//
// Found nothing from the paired-end aligner if one of the reads in the pair is unmapped or mapped with too high an edit distance
//
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
result->location[whichRead] = InvalidGenomeLocation;
result->origLocation[whichRead] = InvalidGenomeLocation;
result->mapq[whichRead] = 0;
result->score[whichRead] = ScoreAboveLimit;
result->status[whichRead] = NotFound;
result->clippingForReadAdjustment[whichRead] = 0;
result->usedAffineGapScoring[whichRead] = false;
result->usedGaplessClipping[whichRead] = false;
result->basesClippedBefore[whichRead] = 0;
result->basesClippedAfter[whichRead] = 0;
result->agScore[whichRead] = ScoreAboveLimit;
result->seedOffset[whichRead] = 0;
result->lvIndels[whichRead] = 0;
result->matchProbability[whichRead] = 0.0;
firstALTResult->status[whichRead] = NotFound;
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Affine: No sufficiently good pairs found.\n");
}
#endif // DEBUG
}
result->probabilityAllPairs = 0.0;
return true;
}
ScoreSet scoresForAllAlignments;
ScoreSet scoresForNonAltAlignments;
//
// In the beginning we only have the best alignment result in the score set.
// It is important to initialize the score set here and not before affine gap scoring, since only affine gap does clipping of alignments
//
bool nonALTAlignment = (!altAwareness) || !genome->isGenomeLocationALT(result->location[0]);
scoresForAllAlignments.init(result);
bool altBestAlignment = false;
if (firstALTResult->status[0] != NotFound && firstALTResult->status[1] != NotFound) {
altBestAlignment = scoresForAllAlignments.updateBestHitIfNeeded(firstALTResult->score[0] + firstALTResult->score[1],
firstALTResult->agScore[0] + firstALTResult->agScore[1], firstALTResult->matchProbability[0] * firstALTResult->matchProbability[1], firstALTResult);
}
if (nonALTAlignment) {
scoresForNonAltAlignments.init(result);
}
//
// Update match probability for reads rescored with affine gap
//
if (!skipAffineGap[0] || !skipAffineGap[1]) {
double newPairProbability = result->matchProbability[0] * result->matchProbability[1];
if (altBestAlignment) { // best result is an ALT result
double newPairProbabilityALT = firstALTResult->matchProbability[0] * firstALTResult->matchProbability[1];
scoresForAllAlignments.updateProbabilityOfAllPairs(oldPairProbabilityBestResultALT);
scoresForAllAlignments.updateProbabilityOfBestPair(newPairProbabilityALT, false); // false parameter needed because newPairProbabilityALT is already added to total probability in updateBestHit above
} else {
scoresForAllAlignments.updateProbabilityOfAllPairs(oldPairProbabilityBestResult);
scoresForAllAlignments.updateProbabilityOfBestPair(newPairProbability);
}
if (nonALTAlignment) {
scoresForNonAltAlignments.updateProbabilityOfAllPairs(oldPairProbabilityBestResult);
scoresForNonAltAlignments.updateProbabilityOfBestPair(newPairProbability);
}
}
//
// Evaluate LV candidates with affine gap scoring
//
if ((*nLVCandidatesForAffineGap > 0) && (!skipAffineGap[0] || !skipAffineGap[1])) {
//
// Reset score limit
//
scoreLimit = min(maxK, bestPairScore) + extraSearchDepth;
//
// We sort all all promising LV candidates and score them with affine gap starting with the best one
//
qsort(lvCandidatesForAffineGap, *nLVCandidatesForAffineGap, sizeof(*lvCandidatesForAffineGap), PairedAlignmentResult::compareByScore);
for (int i = 0; i < *nLVCandidatesForAffineGap; i++) {
PairedAlignmentResult* lvResult = &lvCandidatesForAffineGap[i];
int lvPairScore = lvResult->score[0] + lvResult->score[1];
int lvPairIndels = lvResult->lvIndels[0] + lvResult->lvIndels[1];
//
// Use the maximum scoreLimit if we expect the read could have alignments with large indels
//
if (lvResult->usedGaplessClipping[0] || lvResult->usedGaplessClipping[1]) {
scoreLimit = MAX_K - 1;
} else if ((lvPairScore > bestPairScore + extraSearchDepth) && (lvPairIndels > 1)) {
scoreLimit = maxK + extraSearchDepth;
}
if ((lvPairScore <= bestPairScore + extraSearchDepth) || (lvPairIndels > 1) || lvResult->usedGaplessClipping[0] || lvResult->usedGaplessClipping[1]) {
_ASSERT(lvResult->status[0] != NotFound && lvResult->status[1] != NotFound);
bool nonALTAlignment = (!altAwareness) || !genome->isGenomeLocationALT(lvResult->location[0]);
double oldPairProbability = lvResult->matchProbability[0] * lvResult->matchProbability[1];
if (!skipAffineGap[0]) {
//
// Score first read with affine gap
//
lvResult->usedAffineGapScoring[0] = true;
if (!lvResult->usedGaplessClipping[0]) {
scoreLimit = __max(scoreLimit, lvResult->score[0]);
}
scoreLocationWithAffineGap(0, lvResult->direction[0], lvResult->origLocation[0],
lvResult->seedOffset[0], scoreLimit, &lvResult->score[0], &lvResult->matchProbability[0],
&genomeOffset[0], &lvResult->basesClippedBefore[0], &lvResult->basesClippedAfter[0], &lvResult->agScore[0], &lvResult->refSpan[0]);
}
if ((lvResult->score[0] != ScoreAboveLimit) && (lvResult->score[0] <= MAX_K - 1)) {
lvResult->location[0] = lvResult->origLocation[0] + genomeOffset[0];
if (!skipAffineGap[1]) {
//
// Score mate with affine gap
//
lvResult->usedAffineGapScoring[1] = true;
scoreLimit = scoreLimit - lvResult->score[0];
if (!lvResult->usedGaplessClipping[1]) {
scoreLimit = __max(scoreLimit, lvResult->score[1]);
}
scoreLocationWithAffineGap(1, lvResult->direction[1], lvResult->origLocation[1],
lvResult->seedOffset[1], scoreLimit, &lvResult->score[1], &lvResult->matchProbability[1],
&genomeOffset[1], &lvResult->basesClippedBefore[1], &lvResult->basesClippedAfter[1], &lvResult->agScore[1], &lvResult->refSpan[1]);
} // if !skipAffineGap[1]
if ((lvResult->score[1] != ScoreAboveLimit) && (lvResult->score[1] <= MAX_K - 1)) {
lvResult->location[1] = lvResult->origLocation[1] + genomeOffset[1];
double pairProbability = lvResult->matchProbability[0] * lvResult->matchProbability[1];
int pairScore = lvResult->score[0] + lvResult->score[1];
int pairAGScore = lvResult->agScore[0] + lvResult->agScore[1];
//
// Do not lower MAPQ if we get the same alignment again
//
if (result->location[0] == lvResult->location[0] && result->location[1] == lvResult->location[1]) {
continue;
}
//
// Update match probabilities for read pair and best hit if better
//
scoresForAllAlignments.updateProbabilityOfAllPairs(oldPairProbability);
bool updatedBestScore = scoresForAllAlignments.updateBestHitIfNeeded(pairScore, pairAGScore, pairProbability, lvResult);
if (nonALTAlignment) {
scoresForNonAltAlignments.updateProbabilityOfAllPairs(oldPairProbability);
scoresForNonAltAlignments.updateBestHitIfNeeded(pairScore, pairAGScore, pairProbability, lvResult);
} // nonALTAlignment
//
// Update scoreLimit so that we only look for alignments extraSearchDepth worse than the best
//
scoreLimit = computeScoreLimit(nonALTAlignment, &scoresForAllAlignments, &scoresForNonAltAlignments, 0);
} // lvResult->score[1] != ScoreAboveLimit
} // lvResult->score[0] != ScoreAboveLimit
} // If we want to score this candidate with affine gap
} // for each candidate from LV
}
//
// Emit the final result (i.e., ALT/non-ALT best result and first ALT result, if any)
//
ScoreSet* scoreSetToEmit;
if ((!altAwareness) || scoresForNonAltAlignments.bestPairScore > scoresForAllAlignments.bestPairScore + maxScoreGapToPreferNonAltAlignment) {
scoreSetToEmit = &scoresForAllAlignments;
} else {
scoreSetToEmit = &scoresForNonAltAlignments;
}
scoreSetToEmit->fillInResult(result, result->popularSeedsSkipped);
if (altAwareness && scoreSetToEmit == &scoresForNonAltAlignments &&
(scoresForAllAlignments.bestResultGenomeLocation[0] != scoresForNonAltAlignments.bestResultGenomeLocation[0] ||
scoresForAllAlignments.bestResultGenomeLocation[1] != scoresForNonAltAlignments.bestResultGenomeLocation[1]))
{
_ASSERT(genome->isGenomeLocationALT(scoresForAllAlignments.bestResultGenomeLocation[0]));
scoresForAllAlignments.fillInResult(firstALTResult, firstALTResult->popularSeedsSkipped);
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++)
{
firstALTResult->supplementary[whichRead] = true;
}
} else {
for (int whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++)
{
firstALTResult->status[whichRead] = NotFound;
}
}
#if _DEBUG
if (_DumpAlignments) {
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
fprintf(stderr, "Affine gap scored read %d at %s:%llu score %d, agScore %d, mapq %d\n",
r, genome->getContigAtLocation(result->location[r])->name, result->location[r] - genome->getContigAtLocation(result->location[r])->beginningLocation,
result->score[r], result->agScore[r], result->mapq[r]
);
}
}
#endif // _DEBUG
if (useSoftClip) {
//
// Liftover ALT alignments to primary reference if:
// (1) Best alignment found was to an ALT contig
// (2) ALT alignments is better than non-ALT alignment and the primary contig to which the ALT alignment is projected to is different than the non-ALT alignment
//
int bestAltScore = INT_MAX, bestResScore = INT_MAX;
int altProjContigNum = -1, resContigNum = -1;
bool isResultALT = false;
const Genome* genome = index->getGenome();
if (firstALTResult->status[0] != NotFound && firstALTResult->status[1] != NotFound) {
bestAltScore = firstALTResult->score[0] + firstALTResult->score[1];
altProjContigNum = genome->getProjContigNumAtLocation(firstALTResult->location[0]);
}
if (result->status[0] != NotFound && result->status[1] != NotFound) {
bestResScore = result->score[0] + result->score[1];
resContigNum = genome->getContigNumAtLocation(result->location[0]);
isResultALT = altAwareness && genome->isGenomeLocationALT(result->location[0]) && genome->isGenomeLocationALT(result->location[1]);
}
bool useAltLiftover = altAwareness && (((bestAltScore < bestResScore) && (altProjContigNum != resContigNum)) || isResultALT);
if (useAltLiftover) {
bool foundAltProjection[NUM_READS_PER_PAIR] = { true, true };
Direction newDirectionAfterProjection[NUM_READS_PER_PAIR];
GenomeLocation newStartLocationAfterProjection[NUM_READS_PER_PAIR];
int newSeedOffsetAfterProjection[NUM_READS_PER_PAIR];
int newMapqAfterProjection[NUM_READS_PER_PAIR];
PairedAlignmentResult resultBeforeLiftover = *result;
if (isResultALT) {
Direction projDirection = genome->isProjContigRC(result->location[0]); // orientation of ALT contig w.r.t primary contig
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
newDirectionAfterProjection[r] = (result->direction[r] != projDirection) ? RC : FORWARD;
if (newDirectionAfterProjection[r] != result->direction[r]) {
newSeedOffsetAfterProjection[r] = readLen[r] - result->seedOffset[r] - 1; // flip read orientation
} else {
newSeedOffsetAfterProjection[r] = result->seedOffset[r];
}
newStartLocationAfterProjection[r] = genome->getProjLocation(result->location[r], result->refSpan[r]); // get projected location for ALT alignment
foundAltProjection[r] = newStartLocationAfterProjection[r] != InvalidGenomeLocation ? true : false;
newMapqAfterProjection[r] = result->mapq[r] <= 3 ? 70 : result->mapq[r]; // TODO: make mapq computation more accurate. We see MAPQ 3 sometimes when two ALT alignments liftover give the same primary alignment
}
} else {
Direction projDirection = genome->isProjContigRC(firstALTResult->location[0]); // orientation of ALT contig w.r.t primary contig
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
newDirectionAfterProjection[r] = (firstALTResult->direction[r] != projDirection) ? RC : FORWARD;
if (newDirectionAfterProjection[r] != firstALTResult->direction[r]) {
newSeedOffsetAfterProjection[r] = readLen[r] - firstALTResult->seedOffset[r] - 1; // flip read orientation
} else {
newSeedOffsetAfterProjection[r] = firstALTResult->seedOffset[r];
}
newStartLocationAfterProjection[r] = genome->getProjLocation(firstALTResult->location[r], firstALTResult->refSpan[r]); // get projected location for ALT alignment
foundAltProjection[r] = newStartLocationAfterProjection[r] != InvalidGenomeLocation ? true : false;
newMapqAfterProjection[r] = firstALTResult->mapq[r]; // TODO: make mapq computation more accurate
}
}
if (foundAltProjection[0] && foundAltProjection[1]) {
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
scoreLimit = MAX_K - 1; // using the maximum score limit here since we don't know how well the read aligns to the projected primary reference contig
result->usedAffineGapScoring[r] = true;
result->liftover[r] = true;
result->direction[r] = newDirectionAfterProjection[r];
result->location[r] = newStartLocationAfterProjection[r];
result->seedOffset[r] = newSeedOffsetAfterProjection[r];
result->mapq[r] = newMapqAfterProjection[r];
scoreLocationWithAffineGapLiftover(r, result->direction[r], result->location[r],
result->seedOffset[r], scoreLimit, &result->score[r], &result->matchProbability[r],
&genomeOffset[r], &result->basesClippedBefore[r], &result->basesClippedAfter[r], &result->agScore[r], &result->refSpan[r], true);
if ((result->score[r] != ScoreAboveLimit) && (result->score[r] <= MAX_K - 1)) {
result->location[r] += genomeOffset[r];
} else {
result->status[r] = NotFound;
}
}
if (result->status[0] == NotFound || result->status[1] == NotFound) { // affine gap could not find a liftover alignment
*result = resultBeforeLiftover;
return true;
}
// TODO: make ALT result as a supplementary alignment, store in firstALTResult
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Liftover Affine gap read 0 location %s:%llu score %d agScore %d mapq %d\n",
genome->getContigAtLocation(result->location[0])->name,
result->location[0] - genome->getContigAtLocation(result->location[0])->beginningLocation,
result->score[0], result->agScore[0], result->mapq[0]);
printf("Liftover Affine gap read 1 location %s:%llu score %d agScore %d mapq %d\n",
genome->getContigAtLocation(result->location[1])->name,
result->location[1] - genome->getContigAtLocation(result->location[1])->beginningLocation,
result->score[1], result->agScore[1], result->mapq[1]);
}
#endif
} // found ALT projections
} // useAltLiftover
} // use soft clipping mode
return true;
}
void
IntersectingPairedEndAligner::scoreLocationWithAffineGapLiftover(
unsigned whichRead,
Direction direction,
GenomeLocation genomeLocation,
unsigned seedOffset,
int scoreLimit,
int *score,
double *matchProbability,
int *genomeLocationOffset,
int *basesClippedBefore,
int *basesClippedAfter,
int *agScore,
int *genomeSpan,
bool useAltLiftover
)
{
Read *readToScore = reads[whichRead][direction];
unsigned readDataLength = readToScore->getDataLength();
GenomeDistance genomeDataLength = readDataLength + MAX_K; // Leave extra space in case the read has deletions
const char *data = genome->getSubstring(genomeLocation, genomeDataLength);
*genomeLocationOffset = 0;
*genomeSpan = 0;
if (NULL == data) {
*score = ScoreAboveLimit;
*matchProbability = 0;
*genomeLocationOffset = 0;
*agScore = ScoreAboveLimit;
return;
}
*basesClippedBefore = 0;
*basesClippedAfter = 0;
double matchProb1 = 1.0, matchProb2 = 1.0;
int score1 = 0, score2 = 0; // edit distance
// First, do the forward direction from where the seed aligns to past of it
int readLen = readToScore->getDataLength();
int seedLen = index->getSeedLength();
int agScore1 = 0, agScore2 = 0; // affine gap scores
int textLen, textRem;
if (genomeDataLength > INT32_MAX) {
textLen = INT32_MAX;
} else {
textLen = (int)(genomeDataLength);
}
textRem = 0;
int patternLen = readLen;
//
// Try banded affine-gap when pattern is long and band needed is small
//
if (patternLen >= (3 * (2 * (int)scoreLimit + 1)) && !disabledOptimizations.noBandedAffineGap) {
agScore1 = affineGap->computeScoreBanded(data,
textLen,
readToScore->getData(),
readToScore->getQuality(),
patternLen,
scoreLimit,
readLen,
direction,
&textRem,
basesClippedAfter,
&score1,
&matchProb1,
useSoftClip,
useAltLiftover);
} else {
agScore1 = affineGap->computeScore(data,
textLen,
readToScore->getData(),
readToScore->getQuality(),
patternLen,
scoreLimit,
readLen,
direction,
&textRem,
basesClippedAfter,
&score1,
&matchProb1,
useSoftClip,
useAltLiftover);
}
agScore1 -= readLen;
if (score1 != ScoreAboveLimit && score1 <= MAX_K - 1) {
int limitLeft = score1;
int patternLen = readLen - *basesClippedAfter;
//
// Try banded affine-gap when pattern is long and band needed is small
//
if (patternLen >= (3 * (2 * limitLeft + 1)) && !disabledOptimizations.noBandedAffineGap) {
agScore2 = reverseAffineGap->computeScoreBanded(data + readLen - textRem,
readLen - textRem,
reversedRead[whichRead][direction] + *basesClippedAfter,
reads[whichRead][OppositeDirection(direction)]->getQuality() + *basesClippedAfter,
patternLen,
limitLeft,
readLen,
direction,
genomeLocationOffset,
basesClippedBefore,
&score2,
&matchProb2,
useSoftClip,
useAltLiftover);
} else {
agScore2 = reverseAffineGap->computeScore(data + readLen - textRem,
readLen - textRem,
reversedRead[whichRead][direction] + *basesClippedAfter,
reads[whichRead][OppositeDirection(direction)]->getQuality() + *basesClippedAfter,
patternLen,
limitLeft,
readLen,
direction,
genomeLocationOffset,
basesClippedBefore,
&score2,
&matchProb2,
useSoftClip,
useAltLiftover);
}
agScore2 -= (readLen);
if (score2 == ScoreAboveLimit || score2 > MAX_K - 1) {
*score = ScoreAboveLimit;
*genomeLocationOffset = 0;
*agScore = -1;
} else {
*score = score2;
*agScore = agScore2;
*matchProbability = matchProb2;
*genomeLocationOffset = *basesClippedAfter + *genomeLocationOffset - textRem;
*genomeSpan = (readLen - textRem - *genomeLocationOffset);
}
} else {
*score = ScoreAboveLimit;
*genomeLocationOffset = 0;
*agScore = -1;
}
}
void
IntersectingPairedEndAligner::scoreLocationWithAffineGap(
unsigned whichRead,
Direction direction,
GenomeLocation genomeLocation,
unsigned seedOffset,
int scoreLimit,
int *score,
double *matchProbability,
int *genomeLocationOffset,
int *basesClippedBefore,
int *basesClippedAfter,
int *agScore,
int *genomeSpan,
bool useAltLiftover
)
{
Read *readToScore = reads[whichRead][direction];
unsigned readDataLength = readToScore->getDataLength();
GenomeDistance genomeDataLength = readDataLength + MAX_K; // Leave extra space in case the read has deletions
const char *data = genome->getSubstring(genomeLocation, genomeDataLength);
*genomeLocationOffset = 0;
*genomeSpan = 0;
if (NULL == data) {
*score = ScoreAboveLimit;
*matchProbability = 0;
*genomeLocationOffset = 0;
*agScore = ScoreAboveLimit;
return;
}
*basesClippedBefore = 0;
*basesClippedAfter = 0;
double matchProb1 = 1.0, matchProb2 = 1.0;
int score1 = 0, score2 = 0; // edit distance
// First, do the forward direction from where the seed aligns to past of it
int readLen = readToScore->getDataLength();
int seedLen = index->getSeedLength();
int agScore1 = seedLen, agScore2 = 0; // affine gap scores
if (!useAltLiftover) {
_ASSERT(!memcmp(data+seedOffset, readToScore->getData() + seedOffset, seedLen)); // that the seed actually matches. Cannot be guaranteed for ALT alignments that have been lifted over
}
int tailStart = seedOffset + seedLen;
int textLen, textRem;
if (genomeDataLength - tailStart > INT32_MAX) {
textLen = INT32_MAX;
} else {
textLen = (int)(genomeDataLength - tailStart);
}
textRem = readLen - tailStart;
if (tailStart != readLen) {
int patternLen = readLen - tailStart;
//
// Try banded affine-gap when pattern is long and band needed is small
//
if (patternLen >= (3 * (2 * (int)scoreLimit + 1)) && !disabledOptimizations.noBandedAffineGap) {
agScore1 = affineGap->computeScoreBanded(data + tailStart,
textLen,
readToScore->getData() + tailStart,
readToScore->getQuality() + tailStart,
readLen - tailStart,
scoreLimit,
readLen,
direction,
&textRem,
basesClippedAfter,
&score1,
&matchProb1,
useSoftClip,
useAltLiftover);
} else {
agScore1 = affineGap->computeScore(data + tailStart,
textLen,
readToScore->getData() + tailStart,
readToScore->getQuality() + tailStart,
readLen - tailStart,
scoreLimit,
readLen,
direction,
&textRem,
basesClippedAfter,
&score1,
&matchProb1,
useSoftClip,
useAltLiftover);
}
agScore1 += (seedLen - readLen);
nLocationsScoredAffineGap++;
}
if (score1 != ScoreAboveLimit) {
if (seedOffset != 0) {
int limitLeft = scoreLimit - score1;
int patternLen = seedOffset;
//
// Try banded affine-gap when pattern is long and band needed is small
//
if (patternLen >= (3 * (2 * limitLeft + 1)) && !disabledOptimizations.noBandedAffineGap) {
agScore2 = reverseAffineGap->computeScoreBanded(data + seedOffset,
seedOffset + limitLeft,
reversedRead[whichRead][direction] + readLen - seedOffset,
reads[whichRead][OppositeDirection(direction)]->getQuality() + readLen - seedOffset,
seedOffset,
limitLeft,
readLen,
direction,
genomeLocationOffset,
basesClippedBefore,
&score2,
&matchProb2,
useSoftClip,
useAltLiftover);
} else {
agScore2 = reverseAffineGap->computeScore(data + seedOffset,
seedOffset + limitLeft,
reversedRead[whichRead][direction] + readLen - seedOffset,
reads[whichRead][OppositeDirection(direction)]->getQuality() + readLen - seedOffset,
seedOffset,
limitLeft,
readLen,
direction,
genomeLocationOffset,
basesClippedBefore,
&score2,
&matchProb2,
useSoftClip,
useAltLiftover);
}
agScore2 -= (readLen);
if (score2 == ScoreAboveLimit) {
*score = ScoreAboveLimit;
*genomeLocationOffset = 0;
*agScore = -1;
}
}
} else {
*score = ScoreAboveLimit;
*genomeLocationOffset = 0;
*agScore = -1;
}
if (score1 != ScoreAboveLimit && score2 != ScoreAboveLimit) {
*score = score1 + score2;
// _ASSERT(*score <= scoreLimit);
// Map probabilities for substrings can be multiplied, but make sure to count seed too
*matchProbability = matchProb1 * matchProb2 * pow(1 - SNP_PROB, seedLen);
*genomeSpan = (seedOffset - *genomeLocationOffset) + seedLen + (readLen - tailStart - textRem);
*agScore = agScore1 + agScore2;
} else {
*score = ScoreAboveLimit;
*agScore = -1;
*matchProbability = 0.0;
}
}
void
IntersectingPairedEndAligner::scoreLocation(
unsigned whichRead,
Direction direction,
GenomeLocation genomeLocation,
unsigned seedOffset,
int scoreLimit,
int *score,
double *matchProbability,
int *genomeLocationOffset,
bool *usedAffineGapScoring,
int *basesClippedBefore,
int *basesClippedAfter,
int *agScore,
int *totalIndelsLV,
bool *usedGaplessClipping,
int *genomeSpan)
{
if (disabledOptimizations.noUkkonen) {
scoreLimit = maxK + extraSearchDepth;
}
Read *readToScore = reads[whichRead][direction];
unsigned readDataLength = readToScore->getDataLength();
GenomeDistance genomeDataLength = readDataLength + MAX_K; // Leave extra space in case the read has deletions
const char *data = genome->getSubstring(genomeLocation, genomeDataLength);
*genomeLocationOffset = 0;
*genomeSpan = 0;
*usedGaplessClipping = false;
int origScoreLimit = scoreLimit;
if (NULL == data) {
*score = ScoreAboveLimit;
*matchProbability = 0;
*genomeLocationOffset = 0;
*agScore = ScoreAboveLimit;
return;
}
*basesClippedBefore = 0;
*basesClippedAfter = 0;
// Compute the distance separately in the forward and backward directions from the seed, to allow
// arbitrary offsets at both the start and end but not have to pay the cost of exploring all start
// shifts in BoundedStringDistance
double matchProb1 = 1.0, matchProb2 = 1.0;
int score1 = 0, score2 = 0; // edit distance
// First, do the forward direction from where the seed aligns to past of it
int readLen = readToScore->getDataLength();
int seedLen = index->getSeedLength();
int tailStart = seedOffset + seedLen;
int agScore1 = seedLen, agScore2 = 0; // affine gap scores
_ASSERT(!memcmp(data+seedOffset, readToScore->getData() + seedOffset, seedLen)); // that the seed actually matches
int textLen;
if (genomeDataLength - tailStart > INT32_MAX) {
textLen = INT32_MAX;
} else {
textLen = (int)(genomeDataLength - tailStart);
}
int totalIndels1 = 0, totalIndels2 = 0, textSpan1 = 0, textSpan2 = 0;
nLocationsScoredLandauVishkin++;
score1 = landauVishkin->computeEditDistance(data + tailStart, textLen, readToScore->getData() + tailStart, readToScore->getQuality() + tailStart, readLen - tailStart,
scoreLimit, &matchProb1, NULL, &totalIndels1, &textSpan1);
agScore1 = (seedLen + readLen - tailStart - score1) * matchReward - score1 * subPenalty;
if (score1 != ScoreAboveLimit) {
int limitLeft = scoreLimit - score1;
score2 = reverseLandauVishkin->computeEditDistance(data + seedOffset, seedOffset + MAX_K, reversedRead[whichRead][direction] + readLen - seedOffset,
reads[whichRead][OppositeDirection(direction)]->getQuality() + readLen - seedOffset, seedOffset, limitLeft, &matchProb2, genomeLocationOffset, &totalIndels2, &textSpan2);
agScore2 = (seedOffset - score2) * matchReward - score2 * subPenalty;
}
if (score1 != ScoreAboveLimit && score2 != ScoreAboveLimit) {
*score = score1 + score2;
_ASSERT(*score <= scoreLimit);
// Map probabilities for substrings can be multiplied, but make sure to count seed too
*matchProbability = matchProb1 * matchProb2 * pow(1 - SNP_PROB, seedLen);
*agScore = agScore1 + agScore2;
*genomeSpan = textSpan1 + seedLen + textSpan2;
*totalIndelsLV = totalIndels1 + totalIndels2;
} else {
*score = ScoreAboveLimit;
*agScore = ScoreAboveLimit;
*matchProbability = 0.0;
}
if (disabledOptimizations.noEditDistance) {
//
// Score it with affine gap and throw away the result.
//
int TempScore, TempAgScore, agGenomeLocationOffset, agBasesClippedBefore, agBasesClippedAfter, agGenomeSpan;
double agMatchProbability;
scoreLocationWithAffineGap(whichRead, direction, genomeLocation, seedOffset, scoreLimit, &TempScore, &agMatchProbability, &agGenomeLocationOffset, &agBasesClippedBefore, &agBasesClippedAfter, &TempAgScore, &agGenomeSpan, false);
}
}
void
IntersectingPairedEndAligner::scoreLocationWithHammingDistance(
unsigned whichRead,
Direction direction,
GenomeLocation genomeLocation,
unsigned seedOffset,
int scoreLimit,
int* score,
double* matchProbability,
int* genomeLocationOffset,
bool* usedAffineGapScoring,
int* basesClippedBefore,
int* basesClippedAfter,
int* agScore,
bool* usedGaplessClipping,
int* scoreGapless)
{
if (disabledOptimizations.noUkkonen) {
scoreLimit = maxK + extraSearchDepth;
}
Read* readToScore = reads[whichRead][direction];
unsigned readDataLength = readToScore->getDataLength();
GenomeDistance genomeDataLength = readDataLength + MAX_K; // Leave extra space in case the read has deletions
const char* data = genome->getSubstring(genomeLocation, genomeDataLength);
*genomeLocationOffset = 0;
*usedGaplessClipping = false;
if (NULL == data) {
*score = ScoreAboveLimit;
*matchProbability = 0;
*genomeLocationOffset = 0;
*agScore = ScoreAboveLimit;
return;
}
*basesClippedBefore = 0;
*basesClippedAfter = 0;
double matchProb1 = 1.0, matchProb2 = 1.0;
int score1 = 0, score2 = 0; // Hamming distance including clipping
// First, do the forward direction from where the seed aligns to past of it
int readLen = readToScore->getDataLength();
int seedLen = index->getSeedLength();
int tailStart = seedOffset + seedLen;
int agScore1 = seedLen, agScore2 = 0; // affine gap scores
_ASSERT(!memcmp(data + seedOffset, readToScore->getData() + seedOffset, seedLen)); // that the seed actually matches
int textLen;
if (genomeDataLength - tailStart > INT32_MAX) {
textLen = INT32_MAX;
} else {
textLen = (int)(genomeDataLength - tailStart);
}
// Try gapless scoring to see if we can align the read after clipping
int score1Gapless = 0, score2Gapless = 0; // gapless scores are only for the unclipped portions
if (tailStart != readLen) {
agScore1 = affineGap->computeGaplessScore(data + tailStart, textLen, readToScore->getData() + tailStart, readToScore->getQuality() + tailStart, readLen - tailStart,
readLen, scoreLimit, &score1, NULL, NULL, &matchProb1, &score1Gapless);
agScore1 += (seedLen - readLen);
}
if (score1Gapless != ScoreAboveLimit) {
int limitLeft = scoreLimit - score1Gapless;
if (seedOffset != 0) {
agScore2 = reverseAffineGap->computeGaplessScore(data + seedOffset, seedOffset + MAX_K, reversedRead[whichRead][direction] + readLen - seedOffset,
reads[whichRead][OppositeDirection(direction)]->getQuality() + readLen - seedOffset, seedOffset, readLen, limitLeft, &score2, genomeLocationOffset, NULL, &matchProb2, &score2Gapless);
agScore2 -= (readLen);
if (score2Gapless == ScoreAboveLimit) {
*score = ScoreAboveLimit;
*genomeLocationOffset = 0;
*agScore = ScoreAboveLimit;
}
}
}
if (score1Gapless != ScoreAboveLimit && score2Gapless != ScoreAboveLimit) {
*score = score1 + score2;
// Map probabilities for substrings can be multiplied, but make sure to count seed too
*matchProbability = matchProb1 * matchProb2 * pow(1 - SNP_PROB, seedLen);
*agScore = agScore1 + agScore2;
*scoreGapless = score1Gapless + score2Gapless;
*usedGaplessClipping = true;
} else {
*score = ScoreAboveLimit;
*agScore = ScoreAboveLimit;
*matchProbability = 0.0;
*scoreGapless = ScoreAboveLimit;
}
}
void
IntersectingPairedEndAligner::HashTableHitSet::firstInit(unsigned maxSeeds_, unsigned maxMergeDistance_, BigAllocator *allocator, bool doesGenomeIndexHave64BitLocations_)
{
maxSeeds = maxSeeds_;
maxMergeDistance = maxMergeDistance_;
doesGenomeIndexHave64BitLocations = doesGenomeIndexHave64BitLocations_;
nLookupsUsed = 0;
if (doesGenomeIndexHave64BitLocations) {
lookups64 = (HashTableLookup<GenomeLocation> *)allocator->allocate(sizeof(HashTableLookup<GenomeLocation>) * maxSeeds);
lookups32 = NULL;
} else {
lookups32 = (HashTableLookup<unsigned> *)allocator->allocate(sizeof(HashTableLookup<unsigned>) * maxSeeds);
lookups64 = NULL;
}
disjointHitSets = (DisjointHitSet *)allocator->allocate(sizeof(DisjointHitSet) * maxSeeds);
}
void
IntersectingPairedEndAligner::HashTableHitSet::init()
{
nLookupsUsed = 0;
currentDisjointHitSet = -1;
if (doesGenomeIndexHave64BitLocations) {
lookupListHead64->nextLookupWithRemainingMembers = lookupListHead64->prevLookupWithRemainingMembers = lookupListHead64;
lookupListHead32->nextLookupWithRemainingMembers = lookupListHead32->prevLookupWithRemainingMembers = NULL;
} else {
lookupListHead32->nextLookupWithRemainingMembers = lookupListHead32->prevLookupWithRemainingMembers = lookupListHead32;
lookupListHead64->nextLookupWithRemainingMembers = lookupListHead64->prevLookupWithRemainingMembers = NULL;
}
}
//
// I apologize for this, but I had to do two versions of recordLookup, one for the 32 bit and one for the 64 bit version. The options were
// copying the code or doing a macro with the types as parameters. I chose macro, so you get ugly but unlikely to accidentally diverge.
// At least it's just isolated to the HashTableHitSet class.
//
#define RL(lookups, glType, lookupListHead) \
void \
IntersectingPairedEndAligner::HashTableHitSet::recordLookup(unsigned seedOffset, _int64 nHits, const glType *hits, bool beginsDisjointHitSet) \
{ \
_ASSERT(nLookupsUsed < maxSeeds); \
if (beginsDisjointHitSet) { \
currentDisjointHitSet++; \
_ASSERT(currentDisjointHitSet < (int)maxSeeds); \
disjointHitSets[currentDisjointHitSet].countOfExhaustedHits = 0; \
} \
\
if (0 == nHits) { \
disjointHitSets[currentDisjointHitSet].countOfExhaustedHits++; \
} else { \
_ASSERT(currentDisjointHitSet != -1); /* Essentially that beginsDisjointHitSet is set for the first recordLookup call */ \
lookups[nLookupsUsed].currentHitForIntersection = 0; \
lookups[nLookupsUsed].hits = hits; \
lookups[nLookupsUsed].nHits = nHits; \
lookups[nLookupsUsed].seedOffset = seedOffset; \
lookups[nLookupsUsed].whichDisjointHitSet = currentDisjointHitSet; \
\
/* Trim off any hits that are smaller than seedOffset, since they are clearly meaningless. */ \
\
while (lookups[nLookupsUsed].nHits > 0 && lookups[nLookupsUsed].hits[lookups[nLookupsUsed].nHits - 1] < lookups[nLookupsUsed].seedOffset) { \
lookups[nLookupsUsed].nHits--; \
} \
\
/* Add this lookup into the non-empty lookup list. */ \
\
lookups[nLookupsUsed].prevLookupWithRemainingMembers = lookupListHead; \
lookups[nLookupsUsed].nextLookupWithRemainingMembers = lookupListHead->nextLookupWithRemainingMembers; \
lookups[nLookupsUsed].prevLookupWithRemainingMembers->nextLookupWithRemainingMembers = \
lookups[nLookupsUsed].nextLookupWithRemainingMembers->prevLookupWithRemainingMembers = &lookups[nLookupsUsed]; \
\
if (doAlignerPrefetch) { \
_mm_prefetch((const char *)&lookups[nLookupsUsed].hits[lookups[nLookupsUsed].nHits / 2], _MM_HINT_T2); \
} \
\
nLookupsUsed++; \
} \
}
RL(lookups32, unsigned, lookupListHead32)
RL(lookups64, GenomeLocation, lookupListHead64)
#undef RL
unsigned
IntersectingPairedEndAligner::HashTableHitSet::computeBestPossibleScoreForCurrentHit()
{
//
// Now compute the best possible score for the hit. This is the largest number of misses in any disjoint hit set.
//
for (int i = 0; i <= currentDisjointHitSet; i++) {
disjointHitSets[i].missCount = disjointHitSets[i].countOfExhaustedHits;
}
//
// Another macro. Sorry again.
//
#define loop(glType, lookupListHead) \
for (HashTableLookup<glType> *lookup = lookupListHead->nextLookupWithRemainingMembers; lookup != lookupListHead; \
lookup = lookup->nextLookupWithRemainingMembers) { \
\
if (!(lookup->currentHitForIntersection != lookup->nHits && \
genomeLocationIsWithin(lookup->hits[lookup->currentHitForIntersection], mostRecentLocationReturned + lookup->seedOffset, maxMergeDistance) || \
lookup->currentHitForIntersection != 0 && \
genomeLocationIsWithin(lookup->hits[lookup->currentHitForIntersection-1], mostRecentLocationReturned + lookup->seedOffset, maxMergeDistance))) { \
\
/* This one was not close enough. */ \
\
disjointHitSets[lookup->whichDisjointHitSet].missCount++; \
} \
}
if (doesGenomeIndexHave64BitLocations) {
loop(GenomeLocation, lookupListHead64);
} else {
loop(unsigned, lookupListHead32);
}
#undef loop
unsigned bestPossibleScoreSoFar = 0;
for (int i = 0; i <= currentDisjointHitSet; i++) {
bestPossibleScoreSoFar = max(bestPossibleScoreSoFar, disjointHitSets[i].missCount);
}
return bestPossibleScoreSoFar;
}
bool
IntersectingPairedEndAligner::HashTableHitSet::getNextHitLessThanOrEqualTo(GenomeLocation maxGenomeLocationToFind, GenomeLocation *actualGenomeLocationFound, unsigned *seedOffsetFound)
{
bool anyFound = false;
GenomeLocation bestLocationFound = 0;
for (unsigned i = 0; i < nLookupsUsed; i++) {
//
// Binary search from the current starting offset to either the right place or the end.
//
_int64 limit[2];
GenomeLocation maxGenomeLocationToFindThisSeed;
if (doesGenomeIndexHave64BitLocations) {
limit[0] = (_int64)lookups64[i].currentHitForIntersection;
limit[1] = (_int64)lookups64[i].nHits - 1;
maxGenomeLocationToFindThisSeed = maxGenomeLocationToFind + lookups64[i].seedOffset;
} else {
limit[0] = (_int64)lookups32[i].currentHitForIntersection;
limit[1] = (_int64)lookups32[i].nHits - 1;
maxGenomeLocationToFindThisSeed = maxGenomeLocationToFind + lookups32[i].seedOffset;
}
while (limit[0] <= limit[1]) {
_int64 probe = (limit[0] + limit[1]) / 2;
if (doAlignerPrefetch) { // not clear this helps. We're probably not far enough ahead.
if (doesGenomeIndexHave64BitLocations) {
_mm_prefetch((const char *)&lookups64[i].hits[(limit[0] + probe) / 2 - 1], _MM_HINT_T2);
_mm_prefetch((const char *)&lookups64[i].hits[(limit[1] + probe) / 2 + 1], _MM_HINT_T2);
} else {
_mm_prefetch((const char *)&lookups32[i].hits[(limit[0] + probe) / 2 - 1], _MM_HINT_T2);
_mm_prefetch((const char *)&lookups32[i].hits[(limit[1] + probe) / 2 + 1], _MM_HINT_T2);
}
}
//
// Recall that the hit sets are sorted from largest to smallest, so the strange looking logic is actually right.
// We're evaluating the expression "lookups[i].hits[probe] <= maxGenomeOffsetToFindThisSeed && (probe == 0 || lookups[i].hits[probe-1] > maxGenomeOffsetToFindThisSeed)"
// It's written in this strange way just so the profile tool will show us where the time's going.
//
GenomeLocation probeHit;
GenomeLocation probeMinusOneHit;
unsigned seedOffset;
if (doesGenomeIndexHave64BitLocations) {
probeHit = lookups64[i].hits[probe];
probeMinusOneHit = lookups64[i].hits[probe-1];
seedOffset = lookups64[i].seedOffset;
} else {
probeHit = lookups32[i].hits[probe];
probeMinusOneHit = lookups32[i].hits[probe-1];
seedOffset = lookups32[i].seedOffset;
}
unsigned clause1 = probeHit <= maxGenomeLocationToFindThisSeed;
unsigned clause2 = probe == 0;
if (clause1 && (clause2 || probeMinusOneHit > maxGenomeLocationToFindThisSeed)) {
if (probeHit - seedOffset > bestLocationFound) {
anyFound = true;
mostRecentLocationReturned = *actualGenomeLocationFound = bestLocationFound = probeHit - seedOffset;
*seedOffsetFound = seedOffset;
}
if (doesGenomeIndexHave64BitLocations) {
lookups64[i].currentHitForIntersection = probe;
} else {
lookups32[i].currentHitForIntersection = probe;
}
break;
}
if (probeHit > maxGenomeLocationToFindThisSeed) { // Recode this without the if to avoid the hard-to-predict branch.
limit[0] = probe + 1;
} else {
limit[1] = probe - 1;
}
} // While we're looking
if (limit[0] > limit[1]) {
// We're done with this lookup.
if (doesGenomeIndexHave64BitLocations) {
lookups64[i].currentHitForIntersection = lookups64[i].nHits;
} else {
lookups32[i].currentHitForIntersection = lookups32[i].nHits;
}
}
} // For each lookup
_ASSERT(!anyFound || *actualGenomeLocationFound <= maxGenomeLocationToFind);
return anyFound;
}
bool
IntersectingPairedEndAligner::HashTableHitSet::getFirstHit(GenomeLocation *genomeLocation, unsigned *seedOffsetFound)
{
bool anyFound = false;
*genomeLocation = 0;
//
// Yet another macro. This makes me want to write in a better language sometimes. But then it would be too slow. :-(
//
#define LOOP(lookups) \
for (unsigned i = 0; i < nLookupsUsed; i++) { \
if (lookups[i].nHits > 0 && lookups[i].hits[0] - lookups[i].seedOffset > GenomeLocationAsInt64(*genomeLocation)) { \
mostRecentLocationReturned = *genomeLocation = lookups[i].hits[0] - lookups[i].seedOffset; \
*seedOffsetFound = lookups[i].seedOffset; \
anyFound = true; \
} \
}
if (doesGenomeIndexHave64BitLocations) {
LOOP(lookups64);
} else {
LOOP(lookups32);
}
#undef LOOP
return !anyFound;
}
bool
IntersectingPairedEndAligner::HashTableHitSet::getNextLowerHit(GenomeLocation *genomeLocation, unsigned *seedOffsetFound)
{
//
// Look through all of the lookups and find the one with the highest location smaller than the current one.
//
GenomeLocation foundLocation = 0;
bool anyFound = false;
//
// Run through the lookups pushing up any that are at the most recently returned
//
for (unsigned i = 0; i < nLookupsUsed; i++) {
_int64 *currentHitForIntersection;
_int64 nHits;
GenomeLocation hitLocation;
unsigned seedOffset;
//
// A macro to initialize stuff that we need to avoid a bigger macro later.
//
#define initVars(lookups) \
currentHitForIntersection = &lookups[i].currentHitForIntersection; \
nHits = lookups[i].nHits; \
seedOffset = lookups[i].seedOffset; \
if (nHits != *currentHitForIntersection) { \
hitLocation = lookups[i].hits[*currentHitForIntersection]; \
}
if (doesGenomeIndexHave64BitLocations) {
initVars(lookups64);
} else {
initVars(lookups32);
}
#undef initVars
_ASSERT(*currentHitForIntersection == nHits || hitLocation - seedOffset <= mostRecentLocationReturned || hitLocation < seedOffset);
if (*currentHitForIntersection != nHits && hitLocation - seedOffset == mostRecentLocationReturned) {
(*currentHitForIntersection)++;
if (*currentHitForIntersection == nHits) {
continue;
}
if (doesGenomeIndexHave64BitLocations) {
hitLocation = lookups64[i].hits[*currentHitForIntersection];
} else {
hitLocation = lookups32[i].hits[*currentHitForIntersection];
}
}
if (*currentHitForIntersection != nHits) {
if (foundLocation < hitLocation - seedOffset && // found location is OK
hitLocation >= seedOffset) // found location isn't too small to push us before the beginning of the genome
{
*genomeLocation = foundLocation = hitLocation - seedOffset;
*seedOffsetFound = seedOffset;
anyFound = true;
}
}
}
if (anyFound) {
mostRecentLocationReturned = foundLocation;
}
return anyFound;
}
bool
IntersectingPairedEndAligner::MergeAnchor::checkMerge(GenomeLocation newMoreHitLocation, GenomeLocation newFewerHitLocation, double newMatchProbability, int newPairScore,
int newPairAGScore, double *oldMatchProbability, bool *mergeReplacement)
{
if (locationForReadWithMoreHits == InvalidGenomeLocation || !doesRangeMatch(newMoreHitLocation, newFewerHitLocation)) {
//
// No merge. Remember the new one.
//
locationForReadWithMoreHits = newMoreHitLocation;
locationForReadWithFewerHits = newFewerHitLocation;
matchProbability = newMatchProbability;
pairScore = newPairScore;
pairAGScore = newPairAGScore;
*oldMatchProbability = 0.0;
*mergeReplacement = false;
return false;
} else {
//
// Within merge distance. Keep the better score (or if they're tied the better match probability).
//
if (newPairAGScore > pairAGScore || (newPairAGScore == pairAGScore && newMatchProbability > matchProbability)) {
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Merge replacement at anchor (%llu, %llu), loc (%llu, %llu), old match prob %e, new match prob %e, old pair score %d, new pair score %d\n",
locationForReadWithMoreHits.location, locationForReadWithFewerHits.location, newMoreHitLocation.location, newFewerHitLocation.location,
matchProbability, newMatchProbability, pairScore, newPairScore);
}
#endif // DEBUG
* oldMatchProbability = matchProbability;
matchProbability = newMatchProbability;
pairScore = newPairScore;
pairAGScore = newPairAGScore;
*mergeReplacement = true;
return false;
} else {
//
// The new one should just be ignored.
//
#ifdef _DEBUG
if (_DumpAlignments) {
printf("Merged at anchor (%llu, %llu), loc (%llu, %llu), old match prob %e, new match prob %e, old pair score %d, new pair score %d\n",
locationForReadWithMoreHits.location, locationForReadWithFewerHits.location, newMoreHitLocation.location, newFewerHitLocation.location,
matchProbability, newMatchProbability, pairScore, newPairScore);
}
#endif // DEBUG
*mergeReplacement = false;
return true;
}
}
_ASSERT(!"NOTREACHED");
}
void IntersectingPairedEndAligner::ScoreSet::updateProbabilityOfAllPairs(double oldPairProbability)
{
probabilityOfAllPairs = __max(0, probabilityOfAllPairs - oldPairProbability);
}
bool IntersectingPairedEndAligner::ScoreSet::updateBestHitIfNeeded(int pairScore, int pairAGScore, double pairProbability, int fewerEndScore, int readWithMoreHits, GenomeDistance fewerEndGenomeLocationOffset, ScoringCandidate* candidate, ScoringMateCandidate* mate)
{
probabilityOfAllPairs += pairProbability;
int readWithFewerHits = 1 - readWithMoreHits;
if (pairAGScore > bestPairAGScore || (pairAGScore == bestPairAGScore && pairProbability > probabilityOfBestPair)) {
bestPairScore = pairScore;
bestPairAGScore = pairAGScore;
probabilityOfBestPair = pairProbability;
bestResultGenomeLocation[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation + fewerEndGenomeLocationOffset;
bestResultGenomeLocation[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation + mate->genomeOffset;
bestResultOrigGenomeLocation[readWithFewerHits] = candidate->readWithFewerHitsGenomeLocation;
bestResultOrigGenomeLocation[readWithMoreHits] = mate->readWithMoreHitsGenomeLocation;
bestResultScore[readWithFewerHits] = fewerEndScore;
bestResultScore[readWithMoreHits] = mate->score;
bestResultDirection[readWithFewerHits] = setPairDirection[candidate->whichSetPair][readWithFewerHits];
bestResultDirection[readWithMoreHits] = setPairDirection[candidate->whichSetPair][readWithMoreHits];
bestResultUsedAffineGapScoring[readWithFewerHits] = candidate->usedAffineGapScoring;
bestResultUsedAffineGapScoring[readWithMoreHits] = mate->usedAffineGapScoring;
bestResultUsedGaplessClipping[readWithFewerHits] = candidate->usedGaplessClipping;
bestResultUsedGaplessClipping[readWithMoreHits] = mate->usedGaplessClipping;
bestResultBasesClippedBefore[readWithFewerHits] = candidate->basesClippedBefore;
bestResultBasesClippedAfter[readWithFewerHits] = candidate->basesClippedAfter;
bestResultBasesClippedBefore[readWithMoreHits] = mate->basesClippedBefore;
bestResultBasesClippedAfter[readWithMoreHits] = mate->basesClippedAfter;
bestResultAGScore[readWithFewerHits] = candidate->agScore;
bestResultAGScore[readWithMoreHits] = mate->agScore;
bestResultSeedOffset[readWithFewerHits] = candidate->seedOffset;
bestResultSeedOffset[readWithMoreHits] = mate->seedOffset;
bestResultMatchProbability[readWithFewerHits] = candidate->matchProbability;
bestResultMatchProbability[readWithMoreHits] = mate->matchProbability;
bestResultLVIndels[readWithFewerHits] = candidate->lvIndels;
bestResultLVIndels[readWithMoreHits] = mate->lvIndels;
bestResultRefSpan[readWithFewerHits] = candidate->refSpan;
bestResultRefSpan[readWithMoreHits] = mate->refSpan;
return true;
} else {
return false;
}
} // updateBestHitIfNeeded
bool IntersectingPairedEndAligner::ScoreSet::updateBestHitIfNeeded(int pairScore, int pairAGScore, double pairProbability, PairedAlignmentResult* newResult)
{
probabilityOfAllPairs += pairProbability;
if (pairAGScore > bestPairAGScore || (pairAGScore == bestPairAGScore && pairProbability > probabilityOfBestPair)) {
bestPairScore = pairScore;
bestPairAGScore = pairAGScore;
probabilityOfBestPair = pairProbability;
for (int r = 0; r < NUM_READS_PER_PAIR; r++) {
bestResultGenomeLocation[r] = newResult->location[r];
bestResultOrigGenomeLocation[r] = newResult->origLocation[r];
bestResultScore[r] = newResult->score[r];
bestResultDirection[r] = newResult->direction[r];
bestResultUsedAffineGapScoring[r] = newResult->usedAffineGapScoring[r];
bestResultUsedGaplessClipping[r] = newResult->usedGaplessClipping[r];
bestResultBasesClippedBefore[r] = newResult->basesClippedBefore[r];
bestResultBasesClippedAfter[r] = newResult->basesClippedAfter[r];
bestResultAGScore[r] = newResult->agScore[r];
bestResultSeedOffset[r] = newResult->seedOffset[r];
bestResultMatchProbability[r] = newResult->matchProbability[r];
bestResultLVIndels[r] = newResult->lvIndels[r];
bestResultRefSpan[r] = newResult->refSpan[r];
}
return true;
}
else {
return false;
}
} // updateBestHitIfNeeded
void IntersectingPairedEndAligner::ScoreSet::fillInResult(PairedAlignmentResult* result, unsigned *popularSeedsSkipped)
{
for (unsigned whichRead = 0; whichRead < NUM_READS_PER_PAIR; whichRead++) {
result->location[whichRead] = bestResultGenomeLocation[whichRead];
result->origLocation[whichRead] = bestResultOrigGenomeLocation[whichRead];
result->direction[whichRead] = bestResultDirection[whichRead];
result->mapq[whichRead] = computeMAPQ(probabilityOfAllPairs, probabilityOfBestPair, bestResultScore[whichRead], popularSeedsSkipped[0] + popularSeedsSkipped[1]);
result->status[whichRead] = result->mapq[whichRead] > MAPQ_LIMIT_FOR_SINGLE_HIT ? SingleHit : MultipleHits;
result->score[whichRead] = bestResultScore[whichRead];
result->clippingForReadAdjustment[whichRead] = 0;
result->usedAffineGapScoring[whichRead] = bestResultUsedAffineGapScoring[whichRead];
result->usedGaplessClipping[whichRead] = bestResultUsedGaplessClipping[whichRead];
result->basesClippedBefore[whichRead] = bestResultBasesClippedBefore[whichRead];
result->basesClippedAfter[whichRead] = bestResultBasesClippedAfter[whichRead];
result->agScore[whichRead] = bestResultAGScore[whichRead];
result->seedOffset[whichRead] = bestResultSeedOffset[whichRead];
result->lvIndels[whichRead] = bestResultLVIndels[whichRead];
result->matchProbability[whichRead] = bestResultMatchProbability[whichRead];
result->popularSeedsSkipped[whichRead] = popularSeedsSkipped[whichRead];
result->refSpan[whichRead] = bestResultRefSpan[whichRead];
} // for each read in the pair
result->probabilityAllPairs = probabilityOfAllPairs;
} // fillInResult
int IntersectingPairedEndAligner::computeScoreLimit(bool nonALTAlignment, const ScoreSet * scoresForAllAlignments, const ScoreSet * scoresForNonAltAlignments, GenomeDistance maxBigIndelSeen)
{
if (nonALTAlignment) {
//
// For a non-ALT alignment to matter, it must be no worse than maxScoreGapToPreferNonAltAlignment of the best ALT alignment and at least as good as the best non-ALT alignment.
//
return (int)__min(MAX_K - 1, extraSearchDepth + __min(maxK + maxBigIndelSeen, __min(scoresForAllAlignments->bestPairScore + maxScoreGapToPreferNonAltAlignment, scoresForNonAltAlignments->bestPairScore)));
} else {
//
// For an ALT alignment to matter, it has to be at least maxScoreGapToPreferNonAltAlignment better than the best non-ALT alignment, and better than the best ALT alignment.
//
return(int) __min(MAX_K - 1, extraSearchDepth + __min(maxK + maxBigIndelSeen, __min(scoresForAllAlignments->bestPairScore, scoresForNonAltAlignments->bestPairScore - maxScoreGapToPreferNonAltAlignment)));
}
}
const unsigned IntersectingPairedEndAligner::maxMergeDistance = 31;
#if INSTRUMENTATION_FOR_PAPER
int
IntersectingPairedEndAligner::HashTableHitSet::getNumDistinctHitLocations(unsigned maxK)
{
int nextSeed[MAX_MAX_SEEDS];
int nDistinctHits = 0;
GenomeLocation currentAnchor = InvalidGenomeLocation;
int nSetsRemaining = nLookupsUsed;
for (int i = 0; i < nLookupsUsed; i++) {
nextSeed[i] = 0;
}
#define BODY(lookups) \
while (true) { \
int setForThisPass = -1; \
GenomeLocation locationForThisPass = 0; \
for (int whichSet = 0; whichSet < nLookupsUsed; whichSet++) { \
if (lookups[whichSet].nHits == nextSeed[whichSet]) { \
nextSeed[whichSet]++; \
nSetsRemaining--; \
} else if (lookups[whichSet].nHits > nextSeed[whichSet] && \
((GenomeLocation)lookups[whichSet].hits[nextSeed[whichSet]] - \
lookups[whichSet].seedOffset) > locationForThisPass) { \
setForThisPass = whichSet; \
locationForThisPass = lookups[whichSet].hits[nextSeed[whichSet]] - \
lookups[whichSet].seedOffset; \
} \
} \
\
_ASSERT(nSetsRemaining == 0 || setForThisPass != -1); \
if (nSetsRemaining == 0) { \
return nDistinctHits; \
} \
\
if (currentAnchor - locationForThisPass > maxK) { \
nDistinctHits++; \
currentAnchor = locationForThisPass; \
} \
\
nextSeed[setForThisPass]++; \
}
if (doesGenomeIndexHave64BitLocations) {
BODY(lookups64);
} else {
while (true) {
int setForThisPass = -1;
GenomeLocation locationForThisPass = 0;
for (int whichSet = 0; whichSet < nLookupsUsed; whichSet++) {
if (lookups32[whichSet].nHits == nextSeed[whichSet]) {
nSetsRemaining--;
nextSeed[whichSet]++;
} else if (lookups32[whichSet].nHits > nextSeed[whichSet] &&
((GenomeLocation)lookups32[whichSet].hits[nextSeed[whichSet]] - lookups32[whichSet].seedOffset) > locationForThisPass) {
setForThisPass = whichSet;
locationForThisPass = lookups32[whichSet].hits[nextSeed[whichSet]] - lookups32[whichSet].seedOffset;
}
}
_ASSERT(nSetsRemaining == 0 || setForThisPass != -1);
if (nSetsRemaining == 0) {
return nDistinctHits;
}
if (currentAnchor - locationForThisPass > maxK) {
nDistinctHits++;
currentAnchor = locationForThisPass;
}
nextSeed[setForThisPass]++;
}
}
#undef BODY
_ASSERT(!"NOTREACHED");
return -1;
}
#endif // INSTRUMENTATION_FOR_PAPER
|