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
|
/***************************************************************************
* Copyright (C) 2009-2015 by *
* BUI Quang Minh <minh.bui@univie.ac.at> *
* Lam-Tung Nguyen <nltung@gmail.com> *
* *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iqtree_config.h>
#include "tree/phylotree.h"
#include "tree/phylosupertree.h"
#include "tree/phylosupertreeplen.h"
#include "tree/phylosupertreeunlinked.h"
#include "phyloanalysis.h"
#include "alignment/alignment.h"
#include "alignment/superalignment.h"
#include "alignment/superalignmentunlinked.h"
#include "tree/iqtree.h"
#include "tree/phylotreemixlen.h"
#include "model/modelmarkov.h"
#include "model/modeldna.h"
#include "model/modelpomo.h"
#include "nclextra/myreader.h"
#include "model/rateheterogeneity.h"
#include "model/rategamma.h"
#include "model/rateinvar.h"
#include "model/rategammainvar.h"
//#include "modeltest_wrapper.h"
#include "model/modelprotein.h"
#include "model/modelbin.h"
#include "model/modelcodon.h"
#include "utils/stoprule.h"
#include "tree/mtreeset.h"
#include "tree/mexttree.h"
#include "model/ratemeyerhaeseler.h"
#include "whtest/whtest_wrapper.h"
#include "model/partitionmodel.h"
#include "model/modelmixture.h"
#include "model/modelfactorymixlen.h"
//#include "guidedbootstrap.h"
#include "model/modelset.h"
#include "utils/timeutil.h"
#include "tree/upperbounds.h"
#include "utils/MPIHelper.h"
#include "timetree.h"
#ifdef USE_BOOSTER
extern "C" {
#include "booster/booster.h"
}
#endif
#ifdef IQTREE_TERRAPHAST
#include "terrace/terrace.h"
#endif
void reportReferences(Params ¶ms, ofstream &out) {
out << "To cite IQ-TREE please use:" << endl << endl
<< "Bui Quang Minh, Heiko A. Schmidt, Olga Chernomor, Dominik Schrempf," << endl
<< "Michael D. Woodhams, Arndt von Haeseler, and Robert Lanfear (2020)" << endl
<< "IQ-TREE 2: New models and efficient methods for phylogenetic inference" << endl
<< "in the genomic era. Mol. Biol. Evol., in press." << endl
<< "https://doi.org/10.1093/molbev/msaa015" << endl << endl;
bool modelfinder_only = false;
if (params.model_name.substr(0,4) == "TEST" || params.model_name.substr(0, 2) == "MF" || params.model_name.empty()) {
out << "To cite ModelFinder please use: " << endl << endl
<< "Subha Kalyaanamoorthy, Bui Quang Minh, Thomas KF Wong, Arndt von Haeseler," << endl
<< "and Lars S Jermiin (2017) ModelFinder: Fast model selection for" << endl
<< "accurate phylogenetic estimates. Nature Methods, 14:587–589." << endl
<< "https://doi.org/10.1038/nmeth.4285" << endl << endl;
if (params.model_name.find("ONLY") != string::npos || (params.model_name.substr(0,2)=="MF" && params.model_name.substr(0,3)!="MFP"))
modelfinder_only = true;
}
if (posPOMO(params.model_name) != string::npos) {
out << "For polymorphism-aware models please cite:" << endl << endl
<< "Dominik Schrempf, Bui Quang Minh, Nicola De Maio, Arndt von Haeseler, and Carolin Kosiol" << endl
<< "(2016) Reversible polymorphism-aware phylogenetic models and their application to" << endl
<< "tree inference. J. Theor. Biol., 407:362–370." << endl
<< "https://doi.org/10.1016/j.jtbi.2016.07.042" << endl << endl;
}
if (params.site_freq_file || params.tree_freq_file)
out << "Since you used site-specific frequency model please also cite: " << endl << endl
<< "Huai-Chun Wang, Edward Susko, Bui Quang Minh, and Andrew J. Roger (2018)" << endl
<< "Modeling site heterogeneity with posterior mean site frequency profiles" << endl
<< "accelerates accurate phylogenomic estimation. Syst. Biol., 67:216–235." << endl
<< "https://doi.org/10.1093/sysbio/syx068" << endl << endl;
if (params.gbo_replicates)
out << "Since you used ultrafast bootstrap (UFBoot) please also cite: " << endl << endl
<< "Diep Thi Hoang, Olga Chernomor, Arndt von Haeseler, Bui Quang Minh," << endl
<< "and Le Sy Vinh (2018) UFBoot2: Improving the ultrafast bootstrap" << endl
<< "approximation. Mol. Biol. Evol., 35:518–522." << endl
<< "https://doi.org/10.1093/molbev/msx281" << endl << endl;
if (params.partition_file)
out << "Since you used partition models please also cite:" << endl << endl
<< "Olga Chernomor, Arndt von Haeseler, and Bui Quang Minh (2016)" << endl
<< "Terrace aware data structure for phylogenomic inference from" << endl
<< "supermatrices. Syst. Biol., 65:997-1008." << endl
<< "https://doi.org/10.1093/sysbio/syw037" << endl << endl;
if (params.terrace_analysis)
out << "Since you used terrace analysis please also cite:" << endl << endl
<< "Biczok R, Bozsoky P, Eisenmann P, Ernst J, Ribizel T, Scholz F," << endl
<< "Trefzer A, Weber F, Hamann M, Stamatakis A. (2018)" << endl
<< "Two C++ libraries for counting trees on a phylogenetic" << endl
<< "terrace. Bioinformatics 34:3399–3401." << endl
<< "https://doi.org/10.1093/bioinformatics/bty384" << endl << endl;
if (params.dating_method == "LSD")
out << "Since you used least square dating (LSD) please also cite: " << endl << endl
<< "Thu-Hien To, Matthieu Jung, Samantha Lycett, Olivier Gascuel (2016)" << endl
<< "Fast dating using least-squares criteria and algorithms. Syst. Biol. 65:82-97." << endl
<< "https://doi.org/10.1093/sysbio/syv068" << endl << endl;
}
void reportAlignment(ofstream &out, Alignment &alignment, int nremoved_seqs) {
out << "Input data: " << alignment.getNSeq()+nremoved_seqs << " sequences with "
<< alignment.getNSite() << " ";
switch (alignment.seq_type) {
case SEQ_BINARY: out << "binary"; break;
case SEQ_DNA: out << "nucleotide"; break;
case SEQ_PROTEIN: out << "amino-acid"; break;
case SEQ_CODON: out << "codon"; break;
case SEQ_MORPH: out << "morphological"; break;
case SEQ_POMO: out << "PoMo"; break;
default: out << "unknown"; break;
}
out << " sites" << endl << "Number of constant sites: "
<< round(alignment.frac_const_sites * alignment.getNSite())
<< " (= " << alignment.frac_const_sites * 100 << "% of all sites)" << endl
<< "Number of invariant (constant or ambiguous constant) sites: "
<< round(alignment.frac_invariant_sites * alignment.getNSite())
<< " (= " << alignment.frac_invariant_sites * 100 << "% of all sites)" << endl
<< "Number of parsimony informative sites: " << alignment.num_informative_sites << endl
<< "Number of distinct site patterns: " << alignment.size() << endl
<< endl;
}
/*
void pruneModelInfo(ModelCheckpoint &model_info, PhyloSuperTree *tree) {
ModelCheckpoint res_info;
for (vector<PartitionInfo>::iterator it = tree->part_info.begin(); it != tree->part_info.end(); it++) {
for (ModelCheckpoint::iterator mit = model_info.begin(); mit != model_info.end(); mit++)
if (mit->set_name == it->name)
res_info.push_back(*mit);
}
model_info = res_info;
}
*/
void reportModelSelection(ofstream &out, Params ¶ms, ModelCheckpoint *model_info, PhyloTree *tree) {
out << "Best-fit model according to " << criterionName(params.model_test_criterion) << ": ";
// ModelCheckpoint::iterator it;
string best_model;
PhyloSuperTree *stree = (tree->isSuperTree()) ? ((PhyloSuperTree*)tree) : NULL;
if (tree->isSuperTree()) {
SuperAlignment *saln = (SuperAlignment*)stree->aln;
for (int part = 0; part != stree->size(); part++) {
if (part != 0)
out << ",";
out << saln->partitions[part]->model_name << ":" << saln->partitions[part]->name;
}
// string set_name = "";
// for (it = model_info.begin(); it != model_info.end(); it++) {
// if (it->set_name != set_name) {
// if (set_name != "")
// out << ",";
// out << it->name << ":" << it->set_name;
// set_name = it->set_name;
// }
// }
} else {
// out << model_info[0].name;
model_info->getBestModel(best_model);
out << best_model;
}
if (tree->isSuperTree()) {
out << endl << endl << "List of best-fit models per partition:" << endl << endl;
} else {
out << endl << endl << "List of models sorted by "
<< ((params.model_test_criterion == MTC_BIC) ? "BIC" :
((params.model_test_criterion == MTC_AIC) ? "AIC" : "AICc"))
<< " scores: " << endl << endl;
}
if (tree->isSuperTree())
out << " ID ";
out << "Model LogL AIC w-AIC AICc w-AICc BIC w-BIC" << endl;
/*
if (is_partitioned)
out << "----------";
out << "----------------------------------------------------------------------------------------" << endl;
*/
int setid = 1;
out.precision(3);
CandidateModelSet models;
model_info->getOrderedModels(tree, models);
for (auto it = models.begin(); it != models.end(); it++) {
if (tree->isSuperTree()) {
out.width(4);
out << right << setid << " ";
setid++;
}
out.width(15);
out << left << it->getName() << " ";
out.width(11);
out << right << it->logl << " ";
out.width(11);
out << it->AIC_score << ((it->AIC_conf) ? " + " : " - ");
out.unsetf(ios::fixed);
out.width(8);
out << it->AIC_weight << " ";
out.setf(ios::fixed);
out.width(11);
out << it->AICc_score << ((it->AICc_conf) ? " + " : " - ");
out.unsetf(ios::fixed);
out.width(8);
out << it->AICc_weight << " ";
out.setf(ios::fixed);
out.width(11);
out << it->BIC_score << ((it->BIC_conf) ? " + " : " - ");
out.unsetf(ios::fixed);
out.width(8);
out << it->BIC_weight;
out.setf(ios::fixed);
out << endl;
}
out.precision(4);
/* TODO
for (it = model_info.begin(); it != model_info.end(); it++) {
if (it->AIC_score == DBL_MAX) continue;
if (it != model_info.begin() && it->set_name != (it-1)->set_name)
setid++;
if (is_partitioned && it != model_info.begin() && it->set_name == (it-1)->set_name)
continue;
if (is_partitioned) {
out.width(4);
out << right << setid << " ";
}
out.width(15);
out << left << it->name << " ";
out.width(11);
out << right << it->logl << " ";
out.width(11);
out << it->AIC_score << ((it->AIC_conf) ? " + " : " - ") << it->AIC_weight << " ";
out.width(11);
out << it->AICc_score << ((it->AICc_conf) ? " + " : " - ") << it->AICc_weight << " ";
out.width(11);
out << it->BIC_score << ((it->BIC_conf) ? " + " : " - ") << it->BIC_weight;
out << endl;
}
*/
out << endl;
out << "AIC, w-AIC : Akaike information criterion scores and weights." << endl
<< "AICc, w-AICc : Corrected AIC scores and weights." << endl
<< "BIC, w-BIC : Bayesian information criterion scores and weights." << endl << endl
<< "Plus signs denote the 95% confidence sets." << endl
<< "Minus signs denote significant exclusion." <<endl;
out << endl;
}
void reportModel(ofstream &out, Alignment *aln, ModelSubst *m) {
int i, j, k;
ASSERT(aln->num_states == m->num_states);
double *rate_mat = new double[m->num_states * m->num_states];
if (!m->isSiteSpecificModel())
m->getRateMatrix(rate_mat);
else
((ModelSet*)m)->front()->getRateMatrix(rate_mat);
if (m->num_states <= 4) {
out << "Rate parameter R:" << endl << endl;
if (m->num_states > 4)
out << fixed;
if (m->isReversible()) {
for (i = 0, k = 0; i < m->num_states - 1; i++)
for (j = i + 1; j < m->num_states; j++, k++) {
out << " " << aln->convertStateBackStr(i) << "-" << aln->convertStateBackStr(j) << ": "
<< rate_mat[k];
if (m->num_states <= 4)
out << endl;
else if (k % 5 == 4)
out << endl;
}
} else { // non-reversible model
for (i = 0, k = 0; i < m->num_states; i++)
for (j = 0; j < m->num_states; j++)
if (i != j) {
out << " " << aln->convertStateBackStr(i) << "-" << aln->convertStateBackStr(j)
<< ": " << rate_mat[k];
if (m->num_states <= 4)
out << endl;
else if (k % 5 == 4)
out << endl;
k++;
}
}
//if (tree.aln->num_states > 4)
out << endl;
out.unsetf(ios_base::fixed);
} else if (aln->seq_type == SEQ_PROTEIN && m->getNDim() > 20) {
ASSERT(m->num_states == 20);
out << "WARNING: This model has " << m->getNDim() + m->getNDimFreq() << " parameters that may be overfitting. Please use with caution!" << endl << endl;
double full_mat[400];
out.precision(6);
if (m->isReversible()) {
for (i = 0, k = 0; i < m->num_states - 1; i++)
for (j = i + 1; j < m->num_states; j++, k++) {
full_mat[i*m->num_states+j] = rate_mat[k];
}
out << "Substitution parameters (lower-diagonal) and state frequencies in PAML format (can be used as input for IQ-TREE): " << endl << endl;
for (i = 1; i < m->num_states; i++) {
for (j = 0; j < i; j++)
out << " " << full_mat[j*m->num_states+i];
out << endl;
}
} else {
// non-reversible model
m->getQMatrix(full_mat);
out << "Full Q matrix and state frequencies (can be used as input for IQ-TREE): " << endl << endl;
for (i = 0; i < m->num_states; i++) {
for (j = 0; j < m->num_states; j++)
out << " " << full_mat[i*m->num_states+j];
out << endl;
}
}
double state_freq[20];
m->getStateFrequency(state_freq);
for (i = 0; i < m->num_states; i++)
out << " " << state_freq[i];
out << endl << endl;
out.precision(4);
}
delete[] rate_mat;
if (aln->seq_type == SEQ_POMO) {
m->report(out);
return;
}
out << "State frequencies: ";
if (m->isSiteSpecificModel())
out << "(site specific frequencies)" << endl << endl;
else {
// 2016-11-03: commented out as this is not correct anymore
// if (!m->isReversible())
// out << "(inferred from Q matrix)" << endl;
// else
switch (m->getFreqType()) {
case FREQ_EMPIRICAL:
out << "(empirical counts from alignment)" << endl;
break;
case FREQ_ESTIMATE:
out << "(estimated with maximum likelihood)" << endl;
break;
case FREQ_USER_DEFINED:
out << ((aln->seq_type == SEQ_PROTEIN) ? "(model)" : "(user-defined)") << endl;
break;
case FREQ_EQUAL:
out << "(equal frequencies)" << endl;
break;
default:
break;
}
out << endl;
if ((m->getFreqType() != FREQ_USER_DEFINED || aln->seq_type == SEQ_DNA) && m->getFreqType() != FREQ_EQUAL) {
double *state_freqs = new double[m->num_states];
m->getStateFrequency(state_freqs);
int ncols=(aln->seq_type == SEQ_CODON) ? 4 : 1;
for (i = 0; i < m->num_states; i++) {
out << " pi(" << aln->convertStateBackStr(i) << ") = " << state_freqs[i];
if (i % ncols == ncols-1)
out << endl;
}
delete[] state_freqs;
out << endl;
}
if (m->num_states <= 4 || verbose_mode >= VB_MED) {
// report Q matrix
if (verbose_mode >= VB_MED)
out.precision(6);
double *q_mat = new double[m->num_states * m->num_states];
m->getQMatrix(q_mat);
out << "Rate matrix Q:" << endl << endl;
for (i = 0, k = 0; i < m->num_states; i++) {
out << " " << aln->convertStateBackStr(i);
for (j = 0; j < m->num_states; j++, k++) {
out << " ";
out.width(8);
out << q_mat[k];
}
out << endl;
}
out << endl;
delete[] q_mat;
}
}
}
void reportModel(ofstream &out, PhyloTree &tree) {
// int i, j, k;
int i;
if (tree.getModel()->isMixture() && !tree.getModel()->isPolymorphismAware()) {
out << "Mixture model of substitution: " << tree.getModelName() << endl;
// out << "Full name: " << tree.getModelName() << endl;
ModelSubst *mmodel = tree.getModel();
out << endl << " No Component Rate Weight Parameters" << endl;
i = 0;
int nmix = mmodel->getNMixtures();
for (i = 0; i < nmix; i++) {
ModelMarkov *m = (ModelMarkov*)mmodel->getMixtureClass(i);
out.width(4);
out << right << i+1 << " ";
out.width(12);
out << left << (m)->name << " ";
out.width(7);
out << (m)->total_num_subst << " ";
out.width(7);
out << mmodel->getMixtureWeight(i) << " " << (m)->getNameParams() << endl;
if (tree.aln->seq_type == SEQ_POMO) {
out << endl << "Model for mixture component " << i+1 << ": " << (m)->name << endl;
reportModel(out, tree.aln, m);
}
}
if (tree.aln->seq_type != SEQ_POMO && tree.aln->seq_type != SEQ_DNA)
for (i = 0; i < nmix; i++) {
ModelMarkov *m = (ModelMarkov*)mmodel->getMixtureClass(i);
if (m->getFreqType() == FREQ_EQUAL || m->getFreqType() == FREQ_USER_DEFINED)
continue;
out << endl << "Model for mixture component " << i+1 << ": " << (m)->name << endl;
reportModel(out, tree.aln, m);
}
out << endl;
} else {
out << "Model of substitution: " << tree.getModelName() << endl << endl;
reportModel(out, tree.aln, tree.getModel());
}
}
void reportRate(ostream &out, PhyloTree &tree) {
int i;
RateHeterogeneity *rate_model = tree.getRate();
out << "Model of rate heterogeneity: " << rate_model->full_name << endl;
rate_model->writeInfo(out);
if (rate_model->getNDiscreteRate() > 1 || rate_model->getPInvar() > 0.0) {
out << endl << " Category Relative_rate Proportion" << endl;
if (rate_model->getPInvar() > 0.0)
out << " 0 0 " << rate_model->getPInvar()
<< endl;
int cats = rate_model->getNDiscreteRate();
DoubleVector prop;
if (rate_model->getGammaShape() > 0 || rate_model->getPtnCat(0) < 0) {
// prop.resize(cats, (1.0 - rate_model->getPInvar()) / rate_model->getNRate());
prop.resize(cats);
for (i = 0; i < cats; i++)
prop[i] = rate_model->getProp(i);
} else {
prop.resize(cats, 0.0);
for (i = 0; i < tree.aln->getNPattern(); i++)
prop[rate_model->getPtnCat(i)] += tree.aln->at(i).frequency;
for (i = 0; i < cats; i++)
prop[i] /= tree.aln->getNSite();
}
for (i = 0; i < cats; i++) {
out << " " << i + 1 << " ";
out.width(14);
out << left << rate_model->getRate(i) << " " << prop[i];
out << endl;
}
if (rate_model->isGammaRate()) {
out << "Relative rates are computed as " << ((rate_model->isGammaRate() == GAMMA_CUT_MEDIAN) ? "MEDIAN" : "MEAN") <<
" of the portion of the Gamma distribution falling in the category." << endl;
}
}
/*
if (rate_model->getNDiscreteRate() > 1 || rate_model->isSiteSpecificRate())
out << endl << "See file " << rate_file << " for site-specific rates and categories" << endl;*/
out << endl;
}
void reportTree(ofstream &out, Params ¶ms, PhyloTree &tree, double tree_lh, double lh_variance, double main_tree) {
int ssize = tree.getAlnNSite();
double epsilon = 1.0 / ssize;
double totalLen = tree.treeLength();
int df = tree.getModelFactory()->getNParameters(BRLEN_OPTIMIZE);
double AIC_score, AICc_score, BIC_score;
computeInformationScores(tree_lh, df, ssize, AIC_score, AICc_score, BIC_score);
out << "Log-likelihood of the tree: " << fixed << tree_lh;
if (lh_variance > 0.0)
out << " (s.e. " << sqrt(lh_variance) << ")";
out << endl;
out << "Unconstrained log-likelihood (without tree): " << tree.aln->computeUnconstrainedLogL() << endl;
out << "Number of free parameters (#branches + #model parameters): " << df << endl;
// if (ssize > df) {
// if (ssize > 40*df)
// out << "Akaike information criterion (AIC) score: " << AIC_score << endl;
// else
// out << "Corrected Akaike information criterion (AICc) score: " << AICc_score << endl;
//
// out << "Bayesian information criterion (BIC) score: " << BIC_score << endl;
// } else
out << "Akaike information criterion (AIC) score: " << AIC_score << endl;
out << "Corrected Akaike information criterion (AICc) score: " << AICc_score << endl;
out << "Bayesian information criterion (BIC) score: " << BIC_score << endl;
if (ssize <= df && main_tree) {
out << endl
<< "**************************** WARNING ****************************" << endl
<< "Number of parameters (K, model parameters and branch lengths): " << df << endl
<< "Sample size (n, alignment length): " << ssize << endl << endl
<< "Given that K>=n, the parameter estimates might be inaccurate." << endl
<< "Thus, phylogenetic estimates should be interpreted with caution." << endl << endl
<< "Ideally, it is desirable that n >> K. When selecting optimal models," << endl
<< "1. use AIC or BIC if n > 40K;" << endl
<< "2. use AICc or BIC if 40K >= n > K;" << endl
<< "3. be extremely cautious if n <= K" << endl << endl
<< "To improve the situation (3), consider the following options:" << endl
<< " 1. Increase the sample size (n)" << endl
<< " 2. Decrease the number of parameters (K) to be estimated. If" << endl
<< " possible:" << endl
<< " a. Remove the least important sequences from the alignment" << endl
<< " b. Specify some of the parameter values for the substitution"<< endl
<< " model (e.g., the nucleotide or amino acid frequencies)" << endl
<< " c. Specify some of the parameter values for the rates-across-" << endl
<< " sites model (e.g., the shape parameter for the discrete" << endl
<< " Gamma distribution, the proportion of invariable sites, or" << endl
<< " the rates of change for different rate categories under" << endl
<< " the FreeRate model)" << endl << endl
<< "Reference:" << endl
<< "Burnham KR, Anderson DR (2002). Model Selection and Multimodel" << endl
<< "Inference: A Practical Information-Theoretic Approach. Springer," << endl
<< "New York." << endl
<< "************************ END OF WARNING ***********************" << endl;
}
out << endl;
if (tree.aln->seq_type == SEQ_POMO) {
int N = tree.aln->virtual_pop_size;
out << "NOTE: The branch lengths of PoMo measure mutations and frequency shifts." << endl;
out << "To compare PoMo branch lengths to DNA substitution models use the tree length" << endl;
out << "measured in substitutions per site." << endl << endl;
out << "PoMo branch length = Substitution model branch length * N * N." << endl << endl;
out << "Total tree length (sum of branch lengths)" << endl;
out << " - measured in number of mutations and frequency shifts per site: " << totalLen << endl;
out << " - measured in number of substitutions per site (divided by N^2): " << totalLen / (N * N) << endl;
}
else out << "Total tree length (sum of branch lengths): " << totalLen << endl;
double totalLenInternal = tree.treeLengthInternal(epsilon);
double totalLenInternalP = totalLenInternal*100.0 / totalLen;
if (tree.aln->seq_type == SEQ_POMO) {
int N = tree.aln->virtual_pop_size;
double totLenIntSub = totalLenInternal/(N * N);
out << "Sum of internal branch lengths" << endl;
out << "- measured in mutations and frequency shifts per site: " << totalLenInternal << " (" << totalLenInternalP << "% of tree length)" << endl;
out << "- measured in substitutions per site: " << totLenIntSub << " (" << totalLenInternalP << "% of tree length)" << endl;
out << endl;
}
else {
out << "Sum of internal branch lengths: " << totalLenInternal << " (" << totalLenInternalP << "% of tree length)" << endl;
// out << "Sum of internal branch lengths divided by total tree length: "
// << totalLenInternal / totalLen << endl;
out << endl;
}
if (tree.isMixlen()) {
DoubleVector lenvec;
tree.treeLengths(lenvec);
out << "Class tree lengths: ";
for (int i = 0; i < lenvec.size(); i++)
out << " " << lenvec[i];
out << endl;
}
if (params.partition_type == TOPO_UNLINKED) {
out << "Tree topologies are unlinked across partitions, thus no drawing will be displayed here" << endl;
out << endl;
return;
}
//out << "ZERO BRANCH EPSILON = " << epsilon << endl;
int zero_internal_branches = tree.countZeroInternalBranches(NULL, NULL, epsilon);
if (zero_internal_branches > 0) {
//int zero_internal_branches = tree.countZeroInternalBranches(NULL, NULL, epsilon);
/*
out << "WARNING: " << zero_branches
<< " branches of near-zero lengths (<" << epsilon << ") and should be treated with caution!"
<< endl;
*/
out << "WARNING: " << zero_internal_branches
<< " near-zero internal branches (<" << epsilon << ") should be treated with caution"
<< endl;
/*
cout << endl << "WARNING: " << zero_branches
<< " branches of near-zero lengths (<" << epsilon << ") and should be treated with caution!"
<< endl;
*/
out << " Such branches are denoted by '**' in the figure below"
<< endl << endl;
}
int long_branches = tree.countLongBranches(NULL, NULL, params.max_branch_length-0.2);
if (long_branches > 0) {
//stringstream sstr;
out << "WARNING: " << long_branches << " too long branches (>"
<< params.max_branch_length-0.2 << ") should be treated with caution!" << endl;
//out << sstr.str();
//cout << sstr.str();
}
//<< "Total tree length: " << tree.treeLength() << endl << endl
tree.sortTaxa();
if (tree.rooted)
out << "NOTE: Tree is ROOTED at virtual root '" << tree.root->name << "'" << endl;
else
out << "NOTE: Tree is UNROOTED although outgroup taxon '" << tree.root->name << "' is drawn at root" << endl;
if (tree.isSuperTree() && params.partition_type == BRLEN_OPTIMIZE)
out << "NOTE: Branch lengths are weighted average over all partitions" << endl
<< " (weighted by the number of sites in the partitions)" << endl;
if (tree.isMixlen())
out << "NOTE: Branch lengths are weighted average over heterotachy classes" << endl;
bool is_codon = tree.aln->seq_type == SEQ_CODON;
if (tree.isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*) &tree;
is_codon = true;
for (PhyloSuperTree::iterator sit = stree->begin(); sit != stree->end(); sit++)
if ((*sit)->aln->seq_type != SEQ_CODON) {
is_codon = false;
break;
}
}
if (is_codon)
out << endl << "NOTE: Branch lengths are interpreted as number of nucleotide substitutions per codon site!"
<< endl << " Rescale them by 1/3 if you want to have #nt substitutions per nt site" << endl;
if (main_tree)
if (params.aLRT_replicates > 0 || params.gbo_replicates || (params.num_bootstrap_samples && params.compute_ml_tree)) {
out << "Numbers in parentheses are ";
if (params.aLRT_replicates > 0) {
out << "SH-aLRT support (%)";
if (params.localbp_replicates)
out << " / local bootstrap support (%)";
}
if (params.aLRT_test)
out << " / parametric aLRT support";
if (params.aBayes_test)
out << " / aBayes support";
if (params.num_bootstrap_samples && params.compute_ml_tree) {
if (params.aLRT_replicates > 0 || params.aLRT_test || params.aBayes_test)
out << " /";
out << " standard " << RESAMPLE_NAME << " support (%)";
}
if (params.gbo_replicates) {
if (params.aLRT_replicates > 0 || params.aLRT_test || params.aBayes_test)
out << " /";
out << " ultrafast " << RESAMPLE_NAME << " support (%)";
}
out << endl;
}
out << endl;
//tree.setExtendedFigChar();
tree.setRootNode(params.root, true);
tree.drawTree(out, WT_BR_SCALE, epsilon);
out << "Tree in newick format:";
if (tree.isMixlen())
out << " (class branch lengths are given in [...] and separated by '/' )";
if (tree.aln->seq_type == SEQ_POMO)
out << " (measured in mutations and frequency shifts)";
out << endl << endl;
tree.printTree(out, WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA);
out << endl << endl;
if (tree.aln->seq_type == SEQ_POMO) {
out << "Tree in newick format (measured in substitutions, see above):" << endl;
out << "WARNING: Only for comparison with substitution models." << endl;
out << " These are NOT the branch lengths inferred by PoMo." << endl << endl;
double len_scale_old = tree.len_scale;
int N = tree.aln->virtual_pop_size;
tree.len_scale = 1.0/(N*N);
tree.printTree(out, WT_BR_SCALE | WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA);
tree.len_scale = len_scale_old;
out << endl << endl;
}
tree.setRootNode(params.root, false);
}
void reportCredits(ofstream &out) {
out << "CREDITS" << endl << "-------" << endl << endl
<< "Some parts of the code were taken from the following packages/libraries:"
<< endl << endl
<< "Schmidt HA, Strimmer K, Vingron M, and von Haeseler A (2002)" << endl
<< "TREE-PUZZLE: maximum likelihood phylogenetic analysis using quartets" << endl
<< "and parallel computing. Bioinformatics, 18(3):502-504." << endl << endl
//<< "The source code to construct the BIONJ tree were taken from BIONJ software:"
//<< endl << endl
<< "Gascuel O (1997) BIONJ: an improved version of the NJ algorithm" << endl
<< "based on a simple model of sequence data. Mol. Bio. Evol., 14:685-695." << endl << endl
//<< "The Nexus file parser was taken from the Nexus Class Library:"
//<< endl << endl
<< "Paul O. Lewis (2003) NCL: a C++ class library for interpreting data files in" << endl
<< "NEXUS format. Bioinformatics, 19(17):2330-2331." << endl << endl
<< "Mascagni M and Srinivasan A (2000) Algorithm 806: SPRNG: A Scalable Library" << endl
<< "for Pseudorandom Number Generation. ACM Transactions on Mathematical Software," << endl
<< "26: 436-461." << endl << endl
<< "Guennebaud G, Jacob B, et al. (2010) Eigen v3. http://eigen.tuxfamily.org" << endl << endl;
/*
<< "The Modeltest 3.7 source codes were taken from:" << endl << endl
<< "David Posada and Keith A. Crandall (1998) MODELTEST: testing the model of"
<< endl << "DNA substitution. Bioinformatics, 14(9):817-8." << endl
*/
}
/***********************************************************
* CREATE REPORT FILE
***********************************************************/
extern StringIntMap pllTreeCounter;
void exhaustiveSearchGAMMAInvar(Params ¶ms, IQTree &iqtree);
void searchGAMMAInvarByRestarting(IQTree &iqtree);
void computeLoglFromUserInputGAMMAInvar(Params ¶ms, IQTree &iqtree);
void printOutfilesInfo(Params ¶ms, IQTree &tree) {
cout << endl << "Analysis results written to: " << endl;
if (!(params.suppress_output_flags & OUT_IQTREE))
cout<< " IQ-TREE report: " << params.out_prefix << ".iqtree"
<< endl;
if (params.compute_ml_tree) {
if (!(params.suppress_output_flags & OUT_TREEFILE)) {
if (params.model_name.find("ONLY") != string::npos || (params.model_name.substr(0,2)=="MF" && params.model_name.substr(0,3)!="MFP"))
cout << " Tree used for ModelFinder: " << params.out_prefix << ".treefile" << endl;
else {
cout << " Maximum-likelihood tree: " << params.out_prefix << ".treefile" << endl;
if (params.partition_type == BRLEN_OPTIMIZE && tree.isSuperTree())
cout << " Partition trees: " << params.out_prefix << ".parttrees" << endl;
}
}
// if (params.snni && params.write_local_optimal_trees) {
// cout << " Locally optimal trees (" << tree.candidateTrees.getNumLocalOptTrees() << "): " << params.out_prefix << ".suboptimal_trees" << endl;
// }
}
if (params.num_runs > 1)
cout << " Trees from independent runs: " << params.out_prefix << ".runtrees" << endl;
if (!params.user_file && params.start_tree == STT_BIONJ) {
cout << " BIONJ tree: " << params.out_prefix << ".bionj"
<< endl;
}
if (!params.dist_file) {
//cout << " Juke-Cantor distances: " << params.out_prefix << ".jcdist" << endl;
if (params.compute_ml_dist)
cout << " Likelihood distances: " << params.out_prefix
<< ".mldist" << endl;
if (params.print_conaln)
cout << " Concatenated alignment: " << params.out_prefix
<< ".conaln" << endl;
}
if ((params.model_name.find("TEST") != string::npos || params.model_name.substr(0,2) == "MF") && tree.isSuperTree()) {
cout << " Best partitioning scheme: " << params.out_prefix << ".best_scheme.nex" << endl;
bool raxml_format_printed = true;
for (auto it = ((SuperAlignment*)tree.aln)->partitions.begin();
it != ((SuperAlignment*)tree.aln)->partitions.end(); it++)
if (!(*it)->aln_file.empty()) {
raxml_format_printed = false;
break;
}
if (raxml_format_printed)
cout << " in RAxML format: " << params.out_prefix << ".best_scheme" << endl;
}
if ((tree.getRate()->getGammaShape() > 0 || params.partition_file) && params.print_site_rate)
cout << " Site-specific rates: " << params.out_prefix << ".rate"
<< endl;
if ((tree.getRate()->isSiteSpecificRate() || tree.getRate()->getPtnCat(0) >= 0) && params.print_site_rate)
cout << " Site-rates by MH model: " << params.out_prefix << ".rate"
<< endl;
if (params.print_site_lh)
cout << " Site log-likelihoods: " << params.out_prefix << ".sitelh"
<< endl;
if (params.print_partition_lh)
cout << " Partition log-likelihoods: " << params.out_prefix << ".partlh"
<< endl;
if (params.print_site_prob)
cout << " Site probability per rate/mix: " << params.out_prefix << ".siteprob"
<< endl;
if (params.print_ancestral_sequence) {
cout << " Ancestral state: " << params.out_prefix << ".state" << endl;
// cout << " Ancestral sequences: " << params.out_prefix << ".aseq" << endl;
}
if (params.write_intermediate_trees)
cout << " All intermediate trees: " << params.out_prefix << ".treels"
<< endl;
if (params.writeDistImdTrees) {
tree.intermediateTrees.printTrees(string("ditrees"));
cout << " Distinct intermediate trees: " << params.out_prefix << ".ditrees" << endl;
cout << " Logl of intermediate trees: " << params.out_prefix << ".ditrees_lh" << endl;
}
if (params.gbo_replicates) {
cout << endl << "Ultrafast " << RESAMPLE_NAME << " approximation results written to:" << endl;
if (!tree.isSuperTreeUnlinked())
cout << " Split support values: " << params.out_prefix << ".splits.nex" << endl
<< " Consensus tree: " << params.out_prefix << ".contree" << endl;
if (params.print_ufboot_trees)
cout << " UFBoot trees: " << params.out_prefix << ".ufboot" << endl;
}
if (!params.treeset_file.empty()) {
cout << " Evaluated user trees: " << params.out_prefix << ".trees" << endl;
if (params.print_tree_lh) {
cout << " Tree log-likelihoods: " << params.out_prefix << ".treelh" << endl;
}
}
if (params.lmap_num_quartets >= 0) {
cout << " Likelihood mapping plot (SVG): " << params.out_prefix << ".lmap.svg" << endl;
cout << " Likelihood mapping plot (EPS): " << params.out_prefix << ".lmap.eps" << endl;
}
if (!(params.suppress_output_flags & OUT_LOG))
cout << " Screen log file: " << params.out_prefix << ".log" << endl;
/* if (params.model_name == "WHTEST")
cout <<" WH-TEST report: " << params.out_prefix << ".whtest" << endl;*/
cout << endl;
}
void reportPhyloAnalysis(Params ¶ms, IQTree &tree, ModelCheckpoint &model_info) {
if (!MPIHelper::getInstance().isMaster()) {
return;
}
if (params.suppress_output_flags & OUT_IQTREE) {
printOutfilesInfo(params, tree);
return;
}
if (params.count_trees) {
// addon: print #distinct trees
cout << endl << "NOTE: " << pllTreeCounter.size() << " distinct trees evaluated during whole tree search" << endl;
IntVector counts;
for (StringIntMap::iterator i = pllTreeCounter.begin(); i != pllTreeCounter.end(); i++) {
if (i->second > counts.size())
counts.resize(i->second+1, 0);
counts[i->second]++;
}
for (IntVector::iterator i2 = counts.begin(); i2 != counts.end(); i2++) {
if (*i2 != 0) {
cout << "#Trees occurring " << (i2-counts.begin()) << " times: " << *i2 << endl;
}
}
}
string outfile = params.out_prefix;
outfile += ".iqtree";
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(outfile.c_str());
out << "IQ-TREE " << iqtree_VERSION_MAJOR << "." << iqtree_VERSION_MINOR
<< iqtree_VERSION_PATCH << " built " << __DATE__ << endl
<< endl;
if (params.partition_file)
out << "Partition file name: " << params.partition_file << endl;
if (params.aln_file)
out << "Input file name: " << params.aln_file << endl;
if (params.user_file)
out << "User tree file name: " << params.user_file << endl;
out << "Type of analysis: ";
bool modelfinder = params.model_name.substr(0,4)=="TEST" || params.model_name.substr(0,2) == "MF" || params.model_name.empty();
if (modelfinder)
out << "ModelFinder";
if (params.compute_ml_tree) {
if (modelfinder)
out << " + ";
out << "tree reconstruction";
}
if (params.num_bootstrap_samples > 0) {
if (params.compute_ml_tree)
out << " + ";
out << "non-parametric " << RESAMPLE_NAME << " (" << params.num_bootstrap_samples
<< " replicates)";
}
if (params.gbo_replicates > 0) {
out << " + ultrafast " << RESAMPLE_NAME << " (" << params.gbo_replicates << " replicates)";
}
out << endl;
out << "Random seed number: " << params.ran_seed << endl << endl;
out << "REFERENCES" << endl << "----------" << endl << endl;
reportReferences(params, out);
out << "SEQUENCE ALIGNMENT" << endl << "------------------" << endl
<< endl;
if (tree.isSuperTree()) {
// TODO DS: Changes may be needed here for PoMo.
out << "Input data: " << tree.aln->getNSeq()+tree.removed_seqs.size() << " taxa with "
<< tree.aln->getNSite() << " partitions and "
<< tree.getAlnNSite() << " total sites ("
<< ((SuperAlignment*)tree.aln)->computeMissingData()*100 << "% missing data)" << endl << endl;
PhyloSuperTree *stree = (PhyloSuperTree*) &tree;
int namelen = stree->getMaxPartNameLength();
int part;
out.width(max(namelen+6,10));
out << left << " ID Name" << " Type\tSeq\tSite\tUnique\tInfor\tInvar\tConst" << endl;
//out << string(namelen+54, '-') << endl;
part = 0;
for (PhyloSuperTree::iterator it = stree->begin(); it != stree->end(); it++, part++) {
//out << "FOR PARTITION " << stree->part_info[part].name << ":" << endl << endl;
//reportAlignment(out, *((*it)->aln));
out.width(4);
out << right << part+1 << " ";
out.width(max(namelen,4));
out << left << (*it)->aln->name << " ";
switch ((*it)->aln->seq_type) {
case SEQ_BINARY: out << "BIN"; break;
case SEQ_CODON: out << "CODON"; break;
case SEQ_DNA: out << "DNA"; break;
case SEQ_MORPH: out << "MORPH"; break;
case SEQ_MULTISTATE: out << "MULTI"; break;
case SEQ_PROTEIN: out << "AA"; break;
case SEQ_POMO: out << "POMO"; break;
case SEQ_UNKNOWN: out << "???"; break;
}
out << "\t" << (*it)->aln->getNSeq() << "\t" << (*it)->aln->getNSite()
<< "\t" << (*it)->aln->getNPattern() << "\t" << (*it)->aln->num_informative_sites
<< "\t" << (*it)->getAlnNSite() - (*it)->aln->num_variant_sites
<< "\t" << int((*it)->aln->frac_const_sites*(*it)->getAlnNSite()) << endl;
}
out << endl << "Column meanings:" << endl
<< " Unique: Number of unique site patterns" << endl
<< " Infor: Number of parsimony-informative sites" << endl
<< " Invar: Number of invariant sites" << endl
<< " Const: Number of constant sites (can be subset of invariant sites)" << endl << endl;
} else
reportAlignment(out, *(tree.aln), tree.removed_seqs.size());
out.precision(4);
out << fixed;
if (!model_info.empty()) {
out << "ModelFinder" << endl << "-----------" << endl << endl;
// if (tree.isSuperTree())
// pruneModelInfo(model_info, (PhyloSuperTree*)&tree);
reportModelSelection(out, params, &model_info, &tree);
}
out << "SUBSTITUTION PROCESS" << endl << "--------------------" << endl
<< endl;
if (tree.isSuperTree()) {
if(params.partition_type == BRLEN_SCALE)
out << "Edge-linked-proportional partition model with ";
else if(params.partition_type == BRLEN_FIX)
out << "Edge-linked-equal partition model with ";
else if (params.partition_type == BRLEN_OPTIMIZE)
out << "Edge-unlinked partition model with ";
else
out << "Topology-unlinked partition model with ";
if (params.model_joint)
out << "joint substitution model ";
else
out << "separate substitution models ";
if (params.link_alpha)
out << "and joint gamma shape";
else
out << "and separate rates across sites";
out << endl << endl;
PhyloSuperTree *stree = (PhyloSuperTree*) &tree;
PhyloSuperTree::iterator it;
int part;
if(params.partition_type == BRLEN_OPTIMIZE || params.partition_type == TOPO_UNLINKED)
out << " ID Model TreeLen Parameters" << endl;
else
out << " ID Model Speed Parameters" << endl;
//out << "-------------------------------------" << endl;
for (it = stree->begin(), part = 0; it != stree->end(); it++, part++) {
out.width(4);
out << right << (part+1) << " ";
out.width(14);
if(params.partition_type == BRLEN_OPTIMIZE || params.partition_type == TOPO_UNLINKED)
out << left << (*it)->getModelName() << " " << (*it)->treeLength() << " " << (*it)->getModelNameParams() << endl;
else
out << left << (*it)->getModelName() << " " << stree->part_info[part].part_rate << " " << (*it)->getModelNameParams() << endl;
}
out << endl;
/*
for (it = stree->begin(), part = 0; it != stree->end(); it++, part++) {
reportModel(out, *(*it));
reportRate(out, *(*it));
}*/
PartitionModel *part_model = (PartitionModel*)tree.getModelFactory();
for (auto itm = part_model->linked_models.begin(); itm != part_model->linked_models.end(); itm++) {
for (it = stree->begin(); it != stree->end(); it++)
if ((*it)->getModel() == itm->second) {
out << "Linked model of substitution: " << itm->second->getName() << endl << endl;
bool fixed = (*it)->getModel()->fixParameters(false);
reportModel(out, (*it)->aln, (*it)->getModel());
(*it)->getModel()->fixParameters(fixed);
break;
}
}
} else {
reportModel(out, tree);
reportRate(out, tree);
}
if (params.lmap_num_quartets >= 0) {
tree.reportLikelihoodMapping(out);
}
/*
out << "RATE HETEROGENEITY" << endl << "------------------" << endl
<< endl;
if (tree.isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*) &tree;
int part = 0;
for (PhyloSuperTree::iterator it = stree->begin();
it != stree->end(); it++, part++) {
out << "FOR PARTITION " << stree->part_info[part].name << ":"
<< endl << endl;
reportRate(out, *(*it));
}
} else
reportRate(out, tree);
*/
// Bootstrap analysis:
//Display as outgroup: a
if (params.model_name == "WHTEST") {
out << "TEST OF MODEL HOMOGENEITY" << endl
<< "-------------------------" << endl << endl;
out << "Delta of input data: "
<< params.whtest_delta << endl;
out << ".95 quantile of Delta distribution: "
<< params.whtest_delta_quantile << endl;
out << "Number of simulations performed: "
<< params.whtest_simulations << endl;
out << "P-value: "
<< params.whtest_p_value << endl;
if (params.whtest_p_value < 0.05) {
out
<< "RESULT: Homogeneity assumption is rejected (p-value cutoff 0.05)"
<< endl;
} else {
out
<< "RESULT: Homogeneity assumption is NOT rejected (p-value cutoff 0.05)"
<< endl;
}
out << endl << "*** For this result please cite:" << endl << endl;
out
<< "G. Weiss and A. von Haeseler (2003) Testing substitution models"
<< endl
<< "within a phylogenetic tree. Mol. Biol. Evol, 20(4):572-578"
<< endl << endl;
}
if (params.num_runs > 1) {
out << "MULTIPLE RUNS" << endl
<< "-------------" << endl << endl;
out << "Run logL" << endl;
DoubleVector runLnL;
tree.getCheckpoint()->getVector("runLnL", runLnL);
for (int run = 0; run < runLnL.size(); run++)
out << run+1 << "\t" << fixed << runLnL[run] << endl;
out << endl;
}
/*
out << "TREE SEARCH" << endl << "-----------" << endl << endl
<< "Stopping rule: "
<< ((params.stop_condition == SC_STOP_PREDICT) ? "Yes" : "No")
<< endl << "Number of iterations: "
<< tree.stop_rule.getNumIterations() << endl
<< "Probability of deleting sequences: " << params.p_delete
<< endl << "Number of representative leaves: "
<< params.k_representative << endl
<< "NNI log-likelihood cutoff: " << tree.getNNICutoff() << endl
<< endl;
*/
if (params.compute_ml_tree) {
if (params.model_name.find("ONLY") != string::npos || (params.model_name.substr(0,2) == "MF" && params.model_name.substr(0,3) != "MFP")) {
out << "TREE USED FOR ModelFinder" << endl
<< "-------------------------" << endl << endl;
} else if (params.min_iterations == 0) {
if (params.user_file)
out << "USER TREE" << endl
<< "---------" << endl << endl;
else
out << "STARTING TREE" << endl
<< "-------------" << endl << endl;
} else {
out << "MAXIMUM LIKELIHOOD TREE" << endl
<< "-----------------------" << endl << endl;
}
tree.setRootNode(params.root);
if (params.gbo_replicates) {
if (tree.boot_consense_logl > tree.getBestScore() + 0.1 && !tree.isSuperTreeUnlinked()) {
out << endl << "**NOTE**: Consensus tree has higher likelihood than ML tree found! Please use consensus tree below." << endl;
}
}
reportTree(out, params, tree, tree.getBestScore(), tree.logl_variance, true);
if (tree.isSuperTree() && verbose_mode >= VB_MED) {
PhyloSuperTree *stree = (PhyloSuperTree*) &tree;
// stree->mapTrees();
// int empty_branches = stree->countEmptyBranches();
// if (empty_branches) {
// stringstream ss;
// ss << empty_branches << " branches in the overall tree with no phylogenetic information due to missing data!";
// outWarning(ss.str());
// }
int part = 0;
for (PhyloSuperTree::iterator it = stree->begin();
it != stree->end(); it++, part++) {
out << "FOR PARTITION " << (*it)->aln->name
<< ":" << endl << endl;
(*it)->setRootNode(params.root);
// reportTree(out, params, *(*it), (*it)->computeLikelihood(), (*it)->computeLogLVariance(), false);
reportTree(out, params, *(*it), stree->part_info[part].cur_score, 0.0, false);
}
}
}
/*
if (params.write_intermediate_trees) {
out << endl << "CONSENSUS OF INTERMEDIATE TREES" << endl << "-----------------------" << endl << endl
<< "Number of intermediate trees: " << tree.stop_rule.getNumIterations() << endl
<< "Split threshold: " << params.split_threshold << endl
<< "Burn-in: " << params.tree_burnin << endl << endl;
}*/
if (params.consensus_type == CT_CONSENSUS_TREE && !tree.isSuperTreeUnlinked()) {
out << "CONSENSUS TREE" << endl << "--------------" << endl << endl;
out << "Consensus tree is constructed from "
<< (params.num_bootstrap_samples ? params.num_bootstrap_samples : params.gbo_replicates)
<< " " << RESAMPLE_NAME << " trees";
if (params.gbo_replicates || params.num_bootstrap_samples) {
out << endl << "Log-likelihood of consensus tree: " << fixed << tree.boot_consense_logl;
}
string con_file = params.out_prefix;
con_file += ".contree";
// -- Mon Apr 17 21:14:53 BST 2017
// DONE Minh: merged correctly
if (params.compute_ml_tree)
out << endl << "Robinson-Foulds distance between ML tree and consensus tree: "
<< tree.contree_rfdist << endl;
// --
out << endl << "Branches with support >"
<< floor(params.split_threshold * 1000) / 10 << "% are kept";
if (params.split_threshold == 0.0)
out << " (extended consensus)";
if (params.split_threshold == 0.5)
out << " (majority-rule consensus)";
if (params.split_threshold >= 0.99)
out << " (strict consensus)";
out << endl << "Branch lengths are optimized by maximum likelihood on original alignment" << endl;
out << "Numbers in parentheses are " << RESAMPLE_NAME << " supports (%)" << endl << endl;
bool rooted = false;
MTree contree;
contree.readTree(con_file.c_str(), rooted);
contree.drawTree(out, WT_BR_SCALE);
out << endl << "Consensus tree in newick format: " << endl << endl;
contree.printTree(out);
out << endl << endl;
// tree.freeNode();
// tree.root = NULL;
// tree.readTree(con_file.c_str(), rooted);
// if (removed_seqs.size() > 0) {
// tree.reinsertIdenticalSeqs(tree.aln, removed_seqs, twin_seqs);
// }
// tree.setAlignment(tree.aln);
// bug fix
// if ((tree.sse == LK_EIGEN || tree.sse == LK_EIGEN_SSE) && !tree.isBifurcating()) {
// cout << "NOTE: Changing to old kernel as consensus tree is multifurcating" << endl;
// tree.changeLikelihoodKernel(LK_SSE);
// }
// tree.initializeAllPartialLh();
// tree.fixNegativeBranch(false);
// if (tree.isSuperTree())
// ((PhyloSuperTree*) &tree)->mapTrees();
// tree.optimizeAllBranches();
// tree.printTree(con_file.c_str(), WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA);
// tree.sortTaxa();
// tree.drawTree(out, WT_BR_SCALE);
// out << endl << "Consensus tree in newick format: " << endl << endl;
// tree.printResultTree(out);
// out << endl << endl;
}
#ifdef IQTREE_TERRAPHAST
if (params.terrace_analysis && params.compute_ml_tree) {
out << "TERRACE ANALYSIS" << endl << "----------------" << endl << endl;
cout << "Running additional analysis: Phylogenetic Terraces ..."<< endl;
string filename = params.out_prefix;
filename += ".terrace";
try
{
Terrace terrace(tree, (SuperAlignment*)(tree.aln));
uint64_t terrace_size = terrace.getSize();
if (terrace_size == 1) {
out << "The tree does not lie on a terrace." << endl;
} else {
out << "The tree lies on a terrace of size ";
if (terrace_size == UINT64_MAX) {
out << "at least " << terrace_size << " (integer overflow)";
} else {
out << terrace_size;
}
out << endl;
ofstream terraceout;
terraceout.open(filename.c_str());
terrace.printTreesCompressed(terraceout);
terraceout.close();
out << "Terrace trees written (in compressed Newick format) to " << filename << endl;
}
}
catch (std::exception& e)
{
out << "ERROR: Terrace analysis using Terraphast failed: " << e.what() << endl << endl;
}
out << endl;
out << "For documentation, see the technical supplement to Biczok et al. (2018)" << endl;
out << "https://doi.org/10.1093/bioinformatics/bty384";
out << endl << endl;
cout<< "Done. Results are written in "<<params.out_prefix<<".iqtree file."<<endl;
}
#endif
/* evaluate user trees */
vector<TreeInfo> info;
IntVector distinct_trees;
if (!params.treeset_file.empty()) {
evaluateTrees(params.treeset_file, params, &tree, info, distinct_trees);
out.precision(4);
out.setf(ios_base::fixed);
out << endl << "USER TREES" << endl << "----------" << endl << endl;
out << "See " << params.out_prefix << ".trees for trees with branch lengths." << endl << endl;
if (params.topotest_replicates && info.size() > 1) {
if (params.do_au_test && params.topotest_replicates < 10000)
out << "WARNING: Too few replicates for AU test. At least -zb 10000 for reliable results!" << endl << endl;
out << "Tree logL deltaL bp-RELL p-KH p-SH ";
if (params.do_weighted_test)
out << "p-WKH p-WSH ";
out << " c-ELW";
if (params.do_au_test)
out << " p-AU";
out << endl << "------------------------------------------------------------------";
if (params.do_weighted_test)
out << "------------------";
if (params.do_au_test)
out << "-------";
out << endl;
} else {
out << "Tree logL deltaL" << endl;
out << "-------------------------" << endl;
}
double maxL = -DBL_MAX;
int tid, orig_id;
for (tid = 0; tid < info.size(); tid++)
if (info[tid].logl > maxL) maxL = info[tid].logl;
for (orig_id = 0, tid = 0; orig_id < distinct_trees.size(); orig_id++) {
out.width(3);
out << right << orig_id+1 << " ";
if (distinct_trees[orig_id] >= 0) {
out << " = tree " << distinct_trees[orig_id]+1 << endl;
continue;
}
out.unsetf(ios::fixed);
out.precision(10);
out.width(12);
out << info[tid].logl << " ";
out.width(7);
out.precision(5);
out << maxL - info[tid].logl;
if (!params.topotest_replicates || info.size() <= 1) {
out << endl;
tid++;
continue;
}
out.precision(3);
out << " ";
out.width(6);
out << info[tid].rell_bp;
if (info[tid].rell_confident)
out << " + ";
else
out << " - ";
out.width(6);
out << right << info[tid].kh_pvalue;
if (info[tid].kh_pvalue < 0.05)
out << " - ";
else
out << " + ";
out.width(6);
out << right << info[tid].sh_pvalue;
if (info[tid].sh_pvalue < 0.05)
out << " - ";
else
out << " + ";
if (params.do_weighted_test) {
out.width(6);
out << right << info[tid].wkh_pvalue;
if (info[tid].wkh_pvalue < 0.05)
out << " - ";
else
out << " + ";
out.width(6);
out << right << info[tid].wsh_pvalue;
if (info[tid].wsh_pvalue < 0.05)
out << " - ";
else
out << " + ";
}
out.width(9);
out << right << info[tid].elw_value;
if (info[tid].elw_confident)
out << " + ";
else
out << " - ";
if (params.do_au_test) {
out.width(8);
out << right << info[tid].au_pvalue;
if (info[tid].au_pvalue < 0.05)
out << " - ";
else
out << " + ";
}
out.setf(ios::fixed);
out << endl;
tid++;
}
out << endl;
if (params.topotest_replicates) {
out << "deltaL : logL difference from the maximal logl in the set." << endl
<< "bp-RELL : bootstrap proportion using RELL method (Kishino et al. 1990)." << endl
<< "p-KH : p-value of one sided Kishino-Hasegawa test (1989)." << endl
<< "p-SH : p-value of Shimodaira-Hasegawa test (2000)." << endl;
if (params.do_weighted_test) {
out << "p-WKH : p-value of weighted KH test." << endl
<< "p-WSH : p-value of weighted SH test." << endl;
}
out << "c-ELW : Expected Likelihood Weight (Strimmer & Rambaut 2002)." << endl;
if (params.do_au_test) {
out << "p-AU : p-value of approximately unbiased (AU) test (Shimodaira, 2002)." << endl;
}
out << endl
<< "Plus signs denote the 95% confidence sets." << endl
<< "Minus signs denote significant exclusion." << endl
<< "All tests performed "
<< params.topotest_replicates << " resamplings using the RELL method."<<endl;
}
out << endl;
}
time_t cur_time;
time(&cur_time);
char *date_str;
date_str = ctime(&cur_time);
out.unsetf(ios_base::fixed);
out << "TIME STAMP" << endl << "----------" << endl << endl
<< "Date and time: " << date_str << "Total CPU time used: "
<< (double) params.run_time << " seconds (" << convert_time(params.run_time) << ")" << endl
<< "Total wall-clock time used: " << getRealTime() - params.start_real_time
<< " seconds (" << convert_time(getRealTime() - params.start_real_time) << ")" << endl << endl;
//reportCredits(out); // not needed, now in the manual
out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, outfile);
}
printOutfilesInfo(params, tree);
}
void checkZeroDist(Alignment *aln, double *dist) {
int ntaxa = aln->getNSeq();
IntVector checked;
checked.resize(ntaxa, 0);
int i, j;
for (i = 0; i < ntaxa - 1; i++) {
if (checked[i])
continue;
string str = "";
bool first = true;
for (j = i + 1; j < ntaxa; j++)
if (dist[i * ntaxa + j] <= Params::getInstance().min_branch_length) {
if (first)
str = "ZERO distance between sequences "
+ aln->getSeqName(i);
str += ", " + aln->getSeqName(j);
checked[j] = 1;
first = false;
}
checked[i] = 1;
if (str != "")
outWarning(str);
}
}
void printAnalysisInfo(int model_df, IQTree& iqtree, Params& params) {
// if (!params.raxmllib) {
cout << "Model of evolution: ";
if (iqtree.isSuperTree()) {
cout << iqtree.getModelName() << " (" << model_df << " free parameters)" << endl;
} else {
cout << iqtree.getModelName() << " with ";
switch (iqtree.getModel()->getFreqType()) {
case FREQ_EQUAL:
cout << "equal";
break;
case FREQ_EMPIRICAL:
cout << "counted";
break;
case FREQ_USER_DEFINED:
cout << "user-defined";
break;
case FREQ_ESTIMATE:
cout << "optimized";
break;
case FREQ_CODON_1x4:
cout << "counted 1x4";
break;
case FREQ_CODON_3x4:
cout << "counted 3x4";
break;
case FREQ_CODON_3x4C:
cout << "counted 3x4-corrected";
break;
case FREQ_DNA_RY:
cout << "constrained A+G=C+T";
break;
case FREQ_DNA_WS:
cout << "constrained A+T=C+G";
break;
case FREQ_DNA_MK:
cout << "constrained A+C=G+T";
break;
case FREQ_DNA_1112:
cout << "constrained A=C=G";
break;
case FREQ_DNA_1121:
cout << "constrained A=C=T";
break;
case FREQ_DNA_1211:
cout << "constrained A=G=T";
break;
case FREQ_DNA_2111:
cout << "constrained C=G=T";
break;
case FREQ_DNA_1122:
cout << "constrained A=C,G=T";
break;
case FREQ_DNA_1212:
cout << "constrained A=G,C=T";
break;
case FREQ_DNA_1221:
cout << "constrained A=T,C=G";
break;
case FREQ_DNA_1123:
cout << "constrained A=C";
break;
case FREQ_DNA_1213:
cout << "constrained A=G";
break;
case FREQ_DNA_1231:
cout << "constrained A=T";
break;
case FREQ_DNA_2113:
cout << "constrained C=G";
break;
case FREQ_DNA_2131:
cout << "constrained C=T";
break;
case FREQ_DNA_2311:
cout << "constrained G=T";
break;
default:
outError("Wrong specified state frequencies");
}
cout << " frequencies (" << model_df << " free parameters)" << endl;
}
cout << "Fixed branch lengths: "
<< ((params.fixed_branch_length) ? "Yes" : "No") << endl;
if (params.min_iterations > 0) {
cout << "Tree search algorithm: " << (params.snni ? "Stochastic nearest neighbor interchange" : "IQPNNI") << endl;
cout << "Termination condition: ";
if (params.stop_condition == SC_REAL_TIME) {
cout << "after " << params.maxtime << " minutes" << endl;
} else if (params.stop_condition == SC_UNSUCCESS_ITERATION) {
cout << "after " << params.unsuccess_iteration << " unsuccessful iterations" << endl;
} else if (params.stop_condition == SC_FIXED_ITERATION) {
cout << params.min_iterations << " iterations" << endl;
} else if(params.stop_condition == SC_WEIBULL) {
cout << "predicted in [" << params.min_iterations << ","
<< params.max_iterations << "] (confidence "
<< params.stop_confidence << ")" << endl;
} else if (params.stop_condition == SC_BOOTSTRAP_CORRELATION) {
cout << "min " << params.min_correlation << " correlation coefficient" << endl;
}
if (!params.snni) {
cout << "Number of representative leaves : " << params.k_representative << endl;
cout << "Probability of deleting sequences: " << iqtree.getProbDelete() << endl;
cout << "Number of leaves to be deleted : " << iqtree.getDelete() << endl;
cout << "Important quartets assessed on: "
<< ((params.iqp_assess_quartet == IQP_DISTANCE) ?
"Distance" : ((params.iqp_assess_quartet == IQP_PARSIMONY) ? "Parsimony" : "Bootstrap"))
<< endl;
}
cout << "NNI assessed on: " << ((params.nni5) ? "5 branches" : "1 branch") << endl;
}
cout << "Phylogenetic likelihood library: " << (params.pll ? "Yes" : "No") << endl;
if (params.fixed_branch_length != BRLEN_FIX)
cout << "Branch length optimization method: "
<< ((iqtree.optimize_by_newton) ? "Newton" : "Brent") << endl;
cout << "Number of Newton-Raphson steps in NNI evaluation and branch length optimization: " << NNI_MAX_NR_STEP
<< " / " << PLL_NEWZPERCYCLE << endl;
cout << "SSE instructions: "
<< ((iqtree.sse) ? "Yes" : "No") << endl;
cout << endl;
}
void computeMLDist(Params& params, IQTree& iqtree, double begin_time) {
double longest_dist;
// stringstream best_tree_string;
// iqtree.printTree(best_tree_string, WT_BR_LEN + WT_TAXON_ID);
cout << "Computing ML distances based on estimated model parameters...";
double *ml_dist = NULL;
double *ml_var = NULL;
longest_dist = iqtree.computeDist(params, iqtree.aln, ml_dist, ml_var, iqtree.dist_file);
cout << " " << (getCPUTime() - begin_time) << " sec" << endl;
double max_genetic_dist = MAX_GENETIC_DIST;
if (iqtree.aln->seq_type == SEQ_POMO) {
int N = iqtree.aln->virtual_pop_size;
max_genetic_dist *= N * N;
}
if (longest_dist > max_genetic_dist * 0.99) {
outWarning("Some pairwise ML distances are too long (saturated)");
//cout << "Some ML distances are too long, using old distances..." << endl;
} //else
{
if ( !iqtree.dist_matrix ) {
iqtree.dist_matrix = new double[iqtree.aln->getNSeq() * iqtree.aln->getNSeq()];
}
if ( !iqtree.var_matrix ) {
iqtree.var_matrix = new double[iqtree.aln->getNSeq() * iqtree.aln->getNSeq()];
}
memmove(iqtree.dist_matrix, ml_dist,
sizeof (double) * iqtree.aln->getNSeq() * iqtree.aln->getNSeq());
memmove(iqtree.var_matrix, ml_var,
sizeof(double) * iqtree.aln->getNSeq() * iqtree.aln->getNSeq());
}
delete[] ml_dist;
delete[] ml_var;
}
void computeInitialDist(Params ¶ms, IQTree &iqtree) {
double longest_dist;
if (params.dist_file) {
cout << "Reading distance matrix file " << params.dist_file << " ..." << endl;
} else if (params.compute_jc_dist) {
cout << "Computing Juke-Cantor distances..." << endl;
} else if (params.compute_obs_dist) {
cout << "Computing observed distances..." << endl;
}
if (params.compute_jc_dist || params.compute_obs_dist || params.partition_file) {
longest_dist = iqtree.computeDist(params, iqtree.aln, iqtree.dist_matrix, iqtree.var_matrix, iqtree.dist_file);
checkZeroDist(iqtree.aln, iqtree.dist_matrix);
double max_genetic_dist = MAX_GENETIC_DIST;
if (iqtree.aln->seq_type == SEQ_POMO) {
int N = iqtree.aln->virtual_pop_size;
max_genetic_dist *= N * N;
}
if (longest_dist > max_genetic_dist * 0.99) {
outWarning("Some pairwise distances are too long (saturated)");
}
}
}
void initializeParams(Params ¶ms, IQTree &iqtree)
{
// iqtree.setCurScore(-DBL_MAX);
bool ok_tree = iqtree.root;
if (iqtree.isSuperTreeUnlinked())
ok_tree = ((PhyloSuperTree*)&iqtree)->front()->root;
if (!ok_tree)
{
// compute initial tree
iqtree.computeInitialTree(params.SSE);
}
ASSERT(iqtree.aln);
if (iqtree.aln->model_name == "WHTEST") {
if (iqtree.aln->seq_type != SEQ_DNA)
outError("Weiss & von Haeseler test of model homogeneity only works for DNA");
iqtree.aln->model_name = "GTR+G";
}
if (params.gbo_replicates)
params.speed_conf = 1.0;
// TODO: check if necessary
// if (iqtree.isSuperTree())
// ((PhyloSuperTree*) &iqtree)->mapTrees();
// set parameter for the current tree
// iqtree.setParams(params);
}
void pruneTaxa(Params ¶ms, IQTree &iqtree, double *pattern_lh, NodeVector &pruned_taxa, StrVector &linked_name) {
int num_low_support;
double mytime;
if (params.aLRT_threshold <= 100 && (params.aLRT_replicates > 0 || params.localbp_replicates > 0)) {
mytime = getCPUTime();
cout << "Testing tree branches by SH-like aLRT with " << params.aLRT_replicates << " replicates..." << endl;
iqtree.setRootNode(params.root);
double curScore = iqtree.getCurScore();
iqtree.computePatternLikelihood(pattern_lh, &curScore);
num_low_support = iqtree.testAllBranches(params.aLRT_threshold, curScore,
pattern_lh, params.aLRT_replicates, params.localbp_replicates, params.aLRT_test, params.aBayes_test);
iqtree.printResultTree();
cout << " " << getCPUTime() - mytime << " sec." << endl;
cout << num_low_support << " branches show low support values (<= " << params.aLRT_threshold << "%)" << endl;
//tree.drawTree(cout);
cout << "Collapsing stable clades..." << endl;
iqtree.collapseStableClade(params.aLRT_threshold, pruned_taxa, linked_name, iqtree.dist_matrix);
cout << pruned_taxa.size() << " taxa were pruned from stable clades" << endl;
}
if (!pruned_taxa.empty()) {
cout << "Pruned alignment contains " << iqtree.aln->getNSeq()
<< " sequences and " << iqtree.aln->getNSite() << " sites and "
<< iqtree.aln->getNPattern() << " patterns" << endl;
//tree.clearAllPartialLh();
iqtree.initializeAllPartialLh();
iqtree.clearAllPartialLH();
iqtree.setCurScore(iqtree.optimizeAllBranches());
//cout << "Log-likelihood after reoptimizing model parameters: " << tree.curScore << endl;
// pair<int, int> nniInfo = iqtree.optimizeNNI();
iqtree.optimizeNNI();
cout << "Log-likelihood after optimizing partial tree: "
<< iqtree.getCurScore() << endl;
}
}
void restoreTaxa(IQTree &iqtree, double *saved_dist_mat, NodeVector &pruned_taxa, StrVector &linked_name) {
if (!pruned_taxa.empty()) {
cout << "Restoring full tree..." << endl;
iqtree.restoreStableClade(iqtree.aln, pruned_taxa, linked_name);
delete[] iqtree.dist_matrix;
iqtree.dist_matrix = saved_dist_mat;
iqtree.initializeAllPartialLh();
iqtree.clearAllPartialLH();
iqtree.setCurScore(iqtree.optimizeAllBranches());
//cout << "Log-likelihood after reoptimizing model parameters: " << tree.curScore << endl;
pair<int, int> nniInfo;
nniInfo = iqtree.optimizeNNI();
cout << "Log-likelihood after reoptimizing full tree: " << iqtree.getCurScore() << endl;
//iqtree.setBestScore(iqtree.getModelFactory()->optimizeParameters(params.fixed_branch_length, true, params.model_eps));
}
}
void runApproximateBranchLengths(Params ¶ms, IQTree &iqtree) {
if (!params.fixed_branch_length && params.leastSquareBranch) {
cout << endl << "Computing Least Square branch lengths..." << endl;
iqtree.optimizeAllBranchesLS();
iqtree.clearAllPartialLH();
iqtree.setCurScore(iqtree.computeLikelihood());
string filename = params.out_prefix;
filename += ".lstree";
iqtree.printTree(filename.c_str(), WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA | WT_NEWLINE);
cout << "Logl of tree with LS branch lengths: " << iqtree.getCurScore() << endl;
cout << "Tree with LS branch lengths written to " << filename << endl;
if (params.print_branch_lengths) {
if (params.manuel_analytic_approx) {
cout << "Applying Manuel's analytic approximation.." << endl;
iqtree.approxAllBranches();
}
ofstream out;
filename = params.out_prefix;
filename += ".lsbrlen";
out.open(filename.c_str());
iqtree.printBranchLengths(out);
out.close();
cout << "LS Branch lengths written to " << filename << endl;
}
cout << "Total LS tree length: " << iqtree.treeLength() << endl;
}
if (params.pars_branch_length) {
cout << endl << "Computing parsimony branch lengths..." << endl;
iqtree.fixNegativeBranch(true);
iqtree.clearAllPartialLH();
iqtree.setCurScore(iqtree.computeLikelihood());
string filename = params.out_prefix;
filename += ".mptree";
iqtree.printTree(filename.c_str(), WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA | WT_NEWLINE);
cout << "Logl of tree with MP branch lengths: " << iqtree.getCurScore() << endl;
cout << "Tree with MP branch lengths written to " << filename << endl;
if (params.print_branch_lengths) {
ofstream out;
filename = params.out_prefix;
filename += ".mpbrlen";
out.open(filename.c_str());
iqtree.printBranchLengths(out);
out.close();
cout << "MP Branch lengths written to " << filename << endl;
}
cout << "Total MP tree length: " << iqtree.treeLength() << endl;
}
if (params.bayes_branch_length) {
cout << endl << "Computing Bayesian branch lengths..." << endl;
iqtree.computeAllBayesianBranchLengths();
iqtree.clearAllPartialLH();
iqtree.setCurScore(iqtree.computeLikelihood());
string filename = params.out_prefix;
filename += ".batree";
iqtree.printTree(filename.c_str(), WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA | WT_NEWLINE);
cout << "Logl of tree with Bayesian branch lengths: " << iqtree.getCurScore() << endl;
cout << "Tree with Bayesian branch lengths written to " << filename << endl;
if (params.print_branch_lengths) {
ofstream out;
filename = params.out_prefix;
filename += ".babrlen";
out.open(filename.c_str());
iqtree.printBranchLengths(out);
out.close();
cout << "Bayesian Branch lengths written to " << filename << endl;
}
cout << "Total Bayesian tree length: " << iqtree.treeLength() << endl;
}
}
void printSiteRates(IQTree &iqtree, const char *rate_file, bool bayes) {
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(rate_file);
out << "# Site-specific subtitution rates determined by ";
if (bayes)
out<< "empirical Bayesian method" << endl;
else
out<< "maximum likelihood" << endl;
out << "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab=read.table('" << rate_file << "',header=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl;
if (iqtree.isSuperTree()) {
out << "# Part: Partition ID (1=" << ((PhyloSuperTree*)&iqtree)->front()->aln->name << ", etc)" << endl
<< "# Site: Site ID within partition (starting from 1 for each partition)" << endl;
} else
out << "# Site: Alignment site ID" << endl;
if (bayes)
out << "# Rate: Posterior mean site rate weighted by posterior probability" << endl
<< "# Cat: Category with highest posterior (0=invariable, 1=slow, etc)" << endl
<< "# C_Rate: Corresponding rate of highest category" << endl;
else
out << "# Rate: Site rate estimated by maximum likelihood" << endl;
if (iqtree.isSuperTree())
out << "Part\t";
out << "Site\tRate";
if (bayes)
out << "\tCat\tC_Rate" << endl;
else
out << endl;
iqtree.writeSiteRates(out, bayes);
out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, rate_file);
}
cout << "Site rates printed to " << rate_file << endl;
}
void printMiscInfo(Params ¶ms, IQTree &iqtree, double *pattern_lh) {
if (params.print_site_lh && !params.pll) {
string site_lh_file = params.out_prefix;
site_lh_file += ".sitelh";
if (params.print_site_lh == WSL_SITE)
printSiteLh(site_lh_file.c_str(), &iqtree, pattern_lh);
else
printSiteLhCategory(site_lh_file.c_str(), &iqtree, params.print_site_lh);
}
if (params.print_partition_lh && !iqtree.isSuperTree()) {
outWarning("-wpl does not work with non-partition model");
params.print_partition_lh = false;
}
if (params.print_partition_lh && !params.pll) {
string part_lh_file = (string)params.out_prefix + ".partlh";
printPartitionLh(part_lh_file.c_str(), &iqtree, pattern_lh);
}
if (params.print_site_prob && !params.pll) {
printSiteProbCategory(((string)params.out_prefix + ".siteprob").c_str(), &iqtree, params.print_site_prob);
}
if (params.print_ancestral_sequence) {
printAncestralSequences(params.out_prefix, &iqtree, params.print_ancestral_sequence);
}
if (params.print_site_state_freq != WSF_NONE && !params.site_freq_file && !params.tree_freq_file) {
string site_freq_file = params.out_prefix;
site_freq_file += ".sitesf";
printSiteStateFreq(site_freq_file.c_str(), &iqtree);
}
if (params.print_trees_site_posterior) {
cout << "Computing mixture posterior probabilities" << endl;
IntVector pattern_cat;
int num_mix = iqtree.computePatternCategories(&pattern_cat);
cout << num_mix << " mixture components are necessary" << endl;
string site_mix_file = (string)params.out_prefix + ".sitemix";
ofstream out(site_mix_file.c_str());
if (!out.is_open())
outError("File " + site_mix_file + " could not be opened");
out << "Ptn\tFreq\tNumMix" << endl;
int ptn;
for (ptn = 0; ptn < pattern_cat.size(); ptn++)
out << ptn << "\t" << (int)iqtree.ptn_freq[ptn] << "\t" << pattern_cat[ptn] << endl;
out.close();
cout << "Pattern mixtures printed to " << site_mix_file << endl;
site_mix_file = (string)params.out_prefix + ".sitemixall";
out.open(site_mix_file.c_str());
int ncat = iqtree.getRate()->getNRate();
if (iqtree.getModel()->isMixture() && !iqtree.getModelFactory()->fused_mix_rate)
ncat = iqtree.getModel()->getNMixtures();
out << "Ptn\tFreq\tNumMix\tCat" << endl;
int c;
for (ptn = 0; ptn < iqtree.ptn_cat_mask.size(); ptn++) {
int num_cat = popcount_lauradoux((unsigned*)&iqtree.ptn_cat_mask[ptn], 2);
out << ptn << "\t" << (int)iqtree.ptn_freq[ptn] << "\t" << num_cat << "\t";
for (c = 0; c < ncat; c++)
if (iqtree.ptn_cat_mask[ptn] & ((uint64_t)1<<c))
out << "1";
else
out << "0";
out << endl;
}
out.close();
}
if (params.print_branch_lengths) {
if (params.manuel_analytic_approx) {
cout << "Applying Manuel's analytic approximation.." << endl;
iqtree.approxAllBranches();
}
string brlen_file = params.out_prefix;
brlen_file += ".brlen";
ofstream out;
out.open(brlen_file.c_str());
iqtree.printBranchLengths(out);
out.close();
cout << "Branch lengths written to " << brlen_file << endl;
}
if (params.write_branches) {
string filename = string(params.out_prefix) + ".branches.csv";
ofstream out;
out.open(filename.c_str());
iqtree.writeBranches(out);
out.close();
cout << "Branch lengths written to " << filename << endl;
}
if (params.print_conaln && iqtree.isSuperTree()) {
string str = params.out_prefix;
str = params.out_prefix;
str += ".conaln";
iqtree.aln->printAlignment(params.aln_output_format, str.c_str());
}
if (params.print_partition_info && iqtree.isSuperTree()) {
ASSERT(params.print_conaln);
string aln_file = (string)params.out_prefix + ".conaln";
string partition_info = params.out_prefix;
partition_info += ".partinfo.nex";
((SuperAlignment*)(iqtree.aln))->printPartition(partition_info.c_str(), aln_file.c_str());
partition_info = (string)params.out_prefix + ".partitions";
((SuperAlignment*)(iqtree.aln))->printPartitionRaxml(partition_info.c_str());
}
if (params.mvh_site_rate) {
RateMeyerHaeseler *rate_mvh = new RateMeyerHaeseler(params.rate_file,
&iqtree, params.rate_mh_type);
cout << endl << "Computing site-specific rates by "
<< rate_mvh->full_name << "..." << endl;
rate_mvh->runIterativeProc(params, iqtree);
cout << endl << "BEST SCORE FOUND : " << iqtree.getBestScore()<< endl;
string mhrate_file = params.out_prefix;
mhrate_file += ".mhrate";
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(mhrate_file.c_str());
iqtree.writeSiteRates(out, true);
out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, mhrate_file);
}
if (params.print_site_lh) {
string site_lh_file = params.out_prefix;
site_lh_file += ".mhsitelh";
printSiteLh(site_lh_file.c_str(), &iqtree);
}
}
if (params.print_site_rate & 1) {
string rate_file = params.out_prefix;
rate_file += ".rate";
printSiteRates(iqtree, rate_file.c_str(), true);
}
if (params.print_site_rate & 2) {
string rate_file = params.out_prefix;
rate_file += ".mlrate";
printSiteRates(iqtree, rate_file.c_str(), false);
}
if (params.fixed_branch_length == BRLEN_SCALE) {
string filename = (string)params.out_prefix + ".blscale";
iqtree.printTreeLengthScaling(filename.c_str());
cout << "Scaled tree length and model parameters printed to " << filename << endl;
}
}
void printFinalSearchInfo(Params ¶ms, IQTree &iqtree, double search_cpu_time, double search_real_time) {
cout << "Total tree length: " << iqtree.treeLength() << endl;
if (iqtree.isSuperTree() && verbose_mode >= VB_MAX) {
PhyloSuperTree *stree = (PhyloSuperTree*) &iqtree;
cout << stree->evalNNIs << " NNIs evaluated from " << stree->totalNNIs << " all possible NNIs ( " <<
(int)(((stree->evalNNIs+1.0)/(stree->totalNNIs+1.0))*100.0) << " %)" << endl;
cout<<"Details for subtrees:"<<endl;
int part = 0;
for(auto it = stree->begin(); it != stree->end(); it++,part++){
cout << part+1 << ". " << (*it)->aln->name << ": " << stree->part_info[part].evalNNIs<<" ( "
<< (int)(((stree->part_info[part].evalNNIs+1.0)/((stree->totalNNIs+1.0) / stree->size()))*100.0)
<< " %)" << endl;
}
}
params.run_time = (getCPUTime() - params.startCPUTime);
cout << endl;
cout << "Total number of iterations: " << iqtree.stop_rule.getCurIt() << endl;
// cout << "Total number of partial likelihood vector computations: " << iqtree.num_partial_lh_computations << endl;
cout << "CPU time used for tree search: " << search_cpu_time
<< " sec (" << convert_time(search_cpu_time) << ")" << endl;
cout << "Wall-clock time used for tree search: " << search_real_time
<< " sec (" << convert_time(search_real_time) << ")" << endl;
cout << "Total CPU time used: " << (double) params.run_time << " sec ("
<< convert_time((double) params.run_time) << ")" << endl;
cout << "Total wall-clock time used: "
<< getRealTime() - params.start_real_time << " sec ("
<< convert_time(getRealTime() - params.start_real_time) << ")" << endl;
}
void printTrees(vector<string> trees, Params ¶ms, string suffix) {
ofstream treesOut((string(params.out_prefix) + suffix).c_str(),
ofstream::out);
for (vector<string>::iterator it = trees.begin(); it != trees.end(); it++) {
treesOut << (*it);
treesOut << endl;
}
treesOut.close();
}
/************************************************************
* MAIN TREE RECONSTRUCTION
***********************************************************/
void startTreeReconstruction(Params ¶ms, IQTree* &iqtree, ModelCheckpoint &model_info) {
if (params.root) {
StrVector outgroup_names;
convert_string_vec(params.root, outgroup_names);
for (auto it = outgroup_names.begin(); it != outgroup_names.end(); it++)
if (iqtree->aln->getSeqID(*it) < 0)
outError("Alignment does not have specified outgroup taxon ", *it);
}
// if (params.count_trees && pllTreeCounter == NULL)
// pllTreeCounter = new StringIntMap;
// Temporary fix since PLL only supports DNA/Protein: switch to IQ-TREE parsimony kernel
if (params.start_tree == STT_PLL_PARSIMONY) {
if (iqtree->isSuperTreeUnlinked()) {
params.start_tree = STT_PARSIMONY;
} else if (iqtree->isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)iqtree;
for (PhyloSuperTree::iterator it = stree->begin(); it != stree->end(); it++)
if ((*it)->aln->seq_type != SEQ_DNA && (*it)->aln->seq_type != SEQ_PROTEIN)
params.start_tree = STT_PARSIMONY;
} else if (iqtree->aln->seq_type != SEQ_DNA && iqtree->aln->seq_type != SEQ_PROTEIN)
params.start_tree = STT_PARSIMONY;
}
/***************** Initialization for PLL and sNNI ******************/
if (params.start_tree == STT_PLL_PARSIMONY || params.start_tree == STT_RANDOM_TREE || params.pll) {
/* Initialized all data structure for PLL*/
iqtree->initializePLL(params);
}
/********************* Compute pairwise distances *******************/
if (params.start_tree == STT_BIONJ || params.iqp || params.leastSquareBranch) {
computeInitialDist(params, *iqtree);
}
/******************** Pass the parameter object params to IQTree *******************/
iqtree->setParams(¶ms);
/*************** SET UP PARAMETERS and model testing ****************/
// FOR TUNG: swapping the order cause bug for -m TESTLINK
// iqtree.initSettings(params);
runModelFinder(params, *iqtree, model_info);
}
/**
optimize branch lengths of consensus tree
*/
void optimizeConTree(Params ¶ms, IQTree *tree) {
string contree_file = string(params.out_prefix) + ".contree";
DoubleVector rfdist;
tree->computeRFDist(contree_file.c_str(), rfdist);
tree->contree_rfdist = (int)rfdist[0];
tree->readTreeFile(contree_file);
tree->initializeAllPartialLh();
tree->fixNegativeBranch(false);
tree->boot_consense_logl = tree->optimizeAllBranches();
cout << "Log-likelihood of consensus tree: " << tree->boot_consense_logl << endl;
tree->setRootNode(params.root);
tree->insertTaxa(tree->removed_seqs, tree->twin_seqs);
tree->printTree(contree_file.c_str(), WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA | WT_NEWLINE);
string contree = tree->getTreeString();
tree->getCheckpoint()->put("contree", contree);
}
void runTreeReconstruction(Params ¶ms, IQTree* &iqtree) {
// string dist_file;
params.startCPUTime = getCPUTime();
params.start_real_time = getRealTime();
int absent_states = 0;
if (iqtree->isSuperTree()) {
PhyloSuperTree *stree = (PhyloSuperTree*)iqtree;
for (auto i = stree->begin(); i != stree->end(); i++)
absent_states += (*i)->aln->checkAbsentStates("partition " + (*i)->aln->name);
} else {
absent_states = iqtree->aln->checkAbsentStates("alignment");
}
if (absent_states > 0) {
cout << "NOTE: " << absent_states << " states (see above) are not present and thus removed from Markov process to prevent numerical problems" << endl;
}
// Make sure that no partial likelihood of IQ-TREE is initialized when PLL is used to save memory
if (params.pll) {
iqtree->deleteAllPartialLh();
}
/***************** Initialization for PLL and sNNI ******************/
if ((params.start_tree == STT_PLL_PARSIMONY || params.start_tree == STT_RANDOM_TREE || params.pll) && !iqtree->isInitializedPLL()) {
/* Initialized all data structure for PLL*/
iqtree->initializePLL(params);
}
/********************* Compute pairwise distances *******************/
if ((params.start_tree == STT_BIONJ || params.iqp || params.leastSquareBranch) && !iqtree->root) {
computeInitialDist(params, *iqtree);
}
/******************** Pass the parameter object params to IQTree *******************/
iqtree->setParams(¶ms);
ModelsBlock *models_block = readModelsDefinition(params);
initializeParams(params, *iqtree);
if (posRateHeterotachy(iqtree->aln->model_name) != string::npos && !iqtree->isMixlen()) {
// create a new instance
IQTree* iqtree_new = new PhyloTreeMixlen(iqtree->aln, 0);
iqtree_new->setCheckpoint(iqtree->getCheckpoint());
if (!iqtree->constraintTree.empty())
iqtree_new->constraintTree.readConstraint(iqtree->constraintTree);
iqtree_new->removed_seqs = iqtree->removed_seqs;
iqtree_new->twin_seqs = iqtree->twin_seqs;
if (params.start_tree == STT_PLL_PARSIMONY || params.start_tree == STT_RANDOM_TREE || params.pll) {
/* Initialized all data structure for PLL*/
iqtree_new->initializePLL(params);
}
iqtree_new->setParams(¶ms);
iqtree_new->copyPhyloTree(iqtree);
// replace iqtree object
delete iqtree;
iqtree = iqtree_new;
}
iqtree->setRootNode(params.root);
iqtree->restoreCheckpoint();
if (params.online_bootstrap && params.gbo_replicates > 0) {
cout << "Generating " << params.gbo_replicates << " samples for ultrafast "
<< RESAMPLE_NAME << " (seed: " << params.ran_seed << ")..." << endl;
}
iqtree->initSettings(params);
/*********************** INITIAL MODEL OPTIMIZATION *****************/
if (!iqtree->getModelFactory()) {
iqtree->initializeModel(params, iqtree->aln->model_name, models_block);
}
if (iqtree->getRate()->isHeterotachy() && !iqtree->isMixlen()) {
ASSERT(0 && "Heterotachy tree not properly created");
}
// iqtree.restoreCheckpoint();
delete models_block;
// UpperBounds analysis. Here, to analyse the initial tree without any tree search or optimization
/*
if (params.upper_bound) {
iqtree.setCurScore(iqtree.computeLikelihood());
cout<<iqtree.getCurScore()<<endl;
UpperBounds(¶ms, iqtree.aln, iqtree);
exit(0);
}
*/
// degree of freedom
cout << endl;
if (verbose_mode >= VB_MED) {
cout << "ML-TREE SEARCH START WITH THE FOLLOWING PARAMETERS:" << endl;
int model_df = iqtree->getModelFactory()->getNParameters(BRLEN_OPTIMIZE);
printAnalysisInfo(model_df, *iqtree, params);
}
if (!params.pll) {
uint64_t total_mem = getMemorySize();
if (params.lh_mem_save == LM_MEM_SAVE && params.max_mem_size > total_mem)
params.max_mem_size = total_mem;
uint64_t mem_required = iqtree->getMemoryRequired();
if (mem_required >= total_mem*0.95 && !iqtree->isSuperTree()) {
// switch to memory saving mode
if (params.lh_mem_save != LM_MEM_SAVE) {
params.max_mem_size = (total_mem*0.95)/mem_required;
params.lh_mem_save = LM_MEM_SAVE;
mem_required = iqtree->getMemoryRequired();
cout << "NOTE: Switching to memory saving mode using " << (mem_required / 1073741824.0) << " GB ("
<< (mem_required*100/total_mem) << "% of normal mode)" << endl;
cout << "NOTE: Use -mem option if you want to restrict RAM usage further" << endl;
}
if (mem_required >= total_mem) {
params.lh_mem_save = LM_MEM_SAVE;
params.max_mem_size = 0.0;
mem_required = iqtree->getMemoryRequired();
}
}
if (mem_required >= total_mem) {
cerr << "ERROR: Your RAM is below minimum requirement of " << (mem_required / 1073741824.0) << " GB RAM" << endl;
outError("Memory saving mode cannot work, switch to another computer!!!");
}
//#if defined __APPLE__ || defined __MACH__
cout << "NOTE: " << (mem_required / 1048576) << " MB RAM (" << (mem_required / 1073741824) << " GB) is required!" << endl;
//#else
// cout << "NOTE: " << ((double) mem_size / 1000.0) / 1000 << " MB RAM is required!" << endl;
//#endif
if (params.memCheck)
exit(0);
#ifdef BINARY32
if (mem_required >= 2000000000) {
outError("Memory required exceeds 2GB limit of 32-bit executable");
}
#endif
int max_procs = countPhysicalCPUCores();
if (mem_required * max_procs > total_mem * iqtree->num_threads && iqtree->num_threads > 0) {
outWarning("Memory required per CPU-core (" + convertDoubleToString((double)mem_required/iqtree->num_threads/1024/1024/1024)+
" GB) is higher than your computer RAM per CPU-core ("+convertIntToString(total_mem/max_procs/1024/1024/1024)+
" GB), thus multiple runs may exceed RAM!");
}
}
#ifdef _OPENMP
if (iqtree->num_threads <= 0) {
int bestThreads = iqtree->testNumThreads();
omp_set_num_threads(bestThreads);
params.num_threads = bestThreads;
} else
iqtree->warnNumThreads();
#endif
iqtree->initializeAllPartialLh();
double initEpsilon = params.min_iterations == 0 ? params.modelEps : (params.modelEps*10);
if (iqtree->getRate()->name.find("+I+G") != string::npos) {
if (params.alpha_invar_file != NULL) { // COMPUTE TREE LIKELIHOOD BASED ON THE INPUT ALPHA AND P_INVAR VALUE
computeLoglFromUserInputGAMMAInvar(params, *iqtree);
exit(0);
}
if (params.exh_ai) {
exhaustiveSearchGAMMAInvar(params, *iqtree);
exit(0);
}
}
// Optimize model parameters and branch lengths using ML for the initial tree
string initTree;
iqtree->clearAllPartialLH();
iqtree->getModelFactory()->restoreCheckpoint();
if (iqtree->getCheckpoint()->getBool("finishedModelInit")) {
// model optimization already done: ignore this step
if (!iqtree->candidateTrees.empty())
iqtree->readTreeString(iqtree->getBestTrees()[0]);
iqtree->setCurScore(iqtree->computeLikelihood());
initTree = iqtree->getTreeString();
cout << "CHECKPOINT: Model parameters restored, LogL: " << iqtree->getCurScore() << endl;
} else {
initTree = iqtree->optimizeModelParameters(true, initEpsilon);
if (iqtree->isMixlen())
initTree = ((ModelFactoryMixlen*)iqtree->getModelFactory())->sortClassesByTreeLength();
iqtree->saveCheckpoint();
iqtree->getModelFactory()->saveCheckpoint();
iqtree->getCheckpoint()->putBool("finishedModelInit", true);
iqtree->getCheckpoint()->dump();
// cout << "initTree: " << initTree << endl;
}
if (params.lmap_num_quartets >= 0) {
cout << endl << "Performing likelihood mapping with ";
if (params.lmap_num_quartets > 0)
cout << params.lmap_num_quartets;
else
cout << "all";
cout << " quartets..." << endl;
double lkmap_time = getRealTime();
iqtree->doLikelihoodMapping();
cout << "Likelihood mapping needed " << getRealTime()-lkmap_time << " seconds" << endl << endl;
}
// TODO: why is this variable not used?
// ANSWER: moved to doTreeSearch
// bool finishedCandidateSet = iqtree.getCheckpoint()->getBool("finishedCandidateSet");
bool finishedInitTree = iqtree->getCheckpoint()->getBool("finishedInitTree");
// now overwrite with random tree
if (params.start_tree == STT_RANDOM_TREE && !finishedInitTree) {
cout << "Generate random initial Yule-Harding tree..." << endl;
iqtree->generateRandomTree(YULE_HARDING);
iqtree->wrapperFixNegativeBranch(true);
iqtree->initializeAllPartialLh();
initTree = iqtree->optimizeBranches(params.brlen_num_traversal);
cout << "Log-likelihood of random tree: " << iqtree->getCurScore() << endl;
}
/****************** NOW PERFORM MAXIMUM LIKELIHOOD TREE RECONSTRUCTION ******************/
// Update best tree
if (!finishedInitTree) {
iqtree->addTreeToCandidateSet(initTree, iqtree->getCurScore(), false, MPIHelper::getInstance().getProcessID());
iqtree->printResultTree();
iqtree->intermediateTrees.update(iqtree->getTreeString(), iqtree->getCurScore());
if (iqtree->isSuperTreeUnlinked()) {
PhyloSuperTree* stree = (PhyloSuperTree*)iqtree;
for (auto it = stree->begin(); it != stree->end(); it++)
((IQTree*)(*it))->addTreeToCandidateSet((*it)->getTreeString(),
(*it)->getCurScore(), false, MPIHelper::getInstance().getProcessID());
}
}
if (params.min_iterations && !iqtree->isBifurcating())
outError("Tree search does not work with initial multifurcating tree. Please specify `-n 0` to avoid this.");
// Compute maximum likelihood distance
// ML distance is only needed for IQP
// if ( params.start_tree != STT_BIONJ && ((params.snni && !params.iqp) || params.min_iterations == 0)) {
// params.compute_ml_dist = false;
// }
if ((params.min_iterations <= 1 || params.numInitTrees <= 1) && params.start_tree != STT_BIONJ)
params.compute_ml_dist = false;
if ((params.user_file || params.start_tree == STT_RANDOM_TREE) && params.snni && !params.iqp) {
params.compute_ml_dist = false;
}
if (params.constraint_tree_file)
params.compute_ml_dist = false;
if (iqtree->isSuperTreeUnlinked())
params.compute_ml_dist = false;
//Generate BIONJ tree
if (MPIHelper::getInstance().isMaster() && !iqtree->getCheckpoint()->getBool("finishedCandidateSet")) {
if (!finishedInitTree && ((!params.dist_file && params.compute_ml_dist) || params.leastSquareBranch)) {
computeMLDist(params, *iqtree, getCPUTime());
if (!params.user_file && params.start_tree != STT_RANDOM_TREE) {
// NEW 2015-08-10: always compute BIONJ tree into the candidate set
iqtree->resetCurScore();
double start_bionj = getRealTime();
iqtree->computeBioNJ(params, iqtree->aln, iqtree->dist_file);
cout << getRealTime() - start_bionj << " seconds" << endl;
if (iqtree->isSuperTree())
iqtree->wrapperFixNegativeBranch(true);
else
iqtree->wrapperFixNegativeBranch(false);
iqtree->initializeAllPartialLh();
if (params.start_tree == STT_BIONJ) {
initTree = iqtree->optimizeModelParameters(params.min_iterations==0, initEpsilon);
} else {
initTree = iqtree->optimizeBranches();
}
cout << "Log-likelihood of BIONJ tree: " << iqtree->getCurScore() << endl;
// cout << "BIONJ tree: " << iqtree->getTreeString() << endl;
iqtree->candidateTrees.update(initTree, iqtree->getCurScore());
}
}
}
// iqtree->saveCheckpoint();
double cputime_search_start = getCPUTime();
double realtime_search_start = getRealTime();
if (params.leastSquareNNI) {
iqtree->computeSubtreeDists();
}
if (params.model_name == "WHTEST") {
cout << endl << "Testing model homogeneity by Weiss & von Haeseler (2003)..." << endl;
WHTest(params, *iqtree);
}
NodeVector pruned_taxa;
StrVector linked_name;
double *saved_dist_mat = iqtree->dist_matrix;
double *pattern_lh;
pattern_lh = new double[iqtree->getAlnNPattern()];
// prune stable taxa
pruneTaxa(params, *iqtree, pattern_lh, pruned_taxa, linked_name);
/***************************************** DO STOCHASTIC TREE SEARCH *******************************************/
if (params.min_iterations > 0 && !params.tree_spr) {
iqtree->doTreeSearch();
iqtree->setAlignment(iqtree->aln);
} else {
iqtree->candidateTrees.saveCheckpoint();
/* do SPR with likelihood function */
if (params.tree_spr) {
//tree.optimizeSPRBranches();
cout << "Doing SPR Search" << endl;
cout << "Start tree.optimizeSPR()" << endl;
double spr_score = iqtree->optimizeSPR();
cout << "Finish tree.optimizeSPR()" << endl;
//double spr_score = tree.optimizeSPR(tree.curScore, (PhyloNode*) tree.root->neighbors[0]->node);
if (spr_score <= iqtree->getCurScore()) {
cout << "SPR search did not found any better tree" << endl;
}
}
}
// restore pruned taxa
restoreTaxa(*iqtree, saved_dist_mat, pruned_taxa, linked_name);
double search_cpu_time = getCPUTime() - cputime_search_start;
double search_real_time = getRealTime() - realtime_search_start;
// COMMENT THIS OUT BECAUSE IT DELETES ALL BRANCH LENGTHS OF SUBTREES!
// if (iqtree.isSuperTree())
// ((PhyloSuperTree*) iqtree)->mapTrees();
if (!MPIHelper::getInstance().isMaster()) {
delete[] pattern_lh;
return;
}
if (params.snni && params.min_iterations && verbose_mode >= VB_MED) {
cout << "Log-likelihoods of " << params.popSize << " best candidate trees: " << endl;
iqtree->printBestScores();
cout << endl;
}
if (!params.final_model_opt) {
iqtree->setCurScore(iqtree->computeLikelihood());
} else if (params.min_iterations) {
iqtree->readTreeString(iqtree->getBestTrees()[0]);
iqtree->initializeAllPartialLh();
iqtree->clearAllPartialLH();
cout << "--------------------------------------------------------------------" << endl;
cout << "| FINALIZING TREE SEARCH |" << endl;
cout << "--------------------------------------------------------------------" << endl;
if (iqtree->getCheckpoint()->getBool("finishedModelFinal")) {
iqtree->setCurScore(iqtree->computeLikelihood());
cout << "CHECKPOINT: Final model parameters restored" << endl;
} else {
cout << "Performs final model parameters optimization" << endl;
string tree;
Params::getInstance().fixStableSplits = false;
Params::getInstance().tabu = false;
// why doing NNI search here?
// iqtree->doNNISearch();
tree = iqtree->optimizeModelParameters(true);
iqtree->addTreeToCandidateSet(tree, iqtree->getCurScore(), false, MPIHelper::getInstance().getProcessID());
iqtree->getCheckpoint()->putBool("finishedModelFinal", true);
iqtree->saveCheckpoint();
}
}
if (iqtree->isSuperTree()) {
((PhyloSuperTree*) iqtree)->computeBranchLengths();
((PhyloSuperTree*) iqtree)->printBestPartitionParams((string(params.out_prefix) + ".best_model.nex").c_str());
}
cout << "BEST SCORE FOUND : " << iqtree->getCurScore() << endl;
if (params.write_candidate_trees) {
printTrees(iqtree->getBestTrees(), params, ".imd_trees");
}
if (params.pll)
iqtree->inputModelPLL2IQTree();
/* root the tree at the first sequence */
// BQM: WHY SETTING THIS ROOT NODE????
// iqtree->root = iqtree->findLeafName(iqtree->aln->getSeqName(0));
// assert(iqtree->root);
iqtree->setRootNode(params.root);
if (!params.pll) {
iqtree->computeLikelihood(pattern_lh);
// compute logl variance
iqtree->logl_variance = iqtree->computeLogLVariance();
}
printMiscInfo(params, *iqtree, pattern_lh);
if (params.root_test) {
cout << "Testing root positions..." << endl;
iqtree->testRootPosition(true, params.loglh_epsilon);
}
/****** perform SH-aLRT test ******************/
if ((params.aLRT_replicates > 0 || params.localbp_replicates > 0 || params.aLRT_test || params.aBayes_test) && !params.pll) {
double mytime = getRealTime();
params.aLRT_replicates = max(params.aLRT_replicates, params.localbp_replicates);
cout << endl;
if (params.aLRT_replicates > 0)
cout << "Testing tree branches by SH-like aLRT with "
<< params.aLRT_replicates << " replicates..." << endl;
if (params.localbp_replicates)
cout << "Testing tree branches by local-BP test with " << params.localbp_replicates << " replicates..." << endl;
if (params.aLRT_test)
cout << "Testing tree branches by aLRT parametric test..." << endl;
if (params.aBayes_test)
cout << "Testing tree branches by aBayes parametric test..." << endl;
iqtree->setRootNode(params.root);
if (iqtree->isBifurcating()) {
iqtree->testAllBranches(params.aLRT_threshold, iqtree->getCurScore(),
pattern_lh, params.aLRT_replicates, params.localbp_replicates, params.aLRT_test, params.aBayes_test);
cout << getRealTime() - mytime << " sec." << endl;
} else {
outWarning("Tree is multifurcating and such test is not applicable");
params.aLRT_replicates = params.localbp_replicates = params.aLRT_test = params.aBayes_test = 0;
}
}
if (params.gbo_replicates > 0) {
cout << "Creating " << RESAMPLE_NAME << " support values..." << endl;
if (!params.online_bootstrap)
outError("Obsolete feature");
// runGuidedBootstrap(params, iqtree->aln, iqtree);
else
iqtree->summarizeBootstrap(params);
}
if (params.collapse_zero_branch) {
cout << "Collapsing near-zero internal branches... ";
cout << iqtree->collapseInternalBranches(NULL, NULL, params.min_branch_length*4);
cout << " collapsed" << endl;
}
printFinalSearchInfo(params, *iqtree, search_cpu_time, search_real_time);
if (params.gbo_replicates && params.online_bootstrap && params.print_ufboot_trees)
iqtree->writeUFBootTrees(params);
if (params.gbo_replicates && params.online_bootstrap && !iqtree->isSuperTreeUnlinked()) {
cout << endl << "Computing " << RESAMPLE_NAME << " consensus tree..." << endl;
string splitsfile = params.out_prefix;
splitsfile += ".splits.nex";
double weight_threshold = (params.split_threshold<1) ? params.split_threshold : (params.gbo_replicates-1.0)/params.gbo_replicates;
weight_threshold *= 100.0;
computeConsensusTree(splitsfile.c_str(), 0, 1e6, -1,
weight_threshold, NULL, params.out_prefix, NULL, ¶ms);
// now optimize branch lengths of the consensus tree
string current_tree = iqtree->getTreeString();
optimizeConTree(params, iqtree);
// revert the best tree
iqtree->readTreeString(current_tree);
}
if (Params::getInstance().writeDistImdTrees) {
cout << endl;
cout << "Recomputing the log-likelihood of the intermediate trees ... " << endl;
iqtree->intermediateTrees.recomputeLoglOfAllTrees(*iqtree);
}
// BUG FIX: readTreeString(bestTreeString) not needed before this line
iqtree->printResultTree();
iqtree->saveCheckpoint();
if (params.upper_bound_NNI) {
string out_file_UB = params.out_prefix;
out_file_UB += ".UB.NNI.main";
ofstream out_UB;
out_UB.exceptions(ios::failbit | ios::badbit);
out_UB.open((char *) out_file_UB.c_str(), std::ofstream::out | std::ofstream::app);
out_UB << iqtree->leafNum << "\t" << iqtree->aln->getNSite() << "\t" << iqtree->params->upper_bound_frac << "\t"
<< iqtree->skippedNNIub << "\t" << iqtree->totalNNIub << "\t" << iqtree->getBestScore() << endl;
//iqtree->minUB << "\t" << iqtree->meanUB/iqtree->skippedNNIub << "\t" << iqtree->maxUB << endl;
out_UB.close();
}
if (params.out_file)
iqtree->printTree(params.out_file);
delete[] pattern_lh;
runApproximateBranchLengths(params, *iqtree);
}
/**********************************************************
* MULTIPLE TREE RECONSTRUCTION
***********************************************************/
void runMultipleTreeReconstruction(Params ¶ms, Alignment *alignment, IQTree *tree) {
ModelCheckpoint *model_info = new ModelCheckpoint;
if (params.suppress_output_flags & OUT_TREEFILE)
outError("Suppress .treefile not allowed with -runs option");
string treefile_name = params.out_prefix;
treefile_name += ".treefile";
string runtrees_name = params.out_prefix;
runtrees_name += ".runtrees";
DoubleVector runLnL;
if (tree->getCheckpoint()->getVector("runLnL", runLnL)) {
cout << endl << "CHECKPOINT: " << runLnL.size() << " independent run(s) restored" << endl;
} else if (MPIHelper::getInstance().isMaster()) {
// first empty the runtrees file
try {
ofstream tree_out;
tree_out.exceptions(ios::failbit | ios::badbit);
tree_out.open(runtrees_name.c_str());
tree_out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, runtrees_name);
}
}
double start_time = getCPUTime();
double start_real_time = getRealTime();
int orig_seed = params.ran_seed;
int run;
int best_run = 0;
for (run = 0; run < runLnL.size(); run++)
if (runLnL[run] > runLnL[best_run])
best_run = run;
// do multiple tree reconstruction
for (run = runLnL.size(); run < params.num_runs; run++) {
tree->getCheckpoint()->startStruct("run" + convertIntToString(run+1));
params.ran_seed = orig_seed + run*1000 + MPIHelper::getInstance().getProcessID();
cout << endl << "---> START RUN NUMBER " << run + 1 << " (seed: " << params.ran_seed << ")" << endl;
tree->getCheckpoint()->put("seed", params.ran_seed);
// initialize random stream for replicating the run
int *saved_randstream = randstream;
init_random(params.ran_seed);
IQTree *iqtree;
if (alignment->isSuperAlignment()){
if(params.partition_type != BRLEN_OPTIMIZE){
iqtree = new PhyloSuperTreePlen((SuperAlignment*) alignment, (PhyloSuperTree*) tree);
} else {
iqtree = new PhyloSuperTree((SuperAlignment*) alignment, (PhyloSuperTree*) tree);
}
} else {
// allocate heterotachy tree if neccessary
int pos = posRateHeterotachy(alignment->model_name);
if (params.num_mixlen > 1) {
iqtree = new PhyloTreeMixlen(alignment, params.num_mixlen);
} else if (pos != string::npos) {
iqtree = new PhyloTreeMixlen(alignment, 0);
} else
iqtree = new IQTree(alignment);
}
if (!tree->constraintTree.empty()) {
iqtree->constraintTree.readConstraint(tree->constraintTree);
}
// set checkpoint
iqtree->setCheckpoint(tree->getCheckpoint());
iqtree->num_precision = tree->num_precision;
runTreeReconstruction(params, iqtree);
// read in the output tree file
stringstream ss;
iqtree->printTree(ss);
if (MPIHelper::getInstance().isMaster())
try {
ofstream tree_out;
tree_out.exceptions(ios::failbit | ios::badbit);
tree_out.open(runtrees_name.c_str(), ios_base::out | ios_base::app);
tree_out.precision(10);
tree_out << "[ lh=" << iqtree->getBestScore() << " ]";
tree_out << ss.str() << endl;
tree_out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, runtrees_name);
}
// fix bug: set the model for original tree after testing
if ((params.model_name.substr(0,4) == "TEST" || params.model_name.substr(0,2) == "MF") && tree->isSuperTree()) {
PhyloSuperTree *stree = ((PhyloSuperTree*)tree);
stree->part_info = ((PhyloSuperTree*)iqtree)->part_info;
}
runLnL.push_back(iqtree->getBestScore());
if (MPIHelper::getInstance().isMaster()) {
if (params.num_bootstrap_samples > 0 && params.consensus_type == CT_CONSENSUS_TREE &&
(run == 0 || iqtree->getBestScore() > runLnL[best_run])) {
// 2017-12-08: optimize branch lengths of consensus tree
// now optimize branch lengths of the consensus tree
string current_tree = iqtree->getTreeString();
optimizeConTree(params, iqtree);
// revert the best tree
iqtree->readTreeString(current_tree);
iqtree->saveCheckpoint();
}
}
if (iqtree->getBestScore() > runLnL[best_run])
best_run = run;
if (params.num_runs == 1)
reportPhyloAnalysis(params, *iqtree, *model_info);
delete iqtree;
tree->getCheckpoint()->endStruct();
// clear all checkpointed information
// tree->getCheckpoint()->keepKeyPrefix("iqtree");
tree->getCheckpoint()->putVector("runLnL", runLnL);
// tree->getCheckpoint()->putBool("finished", false);
tree->getCheckpoint()->dump(true);
// restore randstream
finish_random();
randstream = saved_randstream;
}
cout << endl << "---> SUMMARIZE RESULTS FROM " << runLnL.size() << " RUNS" << endl << endl;
cout << "Run " << best_run+1 << " gave best log-likelihood: " << runLnL[best_run] << endl;
// initialize tree and model strucgture
ModelsBlock *models_block = readModelsDefinition(params);
tree->setParams(¶ms);
tree->setNumThreads(params.num_threads);
if (!tree->getModelFactory()) {
tree->initializeModel(params, tree->aln->model_name, models_block);
}
if (tree->getRate()->isHeterotachy() && !tree->isMixlen()) {
ASSERT(0 && "Heterotachy tree not properly created");
}
delete models_block;
// restore the tree and model from the best run
tree->getCheckpoint()->startStruct("run" + convertIntToString(best_run+1));
tree->restoreCheckpoint();
tree->getModelFactory()->restoreCheckpoint();
tree->setCurScore(runLnL[best_run]);
if (params.gbo_replicates && !tree->isSuperTreeUnlinked()) {
string out_file = (string)params.out_prefix + ".splits";
if (params.print_splits_file) {
tree->boot_splits.back()->saveFile(out_file.c_str(), IN_OTHER, true);
cout << "Split supports printed to star-dot file " << out_file << endl;
}
if (params.print_splits_nex_file) {
out_file = (string)params.out_prefix + ".splits.nex";
tree->boot_splits.back()->saveFile(out_file.c_str(), IN_NEXUS, false);
cout << "Split supports printed to NEXUS file " << out_file << endl;
}
// overwrite .ufboot trees
if (params.print_ufboot_trees)
tree->writeUFBootTrees(params);
// overwrite .contree
string contree;
if (!tree->getCheckpoint()->getString("contree", contree))
ASSERT(0 && "Couldn't restore contree");
string contree_file = string(params.out_prefix) + ".contree";
string current_tree = tree->getTreeString();
tree->readTreeString(contree);
tree->setRootNode(params.root);
tree->insertTaxa(tree->removed_seqs, tree->twin_seqs);
tree->printTree(contree_file.c_str(), WT_BR_LEN | WT_BR_LEN_FIXED_WIDTH | WT_SORT_TAXA | WT_NEWLINE);
tree->readTreeString(current_tree);
cout << "Consensus tree written to " << contree_file << endl;
}
tree->getCheckpoint()->endStruct();
// overwrite .treefile
tree->printResultTree();
if (MPIHelper::getInstance().isMaster()) {
cout << "Total CPU time for " << params.num_runs << " runs: " << (getCPUTime() - start_time) << " seconds." << endl;
cout << "Total wall-clock time for " << params.num_runs << " runs: " << (getRealTime() - start_real_time) << " seconds." << endl << endl;
}
delete model_info;
}
void computeLoglFromUserInputGAMMAInvar(Params ¶ms, IQTree &iqtree) {
RateHeterogeneity *site_rates = iqtree.getRate();
site_rates->setFixPInvar(true);
site_rates->setFixGammaShape(true);
vector<double> alphas, p_invars, logl;
ifstream aiFile;
aiFile.open(params.alpha_invar_file, ios_base::in);
if (aiFile.good()) {
double alpha, p_invar;
while (aiFile >> alpha >> p_invar) {
alphas.push_back(alpha);
p_invars.push_back(p_invar);
}
aiFile.close();
cout << "Computing tree logl based on the alpha and p_invar values in " << params.alpha_invar_file << " ..." <<
endl;
} else {
stringstream errMsg;
errMsg << "Could not find file: " << params.alpha_invar_file;
outError(errMsg.str().c_str());
}
string aiResultsFileName = string(params.out_prefix) + "_" + string(params.alpha_invar_file) + ".results";
ofstream aiFileResults;
aiFileResults.open(aiResultsFileName.c_str());
aiFileResults << fixed;
aiFileResults.precision(4);
DoubleVector lenvec;
aiFileResults << "Alpha P_Invar Logl TreeLength\n";
for (int i = 0; i < alphas.size(); i++) {
iqtree.saveBranchLengths(lenvec);
aiFileResults << alphas.at(i) << " " << p_invars.at(i) << " ";
site_rates->setGammaShape(alphas.at(i));
site_rates->setPInvar(p_invars.at(i));
iqtree.clearAllPartialLH();
double lh = iqtree.getModelFactory()->optimizeParameters(params.fixed_branch_length, false, 0.001);
aiFileResults << lh << " " << iqtree.treeLength() << "\n";
iqtree.restoreBranchLengths(lenvec);
}
aiFileResults.close();
cout << "Results were written to: " << aiResultsFileName << endl;
cout << "Wall clock time used: " << getRealTime() - params.start_real_time << endl;
}
void searchGAMMAInvarByRestarting(IQTree &iqtree) {
if (!Params::getInstance().fixed_branch_length)
iqtree.setCurScore(iqtree.optimizeAllBranches(1));
else
iqtree.setCurScore(iqtree.computeLikelihood());
RateHeterogeneity* site_rates = (iqtree.getRate());
double values[] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
vector<double> initAlphas;
if (Params::getInstance().randomAlpha) {
while (initAlphas.size() < 10) {
double initAlpha = random_double();
initAlphas.push_back(initAlpha + iqtree.params->min_gamma_shape*2);
}
} else {
initAlphas.assign(values, values+10);
}
double bestLogl = iqtree.getCurScore();
double bestAlpha = 0.0;
double bestPInvar = 0.0;
double initPInvar = iqtree.getRate()->getPInvar();
/* Back up branch lengths and substitutional rates */
DoubleVector lenvec;
DoubleVector bestLens;
iqtree.saveBranchLengths(lenvec);
int numRateEntries = iqtree.getModel()->getNumRateEntries();
double *rates = new double[numRateEntries];
double *bestRates = new double[numRateEntries];
iqtree.getModel()->getRateMatrix(rates);
int numStates = iqtree.aln->num_states;
double *state_freqs = new double[numStates];
iqtree.getModel()->getStateFrequency(state_freqs);
double *bestStateFreqs = new double[numStates];
for (int i = 0; i < 10; i++) {
cout << endl;
cout << "Testing alpha: " << initAlphas[i] << endl;
// Initialize model parameters
iqtree.restoreBranchLengths(lenvec);
((ModelMarkov*) iqtree.getModel())->setRateMatrix(rates);
((ModelMarkov*) iqtree.getModel())->setStateFrequency(state_freqs);
iqtree.getModel()->decomposeRateMatrix();
site_rates->setGammaShape(initAlphas[i]);
site_rates->setPInvar(initPInvar);
iqtree.clearAllPartialLH();
iqtree.optimizeModelParameters(verbose_mode >= VB_MED, Params::getInstance().testAlphaEps);
double estAlpha = iqtree.getRate()->getGammaShape();
double estPInv = iqtree.getRate()->getPInvar();
double logl = iqtree.getCurScore();
cout << "Est. alpha: " << estAlpha << " / Est. pinv: " << estPInv
<< " / Logl: " << logl << endl;
if (iqtree.getCurScore() > bestLogl) {
bestLogl = logl;
bestAlpha = estAlpha;
bestPInvar = estPInv;
bestLens.clear();
iqtree.saveBranchLengths(bestLens);
iqtree.getModel()->getRateMatrix(bestRates);
iqtree.getModel()->getStateFrequency(bestStateFreqs);
}
}
site_rates->setGammaShape(bestAlpha);
site_rates->setFixGammaShape(false);
site_rates->setPInvar(bestPInvar);
site_rates->setFixPInvar(false);
((ModelMarkov*) iqtree.getModel())->setRateMatrix(bestRates);
((ModelMarkov*) iqtree.getModel())->setStateFrequency(bestStateFreqs);
iqtree.restoreBranchLengths(bestLens);
iqtree.getModel()->decomposeRateMatrix();
iqtree.clearAllPartialLH();
iqtree.setCurScore(iqtree.computeLikelihood());
cout << endl;
cout << "Best initial alpha: " << bestAlpha << " / initial pinv: " << bestPInvar << " / ";
cout << "Logl: " << iqtree.getCurScore() << endl;
delete [] rates;
delete [] state_freqs;
delete [] bestRates;
delete [] bestStateFreqs;
}
// Test alpha fom 0.1 to 15 and p_invar from 0.1 to 0.99, stepsize = 0.01
void exhaustiveSearchGAMMAInvar(Params ¶ms, IQTree &iqtree) {
double alphaMin = 0.01;
double alphaMax = 10.00;
double p_invarMin = 0.01;
double p_invarMax = 1.00;
// double p_invarMax = iqtree.aln->frac_const_sites;
double stepSize = 0.01;
int numAlpha = (int) floor((alphaMax - alphaMin)/stepSize);
int numInvar = (int) floor((p_invarMax - p_invarMin)/stepSize);
cout << "EVALUATING " << numAlpha*numInvar << " COMBINATIONS OF " << " alpha=" << alphaMin << ".." << alphaMax
<< " AND " << " p-invar=" << p_invarMin << ".." << p_invarMax
<< " (epsilon: " << params.modelEps << ")" << endl;
// vector<string> results;
// results.reserve((unsigned long) (numAlpha * numInvar));
DoubleVector lenvec;
iqtree.saveBranchLengths(lenvec);
RateHeterogeneity* site_rates = (iqtree.getRate());
site_rates->setFixPInvar(true);
site_rates->setFixGammaShape(true);
string aiResultsFileName = string(params.out_prefix) + ".ai_results";
ofstream aiFileResults;
aiFileResults.open(aiResultsFileName.c_str());
aiFileResults << fixed;
aiFileResults.precision(4);
aiFileResults << "alpha p_invar logl tree_len\n";
for (double alpha = alphaMin; alpha < alphaMax; alpha = alpha + stepSize) {
cout << "alpha = " << alpha << endl;
for (double p_invar = p_invarMin; p_invar < p_invarMax; p_invar = p_invar + stepSize) {
site_rates->setGammaShape(alpha);
site_rates->setPInvar(p_invar);
iqtree.clearAllPartialLH();
double lh = iqtree.getModelFactory()->optimizeParameters(params.fixed_branch_length, false, params.modelEps);
// stringstream ss;
// ss << fixed << setprecision(2) << alpha << " " << p_invar << " " << lh << " " << iqtree.treeLength();
aiFileResults << alpha << " " << p_invar << " " << lh << " " << iqtree.treeLength() << endl;
//cout << ss.str() << endl;
// results.push_back(ss.str());
iqtree.restoreBranchLengths(lenvec);
}
}
// for (vector<string>::iterator it = results.begin(); it != results.end(); it++) {
// aiFileResults << (*it) << endl;
// }
aiFileResults.close();
cout << "Results were written to: " << aiResultsFileName << endl;
cout << "Wall clock time used: " << getRealTime() - params.start_real_time << endl;
}
/**********************************************************
* STANDARD NON-PARAMETRIC BOOTSTRAP
***********************************************************/
void runStandardBootstrap(Params ¶ms, Alignment *alignment, IQTree *tree) {
ModelCheckpoint *model_info = new ModelCheckpoint;
StrVector removed_seqs, twin_seqs;
// turn off all branch tests
int saved_aLRT_replicates = params.aLRT_replicates;
int saved_localbp_replicates = params.localbp_replicates;
bool saved_aLRT_test = params.aLRT_test;
bool saved_aBayes_test = params.aBayes_test;
params.aLRT_replicates = 0;
params.localbp_replicates = 0;
params.aLRT_test = false;
params.aBayes_test = false;
if (params.suppress_output_flags & OUT_TREEFILE)
outError("Suppress .treefile not allowed for standard bootstrap");
string treefile_name = params.out_prefix;
treefile_name += ".treefile";
string boottrees_name = params.out_prefix;
boottrees_name += ".boottrees";
string bootaln_name = params.out_prefix;
bootaln_name += ".bootaln";
string bootlh_name = params.out_prefix;
bootlh_name += ".bootlh";
int bootSample = 0;
if (tree->getCheckpoint()->get("bootSample", bootSample)) {
cout << "CHECKPOINT: " << bootSample << " bootstrap analyses restored" << endl;
} else if (MPIHelper::getInstance().isMaster()) {
// first empty the boottrees file
try {
ofstream tree_out;
tree_out.exceptions(ios::failbit | ios::badbit);
tree_out.open(boottrees_name.c_str());
tree_out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, boottrees_name);
}
// empty the bootaln file
if (params.print_bootaln)
try {
ofstream tree_out;
tree_out.exceptions(ios::failbit | ios::badbit);
tree_out.open(bootaln_name.c_str());
tree_out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, bootaln_name);
}
}
double start_time = getCPUTime();
double start_real_time = getRealTime();
startTreeReconstruction(params, tree, *model_info);
// 2018-06-21: bug fix: alignment might be changed by -m ...MERGE
alignment = tree->aln;
// do bootstrap analysis
for (int sample = bootSample; sample < params.num_bootstrap_samples; sample++) {
cout << endl << "===> START " << RESAMPLE_NAME_UPPER << " REPLICATE NUMBER "
<< sample + 1 << endl << endl;
// 2015-12-17: initialize random stream for creating bootstrap samples
// mainly so that checkpointing does not need to save bootstrap samples
int *saved_randstream = randstream;
init_random(params.ran_seed + sample);
Alignment* bootstrap_alignment;
cout << "Creating " << RESAMPLE_NAME << " alignment (seed: " << params.ran_seed+sample << ")..." << endl;
if (alignment->isSuperAlignment())
bootstrap_alignment = new SuperAlignment;
else
bootstrap_alignment = new Alignment;
bootstrap_alignment->createBootstrapAlignment(alignment, NULL, params.bootstrap_spec);
// restore randstream
finish_random();
randstream = saved_randstream;
if (params.print_tree_lh && MPIHelper::getInstance().isMaster()) {
double prob;
bootstrap_alignment->multinomialProb(*alignment, prob);
ofstream boot_lh;
if (sample == 0)
boot_lh.open(bootlh_name.c_str());
else
boot_lh.open(bootlh_name.c_str(), ios_base::out | ios_base::app);
boot_lh << "0\t" << prob << endl;
boot_lh.close();
}
IQTree *boot_tree;
if (alignment->isSuperAlignment()){
if(params.partition_type != BRLEN_OPTIMIZE){
boot_tree = new PhyloSuperTreePlen((SuperAlignment*) bootstrap_alignment, (PhyloSuperTree*) tree);
} else {
boot_tree = new PhyloSuperTree((SuperAlignment*) bootstrap_alignment, (PhyloSuperTree*) tree);
}
} else {
// allocate heterotachy tree if neccessary
int pos = posRateHeterotachy(alignment->model_name);
if (params.num_mixlen > 1) {
boot_tree = new PhyloTreeMixlen(bootstrap_alignment, params.num_mixlen);
} else if (pos != string::npos) {
boot_tree = new PhyloTreeMixlen(bootstrap_alignment, 0);
} else
boot_tree = new IQTree(bootstrap_alignment);
}
if (params.print_bootaln && MPIHelper::getInstance().isMaster()) {
bootstrap_alignment->printAlignment(params.aln_output_format, bootaln_name.c_str(), true);
}
if (params.print_boot_site_freq && MPIHelper::getInstance().isMaster()) {
printSiteStateFreq((((string)params.out_prefix)+"."+convertIntToString(sample)+".bootsitefreq").c_str(), bootstrap_alignment);
bootstrap_alignment->printAlignment(params.aln_output_format, (((string)params.out_prefix)+"."+convertIntToString(sample)+".bootaln").c_str());
}
if (!tree->constraintTree.empty()) {
boot_tree->constraintTree.readConstraint(tree->constraintTree);
}
// set checkpoint
boot_tree->setCheckpoint(tree->getCheckpoint());
boot_tree->num_precision = tree->num_precision;
runTreeReconstruction(params, boot_tree);
// read in the output tree file
stringstream ss;
boot_tree->printTree(ss);
// try {
// ifstream tree_in;
// tree_in.exceptions(ios::failbit | ios::badbit);
// tree_in.open(treefile_name.c_str());
// tree_in >> tree_str;
// tree_in.close();
// } catch (ios::failure) {
// outError(ERR_READ_INPUT, treefile_name);
// }
// write the tree into .boottrees file
if (MPIHelper::getInstance().isMaster())
try {
ofstream tree_out;
tree_out.exceptions(ios::failbit | ios::badbit);
tree_out.open(boottrees_name.c_str(), ios_base::out | ios_base::app);
tree_out << ss.str() << endl;
tree_out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, boottrees_name);
}
// OBSOLETE fix bug: set the model for original tree after testing
// if ((params.model_name.substr(0,4) == "TEST" || params.model_name.substr(0,2) == "MF") && tree->isSuperTree()) {
// PhyloSuperTree *stree = ((PhyloSuperTree*)tree);
// stree->part_info = ((PhyloSuperTree*)boot_tree)->part_info;
// }
if (params.num_bootstrap_samples == 1)
reportPhyloAnalysis(params, *boot_tree, *model_info);
// WHY was the following line missing, which caused memory leak?
bootstrap_alignment = boot_tree->aln;
delete boot_tree;
// fix bug: bootstrap_alignment might be changed
delete bootstrap_alignment;
// clear all checkpointed information
tree->getCheckpoint()->keepKeyPrefix("iqtree");
tree->getCheckpoint()->put("bootSample", sample+1);
tree->getCheckpoint()->putBool("finished", false);
tree->getCheckpoint()->dump(true);
}
if (params.consensus_type == CT_CONSENSUS_TREE && MPIHelper::getInstance().isMaster()) {
cout << endl << "===> COMPUTE CONSENSUS TREE FROM " << params.num_bootstrap_samples
<< RESAMPLE_NAME_UPPER << " TREES" << endl << endl;
string root_name = (params.root) ? params.root : alignment->getSeqName(0);
const char* saved_root = params.root;
params.root = root_name.c_str();
computeConsensusTree(boottrees_name.c_str(), 0, 1e6, -1,
params.split_threshold, NULL, params.out_prefix, NULL, ¶ms);
params.root = saved_root;
}
if (params.compute_ml_tree) {
cout << endl << "===> START ANALYSIS ON THE ORIGINAL ALIGNMENT" << endl << endl;
// restore branch tests
params.aLRT_replicates = saved_aLRT_replicates;
params.localbp_replicates = saved_localbp_replicates;
params.aLRT_test = saved_aLRT_test;
params.aBayes_test = saved_aBayes_test;
if (params.num_runs == 1)
runTreeReconstruction(params, tree);
else
runMultipleTreeReconstruction(params, tree->aln, tree);
if (MPIHelper::getInstance().isMaster()) {
if (params.consensus_type == CT_CONSENSUS_TREE && params.num_runs == 1) {
// 2017-12-08: optimize branch lengths of consensus tree
optimizeConTree(params, tree);
}
cout << endl << "===> ASSIGN " << RESAMPLE_NAME_UPPER
<< " SUPPORTS TO THE TREE FROM ORIGINAL ALIGNMENT" << endl << endl;
MExtTree ext_tree;
assignBootstrapSupport(boottrees_name.c_str(), 0, 1e6,
treefile_name.c_str(), false, treefile_name.c_str(),
params.out_prefix, ext_tree, NULL, ¶ms);
tree->copyTree(&ext_tree);
reportPhyloAnalysis(params, *tree, *model_info);
}
} else if (params.consensus_type == CT_CONSENSUS_TREE && MPIHelper::getInstance().isMaster()) {
int mi = params.min_iterations;
STOP_CONDITION sc = params.stop_condition;
params.min_iterations = 0;
params.stop_condition = SC_FIXED_ITERATION;
runTreeReconstruction(params, tree);
params.min_iterations = mi;
params.stop_condition = sc;
tree->stop_rule.initialize(params);
optimizeConTree(params, tree);
reportPhyloAnalysis(params, *tree, *model_info);
} else
cout << endl;
#ifdef USE_BOOSTER
if (params.transfer_bootstrap) {
// transfer bootstrap expectation (TBE)
cout << "Performing transfer bootstrap expectation..." << endl;
string input_tree = (string)params.out_prefix + ".treefile";
string boot_trees = (string)params.out_prefix + ".boottrees";
string out_tree = (string)params.out_prefix + ".tbe.tree";
string out_raw_tree = (string)params.out_prefix + ".tbe.rawtree";
string stat_out = (string)params.out_prefix + ".tbe.stat";
main_booster(input_tree.c_str(), boot_trees.c_str(), out_tree.c_str(),
(params.transfer_bootstrap==2) ? out_raw_tree.c_str() : NULL,
stat_out.c_str(), (verbose_mode >= VB_MED) ? 0 : 1);
cout << "TBE tree written to " << out_tree << endl;
if (params.transfer_bootstrap == 2)
cout << "TBE raw tree written to " << out_raw_tree << endl;
cout << "TBE statistic written to " << stat_out << endl;
cout << endl;
}
#endif
if (MPIHelper::getInstance().isMaster()) {
cout << "Total CPU time for " << RESAMPLE_NAME << ": " << (getCPUTime() - start_time) << " seconds." << endl;
cout << "Total wall-clock time for " << RESAMPLE_NAME << ": " << (getRealTime() - start_real_time) << " seconds." << endl << endl;
cout << "Non-parametric " << RESAMPLE_NAME << " results written to:" << endl;
if (params.print_bootaln)
cout << RESAMPLE_NAME_I << " alignments: " << params.out_prefix << ".bootaln" << endl;
cout << RESAMPLE_NAME_I << " trees: " << params.out_prefix << ".boottrees" << endl;
if (params.consensus_type == CT_CONSENSUS_TREE)
cout << " Consensus tree: " << params.out_prefix << ".contree" << endl;
cout << endl;
}
delete model_info;
}
void convertAlignment(Params ¶ms, IQTree *iqtree) {
Alignment *alignment = iqtree->aln;
if (params.num_bootstrap_samples || params.print_bootaln) {
// create bootstrap alignment
Alignment* bootstrap_alignment;
cout << "Creating " << RESAMPLE_NAME << " alignment..." << endl;
if (alignment->isSuperAlignment())
bootstrap_alignment = new SuperAlignment;
else
bootstrap_alignment = new Alignment;
bootstrap_alignment->createBootstrapAlignment(alignment, NULL, params.bootstrap_spec);
delete alignment;
alignment = bootstrap_alignment;
iqtree->aln = alignment;
}
int exclude_sites = 0;
if (params.aln_nogaps)
exclude_sites += EXCLUDE_GAP;
if (params.aln_no_const_sites)
exclude_sites += EXCLUDE_INVAR;
if (alignment->isSuperAlignment()) {
alignment->printAlignment(params.aln_output_format, params.aln_output, false, params.aln_site_list,
exclude_sites, params.ref_seq_name);
if (params.print_subaln)
((SuperAlignment*)alignment)->printSubAlignments(params);
if (params.aln_output_format != IN_NEXUS) {
string partition_info = string(params.aln_output) + ".nex";
((SuperAlignment*)alignment)->printPartition(partition_info.c_str(), params.aln_output);
partition_info = (string)params.aln_output + ".partitions";
((SuperAlignment*)alignment)->printPartitionRaxml(partition_info.c_str());
}
} else if (params.gap_masked_aln) {
Alignment out_aln;
Alignment masked_aln(params.gap_masked_aln, params.sequence_type, params.intype, params.model_name);
out_aln.createGapMaskedAlignment(&masked_aln, alignment);
out_aln.printAlignment(params.aln_output_format, params.aln_output, false, params.aln_site_list,
exclude_sites, params.ref_seq_name);
string str = params.gap_masked_aln;
str += ".sitegaps";
out_aln.printSiteGaps(str.c_str());
} else {
alignment->printAlignment(params.aln_output_format, params.aln_output, false, params.aln_site_list,
exclude_sites, params.ref_seq_name);
}
}
/**
2016-08-04: compute a site frequency model for profile mixture model
*/
void computeSiteFrequencyModel(Params ¶ms, Alignment *alignment) {
cout << endl << "===> COMPUTING SITE FREQUENCY MODEL BASED ON TREE FILE " << params.tree_freq_file << endl;
ASSERT(params.tree_freq_file);
PhyloTree *tree = new PhyloTree(alignment);
tree->setParams(¶ms);
bool myrooted = params.is_rooted;
tree->readTree(params.tree_freq_file, myrooted);
tree->setAlignment(alignment);
tree->setRootNode(params.root);
ModelsBlock *models_block = readModelsDefinition(params);
tree->setModelFactory(new ModelFactory(params, alignment->model_name, tree, models_block));
delete models_block;
tree->setModel(tree->getModelFactory()->model);
tree->setRate(tree->getModelFactory()->site_rate);
tree->setLikelihoodKernel(params.SSE);
tree->setNumThreads(params.num_threads);
if (!tree->getModel()->isMixture())
outError("No mixture model was specified!");
uint64_t mem_size = tree->getMemoryRequired();
uint64_t total_mem = getMemorySize();
cout << "NOTE: " << (mem_size / 1024) / 1024 << " MB RAM is required!" << endl;
if (mem_size >= total_mem) {
outError("Memory required exceeds your computer RAM size!");
}
#ifdef BINARY32
if (mem_size >= 2000000000) {
outError("Memory required exceeds 2GB limit of 32-bit executable");
}
#endif
#ifdef _OPENMP
if (tree->num_threads <= 0) {
int bestThreads = tree->testNumThreads();
omp_set_num_threads(bestThreads);
} else
tree->warnNumThreads();
#endif
tree->initializeAllPartialLh();
// 2017-12-07: Increase espilon ten times (0.01 -> 0.1) to speedup PMSF computation
tree->getModelFactory()->optimizeParameters(params.fixed_branch_length, true, params.modelEps*10);
size_t nptn = alignment->getNPattern(), nstates = alignment->num_states;
double *ptn_state_freq = new double[nptn*nstates];
tree->computePatternStateFreq(ptn_state_freq);
alignment->site_state_freq.resize(nptn);
for (size_t ptn = 0; ptn < nptn; ptn++) {
double *f = new double[nstates];
memcpy(f, ptn_state_freq+ptn*nstates, sizeof(double)*nstates);
alignment->site_state_freq[ptn] = f;
}
alignment->getSitePatternIndex(alignment->site_model);
printSiteStateFreq(((string)params.out_prefix+".sitefreq").c_str(), tree, ptn_state_freq);
params.print_site_state_freq = WSF_NONE;
delete [] ptn_state_freq;
delete tree;
cout << endl << "===> CONTINUE ANALYSIS USING THE INFERRED SITE FREQUENCY MODEL" << endl;
}
/**********************************************************
* TOP-LEVEL FUNCTION
***********************************************************/
IQTree *newIQTree(Params ¶ms, Alignment *alignment) {
IQTree *tree;
if (alignment->isSuperAlignment()) {
if (params.partition_type == TOPO_UNLINKED) {
tree = new PhyloSuperTreeUnlinked((SuperAlignment*)alignment);
} else if(params.partition_type != BRLEN_OPTIMIZE){
// initialize supertree - Proportional Edges case
tree = new PhyloSuperTreePlen((SuperAlignment*)alignment, params.partition_type);
} else {
// initialize supertree stuff if user specifies partition file with -sp option
tree = new PhyloSuperTree((SuperAlignment*)alignment);
}
// this alignment will actually be of type SuperAlignment
// alignment = tree->aln;
if (((PhyloSuperTree*)tree)->rescale_codon_brlen)
cout << "NOTE: Mixed codon and other data, branch lengths of codon partitions are rescaled by 3!" << endl;
} else {
// allocate heterotachy tree if neccessary
int pos = posRateHeterotachy(alignment->model_name);
if (params.num_mixlen > 1) {
tree = new PhyloTreeMixlen(alignment, params.num_mixlen);
} else if (pos != string::npos) {
tree = new PhyloTreeMixlen(alignment, 0);
} else
tree = new IQTree(alignment);
}
return tree;
}
/** get ID of bad or good symtest results */
void getSymTestID(vector<SymTestResult> &res, set<int> &id, bool bad_res) {
if (bad_res) {
// get significant test ID
switch (Params::getInstance().symtest) {
case SYMTEST_BINOM:
for (auto i = res.begin(); i != res.end(); i++)
if (i->pvalue_binom < Params::getInstance().symtest_pcutoff)
id.insert(i - res.begin());
break;
case SYMTEST_MAXDIV:
for (auto i = res.begin(); i != res.end(); i++)
if (i->pvalue_maxdiv < Params::getInstance().symtest_pcutoff)
id.insert(i - res.begin());
break;
default:
break;
}
} else {
// get non-significant test ID
switch (Params::getInstance().symtest) {
case SYMTEST_BINOM:
for (auto i = res.begin(); i != res.end(); i++)
if (i->pvalue_binom >= Params::getInstance().symtest_pcutoff)
id.insert(i - res.begin());
break;
case SYMTEST_MAXDIV:
for (auto i = res.begin(); i != res.end(); i++)
if (i->pvalue_maxdiv >= Params::getInstance().symtest_pcutoff)
id.insert(i - res.begin());
break;
default:
break;
}
}
}
double computePValueSMax(vector<SymTestResult> &sym, int start, int step) {
double orig_max = sym[start].max_stat;
int count = 0, num = 0;
for (size_t i = start; i < sym.size(); i += step, num++)
if (sym[i].max_stat >= orig_max)
count++;
return double(count)/num;
}
void doSymTest(Alignment *alignment, Params ¶ms) {
double start_time = getRealTime();
cout << "Performing matched-pair tests of symmetry...";
vector<SymTestResult> sym, marsym, intsym;
size_t num_parts = 1;
if (alignment->isSuperAlignment())
num_parts = ((SuperAlignment*)alignment)->partitions.size();
string filename_stat = string(params.out_prefix) + ".symstat.csv";
ofstream *out_stat = NULL;
if (params.symtest_stat) {
out_stat = new ofstream;
out_stat->open(filename_stat);
*out_stat
<< "# Statistic values for matched-pair tests of symmetry" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# dat=read.csv('" << filename_stat << "',comment.char='#')" << endl
<< "# Columns are comma-separated with following meanings:" << endl
<< "# ID: Partition ID" << endl
<< "# Seq1: ID of sequence 1 within partition" << endl
<< "# Seq1: ID of sequence 2 within partition" << endl
<< "# Sym: Statistic for test of symmetry" << endl
<< "# SymChi: Chi-square p-value for test of symmetry" << endl
<< "# Mar: Statistic for test of marginal symmetry" << endl
<< "# MarChi: Chi-square p-value for marginal test of symmetry" << endl
<< "# Int: Statistic for test of internal symmetry" << endl
<< "# MarChi: Chi-square p-value for internal test of symmetry" << endl
<< "ID,Seq1,Seq2,Sym,SymChi,Mar,MarChi,Int,IntChi" << endl;
}
sym.resize(num_parts*params.symtest_shuffle);
marsym.resize(num_parts*params.symtest_shuffle);
intsym.resize(num_parts*params.symtest_shuffle);
for (int i = 0; i < params.symtest_shuffle; i++) {
vector<SymTestStat> *stats = NULL;
if (params.symtest_stat)
stats = new vector<SymTestStat>;
if (i == 0) // original alignment
alignment->doSymTest(i*num_parts, sym, marsym, intsym, NULL, stats);
else {
int *rstream;
init_random(params.ran_seed+i+1, false, &rstream);
alignment->doSymTest(i*num_parts, sym, marsym, intsym, rstream, stats);
finish_random(rstream);
}
if ((i+1)*10 % params.symtest_shuffle == 0) {
cout << " " << (i+1)*100 / params.symtest_shuffle << "%";
cout.flush();
}
if (!stats)
continue;
for (auto it = stats->begin(); it != stats->end(); it++) {
*out_stat << it->part << ',' << it->seq1 << ',' << it->seq2 << ','
<< it->chi2_sym << ',' << it->pval_sym << ','
<< it->chi2_marsym << ',' << it->pval_marsym << ','
<< it->chi2_intsym << ',' << it->pval_intsym << endl;
}
delete stats;
}
if (out_stat) {
out_stat->close();
delete out_stat;
}
if (params.symtest_shuffle > 1) {
// compute p-value for s-max approach
for (int part = 0; part < num_parts; part++) {
sym[part].pvalue_perm = computePValueSMax(sym, part, num_parts);
marsym[part].pvalue_perm = computePValueSMax(marsym, part, num_parts);
intsym[part].pvalue_perm = computePValueSMax(intsym, part, num_parts);
}
}
string filename = string(params.out_prefix) + ".symtest.csv";
ofstream out;
out.open(filename);
out << "# Matched-pair tests of symmetry" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# dat=read.csv('" << filename << "',comment.char='#')" << endl
<< "# Columns are comma-separated with following meanings:" << endl
<< "# Name: Partition name" << endl
<< "# SymSig: Number of significant sequence pairs by test of symmetry" << endl
<< "# SymNon: Number of non-significant sequence pairs by test of symmetry" << endl
<< ((Params::getInstance().symtest == SYMTEST_BINOM) ? "# SymBi: P-value for binomial test of symmetry" : "# SymPval: P-value for maximum test of symmetry") << endl;
if (params.symtest_shuffle > 1)
out << "# SymMax: Maximum of pair statistics by test of symmetry" << endl
<< "# SymPerm: P-value for permutation test of symmetry" << endl;
out << "# MarSig: Number of significant sequence pairs by test of marginal symmetry" << endl
<< "# MarNon: Number of non-significant sequence pairs by test of marginal symmetry" << endl
<< ((Params::getInstance().symtest == SYMTEST_BINOM) ? "# MarBi: P-value for binomial test of marginal symmetry" : "# MarPval: P-value for maximum test of marginal symmetry") << endl;
if (params.symtest_shuffle > 1)
out << "# MarMax: Maximum of pair statistics by test of marginal symmetry" << endl
<< "# MarPerm: P-value for permutation test of marginal symmetry" << endl;
out << "# IntSig: Number of significant sequence pairs by test of internal symmetry" << endl
<< "# IntNon: Number of non-significant sequence pairs by test of internal symmetry" << endl
<< ((Params::getInstance().symtest == SYMTEST_BINOM) ? "# IntBi: P-value for binomial test of symmetry" : "# IntPval: P-value for maximum test of internal symmetry") << endl;
if (params.symtest_shuffle > 1)
out << "# IntMax: Maximum of pair statistics by test of internal symmetry" << endl
<< "# IntPerm: P-value for permutation test of internal symmetry" << endl;
out << "Name,SymSig,SymNon," << ((Params::getInstance().symtest == SYMTEST_BINOM) ? "SymBi" : "SymPval")
<< ((params.symtest_shuffle > 1) ? ",SymMax,SymPerm" : "")
<< ",MarSig,MarNon," << ((Params::getInstance().symtest == SYMTEST_BINOM) ? "MarBi" : "MarPval")
<< ((params.symtest_shuffle > 1) ? ",MarMax,MarPerm" : "")
<< ",IntSig,IntNon," << ((Params::getInstance().symtest == SYMTEST_BINOM) ? "IntBi" : "IntPval")
<< ((params.symtest_shuffle > 1) ? ",IntMax,IntPerm" : "") << endl;
if (alignment->isSuperAlignment()) {
SuperAlignment *saln = (SuperAlignment*)alignment;
for (int part = 0; part < saln->partitions.size(); part++)
out << saln->partitions[part]->name << ','
<< sym[part] << ',' << marsym[part] << ',' << intsym[part] << endl;
} else {
out << alignment->name << ',' << sym[0] << ',' << marsym[0] << ',' << intsym[0] << endl;
}
if (params.symtest_shuffle > 1) {
for (int part = num_parts; part < sym.size(); part++) {
sym[part].pvalue_perm = marsym[part].pvalue_perm = intsym[part].pvalue_perm = -1.0;
out << part % num_parts << ','
<< sym[part] << ',' << marsym[part] << ',' << intsym[part] << endl;
}
// erase the rest
sym.erase(sym.begin()+num_parts, sym.end());
marsym.erase(marsym.begin()+num_parts, marsym.end());
intsym.erase(intsym.begin()+num_parts, intsym.end());
}
out.close();
cout << " " << getRealTime() - start_time << " seconds" << endl;
if (params.symtest_stat)
cout << "SymTest statistics written to " << filename_stat << endl;
cout << "SymTest results written to " << filename << endl;
// now filter out partitions
if (alignment->isSuperAlignment()) {
set<int> part_id;
if (params.symtest_remove == 1) {
// remove bad loci
if (params.symtest_type == 0)
getSymTestID(sym, part_id, true);
else if (params.symtest_type == 1)
getSymTestID(marsym, part_id, true);
else
getSymTestID(intsym, part_id, true);
} else if (params.symtest_remove == 2) {
// remove good loci
if (params.symtest_type == 0)
getSymTestID(sym, part_id, false);
else if (params.symtest_type == 1)
getSymTestID(marsym, part_id, false);
else
getSymTestID(intsym, part_id, false);
}
if (!part_id.empty()) {
SuperAlignment *saln = (SuperAlignment*)alignment;
cout << "Removing " << part_id.size()
<< ((params.symtest_remove == 1)? " bad" : " good") << " partitions (pvalue cutoff = "
<< params.symtest_pcutoff << ")..." << endl;
if (part_id.size() < alignment->getNSite())
saln->removePartitions(part_id);
else
outError("Can't remove all partitions");
if (params.aln_output_format == IN_NEXUS) {
string aln_file = (string)params.out_prefix + ((params.symtest_remove == 1)? ".good.nex" : ".bad.nex");
alignment->printAlignment(params.aln_output_format, aln_file.c_str());
} else {
string aln_file = (string)params.out_prefix + ((params.symtest_remove == 1)? ".good.phy" : ".bad.phy");
alignment->printAlignment(params.aln_output_format, aln_file.c_str());
string filename = (string)params.out_prefix + ((params.symtest_remove == 2)? ".good.nex" : ".bad.nex");
saln->printPartition(filename.c_str(), aln_file.c_str());
}
}
}
if (params.symtest_only)
exit(EXIT_SUCCESS);
}
void runPhyloAnalysis(Params ¶ms, Checkpoint *checkpoint) {
Alignment *alignment;
checkpoint->putBool("finished", false);
checkpoint->setDumpInterval(params.checkpoint_dump_interval);
/****************** read in alignment **********************/
if (params.partition_file) {
// Partition model analysis
if (params.partition_type == TOPO_UNLINKED)
alignment = new SuperAlignmentUnlinked(params);
else
alignment = new SuperAlignment(params);
} else {
alignment = createAlignment(params.aln_file, params.sequence_type, params.intype, params.model_name);
if (params.freq_const_patterns) {
int orig_nsite = alignment->getNSite();
alignment->addConstPatterns(params.freq_const_patterns);
cout << "INFO: " << alignment->getNSite() - orig_nsite << " const sites added into alignment" << endl;
}
// Initialize site-frequency model
if (params.tree_freq_file) {
if (checkpoint->getBool("finishedSiteFreqFile")) {
alignment->readSiteStateFreq(((string)params.out_prefix + ".sitefreq").c_str());
params.print_site_state_freq = WSF_NONE;
cout << "CHECKPOINT: Site frequency model restored" << endl;
} else {
computeSiteFrequencyModel(params, alignment);
checkpoint->putBool("finishedSiteFreqFile", true);
checkpoint->dump();
}
}
if (params.site_freq_file) {
alignment->readSiteStateFreq(params.site_freq_file);
}
}
if (params.symtest) {
doSymTest(alignment, params);
}
if (params.print_aln_info) {
string site_info_file = string(params.out_prefix) + ".alninfo";
alignment->printSiteInfo(site_info_file.c_str());
cout << "Alignment sites statistics printed to " << site_info_file << endl;
}
/*************** initialize tree ********************/
IQTree *tree = newIQTree(params, alignment);
tree->setCheckpoint(checkpoint);
if (params.min_branch_length <= 0.0) {
params.min_branch_length = 1e-6;
if (!tree->isSuperTree() && tree->getAlnNSite() >= 100000) {
params.min_branch_length = 0.1 / (tree->getAlnNSite());
tree->num_precision = max((int)ceil(-log10(Params::getInstance().min_branch_length))+1, 6);
cout.precision(12);
cout << "NOTE: minimal branch length is reduced to " << params.min_branch_length << " for long alignment" << endl;
cout.precision(3);
}
// Increase the minimum branch length if PoMo is used.
if (alignment->seq_type == SEQ_POMO) {
params.min_branch_length *= alignment->virtual_pop_size * alignment->virtual_pop_size;
cout.precision(12);
cout << "NOTE: minimal branch length is increased to " << params.min_branch_length << " because PoMo infers number of mutations and frequency shifts" << endl;
cout.precision(3);
}
}
// Increase the minimum branch length if PoMo is used.
if (alignment->seq_type == SEQ_POMO) {
params.max_branch_length *= alignment->virtual_pop_size * alignment->virtual_pop_size;
cout.precision(1);
cout << "NOTE: maximal branch length is increased to " << params.max_branch_length << " because PoMo infers number of mutations and frequency shifts" << endl;
cout.precision(3);
}
if (params.concatenate_aln) {
Alignment aln(params.concatenate_aln, params.sequence_type, params.intype, params.model_name);
cout << "Concatenating " << params.aln_file << " with " << params.concatenate_aln << " ..." << endl;
alignment->concatenateAlignment(&aln);
}
if (params.constraint_tree_file) {
cout << "Reading constraint tree " << params.constraint_tree_file << "..." << endl;
tree->constraintTree.readConstraint(params.constraint_tree_file, alignment->getSeqNames());
if (params.start_tree == STT_PLL_PARSIMONY)
params.start_tree = STT_PARSIMONY;
else if (params.start_tree == STT_BIONJ)
outError("Constraint tree does not work with -t BIONJ");
if (params.num_bootstrap_samples || params.gbo_replicates)
cout << "INFO: Constraint tree will be applied to ML tree and all bootstrap trees." << endl;
}
if (params.compute_seq_identity_along_tree) {
if (!params.user_file)
outError("Please supply a user tree file!");
tree->readTree(params.user_file, params.is_rooted);
if (!tree->rooted && !params.root) {
outError("Tree is unrooted, thus you have to specify a root with -o option");
}
tree->setAlignment(tree->aln);
if (!tree->rooted)
tree->setRootNode(params.root);
tree->computeSeqIdentityAlongTree();
if (verbose_mode >= VB_MED)
tree->drawTree(cout);
string out_tree = (string)params.out_prefix + ".seqident_tree";
tree->printTree(out_tree.c_str());
cout << "Tree with sequence identity printed to " << out_tree << endl;
} else if (params.aln_output) {
/************ convert alignment to other format and write to output file *************/
convertAlignment(params, tree);
} else if (params.gbo_replicates > 0 && params.user_file && params.second_tree) {
// run one of the UFBoot analysis
// runGuidedBootstrap(params, alignment, *tree);
outError("Obsolete feature");
} else if (params.avh_test) {
// run one of the wondering test for Arndt
// runAvHTest(params, alignment, *tree);
outError("Obsolete feature");
} else if (params.bootlh_test) {
// run Arndt's plot of tree likelihoods against bootstrap alignments
// runBootLhTest(params, alignment, *tree);
outError("Obsolete feature");
} else if (params.num_bootstrap_samples == 0) {
/********************************************************************************
THE MAIN MAXIMUM LIKELIHOOD TREE RECONSTRUCTION
********************************************************************************/
ModelCheckpoint *model_info = new ModelCheckpoint;
alignment->checkGappySeq(params.remove_empty_seq);
// remove identical sequences
if (params.ignore_identical_seqs) {
tree->removeIdenticalSeqs(params);
if (tree->removed_seqs.size() > 0 && MPIHelper::getInstance().isMaster() && (params.suppress_output_flags & OUT_UNIQUESEQ) == 0) {
string filename = (string)params.out_prefix + ".uniqueseq.phy";
tree->aln->printAlignment(params.aln_output_format, filename.c_str());
cout << endl << "For your convenience alignment with unique sequences printed to " << filename << endl;
}
}
alignment = NULL; // from now on use tree->aln instead
startTreeReconstruction(params, tree, *model_info);
// call main tree reconstruction
if (params.num_runs == 1)
runTreeReconstruction(params, tree);
else
runMultipleTreeReconstruction(params, tree->aln, tree);
if (MPIHelper::getInstance().isMaster()) {
reportPhyloAnalysis(params, *tree, *model_info);
}
// reinsert identical sequences
if (tree->removed_seqs.size() > 0) {
// BUG FIX: dont use reinsertIdenticalSeqs anymore
tree->insertTaxa(tree->removed_seqs, tree->twin_seqs);
tree->printResultTree();
}
delete model_info;
if (params.dating_method != "") {
doTimeTree(tree);
}
} else {
// the classical non-parameter bootstrap (SBS)
// if (params.model_name.find("LINK") != string::npos || params.model_name.find("MERGE") != string::npos)
// outError("-m TESTMERGE is not allowed when doing standard bootstrap. Please first\nfind partition scheme on the original alignment and use it for bootstrap analysis");
if (alignment->getNSeq() < 4)
outError("It makes no sense to perform bootstrap with less than 4 sequences.");
runStandardBootstrap(params, alignment, tree);
}
// if (params.upper_bound) {
// UpperBounds(¶ms, alignment, tree);
// }
if(verbose_mode >= VB_MED){
if(tree->isSuperTree() && params.partition_type != BRLEN_OPTIMIZE){
((PhyloSuperTreePlen*) tree)->printNNIcasesNUM();
}
}
// 2015-09-22: bug fix, move this line to before deleting tree
alignment = tree->aln;
delete tree;
// BUG FIX: alignment can be changed, should delete tree->aln instead
// 2015-09-22: THIS IS STUPID: after deleting tree, one cannot access tree->aln anymore
// alignment = tree->aln;
delete alignment;
checkpoint->putBool("finished", true);
checkpoint->dump(true);
}
/**
Perform separate tree reconstruction when tree topologies
are unlinked between partitions
*/
void runUnlinkedPhyloAnalysis(Params ¶ms, Checkpoint *checkpoint) {
SuperAlignment *super_aln;
ASSERT(params.partition_file);
/****************** read in alignment **********************/
// Partition model analysis
super_aln = new SuperAlignmentUnlinked(params);
PhyloSuperTree *super_tree = new PhyloSuperTree(super_aln);
/**** do separate tree reconstruction for each partition ***/
MTreeSet part_trees;
if (params.user_file) {
// reading user tree file for all partitions
bool is_rooted = false;
part_trees.readTrees(params.user_file, is_rooted, 0, super_aln->partitions.size());
if (is_rooted)
outError("Rooted trees not allowed: ", params.user_file);
if (part_trees.size() != super_aln->partitions.size())
outError("User tree file does not have the same number of trees as partitions");
params.user_file = NULL;
}
ModelCheckpoint *model_info = new ModelCheckpoint;
int part = 0;
for (auto alnit = super_aln->partitions.begin(); alnit != super_aln->partitions.end(); alnit++, part++) {
checkpoint->startStruct((*alnit)->name);
// allocate heterotachy tree if neccessary
int pos = posRateHeterotachy((*alnit)->model_name);
IQTree *tree;
if (params.num_mixlen > 1) {
tree = new PhyloTreeMixlen((*alnit), params.num_mixlen);
} else if (pos != string::npos) {
tree = new PhyloTreeMixlen((*alnit), 0);
} else
tree = new IQTree((*alnit));
tree->setCheckpoint(checkpoint);
if (checkpoint->getBool("finished")) {
tree->restoreCheckpoint();
} else {
if (!part_trees.empty())
tree->copyTree(part_trees[part]);
startTreeReconstruction(params, tree, *model_info);
// call main tree reconstruction
if (params.num_runs == 1)
runTreeReconstruction(params, tree);
else
runMultipleTreeReconstruction(params, tree->aln, tree);
checkpoint->putBool("finished", true);
checkpoint->dump();
}
super_tree->at(part)->copyTree(tree);
delete tree;
checkpoint->endStruct();
}
IQTree *iqtree = super_tree;
super_tree->setCheckpoint(checkpoint);
startTreeReconstruction(params, iqtree, *model_info);
runTreeReconstruction(params, iqtree);
if (MPIHelper::getInstance().isMaster())
reportPhyloAnalysis(params, *iqtree, *model_info);
delete super_tree;
delete super_aln;
delete model_info;
}
void assignBranchSupportNew(Params ¶ms) {
if (!params.user_file)
outError("No target tree file provided");
if (params.num_threads == 0)
outError("-nt AUTO is not supported for concordance factor analysis, please specify no. cores");
PhyloTree *tree;
Alignment *aln = NULL;
if (params.site_concordance) {
if (!params.aln_file && !params.partition_file)
outError("Please provide an alignment (-s) or partition file");
if (params.partition_file) {
params.compute_seq_composition = false;
aln = new SuperAlignment(params);
tree = new PhyloSuperTree((SuperAlignment*)aln);
} else {
aln = createAlignment(params.aln_file, params.sequence_type, params.intype, params.model_name);
tree = new PhyloTree;
}
} else {
tree = new PhyloTree;
}
tree->setParams(¶ms);
cout << "Reading tree " << params.user_file << " ..." << endl;
bool rooted = params.is_rooted;
tree->readTree(params.user_file, rooted);
cout << ((tree->rooted) ? "rooted" : "un-rooted") << " tree with "
<< tree->leafNum - tree->rooted << " taxa and " << tree->branchNum << " branches" << endl;
// 2018-12-13: move initialisation to fix rooted vs unrooted tree
if (params.site_concordance) {
tree->setAlignment(aln);
if (tree->isSuperTree())
((PhyloSuperTree*)tree)->mapTrees();
}
BranchVector branches;
tree->getInnerBranches(branches);
BranchVector::iterator brit;
for (brit = branches.begin(); brit != branches.end(); brit++) {
Neighbor *branch = brit->second->findNeighbor(brit->first);
string label = brit->second->name;
if (!label.empty())
PUT_ATTR(branch, label);
}
map<string,string> meanings;
if (!params.treeset_file.empty()) {
bool rooted = params.is_rooted;
MTreeSet trees(params.treeset_file.c_str(), rooted, params.tree_burnin, params.tree_max_count);
double start_time = getRealTime();
cout << "Computing gene concordance factor..." << endl;
tree->computeGeneConcordance(trees, meanings);
if (params.internode_certainty)
tree->computeQuartetConcordance(trees);
cout << getRealTime() - start_time << " sec" << endl;
}
if (params.site_concordance) {
cout << "Computing site concordance factor..." << endl;
double start_time = getRealTime();
tree->computeSiteConcordance(meanings);
cout << getRealTime() - start_time << " sec" << endl;
delete aln;
}
string prefix = (params.out_prefix) ? params.out_prefix : params.user_file;
string str = prefix + ".cf.tree";
tree->printTree(str.c_str());
cout << "Tree with concordance factors written to " << str << endl;
str = prefix + ".cf.tree.nex";
string filename = prefix + ".cf.stat";
tree->printNexus(str, WT_BR_LEN, "See " + filename + " for branch annotation meanings." +
" This file is best viewed in FigTree.");
cout << "Annotated tree (best viewed in FigTree) written to " << str << endl;
if (verbose_mode >= VB_DEBUG)
tree->drawTree(cout);
str = prefix + ".cf.branch";
tree->printTree(str.c_str(), WT_BR_LEN + WT_INT_NODE + WT_NEWLINE);
cout << "Tree with branch IDs written to " << str << endl;
ofstream out;
out.open(filename.c_str());
out << "# Concordance factor statistics" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab=read.table('" << filename << "',header=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl
<< "# ID: Branch ID" << endl;
map<string,string>::iterator mit;
for (mit = meanings.begin(); mit != meanings.end(); mit++)
if (mit->first[0] != '*')
out << "# " << mit->first << ": " << mit->second << endl;
out << "# Label: Existing branch label" << endl;
out << "# Length: Branch length" << endl;
for (mit = meanings.begin(); mit != meanings.end(); mit++)
if (mit->first[0] == '*')
out << "# " << mit->first << ": " << mit->second << endl;
out << "ID";
for (mit = meanings.begin(); mit != meanings.end(); mit++)
if (mit->first[0] != '*')
out << "\t" << mit->first;
out << "\tLabel\tLength" << endl;
for (brit = branches.begin(); brit != branches.end(); brit++) {
Neighbor *branch = brit->second->findNeighbor(brit->first);
int ID = brit->second->id;
out << ID;
for (mit = meanings.begin(); mit != meanings.end(); mit++) {
if (mit->first[0] == '*')
continue; // ignore NOTES
out << '\t';
string val;
if (branch->getAttr(mit->first, val))
out << val;
else
out << "NA";
}
double length = branch->length;
string label;
GET_ATTR(branch, label);
out << '\t' << label << '\t' << length << endl;
}
out.close();
cout << "Concordance factors per branch printed to " << filename << endl;
if (params.print_cf_quartets) {
filename = prefix + ".cf.quartet";
out.open(filename);
out << "# Site concordance factor for all resampled quartets (with replacement)" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab=read.table('" << filename << "',header=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl
<< "# ID: Branch ID" << endl
<< "# QuartID: Quartet ID" << endl
<< "# Seq1: ID of sequence 1 on 'left' side of the branch" << endl
<< "# Seq2: ID of sequence 2 on 'left' side of the branch" << endl
<< "# Seq3: ID of sequence 3 on 'right' side of the branch" << endl
<< "# Seq4: ID of sequence 4 on 'right' side of the branch" << endl
<< "# qCF: Fraction of concordant sites supporting quartet Seq1,Seq2|Seq3,Seq4 (=qCF_N/qN)" << endl
<< "# qCF_N: Number of concordant sites supporting quartet Seq1,Seq2|Seq3,Seq4" << endl
<< "# qDF1: Fraction of discordant sites supporting quartet Seq1,Seq3|Seq2,Seq4 (=qDF1_N/qN)" << endl
<< "# qDF1_N: Number of discordant sites supporting quartet Seq1,Seq3|Seq2,Seq4" << endl
<< "# qDF2: Fraction of discordant sites supporting quartet Seq1,Seq4|Seq2,Seq3 (=qDF2_N/qN)" << endl
<< "# qDF2_N: Number of discordant sites supporting quartet Seq1,Seq4|Seq2,Seq3" << endl
<< "# qN: Number of decisive sites with four taxa Seq1,Seq2,Seq3,Seq4 (=qCF_N+qDF1_N+qDF2_N)" << endl
<< "ID\tQuartID\tSeq1\tSeq2\tSeq3\tSeq4\tqCF\tqCF_N\tqDF1\tqDF1_N\tqDF2\tqDF2_N\tqN" << endl;
for (brit = branches.begin(); brit != branches.end(); brit++) {
Neighbor *branch = brit->second->findNeighbor(brit->first);
int ID = brit->second->id;
for (int qid = 0; ; qid++) {
string qstr;
if (branch->attributes.find("q" + convertIntToString(qid)) == branch->attributes.end())
break;
out << ID << '\t' << qid+1 << '\t' << branch->attributes["q" + convertIntToString(qid)] << endl;
}
}
out.close();
cout << "Site concordance factors for quartets printed to " << filename << endl;
}
if (!params.site_concordance_partition)
return;
// print concordant/discordant gene trees
filename = prefix + ".cf.stat_tree";
out.open(filename);
out << "# Concordance factor statistics for decisive trees" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab2=read.table('" << filename << "',header=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl
<< "# ID: Branch ID" << endl
<< "# TreeID: Tree ID" << endl
<< "# gC: 1/0 if tree is concordant/discordant with branch" << endl
<< "# gD1: 1/0 if NNI-1 tree is concordant/discordant with branch" << endl
<< "# gD2: 1/0 if NNI-2 tree is concordant/discordant with branch" << endl
<< "# NOTE: NA means that tree is not decisive for branch" << endl
<< "ID\tTreeID\tgC\tgD1\tgD2" << endl;
for (brit = branches.begin(); brit != branches.end(); brit++) {
Neighbor *branch = brit->second->findNeighbor(brit->first);
int ID = brit->second->id;
for (int part = 1; ; part++) {
string gC, gD1, gD2;
if (!branch->getAttr("gC" + convertIntToString(part), gC))
break;
branch->getAttr("gD1" + convertIntToString(part), gD1);
branch->getAttr("gD2" + convertIntToString(part), gD2);
out << ID << '\t' << part << '\t' << gC << '\t' << gD1 << '\t' << gD2 << endl;
}
}
out.close();
cout << "Concordance factors per branch and tree printed to " << filename << endl;
if (!params.site_concordance_partition || !tree->isSuperTree())
return;
// print partition-wise concordant/discordant sites
filename = prefix + ".cf.stat_loci";
out.open(filename);
out << "# Concordance factor statistics for loci" << endl
<< "# This file can be read in MS Excel or in R with command:" << endl
<< "# tab2=read.table('" << filename << "',header=TRUE)" << endl
<< "# Columns are tab-separated with following meaning:" << endl
<< "# ID: Branch ID" << endl
<< "# PartID: Locus ID" << endl
<< "# sC: Number of concordant sites averaged over " << params.site_concordance << " quartets" << endl
<< "# sD1: Number of discordant sites for alternative quartet 1" << endl
<< "# sD2: Number of discordant sites for alternative quartet 2" << endl
<< "# NOTE: NA means that locus is not decisive for branch" << endl
<< "ID\tPartID\tsC\tsD1\tsD2" << endl;
for (brit = branches.begin(); brit != branches.end(); brit++) {
Neighbor *branch = brit->second->findNeighbor(brit->first);
int ID = brit->second->id;
for (int part = 1; ; part++) {
string sC, sD1, sD2;
if (!branch->getAttr("sC" + convertIntToString(part), sC))
break;
if (!branch->getAttr("sD1" + convertIntToString(part), sD1))
break;
if (!branch->getAttr("sD2" + convertIntToString(part), sD2))
break;
out << ID << '\t' << part << '\t' << sC << '\t' << sD1 << '\t' << sD2 << endl;
}
}
out.close();
cout << "Concordance factors per branch and locus printed to " << filename << endl;
}
/**
* assign split occurence frequencies from a set of input trees onto a target tree
* NOTE: input trees must have the same taxon set
* @param input_trees file containing NEWICK tree strings
* @param burnin number of beginning trees to discard
* @param max_count max number of trees to read in
* @param target_tree the target tree
* @param rooted TRUE if trees are rooted, false for unrooted trees
* @param output_file file name to write output tree with assigned support values
* @param out_prefix prefix of output file
* @param mytree (OUT) resulting tree with support values assigned from target_tree
* @param tree_weight_file file containing INTEGER weights of input trees
* @param params program parameters
*/
void assignBootstrapSupport(const char *input_trees, int burnin, int max_count,
const char *target_tree, bool rooted, const char *output_tree,
const char *out_prefix, MExtTree &mytree, const char* tree_weight_file,
Params *params) {
bool myrooted = rooted;
// read the tree file
cout << "Reading tree " << target_tree << " ..." << endl;
mytree.init(target_tree, myrooted);
if (mytree.rooted)
cout << "rooted tree detected" << endl;
else
cout << "unrooted tree detected" << endl;
// reindex the taxa in the tree to aphabetical names
NodeVector taxa;
mytree.getTaxa(taxa);
sort(taxa.begin(), taxa.end(), nodenamecmp);
int i = 0;
for (NodeVector::iterator it = taxa.begin(); it != taxa.end(); it++) {
(*it)->id = i++;
}
/*
string filename = params.boot_trees;
filename += ".nolen";
boot_trees.printTrees(filename.c_str(), false);
return;
*/
SplitGraph sg;
SplitIntMap hash_ss;
// make the taxa name
vector<string> taxname;
taxname.resize(mytree.leafNum);
mytree.getTaxaName(taxname);
// read the bootstrap tree file
double scale = 100.0;
if (params->scaling_factor > 0)
scale = params->scaling_factor;
MTreeSet boot_trees;
if (params && detectInputFile(input_trees) == IN_NEXUS) {
sg.init(*params);
for (SplitGraph::iterator it = sg.begin(); it != sg.end(); it++)
hash_ss.insertSplit((*it), (*it)->getWeight());
StrVector sgtaxname;
sg.getTaxaName(sgtaxname);
i = 0;
for (StrVector::iterator sit = sgtaxname.begin();
sit != sgtaxname.end(); sit++, i++) {
Node *leaf = mytree.findLeafName(*sit);
if (!leaf)
outError("Tree does not contain taxon ", *sit);
leaf->id = i;
}
scale /= sg.maxWeight();
} else {
myrooted = rooted;
boot_trees.init(input_trees, myrooted, burnin, max_count,
tree_weight_file);
if (mytree.rooted != boot_trees.isRooted())
outError("Target tree and tree set have different rooting");
if (boot_trees.equal_taxon_set) {
boot_trees.convertSplits(taxname, sg, hash_ss, SW_COUNT, -1, params->support_tag);
scale /= boot_trees.sumTreeWeights();
}
}
//sg.report(cout);
if (!sg.empty()) {
cout << "Rescaling split weights by " << scale << endl;
if (params->scaling_factor < 0)
sg.scaleWeight(scale, true);
else {
sg.scaleWeight(scale, false, params->numeric_precision);
}
cout << sg.size() << " splits found" << endl;
}
// compute the percentage of appearance
// printSplitSet(sg, hash_ss);
//sg.report(cout);
cout << "Creating " << RESAMPLE_NAME << " support values..." << endl;
if (!sg.empty())
mytree.createBootstrapSupport(taxname, boot_trees, hash_ss, params->support_tag);
else {
//mytree.createBootstrapSupport(boot_trees);
cout << "Unequal taxon sets, rereading trees..." << endl;
DoubleVector rfdist;
mytree.computeRFDist(input_trees, rfdist, 1);
}
//mytree.scaleLength(100.0/boot_trees.size(), true);
string out_file;
if (output_tree)
out_file = output_tree;
else {
if (out_prefix)
out_file = out_prefix;
else
out_file = target_tree;
out_file += ".suptree";
}
mytree.printTree(out_file.c_str());
cout << "Tree with assigned support written to " << out_file
<< endl;
/*
if (out_prefix)
out_file = out_prefix;
else
out_file = target_tree;
out_file += ".supval";
mytree.writeInternalNodeNames(out_file);
cout << "Support values written to " << out_file << endl;
*/
}
void computeConsensusTree(const char *input_trees, int burnin, int max_count,
double cutoff, double weight_threshold, const char *output_tree,
const char *out_prefix, const char *tree_weight_file, Params *params) {
bool rooted = false;
// read the bootstrap tree file
/*
MTreeSet boot_trees(input_trees, rooted, burnin, tree_weight_file);
string first_taxname = boot_trees.front()->root->name;
//if (params.root) first_taxname = params.root;
SplitGraph sg;
boot_trees.convertSplits(sg, cutoff, SW_COUNT, weight_threshold);*/
//sg.report(cout);
SplitGraph sg;
SplitIntMap hash_ss;
// make the taxa name
//vector<string> taxname;
//taxname.resize(mytree.leafNum);
//mytree.getTaxaName(taxname);
// read the bootstrap tree file
double scale = 100.0;
if (params->scaling_factor > 0)
scale = params->scaling_factor;
MTreeSet boot_trees;
if (params && detectInputFile(input_trees) == IN_NEXUS) {
char *user_file = params->user_file;
params->user_file = (char*) input_trees;
params->split_weight_summary = SW_COUNT; // count number of splits
sg.init(*params);
params->user_file = user_file;
for (SplitGraph::iterator it = sg.begin(); it != sg.end();)
if ((*it)->getWeight() > weight_threshold) {
hash_ss.insertSplit((*it), (*it)->getWeight());
it++;
} else {
// delete the split
if (it != sg.end()-1) {
*(*it) = (*sg.back());
}
delete sg.back();
sg.pop_back();
}
/* StrVector sgtaxname;
sg.getTaxaName(sgtaxname);
i = 0;
for (StrVector::iterator sit = sgtaxname.begin(); sit != sgtaxname.end(); sit++, i++) {
Node *leaf = mytree.findLeafName(*sit);
if (!leaf) outError("Tree does not contain taxon ", *sit);
leaf->id = i;
}*/
scale /= sg.maxWeight();
} else {
boot_trees.init(input_trees, rooted, burnin, max_count,
tree_weight_file);
boot_trees.convertSplits(sg, cutoff, SW_COUNT, weight_threshold);
scale /= boot_trees.sumTreeWeights();
cout << sg.size() << " splits found" << endl;
}
//sg.report(cout);
if (verbose_mode >= VB_MED)
cout << "Rescaling split weights by " << scale << endl;
if (params->scaling_factor < 0)
sg.scaleWeight(scale, true);
else {
sg.scaleWeight(scale, false, params->numeric_precision);
}
//cout << "Creating greedy consensus tree..." << endl;
MTree mytree;
SplitGraph maxsg;
sg.findMaxCompatibleSplits(maxsg);
if (verbose_mode >= VB_MAX)
maxsg.saveFileStarDot(cout);
//cout << "convert compatible split system into tree..." << endl;
mytree.convertToTree(maxsg);
//cout << "done" << endl;
if (!mytree.rooted) {
string taxname;
if (params->root)
taxname = params->root;
else
taxname = sg.getTaxa()->GetTaxonLabel(0);
Node *node = mytree.findLeafName(taxname);
if (node)
mytree.root = node;
}
// mytree.scaleLength(100.0 / boot_trees.sumTreeWeights(), true);
// mytree.getTaxaID(maxsg.getSplitsBlock()->getCycle());
//maxsg.saveFile(cout);
string out_file;
if (output_tree)
out_file = output_tree;
else {
if (out_prefix)
out_file = out_prefix;
else
out_file = input_trees;
out_file += ".contree";
}
// if (removed_seqs.size() > 0)
// mytree.insertTaxa(removed_seqs, twin_seqs);
mytree.printTree(out_file.c_str(), WT_BR_CLADE);
cout << "Consensus tree written to " << out_file << endl;
if (output_tree)
out_file = output_tree;
else {
if (out_prefix)
out_file = out_prefix;
else
out_file = input_trees;
out_file += ".splits";
}
//sg.scaleWeight(0.01, false, 4);
if (params->print_splits_file) {
sg.saveFile(out_file.c_str(), IN_OTHER, true);
cout << "Non-trivial split supports printed to star-dot file " << out_file << endl;
}
}
void computeConsensusNetwork(const char *input_trees, int burnin, int max_count,
double cutoff, int weight_summary, double weight_threshold, const char *output_tree,
const char *out_prefix, const char* tree_weight_file) {
bool rooted = false;
// read the bootstrap tree file
MTreeSet boot_trees(input_trees, rooted, burnin, max_count,
tree_weight_file);
SplitGraph sg;
//SplitIntMap hash_ss;
boot_trees.convertSplits(sg, cutoff, weight_summary, weight_threshold);
string out_file;
if (output_tree)
out_file = output_tree;
else {
if (out_prefix)
out_file = out_prefix;
else
out_file = input_trees;
out_file += ".nex";
}
sg.saveFile(out_file.c_str(), IN_NEXUS);
cout << "Consensus network printed to " << out_file << endl;
if (output_tree)
out_file = output_tree;
else {
if (out_prefix)
out_file = out_prefix;
else
out_file = input_trees;
out_file += ".splits";
}
if (verbose_mode >= VB_MED) {
sg.saveFile(out_file.c_str(), IN_OTHER, true);
cout << "Non-trivial split supports printed to star-dot file " << out_file << endl;
}
}
|