BUSCO.py 133 KB
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
#!/usr/bin/env python
# coding: utf-8
"""
.. module:: BUSCO
   :synopsis: BUSCO - Benchmarking Universal Single-Copy Orthologs.
.. moduleauthor:: Felipe A. Simao <felipe.simao@unige.ch>
.. moduleauthor:: Robert M. Waterhouse <robert.waterhouse@unige.ch>
.. moduleauthor:: Mathieu Seppey <mathieu.seppey@unige.ch>
.. versionadded:: 1.0
.. versionchanged:: 2.0.1

BUSCO - Benchmarking Universal Single-Copy Orthologs.

To get help, ``python BUSCO.py -h``. See also the user guide.

Visit our website `<http://busco.ezlab.org/>`_

Copyright (C) 2016 E. Zdobnov lab

BUSCO is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. See <http://www.gnu.org/licenses/>

BUSCO 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.

"""

import os
import sys
import subprocess
import argparse
from argparse import RawTextHelpFormatter
import time
import threading
import heapq
import logging
import copy
import traceback
import random
from abc import ABCMeta, abstractmethod
from collections import deque
try:
    import queue as Queue
except ImportError:
    import Queue  # Python 2


class BUSCOLogger(logging.getLoggerClass()):
    """
    This class customizes the _logger class
    """
    def __init__(self, name):
        """
        :param name: the name of the BUSCOLogger instance to be created
        :type name: str
        """
        super(BUSCOLogger, self).__init__(name)
        self.setLevel(logging.INFO)
        self._has_warning = False
        self._formatter = logging.Formatter('%(levelname)s\t%(message)s')
        self._thread_formatter = logging.Formatter('%(levelname)s:%(threadName)s\t%(message)s')
        self._formatter_blank_line = logging.Formatter('')
        self._out_hdlr = logging.StreamHandler(sys.stdout)
        self._out_hdlr.setFormatter(self._formatter)
        self._out_hdlr_blank_line = logging.StreamHandler(sys.stdout)
        self._out_hdlr_blank_line.setFormatter(self._formatter_blank_line)
        self.addHandler(self._out_hdlr)

    def add_blank_line(self):
        """
        This function add a blank line in the logs
        """
        self.removeHandler(self._out_hdlr)
        self.addHandler(self._out_hdlr_blank_line)
        self.info('')
        self.removeHandler(self._out_hdlr_blank_line)
        self.addHandler(self._out_hdlr)

    def add_thread_info(self):
        """
        This function appends the thread name to the logs output, e.g. INFO:BUSCO.py:thread_name
        """
        self._out_hdlr.setFormatter(self._thread_formatter)

    def remove_thread_info(self):
        """
        This function disables the thread name in the logs output, e.g. INFO:BUSCO.py
        """
        self._out_hdlr.setFormatter(self._formatter)

    def warn(self, msg, *args, **kwargs):
        """
        This function overrides the _logger class warn
        :param msg: the message to log
        :type msg: str
        """
        self.warning(msg, *args, **kwargs)

    def warning(self, msg, *args, **kwargs):
        """
        This function overrides the _logger class warning
        :param msg: the message to log
        :type msg: str
        """
        self._has_warning = True
        super(BUSCOLogger, self).warning(msg, *args, **kwargs)

    def has_warning(self):
        """
        :return: whether the _logger did log warnings
        :rtype: book
        """
        return self._has_warning

    def info_external_tool(self, tool, msg, *args, **kwargs):
        """
        This function logs an info line mentioning this is an external tool
        :param tool: the name of the tool
        :type tool: str
        :param msg: the message
        :type msg: str
        :return:
        """
        if msg != '':  # do not log blank lines
            self.info('[%s]\t%s' % (tool, msg), *args, **kwargs)


