1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407
|
#include "rlink.h"
#include "GBitVec.h"
#include <float.h>
//#define GMEMTRACE 1 //debugging memory allocation
#ifdef GMEMTRACE
#include "proc_mem.h"
#endif
#define BSIZE 10000 // bundle size
//import globals from main program:
//extern GffNames* gseqNames;
extern FILE *c_out; // file handle for the input transcripts that are fully covered by reads
extern bool trim;
extern bool eonly;
extern bool nomulti;
extern bool viral;
extern bool mixedMode;
extern bool guided;
extern int allowed_nodes;
extern float isofrac;
extern bool isunitig;
extern bool longreads;
extern bool rawreads;
extern float mcov;
extern int mintranscriptlen; // minimum number for a transcript to be printed
extern uint junctionsupport; // anchor length for junction to be considered well supported <- consider shorter??
extern uint sserror;
extern int junctionthr; // number of reads needed to support a particular junction
extern float readthr; // read coverage per bundle bp to accept it; otherwise considered noise
extern float singlethr; // read coverage per bundle bp to accept it; otherwise considered noise
extern uint bundledist; // reads at what distance should be considered part of separate bundles
// <- this is not addressed everywhere, e.g. in infer_transcripts -> look into this
extern bool includesource;
extern bool geneabundance; // need to compute the gene abundance
extern float fpkm_thr;
extern float tpm_thr;
extern bool enableNames;
extern bool includecov;
extern bool retained_intron;
extern FILE* f_out;
extern GStr label;
static GStr _id("", 256); //to prevent repeated reallocation for each parsed read
//not thread safe -- to only be used in processRead() as long as that's the unique producer
CJunction* add_junction(int start, int end, GList<CJunction>& junction, char strand) {
int oidx=-1;
CJunction *nj=NULL;
CJunction jn(start, end, strand);
if (junction.Found(&jn, oidx)) {
nj=junction.Get(oidx);
}
else {
nj=new CJunction(start, end, strand);
junction.Add(nj);
}
return nj;
}
void printTime(FILE* f) {
time_t ltime; /* calendar time */
ltime=time(NULL);
struct tm *t=localtime(<ime);
fprintf(f, "[%02d/%02d %02d:%02d:%02d]",t->tm_mon+1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec);
}
void printBitVec(GBitVec& bv) {
for (uint i=0;i<bv.size();i++) {
fprintf(stderr, "%c", bv.test(i)?'1':'0');
}
}
void cov_edge_add(GVec<float> *bpcov, int sno, int start, int end, float v) {
bool neutral=false;
if(sno!=1) neutral=true; // why is neutral true here: because if the sno is -/+ than I want to add their counts to bpcov[1] too
bpcov[sno][start+1]+=v; // if sno==1 then I add v to it here
bpcov[sno][end+1]-=v;
if(neutral) { // if neutral (i.e. stranded) gets added to bpcov[1] here too => bpcov[1]=all coverage
bpcov[1][start+1]+=v;
bpcov[1][end+1]-=v;
}
}
void add_read_to_cov(GList<CReadAln>& rd,int n,GVec<float> *bpcov,int refstart) {
int sno=(int)rd[n]->strand+1; // 0(-),1(.),2(+)
float single_count=rd[n]->read_count;
for(int i=0;i<rd[n]->pair_idx.Count();i++) {
single_count-=rd[n]->pair_count[i];
if(rd[n]->pair_idx[i]<=n) { // pair comes before
int np=rd[n]->pair_idx[i];
int pcount=rd[np]->segs.Count();
int rcount=rd[n]->segs.Count();
int snop=(int)rd[np]->strand+1; //v6
int p=0;
int r=0;
int nsegs=pcount+rcount;
while(nsegs) {
int start;
int end;
if(r<rcount) {
if(p==pcount || rd[np]->segs[p].start>rd[n]->segs[r].end) { // no more pair segments or pair segment comes after read segment
start=rd[n]->segs[r].start;
end=rd[n]->segs[r].end;
r++;
nsegs--;
}
else if(rd[np]->segs[p].end<rd[n]->segs[r].start) {
start=rd[np]->segs[p].start;
end=rd[np]->segs[p].end;
p++;
nsegs--;
}
else { // segments overlap
start=rd[np]->segs[p].start;
end=rd[np]->segs[p].end;
if((int)rd[n]->segs[r].start<start) start=rd[n]->segs[r].start;
p++;
nsegs--;
bool cont=true;
while(cont) {
cont=false;
if(r<rcount && (int)(rd[n]->segs[r].start)<=end) {
if((int)rd[n]->segs[r].end>end) end=rd[n]->segs[r].end;
r++;
nsegs--;
cont=true;
}
if(p<pcount && (int)(rd[np]->segs[p].start)<=end) {
if((int)rd[np]->segs[p].end>end) end=rd[np]->segs[p].end;
p++;
nsegs--;
cont=true;
}
}
}
}
else {
start=rd[np]->segs[p].start;
end=rd[np]->segs[p].end;
p++;
nsegs--;
}
int strand=sno;
if(sno!=snop) {
if(sno==1) strand=snop;
else if(snop!=1) strand=1;
}
cov_edge_add(bpcov,strand,start-refstart,end-refstart+1,rd[n]->pair_count[i]);
}
}
}
if(single_count>epsilon) {
for(int i=0;i<rd[n]->segs.Count();i++) {
cov_edge_add(bpcov,sno,rd[n]->segs[i].start-refstart,rd[n]->segs[i].end-refstart+1,single_count);
}
}
}
void countFragment(BundleData& bdata, GSamRecord& brec, int nh) {
static uint32_t BAM_R2SINGLE = BAM_FREAD2 | BAM_FMUNMAP ;
for (int i=0;i<brec.exons.Count();i++) {
bdata.frag_len+=float(1)*brec.exons[i].len()/nh;
}
if (!brec.isPaired() || ((brec.flags()&BAM_FREAD1)!=0) ||
((brec.flags()&BAM_R2SINGLE)==BAM_R2SINGLE ) ) {
bdata.num_fragments+=float(1)/nh;
}
}
bool deljuncmatch(CReadAln *rd,GVec<GSeg> &jd) {
if(rd->juncs.Count()!=jd.Count()) return(false);
for(int i=0;i<rd->juncs.Count();i++) {
uint startj=rd->segs[i].end-rd->juncs[i]->start;
uint endj=rd->juncs[i]->end-rd->segs[i+1].start;
if(startj!=jd[i].start || endj!=jd[i].end) return(false);
}
return(true);
}
bool exonmatch(GVec<GSeg> &prevexons, GVec<GSeg> &exons) {
if(prevexons.Count() != exons.Count()) return false;
for(int i=0;i<exons.Count();i++) {
if(prevexons[i].end!=exons[i].end || prevexons[i].start!=exons[i].start) return false;
}
return true;
}
bool mismatch_anchor(CReadAln *rd,char *mdstr,int refstart, bam1_t *b) {
if(mdstr==NULL) return false;
//--make a copy of the string, in case the original is a const string
// (because the parseUInt() function modifies the string temporarily
char* mdstring=Gstrdup(mdstr);
char *p=mdstring;
int i=0;
int parsedlen=refstart;
int rdlen=0;
while (*p!='\0') {
unsigned int num_matches=0;
if (*p>='0' && *p<='9') {
parseUInt(p,num_matches);
//if (num_matches>0) GMessage("%d matching bases\n", num_matches);
parsedlen+=num_matches;
continue;
}
if (*p=='^') { //deletion --> found a problem with deletion
//GDynArray<char> deletion; //deletion string accumulates here (if needed)
int del_length=0;//tracking deletion length
char delbase=*(++p);
while (delbase>='A' && delbase<='Z') {
//deletion.Add(delbase);
del_length++;
delbase=*(++p);
}
while(i<rd->segs.Count() && rdlen+(int)rd->segs[i].len()<parsedlen) {
rdlen+=rd->segs[i].len();
i++;
}
if(i==rd->segs.Count()) break;
if((i && parsedlen-rd->segs[i].start<junctionsupport) || (i<rd->segs.Count()-1 && rd->segs[i].end+1-parsedlen-del_length<junctionsupport)) {
GFREE(mdstring);
return true;
}
parsedlen+=del_length;
/*GMessage("%d base(s) deletion [", del_length);
for (uint i=0;i<deletion.Count();++i) GMessage("%c",deletion[i]);
GMessage("]\n");*/
continue;
}
if (*p>='A' && *p<='Z') {
//GMessage("base mismatch [%c]\n",*p);
while(i<rd->segs.Count() && rdlen+(int)rd->segs[i].len()<parsedlen) {
rdlen+=rd->segs[i].len();
i++;
}
if(i==rd->segs.Count()) break;
if((i && parsedlen-rd->segs[i].start<junctionsupport) || (i<rd->segs.Count()-1 && rd->segs[i].end-parsedlen<junctionsupport)) {
GFREE(mdstring);
return true;
}
parsedlen++;
}
p++;
}
GFREE(mdstring);
uint32_t *cigar = bam_get_cigar(b);
rdlen=0;
parsedlen=0;
i=0;
for (uint j = 0; j < b->core.n_cigar; ++j) {
int op = bam_cigar_op(cigar[j]);
if (op == BAM_CMATCH || op==BAM_CEQUAL ||
op == BAM_CDIFF || op == BAM_CDEL) {
parsedlen += bam_cigar_oplen(cigar[j]);
}
else if(op == BAM_CINS) {
while(i<rd->segs.Count() && rdlen+(int)rd->segs[i].len()<parsedlen) {
rdlen+=rd->segs[i].len();
i++;
}
if(i==rd->segs.Count()) break;
if((i && parsedlen-rd->segs[i].start<junctionsupport) || (i<rd->segs.Count()-1 && rd->segs[i].end-parsedlen<junctionsupport)) {
return true;
}
}
}
return false;
}
void processRead(int currentstart, int currentend, BundleData& bdata,
GHash<int>& hashread, GReadAlnData& alndata) { // some false positives should be eliminated here in order to break the bundle
GSamRecord& brec=*(alndata.brec); // bam record
if((longreads || (mixedMode && brec.uval)) && (brec.flags() & BAM_FSECONDARY)) return;
GList<CReadAln>& readlist = bdata.readlist; // list of reads gathered so far
GList<CJunction>& junction = bdata.junction; // junctions added so far
char strand=alndata.strand;
int nh=alndata.nh;
int hi=alndata.hi;
int readstart=brec.start;
CReadAln* readaln=NULL; // readaln is initialized with NULL
//bool covSaturated=false; // coverage is set to not saturated
/*
{ // DEBUG ONLY
fprintf(stderr,"Process read %s with strand=%d and exons:",brec.name(),strand);
for (int i=0;i<brec.exons.Count();i++) {
fprintf(stderr," %d-%d", brec.exons[i].start, brec.exons[i].end);
}
fprintf(stderr,"\n");
}
*/
double nm=(double)brec.tag_int("NM"); // read mismatch
float unitig_cov=0;
unitig_cov=brec.tag_float("YK");
bool longr=false;
if(longreads|| brec.uval) longr=true; // second alignment is always from mixed reads
bool match=false; // true if current read matches a previous read
int n=readlist.Count()-1;
if(!mergeMode) while(n>-1 && readlist[n]->start==brec.start) {
if(strand==readlist[n]->strand && (readlist[n]->longread==longr) && (!isunitig || (unitig_cov>0) == readlist[n]->unitig)) {
match=exonmatch(readlist[n]->segs,brec.exons);
if(match && (longreads || mixedMode)) match=deljuncmatch(readlist[n],brec.juncsdel); //DEL AWARE
}
//if(strand==readlist[n]->strand) match=exonmatch(readlist[n]->segs,brec.exons);
if(match) break; // this way I make sure that I keep the n of the matching readlist
n--;
}
else if((alndata.tinfo->cov>=0 && alndata.tinfo->cov<readthr) || (alndata.tinfo->fpkm>=0 && alndata.tinfo->fpkm<fpkm_thr) ||
(alndata.tinfo->tpm>=0 && alndata.tinfo->tpm < tpm_thr)) return; // do not store 'read' if it doesn't meet minimum criteria; this is mergeMode
else { //mergeMode but the read is above thresholds
if(alndata.tinfo->cov>=0) bdata.covflags |= IS_COV_FLAG;
if(alndata.tinfo->fpkm>=0) bdata.covflags |= IS_FPKM_FLAG;
if(alndata.tinfo->tpm>=0) bdata.covflags |= IS_TPM_FLAG;
}
if (bdata.end<currentend) {// I am not sure why this is done here?
bdata.start=currentstart;
bdata.end=currentend;
}
bdata.numreads++; // number of reads gets increased no matter what
//bdata.wnumreads+=float(1)/nh;
if (!match) { // if this is a new read I am seeing I need to set it up
if(mergeMode && mintranscriptlen) {
int len=0;
for (int i=0;i<brec.exons.Count();i++) len+=brec.exons[i].len();
if(len<mintranscriptlen) return;
}
readaln=new CReadAln(strand, nh, brec.start, brec.end, alndata.tinfo);
readaln->longread=longr;
alndata.tinfo=NULL; //alndata.tinfo was passed to CReadAln
for (int i=0;i<brec.exons.Count();i++) {
readaln->len+=brec.exons[i].len();
if(i) {
if(!junction.Count()) { // always add null junction first
CJunction *nullj=new CJunction(0, 0, 0);
junction.Add(nullj);
}
int jstrand=strand;
uint jstart=brec.exons[i-1].end;
uint jend=brec.exons[i].start;
//fprintf(stderr,"exon count=%d junctiondel count=%d exonend=%d exonstart=%d\n",brec.exons.Count(),brec.juncsdel.Count(),jstart,jend);
if((longreads || mixedMode) && (brec.juncsdel[i-1].start || brec.juncsdel[i-1].end)) { // deletion at the junction start/end //DEL AWARE
if(!alndata.juncs.Count() || !alndata.juncs[i-1]->guide_match) { // if this junction matches a guide, I do not need to do anything
jstrand=0;
jstart-=brec.juncsdel[i-1].start;
jend+=brec.juncsdel[i-1].end;
}
}
CJunction* nj=junction.AddIfNew(new CJunction(jstart, jend, jstrand), true);
if (alndata.juncs.Count())
nj->guide_match=alndata.juncs[i-1]->guide_match;
if (nj) {
readaln->juncs.Add(nj);
}
}
readaln->segs.Add(brec.exons[i]);
}
n=readlist.Add(readaln); // reset n for the case there is no match
}
else { //redundant read alignment matching a previous alignment
// keep shortest nh so that I can see for each particular read the multi-hit proportion
if(nh<readlist[n]->nh) readlist[n]->nh=nh;
/*
//for mergeMode, we have to free the transcript info:
if (alndata.tinfo!=NULL) {
delete alndata.tinfo;
alndata.tinfo=NULL;
}
*/
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Add read %s with strand=%d and exons:",brec.name(),strand);
for (int i=0;i<brec.exons.Count();i++) {
fprintf(stderr," %d-%d", brec.exons[i].start, brec.exons[i].end);
}
fprintf(stderr,"\n");
//fprintf(stderr,"Read %s is at n=%d with unitig_cov=%f and strand=%d\n",brec.name(),n,unitig_cov,strand);
}
*/
if((int)brec.end>currentend) {
currentend=brec.end;
bdata.end=currentend;
}
float rdcount=(float)brec.tag_int("YC"); // alignment count
if(!rdcount) rdcount=1;
if(unitig_cov) {
rdcount=unitig_cov;
if(isunitig) readlist[n]->unitig=true; // treat unitig reads differently when -U is set
}
if(!nomulti) rdcount/=nh;
readlist[n]->read_count+=rdcount; // increase single count just in case I don't see the pair
// store the mismatch count per junction so that I can eliminate it later
if(!nm) {
nm=(double)brec.tag_int("nM"); // paired mismatch : big problem with STAR alignments
if(brec.isPaired()) nm/=2;
}
if(brec.clipL) nm++;
if(brec.clipR) nm++;
//nm+=brec.clipL; Note: this clippings were to aggressive
//nm+=brec.clipR;
if(readlist[n]->juncs.Count()) {
bool mismatch=false;
if(readlist[n]->longread) mismatch=true;
else if(nm/readlist[n]->len>mismatchfrac) mismatch=true;
else if(nm && readlist[n]->juncs.Count()) {
if(brec.clipL && readlist[n]->segs[0].len()<junctionsupport+brec.clipL) mismatch=true; // penalize mismatch that's too close to ss
else if(brec.clipR && readlist[n]->segs.Last().len()<junctionsupport+brec.clipR) mismatch=true;
else if(mismatch_anchor(readlist[n],brec.tag_str("MD"),currentstart,brec.get_b())) mismatch=true; // this line was not initially present in vs1 or vs3 but I noticed it doesn't do any difference in real data, so far it only helped with the SR in simulation -> I might want to take it out
}
for(int i=0;i<readlist[n]->juncs.Count();i++) { // if read is PacBio I might want to increase the mismatch fraction, although the nm only gets used for longintrons
if(mismatch || nh>2) readlist[n]->juncs[i]->nm+=rdcount;
if(readlist[n]->segs[i].len()>longintronanchor && readlist[n]->segs[i+1].len()>longintronanchor)
readlist[n]->juncs[i]->mm+=rdcount;
//if(nh>2) readlist[n]->juncs[i]->mm+=rdcount; // vs3; vs2 only has nh>1
readlist[n]->juncs[i]->nreads+=rdcount;
}
}
// now set up the pairing
if (brec.refId()==brec.mate_refId()) { //only consider mate pairing data if mates are on the same chromosome/contig and are properly paired
//if (brec.refId()==brec.mate_refId() && brec.isProperlyPaired()) { //only consider mate pairing data if mates are on the same chromosome/contig and are properly paired
//if (brec.isProperlyPaired()) { //only consider mate pairing data if mates are properly paired
int pairstart=brec.mate_start();
if (currentstart<=pairstart) { // if pairstart is in a previous bundle I don't care about it
//GStr readname();
//GStr id(brec.name(), 16); // init id with readname
_id.assign(brec.name()); //assign can be forced to prevent shrinking of the string
if(pairstart<=readstart) { // if I've seen the pair already <- I might not have seen it yet because the pair starts at the same place
_id+='-';_id+=pairstart;
_id+=".=";_id+=hi; // (!) this suffix actually speeds up the hash by improving distribution!
const int* np=hashread[_id.chars()];
if(np) { // the pair was stored --> why wouldn't it be? : only in the case that the pair starts at the same position
if(readlist[*np]->nh>nh && !nomulti) rdcount=float(1)/readlist[*np]->nh;
bool notfound=true;
for(int i=0;i<readlist[*np]->pair_idx.Count();i++)
if(readlist[*np]->pair_idx[i]==n) {
readlist[*np]->pair_count[i]+=rdcount;
notfound=false;
break;
}
if(notfound) { // I didn't see the pairing before
readlist[*np]->pair_idx.Add(n);
readlist[*np]->pair_count.Add(rdcount);
}
notfound=true;
for(int i=0;i<readlist[n]->pair_idx.Count();i++)
if(readlist[n]->pair_idx[i]==*np) {
readlist[n]->pair_count[i]+=rdcount;
notfound=false;
break;
}
if(notfound) { // I didn't see the pairing before
int i=*np;
readlist[n]->pair_idx.Add(i);
readlist[n]->pair_count.Add(rdcount);
}
hashread.Remove(_id.chars());
}
}
else { // I might still see the pair in the future
_id+='-';_id+=readstart; // this is the correct way
_id+=".=";_id+=hi;
hashread.Add(_id.chars(), n);
}
}
} //<-- if mate is mapped on the same chromosome
}
int get_min_start(CGroup **currgroup) {
int nextgr=0;
if(currgroup[0]!=NULL) {
if(currgroup[1]!=NULL) {
if(currgroup[2]!=NULL) {
int twogr = currgroup[0]->start < currgroup[1]->start ? 0 : 1;
nextgr = currgroup[twogr]->start < currgroup[2]->start ? twogr : 2;
return(nextgr);
}
else {
nextgr = currgroup[0]->start < currgroup[1]->start ? 0 : 1;
return(nextgr);
}
}
else {
if(currgroup[2]!=NULL) {
nextgr = currgroup[0]->start < currgroup[2]->start ? 0 : 2;
return(nextgr);
}
else {
return(0);
}
}
} // end if(currgroup[0]!=NULL)
else {
if(currgroup[1]!=NULL) {
if(currgroup[2]!=NULL) {
nextgr = currgroup[1]->start < currgroup[2]->start ? 1 : 2;
return(nextgr);
}
else {
return(1);
}
}
else {
return(2);
}
}
return(nextgr);
}
void set_strandcol(CGroup *prevgroup, CGroup *group, int grcol, GVec<int>& eqcol, GVec<int>& equalcolor){
int zerocol=eqcol[prevgroup->color];
if(zerocol>-1) {
while(eqcol[zerocol]!=-1 && eqcol[zerocol]!=zerocol) {
zerocol=eqcol[zerocol];
}
int tmpcol=zerocol;
while(equalcolor[zerocol]!=zerocol) {
zerocol=equalcolor[zerocol];
}
eqcol[prevgroup->color]=zerocol;
eqcol[tmpcol]=zerocol;
if(zerocol<grcol) {
equalcolor[grcol]=zerocol;
group->color=zerocol;
}
else if(grcol<zerocol) {
equalcolor[zerocol]=grcol;
eqcol[prevgroup->color]=grcol;
}
} // if(zerocol>-1)
else {
eqcol[prevgroup->color]=grcol;
}
}
void add_group_to_bundle(CGroup *group, CBundle *bundle, GPVec<CBundlenode>& bnode, uint localdist){
CBundlenode *currlastnode=bnode[bundle->lastnodeid];
int bid=bnode.Count();
if(group->start > currlastnode->end + localdist) { // group after last bnode
CBundlenode *currbnode=new CBundlenode(group->start,group->end,group->cov_sum,bid);
currlastnode->nextnode=currbnode;
bnode.Add(currbnode);
bundle->lastnodeid=bid;
bundle->len+=group->end-group->start+1;
bundle->cov+=group->cov_sum;
bundle->multi+=group->multi;
}
else { // group overlaps bnode within bundledist
if(currlastnode->end < group->end) {
bundle->len+= group->end - currlastnode->end;
currlastnode->end= group->end;
}
bundle->cov+=group->cov_sum;
bundle->multi+=group->multi;
currlastnode->cov+=group->cov_sum;
}
}
int create_bundle(GPVec<CBundle>& bundle,CGroup *group,GPVec<CBundlenode>& bnode) {
int bid=bnode.Count();
int bno=bundle.Count();
CBundlenode *startbnode=new CBundlenode(group->start,group->end,group->cov_sum,bid);
CBundle *newbundle=new CBundle(group->end-group->start+1,group->cov_sum,group->multi,bid,bid);
bundle.Add(newbundle);
bnode.Add(startbnode);
return(bno);
}
int setCmp(const pointer p1, const pointer p2) {
CTrInfo *a=(CTrInfo*)p1;
CTrInfo *b=(CTrInfo*)p2;
if(a->trno<b->trno) return -1;
if(a->trno>b->trno) return 1;
return 0;
}
int capCmp(const pointer p1, const pointer p2) {
CTrInfo *a=(CTrInfo*)p1;
CTrInfo *b=(CTrInfo*)p2;
if(a->abundance<b->abundance) return -1;
if(a->abundance>b->abundance) return 1;
return 0;
}
int longtrCmp(const pointer p1, const pointer p2) {
CTransfrag *a=(CTransfrag*)p1;
CTransfrag *b=(CTransfrag*)p2;
if(!a->guide && b->guide) return 1;
if(a->guide && !b->guide) return -1;
if(a->abundance<b->abundance) return 1; // most abundant transcript comes first (I want to keep the one that clearly dominates)
if(a->abundance>b->abundance) return -1;
if(a->nodes.Count()<b->nodes.Count()) return 1; // transfrag with more nodes comes first
if(a->nodes.Count()>b->nodes.Count()) return -1;
if(a->pattern.count()<b->pattern.count()) return 1; // more complete transfrag comes first
if(a->pattern.count()>b->pattern.count()) return -1;
return 0;
}
int trCmp(const pointer p1, const pointer p2) {
CTransfrag *a=(CTransfrag*)p1;
CTransfrag *b=(CTransfrag*)p2;
if(a->nodes.Last()-a->nodes[0]<b->nodes.Last()-b->nodes[0]) return 1; // transfrag with further reach comes first
if(a->nodes.Last()-a->nodes[0]>b->nodes.Last()-b->nodes[0]) return -1;
if(a->nodes.Count()<b->nodes.Count()) return 1; // transfrag with more nodes comes first
if(a->nodes.Count()>b->nodes.Count()) return -1;
if(a->pattern.count()<b->pattern.count()) return 1;
if(a->pattern.count()>b->pattern.count()) return -1;
if(a->abundance<b->abundance) return 1;
if(a->abundance>b->abundance) return -1;
return 0;
}
int mgtrnodeCmp(const pointer p1, const pointer p2) {
CMTransfrag *a=(CMTransfrag*)p1;
CMTransfrag *b=(CMTransfrag*)p2;
if(a->transfrag->pattern.count()<b->transfrag->pattern.count()) return 1;
if(a->transfrag->pattern.count()>b->transfrag->pattern.count()) return -1;
if(!a->transfrag->real && b->transfrag->real) return -1;
if(a->transfrag->real && !b->transfrag->real) return 1;
/*if(a->transfrag->abundance<b->transfrag->abundance) return 1;
if(a->transfrag->abundance>b->transfrag->abundance) return -1;*/
return 0;
}
int mgtrabundCmp(const pointer p1, const pointer p2) {
CMTransfrag *a=(CMTransfrag*)p1;
CMTransfrag *b=(CMTransfrag*)p2;
if(!a->transfrag->real && b->transfrag->real) return 1; // guides come first
if(a->transfrag->real && !b->transfrag->real) return -1;
if(a->transfrag->abundance<b->transfrag->abundance) return 1; // most abundant transcript comes first
if(a->transfrag->abundance>b->transfrag->abundance) return -1;
if(a->transfrag->pattern.count()<b->transfrag->pattern.count()) return 1; // the one with largest pattern comes first
if(a->transfrag->pattern.count()>b->transfrag->pattern.count()) return -1;
// something to decide equal cases
if(a->transfrag->nodes.Count()<b->transfrag->nodes.Count()) return 1; // the one with most nodes comes first
if(a->transfrag->nodes.Count()>b->transfrag->nodes.Count()) return -1;
int i=0;
while(i<a->transfrag->nodes.Count()) {
if(a->transfrag->nodes[i]<b->transfrag->nodes[i]) return 1; // the transcript starting more to the left comes first
if(a->transfrag->nodes[i]>b->transfrag->nodes[i]) return -1;
i++;
}
return 0;
}
int partguideCmp(const pointer p1, const pointer p2) { // sorting partial guides in order of preference
CPartGuide *a=(CPartGuide*)p1;
CPartGuide *b=(CPartGuide*)p2;
if(a->cov<b->cov) return 1;
if(a->cov>b->cov) return -1;
if(a->gcount<b->gcount) return 1;
if(a->gcount>b->gcount) return -1;
if(a->olen<b->olen) return 1;
if(a->olen>b->olen) return -1;
if(a->allolen<b->allolen) return 1;
if(a->allolen>b->allolen) return -1;
if(a->glen<b->glen) return 1;
if(a->glen>b->glen) return -1;
return 0;
}
int edgeCmp(const pointer p1, const pointer p2) {
CNetEdge *a=(CNetEdge*)p1;
CNetEdge *b=(CNetEdge*)p2;
if(a->rate<b->rate) return 1;
if(a->rate>b->rate) return -1;
return 0;
}
int pointCmp(const pointer p1, const pointer p2) {
CTrimPoint *a=(CTrimPoint*)p1;
CTrimPoint *b=(CTrimPoint*)p2;
if(a->start && !b->start) return -1;
if(!a->start && b->start) return 1;
if(a->abundance<b->abundance) return 1;
if(a->abundance>b->abundance) return -1;
return 0;
}
int edgeCmpEM(const pointer p1, const pointer p2) {
CNetEdge *a=(CNetEdge*)p1;
CNetEdge *b=(CNetEdge*)p2;
if(a->fake && !b->fake) return 1; // check if this is right -> I want the fake one to come last
if(!a->fake && b->fake) return -1;
if(a->rate<b->rate) return 1;
if(a->rate>b->rate) return -1;
return 0;
}
int guideabundCmp(const pointer p1, const pointer p2) {
CTransfrag *a=(CTransfrag*)p1;
CTransfrag *b=(CTransfrag*)p2;
if(a->abundance<b->abundance) return 1;
if(a->abundance>b->abundance) return -1;
if(a->pattern.count()<b->pattern.count()) return 1;
if(a->pattern.count()>b->pattern.count()) return -1;
return 0;
}
int guidedabundCmp(const pointer p1, const pointer p2) {
CGuide *a=(CGuide*)p1;
CGuide *b=(CGuide*)p2;
if(a->trf->real && !b->trf->real) return 1; // this ensures included guides are treated last
if(!a->trf->real && b->trf->real) return -1;
if(a->trf->abundance<b->trf->abundance) return 1; // most abundant guide takes precedence
if(a->trf->abundance>b->trf->abundance) return -1;
if(a->trf->pattern.count()<b->trf->pattern.count()) return 1; // longest guide takes precedence
if(a->trf->pattern.count()>b->trf->pattern.count()) return -1;
return 0;
}
int guideCmp(const pointer p1, const pointer p2) {
CGuide *a=(CGuide*)p1;
CGuide *b=(CGuide*)p2;
if(a->trf->pattern.count()<b->trf->pattern.count()) return 1; // longest guide takes precedence
if(a->trf->pattern.count()>b->trf->pattern.count()) return -1;
return 0;
}
int juncCmpEnd(const pointer p1, const pointer p2) {
CJunction* a=(CJunction*)p1;
CJunction* b=(CJunction*)p2;
if (a->end<b->end) return -1;
if (a->end>b->end) return 1;
if (a->start<b->start) return -1;
if (a->start>b->start) return 1;
return 0;
}
void merge_fwd_groups(GPVec<CGroup>& group, CGroup *group1, CGroup *group2, GVec<int>& merge, GVec<int>& eqcol) {
//fprintf(stderr,"merge group=%d into group=%d\n",group2->grid,group1->grid);
// get end of group (group1 is assumed to come before group2)
group1->end=group2->end;
// get smallest color of group
while(eqcol[group1->color]!=group1->color) {
group1->color=eqcol[group1->color];
}
while(eqcol[group2->color]!=group2->color) {
group2->color=eqcol[group2->color];
}
if(group1->color<group2->color) {
eqcol[group2->color]=group1->color;
}
else if(group1->color>group2->color) {
eqcol[group1->color]=group2->color;
group1->color=group2->color;
}
group1->cov_sum+=group2->cov_sum;
group1->next_gr=group2->next_gr; // this is possible because group1->next_gr=group2
merge[group2->grid]=group1->grid;
group1->multi+=group2->multi;
// delete group2
group.freeItem(group2->grid);
}
int merge_read_to_group(int n,int np, int p, float readcov, int sno,int readcol,GList<CReadAln>& readlist,int color,GPVec<CGroup>& group,
CGroup **allcurrgroup,CGroup **startgroup,GVec<int> *readgroup,GVec<int>& eqcol,GVec<int>& merge,int *usedcol) {
//fprintf(stderr,"merge readcol=%d for read=%d:%d-%d with paird=%d and sno=%d\n",readcol,n,readlist[n]->start,readlist[n]->end,np,sno);
// check if read was processed before as a fragment
uint localdist=0;
if(!longreads && !mixedMode) localdist=bundledist+longintronanchor;
//if(!longreads) localdist=bundledist+longintronanchor;
if(np>-1 && np<n && readlist[np]->end<readlist[n]->start && readlist[np]->end+localdist>readlist[n]->start &&
(readlist[np]->segs.Last().len()>=junctionsupport || (readlist[np]->juncs.Count() && readlist[np]->juncs.Last()->strand))
&& (readlist[n]->segs[0].len()>=junctionsupport || (readlist[n]->juncs.Count() && readlist[n]->juncs[0]->strand))) { // valid last/first exon and close
return color;
}
bool first=true;
CGroup *currgroup=allcurrgroup[sno]; // currgroup will be the group that contains readlist[n]->start; initially is the group where the previous read on this strand was added
if(currgroup != NULL) { // this type of group - negative, unknown, or positive - was created before
//set currgroup first
CGroup *lastgroup=NULL;
while(currgroup!=NULL && readlist[n]->start > currgroup->end) { // while read start after the current group's end advance group -> I might have more groups leaving from current group due to splicing
lastgroup=currgroup;
currgroup=currgroup->next_gr;
}
if(currgroup==NULL || readlist[n]->segs[0].end < currgroup->start) // currgroup is null only if we reached end of currgroup list
// because currgroup is not NULL initially and it starts BEFORE read
currgroup=lastgroup; // making sure read comes after currgroup
// now process each group of coordinates individually
CGroup *thisgroup=currgroup;
int ncoord=readlist[n]->segs.Count(); // number of "exons" in read
int lastpushedgroup=-1;
// bool added=false;
int i=0;
while(i<ncoord) {
bool keep=true;
// determine if this exon is good enough to be kept (it is big enough and has good junctions)
if(readlist[n]->segs[i].len()<junctionsupport || (readlist[n]->longread && readlist[n]->segs[i].len()<CHI_THR && readlist[n]->segs[i].len()<DROP*readlist[n]->len)) { // exon is too small to keep
if(i<readlist[n]->juncs.Count()) {
if(!readlist[n]->juncs[i]->strand) { // check first exon
// see if first exon is big enough
if(!i || !readlist[n]->juncs[i-1]->strand) {
keep=false;
if(!i && lastgroup) currgroup=lastgroup;
}
}
}
else if(readlist[n]->juncs.Count()){ // this is last exon
if(!readlist[n]->juncs[i-1]->strand) keep=false;
}
}
if(keep) {
// skip groups that are left behind
while(thisgroup!=NULL && readlist[n]->segs[i].start > thisgroup->end) { // find the group where "exon" fits
lastgroup=thisgroup;
thisgroup=thisgroup->next_gr;
}
if(thisgroup && readlist[n]->segs[i].end + localdist >= thisgroup->start) { // read overlaps group or it's close enough -> it should get group color
// I need to split pairs here if color didn't reach this group: it means there is a gap between these groups and no reads joining them
if(!i) {
int gr=thisgroup->grid;
while(merge[gr]!=gr) {
gr=merge[gr];
}
thisgroup->grid=gr;
for(int g=0;g<readgroup[n].Count();g++) {
gr=readgroup[n][g];
while(merge[gr]!=gr) {
gr=merge[gr];
}
if(gr==thisgroup->grid) {
first=false; // I did see this groups before
break;
}
}
if(np>-1 && readlist[np]->nh && np<n) { // I only consider first exon here because the rest of the groups need to get the same color if the read is still paired
int thiscol=thisgroup->color;
while(eqcol[thiscol]!=thiscol) { // get smallest color
thiscol=eqcol[thiscol];
}
thisgroup->color=thiscol;
if(thiscol!=readcol) { // pair color didn't reach this group
//fprintf(stderr,"Split pairs: %d-%d and %d-%d on strand %d thiscol=%d readcol=%d\n",readlist[np]->start,readlist[np]->end,readlist[n]->start,readlist[n]->end,readlist[n]->strand,thiscol,readcol);
readlist[n]->pair_idx[p]=-1;
for(int j=0;j<readlist[np]->pair_idx.Count();j++)
if(readlist[np]->pair_idx[j]==n) {
readlist[np]->pair_idx[j]=-1;
break;
}
readcol=usedcol[sno]; // readcol gets back the new color
if(readcol<0) {
usedcol[sno]=color;
readcol=color;
eqcol.Add(color);
color++;
}
}
}
}
if(readlist[n]->nh>1) {
thisgroup->multi+=readcov*readlist[n]->segs[i].len(); // where do I add readcov to group coverage -> see below at the end of '}'
}
if(readlist[n]->segs[i].start<thisgroup->start) {
thisgroup->start=readlist[n]->segs[i].start;
}
// find end of new group
CGroup *nextgroup=thisgroup->next_gr;
while(nextgroup!=NULL && readlist[n]->segs[i].end >= nextgroup->start) {
merge_fwd_groups(group,thisgroup,nextgroup,merge,eqcol);
nextgroup=thisgroup->next_gr;
}
if(readlist[n]->segs[i].end > thisgroup->end) {
thisgroup->end=readlist[n]->segs[i].end;
}
// get smallest color of group
while(eqcol[thisgroup->color]!=thisgroup->color) {
thisgroup->color=eqcol[thisgroup->color];
}
if(readcol!=thisgroup->color) { // read color is different from group color
if(i && !readlist[n]->juncs[i-1]->strand) { // bad junction before this exon
// before I equal readcol to thisgroup->color, I need to make sure that the read is not interrupted
// readcol for next exons should still be the color of thisgroup
readcol=thisgroup->color;
}
else {
if(readcol<thisgroup->color) { // set group color to current read color
eqcol[thisgroup->color]=readcol;
thisgroup->color=readcol;
}
else { // read color is bigger than group
eqcol[readcol]=thisgroup->color;
readcol=thisgroup->color;
}
}
}
if(thisgroup->grid != lastpushedgroup) {
//fprintf(stderr,"Assign group %d:%d-%d with color=%d to read %d\n",thisgroup->grid,thisgroup->start,thisgroup->end,thisgroup->color,n);
if(first) readgroup[n].Add(thisgroup->grid); // readgroup for read n gets the id of group
lastpushedgroup=thisgroup->grid;
}
thisgroup->cov_sum+=(readlist[n]->segs[i].end-readlist[n]->segs[i].start+1)*readcov; // coverage is different than number of reads
} // end if(thisgroup && readlist[n]->segs[i].end >= thisgroup->start)
else { // read is at the end of groups, or read is not overlapping other groups -> lastgroup is not null here because currgroup was not null
// I need to split pairs here because I have no overlap => color didn't reach here for sure if I am at the first exon
if(!i && np>-1 && readlist[np]->nh && np<n) {
//fprintf(stderr,"2 Split pairs: %d-%d and %d-%d on strand %d\n",readlist[np]->start,readlist[np]->end,readlist[n]->start,readlist[n]->end,readlist[n]->strand);
readlist[n]->pair_idx[p]=-1;
for(int j=0;j<readlist[np]->pair_idx.Count();j++)
if(readlist[np]->pair_idx[j]==n) {
readlist[np]->pair_idx[j]=-1;
break;
}
readcol=usedcol[sno]; // readcol gets back the new color
if(readcol<0) {
usedcol[sno]=color;
readcol=color;
eqcol.Add(color);
color++;
}
}
else if(i && !readlist[n]->juncs[i-1]->strand) { // if exons are interrupted use new color
// I have to use new color for read and I have no idea if usedcol was already used or not => I have to ignore what was already assigned to usedcol
usedcol[sno]=color;
readcol=color;
eqcol.Add(color);
color++;
}
int ngroup=group.Count();
float multi=0;
if(readlist[n]->nh>1) multi=readcov*readlist[n]->segs[i].len();
CGroup *newgroup=new CGroup(readlist[n]->segs[i].start,readlist[n]->segs[i].end,readcol,ngroup,readlist[n]->segs[i].len()*readcov,multi);
group.Add(newgroup);
merge.Add(ngroup);
lastgroup->next_gr=newgroup; // can lastgroup be null here -> no from the way I got here
newgroup->next_gr=thisgroup;
//fprintf(stderr,"Assign/create group %d:%d-%d with color=%d to read %d\n",ngroup,readlist[n]->segs[i].start,readlist[n]->segs[i].end,readcol,n);
readgroup[n].Add(ngroup); // since group was created it clearly is new
lastpushedgroup=ngroup;
thisgroup=newgroup;
}
/* version that uses paired reads in a fragment to do bundling*/
if(i==ncoord-1) { // last segment in read
if(np!=-1 && np>n && readlist[n]->end<readlist[np]->start && readlist[n]->end+localdist>readlist[np]->start &&
(readlist[np]->segs[0].len()>=junctionsupport || (readlist[np]->juncs.Count() && readlist[np]->juncs[0]->strand))) { // valid last exon and close
n=np; // next I will process read pair as it was part of the same fragment
np=-1;
ncoord=readlist[n]->segs.Count();
first=true;
if(readlist[n]->start>thisgroup->end) { // I need to extend group
CGroup *nextgroup=thisgroup->next_gr;
while(nextgroup!=NULL && readlist[n]->start >= nextgroup->start) {
merge_fwd_groups(group,thisgroup,nextgroup,merge,eqcol);
nextgroup=thisgroup->next_gr;
}
if(readlist[n]->start > thisgroup->end) {
thisgroup->end=readlist[n]->start;
}
}
lastpushedgroup=-1;
i=-1;
}
}
} // if(keep)
i++;
} // for(int i=0;i<ncoord;i++)
} // if(currgroup != NULL)
else { // create new group of this type
// I need to split pairs here because I have no overlap => color didn't reach here for sure
if(np>-1 && readlist[np]->nh && np<n) {
//fprintf(stderr,"3 Split pairs: %d-%d and %d-%d on strand %d\n",readlist[np]->start,readlist[np]->end,readlist[n]->start,readlist[n]->end,readlist[n]->strand);
readlist[n]->pair_idx[p]=-1;
for(int j=0;j<readlist[np]->pair_idx.Count();j++)
if(readlist[np]->pair_idx[j]==n) {
readlist[np]->pair_idx[j]=-1;
break;
}
readcol=usedcol[sno]; // readcol gets back the new color
if(readcol<0) {
usedcol[sno]=color;
readcol=color;
eqcol.Add(color);
color++;
}
// even if I split pairs I do not need to update single_count because this readcov is taken care of
}
int ncoord=readlist[n]->segs.Count();
CGroup *lastgroup=NULL;
float multi=0;
if(readlist[n]->nh>1) multi=readcov; // this will be adjusted by the length of each segment
int i=0;
while(i<ncoord) {
bool keep=true;
// determine if this exon is good enough to be kept (it is big enough and has good junctions)
if(readlist[n]->segs[i].len()<junctionsupport) { // exon is too small to keep --> this exon will not be added to group if it doesn't pass some criteria
if(i<readlist[n]->juncs.Count()) {
if(!readlist[n]->juncs[i]->strand) { // check first exon
// see if first exon is big enough
if(!i || !readlist[n]->juncs[i-1]->strand) keep=false;
}
}
else if(readlist[n]->juncs.Count()){ // this is last exon
if(!readlist[n]->juncs[i-1]->strand) keep=false;
}
}
if(!i || keep) {
// assign new color if read is interrupted
if(i && !readlist[n]->juncs[i-1]->strand) { // if exons are interrupted use new color
usedcol[sno]=color;
readcol=color;
eqcol.Add(color);
color++;
}
int ngroup=group.Count();
CGroup *newgroup=new CGroup(readlist[n]->segs[i].start,readlist[n]->segs[i].end,readcol,ngroup,readlist[n]->segs[i].len()*readcov,readlist[n]->segs[i].len()*multi);
group.Add(newgroup);
merge.Add(ngroup);
if(lastgroup!=NULL) {
lastgroup->next_gr=newgroup;
}
else {
currgroup=newgroup;
}
lastgroup=newgroup;
if(keep) {
//fprintf(stderr,"Assign/create2 group %d:%d-%d with color=%d to read %d\n",ngroup,readlist[n]->segs[i].start,readlist[n]->segs[i].end,readcol,n);
readgroup[n].Add(ngroup); // add group to read so that I can remember what groups belong to a read
/* version that uses paired reads in a fragment to do bundling*/
if(i==ncoord-1) { // last segment in read
if(np!=-1 && np>n && readlist[n]->end<readlist[np]->start && readlist[n]->end+localdist>readlist[np]->start &&
(readlist[np]->segs[0].len()>=junctionsupport || (readlist[np]->juncs.Count() && readlist[np]->juncs[0]->strand))) { // valid last exon and close
n=np; // next I will process read pair as it was part of the same fragment
np=-1;
ncoord=readlist[n]->segs.Count();
if(readlist[n]->segs[0].end>lastgroup->end) { // I need to extend group
//fprintf(stderr,"Group %d:%d-%d will get end at %d n=%d ncoord=%d\n",lastgroup->grid,lastgroup->start,lastgroup->end,readlist[n]->segs[0].end,n,ncoord);
lastgroup->end=readlist[n]->segs[0].end;
if(first) readgroup[n].Add(ngroup); // add group to read so that I can remember what groups belong to a read
lastgroup->cov_sum+=readlist[n]->segs[0].len()*readcov; // coverage is different than number of reads
}
i=0;
}
}
}
}
i++;
}
}
allcurrgroup[sno]=currgroup;
if(startgroup[sno]==NULL) startgroup[sno]=currgroup;
return color;
}
int add_read_to_group(int n,GList<CReadAln>& readlist,int color,GPVec<CGroup>& group,CGroup **allcurrgroup,
CGroup **startgroup,GVec<int> *readgroup,GVec<int>& eqcol,GVec<int>& merge) {
int usedcol[3]={-1,-1,-1}; // remembers last usedcol for read so that I don't use different colors for the same read
float single_count=readlist[n]->read_count; // need to compute read single count
if(!mergeMode) for(int p=0;p<readlist[n]->pair_idx.Count();p++) { // for all pairs of read
// for each pair I have to pretend is independent of the previous one since I grouped together several reads which might be independent
int sno=readlist[n]->strand+1; // 0: negative strand; 1: zero strand; 2: positive strand (starting from -1,0,1) // I have to reset sno every time because it might change due to snop
// check if I've seen read's pair and if yes get its readcol; at the least get read's pair strand if available
int np=readlist[n]->pair_idx[p]; // pair read number
if(np>-1 && readlist[np]->nh) { // read pair still exists and it wasn't deleted -> false keep elminates all these cases
// see if I have the correct read strand
char snop=readlist[np]->strand+1; // snop is the strand of pair read
if(sno!=snop) { // different strands for read and pair
if(sno==1) { // read n is on zero (neutral) strand, but pair has strand
// readlist[n]->strand=readlist[np]->strand; I can not update the read strand anymore -> REMEMBER this later
sno=snop; // assign strand of pair to read
}
else if(snop!=1) { // conflicting strands -> un-pair reads in the hope that one is right
readlist[n]->pair_idx[p]=-1;
for(int j=0;j<readlist[np]->pair_idx.Count();j++) // also unpair read np to n
if(readlist[np]->pair_idx[j]==n) {
readlist[np]->pair_idx[j]=-1;
break;
}
np=-1;
}
}
if(np>-1) { // reads didn't get split
single_count-=readlist[n]->pair_count[p]; // update single count of read here
int readcol=usedcol[sno];
if(np<n) { // there is a pair and it came before the current read in sorted order of position
// first group of pair read is: readgroup[np][0]
int grouppair=readgroup[np][0];
while( merge[grouppair]!=grouppair) {
grouppair=merge[grouppair];
}
readgroup[np][0]=grouppair;
readcol=group[readgroup[np][0]]->color; // readcol gets assigned the color of the pair's first group --> this might not
// work if I split a read into multiple groups
while(eqcol[readcol]!=readcol) { // get smallest color
readcol=eqcol[readcol];
}
group[readgroup[np][0]]->color=readcol;
}
else { // it's the first time I see the read in the fragment
//fragno+=readlist[n]->pair_count[p];
if(usedcol[sno]<0) { // I didn't use the color yet
usedcol[sno]=color;
readcol=color;
eqcol.Add(color); // read might keep the new color so we need to add it to the eqcol
color++;
}
}
float readcov=0;
if(!readlist[n]->unitig)
readcov=readlist[n]->pair_count[p];
color=merge_read_to_group(n,np,p,readcov,sno,readcol,readlist,color,group,
allcurrgroup,startgroup,readgroup,eqcol,merge,usedcol);
} // this ends if(np>-1)
} // if(np>-1 && readlist[np]->nh) : read pair exists and it wasn't deleted
} // for(int p=0,...)
// now I need to deal with the single count
if(mergeMode || single_count>epsilon) { // my way of controlling for rounding errors
//fragno+=single_count;
int readcol=usedcol[readlist[n]->strand+1];
if(readcol<0) {
readcol=color;
usedcol[readlist[n]->strand+1]=color;
eqcol.Add(color); // read might keep the new color so we need to add it to the eqcol
color++;
}
float readcov=0;
if(!readlist[n]->unitig)
readcov=single_count;
color=merge_read_to_group(n,-1,-1,readcov,readlist[n]->strand+1,readcol,readlist,color,group,
allcurrgroup,startgroup,readgroup,eqcol,merge,usedcol);
}
return color;
}
CGraphnode *create_graphnode(int s, int g, uint start,uint end,int nodeno,CBundlenode *bundlenode,
GVec<CGraphinfo> **bundle2graph,GPVec<CGraphnode> **no2gnode) {
/*
{ // DEBUG ONLY
fprintf(stderr,"create_graphnode[%d][%d]:%d-%d nodeno=%d\n",s,g,start,end,nodeno);
}
*/
CGraphnode* gnode=new CGraphnode(start,end,nodeno);
CGraphinfo ginfo(g,nodeno);
bundle2graph[s][bundlenode->bid].Add(ginfo);
no2gnode[s][g].Add(gnode);
return(gnode);
}
float compute_chi(GArray<float>& winleft, GArray<float>& winright, float sumleft, float sumright) {
float chi=0;
for(int j=0;j<CHI_WIN;j++) {
float mul=(winleft[j]+ winright[j])/(sumleft+sumright);
float mur=mul;
mul*=sumleft;
mur*=sumright;
// I wasn't squaring before but it doesn't make sense not to because then I would add a bunch of negatives
if(mul) chi+= (winleft[j]-mul)*(winleft[j]-mul)/mul;
if(mur) chi+=(winright[j]-mur)*(winright[j]-mur)/mur;
}
return(chi);
}
float compute_chi2(GArray<float>& winleft, GArray<float>& winright, float sumleft, float sumright) {
float chi=0;
float basecost=0;
float leftcost=0;
float rightcost=0;
float mubase=(sumleft+sumright)/(2*CHI_WIN);
float muleft=sumleft/CHI_WIN;
float muright=sumright/CHI_WIN;
for(int j=0;j<CHI_WIN;j++) {
basecost+=(winleft[j]-mubase)*(winleft[j]-mubase)+(winright[j]-mubase)*(winright[j]-mubase);
leftcost+=(winleft[j]-muleft)*(winleft[j]-muleft);
rightcost+=(winright[j]-muright)*(winright[j]-muright);
}
chi=basecost/(2*CHI_WIN)-(leftcost+rightcost)/CHI_WIN;
return(chi);
}
float compute_cost(GVec<float>& wincov,float sumleft,float sumright,int leftstart,int rightstart,int rightend) {
float cost=0;
float basecost=0;
float leftcost=0;
float rightcost=0;
int len=rightend-leftstart+1;
int leftlen=rightstart-leftstart;
int rightlen=rightend-rightstart+1;
float mubase=(sumleft+sumright)/len;
float muleft=sumleft/leftlen;
float muright=sumright/rightlen;
for(int j=leftstart;j<rightstart;j++) {
//basecost+=(wincov[j]-mubase)*(wincov[j]-mubase);
basecost+=fabs(wincov[j]-mubase);
//leftcost+=(wincov[j]-muleft)*(wincov[j]-muleft);
leftcost+=fabs(wincov[j]-muleft);
}
for(int j=rightstart;j<=rightend;j++) {
//basecost+=(wincov[j]-mubase)*(wincov[j]-mubase);
basecost+=fabs(wincov[j]-mubase);
//rightcost+=(wincov[j]-muright)*(wincov[j]-muright);
rightcost+=fabs(wincov[j]-muright);
}
cost=basecost/len-leftcost/leftlen-rightcost/rightlen;
return(cost);
}
float compute_cost(GArray<float>& wincov,int i,float sumleft,float sumright,int len) {
float cost=0;
float basecost=0;
float leftcost=0;
float rightcost=0;
float mubase=(sumleft+sumright)/len;
float muleft=sumleft/i;
float muright=sumright/(len-i);
for(int j=0;j<len;j++) {
basecost+=(wincov[j]-mubase)*(wincov[j]-mubase);
if(j<i) leftcost+=(wincov[j]-muleft)*(wincov[j]-muleft);
else rightcost+=(wincov[j]-muright)*(wincov[j]-muright);
}
cost=basecost/len-leftcost/i-rightcost/(len-i);
return(cost);
}
float get_cov(int s,uint start,uint end,GVec<float>* bpcov) {
int m=int((end+1)/BSIZE);
int k=int(start/BSIZE);
float cov=0;
for(int i=k+1;i<=m;i++)
cov+=bpcov[s][i*BSIZE-1];
cov+=bpcov[s][end+1]-bpcov[s][start];
if(cov<0) cov=0;
return(cov);
}
float get_cov_sign(int s,uint start,uint end,GVec<float>* bpcov) {
int m=int((end+1)/BSIZE);
int k=int(start/BSIZE);
int o=2-s;
float cov=0;
for(int i=k+1;i<=m;i++)
cov+=bpcov[1][i*BSIZE-1]-bpcov[o][i*BSIZE-1];
cov+=bpcov[1][end+1]-bpcov[1][start]-bpcov[o][end+1]+bpcov[o][start];
if(cov<0) cov=0;
return(cov);
}
// cummulative bpcov; simple find trims that only checks for significant sudden drops in coverage
//void find_trims(int refstart,int sno,uint start,uint end,GVec<float>* bpcov,uint& sourcestart,float& sourcecovleft, float& sourcecovright,uint& sinkend, float& sinkcovleft,float& sinkcovright){
//void find_trims(int refstart,int sno,uint start,uint end,GVec<float>* bpcov,uint& sourcestart,float& sourceabundance,uint& sinkend,float& sinkabundance) {
void find_trims(int refstart,uint start,uint end,GVec<float>* bpcov,uint& sourcestart,float& sourceabundance,uint& sinkend,float& sinkabundance) {
int len=end-start+1; // length of region where I look for trims
if(len<CHI_THR) return; // very short exon -> do not check
//if(len<CHI_WIN) return; // very short exon -> do not check
float sourcedrop=1;
float sinkdrop=1;
float localdrop=ERROR_PERC;
// bigger trimming window
if(len<2*(CHI_WIN+CHI_THR)+1) {
if(len<CHI_WIN) localdrop=ERROR_PERC/(10*DROP);
for(uint i=start+longintronanchor;i<end-longintronanchor;i++) {
float covleft=get_cov(1,start-refstart,i-1-refstart,bpcov)/(i-start);
float covright=get_cov(1,i-refstart,end-refstart,bpcov)/(end-i+1);
if(covleft<covright) {
float thisdrop=covleft/covright;
if(thisdrop<localdrop && thisdrop<sourcedrop) {
sourcedrop=thisdrop;
sourcestart=i;
sourceabundance=(covright-covleft)/DROP;
}
}
else if(covright<covleft) { // possible sink trimming
float thisdrop=covright/covleft;
if(thisdrop<localdrop && thisdrop<sinkdrop) {
sinkdrop=thisdrop;
sinkend=i-1;
sinkabundance=(covleft-covright)/DROP;
}
}
}
return;
}
int winlen=CHI_WIN+CHI_THR;
localdrop=ERROR_PERC/DROP;
len+=start-winlen;
for(int i=start+winlen-1;i<len;i++) {
float covleft=get_cov(1,i-winlen+1-refstart,i-refstart,bpcov); // I add 1 bp coverage to all so I can avoid 0 coverages
float covright=get_cov(1,i+1-refstart,i+winlen-refstart,bpcov);
if(covleft<covright) { // possible source trimming
float thisdrop=covleft/covright;
if(thisdrop<localdrop && thisdrop<sourcedrop) {
sourcedrop=thisdrop;
sourcestart=i+1;
//maxsourceabundance=covright-covleft;
//sourcecovright=covright/(DROP*winlen);
//sourcecovleft=covleft/(DROP*winlen);
//sourcecovright=(covright-covleft)/winlen;
//sourcecovright=(covright-covleft)/(DROP*winlen);
sourceabundance=(covright-covleft)/(DROP*winlen);
}
}
else if(covright<covleft) { // possible sink trimming
float thisdrop=covright/covleft;
if(thisdrop<localdrop && thisdrop<sinkdrop) {
sinkdrop=thisdrop;
sinkend=i;
//maxsinkabundance=covleft-covright;
//sinkcovright=covright/(DROP*winlen);
//sinkcovleft=covleft/(DROP*winlen);
//sinkcovleft=(covleft-covright)/winlen;
//sinkcovleft=(covleft-covright)/(DROP*winlen);
sinkabundance=(covleft-covright)/(DROP*winlen);
}
}
}
// make sure the drops are consistent across the whole exon
if(sourcestart) {
if(sourcestart<sinkend) {
float covleft=get_cov(1,start-refstart,sourcestart-1-refstart,bpcov)/(sourcestart-start);
float covright=localdrop*get_cov(1,sourcestart-refstart,sinkend-refstart,bpcov)/(sinkend-sourcestart+1);
if(covleft>covright) sourcestart=0;
covleft=get_cov(1,sinkend+1-refstart,end-refstart,bpcov)/(end-sinkend);
if(covleft>covright) sinkend=0;
}
else if(sinkend) {
float covleft=get_cov(1,start-refstart,sinkend-refstart,bpcov)/(sinkend-start+1);
float covright=get_cov(1,sinkend+1-refstart,sourcestart-1-refstart,bpcov)/(sourcestart-sinkend-1);
if(covright>covleft*localdrop) sinkend=0;
covleft=get_cov(1,sourcestart-refstart,end-refstart,bpcov)/(end-sourcestart+1);
if(covright>covleft*localdrop) sourcestart=0;
}
else {
float covleft=get_cov(1,start-refstart,sourcestart-1-refstart,bpcov)/(sourcestart-start);
float covright=localdrop*get_cov(1,sourcestart-refstart,end-refstart,bpcov)/(end-sourcestart+1);
if(covleft>covright) sourcestart=0;
}
}
else if(sinkend) {
float covright=localdrop*get_cov(1,start-refstart,sinkend-refstart,bpcov)/(sinkend-start+1);
float covleft=get_cov(1,sinkend+1-refstart,end-refstart,bpcov)/(end-sinkend);
if(covleft>covright) sinkend=0;
}
}
void find_trims_wsign(int refstart,int sno,uint start,uint end,GVec<float>* bpcov,uint& sourcestart,float& sourceabundance,uint& sinkend,float& sinkabundance) {
//fprintf(stderr,"find trims in region:%d-%d:%d\n",start,end,sno);
int len=end-start+1; // length of region where I look for trims
if(len<CHI_THR) return; // very short exon -> do not check
//if(len<CHI_WIN) return; // very short exon -> do not check
float sourcedrop=1;
float sinkdrop=1;
//int os=2-sno; // other strand
float localdrop=ERROR_PERC;
// bigger trimming window
if(len<2*(CHI_WIN+CHI_THR)+1) {
if(len<CHI_WIN) localdrop=ERROR_PERC/(10*DROP);
for(uint i=start+longintronanchor;i<end-longintronanchor;i++) {
//float covleft=(get_cov(1,start-refstart,i-1-refstart,bpcov)-get_cov(os,start-refstart,i-1-refstart,bpcov))/(i-start);
//float covright=(get_cov(1,i-refstart,end-refstart,bpcov)-get_cov(os,i-refstart,end-refstart,bpcov))/(end-i+1);
float covleft=get_cov_sign(sno,start-refstart,i-1-refstart,bpcov)/(i-start);
float covright=get_cov_sign(sno,i-refstart,end-refstart,bpcov)/(end-i+1);
if(covleft<covright && covright>0) {
float thisdrop=covleft/covright;
if(thisdrop<localdrop && thisdrop<sourcedrop) {
sourcedrop=thisdrop;
sourcestart=i;
sourceabundance=(covright-covleft)/DROP;
}
}
else if(covright<covleft && covleft>0) { // possible sink trimming
float thisdrop=covright/covleft;
if(thisdrop<localdrop && thisdrop<sinkdrop) {
sinkdrop=thisdrop;
sinkend=i-1;
sinkabundance=(covleft-covright)/DROP;
}
}
}
return;
}
int winlen=CHI_WIN+CHI_THR;
/*localdrop=ERROR_PERC*DROP; // sharp drop
// look for short drops first
for(uint i=start+CHI_THR-1;i<start+winlen-1;i++) {
float covleft=get_cov_sign(sno,i-CHI_THR+1-refstart,i-refstart,bpcov); // I add 1 bp coverage to all so I can avoid 0 coverages
float covright=get_cov_sign(sno,i+1-refstart,i+CHI_THR-refstart,bpcov);
if(covleft<covright && covright>0) {
float thisdrop=covleft/covright;
if(thisdrop<localdrop && thisdrop<sourcedrop) {
sourcedrop=thisdrop;
sourcestart=i;
sourceabundance=(covright-covleft)/DROP;
}
}
else if(covright<covleft && covleft>0) { // possible sink trimming
float thisdrop=covright/covleft;
if(thisdrop<localdrop && thisdrop<sinkdrop) {
sinkdrop=thisdrop;
sinkend=i-1;
sinkabundance=(covleft-covright)/DROP;
}
}
}*/
localdrop=ERROR_PERC/DROP;
len+=start-winlen;
for(int i=start+winlen-1;i<len;i++) {
//float covleft=get_cov(1,i-winlen+1-refstart,i-refstart,bpcov)-get_cov(os,i-winlen+1-refstart,i-refstart,bpcov); // I add 1 bp coverage to all so I can avoid 0 coverages
//float covright=get_cov(1,i+1-refstart,i+winlen-refstart,bpcov)-get_cov(os,i+1-refstart,i+winlen-refstart,bpcov);
float covleft=get_cov_sign(sno,i-winlen+1-refstart,i-refstart,bpcov); // I add 1 bp coverage to all so I can avoid 0 coverages
float covright=get_cov_sign(sno,i+1-refstart,i+winlen-refstart,bpcov);
if(covleft<covright && covright>0) { // possible source trimming
float thisdrop=covleft/covright;
if(thisdrop<localdrop && thisdrop<sourcedrop) {
sourcedrop=thisdrop;
sourcestart=i+1;
//maxsourceabundance=covright-covleft;
//sourcecovright=covright/(DROP*winlen);
//sourcecovleft=covleft/(DROP*winlen);
//sourcecovright=(covright-covleft)/winlen;
//sourcecovright=(covright-covleft)/(DROP*winlen);
sourceabundance=(covright-covleft)/(DROP*winlen);
}
}
else if(covright<covleft && covleft>0) { // possible sink trimming
float thisdrop=covright/covleft;
if(thisdrop<localdrop && thisdrop<sinkdrop) {
sinkdrop=thisdrop;
sinkend=i;
//maxsinkabundance=covleft-covright;
//sinkcovright=covright/(DROP*winlen);
//sinkcovleft=covleft/(DROP*winlen);
//sinkcovleft=(covleft-covright)/winlen;
//sinkcovleft=(covleft-covright)/(DROP*winlen);
sinkabundance=(covleft-covright)/(DROP*winlen);
}
}
}
// make sure the drops are consistent across the whole exon --> this might be important
if(sourcestart) {
if(sourcestart<sinkend) {
//float covleft=(get_cov(1,start-refstart,sourcestart-1-refstart,bpcov)-get_cov(os,start-refstart,sourcestart-1-refstart,bpcov))/(sourcestart-start);
//float covright=localdrop*(get_cov(1,sourcestart-refstart,sinkend-refstart,bpcov)-get_cov(os,sourcestart-refstart,sinkend-refstart,bpcov))/(sinkend-sourcestart+1);
float covleft=get_cov_sign(sno,start-refstart,sourcestart-1-refstart,bpcov)/(sourcestart-start);
float covright=localdrop*get_cov_sign(sno,sourcestart-refstart,sinkend-refstart,bpcov)/(sinkend-sourcestart+1);
if(covleft>covright) {
sourcestart=0;
}
//covleft=(get_cov(1,sinkend+1-refstart,end-refstart,bpcov)-get_cov(os,sinkend+1-refstart,end-refstart,bpcov))/(end-sinkend);
covleft=get_cov_sign(sno,sinkend+1-refstart,end-refstart,bpcov)/(end-sinkend);
if(covleft>covright) {
sinkend=0;
}
}
else if(sinkend) {
//float covleft=(get_cov(1,start-refstart,sinkend-refstart,bpcov)-get_cov(os,start-refstart,sinkend-refstart,bpcov))/(sinkend-start+1);
//float covright=(get_cov(1,sinkend+1-refstart,sourcestart-1-refstart,bpcov)-get_cov(os,sinkend+1-refstart,sourcestart-1-refstart,bpcov))/(sourcestart-sinkend-1);
float covleft=get_cov_sign(sno,start-refstart,sinkend-refstart,bpcov)/(sinkend-start+1);
float covright=get_cov_sign(sno,sinkend+1-refstart,sourcestart-1-refstart,bpcov)/(sourcestart-sinkend-1);
if(covright>covleft*localdrop) {
sinkend=0;
}
//covleft=(get_cov(1,sourcestart-refstart,end-refstart,bpcov)-get_cov(os,sourcestart-refstart,end-refstart,bpcov))/(end-sourcestart+1);
covleft=get_cov_sign(sno,sourcestart-refstart,end-refstart,bpcov)/(end-sourcestart+1);
if(covright>covleft*localdrop) {
sourcestart=0;
}
}
else {
//float covleft=(get_cov(1,start-refstart,sourcestart-1-refstart,bpcov)-get_cov(os,start-refstart,sourcestart-1-refstart,bpcov))/(sourcestart-start);
//float covright=localdrop*(get_cov(1,sourcestart-refstart,end-refstart,bpcov)-get_cov(os,sourcestart-refstart,end-refstart,bpcov))/(end-sourcestart+1);
float covleft=get_cov_sign(sno,start-refstart,sourcestart-1-refstart,bpcov)/(sourcestart-start);
float covright=localdrop*get_cov_sign(sno,sourcestart-refstart,end-refstart,bpcov)/(end-sourcestart+1);
if(covleft>covright) {
sourcestart=0;
}
}
}
else if(sinkend) {
//float covright=localdrop*(get_cov(1,start-refstart,sinkend-refstart,bpcov)-get_cov(os,start-refstart,sinkend-refstart,bpcov))/(sinkend-start+1);
//float covleft=(get_cov(1,sinkend+1-refstart,end-refstart,bpcov)-get_cov(os,sinkend+1-refstart,end-refstart,bpcov))/(end-sinkend);
float covright=localdrop*get_cov_sign(sno,start-refstart,sinkend-refstart,bpcov)/(sinkend-start+1);
float covleft=get_cov_sign(sno,sinkend+1-refstart,end-refstart,bpcov)/(end-sinkend);
if(covleft>covright) {
sinkend=0;
}
}
}
void find_all_trims(int refstart,int sno,uint start,uint end,GVec<float>* bpcov,GVec<CTrimPoint> &trimpoint) {
// this procedure returns all trims it finds and stores them in trimpoint
//fprintf(stderr,"find all trims in region:%d-%d:%d\n",start,end,sno);
int len=end-start+1; // length of region where I look for trims
if(len<CHI_THR) return; // very short exon -> do not check
float localdrop=ERROR_PERC; // very sharp drop
if(len<2*(CHI_WIN+CHI_THR)+1) {
if(len<CHI_WIN) { // check very tightly, and only accept one trim
localdrop=ERROR_PERC/(10*DROP); // very sharp drop
}
float lastdrop=localdrop;
for(uint i=start+longintronanchor;i<end-longintronanchor;i++) {
float covleft=get_cov_sign(sno,start-refstart,i-1-refstart,bpcov)/(i-start);
float covright=get_cov_sign(sno,i-refstart,end-refstart,bpcov)/(end-i+1);
if(covleft<covright) { // possible source trimming
//float thisdrop=(covleft+1)/(covright+1); // make sure I add one read to mitigate gaps in coverage
float thisdrop=covleft/covright; // make sure I add one read to mitigate gaps in coverage
//fprintf(stderr,"found source drop=%f covleft=%f covright=%f at i=%d\n",thisdrop,covleft,covright,i+1);
if(thisdrop<localdrop) {
if(!trimpoint.Count() || (!trimpoint.Last().start && i+1-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i+1,(covright-covleft)/DROP,true);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop
lastdrop=thisdrop;
trimpoint.Last().pos=i+1;
trimpoint.Last().abundance=(covright-covleft)/DROP;
trimpoint.Last().start=true;
}
}
}
else if(covright!=covleft) { // possible sink trimming: covright<covleft here
float thisdrop=(covright+1)/(covleft+1);
//fprintf(stderr,"found sink drop=%f covleft=%f covright=%f at i=%d\n",thisdrop,covleft,covright,i);
if(thisdrop<localdrop) {
if(!trimpoint.Count() || (trimpoint.Last().start && i-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i,(covleft-covright)/DROP,false);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop
lastdrop=thisdrop;
trimpoint.Last().pos=i;
trimpoint.Last().abundance=(covleft-covright)/DROP;
trimpoint.Last().start=false;
}
}
}
}
return;
}
// now len >= CHI_WIN
int winlen=CHI_WIN+CHI_THR;
float lastdrop=localdrop;
for(uint i=start+CHI_THR-1;i<start+winlen-1;i++) {
float covleft=get_cov_sign(sno,start-refstart,i-refstart,bpcov)/(i-start);
float covright=get_cov_sign(sno,i+1-refstart,i+winlen-refstart,bpcov)/winlen;
if(covleft<covright) { // possible source trimming
float thisdrop=covleft/covright;
//fprintf(stderr,"found source drop=%f covleft=%f covright=%f at i=%d lastdrop=%f\n",thisdrop,covleft,covright,i+1,lastdrop);
if(thisdrop<localdrop) { // this drop passes threshold
if(!trimpoint.Count() || (!trimpoint.Last().start && i+1-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i+1,(covright-covleft)/DROP,true);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop; it also has to be smallest within a 50bp prevwindow
lastdrop=thisdrop;
trimpoint.Last().pos=i+1;
trimpoint.Last().abundance=(covright-covleft)/DROP;
trimpoint.Last().start=true;
}
}
}
else if(covleft!=covright) { // possible sink trimming: covright<covleft here
float thisdrop=covright/covleft;
//fprintf(stderr,"found sink drop=%f covleft=%f covright=%f at i=%d lastdrop=%f\n",thisdrop,covleft,covright,i,lastdrop);
if(thisdrop<localdrop) { // this drop passes threshold
if(!trimpoint.Count() || (trimpoint.Last().start && i-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i,(covleft-covright)/DROP,false);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop
lastdrop=thisdrop;
trimpoint.Last().pos=i;
trimpoint.Last().abundance=(covleft-covright)/DROP;
trimpoint.Last().start=false;
}
}
}
}
localdrop=ERROR_PERC/DROP; // I might want to use different parameters here
if(mixedMode) localdrop=DROP*DROP; // tolerate more for mixedMode
if(!trimpoint.Count()) lastdrop=localdrop;
len+=start-winlen;
for(int i=start+winlen-1;i<len;i++) {
float covleft=get_cov_sign(sno,i-winlen+1-refstart,i-refstart,bpcov); // I add 1 bp coverage to all so I can avoid 0 coverages
float covright=get_cov_sign(sno,i+1-refstart,i+winlen-refstart,bpcov);
if(covleft<covright) { // possible source trimming
//float thisdrop=(covleft+winlen)/(covright+winlen); // one read is added in order to avoid gaps in coverage
float thisdrop=covleft/covright;
if(thisdrop<localdrop) { // this drop passes threshold
//fprintf(stderr,"found source drop=%f covleft=%f covright=%f at i=%d window:%d-%d lastdrop=%f\n",thisdrop,covleft,covright,i+1,i-winlen+1,i+winlen,lastdrop);
if(!trimpoint.Count() || (!trimpoint.Last().start && i+1-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i+1,(covright-covleft)/(DROP*winlen),true);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop; it also has to be smallest within a 50bp prevwindow
lastdrop=thisdrop;
trimpoint.Last().pos=i+1;
trimpoint.Last().abundance=(covright-covleft)/(DROP*winlen);
trimpoint.Last().start=true;
}
}
}
else if(covleft!=covright) { // possible sink trimming: covright<covleft here
//float thisdrop=(covright+winlen)/(covleft+winlen); // one read is added in order to avoid gaps in coverage
float thisdrop=covright/covleft;
if(thisdrop<localdrop) { // this drop passes threshold
//fprintf(stderr,"found sink drop=%f covleft=%f covright=%f at i=%d window:%d-%d lastdrop=%f\n",thisdrop,covleft,covright,i,i-winlen+1,i+winlen,lastdrop);
if(!trimpoint.Count() || (trimpoint.Last().start && i-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i,(covleft-covright)/(DROP*winlen),false);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop
lastdrop=thisdrop;
trimpoint.Last().pos=i;
trimpoint.Last().abundance=(covleft-covright)/(DROP*winlen);
trimpoint.Last().start=false;
}
}
}
}
localdrop=ERROR_PERC;
for(uint i=len;i<end-CHI_THR-1;i++) {
float covleft=get_cov_sign(sno,i-winlen+1-refstart,i-refstart,bpcov)/winlen;
float covright=get_cov_sign(sno,i+1-refstart,end-refstart,bpcov)/(end-i);
if(covleft<covright) { // possible source trimming
float thisdrop=covleft/covright;
//fprintf(stderr,"found source drop=%f covleft=%f covright=%f at i=%d lastdrop=%f\n",thisdrop,covleft,covright,i+1,lastdrop);
if(thisdrop<localdrop) { // this drop passes threshold
if(!trimpoint.Count() || (!trimpoint.Last().start && i+1-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i+1,(covright-covleft)/DROP,true);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop; it also has to be smallest within a 50bp prevwindow
lastdrop=thisdrop;
trimpoint.Last().pos=i+1;
trimpoint.Last().abundance=(covright-covleft)/DROP;
trimpoint.Last().start=true;
}
}
}
else if(covleft!=covright) { // possible sink trimming: covright<covleft here
float thisdrop=covright/covleft;
//fprintf(stderr,"found sink drop=%f covleft=%f covright=%f at i=%d lastdrop=%f\n",thisdrop,covleft,covright,i,lastdrop);
if(thisdrop<localdrop) { // this drop passes threshold
if(!trimpoint.Count() || (trimpoint.Last().start && i-(int)trimpoint.Last().pos>CHI_THR)) { // add this point to trimpoints
CTrimPoint t(i,(covleft-covright)/DROP,false);
trimpoint.Add(t);
lastdrop=thisdrop;
}
else if(thisdrop<lastdrop){ // smaller drop than before --> replace drop
lastdrop=thisdrop;
trimpoint.Last().pos=i;
trimpoint.Last().abundance=(covleft-covright)/DROP;
trimpoint.Last().start=false;
}
}
}
}
localdrop=ERROR_PERC/DROP; // I might want to use different parameters here
// I might adjust localdrop again here
uint laststart=start;
for(int i=0;i<trimpoint.Count();i++) {
uint midpos=trimpoint[i].pos;
if(trimpoint[i].start) midpos--;
float covleft=get_cov_sign(sno,laststart-refstart,midpos-refstart,bpcov)/(midpos-laststart+1); // I add 1 bp coverage to all so I can avoid 0 coverages
uint endpos=end;
if(i<trimpoint.Count()-1) endpos=trimpoint[i+1].pos;
float covright=get_cov_sign(sno,midpos+1-refstart,endpos-refstart,bpcov)/(endpos-midpos);
if((trimpoint[i].start && covleft<localdrop*covright)||(covright<localdrop*covleft)) { // source|sink above threshold
laststart=trimpoint[i].pos+1;
}
else { // trimpoint is not above threshold --> do not change laststart, but I need to reevaluate previous trimpoints
//fprintf(stderr,"pos=%d failed global test btw %d-%d midpos=%d covlef=%.1f covright=%.1f\n",trimpoint[i].pos,laststart,endpos,midpos,covleft,covright);
trimpoint[i].pos=0;
int k=i-1;
while(k>=0) {
while(k>=0 && !trimpoint[k].pos) k--;
if(k>=0) { // found a point above threshold
midpos=trimpoint[k].pos;
if(trimpoint[k].start) midpos--;
uint leftstart=start;
int j=k-1;
while(j>=0) {
if(trimpoint[j].pos) { leftstart=trimpoint[j].pos;break;}
j--;
}
covleft=get_cov_sign(sno,leftstart-refstart,midpos-refstart,bpcov)/(midpos-leftstart+1); // I add 1 bp coverage to all so I can avoid 0 coverages
covright=get_cov_sign(sno,midpos+1-refstart,endpos-refstart,bpcov)/(endpos-midpos);
if((trimpoint[k].start && covleft<localdrop*covright)||(covright<localdrop*covleft)) { // source|sink above threshold
break; // finished looking for k
}
else {
//fprintf(stderr,"pos=%d failed global test btw %d-%d midpos=%d covlef=%.1f covright=%.1f\n",trimpoint[k].pos,leftstart,endpos,midpos,covleft,covright);
trimpoint[k].pos=0;
}
k--;
}
}
}
}
/*
{ // DEBUG ONLY
fprintf(stderr,"All trim points:");
for(int i=0;i<trimpoint.Count();i++) {
if(trimpoint[i].start) fprintf(stderr," s:%d",trimpoint[i].pos);
else fprintf(stderr," e:%d",trimpoint[i].pos);
}
fprintf(stderr,"\n");
}
*/
}
CGraphnode *add_trim_to_graph(int s, int g,uint lastpos,CTrimPoint& mytrim,CGraphnode *graphnode,CGraphnode *source,CGraphnode *sink,GVec<float>& futuretr,
int& graphno,CBundlenode *bundlenode,GVec<CGraphinfo> **bundle2graph,GPVec<CGraphnode> **no2gnode) {
if(mytrim.start) { // this is a source link
float tmp=graphno-1;
CGraphnode *prevnode=NULL;
if(mytrim.pos>graphnode->start) { // there is place for another node
uint prevend=graphnode->end;
graphnode->end=mytrim.pos-1;
prevnode=graphnode;
graphnode=create_graphnode(s,g,mytrim.pos,prevend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
}
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
if(prevnode) {
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
}
futuretr.Add(tmp);
futuretr.cAdd(0.0);
futuretr.Add(mytrim.abundance);
}
else { // this is a link to sink
float tmp=graphno-1;
if(mytrim.pos<lastpos) { // there is still place for a new node
uint prevend=graphnode->end;
graphnode->end=mytrim.pos;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,mytrim.pos+1,prevend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
sink->parent.Add(prevnode->nodeid); // prevnode is the parent of sink
}
else {
sink->parent.Add(graphnode->nodeid); // prevnode is the parent of sink
}
futuretr.Add(tmp);
futuretr.cAdd(1.0);
futuretr.Add(mytrim.abundance);
}
return(graphnode);
}
// cummulative bpcov
CGraphnode *source2guide(int s, int g, int refstart,uint newstart,uint newend, CGraphnode *graphnode,CGraphnode *source,
GVec<float>* bpcov,GVec<float>& futuretr, int& graphno,CBundlenode *bundlenode,GVec<CGraphinfo> **bundle2graph,
GPVec<CGraphnode> **no2gnode, int &edgeno) {
if(graphnode->start+longintronanchor>newstart) { // newstart is very close to graphnode start
for(int p=0;p<graphnode->parent.Count();p++) if(!graphnode->parent[p]) return(graphnode);
}
// compute maxabund
float leftcov=0;
float rightcov=0;
//int os=2-2*s; // other strand
if(!mergeMode) {
if(newstart>graphnode->start) {
uint gstart=graphnode->start;
if(newstart-gstart > CHI_WIN) {
gstart=newstart-CHI_WIN;
}
//leftcov=get_cov(1,gstart-refstart,newstart-1-refstart,bpcov)- get_cov(os,gstart-refstart,newstart-1-refstart,bpcov);
leftcov=get_cov_sign(2*s,gstart-refstart,newstart-1-refstart,bpcov);
leftcov/=newstart-gstart;
}
if(newstart<newend) {
uint gend=newend;
if(newend-newstart>=CHI_WIN) {
gend=newstart+CHI_WIN-1;
}
//rightcov=get_cov(1,newstart-refstart,gend-refstart,bpcov)-get_cov(os,newstart-refstart,gend-refstart,bpcov);
rightcov=get_cov_sign(2*s,newstart-refstart,gend-refstart,bpcov);
rightcov/=gend-newstart+1;
}
}
float maxabund=rightcov-leftcov;
if(maxabund<trthr) maxabund=trthr;
if(graphnode->start<=newstart-1) {
uint prevend=graphnode->end;
graphnode->end=newstart-1;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,newstart,prevend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
float tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
}
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
float tmp=graphno-1;
futuretr.cAdd(0.0);
futuretr.Add(tmp);
futuretr.Add(maxabund);
// COUNT 1 EDGE HERE because the source to guide edge was already included in our count
edgeno++;
return(graphnode);
}
// cummulative version
CGraphnode *guide2sink(int s, int g, int refstart,uint newstart,uint newend, CGraphnode *graphnode,CGraphnode *sink,
GVec<float>* bpcov,GVec<float>& futuretr, int& graphno,CBundlenode *bundlenode,GVec<CGraphinfo> **bundle2graph,
GPVec<CGraphnode> **no2gnode, int &edgeno) {
// compute maxabund
float leftcov=0;
float rightcov=0;
//int os=2-2*s;
if(!mergeMode) {
if(newstart>=graphnode->start) {
uint gstart=graphnode->start;
if(newstart-gstart >= CHI_WIN) {
gstart=newstart-CHI_WIN+1;
}
//leftcov=get_cov(1,gstart-refstart,newstart-refstart,bpcov)-get_cov(os,gstart-refstart,newstart-refstart,bpcov);
leftcov=get_cov_sign(2*s,gstart-refstart,newstart-refstart,bpcov);
leftcov/=newstart-gstart+1;
}
if(newstart+1<newend) {
uint gend=newend;
if(newend-newstart>CHI_WIN) {
gend=newstart+CHI_WIN;
}
//rightcov=get_cov(1,newstart+1-refstart,gend-refstart,bpcov)-get_cov(os,newstart+1-refstart,gend-refstart,bpcov);
rightcov=get_cov_sign(2*s,newstart+1-refstart,gend-refstart,bpcov);
rightcov/=gend-newstart;
}
}
float maxabund=leftcov-rightcov;
if(maxabund<trthr) maxabund=trthr;
float tmp=graphno-1;
uint prevend=graphnode->end;
graphnode->end=newstart;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,newstart+1,prevend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
sink->parent.Add(prevnode->nodeid); // prevnode is the parent of sink
futuretr.Add(tmp);
futuretr.cAdd(-1.0);
futuretr.Add(maxabund);
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 1 EDGE HERE because the source to guide edge was already included in our count
edgeno++;
return(graphnode);
}
CGraphnode *longtrim(int s, int g, int refstart,int nodeend, int &nls, int &nle, bool &startcov, bool endcov, GVec<CPred> &lstart, GVec<CPred> &lend,
CGraphnode *graphnode,CGraphnode *source, CGraphnode *sink, GVec<float>& futuretr, int& graphno, GVec<float>* bpcov,
CBundlenode *bundlenode,GVec<CGraphinfo> **bundle2graph,GPVec<CGraphnode> **no2gnode, int &edgeno) {
while(nls<lstart.Count() && lstart[nls].predno<(int)graphnode->start) nls++;
while(nle<lend.Count() && lend[nle].predno<(int)graphnode->start) nle++;
while((nls<lstart.Count() && lstart[nls].predno<nodeend) || (nle<lend.Count() && lend[nle].predno<nodeend)){
if(nle>=lend.Count() || (nls<lstart.Count() && lstart[nls].predno<=lend[nle].predno)) { // start comes first
float tmpcov=0;
if((startcov || lstart[nls].predno>(int)(graphnode->start+longintronanchor)) &&(endcov || lstart[nls].predno<nodeend+(int)longintronanchor)) { // start and ends can not be too close to a junction
int startpos=lstart[nls].predno-refstart;
int winstart=startpos-CHI_THR;
if(winstart<0) winstart=0;
int winend=startpos+CHI_THR-1;
if(winend>=bpcov->Count()) winend=bpcov->Count()-1;
/*tmpcov=(get_cov(1,startpos,winend,bpcov)-get_cov(2-2*s,startpos,winend,bpcov)-
get_cov(1,winstart,startpos-1,bpcov)+get_cov(2-2*s,winstart,startpos-1,bpcov))/(DROP*CHI_THR);*/
tmpcov=(get_cov_sign(2*s,startpos,winend,bpcov)-get_cov_sign(2*s,winstart,startpos-1,bpcov))/(DROP*CHI_THR);
}
if(tmpcov<=0 && lstart[nls].cov<0) tmpcov=ERROR_PERC; // to re-estimate later in process_transfrags
if(tmpcov>0) {
tmpcov+=trthr;
uint prevend=graphnode->end;
graphnode->end=lstart[nls].predno-1;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,lstart[nls].predno,prevend,graphno,bundlenode,bundle2graph,no2gnode);
graphnode->hardstart=true;
graphno++;
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
float tmp=graphno-1;
futuretr.cAdd(0.0);
futuretr.Add(tmp);
//tmp=lstart[nls].cov+trthr;
futuretr.Add(tmpcov);
// graphnode->start,lstart[nls].cov,get_cov(2*s,startpos,startpos+CHI_THR-1,bpcov),get_cov(1,startpos,startpos+CHI_THR-1,bpcov),get_cov(2-2*s,startpos,startpos+CHI_THR-1,bpcov),
// get_cov(2*s,startpos-CHI_THR,startpos-1,bpcov),get_cov(1,startpos-CHI_THR,startpos-1,bpcov),get_cov(2-2*s,startpos-CHI_THR,startpos-1,bpcov));
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
startcov=false;
}
nls++;
}
else if(nls>=lstart.Count() || (nle<lend.Count() && lend[nle].predno<lstart[nls].predno)) { // end comes first
float tmpcov=0;
if((!startcov || lend[nle].predno>(int)(graphnode->start+longintronanchor)) &&(!endcov || lend[nle].predno<nodeend+(int)longintronanchor)) {
int endpos=lend[nle].predno-refstart;
int winstart=endpos-CHI_THR+1;
if(winstart<0) winstart=0;
int winend=endpos+CHI_THR;
if(winend>=bpcov->Count()) winend=bpcov->Count()-1;
/*tmpcov=(get_cov(1,winstart,endpos,bpcov)-get_cov(2-2*s,winstart,endpos,bpcov)-
get_cov(1,endpos+1,winend,bpcov)+get_cov(2-2*s,endpos+1,winend,bpcov))/(DROP*CHI_THR);*/
tmpcov=(get_cov_sign(2*s,winstart,endpos,bpcov)-get_cov_sign(2*s,endpos+1,winend,bpcov))/(DROP*CHI_THR);
}
if(tmpcov<=0 && lend[nle].cov<0) tmpcov=ERROR_PERC; // to re-estimate later in process_transfrags
if(tmpcov>0) {
tmpcov+=trthr;
float tmp=graphno-1;
uint prevend=graphnode->end;
graphnode->end=lend[nle].predno;
CGraphnode *prevnode=graphnode;
graphnode->hardend=true;
graphnode=create_graphnode(s,g,lend[nle].predno+1,prevend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
sink->parent.Add(prevnode->nodeid); // prevnode is the parent of sink
// remember to create transfrag as well -> I don't know the gno yet, so I can not create it here
futuretr.Add(tmp);
futuretr.cAdd(-1.0);
//tmp=lend[nle].cov+trthr;
futuretr.Add(tmpcov);
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
startcov=true;
}
nle++;
}
}
return(graphnode);
}
CGraphnode *trimnode(int s, int g, int refstart,uint newend, CGraphnode *graphnode,CGraphnode *source, CGraphnode *sink, GVec<float>* bpcov,
GVec<float>& futuretr, int& graphno,CBundlenode *bundlenode,GVec<CGraphinfo> **bundle2graph,GPVec<CGraphnode> **no2gnode, int &edgeno) {
uint sourcestart=0;
uint sinkend=0;
float sinkabundance=0;
float sourceabundance=0;
//float sourcecovleft=0;
//float sourcecovright=0;
//float sinkcovleft=0;
//float sinkcovright=0;
//find_trims(refstart,2*s,graphnode->start,newend,bpcov,sourcestart,sourcecovleft,sourcecovright,sinkcovleft,sinkcovright);
find_trims_wsign(refstart,2*s,graphnode->start,newend,bpcov,sourcestart,sourceabundance,sinkend,sinkabundance);
//find_trims(refstart,graphnode->start,newend,bpcov,sourcestart,sourceabundance,sinkend,sinkabundance);
if(sourcestart < sinkend) { // source trimming comes first
if(sourcestart) { // there is evidence of graphnode trimming from source
graphnode->end=sourcestart-1;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,sourcestart,newend,graphno,bundlenode,bundle2graph,no2gnode);
graphnode->hardstart=true;
graphno++;
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
float tmp=graphno-1;
futuretr.cAdd(0.0);
futuretr.Add(tmp);
sourceabundance+=trthr;futuretr.Add(sourceabundance);
//sourcecovright+=trthr;futuretr.Add(sourcecovright);
// start TRY linking to end also here
//tmp=prevnode->nodeid;futuretr.Add(tmp);futuretr.cAdd(-1.0);tmp=sourcecovleft+trthr;futuretr.Add(tmp);sink->parent.Add(prevnode->nodeid);edgeno++;
// end TRY linking to end also here
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
}
// sinkend is always positive since it's bigger than sourcestart
float tmp=graphno-1;
graphnode->end=sinkend;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,sinkend+1,newend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
sink->parent.Add(prevnode->nodeid); // prevnode is the parent of sink
prevnode->hardend=true;
// remember to create transfrag as well -> I don't know the gno yet, so I can not create it here
futuretr.Add(tmp);
futuretr.cAdd(-1.0);
sinkabundance+=trthr;futuretr.Add(sinkabundance);
//sinkcovleft+=trthr;futuretr.Add(sinkcovleft);
// start TRY linking to end also here
//tmp=graphnode->nodeid;futuretr.cAdd(0.0);futuretr.Add(tmp);tmp=sinkcovright+trthr;futuretr.Add(tmp);source->child.Add(graphnode->nodeid);edgeno++;
// end TRY linking to end also here
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
}
else if(sourcestart > sinkend) { // sink trimming comes first
if(sinkend) {
graphnode->end=sinkend;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,sinkend+1,newend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
sink->parent.Add(prevnode->nodeid); // prevnode is the parent of sink
prevnode->hardend=true;
// remember to create transfrag as well -> I don't know the gno yet, so I can not create it here
float tmp=graphno-2;
futuretr.Add(tmp);
futuretr.cAdd(-1.0);
sinkabundance+=trthr;futuretr.Add(sinkabundance);
//sinkcovleft+=trthr;futuretr.Add(sinkcovleft);
// start TRY linking to end also here
//tmp=graphnode->nodeid;futuretr.cAdd(0.0);futuretr.Add(tmp);tmp=sinkcovright+trthr;futuretr.Add(tmp);source->child.Add(graphnode->nodeid);edgeno++;
// end TRY linking to end also here
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
}
// sourcestart is positive since it's bigger than sinkend
graphnode->end=sourcestart-1;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,sourcestart,newend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->hardstart=true;
graphnode->parent.Add(source->nodeid); // this node has source as parent
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
float tmp=graphno-1;
futuretr.cAdd(0.0);
futuretr.Add(tmp);
sourceabundance+=trthr;futuretr.Add(sourceabundance);
//sourcecovright+=trthr;futuretr.Add(sourcecovright);
// start TRY linking to end also here
//tmp=prevnode->nodeid;futuretr.Add(tmp);futuretr.cAdd(-1.0);tmp=sourcecovleft+trthr;futuretr.Add(tmp);sink->parent.Add(prevnode->nodeid);edgeno++;
// end TRY linking to end also here
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
}
// else both source and sink trimming are not present
return(graphnode);
}
CGraphnode *trimnode_all(int s, int g, int refstart,uint newend, CGraphnode *graphnode,CGraphnode *source, CGraphnode *sink, GVec<float>* bpcov,
GVec<float>& futuretr, int& graphno,CBundlenode *bundlenode,GVec<CGraphinfo> **bundle2graph,GPVec<CGraphnode> **no2gnode, int &edgeno) {
GVec<CTrimPoint> trimpoint;
find_all_trims(refstart,2*s,graphnode->start,newend,bpcov,trimpoint);
for(int i=0;i<trimpoint.Count();i++) if(trimpoint[i].pos){
if(trimpoint[i].start) { // source trim
graphnode->end=trimpoint[i].pos-1;
//fprintf(stderr,"Create source trim:%d-%d and %d-%d\n",graphnode->start,graphnode->end,trimpoint[i].pos,newend);
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,trimpoint[i].pos,newend,graphno,bundlenode,bundle2graph,no2gnode);
graphnode->hardstart=true;
graphno++;
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
float tmp=graphno-1;
futuretr.cAdd(0.0);
futuretr.Add(tmp);
float sourceabundance=trimpoint[i].abundance+trthr;futuretr.Add(sourceabundance);
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
}
else { // this is sink
graphnode->end=trimpoint[i].pos;
CGraphnode *prevnode=graphnode;
graphnode=create_graphnode(s,g,trimpoint[i].pos+1,newend,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
prevnode->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(prevnode->nodeid); // this node has as parent the previous node
sink->parent.Add(prevnode->nodeid); // prevnode is the parent of sink
prevnode->hardend=true;
// remember to create transfrag as well -> I don't know the gno yet, so I can not create it here
float tmp=graphno-2;
futuretr.Add(tmp);
futuretr.cAdd(-1.0);
float sinkabundance=trimpoint[i].abundance+trthr;futuretr.Add(sinkabundance);
tmp=prevnode->nodeid;futuretr.Add(tmp);
tmp=graphnode->nodeid;futuretr.Add(tmp);
tmp=trthr;futuretr.Add(tmp);
// COUNT 2 EDGES HERE
edgeno+=2;
}
}
return(graphnode);
}
inline int edge(int min, int max, int gno) {
//return((gno-1)*min-min*(min-1)/2+max-min); // this should be changed if source to node edges are also stored
return((gno-1)*(min+1)-min*(min-1)/2+max-min); // this includes source to node edges
}
GBitVec traverse_dfs(int s,int g,CGraphnode *node,CGraphnode *sink,GBitVec parents,int gno, GVec<bool>& visit,
GPVec<CGraphnode> **no2gnode,GPVec<CTransfrag> **transfrag, int &edgeno,GIntHash<int> **gpos,int &lastgpos){
//fprintf(stderr,"Traverse node %d\n",node->nodeid);
if(visit[node->nodeid]) {
node->parentpat = node->parentpat | parents;
for(int n=0;n<gno;n++) {
if(parents[n]) // add node's children to all parents of node
no2gnode[s][g][n]->childpat = no2gnode[s][g][n]->childpat | node->childpat;
else if(node->childpat[n])
no2gnode[s][g][n]->parentpat = no2gnode[s][g][n]->parentpat | node->parentpat;
}
}
else {
node->childpat.resize(gno+edgeno);
node->parentpat.resize(gno+edgeno);
node->parentpat = node->parentpat | parents;
visit[node->nodeid]=true;
parents[node->nodeid]=1; // add the node to the parents
if(node->parent.Count()==1 && !node->parent[0]) { // node has source only as parent -> add transfrag from source to node
GBitVec trpat(gno+edgeno);
trpat[0]=1;
trpat[node->nodeid]=1;
int key=edge(0,node->nodeid,gno);
int *pos=gpos[s][g][key];
if(pos!=NULL) trpat[*pos]=1;
else {
gpos[s][g].Add(key,lastgpos);
trpat[lastgpos]=1;
lastgpos++;
}
GVec<int> nodes;
nodes.cAdd(0);
nodes.Add(node->nodeid);
CTransfrag *tr=new CTransfrag(nodes,trpat,trthr);
/*
{ // DEBUG ONLY
fprintf(stderr,"Add source transfrag[%d][%d]= %d and pattern",s,g,transfrag[s][g].Count());
//printBitVec(trpat);
fprintf(stderr,"\n");
}
*/
/*if(mixedMode) {
tr->abundance*=2;
}*/
transfrag[s][g].Add(tr);
if(mixedMode) { // I need to add a long read as well
CTransfrag *longtr=new CTransfrag(nodes,trpat,trthr);
longtr->longread=true;
transfrag[s][g].Add(longtr);
} else
if(longreads) // || mixedMode)
transfrag[s][g].Last()->longread=true;
}
int n=node->child.Count();
if(node != sink && !n) {
node->child.Add(sink->nodeid); // add sink to the node's children
sink->parent.Add(node->nodeid); // add node to sink's parents
// create the transfrag that ends the node
GBitVec trpat(gno+edgeno);
trpat[node->nodeid]=1;
trpat[gno-1]=1;
int key=edge(node->nodeid,gno-1,gno);
int *pos=gpos[s][g][key];
if(pos!=NULL) trpat[*pos]=1;
else {
gpos[s][g].Add(key,lastgpos);
trpat[lastgpos]=1;
lastgpos++;
}
GVec<int> nodes;
nodes.Add(node->nodeid);
nodes.Add(sink->nodeid);
CTransfrag *tr=new CTransfrag(nodes,trpat,trthr);
/*
{ // DEBUG ONLY
fprintf(stderr,"Add sink transfrag[%d][%d]= %d for nodeid=%d and pattern:",s,g,transfrag[s][g].Count(),node->nodeid);
//printBitVec(trpat);
fprintf(stderr,"\n");
}
*/
/*if(mixedMode) {
tr->abundance*=2;
}*/
transfrag[s][g].Add(tr);
if(mixedMode) { // I need to add a long read as well
CTransfrag *longtr=new CTransfrag(nodes,trpat,trthr);
longtr->longread=true;
transfrag[s][g].Add(longtr);
}
else
if(longreads)// || mixedMode)
transfrag[s][g].Last()->longread=true;
n++;
}
/*
fprintf(stderr,"Add %d children of node %d (%d-%d): ",n,node->nodeid,node->start,node->end);
for(int i=0;i<n;i++) fprintf(stderr," %d",node->child[i]);
fprintf(stderr,"\n");
*/
//edgeno+=n; // this will have to be deleted in the end; now I put it so that I can check equivalence with the one computed when creating the graph
for(int i=0; i< n; i++) { // for all children
GBitVec childparents=parents;
int min=node->nodeid; // nodeid is always smaller than child node ?
int max=node->child[i];
if(min>max) {
max=node->nodeid; // nodeid is always smaller than child node ?
min=node->child[i];
}
int key=edge(min,max,gno);
int *pos=gpos[s][g][key];
if(pos!=NULL) {
childparents[*pos]=1; // add edge from node to child to the set of parents from child
node->childpat[*pos]=1; // add edge from node to child to the set of node children
}
else {
gpos[s][g].Add(key,lastgpos);
childparents[lastgpos]=1;
node->childpat[lastgpos]=1;
lastgpos++;
}
//fprintf(stderr,"Call for child %d with id=%d\n",node->child[i],no2gnode[s][g][node->child[i]]->nodeid);
node->childpat = node->childpat | traverse_dfs(s,g,no2gnode[s][g][node->child[i]],sink,childparents,gno,visit,no2gnode,transfrag,edgeno,gpos,lastgpos);
}
} // end else from if(visit[node->nodeid])
GBitVec children = node->childpat;
children[node->nodeid]=1;
return(children);
}
void delete_Ginterval(GInterval *interv){
if(interv) {
if(interv->next) delete_Ginterval(interv->next);
delete interv;
}
}
GInterval *add_interval(uint start,uint end,GInterval *guidecov) {
if(guidecov==NULL) { // no intervals defined yet
guidecov=new GInterval(start,end);
}
else {
if(end<guidecov->start-1) { // interval before guidecov; if(end==guidecov->start-1) it's like the intervals overlap
GInterval *interval=new GInterval(start,end,guidecov);
guidecov=interval;
}
else { // end>=guidecov->start-1 I need to place the new interval
GInterval *lastinterv=NULL; // last interval before overlap
GInterval *interval=guidecov;
while(interval && start>interval->end+1) { lastinterv=interval; interval = interval->next;}
if(interval) { // start <= interval->end+1; interval could be guidecov here
if(end<interval->start-1) { // (start,end) come before interval but does not intersect lastinterv
GInterval *newinterval=new GInterval(start,end,interval);
lastinterv->next=newinterval; // lastinterv can not be null
}
else { // (start,end) intersect interval
if(start<interval->start) interval->start=start;
lastinterv=interval; // start>=lastinterv->start, end>=lastinterv->start-1
if(end>lastinterv->end) lastinterv->end=end;
interval=interval->next;
while(interval && end>=interval->start-1) { // (start,end) intersects interval
if(lastinterv->end<interval->end) lastinterv->end=interval->end;
lastinterv->next=interval->next;
delete interval;
interval=lastinterv->next;
}
}
}
else { // (start,end) at the end of intervals
interval=new GInterval(start,end);
lastinterv->next=interval;
}
}
}
return(guidecov);
}
bool overlap_interval(uint start,uint end,GInterval *guidecov) {
if(guidecov==NULL || end<guidecov->start) return false; // interval before guide
while(guidecov && start>guidecov->end) guidecov=guidecov->next;
if(guidecov) { // start<=guidecov->end
if(end<guidecov->start) return false;
// end >= guidecov->start
return true;
}
return false;
}
int count_kept_nodes(GVec<CGNode> &node,int gno,GPVec<CGraphnode>& no2gnode) {
int new_graphno=1; // first include source and first node because this is always kept
for(int n=1;n<gno;n++) {
if(node[n].keep) {
bool update_count=true; // by default I update the count
if(!node[n].future && node[n-1].keep && no2gnode[n-1]->end+1==no2gnode[n]->start) { // only in the case that previous node is adjacent I can collapse nodes; never merge a future node
if(no2gnode[n-1]->child.Count()==1 && no2gnode[n-1]->child[0]==n && no2gnode[n]->parent.Count()==1) { // the adjacent parent is the only parent, and this node is the only child of it
update_count=false;
}
}
if(update_count) {
new_graphno++;
node[n].merge=false;
}
else node[n].merge=true;
}
}
return(new_graphno);
}
int gjuncCmp(const pointer p1, const pointer p2) {
CGJunc *a=(CGJunc *)p1;
CGJunc *b=(CGJunc *)p2;
if(a->goodcov>b->goodcov) return 1; // less coverage come first
if(a->goodcov<b->goodcov) return -1;
if(a->cov>b->cov) return 1; // less coverage come first
if(a->cov<b->cov) return -1;
return 0;
}
void delete_connection(GVec<CGNode> &node,int n1, int n2, GPVec<CGraphnode>& no2gnode,int &edgeno,int &estimate_graphno) {
int i=0;
while(i<no2gnode[n1]->child.Count()) {
if(no2gnode[n1]->child[i]==n2) {
no2gnode[n1]->child.Delete(i);
break;
}
i++;
}
if(!no2gnode[n1]->child.Count() && !no2gnode[n1]->parent.Count()){
node[n1].keep=false;
estimate_graphno--;
}
else if(no2gnode[n1]->child.Count()==1 && no2gnode[n1]->child[0]==n1+1 && no2gnode[n1]->end==no2gnode[n1+1]->start-1) { // node n1 can be merged with next one because there is no other junction from n1
estimate_graphno--;
}
i=0;
while(i<no2gnode[n2]->parent.Count()) {
if(no2gnode[n2]->parent[i]==n1) {
no2gnode[n2]->parent.Delete(i);
break;
}
i++;
}
if(!no2gnode[n2]->child.Count() && !no2gnode[n2]->parent.Count()) {
node[n2].keep=false;
estimate_graphno--;
}
else if(no2gnode[n2]->parent.Count()==1 && no2gnode[n2]->parent[0]==n2-1 && no2gnode[n2-1]->end==no2gnode[n2]->start-1) { // node n2 can be merged with previous one because there is no other junction to n2
estimate_graphno--;
}
edgeno--;
}
int prune_graph_nodes(int graphno,int s,int g,GVec<CGraphinfo> **bundle2graph, int bnodecount,
GPVec<CGraphnode> **no2gnode,GList<CJunction>& junction,int &edgeno,GVec<float> &futuretr,CGraphnode *sink){
//fprintf(stderr,"start with edgeno=%d\n",edgeno);
GVec<CGJunc> kjunc; // scan all junctions and keep the ones that are in the graph and I can potentially delete
int n=1; // first node in graph
for(int i=0;i<junction.Count();i++) {
if(junction[i]->start>no2gnode[s][g][graphno-1]->start) break; // all future junctions are out of the graph
if(!junction[i]->guide_match && junction[i]->strand+1==2*s && junction[i]->start>=no2gnode[s][g][1]->end && junction[i]->end<=no2gnode[s][g][graphno-1]->start) { // junction in graph
while(n<graphno && no2gnode[s][g][n]->end<junction[i]->start) n++;
if(n==graphno) break;
if(no2gnode[s][g][n]->end==junction[i]->start) {
int n2=0;
for(int c=0;c<no2gnode[s][g][n]->child.Count();c++) {
if(no2gnode[s][g][no2gnode[s][g][n]->child[c]]->start==junction[i]->end) {
n2=no2gnode[s][g][n]->child[c];
break;
}
}
if(n2) {
CGJunc jc(n,n2,junction[i]->nreads,junction[i]->nreads_good);
kjunc.Add(jc);
}
}
}
}
kjunc.Sort(gjuncCmp);
GVec<CGNode> node;
for(int i=0;i<graphno;i++) {
bool sinklink=false;
if(!no2gnode[s][g][i]->child.Count()) sinklink=true; // I could use this to parse nodes that do not link anywhere
CGNode inode(i,sinklink);
node.Add(inode); // node[0] has id 1
}
for(int i=0;i<futuretr.Count();i+=3) {
int n2=int(futuretr[i+1]);
if(n2>0) node[n2].future=true;
else node[futuretr[i]].last=true; // when n2==-1 there is a link to sink from n1
}
/*
for(int i=1;i<graphno;i++) {
//fprintf(stderr,"Node[%d]:%d-%d with parents:",i,no2gnode[s][g][i]->start,no2gnode[s][g][i]->end);
for(int p=0;p<no2gnode[s][g][i]->parent.Count();p++) fprintf(stderr," %d",no2gnode[s][g][i]->parent[p]);
fprintf(stderr," and children:");
for(int c=0;c<no2gnode[s][g][i]->child.Count();c++) fprintf(stderr," %d",no2gnode[s][g][i]->child[c]);
fprintf(stderr,"\n");
}
fprintf(stderr,"there are %d junctions\n",kjunc.Count());
*/
int i=0;
/*** code to increase threshold requirements for junctions
//int new_graphno=graphno;
while(i<kjunc.Count() && kjunc[i].goodcov<junctionthr+1) { // require at least one more read for support
delete_connection(node,kjunc[i].leftnode,kjunc[i].rightnode,no2gnode[s][g],edgeno);
i++;
}
end code ***/
/*** code that estimates new graphno ***/
int estimate_graphno=graphno;
while(estimate_graphno > allowed_nodes && i<kjunc.Count()) {
delete_connection(node,kjunc[i].leftnode,kjunc[i].rightnode,no2gnode[s][g],edgeno,estimate_graphno);
i++;
}
/*** end code ***/
int new_graphno=count_kept_nodes(node,graphno,no2gnode[s][g]);
/*
while(new_graphno > allowed_nodes && i<kjunc.Count()) {
// delete less covered junctions as long as they have the same coverage
double jcov=kjunc[i].cov+kjunc[i].goodcov;
int n=0;
while(i<kjunc.Count() && kjunc[i].cov+kjunc[i].goodcov==jcov) {
delete_connection(node,kjunc[i].leftnode,kjunc[i].rightnode,no2gnode[s][g]);
i++;
n++;
}
new_graphno=count_kept_nodes(node,graphno,no2gnode[s][g]);
}
*/
// there was a part here to re-create lost children likns, e.g. for 1->2->3 delete link from 1->2 and from 2->3. 1 might still want to link to 3
// I might need to recreate links to source though
// re-number nodes that are kept from 1 to new_graphno instead
i=1;
for(int n=1;n<graphno;n++) {
if(node[n].keep) {
CGraphnode *nnode=no2gnode[s][g][n];
if(node[n].merge) { // this node needs to be merged
int m=n-1;
while(node[m].merge) m--;
CGraphnode *mnode=no2gnode[s][g][m];
mnode->end=nnode->end;
mnode->child=nnode->child;
node[n].keep=false;
nnode=mnode;
}
else {
node[n].id=i++;
// also create links to source if needed --> the only one that does not recreate itself in traverse_dfs
if(!nnode->parent.Count()) { // I need to link to source
CGraphnode *source=no2gnode[s][g][0];
source->child.Add(nnode->nodeid);
nnode->parent.Add(0);
}
}
}
}
// redo the structures in the graph to reflect the new node numbering
// structures to deal with: graphnode->child, graphnode->parent (and edgeno), no2gnode, bundle2graph -> this also needs to be addressed in get_fragment/read_pattern
for(int n=graphno-1;n>0;n--) { // I am doing it from last node to first in order for the deletions to be meaningful
CGraphnode *inode=no2gnode[s][g][n];
if(node[n].keep) {
for(int c=inode->child.Count()-1;c>=0;c--) {
if(node[inode->child[c]].keep) { // if I keep it I have to give it the new id
inode->child[c]=node[inode->child[c]].id;
}
else { // I need to delete the child
inode->child.Delete(c);
edgeno--; // delete edge btwn node and child
}
}
for(int p=inode->parent.Count()-1;p>=0;p--) {
if(inode->parent[p]) { // if the parent is not the source
if(node[inode->parent[p]].keep) { // if I keep it I have to give it the new id
inode->parent[p]=node[inode->parent[p]].id;
}
else if(node[inode->parent[p]].merge) {
int m=inode->parent[p]-1;
while(node[m].merge) m--;
inode->parent[p]=node[m].id;
}
else { // I need to delete the parent
inode->parent.Delete(p);
edgeno--;
}
}
}
inode->nodeid=node[n].id;
}
else { // we need to delete the node
// need to update edge count first
for(int c=0;c<inode->child.Count();c++) {
if(!node[inode->child[c]].keep) edgeno--; // link to a deleted node needs to be removed
}
no2gnode[s][g].Delete(n); // this deletes the actual element too if gpvec was not created with free element =false
}
}
// deal with the source
CGraphnode *source=no2gnode[s][g][0];
for(int c=source->child.Count()-1;c>=0;c--) {
if(node[source->child[c]].keep) { // if I keep it I have to give it the new id
source->child[c]=node[source->child[c]].id;
}
else { // I need to delete the child --> this should never happen as I should never delete a link to source
source->child.Delete(c);
edgeno--; // delete edge btwn node and child
}
}
// deal with the sink --> do I have sink??
for(int p=sink->parent.Count()-1;p>=0;p--) {
if(node[sink->parent[p]].keep) { // if I keep it I have to give it the new id
sink->parent[p]=node[sink->parent[p]].id;
}
else { // I need to delete the parent
sink->parent.Delete(p);
edgeno--; // delete edge btwn node and child
}
}
for(int i=0;i<futuretr.Count();i+=3) {
int n1=int(futuretr[i]);
int n2=int(futuretr[i+1]);
if(n1>0) {
if(node[n1].keep || node[n1].merge) {
while(node[n1].merge) n1--;
if(n2>0) {
if(node[n2].keep) {
futuretr[i]=(float)node[n1].id;
futuretr[i+1]=(float)node[n2].id;
}
else { futuretr[i]=-1; edgeno--;}
}
else futuretr[i]=(float)node[n1].id;
}
else { futuretr[i]=-1; edgeno--;} // no longer interested in this futuretr
}
else { // n1 is the source
if(node[n2].keep) {
futuretr[i+1]=(float)node[n2].id;
}
else { futuretr[i]=-1;edgeno--;}
}
}
for(i=0;i<bnodecount;i++) {
for(int b=bundle2graph[s][i].Count()-1;b>=0;b--) {
if(bundle2graph[s][i][b].ngraph==g) {
if(node[bundle2graph[s][i][b].nodeno].keep) {
bundle2graph[s][i][b].nodeno=node[bundle2graph[s][i][b].nodeno].id;
}
else {
bundle2graph[s][i].Delete(b);
}
}
}
}
/*
{ //DEBUG ONLY
for(int i=0;i<new_graphno;i++) {
fprintf(stderr,"Node %d with parents:",i);
for(int p=0;p<no2gnode[s][g][i]->parent.Count();p++) fprintf(stderr," %d",no2gnode[s][g][i]->parent[p]);
fprintf(stderr," and children:");
for(int c=0;c<no2gnode[s][g][i]->child.Count();c++) fprintf(stderr," %d",no2gnode[s][g][i]->child[c]);
fprintf(stderr,"\n");
}
}
fprintf(stderr,"new edgeno=%d\n",edgeno);
*/
return(new_graphno);
}
int create_graph(int refstart,int s,int g,CBundle *bundle,GPVec<CBundlenode>& bnode,
GList<CJunction>& junction,GList<CJunction>& ejunction,GVec<CGraphinfo> **bundle2graph,
GPVec<CGraphnode> **no2gnode,GPVec<CTransfrag> **transfrag,GIntHash<int> **gpos,BundleData* bdata,
int &edgeno,int &lastgpos,GArray<GEdge>& guideedge, int refend=0){
GVec<float>* bpcov = bdata ? bdata->bpcov : NULL; // I might want to use a different type of data for bpcov to save memory in the case of very long bundles
CGraphnode* source=new CGraphnode(0,0,0);
no2gnode[s][g].Add(source);
CGraphnode* sink=new CGraphnode();
int njunctions=junction.Count();
//fprintf(stderr,"Start graph[%d][%d] with %d edgeno and lastgpos=%d\n",s,g,edgeno,lastgpos);
/*
{ // DEBUG ONLY
fprintf(stderr,"Junctions[%d][%d]: ",s,g);
for(int i=0;i<njunctions;i++) fprintf(stderr," %d-%d:%d",junction[i]->start,junction[i]->end,junction[i]->strand);
fprintf(stderr,"\n");
fprintf(stderr,"eJunctions[%d][%d]: ",s,g);
for(int i=0;i<njunctions;i++) fprintf(stderr," %d-%d:%d",ejunction[i]->start,ejunction[i]->end,ejunction[i]->strand);
fprintf(stderr,"\n");
}
*/
int nge=0;
bool processguide=false;
CBundlenode *bundlenode=bnode[bundle->startnode];
while(nge<guideedge.Count() && bundlenode!=NULL) {
uint start=guideedge[nge].val;
uint end=guideedge[nge].endval;
if(start>end) Gswap(start,end);
if(bundlenode->end<start) bundlenode=bundlenode->nextnode;
else if(guideedge[nge].strand==s && bundlenode->start<=end) { // bundlenode->end>=start
nge=0;
processguide=true;
break;
}
else nge++;
}
bundlenode=bnode[bundle->startnode];
int njs=0; // index of sorted junction starts
int nje=0; // index of sorted junction ends
int graphno=1; // number of nodes in graph
//GHash<GVec<int>* > ends; // keeps ids of all nodes ending at a certain position; OR ALL NODES THAT ARE LINKED BY JUNCTIONS TO A CERTAIN POSITION
GIntHash< GVec<int>* > ends;
GVec<float> futuretr;
if(mergeMode) { // I have a bunch of junctions at the start for which I need to create ends
while(njs<njunctions && !junction[njs]->start ) { // remember ends here for source node
if((junction[njs]->strand+1) == 2*s) {
//GStr je((int)junction[njs]->end);
//GVec<int> *e=ends[je.chars()];
GVec<int> *e=ends[junction[njs]->end];
if(!e) {
e = new GVec<int>();
//ends.Add(je.chars(),e);
ends.Add(junction[njs]->end, e);
}
e->cAdd(0);
}
njs++;
}
}
//int seenjunc=0;
int f=0; // feature index
uint bundle_end=bnode[bundle->lastnodeid]->end;
while(bundlenode!=NULL) {
//fprintf(stderr,"process bundlenode %d-%d:%d bpcov_count=%d refstart=%d\n",bundlenode->start,bundlenode->end,s,bpcov->Count(),refstart);
uint currentstart=bundlenode->start; // current start is bundlenode's start
uint endbundle=bundlenode->end; // initialize end with bundlenode's end for now
int end=0;
while(nje<njunctions && ejunction[nje]->end<=currentstart) { // read all junction ends at or before the current start -> assuming there are any (at this point, smaller junction ends should not be relevant to this bundle/currentstart
if(ejunction[nje]->end==currentstart && (ejunction[nje]->strand+1) == 2*s) { // junction ends at current start and is on the same strand and not deleted
end=1;
}
nje++;
}
GVec<CPred> lstart; // CPred: prediction point class
GVec<CPred> lend;
int fs=-1; // first start feature index in lstart
int fe=-1; // first end feature index in lend
if(longreads) { // this can not work the same in mixedMode!
GPVec<GPtFeature>& feature = bdata->ptfs; // these are point features (confirmed starts/stops)
if(feature.Count()) { // I already know the features
while(f<feature.Count() && feature[f]->coord<currentstart) f++;
}
if(endbundle-currentstart<=CHI_WIN+CHI_THR) { // I only consider the given features for this case
while(f<feature.Count() && feature[f]->coord<=endbundle) {
if(feature[f]->strand==2*s-1) {
if(feature[f]->ftype==GPFT_TSS) { // this is a start
CPred p(feature[f]->coord,-1); // start here -> a -1 indicates this is a given point feature
if(fs<0) fs=lstart.Count();
lstart.Add(p);
}
else if(feature[f]->ftype==GPFT_CPAS) { // this is an end
CPred p(feature[f]->coord,-1); // start here -> a -1 indicates this is a given point feature
if(fe<0) fe=lend.Count();
lend.Add(p);
}
}
f++;
}
}
else { // populate starts and ends for the bundlenode here if I have enough space to determine starts/ends in the bundlenode
while(f<feature.Count() && feature[f]->coord<currentstart+CHI_WIN+CHI_THR+longintronanchor) { // see if there are any features before the start
if(feature[f]->strand==2*s-1) {
if(feature[f]->ftype==GPFT_TSS) { // this is a start
CPred p(feature[f]->coord,-1); // start here -> a -1 indicates this is a given point feature
if(fs<0) fs=lstart.Count();
lstart.Add(p);
}
else if(feature[f]->ftype==GPFT_CPAS) { // this is an end
CPred p(feature[f]->coord,-1); // start here -> a -1 indicates this is a given point feature
if(fe<0) fe=lend.Count();
lend.Add(p);
}
}
f++;
}
GVec<float> diffval;
float sumstartleft=0;
float sumendleft=0;
float sumstartright=0;
float sumendright=0;
//float lastcov=get_cov(2*s,longintronanchor-1,longintronanchor-1,bpcov); // this only computes signed coverage (should I include neutral coverage here too?)
float lastcov=get_cov_sign(2*s,currentstart-refstart+longintronanchor-1,currentstart-refstart+longintronanchor-1,bpcov); // this includes neutral coverage
for(int i=currentstart+longintronanchor;i<(int)currentstart+CHI_THR+(int)longintronanchor;i++) {
//float icov=get_cov(2*s,i-refstart,i-refstart,bpcov);
float icov=get_cov_sign(2*s,i-refstart,i-refstart,bpcov);
float diff=icov-lastcov; // compute how many reads start at position i
diffval.Add(diff);
if(diff>0) sumstartleft+=diff;
else sumendleft-=diff;
lastcov=icov;
}
for(int i=currentstart+CHI_THR+longintronanchor;i<(int)currentstart+CHI_WIN+(int)longintronanchor;i++) {
//float icov=get_cov(2*s,i-refstart,i-refstart,bpcov);
float icov=get_cov_sign(2*s,i-refstart,i-refstart,bpcov);
float diff=icov-lastcov;
diffval.Add(diff);
if(diff>0) sumstartright+=diff;
else sumendright-=diff;
lastcov=icov;
}
int covend=endbundle-refstart;
if(bpcov->Count()<(int)endbundle) covend=bpcov->Count();
covend-=longintronanchor;
for(int i=currentstart+CHI_WIN+longintronanchor-refstart;i<covend;i++) {
// add features at position i
if((uint)i+CHI_THR+refstart<endbundle) while(f<feature.Count() && feature[f]->coord==(uint)i+CHI_THR+refstart) { // see if there are any features before the start
if(feature[f]->strand==2*s-1) {
if(feature[f]->ftype==GPFT_TSS) { // this is a start
CPred p(feature[f]->coord,-1); // start here -> a -1 indicates this is a given point feature
lstart.Add(p);
}
else if(feature[f]->ftype==GPFT_CPAS) { // this is an end
CPred p(feature[f]->coord,-1); // start here -> a -1 indicates this is a given point feature
lend.Add(p);
}
}
f++;
}
int m=(i-CHI_THR-longintronanchor-currentstart+refstart)%CHI_WIN;
if(diffval[m]>1/ERROR_PERC) { // starts here
if(sumstartleft<sumstartright*ERROR_PERC) { // potential start here
bool addstart=true;
int istart=refstart+i-CHI_THR;
if(lstart.Count()) {
int j=lstart.Count()-1;
if(abs(istart-lstart[j].predno)<CHI_WIN) {
addstart=false;
if(lstart[j].cov>0 && diffval[m]>lstart[j].cov) {
lstart[j].predno=istart;
lstart[j].cov=diffval[m];
}
}
}
if(addstart) {
CPred p(istart,diffval[m]);
lstart.Add(p);
}
}
}
//float icov=get_cov(2*s,i,i,bpcov);
float icov=get_cov_sign(2*s,i,i,bpcov);
int p=(m+CHI_THR)%CHI_WIN;
float diff=icov-lastcov;
if(diffval[p]>0) sumstartleft-=diffval[p];
else sumendleft+=diffval[p];
if(diffval[m]>0) {
sumstartleft+=diffval[m];
sumstartright-=diffval[m];
}
else {
sumendleft-=diffval[m];
sumendright+=diffval[m];
}
diffval[p]=diff;
if(diff>0) sumstartright+=diff;
else sumendright-=diff;
lastcov=icov;
if(diffval[m]<-1/ERROR_PERC) { // ends here
if(sumendleft*ERROR_PERC>sumendright) {
bool addend=true;
int istart=refstart+i-CHI_THR-1;
if(lend.Count()) {
int j=lend.Count()-1;
if(abs(istart-lend[j].predno)<CHI_WIN) {
addend=false;
if(lend[j].cov>0 && -diffval[m]>=lend[j].cov) {
lend[j].predno=istart;
lend[j].cov=-diffval[m];
}
}
}
if(addend) {
CPred p(refstart+i-CHI_THR-1,-diffval[m]);
lend.Add(p);
}
}
}
}
//for(int i=0;i<lstart.Count();i++) fprintf(stderr,"s=%d start at coord %d with cov=%f\n",s,lstart[i].predno,lstart[i].cov);
//for(int i=0;i<lend.Count();i++) fprintf(stderr,"s=%d end at coord %d with cov=%f\n",s,lend[i].predno,lend[i].cov);
}
}
// see if I need to adjust the start to ignore little hanging pieces that make no sense
if(!end) {
while(nje<njunctions && ejunction[nje]->strand+1!=2*s) nje++; // skip all junctions that are not on the same strand
if(!mergeMode && (nje<njunctions && ejunction[nje]->end - currentstart < junctionsupport) &&
(fs<0 || (uint)lstart[fs].predno>=ejunction[nje]->end) && // I do not want to miss any hard starts/ends
(fe<0 || (uint)lend[fe].predno>=ejunction[nje]->end)) { // there is a junction ending soon here
float covleft=get_cov(1,currentstart-refstart,ejunction[nje]->end-1-refstart,bpcov);
float covright=get_cov(1,ejunction[nje]->end-refstart,2*ejunction[nje]->end - currentstart-1-refstart,bpcov);
if(covleft<covright*(1-ERROR_PERC)) { // adjust start here if needed
currentstart=ejunction[nje]->end;
// I have to check ending junctions here again
while(nje<njunctions && ejunction[nje]->end<=currentstart) { // read all junction ends at or before the current start -> assuming there are any (at this point, smaller junction ends should not be relevant to this bundle/currentstart
if(ejunction[nje]->end==currentstart && (ejunction[nje]->strand+1) == 2*s) { // junction ends at current start and is on the same strand and not deleted
end=1;
}
nje++;
}
}
}
}
//fprintf(stderr,"create graph 1\n");
CGraphnode *graphnode=create_graphnode(s,g,currentstart,endbundle,graphno,bundlenode,bundle2graph,no2gnode); // creates a $graphno graphnode with start at bundle start, and end at bundle end
graphno++;
if(end) { // I might have nodes finishing here; but I have a junction finishing here for sure
//GStr cs((int)currentstart);
//GVec<int> *e=ends[cs.chars()]; // HOW CAN I HAVE MORE THAN ONE NODE FINISHING HERE???; because this keeps all nodes that are linked by junctions here
GVec<int> *e=ends[currentstart];
if(e) {
for(int i=0;i<e->Count();i++) {
CGraphnode *node=no2gnode[s][g][e->Get(i)];
node->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(node->nodeid); // this node has as parent the previous node
// COUNT EDGE HERE
edgeno++;
//fprintf(stderr,"1 Edge %d-%d, edgeno=%d\n",node->nodeid,graphnode->nodeid,edgeno);
}
}
else { // I haven't seen nodes before that finish here (maybe due to error correction?) => link to source
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
// COUNT EDGE HERE
edgeno++;
//fprintf(stderr,"2 Edge 0-%d, edgeno=%d\n",graphnode->nodeid,edgeno);
}
}
else { // this node comes from source directly
source->child.Add(graphnode->nodeid); // this node is the child of source
graphnode->parent.Add(source->nodeid); // this node has source as parent
// COUNT EDGE HERE
edgeno++;
//fprintf(stderr,"3 Edge 0-%d, edgeno=%d\n",graphnode->nodeid,edgeno);
}
bool completed=false;
bool dropcov=false; // false(0) means start of bundle or junction end (raise in coverage); true(1) means junction start (drop in coverage)
int nls=0; // index in longstart
int nle=0; // index in longend
do {
while(nje<njunctions && (((int)ejunction[nje]->strand+1) != 2*s)) nje++; // skip junctions that don't have the same strand
while(njs<njunctions && ((((int)junction[njs]->strand+1)!= 2*s) || (junction[njs]->start<currentstart))) njs++; // junctions that start before the current graphnode and I haven't seen them before are part of a different bundle
int minjunction = -1; // process next junction -> either a start or an ending whichever has the first position on the genome; if they have same position then process ending first
if((nje<njunctions && (ejunction[nje]->end<=endbundle)) || (njs<njunctions && (junction[njs]->start<=endbundle))) {
if(njs<njunctions && (junction[njs]->start<=endbundle) && junction[njs]->end>bundle_end) njs++;
else {
if(nje<njunctions) { // there are still junctions endings
if(njs<njunctions) { // there are still junctions starting
minjunction = junction[njs]->start >= ejunction[nje]->end ? 1 : 0; // one of them is clearly before the endbundle from the initial if
}
else minjunction = 1;
}
else minjunction = 0;
}
}
//fprintf(stderr,"minjunction=%d\n",minjunction);
//if(nje<njunctions) fprintf(stderr,"Found junction:%d-%d(%d)\n",ejunction[nje]->start,ejunction[nje]->end,ejunction[nje]->strand);
if(minjunction == 0 ) { // found a start junction here
// add guide starts/ends first
if(processguide) {
while(nge<guideedge.Count() && guideedge[nge].val<=graphnode->start) nge++;
if(nge<guideedge.Count()) {
while(true) {
while(nge<guideedge.Count() && guideedge[nge].strand!=s) nge++;
if(nge>=guideedge.Count() || guideedge[nge].val>=junction[njs]->start) break;
uint gstart=guideedge[nge].val;
uint gend=junction[njs]->start;
bool sourceguide=false;
if(guideedge[nge].val<guideedge[nge].endval) sourceguide=true;
nge++;
if(sourceguide) { if(guideedge[nge-1].endval>endbundle) continue;}
else if(guideedge[nge-1].endval<currentstart) continue;
while(nge<guideedge.Count() && guideedge[nge].strand!=s) nge++;
if(nge<guideedge.Count() && guideedge[nge].val<junction[njs]->start) gend=guideedge[nge].val;
// I need to check there is no other trimming needed due to drops from longreads
if(longreads && (lstart.Count() || lend.Count())) graphnode=longtrim(s,g,refstart,gstart,nls,nle,dropcov,!sourceguide,lstart,lend,
graphnode,source,sink,futuretr,graphno,bpcov,bundlenode,bundle2graph,no2gnode,edgeno);
if(sourceguide) {
graphnode=source2guide(s,g,refstart,gstart,gend,graphnode,source,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);
dropcov=false;
}
else {
graphnode=guide2sink(s,g,refstart,gstart,gend,graphnode,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);
dropcov=true;
}
}
}
}
//if(trim && !processguide && !mergeMode) graphnode=trimnode(s,g,refstart,junction[njs]->start,graphnode,source,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);// do something to find intermediate nodes; alternatively, I could only do this for end nodes
else if(longreads && (lstart.Count() || lend.Count())) graphnode=longtrim(s,g,refstart,junction[njs]->start,nls,nle,dropcov,true,lstart,lend,
graphnode,source,sink,futuretr,graphno,bpcov,bundlenode,bundle2graph,no2gnode,edgeno);
if(trim && !longreads && !mergeMode) graphnode=trimnode_all(s,g,refstart,junction[njs]->start,graphnode,source,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);// do something to find intermediate nodes; alternatively, I could only do this for end nodes
dropcov=true;
// if no trimming required just set the end of the node
graphnode->end=junction[njs]->start; // set the end of current graphnode to here; introduce smaller nodes if trimming is activated
uint pos=junction[njs]->start;
while(njs<njunctions && junction[njs]->start==pos ) { // remember ends here
if((junction[njs]->strand+1) == 2*s) {
//seenjunc++;
if(mergeMode && (int)junction[njs]->end==refend) { // this node goes straight to sink
sink->parent.Add(graphnode->nodeid); // graphnode is the parent of sink: check to see if I have a conflict with this
edgeno++; // count edge here
}
else {
//GStr je((int)junction[njs]->end);
//GVec<int> *e=ends[je.chars()];
GVec<int> *e=ends[junction[njs]->end];
if(!e) {
e = new GVec<int>();
//ends.Add(je.chars(),e);
ends.Add(junction[njs]->end, e);
}
e->Add(graphnode->nodeid);
}
}
njs++;
}
if(pos<endbundle) { // there is still place for another node in this bundle (I might put a limit of length here for the graphnode -> because otherwise one can assume this is just a pre-mRNA fragment)
// see if I should just skip node
if(endbundle-pos<junctionsupport) {
while(njs<njunctions && junction[njs]->strand+1 != 2*s) njs++;
if(!mergeMode && (njs>=njunctions || junction[njs]->start > endbundle) && (nje>=njunctions || ejunction[nje]->end > endbundle)) { // there are no more junctions starting within this bundle
float covleft=get_cov(1,2*pos-endbundle+1-refstart,pos-refstart,bpcov);
float covright=get_cov(1,pos+1-refstart,endbundle-refstart,bpcov);
if(covright<covleft*(1-ERROR_PERC)) { // adjust start here if needed
completed=true;
}
}
}
if(!completed) {
//fprintf(stderr,"create graph 2\n");
CGraphnode *nextnode = create_graphnode(s,g,pos+1,endbundle,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
graphnode->child.Add(nextnode->nodeid); // make nextnode a child of current graphnode
nextnode->parent.Add(graphnode->nodeid);// make graphnode a parent of nextnode
// COUNT EDGE HERE
edgeno++;
//fprintf(stderr,"4 Edge %d-%d, edgeno=%d nextnode: %u-%u pos=%d\n",graphnode->nodeid,nextnode->nodeid,edgeno,nextnode->start,nextnode->end,pos);
graphnode=nextnode;
}
}
else completed=true;
}
else if(minjunction == 1) { // found a junction end here
uint pos=ejunction[nje]->end;
while(nje<njunctions && ejunction[nje]->end==pos) { // read all junction ends at the current start
nje++;
}
if(graphnode->start<pos) { // last created node starts before the position of the new node I want to create
// add guide starts/ends first
if(processguide) {
while(nge<guideedge.Count() && guideedge[nge].val<=graphnode->start) nge++;
if(nge<guideedge.Count()) {
while(true) {
while(nge<guideedge.Count() && guideedge[nge].strand!=s) nge++;
if(nge>=guideedge.Count() || guideedge[nge].val>=pos-1) break;
uint start=guideedge[nge].val;
uint end=pos-1;
bool sourceguide=false;
if(guideedge[nge].val<guideedge[nge].endval) sourceguide=true;
nge++;
if(sourceguide) { if(guideedge[nge-1].endval>endbundle) continue;}
else if(guideedge[nge-1].endval<currentstart) continue;
while(nge<guideedge.Count() && guideedge[nge].strand!=s) nge++;
if(nge<guideedge.Count() && guideedge[nge].val<pos-1) end=guideedge[nge].val;
// I need to check there is no other trimming needed due to drops from longreads
if(longreads && (lstart.Count() || lend.Count())) graphnode=longtrim(s,g,refstart,start,nls,nle,dropcov,!sourceguide,lstart,lend,
graphnode,source,sink,futuretr,graphno,bpcov,bundlenode,bundle2graph,no2gnode,edgeno);
if(sourceguide) graphnode=source2guide(s,g,refstart,start,end,graphnode,source,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);
else graphnode=guide2sink(s,g,refstart,start,end,graphnode,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);
}
}
}
//if(trim && !processguide && !mergeMode) graphnode=trimnode(s,g,refstart,pos-1,graphnode,source,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);// do something to find intermediate nodes; alternatively, I could only do this for end nodes
else if(longreads && (lstart.Count() || lend.Count())) graphnode=longtrim(s,g,refstart,pos-1,nls,nle,dropcov,false,lstart,lend,
graphnode,source,sink,futuretr,graphno,bpcov,bundlenode,bundle2graph,no2gnode,edgeno);
if(trim && !longreads && !mergeMode) graphnode=trimnode_all(s,g,refstart,pos-1,graphnode,source,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);// do something to find intermediate nodes; alternatively, I could only do this for end nodes
graphnode->end=pos-1; // set end of current graphnode here
dropcov=false;
//fprintf(stderr,"create graph 3\n");
CGraphnode *nextnode = create_graphnode(s,g,pos,endbundle,graphno,bundlenode,bundle2graph,no2gnode);
graphno++;
graphnode->child.Add(nextnode->nodeid); // make nextnode a child of current graphnode
nextnode->parent.Add(graphnode->nodeid);// make graphnode a parent of nextnode
// COUNT EDGE HERE
edgeno++;
//fprintf(stderr,"5 Edge %d-%d, edgeno=%d\n",graphnode->nodeid,nextnode->nodeid,edgeno);
graphnode=nextnode;
}
//GStr spos((int)pos);
//GVec<int> *e=ends[spos.chars()]; // WHY DOESN'T THIS REPEAT THE SAME THING IN CASE THE START HASN'T BEEN ADJUSTED? because nje is bigger now than the ones that end at the currentstart
GVec<int> *e=ends[pos];
if(e) for(int i=0;i<e->Count();i++) {
CGraphnode *node=no2gnode[s][g][e->Get(i)];
node->child.Add(graphnode->nodeid); // this node is the child of previous node
graphnode->parent.Add(node->nodeid); // this node has as parent the previous node
// COUNT EDGE HERE
edgeno++;
//fprintf(stderr,"6 Edge %d-%d, edgeno=%d\n",node->nodeid,graphnode->nodeid,edgeno);
}
}
} while((nje<njunctions && (ejunction[nje]->end<=endbundle)) || (njs<njunctions && (junction[njs]->start<=endbundle)));
if(!completed) { // I did not finish node --> this will be an ending node
// add guide starts/ends first
if(processguide) {
while(nge<guideedge.Count() && guideedge[nge].val<=graphnode->start) nge++;
if(nge<guideedge.Count()) {
while(true) {
while(nge<guideedge.Count() && guideedge[nge].strand!=s) nge++;
if(nge>=guideedge.Count() || guideedge[nge].val>=endbundle) break;
uint start=guideedge[nge].val;
uint end=endbundle;
bool sourceguide=false;
if(guideedge[nge].val<guideedge[nge].endval) sourceguide=true;
nge++;
if(sourceguide) { if(guideedge[nge-1].endval>endbundle) continue;}
else if(guideedge[nge-1].endval<currentstart) continue;
while(nge<guideedge.Count() && guideedge[nge].strand!=s) nge++;
if(nge<guideedge.Count() && guideedge[nge].val<endbundle) end=guideedge[nge].val;
// I need to check there is no other trimming needed due to drops from longreads
if(longreads && (lstart.Count() || lend.Count())) graphnode=longtrim(s,g,refstart,start,nls,nle,dropcov,!sourceguide,lstart,lend,
graphnode,source,sink,futuretr,graphno,bpcov,bundlenode,bundle2graph,no2gnode,edgeno);
if(sourceguide) graphnode=source2guide(s,g,refstart,start,end,graphnode,source,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);
else graphnode=guide2sink(s,g,refstart,start,end,graphnode,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno);
}
}
}
// if(trim && !processguide && !mergeMode) graphnode=trimnode(s,g,refstart,endbundle,graphnode,source,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno); // do something to find intermediate nodes; alternatively, I could only do this for end nodes
else if(longreads && (lstart.Count() || lend.Count())) graphnode=longtrim(s,g,refstart,endbundle,nls,nle,dropcov,true,lstart,lend,
graphnode,source,sink,futuretr,graphno,bpcov,bundlenode,bundle2graph,no2gnode,edgeno);
if(trim && !longreads && !mergeMode) graphnode=trimnode_all(s,g,refstart,endbundle,graphnode,source,sink,bpcov,futuretr,graphno,bundlenode,bundle2graph,no2gnode,edgeno); // do something to find intermediate nodes; alternatively, I could only do this for end nodes
graphnode->end=endbundle;
// COUNT EDGE HERE (this is an edge to sink)
edgeno++;
//fprintf(stderr,"7 Edge to sink from %d, edgeno=%d\n",graphnode->nodeid,edgeno);
}
bundlenode=bundlenode->nextnode; // advance to next bundle
} // end while(bundlenode!=NULL)
//fprintf(stderr,"graphno=%d\n",graphno);
// add source/sink links for very high coverage drops
if(!mergeMode) for(int i=1;i<graphno;i++) {
float icov=0;
if(i>1 && no2gnode[s][g][i]->parent[0]) { // node i has parents, and does not come from source => might need to be linked to source
/*icov=(get_cov(1,no2gnode[s][g][i]->start-refstart,no2gnode[s][g][i]->end-refstart,bpcov)-
get_cov(2-2*s,no2gnode[s][g][i]->start-refstart,no2gnode[s][g][i]->end-refstart,bpcov))/no2gnode[s][g][i]->len();*/
icov=get_cov_sign(2*s,no2gnode[s][g][i]->start-refstart,no2gnode[s][g][i]->end-refstart,bpcov)/no2gnode[s][g][i]->len();
float parcov=0; // all parents' coverage
bool addsource=true;
for(int j=0;j<no2gnode[s][g][i]->parent.Count();j++) {
if(!no2gnode[s][g][i]->parent[j]) { // parent is source
addsource=false;break;
}
int p=no2gnode[s][g][i]->parent[j];
/*parcov+=(get_cov(1,no2gnode[s][g][p]->start-refstart,no2gnode[s][g][p]->end-refstart,bpcov)-
get_cov(2-2*s,no2gnode[s][g][p]->start-refstart,no2gnode[s][g][p]->end-refstart,bpcov))/no2gnode[s][g][p]->len();*/
parcov+=get_cov_sign(2*s,no2gnode[s][g][p]->start-refstart,no2gnode[s][g][p]->end-refstart,bpcov)/no2gnode[s][g][p]->len();
}
if(addsource && parcov<icov*ERROR_PERC*DROP) {
no2gnode[s][g][i]->parent.Insert(0,source->nodeid);
source->child.Add(i);
futuretr.cAdd(0.0);
float tmp=i;
futuretr.Add(tmp);
tmp=(icov-parcov)/DROP;
futuretr.Add(tmp);
//fprintf(stderr,"Add link to source from node %d with abundance %f\n",i,tmp);
edgeno++;
}
}
if(i<graphno-1) {
if(no2gnode[s][g][i]->child.Count()) { // might need to be linked to sink
bool addsink=true;
for(int j=0;j<sink->parent.Count();j++) {
if(sink->parent[j]==i) {
addsink=false;
break;
}
}
if(addsink) {
/*if(!icov) icov=(get_cov(1,no2gnode[s][g][i]->start-refstart,no2gnode[s][g][i]->end-refstart,bpcov)-
get_cov(2-2*s,no2gnode[s][g][i]->start-refstart,no2gnode[s][g][i]->end-refstart,bpcov))/no2gnode[s][g][i]->len();*/
if(!icov) icov=get_cov_sign(2*s,no2gnode[s][g][i]->start-refstart,no2gnode[s][g][i]->end-refstart,bpcov)/no2gnode[s][g][i]->len();
float chcov=0; // all children coverages
for(int j=0;j<no2gnode[s][g][i]->child.Count();j++) {
int c=no2gnode[s][g][i]->child[j];
/*chcov+=(get_cov(1,no2gnode[s][g][c]->start-refstart,no2gnode[s][g][c]->end-refstart,bpcov)-
get_cov(2-2*s,no2gnode[s][g][c]->start-refstart,no2gnode[s][g][c]->end-refstart,bpcov))/no2gnode[s][g][c]->len();*/
chcov+=get_cov_sign(2*s,no2gnode[s][g][c]->start-refstart,no2gnode[s][g][c]->end-refstart,bpcov)/no2gnode[s][g][c]->len();
}
if(chcov<icov*ERROR_PERC*DROP) {
sink->parent.Add(i); // prevnode is the parent of sink
float tmp=i;
futuretr.Add(tmp);
futuretr.cAdd(-1.0);
tmp=(icov-chcov)/DROP;
futuretr.Add(tmp);
edgeno++;
}
}
}
else edgeno++; // node has no children so it might get linked to sink in traverse_dfs function
}
}
// here I know graphno => I can see if it's too big
if(!mergeMode && graphno>allowed_nodes) { // TODO: define allowed_nodes as a default in stringtie.cpp that varies with the memory
graphno=prune_graph_nodes(graphno,s,g,bundle2graph,bnode.Count(),no2gnode,junction,edgeno,futuretr,sink);
}
sink->nodeid=graphno;
no2gnode[s][g].Add(sink);
graphno++;
if(mergeMode) { // I might have a bunch of sink's parents that are not linked to sink
for(int i=0;i<sink->parent.Count();i++) {
CGraphnode *node=no2gnode[s][g][sink->parent[i]];
node->child.Add(sink->nodeid);
}
}
//fprintf(stderr,"This graph has %d nodes and %d edges and starts at lastpos=%d\n",graphno,edgeno,graphno);
lastgpos=graphno; // nodes are from 0 to graphno-1, so the first "available" position in GBitVec is graphno
// now I can create the future transfrags because I know graphno
for(int i=0;i<futuretr.Count();i+=3) {
// add links between node and sink
int n1=int(futuretr[i]);
if(n1 >=0 ) {
int n2=int(futuretr[i+1]);
GBitVec trpat(graphno+edgeno);
trpat[n1]=1;
GVec<int> nodes;
if(n2<0) {
CGraphnode *node=no2gnode[s][g][n1];
int n3=n1+1;
if(n3<sink->nodeid) {
CGraphnode *prevnode=node;
CGraphnode *nextnode=no2gnode[s][g][n3]; // this should be okay
uint dist=nextnode->len()-1;
bool keeptr=true;
while(nextnode->start==prevnode->end+1 && dist<longintronanchor) {
for(int c=0;c<nextnode->child.Count();c++)
if(nextnode->child[c]==sink->nodeid) {
// do not continue with the futuretr
keeptr=false;
break;
}
n3++;
if(n3==sink->nodeid) {
// no link to sink found -> can continue with futuretr
break;
}
prevnode=nextnode;
nextnode=no2gnode[s][g][n3];
dist+=nextnode->len();
}
if(!keeptr) continue; // found link to sink; no need to keep futuretr
}
node->child.Add(sink->nodeid);
// add node to sink transfrag
trpat[graphno-1]=1;
int key=edge(n1,graphno-1,graphno);
int *pos=gpos[s][g][key];
if(pos!=NULL) trpat[*pos]=1;
else {
gpos[s][g].Add(key,lastgpos);
trpat[lastgpos]=1;
lastgpos++;
}
nodes.Add(n1);
nodes.Add(sink->nodeid);
}
else {
trpat[n2]=1;
int key=edge(n1,n2,graphno);
int *pos=gpos[s][g][key];
if(pos!=NULL) trpat[*pos]=1;
else {
gpos[s][g].Add(key,lastgpos);
trpat[lastgpos]=1;
lastgpos++;
}
nodes.cAdd(n1);
nodes.Add(n2);
}
CTransfrag *tr=new CTransfrag(nodes,trpat,futuretr[i+2]);
/*
{ // DEBUG ONLY
fprintf(stderr,"Add future transfrag[%d][%d]= %d with %d nodes n1=%d n2=%d graphno=%d, abundance=%f and pattern",s,g,transfrag[s][g].Count(),tr->nodes.Count(),n1,n2,graphno,futuretr[i+2]);
//printBitVec(trpat);
fprintf(stderr,"\n");
}
*/
/*if(mixedMode) {
tr->abundance*=2;
}*/
transfrag[s][g].Add(tr);
if(mixedMode) {
CTransfrag *longtr=new CTransfrag(nodes,trpat,futuretr[i+2]);
longtr->longread=true;
transfrag[s][g].Add(longtr);
}
else
if(longreads)// || mixedMode)
transfrag[s][g].Last()->longread=true;
}
}
// finished reading bundle -> now create the parents' and children's patterns
GVec<bool> visit;
visit.Resize(graphno);
GBitVec parents(graphno+edgeno);
//fprintf(stderr,"traverse graph[%d][%d] now with %d nodes, %d edges and lastgpos=%d....\n",s,g,graphno,edgeno,lastgpos);//edgeno=0;
traverse_dfs(s,g,source,sink,parents,graphno,visit,no2gnode,transfrag,edgeno,gpos,lastgpos);
//fprintf(stderr,"done traversing with edgeno=%d lastgpos=%d\n",edgeno,lastgpos);
/*
{ //DEBUG ONLY
fprintf(stderr,"after traverse:\n");
for(int i=0;i<graphno;i++) {
fprintf(stderr,"Node %d with parents:",i);
for(int p=0;p<no2gnode[s][g][i]->parent.Count();p++) fprintf(stderr," %d",no2gnode[s][g][i]->parent[p]);
fprintf(stderr," and children:");
for(int c=0;c<no2gnode[s][g][i]->child.Count();c++) fprintf(stderr," %d",no2gnode[s][g][i]->child[c]);
fprintf(stderr,"\n");
}
}
*/
// delete variables created here, like e.g. ends; do I need to delete the GVec<int> elements created too?
ends.Clear();
return(graphno);
}
void get_read_pattern(int s, float readcov,GVec<int> &rgno, float rprop,GVec<int> *rnode,
GList<CReadAln>& readlist,int n,GVec<int> *readgroup,GVec<int>& merge,GVec<int> *group2bundle,
GVec<CGraphinfo> **bundle2graph,GPVec<CGraphnode> **no2gnode) {
int lastgnode=-1;
int lastngraph=-1;
int ncoord=readlist[n]->segs.Count();
int k=0; // need to keep track of coordinates already added to coverages of graphnodes
int kmer=KMER-1; //f1
GIntHash<bool> hashnode;
for(int i=0;i<readgroup[n].Count();i++) { // how can a read be associated to multiple groups? ---> If it is spliced
int gr=readgroup[n][i];
while(merge[gr]!=gr) gr=merge[gr];
readgroup[n][i]=gr;
int bnode=group2bundle[2*s][gr]; // group was associated to bundle
if(bnode>-1 && bundle2graph[s][bnode].Count()) { // group has a bundle node associated with it and bundle was processed
if(!hashnode[bnode]) {
hashnode.Add(bnode,true);
int nbnode=bundle2graph[s][bnode].Count(); // number of nodes in bundle
int j=0;
//fprintf(stderr,"bundle2graph[%d] for read %d:",bnode,n);
while(j<nbnode && k<ncoord) {
int ngraph=bundle2graph[s][bnode][j].ngraph;
int gnode=bundle2graph[s][bnode][j].nodeno;
CGraphnode *node=no2gnode[s][ngraph].Get(gnode);
// compute graphnode coverage by read here (assuming they come in order on the genomic line)
bool intersect=false;
while(k<ncoord) { // found how much of readlist[n] intersects node represented by bnode; here I assume that read is always included in bundle2graph
if(readlist[n]->segs[k].end<node->start) k++;
else {
int bp = readlist[n]->segs[k].overlapLen(node);
if(bp) {
intersect=true;
if(!readlist[n]->unitig)
node->cov+=rprop*bp*readcov;
if(readlist[n]->segs[k].end<=node->end) k++;
else break;
}
else break;
}
}
if(intersect) { // read intersects gnode
int g=-1; // position of graph in list
if(rgno.Count()) {
if(ngraph!=rgno.Last()) {
for(int r=0;r<rgno.Count()-1;r++) { // count should be small
if(ngraph==rgno[r]) {
g=r;
break;
}
}
}
else g=rgno.Count()-1;
}
if(g<0) { // add ngraph to list of graphs if not seen before
rgno.Add(ngraph);
g=rgno.Count()-1;
}
if(lastngraph!=ngraph || lastgnode!=gnode) { // this is a new graph, or a new gnode
bool trimu=false;
if(readlist[n]->unitig) { //f1
if(rnode[g].Count()==1) { // deal with first node trimming here
if(no2gnode[s][ngraph][gnode]->parent.Count()>1) { // only if this node has more than one parent I might need to trim it
if((int)(no2gnode[s][ngraph][rnode[g][0]]->end - readlist[n]->start) < kmer) { // I have to trim this part of the super-read because it might be wrong
rnode[g].Pop();
}
}
}
if(rnode[g].Count() && no2gnode[s][ngraph][rnode[g].Last()]->child.Count()>1) {
if((int)(readlist[n]->end-no2gnode[s][ngraph][gnode]->start) < kmer) { // super-read extends only a tiny bit into the node -> might be wrong
trimu=true;
}
}
}
if(!trimu) rnode[g].Add(gnode);
}
lastgnode=gnode;
lastngraph=ngraph;
} // end if(intersect)
j++;
} // end while(j<nbnode && k<ncoord)
} // end hashnode
} // end if(bnode>-1 && bundle2graph[s][bnode].Count())
} // end for
}
void get_read_pattern(float readcov,GBitVec& pattern0,GBitVec& pattern1,int *rgno, float *rprop,GVec<int> *rnode,
GList<CReadAln>& readlist,int n,GVec<int> *readgroup,GVec<int>& merge,GVec<int> *group2bundle,
GVec<CGraphinfo> **bundle2graph,GVec<int> *graphno,GVec<int> *edgeno,GIntHash<int> **gpos,
GPVec<CGraphnode> **no2gnode) {
int lastgnode[2]={-1,-1}; // lastgnode[0] is for - strand; [1] is for + strand -> I need these in order to add the edges to the read pattern; check this: if it's not correct than storage was wrong!
int ncoord=readlist[n]->segs.Count();
int k[2]={0,0}; // need to keep track of coordinates already added to coverages of graphnodes
bool valid[2]={true,true};
for(int s=0;s<2;s++) if(!rprop[s]) valid[s]=false;
for(int i=0;i<readgroup[n].Count();i++) // how can a read be associated to multiple groups? ---> If it is spliced
if(valid[0] || valid[1]) { // there are still stranded bundles associated with the read
int gr=readgroup[n][i];
while(merge[gr]!=gr) gr=merge[gr];
for(int s=0;s<2;s++)
if(valid[s]) {
int bnode=group2bundle[2*s][gr]; // group was associated to bundle
if(bnode>-1 && bundle2graph[s][bnode].Count()) { // group $id has a bundle node associated with it and bundle was processed
int nbnode=bundle2graph[s][bnode].Count();
int j=0;
while(j<nbnode && k[s]<ncoord) {
int ngraph=bundle2graph[s][bnode][j].ngraph;
int gnode=bundle2graph[s][bnode][j].nodeno;
CGraphnode *node=no2gnode[s][ngraph].Get(gnode);
// compute graphnode coverage by read here (assuming they come in order on the genomic line)
bool intersect=false;
while(k[s]<ncoord) {
int bp = readlist[n]->segs[k[s]].overlapLen(node);
if(bp) {
intersect=true;
if(!readlist[n]->unitig)
node->cov+=rprop[s]*bp*readcov;
if(readlist[n]->segs[k[s]].end<=node->end) k[s]++;
else break;
}
else break;
}
if(intersect) { // read intersects gnode
if(lastgnode[s]>-1 && gnode!=lastgnode[s]) { // this is not the first time I see a gnode for the read
// need to update the edge pattern
int min=lastgnode[s];
int max=gnode;
if(min>gnode) {
max=min;
min=gnode;
}
int *pos=gpos[s][ngraph][edge(min,max,graphno[s][ngraph])];
if(pos!=NULL) {
if(s) pattern1[*pos]=1; // added edge from previous gnode to current one for the read
else pattern0[*pos]=1; // added edge from previous gnode to current one for the read
}
//else GError("s=%d g=%d edge=%d Found read %d(%d-%d) with edge between nodes %d(%d-%d)-%d(%d-%d) that is not in the graph with %d nodes and %d edges!\n",s,ngraph,edge(min,max,graphno[s][ngraph]),n,readlist[n]->start,readlist[n]->end,min,no2gnode[s][ngraph].Get(min)->start,no2gnode[s][ngraph].Get(min)->end,max,no2gnode[s][ngraph].Get(max)->start,no2gnode[s][ngraph].Get(max)->end,graphno[s][ngraph],edgeno[s][ngraph]);
rnode[s].Add(gnode);
}
else { // first time considering read
rgno[s]=ngraph;
rnode[s].Add(gnode);
}
lastgnode[s]=gnode;
if(s) {
pattern1.resize(graphno[s][ngraph]+edgeno[s][ngraph]);
pattern1[gnode]=1; // here I could remember kids as well to speed things up
}
else {
pattern0.resize(graphno[s][ngraph]+edgeno[s][ngraph]);
pattern0[gnode]=1; // here I could remember kids as well to speed things up
}
} // end if(intersect
j++;
} // end while(j<nbnode && k<ncoord)
} // end if(bnode>-1 && bundle2graph[s][bnode].Count())
else { // I don't need to process this strand for the read anymore because bundle was not processed or read doesn't belong to that stranded bundle
valid[s]=false;
continue;
}
} // endif(valid[s])
} // end if(valid[0] || valid[2])
}
void free_treepat(CTreePat *t){
if(t) {
for(int i=0;i<t->childno;i++) free_treepat(t->nextpat[i]);
GFREE(t->nextpat);
delete t;
}
}
CTreePat *construct_treepat(int gno, GIntHash<int>& gpos,GPVec<CTransfrag>& transfrag) {
// create root CTreePat first
CTreePat *root=new CTreePat(0,gno-1); // if links from source to nodes are desired source==1 and all nodes are treated as +1
// now construct all child CTreePat's
//fprintf(stderr,"There are %d transfrags\n",transfrag.Count());
for(int t=0;t<transfrag.Count();t++)
if(transfrag[t]->nodes[0]){ // don't include transfrags from source -> not needed
CTreePat *tree=root;
int m=0; // previous node in pattern that was set in pattern
for(int n=1;n<gno;n++){
if(transfrag[t]->pattern[n]) {
CTreePat *child;
if(m) { // there is a node m that was seen before
int *pos=gpos[edge(m,n,gno)];
if(pos && transfrag[t]->pattern[*pos]) // there is an edge between m and n
child=tree->settree(gno-1-m+n-m-1,n,2*(gno-n-1));
else child=tree->settree(n-m-1,n,2*(gno-n-1));
}
else // this is the root tree
child=tree->settree(n-1,n,2*(gno-n-1));
tree=child;
m=n;
}
}
tree->tr=transfrag[t];
}
return(root);
}
/* if I ever want to use the source
CTreePat *construct_treepat(int gno, GIntHash<int>& gpos,GPVec<CTransfrag>& transfrag) {
int source=0; // if I ever need source set this to 1
gno+=source;
// create root CTreePat first
CTreePat *root=new CTreePat(0,gno-1); // if links from source to nodes are desired source==1 and all nodes are treated as +1
// now construct all child CTreePat's
for(int t=0;t<transfrag.Count();t++)
if(transfrag[t]->nodes[0]+source){ // don't include transfrags from source -> not needed
CTreePat *tree=root;
int m=0; // previous node in pattern that was set in pattern
for(int n=1;n<gno;n++){
if(transfrag[t]->pattern[n-source]) {
CTreePat *child;
if(m) { // there is a node m that was seen before
int *pos=gpos[edge(m-source,n-source,gno-source)];
if(pos && transfrag[t]->pattern[*pos]) // there is an edge between m and n
child=tree->settree(gno-1-m+n-m-1,n,2*(gno-n-1));
else child=tree->settree(n-m-1,n,2*(gno-n-1));
}
else // this is the root tree
child=tree->settree(n-1,n,2*(gno-n-1));
tree=child;
m=n;
}
}
tree->tr=transfrag[t];
}
return(root);
}*/
void print_pattern(CTreePat *tree,GStr& pattern,int gno) {
if(!tree) return;
pattern+=tree->nodeno;
if(tree->tr) {
fprintf(stderr,"pat: %s %f\n",pattern.chars(),tree->tr->abundance);
}
for(int i=0;i<tree->childno;i++)
if(tree->nextpat[i]) {
GStr tmppat(pattern.chars());
if(i<gno-1-tree->nodeno) tmppat+=".";
else tmppat+="-";
print_pattern(tree->nextpat[i],tmppat,gno);
}
}
CTransfrag *findtrf_in_treepat(int gno,GIntHash<int>& gpos,GVec<int>& node,GBitVec& pattern,CTreePat *tr2no) { // doesn't work for patterns including source node
if(!tr2no) return(NULL);
CTreePat *tree=tr2no;
for(int n=0;n<node.Count();n++) {
if(n) { // not the first node in pattern
int *pos=gpos[edge(node[n-1],node[n],gno)];
if(pos && pattern[*pos]) { // there is an edge between node[n-1] and node[n]
tree=tree->nextpat[gno-1-node[n-1]+node[n]-node[n-1]-1];
}
else tree=tree->nextpat[node[n]-node[n-1]-1];
}
else tree=tree->nextpat[node[n]-1];
if(!tree) return(NULL);
}
return(tree->tr);
}
/* if I want to use the source
CTransfrag *findtrf_in_treepat(int gno,GIntHash<int>& gpos,GVec<int>& node,GBitVec& pattern,CTreePat *tr2no) { // doesn't work for patterns including source node
int source=0; // if I ever need source, set this to 1
gno+=source;
if(!tr2no) return(NULL);
CTreePat *tree=tr2no;
for(int n=0;n<node.Count();n++) {
if(n) { // not the first node in pattern
int *pos=gpos[edge(node[n-1],node[n],gno-source)];
if(pos && pattern[*pos]) // there is an edge between node[n-1] and node[n]
tree=tree->nextpat[gno-1-node[n-1]-source+node[n]-node[n-1]-1];
else tree=tree->nextpat[node[n]-node[n-1]-1];
}
else tree=tree->nextpat[node[n]+source-1];
if(!tree) return(NULL);
}
return(tree->tr);
}*/
CTransfrag *update_abundance(int s,int g,int gno,GIntHash<int>&gpos,GBitVec& pattern,float abundance,GVec<int>& node,
GPVec<CTransfrag> **transfrag,CTreePat ***tr2no, GPVec<CGraphnode>& no2gnode,uint rstart,uint rend,bool is_sr=false,bool is_lr=false){
/*
{ // DEBUG ONLY
fprintf(stderr,"Update transfrag[%d][%d] longread=%d:",s,g,is_lr);
for(int i=0;i<node.Count();i++) fprintf(stderr," %d",node[i]);
fprintf(stderr," with abundance=%f in graph[%d][%d]\n",abundance,s,g);
}
*/
if(is_lr) { // see if I need to adjust nodes in pattern
if(node.Count()>1) { // correct longreads that extend inside introns or past nodes that link back to source or sink
bool is_source=(rstart>=no2gnode[node[0]]->start); // read start could be inside of the node (node could be extended due to other reads)
bool is_sink=(rend<=no2gnode[node.Last()]->end); // read end could be inside of the node (node could be extended due to other reads
if(no2gnode[node[0]]->hardstart) is_source=false; // do not do any trimming if this is an ending node
if(no2gnode[node.Last()]->hardend) is_sink=false; // do not do any trimming if this is an ending node
if(is_sink) { // check last node
int i=node.Count()-1;
while(i>0 && no2gnode[node[i-1]]->end+1==no2gnode[node[i]]->start) {
uint dist=rend-no2gnode[node[i-1]]->end;
if(dist<longintronanchor) { // I can potentially eliminate node[i] from transfrag due to proximity
if(no2gnode[node[i-1]]->hardend || no2gnode[node[i-1]]->cov*DROP*no2gnode[node[i]]->len()>no2gnode[node[i]]->cov*no2gnode[node[i-1]]->len()) { // there is a significant drop
int j=no2gnode[node[i-1]]->child.Count()-1;
bool trim=false;
while(j>=0) {
if(no2gnode[node[i-1]]->child[j]!=node[i]) { // there is a different child and a significant drop within short distance
// adjust pattern
int k=i;
while(k<node.Count()) {
pattern[node[k]]=0;
int *pos=gpos[edge(node[k-1],node[k],gno)];
if(pos) pattern[*pos]=0;
k++;
}
node.setCount(i); // adust number of nodes
trim=true;
break;
}
j--;
}
if(trim) break;
}
}
else if(dist<CHI_WIN) { // check for sink connection
if(no2gnode[node[i-1]]->hardend || no2gnode[node[i-1]]->cov*DROP*no2gnode[node[i]]->len()>no2gnode[node[i]]->cov*no2gnode[node[i-1]]->len()) { // there is a significant drop
int j=no2gnode[node[i-1]]->child.Count()-1;
bool trim=false;
while(j>=0) {
if(no2gnode[node[i-1]]->child[j]==gno-1) { // node[i-1] can connect to source
// adjust pattern
int k=i;
while(k<node.Count()) {
pattern[node[k]]=0;
int *pos=gpos[edge(node[k-1],node[k],gno)];
if(pos) pattern[*pos]=0;
k++;
}
node.setCount(i); // adust number of nodes
trim=true;
break;
}
j--;
}
if(trim) break;
}
}
else break;
i--;
}
}
if(is_source) { // check first node
int i=0;
while(i+1<node.Count() && no2gnode[node[i]]->end+1==no2gnode[node[i+1]]->start) {
uint dist=no2gnode[node[i+1]]->start-rstart;
if(dist<longintronanchor) { // I can potentially eliminate node[i] from transfrag due to proximity
if(no2gnode[node[i+1]]->hardstart || no2gnode[node[i+1]]->cov*DROP*no2gnode[node[i]]->len()>no2gnode[node[i]]->cov*no2gnode[node[i+1]]->len()) { // there is a significant drop
int j=0;
bool trim=false;
while(j<no2gnode[node[i+1]]->parent.Count()) {
if(no2gnode[node[i+1]]->parent[j]!=node[i]) { // there is a different child and a significant drop within short distance
// adjust pattern
int k=i;
while(k>=0) {
pattern[node[k]]=0;
int *pos=gpos[edge(node[k],node[k+1],gno)];
if(pos) pattern[*pos]=0;
k--;
}
node.Shift(i+1); // delete first i+1 nodes in transfrag
trim=true;
break;
}
j++;
}
if(trim) break;
}
}
else if(dist<CHI_WIN) { // check for sink connection
if(no2gnode[node[i+1]]->hardstart || no2gnode[node[i+1]]->cov*DROP*no2gnode[node[i]]->len()>no2gnode[node[i]]->cov*no2gnode[node[i+1]]->len()) { // there is a significant drop
int j=0;
bool trim=false;
while(j<no2gnode[node[i+1]]->parent.Count()) {
if(!no2gnode[node[i+1]]->parent[j]) { // there is a link to source from node[i+1]
// adjust pattern
int k=i;
while(k>=0) {
pattern[node[k]]=0;
int *pos=gpos[edge(node[k],node[k+1],gno)];
if(pos) pattern[*pos]=0;
k--;
}
node.Shift(i+1); // delete first i+1 nodes in transfrag
trim=true;
break;
}
j++;
}
if(trim) break;
}
}
else break;
i++;
}
}
}
}
else if(!mergeMode && node.Count()==1) return(NULL); // do the one node transfrag make any difference? CHECK IF YOU NEED TO KEEP THIS ONE
CTransfrag *t=findtrf_in_treepat(gno,gpos,node,pattern,tr2no[s][g]);
if(!t) { // t is NULL
t=new CTransfrag(node,pattern,0);
/*
{ // DEBUG ONLY
fprintf(stderr,"Add update transfrag[%d][%d]=%d and pattern",s,g,transfrag[s][g].Count());
fprintf(stderr," (check nodes:");
for(int i=0;i<node.Count();i++) fprintf(stderr," %d",node[i]);
fprintf(stderr,")");
//printBitVec(pattern);
fprintf(stderr,"\n");
}
*/
transfrag[s][g].Add(t);
// node.Sort() : nodes should be sorted; if they are not then I should update to sort here
CTreePat *tree=tr2no[s][g];
for(int n=0;n<node.Count();n++) {
CTreePat *child;
if(n) { // not the first node in pattern
int *pos=gpos[edge(node[n-1],node[n],gno)];
if(pos && pattern[*pos]) // there is an edge between node[n-1] and node[n]
child=tree->settree(gno-1-node[n-1]+node[n]-node[n-1]-1,node[n],2*(gno-node[n]-1));
else child=tree->settree(node[n]-node[n-1]-1,node[n],2*(gno-node[n]-1));
}
else child=tree->settree(node[n]-1,node[n],2*(gno-node[n]-1));
tree=child;
}
tree->tr=t;
}
//else if(!is_lr && t->longread) t->longread=false;
if(is_lr) t->longread=true;
else {
//fprintf(stderr,"Set short read\n");
t->shortread=true;
}
if(is_sr) t->srabund+=abundance;
else t->abundance+=abundance;
if(no2gnode[node[0]]->start<=rstart) if(!t->longstart || rstart<t->longstart) t->longstart=rstart; // value of longstart inside node; the other extensions could come from spliced nodes
if(no2gnode[node.Last()]->end>=rend) if(!t->longend|| rend>t->longend) t->longend=rend; // value of longend inside node; the other extensions could come from spliced nodes
return(t);
}
void get_fragment_pattern(GList<CReadAln>& readlist,int n, int np,float readcov,GVec<int> *readgroup,GVec<int>& merge, GVec<int> *group2bundle,
GVec<CGraphinfo> **bundle2graph,GVec<int> *graphno,GVec<int> *edgeno, GIntHash<int> **gpos,GPVec<CGraphnode> **no2gnode,
GPVec<CTransfrag> **transfrag,CTreePat ***tr2no,GPVec<CGroup> &group) {
/*fprintf(stderr,"get fragment for read[%d]:%d-%d-%d-%d-%f with pair[%d] and longread=%d and exons: ",n,readlist[n]->start,readlist[n]->end,int(readlist[n]->strand),readlist[n]->nh,readlist[n]->read_count,np,readlist[n]->longread);
for(int i=0;i<readlist[n]->segs.Count();i++) fprintf(stderr," %d-%d",readlist[n]->segs[i].start,readlist[n]->segs[i].end);
if(np>-1) for(int i=0;i<readlist[np]->segs.Count();i++) fprintf(stderr," %d-%d",readlist[np]->segs[i].start,readlist[np]->segs[i].end);
fprintf(stderr,"\n");*/
uint rstart=readlist[n]->start; // this only works for unpaired long reads -> I will have to take into account the pair if I want to do it for all reads
uint rend=readlist[n]->end;
if(np>-1 && readlist[np]->end>rend) rend=readlist[np]->end;
float rprop[2]={0,0}; // by default read does not belong to any strand
// compute proportions of unstranded read associated to strands
if(readlist[n]->nh && !readlist[n]->strand && np>-1 && readlist[np]->nh && !readlist[np]->strand) { // both reads are unstranded
int ngroup=0; // due to errors read might not belong to any groups
for(int i=0;i<readgroup[n].Count();i++) {
ngroup++;
int gr=readgroup[n][i]; // read is unstranded => it should belong to one group only -> not necessarily see above
while(merge[gr]!=gr) gr=merge[gr];
rprop[0]+=group[gr]->neg_prop;
}
for(int i=0;i<readgroup[np].Count();i++) {
ngroup++;
int gr=readgroup[np][i]; // read is unstranded => it should belong to one group only
while(merge[gr]!=gr) gr=merge[gr];
rprop[0]+=group[gr]->neg_prop;
}
if(ngroup) {
rprop[0]/=ngroup;
rprop[1]=1-rprop[0];
}
}
else {
if(readlist[n]->nh) {
if(!readlist[n]->strand) { // the paired read is not present otherwise it would have the same strand from add_read_to_group
int ngroup=0; // due to errors read might not belong to any groups
for(int i=0;i<readgroup[n].Count();i++) {
ngroup++;
int gr=readgroup[n][i]; // read is unstranded => it should belong to one group only -> not necessarily see above
while(merge[gr]!=gr) gr=merge[gr];
rprop[0]+=group[gr]->neg_prop;
}
if(ngroup) {
rprop[0]/=ngroup;
rprop[1]=1-rprop[0];
}
}
else {
if(readlist[n]->strand==-1) rprop[0]=1;
else rprop[1]=1;
}
}
else if(np>-1 && readlist[np]->nh) { // readlist[n] is deleted
if(!readlist[np]->strand) { // the paired read is not present otherwise it would have the same strand from add_read_to_group
int ngroup=0; // due to errors read might not belong to any groups
for(int i=0;i<readgroup[np].Count();i++) {
ngroup++;
int gr=readgroup[np][i]; // read is unstranded => it should belong to one group only -> not necessarily see above
while(merge[gr]!=gr) gr=merge[gr];
rprop[0]+=group[gr]->neg_prop;
}
if(ngroup) {
rprop[0]/=ngroup;
rprop[1]=1-rprop[0];
}
}
else {
if(readlist[np]->strand==-1) rprop[0]=1;
else rprop[1]=1;
}
}
}
for(int s=0;s<2;s++) if(rprop[s]){
GVec<int> rgno;
GVec<int> *rnode=new GVec<int>[readgroup[n].Count()];
if(readlist[n]->nh)
get_read_pattern(s, readcov,rgno,rprop[s],rnode,readlist,n,readgroup,merge,group2bundle,bundle2graph,no2gnode);
GVec<int> pgno;
GVec<int> *pnode=NULL;
// get pair pattern if pair exists and it hasn't been deleted
if(np>-1 && readlist[np]->nh) {
pnode=new GVec<int>[readgroup[n].Count()];
get_read_pattern(s,readcov,pgno,rprop[s],pnode,readlist,np,readgroup,merge,group2bundle,bundle2graph,no2gnode);
}
GBitVec rpat;
GBitVec ppat;
int usedp=0;
for(int r=0;r<rgno.Count();r++) {
// set read pattern
rpat.clear();
rpat.resize(graphno[s][rgno[r]]+edgeno[s][rgno[r]]);
int i=0;
int clear_rnode=0;
for(int j=0;j<rnode[r].Count();j++) {
rpat[rnode[r][j]]=1;
if(j) { // add edge pattern
if(no2gnode[s][rgno[r]][rnode[r][j]]->start-1==no2gnode[s][rgno[r]][rnode[r][j-1]]->end) { // continuous node
bool cont=true;
if(readlist[n]->unitig) { // see if node j-1 has sink as child, or node j has source as parent -> this means trimming was involved
CGraphnode *jnode=no2gnode[s][rgno[r]][rnode[r][j]];
for(int p=0;p<jnode->parent.Count();p++) {
if(!jnode->parent[p]) { cont=false; break;} // found source among parents
}
if(cont) {
jnode=no2gnode[s][rgno[r]][rnode[r][j-1]];
for(int c=0;c<jnode->child.Count();c++) {
if(jnode->child[c]==graphno[s][rgno[r]]-1) { cont=false; break;} // found sink among children
}
}
if(!cont) { // trimming was involved
rpat[rnode[r][j]]=0;
GVec<int> node;
for(int o=clear_rnode;o<j;o++) {
node.Add(rnode[r][o]);
}
update_abundance(s,rgno[r],graphno[s][rgno[r]],gpos[s][rgno[r]],rpat,rprop[s]*readcov,node,transfrag,tr2no,
no2gnode[s][rgno[r]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
rpat.reset();
rpat[rnode[r][j]]=1; // restart the pattern
clear_rnode=j;
}
}
if(cont) {
int *pos=gpos[s][rgno[r]][edge(rnode[r][j-1],rnode[r][j],graphno[s][rgno[r]])];
if(pos!=NULL) rpat[*pos]=1;
}
}
else { // non-continuous node
while(i<readlist[n]->juncs.Count() && readlist[n]->juncs[i]->end<no2gnode[s][rgno[r]][rnode[r][j]]->start) i++; // end of junction should be after start of node
if(i<readlist[n]->juncs.Count() && readlist[n]->juncs[i]->start<=no2gnode[s][rgno[r]][rnode[r][j-1]]->end) {
if(readlist[n]->juncs[i]->strand && readlist[n]->juncs[i]->start==no2gnode[s][rgno[r]][rnode[r][j-1]]->end &&
readlist[n]->juncs[i]->end==no2gnode[s][rgno[r]][rnode[r][j]]->start) { // valid junction
int *pos=gpos[s][rgno[r]][edge(rnode[r][j-1],rnode[r][j],graphno[s][rgno[r]])];
if(pos!=NULL) rpat[*pos]=1;
}
else { // update abundance for what I have so far
rpat[rnode[r][j]]=0;
GVec<int> node;
for(int o=clear_rnode;o<j;o++) {
node.Add(rnode[r][o]);
}
update_abundance(s,rgno[r],graphno[s][rgno[r]],gpos[s][rgno[r]],rpat,rprop[s]*readcov,node,transfrag,tr2no,
no2gnode[s][rgno[r]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
rpat.reset();
rpat[rnode[r][j]]=1; // restart the pattern
clear_rnode=j;
}
}
}
}
}
for(int j=0;j<clear_rnode;j++) rnode[r].Shift();
int p=0;
while(p<pgno.Count() && rgno[r]!=pgno[p]) p++;
if(p<pgno.Count()) { // I found a node that is within the same graph -> can only happen if pair read is present;
usedp++;
// set pair pattern
ppat.clear();
ppat.resize(graphno[s][rgno[r]]+edgeno[s][rgno[r]]);
i=0;
for(int j=0;j<pnode[p].Count();j++) {
ppat[pnode[p][j]]=1;
if(j) { // add edge pattern
if(no2gnode[s][rgno[r]][pnode[p][j]]->start-1==no2gnode[s][rgno[r]][pnode[p][j-1]]->end) { // continuous node
int *pos=gpos[s][rgno[r]][edge(pnode[p][j-1],pnode[p][j],graphno[s][rgno[r]])];
if(pos!=NULL) ppat[*pos]=1;
}
else { // non-continuous node
while(i<readlist[np]->juncs.Count() && readlist[np]->juncs[i]->start<no2gnode[s][rgno[r]][pnode[p][j-1]]->end) i++;
if(i<readlist[np]->juncs.Count() && readlist[np]->juncs[i]->strand && readlist[np]->juncs[i]->start==no2gnode[s][rgno[r]][pnode[p][j-1]]->end &&
readlist[np]->juncs[i]->end==no2gnode[s][rgno[r]][pnode[p][j]]->start) {
int *pos=gpos[s][rgno[r]][edge(pnode[p][j-1],pnode[p][j],graphno[s][rgno[r]])];
if(pos!=NULL) ppat[*pos]=1;
}
}
}
}
// check if there is a conflict of patterns
CGraphnode *gnode=no2gnode[s][rgno[r]][pnode[p][0]];
GBitVec conflictpattn=gnode->parentpat;
conflictpattn[pnode[p][0]]=1;
if((conflictpattn & rpat)==rpat) { // there isn't a conflict -> pair parents should contain read pattern
i=0;
if(pnode[p][0]==rnode[r].Last()) // read and pair share a node
i++;
while(i<pnode[p].Count()) { rnode[r].Add(pnode[p][i]);i++;}
rpat=rpat|ppat;
update_abundance(s,rgno[r],graphno[s][rgno[r]],gpos[s][rgno[r]],rpat,rprop[s]*readcov,rnode[r],transfrag,tr2no,
no2gnode[s][rgno[r]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
}
else { // update both patterns separately
update_abundance(s,rgno[r],graphno[s][rgno[r]],gpos[s][rgno[r]],rpat,rprop[s]*readcov,rnode[r],transfrag,tr2no,
no2gnode[s][rgno[r]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
update_abundance(s,pgno[p],graphno[s][pgno[p]],gpos[s][pgno[p]],ppat,rprop[s]*readcov,pnode[p],transfrag,tr2no,
no2gnode[s][pgno[p]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
}
pgno[p]=-1;
}
else { // pair has no valid pattern in this graph
update_abundance(s,rgno[r],graphno[s][rgno[r]],gpos[s][rgno[r]],rpat,rprop[s]*readcov,rnode[r],transfrag,tr2no,
no2gnode[s][rgno[r]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
}
}
if(usedp<pgno.Count()) for(int p=0;p<pgno.Count();p++)
if(pgno[p]>-1) {
// set pair pattern
ppat.clear();
ppat.resize(graphno[s][pgno[p]]+edgeno[s][pgno[p]]);
int i=0;
for(int j=0;j<pnode[p].Count();j++) {
ppat[pnode[p][j]]=1;
if(j) { // add edge pattern
if(no2gnode[s][pgno[p]][pnode[p][j]]->start-1==no2gnode[s][pgno[p]][pnode[p][j-1]]->end) { // continuous node
int *pos=gpos[s][pgno[p]][edge(pnode[p][j-1],pnode[p][j],graphno[s][pgno[p]])];
if(pos!=NULL) ppat[*pos]=1;
}
else { // non-continuous node
while(i<readlist[np]->juncs.Count() && readlist[np]->juncs[i]->start<no2gnode[s][pgno[p]][pnode[p][j-1]]->end) i++;
if(i<readlist[np]->juncs.Count() && readlist[np]->juncs[i]->strand && readlist[np]->juncs[i]->start==no2gnode[s][pgno[p]][pnode[p][j-1]]->end &&
readlist[np]->juncs[i]->end==no2gnode[s][pgno[p]][pnode[p][j]]->start) {
int *pos=gpos[s][pgno[p]][edge(pnode[p][j-1],pnode[p][j],graphno[s][pgno[p]])];
if(pos!=NULL) ppat[*pos]=1;
}
}
}
}
update_abundance(s,pgno[p],graphno[s][pgno[p]],gpos[s][pgno[p]],ppat,rprop[s]*readcov,pnode[p],transfrag,tr2no,
no2gnode[s][pgno[p]],rstart, rend,readlist[n]->unitig,readlist[n]->longread);
}
delete [] rnode;
if(pnode) delete [] pnode;
}
}
void get_read_to_transfrag(GList<CReadAln>& readlist,int n,GVec<int> *readgroup,GVec<int>& merge,GVec<int> *group2bundle,
GVec<CGraphinfo> **bundle2graph,GVec<int> *graphno,GVec<int> *edgeno,GIntHash<int> **gpos,GPVec<CGraphnode> **no2gnode,
GPVec<CTransfrag> **transfrag,GPVec<CMTransfrag> **mgt,CTreePat ***tr2no,GPVec<CGroup> &group) {
// compute proportions of read associated to strands
float rprop[2]={1,1};
if(!readlist[n]->strand) { // the paired read is not present otherwise it would have the same strand from add_read_to_group
int gr=readgroup[n][0]; // read is unstranded => it should belong to one group only
while(merge[gr]!=gr) gr=merge[gr];
rprop[0]=group[gr]->neg_prop;
rprop[1]=1-rprop[0];
}
else {
if(readlist[n]->strand==-1) rprop[1]=0;
else rprop[0]=0;
}
GBitVec rpat[2];
int rgno[2]={-1,-1};
GVec<int> rnode[2];
if(readlist[n]->nh) {
get_read_pattern(readlist[n]->read_count,rpat[0],rpat[1],rgno,rprop,rnode,readlist,n,readgroup,merge,group2bundle,bundle2graph,graphno,edgeno,gpos,no2gnode);
}
for(int s=0;s<2;s++)
if(rgno[s]>-1) { // read is valid (has pattern) on strand s
// update transfrag
CTransfrag *t=update_abundance(s,rgno[s],graphno[s][rgno[s]],gpos[s][rgno[s]],rpat[s],rprop[s]*readlist[n]->read_count,rnode[s],transfrag,tr2no,no2gnode[s][rgno[s]],readlist[n]->start,readlist[n]->end);
// if I want to inset source/sink maybe here would be the place
// mark transfrag as guide
if(readlist[n]->tinfo->g>-1) t->real=true;
// update MTransfrag
int i=0;
while(i<mgt[s][rgno[s]].Count()) {
if(mgt[s][rgno[s]][i]->transfrag==t) {
for(int x=0;x<readlist[n]->pair_idx.Count();x++) {
mgt[s][rgno[s]][i]->read.Add(readlist[n]->pair_idx[x]);
}
//mgt[s][rgno[s]][i]->read.Add(n);
mgt[s][rgno[s]][i]->len=readlist[n]->len;
break;
}
i++;
}
if(i==mgt[s][rgno[s]].Count()) { // MTransfrag not found
CMTransfrag *mt=new CMTransfrag(t);
for(int x=0;x<readlist[n]->pair_idx.Count();x++) {
mt->read.Add(readlist[n]->pair_idx[x]);
}
//mt->read.Add(n);
mt->len=readlist[n]->len;
mgt[s][rgno[s]].Add(mt);
}
}
}
void settrf_in_treepat(CTransfrag *t,int gno,GIntHash<int>& gpos,GVec<int>& node,GBitVec& pattern,CTreePat *tr2no) {
if(!tr2no) return;
CTreePat *tree=tr2no;
for(int n=0;n<node.Count();n++) {
if(n) { // not the first node in pattern
int *pos=gpos[edge(node[n-1],node[n],gno)];
if(pos && pattern[*pos]) // there is an edge between node[n-1] and node[n]
tree=tree->nextpat[gno-1-node[n-1]+node[n]-node[n-1]-1];
else tree=tree->nextpat[node[n]-node[n-1]-1];
}
else tree=tree->nextpat[node[n]-1];
if(!tree) return;
}
tree->tr=t;
}
bool eliminate_transfrags_under_thr(int gno,GIntHash<int>& gpos,GPVec<CTransfrag>& transfrag, CTreePat *tr2no,float threshold,GPVec<CTransfrag>& srfrag) {
bool longret=false;
//fprintf(stderr,"eliminate from %d transfrags\n",transfrag.Count());
for(int t=transfrag.Count()-1;t>=0;t--)
//if(transfrag[t]->srabund || (mixedMode && (transfrag[t]->longread || !transfrag[t]->nodes[0] || transfrag[t]->nodes.Last()==gno-1))) { // this is a super-read
if(transfrag[t]->srabund || (mixedMode && transfrag[t]->longread)) { // this is a super-read
srfrag.Add(transfrag[t]);
if(mixedMode) {
if(transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1) // proper longread transfrag
longret=true;
}
}
else if(!transfrag[t]->guide && transfrag[t]->abundance<threshold &&
transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()<gno-1) { // need to delete transfrag that doesn't come from source or ends at sink
settrf_in_treepat(NULL,gno,gpos,transfrag[t]->nodes,transfrag[t]->pattern,tr2no); // this should be eliminated if I want to store transcripts from 0 node
transfrag.Exchange(t,transfrag.Count()-1);
transfrag.Delete(transfrag.Count()-1);
}
while(transfrag.Count()>max_trf_number) {
threshold++;
for(int t=transfrag.Count()-1;t>=0;t--)
if(!transfrag[t]->guide && transfrag[t]->abundance<threshold &&
transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()<gno-1) { // need to delete transfrag that doesn't come from source
settrf_in_treepat(NULL,gno,gpos,transfrag[t]->nodes,transfrag[t]->pattern,tr2no); // this should be eliminated if I want to store transcripts from 0 node
transfrag.Exchange(t,transfrag.Count()-1);
transfrag.Delete(transfrag.Count()-1);
}
}
return(longret);
}
bool conflict(int &i,int node,GVec<int>& trnode,int n,GPVec<CGraphnode>& no2gnode,GBitVec& trpat,int gno, GIntHash<int>& gpos) {
while(i<n && node>trnode[i]) i++;
if(i<n && node==trnode[i]) return(false);
int node1=trnode[i-1];
if(i==n) { // transcript is at the end; $node > $node1
if(no2gnode[node1]->childpat[node]) // node is among children of node1 -> should be equivalent to testing that node1 is among parents of node
return(false);
return(true);
}
int node2=trnode[i]; // node1 < node < node2
if(no2gnode[node1]->childpat[node] && no2gnode[node]->childpat[node2]) {
int *pos=gpos[edge(node1,node2,gno)];
if(pos && trpat[*pos]) return(true);
else return(false);
}
return(true);
}
void binary_insert_link(int n2, float capacity,GVec<int>& link, GVec<float>& val, int first, int last) {
while(first<=last) {
int mid=(first + last) / 2; // compute mid point.
if(capacity>val[mid]) first=mid+1;
else if(capacity<val[mid]) last=mid-1;
else { // found a good position to insert
first=mid;
break;
}
}
int pos=first;
val.idxInsert(pos,capacity);
link.idxInsert(pos,n2);
}
// returns true if at list one node gets assigned the incomplete transfrag
bool binary_insert_trf_to_node(int t, GVec<int>& trf,int first,int last) {
while(first<=last) {
int mid=(first + last) / 2; // compute mid point.
if(t>trf[mid]) first=mid+1;
else if(t<trf[mid]) last=mid-1;
else return false; // transcript already inserted
}
int pos=first;
trf.idxInsert(pos,t);
return true;
}
bool assign_incomplete_trf_to_nodes(int t,int n1, int n2,GPVec<CGraphnode>& no2gnode){
// a better version of this function could take into account also the fragments inner length
bool assigned=false;
for(int i=n1+1;i<n2;i++) {
if(no2gnode[n1]->childpat[i] && no2gnode[i]->childpat[n2]) { // i is a child of n1, and n2 is a child of i
assigned = binary_insert_trf_to_node(t,no2gnode[i]->trf,0,no2gnode[i]->trf.Count()-1) or assigned;
}
}
/* this version was taking a very long time
for(int i=0;i<no2gnode[n1]->child.Count();i++) { // for all children of n1
int child=no2gnode[n1]->child[i];
if(child!=n2 && no2gnode[child]->childpat[n2]) { // n2 is child of n1's child
binary_insert_trf_to_node(t,no2gnode[child]->trf,0,no2gnode[child]->trf.Count()-1);
assign_incomplete_trf_to_nodes(t,child,n2,no2gnode);
}
}
*/
return assigned;
}
inline int comptbl_pos(int t1,int t2,int n){
return(t2+t1*(2*n-t1-1)/2);
}
// this function inspects if there are multiple ways between two nodes in the transfrag; finds the first node like this and distributes the abundance of the transfrag between the two nodes in proportion to the edges that leave the first node
bool trf_real(int t,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag, GIntHash<int> &gpos,int gno) {
int i=0; // index of the current node (the one I am looking at) in transfrag
int nt=transfrag[t]->nodes.Count()-1; // index of last node in transfrag
int n=transfrag[t]->nodes[i]; // start at first node in transfrag
float totalcov=0;
while(i<nt) {
if(n+1==transfrag[t]->nodes[i+1]) { // if next node in transfrag is adjacent -> there is only one way to continue on transfrag path
n=transfrag[t]->nodes[i+1];
i++;
}
else { // there might be multiple ways to reach next node from node
int *pos=gpos[edge(n,transfrag[t]->nodes[i+1],gno)];
if(pos && transfrag[t]->pattern[*pos]) { // if there is an edge between node and nextnode in transfrag -> I don't have discontinuity there
n=transfrag[t]->nodes[i+1];
i++;
}
else { // found a potential discontinuity in transfrag pattern --> try to see if there are different branches going on from here
CGraphnode *node=no2gnode[n];
int nextnode=transfrag[t]->nodes[i+1];
int ntrf=node->trf.Count(); // total number of transfrags in node
int np=0; // upper bound on number of paths I can find from node to nextnode
totalcov=0; // total abundance of transfrags going from node to children of node
// I check if there are different paths to reach nextnode from node
for(int j=0;j<node->child.Count();j++) {
if(node->child[j]>nextnode) break; // if child of node is after nextnode -> I don't care
if(node->child[j]==nextnode || no2gnode[node->child[j]]->childpat[nextnode]) { // I found a node on the path to nextnode
CPath p(n,node->child[j]);
int *pos=gpos[edge(n,node->child[j],gno)];
if(pos) for(int f=0;f<ntrf;f++) {
if(transfrag[node->trf[f]]->pattern[*pos]) { // this is a transfrag that goes through node and child; ATTENTION: it might not reach nextnode!! or be compatible with nextnode
p.abundance+=transfrag[node->trf[f]]->abundance;
totalcov+=transfrag[node->trf[f]]->abundance;
}
}
if(p.abundance) {
transfrag[t]->path.Add(p);
np++;
}
}
}
if(!totalcov || !np) // there is no way to continue
return true;
if(np==1) { // only one way to go forward
n=transfrag[t]->path[0].contnode;
if(n==nextnode) i++;
transfrag[t]->path.Clear();
}
else break; // break at first discontinue point in transfrag -> might be many other ways to continue but this functions doesn't care
}
}
}
if(i==nt) return true;
// this implementation only assumes one break in transfrag
for(int j=0;j<transfrag[t]->path.Count();j++) transfrag[t]->path[j].abundance/=totalcov;
return false;
}
float stitch_trf(CTransfrag *u,float available,int i_start, int i,GPVec<CTransfrag> &seltrfrag,GVec<int> *start,GVec<int> next) {
if(seltrfrag[i]->abundance<available) available=seltrfrag[i]->abundance;
int nl=seltrfrag[i]->nodes.Last();
if(nl==u->nodes.Last()) nl=u->nodes[0];
if(nl==seltrfrag[i_start]->nodes[0]) return(available);
int nf=seltrfrag[i]->nodes[0];
if(nf<seltrfrag[i_start]->nodes[0] && nl>seltrfrag[i_start]->nodes[0]) return(0);
float maxabund=0;
for(int j=0;j<start[nl].Count();j++) {
if(start[nl][j]>i_start && seltrfrag[start[nl][j]]->abundance) maxabund=stitch_trf(u,available,i_start,start[nl][j],seltrfrag,start,next);
if(maxabund) {
next.Add(start[nl][j]);
return(maxabund);
}
}
return(0);
}
void process_srfrag(CTransfrag *u,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,int gno, GIntHash<int> &gpos) { // v7
//fprintf(stderr,"Process super-read with abundance=%f and srabundance=%f\n",u->abundance,u->srabund);
float available=u->srabund*DROP*ERROR_PERC-u->abundance; // abundance of sr is higher than spliced read alignment
if(available>epsilon) { // I have some abundance to explain
GPVec<CTransfrag> seltrfrag(false);
GVec<int> equalinc;
GVec<int> equalext;
int n=u->nodes[0];
for(int j=0;j<no2gnode[n]->trf.Count();j++) if(transfrag[no2gnode[n]->trf[j]]!=u) {
int t=no2gnode[n]->trf[j];
if(transfrag[t]->nodes[0]<=n && transfrag[t]->nodes.Last()>=u->nodes.Last()) { // transcript includes u
if((transfrag[t]->pattern & u->pattern) == u->pattern) { // t contains super-read
available-=transfrag[t]->abundance;
if(available<epsilon) {
available=0;
break;
}
}
else { // this could still be compatible with u
int mini=-1; // min node in t that appears in u
int i=0;
while(i<u->nodes.Count()) {
if(transfrag[t]->pattern[u->nodes[i]]) { // first node in u that is in t
mini=0;
while(transfrag[t]->nodes[mini]!=u->nodes[i]) mini++;
break;
}
i++;
}
if(mini>=0) { // found node in t -> check if it doesn't conflict with u
bool conflict=false;
if(i) { // only in this case I might have conflict
if(no2gnode[u->nodes[i]]->parentpat[transfrag[t]->nodes[mini-1]]) {
int *pos=gpos[edge(transfrag[t]->nodes[mini-1],transfrag[t]->nodes[mini],gno)];
if(pos && transfrag[t]->pattern[*pos]) conflict=true;
}
else conflict=true;
}
if(!conflict) {
int maxi=-1; // max node in t that appears in u
i=u->nodes.Count()-1;
while(i>=0) {
if(transfrag[t]->pattern[u->nodes[i]]) { // last node in u that is in t
maxi=transfrag[t]->nodes.Count()-1;
while(transfrag[t]->nodes[maxi]!=u->nodes[i]) maxi--;
break;
}
i--;
}
if(i<u->nodes.Count()-1) { // only in this case I might have conflict
if(no2gnode[u->nodes[i]]->childpat[transfrag[t]->nodes[maxi+1]]) {
int *pos=gpos[edge(transfrag[t]->nodes[maxi],transfrag[t]->nodes[maxi+1],gno)];
if(pos && transfrag[t]->pattern[*pos]) conflict=true;
}
else conflict=true;
}
if(!conflict) { // check that the transcript is really not conflicting to u
for(i=mini+1;i<=maxi;i++) {
int *pos=gpos[edge(transfrag[t]->nodes[i-1],transfrag[t]->nodes[i],gno)];
if(pos && transfrag[t]->pattern[*pos] && !u->pattern[*pos]) {
conflict=true;
break;
}
}
if(!conflict) {
if(transfrag[t]->nodes[0]==u->nodes[0] && transfrag[t]->nodes.Last()==u->nodes.Last())
equalinc.Add(t);
else equalext.Add(t);
}
}
}
}
}
}
else if((transfrag[t]->pattern & u->pattern) == transfrag[t]->pattern) { // compatible transcripts; transcript is included in u
seltrfrag.Add(transfrag[t]);
}
}
if(available) {
for(int i=0;i<equalinc.Count();i++) {
int t=equalinc[i];
float solveabund=transfrag[t]->abundance;
if(available<solveabund) {
solveabund=available;
}
transfrag[t]->abundance-=solveabund;
transfrag[t]->srabund-=solveabund;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
u->abundance+=solveabund;
available-=solveabund;
if(available<epsilon) {
available=0;
break;
}
}
if(available) {
for(int e=0;e<equalext.Count();e++) {
int t=equalext[e];
int j=0;
for(int i=0;i<u->nodes.Count();i++) {
if(!transfrag[t]->pattern[u->nodes[i]]) {
while(transfrag[t]->nodes[j]<u->nodes[i]) j++;
transfrag[t]->nodes.Insert(j,u->nodes[i]);
}
}
transfrag[t]->pattern = transfrag[t]->pattern | u->pattern;
available -= transfrag[t]->abundance;
if(available<epsilon) {
available=0;
break;
}
}
if(available) { // if I still have abundance left (very likely) -> stitch together transfrags in selfrags
for(int i=1;i<u->nodes.Count();i++) { // compute abundance that needs to be explained at each node
int n=u->nodes[i];
for(int j=0;j<no2gnode[n]->trf.Count();j++) if(transfrag[no2gnode[n]->trf[j]]->nodes[0]==n) { // transfrag starts at node
int t=no2gnode[n]->trf[j];
if((transfrag[t]->pattern & u->pattern) == transfrag[t]->pattern) {
seltrfrag.Add(transfrag[t]);
}
}
}
if(seltrfrag.Count()) {
seltrfrag.Sort(trCmp);
GVec<int> *start=new GVec<int>[gno]; // for each node remembers it's neighbours
for(int i=0;i<seltrfrag.Count();i++) {
start[seltrfrag[i]->nodes[0]].Add(i);
}
int i=0;
while(available && i<seltrfrag.Count()) {
if(seltrfrag[i]->abundance) {
GVec<int> next; // this stores the augmenting path
float maxabund=stitch_trf(u,available,i,i,seltrfrag,start,next);
if(maxabund) {
next.Add(i);
for(int j=0;j<next.Count();j++) {
int t=next[j];
seltrfrag[t]->abundance-=maxabund;
seltrfrag[t]->srabund-=maxabund;
if(seltrfrag[t]->abundance<epsilon) seltrfrag[t]->abundance=0;
}
if(!seltrfrag[i]->abundance) i++; // I solved this transfrag
available-=maxabund;
if(available<epsilon) {
available=0;
}
u->abundance+=maxabund;
}
else i++;
}
else i++;
}
delete [] start;
}
}
}
}
}
}
int compatible_long(int* t,int *len,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,int gno,GIntHash<int> &gpos) {
// return 0 if no compatibility, then 4*(rets)+rete where rets/rete = 1 if t[0] has extra intron, 2 if t[1] has extra intron, 3 if compatible starts/ends
// len[0] is how much t[0] extends past t[1] if positive, otherwise how much t[1] extends past t[0] at the start of transcripts
// len[1] positive: if t[0] has extra intron at start how much is t[1] inside of the intron -> default is 0; negative: same for t[1]
// len[2] is how much t[0] extends past t[1] if positive, otherwise how much t[1] extends past t[0] at the end of transcripts
// len[3] positive: if t[0] has extra intron at end how much is t[1] inside of the intron -> default is 0; negative: same for t[1]
if(transfrag[t[0]]->nodes[0]!=transfrag[t[1]]->nodes[0] &&
no2gnode[transfrag[t[0]]->nodes[0]]->hardstart && no2gnode[transfrag[t[1]]->nodes[0]]->hardstart)
return 0; // both starts can't be hard
if(transfrag[t[0]]->nodes.Last()!=transfrag[t[1]]->nodes.Last() &&
no2gnode[transfrag[t[0]]->nodes.Last()]->hardend && no2gnode[transfrag[t[1]]->nodes.Last()]->hardend)
return 0; // both ends can't be hard
uint tstart[2]={no2gnode[transfrag[t[0]]->nodes[0]]->start,no2gnode[transfrag[t[1]]->nodes[0]]->start};
if(transfrag[t[0]]->longstart) tstart[0]=transfrag[t[0]]->longstart;
if(transfrag[t[1]]->longstart) tstart[1]=transfrag[t[1]]->longstart;
uint tend[2]={no2gnode[transfrag[t[0]]->nodes.Last()]->end,no2gnode[transfrag[t[1]]->nodes.Last()]->end};
if(transfrag[t[0]]->longend) tend[0]=transfrag[t[0]]->longend;
if(transfrag[t[1]]->longend) tend[1]=transfrag[t[1]]->longend;
int f=0; // first starting transcript
int s=1; // second starting transcript
if(tstart[1]<tstart[0]) { // transfrag t1 starts before trf t0
f=1;
s=0;
}
if(transfrag[t[f]]->nodes.Last()<transfrag[t[s]]->nodes[0]) // no overlapping transcripts
return 0;
// check START
int rets=3; // compatible starts by default
int i[2]; // starting index in transfrags where they share a node
i[0]=0;i[1]=0;
len[0]=0;
len[1]=0;
while(transfrag[t[f]]->nodes[i[f]]<transfrag[t[s]]->nodes[0]) { // i[f]<transfrag[t[f]]->nodes.Count() always true due to condition of overlap before
if(no2gnode[transfrag[t[f]]->nodes[i[f]]]->end+1<no2gnode[transfrag[t[f]]->nodes[i[f]+1]]->start) { // found intron in f
rets=1+f;
if(no2gnode[transfrag[t[s]]->nodes[0]]->hardstart) return 0; // there is no compatibility here
}
// len[0]+=no2gnode[transfrag[t[f]]->nodes[i[f]]]->len(); // this only approximates the length
// adj if I want real distances:
if(i[f]) len[0]+=no2gnode[transfrag[t[f]]->nodes[i[f]]]->len();
else len[0]+=no2gnode[transfrag[t[f]]->nodes[i[f]]]->end-tstart[f]+1;
i[f]++;
}
if(transfrag[t[s]]->nodes.Last()<transfrag[t[f]]->nodes[i[f]]) return 0; // no overlap: t[s] is contained in t[f]
// adj for real distance
if(!i[f]) { // transfrag[t[f]]->nodes[0]==transfrag[t[s]]->nodes[0]
len[0]=tstart[s]-tstart[f];
}
if(transfrag[t[s]]->nodes[0]<transfrag[t[f]]->nodes[i[f]]) { // i[f]>0 because f has to start first
if(!no2gnode[transfrag[t[s]]->nodes[0]]->childpat[transfrag[t[f]]->nodes[i[f]]]) return 0; // I can not reach node i[f] from t[s][0]
// to approximate:
// len[1]=no2gnode[transfrag[t[f]]->nodes[i[f]]]->start-no2gnode[transfrag[t[s]]->nodes[0]]->start;
// adj if I want real distances:
len[1]=no2gnode[transfrag[t[f]]->nodes[i[f]]]->start-tstart[s];
while(transfrag[t[s]]->nodes[i[s]]<transfrag[t[f]]->nodes[i[f]]) {
i[s]++;
if(no2gnode[transfrag[t[s]]->nodes[i[s]-1]]->end+1<no2gnode[transfrag[t[s]]->nodes[i[s]]]->start) { // not continuous
return 0;
}
}
}
else if(i[f]){ // no intron -> adj lentgh for real distance
len[0]+=tstart[s]-no2gnode[transfrag[t[s]]->nodes[0]]->start;
}
if(f) len[0]=-len[0]; // a negative value signals that t[1] extends past t[0]
// check END
int rete=3;
f=0;
s=1;
if(tend[1]>tend[0]) { // f should be the longer transcript at the end
f=1;
s=0;
}
int j[2];
j[0]=transfrag[t[0]]->nodes.Count()-1;
j[1]=transfrag[t[1]]->nodes.Count()-1;
len[2]=0;
len[3]=0;
while(transfrag[t[f]]->nodes[j[f]]>transfrag[t[s]]->nodes.Last()) { // s and f should have a node in common by now so fj doesn't have to go all the way back to 0
if(no2gnode[transfrag[t[f]]->nodes[j[f]-1]]->end+1<no2gnode[transfrag[t[f]]->nodes[j[f]]]->start) { // found intron
rete=1+f;
if(rets<3 && rete!=rets) return 0;
if(no2gnode[transfrag[t[s]]->nodes.Last()]->hardend) return 0; // there is no compatibility here
}
// to approximate:
//len[2]+=no2gnode[transfrag[t[f]]->nodes[j[f]]]->len();
// adj:
if(j[f]<transfrag[t[f]]->nodes.Count()-1) len[2]+=no2gnode[transfrag[t[f]]->nodes[j[f]]]->len();
else len[2]+=tend[f]-no2gnode[transfrag[t[f]]->nodes[j[f]]]->start+1;
j[f]--;
}
if(transfrag[t[s]]->nodes[0]>transfrag[t[f]]->nodes[j[f]]) return 0; // no overlap (this shouldn't be the case since there is one node in common)
if(j[f]==transfrag[t[f]]->nodes.Count()-1) len[2]+=tend[f]-tend[s];
if(transfrag[t[s]]->nodes[j[s]]>transfrag[t[f]]->nodes[j[f]]) {
if(!no2gnode[transfrag[t[f]]->nodes[j[f]]]->childpat[transfrag[t[s]]->nodes[j[s]]]) return 0; // I can not reach node j[s] from j[f]
// len[3]=no2gnode[transfrag[t[s]]->nodes.Last()]->end-no2gnode[transfrag[t[f]]->nodes[j[f]]]->end; // to approximate dist
// adj if I want real distances:
len[3]=tend[s]-no2gnode[transfrag[t[f]]->nodes[j[f]]]->end;
while(transfrag[t[s]]->nodes[j[s]]>transfrag[t[f]]->nodes[j[f]]) {
j[s]--;
if(no2gnode[transfrag[t[s]]->nodes[j[s]]]->end+1<no2gnode[transfrag[t[s]]->nodes[j[s]+1]]->start) { // not continuous
return 0;
}
}
}
else if(j[f]<transfrag[t[f]]->nodes.Count()-1) {
len[2]+=no2gnode[transfrag[t[s]]->nodes.Last()]->end-tend[s];
}
if(i[f]>j[f] || i[s]>j[s]) return 0; // there should be i<=j
if(f) len[2]=-len[2]; // a negative value signals that t[1] extends past t[0]
// now if and is point at the same node in transcripts, and so do jf and js
while(i[f]<=j[f] && i[s]<=j[s]) {
if(transfrag[t[f]]->nodes[i[f]]==transfrag[t[s]]->nodes[i[s]]) { // skip equal nodes
i[f]++;
i[s]++;
}
else { // unequal
if(transfrag[t[f]]->nodes[i[f]]>transfrag[t[s]]->nodes[i[s]]) { // make sure node f is always smallest
int k=f;
f=s;
s=k;
}
while(transfrag[t[f]]->nodes[i[f]]<transfrag[t[s]]->nodes[i[s]] &&
no2gnode[transfrag[t[f]]->nodes[i[f]-1]]->end+1==no2gnode[transfrag[t[f]]->nodes[i[f]]]->start) { // advance smallest node until I get to a gap
i[f]++;
}
if(no2gnode[transfrag[t[f]]->nodes[i[f]-1]]->end+1==no2gnode[transfrag[t[f]]->nodes[i[f]]]->start) return 0; // gap in s is filled by transfrag f
// see if gaps are both hard
int *pos=gpos[edge(transfrag[t[f]]->nodes[i[f]-1],transfrag[t[f]]->nodes[i[f]],gno)];
if(pos && transfrag[t[f]]->pattern[*pos]) { // this is a hard edge in t[f]
pos=gpos[edge(transfrag[t[s]]->nodes[i[s]-1],transfrag[t[s]]->nodes[i[s]],gno)];
if(pos && transfrag[t[s]]->pattern[*pos]) return 0; // edge is hard in both f and s
}
if(transfrag[t[f]]->nodes[i[f]]>transfrag[t[s]]->nodes[i[s]]) { // make sure node f is always smallest
int k=f;
f=s;
s=k;
}
while(transfrag[t[f]]->nodes[i[f]]<transfrag[t[s]]->nodes[i[s]]) {
if(no2gnode[transfrag[t[f]]->nodes[i[f]]]->end+1<no2gnode[transfrag[t[f]]->nodes[i[f]+1]]->start) return 0;
i[f]++;
}
}
}
if(rets==1 || rete==1) return(1); // t[0] extends with introns past t[1] at at least one side
if(rets==2 || rete==2) return(2); // t[1] extends with introns past t[0] at at least one side
return(3); // t[0] and t[1] have compatible starts/ends
}
void process_transfrags(int s, int gno,int edgeno,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,CTreePat *tr2no,
GIntHash<int> &gpos,GVec<CGuide>& guidetrf,GList<CPrediction>& pred,GVec<int>& trflong) {
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"There are %d transfrags before clean up:\n",transfrag.Count());
for(int i=0;i<transfrag.Count();i++) {
fprintf(stderr,"transfrag[%d](%f,%f) long=%d short=%d usepath=%d:",i,transfrag[i]->abundance,transfrag[i]->srabund,transfrag[i]->longread,transfrag[i]->shortread,(int)transfrag[i]->usepath);
for(int j=0;j<transfrag[i]->nodes.Count();j++) fprintf(stderr," %d",transfrag[i]->nodes[j]);
fprintf(stderr,"\n");
}
}
*/
// add all guide patterns to the set of transfrags so that I can have a "backbone" for each guide
// I need this because there might be an incompatible transfrag connecting the nodes in the guide
//fprintf(stderr,"There are %d guides\n",guidetrf.Count());
for(int i=0;i<guidetrf.Count();i++) if(guidetrf[i].trf->guide){
CTransfrag *t=NULL;
bool add=true;
if(longreads || mixedMode) {
/*guidetrf[i].trf->pattern[0]=0;
guidetrf[i].trf->pattern[gno-1]=0;
int *pos=gpos[edge(0,guidetrf[i].trf->nodes[1],gno)];
if(pos) guidetrf[i].trf->pattern[*pos]=0;
pos=gpos[edge(guidetrf[i].trf->nodes[guidetrf[i].trf->nodes.Count()-2],guidetrf[i].trf->nodes.Last(),gno)];
if(pos) guidetrf[i].trf->pattern[*pos]=0;
guidetrf[i].trf->nodes.Pop();
guidetrf[i].trf->nodes.Shift();*/
t=findtrf_in_treepat(gno,gpos,guidetrf[i].trf->nodes,guidetrf[i].trf->pattern,tr2no); // I need to adjust first/last node
if(!t) { // t is NULL
float abund=0;
if(mixedMode) abund=trthr*ERROR_PERC;
t=new CTransfrag(guidetrf[i].trf->nodes,guidetrf[i].trf->pattern,abund);
t->longread=true;
}
else add=false;
}
else {
t=new CTransfrag(guidetrf[i].trf->nodes,guidetrf[i].trf->pattern,trthr*ERROR_PERC);
}
if(!longreads) {
if(includesource) {
guidetrf[i].trf->nodes.Insert(0,0); // I need to comment this if I need path not to include the source
guidetrf[i].trf->pattern[0]=1;
int *pos=gpos[edge(0,guidetrf[i].trf->nodes[1],gno)];
if(pos) guidetrf[i].trf->pattern[*pos]=1;
}
int sink=gno-1;
guidetrf[i].trf->nodes.Add(sink);
guidetrf[i].trf->pattern[sink]=1;
int *pos=gpos[edge(guidetrf[i].trf->nodes[guidetrf[i].trf->nodes.Count()-2],guidetrf[i].trf->nodes.Last(),gno)];
if(pos) guidetrf[i].trf->pattern[*pos]=1;
}
/*
float abund=0;
if(!longreads) {
abund=trthr*ERROR_PERC;
}
CTransfrag *t=new CTransfrag(guidetrf[i].trf->nodes,guidetrf[i].trf->pattern,abund);
*/
/*
{ // DEBUG ONLY
fprintf(stderr,"Add guidetrf with nodes:");
for(int j=0;j<guidetrf[i].trf->nodes.Count();j++) fprintf(stderr," %d",guidetrf[i].trf->nodes[j]);
//fprintf(stderr," and pattern: ");
//printBitVec(guidetrf[i].trf->pattern);
fprintf(stderr,"\n");
fprintf(stderr,"Found transfrag %p with nodes:",t);
for(int j=0;j<t->nodes.Count();j++) fprintf(stderr," %d",t->nodes[j]);
//fprintf(stderr," and pattern: ");
//printBitVec(guidetrf[i].trf->pattern);
fprintf(stderr,"\n");
}
*/
/*if(!longreads) {
t->pattern[0]=0;
t->pattern[gno-1]=0;
int *pos=gpos[edge(0,t->nodes[1],gno)];
if(pos) t->pattern[*pos]=0;
pos=gpos[edge(t->nodes[t->nodes.Count()-2],t->nodes.Last(),gno)];
if(pos) t->pattern[*pos]=0;
if(add) {
t->nodes.Pop();
t->nodes.Shift();
}
}*/
t->guide=1+guidetrf[i].g;
//fprintf(stderr,"t->guide set to=%d\n",1+guidetrf[i].g);
t->longstart=no2gnode[t->nodes[0]]->start;
t->longend=no2gnode[t->nodes.Last()]->end;
//if(longreads) t->usepath=guidetrf[i].g; // guide index
no2gnode[t->nodes[0]]->hardstart=1; // I can always trust a guide's start
no2gnode[t->nodes.Last()]->hardend=1; // I can always trust a guide's end
if(add) transfrag.Add(t);
}
else if(!longreads) {
if(includesource) {
guidetrf[i].trf->nodes.Insert(0,0); // I need to comment this if I need path not to include the source
guidetrf[i].trf->pattern[0]=1;
int *pos=gpos[edge(0,guidetrf[i].trf->nodes[1],gno)];
if(pos) guidetrf[i].trf->pattern[*pos]=1;
}
int sink=gno-1;
guidetrf[i].trf->nodes.Add(sink);
guidetrf[i].trf->pattern[sink]=1;
int *pos=gpos[edge(guidetrf[i].trf->nodes[guidetrf[i].trf->nodes.Count()-2],guidetrf[i].trf->nodes.Last(),gno)];
if(pos) guidetrf[i].trf->pattern[*pos]=1;
}
GPVec<CTransfrag> srfrag(false);
// eliminate transfrags below threshold (they represent noise) if they don't come from source
if(!eliminate_transfrags_under_thr(gno,gpos,transfrag,tr2no,trthr,srfrag) && srfrag.Count()) { // long transfrags but only to source/sink
srfrag.Clear();
}
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"\nThere are %d transfrags after clean up:\n",transfrag.Count());
for(int i=0;i<transfrag.Count();i++) {
fprintf(stderr,"transfrag[%d] abund=%f long:%d: short:%d usepath:%d",i,transfrag[i]->abundance,transfrag[i]->longread,transfrag[i]->shortread,(int)transfrag[i]->usepath);
for(int j=0;j<transfrag[i]->nodes.Count();j++) fprintf(stderr," %d",transfrag[i]->nodes[j]);
fprintf(stderr,"\n");
}
}
*/
GBitVec allpat(gno+edgeno);
bool trsort=true;
if(longreads) { // add source/sink links but only if they need to be added to explain the traversals in the graph
transfrag.Sort(longtrCmp); // most abundant transfrag in the graph come first, then the ones with most nodes, then the ones more complete
trsort=false;
int source=0;
int sink=gno-1;
GVec<int> hassource(gno,-1); // remembers transcript number that links given node to source
GVec<int> hassink(gno,-1); // remembers transcript number that links given node to sink
GBitVec keepsource(gno); // if not set then I can remove link from node to source; keeps source link if it exists otherwise otherwise
GBitVec keepsink(gno); // if not set then I can remove link from node to sink; keeps sink link if it exists otherwise otherwise
GVec<CLongTrf> keeptrf; // keeps all potential transfrags that will be kept from most abundant to least, unassembled
float zero=0;
GVec<float> addsource(gno,zero);
GVec<float> addsink(gno,zero);
int edgedist=CHI_WIN; // I need to be consistent (if I change here then I need to change in update_abundance too)
int ssdist=longintronanchor;
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"\nThere are %d transfrags after clean up:\n",transfrag.Count());
for(int i=0;i<transfrag.Count();i++) {
fprintf(stderr,"transfrag[%d] abund=%f:",i,transfrag[i]->abundance);
for(int j=0;j<transfrag[i]->nodes.Count();j++) fprintf(stderr," %d",transfrag[i]->nodes[j]);
if(transfrag[i]->guide) fprintf(stderr," guide");
fprintf(stderr,"\n");
}
}
*/
for(int t1=0;t1<transfrag.Count();t1++) {
/*fprintf(stderr,"Consider t=%d with abund=%f guide=%d and nodes:",t1,transfrag[t1]->abundance,transfrag[t1]->guide);
for(int j=0;j<transfrag[t1]->nodes.Count();j++) {
if(j) {
int *pos=gpos[edge(transfrag[t1]->nodes[j-1],transfrag[t1]->nodes[j],gno)];
if(pos && transfrag[t1]->pattern[*pos]) {
fprintf(stderr,"-");
}
else fprintf(stderr," ");
}
fprintf(stderr,"%d",transfrag[t1]->nodes[j]);
} fprintf(stderr,"\n");*/
if(!transfrag[t1]->nodes[0]) {
hassource[transfrag[t1]->nodes[1]]=t1;
//fprintf(stderr,"Node %d in t=%d with cov=%f has source\n",transfrag[t1]->nodes[1],t1,transfrag[t1]->abundance);
}
else if(transfrag[t1]->nodes.Last()==gno-1) {
hassink[transfrag[t1]->nodes[0]]=t1;
//fprintf(stderr,"Node %d in t=%d with cov=%f has sink\n",transfrag[t1]->nodes[0],t1,transfrag[t1]->abundance);
}
else {
if(eonly && !transfrag[t1]->guide) continue; // do not remember transfrags that are not guides
if(!keepsource[transfrag[t1]->nodes[0]]) {
if(transfrag[t1]->longstart) keepsource[transfrag[t1]->nodes[0]]=1; //fprintf(stderr,"keep source %d\n",transfrag[t1]->nodes[0]);}
else if(no2gnode[transfrag[t1]->nodes[0]]->hardstart) keepsource[transfrag[t1]->nodes[0]]=1;
}
if(!keepsink[transfrag[t1]->nodes.Last()]) {
if(transfrag[t1]->longend) keepsink[transfrag[t1]->nodes.Last()]=1;//fprintf(stderr,"keep sink %d\n",transfrag[t1]->nodes.Last());}
else if(no2gnode[transfrag[t1]->nodes.Last()]) keepsink[transfrag[t1]->nodes.Last()]=1;
}
bool included=false;
// a transfrag that starts at source and ends at sink can never be included in a kept transfrag, so I am safe to do next
for(int t2=0; t2<keeptrf.Count();t2++) {
int t[2]={t1,keeptrf[t2].t}; // t1 current, t2 the one I kept
int len[4]={MAX_NODE,MAX_NODE,MAX_NODE,MAX_NODE};
int ret=compatible_long(t,len,transfrag,no2gnode,gno,gpos);
//fprintf(stderr," ret=%d t[0]=%d t[1]=%d len[0]=%d len[1]=%d len[2]=%d len[3]=%d\n",ret,t[0],t[1],len[0],len[1],len[2],len[3]);
if(ret){
switch(ret) {
case 1: // t[0] includes t[1]: it extends with introns on on one or both sides -> keep unless I can eliminate a previous one
if(!transfrag[t[1]]->guide && transfrag[t1]->longstart && transfrag[t1]->longend && // t[1] might be included in t[0] so I might eliminate if it doesn't pass threshold
(!no2gnode[transfrag[t[1]]->nodes[0]]->hardstart || transfrag[t[0]]->nodes[0] == transfrag[t[1]]->nodes[0] ) &&
(!no2gnode[transfrag[t[1]]->nodes.Last()]->hardend || transfrag[t[0]]->nodes.Last() == transfrag[t[1]]->nodes.Last())) {
//if(transfrag[t[0]]->abundance>(1-ERROR_PERC/DROP)*transfrag[t[1]]->abundance) { // t[0] is within limits of t[1]
if(transfrag[t[0]]->abundance>DROP*transfrag[t[1]]->abundance) { // t[0] is within limits of t[1]
if(len[1]<ssdist && len[3]<ssdist) { // prefer t[0] instead of t[1]
keeptrf[t2].t=t1;
keeptrf[t2].cov+=transfrag[t1]->abundance;
keeptrf[t2].group.Add(t1);
included=true; // I do not want to store transcript
//fprintf(stderr,"trf %d includes %d\n",t[0],t[1]);
}
}
}
break;
case 2: // t[1] includes t[0]: extends with introns past ends of t[0] (t[1] possibly includes t[0]); t[1] is more abundant than t0
//if(transfrag[t[1]]->guide || transfrag[t[1]]->abundance>(1-ERROR_PERC/DROP)*transfrag[t[0]]->abundance) {
if(!transfrag[t[0]]->guide &&
(!no2gnode[transfrag[t[0]]->nodes[0]]->hardstart || transfrag[t[0]]->nodes[0] == transfrag[t[1]]->nodes[0]) &&
(!no2gnode[transfrag[t[0]]->nodes.Last()]->hardend || transfrag[t[0]]->nodes.Last() == transfrag[t[1]]->nodes.Last())) {
if(len[1]<ssdist && len[3]<ssdist) {
keeptrf[t2].cov+=transfrag[t1]->abundance;
keeptrf[t2].group.Add(t1);
included=true;
//fprintf(stderr,"trf %d is intronic including %d\n",t[1],t[0]);
}
}
//}
break;
case 3: // t1 and t0 are compatible --> just look for the edges; t1 goes further apart
if(transfrag[t[0]]->nodes[0]!=transfrag[t[1]]->nodes[0] && transfrag[t[0]]->nodes.Last()!=transfrag[t[1]]->nodes.Last() &&
((no2gnode[transfrag[t[0]]->nodes[0]]->hardstart && !no2gnode[transfrag[t[1]]->nodes[0]]->hardstart &&
!no2gnode[transfrag[t[0]]->nodes.Last()]->hardend && no2gnode[transfrag[t[1]]->nodes.Last()]->hardend) ||
(!no2gnode[transfrag[t[0]]->nodes[0]]->hardstart && no2gnode[transfrag[t[1]]->nodes[0]]->hardstart &&
no2gnode[transfrag[t[0]]->nodes.Last()]->hardend && !no2gnode[transfrag[t[1]]->nodes.Last()]->hardend))) {
// these two transcripts both have one good start and one different --> keep them both (different option would be to add them to another transfrag that is compatible and has both hardends but then it's more complicated
break;
}
// I keep both if both are guides
//if((!transfrag[t[0]]->guide || !transfrag[t[1]]->guide) && abs(len[0])<edgedist && abs(len[2])<edgedist) { // close by
if((!transfrag[t[0]]->guide || !transfrag[t[1]]->guide) && len[0]<edgedist && len[2]<edgedist) { // close by
if(transfrag[t[0]]->guide || (!transfrag[t[1]]->guide && no2gnode[transfrag[t[0]]->nodes[0]]->hardstart && no2gnode[transfrag[t[0]]->nodes.Last()]->hardend))
keeptrf[t2].t=t1; // t[0] to replace t[1]
keeptrf[t2].cov+=transfrag[t1]->abundance;
keeptrf[t2].group.Add(t1);
included=true;
//fprintf(stderr,"trf %d %d equivalent start/ends\n",t[1],t[0]);
}
break;
}
if(included) break; // break from for loop
}
}
if(!included){
if(transfrag[t1]->guide || ((transfrag[t1]->longstart || no2gnode[transfrag[t1]->nodes[0]]->hardstart)&&
(transfrag[t1]->longend || no2gnode[transfrag[t1]->nodes.Last()]->hardend))) { // if this is not included and has correct start/end
CLongTrf kt(t1,transfrag[t1]->abundance);
keeptrf.Add(kt);
keeptrf.Last().group.Add(t1);
//fprintf(stderr,"keep transfrag %d\n",t1);
}
else { // incomplete transcript, possibly wrong
transfrag[t1]->weak=1;
//fprintf(stderr,"Incomplete transcript %d\n",t1);
}
}
}
}
char sign='-';
if(s) { sign='+';}
//GBitVec guidesource(gno);
//GBitVec guidesink(gno);
//for(int i=0;i<keeptrf.Count();i++) {
for(int i=keeptrf.Count()-1;i>=0;i--) { // I add the kept transcripts to trflong from least significant to most in order to make deletion easier
//fprintf(stderr,"Build source/sink for transfrag %d\n",keeptrf[i].t);
int n1=transfrag[keeptrf[i].t]->nodes[0];
int n2=transfrag[keeptrf[i].t]->nodes.Last();
//if(hassource[n1]<0 || hassink[n2]<0) fprintf(stderr,"Build source/sink for transfrag %d\n",keeptrf[i].t);
if(!rawreads && !transfrag[keeptrf[i].t]->guide && ((!no2gnode[n1]->hardstart && (hassource[n1]<0 || !keepsource[n1])) ||
(!no2gnode[n2]->hardend && (hassink[n2]<0 || !keepsink[n2])))) {
//if(!rawreads && (no2gnode[n1]->hardstart || (hassource[n1]>=0 && keepsource[n1])) && (no2gnode[n2]->hardend ||(hassink[n2]>=0 && keepsink[n2]))) {
trflong.Add(keeptrf[i].t);
}
/******* previous implementation here
addsource[n1]=keeptrf[i].cov;
addsink[n2]=keeptrf[i].cov;
*******/
/*
if(!addsource[n1] && hassource[n1]<0) {
int startpos=no2gnode[n1]->start-refstart;
if(startpos-CHI_THR<0 || startpos+CHI_THR>bpcov->Count()) addsource[n1]=1;
else {
addsource[n1]=(get_cov(1,startpos,startpos+CHI_THR-1,bpcov)-get_cov(2-2*s,startpos,startpos+CHI_THR-1,bpcov)-
get_cov(1,startpos-CHI_THR,startpos-1,bpcov)+get_cov(2-2*s,startpos-CHI_THR,startpos-1,bpcov))/(DROP*CHI_THR);
}
}
if(!addsink[n2] && hassink[n1]<0) {
int endpos=no2gnode[n2]->end-refstart;
if(endpos-CHI_THR<0 || endpos+CHI_THR>bpcov->Count()-1) addsink[n2]=1;
else {
addsink[n2]=(get_cov(1,endpos-CHI_THR+1,endpos,bpcov)-get_cov(2-2*s,endpos-CHI_THR+1,endpos,bpcov)-
get_cov(1,endpos+1,endpos+CHI_THR,bpcov)+get_cov(2-2*s,endpos+1,endpos+CHI_THR,bpcov))/(DROP*CHI_THR);
}
}*/
// all
for(int j=0;j<keeptrf[i].group.Count();j++) {
if(n1==transfrag[keeptrf[i].group[j]]->nodes[0]) {
addsource[n1]+=transfrag[keeptrf[i].group[j]]->abundance;
//fprintf(stderr,"Add source t[%d]->cov=%f to node %d = %f\n",keeptrf[i].group[j],transfrag[keeptrf[i].group[j]]->abundance,n1,addsource[n1]);
}
if(n2==transfrag[keeptrf[i].group[j]]->nodes.Last()) {
addsink[n2]+=transfrag[keeptrf[i].group[j]]->abundance;
//fprintf(stderr,"Add sink t[%d]->cov=%f to node %d = %f\n",keeptrf[i].group[j],transfrag[keeptrf[i].group[j]]->abundance,n2,addsink[n2]);
}
}
if(rawreads) {
GVec<GSeg> exons;
int j=0;
int len=0;
int t=keeptrf[i].t;
while(j<transfrag[t]->nodes.Count()) {
int nodestart=no2gnode[transfrag[t]->nodes[j]]->start;
int nodeend=no2gnode[transfrag[t]->nodes[j]]->end;
len+=nodeend-nodestart+1;
while(j+1<transfrag[t]->nodes.Count() && no2gnode[transfrag[t]->nodes[j]]->end+1==no2gnode[transfrag[t]->nodes[j+1]]->start) {
j++;
len+=no2gnode[transfrag[t]->nodes[j]]->len();
nodeend=no2gnode[transfrag[t]->nodes[j]]->end;
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
j++;
}
uint tstart=exons[0].start;
uint tend=exons.Last().end;
if(transfrag[t]->longstart>tstart) {
len-=transfrag[t]->longstart-tstart;
tstart=transfrag[t]->longstart;
}
if(transfrag[t]->longend && transfrag[t]->longend<tend) {
len-=tend-transfrag[t]->longend;
tend=transfrag[t]->longend;
}
CPrediction *p=new CPrediction(s, NULL, tstart, tend, keeptrf[i].cov, sign, len);
exons[0].start=tstart;
exons.Last().end=tend;
p->exons=exons;
pred.Add(p);
}
}
for(int i=keeptrf.Count()-1;i>=0;i--) {
int n1=transfrag[keeptrf[i].t]->nodes[0];
int n2=transfrag[keeptrf[i].t]->nodes.Last();
if(transfrag[keeptrf[i].t]->guide || ((no2gnode[n1]->hardstart || (hassource[n1]>=0 && keepsource[n1])) && (no2gnode[n2]->hardend ||(hassink[n2]>=0 && keepsink[n2]))))
trflong.Add(keeptrf[i].t);
}
/*
{ // DEBUG ONLY
fprintf(stderr,"%d keeptrf:\n",keeptrf.Count());
for(int i=0;i<keeptrf.Count();i++) {
fprintf(stderr,"(%d) %d abund=%f keepcov=%f",i,keeptrf[i].t,transfrag[keeptrf[i].t]->abundance,keeptrf[i].cov);
for(int j=0;j<transfrag[keeptrf[i].t]->nodes.Count();j++) {
fprintf(stderr," %d",transfrag[keeptrf[i].t]->nodes[j]);
}
fprintf(stderr,"\n");
}
fprintf(stderr,"%d trflong:",trflong.Count());
for(int i=0;i<trflong.Count();i++)
fprintf(stderr," %d",trflong[i]);
fprintf(stderr,"\n");
}
*/
// add source/sink connections
for(int i=1;i<gno-1;i++) {
//fprintf(stderr,"i=%d hassource=%d addsource=%f hassink=%d addsink=%f\n",i,hassource[i],addsource[i],hassink[i],addsink[i]);
if(hassource[i]<0) {
if(addsource[i] && no2gnode[i]->hardstart) {
/*float abund=trthr;
if(no2gnode[i]->hardstart) { // node i doesn't have source as parent but it should
abund=addsource[i];
}*/
// else I am not that confident this is a start
no2gnode[i]->parent.Insert(0,zero);
no2gnode[0]->child.Add(i);
GVec<int> nodes;
nodes.Add(source);
nodes.Add(i);
//CTransfrag *t=new CTransfrag(nodes,allpat,abund);
CTransfrag *t=new CTransfrag(nodes,allpat,addsource[i]);
t->pattern[source]=1;
t->pattern[i]=1;
t->longread=true;
transfrag.Add(t);
//fprintf(stderr,"Add link to source: 0-%d with abundance=%f\n",i, addsource[i]);
}
}
else {
if(!keepsource[i]) { // it was a mistake to link this to source --> remove
/*fprintf(stderr,"delete abundance of trf:");
for(int j=0;j<transfrag[hassource[i]]->nodes.Count();j++) fprintf(stderr," %d",transfrag[hassource[i]]->nodes[j]);fprintf(stderr,"\n");*/
transfrag[hassource[i]]->abundance=0;
}
else { // this one has source and it should be kept => update trf abundance to a more realistic value
//fprintf(stderr,"source %d:%d abund=%f addsource=%f\n",i,no2gnode[i]->start,transfrag[hassource[i]]->abundance,addsource[i]);
//if(guidesource[i] && transfrag[hassource[i]]->abundance<addsource[i])
transfrag[hassource[i]]->abundance=addsource[i];
}
}
if(hassink[i]<0) {
if(addsink[i] && no2gnode[i]->hardend) {
/*float abund=trthr;
if(no2gnode[i]->hardend) {
abund=addsink[i];
}*/
// else not very confident about this end
no2gnode[i]->child.Add(sink);
no2gnode[sink]->parent.Add(i);
GVec<int> nodes;
nodes.Add(i);
nodes.Add(sink);
CTransfrag *t=new CTransfrag(nodes,allpat,addsink[i]);
t->pattern[sink]=1;
t->pattern[i]=1;
t->longread=true;
transfrag.Add(t);
//fprintf(stderr,"Add link to sink: %d-%d with abundance=%f\n",i,sink,addsink[i]);
}
}
else {
if(!keepsink[i]) { // it was a mistake to link this to sink --> remove
/*fprintf(stderr,"delete abundance of trf:");
for(int j=0;j<transfrag[hassink[i]]->nodes.Count();j++) fprintf(stderr," %d",transfrag[hassink[i]]->nodes[j]);fprintf(stderr,"\n");*/
transfrag[hassink[i]]->abundance=0;
}
else {
//fprintf(stderr,"sink %d:%d abund=%f addsink=%f\n",i,no2gnode[i]->end,transfrag[hassink[i]]->abundance,addsink[i]);
//if(guidesink[i] && transfrag[hassink[i]]->abundance<addsink[i])
transfrag[hassink[i]]->abundance=addsink[i];
}
}
}
}
else if(srfrag.Count() && mixedMode) { // add source/sink links but only if they need to be added to explain the traversals in the graph
srfrag.Sort(longtrCmp); // most abundant transfrags in the graph come first, then the ones with most nodes, then the ones more complete
int source=0;
int sink=gno-1;
GVec<int> hassource(gno,-1); // remembers transcript number that links given node to source
GVec<int> hassink(gno,-1); // remembers transcript number that links given node to sink
GBitVec keepsource(gno); // if not set then I can remove link from node to source; keeps source link if it exists otherwise otherwise
GBitVec keepsink(gno); // if not set then I can remove link from node to sink; keeps sink link if it exists otherwise otherwise
GVec<CLongTrf> keeptrf; // keeps all potential transfrags that will be kept from most abundant to least, unassembled
float zero=0;
GVec<float> addsource(gno,zero);
GVec<float> addsink(gno,zero);
int edgedist=CHI_WIN; // I need to be consistent (if I change here then I need to change in update_abundance too)
int ssdist=longintronanchor;
int ntrf=0; // number of trflong transcripts
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"\nThere are %d longsrtransfrags after clean up:\n",srfrag.Count());
for(int i=0;i<srfrag.Count();i++) {
fprintf(stderr,"srfrag[%d] longstart=%d longend=%d abund=%f t=%d:",i,srfrag[i]->longstart,srfrag[i]->longend,srfrag[i]->abundance,int(srfrag[i]->usepath));
for(int j=0;j<srfrag[i]->nodes.Count();j++) fprintf(stderr," %d",srfrag[i]->nodes[j]);
fprintf(stderr,"\n");
}
}
*/
for(int t1=0;t1<srfrag.Count();t1++) {
/*fprintf(stderr,"Consider t=%d with abund=%f and nodes:",t1,srfrag[t1]->abundance);
for(int j=0;j<srfrag[t1]->nodes.Count();j++) {
if(j) {
int *pos=gpos[edge(srfrag[t1]->nodes[j-1],srfrag[t1]->nodes[j],gno)];
if(pos && srfrag[t1]->pattern[*pos]) {
fprintf(stderr,"-");
}
else fprintf(stderr," ");
}
fprintf(stderr,"%d",srfrag[t1]->nodes[j]);
} fprintf(stderr,"\n");*/
if(!srfrag[t1]->nodes[0]) {
hassource[srfrag[t1]->nodes[1]]=t1;
//fprintf(stderr,"Node %d in t=%d with cov=%f has source\n",srfrag[t1]->nodes[1],t1,srfrag[t1]->abundance);
}
else if(srfrag[t1]->nodes.Last()==gno-1) {
hassink[srfrag[t1]->nodes[0]]=t1;
//fprintf(stderr,"Node %d in t=%d with cov=%f has sink\n",srfrag[t1]->nodes[0],t1,srfrag[t1]->abundance);
}
else {
if(eonly && !srfrag[t1]->guide) continue; // do not remember transfrags that are not guides
if(!keepsource[srfrag[t1]->nodes[0]]) {
if(srfrag[t1]->longstart) keepsource[srfrag[t1]->nodes[0]]=1;
else if(no2gnode[srfrag[t1]->nodes[0]]->hardstart) keepsource[srfrag[t1]->nodes[0]]=1;
}
if(!keepsink[srfrag[t1]->nodes.Last()]) {
if(srfrag[t1]->longend) keepsink[srfrag[t1]->nodes.Last()]=1;
else if(no2gnode[srfrag[t1]->nodes.Last()]) keepsink[srfrag[t1]->nodes.Last()]=1;
}
bool included=false;
// a transfrag that starts at source and ends at sink can never be included in a kept transfrag, so I am safe to do next
for(int t2=0; t2<keeptrf.Count();t2++) {
int t[2]={t1,keeptrf[t2].t}; // t1 current, t2 the one I kept
int len[4]={MAX_NODE,MAX_NODE,MAX_NODE,MAX_NODE};
int ret=compatible_long(t,len,srfrag,no2gnode,gno,gpos);
//fprintf(stderr," ret=%d t[0]=%d t[1]=%d len[0]=%d len[1]=%d len[2]=%d len[3]=%d\n",ret,t[0],t[1],len[0],len[1],len[2],len[3]);
if(ret){
switch(ret) {
case 1: // t[0] includes t[1]: it extends with introns on on one or both sides -> keep unless I can eliminate a previous one
if(!srfrag[t[1]]->guide && srfrag[t1]->longstart && srfrag[t1]->longend && // t[1] might be included in t[0] so I might eliminate if it doesn't pass threshold
(!no2gnode[srfrag[t[1]]->nodes[0]]->hardstart || srfrag[t[0]]->nodes[0] == srfrag[t[1]]->nodes[0] ) &&
(!no2gnode[srfrag[t[1]]->nodes.Last()]->hardend || srfrag[t[0]]->nodes.Last() == srfrag[t[1]]->nodes.Last())) {
//if(srfrag[t[0]]->abundance>(1-ERROR_PERC/DROP)*srfrag[t[1]]->abundance) { // t[0] is within limits of t[1]
if(srfrag[t[0]]->abundance>DROP*srfrag[t[1]]->abundance) { // t[0] is within limits of t[1]
if(len[1]<ssdist && len[3]<ssdist) { // prefer t[0] instead of t[1]
keeptrf[t2].t=t1;
keeptrf[t2].cov+=srfrag[t1]->abundance;
keeptrf[t2].group.Add(t1);
included=true; // I do not want to store transcript
//fprintf(stderr,"trf %d includes %d\n",t[0],t[1]);
}
}
}
break;
case 2: // t[1] includes t[0]: extends with introns past ends of t[0] (t[1] possibly includes t[0]); t[1] is more abundant than t0
//if(srfrag[t[1]]->guide || srfrag[t[1]]->abundance>(1-ERROR_PERC/DROP)*srfrag[t[0]]->abundance) {
if(!srfrag[t[0]]->guide &&
(!no2gnode[srfrag[t[0]]->nodes[0]]->hardstart || srfrag[t[0]]->nodes[0] == srfrag[t[1]]->nodes[0]) &&
(!no2gnode[srfrag[t[0]]->nodes.Last()]->hardend || srfrag[t[0]]->nodes.Last() == srfrag[t[1]]->nodes.Last())) {
if(len[1]<ssdist && len[3]<ssdist) {
keeptrf[t2].cov+=srfrag[t1]->abundance;
keeptrf[t2].group.Add(t1);
included=true;
//fprintf(stderr,"trf %d is intronic including %d\n",t[1],t[0]);
}
}
//}
break;
case 3: // t1 and t0 are compatible --> just look for the edges; t1 goes further apart
if(srfrag[t[0]]->nodes[0]!=srfrag[t[1]]->nodes[0] && srfrag[t[0]]->nodes.Last()!=srfrag[t[1]]->nodes.Last() &&
((no2gnode[srfrag[t[0]]->nodes[0]]->hardstart && !no2gnode[srfrag[t[1]]->nodes[0]]->hardstart &&
!no2gnode[srfrag[t[0]]->nodes.Last()]->hardend && no2gnode[srfrag[t[1]]->nodes.Last()]->hardend) ||
(!no2gnode[srfrag[t[0]]->nodes[0]]->hardstart && no2gnode[srfrag[t[1]]->nodes[0]]->hardstart &&
no2gnode[srfrag[t[0]]->nodes.Last()]->hardend && !no2gnode[srfrag[t[1]]->nodes.Last()]->hardend))) {
// these two transcripts both have one good start and one different --> keep them both (different option would be to add them to another srfrag that is compatible and has both hardends but then it's more complicated
break;
}
// I keep both if both are guides
//if((!srfrag[t[0]]->guide || !srfrag[t[1]]->guide) && abs(len[0])<edgedist && abs(len[2])<edgedist) { // close by
if((!srfrag[t[0]]->guide || !srfrag[t[1]]->guide) && len[0]<edgedist && len[2]<edgedist) { // close by
if(srfrag[t[0]]->guide || (!srfrag[t[1]]->guide && no2gnode[srfrag[t[0]]->nodes[0]]->hardstart && no2gnode[srfrag[t[0]]->nodes.Last()]->hardend))
keeptrf[t2].t=t1; // t[0] to replace t[1]
keeptrf[t2].cov+=srfrag[t1]->abundance;
keeptrf[t2].group.Add(t1);
included=true;
//fprintf(stderr,"trf %d %d equivalent start/ends\n",t[1],t[0]);
}
break;
}
if(included) break; // break from for loop
}
}
if(!included){
if(srfrag[t1]->guide || ((srfrag[t1]->longstart || no2gnode[srfrag[t1]->nodes[0]]->hardstart)&&
(srfrag[t1]->longend || no2gnode[srfrag[t1]->nodes.Last()]->hardend))) { // if this is not included and has correct start/end
CLongTrf kt(t1,srfrag[t1]->abundance);
keeptrf.Add(kt);
keeptrf.Last().group.Add(t1);
//fprintf(stderr,"keep srfrag %d\n",t1);
}
else { // incomplete transcript, possibly wrong
srfrag[t1]->weak=1;
//fprintf(stderr,"Incomplete transcript %d\n",t1);
}
}
}
}
//GBitVec guidesource(gno);
//GBitVec guidesink(gno);
//for(int i=0;i<keeptrf.Count();i++) {
for(int i=keeptrf.Count()-1;i>=0;i--) { // I add the kept transcripts to trflong from least significant to most in order to make deletion easier
//fprintf(stderr,"Build source/sink for srfrag %d\n",keeptrf[i].t);
int n1=srfrag[keeptrf[i].t]->nodes[0];
int n2=srfrag[keeptrf[i].t]->nodes.Last();
//if(hassource[n1]<0 || hassink[n2]<0) fprintf(stderr,"Build source/sink for srfrag %d\n",keeptrf[i].t);
if(!srfrag[keeptrf[i].t]->guide && ((!no2gnode[n1]->hardstart && (hassource[n1]<0 || !keepsource[n1])) ||
(!no2gnode[n2]->hardend && (hassink[n2]<0 || !keepsink[n2])))) {
//if((no2gnode[n1]->hardstart || (hassource[n1]>=0 && keepsource[n1])) && (no2gnode[n2]->hardend ||(hassink[n2]>=0 && keepsink[n2]))) {
srfrag[keeptrf[i].t]->usepath=-2-ntrf; // order of transfrag
//fprintf(stderr,"keeptrf[%d].t=%d srfrag.usepath=%d\n",i,keeptrf[i].t,t);
ntrf++;
//trflong.Add(keeptrf[i].t);
}
/******* previous implementation here
addsource[n1]=keeptrf[i].cov;
addsink[n2]=keeptrf[i].cov;
*******/
/*
if(!addsource[n1] && hassource[n1]<0) {
int startpos=no2gnode[n1]->start-refstart;
if(startpos-CHI_THR<0 || startpos+CHI_THR>bpcov->Count()) addsource[n1]=1;
else {
addsource[n1]=(get_cov(1,startpos,startpos+CHI_THR-1,bpcov)-get_cov(2-2*s,startpos,startpos+CHI_THR-1,bpcov)-
get_cov(1,startpos-CHI_THR,startpos-1,bpcov)+get_cov(2-2*s,startpos-CHI_THR,startpos-1,bpcov))/(DROP*CHI_THR);
}
}
if(!addsink[n2] && hassink[n1]<0) {
int endpos=no2gnode[n2]->end-refstart;
if(endpos-CHI_THR<0 || endpos+CHI_THR>bpcov->Count()-1) addsink[n2]=1;
else {
addsink[n2]=(get_cov(1,endpos-CHI_THR+1,endpos,bpcov)-get_cov(2-2*s,endpos-CHI_THR+1,endpos,bpcov)-
get_cov(1,endpos+1,endpos+CHI_THR,bpcov)+get_cov(2-2*s,endpos+1,endpos+CHI_THR,bpcov))/(DROP*CHI_THR);
}
}*/
// all
for(int j=0;j<keeptrf[i].group.Count();j++) {
if(n1==srfrag[keeptrf[i].group[j]]->nodes[0]) {
addsource[n1]+=srfrag[keeptrf[i].group[j]]->abundance;
//fprintf(stderr,"Add source t[%d]->cov=%f to node %d = %f\n",keeptrf[i].group[j],srfrag[keeptrf[i].group[j]]->abundance,n1,addsource[n1]);
}
if(n2==srfrag[keeptrf[i].group[j]]->nodes.Last()) {
addsink[n2]+=srfrag[keeptrf[i].group[j]]->abundance;
//fprintf(stderr,"Add sink t[%d]->cov=%f to node %d = %f\n",keeptrf[i].group[j],srfrag[keeptrf[i].group[j]]->abundance,n2,addsink[n2]);
}
}
}
for(int i=keeptrf.Count()-1;i>=0;i--) {
int n1=srfrag[keeptrf[i].t]->nodes[0];
int n2=srfrag[keeptrf[i].t]->nodes.Last();
if(srfrag[keeptrf[i].t]->guide || ((no2gnode[n1]->hardstart || (hassource[n1]>=0 && keepsource[n1])) &&
(no2gnode[n2]->hardend ||(hassink[n2]>=0 && keepsink[n2])))) {
//trflong.Add(keeptrf[i].t);
srfrag[keeptrf[i].t]->usepath=-2-ntrf; // mark transfrag that it needs to be part of trflong
ntrf++;
}
}
/*
{ // DEBUG ONLY
fprintf(stderr,"%d keeptrf:\n",keeptrf.Count());
for(int i=0;i<keeptrf.Count();i++) {
fprintf(stderr,"(%d) %d abund=%f keepcov=%f",i,keeptrf[i].t,srfrag[keeptrf[i].t]->abundance,keeptrf[i].cov);
for(int j=0;j<srfrag[keeptrf[i].t]->nodes.Count();j++) {
fprintf(stderr," %d",srfrag[keeptrf[i].t]->nodes[j]);
}
fprintf(stderr,"\n");
}
fprintf(stderr,"%d trflong:",trflong.Count());
for(int i=0;i<trflong.Count();i++)
fprintf(stderr," %d",trflong[i]);
fprintf(stderr,"\n");
}
*/
// add source/sink connections
for(int i=1;i<gno-1;i++) {
//fprintf(stderr,"i=%d hassource=%d addsource=%f hassink=%d addsink=%f hardstart=%d hardend=%d\n",i,hassource[i],addsource[i],hassink[i],addsink[i],no2gnode[i]->hardstart,no2gnode[i]->hardend);
if(hassource[i]<0) {
if(addsource[i] && no2gnode[i]->hardstart) {
/*float abund=trthr;
if(no2gnode[i]->hardstart) { // node i doesn't have source as parent but it should
abund=addsource[i];
}*/
// else I am not that confident this is a start
no2gnode[i]->parent.Insert(0,zero);
no2gnode[0]->child.Add(i);
GVec<int> nodes;
nodes.Add(source);
nodes.Add(i);
//CTransfrag *t=new CTransfrag(nodes,allpat,abund);
CTransfrag *t=new CTransfrag(nodes,allpat,addsource[i]);
t->pattern[source]=1;
t->pattern[i]=1;
t->longread=true; /// this is only true for longreads;
transfrag.Add(t);
//fprintf(stderr,"Add link to source: 0-%d with abundance=%f\n",i, addsource[i]);
}
}
else {
/*if(keepsource[i]) {
srfrag[hassource[i]]->abundance+=addsource[i];
}*/
if(!keepsource[i]) { // it was a mistake to link this to source --> remove
/*fprintf(stderr,"delete abundance of trf:");
for(int j=0;j<srfrag[hassource[i]]->nodes.Count();j++) fprintf(stderr," %d",srfrag[hassource[i]]->nodes[j]);fprintf(stderr,"\n");*/
srfrag[hassource[i]]->abundance=0;
}
else { // this one has source and it should be kept => update trf abundance to a more realistic value
//fprintf(stderr,"source %d:%d abund=%f addsource=%f\n",i,no2gnode[i]->start,srfrag[hassource[i]]->abundance,addsource[i]);
//if(guidesource[i] && srfrag[hassource[i]]->abundance<addsource[i])
srfrag[hassource[i]]->abundance=addsource[i];
}
}
if(hassink[i]<0) {
if(addsink[i] && no2gnode[i]->hardend) {
/*float abund=trthr;
if(no2gnode[i]->hardend) {
abund=addsink[i];
}*/
// else not very confident about this end
no2gnode[i]->child.Add(sink);
no2gnode[sink]->parent.Add(i);
GVec<int> nodes;
nodes.Add(i);
nodes.Add(sink);
CTransfrag *t=new CTransfrag(nodes,allpat,addsink[i]);
t->pattern[sink]=1;
t->pattern[i]=1;
t->longread=true; //// this is only true for longreads
transfrag.Add(t);
//fprintf(stderr,"Add link to sink: %d-%d with abundance=%f\n",i,sink,addsink[i]);
}
}
else {
if(!keepsink[i]) { // it was a mistake to link this to sink --> remove
/*fprintf(stderr,"delete abundance of trf:");
for(int j=0;j<srfrag[hassink[i]]->nodes.Count();j++) fprintf(stderr," %d",srfrag[hassink[i]]->nodes[j]);fprintf(stderr,"\n");*/
srfrag[hassink[i]]->abundance=0;
}
else {
//fprintf(stderr,"sink %d:%d abund=%f addsink=%f\n",i,no2gnode[i]->end,srfrag[hassink[i]]->abundance,addsink[i]);
//if(guidesink[i] && srfrag[hassink[i]]->abundance<addsink[i])
srfrag[hassink[i]]->abundance=addsink[i];
}
/*if(keepsink[i]) {
//fprintf(stderr,"Add %f to longtransfrag=%d\n",addsink[i],hassink[i]);
srfrag[hassink[i]]->abundance+=addsink[i];
}*/
}
}
//fprintf(stderr,"There should be %d trflong transcripts\n",ntrf);
trflong.Resize(ntrf,-1);
}
// add edges between disconnected parent-child nodes
for(int t=0;t<transfrag.Count();t++) allpat=allpat | transfrag[t]->pattern;
for(int i=1;i<gno-1;i++) { // for all nodes check if there is a connection to child
CGraphnode *n=no2gnode[i];
for(int c=0;c<n->child.Count();c++) {
int *pos=gpos[edge(i,n->child[c],gno)];
if(pos && !allpat[*pos]) {
GVec<int> nodes;
nodes.Add(i);
nodes.Add(n->child[c]);
GBitVec trpat(gno+edgeno);
trpat[i]=1;
trpat[n->child[c]]=1;
trpat[*pos]=1;
CTransfrag *t=new CTransfrag(nodes,trpat,trthr);
if(longreads) t->longread=true;
transfrag.Add(t);
}
}
}
// sort transfrag with smallest being the one that has the most nodes, and ties are decided by the abundance (largest abundance first); last transfrags all have 1 node
if(trsort)
transfrag.Sort(trCmp);
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"There are %d transfrags that remained\n",transfrag.Count());
}
*/
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"\nThere are %d transfrags after sorting:\n",transfrag.Count());
for(int i=0;i<transfrag.Count();i++) {
fprintf(stderr,"transfrag[%d]:",i);
for(int j=0;j<transfrag[i]->nodes.Count();j++) fprintf(stderr," %d",transfrag[i]->nodes[j]);
fprintf(stderr," abundance=%f usepath=%.1f\n",transfrag[i]->abundance,transfrag[i]->usepath);
}
}
*/
GVec<int> incompletetrf; //remembers incomplete transfrags (the ones that don't have edges between two consecutive nodes
// create compatibilities
for(int t1=0;t1<transfrag.Count();t1++) { // transfrags are processed in increasing order -> important for the later considerations
// update nodes
int n1=transfrag[t1]->nodes.Count();
if(mixedMode) {
if(transfrag[t1]->usepath<-1) { // this is a mixedMode long transfrag (TODO: consider using this for longreads mode also)
//fprintf(stderr,"Add transcript %d to trflong with value %d\n",t1,(int)transfrag[t1]->usepath);
trflong[abs(2+(int)transfrag[t1]->usepath)]=t1;
}
//transfrag[t1]->usepath=-1; // restore order
transfrag[t1]->usepath=transfrag[t1]->abundance; // store abundance for later
}
if(n1>1) { // add transfrag to nodes' in and out; if a transfrag only has one node then it is not added to a node; I might want to change this for the computation of fpkm's
bool incomplete = false;
bool nosplice=true; // try to give less priority to unspliced reads vs spliced reads
for(int n=0;n<n1;n++) { // for all nodes in transfrag
if(nosplice && n) { // reduce abundance of continuous transfrags
if(transfrag[t1]->nodes[n]!=1+transfrag[t1]->nodes[n-1] || no2gnode[transfrag[t1]->nodes[n]]->start-1!=no2gnode[transfrag[t1]->nodes[n-1]]->end) {
nosplice=false;
}
}
if(n && n<transfrag[t1]->nodes.Count()-1) {// not first or last node
// add t1 to in and out of node
no2gnode[transfrag[t1]->nodes[n]]->trf.Add(t1);
if(transfrag[t1]->nodes[n-1] && transfrag[t1]->nodes[n]<gno-1) {
// check if transfrag t1 is incomplete between node[n-1] and node [n]
int *pos=gpos[edge(transfrag[t1]->nodes[n-1],transfrag[t1]->nodes[n],gno)];
if(!pos || !transfrag[t1]->pattern[*pos]) // there is no edge between node[n-1] and node[n]
incomplete = assign_incomplete_trf_to_nodes(t1,transfrag[t1]->nodes[n-1],transfrag[t1]->nodes[n],no2gnode) or incomplete; // this ensures that I still have compatibilities when going through a certain path: !!! THIS IS NEW COMPARED TO PERL
}
}
else if(n) { // last but not first node
// add t1 to in of node
no2gnode[transfrag[t1]->nodes[n]]->trf.Add(t1);
if(transfrag[t1]->nodes[n-1] && transfrag[t1]->nodes[n]<gno-1) {
// check if transfrag t1 is incomplete between node[n-1] and node [n]
int *pos=gpos[edge(transfrag[t1]->nodes[n-1],transfrag[t1]->nodes[n],gno)];
if(!pos || !transfrag[t1]->pattern[*pos]) // there is no edge between node[n-1] and node[n]
incomplete = assign_incomplete_trf_to_nodes(t1,transfrag[t1]->nodes[n-1],transfrag[t1]->nodes[n],no2gnode) or incomplete; // this ensures that I still have compatibilities when going through a certain path: !!! THIS IS NEW COMPARED TO PERL
}
}
else { // first node -> only add transfrag to out of node
no2gnode[transfrag[t1]->nodes[n]]->trf.Add(t1);
}
}
//if(nosplice) transfrag[t1]->abundance*=(1-isofrac);
//transfrag[t1]->abundance*=0.5;
if(incomplete) incompletetrf.Add(t1);
else transfrag[t1]->real=true;
}
//else if(longreads) no2gnode[n1]->trf.Add(t1);
/*
else { // this transcript is included completely in node
no2gnode[transfrag[t1]->nodes[0]]->frag+=transfrag[t1]->abundance;
}
*/
} // end for(int t1=0;t1<transfrag.Count();t1++)
if(srfrag.Count() && !mixedMode) {
srfrag.Sort(trCmp); // always start with largest super-read to solve
for(int u=0;u<srfrag.Count();u++) //process_srfrag(srfrag[u],transfrag,no2gnode,gno,gpos);
if(!srfrag[u]->abundance) srfrag[u]->abundance=srfrag[u]->srabund*ERROR_PERC;
}
// set source-to-child transfrag abundances: optional in order not to keep these abundances too low:
// update the abundances of the transfrags coming in from source and going to a node that doesn't have other parents than source
// * this part was removed to improve performance
CGraphnode *source=no2gnode[0];
for(int i=0;i<source->child.Count();i++) {
float abundance=0;
int t0=-1;
if(no2gnode[source->child[i]]->parent.Count()==1 && !no2gnode[source->child[i]]->parent[0]) { // source is the only parent of node
for(int j=0;j<no2gnode[source->child[i]]->trf.Count();j++) {
int t=no2gnode[source->child[i]]->trf[j];
if(transfrag[t]->nodes.Last()==source->child[i]) t0=t;
else abundance+=transfrag[t]->abundance;
}
if(t0>-1 && transfrag[t0]->abundance) { // found transfrag from source to node and the transfrag wasn't deleted
transfrag[t0]->abundance=abundance;
}
}
}
// */
for(int t=0;t<incompletetrf.Count();t++)
transfrag[incompletetrf[t]]->real=trf_real(incompletetrf[t],no2gnode,transfrag,gpos,gno);
}
void process_merge_transfrags(int gno,GPVec<CGraphnode>& no2gnode, GPVec<CMTransfrag>& mgt,GBitVec& compatible,GIntHash<int> &gpos) {
// sort transfrag with smallest being the one that has the most nodes
mgt.Sort(mgtrnodeCmp);
for(int t1=1;t1<mgt.Count();t1++)
for(int t2=0;t2<t1;t2++) {
if(!mgt[t1]->transfrag->real &&
((mgt[t2]->transfrag->pattern & mgt[t1]->transfrag->pattern) == mgt[t1]->transfrag->pattern)) { // t1 is included in t2, and it's not a guide
mgt[t2]->read.Add(mgt[t1]->read);
mgt[t2]->transfrag->abundance+=mgt[t1]->transfrag->abundance;
mgt.Exchange(t1,mgt.Count()-1);
mgt.Delete(mgt.Count()-1);
}
}
mgt.Sort(mgtrabundCmp); // sort transfrags from the most abundant to the least, with guides coming in first
// create compatibilities
for(int t1=0;t1<mgt.Count();t1++) { // transfrags are processed in increasing order -> important for the later considerations
// update nodes
int n1=mgt[t1]->transfrag->nodes.Count();
for(int n=0;n<n1;n++) { // for all nodes in transfrag
no2gnode[mgt[t1]->transfrag->nodes[n]]->trf.Add(t1);
}
// set compatibilities
// add t1 to t1 compatibility
bool comp=true;
compatible[comptbl_pos(t1,t1,mgt.Count())]=1;
for(int t2=t1+1;t2<mgt.Count();t2++) {
// here check compatibility between t1 and t2;
int n2=mgt[t2]->transfrag->nodes.Count();
int i1=0;
int i2=0;
comp=true;
while(i1<n1 && i2<n2) {
if(mgt[t1]->transfrag->nodes[i1]==mgt[t2]->transfrag->nodes[i2]) {
if(i1==n1-1 || i2==n2-1) { // one transcript finishes -> no need to check anymore
i1=n1;i2=n2;
}
else { // advance the smallest one
if(mgt[t1]->transfrag->nodes[i1+1]<mgt[t2]->transfrag->nodes[i2+1]) i1++;
else i2++;
}
}
else if(mgt[t1]->transfrag->nodes[i1]<mgt[t2]->transfrag->nodes[i2]) {
i1++;
if(conflict(i1,mgt[t2]->transfrag->nodes[i2],mgt[t1]->transfrag->nodes,n1,no2gnode,mgt[t1]->transfrag->pattern,gno,gpos)) {
comp=false;
break;
}
}
else {
i2++;
if(conflict(i2,mgt[t1]->transfrag->nodes[i1],mgt[t2]->transfrag->nodes,n2,no2gnode,mgt[t2]->transfrag->pattern,gno,gpos)) {
comp=false;
break;
}
}
}
if(comp) compatible[comptbl_pos(t1,t2,mgt.Count())]=1;
} // end for(int t2=t1+1;t2<transfrag.Count();t2++)
} // end for(int t1=0;t1<transfrag.Count();t1++)
}
void extend_path_left(int n, int gno, GVec<int>& keept, GBitVec &unionpat,GPVec<CGraphnode>& no2gnode,
GPVec<CMTransfrag>& mgt,GIntHash<int> &gpos,GVec<int>& leftpath) {
CGraphnode *node=no2gnode[n];
int maxp=-1;
float maxabund=0;
/*
{ // DEBUG ONLY
fprintf(stderr," continue left node %d with %d parents and %d compatible transcripts:",n,node->parent.Count(),keept.Count());
//for(int i=0;i<keept.Count();i++) fprintf(stderr," %d",keept[i]);
fprintf(stderr,"\n");
}
*/
// this version takes the most abundant path only
for(int i=0;i<node->parent.Count();i++) {
int p=node->parent[i];
if(p) { // parent not source
if(unionpat[p]) { // there might be transcripts on the path: this will not be true for fuzzy continuations
float sumabund=0;
for(int t=0;t<keept.Count();t++) if(mgt[keept[t]]->transfrag->pattern[p]) { // parent is on transcript
if(mgt[keept[t]]->transfrag->nodes[mgt[keept[t]]->nl]==p) {
sumabund+=mgt[keept[t]]->transfrag->abundance;
}
else {
int *pos=gpos[edge(p,n,gno)];
if(pos && mgt[keept[t]]->transfrag->pattern[*pos]) {
sumabund+=mgt[keept[t]]->transfrag->abundance;
}
}
}
//else if(mgt[keept[t]]->transfrag->nodes.Last()<p) sumabund+=mgt[keept[t]]->transfrag->abundance; this transcript shouldn't contribute to the path chosen
if(sumabund>maxabund) {
maxabund=sumabund;
maxp=p;
}
}
}
}
if(maxp>-1) { // I found a non-fuzzy way to continue
GVec<int> ekeept; // extend keept;
for(int t=0;t<keept.Count();t++) {
if(mgt[keept[t]]->transfrag->pattern[maxp]) { // parent is on transcript
if(mgt[keept[t]]->transfrag->nodes[mgt[keept[t]]->nl]==maxp) ekeept.Add(keept[t]);
else {
int *pos=gpos[edge(maxp,n,gno)];
if(pos && mgt[keept[t]]->transfrag->pattern[*pos]) ekeept.Add(keept[t]);
}
}
else if(mgt[keept[t]]->transfrag->nodes.Last()<maxp) ekeept.Add(keept[t]); // keep upstream transcript just in case it might turn useful
else if(mgt[keept[t]]->transfrag->nodes[0]<=maxp && mgt[keept[t]]->transfrag->nodes[mgt[keept[t]]->nf]>maxp){ // the transcript is fuzzy
ekeept.Add(keept[t]);
}
}
if(ekeept.Count()) { // if I can extend path
leftpath.Add(maxp);
extend_path_left(maxp,gno,ekeept,unionpat,no2gnode,mgt,gpos,leftpath);
}
}
else { // the path either stops here or it's fuzzy
int min=n;
GVec<int> path;
for(int t=0;t<keept.Count();t++) { // we need to check if transcripts are fuzzy because they might end further upstream
if(mgt[keept[t]]->transfrag->nodes[mgt[keept[t]]->nf] >= n && mgt[keept[t]]->transfrag->nodes[0]<min) { // transcript is fuzzy and starts before min
for(int j=0;j<mgt[keept[t]]->transfrag->nodes.Count();j++) {
if(mgt[keept[t]]->transfrag->nodes[j]==min) break;
path.Add(mgt[keept[t]]->transfrag->nodes[j]);
}
min=mgt[keept[t]]->transfrag->nodes[0];
}
}
for(int i=path.Count()-1;i>=0;i--) leftpath.Add(path[i]);
}
}
CPrediction* store_merge_prediction(GVec<int>& alltr,GPVec<CMTransfrag>& mgt,GVec<int>& path,
GPVec<CGraphnode>& no2gnode,int strand,int& geneno,bool& first,GList<CReadAln>& readlist,GPVec<GffObj>& guides) {
/*
{ // DEBUG ONLY
fprintf(stderr," store prediction:");
for(int i=0;i<path.Count();i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"\n");
}
*/
GffObj *t=NULL;
GStr name("",128);
// first compute coverage
float cov=0;
for(int i=0;i<alltr.Count();i++) {
int a=alltr[i];
cov+=mgt[alltr[i]]->transfrag->abundance;
mgt[alltr[i]]->transfrag->abundance=0;
if(enableNames || (alltr.Count()==1 && mgt[alltr[0]]->transfrag->real)) for(int j=0;j<mgt[a]->read.Count();j++) {
int r=mgt[a]->read[j];
if(readlist[r]->tinfo->g == -1) {
int fidx=1+readlist[r]->tinfo->fileidx;
//GStr fid(fidx);
if(!name.is_empty()) {
name+=", ";
}
name+=fidx;
name+=':';
name+=readlist[r]->tinfo->name;
}
else {
t=guides[readlist[r]->tinfo->g];
if(!enableNames) break;
}
}
}
int len=0;
CGraphnode *prevnode=NULL;
GVec<GSeg> exons;
bool firstex=true;
for(int i=0;i<path.Count();i++) {
CGraphnode *node=no2gnode[path[i]];
uint nodestart=node->start;
uint nodeend=node->end;
if(!prevnode || firstex || node->start>prevnode->end+1) { // this is a new exon
GSeg exon(nodestart,nodeend);
exons.Add(exon);
firstex=false;
}
else if(!firstex) exons.Last().end=nodeend;
len+=nodeend-nodestart+1;
prevnode=node;
}
char sign='-';
if(strand) { sign='+';}
if(first) { geneno++;}
CPrediction *p=new CPrediction(geneno-1, t, exons[0].start, exons.Last().end, cov, sign, len);
p->exons=exons;
if(enableNames) p->mergename=name;
first=false;
return(p);
}
// used in merge_transfrags
CPrediction* store_merge_prediction(float cov,GVec<int>& alltr,GPVec<CMTransfrag>& mgt,GVec<int>& path,
GPVec<CGraphnode>& no2gnode,int strand,int& geneno,bool& first,GList<CReadAln>& readlist,GPVec<GffObj>& guides, int g) {
/*
{ // DEBUG ONLY
fprintf(stderr," store prediction with cov=%f:",cov);
for(int i=0;i<path.Count();i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"\n");
}
*/
GffObj *t=NULL;
if(g>-1) t=guides[g];
GStr name("", 128);
if(enableNames) for(int i=0;i<alltr.Count();i++) {
int a=alltr[i];
for(int j=0;j<mgt[a]->read.Count();j++) {
int r=mgt[a]->read[j];
if(!name.is_empty()) {
name+=", ";
}
if(readlist[r]->tinfo->g == -1) {
int fidx=1+readlist[r]->tinfo->fileidx;
//GStr fid(fidx);
name+=fidx;
name+=':';
name+=readlist[r]->tinfo->name;
}
else {
name+=t->getID();
}
}
}
int len=0;
CGraphnode *prevnode=NULL;
GVec<GSeg> exons;
bool firstex=true;
for(int i=0;i<path.Count();i++) {
CGraphnode *node=no2gnode[path[i]];
uint nodestart=node->start;
uint nodeend=node->end;
if(!prevnode || firstex || node->start>prevnode->end+1) { // this is a new exon
GSeg exon(nodestart,nodeend);
exons.Add(exon);
firstex=false;
}
else if(!firstex) exons.Last().end=nodeend;
len+=nodeend-nodestart+1;
prevnode=node;
}
char sign='-';
if(strand) { sign='+';}
if(first) { geneno++;}
CPrediction *p=new CPrediction(geneno-1, t, exons[0].start, exons.Last().end, cov/len, sign, len);
p->exons=exons;
if(enableNames) p->mergename=name;
first=false;
return(p);
}
bool bfs(int n,GVec<float> *capacity,GVec<float> *flow,GVec<int> *link,GVec<int>& pred) {
GVec<int> color;
color.Resize(n+2);
int head=0;
int tail=0;
GVec<int> q;
// enque 0 (source)
q.cAdd(0);
tail++;
color[0]=1;
pred[0]=-1;
while(head!=tail) {
// deque
int u=q[head];
head++;
color[u]=2;
//for(int v=0;v<link[u].Count();v++)
for(int v=link[u].Count()-1;v>=0;v--) // do this so longer transcripts would have higher priority (be considered first)
if(!color[link[u][v]] && capacity[u][link[u][v]]-flow[u][link[u][v]]>epsilon) {
// enque v
q.Add(link[u][v]);
tail++;
color[link[u][v]]=1;
pred[link[u][v]]=u;
}
}
return(color[n-1]==2);
}
int mpredCmp(const pointer p1, const pointer p2) {
CMPrediction *a=(CMPrediction*)p1;
CMPrediction *b=(CMPrediction*)p2;
if(a->p->exons.Count() < b->p->exons.Count()) return 1; // more exons come first
if(a->p->exons.Count() > b->p->exons.Count()) return -1;
if(a->p->t_eq==NULL && b->p->t_eq!=NULL) return 1; // known gene come first
if(a->p->t_eq!=NULL && b->p->t_eq==NULL) return -1;
if(a->p->cov < b->p->cov) return 1; // more coverage come first
if(a->p->cov > b->p->cov) return -1;
// add something that guarantees same order
if(a->p->start < b->p->start) return -1; // order based on start
if(a->p->start > b->p->start) return 1;
// same start
// same number of exons
int i=0;
uint a1=0;
uint b1=0;
while(i<a->p->exons.Count()) {
if(a->p->exons[i].start<b->p->exons[i].start) {
a1=a->p->exons[i].start;
b1=b->p->exons[i].start;
break;
}
if(a->p->exons[i].end<b->p->exons[i].end) {
a1=a->p->exons[i].end;
b1=b->p->exons[i].end;
break;
}
i++;
}
if(a1) {
if(a1<b1) return -1; // the one with the first exon comes first
if(a1>b1) return 1;
}
return 0;
}
bool merge_onpath(CTransfrag *t,int nf, int nl,GBitVec& pathpattern,int mini,int maxi,GPVec<CGraphnode>& no2gnode,int gno,
GIntHash<int>& gpos) {
if(t->nodes[nf]<mini) // mini can be reached through transcript
if(!no2gnode[mini]->parentpat[t->nodes[nf]]) return false;
if(t->nodes[nl]>maxi) // from maxi I can reach end of transcript
if(!no2gnode[maxi]->childpat[t->nodes[nl]]) return false;
int first=1;
for(int i=nf;i<=nl;i++) {
if(t->nodes[i]>=mini && t->nodes[i]<=maxi) {
if(!pathpattern[t->nodes[i]]) return false;
int *pos=NULL;
if(i>nf) pos=gpos[edge(t->nodes[i-1],t->nodes[i],gno)];
if(first) {
first=0;
if(pos && t->nodes[i]>mini && t->pattern[*pos])
return false;
if(i>nf && !no2gnode[mini]->parentpat[t->nodes[i-1]]) return false; // I can not reach mini from previous node in transfrag
}
else if(pos && t->pattern[*pos] && !pathpattern[*pos]) return false;
}
if(t->nodes[i]>maxi) {
int *pos=NULL;
if(i>nf) pos=gpos[edge(t->nodes[i-1],t->nodes[i],gno)];
if(pos && t->nodes[i-1]<maxi && t->pattern[*pos])
return false;
if(!no2gnode[maxi]->childpat[t->nodes[i]]) return false; // I can not reach this node from maxi
break;
}
}
return true;
}
bool merge_topath(CTransfrag *t,int nf, int nl,GBitVec& pathpattern,int mini,int maxi,GPVec<CGraphnode>& no2gnode,int gno,
GIntHash<int>& gpos) {
int mint=nf; // first node on path
while(mint<=nl && !pathpattern[t->nodes[mint]]) mint++;
if(mint>nl) return false;
// weird possiblities:
// 1. path = ooo---ooo----
// t = ooooo----
//
// 2. path = ooooo---
// t = ooo---ooo---
bool firstone=false;
bool firsttwo=false;
if(mint>nf) { // first nodes in t are not on path
if(mini<t->nodes[nf]) { // check case 1
int i=mint;
while(i>nf) {
if(t->nodes[i-1]==t->nodes[i]-1 && no2gnode[t->nodes[i-1]]->end+1==no2gnode[t->nodes[i]]->start) i--;
else return false;
}
firstone=true;
}
else if(t->nodes[nf]<mini) { // check case 2
int i=t->nodes[mint];
while(i>mini) {
if(pathpattern[i-1] && no2gnode[i-1]->end+1==no2gnode[i]->start) i--;
else return false;
}
firsttwo=true;
}
}
int maxt=nl; // last node on path
while(maxt>mint && !pathpattern[t->nodes[maxt]]) maxt--;
// weird possiblities:
// 1. path = ---ooo----ooo
// t = ---ooooo
//
// 2. path = ---oooooo
// t = ---oooo----ooo
bool lastone=false;
bool lasttwo=false;
if(maxt<nl) { // last nodes in t are not on path
if(maxi>t->nodes[nl]) { // check case 1
int i=maxt;
while(i<nl) {
if(t->nodes[i]==t->nodes[i+1]-1 && no2gnode[t->nodes[i]]->end+1==no2gnode[t->nodes[i+1]]->start) i++;
else return false;
}
lastone=true;
}
else if(t->nodes[nl]>maxi) { // check case 2
int i=t->nodes[maxt];
while(i<maxi) {
if(pathpattern[i+1] && no2gnode[i]->end+1==no2gnode[i+1]->start) i++;
else return false;
}
lasttwo=true;
}
}
// check if all nodes and introns between mint and maxt are in pathpattern
for(int i=mint;i<maxt;i++) {
if(!pathpattern[t->nodes[i]]) return false;
int *pos=gpos[edge(t->nodes[i],t->nodes[i+1],gno)];
if(pos && t->pattern[*pos] && !pathpattern[*pos]) return false;
}
if(firstone) { // modify start of t
for(int i=nf;i<mint;i++) {
t->pattern[t->nodes[i]]=0;
int *pos=gpos[edge(t->nodes[i],t->nodes[i+1],gno)];
if(pos) t->pattern[*pos]=0;
}
}
else if(firsttwo) { // modify start of pathpattern
for(int i=mini;i<t->nodes[mint];i++) {
pathpattern[i]=0;
int *pos=gpos[edge(i,i+1,gno)];
if(pos) pathpattern[*pos]=0;
}
}
if(lastone) { // modify end of t
for(int i=maxt;i<nl;i++) {
t->pattern[t->nodes[i+1]]=0;
int *pos=gpos[edge(t->nodes[i],t->nodes[i+1],gno)];
if(pos) t->pattern[*pos]=0;
}
}
else if(lasttwo) { // modify start of pathpattern
for(int i=t->nodes[maxt];i<maxi;i++) {
pathpattern[i+1]=0;
int *pos=gpos[edge(i,i+1,gno)];
if(pos) pathpattern[*pos]=0;
}
}
return true;
}
void add_transfrag_to_path(int t,GBitVec& tforlater,int& ntforlater, GPVec<CMTransfrag>& mgt,GBitVec& pathpat,int& min,int &max,
GPVec<CGraphnode>& no2gnode,int gno,GIntHash<int>& gpos,GVec<int>& alltr,float &cov){
//if(merge_onpath(mgt[t]->transfrag,mgt[t]->nf,mgt[t]->nl,pathpat,min,max,no2gnode,gno,gpos)) { // I can add the transfrag if it's on path
if(merge_topath(mgt[t]->transfrag,mgt[t]->nf,mgt[t]->nl,pathpat,min,max,no2gnode,gno,gpos)) { // I can add the transfrag if it's on path
pathpat = pathpat | mgt[t]->transfrag->pattern;
cov+=mgt[t]->transfrag->abundance*mgt[t]->len;
mgt[t]->transfrag->abundance=0;
alltr.Add(t);
int prevmin=min;
int prevmax=max;
if(mgt[t]->transfrag->nodes[mgt[t]->nf]<min) min=mgt[t]->transfrag->nodes[mgt[t]->nf];
if(mgt[t]->transfrag->nodes[mgt[t]->nl]>max) max=mgt[t]->transfrag->nodes[mgt[t]->nl];
if(min<prevmin) {
int i=mgt[t]->nf;
while(ntforlater && mgt[t]->transfrag->nodes[i]<prevmin) { // for all nodes in transfrags that come before prevmin
CGraphnode *node=no2gnode[mgt[t]->transfrag->nodes[i]];
int nn=node->trf.Count();
for(int j=0;j<nn;j++){
int tj=node->trf[j];
if(tforlater[tj]) {
tforlater[tj]=0;
ntforlater--;
add_transfrag_to_path(tj,tforlater,ntforlater,mgt,pathpat,min,max,no2gnode,gno,gpos,alltr,cov);
}
}
i++;
}
}
if(mgt[t]->transfrag->nodes[mgt[t]->nl]>prevmax) { // my max could have been updated -> I do not need to check everything!
int i=mgt[t]->nl;
while(ntforlater && mgt[t]->transfrag->nodes[i]>prevmax) { // for all nodes in transfrags that come after prevmax
CGraphnode *node=no2gnode[mgt[t]->transfrag->nodes[i]];
int nn=node->trf.Count();
for(int j=0;j<nn;j++){
int tj=node->trf[j];
if(tforlater[tj]) {
tforlater[tj]=0;
ntforlater--;
add_transfrag_to_path(tj,tforlater,ntforlater,mgt,pathpat,min,max,no2gnode,gno,gpos,alltr,cov);
if(!ntforlater) break;
}
}
i--;
}
}
}
}
// compute overlap of a small prediction to a larger one with the same exon structure, except for intron retention
int compute_ovlp(CPrediction *small,CPrediction *big)
{
int len=0;
int i=0;
int ovp=0;
while(i<big->exons.Count() && !(ovp=small->exons[0].overlapLen(big->exons[i].start,big->exons[i].end))) i++;
if(ovp) { // if ovp is zero than there is no way I will find anything overlapping
len+=ovp;
ovp=0;
int j=big->exons.Count()-1;
while(j>i && !(ovp=small->exons.Last().overlapLen(big->exons[j].start,big->exons[j].end))) j--;
len+=ovp;
for(int k=i+1; k<j;k++) len+=big->exons[k].len();
}
return len;
}
bool has_retained_intron(CMPrediction &p1,CMPrediction &p2,int gno,GIntHash<int> &gpos) { // this assumes that p2.b & p1.b == p2.b
for(int i=1;i<p1.nodes.Count();i++) {
if(p2.pat[p1.nodes[i-1]] && p2.pat[p1.nodes[i]]) { // both nodes from p1 are also present in p2
int *pos=gpos[edge(p1.nodes[i-1],p1.nodes[i],gno)];
if(pos && p1.b[*pos] && !p2.b[*pos]) return true; // there is an intron from n[i-1] to n[i] in p1 but not in p2
}
}
return false;
}
bool overlaps_one_exon_only(CMPrediction &p1,CMPrediction &p2) { // this assumes that p2 has only one exon
bool exonovlp=false;
bool gap=false;
for(int i=0;i<p2.nodes.Count();i++) {
if(p1.pat[p2.nodes[i]]) { // node in p2 also in p1
if(gap) return false;
if(!exonovlp) exonovlp=true;
}
else if(exonovlp) gap=true;
}
return exonovlp;
}
int merge_transfrags(int gno,GPVec<CGraphnode>& no2gnode, GPVec<CMTransfrag>& mgt,GIntHash<int> &gpos,
int geneno,int strand,GList<CPrediction>& pred,GList<CReadAln>& readlist,GPVec<GffObj>& guides) {
mgt.Sort(mgtrabundCmp); // sort transfrags from the most abundant to the least, with guides coming in first
GVec<CMPrediction> localpred;
bool first=true;
// determine "fuzzy" starts and ends
int ng=0; // stores the number of guides
for(int t=0;t<mgt.Count();t++) {
mgt[t]->nf=0;
mgt[t]->nl=mgt[t]->transfrag->nodes.Count()-1;
if(mgt[t]->transfrag->real) { // this is a guide => it has no fuzzy endings
ng++;
GVec<int> alltr(1,t); // all transfrags used in creating path
int g=-1;
for(int j=0;j<mgt[t]->read.Count();j++) {
int r=mgt[t]->read[j];
if(readlist[r]->tinfo->g > -1) {
g=readlist[r]->tinfo->g;
break;
}
}
CPrediction *p=store_merge_prediction(mgt[t]->transfrag->abundance,alltr,mgt,mgt[t]->transfrag->nodes,no2gnode,strand,geneno,first,readlist,guides,g);
mgt[t]->transfrag->abundance=0; // by making it 0 we only consider extentions worth taking
CMPrediction mp(p,mgt[t]->transfrag->nodes,mgt[t]->transfrag->pattern,mgt[t]->transfrag->pattern);
for(int i=0;i<mgt[t]->transfrag->nodes.Count();i++) {
mp.b[mgt[t]->transfrag->nodes[i]]=0;
if(i && no2gnode[mgt[t]->transfrag->nodes[i]]->start==no2gnode[mgt[t]->transfrag->nodes[i-1]]->end+1) {
int *pos=gpos[edge(mgt[t]->transfrag->nodes[i-1],mgt[t]->transfrag->nodes[i],gno)];
if(pos) mp.b[*pos]=0;
}
}
localpred.Add(mp);
}
// add transfrag to node
no2gnode[mgt[t]->transfrag->nodes[mgt[t]->nf]]->trf.Add(t);
no2gnode[mgt[t]->transfrag->nodes[mgt[t]->nl]]->trf.Add(t);
}
// get compatibilities
for(int t1=0;t1<mgt.Count();t1++) if(mgt[t1]->transfrag->nodes[0] && mgt[t1]->transfrag->nodes.Last()<gno-1 && (mgt[t1]->transfrag->abundance || mgt[t1]->transfrag->real)) { // transfrags are processed in increasing order -> important for the later considerations
/*
{ // DEBUG ONLY
fprintf(stderr,"Start transcript %d(%d-%d) cov=%g ",t1,mgt[t1]->nf,mgt[t1]->nl,mgt[t1]->transfrag->abundance);
//if(mgt[t1]->transfrag->real) fprintf(stderr,"1 out of %d :",mgt.Count());
//else fprintf(stderr,"0 out of %d:",mgt.Count());
//for(int i=0;i<mgt[t1]->transfrag->nodes.Count();i++) fprintf(stderr," %d",mgt[t1]->transfrag->nodes[i]);
fprintf(stderr,"\n");
}
*/
GVec<int> alltr(1,t1);
GBitVec pathpat(mgt[t1]->transfrag->pattern);
float cov=mgt[t1]->transfrag->abundance*mgt[t1]->len;
mgt[t1]->transfrag->abundance=0;
GBitVec tforlater(mgt.Count());
int ntforlater=0;
int min=mgt[t1]->transfrag->nodes[mgt[t1]->nf];
int max=mgt[t1]->transfrag->nodes[mgt[t1]->nl];
int start=ng;
if(t1+1>ng) start=t1+1;
for(int t2=start;t2<mgt.Count();t2++) if(mgt[t2]->transfrag->nodes[0] && mgt[t2]->transfrag->nodes.Last()<gno-1 && mgt[t2]->transfrag->abundance) { // only if the transfrag wasn't used already
if(mgt[t2]->transfrag->nodes[mgt[t2]->nl]<min || mgt[t2]->transfrag->nodes[mgt[t2]->nf]>max) { tforlater[t2]=1; ntforlater++;}
else if((mgt[t2]->transfrag->pattern & pathpat) == mgt[t2]->transfrag->pattern) { // t2 is included in path seen so far
cov+=mgt[t2]->transfrag->abundance*mgt[t2]->len;
mgt[t2]->transfrag->abundance=0;
alltr.Add(t2);
}
else {
add_transfrag_to_path(t2,tforlater,ntforlater,mgt,pathpat,min,max,no2gnode,gno,gpos,alltr,cov);
}
} // end for(int t2=t1+1;t2<transfrag.Count();t2++)
/*
{ // DEBUG ONLY
fprintf(stderr,"min=%d max=%d pathpat=",min,max);
printBitVec(pathpat);
fprintf(stderr,"\n");
}
*/
if(!mgt[t1]->transfrag->real ||
(min<mgt[t1]->transfrag->nodes[mgt[t1]->nf]) || (max>mgt[t1]->transfrag->nodes[mgt[t1]->nl])) { // if transfrag is not real or is extending beyond the initial transfrag
GVec<int> printpath;
if(alltr.Count()==1) printpath=mgt[t1]->transfrag->nodes; // only initial transfrag is in path
else {
for(int i=0;i<alltr.Count();i++) {
int t=alltr[i];
if(mgt[t]->transfrag->nodes[0]<min) { // only fuzzy continuations here
int j=0;
while(mgt[t]->transfrag->nodes[j]<min) { pathpat[j]=1;j++;}
min=mgt[t]->transfrag->nodes[0];
}
if(mgt[t]->transfrag->nodes.Last()>max) { // only fuzzy continuations here
int j=mgt[t]->transfrag->nodes.Count()-1;
while(mgt[t]->transfrag->nodes[j]>max) { pathpat[j]=1;j--;}
max=mgt[t]->transfrag->nodes.Last();
}
}
for(int i=1;i<gno-1;i++) {
if(pathpat[i]) {
printpath.Add(i);
}
}
}
CPrediction *p=store_merge_prediction(cov,alltr,mgt,printpath,no2gnode,strand,geneno,first,readlist,guides,-1);
CMPrediction mp(p,printpath,pathpat,pathpat);
for(int i=0;i<printpath.Count();i++) {
mp.b[printpath[i]]=0;
if(i && no2gnode[printpath[i]]->start==no2gnode[printpath[i-1]]->end+1) {
int *pos=gpos[edge(printpath[i-1],printpath[i],gno)];
if(pos) mp.b[*pos]=0;
}
}
localpred.Add(mp);
}
} // end for(int t1=0;t1<transfrag.Count();t1++)
// process predictions
localpred.Sort(mpredCmp);
for(int i=localpred.Count()-1;i>=0;i--) {
/*
{ // DEBUG ONLY
fprintf(stderr,"Get ");
if(localpred[i].p->t_eq) fprintf(stderr,"guide ");
fprintf(stderr,"prediction %d %d-%d cov=%g ",i,localpred[i].p->start,localpred[i].p->end,localpred[i].p->cov);
//printBitVec(localpred[i].b);
fprintf(stderr,"\n");
}
*/
if(localpred[i].p->t_eq==NULL) { // if a guide -> just store it
for(int j=0;j<i;j++) if(localpred[j].p!=NULL && localpred[j].p->overlap(localpred[i].p)) {
bool remove=false;
if(localpred[j].p->exons.Count()==1) remove=true;
else {
if(localpred[i].p->exons.Count()==1) {
if(overlaps_one_exon_only(localpred[j],localpred[i])) remove=true;
else if(!retained_intron && localpred[i].p->cov<localpred[j].p->cov) remove=true;
}
else if((localpred[i].b & localpred[j].b) == localpred[i].b) {
if(has_retained_intron(localpred[j],localpred[i],gno,gpos)) {
if(!retained_intron && localpred[i].p->cov<localpred[j].p->cov) remove=true;
}
else remove=true;
}
}
if(remove) {
localpred[j].p->cov*=localpred[j].p->tlen; // I need to adjust coverage later
if(localpred[j].p->t_eq==NULL) {
if(localpred[i].p->start<localpred[j].p->start) {
localpred[j].p->tlen+=localpred[j].p->start-localpred[i].p->start;
localpred[j].p->start=localpred[i].p->start;
localpred[j].p->exons[0].start=localpred[i].p->exons[0].start;
}
if(localpred[i].p->end>localpred[j].p->end) {
localpred[j].p->tlen+=localpred[i].p->end-localpred[j].p->end;
localpred[j].p->end=localpred[i].p->end;
localpred[j].p->exons.Last().end=localpred[i].p->exons.Last().end;
}
}
// need to update weighted coverage here
int ovplen=compute_ovlp(localpred[i].p,localpred[j].p);
localpred[j].p->cov=(ovplen*localpred[i].p->cov+localpred[j].p->cov)/localpred[j].p->tlen;
localpred[i].p->cov=0;
break;
}
}
}
if(localpred[i].p->t_eq || localpred[i].p->cov) pred.Add(localpred[i].p);
else { // I have a prediction that needs to be cleaned up
delete localpred[i].p;
localpred[i].p=NULL;
}
}
return(geneno);
}
bool is_compatible(int t1,int t2, int n,GBitVec& compatible) {
if(t1<t2) return(compatible[comptbl_pos(t1,t2,n)]);
else return(compatible[comptbl_pos(t2,t1,n)]);
}
GVec<int> *max_compon_size_with_penalty(int trnumber,float &maxsize,GVec<CTrInfo>& set,GBitVec& compatible,
GBitVec& mark,GBitVec& removable, GHash<CComponent*>& computed) {
// this max_compon presumes the set is always sorted according to the set.trno
GVec<int> *result=NULL;
float penalty=0;
for(int i=0;i<set.Count();i++) {
float size=set[i].abundance-penalty;
float maxagreesize=0;
GVec<CTrInfo> agreeset;
GStr s("",64);
for(int j=i+1;j<set.Count();j++) {
if(compatible[comptbl_pos(set[i].trno,set[j].trno,trnumber)]) { // make sure that the transcripts in set are sorted to speed up things
agreeset.Add(set[j]);
s+=set[j].trno;
if(set[j].abundance) s+=' '; else s+='.';
if(set[j].penalty) s+=' ';else s+='.';
maxagreesize+=set[j].abundance;
}
else if(mark[set[j].trno]) { // set[j] is a special interest transfrag that I prefer keeping
if(removable[set[j].trno]) { // if I can remove set[j]
size-=set[j].penalty; // I need to pay a penalty for removing j
}
else { //# j is not removable -> I can't continue considering i
size=MIN_VAL;
break;
}
}
}
GVec<int> *agreeresult=NULL;
if(size>MIN_VAL && agreeset.Count() && (size+maxagreesize>maxsize)) {
CComponent *agreecomp=computed[s.chars()];
if(!agreecomp) {
float agreesize=MIN_VAL;
agreeresult=max_compon_size_with_penalty(trnumber,agreesize,agreeset,compatible,mark,removable,computed);
agreecomp=new CComponent(agreesize,agreeresult);
computed.Add(s.chars(),agreecomp);
}
else agreeresult=agreecomp->set;
size+=agreecomp->size;
}
if(size>maxsize) {
if(result) {
delete result;
}
result=new GVec<int>();
result->Add(set[i].trno);
if(agreeresult) result->Add(*agreeresult);
maxsize=size;
}
if(mark[set[i].trno]) { // set[i] is a special interest transfrag that I prefer keeping
if(removable[set[i].trno]) { // if I can remove set[i],
penalty+=set[i].penalty; // I need to pay a penalty for removing j
}
else break; //# i is not removable -> I can't continue considering the rest of the transcripts
}
}
return(result);
}
bool onpath_long(GBitVec& trpattern,GVec<int>& trnode,GBitVec& pathpattern,int minp,int maxp,GPVec<CGraphnode>& no2gnode,int gno,
GIntHash<int>& gpos) {
int j=0;
int *edgep=NULL;
int tn=trnode.Count();
edgep=gpos[edge(0,minp,gno)];
if(edgep && pathpattern[*edgep]) { // minp links to source
if(!trnode[0] && trnode[1]!=minp) return false;
else { // transfrag does not link to source
if(trnode[0]<minp) return false;
}
edgep=NULL;
}
edgep=gpos[edge(maxp,gno-1,gno)];
if(edgep && pathpattern[*edgep]) { // maxp links to sink
if(trnode.Last()==gno-1 && trnode[tn-2]!=maxp) return false;
else { // transfrag does not link to sink
if(trnode.Last()>maxp) return false;
}
edgep=NULL;
}
int prevp=-1;
int p=minp;
while(1) {
while(j<tn && trnode[j]<p) {
if(!prevp || (edgep && pathpattern[*edgep]) || p==gno-1) return false; // there is an edge between prevp<trnode[j] and p>trnode[j]; when prevp==0/gno-1 I might not have an edge there
if(!no2gnode[trnode[j]]->childpat[p]) {
//fprintf(stderr,"Node p=%d cannot be reached from node=%d\n",p,trnode[j]);
return false; // I can not reach p from trnode[j]
}
j++;
}
if(j==tn) return true; // went through transcript
// now trnode[j]>=p and trnode[j-1]<p
if(trnode[j]>p) {
if(!no2gnode[p]->childpat[trnode[j]]) return false; // I can not reach trnode[j] from p
int *edget=NULL;
if(j) edget=gpos[edge(trnode[j-1],trnode[j],gno)];
if(edget && trpattern[*edget]) return false; // there is an edge between trnode[j-1]<p and trnode[j]>p
}
else j++; // now trnode[j]>p and trnode[j-1]==prevp
if(p==maxp) return true; // went through full path
prevp=p;
p=pathpattern.find_next(prevp); // p is not -1 since prevp<maxp
edgep=gpos[edge(prevp,p,gno)];
}
return true;
}
bool onpath(GBitVec& trpattern,GVec<int>& trnode,GBitVec& pathpattern,int mini,int maxi,GPVec<CGraphnode>& no2gnode,int gno,
GIntHash<int>& gpos) {
if(trnode[0]<mini) // mini can be reached through transcript
if(!no2gnode[mini]->parentpat[trnode[0]]) return false;
if(trnode.Last()>maxi) // from maxi I can reach end of transcript
if(!no2gnode[maxi]->childpat[trnode.Last()]) return false;
int first=1;
for(int i=0;i<trnode.Count();i++) {
if(trnode[i]>=mini && trnode[i]<=maxi) {
if(!pathpattern[trnode[i]]) return false;
int *pos=NULL;
if(i) pos=gpos[edge(trnode[i-1],trnode[i],gno)];
if(first) {
first=0;
if(i && trnode[i]>mini && pos && trpattern[*pos])
return false;
if(i && !no2gnode[mini]->parentpat[trnode[i-1]]) return false; // I can not reach mini from previous node in transfrag
}
else if(i && pos && trpattern[*pos] && !pathpattern[*pos]) return false;
}
if(trnode[i]>maxi) {
int *pos=gpos[edge(trnode[i-1],trnode[i],gno)];
if(i && trnode[i-1]<maxi && pos && trpattern[*pos])
return false;
if(!no2gnode[maxi]->childpat[trnode[i]]) return false; // I can not reach this node from maxi
break;
}
}
return true;
}
void update_transcript_to_path_back(float abundance,GVec<int>& trnode,GVec<int>& path,GVec<float>& pathincov,
GVec<float>& pathoutcov) {
int lastnode=trnode.Last();
if(path[0]<trnode.Last()) // transcript ends at path[0]
lastnode=path[0];
if(trnode.Last()!=path.Last()) pathoutcov.Last()+=abundance;
for(int i=path.Count()-2;i>=0;i--) {
if(path[i]==lastnode) { // transcript ends at this node
pathincov[i]+=abundance;
break;
}
/* this case should never be true because the transcript can not start in the middle of the path
* else if(path[i]==trnode[0]) { // transcript starts at this node
pathoutcov[i]+=abundance;
}*/
else { // middle of the path
pathincov[i]+=abundance;
pathoutcov[i]+=abundance;
}
}
}
void update_transcript_to_path_fwd(float abundance,GVec<int>& trnode,GVec<int>& path,GVec<float>& pathincov,
GVec<float>& pathoutcov) {
if(trnode[0]!=path.Last()) pathincov.Last()+=abundance;
for(int i=path.Count()-2;i>=0;i--) {
if(path[i]==trnode[0]) { // transcript ends at this node
pathoutcov[i]+=abundance;
break;
}
/* this case should never be true because the transcript can not end in the middle of the path
* else if(path[i]==trnode.Last()) { // transcript starts at this node
pathincov[i]+=abundance;
}*/
else { // middle of the path
pathincov[i]+=abundance;
pathoutcov[i]+=abundance;
}
}
}
bool can_be_removed_back(float abundance,GBitVec& pattern,float& penalty,int lasttrnode,GVec<int>& path,GVec<float>& pathincov,GVec<float>& pathoutcov) { // this assumes the incomplete transcripts only add to the nodes they pass through
if(pattern[path.Last()] && pathoutcov.Last()-abundance<epsilon) { // transcript leaving the last added node to path is the only one
penalty=abundance;
return(false);
}
int lastnode=lasttrnode;
if(path[0]<lasttrnode) // added transcript ends at path[0]
lastnode=path[0];
if(path.Last()!=lasttrnode) { // transcript doesn't end at last node added to path
for(int i=path.Count()-2;i>=0;i--) {
if(path[i]==lastnode) { // transcript ends at this node
if(pattern[path[i]]) {
penalty=abundance;
if(pathincov[i]-abundance<epsilon) return(false);
}
break;
}
else // middle of the path
if(pattern[path[i]]) {
penalty=abundance;
if((pathincov[i]-abundance<epsilon) || (pathoutcov[i]-abundance<epsilon)) return(false);
}
}
}
return(true);
}
bool can_be_removed_fwd(float abundance,GBitVec& pattern, float& penalty, int firstnode,GVec<int>& path,GVec<float>& pathincov,
GVec<float>& pathoutcov) { // incomplete transcripts are all considered to go through their nodes
if(pattern[path.Last()] && pathincov.Last()-abundance<epsilon) {
penalty=abundance;
return(false); // transcript entering the last added node to path is the only one
}
if(path.Last()!=firstnode) { // transcript doesn't start at last node added to path -> this shouldn't happen since the transcript has already been added
for(int i=path.Count()-2;i>=0;i--) {
if(pattern[path[i]] && path[i]==firstnode) { // transcript starts at this node
penalty=abundance;
if(pathoutcov[i]-abundance<epsilon) {
return(false);
}
break;
}
else // middle of the path
if(pattern[path[i]]) {
penalty=abundance;
if((pathincov[i]-abundance<epsilon) || (pathoutcov[i]-abundance<epsilon)) {
return(false);
}
}
}
}
return(true);
}
void compute_weak(GPVec<CTransfrag>& transfrag,int t,GVec<float>& nodecov,GPVec<CGraphnode>& no2gnode) {
transfrag[t]->weak=0;
int n=1;
while(n<transfrag[t]->nodes.Count()) {
//if(inode->child[c]==i+1 && i<gno-2 && inode->end+1==cnode->start &&
// nodecov[i+1]/cnode->len() <1000 && nodecov[i]*(DROP+ERROR_PERC)>nodecov[i+1]) { // adjacent to child
if(transfrag[t]->nodes[n]==transfrag[t]->nodes[n-1]+1 &&
no2gnode[transfrag[t]->nodes[n-1]]->end+1==no2gnode[transfrag[t]->nodes[n]]->start &&
(nodecov[transfrag[t]->nodes[n-1]]*(DROP+ERROR_PERC)>nodecov[transfrag[t]->nodes[n]] ||
nodecov[transfrag[t]->nodes[n]]*(DROP+ERROR_PERC)>nodecov[transfrag[t]->nodes[n-1]])) {
transfrag[t]->weak=1;
break;
}
n++;
}
}
void replace_transfrag(int t,int& tmax,GPVec<CTransfrag>& transfrag,GVec<float>& nodecov,GPVec<CGraphnode>& no2gnode) {
if(tmax==-1) {
tmax=t;
if(transfrag[tmax]->weak<0) {
compute_weak(transfrag,tmax,nodecov,no2gnode);
}
}
else {
if(transfrag[t]->weak<0) {
compute_weak(transfrag,t,nodecov,no2gnode);
}
if(!transfrag[tmax]->weak) {
if(!transfrag[t]->weak && transfrag[t]->abundance>transfrag[tmax]->abundance) {
tmax=t;
}
}
else { // tmax is weak
if(!transfrag[t]->weak || transfrag[t]->abundance>transfrag[tmax]->abundance) tmax=t;
}
}
}
bool fwd_to_sink_fast_long(int i,GVec<int>& path,int& minpath,int& maxpath,GBitVec& pathpat,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecov,int gno,GIntHash<int>& gpos){
// find all parents -> if parent is source then go back
CGraphnode *inode=no2gnode[i];
if(i<maxpath && !inode->childpat[maxpath]) return false; // I can not reach maxpath from node
int nchildren=inode->child.Count(); // number of children
/*
fprintf(stderr,"Children of node %d with maxpath=%d are:",i,maxpath);
for(int c=0;c<nchildren;c++) fprintf(stderr," %d",inode->child[c]);
fprintf(stderr," pathpat=");
printBitVec(pathpat);
fprintf(stderr,"\n");
*/
if(!nchildren) return true; // node is sink
int maxc=-1;
/* I can not do this because then I don't check for continuity
if(nchildren==1) {
maxc=inode->child[0]; // only one child to consider
}
else {
*/
float maxcov=0;
int tmax=-1;
bool exclude=false;
int nextnode=0; // nextnode on path
bool reach=false;
if(maxpath<=i) reach=true;
//int maxchild=inode->child[0];
//float maxchildcov=-1;
if(pathpat[i+1]) {
maxc=i+1;
tmax=-1;
reach=true;
}
else {
for(int c=0;c<nchildren;c++) {
bool childonpath=false;
if(pathpat[inode->child[c]]) childonpath=true;
// check if child is already on the path
int *pos=gpos[edge(i,inode->child[c],gno)];
if(pos && pathpat[*pos]) {
maxc=inode->child[c];
tmax=-1;
reach=true;
break;
}
// check if I can reach nextnode from c
if(maxpath>i) { // actually maxpath is >= i+2 otherwise I wouldn't get here
if(!nextnode) {
int j=i+2;
while(j<=maxpath) {
if(pathpat[j]) {
nextnode=j;
break;
}
j++;
}
}
if(inode->child[c]!=nextnode && !no2gnode[inode->child[c]]->childpat[nextnode]) {
continue;
}
reach=true;
}
/*if(no2gnode[maxpath]->hardend && pathpat[gno-1]) { // this is a trflong transcript
if(!pathpat[c]) continue;
}*/
float childcov=0;
int tchild=-1;
int endpath=maxpath;
if(inode->child[c]>endpath) endpath=inode->child[c];
CGraphnode *cnode=no2gnode[inode->child[c]];
/*
if(nodecov[inode->child[c]]>maxchildcov) {
maxchildcov=nodecov[inode->child[c]];
maxchild=inode->child[c];
}
*/
if(inode->child[c]==i+1 && i<gno-2 && inode->end+1==cnode->start &&
nodecov[i+1]/cnode->len() <1000 && nodecov[i]*(DROP+ERROR_PERC)>nodecov[i+1]) { // adjacent to child
// cnode->len() this is redundant because i<gno-2
//((nodecov[i+1]/cnode->len() <1000 && nodecov[i]*DROP>nodecov[i+1]) || (cnode->len()<longintronanchor && cnode->child.Count()==1 && cnode->child[0]==gno-1 ) )) { // adjacent to child
exclude=true;
}
else {
pathpat[inode->child[c]]=1;
if(pos) pathpat[*pos]=1;
//else GError("Found parent-child: %d-%d not linked by edge!\n",i,inode->child[c]);
for(int j=0;j<cnode->trf.Count();j++) { // for all transfrags going through child
int t=cnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
if(!mixedMode) { cnode->trf.Delete(j); j--;}
else transfrag[t]->abundance=0;
}
else if(transfrag[t]->longread && transfrag[t]->nodes[0]) {
if(inode->child[c]==gno-1) { // child is sink
if(transfrag[t]->nodes[0]==i && maxpath<=i) { // need to check it doesn't violate path
childcov+=transfrag[t]->abundance;
if(tchild==-1 || transfrag[t]->abundance>transfrag[tchild]->abundance) tchild=t;
}
}
else if(transfrag[t]->nodes[0]<=i && transfrag[t]->nodes.Last()>=inode->child[c] && // transfrag goes from i to c
//(transfrag[t]->pattern[inode->child[c]] || transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath_long(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,minpath,endpath,no2gnode,gno,gpos)) { // transfrag is compatible with path
//fprintf(stderr,"add transfr[%d]->abund=%f\n",t,transfrag[t]->abundance);
childcov+=transfrag[t]->abundance;
replace_transfrag(t,tchild,transfrag,nodecov,no2gnode);
//if(tchild==-1 || transfrag[t]->abundance>transfrag[tchild]->abundance) tchild=t;
}
}
}
if(childcov>maxcov) {
if(tmax==-1 || transfrag[tmax]->weak>0 || !transfrag[tchild]->weak) {
maxcov=childcov;
maxc=inode->child[c];
tmax=tchild;
}
}
else if(maxc!=-1 && childcov>maxcov-epsilon) {
if(transfrag[tmax]->weak>0 || !transfrag[tchild]->weak) {
if(nodecov[maxc]<nodecov[inode->child[c]]) {
maxc=inode->child[c];
tmax=tchild;
}
}
}
if(pos) pathpat[*pos]=0;
if(childonpath) break;
pathpat[inode->child[c]]=0;
}
}
}
if(!reach) return false;
if(maxc==-1) {
if(exclude && nodecov[i+1]) {
CGraphnode *cnode=no2gnode[i+1];
tmax=-1;
float childcov=0;
pathpat[i+1]=1;
int *pos=gpos[edge(i,i+1,gno)];
if(pos) pathpat[*pos]=1;
int endpath=maxpath;
if(i+1>endpath) endpath=i+1;
//else GError("Found parent-child: %d-%d not linked by edge\n",i,i+1);
for(int j=0;j<cnode->trf.Count();j++) { // for all transfrags going through child
int t=cnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
if(!mixedMode) { cnode->trf.Delete(j); j--;}
else transfrag[t]->abundance=0;
}
else if(transfrag[t]->longread && transfrag[t]->nodes[0]<=i && transfrag[t]->nodes.Last()>=i+1 && // transfrag goes from i to c
//(transfrag[t]->pattern[i+1] || transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath_long(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,minpath,endpath,no2gnode,gno,gpos)) { // transfrag is compatible with path
childcov+=transfrag[t]->abundance;
//if(tmax==-1 || transfrag[t]->abundance>transfrag[tmax]->abundance) tmax=t;
replace_transfrag(t,tmax,transfrag,nodecov,no2gnode);
}
}
pathpat[i+1]=0; // these were 1 in the previous code, but it doesn't make sense -> I hope it was wrong
if(pos) pathpat[*pos]=0;
if(childcov) {
maxc=i+1;
}
else {
//goback=true;
return false;
}
}
else {
//goback=true;
return false; //maxc=maxchild;
}
}
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"maxc=%d maxcov=%f tmax=%d\n",maxc,maxcov,tmax);
}
*/
// add maxp to path
path.Add(maxc);
pathpat[maxc]=1;
int *pos=gpos[edge(i,maxc,gno)];
if(pos) pathpat[*pos]=1;
//else GError("Found parent-child %d-%d not linked by edge\n",i,maxc);
if(tmax>-1) {
pathpat=pathpat | transfrag[tmax]->pattern;
if(transfrag[tmax]->nodes[0]<minpath) minpath=transfrag[tmax]->nodes[0];
if(transfrag[tmax]->nodes.Last()>maxpath) maxpath=transfrag[tmax]->nodes.Last();
}
return fwd_to_sink_fast_long(maxc,path,minpath,maxpath,pathpat,transfrag,no2gnode,nodecov,gno,gpos);
}
bool back_to_source_fast_long(int i,GVec<int>& path,int& minpath,int& maxpath,GBitVec& pathpat,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecov,int gno,GIntHash<int>& gpos){
// find all parents -> if parent is source then go back
CGraphnode *inode=no2gnode[i];
if(minpath<i && !inode->parentpat[minpath]) return false; // I can not reach maxpath from node
int nparents=inode->parent.Count(); // number of parents
/*
fprintf(stderr,"Parents of node %d are:",i);
for(int p=0;p<nparents;p++) fprintf(stderr," %d",inode->parent[p]);
fprintf(stderr," pathpat=");
printBitVec(pathpat);
fprintf(stderr,"\n");
*/
if(!nparents) return true; // node is source
int maxp=-1;
/* I can not do this because then I don't check for continuity
if(nparents==1) {
maxp=inode->parent[0];
}
else {
*/
float maxcov=0;
int tmax=-1;
bool exclude=false;
int nextnode=gno; // nextnode on path
bool reach=false;
if(minpath>=i) reach=true;
// check if adjacent parent is on the path
if(pathpat[i-1]) {
maxp=i-1;
tmax=-1;
reach=true;
}
else {
//int maxparent=inode->parent[0];
//float maxparentcov=-1;
for(int p=0;p<nparents;p++) {
bool parentonpath=false;
if(pathpat[inode->parent[p]]) parentonpath=true;
// check if parent is already on the path
int *pos=gpos[edge(inode->parent[p],i,gno)];
if(pos && pathpat[*pos]) { // this is next child on the path
maxp=inode->parent[p];
tmax=-1;
reach=true;
break;
}
// check if I can reach nextnode from p
if(minpath<i) { // actually minpath is <= i-2 otherwise I wouldn't get here
if(nextnode==gno) {
int j=i-2;
while(j>=minpath) {
if(pathpat[j]) {
nextnode=j;
break;
}
j++;
}
}
if(inode->parent[p]!=nextnode && !no2gnode[inode->parent[p]]->parentpat[nextnode]) {
continue;
}
reach=true;
}
/*if(no2gnode[minpath]->hardstart && pathpat[gno-1]) { // this is a trflong transcript
if(!pathpat[p]) continue;
}*/
float parentcov=0;
int tpar=-1;
int startpath=minpath;
if(inode->parent[p]<startpath) startpath=inode->parent[p];
CGraphnode *pnode=no2gnode[inode->parent[p]];
/*
if(nodecov[inode->parent[p]]>maxparentcov) {
maxparentcov=nodecov[inode->parent[p]];
maxparent=inode->parent[p];
}
*/
if(inode->parent[p]==i-1 && i>1 && inode->start==pnode->end+1 &&
nodecov[i-1]/pnode->len() <1000 && nodecov[i]*(DROP+ERROR_PERC)>nodecov[i-1]) { // adjacent to parent
exclude=true;
}
else {
pathpat[inode->parent[p]]=1;
if(pos) pathpat[*pos]=1;
//else GError("Found parent-child %d-%d not linked by edge\n",inode->parent[p],i);
for(int j=0;j<pnode->trf.Count();j++) { // for all transfrags going through parent
int t=pnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
if(!mixedMode) { pnode->trf.Delete(j);j--;}
else transfrag[t]->abundance=0;
}
else if(transfrag[t]->longread && transfrag[t]->nodes.Last()!=gno-1) {
if(!inode->parent[p]) { // parent is source
if(transfrag[t]->nodes.Last()==i && minpath>=i) {
parentcov+=transfrag[t]->abundance;
if(tpar==-1 || transfrag[t]->abundance>transfrag[tpar]->abundance) tpar=t;
}
}
else if(transfrag[t]->nodes[0]<=inode->parent[p] && transfrag[t]->nodes.Last()>=i && // transfrag goes from p to i
//(transfrag[t]->pattern[inode->parent[p]]||transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath_long(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,startpath,maxpath,no2gnode,gno,gpos)) { // transfrag is compatible with path
// comment: I need to check for the parent to make sure I am not going through another node!!
//fprintf(stderr,"parent=%d add transfr[%d]->abund=%f\n",inode->parent[p],t,transfrag[t]->abundance);
parentcov+=transfrag[t]->abundance;
//if(tpar==-1 || transfrag[t]->abundance>transfrag[tpar]->abundance) tpar=t;
replace_transfrag(t,tpar,transfrag,nodecov,no2gnode);
}
}
}
if(parentcov>maxcov) {
if(tmax==-1 || transfrag[tmax]->weak>0 || !transfrag[tpar]->weak) {
maxcov=parentcov;
maxp=inode->parent[p];
tmax=tpar;
}
}
else if(maxp!=-1 && parentcov>maxcov-epsilon) {
if(transfrag[tmax]->weak>0 || !transfrag[tpar]->weak) {
if(nodecov[maxp]<nodecov[inode->parent[p]]) {
maxp=inode->parent[p];
tmax=tpar;
}
}
}
if(pos) pathpat[*pos]=0;
if(parentonpath) break;
pathpat[inode->parent[p]]=0;
}
}
}
if(!reach) return false;
if(maxp==-1) {
if(exclude && nodecov[i-1]) {
CGraphnode *pnode=no2gnode[i-1];
tmax=-1;
float parentcov=0;
pathpat[i-1]=1;
int *pos=gpos[edge(i-1,i,gno)];
if(pos) pathpat[*pos]=1;
//else GError("Found parent-child %d-%d not linked by edge\n",i-1,i);
int startpath=minpath;
if(i-1<startpath) startpath=i-1;
for(int j=0;j<pnode->trf.Count();j++) { // for all transfrags going through parent
int t=pnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
if(!mixedMode) { pnode->trf.Delete(j); j--;}
else transfrag[t]->abundance=0;
}
else if(transfrag[t]->longread && transfrag[t]->nodes[0]<=i-1 && transfrag[t]->nodes.Last()>=i && // transfrag goes from p to i
//(transfrag[t]->pattern[i-1]||transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath_long(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,startpath,maxpath,no2gnode,gno,gpos)) { // transfrag is compatible with path
// comment: I need to check for the parent to make sure I am not going through another node!!
//fprintf(stderr,"parent=%d add transfr[%d]->abund=%f\n",i-1,t,transfrag[t]->abundance);
parentcov+=transfrag[t]->abundance;
//if(tmax==-1 || transfrag[t]->abundance>transfrag[tmax]->abundance) tmax=t;
replace_transfrag(t,tmax,transfrag,nodecov,no2gnode);
}
}
pathpat[i-1]=0;
if(pos) pathpat[*pos]=0;
if(parentcov) {
maxp=i-1;
}
else {
//goback=true;
return false;
}
}
else {
//goback=true;
return false; //maxp=maxparent;
}
}
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"maxp=%d maxcov=%f tmax=%d\n",maxp,maxcov,tmax);
}
*/
if(maxp) { // add maxp to path only if not source
path.Add(maxp);
}
pathpat[maxp]=1; // if maxp is source I added it in the pathpat
int *pos=gpos[edge(maxp,i,gno)];
if(pos) pathpat[*pos]=1;
//else GError("Found parent-child %d-%d not linked by edge\n",maxp,i);
if(tmax>-1) {
pathpat=pathpat | transfrag[tmax]->pattern;
if(transfrag[tmax]->nodes[0]<minpath) minpath=transfrag[tmax]->nodes[0];
if(transfrag[tmax]->nodes.Last()>maxpath) maxpath=transfrag[tmax]->nodes.Last();
}
return back_to_source_fast_long(maxp,path,minpath,maxpath,pathpat,transfrag,no2gnode,nodecov,gno,gpos);
}
bool fwd_to_sink_fast(int i,GVec<int>& path,GBitVec& pathpat,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecov,int gno,GIntHash<int>& gpos){
// find all parents -> if parent is source then go back
CGraphnode *inode=no2gnode[i];
int nchildren=inode->child.Count(); // number of children
/*
fprintf(stderr,"Children of node %d are:",i);
for(int c=0;c<nchildren;c++) fprintf(stderr," %d",inode->child[c]);
fprintf(stderr,"\n");
*/
if(!nchildren) return true; // node is sink
int maxc=-1;
/* I can not do this because then I don't check for continuity
if(nchildren==1) {
maxc=inode->child[0]; // only one child to consider
}
else {
*/
float maxcov=0;
//int maxchild=inode->child[0];
//float maxchildcov=-1;
bool exclude=false;
for(int c=0;c<nchildren;c++) {
float childcov=0;
CGraphnode *cnode=no2gnode[inode->child[c]];
/*
if(nodecov[inode->child[c]]>maxchildcov) {
maxchildcov=nodecov[inode->child[c]];
maxchild=inode->child[c];
}
*/
if(inode->child[c]==i+1 && i<gno-2 && inode->end+1==cnode->start &&
nodecov[i+1]/cnode->len() <1000 && nodecov[i]*(DROP+ERROR_PERC)>nodecov[i+1]) { // adjacent to child
// cnode->len() this is redundant because i<gno-2
//((nodecov[i+1]/cnode->len() <1000 && nodecov[i]*DROP>nodecov[i+1]) || (cnode->len()<longintronanchor && cnode->child.Count()==1 && cnode->child[0]==gno-1 ) )) { // adjacent to child
exclude=true;
}
else {
pathpat[inode->child[c]]=1;
int *pos=gpos[edge(i,inode->child[c],gno)];
if(pos) pathpat[*pos]=1;
else GError("1 Found parent-child: %d-%d not linked by edge!\n",i,inode->child[c]);
for(int j=0;j<cnode->trf.Count();j++) { // for all transfrags going through child
int t=cnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
cnode->trf.Delete(j);
j--;
}
else if(transfrag[t]->nodes[0]<=i && transfrag[t]->nodes.Last()>=inode->child[c] && // transfrag goes from i to c
//(transfrag[t]->pattern[inode->child[c]] || transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,path[0],inode->child[c],no2gnode,gno,gpos)) { // transfrag is compatible with path
//fprintf(stderr,"add transfr[%d]->abund=%f\n",t,transfrag[t]->abundance);
childcov+=transfrag[t]->abundance;
}
}
if(childcov>maxcov) {
maxcov=childcov;
maxc=inode->child[c];
}
else if(childcov==maxcov && maxc!=-1) {
if(nodecov[maxc]<nodecov[inode->child[c]]) {
maxc=inode->child[c];
}
}
pathpat[inode->child[c]]=0;
if(pos) pathpat[*pos]=0;
}
}
if(maxc==-1) {
//bool goback=false;
if(exclude && nodecov[i+1]) {
CGraphnode *cnode=no2gnode[i+1];
float childcov=0;
pathpat[i+1]=1;
int *pos=gpos[edge(i,i+1,gno)];
if(pos) pathpat[*pos]=1;
else GError("2 Found parent-child: %d-%d not linked by edge\n",i,i+1);
for(int j=0;j<cnode->trf.Count();j++) { // for all transfrags going through child
int t=cnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
cnode->trf.Delete(j);
j--;
}
else if(transfrag[t]->nodes[0]<=i && transfrag[t]->nodes.Last()>=i+1 && // transfrag goes from i to c
//(transfrag[t]->pattern[i+1] || transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,path[0],i+1,no2gnode,gno,gpos)) { // transfrag is compatible with path
childcov+=transfrag[t]->abundance;
}
}
pathpat[i+1]=0; // these were 1 in the previous code, but it doesn't make sense -> I hope it was wrong
if(pos) pathpat[*pos]=0;
if(childcov) {
maxc=i+1;
}
else {
//goback=true;
//fprintf(stderr,"fwd: return false\n");
return false;
}
}
else {
//goback=true;
//fprintf(stderr,"fwd: return false maxc=maxchild=%d\n",maxc);
return false; //maxc=maxchild;
}
/*if(goback) { // no continuation to source was found
// check if I have a better path before returning false; might want to restrict to long reads?
while(path.Count()>1) {
int c=path.Pop();
pathpat[c]=0;
int p=path.Last();
int *pos=gpos[edge(p,c,gno)];
if(pos) pathpat[*pos]=0;
if(no2gnode[p]->child.Last()==gno-1) { // has sink child --> check if there is any abundance left
for(int j=0;j<no2gnode[p]->trf.Count();j++) { // for all transfrags going through parent
int t=no2gnode[p]->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
no2gnode[p]->trf.Delete(j);
j--;
}
else if(transfrag[t]->nodes.Last()==gno-1) { // transfrag goes through sink
pathpat[gno-1]=1;
int *pos=gpos[edge(p,gno-1,gno)];
if(pos) pathpat[*pos]=1;
c=gno-1;
path.Add(c);
return true;
}
}
}
}
return false;
}*/
}
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"maxc=%d maxcov=%f\n",maxc,maxcov);
}
*/
// add maxp to path
path.Add(maxc);
pathpat[maxc]=1;
int *pos=gpos[edge(i,maxc,gno)];
if(pos) pathpat[*pos]=1;
else GError("3 Found parent-child %d-%d not linked by edge\n",i,maxc);
return fwd_to_sink_fast(maxc,path,pathpat,transfrag,no2gnode,nodecov,gno,gpos);
}
bool back_to_source_fast(int i,GVec<int>& path,GBitVec& pathpat,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecov,int gno,GIntHash<int>& gpos){
// find all parents -> if parent is source then go back
CGraphnode *inode=no2gnode[i];
int nparents=inode->parent.Count(); // number of parents
/*
fprintf(stderr,"Parents of node %d are:",i);
for(int p=0;p<nparents;p++) fprintf(stderr," %d",inode->parent[p]);
fprintf(stderr,"\n");
*/
if(!nparents) return true; // node is source
int maxp=-1;
/* I can not do this because then I don't check for continuity
if(nparents==1) {
maxp=inode->parent[0];
}
else {
*/
float maxcov=0;
//int maxparent=inode->parent[0];
//float maxparentcov=-1;
bool exclude=false;
for(int p=0;p<nparents;p++) {
float parentcov=0;
CGraphnode *pnode=no2gnode[inode->parent[p]];
/*
if(nodecov[inode->parent[p]]>maxparentcov) {
maxparentcov=nodecov[inode->parent[p]];
maxparent=inode->parent[p];
}
*/
if(inode->parent[p]==i-1 && i>1 && inode->start==pnode->end+1 &&
nodecov[i-1]/pnode->len() <1000 && nodecov[i]*(DROP+ERROR_PERC)>nodecov[i-1]) { // adjacent to parent
// pnode->len() && this is redundant because source should always be 0
//((nodecov[i-1]/pnode->len() <1000 && nodecov[i]*DROP>nodecov[i-1]) || (pnode->len()<longintronanchor && pnode->parent.Count()==1 && !pnode->parent[0]))) { // adjacent to parent
exclude=true;
}
else {
pathpat[inode->parent[p]]=1;
int *pos=gpos[edge(inode->parent[p],i,gno)];
if(pos) pathpat[*pos]=1;
else GError("4 Found parent-child %d-%d not linked by edge\n",inode->parent[p],i);
for(int j=0;j<pnode->trf.Count();j++) { // for all transfrags going through parent
int t=pnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
pnode->trf.Delete(j);
j--;
}
else if(transfrag[t]->nodes[0]<=inode->parent[p] && transfrag[t]->nodes.Last()>=i && // transfrag goes from p to i
//(transfrag[t]->pattern[inode->parent[p]]||transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,inode->parent[p],path[0],no2gnode,gno,gpos)) { // transfrag is compatible with path
// comment: I need to check for the parent to make sure I am not going through another node!!
//fprintf(stderr,"parent=%d add transfr[%d]->abund=%f\n",inode->parent[p],t,transfrag[t]->abundance);
parentcov+=transfrag[t]->abundance;
}
}
if(parentcov>maxcov) {
maxcov=parentcov;
maxp=inode->parent[p];
}
else if(parentcov==maxcov && maxp!=-1) {
if(nodecov[maxp]<nodecov[inode->parent[p]]) {
maxp=inode->parent[p];
}
}
pathpat[inode->parent[p]]=0;
if(pos) pathpat[*pos]=0;
}
}
if(maxp==-1) {
//bool goback=false;
if(exclude && nodecov[i-1]) {
CGraphnode *pnode=no2gnode[i-1];
float parentcov=0;
pathpat[i-1]=1;
int *pos=gpos[edge(i-1,i,gno)];
if(pos) pathpat[*pos]=1;
else GError("5 Found parent-child %d-%d not linked by edge\n",i-1,i);
for(int j=0;j<pnode->trf.Count();j++) { // for all transfrags going through parent
int t=pnode->trf[j];
if(transfrag[t]->abundance<epsilon) { // this transfrag was used before -> needs to be deleted
pnode->trf.Delete(j);
j--;
}
else if(transfrag[t]->nodes[0]<=i-1 && transfrag[t]->nodes.Last()>=i && // transfrag goes from p to i
//(transfrag[t]->pattern[i-1]||transfrag[t]->pattern[i]) && // transfrag is not incomplete through these nodes
onpath(transfrag[t]->pattern,transfrag[t]->nodes,pathpat,i-1,path[0],no2gnode,gno,gpos)) { // transfrag is compatible with path
// comment: I need to check for the parent to make sure I am not going through another node!!
//fprintf(stderr,"parent=%d add transfr[%d]->abund=%f\n",i-1,t,transfrag[t]->abundance);
parentcov+=transfrag[t]->abundance;
}
}
pathpat[i-1]=0;
if(pos) pathpat[*pos]=0;
if(parentcov) {
maxp=i-1;
}
else {
//goback=true;
//fprintf(stderr,"return false\n");
return false;
}
}
else {
//goback=true;
//fprintf(stderr,"return false maxp=maxparent=%d\n",maxp);
return false; //maxp=maxparent;
}
}
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"maxp=%d maxcov=%f\n",maxp,maxcov);
}
*/
if(maxp) { // add maxp to path only if not source
path.Add(maxp);
}
pathpat[maxp]=1; // if maxp is source I added it in the pathpat
int *pos=gpos[edge(maxp,i,gno)];
if(pos) pathpat[*pos]=1;
else GError("6 Found parent-child %d-%d not linked by edge\n",maxp,i);
return back_to_source_fast(maxp,path,pathpat,transfrag,no2gnode,nodecov,gno,gpos);
}
void update_capacity(int start,CTransfrag *t,float val,GVec<float>& capacity,GVec<int>& node2path) {
t->abundance-=val;
if(t->abundance<epsilon) t->abundance=0;
for(int j=start;j<t->nodes.Count()-1;j++) { // for all nodes but the last
int i=node2path[t->nodes[j]];
capacity[i]+=val;
}
}
void compute_capacity(int lastn, CTransfrag *t,float val,GVec<float>& capacity,GVec<int>& node2path,GPVec<CGraphnode>& no2gnode) {
int j=0;
while(j<t->nodes.Count()-1 && t->nodes[j]<lastn) {
int i=node2path[t->nodes[j]];
capacity[i]+=val;
j++;
}
if(j<t->nodes.Count() && t->nodes[j]==lastn) {
if(j<t->nodes.Count()-1)
capacity[node2path[t->nodes[j]]]+=val;
else capacity[node2path[t->nodes[j]]]+=val*no2gnode[t->nodes[j]]->rate;
}
}
void compute_capacity_back(int firstn, CTransfrag *t,float val,GVec<float>& capacity,GVec<int>& node2path) {
int j=t->nodes.Count()-2;
while(j>=0 && t->nodes[j]>=firstn) {
int i=node2path[t->nodes[j]];
capacity[i]+=val;
j--;
}
}
bool weight_bfs(int n,GVec<float> *capacity,GVec<float> *flow,GVec<int> *link,GVec<int>& pred) {
GVec<int> color;
color.Resize(n);
int head=0;
int tail=0;
GVec<int> q;
// enque 0 (source)
q.cAdd(0);
tail++;
color[0]=1;
pred[0]=-1;
while(head!=tail) {
// deque
int u=q[head];
head++;
color[u]=2;
for(int v=0;v<link[u].Count();v++)
if(!color[link[u][v]] && capacity[u][link[u][v]]-flow[u][link[u][v]]>epsilon && (link[u][v]<u || capacity[u][u]-flow[u][u]>epsilon)) {
// enque v
q.Add(link[u][v]);
tail++;
color[link[u][v]]=1;
pred[link[u][v]]=u;
}
}
return(color[n-1]==2);
}
void get_rate(int n1, int n2,GVec<CNetEdge>& edg,GVec<float> *capacity,GVec<float> *rate,float noderate) {
int k=0;
int n=edg.Count();
float abundance=capacity[n1][n2];
capacity[n1][n2]=0;
rate[n1][n2]=0;
while(abundance && k<n) {
int n3=edg[k].link;
if(rate[n3][n1]) {
float available=capacity[n3][n1]*noderate/rate[n3][n1];
if(available<abundance) {
capacity[n1][n2]+=capacity[n3][n1];
abundance-=available;
rate[n1][n2]+=available;
}
else {
capacity[n1][n2]+=abundance*rate[n3][n1]/noderate;
rate[n1][n2]+=abundance;
abundance=0;
}
}
else break;
k++;
}
if(rate[n1][n2]) rate[n1][n2]=capacity[n1][n2]/rate[n1][n2];
}
// seems like this would work even if source is not first, and last is not sink
float max_flow(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecapacity,GBitVec& pathpat) { //,float& fragno) {
float flux=0;
int n=path.Count();
GVec<float> *capacity=new GVec<float>[n]; // capacity of edges in network
GVec<float> *flow=new GVec<float>[n]; // flow in network
GVec<int> *link=new GVec<int>[n]; // for each node remembers it's neighbours
GVec<int> pred; // this stores the augmenting path
pred.Resize(n,-1);
GVec<int> node2path;
node2path.Resize(gno,-1);
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Start max flow algorithm for path ");
printBitVec(pathpat);
fprintf(stderr," :");
for(int i=0;i<n;i++) fprintf(stderr," %d:%d",i,path[i]);
fprintf(stderr,"\n");
fprintf(stderr,"Used transcripts:");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d",i);
fprintf(stderr,"\n");
}
*/
for(int i=0;i<n;i++) {
node2path[path[i]]=i;
nodecapacity.cAdd(0.0);
capacity[i].Resize(n);
flow[i].Resize(n);
}
// establish capacities in the network
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) { // this needs to be adjusted
istranscript[t]=1;
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!no2gnode[path[i]]->rate) n1=0;
if(!no2gnode[transfrag[t]->nodes.Last()]->rate) n2=n-1;
//fprintf(stderr,"t=%d n1=%d n2=%d ",t,n1,n2);
if(!capacity[n1][n2]) { // haven't seen this link before
link[n1].Add(n2);
link[n2].Add(n1);
}
capacity[n1][n2]+=transfrag[t]->abundance;
//fprintf(stderr,"capacity[%d][%d]=%f after adding transfrag[%d]->abundance=%f\n",n1,n2,capacity[n1][n2],t,transfrag[t]->abundance);
}
}
}
}
/*
fprintf(stderr,"Used transcripts:");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
fprintf(stderr,"\n");
*/
for(int i=0;i<n;i++) link[i].Sort();
GVec<float> rate;
rate.Resize(n,1);
while(bfs(n,capacity,flow,link,pred)) {
int r=0;
float increment=FLT_MAX;
rate[r++]=1;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
float adjflux=(capacity[pred[u]][u]-flow[pred[u]][u])*rate[r-1];
increment = increment < adjflux ? increment : adjflux; // minimum flux increment on the path
if(pred[pred[u]]>=0) {
if(pred[u]<u) {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1]*no2gnode[path[pred[u]]]->rate;
else rate[r]=rate[r-1];
}
else {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1];
else rate[r]=rate[r-1]/no2gnode[path[pred[u]]]->rate;
}
r++;
}
}
r=0;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
flow[pred[u]][u]+=increment/rate[r];
flow[u][pred[u]]-=increment/rate[r];
r++;
}
flux+=increment;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Flow:");
for(int n1=0;n1<n;n1++)
for(int n2=n1+1;n2<n;n2++) if(flow[n1][n2]) fprintf(stderr," [%d][%d]=%f",n1,n2,flow[n1][n2]);
fprintf(stderr,"\n");
}
*/
// adjust transfrag abundances
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
float sumout=0;
int pos=-1;
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!no2gnode[path[i]]->rate) n1=0;
if(!no2gnode[transfrag[t]->nodes.Last()]->rate) n2=n-1;
if(flow[n1][n2]>0) {
if(flow[n1][n2]<transfrag[t]->abundance) {
if(!i) sumout+=flow[n1][n2];
//fprintf(stderr,"Update capacity of transfrag[%d] with value %f to %f\n",t,transfrag[t]->abundance, transfrag[t]->abundance-flow[n1][n2]);
update_capacity(0,transfrag[t],flow[n1][n2],nodecapacity,node2path);
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=flow[n1][n2];
flow[n1][n2]=0;
}
else {
if(!i) sumout+=transfrag[t]->abundance;
flow[n1][n2]-=transfrag[t]->abundance;
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=transfrag[t]->abundance;
//fprintf(stderr,"Update capacity of transfrag[%d] with value=%f to 0\n",t,transfrag[t]->abundance);
update_capacity(0,transfrag[t],transfrag[t]->abundance,nodecapacity,node2path);
}
}
}
else if(!i && transfrag[t]->nodes.Last()==path[i]) pos=j;
}
}
if(!i && pos>-1) { // this is first node -> adjust entering transfrag
int t=no2gnode[path[i]]->trf[pos];
float val=sumout/no2gnode[path[i]]->rate;
transfrag[t]->abundance-=val;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
}
}
// clean up
delete [] capacity;
delete [] flow;
delete [] link;
return(flux);
}
float long_max_flow(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecapacity,GBitVec& pathpat) {
float flux=0;
int n=path.Count();
GVec<float> *capacity=new GVec<float>[n]; // capacity of edges in network
GVec<float> *flow=new GVec<float>[n]; // flow in network
GVec<int> *link=new GVec<int>[n]; // for each node remembers it's neighbours
GVec<int> pred; // this stores the augmenting path
pred.Resize(n,-1);
GVec<int> node2path;
GVec<float> noderate;
node2path.Resize(gno,-1);
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Start max flow algorithm for gno=%d and path ",gno);
printBitVec(pathpat);
fprintf(stderr," :");
for(int i=0;i<n;i++) fprintf(stderr," %d:%d",i,path[i]);
fprintf(stderr,"\n");
//fprintf(stderr,"Used transcripts:");
//for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d",i);
//fprintf(stderr,"\n");
}
*/
for(int i=0;i<n;i++) {
node2path[path[i]]=i;
nodecapacity.cAdd(0.0);
noderate.cAdd(1.0); // I set up all rates to be 1 for now
capacity[i].Resize(n);
flow[i].Resize(n);
}
float max_fl=0;
// establish capacities in the network
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
float sumleft=0;
float sumright=0;
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->longread && transfrag[t]->nodes[0]==path[i] && transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) {
//if(transfrag[t]->nodes[0]==path[i] && transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) {
bool keeptr=true;
if(i==0) max_fl=transfrag[t]->abundance; // this is the flow from source on this path
else {
int ti=1;
int pi=i+1;
int lenp=0;
while(ti<transfrag[t]->nodes.Count()) {
if(path[pi]!=transfrag[t]->nodes[ti]) { // I found a gap in transfrag => I need to check if it's not too big and can not support path
// node on path is coming before transfrag; otherwise I wouldn't have the match above
lenp+=no2gnode[path[pi]]->len();
if(lenp>CHI_WIN) {
keeptr=false;
break;
}
}
else ti++; // I can only advance path as I reach it
pi++;
}
}
if(keeptr) {
istranscript[t]=1;
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
//fprintf(stderr,"t=%d n1=%d n2=%d(%d) ",t,n1,n2,transfrag[t]->nodes.Last());
if(!capacity[n1][n2]) { // haven't seen this link before
link[n1].Add(n2);
link[n2].Add(n1);
}
capacity[n1][n2]+=transfrag[t]->abundance;
//fprintf(stderr,"capacity[%d][%d]=%f after adding transfrag[%d]->abundance=%f\n",n1,n2,capacity[n1][n2],t,transfrag[t]->abundance);
}
}
if(i>1 && i<n-2) if(transfrag[t]->longread){ // rate needs to stay 1 for nodes next to source and sink
if(path[i]==transfrag[t]->nodes[0]) sumright+=transfrag[t]->abundance; // how many transfrags exit node
if(path[i]==transfrag[t]->nodes.Last()) sumleft+=transfrag[t]->abundance; // how many transfrags enter node
}
}
if(sumright && sumleft) {
noderate[i]=sumright/sumleft;
}
}
/*
fprintf(stderr,"Used transcripts:");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
fprintf(stderr,"\n");
*/
for(int i=0;i<n;i++) link[i].Sort();
GVec<float> rate;
rate.Resize(n,1);
while(bfs(n,capacity,flow,link,pred)) {
int r=0;
float increment=max_fl;
rate[r++]=1;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
float adjflux=(capacity[pred[u]][u]-flow[pred[u]][u])*rate[r-1];
increment = increment < adjflux ? increment : adjflux; // minimum flux increment on the path
if(pred[pred[u]]>=0) {
if(pred[u]<u) {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1]*noderate[pred[u]]; //no2gnode[path[pred[u]]]->rate;
else rate[r]=rate[r-1];
}
else {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1];
else rate[r]=rate[r-1]/noderate[pred[u]]; //no2gnode[path[pred[u]]]->rate;
}
r++;
}
}
r=0;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
flow[pred[u]][u]+=increment/rate[r];
flow[u][pred[u]]-=increment/rate[r];
r++;
}
flux+=increment;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Flow:");
for(int n1=0;n1<n;n1++)
for(int n2=n1+1;n2<n;n2++) if(flow[n1][n2]) fprintf(stderr," [%d][%d]=%f",n1,n2,flow[n1][n2]);
fprintf(stderr,"\n");
}
*/
// adjust transfrag abundances
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
float sumout=0;
int pos=-1;
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(flow[n1][n2]>0) {
if(flow[n1][n2]<transfrag[t]->abundance) {
if(!i) sumout+=flow[n1][n2];
//fprintf(stderr,"Update capacity of transfrag[%d] with value %f to %f\n",t,transfrag[t]->abundance, transfrag[t]->abundance-flow[n1][n2]);
update_capacity(0,transfrag[t],flow[n1][n2],nodecapacity,node2path);
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=flow[n1][n2];
if(transfrag[t]->abundance<DBL_ERROR) transfrag[t]->abundance=0; // stricter threshold for long transfrags
flow[n1][n2]=0;
}
else {
if(!i) sumout+=transfrag[t]->abundance;
flow[n1][n2]-=transfrag[t]->abundance;
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=transfrag[t]->abundance;
//fprintf(stderr,"Update capacity of transfrag[%d] with value=%f to 0\n",t,transfrag[t]->abundance);
update_capacity(0,transfrag[t],transfrag[t]->abundance,nodecapacity,node2path);
if(transfrag[t]->abundance<DBL_ERROR) transfrag[t]->abundance=0; // stricter threshold for long transfrags
}
}
}
else if(!i && transfrag[t]->nodes.Last()==path[i]) pos=j;
}
}
if(!i && pos>-1) { // this is first node -> adjust entering transfrag
int t=no2gnode[path[i]]->trf[pos];
float val=sumout/noderate[i]; //no2gnode[path[i]]->rate;
transfrag[t]->abundance-=val;
if(transfrag[t]->abundance<DBL_ERROR) transfrag[t]->abundance=0;
}
}
// clean up
delete [] capacity;
delete [] flow;
delete [] link;
return(flux);
}
// version of push_max_flow where I weight the incomplete transfrags
float push_max_flow(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodeflux,GBitVec& pathpat, GIntHash<int> &gpos, bool &full) {
int n=path.Count();
GVec<int> node2path;
node2path.Resize(gno,-1);
for(int i=0;i<n;i++) {
node2path[path[i]]=i;
nodeflux.cAdd(0.0);
}
GVec<float> capacityleft; // how many transcripts compatible to path enter node
GVec<float> capacityright; // how many transcripts compatible to path exit node
capacityleft.Resize(n);
capacityright.Resize(n);
GVec<float> sumleft; // how many transcripts enter node
GVec<float> sumright; // how many transcripts exit node
sumleft.Resize(n);
sumright.Resize(n);
//bool full=true;
//if(longreads && path.Count()>3) full=false;
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"Start push max flow algorithm for path ");
//printBitVec(pathpat);
fprintf(stderr," :");
for(int i=0;i<n;i++) fprintf(stderr," %d:%d",i,path[i]);
fprintf(stderr,"\n");
//fprintf(stderr,"Used transcripts:");
//for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
//fprintf(stderr,"\n");
}
*/
// compute capacities and sums for all nodes
for(int i=1;i<n-1;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance) {
bool keeptr=false;
if(istranscript[t]) keeptr=true;
else if(!transfrag[t]->nodes[0]) {
if(transfrag[t]->nodes.Last()==path[1]) keeptr=true;
}
else if(transfrag[t]->nodes.Last()==path.Last()) {
if(transfrag[t]->nodes[0]==path[n-2]) keeptr=true;
}
else if(transfrag[t]->nodes[0]==path[i] && ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern)) { // only need to check transfrag the first time I encounter it
keeptr=true;
if(longreads) { // an extremely gapped transcript should not be considered to support path (I am doing this for longreads but it might work for paired reads too
int ti=1;
int pi=i+1;
int lenp=0;
while(ti<transfrag[t]->nodes.Count()) {
if(path[pi]!=transfrag[t]->nodes[ti]) { // I found a gap in transfrag => I need to check if it's not too big and can not support path
// node on path is coming before transfrag node; otherwise I wouldn't have the match above
lenp+=no2gnode[path[pi]]->len();
if(lenp>CHI_WIN) {
keeptr=false;
break;
}
}
else ti++;
pi++;
}
}
if(keeptr && !full) { // check if transcript fully supports path (full is false means I have not found any transcript to fully support path)
full=true;
int p=1;
if(!transfrag[t]->longstart || !transfrag[t]->longend) full=false;
if(full) while(path[p]<transfrag[t]->nodes[0]) {
if(no2gnode[path[p]]->end+1<no2gnode[path[p+1]]->start) {
full=false;
break;
}
p++;
}
if(full) {
p=path.Count()-2;
while(path[p]>transfrag[t]->nodes.Last()) {
if(no2gnode[path[p-1]]->end+1<no2gnode[path[p]]->start) {
full=false;
break;
}
p--;
}
}
if(full) {
for(p=2;p<path.Count()-2;p++) {
if(!transfrag[t]->pattern[path[p]] && no2gnode[path[p]]->len()>longintronanchor) {
full=false;
break;
}
}
}
}
}
if(keeptr) { // transcript on path
istranscript[t]=1;
//fprintf(stderr,"istranscript[%d] with abund=%f and path[%d]=%d and nodes[0]=%d and nodes[last]=%d\n",t,transfrag[t]->abundance,i,path[i],transfrag[t]->nodes[0],transfrag[t]->nodes.Last());
if(i==1 || transfrag[t]->nodes[0]==path[i]) { // first time I encounter transfrag I have to set what abundance to use
if(!transfrag[t]->real) { // if I still didn't solve transfrag
transfrag[t]->usepath=-1;
for(int p=0;p<transfrag[t]->path.Count();p++) {
int *pos=gpos[edge(transfrag[t]->path[p].node,transfrag[t]->path[p].contnode,gno)];
if(pos && pathpat[*pos]) {
transfrag[t]->usepath=p; // this is path dependent
break;
}
}
}
}
if(transfrag[t]->nodes[0]<path[i]) { // transfrag starts before this node
sumleft[i]+=transfrag[t]->abundance;
if(transfrag[t]->real) capacityleft[i]+=transfrag[t]->abundance;
else if(transfrag[t]->usepath>-1 && int(transfrag[t]->usepath)<transfrag[t]->path.Count()) { //TODO: this crashes with intv.gtf guides -> to fix
capacityleft[i]+=transfrag[t]->abundance*transfrag[t]->path[int(transfrag[t]->usepath)].abundance;
}
//fprintf(stderr,"add transfrag t=%d i=%d sumleft=%f capacityleft=%f\n",t,i,sumleft[i],capacityleft[i]);
}
if(transfrag[t]->nodes.Last()>path[i]) { // transfrag ends after this node
sumright[i]+=transfrag[t]->abundance;
if(transfrag[t]->real) capacityright[i]+=transfrag[t]->abundance;
else if(transfrag[t]->usepath>-1 && int(transfrag[t]->usepath)<transfrag[t]->path.Count())
capacityright[i]+=transfrag[t]->abundance*transfrag[t]->path[int(transfrag[t]->usepath)].abundance;
//fprintf(stderr,"add transfrag t=%d i=%d sumright=%f capacityright=%f\n",t,i,sumright[i],capacityright[i]);
}
}
else { // transfrag not on path
if(path[i]>transfrag[t]->nodes[0]) sumleft[i]+=transfrag[t]->abundance;
if(path[i]<transfrag[t]->nodes.Last()) sumright[i]+=transfrag[t]->abundance;
}
}
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Node %d LEFT: capacity=%f total=%f ",path[i],capacityleft[i],sumleft[i]);
if(sumleft[i]) fprintf(stderr,"perc=%f ",capacityleft[i]/sumleft[i]);
else fprintf(stderr,"perc=n/a ");
fprintf(stderr,"RIGHT: capacity=%f total=%f ",capacityright[i],sumright[i]);
if(sumright[i]) fprintf(stderr,"perc=%f\n",capacityright[i]/sumright[i]);
else fprintf(stderr,"perc=n/a\n");
}
*/
if(!capacityleft[i]) return(0);
if(!capacityright[i]) return(0);
}
//if(!full) return(0);
/*
{ // DEBUG ONLY
for(int i=1;i<n-1;i++) {
fprintf(stderr,"Node %d LEFT: capacity=%f total=%f ",path[i],capacityleft[i],sumleft[i]);
if(sumleft[i]) fprintf(stderr,"perc=%f ",capacityleft[i]/sumleft[i]);
else fprintf(stderr,"perc=n/a ");
fprintf(stderr,"RIGHT: capacity=%f total=%f ",capacityright[i],sumright[i]);
if(sumright[i]) fprintf(stderr,"perc=%f\n",capacityright[i]/sumright[i]);
else fprintf(stderr,"perc=n/a\n");
}
fprintf(stderr,"Used transcripts:");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
fprintf(stderr,"\n");
}
*/
// compute flow
float prevflow=capacityleft[1];
for(int i=1;i<n-1;i++) {
float percleft=prevflow/sumleft[i];
float percright=capacityright[i]/sumright[i];
if(percright>percleft) { // more transfrags leave node
percright=percleft;
}
prevflow=percright*sumright[i];
}
if(!prevflow) return(0);
for(int i=n-2;i>0;i--) {
//fprintf(stderr,"i=%d sumright=%f prevflow=%f\n",i,sumright[i],prevflow);
nodeflux[i]=prevflow/sumright[i];
//fprintf(stderr,"nodeflux=%f\n",nodeflux[i]);
capacityright[i]=prevflow;
prevflow=nodeflux[i]*sumleft[i];
//fprintf(stderr,"i=%d sumright=%f sumleft=%f prevflow=%f capacityright=%f nodeflux=%f\n",i,sumright[i],sumleft[i],prevflow,capacityright[i],nodeflux[i]);
//capacityleft[i]=prevflow; // I don't use this
}
// * here I don't care what node I treat first
for(int i=1;i<n-1;i++) if(capacityright[i]){
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
float trabundance=transfrag[t]->abundance;
if(!transfrag[t]->real) {
if(transfrag[t]->usepath>-1 && int(transfrag[t]->usepath)<transfrag[t]->path.Count())
trabundance=transfrag[t]->abundance*transfrag[t]->path[int(transfrag[t]->usepath)].abundance;
else trabundance=0;
}
if(trabundance && transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
if(capacityright[i]>trabundance) {
//fprintf(stderr,"Update capacity of transfrag[%d] with value=%f to 0\n",t,transfrag[t]->abundance);
capacityright[i]-=trabundance;
int n2=node2path[transfrag[t]->nodes.Last()];
for(int k=i+1;k<n2;k++) {
capacityright[k]-=trabundance;
}
transfrag[t]->abundance-=trabundance;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
else if(!transfrag[t]->real) {
transfrag[t]->path[int(transfrag[t]->usepath)].abundance=0;
if(transfrag[t]->path.Count()-1 < 2) transfrag[t]->real=true;
else {
int np=0;
for(int p=0;p<transfrag[t]->path.Count();p++)
if(transfrag[t]->path[int(transfrag[t]->usepath)].abundance) np++;
if(np<2) transfrag[t]->real=true;
}
}
}
else {
//fprintf(stderr,"Update capacity of transfrag[%d] with value=%f to %f\n",t,transfrag[t]->abundance,transfrag[t]->abundance-capacityright[i]);
transfrag[t]->abundance-=capacityright[i];
if(transfrag[t]->abundance<epsilon) {
transfrag[t]->abundance=0;
}
else if(!transfrag[t]->real) {
//transfrag[t]->path[int(transfrag[t]->usepath)].abundance-=capacityright[i]; // not needed anymore because this stores proportions not actual abundances
//if(transfrag[t]->path[int(transfrag[t]->usepath)].abundance<epsilon) {
if(transfrag[t]->path[int(transfrag[t]->usepath)].abundance*transfrag[t]->abundance-capacityright[i]<epsilon) {
transfrag[t]->path[int(transfrag[t]->usepath)].abundance=0;
if(transfrag[t]->path.Count()-1 < 2) transfrag[t]->real=true;
else {
int np=0;
for(int p=0;p<transfrag[t]->path.Count();p++)
if(transfrag[t]->path[int(transfrag[t]->usepath)].abundance) np++;
if(np<2) transfrag[t]->real=true;
}
}
}
int n2=node2path[transfrag[t]->nodes.Last()];
for(int k=i+1;k<n2;k++) {
capacityright[k]-=capacityright[i];
}
capacityright[i]=0;
break;
}
}
}
}
}
// I only have to deal with source transfrag
int nt=no2gnode[path[0]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[0]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
//fprintf(stderr,"Update capacity of transfrag[%d] with value=%f to %f\n",t,transfrag[t]->abundance,transfrag[t]->abundance-prevflow);
transfrag[t]->abundance-=prevflow;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
break; // there is no point in updating more than one transfrag from source
}
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Flow:");
for(int i=0;i<n;i++)
fprintf(stderr,"Used %f of node %d[%d]\n",nodeflux[i],i,path[i]);
fprintf(stderr,"\nTranscript abundances");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
fprintf(stderr,"\n");
}
*/
return(nodeflux[1]);
}
float push_guide_maxflow(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,GBitVec& pathpat) {
float guideabundance=0;
int n=path.Count();
GVec<int> node2path;
node2path.Resize(gno,-1);
for(int i=0;i<n;i++) {
node2path[path[i]]=i;
}
GVec<float> capacityleft; // how many transcripts compatible to path enter node
GVec<float> capacityright; // how many transcripts compatible to path exit node
capacityleft.Resize(n);
capacityright.Resize(n);
GVec<float> sumleft; // how many transcripts enter node
GVec<float> sumright; // how many transcripts exit node
sumleft.Resize(n);
sumright.Resize(n);
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Start push guide max flow algorithm for path ");
//printBitVec(pathpat);
fprintf(stderr," :");
//for(int i=0;i<n;i++) fprintf(stderr," %d:%d",i,path[i]);
for(int i=0;i<n;i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"\n");
//fprintf(stderr,"Used transcripts:");
//for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
//fprintf(stderr,"\n");
}
*/
bool marginal=false;
if(longreads) marginal=true;
// compute capacities and sums for all nodes
for(int i=1;i<n-1;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance) {
//fprintf(stderr,"Consider transcript %d with abundance %f for node %d\n",t,transfrag[t]->abundance,path[i]);
if(istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern)) { // transcript on path
istranscript[t]=1;
//fprintf(stderr,"...on path\n");
if(marginal && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1) marginal=false;
if(transfrag[t]->nodes[0]<path[i]) { // transfrag starts before this node
sumleft[i]+=transfrag[t]->abundance;
capacityleft[i]+=transfrag[t]->abundance;
}
if(transfrag[t]->nodes.Last()>path[i]) { // transfrag ends after this node
sumright[i]+=transfrag[t]->abundance;
capacityright[i]+=transfrag[t]->abundance;
}
}
else { // transfrag not on path
if(path[i]>transfrag[t]->nodes[0]) sumleft[i]+=transfrag[t]->abundance;
if(path[i]<transfrag[t]->nodes.Last()) sumright[i]+=transfrag[t]->abundance;
}
}
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Node %d LEFT: capacity=%f total=%f ",path[i],capacityleft[i],sumleft[i]);
if(sumleft[i]) fprintf(stderr,"perc=%f ",capacityleft[i]/sumleft[i]);
else fprintf(stderr,"perc=n/a ");
fprintf(stderr,"RIGHT: capacity=%f total=%f ",capacityright[i],sumright[i]);
if(sumright[i]) fprintf(stderr,"perc=%f\n",capacityright[i]/sumright[i]);
else fprintf(stderr,"perc=n/a\n");
}
*/
if(!capacityleft[i]) return(0);
if(!capacityright[i]) return(0);
}
if(marginal) return(0);
/*
{ // DEBUG ONLY
for(int i=1;i<n-1;i++) {
fprintf(stderr,"Node %d LEFT: capacity=%f total=%f ",path[i],capacityleft[i],sumleft[i]);
if(sumleft[i]) fprintf(stderr,"perc=%f ",capacityleft[i]/sumleft[i]);
else fprintf(stderr,"perc=n/a ");
fprintf(stderr,"RIGHT: capacity=%f total=%f ",capacityright[i],sumright[i]);
if(sumright[i]) fprintf(stderr,"perc=%f\n",capacityright[i]/sumright[i]);
else fprintf(stderr,"perc=n/a\n");
}
fprintf(stderr,"Used transcripts:");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d(%f)",i,transfrag[i]->abundance);
fprintf(stderr,"\n");
}
*/
// compute flow
float prevflow=capacityleft[1];
for(int i=1;i<n-1;i++) {
float percleft=prevflow/sumleft[i];
float percright=capacityright[i]/sumright[i];
if(percright>percleft) { // more transfrags leave node
percright=percleft;
}
prevflow=percright*sumright[i];
}
if(!prevflow) return(0);
for(int i=n-2;i>0;i--) {
guideabundance+=no2gnode[path[i]]->cov*prevflow/sumright[i];
prevflow=prevflow*sumleft[i]/sumright[i];
}
return(guideabundance);
}
float guide_max_flow(bool adjust,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecapacity,GBitVec& pathpat,GVec<float> *capacity,GVec<float> *flow,GVec<int> *link,GVec<int>& node2path) {
//float& fragno) {
float flux=0;
int n=path.Count();
/*
{ // DEBUG ONLY
fprintf(stderr,"Flow & Capacity:");
for(int n1=0;n1<n;n1++)
for(int n2=0;n2<link[n1].Count();n2++)
if(link[n1][n2]>n1) fprintf(stderr," flow[%d][%d]=%g capacity[%d][%d]=%g",n1,link[n1][n2],flow[n1][link[n1][n2]],n1,link[n1][n2],capacity[n1][link[n1][n2]]);
fprintf(stderr,"\n");
}
*/
for(int i=0;i<n;i++) {
nodecapacity.cAdd(0.0);
if(adjust) for(int j=0;j<link[i].Count();j++) flow[i][link[i][j]]=0;
}
if(adjust) { // recompute the flow
GVec<int> pred; // this stores the augmenting path
pred.Resize(n,-1);
GVec<float> rate;
rate.Resize(n,1);
while(bfs(n,capacity,flow,link,pred)) {
int r=0;
float increment=FLT_MAX;
rate[r++]=1;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
float adjflux=(capacity[pred[u]][u]-flow[pred[u]][u])*rate[r-1];
increment = increment < adjflux ? increment : adjflux; // minimum flux increment on the path
if(pred[pred[u]]>=0) {
if(pred[u]<u) {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1]*no2gnode[path[pred[u]]]->rate;
else rate[r]=rate[r-1];
}
else {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1];
else rate[r]=rate[r-1]/no2gnode[path[pred[u]]]->rate;
}
r++;
}
}
r=0;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
flow[pred[u]][u]+=increment/rate[r];
flow[u][pred[u]]-=increment/rate[r];
r++;
}
flux+=increment;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Flow:");
for(int n1=0;n1<n;n1++)
for(int n2=0;n2<link[n1].Count();n2++)
if(link[n1][n2]>n1 && flow[n1][link[n1][n2]]>0) fprintf(stderr," flow[%d][%d]=%f",n1,link[n1][n2],flow[n1][link[n1][n2]]);
fprintf(stderr,"\n");
}
*/
}
// store flow in capacities so that I don't have to modify flow
for(int n1=0;n1<n;n1++)
for(int n2=0;n2<link[n1].Count();n2++)
if(link[n1][n2]>n1) capacity[n1][link[n1][n2]]=flow[n1][link[n1][n2]];
// adjust transfrag abundances
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
float sumout=0;
int pos=-1;
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) {
istranscript[t]=1;
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!no2gnode[path[i]]->rate) n1=0;
if(!no2gnode[transfrag[t]->nodes.Last()]->rate) n2=n-1;
if(capacity[n1][n2]>0) {
if(capacity[n1][n2]<transfrag[t]->abundance) {
if(!i) sumout+=capacity[n1][n2];
update_capacity(0,transfrag[t],capacity[n1][n2],nodecapacity,node2path);
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=capacity[n1][n2];
capacity[n1][n2]=0;
}
else {
if(!i) sumout+=transfrag[t]->abundance;
capacity[n1][n2]-=transfrag[t]->abundance;
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=transfrag[t]->abundance;
update_capacity(0,transfrag[t],transfrag[t]->abundance,nodecapacity,node2path);
}
}
}
else if(!i && transfrag[t]->nodes.Last()==path[i]) pos=j;
}
}
if(!i && pos>-1) { // this is first node -> adjust entering transfrag
int t=no2gnode[path[i]]->trf[pos];
float val=sumout/no2gnode[path[i]]->rate;
transfrag[t]->abundance-=val;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
}
}
return(flux);
}
float guideflow(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GBitVec& pathpat,GVec<float> *capacity,GVec<float> *flow,GVec<int> *link,GVec<int>& node2path) {
float flux=0;
int n=path.Count();
GVec<int> pred; // this stores the augmenting path
pred.Resize(n,-1);
node2path.Resize(gno,-1);
for(int i=0;i<n;i++) {
node2path[path[i]]=i;
capacity[i].Resize(n);
flow[i].Resize(n);
}
// establish capacities in the network
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) {
istranscript[t]=1;
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!no2gnode[path[i]]->rate) n1=0;
if(!no2gnode[transfrag[t]->nodes.Last()]->rate) n2=n-1;
if(!capacity[n1][n2]) { // haven't seen this link before
link[n1].Add(n2);
link[n2].Add(n1);
}
capacity[n1][n2]+=transfrag[t]->abundance;
}
}
}
}
for(int i=0;i<n;i++) link[i].Sort();
GVec<float> rate;
rate.Resize(n,1);
while(bfs(n,capacity,flow,link,pred)) {
int r=0;
float increment=FLT_MAX;
rate[r++]=1;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
float adjflux=(capacity[pred[u]][u]-flow[pred[u]][u])*rate[r-1];
increment = increment < adjflux ? increment : adjflux;
if(pred[pred[u]]>=0) {
if(pred[u]<u) {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1]*no2gnode[path[pred[u]]]->rate;
else rate[r]=rate[r-1];
}
else {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1];
else rate[r]=rate[r-1]/no2gnode[path[pred[u]]]->rate;
}
r++;
}
}
r=0;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
flow[pred[u]][u]+=increment/rate[r];
flow[u][pred[u]]-=increment/rate[r];
r++;
}
flux+=increment;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Flow:");
for(int n1=0;n1<n;n1++)
for(int n2=n1+1;n2<n;n2++) if(flow[n1][n2]) fprintf(stderr," [%d][%d]=%f",n1,n2,flow[n1][n2]);
fprintf(stderr,"\n");
}
*/
return(flux);
}
float guidepushflow(int g,GVec<CGuide>& guidetrf,int gno,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,
GPVec<CGraphnode>& no2gnode,GVec<float>& nodeflux) {
int n=guidetrf[g].trf->nodes.Count();
GVec<int> node2path;
node2path.Resize(gno,-1);
//fprintf(stderr,"Process guide %d with pattern: ",g);
//printBitVec(guidetrf[g].trf->pattern);
for(int i=0;i<n;i++) {
node2path[guidetrf[g].trf->nodes[i]]=i;
nodeflux.cAdd(0.0);
}
GVec<float> capacityleft; // how many transcripts compatible to path enter node
GVec<float> capacityright; // how many transcripts compatible to path exit node
capacityleft.Resize(n);
capacityright.Resize(n);
GVec<float> sumleft; // how many transcripts enter node
GVec<float> sumright; // how many transcripts exit node
sumleft.Resize(n);
sumright.Resize(n);
// compute capacities and sums for all nodes
for(int i=1;i<n-1;i++) {
int pathi=guidetrf[g].trf->nodes[i];
int nt=no2gnode[pathi]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[pathi]->trf[j];
if(transfrag[t]->abundance) {
if(istranscript[t] || ((guidetrf[g].trf->pattern & transfrag[t]->pattern)==transfrag[t]->pattern)) { // transcript on path
istranscript[t]=1;
// check if there are other guides sharing this transcript so that I can allocate proportionally to guide abundances
float totalcov=guidetrf[g].trf->abundance;
for(int r=g-1;r>=0;r--) if((guidetrf[r].trf->pattern & transfrag[t]->pattern)==transfrag[t]->pattern) {
totalcov+=guidetrf[r].trf->abundance;
}
float prop=1;
if(totalcov>guidetrf[g].trf->abundance) prop=guidetrf[g].trf->abundance/totalcov;
transfrag[t]->usepath=prop*transfrag[t]->abundance;
if(transfrag[t]->nodes[0]<pathi) { // transfrag starts before this node
sumleft[i]+=transfrag[t]->usepath;
capacityleft[i]+=transfrag[t]->usepath;
}
if(transfrag[t]->nodes.Last()>pathi) { // transfrag ends after this node
sumright[i]+=transfrag[t]->usepath;
capacityright[i]+=transfrag[t]->usepath;
}
}
else { // transfrag not on path
if(pathi>transfrag[t]->nodes[0]) sumleft[i]+=transfrag[t]->abundance;
if(pathi<transfrag[t]->nodes.Last()) sumright[i]+=transfrag[t]->abundance;
}
}
}
if(!capacityleft[i]) return(0);
if(!capacityright[i]) return(0);
}
// compute flow -> deal with rounding errors here
float prevflow=capacityleft[1];
for(int i=1;i<n-1;i++) {
float percleft=prevflow/sumleft[i];
float percright=capacityright[i]/sumright[i];
if(percright>percleft) { // more transfrags leave node
percright=percleft;
}
prevflow=percright*sumright[i];
}
if(!prevflow) return(0);
for(int i=n-2;i>0;i--) {
nodeflux[i]=prevflow/sumright[i];
if(nodeflux[i]>1) nodeflux[i]=1; // because of rounding errors this could become more than 1
capacityright[i]=prevflow;
prevflow=prevflow*sumleft[i]/sumright[i];
//capacityleft[i]=prevflow;
}
for(int i=1;i<n-1;i++) {
int pathi=guidetrf[g].trf->nodes[i];
int nt=no2gnode[pathi]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[pathi]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
float trabundance=transfrag[t]->usepath;
if(transfrag[t]->nodes[0]==pathi) { // transfrag starts at this node
if(capacityright[i]>trabundance) {
capacityright[i]-=trabundance;
int n2=node2path[transfrag[t]->nodes.Last()];
for(int k=i+1;k<n2;k++) {
capacityright[k]-=trabundance;
}
transfrag[t]->abundance-=trabundance;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
else transfrag[t]->usepath=0; // I only need to delete this if I still have abundance left in transfrag
}
else if(capacityright[i]) {
transfrag[t]->abundance-=capacityright[i];
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
else {
transfrag[t]->usepath-=capacityright[i];
if(transfrag[t]->usepath<epsilon)
transfrag[t]->usepath=0;
}
int n2=node2path[transfrag[t]->nodes.Last()];
for(int k=i+1;k<n2;k++) {
capacityright[k]-=capacityright[i];
}
capacityright[i]=0;
// break; I can not break because I might still have transfrag that need the cleanup
}
}
}
}
}
// I only have to deal with source transfrag
int nt=no2gnode[guidetrf[g].trf->nodes[0]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[guidetrf[g].trf->nodes[0]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
transfrag[t]->abundance-=prevflow;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
break;
}
} //*/
return(nodeflux[1]);
}
float max_flow_EM(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecapacity,GBitVec& pathpat) {//,float &fragno) {
float flux=0;
int n=path.Count();
int m=n+2;
GVec<float> *capacity=new GVec<float>[m]; // capacity of edges in network
GVec<float> *flow=new GVec<float>[m]; // flow in network
GVec<int> *link=new GVec<int>[m]; // for each node remembers it's neighbours
GVec<int> pred; // this stores the augmenting path
pred.Resize(m,-1);
GVec<int> node2path;
node2path.Resize(gno,-1);
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Start max flow algorithm for path ");
//printBitVec(pathpat);
fprintf(stderr," :");
for(int i=0;i<n;i++) fprintf(stderr," %d:%d",i,path[i]);
fprintf(stderr,"\n");
fprintf(stderr,"Used transcripts:");
for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d",i);
fprintf(stderr,"\n");
}
*/
GVec<float> through; // these are the capacity of the "trough" transfrags through each node in the path
through.Resize(n);
for(int i=0;i<m;i++) {
if(i<n) node2path[path[i]]=i;
if(i<n) nodecapacity.cAdd(0.0);
capacity[i].Resize(m);
flow[i].Resize(m);
}
// establish capacities in the network
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) {
istranscript[t]=1;
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!capacity[n1][n2]) { // haven't seen this link before
link[n1].Add(n2);
link[n2].Add(n1);
}
capacity[n1][n2]+=transfrag[t]->abundance;
}
else if(transfrag[t]->nodes[0]<path[i] && transfrag[t]->nodes.Last()>path[i] && transfrag[t]->pattern[path[i]]) { // through transfrag
through[i]+=transfrag[t]->abundance;
}
}
}
if(i && i<n-1 && through[i]) { // not source or sink and I have transfrags going through the node
// 0 -> n : source links to fake node n
link[n].Add(i);
link[i].Add(n);
// n+1 -> sink : fake node n+1 links to sink
int n1=n+1;
link[n1].Add(i);
link[i].Add(n1);
capacity[n][i]+=through[i];
capacity[i][n1]+=through[i];
int sink=n-1;
if(!capacity[n1][sink]) {
link[n1].Add(sink);
link[sink].Add(n1);
}
capacity[n1][sink]+=through[i];
if(!capacity[0][n]) {
link[0].Add(n);
link[n].cAdd(0);
}
capacity[0][n]+=through[i];
capacity[0][0]+=through[i];
}
}
for(int i=0;i<n;i++) link[i].Sort();
bool doEM=true;
int iterations=0;
GIntHash<float> tabund;
GVec<float> rate;
rate.Resize(m,1);
while(doEM && iterations<10) {
flux=0;
while(bfs(n,capacity,flow,link,pred)) {
int r=0;
float increment=FLT_MAX;
rate[r++]=1;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
float adjflux=(capacity[pred[u]][u]-flow[pred[u]][u])*rate[r-1];
increment = increment < adjflux ? increment : adjflux;
if(pred[pred[u]]>=0) {
if(pred[u]>=n) rate[r]=rate[r-1];
else
if(pred[u]<u) {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1]*no2gnode[path[pred[u]]]->rate;
else rate[r]=rate[r-1];
}
else {
if(pred[pred[u]]<pred[u]) rate[r]=rate[r-1];
else rate[r]=rate[r-1]/no2gnode[path[pred[u]]]->rate;
}
r++;
}
}
r=0;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
flow[pred[u]][u]+=increment/rate[r];
flow[u][pred[u]]-=increment/rate[r];
r++;
}
flux+=increment;
}
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Flow:");
for(int n1=0;n1<n;n1++)
for(int n2=n1+1;n2<n;n2++) if(flow[n1][n2]) fprintf(stderr," [%d][%d]=%f",n1,n2,flow[n1][n2]);
fprintf(stderr,"\n");
}
*/
tabund.Clear();
doEM=false;
for(int i=0;i<n;i++) {
through[i]=0;
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(flow[n1][n2]>0) {
if(flow[n1][n2]<transfrag[t]->abundance) {
//GStr tid(t);
tabund.Add(t,flow[n1][n2]);
flow[n1][n2]=0;
}
else {
flow[n1][n2]-=transfrag[t]->abundance;
//GStr tid(t);
tabund.Add(t,transfrag[t]->abundance);
}
}
}
else if(transfrag[t]->nodes[0]<path[i] && transfrag[t]->nodes.Last()>path[i] && transfrag[t]->pattern[path[i]]) { // through transfrag
//GStr tid(t);
const float *abund=tabund[t];
if(abund) through[i]+= *abund;
}
}
}
// now check if I should continue the EM algorithm
if(flow[n][i]-through[i]>epsilon) {
doEM=true;
capacity[n][i]=through[i];
}
if(flow[i][n+1]-through[i]>epsilon) {
doEM=true;
capacity[i][n+1]=through[i];
}
}
if(doEM) // reset flow to 0
for(int i=0;i<m;i++) {
flow[i].Clear();
flow[i].Resize(m);
}
iterations++;
}
// adjust transfrag abundances
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance && transfrag[t]->nodes[0]==path[i]) {
//GStr tid(t);
const float *abund=tabund[t];
if(abund) {
update_capacity(0,transfrag[t],*abund,nodecapacity,node2path);
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=*abund;
}
}
}
}
// clean up
delete [] capacity;
delete [] flow;
delete [] link;
return(flux);
}
float weight_max_flow(int gno,GVec<int>& path,GBitVec& istranscript,GPVec<CTransfrag>& transfrag,GPVec<CGraphnode>& no2gnode,
GVec<float>& nodecapacity,GBitVec& pathpat) {//,float& fragno) {
int n=path.Count();
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Start max flow algorithm for path ");
printBitVec(pathpat);
fprintf(stderr," :");
for(int i=0;i<n;i++) fprintf(stderr," %d:%d",i,path[i]);
fprintf(stderr,"\n");
}
*/
float flux=0;
GVec<float> *capacity=new GVec<float>[n]; // capacity of edges in network
GVec<float> *flow=new GVec<float>[n]; // flow in network
GVec<float> *rate=new GVec<float>[n]; // edge rates
GVec<int> *link=new GVec<int>[n]; // for each node remembers it's neighbours
GVec<int> pred; // this stores the augmenting path
pred.Resize(n,-1);
GVec<int> node2path;
node2path.Resize(gno,-1);
for(int i=0;i<n;i++) {
node2path[path[i]]=i;
nodecapacity.cAdd(0.0);
capacity[i].Resize(n);
flow[i].Resize(n);
rate[i].Resize(n,1);
}
// establish capacities in the network
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(transfrag[t]->abundance && (istranscript[t] || ((pathpat & transfrag[t]->pattern)==transfrag[t]->pattern))) {
istranscript[t]=1;
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!no2gnode[path[i]]->rate) n1=0;
if(!no2gnode[transfrag[t]->nodes.Last()]->rate) n2=n-1;
if(!capacity[n1][n2]) { // haven't seen this link before
link[n1].Add(n2);
link[n2].Add(n1);
}
capacity[n1][n2]+=transfrag[t]->abundance;
capacity[n1][n1]+=transfrag[t]->abundance;
}
}
}
}
/*
{ //DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Abundances:");
for(int n1=0;n1<n;n1++) {
for(int n2=n1+1;n2<n;n2++) if(capacity[n1][n2]) {
fprintf(stderr," [%d][%d]=%f",n1,n2,capacity[n1][n2]);
}
fprintf(stderr," tr=");
for(int j=0;j<no2gnode[path[n1]]->trf.Count();j++) {
int t=no2gnode[path[n1]]->trf[j];
if(transfrag[t]->nodes[0]==path[n1] && istranscript[t]) fprintf(stderr," %d(->%d)",t,transfrag[t]->nodes.Last());
}
}
fprintf(stderr,"\n");
}
*/
// Now compute the rates and capacities
for(int n1=1;n1<n;n1++) {
GVec<CNetEdge> sortedg;
for(int n2=0;n2<link[n1].Count();n2++) if(capacity[link[n1][n2]][n1]) { // incoming edge
CNetEdge e(link[n1][n2],rate[link[n1][n2]][n1]);
sortedg.Add(e);
}
sortedg.Sort(edgeCmp); // largest rate comes first
get_rate(n1,n1,sortedg,capacity,rate,no2gnode[path[n1]]->rate);
for(int n2=0;n2<link[n1].Count();n2++) if(capacity[n1][link[n1][n2]]) // outgoing edge
get_rate(n1,link[n1][n2],sortedg,capacity,rate,no2gnode[path[n1]]->rate);
}
/*
{ //DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Capacities:");
for(int n1=0;n1<n;n1++) {
fprintf(stderr," rate[%d]=%f",path[n1],no2gnode[path[n1]]->rate);
for(int n2=n1;n2<n;n2++) if(capacity[n1][n2]) {
fprintf(stderr," [%d][%d]=%f(%f)",n1,n2,capacity[n1][n2],rate[n1][n2]);
}
}
fprintf(stderr,"\n");
}
*/
while(weight_bfs(n,capacity,flow,link,pred)) {
float increment=FLT_MAX;
for(int u=n-1;pred[u]>=0;u=pred[u]) {
float adjflux=capacity[pred[u]][u]-flow[pred[u]][u];
increment = increment < adjflux ? increment : adjflux;
if(pred[u]<u) {
adjflux=capacity[pred[u]][pred[u]]-flow[pred[u]][pred[u]];
increment = increment < adjflux ? increment : adjflux; // don't allow to go over the node capacity
}
}
for(int u=n-1;pred[u]>=0;u=pred[u]) {
flow[pred[u]][u]+=increment;
flow[u][pred[u]]-=increment;
if(pred[u]<u) flow[pred[u]][pred[u]]+=increment;
else flow[u][u]-=increment;
}
flux+=increment;
}
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Flow:");
for(int n1=0;n1<n;n1++)
for(int n2=n1+1;n2<n;n2++) if(flow[n1][n2]) fprintf(stderr," [%d][%d]=%f(%f)",n1,n2,flow[n1][n2],flow[n1][n2]/rate[n1][n2]);
fprintf(stderr,"\n");
}
*/
// adjust transfrag abundances
for(int i=0;i<n;i++) {
int nt=no2gnode[path[i]]->trf.Count();
float sumout=0;
int pos=-1;
for(int j=0;j<nt;j++) {
int t=no2gnode[path[i]]->trf[j];
if(istranscript[t] && transfrag[t]->abundance) {
if(transfrag[t]->nodes[0]==path[i]) { // transfrag starts at this node
int n1=i;
int n2=node2path[transfrag[t]->nodes.Last()];
if(!no2gnode[path[i]]->rate) n1=0;
if(!no2gnode[transfrag[t]->nodes.Last()]->rate) n2=n-1;
if(flow[n1][n2]>0) {
float flown1n2=flow[n1][n2]/rate[n1][n2];
if(flown1n2<transfrag[t]->abundance) {
if(!i) sumout+=flown1n2;
update_capacity(0,transfrag[t],flown1n2,nodecapacity,node2path);
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=flown1n2;
flow[n1][n2]=0;
}
else {
if(!i) sumout+=transfrag[t]->abundance;
flow[n1][n2]-=transfrag[t]->abundance*rate[n1][n2];
//if(path[i] && transfrag[t]->nodes.Last()!=gno-1) fragno+=transfrag[t]->abundance;
update_capacity(0,transfrag[t],transfrag[t]->abundance,nodecapacity,node2path);
}
}
}
else if(!i && transfrag[t]->nodes.Last()==path[i]) pos=j; // NOTE: this will never work if the pathpat doesn't include the link to source, because the transcript linking back to source is not on the path
}
}
if(!i && pos>-1) { // this is first node -> adjust entering transfrag
int t=no2gnode[path[i]]->trf[pos];
float val=sumout/no2gnode[path[i]]->rate;
transfrag[t]->abundance-=val;
if(transfrag[t]->abundance<epsilon) transfrag[t]->abundance=0;
}
}
// clean up
delete [] capacity;
delete [] flow;
delete [] link;
delete [] rate;
return(flux);
}
float store_transcript(GList<CPrediction>& pred,GVec<int>& path,GVec<float>& nodeflux,GVec<float>& nodecov,
GPVec<CGraphnode>& no2gnode,int& geneno,bool& first,int strand,int gno,GIntHash<int>& gpos, bool& included,
GBitVec& prevpath, bool full=false,BundleData *bdata=NULL, //float fragno, char* id=NULL) {
GffObj* t=NULL) {
float cov=0;
int len=0;
CGraphnode *prevnode=NULL;
GVec<GSeg> exons;
GVec<float> exoncov;
float excov=0;
uint refstart=0;
if(bdata) refstart=(uint)bdata->start;
/*
fprintf(stderr,"store transcript path[0]=%d",path[0]);
if(t) fprintf(stderr," with id=%s",t->getID());
fprintf(stderr,"\n");
*/
int s=0;
if(!path[0]) s=1;
bool firstex=true;
bool lastex=false;
for(int i=s;i<path.Count()-1;i++) {
if(!prevpath[path[i]]) { // if I can find a node that was not included previously in any path then this is a new path
included=false;
prevpath[path[i]]=1;
}
int *pos=gpos[edge(path[i-1],path[i],gno)]; // if I can find an edge that was not included in any previous path then this is a new path
if(i && pos && !prevpath[*pos]) {
included=false;
if(pos) prevpath[*pos]=1;
}
CGraphnode *node=no2gnode[path[i]];
// moved this one before the usedcov computation since that one wasn't used
if(t && (node->end<t->start || lastex)) { // I am skipping the nodes that do not overlap the guide so that I don't add them up to coverage
prevnode=node; continue;
}
// push
float usedcov=nodecov[path[i]]*nodeflux[i]*(node->end-node->start+1);
//fprintf(stderr,"usedcov=%f for nodecov[path[%d]]=%f nodeflux[%d]=%f node->end=%d node->start=%d\n",usedcov,i,nodecov[path[i]],i,nodeflux[i],node->end,node->start);
uint nodestart=node->start;
uint nodeend=node->end;
if(t) { // I am adjusting the start/end of the exon but shouldn't I also adjust the coverage? -> I added two ifs below
float firstprop=0;
float lastprop=0;
if(firstex) {
if(nodestart<t->start && bdata) {
float rightcov=0;
// cummulative bpcov
float leftcov=get_cov(2*strand,node->start-refstart,t->start-1-refstart,bdata->bpcov);
if(node->end>t->start) rightcov=get_cov(2*strand,t->start-refstart,node->end-refstart,bdata->bpcov);
if(leftcov) firstprop=leftcov/(leftcov+rightcov);
}
nodestart=t->start;
}
if(t->end<=nodeend || i==path.Count()-2) {
lastex=true;
if(t->end<node->end && bdata) {
//usedcov*=(t->end-nodestart+1)/(nodeend-nodestart+1); // this way I am keeping coverage proportions right
float leftcov=0;
// cummulative bpcov
if(node->start<t->end) {
leftcov=get_cov(2*strand,node->start-refstart,t->end-refstart,bdata->bpcov);
}
float rightcov=get_cov(2*strand,t->end+1-refstart,node->end-refstart,bdata->bpcov);
if(rightcov) lastprop=rightcov/(leftcov+rightcov);
}
nodeend=t->end;
}
if(firstprop || lastprop) {
usedcov-=(firstprop +lastprop)*usedcov;
nodeflux[i]*=(1-firstprop-lastprop);
}
}
nodecov[path[i]]*=(1-nodeflux[i]); // don't allow this to be less than 0
if(!prevnode || firstex || node->start>prevnode->end+1) { // this is a new exon
if(prevnode && !firstex) { // compute exon coverage
excov/=exons.Last().end-exons.Last().start+1;
exoncov.Add(excov);
excov=0;
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
firstex=false;
}
else if(!firstex) exons.Last().end=nodeend;
len+=nodeend-nodestart+1;
cov+=usedcov;
excov+=usedcov;
//if(node->cov) fragno+=node->frag*usedcov/node->cov;
prevnode=node;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Predicted transcript cov=%f usedcov=%f len=%d path.count=%d ",cov/len, cov,len,path.Count());
fprintf(stderr,"and exons cov:");
for(int e=0;e<exons.Count();e++) fprintf(stderr," %d-%d",exons[e].start,exons[e].end);
fprintf(stderr,"\n");
if(t) fprintf(stderr,"Ref_id=%s\n",t->getID());
}
*/
// Add last exon coverage
if(prevnode) { // compute exon coverage
excov/=exons.Last().end-exons.Last().start+1;
exoncov.Add(excov);
}
if(len) cov/=len;
//if(t || (cov>=readthr && len>=mintranscriptlen)) { // store transcript here; also accept some coverage fuzziness that would get eliminated later
//if(t || (cov>=1 && len>=mintranscriptlen)) { // store transcript here; also accept some coverage fuzziness that would get eliminated later
// sensitive mode:
if(t || (cov && len>=mintranscriptlen)) { // store transcript here;
char sign='-';
if(strand) { sign='+';}
if(first) { geneno++;}
//CPrediction *p=new CPrediction(geneno-1, id, exons[0].start, exons.Last().end, cov, sign, fragno, len);
//if(t) fprintf(stderr,"store prediction with start=%d and end=%d\n",exons[0].start, exons.Last().end);
float gcov=cov;
if (t && t->uptr) {
RC_TData &td = *(RC_TData*) (t->uptr);
td.in_bundle=3;
//fprintf(stderr,"st guide %s is stored\n",t->getID());
}
/*
// this was up to version 1.2.1 -> I am not sure about keeping it
if(t && t->exons.Count()==1) { // if single exon
RC_TData* tdata=(RC_TData*)(t->uptr);
if(len) gcov=(tdata->t_exons[0])->movlcount/len;
if(cov<gcov) gcov=cov;
}
*/
/*
{ // DEBUG ONLY
fprintf(stderr,"Store transcript in prediction %d with coverage %f \n",pred.Count(),gcov);
fprintf(stderr,"And exons cov:");
for(int e=0;e<exons.Count();e++) fprintf(stderr," %g",exoncov[e]);
fprintf(stderr,"\n");
}
*/
CPrediction *p=new CPrediction(geneno-1, t, exons[0].start, exons.Last().end, gcov, sign, len);
p->exons=exons;
if(t && t->exons.Count()==1) exoncov[0]=gcov;
p->exoncov=exoncov;
if(full) p->mergename+='.';
if(longreads) p->tlen=-p->tlen;
pred.Add(p);
first=false;
//fprintf(stderr,"Transcript stored\n");
}
return(cov);
}
// pred[np] = prediction to update; path = the nodes in the prediction or the nodes used from the prediction?
// nodeflux = in store transcript: quantity of transfrags that's used going out from each node;
// nodeflux = here: proportion of the node that is used
// nodecov = coverage of nodes
void update_guide_pred(GList<CPrediction>& pred,int np, GVec<int>& path,GVec<float>& nodeflux,GVec<float>& nodecov,
GPVec<CGraphnode>& no2gnode,int gno,bool update) {
/*
{ // DEBUG ONLY
fprintf(stderr,"Update guide ");
if(pred[np]->t_eq) fprintf(stderr,"%s ",pred[np]->t_eq->getID());
fprintf(stderr,"pred[%d]:",np);
for(int j=0;j<pred[np]->exons.Count();j++) fprintf(stderr," %d-%d",pred[np]->exons[j].start,pred[np]->exons[j].end);
fprintf(stderr,"\n");
}
*/
int e=0;
int nex=pred[np]->exons.Count();
for(int i=0;i<path.Count();i++) {
if(path[i] && path[i]<gno-1) { // not first or last node in graph
CGraphnode *node=no2gnode[path[i]];
float addcov=nodeflux[i]*nodecov[path[i]];
if(update) nodecov[path[i]]-=addcov;
// addcov/=node->len(); this is not necessary because it was already divided to node length
while(e<nex && pred[np]->exons[e].end<node->start) e++; // if exon end before start of node skip it
while(e<nex && pred[np]->exons[e].start<=node->end) { // there is overlap between exon and node
int ovplen=node->overlapLen(pred[np]->exons[e].start, pred[np]->exons[e].end);
float excov=addcov*ovplen;
pred[np]->exoncov[e]+=excov/pred[np]->exons[e].len();
pred[np]->cov+=excov/abs(pred[np]->tlen);
e++;
}
}
}
}
int store_guide_transcript(GList<CPrediction>& pred,GVec<int>& path,GVec<float>& nodeflux,GVec<float>& nodecov,
GPVec<CGraphnode>& no2gnode,int& geneno,bool& first,int gno, GffObj* t,bool update) {
// first create the prediction based on the GffObj and then update it's coverage
GVec<GSeg> exons;
GVec<float> exoncov;
int len=0;
for(int i=0;i<t->exons.Count();i++) {
exons.Add(t->exons[i]);
exoncov.cAdd(0.0);
len+=t->exons[i]->len();
}
if(first) { geneno++;first=false;}
int np=pred.Count();
CPrediction *p=new CPrediction(geneno-1, t, exons[0].start, exons.Last().end, 0, t->strand, len);
p->exons=exons;
p->exoncov=exoncov;
if(longreads) p->tlen=-p->tlen;
pred.Add(p);
if (t && t->uptr) {
RC_TData &td = *(RC_TData*) (t->uptr);
td.in_bundle=3;
//fprintf(stderr,"sg guide %s is stored\n",t->getID());
}
update_guide_pred(pred,np,path,nodeflux,nodecov,no2gnode,gno,update);
return(np);
}
/*
int best_trf_match(CTransfrag *t,GVec<CTransfrag>& keeptrf,GPVec<CGraphnode>& no2gnode,int gno) {
int mineditdist=no2gnode[gno-2]->end-no2gnode[1]->start+1; // bp different between the 2
int mininternaldist=mineditdist; // internal bp that are different -> preferably equal to 0
int maxintersect=0; // nodes in common
int mink=-1;
for(int k=0;k<keeptrf.Count();k++) if(t->nodes[0]<=keeptrf[k].nodes[keeptrf[k].nodes.Count()-2] && keeptrf[k].nodes[1]<=t->nodes.Last()){
int editdist=0;
int internaldist=0;
int intersect=0;
int i=0; // t index
int j=1; // k index
while(j<keeptrf[k].nodes.Count()-1 && t->nodes[i]>keeptrf[k].nodes[j]) {
editdist+=no2gnode[keeptrf[k].nodes[j]]->len();
j++;
}
while(i<t->nodes.Count() && t->nodes[i]<keeptrf[k].nodes.Last() && j<keeptrf[k].nodes.Count()-1) {
if(t->nodes[i]<keeptrf[k].nodes[j]) {
editdist+=no2gnode[t->nodes[i]]->len();
if(j>1) internaldist+=no2gnode[t->nodes[i]]->len();
i++;
}
else if(t->nodes[i]>keeptrf[k].nodes[j]) {
editdist+=no2gnode[keeptrf[k].nodes[j]]->len();
internaldist+=no2gnode[keeptrf[k].nodes[j]]->len();
j++;
}
else { // nodes are equal
i++;
j++;
intersect++;
}
}
if(!intersect || internaldist>CHI_THR) continue;
if(intersect>maxintersect) { // more nodes in common
mink=k;
while(i<t->nodes.Count()) { // i>=1 because t intersects k
editdist+=no2gnode[t->nodes[i]]->len();
if(no2gnode[t->nodes[i-1]]->end+1<no2gnode[t->nodes[i]]->start) internaldist+=no2gnode[t->nodes[i]]->len();
i++;
}
while(j<keeptrf[k].nodes.Count()-1) {
editdist+=no2gnode[keeptrf[k].nodes[j]]->len();
j++;
}
mineditdist=editdist;
mininternaldist=internaldist;
maxintersect=intersect;
}
else if(intersect==maxintersect) {
if(internaldist<mininternaldist) {
while(i<t->nodes.Count()) { // i>=1 because t intersects k
editdist+=no2gnode[t->nodes[i]]->len();
if(no2gnode[t->nodes[i-1]]->end+1<no2gnode[t->nodes[i]]->start) internaldist+=no2gnode[t->nodes[i]]->len();
i++;
}
while(j<keeptrf[k].nodes.Count()-1) {
editdist+=no2gnode[keeptrf[k].nodes[j]]->len();
j++;
}
if(internaldist<mininternaldist) {
mink=k;
mineditdist=editdist;
mininternaldist=internaldist;
}
}
else if(internaldist==mininternaldist) {
if(mink>=0) {
if(editdist>=mineditdist) { // the only time I can replace mink here is if a(mink)==0 && a(k)>0
if(keeptrf[mink].abundance || !keeptrf[k].abundance) continue;
}
else if(keeptrf[mink].abundance && !keeptrf[k].abundance) continue; // there is no way I can replace mink in this case
}
// finish computing editdist
while(i<t->nodes.Count()) {
editdist+=no2gnode[t->nodes[i]]->len();
i++;
}
while(j<keeptrf[k].nodes.Count()-1) {
editdist+=no2gnode[keeptrf[k].nodes[j]]->len();
j++;
}
if(mink<0 || (!keeptrf[mink].abundance && keeptrf[k].abundance)) { // I always replace in this case
mink=k;
mineditdist=editdist;
}
else if(editdist<mineditdist && (!keeptrf[mink].abundance || keeptrf[k].abundance)) {
mink=k;
mineditdist=editdist;
}
}
}
}
return(mink);
}
*/
float best_trf_match(CTransfrag *t,GVec<CTransfrag>& keeptrf,GPVec<CGraphnode>& no2gnode,int gno,GVec<int>& tmatch) {
int mininternaldist=no2gnode[gno-2]->end-no2gnode[1]->start+1; // bp different between the 2 internally (in between nodes) -> preferably equal to 0
int maxintersect=0; // nodes in common
float abundancesum=0;
for(int k=0;k<keeptrf.Count();k++) if(t->nodes[0]<=keeptrf[k].nodes[keeptrf[k].nodes.Count()-2] && keeptrf[k].nodes[1]<=t->nodes.Last()){
int internaldist=0;
int intersect=0;
int i=0; // t index
int j=1; // k index
while(j<keeptrf[k].nodes.Count()-1 && t->nodes[i]>keeptrf[k].nodes[j]) {
j++;
}
while(i<t->nodes.Count() && t->nodes[i]<keeptrf[k].nodes.Last() && j<keeptrf[k].nodes.Count()-1) {
if(t->nodes[i]<keeptrf[k].nodes[j]) {
if(j>1) internaldist+=no2gnode[t->nodes[i]]->len();
i++;
}
else if(t->nodes[i]>keeptrf[k].nodes[j]) {
internaldist+=no2gnode[keeptrf[k].nodes[j]]->len();
j++;
}
else { // nodes are equal
i++;
j++;
intersect++;
}
}
if(!intersect || internaldist>CHI_THR) continue;
if(intersect>maxintersect) { // more nodes in common
tmatch.Clear();
tmatch.Add(k);
abundancesum=keeptrf[k].abundance;
while(i<t->nodes.Count()) { // i>=1 because t intersects k
if(no2gnode[t->nodes[i-1]]->end+1<no2gnode[t->nodes[i]]->start) internaldist+=no2gnode[t->nodes[i]]->len();
i++;
}
while(j<keeptrf[k].nodes.Count()-1) {
j++;
}
mininternaldist=internaldist;
maxintersect=intersect;
}
else if(intersect==maxintersect) { // same number of nodes that intersect
if(internaldist<mininternaldist) {
while(i<t->nodes.Count()) { // i>=1 because t intersects k
if(no2gnode[t->nodes[i-1]]->end+1<no2gnode[t->nodes[i]]->start) internaldist+=no2gnode[t->nodes[i]]->len();
i++;
}
while(j<keeptrf[k].nodes.Count()-1) {
j++;
}
if(internaldist<mininternaldist) { // better internal distance
tmatch.Clear();
tmatch.Add(k);
mininternaldist=internaldist;
abundancesum=keeptrf[k].abundance;
}
}
else if(internaldist==mininternaldist) { // same internal distance --> keep them both
tmatch.Add(k);
abundancesum+=keeptrf[k].abundance;
}
}
}
return(abundancesum);
}
/*
void get_trf_long(int gno,int edgeno, GIntHash<int> &gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,
int& geneno,int strand,GList<CPrediction>& pred,GVec<int>& trflong,BundleData *bdata) {
GPVec<GffObj>& guides = bdata->keepguides;
GVec<float> nodecov; // the coverage of all transfrags entering a node
GVec<float> noderate;
for(int i=0;i<gno;i++) {
CGraphnode *inode=no2gnode[i]; // this is here only because of the DEBUG option below
nodecov.cAdd(0.0); // this are all transfrags that link nodes together
float rate=1;
if(i && i<gno-1) {
for(int j=0;j<inode->trf.Count();j++) { // for all transfrags going through node
int t=inode->trf[j];
if(transfrag[t]->nodes[0]<i) { // entering transfrags:
nodecov[i]+=transfrag[t]->abundance;
}
}
if(nodecov[i]) rate=nodecov[i];
if(rate<=0) rate=1; // this shouldn't happen
rate=inode->cov/rate;
}
noderate.Add(rate);
}
GBitVec istranscript(transfrag.Count());
GVec<int> path;
GBitVec pathpat(gno+edgeno);
int minp;
int maxp;
int maxi;
char sign='-';
if(strand) { sign='+';}
int npred=pred.Count();
GVec<CTransfrag> keeptrf;
GVec<int> checktrf;
for(int f=trflong.Count()-1;f>=0;f--) { // if this is a guide it should be reflected in the prediction downstream
path.Clear();
int t=trflong[f];
if(t<0) GError("Stored long transcript is negative!\n");
pathpat=transfrag[t]->pattern;
minp=transfrag[t]->nodes[0];
maxp=transfrag[t]->nodes.Last();
//if(no2gnode[transfrag[t]->nodes[0]]->hardstart) {
int *pos=gpos[edge(0,minp,gno)];
if(pos) pathpat[*pos]=1;
//minp=0;
//}
//if(no2gnode[transfrag[t]->nodes.Last()]->hardend) {
pos=gpos[edge(maxp,gno-1,gno)];
if(pos) pathpat[*pos]=1;
//maxp=gno-1;
//}
maxi=minp;
path.Add(maxi);
pathpat[maxi]=1;
istranscript.reset();
float flux=0;
//float fragno=0;
GVec<float> nodeflux;
bool tocheck=true;
if(back_to_source_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
path.cAdd(0);
path.Reverse(); // back to source adds the nodes at the end to avoid pushing the list all the time
if(fwd_to_sink_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
flux=long_max_flow(gno,path,istranscript,transfrag,no2gnode,nodeflux,pathpat);
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"flux=%g Path:",flux);
for(int i=0;i<path.Count();i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"\n");
fprintf(stderr,"Nodecapacities:");
for(int i=0;i<path.Count();i++) fprintf(stderr," %f",nodeflux[i]);
fprintf(stderr,"***\n");
}
if(flux) { // these are not valid paths in the graph
tocheck=false;
GVec<GSeg> exons;
GVec<float> exoncov;
int j=1;
int len=0;
float cov=0;
int startnode=j;
int lastnode=path.Count()-2;
uint startpoint=no2gnode[path[lastnode]]->end;
uint endpoint=no2gnode[path[1]]->start;
if(mixedMode) { // establish start/end point of path
while(j<path.Count()-1) {
CGraphnode *jnode=no2gnode[path[j]];
for(int i=0;i<jnode->trf.Count();i++) { // for all transfrags going through node
int t=jnode->trf[i];
if(istranscript[t] && transfrag[t]->longread && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1) {
if(transfrag[t]->nodes[0]==path[j]) {
if(transfrag[t]->longstart) {
if(transfrag[t]->longstart<startpoint) { startpoint=transfrag[t]->longstart; startnode=j;}
}
else if(jnode->start<startpoint) { startpoint=jnode->start; startnode=j;}
}
if(transfrag[t]->nodes.Last()==path[j]) {
if(transfrag[t]->longend) {
if(transfrag[t]->longend>endpoint) { endpoint=transfrag[t]->longend; lastnode=j;}
}
else if(jnode->end>endpoint) {endpoint=jnode->end; lastnode=j;}
}
}
}
j++;
}
if(startpoint>endpoint) {
j=1;
lastnode=path.Count()-2;
startpoint=no2gnode[path[1]]->start;
endpoint=no2gnode[path[lastnode]]->end;
}
else j=startnode;
}
while(j<=lastnode) {
//while(j<path.Count()-1) {
int nodestart=no2gnode[path[j]]->start;
if(mixedMode && j==startnode) nodestart=startpoint;
int nodeend=no2gnode[path[j]]->end;
if(mixedMode && j==lastnode) nodeend=endpoint;
nodecov[path[j]]-=nodeflux[j];
len+=nodeend-nodestart+1;
float ecov=nodeflux[j]*noderate[path[j]];
float excov=ecov;
//if(mixedMode) {
// no2gnode[path[j]]->cov-=ecov;
//if(no2gnode[path[j]]->cov<epsilon) no2gnode[path[j]]->cov=0;
//}
//float excov=nodeflux[j]*noderate[path[j]];
while(j+1<=lastnode && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
//while(j+1<path.Count()-1 && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
j++;
nodeend=no2gnode[path[j]]->end;
ecov=nodeflux[j]*noderate[path[j]];
excov+=ecov;
if(mixedMode) {
//no2gnode[path[j]]->cov-=ecov;
//if(no2gnode[path[j]]->cov<epsilon) no2gnode[path[j]]->cov=0;
if(j==lastnode) nodeend=endpoint;
}
len+=nodeend-no2gnode[path[j]]->start+1;
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
cov+=excov;
exoncov.Add(excov);
j++;
}
if(transfrag[t]->nodes.Count()==1) transfrag[t]->abundance=0;
GffObj *g=NULL;
if(transfrag[t]->guide && longreads) {
g=guides[int(transfrag[t]->usepath)];
if (g && g->uptr) {
RC_TData &td = *(RC_TData*) (g->uptr);
td.in_bundle=3;
}
}
if(!eonly || g) {
CPrediction *p=new CPrediction(geneno, g,exons[0].start , exons.Last().end, cov, sign, len);
p->exons=exons;
p->exoncov=exoncov;
p->mergename='.'; // I should not delete this prediction
p->tlen=-p->tlen; // negative transcript length signifies assembly is from a long read
pred.Add(p);
CTransfrag u(path,pathpat,cov/len);
keeptrf.Add(u);
}
}
else if(transfrag[t]->guide) {
checktrf.Add(t);
}
}
}
if(tocheck) { // try to see if you can rescue transfrag -> they are stored from more abundant to least -> not if using mixedMode
checktrf.Add(t);
}
}
//keeptrf.Sort(longtrCmp); // most abundant transfrag in the graph come first, then the ones with most nodes, then the ones more complete
for(int c=0;c<checktrf.Count();c++) if(transfrag[checktrf[c]]->guide || transfrag[checktrf[c]]->abundance>=readthr) { // only in this case it is worth considering it as a potential prediction
int t=checktrf[c];
int mink=best_trf_match(transfrag[t],keeptrf,no2gnode,gno);
if(mink>=0) { // found good match
int p=0;
int i=0;
int np=npred+mink; // how do I know that keeptrf lead to a prediction -> because keeptrf represent the predictions that were added
while(i<transfrag[t]->nodes.Count() && p<pred[np]->exons.Count()) {
if(no2gnode[transfrag[t]->nodes[i]]->end<pred[np]->exons[p].start) i++;
else if(pred[np]->exons[p].end<no2gnode[transfrag[t]->nodes[i]]->start) p++;
else { // the two intersect (I can only have the full node included in exon)
if(nodecov[transfrag[t]->nodes[i]]>epsilon){
//float addcov=transfrag[t]->abundance*noderate[transfrag[t]->nodes[i]];
float addcov=transfrag[t]->abundance*no2gnode[transfrag[t]->nodes[i]]->len();
float newnodecov=nodecov[transfrag[t]->nodes[i]]-addcov/noderate[transfrag[t]->nodes[i]];
if(newnodecov<0) {
addcov=nodecov[transfrag[t]->nodes[i]]*noderate[transfrag[t]->nodes[i]];
newnodecov=0;
}
nodecov[transfrag[t]->nodes[i]]=newnodecov;
pred[np]->exoncov[p]+=addcov;
pred[np]->cov+=addcov;
}
i++;
}
}
}
else if(!eonly || transfrag[t]->guide) { // store it as an independent prediction
pathpat=transfrag[t]->pattern; // not used right now but maybe in the future?
path.Clear();
path.cAdd(0);
path.Add(transfrag[t]->nodes[0]);
for(int j=1;j<transfrag[t]->nodes.Count();j++) {
if(transfrag[t]->nodes[j]!=1+transfrag[t]->nodes[j-1] ||
no2gnode[transfrag[t]->nodes[j]]->start-1!=no2gnode[transfrag[t]->nodes[j-1]]->end) {
// check if transfrag t1 is incomplete between node[n-1] and node [n]
int *pos=gpos[edge(transfrag[t]->nodes[j-1],transfrag[t]->nodes[j],gno)];
if(!pos || !transfrag[t]->pattern[*pos]) { // incomplete transfrag
break;
}
if(pos) pathpat[*pos]=1;
path.Add(transfrag[t]->nodes[j]);
}
else path.Add(transfrag[t]->nodes[j]);
}
if(path.Last()==transfrag[t]->nodes.Last()) { // this transfrag is complete, might be worth rescuing
int sink=gno-1;
path.Add(sink);
GVec<GSeg> exons;
GVec<float> exoncov;
int j=1;
int len=0;
float cov=0;
while(j<path.Count()-1) {
int nodestart=no2gnode[path[j]]->start;
int nodeend=no2gnode[path[j]]->end;
// nodecov[path[j]]-=transfrag[t]->abundance; // do not need this here anymore
len+=nodeend-nodestart+1;
float excov=0;
if(nodecov[path[j]]>epsilon) {
excov=transfrag[t]->abundance*no2gnode[path[j]]->len();
float newnodecov=nodecov[path[j]]-excov/noderate[path[j]];
if(newnodecov<0) {
excov=nodecov[path[j]]*noderate[path[j]];
newnodecov=0;
}
nodecov[path[j]]=newnodecov;
}
while(j+1<path.Count()-1 && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
j++;
len+=no2gnode[path[j]]->len();
nodeend=no2gnode[path[j]]->end;
float addcov=0;
if(nodecov[path[j]]>epsilon) {
addcov=transfrag[t]->abundance*no2gnode[path[j]]->len();
float newnodecov=nodecov[path[j]]-addcov/noderate[path[j]];
if(newnodecov<0) {
addcov=nodecov[path[j]]*noderate[path[j]];
newnodecov=0;
}
nodecov[path[j]]=newnodecov;
}
excov+=addcov;
//excov+=transfrag[t]->abundance*noderate[path[j]];
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
cov+=excov;
exoncov.Add(excov);
j++;
}
GffObj *g=NULL;
if(transfrag[t]->guide && longreads) {
g=guides[int(transfrag[t]->usepath)];
if (g && g->uptr) {
RC_TData &td = *(RC_TData*) (g->uptr);
td.in_bundle=3;
}
}
CPrediction *p=new CPrediction(geneno, g,exons[0].start , exons.Last().end, cov, sign, len);
p->exons=exons;
p->exoncov=exoncov;
p->tlen=-p->tlen; // negative transcript length signifies assembly is from a long read
pred.Add(p);
CTransfrag u(path,pathpat,cov/len);
keeptrf.Add(u);
}
}
transfrag[t]->abundance=0;
}
if(pred.Count()>npred) {
if(mixedMode) {
for(int t=0;t<transfrag.Count();t++) {
if(transfrag[t]->longread && (!transfrag[t]->nodes[0] || transfrag[t]->nodes.Last()==gno-1) )
transfrag[t]->abundance=0;
else
transfrag[t]->abundance=transfrag[t]->usepath;
transfrag[t]->usepath=-1;
}
}
else for(int t=0;t<transfrag.Count();t++) { // longreads mode --> tries to add all transfrags to predictions
if(transfrag[t]->longread && transfrag[t]->abundance>epsilon && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1 ) {
int mink=best_trf_match(transfrag[t],keeptrf,no2gnode,gno);
if(mink>=0) { // mink gives the prediction's position too
int p=0;
int i=0;
int np=npred+mink;
while(i<transfrag[t]->nodes.Count() && p<pred[np]->exons.Count()) {
if(no2gnode[transfrag[t]->nodes[i]]->end<pred[np]->exons[p].start) i++;
else if(pred[np]->exons[p].end<no2gnode[transfrag[t]->nodes[i]]->start) p++;
else { // the two intersect (I can only have the full node included in exon)
if(nodecov[transfrag[t]->nodes[i]]>epsilon){
//float addcov=transfrag[t]->abundance*noderate[transfrag[t]->nodes[i]];
float addcov=transfrag[t]->abundance*no2gnode[transfrag[t]->nodes[i]]->len();
float newnodecov=nodecov[transfrag[t]->nodes[i]]-addcov/noderate[transfrag[t]->nodes[i]];
if(newnodecov<0) {
addcov=nodecov[transfrag[t]->nodes[i]]*noderate[transfrag[t]->nodes[i]];
newnodecov=0;
}
nodecov[transfrag[t]->nodes[i]]=newnodecov;
pred[np]->exoncov[p]+=addcov;
pred[np]->cov+=addcov;
}
i++;
}
}
transfrag[t]->abundance=0; // delete abundance in order not to use it in short reads
}
}
}
int p=npred;
while(p<pred.Count()) {
if(pred[p]->cov) {
pred[p]->cov/=abs(pred[p]->tlen);
for(int i=0;i<pred[p]->exons.Count();i++)
pred[p]->exoncov[i]/=pred[p]->exons[i].len();
p++;
}
else if(!eonly) { // || !pred[p]->t_eq) {
pred.Delete(p); // I delete all predictions that have 0 coverage unless it's eonly mode
}
else p++;
}
}
}
*/
void get_trf_long_mix(int gno,int edgeno, GIntHash<int> &gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,int& geneno,int strand,
GList<CPrediction>& pred,GVec<int>& trflong,GVec<float>& nodecovall,GBitVec& istranscript,GBitVec& prevpath,BundleData *bdata,bool &first) {
GPVec<GffObj>& guides = bdata->keepguides;
GVec<float> nodecov; // the coverage of all transfrags entering a node
GVec<float> noderate;
for(int i=0;i<gno;i++) {
CGraphnode *inode=no2gnode[i]; // this is here only because of the DEBUG option below
nodecov.cAdd(0.0); // this are all transfrags that link nodes together
float rate=1;
if(i && i<gno-1) {
for(int j=0;j<inode->trf.Count();j++) { // for all transfrags going through node
int t=inode->trf[j];
//if(transfrag[t]->longread && transfrag[t]->nodes[0]<i) { // entering transfrags:
if(transfrag[t]->longread && transfrag[t]->nodes.Last()>i) { // exiting transfrags: this is more consistent with the nodeflux computation
nodecov[i]+=transfrag[t]->abundance;
}
}
if(nodecov[i]) rate=nodecov[i];
if(rate<=0) rate=1; // this shouldn't happen
//fprintf(stderr,"rate=%f\n",rate);
rate=inode->cov/rate;
}
noderate.Add(rate);
//fprintf(stderr,"Node[%d]:%d-%d no2gnode->cov=%f nodecov=%f noderate=%f\n",i,inode->start,inode->end,inode->cov,nodecov[i],noderate[i]);
}
GVec<int> path;
GBitVec pathpat(gno+edgeno);
int minp;
int maxp;
int maxi;
char sign='-';
if(strand) { sign='+';}
int npred=pred.Count();
GVec<CTransfrag> keeptrf;
GVec<int> checktrf;
for(int f=trflong.Count()-1;f>=0;f--) { // if this is a guide it should be reflected in the prediction downstream
path.Clear();
int t=trflong[f];
if(t<0) GError("Stored long transcript is negative!\n");
pathpat=transfrag[t]->pattern;
minp=transfrag[t]->nodes[0];
maxp=transfrag[t]->nodes.Last();
int *pos=gpos[edge(0,minp,gno)];
if(pos) pathpat[*pos]=1;
pos=gpos[edge(maxp,gno-1,gno)];
if(pos) pathpat[*pos]=1;
maxi=minp;
path.Add(maxi);
pathpat[maxi]=1;
istranscript.reset();
float flux=0;
GVec<float> nodeflux;
/*
{ // DEBUG ONLY
fprintf(stderr,"\n\n***Start get_trf_long_mix with maxi=%d minp=%d maxp=%d guide=%d and transcript:",maxi,minp,maxp,transfrag[t]->guide);
for(int i=0;i<transfrag[t]->nodes.Count();i++) fprintf(stderr," %d",transfrag[t]->nodes[i]);
fprintf(stderr," pathpat=");
//printBitVec(pathpat);
fprintf(stderr,"\n");
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(s):parse_trf memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
}
*/
bool tocheck=true;
if(back_to_source_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
path.cAdd(0);
path.Reverse(); // back to source adds the nodes at the end to avoid pushing the list all the time
if(fwd_to_sink_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
flux=long_max_flow(gno,path,istranscript,transfrag,no2gnode,nodeflux,pathpat);
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"flux=%g Path:",flux);
for(int i=0;i<path.Count();i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"\n");
fprintf(stderr,"Nodecapacities:");
for(int i=0;i<path.Count();i++) fprintf(stderr," %f",nodeflux[i]);
fprintf(stderr,"***\n");
}
*/
if(flux) { // these are not valid paths in the graph
tocheck=false;
GVec<GSeg> exons;
GVec<float> exoncov;
int j=1;
int len=0;
float cov=0;
int startnode=1;
int lastnode=path.Count()-2;
uint startpoint=no2gnode[path[startnode]]->end;
uint endpoint=no2gnode[path[lastnode]]->start;
CGraphnode *jnode=no2gnode[path[startnode]];
for(int i=0;i<jnode->trf.Count();i++) { // for all transfrags going through startnode
int t=jnode->trf[i];
if(istranscript[t] && transfrag[t]->longread && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1) {
if(transfrag[t]->nodes[0]==path[startnode]) {
if(transfrag[t]->longstart) {
if(transfrag[t]->longstart<startpoint) { startpoint=transfrag[t]->longstart;}
}
}
}
}
jnode=no2gnode[path[lastnode]];
for(int i=0;i<jnode->trf.Count();i++) { // for all transfrags going through lastnode
int t=jnode->trf[i];
if(istranscript[t] && transfrag[t]->longread && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1) {
if(transfrag[t]->nodes.Last()==path[lastnode]) {
if(transfrag[t]->longend) {
if(transfrag[t]->longend>endpoint) { endpoint=transfrag[t]->longend;}
}
}
}
}
if(startpoint==no2gnode[path[startnode]]->end) startpoint=no2gnode[path[1]]->start;
if(endpoint==no2gnode[path[lastnode]]->start) endpoint=no2gnode[path[lastnode]]->end;
while(j<=lastnode) {
int nodestart=no2gnode[path[j]]->start;
int nodeend=no2gnode[path[j]]->end;
len+=nodeend-nodestart+1;
nodecov[path[j]]-=nodeflux[j];
float ecov=nodeflux[j]*noderate[path[j]];
float excov=ecov;
/*if(mixedMode) {
no2gnode[path[j]]->cov-=ecov;
if(no2gnode[path[j]]->cov<epsilon) no2gnode[path[j]]->cov=0;
}*/
//float excov=nodeflux[j]*noderate[path[j]];
while(j+1<=lastnode && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
//while(j+1<path.Count()-1 && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
j++;
nodeend=no2gnode[path[j]]->end;
ecov=nodeflux[j]*noderate[path[j]];
nodecov[path[j]]-=nodeflux[j];
excov+=ecov;
len+=nodeend-no2gnode[path[j]]->start+1;
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
cov+=excov;
exoncov.Add(excov);
j++;
}
if(transfrag[t]->nodes.Count()==1) transfrag[t]->abundance=0;
//fprintf(stderr,"Store prediction %d with abundance=%f len=%d\n",pred.Count(),cov/len,len);
//GffObj *g=NULL;
if(len>=mintranscriptlen) {
if(first) { geneno++; first=false;}
/*fprintf(stderr,"1 Store prediction %d with abundance=%f totalabundance=%f len=%d startpoint=%d endpoint=%d and exons:",pred.Count(),cov/len,cov,len,startpoint,endpoint);
for(int i=0;i<exons.Count();i++) fprintf(stderr," %d-%d",exons[i].start,exons[i].end);
fprintf(stderr,"\n");*/
GffObj *g=NULL;
if(transfrag[t]->guide) {
g=guides[int(transfrag[t]->guide-1)];
if (g && g->uptr) {
RC_TData &td = *(RC_TData*) (g->uptr);
td.in_bundle=3;
//fprintf(stderr,"sg guide %s is stored\n",g->getID());
}
}
CPrediction *p=new CPrediction(geneno, g,startpoint , endpoint, cov, sign, len);
p->exons=exons;
p->exoncov=exoncov;
p->mergename='.'; // I should not delete this prediction
p->tlen=-p->tlen; // negative transcript length signifies assembly is from a long read
pred.Add(p);
//fprintf(stderr,"Added prediction=%d with totalcov=%.1f\n",pred.Count()-1,pred.Last()->cov);
CTransfrag u(path,pathpat,cov/len);
keeptrf.Add(u);
}
}
}
}
if(tocheck) { // try to see if you can rescue transfrag
if(!guided || transfrag[t]->guide || (no2gnode[transfrag[t]->nodes[0]]->parent[0]==0 &&
no2gnode[transfrag[t]->nodes.Last()]->child.Last()==gno-1) )
// only accept long transfrags that are linked to source and sink
checktrf.Add(t);
}
}
//keeptrf.Sort(longtrCmp); // most abundant transfrag in the graph come first, then the ones with most nodes, then the ones more complete
for(int c=0;c<checktrf.Count();c++) if(transfrag[checktrf[c]]->guide || transfrag[checktrf[c]]->abundance>=readthr) { // only in this case it is worth considering it as a potential prediction
int t=checktrf[c];
/*fprintf(stderr,"checktrf[%d]=%d with abundance=%f with start=%d end=%d nodes:",c,t,transfrag[t]->abundance,transfrag[t]->longstart,transfrag[t]->longend);
for(int i=0;i<transfrag[t]->nodes.Count();i++) fprintf(stderr," %d",transfrag[t]->nodes[i]);
fprintf(stderr,"\n");*/
GVec<int> tmatch;
float abundancesum=best_trf_match(transfrag[t],keeptrf,no2gnode,gno,tmatch);
if(abundancesum>0) {
if(!transfrag[t]->shortread && transfrag[t]->nodes.Count()>1) {
for(int j=0;j<tmatch.Count();j++) { // found good match(es) but transcript has more than one node for this to make sense
float abundprop=transfrag[t]->abundance*keeptrf[tmatch[j]].abundance/abundancesum;
int p=0;
int i=0;
int np=npred+tmatch[j]; // how do I know that keeptrf lead to a prediction -> because keeptrf represent the predictions that were added
//fprintf(stderr,"Add %.1f to prediction %d with cov=%.1f\n",abundprop,np,pred[np]->cov);
while(i<transfrag[t]->nodes.Count() && p<pred[np]->exons.Count()) {
if(no2gnode[transfrag[t]->nodes[i]]->end<pred[np]->exons[p].start) i++;
else if(pred[np]->exons[p].end<no2gnode[transfrag[t]->nodes[i]]->start) p++;
else { // the two intersect (I can only have the full node included in exon)
if(nodecov[transfrag[t]->nodes[i]]>epsilon){
//float addcov=transfrag[t]->abundance*noderate[transfrag[t]->nodes[i]];
float addcov=abundprop*no2gnode[transfrag[t]->nodes[i]]->len();
float newnodecov=nodecov[transfrag[t]->nodes[i]]-addcov/noderate[transfrag[t]->nodes[i]];
//fprintf(stderr,"newnodecov=%.1f\n",newnodecov);
if(newnodecov<0) {
newnodecov=nodecov[transfrag[t]->nodes[i]]*keeptrf[tmatch[j]].abundance/abundancesum;
addcov=newnodecov*noderate[transfrag[t]->nodes[i]];
newnodecov=nodecov[transfrag[t]->nodes[i]]-newnodecov;
}
nodecov[transfrag[t]->nodes[i]]=newnodecov;
pred[np]->exoncov[p]+=addcov;
pred[np]->cov+=addcov;
//fprintf(stderr,"...add cov=%1.f (totalcov=%.1f) to exon[%d] and pred[%d]->cov=%f\n",addcov/no2gnode[transfrag[t]->nodes[i]]->len(),addcov,p,np,pred[np]->cov);
}
i++;
}
}
}
transfrag[t]->abundance=0;
}
}
else {
if(!eonly || transfrag[t]->guide) { // store it as an independent prediction
pathpat=transfrag[t]->pattern; // not used right now but maybe in the future?
path.Clear();
path.cAdd(0);
path.Add(transfrag[t]->nodes[0]);
for(int j=1;j<transfrag[t]->nodes.Count();j++) {
if(transfrag[t]->nodes[j]!=1+transfrag[t]->nodes[j-1] ||
no2gnode[transfrag[t]->nodes[j]]->start-1!=no2gnode[transfrag[t]->nodes[j-1]]->end) {
// check if transfrag t1 is incomplete between node[n-1] and node [n]
int *pos=gpos[edge(transfrag[t]->nodes[j-1],transfrag[t]->nodes[j],gno)];
if(!pos || !transfrag[t]->pattern[*pos]) { // incomplete transfrag
break;
}
if(pos) pathpat[*pos]=1;
path.Add(transfrag[t]->nodes[j]);
}
else path.Add(transfrag[t]->nodes[j]);
}
if(path.Last()==transfrag[t]->nodes.Last()) { // this transfrag is complete, might be worth rescuing
uint startpoint=no2gnode[path[1]]->end;
uint endpoint=no2gnode[path.Last()]->start;
if(transfrag[t]->longstart) startpoint=transfrag[t]->longstart;
if(transfrag[t]->longend) endpoint=transfrag[t]->longend;
int sink=gno-1;
path.Add(sink);
GVec<GSeg> exons;
GVec<float> exoncov;
int j=1;
int len=0;
float cov=0;
while(j<path.Count()-1) {
int nodestart=no2gnode[path[j]]->start;
int nodeend=no2gnode[path[j]]->end;
// nodecov[path[j]]-=transfrag[t]->abundance; // do not need this here anymore
len+=nodeend-nodestart+1;
float excov=0;
if(nodecov[path[j]]>epsilon) {
excov=transfrag[t]->abundance*no2gnode[path[j]]->len();
float newnodecov=nodecov[path[j]]-excov/noderate[path[j]];
if(newnodecov<0) {
excov=nodecov[path[j]]*noderate[path[j]];
newnodecov=0;
}
nodecov[path[j]]=newnodecov;
}
while(j+1<path.Count()-1 && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
j++;
len+=no2gnode[path[j]]->len();
nodeend=no2gnode[path[j]]->end;
float addcov=0;
if(nodecov[path[j]]>epsilon) {
addcov=transfrag[t]->abundance*no2gnode[path[j]]->len();
float newnodecov=nodecov[path[j]]-addcov/noderate[path[j]];
if(newnodecov<0) {
addcov=nodecov[path[j]]*noderate[path[j]];
newnodecov=0;
}
nodecov[path[j]]=newnodecov;
}
excov+=addcov;
//excov+=transfrag[t]->abundance*noderate[path[j]];
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
cov+=excov;
exoncov.Add(excov);
j++;
}
//GffObj *g=NULL;
if(len>=mintranscriptlen) {
if(first) { geneno++; first=false;}
GffObj *g=NULL;
if(transfrag[t]->guide) {
g=guides[int(transfrag[t]->guide-1)];
if (g && g->uptr) {
RC_TData &td = *(RC_TData*) (g->uptr);
td.in_bundle=3;
//fprintf(stderr,"sg guide %s is stored\n",g->getID());
}
}
//fprintf(stderr,"2 Store prediction %d:%d-%d with len=%d and abundance=%f startpoint=%d endpoint=%d\n",pred.Count(),exons[0].start ,exons.Last().end,len,cov/len,startpoint,endpoint);
CPrediction *p=new CPrediction(geneno, g,startpoint , endpoint, cov, sign, len);
p->exons=exons;
p->exoncov=exoncov;
p->tlen=-p->tlen; // negative transcript length signifies assembly is from a long read
pred.Add(p);
CTransfrag u(path,pathpat,cov/len);
keeptrf.Add(u);
}
}
}
transfrag[t]->abundance=0;
}
}
if(pred.Count()>npred) {
for(int t=0;t<transfrag.Count();t++) if(transfrag[t]->longread) {
if(!transfrag[t]->shortread && transfrag[t]->nodes.Count()>1 && transfrag[t]->abundance>epsilon && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1 ) {
/*fprintf(stderr,"Consider transfrag[%d]->abundance=%f with start=%d end=%d nodes:",t,transfrag[t]->abundance,transfrag[t]->longstart,transfrag[t]->longend);
for(int i=0;i<transfrag[t]->nodes.Count();i++) fprintf(stderr," %d",transfrag[t]->nodes[i]);
fprintf(stderr,"\n");*/
GVec<int> tmatch;
float abundancesum=best_trf_match(transfrag[t],keeptrf,no2gnode,gno,tmatch); // abundancesum is the sum of all matching transcripts
if(abundancesum>0) for(int j=0;j<tmatch.Count();j++){ // found good match(es)
float abundprop=transfrag[t]->abundance*keeptrf[tmatch[j]].abundance/abundancesum; // proportion of transcript that will be allocated to this matching one
int p=0;
int i=0;
int np=npred+tmatch[j];
//fprintf(stderr,"Add %.1f to prediction %d with cov=%.1f",abundprop,np,pred[np]->cov);
//for(int i=0;i<keeptrf[tmatch[j]].nodes.Count();i++) fprintf(stderr," %d",keeptrf[tmatch[j]].nodes[i]);
//fprintf(stderr,"\n");
while(i<transfrag[t]->nodes.Count() && p<pred[np]->exons.Count()) {
if(no2gnode[transfrag[t]->nodes[i]]->end<pred[np]->exons[p].start) i++;
else if(pred[np]->exons[p].end<no2gnode[transfrag[t]->nodes[i]]->start) p++;
else { // the two intersect (I can only have the full node included in exon)
if(nodecov[transfrag[t]->nodes[i]]>epsilon){
//float addcov=transfrag[t]->abundance*noderate[transfrag[t]->nodes[i]];
float addcov=abundprop*no2gnode[transfrag[t]->nodes[i]]->len();
float newnodecov=nodecov[transfrag[t]->nodes[i]]-addcov/noderate[transfrag[t]->nodes[i]];
//fprintf(stderr,"newnodecov=%.1f\n",newnodecov);
if(newnodecov<0) {
newnodecov=nodecov[transfrag[t]->nodes[i]]*keeptrf[tmatch[j]].abundance/abundancesum;
addcov=newnodecov*noderate[transfrag[t]->nodes[i]];
newnodecov=nodecov[transfrag[t]->nodes[i]]-newnodecov;
}
nodecov[transfrag[t]->nodes[i]]=newnodecov;
pred[np]->exoncov[p]+=addcov;
pred[np]->cov+=addcov;
//fprintf(stderr,"...add cov=%1.f (totalcov=%.1f) to exon[%d] and pred[%d]->cov=%f\n",addcov/no2gnode[transfrag[t]->nodes[i]]->len(),addcov,p,np,pred[np]->cov);
}
i++;
}
}
}
}
if(!transfrag[t]->nodes[0] || transfrag[t]->nodes.Last()==gno-1) // deletes starting transfrangs
transfrag[t]->abundance=0;
else transfrag[t]->abundance=transfrag[t]->usepath; // this restores tranfrag[t] abundance to what it was before so when I do the short read flux I can utilizes fully
transfrag[t]->usepath=-1;
}
int p=npred;
while(p<pred.Count()) {
if(pred[p]->cov) {
//fprintf(stderr,"Pred[%d] has coverage=%.1f (totalcov=%.1f)\n",p,pred[p]->cov,pred[p]->cov/abs(pred[p]->tlen));
pred[p]->cov/=abs(pred[p]->tlen);
for(int i=0;i<pred[p]->exons.Count();i++)
pred[p]->exoncov[i]/=pred[p]->exons[i].len();
// adjust start/endpoints
if(pred[p]->start!=pred[p]->exons[0].start) {
pred[p]->tlen+=pred[p]->start-pred[p]->exons[0].start;
pred[p]->exons[0].start=pred[p]->start;
}
if(pred[p]->end!=pred[p]->exons.Last().end) {
pred[p]->tlen+=pred[p]->exons.Last().end-pred[p]->end;
pred[p]->exons.Last().end=pred[p]->end;
}
p++;
}
else if(!eonly) { // || !pred[p]->t_eq) {
//fprintf(stderr,"delete prediction %d\n",p);
pred.Delete(p); // I delete all predictions that have 0 coverage unless it's eonly mode
}
else p++;
}
}
int nkeep=keeptrf.Count();
/*for(int i=nkeep-1;i>nkept-1;i--) { // delete all kept transfrags we are not confident in
keeptrf.Delete(i);
}*/
for(int i=0;i<nkeep;i++) keeptrf[i].weak=i+npred; // I need to remember the prediction it represents
keeptrf.Sort(longtrCmp); // most abundant transfrag in the graph comes first, then the one with most nodes, then the one more complete
float flux=0;
GVec<float> nodeflux;
path.Clear();
for(int i=0;i<nkeep;i++) { // compute flux from short read data here
istranscript.reset();
nodeflux.Clear();
bool full=true;
// make sure source and sink are present and they are connected in the pattern of the prediction
if(keeptrf[i].nodes[0]) {
keeptrf[i].nodes.Insert(0,0);
keeptrf[i].pattern[0]=1;
}
int sink=gno-1;
if(keeptrf[i].nodes.Last()!=gno-1) {
keeptrf[i].nodes.Add(sink);
keeptrf[i].pattern[sink]=1;
}
int key=edge(0,keeptrf[i].nodes[1],gno);
int *pos=NULL;
if(key<(int)gpos.Count()) pos=gpos[key];
if(pos!=NULL) keeptrf[i].pattern[*pos]=1;
pos=NULL;
int n=keeptrf[i].nodes.Count();
key=edge(keeptrf[i].nodes[n-2],sink,gno);
if(pos!=NULL) keeptrf[i].pattern[*pos]=1;
flux=push_max_flow(gno,keeptrf[i].nodes,istranscript,transfrag,no2gnode,nodeflux,keeptrf[i].pattern,gpos,full);
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"flux=%g Path:",flux);
for(int j=0;j<keeptrf[i].nodes.Count();j++) fprintf(stderr," %d",keeptrf[i].nodes[j]);
fprintf(stderr,"***\n");
}
*/
if(flux>epsilon) {
bool included=true;
float cov=store_transcript(pred,keeptrf[i].nodes,nodeflux,nodecovall,no2gnode,geneno,first,strand,gno,gpos,included,prevpath);
if(cov) {
//fprintf(stderr,"Coverage of long pred[%d]=%f vs. short pred=%f\n",keeptrf[i].weak,pred[keeptrf[i].weak]->cov,pred.Last()->cov);
if(pred.Last()->cov>pred[keeptrf[i].weak]->cov) { // new prediction is better than the previous one -- shouldn't I add this to previous prediction?
int p=keeptrf[i].weak;
pred[p]->cov=pred.Last()->cov;
for(int k=0;k<pred[p]->exons.Count();k++) {
pred[p]->exoncov[k]=pred.Last()->exoncov[k];
}
/*pred[p]->start=pred.Last()->start;
pred[p]->end=pred.Last()->end;
pred[p]->exons[0].start=pred.Last()->exons[0].start;
pred[p]->exons.Last().end=pred.Last()->exons.Last().end;
pred[p]->tlen=pred.Last()->tlen;*/
//pred[p]->tlen=abs(pred[p]->tlen);
}
delete pred.Pop(); //prevent memory leak, popped element is otherwise "forgotten"
}
}
}
}
void get_trf_long(int gno,int edgeno, GIntHash<int> &gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,
int& geneno,int strand,GList<CPrediction>& pred,GVec<int>& trflong,BundleData *bdata) {
GPVec<GffObj>& guides = bdata->keepguides;
GVec<float> nodecov; // the coverage of all transfrags entering a node
GVec<float> noderate;
for(int i=0;i<gno;i++) {
CGraphnode *inode=no2gnode[i]; // this is here only because of the DEBUG option below
nodecov.cAdd(0.0); // this are all transfrags that link nodes together
float rate=1;
if(i && i<gno-1) {
for(int j=0;j<inode->trf.Count();j++) { // for all transfrags going through node
int t=inode->trf[j];
//if(transfrag[t]->nodes[0]<i) { // entering transfrags:
if(transfrag[t]->nodes.Last()>i) { // exiting transfrags: this is more consistent with the nodeflux computation
nodecov[i]+=transfrag[t]->abundance;
}
}
if(nodecov[i]) rate=nodecov[i];
if(rate<=0) rate=1; // this shouldn't happen
//fprintf(stderr,"rate=%f\n",rate);
rate=inode->cov/rate;
}
noderate.Add(rate);
//fprintf(stderr,"Node[%d]:%d-%d no2gnode->cov=%f nodecov=%f noderate=%f\n",i,inode->start,inode->end,inode->cov,nodecov[i],noderate[i]);
}
GBitVec istranscript(transfrag.Count());
GVec<int> path;
GBitVec pathpat(gno+edgeno);
int minp;
int maxp;
int maxi;
char sign='-';
if(strand) { sign='+';}
int npred=pred.Count();
GVec<CTransfrag> keeptrf;
GVec<int> checktrf;
for(int f=trflong.Count()-1;f>=0;f--) { // if this is a guide it should be reflected in the prediction downstream
path.Clear();
int t=trflong[f];
if(t<0) GError("Stored long transcript is negative!\n");
pathpat=transfrag[t]->pattern;
minp=transfrag[t]->nodes[0];
maxp=transfrag[t]->nodes.Last();
//if(no2gnode[transfrag[t]->nodes[0]]->hardstart) {
int *pos=gpos[edge(0,minp,gno)];
if(pos) pathpat[*pos]=1;
//minp=0;
//}
//if(no2gnode[transfrag[t]->nodes.Last()]->hardend) {
pos=gpos[edge(maxp,gno-1,gno)];
if(pos) pathpat[*pos]=1;
//maxp=gno-1;
//}
maxi=minp;
path.Add(maxi);
pathpat[maxi]=1;
istranscript.reset();
float flux=0;
//float fragno=0;
GVec<float> nodeflux;
/*
{ // DEBUG ONLY
fprintf(stderr,"\n\n***Start get_trf_long with maxi=%d minp=%d maxp=%d guide=%d and transcript:",maxi,minp,maxp,transfrag[t]->guide);
for(int i=0;i<transfrag[t]->nodes.Count();i++) {
if(i) {
pos=gpos[edge(transfrag[t]->nodes[i-1],transfrag[t]->nodes[i],gno)];
if(pos && pathpat[*pos])
fprintf(stderr,"-");
}
fprintf(stderr," %d",transfrag[t]->nodes[i]);
}
fprintf(stderr," pathpat=");
//printBitVec(pathpat);
fprintf(stderr,"\n");
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(s):parse_trf memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
}
*/
bool tocheck=true;
if(back_to_source_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
path.cAdd(0);
path.Reverse(); // back to source adds the nodes at the end to avoid pushing the list all the time
if(fwd_to_sink_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
flux=long_max_flow(gno,path,istranscript,transfrag,no2gnode,nodeflux,pathpat);
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"flux=%g Path:",flux);
for(int i=0;i<path.Count();i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"\n");
fprintf(stderr,"Nodecapacities:");
for(int i=0;i<path.Count();i++) fprintf(stderr," %f",nodeflux[i]);
fprintf(stderr,"***\n");
}
*/
if(flux) { // these are not valid paths in the graph
tocheck=false;
GVec<GSeg> exons;
GVec<float> exoncov;
int j=1;
int len=0;
float cov=0;
//int startnode=j;
int lastnode=path.Count()-2;
//uint startpoint=no2gnode[path[lastnode]]->end;
//uint endpoint=no2gnode[path[1]]->start;
/* if(mixedMode) { // establish start/end point of path
while(j<path.Count()-1) {
CGraphnode *jnode=no2gnode[path[j]];
for(int i=0;i<jnode->trf.Count();i++) { // for all transfrags going through node
int t=jnode->trf[i];
if(istranscript[t] && transfrag[t]->longread && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1) {
if(transfrag[t]->nodes[0]==path[j]) {
if(transfrag[t]->longstart) {
if(transfrag[t]->longstart<startpoint) { startpoint=transfrag[t]->longstart; startnode=j;}
}
else if(jnode->start<startpoint) { startpoint=jnode->start; startnode=j;}
}
if(transfrag[t]->nodes.Last()==path[j]) {
if(transfrag[t]->longend) {
if(transfrag[t]->longend>endpoint) { endpoint=transfrag[t]->longend; lastnode=j;}
}
else if(jnode->end>endpoint) {endpoint=jnode->end; lastnode=j;}
}
}
}
j++;
}
if(startpoint>endpoint) {
j=1;
lastnode=path.Count()-2;
startpoint=no2gnode[path[1]]->start;
endpoint=no2gnode[path[lastnode]]->end;
}
else j=startnode;
//fprintf(stderr,"startnode=%d lastnode=%d startpoint=%d endpoint=%d\n",path[startnode],path[lastnode],startpoint,endpoint);
}*/
while(j<=lastnode) {
//while(j<path.Count()-1) {
int nodestart=no2gnode[path[j]]->start;
int nodeend=no2gnode[path[j]]->end;
nodecov[path[j]]-=nodeflux[j];
len+=nodeend-nodestart+1;
float ecov=nodeflux[j]*noderate[path[j]];
float excov=ecov;
//fprintf(stderr,"excov+=%f * %f = %f\n",nodeflux[j],noderate[path[j]],excov);
/*if(mixedMode) {
no2gnode[path[j]]->cov-=ecov;
if(no2gnode[path[j]]->cov<epsilon) no2gnode[path[j]]->cov=0;
}*/
//float excov=nodeflux[j]*noderate[path[j]];
while(j+1<=lastnode && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
//while(j+1<path.Count()-1 && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
j++;
nodecov[path[j]]-=nodeflux[j];
nodeend=no2gnode[path[j]]->end;
ecov=nodeflux[j]*noderate[path[j]];
excov+=ecov;
//fprintf(stderr,"excov+=%f * %f = %f\n",nodeflux[j],noderate[path[j]],excov);
len+=nodeend-no2gnode[path[j]]->start+1;
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
//fprintf(stderr,"excov=%f\n",excov/(exon.end-exon.start+1));
cov+=excov;
//fprintf(stderr,"cov+=%f=%f\n",excov,cov);
exoncov.Add(excov);
j++;
}
if(transfrag[t]->nodes.Count()==1) transfrag[t]->abundance=0;
//fprintf(stderr,"Store prediction %d with abundance=%f len=%d\n",pred.Count(),cov/len,len);
GffObj *g=NULL;
if(transfrag[t]->guide) {
g=guides[int(transfrag[t]->guide-1)];
if (g && g->uptr) {
RC_TData &td = *(RC_TData*) (g->uptr);
td.in_bundle=3;
//fprintf(stderr,"sg guide %s is stored\n",g->getID());
}
}
if(!eonly || g) {
/*fprintf(stderr,"1 Store prediction %d with abundance=%f len=%d and exons:",pred.Count(),cov/len,len);
for(int i=0;i<exons.Count();i++) fprintf(stderr," %d-%d",exons[i].start,exons[i].end);
fprintf(stderr,"\n");*/
CPrediction *p=new CPrediction(geneno, g,exons[0].start , exons.Last().end, cov, sign, len);
p->exons=exons;
p->exoncov=exoncov;
p->mergename='.'; // I should not delete this prediction
p->tlen=-p->tlen; // negative transcript length signifies assembly is from a long read
pred.Add(p);
CTransfrag u(path,pathpat,cov/len);
keeptrf.Add(u);
}
}
else if(transfrag[t]->guide) {
checktrf.Add(t);
}
}
}
if(tocheck) { // try to see if you can rescue transfrag -> they are stored from more abundant to least -> not if using mixedMode
checktrf.Add(t);
}
}
//keeptrf.Sort(longtrCmp); // most abundant transfrag in the graph come first, then the ones with most nodes, then the ones more complete
for(int c=0;c<checktrf.Count();c++) if(transfrag[checktrf[c]]->guide || transfrag[checktrf[c]]->abundance>=readthr) { // only in this case it is worth considering it as a potential prediction
int t=checktrf[c];
//fprintf(stderr,"checktrf[%d]=%d with abundance=%f\n",c,t,transfrag[t]->abundance);
GVec<int> tmatch;
float abundancesum=best_trf_match(transfrag[t],keeptrf,no2gnode,gno,tmatch);
if(abundancesum>0) for(int j=0;j<tmatch.Count();j++){ // found good match(es)
float abundprop=transfrag[t]->abundance*keeptrf[tmatch[j]].abundance/abundancesum;
int p=0;
int i=0;
int np=npred+tmatch[j]; // how do I know that keeptrf lead to a prediction -> because keeptrf represent the predictions that were added
while(i<transfrag[t]->nodes.Count() && p<pred[np]->exons.Count()) {
if(no2gnode[transfrag[t]->nodes[i]]->end<pred[np]->exons[p].start) i++;
else if(pred[np]->exons[p].end<no2gnode[transfrag[t]->nodes[i]]->start) p++;
else { // the two intersect (I can only have the full node included in exon)
if(nodecov[transfrag[t]->nodes[i]]>epsilon){
//float addcov=transfrag[t]->abundance*noderate[transfrag[t]->nodes[i]];
float addcov=abundprop*no2gnode[transfrag[t]->nodes[i]]->len();
float newnodecov=nodecov[transfrag[t]->nodes[i]]-addcov/noderate[transfrag[t]->nodes[i]];
if(newnodecov<0) {
newnodecov=nodecov[transfrag[t]->nodes[i]]*keeptrf[tmatch[j]].abundance/abundancesum;
addcov=newnodecov*noderate[transfrag[t]->nodes[i]];
newnodecov=nodecov[transfrag[t]->nodes[i]]-newnodecov;
}
nodecov[transfrag[t]->nodes[i]]=newnodecov;
pred[np]->exoncov[p]+=addcov;
pred[np]->cov+=addcov;
}
i++;
}
}
}
else if(!eonly || transfrag[t]->guide) { // store it as an independent prediction
pathpat=transfrag[t]->pattern; // not used right now but maybe in the future?
path.Clear();
path.cAdd(0);
path.Add(transfrag[t]->nodes[0]);
for(int j=1;j<transfrag[t]->nodes.Count();j++) {
if(transfrag[t]->nodes[j]!=1+transfrag[t]->nodes[j-1] ||
no2gnode[transfrag[t]->nodes[j]]->start-1!=no2gnode[transfrag[t]->nodes[j-1]]->end) {
// check if transfrag t1 is incomplete between node[n-1] and node [n]
int *pos=gpos[edge(transfrag[t]->nodes[j-1],transfrag[t]->nodes[j],gno)];
if(!pos || !transfrag[t]->pattern[*pos]) { // incomplete transfrag
break;
}
if(pos) pathpat[*pos]=1;
path.Add(transfrag[t]->nodes[j]);
}
else path.Add(transfrag[t]->nodes[j]);
}
if(path.Last()==transfrag[t]->nodes.Last()) { // this transfrag is complete, might be worth rescuing
int sink=gno-1;
path.Add(sink);
GVec<GSeg> exons;
GVec<float> exoncov;
int j=1;
int len=0;
float cov=0;
while(j<path.Count()-1) {
int nodestart=no2gnode[path[j]]->start;
int nodeend=no2gnode[path[j]]->end;
// nodecov[path[j]]-=transfrag[t]->abundance; // do not need this here anymore
len+=nodeend-nodestart+1;
float excov=0;
if(nodecov[path[j]]>epsilon) {
excov=transfrag[t]->abundance*no2gnode[path[j]]->len();
float newnodecov=nodecov[path[j]]-excov/noderate[path[j]];
if(newnodecov<0) {
excov=nodecov[path[j]]*noderate[path[j]];
newnodecov=0;
}
nodecov[path[j]]=newnodecov;
}
while(j+1<path.Count()-1 && no2gnode[path[j]]->end+1==no2gnode[path[j+1]]->start) {
j++;
len+=no2gnode[path[j]]->len();
nodeend=no2gnode[path[j]]->end;
float addcov=0;
if(nodecov[path[j]]>epsilon) {
addcov=transfrag[t]->abundance*no2gnode[path[j]]->len();
float newnodecov=nodecov[path[j]]-addcov/noderate[path[j]];
if(newnodecov<0) {
addcov=nodecov[path[j]]*noderate[path[j]];
newnodecov=0;
}
nodecov[path[j]]=newnodecov;
}
excov+=addcov;
//excov+=transfrag[t]->abundance*noderate[path[j]];
}
GSeg exon(nodestart,nodeend);
exons.Add(exon);
cov+=excov;
exoncov.Add(excov);
j++;
}
GffObj *g=NULL;
if(transfrag[t]->guide) {
g=guides[int(transfrag[t]->guide-1)];
if (g && g->uptr) {
RC_TData &td = *(RC_TData*) (g->uptr);
td.in_bundle=3;
//fprintf(stderr,"sg guide %s is stored\n",g->getID());
}
}
//fprintf(stderr,"2 Store prediction %d:%d-%d with len=%d and abundance=%f\n",pred.Count(),exons[0].start ,exons.Last().end,len,cov/len);
CPrediction *p=new CPrediction(geneno, g,exons[0].start , exons.Last().end, cov, sign, len);
p->exons=exons;
p->exoncov=exoncov;
p->tlen=-p->tlen; // negative transcript length signifies assembly is from a long read
pred.Add(p);
CTransfrag u(path,pathpat,cov/len);
keeptrf.Add(u);
}
}
transfrag[t]->abundance=0;
}
if(pred.Count()>npred) {
/*if(mixedMode) {
for(int t=0;t<transfrag.Count();t++) {
if(transfrag[t]->longread && (!transfrag[t]->nodes[0] || transfrag[t]->nodes.Last()==gno-1) )
transfrag[t]->abundance=0;
else
transfrag[t]->abundance=transfrag[t]->usepath;
transfrag[t]->usepath=-1;
}
}
else */for(int t=0;t<transfrag.Count();t++) if(transfrag[t]->longread) { // longreads mode --> tries to add all transfrags to predictions
if(transfrag[t]->abundance>epsilon && transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1 ) {
/*fprintf(stderr,"Consider transfrag[%d]->abundance=%f with start=%d end=%d nodes:",t,transfrag[t]->abundance,transfrag[t]->longstart,transfrag[t]->longend);
for(int i=0;i<transfrag[t]->nodes.Count();i++) fprintf(stderr," %d",transfrag[t]->nodes[i]);
fprintf(stderr,"\n");*/
GVec<int> tmatch;
float abundancesum=best_trf_match(transfrag[t],keeptrf,no2gnode,gno,tmatch);
if(abundancesum>0) for(int j=0;j<tmatch.Count();j++){ // found good match(es)
float abundprop=transfrag[t]->abundance*keeptrf[tmatch[j]].abundance/abundancesum;
//fprintf(stderr,"Added %.1f to prediction:",abundprop);
//for(int i=0;i<keeptrf[tmatch[j]].nodes.Count();i++) fprintf(stderr," %d",keeptrf[tmatch[j]].nodes[i]);
int p=0;
int i=0;
int np=npred+tmatch[j];
while(i<transfrag[t]->nodes.Count() && p<pred[np]->exons.Count()) {
if(no2gnode[transfrag[t]->nodes[i]]->end<pred[np]->exons[p].start) i++;
else if(pred[np]->exons[p].end<no2gnode[transfrag[t]->nodes[i]]->start) p++;
else { // the two intersect (I can only have the full node included in exon)
if(nodecov[transfrag[t]->nodes[i]]>epsilon){
//float addcov=transfrag[t]->abundance*noderate[transfrag[t]->nodes[i]];
float addcov=abundprop*no2gnode[transfrag[t]->nodes[i]]->len();
float newnodecov=nodecov[transfrag[t]->nodes[i]]-addcov/noderate[transfrag[t]->nodes[i]];
if(newnodecov<0) {
newnodecov=nodecov[transfrag[t]->nodes[i]]*keeptrf[tmatch[j]].abundance/abundancesum;
addcov=newnodecov*noderate[transfrag[t]->nodes[i]];
newnodecov=nodecov[transfrag[t]->nodes[i]]-newnodecov;
}
nodecov[transfrag[t]->nodes[i]]=newnodecov;
//fprintf(stderr," newnodecov=%f\n",newnodecov);
pred[np]->exoncov[p]+=addcov;
pred[np]->cov+=addcov;
}
i++;
}
}
//fprintf(stderr," new abundance=%f\n",pred[np]->cov/pred[np]->tlen);
}
}
transfrag[t]->abundance=0; // delete abundance in order not to use it in short reads
}
int p=npred;
while(p<pred.Count()) {
if(pred[p]->cov) {
pred[p]->cov/=abs(pred[p]->tlen);
for(int i=0;i<pred[p]->exons.Count();i++)
pred[p]->exoncov[i]/=pred[p]->exons[i].len();
p++;
}
else if(!eonly) { // || !pred[p]->t_eq) {
//fprintf(stderr,"delete prediction %d\n",p);
pred.Delete(p); // I delete all predictions that have 0 coverage unless it's eonly mode
}
else p++;
}
}
}
/*
void parse_trf_long(int maxi,int gno,int edgeno, GIntHash<int> &gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,
int& geneno,bool first,int strand,GList<CPrediction>& pred,GVec<float>& nodecov,
GBitVec& istranscript,GBitVec& removable,GBitVec& usednode,float maxcov,GBitVec& prevpath,GVec<int>& trflong) {
GVec<int> path;
GBitVec pathpat(gno+edgeno);
int minp=maxi;
int maxp=maxi;
bool usetrflong=false;
if(trflong.Count()) {
int t=trflong.Pop();
usetrflong=true;
pathpat=pathpat | transfrag[t]->pattern;
minp=transfrag[t]->nodes[0];
maxp=transfrag[t]->nodes.Last();
int *pos=gpos[edge(0,minp,gno)];
if(pos) pathpat[*pos]=1;
pos=gpos[edge(maxp,gno-1,gno)];
if(pos) pathpat[*pos]=1;
maxi=minp;
}
path.Add(maxi);
pathpat[maxi]=1;
bool full=false;
istranscript.reset();
float flux=0;
//float fragno=0;
GVec<float> nodeflux;
if(back_to_source_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
if(includesource) path.cAdd(0);
path.Reverse(); // back to source adds the nodes at the end to avoid pushing the list all the time
if(fwd_to_sink_fast_long(maxi,path,minp,maxp,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
flux=push_max_flow(gno,path,istranscript,transfrag,no2gnode,nodeflux,pathpat,gpos,full);
}
}
if(flux>epsilon) {
bool included=true;
float cov=store_transcript(pred,path,nodeflux,nodecov,no2gnode,geneno,first,strand,gno,gpos,included,prevpath,full);
if(!usetrflong && (included || cov<isofrac*maxcov)) { // maybe not use it for long reads if
usednode[maxi]=1;
maxi=0;
maxcov=0;
//cont=false;
}
else if(cov>maxcov) maxcov=cov;
}
else {
usednode[maxi]=1;
maxi=0;
maxcov=0;
//cont=false;
}
// Node coverages:
for(int i=1;i<gno;i++) {
if(!usednode[i] && nodecov[i]>nodecov[maxi]) maxi=i;
if(i<gno-1 && no2gnode[i]->end==no2gnode[i+1]->start) {
for(int t=0;t<no2gnode[i]->trf.Count();t++) if(transfrag[t]->weak>0 && transfrag[t]->pattern[i+1]) transfrag[t]->weak=-1;
}
}
//if(nodecov[maxi]>=readthr && (!specific || cont)) { // if I still have nodes that are above coverage threshold
if(nodecov[maxi]>=1) { // if I still have nodes to use
path.Clear();
nodeflux.Clear();
parse_trf_long(maxi,gno,edgeno,gpos,no2gnode,transfrag,geneno,first,strand,pred,nodecov,istranscript,removable,usednode,maxcov,prevpath,trflong);
}
}
*/
void parse_trf(int maxi,int gno,int edgeno, GIntHash<int> &gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,
int& geneno,bool first,int strand,GList<CPrediction>& pred,GVec<float>& nodecov,
GBitVec& istranscript,GBitVec& usednode,float maxcov,GBitVec& prevpath) {
GVec<int> path;
path.Add(maxi);
GBitVec pathpat(gno+edgeno);
pathpat[maxi]=1;
istranscript.reset();
float flux=0;
//float fragno=0;
GVec<float> nodeflux;
/*
{ // DEBUG ONLY
fprintf(stderr,"\n\n***Start parse_trf with maxi=%d and cov=%f\n",maxi,nodecov[maxi]);
//fprintf(stderr,"Transcripts before path:");
//for(int i=0;i<transfrag.Count();i++) if(istranscript[i]) fprintf(stderr," %d",i);
//fprintf(stderr,"\n");
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(s):parse_trf memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
}
*/
if(back_to_source_fast(maxi,path,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
if(includesource) path.cAdd(0);
path.Reverse(); // back to source adds the nodes at the end to avoid pushing the list all the time
if(fwd_to_sink_fast(maxi,path,pathpat,transfrag,no2gnode,nodecov,gno,gpos)) {
bool full=true;
flux=push_max_flow(gno,path,istranscript,transfrag,no2gnode,nodeflux,pathpat,gpos,full);
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"flux=%g Path:",flux);
for(int i=0;i<path.Count();i++) fprintf(stderr," %d",path[i]);
fprintf(stderr,"***\n");
}
*/
}
/*else {
//pathpat.reset();
//pathpat[maxi]=1;
}*/
}
/*else {
//pathpat.reset();
//pathpat[maxi]=1;
}*/
//bool cont=true;
if(flux>epsilon) {
bool included=true;
float cov=store_transcript(pred,path,nodeflux,nodecov,no2gnode,geneno,first,strand,gno,gpos,included,prevpath);
/*
{ // DEBUG ONLY
//fprintf(stderr,"Prevpath=");
//printBitVec(prevpath);
//fprintf(stderr,"\n");
fprintf(stderr,"cov=%f maxcov=%f\n",cov,maxcov);
}
*/
float frac=isofrac;
if(mixedMode && frac<ERROR_PERC) frac=ERROR_PERC;
if(included || cov<frac*maxcov) {
/*
if(sensitivitylevel) usednode[maxi]=1;
else usednode = usednode | prevpath;
*/
//fprintf(stderr,"included\n");
usednode[maxi]=1;
//fprintf(stderr,"used maxi=%d\n",maxi);
maxi=0;
maxcov=0;
//cont=false;
}
else if(cov>maxcov) maxcov=cov;
}
else {
/*
if(sensitivitylevel) usednode[maxi]=1; // start at different locations in graph
else {
usednode = usednode | prevpath;
usednode = usednode | pathpat;
}
*/
usednode[maxi]=1;
//fprintf(stderr,"set usednode of %d\n",maxi);
maxi=0;
maxcov=0;
//cont=false;
}
//fprintf(stderr,"maxcov=%g gno=%d\n",maxcov,gno);
// Node coverages:
for(int i=1;i<gno;i++)
if(!usednode[i] && nodecov[i]>nodecov[maxi]) maxi=i;
//fprintf(stderr," maxi=%d nodecov=%f\n",maxi,nodecov[maxi]);
//if(nodecov[maxi]>=readthr && (!specific || cont)) { // if I still have nodes that are above coverage threshold
if(nodecov[maxi]>=1) { // if I still have nodes to use
/*
{ // DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"\nAfter update:\n");
for(int i=0;i<gno;i++) {
fprintf(stderr,"Node %d: %f ",i,nodecov[i]);
fprintf(stderr,"trf=");
for(int t=0;t<no2gnode[i]->trf.Count();t++) fprintf(stderr," %d(%f)",no2gnode[i]->trf[t],transfrag[no2gnode[i]->trf[t]]->abundance);
fprintf(stderr," maxi=%d maxcov=%f\n",maxi,nodecov[maxi]);
}
}
*/
path.Clear();
nodeflux.Clear();
parse_trf(maxi,gno,edgeno,gpos,no2gnode,transfrag,geneno,first,strand,pred,nodecov,istranscript,usednode,maxcov,prevpath);
}
}
CTransfrag *find_guide_pat(GffObj *guide,GPVec<CGraphnode>& no2gnode,int gno,int edgeno,GIntHash<int> &gpos) {
CTransfrag *trguide=NULL;
int i=1;
while(i<gno-1) {
if(no2gnode[i]->overlap(guide->exons[0])) { // first exon of guide overlaps node i
int j=i+1;
while(j<gno-1 && no2gnode[j]->overlap(guide->exons[0]) && no2gnode[j]->start==no2gnode[j-1]->end+1
&& no2gnode[j-1]->child.Count() && no2gnode[j-1]->child[0]==j) j++;
if(j<gno-1 && no2gnode[j]->overlap(guide->exons[0])) i=j-1; // I am skipping nodes that are linked by introns to the last node that is overlapped by the first exon in guide
else break;
}
i++;
}
if(i<gno-1) { // found start node
GBitVec guidepat(gno+edgeno);
GVec<int> nodes;
guidepat[i]=1;
nodes.Add(i);
CGraphnode *inode=no2gnode[i];
int j=0; // guide coordinate I am looking at
int n=guide->exons.Count();
while(j<n) {
if(guide->exons[j]->end<inode->end) {
if(j==n-1) trguide=new CTransfrag(nodes,guidepat); // only find guide abundance later if necessary
return(trguide);
}
else if(guide->exons[j]->end==inode->end) {
if(j==n-1) {
trguide=new CTransfrag(nodes,guidepat);
return(trguide);
}
j++;
int k=0;
int nc=inode->child.Count();
while(k<nc && no2gnode[inode->child[k]]->start != guide->exons[j]->start) k++;
if(k==nc) return(trguide);
guidepat[inode->child[k]]=1;
int *pos=gpos[edge(i,inode->child[k],gno)];
if(pos) guidepat[*pos]=1;
//else GError("Found parent-child %d-%d not linked by edge\n",i,inode->child[k]);
i=inode->child[k];
nodes.Add(i);
inode=no2gnode[i];
}
else {
if(i<gno-1 && (no2gnode[i+1]->start==inode->end+1)) { // !!! maybe here I need to consider bundledist
if(inode->child.Count() && inode->child[0]==i+1) {
guidepat[i+1]=1;
int *pos=gpos[edge(i,i+1,gno)];
if(pos) guidepat[*pos]=1;
//else GError("Found parent-child %d-%d not linked by edge\n",i,i+1);
i++;
nodes.Add(i);
inode=no2gnode[i];
}
else return(trguide);
}
else { // node doesn't continue
if(j==n-1) trguide=new CTransfrag(nodes,guidepat); // only find guide abundance later if necessary
return(trguide);
}
}
}
}
return(trguide);
}
CTransfrag *find_guide_partial_pat(GffObj *guide,GPVec<CGraphnode>& no2gnode,int gno,int edgeno,GIntHash<int> &gpos,GVec<int>& olen,int &olensum) {
CTransfrag *trguide=NULL;
GBitVec guidepat(gno+edgeno);
GVec<int> nodes;
olensum=0;
int nex=guide->exons.Count();
int e=0;
bool terminal=false;
int lastnode=0; // lastnode intersected by guide
for(int i=1;i<gno-1;i++) {
CGraphnode *inode=no2gnode[i];
int len=inode->overlapLen(guide->exons[e]->start,guide->exons[e]->end);
if(len) { // if node i intersects exon e of guide
guidepat[i]=1;
nodes.Add(i);
olen.Add(len);
olensum+=len;
if(lastnode && inode->parentpat[lastnode]) { // the guide has intersected another node in the graph which was i's parent
if(guide->exons[e]->start==inode->start) {
if(terminal) { // lastnode ends the same as guide's exon
int *pos=gpos[edge(lastnode,i,gno)];
if(pos) guidepat[*pos]=1;
}
}
else if(guide->exons[e]->start<inode->start) {
if(no2gnode[lastnode]->end+1==inode->start) { // the previous lastnode comes right before this one
int *pos=gpos[edge(lastnode,i,gno)];
if(pos) guidepat[*pos]=1;
}
}
}
lastnode=i;
terminal=false;
if(guide->exons[e]->end<=inode->end) {
if(guide->exons[e]->end==inode->end) terminal=true;
e++;
if(e==nex) break; // I've seen all guide's exons
}
}
else if(inode->start>guide->exons[e]->end){ // stay with the same node if node comes after exon
e++;
i--;
if(e==nex) break; // I've seen all guide's exons
}
}
if(olensum) { // guide intersects at least one node in graph
trguide=new CTransfrag(nodes,guidepat,0,false);
}
return(trguide);
}
void process_refguides(int gno,int edgeno,GIntHash<int>& gpos,int& lastgpos,GPVec<CGraphnode>& no2gnode,
GPVec<CTransfrag>& transfrag,int s,GVec<CGuide>& guidetrf,BundleData *bdata) {
GPVec<GffObj>& guides = bdata->keepguides;
//fprintf(stderr,"In refguides with %d guides\n",guides.Count());
char strand='-';
if(s) strand='+';
// find guides' patterns
for(int g=0;g<guides.Count();g++) {
//fprintf(stderr,"Consider guide[%d out of %d] %s in_bundle=%d\n",g,guides.Count(),guides[g]->getID(),((RC_TData*)(guides[g]->uptr))->in_bundle);
if((guides[g]->strand==strand || guides[g]->strand=='.') && ((RC_TData*)(guides[g]->uptr))->in_bundle>=2 && (guides[g]->overlap(no2gnode[1]->start,no2gnode[gno-2]->end))) {
CTransfrag *trguide=find_guide_pat(guides[g],no2gnode,gno,edgeno,gpos);
if(trguide) { // the guide can be found among the graph nodes
/*if(longreads) { // do not allow guide to be too far away from start/end of the transfrag
if(abs((int)(no2gnode[trguide->nodes[0]]->start-guides[g]->start))<CHI_WIN+CHI_THR && abs((int)(guides[g]->end-no2gnode[trguide->nodes.Last()]->end))<CHI_WIN+CHI_THR) {
CGuide newguide(trguide,g);
guidetrf.Add(newguide);
trguide->guide=true;
}
else delete trguide;
}
else {*/
//CGuide newguide(trguide,guides[g]);
CGuide newguide(trguide,g);
//if(!longreads)
trguide->real=true;
trguide->guide=1;
guidetrf.Add(newguide);
//}
/*
{ // DEBUG ONLY
if(trguide) {
fprintf(stderr,"Added guidetrf %d (%d) with ID=%s overlapping transcript interval %d - %d with nodes:",g,guidetrf.Count()-1,guides[g]->getID(),no2gnode[1]->start,no2gnode[gno-2]->end);
for(int i=0;i<trguide->nodes.Count();i++) fprintf(stderr," %d",trguide->nodes[i]);
fprintf(stderr,"\n");
//fprintf(stderr,"s=%d strand = %c trguide[%d]=",s,strand,g);
//printBitVec(trguide->pattern);
//fprintf(stderr,"\n");
}
}
*/
}
}
} //for g
/*if(longreads && guidetrf.Count()) { // if a guide is not matching any transcript the best do not include TODO: rewrite this!!
int ng=guidetrf.Count();
GVec<bool> covered(ng,false);
GVec<int> gcount; // count number of bits set in each guide's pattern
for(int g=0;g<guidetrf.Count();g++) {
int gc=guidetrf[g].trf->pattern.count();
gcount.Add(gc);
}
for(int t=0;t<transfrag.Count();t++) if(transfrag[t]->nodes[0] && transfrag[t]->nodes.Last()!=gno-1){
int maxg=-1;
int maxcovscore=0;
//int mingscore=0;
for(int g=0;g<guidetrf.Count();g++) {
GBitVec intersect=transfrag[t]->pattern & guidetrf[g].trf->pattern;
int covscore=intersect.count();
if(covscore>maxcovscore) { // only allows guides that have something in common
maxg=g;
maxcovscore=covscore;
//mingscore=gcount[g]-covscore;
}
else if(covscore==maxcovscore){
int gcov=gcount[g]-covscore;
if(gcov<mingscore) {
mingscore=gcov;
maxg=g;
}
else if(gcov==mingscore && !covered[maxg] && covered[g]) {
maxg=g;
}
}
}
if(maxg>=0 && !covered[maxg]) {
covered[maxg]=true;
ng--;
if(!ng) break;
}
}
if(ng) {
for(int g=0;g<guidetrf.Count();g++) if(!covered[g]) {
delete guidetrf[g].trf;
guidetrf.Delete(g);
}
}
}*/
// print guide coverages
if(c_out) {
for(int g=0;g<guidetrf.Count();g++) {
GBitVec guidepattern;
float guideabundance=0;
for(int t=0;t<transfrag.Count();t++) { // check compatibility with guides
int tstart=0;
GBitVec trpattern(transfrag[t]->pattern);
bool edgecompatible=true;
if(guidetrf[g].trf->nodes[0]>transfrag[t]->nodes[0]) { // transfrag starts before guide -> see if I can adjust trpattern to the guide limit
tstart=1;
while(tstart<transfrag[t]->nodes.Count() && transfrag[t]->nodes[tstart-1]<guidetrf[g].trf->nodes[0]) {
if(transfrag[t]->nodes[tstart]==transfrag[t]->nodes[tstart-1]+1 && 1+no2gnode[transfrag[t]->nodes[tstart-1]]->end==no2gnode[transfrag[t]->nodes[tstart]]->start) {
trpattern[transfrag[t]->nodes[tstart-1]]=0;
int *pos=gpos[edge(transfrag[t]->nodes[tstart-1],transfrag[t]->nodes[tstart],gno)];
if(pos) trpattern[*pos]=0;
}
else {
edgecompatible=false;
break;
}
tstart++;
}
}
int tend=transfrag[t]->nodes.Count()-1;
if(edgecompatible && guidetrf[g].trf->nodes.Last()<transfrag[t]->nodes.Last()) { // transfrag starts before guide -> see if I can adjust trpattern to the guide limit
tend--;
while(tend>=0 && transfrag[t]->nodes[tend+1]>guidetrf[g].trf->nodes.Last()) {
if(transfrag[t]->nodes[tend]==transfrag[t]->nodes[tend+1]-1 && 1+no2gnode[transfrag[t]->nodes[tend]]->end==no2gnode[transfrag[t]->nodes[tend+1]]->start) {
trpattern[transfrag[t]->nodes[tend+1]]=0;
int *pos=gpos[edge(transfrag[t]->nodes[tend],transfrag[t]->nodes[tend+1],gno)];
if(pos) trpattern[*pos]=0;
}
else {
edgecompatible=false;
break;
}
tend--;
}
}
if(edgecompatible && ((trpattern & guidetrf[g].trf->pattern) == trpattern)) { // transfrag is completely included in guide
guidepattern = guidepattern | trpattern;
// compute guideabundance here
for(int i=tstart; i<=tend;i++) guideabundance+=transfrag[t]->abundance*no2gnode[transfrag[t]->nodes[i]]->len();
}
}
if(guidepattern==guidetrf[g].trf->pattern) {
int len=0;
for(int i=0;i<guidetrf[g].trf->nodes.Count();i++) len+=no2gnode[guidetrf[g].trf->nodes[i]]->len();
guideabundance/=len;
GStr guidecov;
guidecov.appendfmt("%.2f",guideabundance);
guides[guidetrf[g].g]->addAttr("coverage",guidecov.chars());
guides[guidetrf[g].g]->printTranscriptGff(c_out);
}
}
}
// **** NEXT PORTION NEEDS TO BE CHECKED!!!
guidetrf.Sort(guideCmp); // guide with most bits set in pattern comes first
uint refstart=(uint)bdata->start;
int g=0;
while(g<guidetrf.Count()) {
// check if guide is included in previous guide paths
int p=0;
//fprintf(stderr,"Process guide=%s\n",guides[guidetrf[g].g]->getID());
while(p<g) { // here I assume that the guides are sorted by pattern
//CTransfrag guideg=guidetrf[g];
//CTransfrag guidep=guidetrf[p];
if((guidetrf[g].trf->pattern & guidetrf[p].trf->pattern)==guidetrf[g].trf->pattern) {
guidetrf[g].trf->real=false; // this marks a guide that is included in another one -> I might want to swap them if they have the same abundance
guidetrf[g].trf->guide=0; // this marks a guide that is included in another one -> I might want to swap them if they have the same abundance
break;
}
p++;
}
// find if first node of guidetrf extends to source
int nodei=guidetrf[g].trf->nodes[0]; // first node of guide
if(nodei) { // if source it isn't already in guide's pattern -> it shouldn't be
int *pos=gpos[edge(0,nodei,gno)];
if(!pos) { // here is where I need lastgpos
//fprintf(stderr,"Add source link to position %d for guide=%d\n",no2gnode[nodei]->start,guidetrf[g].g);
int key=edge(0,nodei,gno);
gpos.Add(key,lastgpos);
lastgpos++;
pos=gpos[key];
}
/*if(includesource && !longreads) {
guidetrf[g].trf->nodes.Insert(0,0); // I need to comment this if I need path not to include the source
guidetrf[g].trf->pattern[0]=1;
guidetrf[g].trf->pattern[*pos]=1;
}*/
bool sourcestart=false; // assume there is no extension to source
CGraphnode *inode=no2gnode[nodei];
float leftcov=0;
float rightcov=0;
int previ=-1;
for(int p=0;p<inode->parent.Count();p++) {
if(!inode->parent[p]) { sourcestart=true; break;} // found link to source -> break from path
if(no2gnode[inode->parent[p]]->end==inode->start-1) { // no splice site between parent and inode
previ=inode->parent[p];
if(inode->start>=guides[guidetrf[g].g]->start) {
rightcov=inode->cov/inode->len();
leftcov=no2gnode[previ]->cov/no2gnode[previ]->len();
}
}
}
if(!sourcestart) { // source is not the parent of first node
// if guide starts inside node -> I need to compute abundances
if(inode->start<guides[guidetrf[g].g]->start) {
// cummulative bpcov
leftcov+=get_cov(1,inode->start-refstart,guides[guidetrf[g].g]->start-1-refstart,bdata->bpcov);
leftcov/=(guides[guidetrf[g].g]->start-inode->start);
uint thisend=inode->end+1;
if(guides[guidetrf[g].g]->end<inode->end) thisend=guides[guidetrf[g].g]->end+1;
// cummulative bpcov
if(thisend>guides[guidetrf[g].g]->start) {
rightcov+=get_cov(1,guides[guidetrf[g].g]->start-refstart,thisend-1-refstart,bdata->bpcov);
}
rightcov/=(thisend-guides[guidetrf[g].g]->start);
}
float maxabund=trthr;
if(rightcov>leftcov) {
maxabund=rightcov-leftcov;
}
// add source to nodei transfrag
GVec<int> nodes;
nodes.cAdd(0);
nodes.Add(nodei);
GBitVec trpat(gno+edgeno);
trpat[0]=1;
trpat[nodei]=1;
trpat[*pos]=1;
CTransfrag *tr=new CTransfrag(nodes,trpat,maxabund);
//fprintf(stderr,"introduce node from source to %d wih abundance=%g where pos=%d\n",nodei,maxabund,*pos);
if(longreads) tr->longread=true;
transfrag.Add(tr);
// add source among maxnode parents
inode->parent.Insert(0,0);
inode->parentpat[*pos]=1; // source should be already among parents of maxnode but not the edge to source
}
}
// find if I can extend guidetrf to sink
nodei=guidetrf[g].trf->nodes.Last();
if(nodei != gno-1) { // sink is not already present in guide pattern
int sink=gno-1;
int *pos=gpos[edge(nodei,sink,gno)];
if(!pos) {
//fprintf(stderr,"Add sink link from position %d for guide=%d\n",no2gnode[nodei]->end,guidetrf[g].g);
int key=edge(nodei,sink,gno);
gpos.Add(key,lastgpos);
lastgpos++;
pos=gpos[key];
}
/*if(!longreads) {
guidetrf[g].trf->nodes.Add(sink);
guidetrf[g].trf->pattern[sink]=1;
guidetrf[g].trf->pattern[*pos]=1;
}*/
bool sinkend=false;
CGraphnode *inode=no2gnode[nodei];
float leftcov=0;
float rightcov=0;
int nexti=-1;
for(int c=0;c<inode->child.Count();c++) {
if(inode->child[c]==gno-1) { sinkend=true; break;} // found link to source
if(no2gnode[inode->child[c]]->start==inode->end+1) { // no splice site
nexti=inode->child[c];
if(inode->end<=guides[guidetrf[g].g]->end) {
leftcov=inode->cov/inode->len();
rightcov=no2gnode[nexti]->cov/no2gnode[nexti]->len();
}
}
}
if(!sinkend) { // if no path to sink was found I need to add one
// node is longer than guide
if(inode->end>guides[guidetrf[g].g]->end) {
uint thisstart=inode->start;
if(guides[guidetrf[g].g]->start>inode->start) thisstart=guides[guidetrf[g].g]->start;
// cummulative bpcov
leftcov+=get_cov(1,thisstart-refstart,guides[guidetrf[g].g]->end-refstart,bdata->bpcov);
leftcov/=(guides[guidetrf[g].g]->end-thisstart+1);
// cummulative bpcov
rightcov+=get_cov(1,guides[guidetrf[g].g]->end-refstart,inode->end-refstart,bdata->bpcov);
rightcov/=(inode->end-guides[guidetrf[g].g]->end+1);
}
float maxabund=trthr;
if(rightcov<leftcov) {
maxabund=leftcov-rightcov;
}
// add maxnode to sink transfrag
GVec<int> nodes;
nodes.Add(nodei);
nodes.Add(sink);
GBitVec trpat(gno+edgeno);
trpat[nodei]=1;
trpat[sink]=1;
trpat[*pos]=1;
//fprintf(stderr,"introduce node from %d to sink=%d wih abundance=%g where pos=%d\n",nodei,sink,maxabund,*pos);
CTransfrag *tr=new CTransfrag(nodes,trpat,maxabund);
if(longreads) tr->longread=true;
transfrag.Add(tr);
// add sink among maxnode children
inode->child.Add(sink);
inode->childpat[*pos]=1; // source should be already among parents of maxnode but not the edge to source
}
}
g++;
}
}
bool is_reference_transcript(GVec<CGuide>& guidetrf,GBitVec& pattern) {
int g=0;
while(g<guidetrf.Count()){
if((guidetrf[g].trf->pattern & pattern)==pattern) return true;
g++;
}
return false;
}
bool sharedlink(int gno,GIntHash<int>& gpos,int g1,int g2,GVec<CGuide>& guidetrf,int i, int j) { // the two guides share the path between n1 and n2
if(!guidetrf[g2].trf->pattern[guidetrf[g1].trf->nodes[i]]) return false;
for(int k=i+1;k<=j;k++) {
if(!guidetrf[g2].trf->pattern[guidetrf[g1].trf->nodes[k]]) return false;
int *pos=gpos[edge(guidetrf[g1].trf->nodes[k-1],guidetrf[g1].trf->nodes[k],gno)];
if(!pos || !guidetrf[g2].trf->pattern[*pos])
return false;
}
return true;
}
int find_cguidepat(GBitVec& pat,GVec<CTrGuidePat>& patvec) {
for(int i=0;i<patvec.Count();i++) {
if(pat==patvec[i].pat) return(i);
}
return(-1);
}
int guides_pushmaxflow(int gno,int edgeno,GIntHash<int>& gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,GVec<CGuide>& guidetrf,int& geneno,
int s,GList<CPrediction>& pred,GVec<float>& nodecov,GBitVec& istranscript,GBitVec& pathpat,bool &first,GPVec<GffObj>& guides,GVec<int> &guidepred, BundleData *bdata) {
int maxi=1;
int ng=guidetrf.Count();
if(ng==1) { // if only one guide I do not need to do the 2 pass
GVec<float> nodeflux;
//float fragno=0;
bool full=true;
float flux= push_max_flow(gno,guidetrf[0].trf->nodes,istranscript,transfrag,no2gnode,nodeflux,guidetrf[0].trf->pattern,gpos,full);
istranscript.reset();
/*
{ // DEBUG ONLY
fprintf(stderr,"guide=%s flux[0]=%g\n",guides[guidetrf[0].g]->getID(),flux);
}
*/
if(flux>epsilon) {
bool include=true;
if(guidepred[guidetrf[0].g]==-1) {
store_transcript(pred,guidetrf[0].trf->nodes,nodeflux,nodecov,no2gnode,geneno,first,s,gno,gpos,include,pathpat,false,bdata,guides[guidetrf[0].g]);
//if(eonly) { // this is not correct because it might have been assigned before
guidepred[guidetrf[0].g]=pred.Count()-1; // NEED TO TEST: if this doesn't work for single genes I might want to recombine with the previous prediction in store_transcript
//fprintf(stderr,"guidepred[%d]=%d\n",guidetrf[0].g,guidepred[guidetrf[0].g]);
//}
}
else {
update_guide_pred(pred,guidepred[guidetrf[0].g],guidetrf[0].trf->nodes,nodeflux,nodecov,no2gnode,gno,true);
}
}
//if(nodecov[maxi]<readthr) break; // no need to find other paths since they aren't any above allowed read threshold
//if(nodecov[maxi]<1) break; // I shouldn't be restricting this at all?
/*
{ // DEBUG ONLY
fprintf(stderr,"\nAfter update:\n");
for(int i=0;i<gno;i++) {
fprintf(stderr,"Node %d: %f ",i,nodecov[i]);
fprintf(stderr,"trf=");
for(int t=0;t<no2gnode[i]->trf.Count();t++) fprintf(stderr," %d(%f)",no2gnode[i]->trf[t],transfrag[no2gnode[i]->trf[t]]->abundance);
fprintf(stderr," maxi=%d maxcov=%f\n",maxi,nodecov[maxi]);
}
}
*/
//return(maxi);
}
else if(ng) {
// this is an abundance for guides based on maximum flow for each guide (how much can they each carry
for(int g=0;g<guidetrf.Count();g++) {
guidetrf[g].trf->abundance=push_guide_maxflow(gno,guidetrf[g].trf->nodes,istranscript,transfrag,no2gnode,guidetrf[g].trf->pattern);
istranscript.reset();
}
guidetrf.Sort(guidedabundCmp);
/*
{ // DEBUG ONLY
for(int g=0;g<guidetrf.Count();g++) {
fprintf(stderr,"Abundance of guide[%d]=%f with nodes:",g,guidetrf[g].trf->abundance);
for(int i=0;i<guidetrf[g].trf->nodes.Count();i++) fprintf(stderr," %d",guidetrf[g].trf->nodes[i]);
fprintf(stderr,"\n");
}
}
*/
GVec<float> nodeflux;
for(int g=ng-1;g>=0;g--) if(guidetrf[g].trf->abundance){ // calculate maximum push flow for each guide starting from the less covered one
float flux=guidepushflow(g,guidetrf,gno,istranscript,transfrag,no2gnode,nodeflux);
istranscript.reset();
/*
{ // DEBUG ONLY
fprintf(stderr,"guide=%s flux[%d]=%f\n",guides[g]->getID(),g,flux);
}
*/
bool include=true;
if(flux>epsilon) {
if(guidepred[guidetrf[g].g]==-1) {
store_transcript(pred,guidetrf[g].trf->nodes,nodeflux,nodecov,no2gnode,geneno,first,s,gno,gpos,include,pathpat,false,bdata,guides[guidetrf[g].g]);
//if(eonly) {
guidepred[guidetrf[g].g]=pred.Count()-1; // NEED TO TEST: if this doesn't work for single genes I might want to recombine with the previous prediction in store_transcript
//fprintf(stderr,"2 guidepred[%d]=%d\n",guidetrf[g].g,guidepred[guidetrf[g].g]);
//}
/*
{ // DEBUG ONLY
fprintf(stderr,"\nAfter update:\n");
for(int i=0;i<gno;i++) {
fprintf(stderr,"Node %d: %f ",i,nodecov[i]);
fprintf(stderr,"trf=");
for(int t=0;t<no2gnode[i]->trf.Count();t++) fprintf(stderr," %d(%f)",no2gnode[i]->trf[t],transfrag[no2gnode[i]->trf[t]]->abundance);
fprintf(stderr," maxi=%d maxcov=%f\n",maxi,nodecov[maxi]);
}
}
*/
}
else {
update_guide_pred(pred,guidepred[guidetrf[g].g],guidetrf[g].trf->nodes,nodeflux,nodecov,no2gnode,gno,true);
}
nodeflux.Clear();
}
else { // it's possible that this is a single exon gene included in a much larger interval and this is why it didn't get predicted
if(guides[guidetrf[g].g]->exons.Count()==1) { // single exon gene included in another prediction
// check if it overlaps other single exon genes
bool overlap=false;
for(int r=ng-1;r>g;r--) if(guidepred[guidetrf[r].g]>-1){
if((guidetrf[g].trf->pattern & guidetrf[r].trf->pattern)==guidetrf[g].trf->pattern) {
if(guides[guidetrf[r].g]->exons.Count()>1) {
overlap=true;
break;
}
else { // overlaps single exon gene -> check if it's a true overlap
if(guides[guidetrf[r].g]->exons[0]->overlap(guides[guidetrf[g].g]->exons[0])) {
overlap=true;
break;
}
}
}
}
if(!overlap) { // no overlap detected
for(int z=0;z<guidetrf[g].trf->nodes.Count();z++) nodeflux.cAdd(1.0);
if(guidepred[guidetrf[g].g]==-1) {
store_transcript(pred,guidetrf[g].trf->nodes,nodeflux,nodecov,no2gnode,geneno,first,s,gno,gpos,include,pathpat,false,bdata,guides[guidetrf[g].g]);
//if(eonly) {
guidepred[guidetrf[g].g]=pred.Count()-1; // NEED TO TEST: if this doesn't work for single genes I might want to recombine with the previous prediction in store_transcript
//fprintf(stderr,"2 guidepred[%d]=%d\n",guidetrf[g].g,guidepred[guidetrf[g].g]);
//}
}
else {
update_guide_pred(pred,guidepred[guidetrf[g].g],guidetrf[0].trf->nodes,nodeflux,nodecov,no2gnode,gno,true);
}
nodeflux.Clear();
}
}
}
}
}
// Node coverages:
for(int i=1;i<gno-1;i++)
if(nodecov[i]>nodecov[maxi]) maxi=i;
if(eonly && nodecov[maxi]>epsilon) { // this is the end for eonly so I should make sure I use all reads
for(int g=0;g<guidetrf.Count();g++) delete guidetrf[g].trf;
guidetrf.Clear();
char strand='-';
if(s) strand='+';
GVec<CNodeGuide> nodeinfo(gno);
nodeinfo.setCount(gno);
int ng=0;
GVec<int> olen;
// find guides' partial patterns
for(int g=0;g<guides.Count();g++) {
//fprintf(stderr,"Consider guide[%d out of %d] %s\n",g,guides.Count(),guides[g]->getID());
if((guides[g]->strand==strand) && (guides[g]->overlap(no2gnode[1]->start,no2gnode[gno-2]->end))) { // if guide on the same strand and overlaps at all the graph
//fprintf(stderr,"...there is overlap\n");
olen.Clear();
int olensum;
CTransfrag *trguide=find_guide_partial_pat(guides[g],no2gnode,gno,edgeno,gpos,olen,olensum);
if(trguide) { // the guide can be found among the graph nodes
//fprintf(stderr,"...partial pattern found!\n");
CGuide newguide(trguide,g);
guidetrf.Add(newguide);
for(int i=0;i<trguide->nodes.Count();i++) {
CPartGuide pg(ng,olen[i],olensum,guides[g]->covlen);
nodeinfo[trguide->nodes[i]].guide.Add(pg);
int idx=nodeinfo[trguide->nodes[i]].guide.Count()-1; // position of guide in nodeinfo
bool terminal=true;
if(i) { // not first node in guide covered
int *pos=gpos[edge(trguide->nodes[i-1],trguide->nodes[i],gno)];
if(pos && trguide->pattern[*pos]) terminal=false; // if there is edge from previous node and it's present in guide
}
nodeinfo[trguide->nodes[i]].guide[idx].terminal_in=terminal;
terminal=true;
if(i<trguide->nodes.Count()-1) { // not last node in guide covered
int *pos=gpos[edge(trguide->nodes[i],trguide->nodes[i+1],gno)];
if(pos && trguide->pattern[*pos]) terminal=false; // if there is edge from previous node and it's present in guide
}
nodeinfo[trguide->nodes[i]].guide[idx].terminal_out=terminal;
}
ng++;
}
}
}
// future: compute maxflow for each guide starting at the most covered node maybe and going all the way to where I can do it.
// or maybe compute maxflow for each guide from all terminal nodes and then assign coverages based on winners or the one that gets the most coverage
// hint: max_flow doesn't need source/sink in the path so I can go with that
// or: do some type EM algorithm like I am trying to do below
GVec<int> path(1);
path.setCount(1);
GVec<float> nodeflux(1);
nodeflux.setCount(1);
GVec<int> coverednode; // array of all nodes that still have coverage _and_ guides
// determine gcounts and the strict assignments to guides
for(int n=1;n<gno-1;n++) if(nodecov[n]>epsilon && nodeinfo[n].guide.Count()) { // for all nodes for which there is still coverage and have guides
ng=nodeinfo[n].guide.Count(); // number of guides in node
if(ng==1) { // there is only one guide -> it gets all the coverage
int g=guidetrf[nodeinfo[n].guide[0].idx].g;
path[0]=n;
nodeflux[0]=1;
//fprintf(stderr,"1 g=%d\n",g);
if(guidepred[g]!=-1) update_guide_pred(pred,guidepred[g],path,nodeflux,nodecov,no2gnode,gno,true);
else // new prediction for this guide
guidepred[g]=store_guide_transcript(pred,path,nodeflux,nodecov,no2gnode,geneno,first,gno,guides[g],true);
}
else { // there are more than one guide overlapping the node -> count the strict/loose counts; might want to rethink doing this for single nodes in the graph
float incount=0; // should be distrtibuted between incoming guides that continue and terminal ones -> not doing this now
float outcount=0;
//float throughcount=0;
float terminal_incount=0;
float terminal_outcount=0;
float guide_incount=0;
float guide_outcount=0;
GVec<float> in_strictcount(ng,float(0)); // these are abundances that are unique to a single guide -> this will get assigned to guides
GVec<float> in_loosecount(ng,float(0)); // these are guide abundances that are shared with other guides
GVec<float> in_looseterminalcount(ng,float(0)); // these are guide abundances that are shared with other guides
GVec<float> out_strictcount(ng,float(0));
GVec<float> out_loosecount(ng,float(0));
GVec<float> out_looseterminalcount(ng,float(0));
GVec<CTrGuidePat> out_trcount; // I can use the node trcount for the in_counts but I need for the outcount because it needs to be adjusted by the rate
int ncovguides=0;
bool allstrictzero=true;
bool allloosezero=true;
CGraphnode *inode=no2gnode[n];
int nn=inode->trf.Count();
for(int j=0;j<nn;j++){
int t=inode->trf[j];
if(transfrag[t]->abundance>epsilon) { // only if transfrag still has abundance it's worth considering
GVec<int> compguide; // keeps all guides that are compatible with this transfrag
GBitVec guidepat(guidetrf.Count()); // pattern of guides that are present in transfrag
bool terminal_in=true; // true only if all guides compatible with transfrag are terminal
bool terminal_out=true;
for(int i=0;i<ng;i++) {
int g=nodeinfo[n].guide[i].idx;
if(((transfrag[t]->pattern) & guidetrf[g].trf->pattern) == transfrag[t]->pattern) { // transfrag is compatible to guide
compguide.Add(i); // make sure that later you change it to guidetrf indexes
guidepat[g]=1;
if(terminal_in && !nodeinfo[n].guide[i].terminal_in) terminal_in=false;
if(terminal_out && !nodeinfo[n].guide[i].terminal_out) terminal_out=false;
if(!nodeinfo[n].guide[i].gcount) {
nodeinfo[n].guide[i].gcount=1;
ncovguides++;
}
}
}
if(!compguide.Count()) {
terminal_in=false;
terminal_out=false;
}
if(transfrag[t]->nodes.Last()==n) { // transfrag ends at this node (in transfrag)
if(terminal_in) {
if(compguide.Count()>1) { // all guides compatible with transfrag are terminal
terminal_incount+=transfrag[t]->abundance;
for(int i=0;i<compguide.Count();i++) {
in_looseterminalcount[compguide[i]]+=transfrag[t]->abundance;
allloosezero=false;
}
}
}
else incount+=transfrag[t]->abundance; // this biases in favor of continuing guides -> might want to rethink this
if(compguide.Count()==1) { // only one guide compatible with transfrag
in_strictcount[compguide[0]]+=transfrag[t]->abundance;
allstrictzero=false;
}
else if(compguide.Count()) { // there are multiple guides in transfrag
int p=find_cguidepat(guidepat,nodeinfo[n].trcount);
if(p==-1) { // didn't find the guide pattern
CTrGuidePat pat(guidepat,transfrag[t]->abundance,terminal_in);
nodeinfo[n].trcount.Add(pat);
for(int i=0;i<compguide.Count();i++) nodeinfo[n].trcount[nodeinfo[n].trcount.Count()-1].g.Add(nodeinfo[n].guide[compguide[i]].idx);
}
else nodeinfo[n].trcount[p].abund+=transfrag[t]->abundance;
if(!terminal_in) {
guide_incount+=transfrag[t]->abundance; // terminals can only be guide transfrags
for(int i=0;i<compguide.Count();i++) {
in_loosecount[compguide[i]]+=transfrag[t]->abundance;
allloosezero=false;
}
}
}
}
else if(transfrag[t]->nodes[0]==n) { // transfrag starts at this node (out transfrag)
if(terminal_out) {
if(compguide.Count()>1) {
terminal_outcount+=transfrag[t]->abundance;
for(int i=0;i<compguide.Count();i++) {
out_looseterminalcount[compguide[i]]+=transfrag[t]->abundance;
allloosezero=false;
}
}
}
else outcount+=transfrag[t]->abundance;
if(compguide.Count()==1) {
out_strictcount[compguide[0]]+=transfrag[t]->abundance; // only one guide compatible with transfrag
allstrictzero=false;
}
else if(compguide.Count()){
int p=find_cguidepat(guidepat,out_trcount);
if(p==-1) { // didn't find the guide pattern
CTrGuidePat pat(guidepat,transfrag[t]->abundance,terminal_out);
out_trcount.Add(pat);
for(int i=0;i<compguide.Count();i++) out_trcount[out_trcount.Count()-1].g.Add(nodeinfo[n].guide[compguide[i]].idx);
}
else out_trcount[p].abund+=transfrag[t]->abundance;
if(!terminal_out) {
guide_outcount+=transfrag[t]->abundance;
for(int i=0;i<compguide.Count();i++) {
out_loosecount[compguide[i]]+=transfrag[t]->abundance;
allloosezero=false;
}
}
}
}
else if(transfrag[t]->pattern[n]) { // through transfrag (here I checked that the transfrag clearly goes through the node)
//throughcount+=transfrag[t]->abundance;
incount+=transfrag[t]->abundance; // I do this instead of the above because the throughout could be very high and the in/outcounts shouldn't dominate in that case
outcount+=transfrag[t]->abundance;
if(compguide.Count()==1) {
in_strictcount[compguide[0]]+=transfrag[t]->abundance; // only one guide compatible with transfrag
out_strictcount[compguide[0]]+=transfrag[t]->abundance; // only one guide compatible with transfrag
allstrictzero=false;
}
else if(compguide.Count()) {
guide_incount+=transfrag[t]->abundance;
guide_outcount+=transfrag[t]->abundance;
int p=find_cguidepat(guidepat,nodeinfo[n].trcount);
if(p==-1) { // didn't find the guide pattern
CTrGuidePat pat(guidepat,transfrag[t]->abundance,terminal_in);
nodeinfo[n].trcount.Add(pat);
for(int i=0;i<compguide.Count();i++) nodeinfo[n].trcount[nodeinfo[n].trcount.Count()-1].g.Add(nodeinfo[n].guide[compguide[i]].idx);
}
else {
nodeinfo[n].trcount[p].abund+=transfrag[t]->abundance;
}
p=find_cguidepat(guidepat,out_trcount);
if(p==-1) { // didn't find the guide pattern
CTrGuidePat pat(guidepat,transfrag[t]->abundance,terminal_out);
out_trcount.Add(pat);
for(int i=0;i<compguide.Count();i++) out_trcount[out_trcount.Count()-1].g.Add(nodeinfo[n].guide[compguide[i]].idx);
}
else {
out_trcount[p].abund+=transfrag[t]->abundance;
}
for(int i=0;i<compguide.Count();i++) {
in_loosecount[compguide[i]]+=transfrag[t]->abundance;
out_loosecount[compguide[i]]+=transfrag[t]->abundance;
allloosezero=false;
}
}
}
}
} // done computing counts for node
if(allstrictzero && allloosezero) { // only single guides or no transfrag compatible to guides
// -> I need to choose some preferences: bias toward longest overlapping guide
for(int i=0;i<ng;i++) { // ng>1
nodeinfo[n].guide[i].gcount=1; // give them a uniform probability at node level: coverage probabilities take priority
}
nodeinfo[n].sumtrcount=1; // one guide is sufficient to explain all abundances;
// Note: pattern of guides in trcount should all be with only one 1 for the actual guide but we don't need to use it since using the guide explains everything
}
else { // some guides are compatible to the node transfrags
if(ncovguides==1) { // only one guide is compatible with the node transfrags -> takes all node coverage (this biases strongly against single exon guides, or incomplete guides -> might want to rethink)
int g=guidetrf[nodeinfo[n].guide[0].idx].g;
path[0]=n;
nodeflux[0]=1;
//fprintf(stderr,"2 g=%d\n",g);
if(guidepred[g]!=-1) update_guide_pred(pred,guidepred[g],path,nodeflux,nodecov,no2gnode,gno,true);
else // new prediction for this guide
guidepred[g]=store_guide_transcript(pred,path,nodeflux,nodecov,no2gnode,geneno,first,gno,guides[g],true);
}
else { // more than one guide got counts
// first get the rate
float rate=1;
nodeinfo[n].sumtrcount=0;
if(incount && outcount) {
rate=incount/outcount;
nodeinfo[n].sumtrcount+=rate*terminal_outcount;
nodeinfo[n].sumtrcount+=terminal_incount;
}
nodeinfo[n].sumtrcount+=guide_incount+rate*guide_outcount+terminal_incount+rate*terminal_outcount;
float sumstrict=nodeinfo[n].sumtrcount;
if(!allstrictzero) { // there are strict counts that need to be assigned to
for(int i=0;i<ng;i++) {
sumstrict+=in_strictcount[i]+rate*out_strictcount[i];
if(nodeinfo[n].guide[i].terminal_in) sumstrict+=in_strictcount[i]; // if node is terminal the counts should be adjusted
if(nodeinfo[n].guide[i].terminal_out) sumstrict+=rate*out_strictcount[i];
}
}
// update guide coverages with unique reads and gcounts for later
for(int i=0;i<ng;i++) {
if(!allstrictzero) {
float strictcount=in_strictcount[i]+rate*out_strictcount[i];
if(incount && outcount) {
if(nodeinfo[n].guide[i].terminal_in) strictcount+=in_strictcount[i];
if(nodeinfo[n].guide[i].terminal_out) strictcount+=rate*out_strictcount[i];
}
if(strictcount) { // if there are reads unique to the guide
int g=guidetrf[nodeinfo[n].guide[i].idx].g;
path[0]=n;
nodeflux[0]=strictcount/sumstrict;
//fprintf(stderr,"3 g=%d\n",g);
if(guidepred[g]!=-1) update_guide_pred(pred,guidepred[g],path,nodeflux,nodecov,no2gnode,gno,false);
else // new prediction for this guide
guidepred[g]=store_guide_transcript(pred,path,nodeflux,nodecov,no2gnode,geneno,first,gno,guides[g],false);
}
}
// now set gcounts
nodeinfo[n].guide[i].gcount=in_loosecount[i]+rate*out_loosecount[i]+
in_looseterminalcount[i]+rate*out_looseterminalcount[i];
if(incount && outcount) {
if(nodeinfo[n].guide[i].terminal_in) nodeinfo[n].guide[i].gcount+=in_looseterminalcount[i];
if(nodeinfo[n].guide[i].terminal_out) nodeinfo[n].guide[i].gcount+=rate*out_looseterminalcount[i];
}
}
if(!allstrictzero) { // update node coverage here
if(allloosezero) nodecov[n]=0;
else nodecov[n]*=nodeinfo[n].sumtrcount/sumstrict;
}
if(!allloosezero && nodecov[n]) { // get the pattern counts
if(incount && outcount) for(int i=0;i<nodeinfo[n].trcount.Count();i++)
if(nodeinfo[n].trcount[i].terminal) nodeinfo[n].trcount[i].abund*=2;
for(int i=0;i<out_trcount.Count();i++) {
int t=find_cguidepat(out_trcount[i].pat,nodeinfo[n].trcount);
out_trcount[i].abund*=rate;
if(out_trcount[i].terminal && incount && outcount) out_trcount[i].abund*=2;
//else out_trcount[i].terminal=false; // I can not have a trcount with the same guides that is terminal both for in and out
if(t==-1) { // didn't find the guide pattern
nodeinfo[n].trcount.Add(out_trcount[i]);
}
else nodeinfo[n].trcount[t].abund+=out_trcount[i].abund;
}
}
}
}
}
if(nodecov[n]>epsilon) { // there is still coverage left for the node
coverednode.Add(n);
}
}
if(coverednode.Count()) { // I still have covered nodes: asign reads to guides; I need to do some sort of EM algorithm here
// my prior bias in assigning reads should be based on coverages allready found
int nEM=10; // number of times to repeat the EM algorithm: need to see if this is a good count, or if I should use and epsilon change to stop
ng=guidetrf.Count();
GVec<float> initgcov(ng,float(0));
// first set the initial coverages in covered nodes
for(int i=0;i<ng;i++) {
int np=guidepred[guidetrf[i].g];
if(np!=-1) {
initgcov[i]=pred[np]->cov*abs(pred[np]->tlen);
}
}
GVec<float> prevgcov(ng,float(0)); // the new gcov that will be computed as part of the EM algorithm
// now set the cov's in CPartGuide -> for sort purposes and for the EM algorithm
for(int i=0;i<coverednode.Count();i++) {
int n=coverednode[i];
for(int j=0;j<nodeinfo[n].guide.Count();j++) {
int g=nodeinfo[n].guide[j].idx;
nodeinfo[n].guide[j].cov=initgcov[g];
prevgcov[g]=initgcov[g];
}
}
GVec<float> gcov(ng,float(0)); // the new gcov that will be computed as part of the EM algorithm
int m=0;
while(m<nEM) { // do the EM
for(int i=0;i<ng;i++) gcov[i]=initgcov[i];
for(int i=0;i<coverednode.Count();i++) { // for each node recompute probabilities
int n=coverednode[i];
nodeinfo[n].guide.Sort(partguideCmp); // I need to sort at each step because the cov's get updated
float totalcount=0;
bool covnotreached=true;
float sumgcov=0;
for(int j=0;j<nodeinfo[n].guide.Count();j++) { // for each guide in the node, starting from the most abundant to the least
nodeinfo[n].guide[j].ncov=0; // I need to set this for each guide -> this is why I not break from the loop below
int g=nodeinfo[n].guide[j].idx; // index in guidetrf
sumgcov+=prevgcov[g];
if(covnotreached) for(int t=0;t<nodeinfo[n].trcount.Count();t++) { // for each trguidepat in the node
if(nodeinfo[n].trcount[t].pat[g]) { // current guide is in this pattern
float sum=0; // sum of all coverages of guides in the transcript
for(int k=0;k<nodeinfo[n].trcount[t].g.Count();k++) {
int l=nodeinfo[n].trcount[t].g[k];
sum+=prevgcov[l];
}
float abund=nodeinfo[n].sumtrcount-totalcount; // this is the maximum abundance allowed for this guide
if(sum) { // I have some guides that have coverage
float newabund=nodeinfo[n].trcount[t].abund*prevgcov[g]/sum;
if(newabund<abund) abund=newabund;
}
else { // no guide has assigned coverages yet -> winner takes all
if(nodeinfo[n].trcount[t].abund<abund) abund=nodeinfo[n].trcount[t].abund;
}
nodeinfo[n].guide[j].ncov+=abund;
gcov[g]+=abund*nodeinfo[n].guide[j].olen/no2gnode[n]->len();
totalcount+=abund;
if(nodeinfo[n].sumtrcount-totalcount<epsilon) {
covnotreached=false;
break;
}
}
}
}
if(covnotreached) { // there were not enough transfrags to give coverages -> redistribute reads based on coverages
float abund=nodeinfo[n].sumtrcount-totalcount; // this is how much is left
if(sumgcov) for(int j=0;j<nodeinfo[n].guide.Count();j++) {
if(!nodeinfo[n].guide[j].cov) break;
float newabund=abund*nodeinfo[n].guide[j].cov/sumgcov;
nodeinfo[n].guide[j].ncov+=newabund;
int g=nodeinfo[n].guide[j].idx;
gcov[g]+=newabund*nodeinfo[n].guide[j].olen/no2gnode[n]->len();
}
else { // all guides have cov zero -> winner takes all
nodeinfo[n].guide[0].ncov+=abund;
int g=nodeinfo[n].guide[0].idx;
gcov[g]+=abund*nodeinfo[n].guide[0].olen/no2gnode[n]->len();
}
}
} // end node
bool nochange=true;
// check coverages
for(int i=0;i<coverednode.Count();i++) {
int n=coverednode[i];
for(int j=0;j<nodeinfo[n].guide.Count();j++) {
int g=nodeinfo[n].guide[j].idx;
float diff=nodeinfo[n].guide[j].cov-gcov[g];
if(diff<0) diff=-diff;
if(diff) {
prevgcov[g]=gcov[g];
nodeinfo[n].guide[j].cov=gcov[g];
if(diff>1) nochange=false;
}
}
}
// see if there is a change in probability
if(nochange) break;
m++;
} // end EM
// new coverages are estimated so now I can assign the reads to the predictions
for(int g=0;g<guidetrf.Count();g++) if(gcov[g]>initgcov[g]) { // for each guide that has more coverage to add
path.Clear();
nodeflux.Clear();
for(int i=0;i<guidetrf[g].trf->nodes.Count();i++) if(nodecov[guidetrf[g].trf->nodes[i]]) { // for each covered node
int n=guidetrf[g].trf->nodes[i];
for(int j=0;j<nodeinfo[n].guide.Count();j++) if(g==nodeinfo[n].guide[j].idx){ // found my guide
if(nodeinfo[n].guide[j].ncov) { // if there is coverage assigned to node -> i should add it to the path
path.Add(n);
float prop=nodeinfo[n].guide[j].ncov/nodeinfo[n].sumtrcount;
nodeflux.Add(prop);
}
break;
}
}
//fprintf(stderr,"4 g=%d\n",guidetrf[g].g);
if(guidepred[guidetrf[g].g]!=-1) update_guide_pred(pred,guidepred[guidetrf[g].g],path,nodeflux,nodecov,no2gnode,gno,false);
else // new prediction for this guide
guidepred[guidetrf[g].g]=store_guide_transcript(pred,path,nodeflux,nodecov,no2gnode,geneno,first,gno,guides[guidetrf[g].g],false);
}
}
maxi=0;
}
return(maxi);
}
bool transcript_cont_path(GVec<int>& path,CTransfrag *transfrag, int &ni,GVec<int>& alltr,int t) {
int np=path.Count();
int n=0;
while(path[n]<transfrag->nodes[0]) n++;
for(int i=0;i<transfrag->nodes.Count();i++) {
if(n==np) { // I reached the end of search and didn't find any mismatch
ni=i;
return true;
}
if(path[n]!=transfrag->nodes[i]) return false;
n++;
}
if(n==np) { // transfrag is completely included in path
transfrag->abundance=0;
alltr.Add(t);
return false;
}
return true;
}
void collect_path(GPVec<CMTransfrag>& mgt,GVec<int>& alltr,GVec<int>& path,GPVec<CGraphnode>& no2gnode,int n, int gno) {
CGraphnode *node=no2gnode[path[n]];
if(node->child.Count()==1 && node->child[0]==gno-1) return; // only child of node is sink
float maxabund=0;
int maxt=-1;
bool found=false;
int nexti=-1;
for(int j=0;j<node->trf.Count();j++) {
int t=node->trf[j];
if(mgt[t]->transfrag->abundance && mgt[t]->transfrag->nodes[0] &&
(!mgt[t]->transfrag->real || mgt[t]->transfrag->nodes[0]==path[n] )) { // if t is a guide it should start at this node to be included in transcript
int ni=-1;
if(!found) {
if(mgt[t]->transfrag->real && transcript_cont_path(path,mgt[t]->transfrag,ni,alltr,t)) {
maxt=t;
nexti=ni;
found=true; // found my continuation transcript -> no need to look further
}
else if(!mgt[t]->transfrag->real && mgt[t]->transfrag->abundance>maxabund && transcript_cont_path(path,mgt[t]->transfrag,ni,alltr,t)) {
maxt=t;
nexti=ni;
maxabund=mgt[t]->transfrag->abundance;
}
}
else transcript_cont_path(path,mgt[t]->transfrag,ni,alltr,t);
}
}
if(maxt==-1) return; // path ends here
// found maxt -> extend path
alltr.Add(maxt);
if(!mgt[maxt]->transfrag->real) mgt[maxt]->transfrag->abundance=0;
n++;
for(int i=nexti;i<mgt[maxt]->transfrag->nodes.Count();i++) {
path.Add(mgt[maxt]->transfrag->nodes[i]);
}
}
int find_transcripts(int gno,int edgeno, GIntHash<int> &gpos,GPVec<CGraphnode>& no2gnode,GPVec<CTransfrag>& transfrag,int geneno,int strand,
GVec<CGuide>& guidetrf,GPVec<GffObj>& guides,GVec<int>& guidepred,BundleData* bdata,GVec<int>& trflong) {
GList<CPrediction>& pred = bdata->pred;
/*
if(trflong.Count()) get_trf_long(gno,edgeno, gpos,no2gnode,transfrag,geneno,strand,pred,trflong,bdata);
if(longreads) return(geneno);*/
if(longreads) {
if(trflong.Count()) get_trf_long(gno,edgeno, gpos,no2gnode,transfrag,geneno,strand,pred,trflong,bdata);
return(geneno);
}
// process in and out coverages for each node
int maxi=0; // node with maximum coverage
GVec<float> nodecov; // node coverages
for(int i=0;i<gno;i++) {
CGraphnode *inode=no2gnode[i]; // this is here only because of the DEBUG option below
nodecov.cAdd(0.0);
if(i) { // for all nodes but the source
if(i<gno-1 && inode->len()) nodecov[i]=inode->cov/inode->len(); // sink also has 0 coverage
if(nodecov[i]>nodecov[maxi]) maxi=i;
int nn=inode->trf.Count();
float abundin=0;
float abundout=0;
float abundthrough=0;
for(int j=0;j<nn;j++){
int t=inode->trf[j];
if(transfrag[t]->nodes.Last()==i) { // transfrag ends at this node (in transfrag)
abundin+=transfrag[t]->abundance;
}
else if(transfrag[t]->nodes[0]==i) { // transfrag starts at this node (out transfrag)
abundout+=transfrag[t]->abundance;
}
else if(transfrag[t]->pattern[i]) { // through transfrag (here I checked that the transfrag clearly goes through the node)
abundthrough+=transfrag[t]->abundance;
}
}
if(abundin) inode->rate=abundout/abundin;
if(abundout) inode->capacity=abundout+abundthrough; // node capacity tells me how much of that node coverage I can use given how many transfrags leave the node
else inode->capacity=abundin+abundthrough;
} // end if i
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Node %d: cov=%f capacity=%f rate=%f ",i,inode->cov/(inode->end-inode->start+1),inode->capacity,inode->rate);
fprintf(stderr,"trf=");
for(int t=0;t<inode->trf.Count();t++) fprintf(stderr," %d(%f)",inode->trf[t],transfrag[inode->trf[t]]->abundance);
fprintf(stderr," maxi=%d maxcov=%f\n",maxi,nodecov[maxi]);
}
*/
} // end for i
GBitVec istranscript(transfrag.Count());
GBitVec pathpat(gno+edgeno);
/*
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(after istranscript and pathpat init):find_transcripts memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
// process guides first
//fprintf(stderr,"guidetrf.count=%d\n",guidetrf.Count());
//if(guidetrf.Count()) maxi=guides_flow(gno,no2gnode,transfrag,guidetrf,geneno,strand,pred,nodecov,istranscript,pathpat);
bool first=true;
//fprintf(stderr,"guide count=%d\n",guidetrf.Count());
if (eonly)
guides_pushmaxflow(gno,edgeno,gpos,no2gnode,transfrag,guidetrf,geneno,strand,pred,nodecov,istranscript,pathpat,first,guides,guidepred,bdata);
else { //if(!eonly) {
if(mixedMode && trflong.Count()) get_trf_long_mix(gno,edgeno, gpos,no2gnode,transfrag,geneno,strand,pred,trflong,nodecov,istranscript,pathpat,bdata,first);
if(!mixedMode && guidetrf.Count()) maxi=guides_pushmaxflow(gno,edgeno,gpos,no2gnode,transfrag,guidetrf,geneno,strand,pred,nodecov,istranscript,pathpat,first,guides,guidepred,bdata);
/*
{ // DEBUG ONLY
if(mixedMode) {
fprintf(stderr,"After get_trf_long:\n");
for(int i=0;i<gno;i++) {
CGraphnode *inode=no2gnode[i];
printTime(stderr);
fprintf(stderr,"Node %d: cov=%f capacity=%f rate=%f ",i,inode->cov/(inode->end-inode->start+1),inode->capacity,inode->rate);
fprintf(stderr,"trf=");
for(int t=0;t<inode->trf.Count();t++) fprintf(stderr," %d(%f)",inode->trf[t],transfrag[inode->trf[t]]->abundance);
fprintf(stderr," maxi=%d maxcov=%f\n",maxi,nodecov[maxi]);
}
fprintf(stderr,"There are %d transfrags:\n",transfrag.Count());
for(int t=0;t<transfrag.Count();t++) {
fprintf(stderr,"%d: ",t);
//printBitVec(transfrag[s][b][t]->pattern);
fprintf(stderr," %f(%f,%d,%d) long=%d nodes=%d",transfrag[t]->abundance,transfrag[t]->srabund, transfrag[t]->longstart,transfrag[t]->longend,transfrag[t]->longread,transfrag[t]->nodes.Count());
for(int i=0;i<transfrag[t]->nodes.Count();i++) fprintf(stderr," %d",transfrag[t]->nodes[i]);
if(!transfrag[t]->abundance) fprintf(stderr," *");
fprintf(stderr,"\n");
}
}
}
*/
if(nodecov[maxi]>=1) { // sensitive mode only; otherwise >=readthr
// 1:
// parse_trf_weight_max_flow(gno,no2gnode,transfrag,geneno,strand,pred,nodecov,pathpat);
// 2:
GBitVec usednode(gno+edgeno);
parse_trf(maxi,gno,edgeno,gpos,no2gnode,transfrag,geneno,first,strand,pred,nodecov,istranscript,usednode,0,pathpat);
}
}
return(geneno);
}
void exon_covered(int ex,GffObj *guide,int &b,GPVec<CBundle>& bundle,GPVec<CBundlenode>& bnode,
int& maxlen,int& leftlen,int& rightlen) {
while(b<bundle.Count()){
if(guide->exons[ex]->end<bnode[bundle[b]->startnode]->start) break;
int ovlp=guide->exons[ex]->overlapLen(bnode[bundle[b]->startnode]->start,bnode[bundle[b]->lastnodeid]->end);
if(ovlp>maxlen) maxlen=ovlp;
if(guide->exons[ex]->start>=bnode[bundle[b]->startnode]->start) leftlen=ovlp;
if(guide->exons[ex]->end<=bnode[bundle[b]->lastnodeid]->end) {
rightlen=ovlp;
break;
}
b++;
}
}
bool get_covered(GffObj *guide,GPVec<CBundle>& bundle,GPVec<CBundlenode>& bnode,GList<CJunction>& junction,
GVec<int>* bnodeguides,int g) {
bool covered=true;
int s=-1;
if(guide->strand=='+') s=1;
// first check if all exons are covered by junctions
int nj=0; // index of junctions
int njunctions=junction.Count();
for(int i=1;i<guide->exons.Count();i++) {
while(nj<njunctions && junction[nj]->start<guide->exons[i-1]->end) nj++;
if(nj==njunctions || junction[nj]->start>guide->exons[i-1]->end) {
covered=false;
break;
}
bool found=false;
while(nj<njunctions && junction[nj]->start==guide->exons[i-1]->end){
if(junction[nj]->strand==s && junction[nj]->end==guide->exons[i]->start) {
found=true;
break;
}
nj++;
}
if(!found) {
covered=false;
break;
}
}
// now check if the exons are covered
if(covered) {
covered=false;
int b=0;
uint guidestart=0;
uint maxguidelen=0;
while(!covered && b<bundle.Count()) {
if(guide->end<bnode[bundle[b]->startnode]->start) break;
if(guide->overlap(bnode[bundle[b]->startnode]->start,bnode[bundle[b]->lastnodeid]->end)) {
CBundlenode *currbnode=bnode[bundle[b]->startnode];
covered=true;
int i=0;
while(currbnode!=NULL && i<guide->exons.Count()) {
if(guide->exons[i]->end<currbnode->start) break;
if(guide->exons.Count()==1) {
uint ovlp=(uint)guide->overlapLen(currbnode->start,currbnode->end);
if(maxguidelen<ovlp) {
maxguidelen=ovlp;
covered=true;
i++;
// break; // should I have a break in here?
}
if(ovlp && bnodeguides) {
bnodeguides[currbnode->bid].Add(g);
}
}
else {
if(i<guide->exons.Count()-1) { // not last exon
if(guide->exons[i]->end<=currbnode->end) { // exon end within currbnode
if(i) { // not first exon
if(currbnode->start<=guide->exons[i]->start && guide->exons[i]->start<=currbnode->end) { // exon included within currbnode
i++;
continue;
}
else break;
}
else {
if(!guidestart) {
if(currbnode->start<guide->exons[i]->start) guidestart=guide->exons[i]->start;
else guidestart=currbnode->start;
}
i++;
continue;
}
}
}
else { // last exon -> only start needs to be within currbnode
if(currbnode->start<=guide->exons[i]->start && guide->exons[i]->start<=currbnode->end) {
if(!maxguidelen) {
if(guide->exons[i]->end<currbnode->end) maxguidelen=guide->exons[i]->end-guidestart+1;
else maxguidelen=currbnode->end-guidestart+1;
}
i++; break;
}
}
}
currbnode=currbnode->nextnode;
}
if(i<guide->exons.Count()) covered=false;
}
b++;
}
//fprintf(stderr,"covered=%d guidelen=%d\n",covered,maxguidelen);
//if(covered && maxguidelen>=(uint)mintranscriptlen) { if(c_out) guide->printTranscriptGff(c_out);}
//else covered=false;
if(maxguidelen<(uint)mintranscriptlen) covered=false;
}
return(covered);
}
bool guide_exon_overlap(GPVec<GffObj>& guides,int sno,uint start,uint end) {
// maybe this shouldn't link groups together that are clear borders of other nodes because then I don't have any read spanning the edges
char strand='.';
if(sno==2) strand='+';
else if(sno==0) strand='-';
for(int g=0;g<guides.Count();g++) {
if((sno==1 || guides[g]->strand==strand) && guides[g]->overlap(start,end)) { // guide overlaps than look at the exons
for(int i=0;i<guides[g]->exons.Count();i++) {
if(end<guides[g]->exons[i]->start) break; // there won't be any further overlap
if(start<guides[g]->exons[i]->start) break; // overlap is before start of exon
if(end<=guides[g]->exons[i]->end) {
//fprintf(stderr,"overlap btw %d-%d and exon %d-%d of guide %s\n",start,end,guides[g]->exons[i]->start,guides[g]->exons[i]->end,guides[g]->getID());
return true; // start is biger than exon start
}
}
}
}
return false;
}
bool good_junc(CJunction& jd,int refstart, GVec<float>* bpcov) {
//fprintf(stderr,"consider junction:%d-%d:%d support=%f,%f nreads=%f\n",jd.start,jd.end,jd.strand,jd.leftsupport,jd.rightsupport,jd.nreads);
/*** 1. if only we do estimation and it does not match guide do not consider ***/
if(eonly && !jd.guide_match) { // this way I am using only reads that are compatible to annotated transcripts
jd.strand=0;
return false;
}
/*** 2. keep if it's in the annotation ***/
if(jd.guide_match) return true; // this junction is covered by at least one read: the one that calls good_junc
// ^ KEEP THIS IN MIND IF WE CHANGE HOW WE USE GOOD_JUNC
/*** 3. don't keep if it's below threshold ***/
if (jd.nreads_good<junctionthr) { // junctionthr is always positive
//if (jd.leftsupport<junctionthr || jd.rightsupport<junctionthr || (jd.end-jd.start>longintron && jd.nreads_good<junctionthr)) {
jd.strand=0;
//fprintf(stderr,"nosupport: left=%f right=%f good=%f\n",jd.leftsupport,jd.rightsupport,jd.nreads_good);
return false;
}
// if(!jd.strand) return false; the strand has to be non-zero when we call good_junc -> KEEP THIS IN MIND IF WE CHANGE HOW WE USE GOOD_JUNC
// don't trust spliced reads that have a very low coverage:
//int sno=(int)jd.strand+1;
bool mismatch=false;
/*** 5. don't keep if it's a long intron and all junctions are from bad reads ***/
if (jd.nm && round(jd.nm)==round(jd.nreads)) {
mismatch=true;
if(jd.end-jd.start>longintron && jd.nreads<CHI_WIN*ERROR_PERC) { // don't believe long intron if all junctions are from bad reads unless highly covered
jd.strand=0;
//jd.nm=0; // not sure why this was set here, as it doesn't seem to be used again
//fprintf(stderr,"bad longintron\n");
return false;
}
}
/*** 4. don't keep if coverage remains relatively constant and the junction is not a high fraction of coverage ***/
// cummulative bpcov on bw=3 (I should be looking in a 'codon' window
float mult=1/ERROR_PERC; // test if this is needed for longreads
//if(!longreads) {
if(longreads) mult/=ERROR_PERC; // higher tolerance for long reads
int bw=5;
int j=jd.start-refstart;
float lleftcov=0;
float lrightcov=0;
int sno=(int)jd.strand+1;
if(j+bw+1<bpcov[1].Count() && j>=bw) {
lleftcov=get_cov(1,j-bw+1,j,bpcov);
lrightcov=get_cov(1,j+1,j+bw,bpcov);
if(longreads) {
lleftcov-=get_cov(2-sno,j-bw+1,j,bpcov);
lrightcov-=get_cov(2-sno,j+1,j+bw,bpcov);
}
}
// shouldn't leftcov be normalized by bw below when comparing to leftsupport?
if(lleftcov>1/ERROR_PERC && jd.leftsupport*mult<ERROR_PERC*lleftcov && (mismatch || lrightcov>lleftcov*(1-ERROR_PERC))) { // gave some boost (*10) to junctions here assumming not all of them are captured
jd.strand=0;
//fprintf(stderr," left j=%d leftcov=%f leftsupprt=%f rightcov=%f\n",j+refstart,lleftcov,jd.leftsupport,lrightcov);
return false;
}
j=jd.end-refstart-1;
/* strand based */
float rleftcov=0;
float rrightcov=0;
if(j+bw+1<bpcov[1].Count() && j>=bw) {
rleftcov=get_cov(1,j-bw+1,j,bpcov);
rrightcov=get_cov(1,j+1,j+bw,bpcov);
if(longreads) {
rleftcov-=get_cov(2-sno,j-bw+1,j,bpcov);
rrightcov-=get_cov(2-sno,j+1,j+bw,bpcov);
}
}
if(rrightcov>1/ERROR_PERC && jd.rightsupport*mult<rrightcov*ERROR_PERC && (mismatch || rleftcov>rrightcov*(1-ERROR_PERC))) { // gave some boost (*10) to junctions here assumming not all of them are captured
jd.strand=0;
//fprintf(stderr," right j=%d leftcov=%f rightsupprt=%f rightcov=%f\n",j+refstart,rleftcov,jd.rightsupport,rrightcov);
return false;
}
/*if(lleftcov<rrightcov*ERROR_PERC*DROP || lleftcov*ERROR_PERC*DROP>rrightcov) { // significant drop between exons
jd.strand=0;
return false;
}*/
//}
/*** 6. don't keep it if it's not above 1% of all junctions -> might be spliceosome error ***/
//if(jd.nreads<1/ERROR_PERC && (jd.nreads*10<ERROR_PERC*jd.leftsupport || jd.nreads*10<ERROR_PERC*jd.rightsupport)) {
if(jd.nreads*10<ERROR_PERC*jd.leftsupport || jd.nreads*10<ERROR_PERC*jd.rightsupport) {
//fprintf(stderr,"nreads=%f leftsuport=%f rightsupport=%f\n",jd.nreads,jd.leftsupport,jd.rightsupport);
jd.strand=0;
return false;
}
return true;
}
bool good_merge_junc(CJunction& jd,GList<CJunction>& junction) {
if(jd.guide_match) return true; // this junction is covered by at least one read: the one that calls good_junc
// if(!jd.strand) return false; the strand has to be non-zero when we call good_junc -> KEEP THIS IN MIND IF WE CHANGE HOW WE USE GOOD_JUNC
// don't trust junctions that have a very low coverage: (note: junctions are stored by start)
int nj=junction.IndexOf(&jd);
if(nj<0 || !jd.nreads_good) {
//if(nj<0 || !jd.leftsupport || !jd.rightsupport) {
jd.strand=0;
return false;
}
int j=nj-1;
float sumjunc=jd.nreads_good;
while(j>=0 && junction[j]->start==jd.start) {
sumjunc+=junction[j]->nreads_good; j--;
}
j=nj+1;
while(j<junction.Count() && junction[j]->start==jd.start) {
sumjunc+=junction[j]->nreads_good; j++;
}
// this sorts some of the really bad junctions out
if(jd.nreads_good*100/sumjunc<isofrac) {
jd.strand=0;
return false;
}
return true;
}
void continue_read(GList<CReadAln>& readlist,int n,int idx) {
// keep longest part of read
readlist[n]->end=readlist[n]->segs[idx].end;
for(int i=readlist[n]->segs.Count()-1;i>idx;i--) {
readlist[n]->segs.Delete(i);
readlist[n]->juncs.Delete(i-1);
}
}
int build_graphs(BundleData* bdata) {
int refstart = bdata->start;
GList<CReadAln>& readlist = bdata->readlist;
GList<CJunction>& junction = bdata->junction;
GPVec<GffObj>& guides = bdata->keepguides;
GVec<float>* bpcov = bdata->bpcov; // I might want to use a different type of data for bpcov to save memory in the case of very long bundles
GList<CPrediction>& pred = bdata->pred;
// form groups on strands: all groups below are like this: 0 = negative strand; 1 = unknown strand; 2 = positive strand
GPVec<CGroup> group;
CGroup *currgroup[3]={NULL,NULL,NULL}; // current group of each type
CGroup *startgroup[3]={NULL,NULL,NULL}; // start group of each type
int color=0; // next color to assign
GVec<int> merge; // remembers merged groups
GVec<int> equalcolor; // remembers colors for the same bundle
GVec<int> *readgroup=new GVec<int>[readlist.Count()]; // remebers groups for each read; don't forget to delete it when no longer needed
GVec<int> guidepred; // for eonly keeps the prediction number associated with a guide
GArray<GEdge> guideedge; // 0: negative starts; 1 positive starts
/*GPVec<GPtFeature>& feature = bdata->ptfs; // these are point features (confirmed starts/stops)
for(int i=0;i<feature.Count();i++) {
if(feature[i]->ftype==GPFT_TSS)
fprintf(stderr,"TSS at position %d on strand %d\n",feature[i]->coord,feature[i]->strand);
if(feature[i]->ftype==GPFT_CPAS)
fprintf(stderr,"CPAS at position %d on strand %d\n",feature[i]->coord,feature[i]->strand);
}*/
//fprintf(stderr,"build_graphs with %d guides\n",guides.Count());
if(guides.Count()) {
guideedge.setSorted(true);
guideedge.setUnique(true);
//if(eonly)
for(int g=0;g<guides.Count();g++) {
guidepred.cAdd(-1);
bool covered=true;
RC_TData* tdata=(RC_TData*)(guides[g]->uptr);
if(longreads || mixedMode) {
for(int i=1;i<guides[g]->exons.Count();i++) {
char s=0; // unknown strand
if(guides[g]->strand=='+') s=1; // guide on positive strand
else if(guides[g]->strand=='-') s=-1; // guide on negative strand
CJunction jn(guides[g]->exons[i-1]->end,guides[g]->exons[i]->start,s);
int oidx=-1;
if (!junction.Found(&jn, oidx)) {
covered=false;
break;
}
}
}
else {
for(int i=0;i<tdata->t_introns.Count();i++) {
if(!tdata->t_introns[i]->rcount) {
covered=false;
break;
}
}
}
if(covered) {
tdata->in_bundle=2;
int s=-1; // unknown strand
if(guides[g]->strand=='+') s=1; // guide on positive strand
else if(guides[g]->strand=='-') s=0; // guide on negative strand
//fprintf(stderr,"Look to add guide g=%d start %d-%d and end %d-%d on strand %d\n",g,guides[g]->start,guides[g]->exons[0]->end,guides[g]->end,guides[g]->exons.Last()->start,s);
int uses=s;
if(s<0) uses=0;
GEdge ge(guides[g]->start,guides[g]->exons[0]->end,uses);
int idx=guideedge.IndexOf(ge);
//fprintf(stderr,"look for ge(%d,%d,%d) => start idx=%d\n",ge.val,ge.endval,ge.strand,idx);
if(idx<0) guideedge.Add(ge);
else if(guideedge[idx].endval>guides[g]->exons[0]->end) guideedge[idx].endval=guides[g]->exons[0]->end;
if(s<0) {
ge.strand=1;
idx=guideedge.IndexOf(ge);
if(idx<0) guideedge.Add(ge);
else if(guideedge[idx].endval>guides[g]->exons[0]->end) guideedge[idx].endval=guides[g]->exons[0]->end;
}
ge.val=guides[g]->end;
ge.endval=guides[g]->exons.Last()->start;
idx=guideedge.IndexOf(ge);
//fprintf(stderr,"look for ge(%d,%d,%d) => end idx=%d\n",ge.val,ge.endval,ge.strand,idx);
if(idx<0) guideedge.Add(ge);
else if(guideedge[idx].endval<guides[g]->exons.Last()->start) guideedge[idx].endval=guides[g]->exons.Last()->start;
if(s<0) {
ge.strand=0; // ge.strand was set as 1 before
idx=guideedge.IndexOf(ge);
if(idx<0) guideedge.Add(ge);
else if(guideedge[idx].endval<guides[g]->exons.Last()->start) guideedge[idx].endval=guides[g]->exons.Last()->start;
}
}
}
}
// this part is for adjusting leftsupport and rightsupport when considering all junctions that start at a given point
// sort junctions -> junctions are sorted already according with their start, but not their end
GList<CJunction> ejunction(junction);
ejunction.setFreeItem(false);
if(ejunction.Count()) ejunction.setSorted(juncCmpEnd);
uint start=0;
uint end=0;
double leftsupport[2]={0,0}; // should be strand based
double rightsupport[2]={0,0};
bool higherr=false;
char leftcons=-1;
char rightcons=-1;
for(int i=0;i<junction.Count();i++) {
//fprintf(stderr,"check junction:%d-%d:%d leftsupport=%f rightsupport=%f nm=%f nreads=%f\n",junction[i]->start,junction[i]->end,junction[i]->strand,junction[i]->leftsupport,junction[i]->rightsupport,junction[i]->nm,junction[i]->nreads);
if((!higherr || mixedMode) && junction[i]->strand && junction[i]->nm==junction[i]->nreads && !junction[i]->guide_match) {
higherr=true;
if(mixedMode) {
int j=i-1;
while(j>=0 && junction[j]->start+sserror>junction[i]->start) {
if(junction[j]->strand && junction[i]->strand!=junction[j]->strand && abs((int)(junction[j]->end-junction[i]->end))<(int)sserror && junction[j]->nm<junction[j]->nreads) {
junction[i]->strand = 0;
break;
}
j--;
}
if(junction[i]->strand) {
j=i+1;
while(j<junction.Count() && junction[j]->start-sserror<junction[i]->start) {
if(junction[j]->strand && junction[i]->strand!=junction[j]->strand && abs((int)(junction[j]->end-junction[i]->end))<(int)sserror && junction[j]->nm<junction[j]->nreads) {
junction[i]->strand = 0;
break;
}
j++;
}
}
}
}
if(junction[i]->start!=start) { // new junction starting at i
int j=i-1;
while(j>=0 && junction[j]->start==start) {
junction[j]->consleft=leftcons;
if(!junction[j]->guide_match && !leftcons && junction[j]->nreads_good<DROP/ERROR_PERC) junction[j]->strand=0;
if(junction[j]->strand) junction[j]->leftsupport=leftsupport[(1+junction[j]->strand)/2];
j--;
}
j=i+1; // check if there is the same junction further ahead first
if(junction[i]->strand) while(j<junction.Count() && junction[j]->start==junction[i]->start && junction[j]->end==junction[i]->end) {
if(junction[j]->strand && junction[i]->strand!=junction[j]->strand) {
//possible missaligned junction --> delete junction strand
if(junction[i]->nreads>junction[j]->nreads && junction[i]->nreads_good>junction[j]->nreads_good) junction[j]->strand=0;
if(junction[i]->nreads<junction[j]->nreads && junction[i]->nreads_good<junction[j]->nreads_good) junction[i]->strand=0;
}
j++;
}
leftsupport[0]=0;
leftsupport[1]=0;
if(junction[i]->strand) leftsupport[(1+junction[i]->strand)/2]=junction[i]->leftsupport; // I might have deleted the i junction above
start=junction[i]->start;
if(bdata->gseq) {
if(junction[i]->strand>0) {
if((bdata->gseq[junction[i]->start+1-refstart]=='g'||bdata->gseq[junction[i]->start+1-refstart]=='G') &&
(bdata->gseq[junction[i]->start+2-refstart]=='T'||bdata->gseq[junction[i]->start+2-refstart]=='t'||
bdata->gseq[junction[i]->start+2-refstart]=='C'||bdata->gseq[junction[i]->start+2-refstart]=='c')) {
junction[i]->consleft=1;
leftcons=1;
}
else {
junction[i]->consleft=0;
leftcons=0;
}
}
else if(junction[i]->strand<0) {
if((bdata->gseq[junction[i]->start+1-refstart]=='c'||bdata->gseq[junction[i]->start+1-refstart]=='C') &&
(bdata->gseq[junction[i]->start+2-refstart]=='T'||bdata->gseq[junction[i]->start+2-refstart]=='t')) {
junction[i]->consleft=1;
leftcons=1;
}
else {
junction[i]->consleft=0;
leftcons=0;
}
}
//fprintf(stderr,"junction:%d-%d:%d is %c%c-%c%c\n",junction[i]->start,junction[i]->end,junction[i]->strand,bdata->gseq[junction[i]->start+1-refstart],bdata->gseq[junction[i]->start+2-refstart],bdata->gseq[junction[i]->end-2-refstart],bdata->gseq[junction[i]->end-1-refstart]);
}
}
else if(junction[i]->strand) leftsupport[(1+junction[i]->strand)/2]+=junction[i]->leftsupport;
//fprintf(stderr,"leftsupport[%d]=%f\n",(1+junction[i]->strand)/2,leftsupport[(1+junction[i]->strand)/2]);
//fprintf(stderr,"check ejunction:%d-%d:%d leftsupport=%f rightsupport=%f nm=%f nreads=%f\n",ejunction[i]->start,ejunction[i]->end,ejunction[i]->strand,ejunction[i]->leftsupport,ejunction[i]->rightsupport,ejunction[i]->nm,ejunction[i]->nreads);
if(ejunction[i]->end!=end) { // I do not check if I deleted the junction here for support
int j=i-1;
while(j>=0 && ejunction[j]->end==end) {
ejunction[j]->consright=rightcons;
if(!ejunction[j]->guide_match && !rightcons && ejunction[j]->nreads_good<DROP/ERROR_PERC) ejunction[j]->strand=0;
if(ejunction[j]->strand) ejunction[j]->rightsupport=rightsupport[(1+ejunction[j]->strand)/2];
j--;
}
// I do not check here for possible missalignments
rightsupport[0]=0;
rightsupport[1]=0;
if(ejunction[i]->strand) rightsupport[(1+ejunction[i]->strand)/2]=ejunction[i]->rightsupport;
end=ejunction[i]->end;
if(bdata->gseq) {
if(ejunction[i]->strand>0) {
if((bdata->gseq[ejunction[i]->end-2-refstart]=='a'||bdata->gseq[ejunction[i]->end-2-refstart]=='A') &&
(bdata->gseq[ejunction[i]->end-1-refstart]=='G'||bdata->gseq[ejunction[i]->end-1-refstart]=='g')) {
ejunction[i]->consright=1;
rightcons=1;
}
else {
ejunction[i]->consright=0;
rightcons=0;
}
}
else if(ejunction[i]->strand<0) {
if((bdata->gseq[ejunction[i]->end-1-refstart]=='C'||bdata->gseq[ejunction[i]->end-1-refstart]=='c') &&
(bdata->gseq[ejunction[i]->end-2-refstart]=='A'||bdata->gseq[ejunction[i]->end-2-refstart]=='a'||
bdata->gseq[ejunction[i]->end-2-refstart]=='G'||bdata->gseq[ejunction[i]->end-2-refstart]=='g')) {
ejunction[i]->consright=1;
rightcons=1;
}
else {
ejunction[i]->consright=0;
rightcons=0;
}
}
//fprintf(stderr,"ejunction:%d-%d:%d is %c%c-%c%c\n",ejunction[i]->start,ejunction[i]->end,ejunction[i]->strand,bdata->gseq[ejunction[i]->start+1-refstart],bdata->gseq[ejunction[i]->start+2-refstart],bdata->gseq[ejunction[i]->end-2-refstart],bdata->gseq[ejunction[i]->end-1-refstart]);
}
}
else if(ejunction[i]->strand) rightsupport[(1+ejunction[i]->strand)/2]+=ejunction[i]->rightsupport;
//fprintf(stderr,"rightsupport[%d]=%f\n",(1+ejunction[i]->strand)/2,rightsupport[(1+ejunction[i]->strand)/2]);
}
// end adjusting leftsupport and rightsupport
//fprintf(stderr,"junction support computed\n");
if(higherr) { // there are some reads that contain very bad junctions -> need to find better closest junctions
uint juncsupport=junctionsupport;
if(longreads)
juncsupport=sserror;
else if(mixedMode) juncsupport=sserror/DROP;
//fprintf(stderr,"In higherr!\n");
GVec<int> jstarts; // good starting junctions
GVec<int> jends; // good ending junctions
if(viral) {
for(int i=1;i<junction.Count();i++) { // junction is sorted based on start
if(junction[i]->strand && junction[i]->nm && !junction[i]->guide_match && junction[i]->nm>=junction[i]->nreads) { // this is a bad junction -> check if it's maximal;
if(junction[i]->nreads_good>=0 && (junction[i]->nreads_good<1.25*junctionthr || !good_junc(*junction[i],refstart,bpcov))) { // threshold for bad junctions is higher; (should I also add that too short junctions not to be accepted?)
//junction[i]->strand=0; // just delete junction if it's low count
junction[i]->mm=-1;
//fprintf(stderr,"...delete due to being under threshold\n");
}
int j=i-1;
while(j>0 && junction[i]->start-junction[j]->start<juncsupport) {
if(junction[j]->strand==junction[i]->strand && junction[j]->nreads_good>=0 && junction[i]->nreads<junction[j]->nreads &&
abs((int)junction[i]->end-(int)junction[j]->end)<(int)juncsupport) { // j was not elminated and is better
if(junction[i]->nreads_good<0) { // i was eliminated before
int k=-junction[i]->nreads_good;
if(junction[k]->nreads<junction[j]->nreads) junction[i]->nreads_good=-j;
}
else {
junction[i]->nreads_good=-j;
}
}
j--;
}
}
}
for(int i=junction.Count()-1;i>0;i--) {
if(junction[i]->strand && junction[i]->nm && !junction[i]->guide_match && junction[i]->nm>=junction[i]->nreads) { // this is a bad junction -> check if it's maximal;
int j=i+1;
while(j<junction.Count() && junction[j]->start-junction[i]->start<juncsupport) {
if(junction[j]->strand==junction[i]->strand && junction[j]->nreads_good>=0 && junction[i]->nreads<junction[j]->nreads &&
abs((int)junction[i]->end-(int)junction[j]->end)<(int)juncsupport) { // j was not elminated and is better
if(junction[i]->nreads_good<0) { // i was eliminated before
int k=-junction[i]->nreads_good;
if(junction[k]->nreads<junction[j]->nreads) junction[i]->nreads_good=-j;
}
else {
junction[i]->nreads_good=-j;
}
}
j++;
}
}
}
}
else {
float tolerance=1-ERROR_PERC;
// strand based version
for(int i=1;i<junction.Count();i++) { // junction is sorted based on start
//fprintf(stderr,"junct[%d]:%d-%d:%d lefttsupport=%f nm=%f mm=%f nreads=%f nreads_good=%f\n",i,junction[i]->start,junction[i]->end,junction[i]->strand,junction[i]->leftsupport,junction[i]->nm,junction[i]->mm,junction[i]->nreads,junction[i]->nreads_good);
if(junction[i]->strand) {
if(junction[i]->nm && !junction[i]->guide_match && junction[i]->nm>=junction[i]->nreads) { // this is a bad junction -> check if it's maximal;
if(junction[i]->nreads_good>=0 && junction[i]->nreads_good<1.25*junctionthr) { // threshold for bad junctions is higher; (should I also add that too short junctions not to be accepted?)
//junction[i]->strand=0; // just delete junction if it's low count
junction[i]->mm=-1;
//fprintf(stderr,"...delete due to being under threshold\n");
}
int j=i-1;
float support=0;
bool searchjunc=true;
bool reliable=false;
//if(j>=0) fprintf(stderr,"...start at junct:%d-%d:%d leftsupport=%f dist=%d\n",junction[j]->start,junction[j]->end,junction[j]->strand,junction[j]->leftsupport,junction[i]->start-junction[j]->start);
while(j>0 && junction[i]->start-junction[j]->start<juncsupport) {
if(junction[j]->strand==junction[i]->strand) {
if(junction[j]->start==junction[i]->start) { // found a junction with the same start -> I have already searched it if it's bad
if(junction[j]->nreads<0) {
junction[i]->nreads=junction[j]->nreads;
searchjunc=false;
}
break;
}
else if(junction[j]->guide_match || junction[j]->nm<junction[j]->nreads) { // nearby junction is much more reliable
if(junction[j]->leftsupport>junction[i]->leftsupport*tolerance) { // the good junction is close enough
reliable=true;
junction[i]->nreads=-j;
support=junction[j]->leftsupport;
break;
}
}
else if(junction[j]->leftsupport>support && junction[i]->start-junction[j]->start<sserror && junction[j]->leftsupport*tolerance>junction[i]->leftsupport) {
//fprintf(stderr,"...1 compare to [%d]:%d-%d:%d leftsupport=%f\n",j,junction[j]->start,junction[j]->end,junction[j]->strand,junction[j]->leftsupport);
junction[i]->nreads=-j;
support=junction[j]->leftsupport;
}
}
j--;
}
if(searchjunc) {
j=i+1;
int dist=juncsupport;
if(junction[i]->nreads<0) {
dist=junction[i]->start-junction[abs((int)junction[i]->nreads)]->start;
}
//if(j<junction.Count()) fprintf(stderr,"...start at junct:%d-%d:%d leftsupport=%f dist=%d\n",junction[j]->start,junction[j]->end,junction[j]->strand,junction[j]->leftsupport,junction[j]->start-junction[i]->start);
while(j<junction.Count() && junction[j]->start-junction[i]->start<juncsupport) {
if(junction[j]->strand==junction[i]->strand && junction[j]->start!=junction[i]->start) {
int d=(int)(junction[j]->start-junction[i]->start);
if(junction[j]->guide_match || junction[j]->nm<junction[j]->nreads) {
if((d<dist || (d==dist && junction[j]->leftsupport>support)) && junction[j]->leftsupport>junction[i]->leftsupport*tolerance) {
junction[i]->nreads=-j;
support=junction[j]->leftsupport;
break;
}
}
else if(!reliable && junction[j]->leftsupport>support && (uint)d<sserror && junction[j]->leftsupport*tolerance>junction[i]->leftsupport) { // junction is not best within window
//fprintf(stderr,"...2 compare to [%d]:%d-%d:%d leftsupport=%f\n",j,junction[j]->start,junction[j]->end,junction[j]->strand,junction[j]->leftsupport);
junction[i]->nreads=-j;
support=junction[j]->leftsupport;
}
}
j++;
}
}
}
else if(mixedMode && junction[i]->nm<junction[i]->nreads) {
jstarts.Add(i);
}
}
//fprintf(stderr,"ejunct[%d]:%d-%d:%d rightsupport=%f nm=%f nreads=%f\n",i,ejunction[i]->start,ejunction[i]->end,ejunction[i]->strand,ejunction[i]->rightsupport,ejunction[i]->nm,ejunction[i]->nreads);
if(ejunction[i]->strand) {
if(ejunction[i]->nm && !ejunction[i]->guide_match && ejunction[i]->nm>=ejunction[i]->nreads) { // this is a bad junction -> check if it's maximal
if(ejunction[i]->nreads_good>=0 && ejunction[i]->nreads_good<1.25*junctionthr) { // threshold for bad junctions is higher
//ejunction[i]->strand=0;
ejunction[i]->mm=-1;
//fprintf(stderr,"...delete due to being under threshold\n");
}
int j=i-1;
float support=0;
bool searchjunc=true;
bool reliable=false;
//if(j>=0) fprintf(stderr,"...start at junct:%d-%d:%d rightsupport=%f dist=%d\n",ejunction[j]->start,ejunction[j]->end,ejunction[j]->strand,ejunction[j]->rightsupport,ejunction[i]->end-ejunction[j]->end);
while(j>0 && ejunction[i]->end-ejunction[j]->end<juncsupport) {
if(ejunction[j]->strand==ejunction[i]->strand) {
if(ejunction[j]->end==ejunction[i]->end) {
if(ejunction[j]->nreads_good<0) {
ejunction[i]->nreads_good=ejunction[j]->nreads_good;
searchjunc=false;
}
break;
}
else if(ejunction[j]->guide_match || ejunction[j]->nm<ejunction[j]->nreads) { // nearby junction is much more reliable
if(ejunction[j]->rightsupport>ejunction[i]->rightsupport*tolerance) { // the good junction is close enough
reliable=true;
ejunction[i]->nreads_good=-j;
support=ejunction[j]->rightsupport;
break;
}
}
else if(ejunction[j]->rightsupport>support && ejunction[i]->end-ejunction[j]->end < sserror && ejunction[j]->rightsupport*tolerance>ejunction[i]->rightsupport) {
//fprintf(stderr,"...1 compare to [%d]:%d-%d:%d rightsupport=%f\n",j,ejunction[j]->start,ejunction[j]->end,ejunction[j]->strand,ejunction[j]->rightsupport);
ejunction[i]->nreads_good=-j;
support=ejunction[j]->rightsupport;
}
}
j--;
}
if(searchjunc) {
j=i+1;
int dist=juncsupport;
if(ejunction[i]->nreads_good<0) {
dist=ejunction[i]->end-ejunction[abs((int)ejunction[i]->nreads_good)]->end;
}
//if(j<junction.Count()) fprintf(stderr,"...start at junct:%d-%d:%d rightsupport=%f dist=%d\n",ejunction[j]->start,ejunction[j]->end,ejunction[j]->strand,ejunction[j]->rightsupport,ejunction[j]->end-ejunction[i]->end);
while(j<junction.Count() && ejunction[j]->end-ejunction[i]->end<juncsupport) {
if(ejunction[j]->strand==ejunction[i]->strand && ejunction[j]->end!=ejunction[i]->end) {
int d=ejunction[j]->end-ejunction[i]->end;
if(ejunction[j]->guide_match || ejunction[j]->nm<ejunction[j]->nreads) {
if((d<dist || (d==dist && ejunction[j]->rightsupport>support)) && ejunction[j]->rightsupport>ejunction[i]->rightsupport*tolerance) {
ejunction[i]->nreads_good=-j;
support=ejunction[j]->rightsupport;
break;
}
}
else if((!reliable && ejunction[j]->rightsupport>support && ejunction[j]->end-ejunction[i]->end < sserror && ejunction[j]->rightsupport*tolerance>ejunction[i]->rightsupport) || ((int)(ejunction[j]->end-ejunction[i]->end)<dist && (ejunction[j]->guide_match || ejunction[j]->nm<ejunction[j]->nreads))) {
//fprintf(stderr,"...2 compare to [%d]:%d-%d:%d rightsupport=%f\n",j,ejunction[j]->start,ejunction[j]->end,ejunction[j]->strand,ejunction[j]->rightsupport);
ejunction[i]->nreads_good=-j;
support=ejunction[j]->rightsupport;
}
}
j++;
}
}
}
else if(mixedMode && ejunction[i]->nm<ejunction[i]->nreads) {
jends.Add(i);
}
}
}
}
if(mixedMode) { // check if there are junctions inside bigger junctions that can form small exons
int si=0;
for(int ei=0;ei<jends.Count();ei++) {
while(si<jstarts.Count() && junction[jstarts[si]]->start<=ejunction[jends[ei]]->end) si++;
int k=si;
while(k<jstarts.Count() && junction[jstarts[k]]->start-ejunction[jends[ei]]->end<SMALL_EXON) {
if(junction[jstarts[k]]->strand == ejunction[jends[ei]]->strand) {
CJunction jn(ejunction[jends[ei]]->start,junction[jstarts[k]]->end,junction[jstarts[k]]->strand);
int oidx=-1;
if (junction.Found(&jn, oidx) && junction[oidx]->nm>=junction[oidx]->nreads) { // candidate junction for deletion
junction[oidx]->strand=0;
break;
}
}
k++;
}
}
}
} //if higherr
/*
{ // DEBUG ONLY
for(int i=0;i<junction.Count();i++) {
if(junction[i]->guide_match) fprintf(stderr,"G");
if(junction[i]->strand && junction[i]->nreads>0 && junction[i]->nreads_good>0 && junction[i]->mm>=0) fprintf(stderr,"***");
//if(junction[i]->strand && junction[i]->mm>=0)
fprintf(stderr,"Junction[%d] %d-%d:%d has nm=%f mm=%f nreads=%f nreads_good=%f leftsupport=%f and rightsupport=%f\n",i,junction[i]->start,junction[i]->end,junction[i]->strand,
junction[i]->nm,junction[i]->mm,junction[i]->nreads,
junction[i]->nreads_good,junction[i]->leftsupport,junction[i]->rightsupport);
}
}
*/
//int **readgroup = new int*[readlist.Count()];
/*
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(s):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
//float fraglen=0;
//uint fragno=0;
//GHash<bool> boundaryleft;
//GHash<bool> boundaryright;
GIntHash<bool> boundaryleft;
GIntHash<bool> boundaryright;
bool resort=false;
int njunc=junction.Count();
for (int n=0;n<readlist.Count();n++) {
CReadAln & rd=*(readlist[n]);
// version that does not adjust read but discards it completely
bool keep=true;
int i=0;
/*fprintf(stderr,"check read[%d]:%d-%d:%d refstart=%d w/exons:",n,readlist[n]->start,readlist[n]->end,readlist[n]->strand,refstart);
for(i=0;i<rd.juncs.Count();i++) { fprintf(stderr," %d-%d:%d",rd.segs[i].start,rd.segs[i].end,rd.juncs[i]->strand);}
fprintf(stderr," %d-%d\n",rd.segs[i].start,rd.segs[i].end);
i=0;*/
while(i<rd.juncs.Count()) {
CJunction& jd=*(rd.juncs[i]);
//fprintf(stderr, " read junc %d-%d:%d nreads=%f nreads_good=%f nm=%f support=%f,%f between exons:%d-%d and %d-%d\n", jd.start, jd.end, jd.strand,jd.nreads,jd.nreads_good,jd.nm,jd.leftsupport,jd.rightsupport,rd.segs[i].start,rd.segs[i].end,rd.segs[i+1].start,rd.segs[i+1].end);
bool changeright=jd.nreads_good<0;
bool changeleft=jd.nreads<0;
if(viral && changeright) {
changeleft=true;
jd.nreads=jd.nreads_good;
}
if(jd.strand) {
if(!good_junc(jd,refstart,bpcov)) jd.mm=-1; // bad junction
if(changeleft || changeright) jd.strand=0;
if(jd.mm<0) jd.strand=0; // I can't believe the junction because it's too low
}
if(!jd.strand) { // found a bad junction
//instead of deleting read -> just delete junction and make sure that add_read_to_group adds read to multiple groups
//jd.nreads-=rd.read_count;
//if(jd.mm>=0 && (changeleft || changeright)) { // not sure why jd.mm should be positive here since I am searching the junction against the others anyway
if(changeleft || changeright) {
uint newstart=rd.segs[i].end;
uint newend=rd.segs[i+1].start;
int jk=-1;
int ek=-1;
if(changeleft) {
jk=abs(int(jd.nreads));
if(junction[jk]->nreads<0) { // not a valid left support -> delete junction
newstart=rd.segs[i].start-1;
}
else {
newstart=junction[jk]->start; // junction jk is good
//fprintf(stderr,"junction has newstart=%d from junction[jk=%d]\n",newstart,jk);
if(junction[jk]->strand) jk=-1;
}
}
if(changeright) {
ek=abs(int(jd.nreads_good));
if(viral) {
if(junction[ek]->nreads_good<0) {
newend=rd.segs[i+1].end+1;
}
else {
newend=junction[ek]->end;
//fprintf(stderr,"junction has newend=%d from junction[ek=%d]\n",newend,ek);
}
}
else {
if(ejunction[ek]->nreads_good<0) {
newend=rd.segs[i+1].end+1;
}
else {
newend=ejunction[ek]->end;
//fprintf(stderr,"junction has newend=%d from junction[ek=%d]\n",newend,ek);
if(ejunction[ek]->strand) ek=-1;
}
}
}
//if(jd.mm>=0 && newstart>=rd.segs[i].start && newend<=rd.segs[i+1].end) { // junction inside read boundaries
if(newstart>=rd.segs[i].start && newend<=rd.segs[i+1].end && newstart<=newend) { // junction inside read boundaries
bool searchjunc=true;
bool addjunction=true;
rd.segs[i].end=newstart; // adjust start
rd.segs[i+1].start=newend; // adjust end
if(jd.mm>=0) {
if(jk>0) { // search junctions
int k=jk;
while(k>0 && junction[k]->start==newstart) {
if(mixedMode && junction[k]->nm<junction[k]->nreads) addjunction=false;
if(rd.strand==junction[k]->strand && junction[k]->end==newend) {
rd.juncs.Put(i,junction[k]);
searchjunc=false;
break;
}
k--;
}
if(searchjunc) {
k=jk+1;
while(k<junction.Count() && junction[k]->start==newstart) {
if(mixedMode && junction[k]->nm<junction[k]->nreads) addjunction=false;
if(rd.strand==junction[k]->strand && junction[k]->end==newend) {
rd.juncs.Put(i,junction[k]);
searchjunc=false;
break;
}
k++;
}
}
if(searchjunc) { // I did not find junction -> I need to create a new one
// first check if I already added such a junction
for(k=njunc;k<junction.Count();k++) {
if(rd.strand==junction[k]->strand && junction[k]->start==newstart && junction[k]->end==newend) {
rd.juncs.Put(i,junction[k]);
searchjunc=false;
break;
}
}
if(searchjunc && addjunction) {
if(!resort) {
junction.setSorted(false);
ejunction.setSorted(false);
resort=true;
}
//fprintf(stderr,"Add new junction:%d-%d:%d at position %d njunc=%d\n",newstart,newend,rd.strand,junction.Count(),njunc);
CJunction *junc=new CJunction(newstart,newend,rd.strand);
junction.Add(junc);
ejunction.Add(junc);
rd.juncs.Put(i,junc);
}
}
}
else if(ek>0) { // ek>0 => search ejunctions; ek>0 because I have either changeleft or changeright
int k=ek;
while(k>0 && ejunction[k]->end==newend) {
if(mixedMode && junction[k]->nm<junction[k]->nreads) addjunction=false;
if(rd.strand==ejunction[k]->strand && ejunction[k]->start==newstart) {
rd.juncs.Put(i,ejunction[k]);
searchjunc=false;
break;
}
k--;
}
if(searchjunc) {
k=ek+1;
while(k<ejunction.Count() && ejunction[k]->end==newend) {
if(mixedMode && junction[k]->nm<junction[k]->nreads) addjunction=false;
if(rd.strand==ejunction[k]->strand && ejunction[k]->start==newstart) {
rd.juncs.Put(i,ejunction[k]);
searchjunc=false;
break;
}
k++;
}
}
if(searchjunc && addjunction) { // I did not find junction -> I need to create a new one
// first check if I already added such a junction
for(k=njunc;k<ejunction.Count();k++) {
if(rd.strand==ejunction[k]->strand && ejunction[k]->start==newstart && ejunction[k]->end==newend) {
rd.juncs.Put(i,ejunction[k]);
searchjunc=false;
break;
}
}
if(searchjunc) {
if(!resort) {
junction.setSorted(false);
ejunction.setSorted(false);
resort=true;
}
//fprintf(stderr,"Add new junction:%d-%d:%d at position %d njunc=%d\n",newstart,newend,rd.strand,junction.Count(),njunc);
CJunction *junc=new CJunction(newstart,newend,rd.strand);
junction.Add(junc);
ejunction.Add(junc);
rd.juncs.Put(i,junc);
}
}
}
}
}
//fprintf(stderr, "read[%d] adjusted to junction:%d-%d\n",n,rd.segs[i].end,rd.segs[i+1].start);
}
// because read might be poorly mapped I also have to unpair it
if(keep) { // this is the first time I unpair read -> remove strand if pair has single exon?
for(int p=0;p<rd.pair_idx.Count();p++) {
int np=rd.pair_idx[p];
if(np>-1) {
rd.pair_idx[p]=-1;
for(int j=0;j<readlist[np]->pair_idx.Count();j++) // also unpair read np to n
if(readlist[np]->pair_idx[j]==n) {
readlist[np]->pair_idx[j]=-1;
break;
}
// remove strand for pair read if single exon ? is strand assigned before here ?
if(!readlist[np]->juncs.Count()) readlist[np]->strand=0;
}
}
keep=false;
}
}
else if(guides.Count()){ // need to remember boundary
bool exist=true;
//GStr bs((int)jd.start);
if(!boundaryleft[jd.start]) boundaryleft.Add(jd.start,exist);
//GStr be((int)jd.end);
if(!boundaryright[jd.end]) boundaryright.Add(jd.end,exist);
}
i++;
}
if(!keep) { // read has bad junctions -> check if I need to unstrand it
if(rd.strand) {
bool keepstrand=false;
for(int j=0;j<rd.juncs.Count();j++) if(rd.juncs[j]->strand) { keepstrand=true; break; }
if(!keepstrand) rd.strand=0;
}
}
else if(!rd.juncs.Count() && rd.strand) { // check if I need to unstrand current read due to future mapping
if(rd.pair_idx.Count()) {
bool keepstrand=false;
for(int p=0;p<rd.pair_idx.Count();p++) {
int np=rd.pair_idx[p];
if(np>-1 && n<np) {
if(!readlist[np]->juncs.Count()) {
if(readlist[np]->strand==rd.strand) {
keepstrand=true;
break;
}
}
else {
for(int j=0;j<readlist[np]->juncs.Count();j++) {
CJunction& jd=*(readlist[np]->juncs[j]);
if(jd.strand && good_junc(jd,refstart,bpcov)) {
keepstrand=true;
break;
}
}
if(!keepstrand) readlist[np]->strand=0;
}
}
if(keepstrand) break;
}
if(!keepstrand) rd.strand=0;
}
}
//if(rd.juncs.Count()) fprintf(stderr,"read[%d] keep=%d\n",n,keep);
//if(rd.strand) fprintf(stderr,"read[%d] has strand %d\n",n,rd.strand);
//if(keep) { // if it's a good read that needs to be kept
/*fprintf(stderr,"add read %d:%d-%d w/count=%g for color=%d with npairs=%d\n",n,readlist[n]->start,readlist[n]->end,readlist[n]->read_count,color,readlist[n]->pair_idx.Count());
fprintf(stderr,"add read[%d]:%d-%d:%d w/count=%g w/exons:",n,readlist[n]->start,readlist[n]->end,readlist[n]->strand,readlist[n]->read_count);
for(i=0;i<rd.juncs.Count();i++) { fprintf(stderr," %d-%d:%d",rd.segs[i].start,rd.segs[i].end,rd.juncs[i]->strand);}
fprintf(stderr," %d-%d\n",rd.segs[i].start,rd.segs[i].end);*/
color=add_read_to_group(n,readlist,color,group,currgroup,startgroup,readgroup,equalcolor,merge);
// count fragments
if(!rd.unitig)
bdata->frag_len+=rd.len*rd.read_count; // TODO: adjust this to work with FPKM for super-reads and Pacbio
double single_count=rd.read_count;
if(keep) for(int i=0;i<rd.pair_idx.Count();i++) {
// I am not counting the fragment if I saw the pair before and it wasn't deleted
if(rd.pair_idx[i]!=-1 && n>rd.pair_idx[i] && readlist[rd.pair_idx[i]]->nh) {// only if read is paired and it comes first in the pair I count the fragments
single_count-=rd.pair_count[i];
}
}
if(!rd.unitig && single_count>epsilon) {
bdata->num_fragments+=single_count; // TODO: FPKM will not work for super-reads here because I have multiple fragments in
// a super-read -> I might want to re-estimate this from coverage and have some input for read length; or I might only use TPM
}
//fprintf(stderr,"now color=%d\n",color);
//}
//else { fprintf(stderr,"read[%d] is not kept\n",n);}
//else clean_read_junctions(readlist[n]);
}
if(resort) {
junction.setSorted(true);
ejunction.setSorted(juncCmpEnd);
}
//fprintf(stderr,"fragno=%d fraglen=%g\n",fragno,fraglen);
//if(fragno) fraglen/=fragno;
// merge groups that are close together or __groups that are within the same exon of a reference gene__
if(bundledist || (guides.Count() && !longreads)) {
for(int sno=0;sno<3;sno++) {
CGroup *lastgroup=NULL;
CGroup *procgroup=startgroup[sno];
while(procgroup!=NULL) {
if(lastgroup) {
//fprintf(stderr,"sno=%d lastgroup->end=%d procgroup->start=%d procgroup->end=%d\n",sno,lastgroup->end,procgroup->start,procgroup->end);
//GStr bstart((int)lastgroup->end);
//GStr bend((int)procgroup->start);
if(!boundaryleft[lastgroup->end] && !boundaryright[procgroup->start] && (procgroup->start-lastgroup->end<=bundledist ||
(guides.Count() && guide_exon_overlap(guides,sno,lastgroup->end,procgroup->start)))) {
//fprintf(stderr,"sno=%d merge groups btw %d and %d dist=%d\n",sno,lastgroup->end,procgroup->start,procgroup->start-lastgroup->end);
merge_fwd_groups(group,lastgroup,procgroup,merge,equalcolor);
procgroup=lastgroup->next_gr;
continue;
}
}
lastgroup=procgroup;
procgroup=procgroup->next_gr;
}
}
}
if(guides.Count()) {
boundaryleft.Clear();
boundaryright.Clear();
}
/*
{ // DEBUG ONLY
fprintf(stderr,"%d groups created!\n",group.Count());
for(int sno=0;sno<3;sno++) {
fprintf(stderr, "Groups on strand %d:\n",sno);
CGroup *procgroup=startgroup[sno];
while(procgroup!=NULL) {
fprintf(stderr, " gr %d(%d,%.6f): %d-%d",procgroup->grid,procgroup->color,procgroup->cov_sum,procgroup->start,procgroup->end);
procgroup=procgroup->next_gr;
}
fprintf(stderr,"\n");
}
}
*/
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(after groups created):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
// ### form bundles here
// first do color assignment
for (int i=0;i<3;i++) currgroup[i]=startgroup[i];
CGroup *prevgroup[3]={NULL,NULL,NULL};
GVec<int> eqposcol(true);
GVec<int> eqnegcol(true);
eqposcol.Resize(equalcolor.Count(),-1);
eqnegcol.Resize(equalcolor.Count(),-1);
// each unstranded group needs to remember what proportion of stranded group it overlaps so that it can distribute reads later on -> maybe I can do this in the following while?
while(currgroup[0]!=NULL || currgroup[1]!=NULL || currgroup[2]!=NULL) { // there are still groups to process
int nextgr=get_min_start(currgroup); // gets the index of currgroup with the left most begining
int grcol = currgroup[nextgr]->color; // set smallest color for currgroup[$nextgr]
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[nextgr]->color=grcol;
//fprintf(stderr,"group %d id=%d: %u-%u col=%d from col=%d\n",nextgr,currgroup[nextgr]->grid,currgroup[nextgr]->start,currgroup[nextgr]->end,grcol,prevcol);
if(nextgr == 1) { // unknown strand group
if(prevgroup[0]!=NULL && currgroup[nextgr]->start <= prevgroup[0]->end+bundledist) { // overlaps previous negative group ; this needs bundledist
//fprintf(stderr,"\tovlp to neg group: %u-%u\n",prevgroup[0]->start,prevgroup[0]->end);
set_strandcol(currgroup[nextgr],prevgroup[0],prevgroup[0]->color,eqnegcol,equalcolor);
uint maxstart = currgroup[nextgr]->start > prevgroup[0]->start ? currgroup[nextgr]->start : prevgroup[0]->start;
uint minend = currgroup[nextgr]->end < prevgroup[0]->end ? currgroup[nextgr]->end : prevgroup[0]->end;
if(minend<maxstart) minend=maxstart; // this can only happen if bundledist >0
currgroup[nextgr]->neg_prop+=prevgroup[0]->cov_sum*(minend-maxstart+1)/prevgroup[0]->len();
}
while(currgroup[0]!=NULL && currgroup[nextgr]->start <= currgroup[0]->end+bundledist && currgroup[0]->start <= currgroup[nextgr]->end +bundledist) { // overlaps current negative strand group
//fprintf(stderr,"\tovlp to neg group: %u-%u\n",currgroup[0]->start,currgroup[0]->end);
int grcol = currgroup[0]->color; // set smallest color for currgroup[$nextgr]
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[0]->color=grcol;
currgroup[0]->neg_prop=1;
set_strandcol(currgroup[nextgr],currgroup[0],currgroup[0]->color,eqnegcol,equalcolor);
uint maxstart = currgroup[nextgr]->start > currgroup[0]->start ? currgroup[nextgr]->start : currgroup[0]->start;
uint minend = currgroup[nextgr]->end < currgroup[0]->end ? currgroup[nextgr]->end : currgroup[0]->end;
if(minend<maxstart) minend=maxstart;
currgroup[nextgr]->neg_prop+=currgroup[0]->cov_sum*(minend-maxstart+1)/currgroup[0]->len();
prevgroup[0]=currgroup[0];
currgroup[0]=currgroup[0]->next_gr;
}
float pos_prop=0;
if(prevgroup[2]!=NULL && currgroup[nextgr]->start <= prevgroup[2]->end + bundledist) { // overlaps positive strand group
//fprintf(stderr,"\tovlp to pos group: %u-%u\n",prevgroup[2]->start,prevgroup[2]->end);
set_strandcol(currgroup[nextgr],prevgroup[2],prevgroup[2]->color,eqposcol,equalcolor);
if(currgroup[nextgr]->neg_prop) {
uint maxstart = currgroup[nextgr]->start > prevgroup[2]->start ? currgroup[nextgr]->start : prevgroup[2]->start;
uint minend = currgroup[nextgr]->end < prevgroup[2]->end ? currgroup[nextgr]->end : prevgroup[2]->end;
if(minend<maxstart) minend=maxstart; // this can only happen if bundledist >0
pos_prop+=prevgroup[2]->cov_sum*(minend-maxstart+1)/prevgroup[2]->len();
}
}
while(currgroup[2]!=NULL && currgroup[nextgr]->start <= currgroup[2]->end +bundledist && currgroup[2]->start <= currgroup[nextgr]->end + bundledist) { // overlaps positive strand group
//fprintf(stderr,"\tovlp to pos group: %u-%u\n",currgroup[2]->start,currgroup[2]->end);
int grcol = currgroup[2]->color; // set smallest color for currgroup[$nextgr]
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[2]->color=grcol;
set_strandcol(currgroup[nextgr],currgroup[2],currgroup[2]->color,eqposcol,equalcolor);
if(currgroup[nextgr]->neg_prop) {
uint maxstart = currgroup[nextgr]->start > currgroup[2]->start ? currgroup[nextgr]->start : currgroup[2]->start;
uint minend = currgroup[nextgr]->end < currgroup[2]->end ? currgroup[nextgr]->end : currgroup[2]->end;
if(minend<maxstart) minend=maxstart; // this can only happen if bundledist >0
pos_prop+=currgroup[2]->cov_sum*(minend-maxstart+1)/currgroup[2]->len();
}
prevgroup[2]=currgroup[2];
currgroup[2]=currgroup[2]->next_gr;
}
if(pos_prop) {
currgroup[nextgr]->neg_prop/=(currgroup[nextgr]->neg_prop+pos_prop);
}
else if(currgroup[nextgr]->neg_prop) currgroup[nextgr]->neg_prop=1;
//fprintf(stderr,"neg_prop=%g pos_prop=%g\n",currgroup[nextgr]->neg_prop,pos_prop);
}
else if(nextgr == 0) { // negative strand group
currgroup[nextgr]->neg_prop=1;
}
prevgroup[nextgr]=currgroup[nextgr];
currgroup[nextgr]=currgroup[nextgr]->next_gr;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Colors assigned!\n");
for(int sno=0;sno<3;sno++) {
fprintf(stderr, "Colors of groups on strand %d:\n",sno);
CGroup *procgroup=startgroup[sno];
while(procgroup!=NULL) {
int grcol = procgroup->color;
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
int negcol=eqnegcol[grcol];
if(eqnegcol[grcol]!=-1){
while(equalcolor[negcol]!=negcol) {
negcol=equalcolor[negcol];
}
}
int poscol=eqposcol[grcol];
if(eqposcol[grcol]!=-1){
while(equalcolor[poscol]!=poscol) {
poscol=equalcolor[poscol];
}
}
fprintf(stderr, " gr %d(%d,%d,%d,%.6f): %d-%d\n",procgroup->grid,grcol,negcol,poscol,procgroup->cov_sum,procgroup->start,procgroup->end);
procgroup=procgroup->next_gr;
}
//fprintf(stderr,"\n");
}
//exit(0);
}
*/
// create bundles : bundles collect connected groups (with same color)
for (int i=0;i<3;i++) {
currgroup[i]=startgroup[i];
prevgroup[i]=NULL;
}
GPVec<CBundle> bundle[3]; // all bundles on all strands: 0,1,2
GPVec<CBundlenode> bnode[3]; // last bnodes on all strands: 0,1,2 for each bundle : this might be the key for overalps
GVec<int> group2bundle[3]; // to retrace reads from group no to bundle
for(int sno=0;sno<3;sno++) {
group2bundle[sno].Resize(group.Count(),-1); // for a given group id we get a certain bnode id
bnode[sno].setFreeItem(false);
}
GVec<int> bundlecol(true); // associates a bundle number to a group color
bundlecol.Resize(equalcolor.Count(),-1);
while(currgroup[0]!=NULL || currgroup[1]!=NULL || currgroup[2]!=NULL) { // there are still groups to process
int nextgr=get_min_start(currgroup); // next group based on starting position
// get group color; I need to redo this to ensure I equalize all colors -> they could still be hanged by set_strandcol
int grcol = currgroup[nextgr]->color;
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[nextgr]->color=grcol;
if(nextgr == 0 || nextgr ==2 || (nextgr==1 &&(eqnegcol[grcol]==-1) && (eqposcol[grcol]==-1))) { // negative or positive strand bundle or unstranded bundle
int bno=bundlecol[grcol];
if(bno>-1) { // bundle for group has been created before
//fprintf(stderr,"Add group=%d to bundle[%d][%d]\n",currgroup[nextgr]->grid,nextgr,bno);
add_group_to_bundle(currgroup[nextgr],bundle[nextgr][bno],bnode[nextgr],bundledist);
}
else { // create new bundle
bno=create_bundle(bundle[nextgr],currgroup[nextgr],bnode[nextgr]);
//fprintf(stderr,"Add group=%d to new bundle[%d][%d]\n",currgroup[nextgr]->grid,nextgr,bno);
bundlecol[grcol]=bno;
}
group2bundle[nextgr][currgroup[nextgr]->grid]=bundle[nextgr][bno]->lastnodeid;
}
else { // unknown strand : here is where I should compute positive and negative proportions
if(eqnegcol[grcol]!=-1){
int negcol=eqnegcol[grcol];
while(equalcolor[negcol]!=negcol) {
negcol=equalcolor[negcol];
}
int bno=bundlecol[negcol];
if(bno>-1) { // bundle for group has been created before
//fprintf(stderr,"Add group=%d to bundle[%d:0][%d]\n",currgroup[nextgr]->grid,nextgr,bno);
add_group_to_bundle(currgroup[nextgr],bundle[0][bno],bnode[0],bundledist); // this needs bundledist
}
else { // create new bundle
bno=create_bundle(bundle[0],currgroup[nextgr],bnode[0]);
//fprintf(stderr,"Add group=%d to new bundle[%d:0][%d]\n",currgroup[nextgr]->grid,nextgr,bno);
bundlecol[negcol]=bno;
}
group2bundle[0][currgroup[nextgr]->grid]=bundle[0][bno]->lastnodeid;
} // if(eqnegcol[grcol]!=-1)
if(eqposcol[grcol]!=-1){
int poscol=eqposcol[grcol];
while(equalcolor[poscol]!=poscol) {
poscol=equalcolor[poscol];
}
int bno=bundlecol[poscol];
if(bno>-1) { // bundle for group has been created before
//fprintf(stderr,"Add group=%d to new bundle[%d][%d:2]\n",currgroup[nextgr]->grid,nextgr,bno);
add_group_to_bundle(currgroup[nextgr],bundle[2][bno],bnode[2],bundledist);
}
else { // create new bundle
bno=create_bundle(bundle[2],currgroup[nextgr],bnode[2]);
//fprintf(stderr,"Add group=%d to new bundle[%d:2][%d]\n",currgroup[nextgr]->grid,nextgr,bno);
bundlecol[poscol]=bno;
}
group2bundle[2][currgroup[nextgr]->grid]=bundle[2][bno]->lastnodeid;
}
}
currgroup[nextgr]=currgroup[nextgr]->next_gr;
} // while(currgroup[0]!=NULL || currgroup[1]!=NULL || currgroup[2]!=NULL)
// Clean up no longer needed variables
// group.Clear(); maybe I still need this?
equalcolor.Clear();
eqposcol.Clear();
eqnegcol.Clear();
bundlecol.Clear();
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(after bundles created):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
// next variables are in order to remember if I get guide coverage
GVec<int>* bnodeguides=NULL;
if(bundle[1].Count() && bnode[1].Count()) {
bnodeguides = new GVec<int>[bnode[1].Count()];
}
//if(guides.Count()) fprintf(stderr,"No of guides=%d\n",guides.Count());
if(c_out || (bundle[1].Count() && bnode[1].Count())) // coverage is needed
for(int g=0;g<guides.Count();g++) {
//fprintf(stderr,"consider guide %d\n",g);
int s=0;
if(guides[g]->strand=='+') s=2;
if((c_out && !get_covered(guides[g],bundle[s],bnode[s],junction,NULL,0)) ||
(bundle[1].Count() && bnode[1].Count() && guides[g]->exons.Count()==1))
get_covered(guides[g],bundle[1],bnode[1],junction,bnodeguides,g);
}
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr, "There are %d unstranded bundles %d negative bundles and %d positive bundles\n",bundle[1].Count(),bundle[0].Count(),bundle[2].Count());
for(int sno=0;sno<3;sno++) {
fprintf(stderr, "Bundles on strand %d:\n",sno);
for(int b=0;b<bundle[sno].Count();b++) {
int elen=bnode[sno][bundle[sno][b]->lastnodeid]->end-bnode[sno][bundle[sno][b]->startnode]->start+1;
CBundlenode *currbnode=bnode[sno][bundle[sno][b]->startnode];
fprintf(stderr,"***Bundle %d with len=%d:",b,elen);
int nodes=0;
while(currbnode!=NULL) {
fprintf(stderr, " %d-%d cov=%.6f",currbnode->start,currbnode->end,currbnode->cov/(currbnode->end-currbnode->start+1));
currbnode=currbnode->nextnode;
nodes++;
}
currbnode=bnode[sno][bundle[sno][b]->lastnodeid];
nodes++;
fprintf(stderr," last node:%d-%d total nodes=%d\n",currbnode->start,currbnode->end,nodes);
}
}
}
*/
int geneno=0;
// ### predict transcripts for unstranded bundles here
//if(fraglen)
int g=0;
for(int b=0;b<bundle[1].Count();b++) { // these are neutral bundles that do not overlap any signed reads
// I need to address features here too -> TODO
bool guide_ovlp=false;
while(g<guides.Count() && (guides[g]->exons.Count()>1 || guides[g]->end<bnode[1][bundle[1][b]->startnode]->start)) {
g++;
}
// now guides[g]->end>=bnode[1][bundle[1][b]->startnode]->start
if(g<guides.Count() && guides[g]->start<=bnode[1][bundle[1][b]->startnode]->end) guide_ovlp=true;
if(bundle[1][b]->cov && ((bundle[1][b]->multi/bundle[1][b]->cov)<=mcov*(1-ERROR_PERC) || guide_ovlp || rawreads)) { // && (guides.Count() || adaptive || bundle[1][b]->len >= mintranscriptlen)) { // there might be small transfrags that are worth showing, but here I am ignoring them
// bundle might contain multiple fragments of a transcript but since we don't know the complete structure -> print only the pieces that are well represented
CBundlenode *currbnode=bnode[1][bundle[1][b]->startnode];
int t=1;
while(currbnode!=NULL) {
//int len=currbnode->end-currbnode->start+1;
//float cov=currbnode->cov/(currbnode->end-currbnode->start+1);
bool printguides=false;
if(!rawreads) for(int i=0;i<bnodeguides[currbnode->bid].Count();i++) {
int g=bnodeguides[currbnode->bid][i];
geneno++;
int glen=guides[g]->end-guides[g]->start+1;
if(glen && guides[g]->exons.Count()==1) {
RC_TData* tdata=(RC_TData*)(guides[g]->uptr);
tdata->in_bundle=3;
float gcov=(tdata->t_exons[0])->movlcount/glen;
// if(cov<gcov) gcov=cov; WHY DO I DO THIS?? CHECK!!!
CPrediction *p=new CPrediction(geneno-1, guides[g], guides[g]->start, guides[g]->end, gcov, guides[g]->strand, glen);
if(c_out) {
GStr guidecov;
guidecov.appendfmt("%.2f",gcov);
guides[g]->addAttr("coverage",guidecov.chars());
guides[g]->printTranscriptGff(c_out);
}
GSeg exon(guides[g]->start, guides[g]->end);
p->exons.Add(exon);
p->exoncov.Add(gcov);
if(longreads) p->tlen=-p->tlen;
pred.Add(p);
printguides=true;
guidepred[g]=pred.Count()-1;
}
}
if(!printguides) { // && (adaptive || (cov>=readthr && len>=mintranscriptlen))) {
if(t==1) { geneno++;}
char sign='.';
GVec<CTrimPoint> trimpoint;
find_all_trims(refstart,0,currbnode->start, currbnode->end,bpcov,trimpoint); // sign should not matter as I am in a totally neutral zone
uint predstart=currbnode->start;
uint predend=currbnode->end;
for(int i=0;i<trimpoint.Count();i++) {
if(trimpoint[i].pos) {
if(trimpoint[i].start) {
int len=trimpoint[i].pos-CHI_WIN-predstart+1;
if(len>mintranscriptlen) {
float cov=get_cov(1,predstart-refstart,trimpoint[i].pos-CHI_WIN-refstart,bpcov)/len;
//fprintf(stderr,"Store single prediction:%d - %d with cov=%f\n",predstart, trimpoint[i].pos-CHI_WIN, cov);
CPrediction *p=new CPrediction(geneno-1, NULL, predstart, trimpoint[i].pos-CHI_WIN, cov, sign, len);
GSeg exon(predstart, trimpoint[i].pos-CHI_WIN);
p->exons.Add(exon);
if(!rawreads) p->exoncov.Add(cov);
if(longreads) p->tlen=-p->tlen;
pred.Add(p);
t++;
}
predstart=trimpoint[i].pos;
}
else {
int len=trimpoint[i].pos-predstart+1;
if(len>mintranscriptlen) {
float cov=get_cov(1,predstart-refstart,trimpoint[i].pos-refstart,bpcov)/len;
//fprintf(stderr,"Store single prediction:%d - %d with cov=%f\n",predstart, trimpoint[i].pos, cov);
CPrediction *p=new CPrediction(geneno-1, NULL, predstart, trimpoint[i].pos, cov, sign, len);
GSeg exon(predstart, trimpoint[i].pos);
p->exons.Add(exon);
if(!rawreads) p->exoncov.Add(cov);
if(longreads) p->tlen=-p->tlen;
pred.Add(p);
t++;
}
predstart=trimpoint[i].pos+CHI_WIN;
}
}
}
int len=predend-predstart+1;
if(len>mintranscriptlen) {
float cov=get_cov(1,predstart-refstart,predend-refstart,bpcov)/len;
//fprintf(stderr,"Store single prediction:%d - %d with cov=%f\n",predstart, predend, cov);
CPrediction *p=new CPrediction(geneno-1, NULL, predstart, predend, cov, sign, len);
GSeg exon(predstart, predend);
p->exons.Add(exon);
if(!rawreads) p->exoncov.Add(cov);
if(longreads) p->tlen=-p->tlen;
pred.Add(p);
t++;
}
}
currbnode=currbnode->nextnode;
}
}
}
//fprintf(stderr,"Done with unstranded bundles\n");
if (bnodeguides) delete[] bnodeguides;
// ### build graphs for stranded bundles here
if(startgroup[0]!=NULL || startgroup[2]!=NULL) { //# there are stranded groups to process
// I don't need the groups here anymore : I only use their numbers
// group.Clear(); // I will need the proportions later on
GVec<CGraphinfo> *bundle2graph[2]; // should I keep the neutral strand for consistency ? -> remember not to delete it
GVec<int> graphno[2]; // how many nodes are in a certain graph g, on strand s: graphno[s][g]
GVec<int> edgeno[2]; // how many edges are in a certain graph g, on strand s: edgeno[s][g]
// GVec<int> trnumber[2]; // how many transfrags are on a strand s, in a graph g -> I can find out this from transfrag[s][g].Count()
// int ngraph[2]={0,0}; // how many graphs are in each strand: negative (0), or positive(1) -> keep one for each bundle
GPVec<CTransfrag> *transfrag[2]; // for each transfrag t on a strand s, in a graph g, transfrag[s][g][t] gives it's abundance and it's pattern
GPVec<CGraphnode> *no2gnode[2]; // for each graph g, on a strand s, no2gnode[s][g][i] gives the node i
CTreePat **tr2no[2]; // for each graph g, on a strand s, tr2no[s][g] keeps the tree pattern structure for quick retrieval of the index t of a tansfrag
GIntHash<int> *gpos[2]; // for each graph g, on a strand s, gpos[s][g] keeps the hash between edges and positions in the bitvec associated to a pattern
GVec<int> lastgpos[2];
int bno[2]={0,0};
// build graph structure
for(int sno=0;sno<3;sno+=2) { // skip neutral bundles -> those shouldn't have junctions
// guides appear to be sorted by start --> CHECK THIS!!
int g=0;
int ng=guides.Count();
int s=sno/2; // adjusted strand due to ignoring neutral strand
char strnd='-';
if(s) strnd='+';
bundle2graph[s]=NULL;
if(bnode[sno].Count()) bundle2graph[s]=new GVec<CGraphinfo>[bnode[sno].Count()];
transfrag[s]=NULL;
no2gnode[s]=NULL;
tr2no[s]=NULL;
gpos[s]=NULL;
if(bundle[sno].Count()) {
transfrag[s]=new GPVec<CTransfrag>[bundle[sno].Count()]; // for each bundle I have a graph ? only if I don't ignore the short bundles
no2gnode[s]=new GPVec<CGraphnode>[bundle[sno].Count()];
gpos[s]=new GIntHash<int>[bundle[sno].Count()];
GCALLOC(tr2no[s],bundle[sno].Count()*sizeof(CTreePat *));
bno[s]=bundle[sno].Count();
for(int b=0;b<bundle[sno].Count();b++) {
graphno[s].cAdd(0);
edgeno[s].cAdd(0);
lastgpos[s].cAdd(0);
// I am overestmating the edgeno below, hopefully not by too much
//fprintf(stderr,"Bundle is: %d - %d start at g=%d sno=%d b=%d\n",bnode[sno][bundle[sno][b]->startnode]->start,bnode[sno][bundle[sno][b]->lastnodeid]->end,g,sno,b);
while(g<ng && guides[g]->end<bnode[sno][bundle[sno][b]->startnode]->start) g++;
int cg=g;
int nolap=0;
while(cg<ng && guides[cg]->start<=bnode[sno][bundle[sno][b]->lastnodeid]->end) { // this are potential guides that might overlap the current bundle, and they might introduce extra edges
//fprintf(stderr,"...consider guide cg=%d with strand=%c and in_bundle=%d\n",cg,guides[cg]->strand,((RC_TData*)(guides[cg]->uptr))->in_bundle);
if((guides[cg]->strand==strnd || guides[cg]->strand=='.') && ((RC_TData*)(guides[cg]->uptr))->in_bundle>=2) {
//fprintf(stderr,"Add guide g=%d with start=%d end=%d\n",cg,guides[cg]->start,guides[cg]->end);
edgeno[s][b]+=2; // this is an overestimate: possibly I have both an extra source and an extra sink link
nolap++;
}
cg++;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"edgeno[%d][%d]=%d\n",s,b,edgeno[s][b]);
if(bundle[sno][b]->cov) {
fprintf(stderr,"proc bundle[%d][%d] %f/%f is %f len=%d and %d guides\n",sno,b,
bundle[sno][b]->multi,bundle[sno][b]->cov,(float)bundle[sno][b]->multi/bundle[sno][b]->cov,
bundle[sno][b]->len,nolap);
}
}
*/
// here I can add something in stringtie to lower the mintranscript len if there are guides?
if(bundle[sno][b]->cov &&
(((bundle[sno][b]->multi/bundle[sno][b]->cov)<=mcov && bundle[sno][b]->len >= mintranscriptlen)
||nolap)) { // bundle is worth processing: it might be that there are small transfrags from source to sink that are worth processing
/*
// first identify drops/spikes in coverage points
GVec<CTrimPoint> trims;
if(trim) {
get_trims(trims,bnode[sno][bundle[sno][b]->startnode],refstart,bpcov);
{ // DEBUG ONLY
fprintf(stderr,"Trims found:");
for(int z=0;z<trims.Count();z++) fprintf(stderr," %d(%d,%f)",trims[z].pos,trims[z].start,trims[z].abundance);
fprintf(stderr,"\n");
}
}
graphno[s][b]=create_graph(s,b,bundle[sno][b],bnode[sno],junction,ejunction,
bundle2graph,no2gnode,transfrag,trims); // also I need to remember graph coverages somewhere -> probably in the create_graph procedure
*
*/
// create graph then
graphno[s][b]=create_graph(refstart,s,b,bundle[sno][b],bnode[sno],junction,ejunction,
bundle2graph,no2gnode,transfrag,gpos,bdata,edgeno[s][b],lastgpos[s][b],guideedge); // also I need to remember graph coverages somewhere -> probably in the create_graph procedure
if(graphno[s][b]) tr2no[s][b]=construct_treepat(graphno[s][b],gpos[s][b],transfrag[s][b]);
else tr2no[s][b]=NULL;
}
else tr2no[s][b]=NULL;
}
}
}
//fprintf(stderr,"Done creating graphs\n");
/*
{ // DEBUG ONLY
printTime(stderr);
for(int s=0;s<2;s++) {
fprintf(stderr, "There are %d stranded[%d] graphs\n",bno[s],int(2*s));
for(int b=0;b<bno[s];b++) {
if(graphno[s][b]) {
GStr pat;
fprintf(stderr,"Graph[%d][%d] with %d nodes and %d edges with lastgpos=%d:",int(2*s),b,graphno[s][b],edgeno[s][b],lastgpos[s][b]);
for(int nd=1;nd<graphno[s][b]-1;nd++)
fprintf(stderr," %d(%d-%d)",nd,no2gnode[s][b][nd]->start,no2gnode[s][b][nd]->end);
fprintf(stderr,"\n");
//print_pattern(tr2no[s][b],pat,graphno[s][b]);
}
}
}
}
*/
/*
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(after graphs created):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
// I can clean up some data here:
for(int sno=0;sno<3;sno++) {
int n=bnode[sno].Count();
for(int b=0;b<n;b++) delete bnode[sno][b];
bnode[sno].Clear();
bundle[sno].Clear();
}
// because of this going throu
// compute probabilities for stranded bundles
for (int n=0;n<readlist.Count();n++) {
/*if(readlist[n]->unitig) { // super-reads are unpaired
float srcov=0;
for(int i=0;i<readlist[n]->segs.Count();i++)
srcov+=get_cov(1,readlist[n]->segs[i].start-refstart,readlist[n]->segs[i].end-refstart,bpcov)/readlist[n]->segs[i].len();
if(srcov) get_fragment_pattern(readlist,n,-1,readlist[n]->read_count/srcov,readgroup,merge,group2bundle,bundle2graph,graphno,edgeno,gpos,no2gnode,transfrag,tr2no,group);
}
else {*/
float single_count=readlist[n]->read_count;
for(int j=0; j<readlist[n]->pair_idx.Count();j++) {
int np=readlist[n]->pair_idx[j];
if(np>-1) {
single_count-=readlist[n]->pair_count[j];
if(n<np) {
get_fragment_pattern(readlist,n,np,readlist[n]->pair_count[j],readgroup,merge,group2bundle,bundle2graph,graphno,edgeno,gpos,no2gnode,transfrag,tr2no,group);
}
}
}
if(single_count>epsilon) {
get_fragment_pattern(readlist,n,-1,single_count,readgroup,merge,group2bundle,bundle2graph,graphno,edgeno,gpos,no2gnode,transfrag,tr2no,group);
}
//}
}
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(read patterns counted):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
// shouldn't readlist be also cleared up here? maybe bpcov too?
// don't forget to clean up the allocated data here
delete [] readgroup;
group.Clear();
// parse graph
for(int s=0;s<2;s++) {
for(int b=0;b<bno[s];b++) {
//fprintf(stderr,"Process graph[%d][%d] with %d nodes\n",s,b,graphno[s][b]);
if(graphno[s][b]) {
// include source to guide starts links
GVec<CGuide> guidetrf;
/*
{ // DEBUG ONLY
fprintf(stderr,"process refguides for s=%d b=%d edgeno=%d gno=%d lastgpos=%d guidescount=%d\n",s,b,edgeno[s][b],graphno[s][b],lastgpos[s][b],guides.Count());
fprintf(stderr,"There are %d nodes for graph[%d][%d]:\n",graphno[s][b],s,b);
for(int i=0;i<graphno[s][b];i++) {
fprintf(stderr,"%d (%d-%d): %f len=%d cov=%f",i,no2gnode[s][b][i]->start,no2gnode[s][b][i]->end,no2gnode[s][b][i]->cov,no2gnode[s][b][i]->len(),no2gnode[s][b][i]->cov/no2gnode[s][b][i]->len());
fprintf(stderr," parents:");
for(int j=0;j<no2gnode[s][b][i]->parent.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->parent[j]);
fprintf(stderr," trf=");
for(int j=0;j<no2gnode[s][b][i]->trf.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->trf[j]);
fprintf(stderr,"\n");
}
}
*/
if(guides.Count()) process_refguides(graphno[s][b],edgeno[s][b],gpos[s][b],lastgpos[s][b],no2gnode[s][b],transfrag[s][b],s,guidetrf,bdata);
GVec<int> trflong; // non-redundant long transfrags that I can use to guide the long read assemblies
//process transfrags to eliminate noise, and set compatibilities, and node memberships
process_transfrags(s,graphno[s][b],edgeno[s][b],no2gnode[s][b],transfrag[s][b],tr2no[s][b],gpos[s][b],guidetrf,pred,trflong);
//get_trf_long(graphno[s][b],edgeno[s][b], gpos[s][b],no2gnode[s][b],transfrag[s][b],geneno,s,pred,trflong);
/*
{ //DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"There are %d nodes for graph[%d][%d]:\n",graphno[s][b],s,b);
for(int i=0;i<graphno[s][b];i++) {
fprintf(stderr,"%d (%d-%d): %f len=%d cov=%f",i,no2gnode[s][b][i]->start,no2gnode[s][b][i]->end,no2gnode[s][b][i]->cov,no2gnode[s][b][i]->len(),no2gnode[s][b][i]->cov/no2gnode[s][b][i]->len());
fprintf(stderr," parents:");
for(int j=0;j<no2gnode[s][b][i]->parent.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->parent[j]);
fprintf(stderr," children:");
for(int j=0;j<no2gnode[s][b][i]->child.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->child[j]);
fprintf(stderr," trf=");
for(int j=0;j<no2gnode[s][b][i]->trf.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->trf[j]);
fprintf(stderr,"\n");
}
fprintf(stderr,"There are %d transfrags[%d][%d]:\n",transfrag[s][b].Count(),s,b);
for(int t=0;t<transfrag[s][b].Count();t++) {
fprintf(stderr,"%d: ",t);
//printBitVec(transfrag[s][b][t]->pattern);
fprintf(stderr," %f(%f) long=%d short=%d nodes=%d",transfrag[s][b][t]->abundance,transfrag[s][b][t]->srabund, transfrag[s][b][t]->longread,transfrag[s][b][t]->shortread,transfrag[s][b][t]->nodes.Count());
for(int i=0;i<transfrag[s][b][t]->nodes.Count();i++) fprintf(stderr," %d",transfrag[s][b][t]->nodes[i]);
if(!transfrag[s][b][t]->abundance) fprintf(stderr," *");
fprintf(stderr,"\n");
}
}
*/
/*
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(after process_transfrags):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
//fprintf(stderr,"guidetrf no=%d\n",guidetrf.Count());
//if(!longreads) {
// find transcripts now
if(!rawreads) geneno=find_transcripts(graphno[s][b],edgeno[s][b],gpos[s][b],no2gnode[s][b],transfrag[s][b],
geneno,s,guidetrf,guides,guidepred,bdata,trflong);
//}
for(int g=0;g<guidetrf.Count();g++) delete guidetrf[g].trf;
/*
{ //DEBUG ONLY
printTime(stderr);
fprintf(stderr,"Processed transcripts for s=%d b=%d\n",s,b);
}
*/
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(after processed transcripts):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
}
// clean up what can be cleaned
if(tr2no[s][b]) free_treepat(tr2no[s][b]);
}
// final clean up: no2gnode, no2tr, transfrag, bundle2graph
if(bundle2graph[s]) delete [] bundle2graph[s];
if(transfrag[s]) delete [] transfrag[s];
if(no2gnode[s]) delete [] no2gnode[s];
if(gpos[s]) delete [] gpos[s];
if(tr2no[s]) GFREE(tr2no[s]);
}
} // end if(startgroup[0]!=NULL || startgroup[2]!=NULL)
else {
delete [] readgroup;
// clean up readgroup, bundle
for(int sno=0;sno<3;sno++) {
int n=bnode[sno].Count();
for(int b=0;b<n;b++) delete bnode[sno][b];
bnode[sno].Clear();
}
}
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(e):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
/*
{ // DEBUG ONLY
for(int i=0;i<pred.Count();i++) {
if(pred[i]->t_eq) fprintf(stderr,"%s ",pred[i]->t_eq->getID());
fprintf(stderr,"pred[%d] (cov=%f,strand=%c):",i,pred[i]->cov,pred[i]->strand);
for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %d-%d",pred[i]->exons[j].start,pred[i]->exons[j].end);
fprintf(stderr,"\n");
}
}
*/
// don't forget to clean up the allocated data here
return(geneno);
}
CReadAln *guide_to_read(GffObj *t, int g, GList<CJunction>& junction, int refend) {
char s=0;
if(t->strand=='-') s=-1;
else if(t->strand=='+') s=1;
else s=0;
TAlnInfo *tif=new TAlnInfo();
tif->g=g;
CReadAln *r=new CReadAln(s,1,t->start,t->end,tif);
r->read_count=0;
// add junction from start here --> needs to be specially handled in build_merge
CJunction* njsource=add_junction(0, t->start, junction, r->strand);
if (njsource) {
r->juncs.Add(njsource);
njsource->guide_match=1;
}
for(int i=0;i<t->exons.Count();i++) {
r->segs.Add(t->exons[i]);
r->len+=t->exons[i]->len();
if(i) {
CJunction* nj=add_junction(t->exons[i-1]->end, t->exons[i]->start, junction, r->strand);
if (nj) {
r->juncs.Add(nj);
nj->guide_match=1;
}
}
}
// add junction to sink here as well
CJunction* njsink=add_junction(t->end, refend, junction, r->strand);
if (njsink) {
r->juncs.Add(njsink);
njsink->guide_match=1;
}
return(r);
}
int build_merge(BundleData* bdata) { // here a "read" is in fact a transcript
int refstart = bdata->start;
int refend = bdata->end+1;
GList<CReadAln>& readlist = bdata->readlist;
GList<CJunction>& junction = bdata->junction;
GPVec<GffObj>& guides = bdata->keepguides; // I need to insert the guides with the reads and process them separately
GList<CPrediction>& pred = bdata->pred;
// form groups on strands: all groups below are like this: 0 = negative strand; 1 = unknown strand; 2 = positive strand
GPVec<CGroup> group;
CGroup *currgroup[3]={NULL,NULL,NULL}; // current group of each type
CGroup *startgroup[3]={NULL,NULL,NULL}; // start group of each type
int color=0; // next color to assign
GVec<int> merge; // remembers merged groups
GVec<int> equalcolor; // remembers colors for the same bundle
if(guides.Count()) {
for(int i=0;i<guides.Count();i++) { // more guides left
CReadAln *rg=guide_to_read(guides[i],i,junction,refend);
readlist.Add(rg);
}
readlist.setSorted(true); // I need to do this before adding color otherwise I am loosing the color, readgroup ordering etc.
}
int nreads=readlist.Count(); // initial number of transcripts before I add the guides
GVec<int> *readgroup=new GVec<int>[nreads]; // remebers groups for each read; don't forget to delete it when no longer needed
for (int n=0;n<nreads;n++) if(readlist[n]->nh){
//fprintf(stderr,"Add read %d\n",n);
CReadAln & rd=*(readlist[n]);
/* // if I want to eliminate transcripts that have very bad junctions this is the code to do it
bool keep=true;
if(rd.tinfo->g==-1) { // if this is not a guide
int i=0;
while(i<rd.juncs.Count()) {
CJunction& jd=*(rd.juncs[i]);
if(!jd.strand || !good_merge_junc(jd,junction)) { // found a bad junction: no need of this or count_junctions procedure probably -> just colapse reads instead
keep=false;
rd.nh=0;
break;
}
i++;
}
}
if(keep) {*/
rd.pair_idx.Add(n);
if(rd.tinfo->g==-1) { // if not guide : only collapse non guides
// I need to adjust read abundance
if((bdata->covflags & IS_TPM_FLAG)!=0) rd.read_count=rd.tinfo->tpm;
else if((bdata->covflags & IS_FPKM_FLAG)!=0) rd.read_count=rd.tinfo->fpkm;
else if((bdata->covflags & IS_COV_FLAG)!=0) rd.read_count=rd.tinfo->cov;
//if(rd.juncs.Count()) { // why is this commented?
int m=n+1;
while(m<nreads && readlist[m]->start<=rd.segs[0].end) {
if(readlist[m]->nh && readlist[m]->tinfo->g==-1 && readlist[m]->juncs.Count()==rd.juncs.Count()) {
bool samejuncs=true;
for(int i=0;i<rd.juncs.Count();i++)
if(rd.juncs[i]!=readlist[m]->juncs[i]) {
samejuncs=false;
break;
}
if(samejuncs) {
rd.pair_idx.Add(m);
readlist[m]->nh=0;
if((bdata->covflags & IS_TPM_FLAG)!=0) readlist[m]->read_count=readlist[m]->tinfo->tpm;
else if((bdata->covflags & IS_FPKM_FLAG)!=0) readlist[m]->read_count=readlist[m]->tinfo->fpkm;
else if((bdata->covflags & IS_COV_FLAG)!=0) readlist[m]->read_count=readlist[m]->tinfo->cov;
rd.read_count=rd.read_count*rd.len+readlist[m]->read_count*readlist[m]->len;
if(readlist[m]->end>rd.end) {
rd.len+=readlist[m]->end-rd.end;
rd.end=readlist[m]->end;
rd.segs.Last().end=rd.end;
}
rd.read_count/=rd.len;
}
}
m++;
}
}
// I need to add the source to start, and end to sink junctions to read as well
char strand=-1;
if(rd.strand) strand=rd.strand;
CJunction* nj=add_junction(0, rd.start, junction, strand);
if (nj) rd.juncs.Insert(0,nj);
nj=NULL;
nj=add_junction(rd.end, refend, junction, strand);
if (nj) rd.juncs.Add(nj);
if(!rd.strand) { // add junction to the other strand as well
strand=1;
nj=add_junction(0, rd.start, junction, strand);
//if (nj) rd.juncs.Insert(0,nj); I don't do this anymore because I don't know the strand
nj=add_junction(rd.end, refend, junction, strand);
//if (nj) rd.juncs.Add(nj);
}
/*
if(!rd.read_count) {
rd.read_count=0.000001; // if fpkm is zero I don't want to ignore the transcript completely
GError("rd[%d].read_count=%f name=%s\n",n,rd.read_count,rd.tinfo->name.chars());
}
*/
color=add_read_to_group(n,readlist,color,group,currgroup,startgroup,readgroup,equalcolor,merge);
//} //end if(keep)
//else fprintf(stderr,"keep false for read %d\n",n);
}
// ### form bundles here
// first do color assignment
for (int i=0;i<3;i++) currgroup[i]=startgroup[i];
CGroup *prevgroup[3]={NULL,NULL,NULL};
GVec<int> eqposcol(true);
GVec<int> eqnegcol(true);
eqposcol.Resize(equalcolor.Count(),-1);
eqnegcol.Resize(equalcolor.Count(),-1);
// each unstranded group needs to remember what proportion of stranded group it overlaps so that it can distribute reads later on -> maybe I can do this in the following while?
while(currgroup[0]!=NULL || currgroup[1]!=NULL || currgroup[2]!=NULL) { // there are still groups to process
int nextgr=get_min_start(currgroup); // gets the index of currgroup with the left most begining
int grcol = currgroup[nextgr]->color; // set smallest color for currgroup[$nextgr]
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[nextgr]->color=grcol;
if(nextgr == 1) { // unknown strand group
//if(prevgroup[0]!=NULL && currgroup[nextgr]->start <= prevgroup[0]->end+bundledist) { // overlaps previous negative group
if(prevgroup[0]!=NULL && currgroup[nextgr]->start <= prevgroup[0]->end) { // overlaps previous negative group
set_strandcol(currgroup[nextgr],prevgroup[0],prevgroup[0]->color,eqnegcol,equalcolor);
uint maxstart = currgroup[nextgr]->start > prevgroup[0]->start ? currgroup[nextgr]->start : prevgroup[0]->start;
uint minend = currgroup[nextgr]->end < prevgroup[0]->end ? currgroup[nextgr]->end : prevgroup[0]->end;
currgroup[nextgr]->neg_prop+=prevgroup[0]->cov_sum*(minend-maxstart+1)/prevgroup[0]->len();
}
//while(currgroup[0]!=NULL && currgroup[nextgr]->start <= currgroup[0]->end+bundledist && currgroup[0]->start <= currgroup[nextgr]->end+bundledist) { // overlaps current negative strand group
while(currgroup[0]!=NULL && currgroup[nextgr]->start <= currgroup[0]->end && currgroup[0]->start <= currgroup[nextgr]->end) { // overlaps current negative strand group
int grcol = currgroup[0]->color; // set smallest color for currgroup[$nextgr]
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[0]->color=grcol;
currgroup[0]->neg_prop=1;
set_strandcol(currgroup[nextgr],currgroup[0],currgroup[0]->color,eqnegcol,equalcolor);
uint maxstart = currgroup[nextgr]->start > currgroup[0]->start ? currgroup[nextgr]->start : currgroup[0]->start;
uint minend = currgroup[nextgr]->end < currgroup[0]->end ? currgroup[nextgr]->end : currgroup[0]->end;
currgroup[nextgr]->neg_prop+=currgroup[0]->cov_sum*(minend-maxstart+1)/currgroup[0]->len();
prevgroup[0]=currgroup[0];
currgroup[0]=currgroup[0]->next_gr;
}
float pos_prop=0;
//if(prevgroup[2]!=NULL && currgroup[nextgr]->start <= prevgroup[2]->end + bundledist) { // overlaps positive strand group
if(prevgroup[2]!=NULL && currgroup[nextgr]->start <= prevgroup[2]->end) { // overlaps positive strand group
set_strandcol(currgroup[nextgr],prevgroup[2],prevgroup[2]->color,eqposcol,equalcolor);
if(currgroup[nextgr]->neg_prop) {
uint maxstart = currgroup[nextgr]->start > prevgroup[2]->start ? currgroup[nextgr]->start : prevgroup[2]->start;
uint minend = currgroup[nextgr]->end < prevgroup[2]->end ? currgroup[nextgr]->end : prevgroup[2]->end;
pos_prop+=prevgroup[2]->cov_sum*(minend-maxstart+1)/prevgroup[2]->len();
}
}
//while(currgroup[2]!=NULL && currgroup[nextgr]->start <= currgroup[2]->end + bundledist && currgroup[2]->start <= currgroup[nextgr]->end + bundledist) { // overlaps positive strand group
while(currgroup[2]!=NULL && currgroup[nextgr]->start <= currgroup[2]->end && currgroup[2]->start <= currgroup[nextgr]->end) { // overlaps positive strand group
int grcol = currgroup[2]->color; // set smallest color for currgroup[$nextgr]
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[2]->color=grcol;
set_strandcol(currgroup[nextgr],currgroup[2],currgroup[2]->color,eqposcol,equalcolor);
if(currgroup[nextgr]->neg_prop) {
uint maxstart = currgroup[nextgr]->start > currgroup[2]->start ? currgroup[nextgr]->start : currgroup[2]->start;
uint minend = currgroup[nextgr]->end < currgroup[2]->end ? currgroup[nextgr]->end : currgroup[2]->end;
pos_prop+=currgroup[2]->cov_sum*(minend-maxstart+1)/currgroup[2]->len();
}
prevgroup[2]=currgroup[2];
currgroup[2]=currgroup[2]->next_gr;
}
if(pos_prop) {
currgroup[nextgr]->neg_prop/=(currgroup[nextgr]->neg_prop+pos_prop);
}
else if(currgroup[nextgr]->neg_prop) currgroup[nextgr]->neg_prop=1;
//fprintf(stderr,"neg_prop=%g pos_prop=%g\n",currgroup[nextgr]->neg_prop,pos_prop);
}
else if(nextgr == 0) { // negative strand group
currgroup[nextgr]->neg_prop=1;
}
prevgroup[nextgr]=currgroup[nextgr];
currgroup[nextgr]=currgroup[nextgr]->next_gr;
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Colors assigned!\n");
for(int sno=0;sno<3;sno++) {
fprintf(stderr, "Colors of groups on strand %d:\n",sno);
CGroup *procgroup=startgroup[sno];
while(procgroup!=NULL) {
int grcol = procgroup->color;
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
int negcol=eqnegcol[grcol];
if(eqnegcol[grcol]!=-1){
while(equalcolor[negcol]!=negcol) {
negcol=equalcolor[negcol];
}
}
int poscol=eqposcol[grcol];
if(eqposcol[grcol]!=-1){
while(equalcolor[poscol]!=poscol) {
poscol=equalcolor[poscol];
}
}
fprintf(stderr, " gr %d(%d,%d,%d,%.6f): %d-%d\n",procgroup->grid,grcol,negcol,poscol,procgroup->cov_sum,procgroup->start,procgroup->end);
procgroup=procgroup->next_gr;
}
//fprintf(stderr,"\n");
}
exit(0);
}
*/
// create bundles : bundles collect connected groups (with same color)
for (int i=0;i<3;i++) {
currgroup[i]=startgroup[i];
prevgroup[i]=NULL;
}
GPVec<CBundle> bundle[3]; // all bundles on all strands: 0,1,2
GPVec<CBundlenode> bnode[3]; // last bnodes on all strands: 0,1,2 for each bundle : this might be the key for overalps
GVec<int> group2bundle[3]; // to retrace reads from group no to bundle
for(int sno=0;sno<3;sno++) {
group2bundle[sno].Resize(group.Count(),-1); // for a given group id we get a certain bnode id
bnode[sno].setFreeItem(false);
}
GVec<int> bundlecol(true); // associates a bundle number to a group color
bundlecol.Resize(equalcolor.Count(),-1);
while(currgroup[0]!=NULL || currgroup[1]!=NULL || currgroup[2]!=NULL) { // there are still groups to process
int nextgr=get_min_start(currgroup); // next group based on starting position
// get group color; I need to redo this to ensure I equalize all colors -> they could still be hanged by set_strandcol
int grcol = currgroup[nextgr]->color;
while(equalcolor[grcol]!=grcol) {
grcol=equalcolor[grcol];
}
currgroup[nextgr]->color=grcol;
if(nextgr == 0 || nextgr ==2 || (nextgr==1 &&(eqnegcol[grcol]==-1) && (eqposcol[grcol]==-1))) { // negative or positive strand bundle or unstranded bundle
int bno=bundlecol[grcol];
if(bno>-1) { // bundle for group has been created before
add_group_to_bundle(currgroup[nextgr],bundle[nextgr][bno],bnode[nextgr],0); // last parameter was bundledist before
}
else { // create new bundle
bno=create_bundle(bundle[nextgr],currgroup[nextgr],bnode[nextgr]);
bundlecol[grcol]=bno;
}
group2bundle[nextgr][currgroup[nextgr]->grid]=bundle[nextgr][bno]->lastnodeid;
}
else { // unknown strand : here is where I should compute positive and negative proportions
if(eqnegcol[grcol]!=-1){
int negcol=eqnegcol[grcol];
while(equalcolor[negcol]!=negcol) {
negcol=equalcolor[negcol];
}
int bno=bundlecol[negcol];
if(bno>-1) { // bundle for group has been created before
add_group_to_bundle(currgroup[nextgr],bundle[0][bno],bnode[0],0); // last parameter was bundledist before
}
else { // create new bundle
bno=create_bundle(bundle[0],currgroup[nextgr],bnode[0]);
bundlecol[negcol]=bno;
}
group2bundle[0][currgroup[nextgr]->grid]=bundle[0][bno]->lastnodeid;
} // if(eqnegcol[grcol]!=-1)
if(eqposcol[grcol]!=-1){
int poscol=eqposcol[grcol];
while(equalcolor[poscol]!=poscol) {
poscol=equalcolor[poscol];
}
int bno=bundlecol[poscol];
if(bno>-1) { // bundle for group has been created before
add_group_to_bundle(currgroup[nextgr],bundle[2][bno],bnode[2],0); // last parameter was bundledist before
}
else { // create new bundle
bno=create_bundle(bundle[2],currgroup[nextgr],bnode[2]);
bundlecol[poscol]=bno;
}
group2bundle[2][currgroup[nextgr]->grid]=bundle[2][bno]->lastnodeid;
}
}
currgroup[nextgr]=currgroup[nextgr]->next_gr;
} // while(currgroup[0]!=NULL || currgroup[1]!=NULL || currgroup[2]!=NULL)
// Clean up no longer needed variables
// group.Clear(); maybe I still need this?
equalcolor.Clear();
eqposcol.Clear();
eqnegcol.Clear();
bundlecol.Clear();
/*
{ // DEBUG ONLY
printTime(stderr);
fprintf(stderr, "There are %d unstranded bundles %d negative bundles and %d positive bundles\n",bundle[1].Count(),bundle[0].Count(),bundle[2].Count());
for(int sno=0;sno<3;sno++) {
fprintf(stderr, "Bundles on strand %d:\n",sno);
for(int b=0;b<bundle[sno].Count();b++) {
int elen=bnode[sno][bundle[sno][b]->lastnodeid]->end-bnode[sno][bundle[sno][b]->startnode]->start+1;
CBundlenode *currbnode=bnode[sno][bundle[sno][b]->startnode];
fprintf(stderr,"***Bundle %d with len=%d:",b,elen);
while(currbnode!=NULL) {
fprintf(stderr, " %d-%d cov=%.6f",currbnode->start,currbnode->end,currbnode->cov/(currbnode->end-currbnode->start+1));
currbnode=currbnode->nextnode;
}
currbnode=bnode[sno][bundle[sno][b]->lastnodeid];
fprintf(stderr," last node:%d-%d\n",currbnode->start,currbnode->end);
}
}
}
*/
int geneno=0;
// ### store transcripts in unstranded bundles here; I can not have guides in here because those are signed
for(int b=0;b<bundle[1].Count();b++) {
if(bundle[1][b]->cov) {
char sign='.';
// bundle shouldn't contain multiple transcripts since there is no pairing inside merging
CBundlenode *currbnode=bnode[1][bundle[1][b]->startnode];
int t=1;
while(currbnode!=NULL) {
if(t==1) { geneno++;}
//fprintf(stderr,"Store unstranded prediction: geneno=%d start=%d end=%d cov=%f\n",geneno,currbnode->start,currbnode->end,currbnode->cov);
int len=currbnode->end-currbnode->start+1;
CPrediction *p=new CPrediction(geneno-1, NULL, currbnode->start, currbnode->end, currbnode->cov/len, sign, len);
GSeg exon(currbnode->start,currbnode->end);
p->exons.Add(exon);
/* not clear how to store retrieve info without wasting memory and time
if(enableNames) {
p->mergename
}
*/
pred.Add(p);
t++;
currbnode=currbnode->nextnode;
}
}
}
//fprintf(stderr,"Done with unstranded bundles geneno=%d\n",geneno);
// ### build graphs for stranded bundles here
if(startgroup[0]!=NULL || startgroup[2]!=NULL) { //# there are stranded groups to process
// sort junctions -> junctions are sorted already according with their start, but not their end
GList<CJunction> ejunction(junction);
ejunction.setFreeItem(false);
if(ejunction.Count()) ejunction.setSorted(juncCmpEnd);
GVec<CGraphinfo> *bundle2graph[2]; // should I keep the neutral strand for consistency ? -> remember not to delete it
GVec<int> graphno[2]; // how many nodes are in a certain graph g, on strand s: graphno[s][g]
GVec<int> edgeno[2]; // how many edges are in a certain graph g, on strand s: edgeno[s][g]
GPVec<CTransfrag> *transfrag[2]; // for each transfrag t on a strand s, in a graph g, transfrag[s][g][t] gives it's abundance and it's pattern
GPVec<CMTransfrag> *mgt[2]; // merged super-transfrags
GPVec<CGraphnode> *no2gnode[2]; // for each graph g, on a strand s, no2gnode[s][g][i] gives the node i
CTreePat **tr2no[2]; // for each graph g, on a strand s, tr2no[s][g] keeps the tree pattern structure for quick retrieval of the index t of a tansfrag
GIntHash<int> *gpos[2]; // for each graph g, on a strand s, gpos[s][g] keeps the hash between edges and positions in the bitvec associated to a pattern
GVec<int> lastgpos[2];
int bno[2]={0,0};
// build graph structure
for(int sno=0;sno<3;sno+=2) { // skip neutral bundles -> those shouldn't have junctions
int s=sno/2; // adjusted strand due to ignoring neutral strand
//char strnd='-';
//if(s) strnd='+';
bundle2graph[s]=NULL;
if(bnode[sno].Count()) bundle2graph[s]=new GVec<CGraphinfo>[bnode[sno].Count()];
transfrag[s]=NULL;
mgt[s]=NULL;
no2gnode[s]=NULL;
tr2no[s]=NULL;
gpos[s]=NULL;
if(bundle[sno].Count()) {
transfrag[s]=new GPVec<CTransfrag>[bundle[sno].Count()]; // for each bundle I have a graph ? only if I don't ignore the short bundles
mgt[s]=new GPVec<CMTransfrag>[bundle[sno].Count()];
no2gnode[s]=new GPVec<CGraphnode>[bundle[sno].Count()];
gpos[s]=new GIntHash<int>[bundle[sno].Count()];
GCALLOC(tr2no[s],bundle[sno].Count()*sizeof(CTreePat *));
bno[s]=bundle[sno].Count();
for(int b=0;b<bundle[sno].Count();b++) {
graphno[s].cAdd(0);
edgeno[s].cAdd(0);
lastgpos[s].cAdd(0);
/*
{ // DEBUG ONLY
if(bundle[sno][b]->nread) {
fprintf(stderr,"proc bundle[%d][%d] %f/%f is %f len=%d\n",sno,b,bundle[sno][b]->multi,bundle[sno][b]->nread,(float)bundle[sno][b]->multi/bundle[sno][b]->nread,bundle[sno][b]->len);
} }
*/
// create graph
GArray<GEdge> unused;
graphno[s][b]=create_graph(refstart,s,b,bundle[sno][b],bnode[sno],junction,ejunction,
bundle2graph,no2gnode,transfrag,gpos,NULL,edgeno[s][b],lastgpos[s][b],unused,refend);
if(graphno[s][b]) tr2no[s][b]=construct_treepat(graphno[s][b],gpos[s][b],transfrag[s][b]);
else tr2no[s][b]=NULL;
for(int i=0; i<transfrag[s][b].Count();i++) {
CMTransfrag *tr=new CMTransfrag(transfrag[s][b][i]); // transfrags that are created in the graph process can not be associated with any read
mgt[s][b].Add(tr);
}
}
}
}
//fprintf(stderr,"Done creating graphs\n");
/*
{ // DEBUG ONLY
printTime(stderr);
for(int s=0;s<2;s++) {
fprintf(stderr, "There are %d stranded[%d] graphs\n",bno[s],int(2*s));
for(int b=0;b<bno[s];b++) {
if(graphno[s][b]) {
GStr pat;
fprintf(stderr,"Graph[%d][%d] with %d nodes and %d edges with lastgpos=%d:",int(2*s),b,graphno[s][b],edgeno[s][b],lastgpos[s][b]);
for(int nd=1;nd<graphno[s][b]-1;nd++)
fprintf(stderr," %d(%d-%d)",nd,no2gnode[s][b][nd]->start,no2gnode[s][b][nd]->end);
fprintf(stderr,"\n");
//print_pattern(tr2no[s][b],pat,graphno[s][b]);
}
}
}
}
*/
// I can clean up some data here:
for(int sno=0;sno<3;sno++) {
int n=bnode[sno].Count();
for(int b=0;b<n;b++) delete bnode[sno][b];
bnode[sno].Clear();
bundle[sno].Clear();
}
for (int n=0;n<readlist.Count();n++) { // check if read is active: nh>0
/*
{ // DEBUG ONLY
fprintf(stderr,"Read[%d]:",n);
for(int i=0;i<readlist[n]->segs.Count();i++) {
fprintf(stderr," %d-%d",readlist[n]->segs[i].start,readlist[n]->segs[i].end);
}
fprintf(stderr," gets tr: ");
}
*/
if(readlist[n]->nh) get_read_to_transfrag(readlist,n,readgroup,merge,group2bundle,bundle2graph,graphno,edgeno,gpos,no2gnode,transfrag,mgt,tr2no,group);
/*
{ // DEBUG ONLY
fprintf(stderr,"\n");
}
*/
}
// don't forget to clean up the allocated data here
delete [] readgroup;
group.Clear();
// parse graph
for(int s=0;s<2;s++) {
for(int b=0;b<bno[s];b++) {
if(graphno[s][b]) {
//process transfrags to eliminate noise, and set compatibilities, and node memberships
/*
GBitVec compatible((1+transfrag[s][b].Count())*transfrag[s][b].Count()/2); // I might want to change this to gbitvec
process_merge_transfrags(graphno[s][b],no2gnode[s][b],mgt[s][b],compatible,gpos[s][b]);
geneno=merge_transcripts(graphno[s][b],no2gnode[s][b],mgt[s][b],
geneno,s,pred,readlist,guides);
*/
/*
{ //DEBUG ONLY
//printTime(stderr);
fprintf(stderr,"There are %d nodes for graph[%d][%d]:\n",graphno[s][b],s,b);
for(int i=0;i<graphno[s][b];i++) {
fprintf(stderr,"%d (%d-%d): %f len=%d cov=%f",i,no2gnode[s][b][i]->start,no2gnode[s][b][i]->end,no2gnode[s][b][i]->cov,no2gnode[s][b][i]->len(),no2gnode[s][b][i]->cov/no2gnode[s][b][i]->len());
fprintf(stderr," parents:");
for(int j=0;j<no2gnode[s][b][i]->parent.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->parent[j]);
fprintf(stderr," trf=");
for(int j=0;j<no2gnode[s][b][i]->trf.Count();j++) fprintf(stderr," %d",no2gnode[s][b][i]->trf[j]);
fprintf(stderr,"\n");
}
mgt[s][b].Sort(mgtrabundCmp); // sort transfrags from the most abundant to the least, with guides coming in first
fprintf(stderr,"There are %d transfrags[%d][%d]:\n",mgt[s][b].Count(),s,b);
for(int t=0;t<mgt[s][b].Count();t++) {
fprintf(stderr,"%d (%d-%d): ",t,no2gnode[s][b][mgt[s][b][t]->transfrag->nodes[0]]->start,no2gnode[s][b][mgt[s][b][t]->transfrag->nodes.Last()]->end);
//printBitVec(transfrag[s][b][t]->pattern);
fprintf(stderr," %f:",mgt[s][b][t]->transfrag->abundance);
for(int i=0;i<mgt[s][b][t]->transfrag->nodes.Count();i++) fprintf(stderr," %d",mgt[s][b][t]->transfrag->nodes[i]);
fprintf(stderr,"\n");
}
}
*/
/*
// reads already have length computed so I could already get from the get_read_to_transfrag instead
// for each mtransfrag compute its length
for(int t=0;t<mgt[s][b].Count();t++) {
for(int i=0;i<mgt[s][b][t]->transfrag->nodes.Count();i++) {
CGraphnode *inode=no2gnode[s][b][mgt[s][b][t]->transfrag->nodes[i]];
mgt[s][b][t]->len+=inode->end-inode->start+1;
}
}
*/
geneno=merge_transfrags(graphno[s][b],no2gnode[s][b], mgt[s][b],gpos[s][b],geneno,s,pred,readlist,guides);
//geneno=merge_transfrags_EM(graphno[s][b],no2gnode[s][b], mgt[s][b],gpos[s][b],geneno,s,pred,readlist,guides);
}
// clean up what can be cleaned
if(tr2no[s][b]) free_treepat(tr2no[s][b]);
}
// final clean up: no2gnode, no2tr, transfrag, bundle2graph
if(bundle2graph[s]) delete [] bundle2graph[s];
if(transfrag[s]) delete [] transfrag[s];
if(mgt[s]) delete [] mgt[s];
if(no2gnode[s]) delete [] no2gnode[s];
if(gpos[s]) delete [] gpos[s];
if(tr2no[s]) GFREE(tr2no[s]);
}
} // end if(startgroup[0]!=NULL || startgroup[2]!=NULL)
else {
delete [] readgroup;
// clean up readgroup, bundle
for(int sno=0;sno<3;sno++) {
int n=bnode[sno].Count();
for(int b=0;b<n;b++) delete bnode[sno][b];
bnode[sno].Clear();
}
}
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(e):build_graphs memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
// don't forget to clean up the allocated data here
return(geneno);
}
// compute coverages and junction support here
void count_good_junctions(BundleData* bdata) {
GList<CReadAln>& readlist = bdata->readlist;
GList<CJunction>& junction = bdata->junction;
GVec<float>* bpcov = bdata->bpcov;
int refstart=bdata->start;
int refend=bdata->end;
bool modified=false;
//GHash<CJunction*> jhash(false);
GHashMap<CJunction*, CJunction*> jhash(false); //hash of pointers
//char sbuf[20];
if((longreads||mixedMode) && bdata->keepguides.Count()) { // there are guides to consider with longreads -> I might need to adjust the splice sites
GPVec<GffObj>& guides = bdata->keepguides;
GList<CJunction> gjunc(true, true, true);
for(int g=0;g<guides.Count();g++) {
char s=0; // unknown strand
if(guides[g]->strand=='+') s=1; // guide on positive strand
else if(guides[g]->strand=='-') s=-1; // guide on negative strand
for(int i=1;i<guides[g]->exons.Count();i++) { //add_junction((int)guides[g]->exons[i-1]->end,(int)guides[g]->exons[i]->start,gjunc,s);
int gidx=gjunc.AddedIfNew(new CJunction(guides[g]->exons[i-1]->end,guides[g]->exons[i]->start,s));
if(gidx>-1) { // item is new
gjunc[gidx]->guide_match=1;
if(mixedMode) { // this should favor junctions already covered by short reads
CJunction jn(guides[g]->exons[i-1]->end,guides[g]->exons[i]->start,s);
int oidx=-1;
if (!junction.Found(&jn, oidx) || junction[oidx]->nm>=junction[oidx]->nreads) {
gjunc[gidx]->guide_match=0;
break;
}
}
}
//fprintf(stderr,"Add guide junction=%d-%d:%d from reference %s\n",guides[g]->exons[i-1]->end,guides[g]->exons[i]->start,s,guides[g]->getID());
}
}
if(gjunc.Count()) {
//for(int i=0;i<gjunc.Count();i++) fprintf(stderr,"Guide junction=%d-%d:%d\n",gjunc[i]->start,gjunc[i]->end,gjunc[i]->strand);
//int ssdist=1/ERROR_PERC;
//int ssdist=longintronanchor;
GVec<int> smodjunc; // keeps a list of all modified start junctions' indices (might keep the same junction twice)
GVec<int> emodjunc; // keeps a list of all modified end junctions' indices (might keep the same junction twice)
GList<CJunction> ejunction(junction);
ejunction.setFreeItem(false);
if(ejunction.Count()) ejunction.setSorted(juncCmpEnd);
GList<CJunction> egjunc(gjunc);
egjunc.setFreeItem(false);
egjunc.setSorted(juncCmpEnd);
int s=0;
int e=0;
for(int i=1;i<junction.Count();i++) {
if(junction[i]->nm>=junction[i]->nreads){ // for all junctions -> try to see if I can correct them
//fprintf(stderr,"check junction[%d]:%d-%d:%d rightsupport=%f nm=%f nreads=%f\n",i,junction[i]->start,junction[i]->end,junction[i]->strand,junction[i]->rightsupport,junction[i]->nm,junction[i]->nreads);
// check start junction
while(s<gjunc.Count() && gjunc[s]->start+sserror<junction[i]->start) s++;
int k=s;
int c=-1;
int dist=1+sserror;
while(k<gjunc.Count() && gjunc[k]->start<=junction[i]->start+sserror) {
if(!junction[i]->strand || gjunc[k]->strand==junction[i]->strand) {
if(gjunc[k]->start==junction[i]->start && gjunc[k]->guide_match) { // perfect match --> no need to change anything
c=-1;
break;
}
int d=dist;
if(c<0 || gjunc[c]->guide_match==gjunc[k]->guide_match) d=abs((int)gjunc[k]->start-(int)junction[i]->start);
if(d<dist || (!gjunc[c]->guide_match && gjunc[k]->guide_match)) {
dist=d;
c=k;
smodjunc.Add(i);
}
}
k++;
}
if(c>=0) {
//fprintf(stderr,"...correct start of junction[%d] to %d\n",i,gjunc[c]->start);
junction[i]->start=gjunc[c]->start;
junction[i]->strand=gjunc[c]->strand;
while(c<gjunc.Count() && gjunc[c]->start==junction[i]->start) {
if(junction[i]->end==gjunc[c]->end && junction[i]->strand==gjunc[c]->strand) {
junction[i]->guide_match=true;
break;
}
c++;
}
}
}
if(ejunction[i]->nm>=ejunction[i]->nreads){ // for all junctions -> try to see if I can correct them
//fprintf(stderr,"check ejunction[%d]:%d-%d:%d rightsupport=%f nm=%f nreads=%f\n",i,ejunction[i]->start,ejunction[i]->end,ejunction[i]->strand,ejunction[i]->rightsupport,ejunction[i]->nm,ejunction[i]->nreads);
// check end junction
while(e<egjunc.Count() && egjunc[e]->end+sserror<ejunction[i]->end) e++;
int k=e;
int c=-1;
int dist=1+sserror;
while(k<egjunc.Count() && egjunc[k]->end<=ejunction[i]->end+sserror) {
if(!ejunction[i]->strand || egjunc[k]->strand==ejunction[i]->strand) {
if(egjunc[k]->end==ejunction[i]->end && egjunc[k]->guide_match) { // perfect match --> no need to change anything
c=-1;
break;
}
int d=dist;
if(c<0 || egjunc[c]->guide_match==egjunc[k]->guide_match) d=abs((int)egjunc[k]->end-(int)ejunction[i]->end);
if(d<dist || (!egjunc[c]->guide_match && egjunc[k]->guide_match)) {
dist=d;
c=k;
emodjunc.Add(i);
}
}
k++;
}
if(c>=0) {
//fprintf(stderr,"...correct end of ejunction[%d] to %d\n",i,egjunc[c]->end);
ejunction[i]->end=egjunc[c]->end;
ejunction[i]->strand=egjunc[c]->strand;
while(c<egjunc.Count() && egjunc[c]->end==ejunction[i]->end) {
if(ejunction[i]->start==egjunc[c]->start && ejunction[i]->strand==egjunc[c]->strand) {
ejunction[i]->guide_match=true; break;
}
c++;
}
}
if(s==gjunc.Count() && e==egjunc.Count()) break;
}
}
if(smodjunc.Count()||emodjunc.Count()) {
modified=true;
for(int i=0;i<smodjunc.Count();i++) {
int j=smodjunc[i]; // junction that I modified --> try to see if there are other equal junctions
//sprintf(sbuf, "%p", junction[j]);
const CJunction* jp=jhash[junction[j]];
if(!jp) { // did not process junction before
//fprintf(stderr,"smodified junction[%d]:%d-%d:%d %p nreads=%f\n",j,junction[j]->start,junction[j]->end,junction[j]->strand,junction[j],junction[j]->nreads);
s=j-1;
GVec<int> equal;
while(s>=0 && junction[s]->start==junction[j]->start) {
if(junction[s]->end==junction[j]->end && junction[s]->strand==junction[j]->strand) equal.Add(s);
s--;
}
s=j+1;
while(s<junction.Count() && junction[s]->start==junction[j]->start) {
if(junction[s]->end==junction[j]->end && junction[s]->strand==junction[j]->strand) equal.Add(s);
s++;
}
if(equal.Count()) { // junction j is equal to other junctions
for(s=0;s<equal.Count();s++) {
//sprintf(sbuf, "%p", junction[equal[s]]);
//jhash.Add(sbuf,junction[j]);
CJunction* jct=junction[equal[s]];
//fprintf(stderr,"...equal to junction[%d]:%d-%d:%d %p nreads=%f\n",equal[s],jct->start,jct->end,jct->strand,jct,jct->nreads);
jhash.Add(jct, junction[j]);
if(mixedMode) { // I can trust the reads coming from mixed data but not so much from long reads
junction[j]->nreads+=jct->nreads;
junction[j]->nm+=jct->nm;
jct->nreads=0;
}
jct->strand=0;
jct->guide_match=false;
}
}
}
}
for(int i=0;i<emodjunc.Count();i++) {
int j=emodjunc[i];
//sprintf(sbuf, "%p", ejunction[j]);
CJunction* jp=jhash[ejunction[j]];
if(!jp) { // did not process junction before
//fprintf(stderr,"emodified ejunction[%d]:%d-%d:%d %p nreads=%f\n",j,ejunction[j]->start,ejunction[j]->end,ejunction[j]->strand,ejunction[j],ejunction[j]->nreads);
s=j-1;
GVec<int> equal;
while(s>=0 && ejunction[s]->end==ejunction[j]->end) {
if(ejunction[s]->start==ejunction[j]->start && ejunction[s]->strand==ejunction[j]->strand) equal.Add(s);
s--;
}
s=j+1;
while(s<ejunction.Count() && ejunction[s]->end==ejunction[j]->end) {
if(ejunction[s]->start==ejunction[j]->start && ejunction[s]->strand==ejunction[j]->strand) equal.Add(s);
s++;
}
if(equal.Count()) { // junction j is equal to other junctions
for(s=0;s<equal.Count();s++) {
//sprintf(sbuf, "%p", ejunction[equal[s]]);
//jhash.Add(sbuf,ejunction[j]);
//ejunction[equal[s]]->strand=0;
//ejunction[equal[s]]->guide_match=false;
CJunction* ej=ejunction[equal[s]];
jhash.Add(ej, ejunction[j]);
//fprintf(stderr,"...equal to ejunction[%d]:%d-%d:%d %p nreads=%f\n",equal[s],ej->start,ej->end,ej->strand,ej,ej->nreads);
if(mixedMode) { // I can trust the reads coming from mixed data but not so much from long reads
ejunction[j]->nreads+=ej->nreads;
ejunction[j]->nm+=ej->nm;
ej->nreads=0;
}
ej->strand=0;
ej->guide_match=false;
}
}
}
}
}
junction.Sort();
}
gjunc.Clear();
}
for(int s=0;s<3;s++) bpcov[s].Resize(refend-refstart+3);
GVec<int> unstranded; // remembers unstranded reads
for(int n=0;n<readlist.Count();n++) {
CReadAln & rd=*(readlist[n]);
float rdcount=rd.read_count;
int nex=rd.segs.Count();
if(!rd.unitig) add_read_to_cov(readlist,n,bpcov,refstart);
else if(rdcount>1) rdcount=1;
GVec<uint> leftsup;
GVec<uint> rightsup;
uint maxleftsupport=0;
uint maxrightsupport=0;
//int sno=(int)rd.strand+1; // 0(-),1(.),2(+)
//if(nex>1) fprintf(stderr,"Process spliced read[%d] with cov=%f and sno=%d: ",n,rdcount,sno);
for(int i=0;i<nex;i++) {
//if(nex>1) fprintf(stderr," %d-%d",rd.segs[i].start,rd.segs[i].end);
if(i) {
//fprintf(stderr,":%d",rd.juncs[i-1]->strand);
if(modified) { // see if read uses modified junction -> correct it
//sprintf(sbuf, "%p", rd.juncs[i-1]);
CJunction* jp=jhash[rd.juncs[i-1]];
if(jp) {
if(rd.segs[i-1].start>jp->start || rd.segs[i].end<jp->end) {
if(rd.segs[i-1].start<=jp->start) rd.segs[i-1].end=jp->start;
if(rd.segs[i].end>=jp->end) rd.segs[i].start=jp->end;
rd.juncs[i-1]->nreads-=rd.read_count;
//if(rd.juncs[i-1]->nreads<ERROR_PERC) rd.juncs[i-1]->strand=0; // this approach removes a perfectly valid (guide) junction which might not be the desired effect
rd.juncs[i-1]=junction[0];
}
else {
rd.juncs[i-1]=jp;
if(!rd.strand) rd.strand=jp->strand;
//fprintf(stderr," [correct rd from %d-%d to %d-%d]",rd.segs[i-1].end,rd.segs[i].start,jp->start,jp->end);
if(rd.segs[i-1].start<=jp->start) rd.segs[i-1].end=jp->start;
if(rd.segs[i].end>=jp->end) rd.segs[i].start=jp->end;
}
}
else {
if(rd.segs[i-1].start>rd.juncs[i-1]->start || rd.segs[i].end<rd.juncs[i-1]->end) {
if(rd.segs[i-1].end!=rd.juncs[i-1]->start && rd.segs[i-1].start<=rd.juncs[i-1]->start) rd.segs[i-1].end=rd.juncs[i-1]->start;
if(rd.segs[i].start!=rd.juncs[i-1]->end && rd.segs[i].end>=rd.juncs[i-1]->end) rd.segs[i].start=rd.juncs[i-1]->end;
rd.juncs[i-1]->nreads-=rd.read_count;
//if(rd.juncs[i-1]->nreads<ERROR_PERC) rd.juncs[i-1]->strand=0; // this approach removes a perfectly valid (guide) junction which might not be the desired effect
rd.juncs[i-1]=junction[0];
}
else {
//if(rd.segs[i-1].end!=rd.juncs[i-1]->start || rd.segs[i].start!=rd.juncs[i-1]->end) fprintf(stderr," [chg rd from %d-%d to %d-%d]",rd.segs[i-1].end,rd.segs[i].start,rd.juncs[i-1]->start,rd.juncs[i-1]->end);
if(rd.segs[i-1].end!=rd.juncs[i-1]->start && rd.segs[i-1].start<=rd.juncs[i-1]->start) rd.segs[i-1].end=rd.juncs[i-1]->start;
if(rd.segs[i].start!=rd.juncs[i-1]->end && rd.segs[i].end>=rd.juncs[i-1]->end) rd.segs[i].start=rd.juncs[i-1]->end;
}
}
}
/* DEL AWARE*/
else if(!rd.juncs[i-1]->strand && (longreads || mixedMode) && (rd.segs[i-1].end!=rd.juncs[i-1]->start || rd.segs[i].start!=rd.juncs[i-1]->end)){ // see if I need to adjust read start/ends due to junction having deletions around it
CJunction *nj=NULL;
CJunction jn(rd.juncs[i-1]->start, rd.juncs[i-1]->end, rd.strand); // if the deletion makes sense then keep it
int oidx=-1;
if (junction.Found(&jn, oidx)) {
nj=junction.Get(oidx);
nj->nreads+=rd.juncs[i-1]->nreads;
nj->mm+=rd.juncs[i-1]->mm;
nj->nm+=rd.juncs[i-1]->nm;
rd.juncs[i-1]=nj;
// adjust start/end of read
rd.segs[i-1].end=rd.juncs[i-1]->start;
rd.segs[i].start=rd.juncs[i-1]->end;
}
else { // restore the correct junction
CJunction jn(rd.segs[i-1].end, rd.segs[i].start, rd.strand);
if (junction.Found(&jn, oidx)) {
nj=junction.Get(oidx);
nj->nreads+=rd.juncs[i-1]->nreads;
nj->mm+=rd.juncs[i-1]->mm;
nj->nm+=rd.juncs[i-1]->nm;
rd.juncs[i-1]=nj;
}
else { // new junction
rd.juncs[i-1]->strand=rd.strand;
rd.juncs[i-1]->start=rd.segs[i-1].end;
rd.juncs[i-1]->end=rd.segs[i].start;
}
}
}
if(rd.segs[i-1].len()>maxleftsupport) maxleftsupport=rd.segs[i-1].len();
if(rd.segs[nex-i].len()>maxrightsupport) maxrightsupport=rd.segs[nex-i].len();
leftsup.Add(maxleftsupport);
rightsup.Add(maxrightsupport);
//rd.juncs[i-1]->nreads+=rd.read_count;
//if(rd.unitig) rd.juncs[i-1]->guide_match=true; // v7 this might be a little too much!
}
//if(!rd.unitig) cov_edge_add(bpcov,sno,rd.segs[i].start-refstart,rd.segs[i].end+1-refstart,rd.read_count);
}
//if(nex>1) fprintf(stderr," With anchors: ");
for(int i=1;i<nex;i++) {
//if(!rd.juncs[i-1]->strand) { rd.juncs[i-1]->strand = rd.strand; }
uint anchor=junctionsupport;
//if(rd.juncs[i-1]->len()>longintron || rd.juncs[i-1]->nreads-rd.juncs[i-1]->mm<junctionthr || rd.juncs[i-1]->nreads-rd.juncs[i-1]->nm<junctionthr) {
if(rd.juncs[i-1]->len()>longintron || (!longreads && rd.juncs[i-1]->nreads-rd.juncs[i-1]->nm<junctionthr && !rd.juncs[i-1]->mm)) {
//if(rd.juncs[i-1]->len()>verylongintron) { if(anchor<verylongintronanchor) anchor=verylongintronanchor; } // I want to use a longer anchor for long introns to believe them
//else
if(anchor<longintronanchor) anchor=longintronanchor;
}
//if(rd.unitig) anchor=1; // v7 also **** if not trimming involved in super-read creation then comment this; unitigs should be trimmed so I will accept them as anchors
//if(leftsup[i-1]>=anchor && rightsup[nex-i-1]>=anchor) rd.juncs[i-1]->nreads_good+=rd.read_count;
if(leftsup[i-1]>=anchor) { // support only comes from spliced reads that are bigger than the anchor
rd.juncs[i-1]->leftsupport+=rdcount;
if(rightsup[nex-i-1]>=anchor) {
rd.juncs[i-1]->rightsupport+=rdcount;
rd.juncs[i-1]->nreads_good+=rdcount;
//rd.juncs[i-1]->nreads_good+=rd.read_count*rd.nh; // try to see if this helps
//if(leftsup[i-1]>=anchor+1/ERROR_PERC && rightsup[nex-i-1]>=anchor+1/ERROR_PERC) rd.juncs[i-1]->strong=true;
}
}
else if(rightsup[nex-i-1]>=anchor) {
rd.juncs[i-1]->rightsupport+=rdcount;
}
//fprintf(stderr," %d(%d-%d)[%f-%f][%d][%f][%f]",anchor,leftsup[i-1],rightsup[nex-i-1],rd.juncs[i-1]->leftsupport,rd.juncs[i-1]->rightsupport,rd.juncs[i-1]->strand,rd.juncs[i-1]->nm,rd.juncs[i-1]->nreads);
}
if((mixedMode || longreads) && !rd.strand && nex>1) unstranded.Add(n);
//if(nex>1) fprintf(stderr,"\n");
}
//fprintf(stderr,"Compute coverages:\n");
// this code enssures that I can find interval coverages very fast
int m=int((bpcov[1].Count()-1)/BSIZE);
//fprintf(stderr,"m=%d refstart=%d refend=%d bpcount=%d\n",m,refstart,refend,bpcov[1].Count());
int k=0;
float prev_val[3]={0,0,0};
float prev_sum[3]={0,0,0};
while(k<m) {
int end=(k+1)*BSIZE;
//fprintf(stderr,"end=%d\n",end);
for(int i=k*BSIZE;i<end;i++) {
for(int s=0;s<3;s++) {
//fprintf(stderr,"(1)bpcov[%d][%d]=%f ",s,i,bpcov[s][i]);
bpcov[s][i]+=prev_val[s];
if(bpcov[s][i]<0) bpcov[s][i]=0;
prev_val[s]=bpcov[s][i];
//fprintf(stderr,"(2)bpcov[%d][%d]=%f ",s,i,bpcov[s][i]);
bpcov[s][i]+=prev_sum[s];
prev_sum[s]=bpcov[s][i];
//fprintf(stderr,"(2)bpcov[%d][%d]=%f ",s,i,bpcov[s][i]);
//fprintf(stderr,"bpPos[%d][%d]: prev_val=%f prev_sum=%f\n",s,i,prev_val[s],prev_sum[s]);
}
}
for(int s=0;s<3;s++) prev_sum[s]=0;
k++;
}
for(int i=k*BSIZE;i<bpcov[1].Count();i++)
for(int s=0;s<3;s++) {
bpcov[s][i]+=prev_val[s];
if(bpcov[s][i]<0) bpcov[s][i]=0;
prev_val[s]=bpcov[s][i];
bpcov[s][i]+=prev_sum[s];
prev_sum[s]=bpcov[s][i];
//fprintf(stderr,"bpPos[%d][%d]: cov=%f sumbpcov=%f\n",s,i,prev_val[s],prev_sum[s]);
}
if(longreads || mixedMode) {
for(int n=0;n<unstranded.Count();n++) {
CReadAln & rd=*(readlist[unstranded[n]]);
if(rd.start>=(uint)refstart && (int)(rd.end-(uint)refstart)<bpcov[1].Count()) {
int nex=rd.segs.Count();
float pos=0;
float neg=0;
if(longreads) {
pos=get_cov(2,rd.segs[0].start-refstart,rd.segs[0].end-refstart,bpcov);
neg=get_cov(0,rd.segs[0].start-refstart,rd.segs[0].end-refstart,bpcov);
}
bool posjunc=false;
bool negjunc=false;
for(int i=1;i<nex;i++) { // some junctions don't get an assigned strand by buggy aligners
if(longreads) {
pos+=get_cov(2,rd.segs[i].start-refstart,rd.segs[i].end-refstart,bpcov);
neg+=get_cov(0,rd.segs[i].start-refstart,rd.segs[i].end-refstart,bpcov);
}
if(rd.juncs[i-1]->strand>0) posjunc=true;
else if(rd.juncs[i-1]->strand<0) negjunc=true;
else {
int oidx=-1;
CJunction jn(rd.juncs[i-1]->start, rd.juncs[i-1]->end, 1);
if (junction.Found(&jn, oidx)) {
posjunc=true;
}
jn.strand=-1;
if (junction.Found(&jn, oidx)) {
negjunc=true;
}
}
}
if(posjunc && !negjunc) {
rd.strand=1;
}
else if(negjunc && !posjunc) {
rd.strand=-1;
}
else {
if(neg<1) neg=0;
if(pos<1) pos=0;
if(neg>pos) {rd.strand=-1;}
else if(pos>neg) { rd.strand=1;}
}
//fprintf(stderr,"read strand is:%d for pos=%f neg=%f\n",rd.strand,pos,neg);
if(rd.strand) {
for(int i=1;i<nex;i++)
if(!rd.juncs[i-1]->strand) {
// first check to see if the junction already exists
int oidx=-1;
CJunction *nj=NULL;
CJunction jn(rd.juncs[i-1]->start, rd.juncs[i-1]->end, rd.strand);
if (junction.Found(&jn, oidx)) {
nj=junction.Get(oidx);
//fprintf(stderr,"found strand junction at %p",nj);
nj->nreads+=rd.juncs[i-1]->nreads;
nj->nreads_good+=rd.juncs[i-1]->nreads_good;
nj->nm+=rd.juncs[i-1]->nm;
nj->mm+=rd.juncs[i-1]->mm;
nj->leftsupport+=rd.juncs[i-1]->leftsupport;
nj->rightsupport+=rd.juncs[i-1]->rightsupport;
rd.juncs[i-1]=nj;
}
else rd.juncs[i-1]->strand = rd.strand;
}
}
}
}
}
}
void count_merge_junctions(GList<CReadAln>& readlist,char covflags) { // why do I need to impose any thresholds here??
for(int n=0;n<readlist.Count();n++) {
CReadAln & rd=*(readlist[n]);
int nex=rd.segs.Count();
for(int i=0;i<nex;i++) {
if(i) {
rd.juncs[i-1]->nreads+=rd.read_count;
if((covflags & IS_TPM_FLAG)!=0) rd.juncs[i-1]->nreads_good+=rd.tinfo->tpm;
else if((covflags & IS_FPKM_FLAG)!=0) rd.juncs[i-1]->nreads_good+=rd.tinfo->fpkm;
else if((covflags & IS_COV_FLAG)!=0) rd.juncs[i-1]->nreads_good+=rd.tinfo->cov;
else rd.juncs[i-1]->nreads_good+=rd.read_count;
}
}
}
}
//int infer_transcripts(int refstart, GList<CReadAln>& readlist,
//GList<CJunction>& junction, GPVec<GffObj>& guides, GVec<float>& bpcov, GList<CPrediction>& pred, bool fast) {
int infer_transcripts(BundleData* bundle) {
int geneno=0;
//DEBUG ONLY: showReads(refname, readlist);
/*
#ifdef GMEMTRACE
double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(s):infer_transcripts memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
if(mergeMode) {
//count_merge_junctions(bundle->readlist,bundle->covflags); // this make sense only if I want to count junctions
geneno = build_merge(bundle);
}
else if(bundle->keepguides.Count() || !eonly) {
//fprintf(stderr,"Process %d reads from %lu.\n",bundle->readlist.Count(),bundle->numreads);
count_good_junctions(bundle);
geneno = build_graphs(bundle);
}
/*
#ifdef GMEMTRACE
//double vm,rsm;
get_mem_usage(vm, rsm);
GMessage("\t\tM(e):infer_transcripts memory usage: rsm=%6.1fMB vm=%6.1fMB\n",rsm/1024,vm/1024);
#endif
*/
return(geneno);
}
void printGff3Header(FILE* f, GArgs& args) {
fprintf(f, "# ");
args.printCmdLine(f);
fprintf(f, "##gff-version 3\n");
}
int predCmp(const pointer p1, const pointer p2) {
CPrediction *a=(CPrediction*)p1;
CPrediction *b=(CPrediction*)p2;
if(a->start < b->start) return -1; // order based on start
if(a->start > b->start) return 1;
if(a->cov > b->cov) return -1; // the one with higher coverage comes first
if(a->cov < b->cov) return 1;
// same start
if(a->exons.Count() < b->exons.Count()) return -1; // order based on number of exons
if(a->exons.Count() > b->exons.Count()) return 1;
// same number of exons
int i=0;
uint a1=0;
uint b1=0;
while(i<a->exons.Count()) {
if(a->exons[i].start<b->exons[i].start) {
a1=a->exons[i].start;
b1=b->exons[i].start;
break;
}
if(a->exons[i].end<b->exons[i].end) {
a1=a->exons[i].end;
b1=b->exons[i].end;
break;
}
i++;
}
if(a1) {
if(a1<b1) return -1; // the one with the first exon comes first
if(a1>b1) return 1;
}
//}
return 0;
}
int predexCmp(const pointer p1, const pointer p2) {
CPrediction *a=(CPrediction*)p1;
CPrediction *b=(CPrediction*)p2;
if(a->exons.Count() < b->exons.Count()) return -1;
if(a->exons.Count() > b->exons.Count()) return 1;
if(abs(a->tlen) < abs(b->tlen)) return -1;
if(abs(a->tlen) > abs(b->tlen)) return 1;
return 0;
}
int predcovCmp(const pointer p1, const pointer p2) { // sort from highest to lowest coverage
CPrediction *a=(CPrediction*)p1;
CPrediction *b=(CPrediction*)p2;
if(a->cov < b->cov) return 1;
if(a->cov > b->cov) return -1;
return 0;
}
int predordCmp(const pointer p1, const pointer p2) { // sort from highest to lowest coverage
CPred *a=(CPred*)p1;
CPred *b=(CPred*)p2;
if(a->cov < b->cov) return 1;
if(a->cov > b->cov) return -1;
return 0;
}
int predlenCmp(const pointer p1, const pointer p2) { // sort from highest to lowest coverage
CPrediction *a=(CPrediction*)p1;
CPrediction *b=(CPrediction*)p2;
if(a->exons.Count() < b->exons.Count()) return 1;
if(a->exons.Count() > b->exons.Count()) return -1;
if(a->t_eq==NULL && b->t_eq!=NULL) return 1;
if(a->t_eq!=NULL && b->t_eq==NULL) return -1;
if(a->cov < b->cov) return 1;
if(a->cov > b->cov) return -1;
return 0;
}
bool equal_pred(GList<CPrediction>& pred,int n1,int n2){
if(pred[n1]->strand!=pred[n2]->strand) return false;
//if(pred[n1]->start!=pred[n2]->start) return(false); // this allows genes with different start/ends to be merged together
//if(pred[n1]->end!=pred[n2]->end) return(false); // but I need to check if they overlap in case of single exons
if((pred[n1]->end < pred[n2]->start) || (pred[n2]->end<pred[n1]->start)) return(false); // genes don't overlap
int nex=pred[n1]->exons.Count();
if(nex!=pred[n2]->exons.Count()) return(false);
for(int i=0;i<nex;i++) {
//if(pred[n1]->exons[i].start!=pred[n2]->exons[i].start) { fprintf(stderr,"ret false start[%d]: %d vs %d\n",i,pred[n1]->exons[i].start,pred[n2]->exons[i].start); return(false);}
//if(pred[n1]->exons[i].end!=pred[n2]->exons[i].end) { fprintf(stderr,"ret false end[%d]: %d vs %d\n",i,pred[n1]->exons[i].end,pred[n2]->exons[i].end); return(false);}
if(i>0 && (pred[n1]->exons[i].start!=pred[n2]->exons[i].start)) return(false);
if(i<nex-1 && (pred[n1]->exons[i].end!=pred[n2]->exons[i].end)) return(false);
}
return(true);
}
bool is_pred_above_frac(CInterval *maxcov,CPrediction* pred) {
CInterval *lastinterv=NULL;
while(maxcov && pred->start>=maxcov->pos) {
lastinterv=maxcov;
maxcov=maxcov->next;
}
if(lastinterv && ((pred->exons.Count()==1 && pred->cov<lastinterv->val) || pred->cov<isofrac*lastinterv->val)) return(false); // I need to deal with single exons too here
while(maxcov && pred->end>=maxcov->pos) {
if((pred->exons.Count()==1 && pred->cov<maxcov->val) || pred->cov<isofrac*maxcov->val) return(false);
maxcov=maxcov->next;
}
return(true);
}
//bool is_exon_above_frac(CInterval *maxcov,uint start,uint end,float cov,int exonno) {
bool is_exon_above_frac(CInterval *maxcov,uint start,uint end,float cov) {
CInterval *lastinterv=NULL;
while(maxcov && start>=maxcov->pos) {
lastinterv=maxcov;
maxcov=maxcov->next;
}
//if(lastinterv && ((exonno==1 && cov<lastinterv->val) || cov<isofrac*lastinterv->val)) return(false); // I need to deal with single exons too here
if(lastinterv && cov<isofrac*lastinterv->val) return(false); // I need to deal with single exons too here
while(maxcov && end>=maxcov->pos) {
//if((exonno==1 && cov<maxcov->val) || cov<isofrac*maxcov->val) return(false);
if(cov<isofrac*maxcov->val) return(false);
maxcov=maxcov->next;
}
return(true);
}
void delete_Cinterval(CInterval *interv){
if(interv) {
if(interv->next) delete_Cinterval(interv->next);
delete interv;
}
}
uint min(uint n1,uint n2) {
if(n1<n2) return(n1);
return(n2);
}
uint max(uint n1,uint n2) {
if(n1<n2) return(n2);
return n1;
}
/*
bool retainedintron(GList<CPrediction>& pred,int n1,int n2,GVec<GBitVec>& lowintron) {
int j=1;
for(int i=1;i<pred[n1]->exons.Count();i++) {
if(j>pred[n2]->exons.Count()-2) return false;
if(lowintron[n1][i-1]) {
while(j<pred[n2]->exons.Count()-1 && pred[n2]->exons[j].end<pred[n1]->exons[i].start) j++; // now pred[n2]->exons[j].end>=pred[n1]->exons[i].start
if(j<pred[n2]->exons.Count()-1 && pred[n2]->exons[j].start<=pred[n1]->exons[i-1].end) return true;
}
}
return false;
}
*/
int retainedintron(GList<CPrediction>& pred,int n1,int n2,GVec<GBitVec>& lowintron) {
float frac=ERROR_PERC;
if(mixedMode && isofrac<frac && pred[n2]->tlen<0 && pred[n2]->cov>DROP/ERROR_PERC) frac=isofrac;
int j=0;
for(int i=1;i<pred[n1]->exons.Count();i++) {
if(j>pred[n2]->exons.Count()-1) return(0);
if(lowintron[n1][i-1]) { // pred[n1] has lowintron i-1
if(j==pred[n2]->exons.Count()-1 && pred[n2]->cov<frac*pred[n1]->cov && pred[n2]->exons[j].start<=pred[n1]->exons[i-1].end)
return(1);
while(j<pred[n2]->exons.Count() && pred[n2]->exons[j].end<pred[n1]->exons[i].start) j++; // now pred[n2]->exons[j].end>=pred[n1]->exons[i].start
if(!j && pred[n2]->cov<frac*pred[n1]->cov) return(1);
if(j<pred[n2]->exons.Count() && pred[n2]->exons[j].start<=pred[n1]->exons[i-1].end) {
if(j && j<pred[n2]->exons.Count()-1) {
/*fprintf(stderr,"middle exon i=%d j=%d pred[n2=%d]=%f < pred[n1=%d]=%f for intron %d-%d in n1 and exon %d-%d in n2\n",i,j,
n2,pred[n2]->cov,n1,pred[n1]->cov,pred[n1]->exons[i-1].end,pred[n1]->exons[i].start,pred[n2]->exons[j].start,pred[n2]->exons[j].end);*/
return(2); // middle exon
}
else if(pred[n2]->cov<frac*pred[n1]->cov) {
/*fprintf(stderr,"i=%d j=%d pred[n2=%d]=%f < pred[n1=%d]=%f for intron %d-%d in n1 and exon %d-%d in n2\n",i,j,
n2,pred[n2]->cov,n1,pred[n1]->cov,pred[n1]->exons[i-1].end,pred[n1]->exons[i].start,pred[n2]->exons[j].start,pred[n2]->exons[j].end);*/
return(1);
}
}
}
}
return(0);
}
bool included_pred(GList<CPrediction>& pred,int n1,int n2,uint refstart=0,GVec<float>* bpcov = NULL,bool reference=true) { // check if the small prediction is included in the larger prediction
int intronextension=2*longintronanchor;
if(longreads) intronextension=CHI_WIN; // more aggressive inclusion rules for long reads
if(pred[n1]->start > pred[n2]->end || pred[n2]->start>pred[n1]->end) return false;
int big=n1;
int small=n2;
if(pred[n1]->exons.Count()<pred[n2]->exons.Count()) {
big=n2;
small=n1;
}
if(reference && pred[small]->t_eq) { // this is a reference guide included into another transcript -> only keep one of them
if(pred[big]->t_eq && pred[small]->t_eq!=pred[big]->t_eq) return false;
if(pred[small]->exons.Count()!=pred[big]->exons.Count()) return false;
}
int bex=0;
while(bex<pred[big]->exons.Count()) {
if(pred[small]->exons[0].start>pred[big]->exons[bex].end) bex++;
else { // now pred[small]->exons[0].start <= pred[big]->exons[bex].end
if(pred[small]->exons[0].end<pred[big]->exons[bex].start) return false; // no overlap
// now: pred[small]->exons[0].end>=pred[big]->exons[bex].start
int sex=0;
//if(pred[small]->exons.Count()>1) while(bex<pred[big]->exons.Count() && pred[big]->exons[bex].end<pred[small]->exons[0].end) bex++;
//if(bex==pred[big]->exons.Count()) return false;
while(sex<pred[small]->exons.Count() && bex<pred[big]->exons.Count()) {
if(sex==pred[small]->exons.Count()-1) { // I am at end of small pred
if(bex==pred[big]->exons.Count()-1) return true; // same intron structure and there is overlap; if small pred is single exon then I didn't check if it extends past the end of bex which is problematic since above I do
if(sex && pred[small]->exons[sex].end>pred[big]->exons[bex+1].start) return false; // might be able to eliminate some transcripts here if the drop is big -> I should probably just comment this because below I take care of it; or make it as an else to the if below
//if(sex && pred[small]->exons[sex].end>pred[big]->exons[bex].end+longintronanchor) { // small prediction extends well into intron of big prediction
if(sex && pred[small]->exons[sex].end>pred[big]->exons[bex].end+intronextension) { // small prediction extends well into intron of big prediction
uint endin=pred[small]->exons[sex].end > pred[big]->exons[bex+1].start ? pred[big]->exons[bex+1].start : pred[small]->exons[sex].end;
float covintron=get_cov(1,pred[big]->exons[bex].end+1-refstart,endin-refstart,bpcov)/(endin-pred[big]->exons[bex].end);
if(covintron>singlethr) {
uint startex=pred[small]->exons[sex].start > pred[big]->exons[bex].start ? pred[small]->exons[sex].start : pred[big]->exons[bex].start;
float covexon=get_cov(1,startex-refstart,pred[big]->exons[bex].end-refstart,bpcov)/(pred[big]->exons[bex].end-startex+1);
if(covintron > ERROR_PERC*covexon && pred[big]->exons[bex].end-longintronanchor>refstart) { // return false
float exondrop=get_cov(1,pred[big]->exons[bex].end-longintronanchor+1-refstart,pred[big]->exons[bex].end-refstart,bpcov);
float introndrop=get_cov(1,pred[big]->exons[bex].end+1-refstart,pred[big]->exons[bex].end+longintronanchor-refstart,bpcov);
if(introndrop>ERROR_PERC*exondrop)
return false;
}
}
}
return true;
}
// sex is not last exon in small prediction but overlaps bex
if(bex==pred[big]->exons.Count()-1) return false; // small pred extends past big pred
if(pred[small]->exons[sex].end != pred[big]->exons[bex].end) return false;
//if(!sex && bex && pred[small]->exons[sex].start<pred[big]->exons[bex].start-longintronanchor) { // first exon of small prediction extends within intron of big prediction
if(!sex && bex && pred[small]->exons[sex].start<pred[big]->exons[bex].start-intronextension) { // first exon of small prediction extends within intron of big prediction
uint startin=pred[small]->exons[sex].start > pred[big]->exons[bex-1].end ? pred[small]->exons[sex].start : pred[big]->exons[bex-1].end;
float covintron=get_cov(1,startin-refstart,pred[big]->exons[bex].start-1-refstart,bpcov)/(pred[big]->exons[bex].start-startin);
if(covintron>singlethr) {
uint endex=pred[small]->exons[sex].end > pred[big]->exons[bex].end ? pred[big]->exons[bex].end : pred[small]->exons[sex].end;
float covexon=get_cov(1,pred[big]->exons[bex].start-refstart,endex-refstart,bpcov)/(endex-pred[big]->exons[bex].start+1);
if(covintron > ERROR_PERC*covexon && pred[big]->exons[bex].start-longintronanchor>=refstart) { // return false
float introndrop=get_cov(1,pred[big]->exons[bex].start-longintronanchor-refstart,pred[big]->exons[bex].start-1-refstart,bpcov);
float exondrop=get_cov(1,pred[big]->exons[bex].start-refstart,pred[big]->exons[bex].start+longintronanchor-1-refstart,bpcov);
if(introndrop>ERROR_PERC*exondrop)
return false;
}
}
}
bex++;
sex++;
if(pred[small]->exons[sex].start != pred[big]->exons[bex].start) return false;
}
return false;
}
}
return false;
}
void update_cov(GList<CPrediction>& pred,int big,int small,float frac=1) { // small gets included into big
if(pred[big]->strand=='.') pred[big]->strand=pred[small]->strand;
if(pred[small]->t_eq && !pred[big]->t_eq) { // this can only happen if big pred has the same number of exons
pred[big]->tlen=pred[small]->tlen;
pred[big]->exons[0].start=pred[small]->exons[0].start;
pred[big]->start=pred[small]->start;
pred[big]->exons.Last().end=pred[small]->exons.Last().end;
pred[big]->end=pred[small]->end;
pred[big]->t_eq=pred[small]->t_eq;
}
int bex=0; // first exon in big pred that overlaps small pred
while(pred[small]->exons[0].start>pred[big]->exons[bex].end) bex++;
if(pred[big]->cov<pred[small]->cov && !pred[big]->t_eq && !bex && pred[small]->exons.Count()>1 && pred[big]->exons[0].start<pred[small]->exons[0].start) { // adjust start to account for trimming -> this messes up coverage of big pred though
pred[big]->tlen-=pred[small]->exons[0].start-pred[big]->exons[0].start;
pred[big]->exons[0].start=pred[small]->exons[0].start;
pred[big]->start=pred[small]->start;
}
int sex=0;
int overlap=0;
while(sex<pred[small]->exons.Count()) {
int exovlp=(pred[small]->exons[sex].end<pred[big]->exons[bex].end ? pred[small]->exons[sex].end : pred[big]->exons[bex].end)-
(pred[small]->exons[sex].start>pred[big]->exons[bex].start ? pred[small]->exons[sex].start : pred[big]->exons[bex].start)+1;
if(pred[big]->cov<pred[small]->cov && !pred[big]->t_eq && bex==pred[big]->exons.Count()-1 && sex>=1 && pred[big]->exons[bex].end>pred[small]->exons[sex].end) { // adjust end
pred[big]->tlen-=pred[big]->exons[bex].end-pred[small]->exons[sex].end;
pred[big]->exons[bex].end=pred[small]->exons[sex].end;
pred[big]->end=pred[small]->end;
}
pred[big]->exoncov[bex]=(pred[big]->exoncov[bex]*pred[big]->exons[bex].len()+frac*pred[small]->exoncov[sex]*exovlp)/pred[big]->exons[bex].len();
overlap+=exovlp;
sex++;bex++;
}
pred[big]->cov=(pred[big]->tlen*pred[big]->cov+overlap*frac*pred[small]->cov)/pred[big]->tlen;
}
void merge_exons(CGene& gene,GList<GffExon>& exons) {
int ig=0;
int ie=0;
while(ie<exons.Count()) {
if(ig==gene.exons.Count() || exons[ie]->end<gene.exons[ig].start) {
GSeg ex(exons[ie]->start,exons[ie]->end);
gene.exons.Insert(ig,ex);
ie++;
ig++;
continue;
}
while(ig<gene.exons.Count() && exons[ie]->start>gene.exons[ig].end) ig++;
if(ig<gene.exons.Count()) { // here exons[ie]->start<=gene.exons[ig].end and exons[ie]->end>=gene.exons[ig].start
if(exons[ie]->start<=gene.exons[ig].start) gene.exons[ig].start=exons[ie]->start;
if(exons[ie]->end>=gene.exons[ig].end) {
gene.exons[ig].end=exons[ie]->end;
ig++;
while(ig<gene.exons.Count() && exons[ie]->end>=gene.exons[ig].start) {
if(gene.exons[ig].end>exons[ie]->end) gene.exons[ig-1].end=gene.exons[ig].end;
gene.exons.Delete(ig);
}
}
ie++;
}
}
}
void merge_exons(CGene& gene,GVec<GSeg>& exons) {
int ig=0;
int ie=0;
while(ie<exons.Count()) {
if(ig==gene.exons.Count() || exons[ie].end<gene.exons[ig].start) {
gene.exons.Insert(ig,exons[ie]);
ie++;
ig++;
continue;
}
while(ig<gene.exons.Count() && exons[ie].start>gene.exons[ig].end) ig++;
if(ig<gene.exons.Count()) { // here exons[ie]->start<=gene.exons[ig].end and exons[ie]->end>=gene.exons[ig].start
if(exons[ie].start<=gene.exons[ig].start) gene.exons[ig].start=exons[ie].start;
if(exons[ie].end>=gene.exons[ig].end) {
gene.exons[ig].end=exons[ie].end;
ig++;
while(ig<gene.exons.Count() && exons[ie].end>=gene.exons[ig].start) {
if(gene.exons[ig].end>exons[ie].end) gene.exons[ig-1].end=gene.exons[ig].end;
gene.exons.Delete(ig);
}
}
ie++;
}
}
}
void update_overlap(GList<CPrediction>& pred,int p,int e,GVec<CExon>& node,GVec<bool>& overlap) {
int n=pred.Count();
for(int i=0;i<node.Count();i++) if(!overlap[n*node[i].predno+p]) { // there is no overlap detected yet
// exon e in prediction p overlaps exon ei in prediction pi
int pi=node[i].predno;
int ei=node[i].exonno;
overlap[n*pi+p]=true;
// overlap is not significant in the following cases
if(!e && pred[p]->exons[0].end>=pred[pi]->end) { // I am at the beginning of prediction p
int len=pred[pi]->end-pred[p]->start+1;
if(len<ERROR_PERC*abs(pred[p]->tlen)) overlap[n*pi+p]=false; // prediction p doesn't overlap prediction pi by a considerable amount
}
if(overlap[n*pi+p] && !ei && pred[pi]->exons[0].end>=pred[p]->end) { // I am at the beginning of prediction pi
int len=pred[p]->end-pred[pi]->start+1;
if(len<ERROR_PERC*abs(pred[pi]->tlen)) overlap[n*pi+p]=false; // prediction pi doesn't overlap prediction p by a considerable amount
}
if(overlap[n*pi+p] && e==pred[p]->exons.Count()-1 && pred[p]->exons[e].start<=pred[pi]->start) { // I am at the end of prediction p
int len=pred[p]->end-pred[pi]->start+1;
if(len<ERROR_PERC*abs(pred[p]->tlen)) overlap[n*pi+p]=false; // prediction p doesn't overlap prediction pi by a considerable amount
}
if(overlap[n*pi+p] && ei==pred[pi]->exons.Count()-1 && pred[pi]->exons[ei].start<=pred[p]->start) { // I am at the end of prediction pi
int len=pred[pi]->end-pred[p]->start+1;
if(len<ERROR_PERC*abs(pred[pi]->tlen)) overlap[n*pi+p]=false; // prediction pi doesn't overlap prediction p by a considerable amount
}
}
}
CMaxIntv *add_exon_to_maxint(CMaxIntv *maxint,uint start,uint end,int p,int e,float c,GList<CPrediction>& pred,GVec<bool>& overlap) {
CMaxIntv *prevmaxint=NULL;
while(maxint && start>maxint->end) {
prevmaxint=maxint;
maxint=maxint->next; // skip maxint until I get to the one that overlaps my exon or after it
}
CExon ex=CExon(p,e,c);
CMaxIntv *nextmaxint;
if(maxint) { // start <= maxint->end, start>prexmaxint->end ; there might be overlap with maxint
if(end<maxint->start) { // --> no overlap -> exon is in between nodes of maxint -> I need to keep previous maxint for this
if(!prevmaxint) { // this shouldn't happen due to maxint construction
GError("No overlap with exon in printing results!\n");
}
nextmaxint=new CMaxIntv(start,end);
nextmaxint->node.Add(ex);
nextmaxint->next=maxint;
prevmaxint->next=nextmaxint;
return nextmaxint;
}
else { // end>=maxint->start --> there is overlap
if(maxint->start<start) { // some region of maxint comes before exon
nextmaxint=new CMaxIntv(maxint->node,start,maxint->end,maxint->next);
maxint->next=nextmaxint;
maxint->end=start-1;
}
else if(start<maxint->start) { // this does nothing to maxint
nextmaxint=new CMaxIntv(start,maxint->start-1);
nextmaxint->next=maxint;
if(prevmaxint) prevmaxint->next=nextmaxint;
}
else { // start==maxint->start and this does nothing to maxint
nextmaxint=maxint;
}
update_overlap(pred,p,e,nextmaxint->node,overlap);
nextmaxint->node.Add(ex);
if(end<nextmaxint->end) { // nextmaxint now ends where previous maxint ended
maxint=new CMaxIntv(nextmaxint->node,end+1,nextmaxint->end,nextmaxint->next);
nextmaxint->end=end;
maxint->node.Pop();
nextmaxint->next=maxint;
}
else if(end>nextmaxint->end) {
maxint=nextmaxint;
while(maxint->next && end>=maxint->next->start) {
if(maxint->end+1<maxint->next->start) {
CMaxIntv *newintv=new CMaxIntv(maxint->end+1,maxint->next->start-1);
newintv->node.Add(ex);
newintv->next=maxint->next;
maxint->next=newintv;
maxint=newintv;
}
update_overlap(pred,p,e,maxint->next->node,overlap);
maxint->next->node.Add(ex);
maxint=maxint->next;
}
// end<maxint->next->start or maxint->next is NULL
if(end>maxint->end) {
CMaxIntv *newintv=new CMaxIntv(maxint->end+1,end);
newintv->node.Add(ex);
newintv->next=maxint->next;
maxint->next=newintv;
}
else if(end<maxint->end) {
CMaxIntv *newintv=new CMaxIntv(maxint->node,end+1,maxint->end,maxint->next);
newintv->node.Pop();
maxint->next=newintv;
maxint->end=end;
}
}
}
}
else { // start > prevmaxint->end and maxint is NULL --> no overlap here
nextmaxint=new CMaxIntv(start,end);
nextmaxint->node.Add(ex);
prevmaxint->next=nextmaxint;
}
return nextmaxint;
}
bool intronic(GList<CPrediction>& pred,int m,int M) {
int i=0;
while(i<pred[M]->exons.Count() && pred[m]->start>=pred[M]->exons[i].start) i++;
if(i==pred[M]->exons.Count() || !i) return false;
// now pred[m]->start<pred[M]->exons[i].start
if(pred[m]->exons[0].end<pred[M]->exons[i-1].end || pred[m]->exons.Last().start>pred[M]->exons[i].start) return false; // full first|last exon inside exon of big prediction
if(pred[m]->start<=pred[M]->exons[i-1].end) {
int len=pred[M]->exons[i-1].end-pred[m]->start+1;
if(len>ERROR_PERC*abs(pred[m]->tlen)) return false; // overlap too big for prediction to be considered intronic
}
if(pred[m]->end>=pred[M]->exons[i].start) {
int len=pred[m]->end-pred[M]->exons[i].start+1;
if(len>ERROR_PERC*abs(pred[m]->tlen)) return false;
}
return true;
}
bool transcript_overlap(GList<CPrediction>& pred,int n1,int n2) {
if(pred[n1]->end>=pred[n2]->start && pred[n2]->end>=pred[n1]->start) { // there is overlap --> check if it's substantial by looking at first/last exons as in update_overlap
if(pred[n1]->exons.Last().start<=pred[n2]->exons[0].end || pred[n2]->exons.Last().start<=pred[n1]->exons[0].end) return false;
return true;
}
return false;
}
int print_predcluster(GList<CPrediction>& pred,int geneno,GStr& refname,
GVec<CGene>& refgene, GHash<int>& hashgene, GVec<CGene>& predgene, BundleData* bundleData,bool checkincomplete) {
uint runoffdist=200;
if(longreads) runoffdist=0;
if(bundledist>runoffdist) runoffdist=bundledist;
int npred=pred.Count();
GVec<bool> overlap;
overlap.Resize(npred*npred-npred);
GVec<CPred> predord;
//CPred p(0,pred[0]->cov);
CPred p(0,abs(pred[0]->tlen)*pred[0]->cov); // priority based on number of bases covered -> this should a give a boost to predictions that are longer
predord.Add(p);
GVec<int> color;
color.cAdd(0);
GVec<int> incomplete;
GHash<bool> guideintron;
GVec<GBitVec> lowintron;
GBitVec intron;
if(pred[0]->exons.Count()>1) {
intron.resize(pred[0]->exons.Count()-1,false);
if(checkincomplete && !pred[0]->t_eq && pred[0]->mergename.is_empty()) { // incomplete transcript
incomplete.cAdd(0);
}
}
GVec<float>* bpcov = bundleData->bpcov;
float intronfrac=DROP-ERROR_PERC;
if(longreads && isofrac<intronfrac) intronfrac=isofrac;
// build maxIntv
CMaxIntv *maxint=new CMaxIntv(pred[0]->exons[0].start,pred[0]->exons[0].end);
if(!pred[0]->t_eq) {
if(eonly) pred[0]->flag=false;
else if(pred[0]->exons.Count()==1 && pred[0]->strand!='.') { // neutral strand if most reads are neutral
int s=0;
if(pred[0]->strand=='+') s=2;
float totalcov=get_cov(1,pred[0]->start-bundleData->start,pred[0]->end-bundleData->start,bpcov);
float strandcov=get_cov(s,pred[0]->start-bundleData->start,pred[0]->end-bundleData->start,bpcov);
if(strandcov<ERROR_PERC*totalcov) pred[0]->strand='.';
}
}
float excov=pred[0]->cov;
if(!longreads) excov*=abs(pred[0]->tlen); // it was len() before but that doesn't make any sense
CExon ex(0,0,excov); // this keeps the exon flow based on per bp coverage
//CExon ex(0,0,pred[0]->exoncov[0]*pred[0]->exons[0].len()); // this keeps the exon flow based on read coverage (elen factor)
//pred[0]->exoncov[0]=0;
maxint->node.Add(ex);
CMaxIntv *nextmaxint=maxint;
bool exist=true;
GStr id("", 32);
for(int j=1;j<pred[0]->exons.Count();j++) {
if(checkincomplete && pred[0]->t_eq) {
id.assign((int)pred[0]->exons[j-1].end);
id+=pred[0]->strand;
id+=(int)pred[0]->exons[j].start;
bool *gi=guideintron[id.chars()];
if(!gi) guideintron.Add(id.chars(), exist);
}
float introncov=get_cov(1,pred[0]->exons[j-1].end+1-bundleData->start,pred[0]->exons[j].start-1-bundleData->start,bpcov)/(pred[0]->exons[j].start-pred[0]->exons[j-1].end-1);
if(introncov) {
if(introncov<1 || (!longreads && introncov<singlethr)) intron[j-1]=1;
else {
float exoncov=(get_cov(1,pred[0]->exons[j-1].start-bundleData->start,pred[0]->exons[j-1].end-bundleData->start,bpcov)+
get_cov(1,pred[0]->exons[j].start-bundleData->start,pred[0]->exons[j].end-bundleData->start,bpcov))/(pred[0]->exons[j-1].len()+pred[0]->exons[j].len());
if(introncov<exoncov*intronfrac) intron[j-1]=1;
else {
// left drop
int start=pred[0]->exons[j-1].end-longintronanchor+1-bundleData->start;
if(start<0) start=0;
int end=pred[0]->exons[j-1].end+longintronanchor-bundleData->start;
if(end>bpcov->Count()-2) end=bpcov->Count()-2;
exoncov=get_cov(1,start,pred[0]->exons[j-1].end-bundleData->start,bpcov);
introncov=get_cov(1,pred[0]->exons[j-1].end+1-bundleData->start,end,bpcov);
if(introncov<exoncov*intronfrac) intron[j-1]=1;
else { // right drop
int start=pred[0]->exons[j].start-longintronanchor-bundleData->start;
if(start<0) start=0;
int end=pred[0]->exons[j].start+longintronanchor-1-bundleData->start;
if(end>bpcov->Count()-2) end=bpcov->Count()-2;
introncov=get_cov(1,start,pred[0]->exons[j].start-1-bundleData->start,bpcov);
exoncov=get_cov(1,pred[0]->exons[j].start-bundleData->start,end,bpcov);
if(introncov<exoncov*intronfrac) intron[j-1]=1;
}
}
//fprintf(stderr,"pred[%d] intron[%d]:%d-%d introncov=%f exoncov=%f\n",0,j-1,pred[0]->exons[j-1].end,pred[0]->exons[j].start,introncov,exoncov);
}
}
nextmaxint=add_exon_to_maxint(nextmaxint,pred[0]->exons[j].start,pred[0]->exons[j].end,0,j,excov,pred,overlap); // per bp coverage
//nextmaxint=add_exon_to_maxint(nextmaxint,pred[0]->exons[j].start,pred[0]->exons[j].end,0,j,pred[0]->exoncov[j]*pred[0]->exons[j].len(),pred,overlap); // per read coverage
//pred[0]->exoncov[j]=0;
}
lowintron.Add(intron);
nextmaxint=maxint;
for(int n=1;n<npred;n++) {
if(!pred[n]->t_eq) {
if(eonly) pred[n]->flag=false;
else if(pred[n]->exons.Count()==1 && pred[n]->strand!='.') { // neutral strand if most reads are neutral
int s=0;
if(pred[n]->strand=='+') s=2;
float totalcov=get_cov(1,pred[n]->start-bundleData->start,pred[n]->end-bundleData->start,bpcov);
float strandcov=get_cov(s,pred[n]->start-bundleData->start,pred[n]->end-bundleData->start,bpcov);
if(strandcov<ERROR_PERC*totalcov) pred[n]->strand='.';
}
}
color.Add(n);
excov=pred[n]->cov;
if(!longreads) excov*=abs(pred[n]->tlen);
//CPred p(n,pred[n]->cov); // priority based on cov/bp
CPred p(n,abs(pred[n]->tlen)*pred[n]->cov); // priority based on number of bases covered
predord.Add(p);
nextmaxint=add_exon_to_maxint(nextmaxint,pred[n]->exons[0].start,pred[n]->exons[0].end,n,0,excov,pred,overlap); // per bp coverage
//nextmaxint=add_exon_to_maxint(nextmaxint,pred[n]->exons[0].start,pred[n]->exons[0].end,n,0,pred[n]->exoncov[0]*pred[n]->exons[0].len(),pred,overlap); // read coverage
//pred[n]->exoncov[0]=0;
intron.clear();
intron.resize(pred[n]->exons.Count()-1,false);
if(checkincomplete && !pred[n]->t_eq && pred[n]->exons.Count()>1 && pred[n]->mergename.is_empty()) { // incomplete transcript
incomplete.Add(n);
}
CMaxIntv *nextintv=nextmaxint;
for(int j=1;j<pred[n]->exons.Count();j++) {
if(checkincomplete && pred[n]->t_eq) {
//GStr id((int)pred[n]->exons[j-1].end);
id.assign((int)pred[n]->exons[j-1].end);
id+=pred[n]->strand;
id+=(int)pred[n]->exons[j].start;
bool *gi=guideintron[id.chars()];
if(!gi) guideintron.Add(id.chars(),exist);
}
float introncov=get_cov(1,pred[n]->exons[j-1].end+1-bundleData->start,pred[n]->exons[j].start-1-bundleData->start,bpcov)/(pred[n]->exons[j].start-pred[n]->exons[j-1].end-1);
if(introncov) {
if(introncov<1 || (!longreads && introncov<singlethr)) intron[j-1]=1;
else {
float exoncov=(get_cov(1,pred[n]->exons[j-1].start-bundleData->start,pred[n]->exons[j-1].end-bundleData->start,bpcov)+
get_cov(1,pred[n]->exons[j].start-bundleData->start,pred[n]->exons[j].end-bundleData->start,bpcov))/(pred[n]->exons[j-1].len()+pred[n]->exons[j].len());
if(introncov<exoncov*intronfrac) intron[j-1]=1;
else {
// left drop
int start=pred[n]->exons[j-1].end-longintronanchor+1-bundleData->start;
if(start<0) start=0;
int end=pred[n]->exons[j-1].end+longintronanchor-bundleData->start;
if(end>bpcov->Count()-2) end=bpcov->Count()-2;
exoncov=get_cov(1,start,pred[n]->exons[j-1].end-bundleData->start,bpcov);
introncov=get_cov(1,pred[n]->exons[j-1].end+1-bundleData->start,end,bpcov);
if(introncov<exoncov*intronfrac) intron[j-1]=1;
else { // right drop
int start=pred[n]->exons[j].start-longintronanchor-bundleData->start;
if(start<0) start=0;
int end=pred[n]->exons[j].start+longintronanchor-1-bundleData->start;
if(end>bpcov->Count()-2) end=bpcov->Count()-2;
introncov=get_cov(1,start,pred[n]->exons[j].start-1-bundleData->start,bpcov);
exoncov=get_cov(1,pred[n]->exons[j].start-bundleData->start,end,bpcov);
if(introncov<exoncov*intronfrac) intron[j-1]=1;
}
}
}
}
nextintv=add_exon_to_maxint(nextintv,pred[n]->exons[j].start,pred[n]->exons[j].end,n,j,excov,pred,overlap); // per bp coverage
//nextintv=add_exon_to_maxint(nextintv,pred[n]->exons[j].start,pred[n]->exons[j].end,n,j,pred[n]->exoncov[j]*pred[n]->exons[j].len(),pred,overlap); // read coverage
//pred[n]->exoncov[j]=0;
}
lowintron.Add(intron);
/*
{ // DEBUG ONLY
fprintf(stderr,"After adding pred %d\n",n);
CMaxIntv *intv=maxint;
while(intv) {
fprintf(stderr,"...average coverage for interval:%d-%d=%f (%f perbp)\n",intv->start,intv->end,bpcov[1][intv->end-bundleData->start]-bpcov[1][intv->start-1-bundleData->start],(bpcov[1][intv->end-bundleData->start]-bpcov[1][intv->start-1-bundleData->start])/(intv->end-intv->start+1));
intv=intv->next;
}
}
*/
}
if(checkincomplete) {
for(int i=0;i<incomplete.Count();i++) {
int n=incomplete[i];
bool eliminate=true;
for(int j=1;j<pred[n]->exons.Count();j++) {
//GStr id((int)pred[n]->exons[j-1].end);
id.assign((int)pred[n]->exons[j-1].end);
id+=pred[n]->strand;
id+=pred[n]->exons[j].start;
bool *gi=guideintron[id.chars()];
if(!gi) {
eliminate=false; break;
}
}
if(eliminate) {
pred[n]->flag=false;
//fprintf(stderr,"falseflag: incomplete pred[%d]\n",n);
}
}
}
//GVec<int> bettercov[npred];
GVec<int> ivec;
GVec< GVec<int> > bettercov(npred, ivec);
predord.Sort(predordCmp); // sort predictions from the most highest coverage to lowest
for(int i=0;i<predord.Count()-1;i++) {
if(pred[predord[i].predno]->flag) {
int n1=predord[i].predno;
//fprintf(stderr,"first consideration of pred[%d] with cov=%f and strand=%c\n",n1,pred[n1]->cov,pred[n1]->strand);
for(int j=i+1;j<predord.Count();j++) if(pred[predord[j].predno]->flag) {
int n2=predord[j].predno; // always predord.cov(n1)>=predord.cov(n2)
int m = n1;
int M = n2;
//fprintf(stderr,"...vs prediction n2=%d with cov=%f and strand=%c\n",n2,pred[n2]->cov,pred[n2]->strand);
if(m>M) { m=n2; M=n1;}
if(overlap[npred*m+M]) { // n1 could get eliminated by some other genes for instance if it has fewer exons and it's included in a bigger one
//fprintf(stderr,"overlap\n");
if(!pred[n2]->t_eq) { // this is not a known gene -> only then I can eliminate it
if(pred[n1]->t_eq && pred[n2]->cov<ERROR_PERC*pred[n1]->cov) { // more strict about novel predictions if annotation is available
pred[n2]->flag=false;
continue;
}
uint anchor=longintronanchor;
if(pred[n2]->tlen<0 && pred[n2]->cov>readthr) anchor=junctionsupport;
if(pred[n2]->exons[0].len()<anchor || pred[n2]->exons.Last().len()<anchor) { // VAR8: leave this one out
//fprintf(stderr,"falseflag: pred[%d] n2=%d has low first/last exon\n",n2,n2);
pred[n2]->flag=false;
}
else if(retainedintron(pred,n1,n2,lowintron)) {
//if(ret>1 || pred[n2]->cov<ERROR_PERC*pred[n1]->cov) {
//fprintf(stderr,"falseflag: pred[%d] n2=%d has low intron coverage\n",n2,n2);
pred[n2]->flag=false;
//}
}
else if(pred[n1]->strand != pred[n2]->strand) {
//fprintf(stderr,"diff strand\n");
if(pred[n2]->exons.Count()==1 || (pred[n1]->tlen<0 && pred[n2]->tlen>0 && pred[n2]->cov<1/ERROR_PERC)) { // why was I restricting it to single exons?
//fprintf(stderr,"falseflag: ...strand elmination of pred[%d] n2=%d by n1=%d\n",n2,n2,n1);
pred[n2]->flag=false;
}
else if(!pred[n1]->t_eq && pred[n1]->exons.Count()==1) {
if(pred[n1]->cov < pred[n2]->cov+singlethr) {
//fprintf(stderr,"flaseflag: pred[%d] n1=%d with 1 exon eliminated by n2=%d\n",n1,n1,n2);
pred[n1]->flag=false;
break;
}
/*else {
float totalcov=get_cov(1,pred[n1]->start-bundleData->start,pred[n1]->end-bundleData->start,bundleData->bpcov);
if(totalcov*DROP>pred[n1]->cov*pred[n1]->len())
pred[n1]->flag=false; break;
}*/
}
else if(pred[n2]->exons.Count()<=pred[n1]->exons.Count() && included_pred(pred,n1,n2,(uint)bundleData->start,bpcov)) {
//fprintf(stderr,"falseflag: pred[%d] n2=%d is included in n1=%d\n",n2,n2,n1);
pred[n2]->flag=false;
}
else if(pred[n2]->tlen>0 && !mixedMode){
bool lowcov=true;
for(int e=0;e<pred[n2]->exons.Count();e++) {
float totalcov=get_cov(1,pred[n2]->exons[e].start-bundleData->start,pred[n2]->exons[e].end-bundleData->start,bundleData->bpcov);
if(pred[n2]->exoncov[e]*pred[n2]->exons[e].len()>totalcov/2) {
lowcov=false;
break;
}
}
if(lowcov) {
pred[n2]->flag=false;
//fprintf(stderr,"falseflag: pred[%d] n2=%d has lowcov\n",n2,n2);
}
}
} // end pred[n1]->strand != pred[n2]->strand
//else if(pred[n2]->cov<isofrac*pred[n1]->cov) pred[n2]->flag=false; // I am only considering inclusions here since this might change allocations
else if(pred[n2]->exons.Count()<=pred[n1]->exons.Count() && pred[n1]->cov>pred[n2]->cov*DROP && included_pred(pred,n1,n2,(uint)bundleData->start,bpcov)) {
pred[n2]->flag=false;
//fprintf(stderr,"falseflag: ...included elmination of pred[%d] n2=%d by n1=%d\n",n2,n2,n1);
}
else if(!pred[n1]->t_eq && n1 && ((pred[n1]->tlen>0 && pred[n1]->exons.Count()<=2 && pred[n2]->cov>lowisofrac*pred[n1]->cov) || pred[n1]->cov < pred[n2]->cov+singlethr) && pred[n1]->exons.Count()<pred[n2]->exons.Count() && included_pred(pred,n2,n1,(uint)bundleData->start,bpcov)) {
pred[n1]->flag=false;
//fprintf(stderr,"falseflag: ...included elmination of pred[%d] n1=%d by n2=%d\n",n1,n1,n2);
break;
}
}
else if(!pred[n1]->t_eq && n1 && ((pred[n1]->tlen>0 && pred[n1]->exons.Count()<=2 && pred[n2]->cov>lowisofrac*pred[n1]->cov) || pred[n1]->cov < pred[n2]->cov+singlethr) && pred[n1]->exons.Count()<=pred[n2]->exons.Count() && included_pred(pred,n2,n1,(uint)bundleData->start,bpcov)) {
//fprintf(stderr,"falseflag: ...included elmination of pred[%d] n1=%d(%f) by n2=%d(%f)\n",n1,n1,pred[n1]->cov,n2,pred[n2]->cov);
pred[n1]->flag=false;
break;
}
else if(pred[n2]->tlen<0 && !pred[n2]->t_eq && pred[n2]->cov < DROP && pred[n2]->exons.Count()<=pred[n1]->exons.Count() && included_pred(pred,n1,n2,(uint)bundleData->start,bpcov,false)) {
pred[n2]->flag=false;
//fprintf(stderr,"falseflag: pred[%d] n2=%d is included in n1=%d\n",n2,n2,n1);
}
}
//else if(!pred[n2]->t_eq && pred[n2]->exons.Count()==1 && pred[n2]->cov<DROP*pred[n1]->cov && pred[n1]->start<pred[n2]->start && pred[n2]->end<pred[n1]->end) {
else if(!pred[n2]->t_eq && pred[n2]->exons.Count()==1 && ((pred[n2]->tlen>0 && pred[n2]->cov<pred[n1]->cov) || pred[n2]->cov<isofrac*pred[n1]->cov) && pred[n1]->start<=pred[n2]->start && pred[n2]->end<=pred[n1]->end) {
//fprintf(stderr,"falseflag: ...single exon elmination of pred[%d] n2=%d by n1=%d\n",n2,n2,n1);
pred[n2]->flag=false; // delete intronic prediction if single exon and at realtively low coverage
}
else if(pred[n1]->tlen>0) {
if(!pred[n1]->t_eq && pred[n1]->exons.Count()==1 && pred[n1]->cov<pred[n2]->cov && pred[n2]->start<=pred[n1]->start && pred[n1]->end<=pred[n2]->end) {
//fprintf(stderr,"falseflag: ...single exon elmination of pred[%d] n1=%d by n2=%d\n",n1, n1,n2);
pred[n1]->flag=false;
break;
}
else if(pred[n2]->tlen>0 && !pred[n2]->t_eq) {
if(transcript_overlap(pred,n1,n2)) {
for(int p=0;p<bettercov[n2].Count();p++) {
int m = n1;
int M = bettercov[n2][p];
if(m>M) { m=bettercov[n2][p]; M=n1;}
if(!overlap[npred*m+M]) {
pred[n2]->flag=false;
//fprintf(stderr,"falseflag: pred[%d] eliminated because of overlap to %d and %d\n",n2,m,M);
break;
}
}
if(pred[n2]->flag) {
if((mixedMode || pred[n1]->strand==pred[n2]->strand) && ((mixedMode && pred[n2]->cov<singlethr) || pred[n2]->cov<pred[n1]->cov*ERROR_PERC) && pred[n1]->start<=pred[n2]->start && pred[n2]->end<=pred[n1]->end && intronic(pred,n2,n1)) { // n2 is an intronic prediction to n1
//fprintf(stderr,"falseflag: eliminate pred[%d] is intronic into pred[%d]\n",n2,n1);
pred[n2]->flag=false;
}
else bettercov[n2].Add(n1);
}
}
else if(mixedMode && pred[n2]->strand!=pred[n1]->strand && pred[n2]->cov<singlethr) {
if(pred[n1]->start<=pred[n2]->end && pred[n2]->start<=pred[n1]->end) pred[n2]->flag=false; // antisense short read overlap
}
}
}
else if(pred[n2]->tlen>0 && !pred[n2]->t_eq ) { // && pred[n2]->strand!=pred[n1]->strand){ // now pred[n1]->tlen<0; n1 & n2 are antisense
if(pred[n1]->start<=pred[n2]->end && pred[n2]->start<=pred[n1]->end) {// n1 & n2 overlap but not within the exons
if(pred[n2]->cov<1/ERROR_PERC || (pred[n2]->strand==pred[n1]->strand && pred[n2]->cov<ERROR_PERC*pred[n1]->cov)) pred[n2]->flag=false; // mixed mode doesn't accept low covered anti-senses
}
}
//if(!pred[n1]->flag) fprintf(stderr,"pred[%d] eliminated\n",n1);
//if(!pred[n2]->flag) fprintf(stderr,"pred[%d] eliminated\n",n2);
}
}
}
/*
// eliminate included predictions
GVec<bool> keep;
keep.Resize(npred,false);
nextmaxint=maxint;
while(nextmaxint) {
GVec<CPred> exord; // only remember those predictions that have an intron
for(int i=0;i<nextmaxint->node.Count();i++) if(pred[nextmaxint->node[i].predno]->flag) {
int n=nextmaxint->node[i].predno;
int e=nextmaxint->node[i].exonno;
if(e<pred[n]->exons.Count()-1 && pred[n]->exons[e].end==nextmaxint->end) { // intron coming here
CPred ex(i,pred[nextmaxint->node[i].predno]->tlen*pred[nextmaxint->node[i].predno]->cov);
exord.Add(ex); //exord only remembers the non-false predictions that have introns starting here
}
}
if(exord.Count()) { // there are introns starting here
GVec<int> introns; // remembers end of introns starting here
exord.Sort(predordCmp);
for(int j=0;j<exord.Count();j++) {
int i=exord[j].predno;
int n=nextmaxint->node[i].predno;
int e=nextmaxint->node[i].exonno;
if(e<pred[n]->exons.Count()-1 && pred[n]->exons[e].end==nextmaxint->end) { // intron coming here
// check if new intron
bool newintron=true;
int end=pred[n]->exons[e+1].start;
for(int k=0;k<introns.Count();k++) {
if(introns[k]==end) {
newintron=false;
break;
}
}
if(newintron) {
introns.Add(end); // add new intron end here
keep[n]=true;
}
}
}
}
nextmaxint=nextmaxint->next;
}
*/
if(longreads) { // eliminate predictions under threshold without doing the coverage adjustment
nextmaxint=maxint;
while(nextmaxint) {
if((int)nextmaxint->start-bundleData->start<bpcov[1].Count()) {
GVec<CPred> exord;
for(int i=0;i<nextmaxint->node.Count();i++) if(pred[nextmaxint->node[i].predno]->flag) {
CPred ex(i,abs(pred[nextmaxint->node[i].predno]->tlen)*pred[nextmaxint->node[i].predno]->cov);
exord.Add(ex); //exord only remembers the non-false predictions
}
if(exord.Count()) {
exord.Sort(predordCmp); // sort exons from the most highest coverage to lowest
int i=exord[0].predno;
int n=nextmaxint->node[i].predno;
float usedcov[2]={0,0};
float multicov[2]={0,0};
int s=0;
if(pred[n]->strand=='+') s=1;
usedcov[s]=pred[n]->cov;
if(pred[n]->exons.Count()>1) multicov[s]=usedcov[s];
//fprintf(stderr,"maxint=%d-%d has first pred[%d] with cov=%f usedcov=%f\n",nextmaxint->start,nextmaxint->end,n,pred[n]->cov,usedcov[s]);
for(int j=1;j<exord.Count();j++) {
i=exord[j].predno;
n=nextmaxint->node[i].predno;
bool longunder=false;
if(pred[n]->strand=='+') s=1;
else s=0;
if(!pred[n]->t_eq) {
float isofraclong=isofrac;
if(pred[n]->cov>CHI_WIN) isofraclong=isofrac*ERROR_PERC*DROP; // more abundant transcript have higher error tollerance
else if(pred[n]->cov>CHI_THR) isofraclong=isofrac*DROP;
//else if(pred[n]->cov>1/ERROR_PERC) isofraclong=isofrac*DROP;
if(pred[n]->exons.Count()>1) {
if((!multicov[s] && pred[n]->cov<isofraclong*usedcov[s] && pred[n]->cov<DROP/ERROR_PERC) ||
pred[n]->cov<isofraclong*multicov[s]) longunder=true;
}
else if(pred[n]->cov<isofraclong*usedcov[s]) longunder=true;
}
if(longunder) {
//fprintf(stderr,"flaseflag: pred[%d] has low cov=%f percentage from usedcoverage=%f\n",n,pred[n]->cov,usedcov[s]);
pred[n]->flag=false;
}
else {
usedcov[s]+=pred[n]->cov;
if(pred[n]->exons.Count()>1) multicov[s]+=pred[n]->cov;
//fprintf(stderr,"maxint=%d-%d add pred[%d]->cov=%f to usedcov=%f\n",nextmaxint->start,nextmaxint->end,n,pred[n]->cov,usedcov[s]);
}
}
}
}
nextmaxint=nextmaxint->next;
}
}
else { // recompute coverages -> mostly for short reads; long reads should be more reliable in the way coverages are estimated
bool adjust=true;
while(adjust) { // by here I eliminated inclusions and intronic single exons
adjust=false;
for(int n=0;n<npred;n++) if(pred[n]->flag) {
/*if(!pred[n]->t_eq && !keep[n] && pred[n]->cov<lowcov) pred[n]->flag=false; // this was commented and it was almost there Pr 29.8 for 534291
else*/
for(int i=0;i<pred[n]->exons.Count();i++) if(pred[n]->tlen>0)
pred[n]->exoncov[i]=0;
}
nextmaxint=maxint;
while(nextmaxint) {
if((int)nextmaxint->start-bundleData->start<bpcov[1].Count()) {
float covsum=0;
GVec<CPred> exord;
for(int i=0;i<nextmaxint->node.Count();i++) if(pred[nextmaxint->node[i].predno]->flag) {
//CPred ex(i,pred[nextmaxint->node[i].predno]->cov);
CPred ex(i,abs(pred[nextmaxint->node[i].predno]->tlen)*pred[nextmaxint->node[i].predno]->cov);
exord.Add(ex); //exord only remembers the non-false predictions
//covsum+=pred[nextmaxint->node[i].predno]->cov; // priority based on cov/bp
//covsum+=pred[nextmaxint->node[i].predno]->tlen*pred[nextmaxint->node[i].predno]->cov; // priority based on number of bases covered
covsum+=nextmaxint->node[i].exoncov; // priority based on exoncov
}
if(covsum) {
float totalcov=get_cov(1,nextmaxint->start-bundleData->start,nextmaxint->end-bundleData->start,bpcov);
exord.Sort(predordCmp); // sort exons from the most highest coverage to lowest
int i=exord[0].predno;
int n=nextmaxint->node[i].predno;
int e=nextmaxint->node[i].exonno;
//float exoncov=totalcov*pred[n]->tlen*pred[n]->cov/covsum; // priority based on number of bases covered
//float exoncov=totalcov*pred[n]->cov/covsum; // priority based on per bp cov
float exoncov=totalcov*nextmaxint->node[i].exoncov/covsum; // priority based on per bp cov
bool shortmax=false;
if(pred[n]->tlen>0) {
pred[n]->exoncov[e]+=exoncov;
if(mixedMode && exord.Count()==1) {
if(pred[n]->exons.Count()==1 && pred[n]->cov<singlethr/DROP) pred[n]->flag=false; // stricter criteria for random single exon short-read genes
else if(pred[n]->exons.Count()==2 && pred[n]->cov<singlethr*DROP) pred[n]->flag=false; // stricter criteria for random two-exon short-read genes
}
shortmax=true;
}
//fprintf(stderr,"pred[%d]->exoncov[%d]=%f exoncov=%f totalcov=%f covsum=%f\n",n,e,pred[n]->exoncov[e],exoncov,totalcov,covsum);
float usedcov=pred[n]->cov;
//fprintf(stderr,"maxint=%d-%d has first pred[%d] with cov=%f usedcov=%f\n",nextmaxint->start,nextmaxint->end,n,pred[n]->cov,usedcov);
for(int j=1;j<exord.Count();j++) {
i=exord[j].predno;
n=nextmaxint->node[i].predno;
float allowedfrac=isofrac;
if(mixedMode) {
if(pred[n]->cov>1/ERROR_PERC) allowedfrac*=DROP;
else if(pred[n]->tlen>0) {
allowedfrac/=DROP; // stricter criteria for short read data
if(shortmax) allowedfrac=DROP; // very strict criteria if short reads are maximal
}
}
if(!pred[n]->t_eq && (pred[n]->cov<allowedfrac*usedcov || (pred[n]->cov<lowcov && pred[n]->cov<lowisofrac*usedcov) ||
(pred[n]->exons.Count()==1 && pred[n]->cov<usedcov) || pred[n]->cov<1 ||
(pred[n]->exons.Count()==2 && (pred[n]->cov<lowcov || (pred[n]->geneno>=0 && pred[n]->cov<ERROR_PERC*usedcov))))) {
adjust=true;
//fprintf(stderr,"flaseflag: pred[%d] has low cov=%f percentage from usedcoverage=%f < %f\n",n,pred[n]->cov,usedcov,allowedfrac*usedcov);
pred[n]->flag=false;
}
else {
e=nextmaxint->node[i].exonno;
//exoncov=totalcov*pred[n]->cov/covsum; // priority based on per bp cov
//float exoncov=totalcov*pred[n]->tlen*pred[n]->cov/covsum; // priority based on number of bases covered
exoncov=totalcov*nextmaxint->node[i].exoncov/covsum; // priority based on per bp cov
if(pred[n]->tlen>0) pred[n]->exoncov[e]+=exoncov;
usedcov+=pred[n]->cov;
//fprintf(stderr,"maxint=%d-%d add pred[%d]->cov=%f to usedcov=%f\n",nextmaxint->start,nextmaxint->end,n,pred[n]->cov,usedcov);
}
}
}
}
nextmaxint=nextmaxint->next;
}
//for(int p=0;p<npred;p++) {
// int n=predord[p].predno;
for(int n=0;n<npred;n++) {
if(pred[n]->flag && pred[n]->tlen>0) {
// compute prediction coverage first
pred[n]->cov=0;
for(int i=0;i<pred[n]->exons.Count();i++) {
pred[n]->cov+=pred[n]->exoncov[i];
pred[n]->exoncov[i]/=pred[n]->exons[i].len();
}
pred[n]->cov/=pred[n]->tlen;
if(!pred[n]->t_eq) {
if(pred[n]->cov<1 || (pred[n]->exons.Count()==1 && pred[n]->cov<singlethr)) {
//if(pred[n]->cov<readthr || (pred[n]->exons.Count()==1 && pred[n]->cov<singlethr) ) {
pred[n]->flag=false;
//fprintf(stderr,"falseflag: pred[%d]->cov=%f eliminated due to low coverage\n",n,pred[n]->cov);
adjust=true;
}
}
//predord[p].cov=pred[n]->tlen*pred[n]->cov; ** use this
//predord[p].cov=pred[n]->cov;
//fprintf(stderr,"coverage of pred[%d]=%f\n",n,pred[n]->cov);
}
}
}
}
// eliminate possible polymerase run-offs
for(int i=0;i<npred;i++) if(pred[i]->flag && pred[i]->exons.Count()==1 && !pred[i]->t_eq) { // only check prediction that can be deleted
int p=i-1;
while(p>-1 && !pred[p]->flag) p--;
int c=i+1;
while(c<npred && !pred[c]->flag) c++;
uint runoff=runoffdist;
//if(mixedMode && pred[i]->tlen<0) runoff=0;
if((p<0 || pred[p]->end<pred[i]->start) && (c==npred || pred[c]->start>pred[i]->end)) { // pred[i] alone between two predictions
//if(pred[i]->exons.Count()==1) { // single exon prediction -> check if I can delete it
if(p>-1 && pred[p]->exons.Count()>1 && pred[p]->end+runoff>=pred[i]->start) { // previous prediction is nearby
float exoncov=get_cov(1,pred[p]->exons.Last().start-bundleData->start,pred[p]->exons.Last().end-bundleData->start,bpcov);
if(pred[i]->cov<exoncov+singlethr) {
pred[i]->flag=false;
//fprintf(stderr,"falseflag: elim pred[%d] as possible polymerase runoff\n",i);
}
}
if(pred[i]->flag && c<npred && pred[c]->exons.Count()>1 && pred[i]->end+runoff>=pred[c]->start) { // next prediction is nearby
float exoncov=get_cov(1,pred[c]->exons[0].start-bundleData->start,pred[c]->exons[0].end-bundleData->start,bpcov);
if(pred[i]->cov<exoncov+singlethr) {
pred[i]->flag=false;
//fprintf(stderr,"falseflag: elim pred[%d] as possible polymerase runoff\n",i);
}
}
//}
// else if pred[i]->cov<singlethr -> here I would do the stiching of partial genes
}
}
// assign gene numbers
GVec<int> genes; // for each prediction remembers it's geneno
genes.Resize(npred,-1);
GVec<int> transcripts; // for each gene remembers how many transcripts were printed
//pred.Sort();
for(int i=0;i<npred;i++)
if(pred[i]->flag && !eonly) {
if ( pred[i]->cov<1 ||
(!pred[i]->t_eq && (pred[i]->cov<readthr || (mixedMode && guided && pred[i]->cov<singlethr)))) {
// ---- or forget about eonly and just consider (!pred[i]->t_eq && pred[i]->cov<1)
//if ( !pred[i]->t_eq && (pred[i]->cov<readthr || (mixedMode && guided && pred[i]->cov<singlethr)) ) {
pred[i]->flag=false;
//fprintf(stderr,"falseflag: elim pred[%d] due to low cov=%f\n",i,pred[i]->cov);
continue;
}
//fprintf(stderr,"check pred i=%d with end=%d and next start=%d\n",i,pred[i]->end,pred[i+1]->start);
int ci=color[i];
while(ci!=color[ci]) { ci=color[ci];color[i]=ci;}
int j=i+1;
while(j<npred && pred[i]->end>=pred[j]->start) {
//fprintf(stderr,"... check pred j=%d\n",j);
if(pred[j]->flag && pred[i]->strand==pred[j]->strand && overlap[npred*i+j]) {
if(!pred[j]->t_eq && pred[j]->cov<readthr) {
pred[j]->flag=false;
//fprintf(stderr,"falseflag: elim pred[%d] due to low cov=%f\n",j,pred[j]->cov);
j++;
continue;
}
//fprintf(stderr,"pred %d overlaps pred %d\n",j,i);
int cj=color[j];
while(cj!=color[cj]) { cj=color[cj];color[j]=cj;}
if(cj<ci) {
color[ci]=cj;
color[i]=cj;
}
else if(ci<cj){
color[cj]=ci;
color[j]=ci;
}
}
j++;
}
}
for(int n=0;n<npred;n++) if(pred[n]->flag && genes[n]==-1) { // no gene was assigned to this prediction
int cn=color[n];
genes[n]=transcripts.Count();
transcripts.cAdd(0);
while(cn!=color[cn]) { cn=color[cn];color[n]=cn;}
uint currentend=pred[n]->end;
int m=n+1;
while(m<npred && pred[m]->start<=currentend) {
if(pred[m]->flag) {
int cm=color[m];
while(cm!=color[cm]) { cm=color[cm];color[m]=cm;}
if(cn==cm) {
if(genes[m]>-1) GError("Overlapping predictions with different gene number!\n");
genes[m]=genes[n];
}
if(pred[m]->end>currentend) currentend=pred[m]->end;
}
m++;
}
}
for(int n=0;n<npred;n++) if(pred[n]->flag){
/*
{ // DEBUG ONLY
fprintf(stderr,"\nprint prediction %d with cov=%f len=%d",n,pred[n]->cov,pred[n]->tlen);
if(pred[n]->flag) fprintf(stderr," with true flag");
fprintf(stderr," with geneno=%d and exons:",pred[n]->geneno);
for(int i=0;i<pred[n]->exons.Count();i++) fprintf(stderr," cov=%f len=%d",pred[n]->exoncov[i],pred[n]->exons[i].len());
fprintf(stderr,"\n");
}
*/
transcripts[genes[n]]++;
pred[n]->geneno=genes[n]+geneno+1;
uint t_id=0;
if (pred[n]->t_eq && pred[n]->t_eq->uptr) {
t_id = ((RC_TData*)pred[n]->t_eq->uptr)->t_id;
}
pred[n]->tlen=abs(pred[n]->tlen);
//fprintf(f_out,"%d %d %d %.6f %.6f\n",pred[n]->exons.Count()+1,pred[n]->tlen, t_id, pred[n]->frag,pred[n]->cov);
fprintf(f_out,"1 %d %d %d %.6f\n",pred[n]->exons.Count()+1,pred[n]->tlen, t_id,pred[n]->cov);
GStr geneid(label, 10);geneid+='.';geneid+=pred[n]->geneno;
GStr trid(geneid.chars(), 10); trid+='.';trid+=transcripts[genes[n]];
if(eonly && pred[n]->t_eq && pred[n]->t_eq->getGeneID()) geneid=pred[n]->t_eq->getGeneID();
if(eonly && pred[n]->t_eq) trid=pred[n]->t_eq->getID();
fprintf(f_out,"%s\tStringTie\ttranscript\t%d\t%d\t1000\t%c\t.\tgene_id \"%s\"; transcript_id \"%s\"; ",
refname.chars(),pred[n]->start,pred[n]->end,pred[n]->strand,geneid.chars(),trid.chars());
//fprintf(stderr,"print pred[%d] gene_id %s transcript_id %s\n",n,geneid.chars(),trid.chars());
if(pred[n]->t_eq) {
if(!eonly) fprintf(f_out,"reference_id \"%s\"; ",pred[n]->t_eq->getID());
if (!eonly && pred[n]->t_eq->getGeneID())
fprintf(f_out,"ref_gene_id \"%s\"; ",pred[n]->t_eq->getGeneID());
if (pred[n]->t_eq->getGeneName())
fprintf(f_out,"ref_gene_name \"%s\"; ",pred[n]->t_eq->getGeneName());
}
fprintf(f_out,"cov \"%.6f\";\n",pred[n]->cov);
for(int j=0;j<pred[n]->exons.Count();j++) {
fprintf(f_out,"%s\tStringTie\texon\t%d\t%d\t1000\t%c\t.\tgene_id \"%s\"; transcript_id \"%s\"; exon_number \"%d\"; ",
refname.chars(),pred[n]->exons[j].start,pred[n]->exons[j].end,pred[n]->strand,geneid.chars(),
trid.chars(),j+1); // maybe add exon coverage here
if(pred[n]->t_eq) {
if(!eonly) fprintf(f_out,"reference_id \"%s\"; ",pred[n]->t_eq->getID());
if (!eonly && pred[n]->t_eq->getGeneID())
fprintf(f_out,"ref_gene_id \"%s\"; ",pred[n]->t_eq->getGeneID());
if (pred[n]->t_eq->getGeneName())
fprintf(f_out,"ref_gene_name \"%s\"; ",pred[n]->t_eq->getGeneName());
}
fprintf(f_out,"cov \"%.6f\";\n",pred[n]->exoncov[j]);
}
// now deal with the genes
// predicted:
int gno=genes[n];
//fprintf(stderr,"gno=%d\n",gno);
if(!eonly) {
if(gno>=predgene.Count()) { // I did not see this gene before
CGene g(pred[n]->start,pred[n]->end,pred[n]->strand);
for(int i=0;i<pred[n]->exons.Count();i++) {
g.exons.Add(pred[n]->exons[i]);
}
g.cov+=pred[n]->cov*pred[n]->tlen;
g.covsum+=pred[n]->cov;
//fprintf(stderr,"3:add pred[%d]'s coverage=%g to gene cov\n",n,pred[n]->cov);
predgene.Add(g);
}
else { // I've seen this gene before
if(pred[n]->start<predgene[gno].start) predgene[gno].start=pred[n]->start;
if(pred[n]->end>predgene[gno].end) predgene[gno].end=pred[n]->end;
merge_exons(predgene[gno],pred[n]->exons);
predgene[gno].cov+=pred[n]->cov*pred[n]->tlen;
predgene[gno].covsum+=pred[n]->cov;
//fprintf(stderr,"4:add pred[%d]'s coverage=%g to gene cov\n",n,pred[n]->cov);
}
}
// annotated
if(pred[n]->t_eq && (geneabundance ||eonly)) {
GStr gid(pred[n]->t_eq->getGeneID());
if(gid.is_empty()) gid=pred[n]->t_eq->getGeneName();
if(!gid.is_empty()) {
gid+=pred[n]->strand;
const int *ng=hashgene[gid.chars()];
if(ng) { // this should always be true because we parsed all predictions in printResults
gno=*ng;
refgene[gno].cov+=pred[n]->cov*pred[n]->tlen;
refgene[gno].covsum+=pred[n]->cov;
}
else {
//fprintf(stderr,"1:add pred[%d]'s coverage=%g\n",n,pred[n]->cov);
bundleData->sum_cov+=pred[n]->cov; // I am adding to cov_sum the reference transcript's coverage --> isn't this double counting?
}
}
else {
//fprintf(stderr,"2:add pred[%d]'s coverage=%g\n",n,pred[n]->cov);
bundleData->sum_cov+=pred[n]->cov;
}
}
}
// clean-up maxint
while(maxint) {
nextmaxint=maxint->next;
delete maxint;
maxint=nextmaxint;
}
geneno+=transcripts.Count();
return(geneno);
}
void add_pred(GList<CPrediction>& pred,int x,int y, float cov) { // add single exon prediction y to prediction x
if(pred[y]->start<pred[x]->exons[0].end) { // add y to first exon in x
int addlen=0;
if(pred[y]->end<pred[x]->start) // predictions do not overlap
addlen=pred[x]->start-pred[y]->end-1;
pred[x]->cov=(pred[x]->cov*abs(pred[x]->tlen)+cov*abs(pred[y]->tlen))/(abs(pred[x]->tlen)+addlen+abs(pred[y]->tlen));
pred[x]->exoncov[0]= (pred[x]->exoncov[0]*(pred[x]->exons[0].end-pred[x]->exons[0].start+1)+
cov*abs(pred[y]->tlen))/(pred[x]->exons[0].end-pred[x]->exons[0].start+1+addlen+abs(pred[y]->tlen));
if(pred[y]->start<pred[x]->start) {
pred[x]->start=pred[y]->start;
pred[x]->exons[0].start=pred[y]->start;
}
if(pred[x]->tlen<0) pred[x]->tlen-=addlen;
else pred[x]->tlen+=addlen;
}
else { // add y to last exon in x
int addlen=0;
if(pred[x]->end<pred[y]->start) // predictions do not overlap
addlen=pred[y]->start-pred[x]->end-1;
pred[x]->cov=(pred[x]->cov*abs(pred[x]->tlen)+cov*abs(pred[y]->tlen))/(abs(pred[x]->tlen)+addlen+abs(pred[y]->tlen));
pred[x]->exoncov.Last()= (pred[x]->exoncov.Last()*(pred[x]->exons.Last().end-pred[x]->exons.Last().start+1)+
cov*abs(pred[y]->tlen))/(pred[x]->exons.Last().end-pred[x]->exons.Last().start+1+addlen+abs(pred[y]->tlen));
if(pred[x]->end<pred[y]->end) {
pred[x]->end=pred[y]->end;
pred[x]->exons.Last().end=pred[y]->end;
}
if(pred[x]->tlen<0) pred[x]->tlen-=addlen;
else pred[x]->tlen+=addlen;
}
//pred[x]->frag+=pred[y]->frag;
}
bool equal_strand(CPrediction *p1,CPrediction *p2) {
if(p1->strand==p2->strand || p2->strand=='.') return true;
if(p1->strand=='.') { p1->strand=p2->strand; return true;}
return false;
}
int printMergeResults(BundleData* bundleData, int geneno, GStr& refname) {
GList<CPrediction>& pred = bundleData->pred;
int npred=pred.Count();
// this version sorts the predictions according to their start and only eliminates predictions that are overlaped by others that are more abundant within the threshold
GVec<bool> keep(npred,bool(true));
pred.setSorted(predCmp);
for(int n=0;n<npred;n++) if(keep[n]){
//fprintf(stderr,"Evaluate prediction[%d] of cov %g %c:",n,pred[n]->cov,pred[n]->strand);
//for(int e=0;e<pred[n]->exons.Count();e++) fprintf(stderr," %d-%d",pred[n]->exons[e].start,pred[n]->exons[e].end);
//fprintf(stderr,"\n");
int m=n+1;
while(m<npred && pred[m]->start<=pred[n]->end+bundledist) { // prediction m overlaps prediction n or is very close by
if(keep[m] && equal_strand(pred[n],pred[m])) {
if(pred[m]->start<=pred[n]->end) { // predicions actually overlap
if(!pred[n]->t_eq && ((pred[m]->exons.Count()>1 && pred[n]->cov<isofrac*pred[m]->cov) ||
(pred[n]->exons.Count()==1 && pred[n]->cov<pred[m]->cov))) { // only eliminate prediction if it's not guide
keep[n]=false;
//fprintf(stderr," pred[%d] eliminated by pred[%d]\n",n,m);
break;
}
if(!pred[m]->t_eq && ((pred[n]->exons.Count()>1 && pred[m]->cov<isofrac*pred[n]->cov) ||
(pred[m]->exons.Count()==1 && pred[m]->cov<pred[n]->cov))) // don't believe an intronic single exon prediction
keep[m]=false;
}
else // pred[m] is within bundledist of pred[n] -> see if we can merge them
if((pred[n]->exons.Count()==1 || pred[m]->exons.Count()==1)) {
//fprintf(stderr," pred[%d] of len=%d eliminated pred[%d] of len=%d and cov %g %c:",n,pred[n]->tlen,m,pred[m]->tlen,pred[m]->cov,pred[m]->strand);
//for(int e=0;e<pred[m]->exons.Count();e++) fprintf(stderr," %d-%d",pred[m]->exons[e].start,pred[m]->exons[e].end);
//fprintf(stderr,"\n");
if(pred[n]->exons.Count()==1 && pred[m]->exons.Count()==1 && !pred[n]->t_eq && !pred[m]->t_eq) { // merge predictions if both single exons (code also works if only one is single exon
keep[m]=false;
pred[n]->cov=pred[n]->cov*pred[n]->tlen+pred[m]->cov*pred[m]->tlen;
pred[n]->tlen+=pred[m]->tlen+pred[m]->start-pred[n]->end-1;
pred[n]->cov/=pred[n]->tlen;
//fprintf(stderr," and got new len=%d and new cov=%g\n",pred[n]->tlen,pred[n]->cov);
pred[n]->end=pred[m]->end;
if(pred[m]->exons.Count()==1) {
pred[n]->exons.Last().end=pred[n]->end;
}
else { // pred[m] has more than one exon => pred[n] has one exon
pred[n]->exons[0].end=pred[m]->exons[0].end;
for(int e=1;e<pred[m]->exons.Count();e++) pred[n]->exons.Add(pred[m]->exons[e]);
}
}
else {
if(pred[n]->exons.Count()==1 && !pred[n]->t_eq && pred[n]->cov<pred[m]->cov) { // polymerase run-on ?
keep[n]=false;
break;
}
while(m<npred && pred[m]->exons.Count()==1 && !pred[m]->t_eq && pred[m]->cov<pred[n]->cov && equal_strand(pred[n],pred[m])) { // polymerase run-on ?
keep[m]=false;
m++;
}
}
}
}
m++;
}
}
int n=0;
while(n<npred) {
if(keep[n]){
uint currentend=pred[n]->end;
int t=0;
int m=n;
while(m<npred && pred[m]->start<=currentend) {
if(keep[m] && pred[m]->geneno ==pred[n]->geneno) { // this is a prediction worth printing
if(!t) geneno++;
t++;
if(pred[m]->end>currentend) currentend=pred[m]->end;
GStr trid("", 64);
if(pred[m]->t_eq) trid=pred[m]->t_eq->getID();
else {
trid=label+'.';
trid+=geneno;
trid+='.';
trid+=t;
}
fprintf(f_out,"%s\tStringTie\ttranscript\t%d\t%d\t1000\t%c\t.\tgene_id \"%s.%d\"; transcript_id \"%s\"; ",
refname.chars(),pred[m]->start,pred[m]->end,pred[m]->strand,label.chars(),geneno,
trid.chars());
if(pred[m]->t_eq) {
//fprintf(f_out,"reference_id \"%s\"; ",pred[m]->t_eq->getID());
if (pred[m]->t_eq->getGeneName())
fprintf(f_out,"gene_name \"%s\"; ",pred[m]->t_eq->getGeneName());
if (pred[m]->t_eq->getGeneID())
fprintf(f_out,"ref_gene_id \"%s\"; ",pred[m]->t_eq->getGeneID());
}
if(includecov) fprintf(f_out,"cov \"%g\"; ",pred[m]->cov);
if(enableNames) fprintf(f_out,"input_transcripts \"%s\";\n",pred[m]->mergename.chars());
else fprintf(f_out,"\n");
for(int j=0;j<pred[m]->exons.Count();j++) {
fprintf(f_out,"%s\tStringTie\texon\t%d\t%d\t1000\t%c\t.\tgene_id \"%s.%d\"; transcript_id \"%s\"; exon_number \"%d\"; ",
refname.chars(),pred[m]->exons[j].start,pred[m]->exons[j].end,pred[m]->strand,label.chars(),geneno,
trid.chars(),j+1);
if(pred[m]->t_eq) {
//fprintf(f_out,"reference_id \"%s\"; ",pred[m]->t_eq->getID());
if (pred[m]->t_eq->getGeneName())
fprintf(f_out,"gene_name \"%s\"; ",pred[m]->t_eq->getGeneName());
if (pred[m]->t_eq->getGeneID())
fprintf(f_out,"ref_gene_id \"%s\"; ",pred[m]->t_eq->getGeneID());
}
fprintf(f_out,"\n");
}
keep[m]=false; // no need to print it again
} // end if keep[m]
m++;
} // end while(m<npred ...)
} // end if keep[n]
n++;
}
return(geneno);
}
void find_endpoints(int refstart,uint start,uint end,GVec<float>* bpcov, uint &newstart, uint &newend) {
newstart=start+longintronanchor-1-(uint)refstart;
newend=end-longintronanchor+1-(uint)refstart;
start-=(uint)refstart;
end-=(uint)refstart;
float maxcov=get_cov(1,start,newstart,bpcov)/(newstart-start+1)-get_cov(1,newstart+1,newstart+longintronanchor,bpcov)/longintronanchor+
get_cov(1,newend,end,bpcov)/(end-newend+1)-get_cov(1,newend-longintronanchor,newend-1,bpcov)/longintronanchor;
uint istart=newstart+1;
uint iend=newend-1;
while(istart<iend) {
float icov=get_cov(1,start,istart,bpcov)/(istart-start+1)-get_cov(1,istart+1,istart+longintronanchor,bpcov)/longintronanchor+
get_cov(1,iend,end,bpcov)/(end-iend+1)-get_cov(1,iend-longintronanchor,iend-1,bpcov)/longintronanchor;
if(icov>maxcov) {
newstart=istart;
newend=iend;
maxcov=icov;
}
istart++;
iend--;
}
newstart+=(uint)refstart;
newend+=(uint)refstart;
}
/*
uint find_midhash(int refstart,int start,int end,GVec<float>* bpcov) {
//if(end-refstart>bpcov[1].Count()) return(0);
uint midpoint=start+longintronanchor-refstart;
float mincov=get_cov(1,midpoint,midpoint,bpcov);
start-=refstart;
end-=refstart;
float maxcov=fabs(get_cov(1,start,midpoint,bpcov)/(midpoint-start+1)-get_cov(1,midpoint+1,end,bpcov)/(end-midpoint));
int i=midpoint+1;
int endcheck=end-longintronanchor;
while(i<endcheck) {
float newcov=get_cov(1,i,i,bpcov);
if(newcov<mincov) {
midpoint=(uint)i;
mincov=newcov;
maxcov=fabs(get_cov(1,start,midpoint,bpcov)/(midpoint-start+1)-get_cov(1,midpoint+1,end,bpcov)/(end-midpoint));
if(!newcov) break;
}
else if(newcov==mincov) { // check if there is a better place to split; longreads modification
float icov=fabs(get_cov(1,start,i,bpcov)/(i-start+1)-get_cov(1,i+1,end,bpcov)/(end-i));
if(icov>maxcov) {
midpoint=(uint)i;
maxcov=icov;
}
}
i++;
}
midpoint+=refstart;
return(midpoint);
}
uint find_midhash(int refstart,int start,int end,GVec<float>* bpcov) {
if(end-refstart>bpcov[1].Count()) return(0);
uint midpoint=start+longintronanchor;
float mincov=get_cov(1,midpoint-refstart,midpoint-refstart,bpcov);
end-=longintronanchor;
int i=midpoint+1;
while(i<end) {
float newcov=get_cov(1,i-refstart,i-refstart,bpcov);
if(newcov<mincov) {
midpoint=(uint)i;
mincov=newcov;
if(!newcov) break;
}
i++;
}
return(midpoint);
}
*/
int printResults(BundleData* bundleData, int geneno, GStr& refname) {
uint runoffdist=200;
if(longreads) runoffdist=0;
if(bundledist>runoffdist) runoffdist=bundledist;
// print transcripts including the necessary isoform fraction cleanings
GList<CPrediction>& pred = bundleData->pred;
/*
{ // DEBUG ONLY
fprintf(stderr,"Pred set before sorting:\n");
for(int i=0;i<pred.Count();i++) {
if(pred[i]->t_eq) fprintf(stderr,"%s ",pred[i]->t_eq->getID());
fprintf(stderr,"pred[%d]:%d-%d (cov=%f, readcov=%f, strand=%c):",i,pred[i]->start,pred[i]->end,pred[i]->cov,pred[i]->tlen*pred[i]->cov,pred[i]->strand);
for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %d-%d",pred[i]->exons[j].start,pred[i]->exons[j].end);
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
*/
int npred=pred.Count();
pred.setSorted(predCmp);
GVec<CGene> predgene;
int refstart=bundleData->start;
GVec<float>* bpcov = bundleData->bpcov;
int startgno=geneno+1;
if(rawreads) { //-R mode
// assign gene numbers
GVec<int> genes; // for each prediction remembers it's geneno
genes.Resize(npred,-1);
GVec<int> transcripts; // for each gene remembers how many transcripts were printed
GVec<int> color;
for(int i=0;i<npred;i++) color.Add(i);
for(int i=0;i<npred-1;i++) if(pred[i]->flag) {
if(pred[i]->cov<readthr) {
pred[i]->flag=false;
//fprintf(stderr,"falseflag: elim pred[%d] due to low cov=%f\n",i,pred[i]->cov);
continue;
}
//fprintf(stderr,"check pred i=%d with end=%d and next start=%d\n",i,pred[i]->end,pred[i+1]->start);
int ci=color[i];
while(ci!=color[ci]) { ci=color[ci];color[i]=ci;}
int j=i+1;
while(j<npred && pred[i]->end>=pred[j]->start) {
//fprintf(stderr,"... check pred j=%d\n",j);
if(pred[j]->cov<readthr) {
pred[j]->flag=false;
//fprintf(stderr,"falseflag: elim pred[%d] due to low cov=%f\n",j,pred[j]->cov);
j++;
continue;
}
if(pred[j]->flag && pred[i]->strand==pred[j]->strand) {
// check overlap betweeg genes
bool overlap=false;
int m=0;
for(int k=0; k<pred[i]->exons.Count();k++) {
while(m<pred[j]->exons.Count() && pred[j]->exons[m].end<pred[i]->exons[k].start) m++;
if(m==pred[j]->exons.Count()) break;
if(pred[j]->exons[m].overlap(pred[i]->exons[k])) {
overlap=true;
break;
}
m++;
}
if(overlap) {
//fprintf(stderr,"pred %d overlaps pred %d\n",j,i);
int cj=color[j];
while(cj!=color[cj]) { cj=color[cj];color[j]=cj;}
if(cj<ci) {
color[ci]=cj;
color[i]=cj;
}
else if(ci<cj){
color[cj]=ci;
color[j]=ci;
}
}
}
j++;
}
}
for(int n=0;n<npred;n++) if(pred[n]->flag && genes[n]==-1) { // no gene was assigned to this prediction
int cn=color[n];
genes[n]=transcripts.Count();
transcripts.cAdd(0);
while(cn!=color[cn]) { cn=color[cn];color[n]=cn;}
uint currentend=pred[n]->end;
int m=n+1;
while(m<npred && pred[m]->start<=currentend) {
if(pred[m]->flag) {
int cm=color[m];
while(cm!=color[cm]) { cm=color[cm];color[m]=cm;}
if(cn==cm) {
if(genes[m]>-1) GError("Overlapping predictions with different gene number!\n");
genes[m]=genes[n];
}
if(pred[m]->end>currentend) currentend=pred[m]->end;
}
m++;
}
}
for(int n=0;n<npred;n++) if(pred[n]->flag){
/*
{ // DEBUG ONLY
fprintf(stderr,"print prediction %d with cov=%f len=%d",n,pred[n]->cov,pred[n]->tlen);
if(pred[n]->flag) fprintf(stderr," with true flag");
fprintf(stderr," with geneno=%d and exons:",pred[n]->geneno);
for(int i=0;i<pred[n]->exons.Count();i++) fprintf(stderr," len=%d",pred[n]->exons[i].len());
fprintf(stderr,"\n");
}
*/
transcripts[genes[n]]++;
pred[n]->geneno=genes[n]+geneno+1;
//fprintf(f_out,"%d %d %d %.6f %.6f\n",pred[n]->exons.Count()+1,pred[n]->tlen, t_id, pred[n]->frag,pred[n]->cov);
fprintf(f_out,"1 %d %d 0 %.6f\n",pred[n]->exons.Count()+1,pred[n]->tlen,pred[n]->cov);
GStr geneid(label);geneid+='.';geneid+=pred[n]->geneno;
GStr trid(geneid.chars()); trid+='.';trid+=transcripts[genes[n]];
fprintf(f_out,"%s\tStringTie\ttranscript\t%d\t%d\t1000\t%c\t.\tgene_id \"%s\"; transcript_id \"%s\"; ",
refname.chars(),pred[n]->start,pred[n]->end,pred[n]->strand,geneid.chars(),trid.chars());
//fprintf(stderr,"print pred[%d] gene_id %s transcript_id %s\n",n,geneid.chars(),trid.chars());
fprintf(f_out,"cov \"%.6f\";\n",pred[n]->cov);
for(int j=0;j<pred[n]->exons.Count();j++) {
fprintf(f_out,"%s\tStringTie\texon\t%d\t%d\t1000\t%c\t.\tgene_id \"%s\"; transcript_id \"%s\"; exon_number \"%d\"; ",
refname.chars(),pred[n]->exons[j].start,pred[n]->exons[j].end,pred[n]->strand,geneid.chars(),
trid.chars(),j+1); // maybe add exon coverage here
fprintf(f_out,"\n");
}
// now deal with the genes
// predicted:
int gno=genes[n];
//fprintf(stderr,"gno=%d\n",gno);
if(gno>=predgene.Count()) { // I did not see this gene before
CGene g(pred[n]->start,pred[n]->end,pred[n]->strand);
for(int i=0;i<pred[n]->exons.Count();i++) {
g.exons.Add(pred[n]->exons[i]);
}
g.cov+=pred[n]->cov*pred[n]->tlen;
g.covsum+=pred[n]->cov;
//fprintf(stderr,"3:add pred[%d]'s coverage=%g to gene cov\n",n,pred[n]->cov);
predgene.Add(g);
}
else { // I've seen this gene before
if(pred[n]->start<predgene[gno].start) predgene[gno].start=pred[n]->start;
if(pred[n]->end>predgene[gno].end) predgene[gno].end=pred[n]->end;
merge_exons(predgene[gno],pred[n]->exons);
predgene[gno].cov+=pred[n]->cov*pred[n]->tlen;
predgene[gno].covsum+=pred[n]->cov;
//fprintf(stderr,"4:add pred[%d]'s coverage=%g to gene cov\n",n,pred[n]->cov);
}
}
geneno+=transcripts.Count();
for(int i=0;i<predgene.Count();i++) {
float cov=0;
int s=1; // strand of gene
if(predgene[i].strand=='+') s=2;
else if(predgene[i].strand=='-') s=0;
int glen=0;
for(int j=0;j<predgene[i].exons.Count();j++) { // evaluate unused coverage
glen+=predgene[i].exons[j].len();
int start=(int)predgene[i].exons[j].start-refstart;
int end=(int)predgene[i].exons[j].end-refstart+1;
// predgene start and end might have been also adjusted to reflect the annotation
if(start<0) start=0;
if(end>=bpcov[1].Count()) end=bpcov[1].Count()-1;
// cummulative bpcov
float localcov[3]={0,0,0};
for(int i=0;i<3;i++) {
if(end) localcov[i]=get_cov(i,start,end-1,bpcov);
}
switch(s) {
case 0:
if(localcov[2]) cov+=localcov[0]+(localcov[1]-localcov[0]-localcov[2])*localcov[0]/(localcov[0]+localcov[2]);
else cov+=localcov[1];
break;
case 1: cov+=localcov[1]-localcov[2]-localcov[0];break;
case 2:
if(localcov[0]) cov+=localcov[2]+(localcov[1]-localcov[0]-localcov[2])*localcov[2]/(localcov[0]+localcov[2]);
else cov+=localcov[1];
break;
}
}
predgene[i].cov=cov-predgene[i].cov; // THIS is the read coverage that is left for the genes after all the predictions were taken into account
if(predgene[i].cov>epsilon) predgene[i].covsum+=predgene[i].cov/glen;
bundleData->sum_cov+=predgene[i].covsum;
if(geneabundance) {
predgene[i].cov=cov/glen; // only if I want to store the real gene coverage
fprintf(f_out,"0 1 %d 0 %.6f\n",glen, predgene[i].covsum);
fprintf(f_out,"%s.%d\t",label.chars(),startgno+i);
fprintf(f_out,"-\t");
//fprintf(f_out,"%s\t%c\t%d\t%d\t%d\t%.6f\n",refname.chars(),predgene[i].strand,predgene[i].start,predgene[i].end,glen,predgene[i].cov);
fprintf(f_out,"%s\t%c\t%d\t%d\t%.6f\n",refname.chars(),predgene[i].strand,predgene[i].start,predgene[i].end,predgene[i].cov);
}
}
return(geneno);
} // ^^^^ rawreads processing mode (-R)
/*
{ // DEBUG ONLY
fprintf(stderr,"Initial set:\n");
for(int i=0;i<pred.Count();i++) {
if(pred[i]->t_eq) fprintf(stderr,"%s ",pred[i]->t_eq->getID());
fprintf(stderr,"pred[%d]:%d-%d (cov=%f, readcov=%f, strand=%c):",i,pred[i]->start,pred[i]->end,pred[i]->cov,pred[i]->tlen*pred[i]->cov,pred[i]->strand);
for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %d-%d",pred[i]->exons[j].start,pred[i]->exons[j].end);
fprintf(stderr," (");
for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %f",pred[i]->exoncov[j]);
fprintf(stderr,")\n");
}
fprintf(stderr,"\n");
}
*/
bool preddel=false;
// this are needed for gene abundance estimations
GVec<CGene> refgene;
GHash<int> hashgene;
bool isintronguide=false;
// process predictions that equal the same single exon guide and stich them together
GPVec<GffObj>& guides = bundleData->keepguides;
if(guides.Count()) {
//fprintf(stderr,"guides count=%d\n",guides.Count());
// first create reference genes
int gno=0;
for(int i=0;i<guides.Count();i++) {
if(guides[i]->exons.Count()>1 && longreads) isintronguide=true;
if (eonly) { // if eonly I need to print all guides that were not printed yet
if (guides[i]->uptr && ((RC_TData*)guides[i]->uptr)->in_bundle<3) {
fprintf(f_out,"1 %d %d %d 0.0\n",guides[i]->exons.Count()+1,guides[i]->covlen, ((RC_TData*)guides[i]->uptr)->t_id);
fprintf(f_out, "%s\t%s\ttranscript\t%d\t%d\t.\t%c\t.\t",refname.chars(),
guides[i]->getTrackName(), guides[i]->start,guides[i]->end, guides[i]->strand);
if (guides[i]->getGeneID())
fprintf(f_out, "gene_id \"%s\"; ", guides[i]->getGeneID()); // this shouldn't come up empty
fprintf(f_out, "transcript_id \"%s\";",guides[i]->getID());
if (guides[i]->getGeneName())
fprintf(f_out, " ref_gene_name \"%s\";", guides[i]->getGeneName());
fprintf(f_out, " cov \"0.0\";\n");
for (int e=0;e<guides[i]->exons.Count();++e) {
fprintf(f_out,"%s\t%s\texon\t%d\t%d\t.\t%c\t.\t",refname.chars(),
guides[i]->getTrackName(), guides[i]->exons[e]->start, guides[i]->exons[e]->end, guides[i]->strand);
if (guides[i]->getGeneID())
fprintf(f_out, "gene_id \"%s\"; ", guides[i]->getGeneID());
fprintf(f_out,"transcript_id \"%s\"; exon_number \"%d\";",guides[i]->getID(), e+1);
if (guides[i]->getGeneName())
fprintf(f_out, " ref_gene_name \"%s\";", guides[i]->getGeneName());
fprintf(f_out, " cov \"0.0\";\n");
}
//((RC_TData*)guides[i]->uptr)->in_bundle=1;
}
}
GStr gid(guides[i]->getGeneID()); // geneid and strand should determine gene cluster; what if no geneid is present?
if(gid.is_empty()) {
gid=guides[i]->getGeneName();
}
if(!gid.is_empty()) {
gid+=guides[i]->strand;
const int *n=hashgene[gid.chars()];
if(n) { // I've seen the gene before
if(guides[i]->start<refgene[*n].start) refgene[*n].start=guides[i]->start;
if(guides[i]->end>refgene[*n].end) refgene[*n].end=guides[i]->end;
merge_exons(refgene[*n],guides[i]->exons);
}
else { // create gene and hash
hashgene.Add(gid.chars(),gno);
CGene g(guides[i]->start,guides[i]->end,guides[i]->strand,guides[i]->getGeneID(),guides[i]->getGeneName());
// now add the exons
for(int j=0;j<guides[i]->exons.Count();j++) {
GSeg ex(guides[i]->exons[j]->start,guides[i]->exons[j]->end);
g.exons.Add(ex);
}
refgene.Add(g);
gno++;
}
}
}
// this version is more inclusive by stiching together single exons to reference guides that overlap them, but doesn't print them -> this is still done later on
GVec< GVec<int> > reflink(npred); reflink.Resize(npred);
for(int n=0;n<npred;n++) {
if(pred[n] && pred[n]->t_eq) {
if(mixedMode && pred[n]->cov<DROP) { // need to be more strict with mixed data since we introduced the guides by default
pred[n]->flag=false;
continue;
}
//fprintf(stderr,"pred[%d]: start=%d end=%d ID=%s strand=%c refstrand=%c refstart=%d\n",n,pred[n]->start,pred[n]->end,pred[n]->t_eq->getID(),pred[n]->strand,pred[n]->t_eq->strand,pred[n]->t_eq->start);
// check if there are single exon on the left of the predicted transcript
int i=n-1;
while(i>=0 && pred[i]->start>=pred[n]->t_eq->start) {
//fprintf(stderr,"%d: excnot=%d end=%d start=%d str=%c\n",i,pred[i]->exons.Count(), pred[i]->end,pred[n]->start, pred[i]->strand);
if(pred[i]->exons.Count()==1 && pred[i]->end<pred[n]->start && (pred[i]->strand==pred[n]->strand || pred[i]->strand=='.')) {
if(!pred[i]->t_eq || !strcmp(pred[i]->t_eq->getID(),pred[n]->t_eq->getID())) reflink[i].Add(n);
}
if(!pred[i]->t_eq && pred[i]->end>pred[n]->start && pred[i]->cov<pred[n]->cov*ERROR_PERC) {
//fprintf(stderr,"1 set pred[%d] to false\n",i);
pred[i]->flag=false;
}
i--;
}
while(i>=0 && pred[i]->end>pred[n]->start){
if(!pred[i]->t_eq && pred[i]->cov<pred[n]->cov*ERROR_PERC)
pred[i]->flag=false;
i--;
}
// check if there are single exon on the right of the predicted transcript
i=n+1;
while(i<npred && pred[i]->start<pred[n]->t_eq->end) {
if(pred[i]->exons.Count()==1 && pred[i]->start>pred[n]->end && (pred[i]->strand==pred[n]->strand || pred[i]->strand=='.')) {
if(pred[i]->t_eq && !strcmp(pred[i]->t_eq->getID(),pred[n]->t_eq->getID())) { // same ID is pred[n]
reflink[i].Add(n);
}
else if(pred[i]->end<=pred[n]->t_eq->end && !pred[i]->t_eq) reflink[i].Add(n);
}
if(!pred[i]->t_eq && pred[i]->start<pred[n]->end && pred[i]->cov<pred[n]->cov*ERROR_PERC) {
//fprintf(stderr,"2 set pred[%d] to false\n",i);
pred[i]->flag=false;
}
i++;
}
while(i<npred && pred[i]->start<pred[n]->end) {
if(!pred[i]->t_eq && pred[i]->cov<pred[n]->cov*ERROR_PERC)
pred[i]->flag=false;
i++;
}
}
}
for(int n=0;n<npred;n++) {
//fprintf(stderr,"pred[%d] falseflag=%d reflink_cnt=%d\n",n,pred[n]->flag,reflink[n].Count());
if(pred[n]) {
if(reflink[n].Count()) {
int mindist=100000;
float sumcov=0;
uint start=0;
for(int i=0;i<reflink[n].Count();i++) {
int ri=reflink[n][i];
//fprintf(stderr,"pred[%d] is linked to pred[%d]\n",n,ri);
if(pred[ri]) {
int d;
if(pred[ri]->start<pred[n]->start) d= pred[n]->start-pred[ri]->end;
else d=pred[ri]->start-pred[n]->end;
if(d<mindist) {
mindist=d;
sumcov=pred[ri]->cov;
start=pred[ri]->start;
}
else if(d==mindist) sumcov+=pred[ri]->cov;
}
}
if(sumcov) {
for(int i=0;i<reflink[n].Count();i++) {
int ri=reflink[n][i];
if(pred[ri] && pred[ri]->start==start) add_pred(pred,ri,n,pred[n]->cov*pred[ri]->cov/sumcov);
}
// now replace pred[y] with null
//fprintf(stderr,"Replace pred[%d] with null\n",n);
CPrediction *p=pred[n];
pred.Forget(n);
delete p;
}
}
/*if(!del && !pred[n]->flag) {
CPrediction *p=pred[n];
pred.Forget(n);
delete p;
}*/
}
}
pred.Pack();
pred.Sort();
npred=pred.Count();
}
//preddel=false;
/* adaptive mode: stitch together nearby single predictions if not within trimming parameters */
//if(adaptive) { // only in adaptive mode I am storing all single transcripts
GHash<uint> starthash;
GHash<uint> endhash;
bool incomplete=false;
GStr id("", 32);
for(int n=0;n<npred-1;n++) {
//fprintf(stderr,"check pred[%d]:%d-%d:%c with noexon=%d and cov=%f\n",n,pred[n]->start,pred[n]->end,pred[n]->strand,pred[n]->exons.Count(),pred[n]->cov);
bool ndel=false;
if(!pred[n]->t_eq && (abs(pred[n]->tlen)<mintranscriptlen)) { ndel=true;}
else {
int m=n+1;
while(!ndel && m<npred && pred[m]->start<=pred[n]->end) {
if(pred[n]->strand==pred[m]->strand) {
if(equal_pred(pred,n,m)) {
if(pred[n]->t_eq && pred[m]->t_eq && pred[n]->t_eq!=pred[m]->t_eq) { m++; continue;} // both are equal but represent different transcripts
if(mixedMode && pred[n]->tlen*pred[m]->tlen<0) { // choose the larger one
if(pred[n]->t_eq) {
pred[m]->t_eq=pred[n]->t_eq;
pred[m]->flag=true; // make sure I do not delete the prediction
pred[n]->cov+=pred[m]->cov; // add coverage to annotated gene in this case
}
if(pred[n]->cov>pred[m]->cov) { // replace with higher coverage
pred[m]->start=pred[n]->start;
pred[m]->end=pred[n]->end;
pred[m]->cov=pred[n]->cov;
pred[m]->tlen=-abs(pred[n]->tlen); // here is to say structure is supported by long read --> might decrease precision
pred[m]->exons[0].start=pred[n]->exons[0].start;
pred[m]->exons.Last().end=pred[n]->exons.Last().end;
for(int k=0;k<pred[m]->exons.Count();k++) {
pred[m]->exoncov[k]=pred[n]->exoncov[k];
}
pred[m]->geneno=-abs(pred[m]->geneno);
}
//pred[m]->tlen=abs(pred[m]->tlen); // make sure the prediction is conserved as it is
ndel=true;
break;
}
if(pred[n]->exons.Count()==1) {
if(pred[m]->cov>ERROR_PERC*pred[n]->cov && pred[n]->cov>ERROR_PERC*pred[m]->cov) { // predictions close to each other in abundance -> otherwise I just delete the less abundant overlapping single exon gene
if(!pred[m]->t_eq && pred[n]->end>pred[m]->end) pred[m]->end=pred[n]->end;
//fprintf(stderr,"pred[%d] start=%d end=%d\n",m,pred[m]->start,pred[m]->end);
if(!pred[m]->t_eq) pred[m]->start=pred[n]->start; // pred[n]->start comes before pred[m]->start -> adjust if pred[m] is not reference
if(pred[n]->t_eq) {
pred[m]->t_eq=pred[n]->t_eq;
pred[m]->end=pred[n]->end;
pred[m]->flag=true;
}
//fprintf(stderr,"pred[%d] start=%d end=%d\n",m,pred[m]->start,pred[m]->end);
pred[m]->cov=(pred[n]->cov*abs(pred[n]->tlen)+pred[m]->cov*abs(pred[m]->tlen))/(pred[m]->end-pred[m]->start+1);
pred[m]->tlen=pred[m]->end-pred[m]->start+1;
if(longreads) pred[m]->tlen=-pred[m]->tlen;
else if(mixedMode){
if(pred[m]->cov>pred[n]->cov) {
if(pred[m]->tlen<0) pred[m]->tlen=-pred[m]->tlen;
}
else if(pred[n]->tlen<0) pred[m]->tlen=-pred[m]->tlen;
}
pred[m]->exoncov[0]=pred[m]->cov;
pred[m]->exons[0].start=pred[m]->start;
pred[m]->exons[0].end = pred[m]->end;
if(pred[m]->strand=='.') pred[m]->strand=pred[n]->strand;
}
else if(pred[n]->t_eq) { m++; continue;}
else { // prefer prediction with higher coverage
if(!pred[m]->t_eq && (pred[n]->t_eq || pred[n]->cov>pred[m]->cov)) { // prefer prediction with higher coverage here
pred[m]->start=pred[n]->start;
pred[m]->exons[0].start=pred[n]->exons[0].start;
pred[m]->end=pred[n]->end;
pred[m]->exons.Last().end=pred[n]->exons.Last().end;
pred[m]->tlen=pred[n]->tlen;
pred[m]->t_eq=pred[n]->t_eq;
if(pred[n]->t_eq) pred[m]->flag=true;
}
pred[m]->cov+=pred[n]->cov;
//fprintf(stderr,"--ndel Prediction m=%d (new cov=%f) is equal\n",m,pred[m]->cov);
for(int k=0;k<pred[m]->exons.Count();k++) {
pred[m]->exoncov[k]+=pred[n]->exoncov[k];
}
}
//fprintf(stderr,"--ndel pred[%d] start=%d end=%d\n",m,pred[m]->start,pred[m]->end);
}
else {
if(!pred[m]->t_eq && (pred[n]->t_eq || pred[n]->cov>pred[m]->cov)) { // prefer prediction with higher coverage here
pred[m]->start=pred[n]->start;
pred[m]->exons[0].start=pred[n]->exons[0].start;
pred[m]->end=pred[n]->end;
pred[m]->exons.Last().end=pred[n]->exons.Last().end;
pred[m]->tlen=pred[n]->tlen;
pred[m]->t_eq=pred[n]->t_eq;
if(pred[n]->t_eq) pred[m]->flag=true;
}
pred[m]->cov+=pred[n]->cov;
//fprintf(stderr,"--ndel Prediction m=%d (new cov=%f) is equal\n",m,pred[m]->cov);
for(int k=0;k<pred[m]->exons.Count();k++) {
pred[m]->exoncov[k]+=pred[n]->exoncov[k];
}
}
ndel=true;
break;
}
}
else if(pred[n]->exons.Count()>1) { // check if overlap on different strands
// first check for split read alignment errors
if(m==n+1 && !pred[n]->t_eq && pred[n]->exons.Count()==2) {
int p=n-1;
bool err=true;
while(p>=0) {
if(pred[p]!=NULL && pred[p]->end>pred[n]->start) {
err=false;
break;
}
p--;
}
if(err) {
/* version before longreads
float firstexoncov=get_cov(1,pred[n]->start-bundleData->start,pred[n]->exons[0].end-bundleData->start,bundleData->bpcov)/pred[n]->exons[0].len();
float lastexoncov=get_cov(1,pred[n]->exons.Last().start-bundleData->start,pred[n]->end-bundleData->start,bundleData->bpcov)/pred[n]->exons.Last().len();*/
int len1=pred[n]->exons[0].len();
int len2=pred[n]->exons.Last().len();
if(len1>CHI_WIN) len1=CHI_WIN;
if(len2>CHI_WIN) len2=CHI_WIN;
float firstexoncov=get_cov(1,pred[n]->exons[0].end-len1+1-bundleData->start,pred[n]->exons[0].end-bundleData->start,bundleData->bpcov)/len1;
float lastexoncov=get_cov(1,pred[n]->exons.Last().start-bundleData->start,pred[n]->exons.Last().start+len2-1-bundleData->start,bundleData->bpcov)/len2;
if(firstexoncov<lastexoncov*ERROR_PERC) {
//fprintf(stderr,"--ndel pred[%d] has firstexoncov:%d-%d=%f and lastexoncov:%d-%d=%f\n",n,pred[n]->start,pred[n]->exons[0].end,firstexoncov,pred[n]->exons.Last().start,pred[n]->end,lastexoncov);
ndel=true;
}
}
}
if(!ndel && !longreads && pred[m]->exons.Count()>1 && (!pred[n]->t_eq || !pred[m]->t_eq) ) { // at least one prediction can be modified
int l=0;
int f=0;
if(pred[n]->exons.Last().start<pred[m]->exons[0].end) {
l=n;f=m;
}
else if(pred[m]->exons.Last().start<pred[n]->exons[0].end) {
l=m;f=n;
}
if(f || l) {
int lastval=(int)pred[l]->exons.Last().start;
if(pred[l]->t_eq) lastval=pred[l]->end;
int firstval=(int)pred[f]->exons[0].end;
if(pred[f]->t_eq) firstval=pred[f]->start;
if(firstval-lastval>(int)(2*longintronanchor)) { // far apart so I can store hash
//GStr id(lastval);
id.assign(lastval);
id+=':';
id+=firstval;
uint startval=0;
uint endval=0;
uint *val=starthash[id];
if(!val) {
find_endpoints(bundleData->start,(uint)lastval,(uint)firstval,bundleData->bpcov,startval,endval);
starthash.Add(id.chars(),startval);
endhash.Add(id.chars(),endval);
}
else {
startval=*val;
val=endhash[id];
endval=*val;
}
// adjust pred[l] and pred[f] here
if(startval) {
int prednlen=abs(pred[l]->tlen)-pred[l]->end+startval;
int predmlen=abs(pred[f]->tlen)-endval+pred[f]->start;
//fprintf(stderr,"l=%d f=%d prednlen=%d predmlen=%d startval=%d endval=%d predlend=%d predstart=%d\n",l,f,prednlen,predmlen,startval,endval,pred[l]->end,pred[f]->start);
if(prednlen>mintranscriptlen && predmlen>mintranscriptlen) {
if(!pred[l]->t_eq && pred[l]->end>startval) {
float totalcov=get_cov(1,pred[l]->exons.Last().start-bundleData->start,pred[l]->end-bundleData->start,bundleData->bpcov);
float ratio=0;
float exoncov=pred[l]->exons.Last().len()*pred[l]->exoncov.Last();
if(totalcov) ratio=exoncov/totalcov;
pred[l]->cov=pred[l]->cov*abs(pred[l]->tlen)-exoncov;
//pred[l]->tlen-=pred[l]->end-midpoint;
if(pred[l]->tlen<0) pred[l]->tlen=-prednlen;
else pred[l]->tlen=prednlen;
pred[l]->exoncov.Last()=ratio*get_cov(1,pred[l]->exons.Last().start-bundleData->start,startval-bundleData->start,bundleData->bpcov);
pred[l]->cov=(pred[l]->cov+pred[l]->exoncov.Last())/abs(pred[l]->tlen);
pred[l]->exons.Last().end=startval;
pred[l]->end=startval;
pred[l]->exoncov.Last()/=pred[l]->exons.Last().len();
preddel=true;
//if(pred[l]->tlen<mintranscriptlen) ndel=true;
}
if(!pred[f]->t_eq && pred[f]->start<endval) { // adjust pred[f] coverage
float totalcov=get_cov(1,pred[f]->start-bundleData->start,pred[f]->exons[0].end-bundleData->start,bundleData->bpcov);
float ratio=0;
float exoncov=pred[f]->exons[0].len()*pred[f]->exoncov[0];
if(totalcov) ratio=exoncov/totalcov;
pred[f]->cov=pred[f]->cov*abs(pred[f]->tlen)-exoncov;
//pred[f]->tlen-=midpoint-pred[f]->start;
if(pred[f]->tlen<0) pred[f]->tlen=-predmlen;
else pred[f]->tlen=predmlen;
pred[f]->exoncov[0]=ratio*get_cov(1,endval-bundleData->start,pred[f]->exons[0].end-bundleData->start,bundleData->bpcov);
pred[f]->cov=(pred[f]->cov+pred[f]->exoncov[0])/abs(pred[f]->tlen);
pred[f]->exons[0].start=endval;
pred[f]->start=endval;
pred[f]->exoncov[0]/=pred[f]->exons[0].len();
preddel=true;
}
//fprintf(stderr,"midpoint=%d pred[n=%d]->cov=%f pred[m=%d]->cov=%f\n",midpoint,n,pred[l]->cov,m,pred[f]->cov);
}
}
}
}
}
}
m++;
}
// now pred[m]->start > pred[n]->end
uint runoff=runoffdist;
if(mixedMode && pred[n]->tlen<0) runoff=0;
if(m<npred && !ndel && !pred[n]->t_eq) { // pred[n] can be deleted
if (pred[n]->exons.Count()==1) {
if(pred[m]->exons.Count()==1 && pred[m]->start<pred[n]->end+runoff &&
(pred[n]->strand == pred[m]->strand || pred[n]->strand == '.' || pred[m]->strand == '.') &&
pred[m]->cov>ERROR_PERC*pred[n]->cov && pred[n]->cov>ERROR_PERC*pred[m]->cov && !pred[m]->t_eq) {
// if both are single predictions and are within bundledist on the same strand and not in reference and are not within error_perc from each other
//fprintf(stderr,"Stich predictions %d and %d with cov=%f and %f\n",n,m,pred[n]->cov,pred[m]->cov);
pred[m]->start=pred[n]->start;
pred[m]->cov=(pred[n]->cov*abs(pred[n]->tlen)+pred[m]->cov*abs(pred[m]->tlen))/(pred[m]->end-pred[m]->start+1);
int mult=1;
if(longreads) mult=-1;
else if(mixedMode){
if(pred[m]->cov>pred[n]->cov) {
if(pred[m]->tlen<0) mult=-1;
}
else if(pred[n]->tlen<0) mult=-1;
}
pred[m]->tlen=mult*(pred[m]->end-pred[m]->start+1);
pred[m]->exoncov[0]=pred[m]->cov;
pred[m]->exons[0].start=pred[m]->start;
if(pred[m]->strand=='.') pred[m]->strand=pred[n]->strand;
ndel=true;
}
else if(pred[n]->cov<singlethr) { /****** single exon different threshold ******/
ndel=true;
}
else if(m==n+1){
int m=n-1;
while(m>=0 && pred[m]==NULL) m--;
//if(m>=0 && pred[m]->end>=pred[n]->start) fprintf(stderr,"pred[%d] overlaps pred[%d]\n",n,m);
if(m<0 || pred[m]->end<pred[n]->start) { // pred[n] does not overlap previous prediction --> check if I can delete it
if(pred[n+1]->start-pred[n]->end<runoff) {
float exoncov=get_cov(1,pred[n+1]->start-bundleData->start,pred[n+1]->exons[0].end-bundleData->start,bundleData->bpcov)/pred[n+1]->exons[0].len();
//fprintf(stderr,"Pred %d to be deleted because under first exoncov of pred %d\n",n,n+1);
if(pred[n]->cov<exoncov+singlethr) ndel=true;
}
if(!ndel && m>=0 && pred[n]->start-pred[m]->end<runoff) {
float exoncov=get_cov(1,pred[m]->exons.Last().start-bundleData->start,pred[m]->end-bundleData->start,bundleData->bpcov)/pred[m]->exons.Last().len();
//fprintf(stderr,"Pred %d to be deleted because under last exoncov of pred %d\n",n,m);
if(pred[n]->cov<exoncov+singlethr) ndel=true;
}
}
}
}
else if(m==n+1 && pred[n]->exons.Count()==2) { // check for splice read alignment error
int p=n-1;
bool err=true;
while(p>=0) {
if(pred[p]!=NULL && (pred[p]->end>=pred[n]->exons.Last().start || (pred[p]->strand==pred[n]->strand && pred[p]->end>=pred[n]->start))) {
err=false;
break;
}
p--;
}
if(err) {
/* version before longreads
float firstexoncov=get_cov(1,pred[n]->start-bundleData->start,pred[n]->exons[0].end-bundleData->start,bundleData->bpcov)/pred[n]->exons[0].len();
float lastexoncov=get_cov(1,pred[n]->exons.Last().start-bundleData->start,pred[n]->end-bundleData->start,bundleData->bpcov)/pred[n]->exons.Last().len();*/
int len1=pred[n]->exons[0].len();
int len2=pred[n]->exons.Last().len();
if(len1>CHI_WIN) len1=CHI_WIN;
if(len2>CHI_WIN) len2=CHI_WIN;
float firstexoncov=get_cov(1,pred[n]->exons[0].end-len1+1-bundleData->start,pred[n]->exons[0].end-bundleData->start,bundleData->bpcov)/len1;
float lastexoncov=get_cov(1,pred[n]->exons.Last().start-bundleData->start,pred[n]->exons.Last().start+len2-1-bundleData->start,bundleData->bpcov)/len2;
if(lastexoncov<firstexoncov*ERROR_PERC) {
ndel=true;
//fprintf(stderr,"pred[%d] has firstexoncov:%d-%d=%f and lastexoncov:%d-%d=%f\n",n,pred[n]->start,pred[n]->exons[0].end,firstexoncov,pred[n]->exons.Last().start,pred[n]->end,lastexoncov);
}
}
}
}
}
if(ndel) {
// now replace pred[n] with null
CPrediction *p=pred[n];
pred.Forget(n);
delete p;
preddel=true;
}
else if(isintronguide && !incomplete && !pred[n]->t_eq && pred[n]->exons.Count()>1 && pred[n]->mergename.is_empty()){
incomplete=true;
}
}
// stich last prediction
if(npred && !pred[npred-1]->t_eq) {
bool check=true;
if(abs(pred[npred-1]->tlen)<mintranscriptlen || (pred[npred-1]->exons.Count()==1 && pred[npred-1]->cov<singlethr)) { /****** single exon different threshold ******/
// now replace pred[n] with null
CPrediction *p=pred[npred-1];
pred.Forget(npred-1);
delete p;
preddel=true;
check=false;
}
else if(pred[npred-1]->exons.Count()==1) {
if(npred>1) {
int m=npred-2;
while(m>=0 && pred[m]==NULL) m--;
uint runoff=runoffdist;
if(mixedMode && pred[npred-1]->tlen<0) runoff=0;
if(m>=0 && pred[m]->end<pred[npred-1]->start && pred[npred-1]->start-pred[m]->end<runoff) {
float exoncov=get_cov(1,pred[m]->exons.Last().start-bundleData->start,pred[m]->end-bundleData->start,bundleData->bpcov)/pred[m]->exons.Last().len();
if(pred[npred-1]->cov<exoncov) {
CPrediction *p=pred[npred-1];
pred.Forget(npred-1);
delete p;
preddel=true;
check=false;
}
}
}
}
else if(pred[npred-1]->exons.Count()==2) { // check for spliced read alignment error
int k=npred-2;
bool err=true;
while(k>=0) {
if(pred[k]!=NULL && (pred[k]->end>pred[npred-1]->exons.Last().start || (pred[k]->strand==pred[npred-1]->strand && pred[k]->end>=pred[npred-1]->start))) {
err=false;
break;
}
k--;
}
if(err) {
/* version before longreads
float firstexoncov=get_cov(1,pred[npred-1]->start-bundleData->start,pred[npred-1]->exons[0].end-bundleData->start,bundleData->bpcov)/pred[npred-1]->exons[0].len();
float lastexoncov=get_cov(1,pred[npred-1]->exons.Last().start-bundleData->start,pred[npred-1]->end-bundleData->start,bundleData->bpcov)/pred[npred-1]->exons.Last().len();*/
int len1=pred[npred-1]->exons[0].len();
int len2=pred[npred-1]->exons.Last().len();
if(len1>CHI_WIN) len1=CHI_WIN;
if(len2>CHI_WIN) len2=CHI_WIN;
float firstexoncov=get_cov(1,pred[npred-1]->exons[0].end-len1+1-bundleData->start,pred[npred-1]->exons[0].end-bundleData->start,bundleData->bpcov)/len1;
float lastexoncov=get_cov(1,pred[npred-1]->exons.Last().start-bundleData->start,pred[npred-1]->exons.Last().start+len2-1-bundleData->start,bundleData->bpcov)/len2;
if(lastexoncov<firstexoncov*ERROR_PERC) {
CPrediction *p=pred[npred-1];
pred.Forget(npred-1);
delete p;
check=false;
preddel=true;
}
}
}
if(check && isintronguide && !incomplete && !pred[npred-1]->t_eq && pred[npred-1]->exons.Count()>1 && pred[npred-1]->mergename.is_empty()){
incomplete=true;
}
}
if(preddel) {
pred.Pack();
pred.Sort();
npred=pred.Count();
}
//}
/*
{ // DEBUG ONLY
fprintf(stderr,"Before predcluster:\n");
for(int i=0;i<pred.Count();i++) {
if(pred[i]->t_eq) fprintf(stderr,"%s ",pred[i]->t_eq->getID());
fprintf(stderr,"pred[%d]:%d-%d (cov=%f, readcov=%f, strand=%c falseflag=%d):",i,pred[i]->start,pred[i]->end,pred[i]->cov,pred[i]->tlen*pred[i]->cov,pred[i]->strand,pred[i]->flag);
//for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %d-%d(%f)",pred[i]->exons[j].start,pred[i]->exons[j].end,pred[i]->exoncov[j]);
for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %d-%d",pred[i]->exons[j].start,pred[i]->exons[j].end);
fprintf(stderr," (");
for(int j=0;j<pred[i]->exons.Count();j++) fprintf(stderr," %f",pred[i]->exoncov[j]);
fprintf(stderr,")\n");
}
fprintf(stderr,"\n");
}
*/
if(npred) geneno=print_predcluster(pred,geneno,refname,refgene,hashgene,predgene,bundleData,incomplete);
hashgene.Clear();
// I am done printing all transcripts, now evaluate/print the gene abundances
if(eonly || geneabundance) { // I only need to evaluate the refgene coverages if geneabundance is required, or these are the only gene coverages
for(int i=0;i<refgene.Count();i++) {
float cov=0;
int s=1; // strand of gene
if(refgene[i].strand=='+') s=2;
else if(refgene[i].strand=='-') s=0;
int glen=0;
for(int j=0;j<refgene[i].exons.Count();j++) { // evaluate unused coverage
glen+=refgene[i].exons[j].len();
if(!eonly) {
int start=(int)refgene[i].exons[j].start-refstart;
int end=(int)refgene[i].exons[j].end-refstart+1;
if(start<bpcov[1].Count()) {
if(start<0) start=0;
if(end>=bpcov[1].Count()) end=bpcov[1].Count()-1;
// cummulative bpcov
float localcov[3]={0,0,0};
for(int i=0;i<3;i++) {
if(end) localcov[i]=get_cov(i,start,end-1,bpcov);
}
switch(s) {
case 0:
if(localcov[2]) cov+=localcov[0]+(localcov[1]-localcov[0]-localcov[2])*localcov[0]/(localcov[0]+localcov[2]);
else cov+=localcov[1];
break;
case 1: cov+=localcov[1]-localcov[2]-localcov[0];break;
case 2:
if(localcov[0]) cov+=localcov[2]+(localcov[1]-localcov[0]-localcov[2])*localcov[2]/(localcov[0]+localcov[2]);
else cov+=localcov[1];
break;
}
}
}
}
if(eonly) bundleData->sum_cov+=refgene[i].covsum;
else { // for eonly I only use the annotated transcripts, nothing more
refgene[i].cov=cov-refgene[i].cov;
if(refgene[i].cov>epsilon) refgene[i].covsum+=refgene[i].cov/glen;
}
if(geneabundance) {
if(!eonly) refgene[i].cov=cov/glen; // only if I want to store the real gene coverage
else refgene[i].cov/=glen;
fprintf(f_out,"0 1 %d 0 %.6f\n",glen, refgene[i].covsum);
const char* geneID=refgene[i].geneID;
if (geneID==NULL) geneID=".";
fprintf(f_out,"%s\t",geneID);
if(refgene[i].geneName) fprintf(f_out,"%s\t",refgene[i].geneName);
else fprintf(f_out,"-\t");
//fprintf(f_out,"%s\t%c\t%d\t%d\t%d\t%.6f\n",refname.chars(),refgene[i].strand,refgene[i].start,refgene[i].end,glen,refgene[i].cov);
fprintf(f_out,"%s\t%c\t%d\t%d\t%.6f\n",refname.chars(),refgene[i].strand,refgene[i].start,refgene[i].end,refgene[i].cov);
}
}
}
if(!eonly) {
for(int i=0;i<predgene.Count();i++) {
float cov=0;
int s=1; // strand of gene
if(predgene[i].strand=='+') s=2;
else if(predgene[i].strand=='-') s=0;
int glen=0;
for(int j=0;j<predgene[i].exons.Count();j++) { // evaluate unused coverage
glen+=predgene[i].exons[j].len();
int start=(int)predgene[i].exons[j].start-refstart;
int end=(int)predgene[i].exons[j].end-refstart+1;
// predgene start and end might have been also adjusted to reflect the annotation
if(start<0) start=0;
if(end>=bpcov[1].Count()) end=bpcov[1].Count()-1;
// cummulative bpcov
float localcov[3]={0,0,0};
for(int i=0;i<3;i++) {
if(end) localcov[i]=get_cov(i,start,end-1,bpcov);
}
switch(s) {
case 0:
if(localcov[2]) cov+=localcov[0]+(localcov[1]-localcov[0]-localcov[2])*localcov[0]/(localcov[0]+localcov[2]);
else cov+=localcov[1];
break;
case 1: cov+=localcov[1]-localcov[2]-localcov[0];break;
case 2:
if(localcov[0]) cov+=localcov[2]+(localcov[1]-localcov[0]-localcov[2])*localcov[2]/(localcov[0]+localcov[2]);
else cov+=localcov[1];
break;
}
}
predgene[i].cov=cov-predgene[i].cov; // THIS is the read coverage that is left for the genes after all the predictions were taken into account
if(predgene[i].cov>epsilon) predgene[i].covsum+=predgene[i].cov/glen;
bundleData->sum_cov+=predgene[i].covsum;
if(geneabundance) {
predgene[i].cov=cov/glen; // only if I want to store the real gene coverage
fprintf(f_out,"0 1 %d 0 %.6f\n",glen, predgene[i].covsum);
fprintf(f_out,"%s.%d\t",label.chars(),startgno+i);
fprintf(f_out,"-\t");
//fprintf(f_out,"%s\t%c\t%d\t%d\t%d\t%.6f\n",refname.chars(),predgene[i].strand,predgene[i].start,predgene[i].end,glen,predgene[i].cov);
fprintf(f_out,"%s\t%c\t%d\t%d\t%.6f\n",refname.chars(),predgene[i].strand,predgene[i].start,predgene[i].end,predgene[i].cov);
}
}
}
/*** I might resque this if I want to write a non-conflicting (among threads) version of the covered references
if (c_out) {
for (int i=0;i<bundleData->covguides.Count();i++)
bundleData->covguides[i]->print(c_out);
}
***/
//rc_write_counts(refname.chars(), *bundleData);
return(geneno);
}
|