class Analysis(object):
    """
    This class is the parent of all type of analysis that can be done by BUSCO. It has to be extended by a subclass \
    to represent an actual analysis
    """

    class _AugustusThreads(threading.Thread):
        """
        This class extends ``threading.Thread`` to run Augustus in a multi-threaded manner.
        .. seealso:: Analysis._augustus(), Analysis._augustus_rerun(), Analysis._process_augustus_tasks()
        """

        CLASS_ABREV = 'augustus'

        def __init__(self, thread_id, name, analysis):
            """
            :param thread_id: an int id for the thread
            :type thread_id: int
            :param name: a name for the thread
            :type name: str
            :param analysis: the Analysis object that is bound to this thread
            :type analysis: Analysis
            """
            threading.Thread.__init__(self)
            self.thread_id = thread_id
            self.name = name
            self.analysis = analysis

        def run(self):
            """
            This function defines what is run by within the thread
            """
            self.analysis._process_augustus_tasks()

    class _HmmerThreads(threading.Thread):
        """
        This class extends ``threading.Thread`` to run hmmersearch in a multi-threaded manner.
        .. seealso:: Analysis._hmmer(), Analysis._augustus_rerun(), Analysis._process_hmmer_tasks()
        """

        CLASS_ABREV = 'hmmer'

        def __init__(self, thread_id, name, analysis):
            """
            :param thread_id: an int id for the thread
            :type thread_id: int
            :param name: a name for the thread
            :type name: str
            :param analysis: the Analysis object that is bound to this thread
            :type analysis: Analysis
            """
            threading.Thread.__init__(self)
            self.thread_id = thread_id
            self.name = name
            self.analysis = analysis

        def run(self):
            """
            This function defines what is run by within the thread
            """
            self.analysis._process_hmmer_tasks()

    class _Gff2gbSmallDNAThreads(threading.Thread):
        """
        This class extends ``threading.Thread`` to run the gff2gbSmallDNA.pl script in a multi-threaded manner.
        .. seealso:: Analysis._process_gff2gbsmalldna_tasks()
        """

        CLASS_ABREV = 'gff2gbsmalldna'

        def __init__(self, thread_id, name, analysis):
            """
            :param thread_id: an int id for the thread
            :type thread_id: int
            :param name: a name for the thread
            :type name: str
            :param analysis: the Analysis object that is bound to this thread
            :type analysis: Analysis
            """
            threading.Thread.__init__(self)
            self.thread_id = thread_id
            self.name = name
            self.analysis = analysis

        def run(self):
            """
            This function defines what is run by within the thread
            """
            self.analysis._process_gff2gbsmalldna_tasks()

    # declare a metaclass ABCMeta, which means that this class is abstract
    __metaclass__ = ABCMeta

    # Default params
    EVALUE_DEFAULT = 1e-3
    MAX_FLANK = 20000
    REGION_LIMIT_DEFAULT = 3
    CPUS_DEFAULT = 1
    TMP_DEFAULT = './tmp'
    SPECIES_DEFAULT = 'fly'

    # Genetic code for translating nucleotides
    CODONS = {'TTT': 'F', 'TTC': 'F', 'TTY': 'F',
              'TTA': 'L', 'TTG': 'L', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L', 'CTG': 'L', 'CTN': 'L',
              'YTN': 'L', 'TTR': 'L',
              'ATT': 'I', 'ATC': 'I', 'ATA': 'I', 'ATH': 'I',
              'ATG': 'M',
              'GTT': 'V', 'GTC': 'V', 'GTA': 'V', 'GTG': 'V', 'GTN': 'V',
              'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S', 'TCN': 'S',
              'AGT': 'S', 'AGC': 'S', 'WSN': 'S', 'AGY': 'S',
              'CCT': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P', 'CCN': 'P',
              'ACT': 'T', 'ACC': 'T', 'ACA': 'T', 'ACG': 'T', 'ACN': 'T',
              'GCT': 'A', 'GCC': 'A', 'GCA': 'A', 'GCG': 'A', 'GCN': 'A',
              'TAT': 'Y', 'TAC': 'Y', 'TAY': 'Y',
              'TAA': 'X', 'TAG': 'X', 'TGA': 'X', 'TRR': 'X', 'TAR': 'X', 'NNN': 'X',
              'CAT': 'H', 'CAC': 'H', 'CAY': 'H',
              'CAA': 'Q', 'CAG': 'Q', 'CAR': 'Q',
              'AAT': 'N', 'AAC': 'N', 'AAY': 'N',
              'AAA': 'K', 'AAG': 'K', 'AAR': 'K',
              'GAT': 'D', 'GAC': 'D', 'GAY': 'D',
              'GAA': 'E', 'GAG': 'E', 'GAR': 'E',
              'TGT': 'C', 'TGC': 'C', 'TGY': 'C',
              'TGG': 'W',
              'CGT': 'R', 'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'MGN': 'R', 'CGN': 'R', 'AGR': 'R',
              'AGA': 'R', 'AGG': 'R',
              'GGT': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G', 'GGN': 'G'}

    # Complementary nucleotides
    COMP = {'A': 'T', 'T': 'A', 'U': 'A',
            'C': 'G', 'G': 'C',
            'B': 'V', 'V': 'B',
            'D': 'H', 'H': 'D',
            'K': 'M', 'M': 'K',
            'S': 'S', 'W': 'W',
            'R': 'Y', 'Y': 'R',
            'X': 'X', 'N': 'N'}

    @staticmethod
    def cmd_exists(cmd):
        """
        Check if command exists and is accessible from the command-line
        :param cmd: a bash command
        :type cmd: str
        :return: True if the command can be run, False if it is not the case
        :rtype: bool
        """
        return subprocess.call('type %s' % cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0

    @staticmethod
    def p_open(cmd, name, shell=False):
        """
        This function call subprocess.Popen for the provided command and log the results with the provided name
        :param cmd: the command to execute
        :type cmd: list
        :param name: the name to use in the log
        :type name: str
        :param shell: whether to use the shell parameter to Popen. Needed if wildcard charcter used (*?). See on web
        :type shell: bool
        """
        # note, all augustus related commands do not write to the stdout and stderr and therefore get nothing here
        process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=shell)
        process_out = process.stderr.readlines() + process.stdout.readlines()
        for line in process_out:
            _logger.info_external_tool(name, line.decode("utf-8").strip())

    @staticmethod
    def check_fasta_header(header):
        """
        This function checks problematic characters in fasta headers, and warns the user and stops the execution
        :param header: a fasta header to check
        :type header: str
        :raises SystemExit: if a problematic character is found
        """
        for char in FORBIDDEN_HEADER_CHARS:
            if char in header:
                _logger.error('The character \'%s\' is present in the fasta header %s, '
                              'which will crash BUSCO. '
                              'Please clean the header of your input file.' % (char, header.strip()))
                raise SystemExit

        for char in FORBIDDEN_HEADER_CHARS_BEFORE_SPLIT:
            if char in header.split()[0]:
                _logger.error('The character \'%s\' is present in the fasta header %s, '
                              'which will crash BUSCO. '
                              'Please clean the header of your input file.' % (char, header.split()[0].strip()))
                raise SystemExit

        if header.split()[0] == '>':
            _logger.error('A space is present in the fasta header %s, directly after \'>\' '
                          'which will crash BUSCO. '
                          'Please clean the header of your input file.' % (header.strip()))
            raise SystemExit

    @staticmethod
    def _check_blast():
        """
        Check if blast is accessible from command-line (tblastn)
        :raises SystemExit: if blast is not accessible
        """
        if not Analysis.cmd_exists('tblastn'):
            _logger.error('Blast is not accessible from the command-line, please add it to the environment')
            raise SystemExit

    @staticmethod
    def _check_hmmer():
        """
        Check if it is accessible from command-line (as 'hmmsearch')
        Also check if HMMer is the correct version (3.1+)
        :raises SystemExit: if HMMer is not accessible or not the correct version
        """
        if not Analysis.cmd_exists('hmmsearch'):
            _logger.error('HMMer is not accessible from the command-line, please add it to the environment')
            raise SystemExit
        else:
            try:
                hmmer_check = subprocess.check_output('hmmsearch -h', shell=True)
                hmmer_check = hmmer_check.decode('utf-8')
                hmmer_check = hmmer_check.split('\n')[1].split()[2]
                hmmer_check = float(hmmer_check[:3])
            except ValueError:
                # to avoid a crash with super old version and notify the user, will be useful
                hmmer_check = subprocess.check_output('hmmsearch -h', shell=True)
                hmmer_check = hmmer_check.decode('utf-8')
                hmmer_check = hmmer_check.split('\n')[1].split()[1]
                hmmer_check = float(hmmer_check[:3])
            except subprocess.CalledProcessError:
                _logger.error('HMMer is not accessible from the command-line, please add it to the environment')
                raise SystemExit
            if hmmer_check >= 3.1:
                pass
            else:
                _logger.error('HMMer version detected is not supported, please use HMMer 3.1+')
                raise SystemExit

    @staticmethod
    def _split_seq_id(seq_id):
        """
        This function split the provided seq id into id, start and stop
        :param seq_id: the seq id to split
        :type seq_id: str
        :return: a dict containing the id, the start, the end found in seq_id
        :rtype: dict
        """
        # -2,-1 instead of 0,1, if ':' in the fasta header, same for [,]
        name = seq_id.replace(']', '').split('[')[-1].split(':')[-2]
        start = seq_id.replace(']', '').split('[')[-1].split(':')[-1].split('-')[0]
        end = seq_id.replace(']', '').split('[')[-1].split(':')[-1].split('-')[1]
        return {'id': name, 'start': start, 'end': end}

    @staticmethod
    def _reformats_seq_id(seq_id):
        """
        This function reformats the sequence id to its original values, if it was somehow modified during the process
        It has to be overriden by subclasses when needed
        :param seq_id: the seq id to reformats
        :type seq_id: str
        :return: the reformatted seq_id
        :rtype: str
        """
        return seq_id

    def check_dataset(self):
        """
        Check the dataset integrity, if files and folder are present
        :raises SystemExit: if the dataset miss files or folders
        """
        # hmm folder
        flag = False
        for dirpath, dirnames, files in os.walk('%shmms' % self._clade_path):
            if files:
                flag = True
        if not flag:
            _logger.error('The dataset you provided lacks hmm profiles in %shmms' % self._clade_path)
            raise SystemExit
        # note: score and length cutoffs are checked when read, see _load_scores and _load_lengths

    def _check_augustus(self):
        """
        Check if Augustus is accessible from command-line and properly configured.
        :raises SystemExit: if Augustus is not accessible
        :raises SystemExit: if Augustus config path is not writable or not set at all
        :raises SystemExit: if Augustus config path does not contain the needed species
        :raises SystemExit: if additional perl scripts for retraining are not present
        """
        if not Analysis.cmd_exists('augustus'):
            _logger.error('Augustus is not accessible from the command-line, please add it to the environment')
            raise SystemExit

        try:
            if not os.access(self._augustus_config_path, os.W_OK):
                _logger.error('Cannot write to Augustus config path, please make sure you have '
                              'write permissions to %s' % self._augustus_config_path)
                raise SystemExit
        except TypeError:
                _logger.error('The environment variable AUGUSTUS_CONFIG_PATH is not set')
                raise SystemExit

        if not os.path.exists(self._augustus_config_path + '/species/%s' % self._target_species):
            _logger.error('Impossible to locate the species "%s" in Augustus config path (%sspecies), check '
                          'that AUGUSTUS_CONFIG_PATH is properly set and contains this species. '
                          '\n\t\tSee the help if you want to provide an alternative species'
                          % (self._target_species, self._augustus_config_path))
            raise SystemExit
        if not Analysis.cmd_exists('gff2gbSmallDNA.pl'):
            _logger.error('Impossible to locate the required script gff2gbSmallDNA.pl. Check that you declared '
                          'the Augustus scripts folder in your $PATH environmental variable')
            raise SystemExit
        if not Analysis.cmd_exists('new_species.pl'):
            _logger.error('Impossible to locate the required script new_species.pl. Check that you declared '
                          'the Augustus scripts folder in your $PATH environmental variable')
            raise SystemExit
        if self._long and not Analysis.cmd_exists('optimize_augustus.pl'):
            _logger.error('Impossible to locate the required script optimize_augustus.pl. Check that you declared '
                          'the Augustus scripts folder in your $PATH environmental variable')
            raise SystemExit

    def _check_nucleotide(self):
        """
        This function checks that the provided file is nucleotide
        :raises SystemExit: if AA found
        """
        aas = set(Analysis.CODONS.values())
        nucls = Analysis.COMP.keys()
        for nucl in nucls:
            try:
                aas.remove(nucl)
            except KeyError:
                pass
        nucl_file = open(self._sequences)
        n = 0
        for line in nucl_file:
            if n > 10:
                break
            n += 1
            if '>' not in line:
                for aa in aas:
                    if aa.upper() in line or aa.lower() in line:
                        _logger.error('Please provide a nucleotide file as input, it should not contains \'%s or %s\''
                                      % (aa.upper(), aa.lower()))
                        file.close()
                        raise SystemExit
        nucl_file.close()

    def _check_protein(self):
        """
        This function checks that the provided file is protein
        :raises SystemExit: if only ACGTN is found over a reasonable amount of lines
        """
        aas = set(Analysis.CODONS.values())
        aas.remove('A')
        aas.remove('C')
        aas.remove('G')
        aas.remove('T')
        aas.remove('N')
        is_aa = False
        prot_file = open(self._sequences)
        n = 0
        for line in prot_file:
            if n > 100:
                break
            n += 1
            if '>' not in line:
                for aa in aas:
                    if aa.lower() in line or aa.upper() in line:
                        is_aa = True
                        break
        prot_file.close()
        if not is_aa:
            _logger.error('Please provide a protein file as input')
            raise SystemExit

    def _define_checkpoint(self, nb=None):
        """
        This function update the checkpoint file with the provided id or delete it if none is provided
        :param nb: the id of the checkpoint
        :type nb: int
        """
        if nb:
            open('%scheckpoint.tmp' % self.mainout, 'w').write('%s.%s.%s' % (nb, self._mode, self._random))
        else:
            if os.path.exists('%scheckpoint.tmp' % self.mainout):
                os.remove('%scheckpoint.tmp' % self.mainout)

    def _get_checkpoint(self, reset_random_suffix=False):
        """
        This function return the checkpoint if the checkpoint.tmp file exits or None if absent
        :param reset_random_suffix: to tell whether to reset the self._random value with the one found the checkpoint
        :type reset_random_suffix: bool
        :return: the checkpoint name
        :rtype: int
        """
        if os.path.exists('%scheckpoint.tmp' % self.mainout):
            line = open('%scheckpoint.tmp' % self.mainout, 'r').readline()
            if reset_random_suffix:
                _logger.debug('Resetting random suffix to %s' % self._random)
                self._random = line.split('.')[-1]
            return int(int(line.split('.')[0]))
        else:
            return None

    def _extract_missing_and_frag_buscos_ancestral(self, ancestral_variants=False):
        """
        This function extracts from the file ancestral the sequences that match missing or fragmented buscos
        :param ancestral_variants: tell whether to use the ancestral_variants file
        :type ancestral_variants: bool
        """
        if self._has_variants_file:
            _logger.info('Extracting missing and fragmented buscos from the ancestral_variants file...')
        else:
            _logger.info('Extracting missing and fragmented buscos from the ancestral file...')

        if ancestral_variants:
            ancestral = open('%sancestral_variants' % self._clade_path, 'r')
            output = open('%sblast_output/missing_and_frag_ancestral_variants' % self.mainout, 'w')
        else:
            ancestral = open('%sancestral' % self._clade_path, 'r')
            output = open('%sblast_output/missing_and_frag_ancestral' % self.mainout, 'w')

        result = ''

        buscos_to_retrieve = self._missing_busco_list + self._fragmented_busco_list
        buscos_retrieved = []
        add = False
        for line in ancestral:
            if line.startswith('>'):
                if ancestral_variants:
                    line = '_'.join(line.split("_")[:-1])
                    # This pattern can support name like EOG00_1234_1
                busco_id = line.strip().strip('>')
                if busco_id in buscos_to_retrieve:
                    _logger.debug('Found contig %s' % busco_id)
                    add = True
                    buscos_retrieved.append(busco_id)
                else:
                    add = False
            if add:
                if line.endswith('\n'):
                    result += line
                else:
                    result += line + '\n'
        if len(list(set(buscos_to_retrieve) - set(buscos_retrieved))) > 0:
            if self._has_variants_file:
                _logger.warning('The busco id(s) %s were not found in the ancestral_variants file' %
                                list(set(buscos_to_retrieve) - set(buscos_retrieved)))
            else:
                _logger.warning('The busco id(s) %s were not found in the ancestral file' %
                                list(set(buscos_to_retrieve) - set(buscos_retrieved)))

        output.write(result)
        output.close()
        ancestral.close()
        output.close()

    @staticmethod
    def _check_overlap(a, b):
        """
        This function checks whether two regions overlap
        :param a: first region, start and end
        :type a: list
        :param b: second region, start and end
        :type b: list
        :return: the number of overlapping positions
        :rtype: int
        """
        return max(0, min(a[1], b[1]) - max(a[0], b[0]))

    @staticmethod
    def _define_boundary(a, b):
        """
        This function defines the boundary of two overlapping regions
        :param a: first region, start and end
        :type a: list
        :param b: second region, start and end
        :type b: list
        :return: the boundaries, i.e. start and end
        :rtype: collections.deque
        """
        temp_start = a[0]
        temp_end = a[1]
        current_start = b[0]
        current_end = b[1]
        boundary = None
        if temp_start < current_start and temp_end < current_start:
            # i.e. entry is fully before
            # append left, IF entry is the first one; otherwise put into the proper position
            boundary = deque([a, b])
        elif temp_start < current_start <= temp_end <= current_end:
            # i.e. overlap starts before, but ends inside
            boundary = deque([temp_start, current_end])
        elif current_start <= temp_start <= current_end < temp_end:
            # overlap starts inside, but ends outside
            boundary = deque([current_start, temp_end])
        elif temp_start > current_end and temp_end > current_end:
            # i.e. query is fully after
            # append right; otherwise put into the proper position
            boundary = deque([b, a])
        elif current_start <= temp_start <= temp_end <= current_end:
            # i.e. query is fully inside, no further operations needed
            boundary = deque(b)
        elif temp_start == current_start and temp_end == current_end:
            boundary = deque(a)
        elif temp_start <= current_start and temp_end >= current_end:
            # i.e. query is longer and contains all coordinates
            # replace by the query
            boundary = deque(a)
        return boundary

    @staticmethod
    def _gargantua(deck):
        """
        :param deck:
        :type deck: list
        :return:
        :rtype: int
        """
        # todo comment
        total = 0
        for entry in deck:
            total += entry[1] - entry[0]
        return total

    @staticmethod
    def _sixpack(seq):
        """
        Gets the sixframe translation for the provided sequence
        :param seq: the sequence to be translated
        :type seq: str
        :return: the six translated sequences
        :rtype: list
        """
        s1 = seq
        s2 = seq[1:]
        s3 = seq[2:]
        rev = ''
        for letter in seq[::-1]:
            try:
                rev += Analysis.COMP[letter]
            except KeyError:
                rev += Analysis.COMP['N']
        r1 = rev
        r2 = rev[1:]
        r3 = rev[2:]
        transc = []
        frames = [s1, s2, s3, r1, r3, r2]
        for sequence in frames:
            part = ''
            new = ''
            for letter in sequence:
                if len(part) == 3:
                    try:
                        new += Analysis.CODONS[part]
                    except KeyError:
                        new += 'X'
                    part = ''
                    part += letter
                else:
                    part += letter
            if len(part) == 3:
                try:
                    new += Analysis.CODONS[part]
                except KeyError:
                    new += 'X'
            transc.append(new)
        return transc

    @staticmethod
    def _measuring(nested):
        """
        :param nested:
        :type nested:
        :return:
        :rtype:
        """
        # todo comment
        total_len = 0

        if isinstance(nested, str):
            return '0'
        scaffolds = list(nested.keys())
        if len(nested) == 1:
            total_len = [0]
            for hit in nested[scaffolds[0]]:
                total_len[0] += hit[1] - hit[0]
        elif len(nested) > 1:
            total_len = [0] * len(nested)
            for entry in range(0, len(scaffolds)):
                for hit in nested[scaffolds[entry]]:
                    total_len[entry] += hit[1] - hit[0]
        return total_len

    @staticmethod
    def _remove_bad_ratio_genes(original):
        """
        This function removes duplicate positive results if the score is above a 0.85 threshold compared to the top
        scoring match
        :param original: a dict with BUSCO as key, and a dict of matching genes as values
        :type original: dict
        :return: the filtered dict
        :rtype: dict
        """
        ratio = 0.85
        filtered = copy.deepcopy(original)
        for k in original.keys():
            max_score = 0
            for k2 in original[k]:
                if original[k][k2][2] > max_score:
                    max_score = original[k][k2][2]
            for k2 in original[k]:
                if original[k][k2][2] < max_score*ratio:
                    del filtered[k][k2]
                    if len(filtered[k]) == 0:
                        del filtered[k]

        return filtered

    @staticmethod
    def _filter_multi_match_genes(original):
        """
        This function identifies genes that match the same BUSCO, and keeps the one with the best score only
        :param original: a dict with BUSCO as key, and a dict of matching genes as values
        :type original: dict
        :return: the filtered dict
        :rtype: dict
        """
        filtered = copy.deepcopy(original)

        # reorganize the key/value by gene
        gene_dict = {}
        for d in original.values():
            for key in d.keys():
                if key in gene_dict:
                    gene_dict[key].append(d[key])
                else:
                    gene_dict[key] = [d[key]]

        # identify genes belonging to two or more buscos
        # keep the best score
        to_keep = {}
        for key in gene_dict.keys():
            if len(gene_dict[key]) > 1:
                max_score = 0
                busco_to_keep = ""
                for busco in gene_dict[key]:
                    if max_score < busco[2]:
                        max_score = busco[2]
                        busco_to_keep = busco[5][0:11]
                to_keep[key] = busco_to_keep

        # clean the original list
        for k in original.keys():
            for k2 in original[k].keys():
                if k2 in to_keep.keys():
                    if to_keep[k2] != k:
                        del filtered[k][k2]
                        if len(filtered[k]) == 0:
                            del filtered[k]

        return filtered

    @abstractmethod
    def __init__(self, params):
        """
        Initialize an instance, need to be overriden by subclasses
        :param params: Values of all parameters that have to be defined
        :type params: dict
        """
        # todo move child specific variable to its child class, e.g. self._transcriptome_by_scaff
        self._random = "_"+str(random.getrandbits(32))  # to have a unique value for temporary file names
        self._abrev = params['abrev']
        self._tmp = params['tmp']
        self._force = params['force']
        self._restart = params['restart']
        self._sequences = params['sequences']
        self._cpus = params['cpus']
        self._clade_path = params['clade_path']
        self._clade_name = params['clade_name']
        self._domain = params['domain']
        self._ev_cutoff = params['ev_cutoff']
        self._region_limit = params['region_limit']
        self._flank = params['flank']
        self._long = params['long']
        self._target_species = params['target_species']
        self._augustus_parameters = params['augustus_parameters']
        self._augustus_config_path = params['augustus_config_path']
        self._tarzip = params['tarzip']
        self._dataset_creation_date = params['dataset_creation_date']
        self._dataset_nb_species = params['dataset_nb_species']
        self._dataset_nb_buscos = params['dataset_nb_buscos']
        self.mainout = None
        self._totalbuscos = 0
        self._total = 0
        self._cutoff_dictionary = {}
        self._thread_list = None
        self._no_prediction = None
        self._exit_flag = None
        self._queue_lock = None
        self._work_queue = None
        self._missing_busco_list = []
        self._fragmented_busco_list = []
        self._location_dic = {}
        self._single_copy_files = None
        self._transcriptome_by_scaff = {}
        self._mode = None
        self._has_variants_file = False
        self._contig_length = {}

    def cleanup(self):
        """
        This function cleans temporary files. \
        It has to be overriden by subclasses when needed
        """
        Analysis.p_open(['rm', '%stemp_%s%s' % (self._tmp, self._abrev, self._random)], 'bash', shell=False)
        if self._tarzip:
            self._run_tarzip()

    def _run_tarzip(self):
        """
        This function tarzips results folder
        It has to be overriden by subclasses when needed
        """
        Analysis.p_open(['tar', '-C', '%s' % self.mainout, '-zcf',
                         '%shmmer_output.tar.gz' % self.mainout, 'hmmer_output',
                         '--remove-files'],
                        'bash', shell=False)

    def _get_coordinates(self):
        """
        This function gets coordinates for candidate regions from tblastn result file. \
        It has to be overriden by subclasses when needed
        """
        pass

    def _extract_scaffolds(self, missing_and_frag_only=False):
        """
        This function extract the scaffold having blast results
        :param missing_and_frag_only: to tell which coordinate file to look for, complete or just missing and fragment
        :type missing_and_frag_only: bool
        """
        _logger.info('Pre-Augustus scaffold extraction...')
        if missing_and_frag_only:
            coord = open('%s/blast_output/coordinates_%s_missing_and_frag_rerun.tsv' % (self.mainout, self._abrev))
        else:
            coord = open('%s/blast_output/coordinates_%s.tsv' % (self.mainout, self._abrev))
        dic = {}
        scaff_list = []
        for i in coord:
            i = i.strip().split()
            if len(i) != 2:
                dic[i[0]] = [i[1], i[2], i[3]]
                if i[1] not in scaff_list:
                    scaff_list.append(i[1])
        coord.close()
        f = open(self._sequences)
        check = 0
        out = None
        contig_len = 0
        contig_id = None
        for i in f:
            if i.startswith('>'):
                i = i.split()
                i = i[0][1:]
                if i in scaff_list:
                    out = open('%s%s%s%s_.temp' % (self._tmp, i, self._abrev, self._random), 'w')
                    out.write('>%s\n' % i)
                    check = 1
                    contig_id = i
                else:
                    check = 0
            elif check == 1:
                out.write(i)
                if i != '\n':
                    contig_len += len(i)
        f.close()
        if out:
            out.close()
            # Keep track of the contig max lenght
            #  Not used yet but might be useful
            self._contig_length.update({contig_id: contig_len})

    @abstractmethod
    def _hmmer(self):
        """
        This function runs hmmsearch. It has to be overriden by subclasses
        """
        pass

    def _write_output_header(self, out):
        """
        This function adds a header to the provided file
        :param out: a file to which the header will be added
        :type out: file
        """
        out.write('# BUSCO version is: %s \n# The lineage dataset is: %s (Creation date: %s,'
                  ' number of species: %s, number of BUSCOs: %s)\n'
                  % (VERSION, self._clade_name, self._dataset_creation_date, self._dataset_nb_species,
                     self._dataset_nb_buscos))
        out.write('# To reproduce this run: %s\n#\n' % _rerun_cmd)

    @staticmethod
    def _write_full_table_header(out):
        """
        This function adds a header line to the full table file
        :param out: a full table file
        :type out: file
        """
        out.write('# Busco id\tStatus\tSequence\tScore\tLength\n')

    def _blast(self, missing_and_frag_only=False, ancestral_variants=False):
        """
        This function runs tblastn
        :param missing_and_frag_only: to tell whether to blast only missing and fragmented buscos
        :type missing_and_frag_only: bool
        :param ancestral_variants: to tell whether to use the ancestral_variants file
        :type ancestral_variants: bool
        """
        if ancestral_variants:
            ancestral_suffix = '_variants'
        else:
            ancestral_suffix = ''

        if missing_and_frag_only:
            self._extract_missing_and_frag_buscos_ancestral(ancestral_variants)
            output_suffix = '_missing_and_frag_rerun'
            query_file = '%sblast_output/missing_and_frag_ancestral%s' % (self.mainout, ancestral_suffix)
        else:
            output_suffix = ''
            query_file = '%sancestral%s' % (self._clade_path, ancestral_suffix)

        if not missing_and_frag_only:
            _logger.info('Create blast database...')
            Analysis.p_open(['makeblastdb', '-in', self._sequences, '-dbtype', 'nucl', '-out',
                                            '%s%s%s' % (self._tmp, self._abrev, self._random)], 'makeblastdb',
                            shell=False)
            if not os.path.exists('%sblast_output' % self.mainout):
                Analysis.p_open(['mkdir', '%sblast_output' % self.mainout], 'bash', shell=False)
        _logger.info('Running tblastn, writing output to %sblast_output/tblastn_%s%s.tsv...'
                     % (self.mainout, self._abrev, output_suffix))

        Analysis.p_open(['tblastn', '-evalue', str(self._ev_cutoff), '-num_threads', str(self._cpus),
                         '-query', query_file,
                         '-db', '%s%s%s' % (self._tmp, self._abrev, self._random),
                         '-out', '%sblast_output/tblastn_%s%s.tsv'
                         % (self.mainout, self._abrev, output_suffix), '-outfmt', '7'], 'tblastn',
                        shell=False)
        # check that blast worked
        if not os.path.exists('%sblast_output/tblastn_%s%s.tsv' % (self.mainout, self._abrev, output_suffix)):
            _logger.error('tblastn failed !')
            raise SystemExit
        # check that the file is not truncated
        try:
            if "processed" not in open('%sblast_output/tblastn_%s%s.tsv' % (self.mainout, self._abrev, output_suffix),
                                       'r').readlines()[-1]:
                _logger.error('tblastn has ended prematurely (the result file lacks the expected final line), '
                              'which will produce incomplete results in the next steps ! '
                              'This problem likely appeared in blast+ 2.4 and seems not fully fixed in 2.6. '
                              'It happens only when using multiple cores. You can use a single core (-c 1) or '
                              'downgrade to blast+ 2.2.x, a safe choice regarding this issue. '
                              'See blast+ documentation for more information.')
                raise SystemExit
        except IndexError:
                pass  # if the tblastn result file is empty, for example in phase 2 if 100% was found in phase 1

    def _run_threads(self, command_strings, thread_class, display_percents=True):
        """
        This class creates and run threads of the provided type for each provided command
        :param command_strings: the list of commands to be run in the threads
        :type command_strings: list
        :param thread_class: the type of thread class to create
        :type thread_class: type Analysis.threads
        :param display_percents: to tell whether to display a log for 0% and 100% complete
        :type display_percents: bool
        """
        self.slate = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
        if len(command_strings) < 11:
            self.slate = [100, 50]  # to avoid false progress display if not enough entries
        self._exit_flag = 0
        # Create X number of threads
        self._thread_list = []
        self._total = len(command_strings)
        mark = 0
        for i in range(int(self._cpus)):
            mark += 1
            self._thread_list.append("%s-%s-%s" % (thread_class.CLASS_ABREV, self._abrev, str(i + 1)))
            if mark >= self._total:
                break
        self._queue_lock = threading.Lock()
        self._work_queue = Queue.Queue(len(command_strings))
        threads = []
        thread_id = 1

        # Generate the new threads
        for t_name in self._thread_list:
            thread = thread_class(thread_id, t_name, self)
            thread.start()
            threads.append(thread)
            thread_id += 1

        if display_percents:
            _logger.info('%s =>\t0%% of predictions performed (%i to be done)'
                         % (time.strftime("%m/%d/%Y %H:%M:%S"), self._total))

        # Fill the queue with the commands
        self._queue_lock.acquire()
        for word in command_strings:
            self._work_queue.put(word)
        self._queue_lock.release()

        # Wait for all jobs to finish (i.e. queue being empty)
        while not self._work_queue.empty():
            time.sleep(0.01)
            pass
        # Send exit signal
        self._exit_flag = 1

        # Wait for all threads to finish
        for t in threads:
            t.join()

        if display_percents:
            _logger.info('%s =>\t100%% of predictions performed' % time.strftime("%m/%d/%Y %H:%M:%S"))

    def _augustus(self):
        """
        This function runs Augustus
        """
        # Run Augustus on all candidate regions
        # 1- Get the temporary sequence files (no multi-fasta support in Augustus)
        # 2- Build a list with the running commands (for threading)
        # 3- Launch Augustus in paralell using Threading
        # 4- Prepare the sequence files to be analysed with HMMer 3.1

        # Extract candidate contigs/scaffolds from genome assembly
        # Augustus can't handle multi-fasta files, each sequence has to be present in its own file
        # Write the temporary sequence files

        # First, delete the augustus result folder, in case we are in the restart mode at this point
        Analysis.p_open(['rm -rf %saugustus_output/*' % self.mainout], 'bash', shell=True)

        # get all scaffolds with blast results
        self._extract_scaffolds()

        # Now run Augustus on each candidate region with its respective Block-profile

        _logger.info('Running Augustus prediction using %s as species:' % self._target_species)

        if self._augustus_parameters:
            _logger.info('Additional parameters for Augustus are %s: ' % self._augustus_parameters)

        augustus_log = '%saugustus_output/augustus.log' % self.mainout
        _logger.info('[augustus] Please find all logs related to Augustus here: %s' % augustus_log)
        if not os.path.exists('%saugustus_output/predicted_genes' % self.mainout):
            Analysis.p_open(['mkdir', '-p', '%saugustus_output/predicted_genes' % self.mainout], 'bash', shell=False)

        # coordinates of hits by BUSCO
        self._location_dic = {}
        f = open('%s/blast_output/coordinates_%s.tsv' % (self.mainout, self._abrev))
        for line in f:
            line = line.strip().split('\t')
            scaff_id = line[1]
            scaff_start = line[2]
            scaff_end = line[3]
            group_name = line[0]

            if group_name not in self._location_dic:
                self._location_dic[group_name] = [[scaff_id, scaff_start, scaff_end]]  # scaffold,start and end
            elif group_name in self._location_dic:
                self._location_dic[group_name].append([scaff_id, scaff_start, scaff_end])
        f.close()
        # Make a list containing the commands to be executed in parallel with threading.
        augustus_first_run_strings = []

        for entry in self._location_dic:

            for location in self._location_dic[entry]:
                scaff = location[0] + self._abrev + str(self._random) + '_.temp'
                scaff_start = location[1]
                scaff_end = location[2]
                output_index = self._location_dic[entry].index(location) + 1

                out_name = '%saugustus_output/predicted_genes/%s.out.%s' % (self.mainout, entry, output_index)

                augustus_call = 'augustus --codingseq=1 --proteinprofile=%(clade)sprfl/%(busco_group)s.prfl ' \
                                '--predictionStart=%(start_coord)s --predictionEnd=%(end_coord)s ' \
                                '--species=%(species)s %(augustus_parameters)s \'%(tmp)s%(scaffold)s\' > %(output)s ' \
                                '2>> %(augustus_log)s' % \
                                {'clade': self._clade_path, 'species': self._target_species,
                                 'augustus_parameters': self._augustus_parameters,
                                 'busco_group': entry, 'start_coord': scaff_start, 'end_coord': scaff_end,
                                 'tmp': self._tmp, 'scaffold': scaff, 'output': out_name, 'augustus_log': augustus_log}
                augustus_first_run_strings.append(augustus_call)  # list of call strings

        self._run_threads(augustus_first_run_strings, self._AugustusThreads)

        # Preparation of sequences for use with HMMer

        # Parse Augustus output files ('run_XXXX/augustus') and extract protein sequences
        # to a FASTA file ('run_XXXX/augustus_output/extracted_proteins').
        _logger.info('Extracting predicted proteins...')
        files = os.listdir('%saugustus_output/predicted_genes' % self.mainout)
        files.sort()
        for entry in files:
            Analysis.p_open(['sed -i.bak \'1,3d\' %saugustus_output/predicted_genes/%s;'
                             'rm %saugustus_output/predicted_genes/%s.bak'
                            % (self.mainout, entry, self.mainout, entry)], 'bash', shell=True)
        if not os.path.exists(self.mainout + 'augustus_output/extracted_proteins'):
            Analysis.p_open(['mkdir', '%saugustus_output/extracted_proteins' % self.mainout], 'bash', shell=False)

        self._no_predictions = []
        for entry in files:
            self._extract(self.mainout, entry)
            self._extract(self.mainout, entry, aa=False)

        Analysis.p_open(['find %saugustus_output/extracted_proteins -size 0 -delete' % self.mainout], 'bash',
                        shell=True)

    def _augustus_rerun(self):
        """
        This function runs Augustus and hmmersearch for the second time
        """
        # todo: augustus and augustus rerun should use the same code when possible, and hmmer should not be here

        augustus_log = '%saugustus_output/augustus.log' % self.mainout

        if not os.path.exists('%saugustus_output/gffs' % self.mainout):
            Analysis.p_open(['mkdir', '%saugustus_output/gffs' % self.mainout], 'bash', shell=False)
        if not os.path.exists('%saugustus_output/gb' % self.mainout):
            Analysis.p_open(['mkdir', '%saugustus_output/gb' % self.mainout], 'bash', shell=False)

        _logger.info('Training Augustus using Single-Copy Complete BUSCOs:')
        _logger.info('%s =>\tConverting predicted genes to short genbank files...'
                     % time.strftime("%m/%d/%Y %H:%M:%S"))

        gff2gbsmalldna_strings = []

        for entry in self._single_copy_files:
            check = 0
            file_name = self._single_copy_files[entry].split('-')[-1]
            target_seq_name = self._single_copy_files[entry].split('[')[0]
            group_name = file_name.split('.')[0]

            # create GFFs with only the "single-copy" BUSCO sequences
            pred_file = open('%saugustus_output/predicted_genes/%s' % (self.mainout, file_name))
            gff_file = open('%saugustus_output/gffs/%s.gff' % (self.mainout, group_name), 'w')
            for line in pred_file:
                if line.startswith('# start gene'):
                    pred_name = line.strip().split()[-1]
                    if pred_name == target_seq_name:
                        check = 1
                elif line.startswith('#'):
                    check = 0
                elif check == 1:
                    gff_file.write(line)
            pred_file.close()
            gff_file.close()

            gff2gbsmalldna_call = ('gff2gbSmallDNA.pl %saugustus_output/gffs/%s.gff %s \
                1000 %saugustus_output/gb/%s.raw.gb 1>>%s 2>&1' %
                                   (self.mainout, entry, self._sequences, self.mainout, entry, augustus_log))

            gff2gbsmalldna_strings.append(gff2gbsmalldna_call)  # list of call strings

        self._run_threads(gff2gbsmalldna_strings, self._Gff2gbSmallDNAThreads, display_percents=False)
        _logger.info('%s =>\tAll files converted to short genbank files, now running the training scripts...'
                     % time.strftime("%m/%d/%Y %H:%M:%S"))

        # bacteria clade needs to be flagged as "prokaryotic"
        if self._domain == 'prokaryota':
            Analysis.p_open(['new_species.pl --prokaryotic --species=BUSCO_%s%s 1>>%s \
                2>&1' %
                            (self._abrev, self._random, augustus_log)], 'new_species.pl',
                            shell=True)  # create new species config file from template
        else:
            Analysis.p_open(['new_species.pl --species=BUSCO_%s%s  1>>%s'
                            ' 2>&1'
                             % (self._abrev, self._random, augustus_log)], 'new_species.pl', shell=True)

        Analysis.p_open(
            ['find %saugustus_output/gb/ -type f -name "*.gb" -exec cat {} \; > %saugustus_output/training_set_%s.txt'
             % (self.mainout, self.mainout, self._abrev)],
            'bash',
            shell=True)
        
        # train on new training set (complete single copy buscos)
        Analysis.p_open(['etraining --species=BUSCO_%s%s %saugustus_output/training_set_%s.txt 1>>%s 2>&1' %
                        (self._abrev, self._random, self.mainout, self._abrev, augustus_log)], 'augustus etraining',
                        shell=True)
        # long mode (--long) option - runs all the Augustus optimization scripts (adds ~1 day of runtime)
        if self._long:
            _logger.warning('%s => Optimizing augustus metaparameters, this may take a very long time...'
                            % time.strftime("%m/%d/%Y %H:%M:%S"))
            Analysis.p_open(['optimize_augustus.pl --cpus=%s --species=BUSCO_%s%s %saugustus_output/training_set_%s.txt \
                1>>%s 2>&1' %
                            (self._cpus, self._abrev, self._random, self.mainout, self._abrev,
                             augustus_log)], 'optimize_augustus.pl',
                            shell=True)
            Analysis.p_open(['etraining --species=BUSCO_%s%s %saugustus_output/training_set_%s.txt 1>>%s 2>&1' %
                            (self._abrev, self._random, self.mainout, self._abrev, augustus_log)], 'augustus etraining',
                            shell=True)

        #######################################################

        # get all scaffolds with blast results
        self._extract_scaffolds(missing_and_frag_only=True)

        _logger.info('Re-running Augustus with the new metaparameters, '
                     'number of target BUSCOs: %s' % len(self._missing_busco_list + self._fragmented_busco_list))

        augustus_rerun_strings = []
        augustus_rerun_seds = []
        hmmer_rerun_strings = []

        # Move first run and create a folder for the rerun
        Analysis.p_open(['mv', '%saugustus_output/predicted_genes'
                         % self.mainout, '%saugustus_output/predicted_genes_run1'
                         % self.mainout], 'bash', shell=False)
        Analysis.p_open(['mkdir', '%saugustus_output/predicted_genes' % self.mainout], 'bash', shell=False)

        Analysis.p_open(['mv', '%shmmer_output/' % self.mainout, '%shmmer_output_run1/' % self.mainout], 'bash',
                        shell=False)
        Analysis.p_open(['mkdir', '%shmmer_output/' % self.mainout], 'bash', shell=False)

        # Update the location dict with the new blast search
        # coordinates of hits by BUSCO
        self._location_dic = {}
        f = open('%s/blast_output/coordinates_%s_missing_and_frag_rerun.tsv' % (self.mainout, self._abrev))
        for line in f:
            line = line.strip().split('\t')
            scaff_id = line[1]
            scaff_start = line[2]
            scaff_end = line[3]
            group_name = line[0]

            if group_name not in self._location_dic:
                self._location_dic[group_name] = [[scaff_id, scaff_start, scaff_end]]  # scaffold,start and end
            elif group_name in self._location_dic:
                self._location_dic[group_name].append([scaff_id, scaff_start, scaff_end])
        f.close()

        for entry in self._missing_busco_list + self._fragmented_busco_list:
            if entry in self._location_dic:
                for location in self._location_dic[entry]:
                    scaff = location[0] + self._abrev + str(self._random) + '_.temp'
                    scaff_start = location[1]
                    scaff_end = location[2]
                    output_index = self._location_dic[entry].index(location) + 1

                    out_name = '%saugustus_output/predicted_genes/%s.out.%s' % (self.mainout, entry, output_index)

                    augustus_call = 'augustus --codingseq=1 --proteinprofile=%(clade)sprfl/%(busco_group)s.prfl \
                        --predictionStart=%(start_coord)s --predictionEnd=%(end_coord)s --species=BUSCO_%(species)s \
                        \'%(tmp)s%(scaffold)s\' > %(output)s 2>> %(augustus_log)s' % \
                                    {'clade': self._clade_path, 'species': self._abrev + str(self._random),
                                     'busco_group': entry,
                                     'start_coord': scaff_start, 'augustus_log': augustus_log, 'tmp': self._tmp,
                                     'end_coord': scaff_end, 'scaffold': scaff, 'output': out_name}
                    augustus_rerun_strings.append(augustus_call)  # list of call strings

                    sed_call = 'sed -i.bak \'1,3d\' %s;rm %s.bak' % (out_name, out_name)
                    augustus_rerun_seds.append(sed_call)

                    out_name = '%shmmer_output/%s.out.%s' % (self.mainout, entry, output_index)
                    augustus_fasta = '%saugustus_output/extracted_proteins/%s.faa.%s'\
                                     % (self.mainout, entry, output_index)

                    hmmer_call = ['hmmsearch',
                                  '--domtblout', '%s' % out_name,
                                  '-o', '%stemp_%s%s' % (self._tmp, self._abrev, self._random),
                                  '--cpu', '1',
                                  '%shmms/%s.hmm' % (self._clade_path, entry),
                                  '%s' % augustus_fasta]

                    hmmer_rerun_strings.append(hmmer_call)

            else:
                pass

        self._run_threads(augustus_rerun_strings, self._AugustusThreads)

        for sed_string in augustus_rerun_seds:
            Analysis.p_open(['%s' % sed_string], 'bash', shell=True)
        # Extract fasta files from augustus output
        _logger.info('Extracting predicted proteins...')
        self._no_predictions = []
        for entry in self._missing_busco_list + self._fragmented_busco_list:
            if entry in self._location_dic:
                for location in self._location_dic[entry]:
                    output_index = self._location_dic[entry].index(location) + 1
                    # when extract gets reworked to not need MAINOUT, change to OUT_NAME
                    plain_name = '%s.out.%s' % (entry, output_index)
                    self._extract(self.mainout, plain_name)
                    self._extract(self.mainout, plain_name, aa=False)
            else:
                pass

        # Run hmmer
        hmmer_rerun_strings_filtered = []

        # filter out the line that have to augustus prediction
        for word in hmmer_rerun_strings:
            target_seq = word[-1].split('/')[-1]
            if target_seq not in self._no_predictions:
                hmmer_rerun_strings_filtered.append(word)

        _logger.info('****** Step 3/3, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
        _logger.info('Running HMMER to confirm orthology of predicted proteins:')

        self._run_threads(hmmer_rerun_strings_filtered, self._HmmerThreads)

        # Fuse the run1 and rerun folders
        Analysis.p_open(['mv %saugustus_output/predicted_genes/*.* %saugustus_output/predicted_genes_run1/ 2> /dev/null'
                        % (self.mainout, self.mainout)], 'bash', shell=True)
        Analysis.p_open(['mv %shmmer_output/*.* %shmmer_output_run1/ 2> /dev/null'
                        % (self.mainout, self.mainout)], 'bash', shell=True)
        Analysis.p_open(['rm', '-r', '%saugustus_output/predicted_genes' % self.mainout], 'bash', shell=False)
        Analysis.p_open(['rm', '-r', '%shmmer_output' % self.mainout], 'bash', shell=False)
        Analysis.p_open(['mv', '%saugustus_output/predicted_genes_run1' % self.mainout,
                         '%saugustus_output/predicted_genes' % self.mainout], 'bash', shell=False)
        Analysis.p_open(['mv', '%shmmer_output_run1' % self.mainout, '%shmmer_output' % self.mainout], 'bash',
                        shell=False)

        # Compute the final results
        self._produce_short_summary()

        if len(self._missing_busco_list) == self._totalbuscos:
            _logger.add_blank_line()
            _logger.warning('BUSCO did not find any match. Do not forget to check the file %s '
                            'to exclude a problem regarding Augustus'
                            % augustus_log)
        # get single-copy files as fasta
        if not os.path.exists('%ssingle_copy_busco_sequences' % self.mainout):
            Analysis.p_open(['mkdir', '%ssingle_copy_busco_sequences' % self.mainout], 'bash', shell=False)

        _logger.debug('Getting single-copy files...')
        for entry in self._single_copy_files:
            check = 0

            file_name = self._single_copy_files[entry].split('-')[-1].replace('out', 'faa')
            file_name_nucl = self._single_copy_files[entry].split('-')[-1].replace('out', 'fna')
            target_seq_name = self._single_copy_files[entry].split('[')[0]
            group_name = file_name.split('.')[0]
            seq_coord_start = self._single_copy_files[entry].split(']-')[0].split('[')[1]

            pred_fasta_file = open('%saugustus_output/extracted_proteins/%s' % (self.mainout, file_name))
            single_copy_outfile = open('%ssingle_copy_busco_sequences/%s.faa' % (self.mainout, group_name), 'w')

            pred_fasta_file_nucl = open('%saugustus_output/extracted_proteins/%s' % (self.mainout, file_name_nucl))
            single_copy_outfile_nucl = open('%ssingle_copy_busco_sequences/%s.fna' % (self.mainout, group_name), 'w')

            for line in pred_fasta_file:
                if line.startswith('>%s' % target_seq_name):
                    single_copy_outfile.write('>%s:%s:%s\n' % (group_name, self._sequences, seq_coord_start))
                    check = 1
                elif line.startswith('>'):
                    check = 0
                elif check == 1:
                    single_copy_outfile.write(line)

            for line in pred_fasta_file_nucl:
                if line.startswith('>%s' % target_seq_name):
                    single_copy_outfile_nucl.write('>%s:%s:%s\n' % (group_name, self._sequences, seq_coord_start))
                    check = 1
                elif line.startswith('>'):
                    check = 0
                elif check == 1:
                    single_copy_outfile_nucl.write(line)

            pred_fasta_file.close()
            single_copy_outfile.close()
            pred_fasta_file_nucl.close()
            single_copy_outfile_nucl.close()

    def _extract(self, path, group, aa=True):
        """
        This function extracts fasta files from augustus output
        :param path: the path to the BUSCO run folder
        :type path: str
        :param group: the BUSCO group id
        :type group: str
        :param aa: to tell whether to extract amino acid instead of nucleotide sequence
        :type aa: bool
        """
        ext = 'fna'
        start_str = '# coding sequence'
        end_str = '# protein'
        if aa:
            ext = 'faa'
            start_str = '# protein'
            end_str = '# end'

        count = 0
        group_name = group.split('.')[0]
        try:
            group_index = int(group.split('.')[-1])
        except IndexError:
            group_index = '1'
            group += '.out.1'
        group_index = str(group_index)

        f = open('%saugustus_output/predicted_genes/%s' % (path, group))
        written_check = 0
        check = 0
        while True:
            line = f.readline()
            if not line:
                break
            if line.startswith('# start gene'):
                line = f.readline()
                line = line.split()
                places = [line[0], line[3], line[4]]
            elif line.startswith(start_str):
                line = line.strip().split('[')
                count += 1
                if written_check == 0:
                    out = open('%saugustus_output/extracted_proteins/%s.%s.%s'
                               % (path, group_name, ext, group_index), 'w')
                    written_check = 1
                out.write('>g%s[%s:%s-%s]\n' % (count, places[0], places[1], places[2]))
                if line[1][-1] == ']':
                    line[1] = line[1][:-1]
                out.write(line[1])
                check = 1
            else:
                if line.startswith('# sequence of block'):
                    check = 0
                elif line.startswith(end_str):
                    check = 0
                    out.write('\n')
                elif check == 1:
                    line = line.split()[1]
                    if line[-1] == ']':
                        line = line[:-1]
                    out.write(line)
        f.close()
        if written_check == 1:
            out.close()
        else:
            self._no_predictions.append('%s.faa.%s' % (group_name, group_index))

    def _parse_hmmer(self, hmmer_results_files):
        """
        This function parses the hmmsearch output files and produces the full_table output file
        :param hmmer_results_files: the list of all output files
        :type hmmer_results_files: list
        """
        # todo: replace self._mode ==... by a proper parent-child behavior that overrides code when needed

        env = []
        everything = {}  # all info from hit_dic + lengths

        for file_name in hmmer_results_files:

            f = open('%shmmer_output/%s' % (self.mainout, file_name))

            hit_dic = {}
            bit_score_list = []
            busco_query = None

            for line in f:
                if line.startswith('#'):
                    pass
                else:
                    line = line.strip().split()

                    if self._mode == 'genome':
                        prot_id = line[0] + '-' + file_name
                    else:
                        prot_id = line[0]
                    busco_query = line[3]

                    bit_score = float(line[7])
                    bit_score_list.append(bit_score)
                    hmm_start = int(line[15])
                    hmm_end = int(line[16])

                    # new protein that passes score cutoff
                    if bit_score >= self._cutoff_dictionary[busco_query]['score']:
                        if prot_id not in hit_dic.keys():
                            hit_dic[prot_id] = [[hmm_start, hmm_end, bit_score]]
                        else:
                            hit_dic[prot_id].append([hmm_start, hmm_end, bit_score])
            f.close()

            length = Analysis._measuring(hit_dic)

            length_count = 0

            if busco_query:
                if busco_query not in everything:
                    everything[busco_query] = hit_dic
                else:
                    for part in hit_dic:
                        everything[busco_query][part] = hit_dic[part]

                for hit in hit_dic:
                    everything[busco_query][hit][0].append(length[length_count])
                    length_count += 1
                # classify genes using sigmas
                for entry in everything[busco_query]:
                    size = everything[busco_query][entry][0][3]
                    sigma = (self._cutoff_dictionary[busco_query]['length'] -
                             size) / self._cutoff_dictionary[busco_query]['sigma']
                    everything[busco_query][entry][0].append(sigma)
                    everything[busco_query][entry][0].append(file_name)

        # REFINE CLASSIFICATION

        # separate complete into multi and single-copy, and keep gene over 2 sigma in a separate dict
        is_complete = {}
        is_fragment = {}
        is_very_large = {}

        for thing in everything:
            for sequence in everything[thing]:

                all_data = everything[thing][sequence][0]
                sigma = everything[thing][sequence][0][-2]
                seq_name = sequence
                if -2 <= sigma <= 2:
                    if thing not in is_complete:
                        is_complete[thing] = {}
                    is_complete[thing][seq_name] = all_data
                elif sigma > 2:
                    if thing not in is_fragment:
                        is_fragment[thing] = {}
                    is_fragment[thing][seq_name] = all_data
                else:
                    if thing not in is_very_large:
                        is_very_large[thing] = {}
                    is_very_large[thing][seq_name] = all_data

        the_sc = {}
        the_mc = {}
        the_fg = {}

        sc_count = 0
        mc_count = 0
        fg_count = 0

        has_complete_match = []

        # filter gene matching two BUSCOs
        is_complete = Analysis._filter_multi_match_genes(is_complete)
        is_very_large = Analysis._filter_multi_match_genes(is_very_large)
        # filter duplicated gene that have a bad ratio compared to the top scoring match
        is_complete = Analysis._remove_bad_ratio_genes(is_complete)
        is_very_large = Analysis._remove_bad_ratio_genes(is_very_large)

        for entity in is_complete:
            # single copy
            if len(is_complete[entity]) == 1:  # e.g. BUSCOaEOG7QCM97
                the_sc[entity] = is_complete[entity]
                sc_count += 1
                has_complete_match.append(entity)
            elif len(is_complete[entity]) >= 2:
                the_mc[entity] = is_complete[entity]
                mc_count += 1
                has_complete_match.append(entity)

        # consider the very large genes as true findings only if there is no BUSCO < 2 sigma already found.
        for entity in is_very_large:
            if entity not in the_sc and entity not in the_mc:
                if len(is_very_large[entity]) >= 2:
                    the_mc[entity] = is_very_large[entity]
                else:
                    the_sc[entity] = is_very_large[entity]
                has_complete_match.append(entity)

        for entity in is_fragment:
            if entity not in has_complete_match:
                best_fragment_key = list(is_fragment[entity].keys())[0]
                for fragment_key in list(is_fragment[entity].keys()):
                    if is_fragment[entity][fragment_key][2] > is_fragment[entity][best_fragment_key][2]:  # best score
                        best_fragment_key = fragment_key
                fg_count += 1
                the_fg[entity] = {best_fragment_key: is_fragment[entity][best_fragment_key]}

        sc_count = len(the_sc)
        mc_count = len(the_mc)

        env.append(sc_count)
        env.append(mc_count)
        env.append(fg_count)

        out = open('%sfull_table_%s.tsv' % (self.mainout, self._abrev), 'w')
        self._write_output_header(out)
        self._write_full_table_header(out)
        out_lines = []

        not_missing = []
        fragmented = []
        csc = {}

        for entity in the_sc:

            for seq_id in the_sc[entity]:
                bit_score = the_sc[entity][seq_id][2]
                seq_len = the_sc[entity][seq_id][3]

                not_missing.append(entity)

                if self._mode == 'proteins' or self._mode == 'tran':
                    out_lines.append('%s\tComplete\t%s\t%s\t%s\n' % (entity, self._reformats_seq_id(seq_id),
                                                                     bit_score, seq_len))
                elif self._mode == 'genome':
                    scaff = self._split_seq_id(seq_id)
                    out_lines.append(
                        '%s\tComplete\t%s\t%s\t%s\t%s\t%s\n' %
                        (entity, self._reformats_seq_id(scaff['id']), scaff['start'], scaff['end'], bit_score, seq_len))
                    csc[entity] = seq_id

        for entity in the_mc:
            for seq_id in the_mc[entity]:
                bit_score = the_mc[entity][seq_id][2]
                seq_len = the_mc[entity][seq_id][3]

                not_missing.append(entity)

                if self._mode == 'proteins' or self._mode == 'tran':
                    out_lines.append('%s\tDuplicated\t%s\t%s\t%s\n' % (entity, self._reformats_seq_id(seq_id),
                                                                       bit_score, seq_len))
                elif self._mode == 'genome':
                    scaff = self._split_seq_id(seq_id)
                    out_lines.append(
                        '%s\tDuplicated\t%s\t%s\t%s\t%s\t%s\n' % (entity, self._reformats_seq_id(scaff['id']),
                                                                  scaff['start'], scaff['end'],
                                                                  bit_score, seq_len))

        for entity in the_fg:
            for seq_id in the_fg[entity]:
                bit_score = the_fg[entity][seq_id][2]
                seq_len = the_fg[entity][seq_id][3]

                not_missing.append(entity)
                fragmented.append(entity)

                if self._mode == 'proteins' or self._mode == 'tran':
                    out_lines.append('%s\tFragmented\t%s\t%s\t%s\n' % (entity, self._reformats_seq_id(seq_id),
                                                                       bit_score, seq_len))
                elif self._mode == 'genome':
                    scaff = self._split_seq_id(seq_id)
                    out_lines.append(
                        '%s\tFragmented\t%s\t%s\t%s\t%s\t%s\n' % (entity, self._reformats_seq_id(scaff['id']),
                                                                  scaff['start'], scaff['end'],
                                                                  bit_score, seq_len))

        missing = []
        miss_file = open('%smissing_busco_list_%s.tsv' % (self.mainout, self._abrev), 'w')
        self._write_output_header(miss_file)
        for busco_group in self._cutoff_dictionary:
            if busco_group in not_missing:
                pass
            else:
                out_lines.append('%s\tMissing\n' % busco_group)
                missing.append(busco_group)

        env.append(missing)
        env.append(fragmented)
        env.append(csc)

        for line in sorted(missing):
            miss_file.write('%s\n' % line)
        miss_file.close()
        for line in sorted(out_lines):
            out.write(line)
        out.close()
        return env

    def _load_score(self):
        """
        This function loads the score cutoffs file
        :raises SystemExit: if the scores_cutoff file cannot be read
        """
        try:
            score_file = open('%sscores_cutoff' % self._clade_path)  # open target scores file
        except IOError:
            _logger.error('Impossible to read the scores in %sscores_cutoff' % self._clade_path)
            raise SystemExit
        score_dic = {}
        for entry in score_file:
            entry = entry.strip().split()
            try:
                score_dic[entry[0]] = float(entry[1])  # name : score
                self._cutoff_dictionary[entry[0]] = {'score': float(entry[1])}
            except(IndexError, KeyError):
                pass
            self._totalbuscos = len(list(self._cutoff_dictionary.keys()))
        score_file.close()

    def _load_length(self):
        """
        This function loads the length cutoffs file
        """
        leng_dic = {}
        sd_dic = {}
        try:
            f = open('%slengths_cutoff' % self._clade_path)
        except IOError:
            _logger.error('Impossible to read the lengths in %slengths_cutoff' % self._clade_path)
            raise SystemExit

        for line in f:
            line = line.strip().split()

            leng_dic[line[0]] = float(line[3])  # legacy
            sd_dic[line[0]] = float(line[2])  # legacy

            self._cutoff_dictionary[line[0]]['sigma'] = float(line[2])
            # there is an arthropod profile with sigma 0 that causes a crash on divisions
            if float(line[2]) == 0.0:
                self._cutoff_dictionary[line[0]]['sigma'] = 1

            self._cutoff_dictionary[line[0]]['length'] = float(line[3])
        f.close()

    def _create_directory(self):
        """
        This function creates the run and the temporary directories
        :raises SystemExit: if a run with the same name already exists and the force option is not set
        :raises SystemExit: if the user cannot write in the tmp directory
        """
        # create the run directory
        self.mainout = ROOT_FOLDER+'/run_%s/' % self._abrev  # final output directory
        # complain about the -r option if there is no checkpoint.tmp file
        if not self._get_checkpoint() and self._restart:
            _logger.warning('This is not an uncompleted run that can be restarted')
            self._restart = False

        if not os.path.exists(self.mainout) and self._abrev:
            Analysis.p_open(['mkdir', self.mainout], 'bash', shell=False)
        else:
            if not self._force and not self._restart:
                restart_msg1 = ''
                restart_msg2 = ''
                if self._get_checkpoint():
                    restart_msg1 = ' and seems uncompleted'
                    restart_msg2 = ', or use the -r option to continue an uncompleted run'
                _logger.error('A run with that name already exists%s...'
                              '\n\tIf you are sure you wish to overwrite existing files, please use the -f option%s'
                              % (restart_msg1, restart_msg2))

                raise SystemExit
            elif not self._restart:
                _logger.info('Delete the current result folder and start a new run')
                Analysis.p_open(['rm -rf %s*' % self.mainout], 'bash', shell=True)

        # create the tmp directory
        if self._tmp != './':
            if not os.path.exists(self._tmp):
                Analysis.p_open(['mkdir', self._tmp], 'bash', shell=False)
            if self._tmp[-1] != '/':
                self._tmp += '/'
        _logger.info('Temp directory is %s' % self._tmp)

        if not os.access(self._tmp, os.W_OK):
                _logger.error('Cannot write to the temp directory, please make sure you have '
                              'write permissions to %s' % self._tmp)
                raise SystemExit

    @abstractmethod
    def check_dependencies(self):
        """
        This function checks that all dependencies are satisfied.  It has to be overriden by subclasses
        """
        pass

    def _produce_short_summary(self):
        """
        This function reads the result files and produces the final short summary file
        """

        hmmer_results = os.listdir('%shmmer_output' % self.mainout)
        hmmer_results.sort()
        hmmer_results_files = []
        for entry in hmmer_results:
            hmmer_results_files.append(entry)

        results_from_hmmer = self._parse_hmmer(hmmer_results_files)
        single_copy = results_from_hmmer[0]  # int
        multi_copy = results_from_hmmer[1]  # int
        only_fragments = results_from_hmmer[2]  # int
        self._missing_busco_list = results_from_hmmer[3]  # list of BUSCO ids
        self._fragmented_busco_list = results_from_hmmer[4]  # list of BUSCO ids
        self._single_copy_files = results_from_hmmer[5]

        summary_file = open('%sshort_summary_%s.txt' % (self.mainout, self._abrev), 'w')
        self._write_output_header(summary_file)
        summary_file.write('# Summarized benchmarking in BUSCO notation for file %s\n# BUSCO was run in mode: %s\n\n'
                           % (self._sequences, self._mode))
        s_percent = round((single_copy/float(self._totalbuscos))*100, 1)
        d_percent = round((multi_copy/float(self._totalbuscos))*100, 1)
        f_percent = round((only_fragments/float(self._totalbuscos))*100, 1)
        _logger.info('Results:')
        out_line = ('\tC:%s%%[S:%s%%,D:%s%%],F:%s%%,M:%s%%,n:%s\n\n' %
                    (round(s_percent + d_percent, 1), s_percent, d_percent, f_percent,
                     round(100 - s_percent - d_percent - f_percent, 1), self._totalbuscos))
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', '').strip())
        out_line = ('\t%s\tComplete BUSCOs (C)\n' % (single_copy + multi_copy))
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', ' ').strip())
        out_line = ('\t%s\tComplete and single-copy BUSCOs (S)\n' % single_copy)
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', ' ').strip())
        out_line = ('\t%s\tComplete and duplicated BUSCOs (D)\n' % multi_copy)
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', ' ').strip())
        out_line = ('\t%s\tFragmented BUSCOs (F)\n' % only_fragments)
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', ' ').strip())
        out_line = ('\t%s\tMissing BUSCOs (M)\n' %
                    str(self._totalbuscos - single_copy - multi_copy - only_fragments))
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', ' ').strip())
        out_line = ('\t%s\tTotal BUSCO groups searched\n' % self._totalbuscos)
        summary_file.write(out_line)
        _logger.info(out_line.replace('\t', ' ').strip())
        summary_file.close()

    def _process_augustus_tasks(self):
        """
        This function takes Augustus tasks in the queue and executes them.
        """
        while not self._exit_flag:
            self._queue_lock.acquire()
            if not self._work_queue.empty():
                data = self._work_queue.get()
                self._queue_lock.release()
                check = len([name for name in os.listdir('%saugustus_output/predicted_genes' % self.mainout) if
                             os.path.isfile(os.path.join('%saugustus_output/predicted_genes' % self.mainout, name))])
                state = 100 * check / self._total
                if state > self.slate[-1]:
                    _logger.info('%s =>\t%s%% of predictions performed (%i/%i candidate regions)'
                                 % (time.strftime("%m/%d/%Y %H:%M:%S"), self.slate.pop(), check, self._total))
                Analysis.p_open([data], 'augustus', shell=True)
            else:
                self._queue_lock.release()

    def _process_hmmer_tasks(self):
        """
        This function takes hmmersearch tasks in the queue and executes them.
        """
        while not self._exit_flag:
            self._queue_lock.acquire()
            if not self._work_queue.empty():
                data = self._work_queue.get()
                self._queue_lock.release()
                check = len([name for name in os.listdir('%shmmer_output' % self.mainout) if
                             os.path.isfile(os.path.join('%shmmer_output' % self.mainout, name))])
                state = 100 * check / self._total
                if state > self.slate[-1]:
                    _logger.info('%s =>\t%s%% of predictions performed (%i/%i candidate proteins)'
                                 % (time.strftime("%m/%d/%Y %H:%M:%S"), self.slate.pop(), check, self._total))
                Analysis.p_open(data, 'hmmersearch', shell=False)
            else:
                self._queue_lock.release()

    def _process_gff2gbsmalldna_tasks(self):
        """
        This function takes gff2gbSmallDNA.pl tasks in the queue and executes them.
        """
        while not self._exit_flag:
            self._queue_lock.acquire()
            if not self._work_queue.empty():
                data = self._work_queue.get()
                self._queue_lock.release()
                Analysis.p_open([data], 'gff2gbSmallDNA.pl', shell=True)
            else:
                self._queue_lock.release()

    @abstractmethod
    def run_analysis(self):
        """
        This function calls all needed steps for running the analysis. It has to be overriden by subclasses
        """
        pass


class GenomeAnalysis(Analysis):
    """
    This class runs a BUSCO analysis on a genome. It extends Analysis.
    """

    def check_dataset(self):
        """
        Check if the dataset integrity, if files and folder are present
        :raises SystemExit: if the dataset miss files or folders
        """
        # prfl folder
        flag = False
        for dirpath, dirnames, files in os.walk('%sprfl' % self._clade_path):
            if files:
                flag = True
        if not flag:
            _logger.error('The dataset you provided lacks elements in %sprfl' % self._clade_path)
            raise SystemExit
        super(GenomeAnalysis, self).check_dataset()
        # note: score and length cutoffs are checked when read, see _load_scores and _load_lengths
        # ancestral would cause blast to fail, and be detected, see _blast()
        # dataset.cfg is not mandatory

        # check whether the ancestral_variants file is present
        if os.path.exists('%sancestral_variants' % self._clade_path):
            self._has_variants_file = True
        else:
            self._has_variants_file = False
            _logger.warning("The dataset you provided does not contain the file ancestral_variants, "
                            "likely because it is an old version. "
                            "All blast steps will use the file ancestral instead")

    def check_dependencies(self):
        """
        This function checks that all dependencies are satisfied.
        """
        self._check_augustus()
        Analysis._check_blast()
        Analysis._check_hmmer()

    def __init__(self, params):
        """
        Initialize an instance.
        :param params: Values of all parameters that have to be defined
        :type params: dict
        """
        super(GenomeAnalysis, self).__init__(params)
        self._mode = 'genome'

    def _fix_restart_augustus_folder(self):
        """
        This function resets and checks the augustus folder to make a restart possible in phase 2
        :raises SystemExit: if it is not possible to fix the folders
        """
        if os.path.exists('%saugustus_output/predicted_genes_run1' % self.mainout) and \
                os.path.exists('%shmmer_output_run1' % self.mainout):
            Analysis.p_open(['rm', '-fr', '%saugustus_output/predicted_genes' % self.mainout], 'bash', shell=False)
            Analysis.p_open(['mv', '%saugustus_output/predicted_genes_run1'
                             % self.mainout, '%saugustus_output/predicted_genes'
                             % self.mainout], 'bash', shell=False)
            Analysis.p_open(['rm', '-fr', '%shmmer_output' % self.mainout], 'bash', shell=False)
            Analysis.p_open(['mv', '%shmmer_output_run1/' % self.mainout, '%shmmer_output/' % self.mainout], 'bash',
                            shell=False)

        elif os.path.exists('%saugustus_output/predicted_genes' % self.mainout) and \
                os.path.exists('%shmmer_output' % self.mainout):
            pass
        else:
            _logger.error('Impossible to restart the run, necessary folders are missing. '
                          'Use the -f option instead of -r')
            raise SystemExit

    def run_analysis(self):
        """
        This function calls all needed steps for running the analysis.
        """
        self.check_dataset()
        self._check_nucleotide()
        self._create_directory()
        _logger.add_blank_line()
        if self._restart:
            checkpoint = self._get_checkpoint(reset_random_suffix=True)
            _logger.warning('Restarting an uncompleted run')
        else:
            checkpoint = 0  # all steps will be done

        _logger.info('****** Phase 1 of 2, initial predictions ******')
        if checkpoint < 1:
            _logger.info('****** Step 1/3, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
            self._blast()
            self._define_checkpoint(1)

        if checkpoint < 2:
            _logger.info('****** Step 2/3, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
            self._get_coordinates()
            self._augustus()
            _logger.info('****** Step 3/3, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
            self._hmmer()
            self._define_checkpoint(2)
        self._load_score()
        self._load_length()
        if checkpoint == 2 or checkpoint == 3:
            _logger.info('Phase 1 was already completed.')
        if checkpoint == 3:
            self._fix_restart_augustus_folder()
        self._produce_short_summary()
        _logger.add_blank_line()
        _logger.info('****** Phase 2 of 2, predictions using species specific training ******')
        if checkpoint < 3:
            _logger.info('****** Step 1/3, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
            if self._has_variants_file:
                self._blast(missing_and_frag_only=True, ancestral_variants=True)
                self._get_coordinates(missing_and_frag_only=True)
            else:
                self._blast(missing_and_frag_only=True, ancestral_variants=False)
                self._get_coordinates(missing_and_frag_only=True)
            self._define_checkpoint(3)
        _logger.info('****** Step 2/3, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
        self._augustus_rerun()
        self._move_retraining_parameters()
        self.cleanup()
        self._define_checkpoint()  # remove the checkpoint, run is done

    @staticmethod
    def _write_full_table_header(out):
        """
        This function adds a header line to the full table file
        :param out: a full table file
        :type out: file
        """
        out.write('# Busco id\tStatus\tContig\tStart\tEnd\tScore\tLength\n')

    def _move_retraining_parameters(self):
        """
        This function moves retraining parameters from augustus species folder to the run folder
        """
        if os.path.exists(self._augustus_config_path + ('/species/BUSCO_%s%s' % (self._abrev, self._random))):
            Analysis.p_open(['cp', '-r', '%sspecies/BUSCO_%s%s'
                             % (self._augustus_config_path, self._abrev, self._random),
                             '%saugustus_output/retraining_parameters' % self.mainout], 'bash', shell=False)
            Analysis.p_open(['rm', '-rf', '%sspecies/BUSCO_%s%s'
                             % (self._augustus_config_path, self._abrev, self._random)],
                            'bash', shell=False)
        else:
            _logger.add_blank_line()
            _logger.warning('Augustus did not produce a retrained species folder, please check the augustus log file '
                            'in the run folder to ensure that nothing went wrong (%saugustus_output/augustus.log)'
                            % self.mainout)

    def cleanup(self):
        """
        This function cleans temporary files and move some files to their final place
        """
        super(GenomeAnalysis, self).cleanup()
        Analysis.p_open(['rm %s*%s%s_.temp' % (self._tmp, self._abrev, self._random)], 'bash', shell=True)
        Analysis.p_open(['rm %(tmp)s%(abrev)s.*ns? %(tmp)s%(abrev)s.*nin %(tmp)s%(abrev)s.*nhr'
                        % {'tmp': self._tmp, 'abrev': self._abrev + str(self._random)}], 'bash', shell=True)

    def _run_tarzip(self):
        """
        This function tarzips results folder
        """
        super(GenomeAnalysis, self)._run_tarzip()
        # augustus_output/predicted_genes
        Analysis.p_open(['tar', '-C', '%saugustus_output' % self.mainout, '-zcf',
                         '%saugustus_output/predicted_genes.tar.gz' % self.mainout, 'predicted_genes',
                         '--remove-files'],
                        'bash', shell=False)
        # augustus_output/extracted_proteins
        Analysis.p_open(['tar', '-C', '%saugustus_output' % self.mainout, '-zcf',
                         '%saugustus_output/extracted_proteins.tar.gz' % self.mainout, 'extracted_proteins',
                         '--remove-files'],
                        'bash', shell=False)
        # augustus_output/gb
        Analysis.p_open(['tar', '-C', '%saugustus_output' % self.mainout, '-zcf',
                         '%saugustus_output/gb.tar.gz' % self.mainout, 'gb',
                         '--remove-files'],
                        'bash', shell=False)
        # augustus_output/gffs
        Analysis.p_open(['tar', '-C', '%saugustus_output' % self.mainout, '-zcf',
                         '%saugustus_output/gffs.tar.gz' % self.mainout, 'gffs',
                         '--remove-files'],
                        'bash', shell=False)
        # single_copy_busco_sequences
        Analysis.p_open(['tar', '-C', '%s' % self.mainout, '-zcf',
                         '%ssingle_copy_busco_sequences.tar.gz' % self.mainout, 'single_copy_busco_sequences',
                         '--remove-files'],
                        'bash', shell=False)

    def _get_coordinates(self, missing_and_frag_only=False):
        """
        This function gets coordinates for candidate regions from tblastn result file
        :param missing_and_frag_only: tell whether to use the missing_and_frag_rerun tblastn file
        :type missing_and_frag_only: bool
        """

        if missing_and_frag_only:
            blast_file = open('%sblast_output/tblastn_%s_missing_and_frag_rerun.tsv' % (self.mainout, self._abrev))
        else:
            blast_file = open('%sblast_output/tblastn_%s.tsv' % (self.mainout, self._abrev))

        _logger.info('Getting coordinates for candidate regions...')

        dic = {}
        coords = {}
        for line in blast_file:
            if line.startswith('#'):
                pass
            else:
                try:
                    line = line.strip().split()
                    busco_name = line[0]
                    contig = line[1]  # busco_og and contig name, respectively
                    busco_start = int(line[6])
                    busco_end = int(line[7])  # busco hit positions
                    contig_start = int(line[8])
                    contig_end = int(line[9])  # contig postions
                    aln_len = int(line[3])  # e_value and alignment length
                    blast_eval = float(line[10])

                    if contig_end < contig_start:  # for minus-strand genes, invert coordinates for convenience
                        temp = contig_end
                        contig_end = contig_start
                        contig_start = temp
                    if busco_name not in dic.keys():  # create new entry in dictionary for current BUSCO
                        dic[busco_name] = [contig]
                        coords[busco_name] = {}
                        coords[busco_name][contig] = [contig_start, contig_end, deque([[busco_start, busco_end]]),
                                                      aln_len, blast_eval]
                    # get just the top scoring regions according to region limits
                    elif contig not in dic[busco_name] and len(dic[busco_name]) < self._region_limit:
                        # scoring regions
                        dic[busco_name].append(contig)
                        coords[busco_name][contig] = [contig_start, contig_end, deque([[busco_start, busco_end]]),
                                                      aln_len, blast_eval]

                    # replace the lowest scoring region if the current has a better score.
                    # needed because of multiple blast query having the same name when using ancestral_variants
                    # and not sorted by eval in the tblastn result file
                    elif contig not in dic[busco_name] and len(dic[busco_name]) >= self._region_limit:
                        to_replace = None
                        for entry in list(coords[busco_name].keys()):
                            if coords[busco_name][entry][4] > blast_eval:
                                if (to_replace and  # check if there is already a to_replace entry and compare the eval
                                        coords[busco_name][entry][4] > list(to_replace.values())[0]) \
                                        or not to_replace:
                                    # use a single entry dictionary to store the id to replace and its eval
                                    to_replace = {entry: coords[busco_name][entry][4]}
                        if to_replace:
                            dic[busco_name].remove(list(to_replace.keys())[0])
                            dic[busco_name].append(contig)
                            coords[busco_name][contig] = [contig_start, contig_end, deque([[busco_start, busco_end]]),
                                                          aln_len, blast_eval]

                    elif contig in dic[busco_name]:  # contigold already checked,
                        # now update coordinates
                        if contig_start < coords[busco_name][contig][0] and coords[busco_name][contig][0] - \
                                contig_start <= 50000:  # starts before, and withing 50kb of current position
                            coords[busco_name][contig][0] = contig_start
                            coords[busco_name][contig][2].append([busco_start, busco_end])
                        if contig_end > coords[busco_name][contig][1] \
                                and contig_end - coords[busco_name][contig][1] \
                                <= 50000:  # ends after and within 50 kbs
                            coords[busco_name][contig][1] = contig_end
                            coords[busco_name][contig][3] = busco_end
                            coords[busco_name][contig][2].append([busco_start, busco_end])
                        elif coords[busco_name][contig][1] > contig_start > coords[busco_name][contig][0]:
                            # starts inside current coordinates
                            if contig_end < coords[busco_name][contig][1]:
                                # if ending inside, just add alignemnt positions to deque
                                coords[busco_name][contig][2].append([busco_start, busco_end])
                                # if ending after current coordinates, extend
                            elif contig_end > coords[busco_name][contig][1]:
                                coords[busco_name][contig][2][1] = contig_end
                                coords[busco_name][contig][2].append([busco_start, busco_end])

                except (IndexError, ValueError):
                    pass

        blast_file.close()
        final_locations = {}
        if missing_and_frag_only:
            out = open('%s/blast_output/coordinates_%s_missing_and_frag_rerun.tsv'
                       % (self.mainout, self._abrev), 'w')  # open Coordinates output file
        else:
            out = open('%s/blast_output/coordinates_%s.tsv'
                       % (self.mainout, self._abrev), 'w')  # open Coordinates output file

        for busco_group in coords:
            final_locations[busco_group] = []
            candidate_contigs = list(coords[busco_group].keys())  # list of candidate contigs
            size_lists = []

            for contig in candidate_contigs:
                potential_locations = coords[busco_group][contig][2]
                max_iterations = len(potential_locations)
                iter_count = 0

                final_regions = []  # nested list of regions
                used_pieces = []
                non_used = []

                while iter_count < max_iterations:
                    currently = potential_locations[iter_count]
                    if len(final_regions) == 0:
                        final_regions.append(currently)
                    else:
                        for region in final_regions:
                            if Analysis._check_overlap(currently, region) != 0:
                                gg = Analysis._define_boundary(currently, region)
                                region_index = final_regions.index(region)
                                final_regions[region_index] = gg
                                used_pieces.append(iter_count)
                            else:
                                non_used.append(iter_count)
                    iter_count += 1

                # done for this contig, now consolidate
                for entry_index in non_used:
                    entry = potential_locations[entry_index]
                    if entry in used_pieces:
                        pass  # already used
                    else:
                        ok = []
                        for region in final_regions:
                            checking = Analysis._check_overlap(entry, region)
                            if checking == 0:
                                # i.e. no overlap
                                pass
                            else:
                                ok.append([region, entry])
                        if len(ok) == 0:
                            # no overlaps at all (i.e. unique boundary)
                            final_regions.append(entry)
                        else:
                            region = ok[0][0]
                            currently = ok[0][1]
                            gg = Analysis._define_boundary(currently, region)
                            final_regions[final_regions.index(region)] = gg

                size_lists.append(Analysis._gargantua(final_regions))
            max_size = max(size_lists)
            size_cutoff = int(0.7 * max_size)
            index_passed_cutoffs = heapq.nlargest(self._region_limit, range(len(size_lists)), size_lists.__getitem__)

            for candidate in index_passed_cutoffs:
                if size_lists[candidate] >= size_cutoff:
                    seq_name = candidate_contigs[candidate]
                    seq_start = int(coords[busco_group][candidate_contigs[candidate]][0]) - self._flank
                    if seq_start < 0:
                        seq_start = 0
                    seq_end = int(coords[busco_group][candidate_contigs[candidate]][1]) + self._flank
                    final_locations[busco_group].append([seq_name, seq_start, seq_end])
                    out.write('%s\t%s\t%s\t%s\n' % (busco_group, seq_name, seq_start, seq_end))
        out.close()

    def _hmmer(self):
        """
        This function runs hmmsearch.
        :raises SystemExit: if the hmmsearch result folder is empty after the run
        """
        _logger.info('Running HMMER to confirm orthology of predicted proteins:')

        files = os.listdir('%saugustus_output/extracted_proteins' % self.mainout)
        files.sort()
        if not os.path.exists(self.mainout + 'hmmer_output'):
            Analysis.p_open(['mkdir', '%shmmer_output' % self.mainout], 'bash', shell=False)

        count = 0

        hmmer_run_strings = []

        for entry in files:
            if entry.split('.')[-2] == 'faa':
                count += 1
                group_name = entry.split('.')[0]
                group_index = entry.split('.')[-1]
                hmmer_call = ['hmmsearch',
                              '--domtblout', '%shmmer_output/%s.out.%s' % (self.mainout, group_name, group_index),
                              '-o', '%stemp_%s%s' % (self._tmp, self._abrev, self._random),
                              '--cpu', '1',
                              '%shmms/%s.hmm' % (self._clade_path, group_name),
                              '%saugustus_output/extracted_proteins/%s' % (self.mainout, entry)]

                hmmer_run_strings.append(hmmer_call)

        self._run_threads(hmmer_run_strings, self._HmmerThreads)


class TranscriptomeAnalysis(Analysis):
    """
    This class runs a BUSCO analysis on a transcriptome. It extends Analysis.
    """

    @staticmethod
    def _reformats_seq_id(seq_id):
        """
        This function reformats the sequence id to its original values
        :param seq_id: the seq id to reformats
        :type seq_id: str
        :return: the reformatted seq_id
        :rtype: str
        """
        return "_".join(seq_id.split('_')[:-1])

    def check_dataset(self):
        """
        Check if the dataset integrity, if files and folder are present
        :raises SystemExit: if the dataset miss files or folders
        """
        # check whether the ancestral_variants file is present
        if os.path.exists('%sancestral_variants' % self._clade_path):
            self._has_variants_file = True
        else:
            self._has_variants_file = False
            _logger.warning("The dataset you provided does not contain the file ancestral_variants, "
                            "likely because it is an old version. "
                            "All blast steps will use the file ancestral")

    def check_dependencies(self):
        """
        This function checks that all dependencies are satisfied.
        """
        Analysis._check_blast()
        Analysis._check_hmmer()

    def __init__(self, params):
        """
        Initialize an instance.
        :param params: Values of all parameters that have to be defined
        :type params: dict
        """
        super(TranscriptomeAnalysis, self).__init__(params)
        self._mode = 'tran'

    def run_analysis(self):
        """
        This function calls all needed steps for running the analysis.
        """
        self.check_dataset()
        self._check_nucleotide()
        self._create_directory()
        if self._restart:
            checkpoint = self._get_checkpoint(reset_random_suffix=True)
            _logger.warning('Restarting an uncompleted run')
        else:
            checkpoint = 0  # all steps will be done
        if checkpoint < 1:
            _logger.info('****** Step 1/2, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
            if self._has_variants_file:
                self._blast(ancestral_variants=True)
            else:
                self._blast(ancestral_variants=False)
            self._define_checkpoint(1)
        _logger.info('****** Step 2/2, current time: %s ******' % time.strftime("%m/%d/%Y %H:%M:%S"))
        self._load_score()
        self._load_length()
        self._get_coordinates()
        self._hmmer()
        self._produce_short_summary()
        self.cleanup()
        self._define_checkpoint()  # remove the checkpoint, run is done

    def cleanup(self):
        """
        This function cleans temporary files.
        """
        super(TranscriptomeAnalysis, self).cleanup()
        Analysis.p_open(['rm %s*%s%s_.temp' % (self._tmp, self._abrev, self._random)], 'bash', shell=True)
        Analysis.p_open(['rm %(tmp)s%(abrev)s.*ns? %(tmp)s%(abrev)s.*nin %(tmp)s%(abrev)s.*nhr'
                        % {'tmp': self._tmp, 'abrev': self._abrev + str(self._random)}], 'bash', shell=True)

    def _run_tarzip(self):
        """
        This function tarzips results folder
        """
        super(TranscriptomeAnalysis, self)._run_tarzip()
        # translated_proteins
        Analysis.p_open(['tar', '-C', '%s' % self.mainout, '-zcf',
                         '%stranslated_proteins.tar.gz' % self.mainout, 'translated_proteins',
                         '--remove-files'],
                        'bash', shell=False)

    def _get_coordinates(self):
        """
        This function gets coordinates for candidate regions from tblastn result file
        """
        _logger.info('Getting coordinates for candidate transcripts...')
        f = open('%sblast_output/tblastn_%s.tsv' % (self.mainout, self._abrev))  # open input file
        transcriptome_by_busco = {}
        self._transcriptome_by_scaff = {}
        maxi = 0
        for i in f:  # get a dictionary of BUSCO matches vs candidate scaffolds
            if i.startswith('#'):
                pass
            else:
                line = i.strip().split()
                if self._has_variants_file:
                    busco = '_'.join(line[0].split("_")[:-1])  # This pattern can support name like EOG00_1234_1
                else:
                    busco = line[0]
                scaff = line[1]
                leng = int(line[3])
                blast_eval = float(line[10])
                if busco not in transcriptome_by_busco.keys():
                    # Simply add it
                    # Use a single entry dict to keep scaffs id and their blast eval, for each busco
                    transcriptome_by_busco[busco] = [{scaff: blast_eval}]
                    # and keep a list of each busco by scaff
                    try:
                        self._transcriptome_by_scaff[scaff].append(busco)
                    except KeyError:
                        self._transcriptome_by_scaff[scaff] = [busco]
                    maxi = leng
                elif len(transcriptome_by_busco[busco]) < self._region_limit and leng >= 0.7 * maxi:
                    # check that this transcript is not already in, and update its eval if needed
                    add = True
                    for scaff_dict in transcriptome_by_busco[busco]:
                        if list(scaff_dict.keys())[0] == scaff:
                            add = False
                            if blast_eval < list(scaff_dict.values())[0]:
                                scaff_dict[scaff] = blast_eval  # update the eval for this scaff
                    if add:
                        transcriptome_by_busco[busco].append({scaff: blast_eval})
                        try:
                            self._transcriptome_by_scaff[scaff].append(busco)
                        except KeyError:
                            self._transcriptome_by_scaff[scaff] = [busco]
                        if leng > maxi:
                            maxi = leng
                elif len(transcriptome_by_busco[busco]) >= self._region_limit and leng >= 0.7 * maxi:
                    # replace the lowest scoring transcript if the current has a better score.
                    # needed because of multiple blast query having the same name when using ancestral_variants
                    # and not sorted by eval in the tblastn result file
                    to_replace = None
                    # Define if something has to be replaced
                    for entry in transcriptome_by_busco[busco]:
                        if list(entry.values())[0] > blast_eval:
                            if (to_replace and  # check if there is already a to_replace entry and compare the eval
                                    list(entry.values())[0] > list(to_replace.values())[0]) or not to_replace:
                                to_replace = {list(entry.keys())[0]: list(entry.values())[0]}

                    if to_replace:
                        # try to add the new one
                        # check that this scaffold is not already in, and update the eval if needed
                        # if the scaff was already in, do not replace the to_replace entry to keep the max number of
                        # candidate regions
                        add = True
                        for scaff_dict in transcriptome_by_busco[busco]:
                            if list(scaff_dict.keys())[0] == scaff:
                                add = False
                                if blast_eval < list(scaff_dict.values())[0]:
                                    scaff_dict[scaff] = blast_eval  # update the eval for this scaff
                        if add:
                            # add the new one
                            transcriptome_by_busco[busco].append({scaff: blast_eval})
                            try:
                                self._transcriptome_by_scaff[scaff].append(busco)
                            except KeyError:
                                self._transcriptome_by_scaff[scaff] = [busco]

                            # remove the old one
                            for entry in transcriptome_by_busco[busco]:
                                if list(entry.keys())[0] == list(to_replace.keys())[0]:
                                    scaff_to_remove = list(entry.keys())[0]
                                    break
                            transcriptome_by_busco[busco].remove(entry)

                            for entry in self._transcriptome_by_scaff[scaff_to_remove]:
                                if entry == busco:
                                    break
                            self._transcriptome_by_scaff[scaff_to_remove].remove(entry)

                            if leng > maxi:
                                maxi = leng

        _logger.info('Extracting candidate transcripts...')
        f = open(self._sequences)
        check = 0
        out = None
        for i in f:
            if i.startswith('>'):
                i = i.strip().split()
                i = i[0][1:]
                if i in list(self._transcriptome_by_scaff.keys()):
                    out = open('%s%s%s%s_.temp' % (self._tmp, i, self._abrev, self._random), 'w')
                    out.write('>%s\n' % i)
                    check = 1
                else:
                    check = 0
            elif check == 1:
                out.write(i)
        f.close()
        if out:
            out.close()
        if not os.path.exists('%stranslated_proteins' % self.mainout):
            Analysis.p_open(['mkdir', '%stranslated_proteins' % self.mainout], 'bash', shell=False)
        files = os.listdir(self._tmp)
        files.sort()
        lista = []
        for entry in files:
            if entry.endswith(self._abrev + str(self._random) + '_.temp'):
                lista.append(entry)

        _logger.info('Translating candidate transcripts...')
        for entry in lista:
            raw_seq = open(self._tmp + entry)
            name = self._abrev.join(entry.replace('_.temp', '')
                                    .split(self._abrev)[:-1])  # this works even if the runname is in the header
            trans_seq = open(self.mainout + 'translated_proteins/' + name + '.faa', 'w')
            nucl_seq = ''
            header = ''
            for line in raw_seq:
                if line.startswith('>'):
                    header = line.strip() + '_'
                else:
                    nucl_seq += line.strip()
            seq_count = 0
            for translation in Analysis._sixpack(nucl_seq):
                seq_count += 1
                trans_seq.write('%s%s\n%s\n' % (header, seq_count, translation))
            raw_seq.close()
            trans_seq.close()

        f2 = open('%sscores_cutoff' % self._clade_path)  # open target scores file
        # Load dictionary of HMM expected scores and full list of groups
        score_dic = {}
        for i in f2:
            i = i.strip().split()
            try:
                score_dic[i[0]] = float(i[1])  # float [1] = mean value; [2] = minimum value
            except IndexError:
                pass
        f2.close()
        self._totalbuscos = len(list(score_dic.keys()))

    def _hmmer(self):
        """
        This function runs hmmsearch.
        """
        _logger.info('Running HMMER to confirm transcript orthology:')
        files = os.listdir('%stranslated_proteins/' % self.mainout)
        files.sort()
        if not os.path.exists('%shmmer_output' % self.mainout):
            Analysis.p_open(['mkdir', '%shmmer_output' % self.mainout], 'bash', shell=False)

        count = 0

        hmmer_run_strings = []

        busco_index = {}

        for f in files:
            if f.endswith('.faa'):
                count += 1
                scaff = f[:-4]
                scaff_buscos = self._transcriptome_by_scaff[scaff]
                for busco in scaff_buscos:

                    try:
                        busco_index[busco] += 1
                    except KeyError:
                        busco_index[busco] = 1

                    hmmer_call = ['hmmsearch',
                                  '--domtblout',
                                  '%shmmer_output/%s.out.%s' % (self.mainout, busco, busco_index[busco]),
                                  '-o', '%stemp_%s%s' % (self._tmp, self._abrev, str(self._random)),
                                  '--cpu', '1',
                                  '%shmms/%s.hmm' % (self._clade_path, busco),
                                  '%stranslated_proteins/%s' % (self.mainout, f)]

                    hmmer_run_strings.append(hmmer_call)

        # Run hmmer
        self._run_threads(hmmer_run_strings, self._HmmerThreads)


class GeneSetAnalysis(Analysis):
    """
    This class runs a BUSCO analysis on a gene set (proteins). It extends Analysis.
    """

    def check_dependencies(self):
        """
        This function checks that all dependencies are satisfied.
        """
        Analysis._check_hmmer()

    def __init__(self, params):
        """
        Initialize an instance.
        :param params: Values of all parameters that have to be defined
        :type params: dict
        """
        super(GeneSetAnalysis, self).__init__(params)
        if self._restart:
            _logger.error('There is no restart allowed for the protein mode')
            raise SystemExit
        self._mode = 'proteins'

    def run_analysis(self):
        """
        This function calls all needed steps for running the analysis.
        """
        self.check_dataset()
        self._check_protein()
        self._create_directory()
        self._load_score()
        self._load_length()
        self._hmmer()
        self._produce_short_summary()
        self.cleanup()

    def _hmmer(self):
        """
        This function runs hmmsearch.
        """

        # Run hmmer
        _logger.info('Running HMMER on the proteins:')

        if not os.path.exists(self.mainout + 'hmmer_output'):
            Analysis.p_open(['mkdir', '%shmmer_output' % self.mainout], 'bash', shell=False)
        files = os.listdir(self._clade_path + '/hmms')
        files.sort()
        f2 = open('%sscores_cutoff' % self._clade_path)  # open target scores file
        #   Load dictionary of HMM expected scores and full list of groups
        score_dic = {}
        for i in f2:
            i = i.strip().split()
            try:
                score_dic[i[0]] = float(i[1]) 	# [1] = mean value; [2] = minimum value
            except IndexError:
                pass
        self._totalbuscos = len(list(score_dic.keys()))
        f2.close()

        hmmer_run_strings = []
        for i in files:
            name = i[:-4]
            if name in score_dic:
                hmmer_run_strings.append(['hmmsearch',
                                          '--domtblout', '%shmmer_output/%s.out.1' % (self.mainout, name),
                                          '-o', '%stemp_%s%s' % (self._tmp, self._abrev, str(self._random)),
                                          '--cpu', '1',
                                          '%s/hmms/%s.hmm' % (self._clade_path, name),
                                          '%s' % self._sequences])

        self._run_threads(hmmer_run_strings, self._HmmerThreads)


# end of classes definition, now module code

VERSION = '2.0.1'

CONTACT = 'mailto:support@orthodb.org'

ROOT_FOLDER = os.getcwd()

FORBIDDEN_HEADER_CHARS_BEFORE_SPLIT = ['/', '\'']

FORBIDDEN_HEADER_CHARS = ['ç', '¬', '¢', '´', 'ê', 'î', 'ô', 'ŵ', 'ẑ', 'û', 'â', 'ŝ', 'ĝ', 'ĥ', 'ĵ', 'ŷ',
                          'ĉ', 'é', 'ï', 'ẅ', 'ë', 'ẅ', 'ë', 'ẗ,', 'ü', 'í', 'ö', 'ḧ', 'é', 'ÿ', 'ẍ', 'è', 'é',
                          'à', 'ä', '¨', '€', '£', 'á']

#: Get an instance of _logger for keeping track of events
logging.setLoggerClass(BUSCOLogger)
_logger = logging.getLogger(__file__.split("/")[-1])

_rerun_cmd = ''


def _parse_args():
    """
    This function parses the arguments provided by the user
    :return: a dictionary having a key for each arguments
    :rtype: dict
    """

    # small hack to get sub-parameters with dash and pass it to Augustus
    for i, arg in enumerate(sys.argv):
        if (arg[0] == '-' or arg[0] == '--') and (sys.argv[i - 1] == '-a' or sys.argv[i - 1] == '--augustus'):
            sys.argv[i] = ' ' + arg

    parser = argparse.ArgumentParser(
        description='Welcome to BUSCO %s: the Benchmarking Universal Single-Copy Ortholog assessment tool.\n'
                    'For more detailed usage information, please review the README file provided with '
                    'this distribution and the BUSCO user guide.' % VERSION,
        usage='python BUSCO.py -i [SEQUENCE_FILE] -l [LINEAGE] -o [OUTPUT_NAME] -m [MODE] [OTHER OPTIONS]',
        formatter_class=RawTextHelpFormatter, add_help=False)

    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')

    required.add_argument(
        '-i', '--in', dest='in', required=True, metavar='FASTA FILE', help='Input sequence file in FASTA format. '
        'Can be an assembled genome or transcriptome (DNA), or protein sequences from an annotated gene set.')

    optional.add_argument(
        '-c', '--cpu', dest='cpu', required=False, metavar='N', help='Specify the number (N=integer) '
                                                                     'of threads/cores to use.')
    required.add_argument(
        '-o', '--out', dest='abrev', required=True, metavar='OUTPUT',
        help='Give your analysis run a recognisable short name. '
             'Output folders and files will be labelled with this name. WARNING: do not provide a path')

    optional.add_argument(
        '-e', '--evalue', dest='evalue', required=False, metavar='N', type=float, default=Analysis.EVALUE_DEFAULT,
        help='E-value cutoff for BLAST searches. '
             'Allowed formats, 0.001 or 1e-03 (Default: %.0e)' % Analysis.EVALUE_DEFAULT)

    required.add_argument(
        '-m', '--mode', dest='mode', required=True, metavar='MODE', help='Specify which BUSCO analysis mode to run.\n'
        'There are three valid modes:\n- geno or genome, for genome assemblies (DNA)\n- tran or transcriptome, for '
        'transcriptome assemblies (DNA)\n- prot or proteins, for annotated gene sets (protein)')
    required.add_argument(
        '-l', '--lineage', dest='clade', required=True, metavar='LINEAGE',
        help='Specify location of the BUSCO lineage data to be used.\n'
             'Visit http://busco.ezlab.org for available lineages.')

    optional.add_argument(
        '-f', '--force', action='store_true',  required=False, default=False, dest='force',
        help='Force rewriting of existing files. Must be used when output files with the provided name already exist.')

    optional.add_argument(
        '-r', '--restart', action='store_true',  required=False, default=False, dest='restart',
        help='Restart an uncompleted run. Not available for the protein mode')

    optional.add_argument(
        '-sp', '--species', required=False, dest='species', metavar='SPECIES',
        help='Name of existing Augustus species gene finding parameters. '
             'See Augustus documentation for available options.')

    optional.add_argument('--augustus_parameters', required=False, default='', dest='augustus_parameters',
                          help='Additional parameters for the fine-tuning of Augustus run. '
                               'For the species, do not use this option.\n'
                               'Use single quotes as follow: \'--param1=1 --param2=2\', '
                               'see Augustus documentation for available options.')

    optional.add_argument(
        '-t', '--tmp', metavar='PATH', required=False, dest='tmp', default='%s' % Analysis.TMP_DEFAULT,
        help='Where to store temporary files (Default: %s)' % Analysis.TMP_DEFAULT)

    optional.add_argument(
        '--limit', dest='limit', metavar='REGION_LIMIT', required=False, default=Analysis.REGION_LIMIT_DEFAULT,
        type=int, help='How many candidate regions to consider (default: %s)' % str(Analysis.REGION_LIMIT_DEFAULT))

    optional.add_argument(
        '--long', action='store_true', required=False, default=False, dest='long', help='Optimization mode Augustus '
        'self-training (Default: Off) adds considerably to the run time, but can improve results for some non-model '
                                                                                        'organisms')

    optional.add_argument(
        '-q', '--quiet', dest='quiet', required=False, help='Disable the info logs, displays only errors',
        action="store_true")

    optional.add_argument(
        '-z', '--tarzip', dest='tarzip', required=False, help='Tarzip the output folders likely to '
                                                              'contain thousands of files',
        action="store_true")

    optional.add_argument('-v', '--version', action='version', help="Show this version and exit", version='BUSCO %s'
                                                                                                          % VERSION)

    optional.add_argument('-h', '--help', action="help", help="Show this help message and exit")

    args = vars(parser.parse_args())

    if args['quiet']:
        _logger.setLevel(logging.ERROR)

    _logger.debug('Args list is %s' % str(args))

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    return args  # parse arguments


def _define_parameters(args):
    """
    This function defines the value of all parameters needed to start an analysis, \
    based on user provided and default values
    :param args: a dictionary having a key for each arguments, representing the user provided values
    :type args: dict
    :return: a dictionary having a key for each arguments, representing all values
    :rtype: dict
    :raises SystemExit: if the provided clade does not exist
    :raises SystemExit: if the provided mode does not exist
    :raises SystemExit: if the provided maximum number of regions is not an int between 1 and 20
    :raises SystemExit: if the provided input file does not exist
    """
    # Use an e-value cutoff of the default value, unless user has supplied a custom value using "-evalue float" option
    ev_cutoff = Analysis.EVALUE_DEFAULT  # default e-value cuttof
    if args['evalue'] and args['evalue'] != ev_cutoff:
        _logger.warning('You are using a custom e-value cutoff')
        ev_cutoff = args['evalue']
    maxflank = Analysis.MAX_FLANK
    region_limit = Analysis.REGION_LIMIT_DEFAULT
    if args['clade']:
        if args['clade'][-1] != '/':
            args['clade'] += '/'
        target_species = None
        clade_name = None
        domain = None
        dataset_creation_date = "N/A"
        dataset_nb_buscos = "N/A"
        dataset_nb_species = "N/A"
        # load the dataset config, or warn the user if not present
        try:
            target_species_file = open('%sdataset.cfg' % args['clade'])
            for l in target_species_file:
                if l.split("=")[0] == "name":
                    clade_name = l.strip().split("=")[1]
                elif l.split("=")[0] == "species":
                    target_species = l.strip().split("=")[1]
                elif l.split("=")[0] == "domain":
                    domain = l.strip().split("=")[1]
                elif l.split("=")[0] == "creation_date":
                    dataset_creation_date = l.strip().split("=")[1]
                elif l.split("=")[0] == "number_of_BUSCOs":
                    dataset_nb_buscos = l.strip().split("=")[1]
                elif l.split("=")[0] == "number_of_species":
                    dataset_nb_species = l.strip().split("=")[1]
            if domain != 'prokaryota' and domain != 'eukaryota':
                _logger.error('Corrupted dataset.cfg file: domain is %s, should be eukaryota or prokaryota' % domain)
                raise SystemExit

        except IOError:
            _logger.warning("The dataset you provided does not contain the file dataset.cfg, "
                            "likely because it is an old version. "
                            "Some parameters will be deduced from the dataset folder name")
    else:
        _logger.error('Please indicate the full path to a BUSCO clade dataset, example: -l /path/to/clade')
        raise SystemExit

    if not clade_name:  # 1.x datasets backward compatibility
        clade_name = args['clade'].strip('/').split('/')[-1].lower()
    if not domain:  # 1.x datasets backward compatibility
        if clade_name.startswith('bacteria'):
            domain = 'prokaryota'
        else:
            domain = 'eukaryota'

    # Use "generic" as the Augustus species unless user has specified the desired species metaparameters using the
    #  "-sp species" option
    if not args['species']:
        if not target_species:  # 1.x datasets backward compatibility
            if clade_name.startswith(('arthrop', 'examp')):
                target_species = 'fly'
            elif clade_name.startswith('vertebr'):
                target_species = 'human'
            elif clade_name.startswith('fung'):
                target_species = 'aspergillus_nidulans'
            elif clade_name.startswith('metazoa'):
                target_species = 'fly'
            elif clade_name.startswith('bacter'):
                target_species = 'E_coli_K12'
            elif clade_name.startswith('plant'):
                target_species = 'maize'
            elif clade_name.startswith('eukary'):
                target_species = 'fly'
            else:
                target_species = Analysis.SPECIES_DEFAULT
    else:
        target_species = args['species']

    _logger.info('The lineage dataset is: %s (%s)' % (clade_name, domain))

    # Set up the number of cores to be used
    # Augustus uses the python 'threading' library to be run in parallel, blast and HMMer allow this by default
    cpus = Analysis.CPUS_DEFAULT  # 1 core default
    if args['cpu']:
        cpus = args['cpu']

    # BUSCO mode (valid modes are genome, transcriptome and proteins)
    mode = args['mode']
    if mode == 'prot' or mode == 'proteins':
        mode = 'proteins'
    elif mode == 'geno' or mode == 'genome':
        mode = 'genome'
    elif mode == 'transcriptome' or mode == 'tran':
        mode = 'tran'
    else:
        _logger.error('Unknown mode specified * %s *, please check the documentation'
                      ' for valid modes.' % mode)
        raise SystemExit

    _logger.info('Mode is: %s' % mode)

    if mode == 'genome':
        if args['limit'] == 0 or args['limit'] > 20:
            _logger.error('Limit must be an integer between 1 and 20 (you have used: %s).' % args['limit'])
            raise SystemExit
        else:
            region_limit = args['limit']
            _logger.info('Maximum number of regions limited to: %s' % region_limit)

        # Fine tuning paramets for Augustus run
        # Example -a '--translation_table=6'
        if args['augustus_parameters']:
            augustus_parameters = args['augustus_parameters']
            _logger.info('The additional Augustus parameter(s) is/are: %s' % augustus_parameters)

    # Get the flank size
    # Minimum 5 Kbp and maximum 20 Kbp
    # Scaled as GenomeSize/50
    flank = None
    if mode == 'genome':  # scalled flanks
        try:
            f = open(args['in'])
            size = 0
            for line in f:
                if line.startswith('>'):
                    pass
                else:
                    size += len(line.strip())
            size /= 1000  # size in mb
            flank = int(size / 50)  # proportional flank size
            if flank < 5000:
                flank = 5000
            elif flank > maxflank:
                flank = maxflank
            f.close()
        except IOError:
            _logger.error('Impossible to read the fasta file %s ' % args['in'])
            raise SystemExit

    augustus_config_path = os.environ.get('AUGUSTUS_CONFIG_PATH')
    try:
        if augustus_config_path[-1] != '/':
            augustus_config_path += '/'
    except TypeError:
        augustus_config_path = None

    if '/' in args['abrev']:
        _logger.error('Please do not provide a full path as output (no slash), just a name. '
                      'Your entry for -o is %s\n\t\tThe results will be written in a subfolder of the current location '
                      'called run_name'
                      % args['abrev'])
        raise SystemExit

    return {"mode": mode, "target_species": target_species, "abrev": args['abrev'], "tmp": args['tmp'],
            "force": args['force'], "sequences": args['in'], "cpus": cpus, "clade_name": clade_name,
            "clade_path": args['clade'], "ev_cutoff": ev_cutoff, "domain": domain, "restart": args['restart'],
            "augustus_config_path": augustus_config_path, "tarzip": args['tarzip'],
            "region_limit": region_limit, "flank": flank, "long": args['long'],
            "dataset_creation_date": dataset_creation_date, "dataset_nb_species": dataset_nb_species,
            "dataset_nb_buscos": dataset_nb_buscos, "augustus_parameters": args['augustus_parameters']
            }


def _check_path_exist(path):
    """
    This function checks whether the provided path exists
    :param path: the path to be tested
    :type path: str
    :raises SystemExit: if the path cannot be reached
    """
    if not os.path.exists(path):
        _logger.error('Impossible to read %s' % path)
        raise SystemExit


def _set_rerun_busco_command(params):
    """
    This function sets the command line to call to reproduce this run
    :param params: the params provided by the user
    :type params: dict
    """
    global _rerun_cmd
    _rerun_cmd = 'python %s -i %s -o %s -l %s -m %s -c %s' % (__file__, params['sequences'], params['abrev'],
                                                              params['clade_path'], params['mode'],
                                                              str(params['cpus']))

    if params['long']:
        _rerun_cmd += ' --long'
    if params['region_limit'] != Analysis.REGION_LIMIT_DEFAULT:
        _rerun_cmd += ' --limit %s' % str(params['region_limit'])
    if params['tmp'] != './tmp':
        _rerun_cmd += ' -t %s' % params['tmp']
    if params['target_species']:
        _rerun_cmd += ' -sp %s' % params['target_species']
    if params['ev_cutoff'] != Analysis.EVALUE_DEFAULT:
        _rerun_cmd += ' -e %s' % str(params['ev_cutoff'])
    if params['tarzip']:
        _rerun_cmd += ' -z'
    if params['augustus_parameters']:
        _rerun_cmd += ' --augustus_parameters \'%s\'' % params['augustus_parameters']


def main(show_thread=False):
    """
    This function runs a BUSCO analysis according to the provided parameters.
    See the help for more details:
    ``python BUSCO.py -h``

    :param show_thread:  a bool to append or not the thread name in the logs, e.g. INFO:BUSCO.py:thread_name
    :type show_thread: bool
    :raises SystemExit: if any errors occur
    """

    if show_thread:
        _logger.add_thread_info()

    start_time = time.time()

    # 1) Set-up the parameters
    args = _parse_args()

    try:

        _logger.add_blank_line()
        _logger.info('****************** Start a BUSCO %s analysis, current time: %s ******************'
                     % (VERSION, time.strftime("%m/%d/%Y %H:%M:%S")))
        _check_path_exist(args['in'])
        _check_path_exist(args['clade'])
        params = _define_parameters(args)
        _set_rerun_busco_command(params)

        _logger.info('To reproduce this run: %s' % _rerun_cmd)

        # 2) init the appropriate analysis instance
        analysis = None
        if params['mode'] == 'proteins':
            analysis = GeneSetAnalysis(params)
        elif params['mode'] == 'genome':
            analysis = GenomeAnalysis(params)
        elif params['mode'] == 'tran':
            analysis = TranscriptomeAnalysis(params)

        # 3) Check dependencies
        _logger.info('Check dependencies...')
        analysis.check_dependencies()

        # 4) Check invalid header characters
        _logger.info('Check input file...')
        for line in open(params['sequences']):
            if line.startswith('>'):
                Analysis.check_fasta_header</