statistics.py 144 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 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159
#!/usr/bin/python3

# RNANet statistics
# Developed by Louis Becquey, Khodor Hannoush & Aglaé Tabot, 2019-2021 

# This file computes additional statistics over the produced dataset.
# Run this file if you want the base counts, pair-type counts, identity percents, etc
# in the database.

import getopt, os, pickle, sqlite3, shlex, subprocess, sys, warnings
import numpy as np
import pandas as pd
import threading as th
import scipy.stats as st
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.patches as mpatches
import scipy.cluster.hierarchy as sch
import sklearn
import json
import glob
import pickle
import Bio
from scipy.spatial.distance import squareform
from mpl_toolkits.mplot3d import axes3d
from Bio import AlignIO, SeqIO
from Bio.PDB.MMCIFParser import MMCIFParser
from Bio.PDB.vectors import Vector, calc_angle, calc_dihedral
from functools import partial
from multiprocessing import Pool, Manager
from os import path
from tqdm import tqdm
from collections import Counter
from setproctitle import setproctitle
from RNAnet import Job, read_cpu_number, sql_ask_database, sql_execute, warn, notify, init_worker, trace_unhandled_exceptions
from sklearn.mixture import GaussianMixture
import warnings
from pandas.core.common import SettingWithCopyWarning
from joblib import Parallel, delayed


np.set_printoptions(threshold=sys.maxsize, linewidth=np.inf, precision=8)
path_to_3D_data = "tobedefinedbyoptions"
path_to_seq_data = "tobedefinedbyoptions"
runDir = os.getcwd()
res_thr = 20.0 # default: all structures

LSU_set = ("RF00002", "RF02540", "RF02541", "RF02543", "RF02546")   # From Rfam CLAN 00112
SSU_set = ("RF00177", "RF02542",  "RF02545", "RF01959", "RF01960")  # From Rfam CLAN 00111

@trace_unhandled_exceptions
def reproduce_wadley_results(carbon=4, show=False, sd_range=(1,4), res=2.0):
    """
    Plot the joint distribution of pseudotorsion angles, in a Ramachandran-style graph.
    See Wadley & Pyle (2007).
    Only unique unmapped chains with resolution < res argument are considered.

    Arguments:
    carbon:     1 or 4, use C4' (eta and theta) or C1' (eta_prime and theta_prime)
    show:       True or False, call plt.show() at this end or not
    sd_range:   tuple, set values below avg + sd_range[0] * stdev to 0,
                    and values above avg + sd_range[1] * stdev to avg + sd_range[1] * stdev.
                    This removes noise and cuts too high peaks, to clearly see the clusters.
    res:        Minimal resolution (maximal resolution value, actually) of the structure to 
                    consider its nucleotides.
    """

    os.makedirs(runDir + "/results/figures/wadley_plots/", exist_ok=True)

    if carbon == 4:
        angle = "eta"
        xlabel = "$\\eta=C_4'^{i-1}-P^i-C_4'^i-P^{i+1}$"
        ylabel = "$\\theta=P^i-C_4'^i-P^{i+1}-C_4'^{i+1}$"
    elif carbon == 1:
        angle = "eta_prime"
        xlabel = "$\\eta'=C_1'^{i-1}-P^i-C_1'^i-P^{i+1}$"
        ylabel = "$\\theta'=P^i-C_1'^i-P^{i+1}-C_1'^{i+1}$"
    else:
        exit("You overestimate my capabilities !")

    
    if not path.isfile(runDir + f"/data/wadley_kernel_{angle}_{res}A.npz"):

        # Get a worker number to position the progress bar
        global idxQueue
        thr_idx = idxQueue.get()
        setproctitle(f"RNANet statistics.py Worker {thr_idx+1} reproduce_wadley_results(carbon={carbon})")

        pbar = tqdm(total=2, desc=f"Worker {thr_idx+1}: eta/theta C{carbon} kernels", unit="kernel", position=thr_idx+1, leave=False)

        # Extract the angle values of c2'-endo and c3'-endo nucleotides
        with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
            conn.execute('pragma journal_mode=wal')
            df = pd.read_sql(f"""SELECT {angle}, th{angle} 
                                 FROM (
                                    SELECT chain_id FROM chain JOIN structure ON chain.structure_id = structure.pdb_id
                                    WHERE chain.rfam_acc = 'unmappd' AND structure.resolution <= {res} AND issue = 0
                                 ) AS c NATURAL JOIN nucleotide
                                 WHERE puckering="C2'-endo" 
                                    AND {angle} IS NOT NULL 
                                    AND th{angle} IS NOT NULL;""", conn)
            c2_endo_etas = df[angle].values.tolist()
            c2_endo_thetas = df["th"+angle].values.tolist()
            df = pd.read_sql(f"""SELECT {angle}, th{angle} 
                                 FROM (
                                    SELECT chain_id FROM chain JOIN structure ON chain.structure_id = structure.pdb_id
                                    WHERE chain.rfam_acc = 'unmappd' AND structure.resolution <= {res} AND issue = 0
                                 ) AS c NATURAL JOIN nucleotide 
                                 WHERE form = '.' 
                                    AND puckering="C3'-endo" 
                                    AND {angle} IS NOT NULL 
                                    AND th{angle} IS NOT NULL;""", conn)
            c3_endo_etas = df[angle].values.tolist()
            c3_endo_thetas = df["th"+angle].values.tolist()
        
        # Create arrays with (x,y) coordinates of the points
        values_c3 = np.vstack([c3_endo_etas, c3_endo_thetas])
        values_c2 = np.vstack([c2_endo_etas, c2_endo_thetas])

        # Approximate the Densité by a gaussian kernel
        kernel_c3 = st.gaussian_kde(values_c3)
        kernel_c2 = st.gaussian_kde(values_c2)

        # Create 100x100 regular (x,y,z) values for the plot
        xx, yy = np.mgrid[0:2*np.pi:100j, 0:2*np.pi:100j]
        positions = np.vstack([xx.ravel(), yy.ravel()])
        f_c3 = np.reshape(kernel_c3(positions).T, xx.shape)
        pbar.update(1)
        f_c2 = np.reshape(kernel_c2(positions).T, xx.shape)
        pbar.update(1)

        # Save the data to an archive for later use without the need to recompute
        np.savez(runDir + f"/data/wadley_kernel_{angle}_{res}A.npz",
                  c3_endo_e=c3_endo_etas, c3_endo_t=c3_endo_thetas,
                  c2_endo_e=c2_endo_etas, c2_endo_t=c2_endo_thetas,
                  kernel_c3=f_c3, kernel_c2=f_c2)
        pbar.close()
        idxQueue.put(thr_idx)
    else:
        setproctitle(f"RNANet statistics.py reproduce_wadley_results(carbon={carbon})")

        f = np.load(runDir + f"/data/wadley_kernel_{angle}_{res}A.npz")
        c2_endo_etas = f["c2_endo_e"]
        c3_endo_etas = f["c3_endo_e"]
        c2_endo_thetas = f["c2_endo_t"]
        c3_endo_thetas = f["c3_endo_t"]
        f_c3 = f["kernel_c3"]
        f_c2 = f["kernel_c2"]
        xx, yy = np.mgrid[0:2*np.pi:100j, 0:2*np.pi:100j]

    # notify(f"Kernel computed for {angle}/th{angle} (or loaded from file).")

    # exact counts:
    hist_c2, xedges, yedges = np.histogram2d(c2_endo_etas, c2_endo_thetas, bins=int(2*np.pi/0.1), 
                                             range=[[0, 2*np.pi], [0, 2*np.pi]])
    hist_c3, xedges, yedges = np.histogram2d(c3_endo_etas, c3_endo_thetas, bins=int(2*np.pi/0.1), 
                                             range=[[0, 2*np.pi], [0, 2*np.pi]])
    cmap = cm.get_cmap("jet")
    color_values = cmap(hist_c3.ravel()/hist_c3.max())

    for x, y, hist, f, l in zip( (c3_endo_etas, c2_endo_etas), 
                                 (c3_endo_thetas, c2_endo_thetas), 
                                 (hist_c3, hist_c2), 
                                 (f_c3, f_c2), ("c3","c2")):
        # cut hist and kernel
        hist_sup_thr = hist.mean() + sd_range[1]*hist.std()
        hist_cut = np.where( hist > hist_sup_thr, hist_sup_thr, hist)
        f_sup_thr = f.mean() + sd_range[1]*f.std()
        f_low_thr = f.mean() + sd_range[0]*f.std()
        f_cut = np.where(f > f_sup_thr, f_sup_thr, f)
        f_cut = np.where(f_cut < f_low_thr, 0, f_cut)
        levels = [ f.mean()+f.std(), f.mean()+2*f.std(), f.mean()+4*f.std()]

        # histogram:
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1], indexing="ij")
        ax.bar3d(xpos.ravel(), ypos.ravel(), 0.0, 0.09, 0.09, hist_cut.ravel(), color=color_values, zorder="max")
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        fig.savefig(runDir + f"/results/figures/wadley_plots/wadley_hist_{angle}_{l}_{res}A.png")
        if show:
            fig.show()
        plt.close()

        # Smoothed joint distribution
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.plot_surface(xx, yy, f_cut, cmap=cm.get_cmap("coolwarm"), linewidth=0, antialiased=True)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        fig.savefig(runDir + f"/results/figures/wadley_plots/wadley_distrib_{angle}_{l}_{res}A.png")
        if show:
            fig.show()
        plt.close()

        # 2D Wadley plot
        fig = plt.figure(figsize=(5,5))
        ax = fig.gca()
        ax.scatter(x, y, s=1, alpha=0.1)
        ax.contourf(xx, yy, f, alpha=0.5, cmap=cm.get_cmap("coolwarm"), levels=levels, extend="max")
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        fig.savefig(runDir + f"/results/figures/wadley_plots/wadley_{angle}_{l}_{res}A.png")
        if show:
            fig.show()
        plt.close()

    setproctitle(f"RNANet statistics.py reproduce_wadley_results(carbon={carbon}) finished")

    # print(f"[{worker_nbr}]\tComputed joint distribution of angles (C{carbon}) and saved the figures.")

@trace_unhandled_exceptions
def stats_len():
    """Plots statistics on chain lengths in RNA families.
    Uses all chains mapped to a family including copies, inferred or not.
    
    REQUIRES tables chain, nucleotide up to date.
    """

    setproctitle(f"RNANet statistics.py stats_len({res_thr})")
    
    # Get a worker number to position the progress bar
    global idxQueue
    thr_idx = idxQueue.get()

    cols = []
    lengths = []
    
    for f in tqdm(famlist, position=thr_idx+1, desc=f"Worker {thr_idx+1}: Average chain lengths", unit="family", leave=False):

        # Define a color for that family in the plot
        if f in LSU_set:
            cols.append("red") # LSU
        elif f in SSU_set:
            cols.append("blue") # SSU
        elif f in ["RF00001"]:
            cols.append("green")
        elif f in ["RF00005"]:
            cols.append("orange")
        else:
            cols.append("grey")

        # Get the lengths of chains
        with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
            conn.execute('pragma journal_mode=wal')
            l = [ x[0] for x in sql_ask_database(conn, f"""SELECT COUNT(index_chain) 
                                                            FROM (
                                                                SELECT chain_id 
                                                                FROM chain JOIN structure ON chain.structure_id = structure.pdb_id 
                                                                WHERE rfam_acc='{f}' AND resolution <= {res_thr}
                                                            ) NATURAL JOIN nucleotide 
                                                            GROUP BY chain_id;""", warn_every=0) ]
        lengths.append(l) # list of chain lengths from the family

    # Plot the figure
    fig = plt.figure(figsize=(10,3))
    ax = fig.gca()
    ax.hist(lengths, bins=100, stacked=True, log=True, color=cols, label=famlist)
    ax.set_xlabel("Sequence length (nucleotides)", fontsize=8)
    ax.set_ylabel("Number of 3D chains", fontsize=8)
    ax.set_xlim(left=-150)
    ax.tick_params(axis='both', which='both', labelsize=8)
    fig.tight_layout()

    # Draw the legend
    fig.subplots_adjust(right=0.78)
    filtered_handles = [mpatches.Patch(color='red'), mpatches.Patch(color='white'), mpatches.Patch(color='white'), mpatches.Patch(color='white'),
                        mpatches.Patch(color='blue'), mpatches.Patch(color='white'), mpatches.Patch(color='white'),
                        mpatches.Patch(color='green'), mpatches.Patch(color='white'),
                        mpatches.Patch(color='orange'), mpatches.Patch(color='white'),
                        mpatches.Patch(color='grey')]
    filtered_labels = ['Large Ribosomal Subunits', '(RF00002, RF02540,', 'RF02541, RF02543,', 'RF02546)',
                        'Small Ribosomal Subunits','(RF01960, RF00177,', 'RF02545)',
                       '5S rRNA', '(RF00001)', 
                       'tRNA', '(RF00005)', 
                       'Other']
    ax.legend(filtered_handles, filtered_labels, loc='right', 
                ncol=1, fontsize='small', bbox_to_anchor=(1.3, 0.5))

    # Save the figure

    fig.savefig(runDir + f"/results/figures/lengths_{res_thr}A.png")
    idxQueue.put(thr_idx) # replace the thread index in the queue
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")
    # notify("Computed sequence length statistics and saved the figure.")

def format_percentage(tot, x):
        if not tot:
            return '0 %'
        x = 100*x/tot
        if x >= 0.01:
            x = "%.2f" % x
        elif x == 0:
            return "0 %"
        else:
            x = "<.01"
        return x + '%'

@trace_unhandled_exceptions
def stats_freq():
    """Computes base frequencies in all RNA families.
    Uses all chains mapped to a family including copies, inferred or not.

    Outputs results/frequencies.csv
    REQUIRES tables chain, nucleotide up to date."""

    # Get a worker number to position the progress bar
    global idxQueue
    thr_idx = idxQueue.get()

    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} stats_freq()")

    # Initialize a Counter object for each family
    freqs = {}
    for f in famlist:
        freqs[f] = Counter()

    # List all nt_names happening within a RNA family and store the counts in the Counter
    for f in tqdm(famlist, position=thr_idx+1, desc=f"Worker {thr_idx+1}: Base frequencies", unit="family", leave=False):
        with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
            conn.execute('pragma journal_mode=wal')
            counts = dict(sql_ask_database(conn, f"SELECT nt_name, COUNT(nt_name) FROM (SELECT chain_id from chain WHERE rfam_acc='{f}') NATURAL JOIN nucleotide GROUP BY nt_name;", warn_every=0))
        freqs[f].update(counts)
    
    # Create a pandas DataFrame, and save it to CSV.
    df = pd.DataFrame()
    for f in tqdm(famlist, position=thr_idx+1, desc=f"Worker {thr_idx+1}: Base frequencies", unit="family", leave=False):
        tot = sum(freqs[f].values())
        df = pd.concat([ df, pd.DataFrame([[ format_percentage(tot, x) for x in freqs[f].values() ]], columns=list(freqs[f]), index=[f]) ])
    df = df.fillna(0)
    df.to_csv(runDir + "/results/frequencies.csv")    
    idxQueue.put(thr_idx) # replace the thread index in the queue
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")
    # notify("Saved nucleotide frequencies to CSV file.")

@trace_unhandled_exceptions
def parallel_stats_pairs(f):
    """Counts occurrences of intra-chain base-pair types in one RNA family

    REQUIRES tables chain, nucleotide up-to-date.""" 

    if path.isfile(runDir + "/data/"+f+"_pairs.csv") and path.isfile(runDir + "/data/"+f+"_counts.csv"):
        return

    # Get a worker number to position the progress bar
    global idxQueue
    thr_idx = idxQueue.get()

    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} p_stats_pairs({f})")

    chain_id_list = mappings_list[f]
    data = []
    sqldata = []
    for cid in tqdm(chain_id_list, position=thr_idx+1, desc=f"Worker {thr_idx+1}: {f} basepair types", unit="chain",leave=False):
        with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
            conn.execute('pragma journal_mode=wal')
            # Get comma separated lists of basepairs per nucleotide
            interactions = pd.DataFrame(
                            sql_ask_database(conn, f"SELECT nt_code as nt1, index_chain, paired, pair_type_LW FROM nucleotide WHERE chain_id='{cid}';"), 
                            columns = ["nt1", "index_chain", "paired", "pair_type_LW"]
                           )
        # expand the comma-separated lists in real lists
        expanded_list = pd.concat([ pd.DataFrame({  'nt1':[ row["nt1"] for x in row["paired"].split(',') ],
                                                    'index_chain':[ row['index_chain'] for x in row["paired"].split(',') ],
                                                    'paired':row['paired'].split(','), 
                                                    'pair_type_LW':row['pair_type_LW'].split(',') 
                                                }) 
                                    for _, row in interactions.iterrows() 
                                ]).reset_index(drop=True)

        # Add second nucleotide
        nt2 = []
        for _, row in expanded_list.iterrows():
            if row.paired in ['', '0']:
                nt2.append('')
            else:
                try:
                    n = expanded_list[expanded_list.index_chain == int(row.paired)].nt1.tolist()[0]
                    nt2.append(n)
                except IndexError:
                    print(cid, flush=True)
        try:
            expanded_list["nt2"] = nt2
        except ValueError:
            print(cid, flush=True)
            print(expanded_list, flush=True)
            return 0,0

        # keep only intra-chain interactions
        expanded_list = expanded_list[ ~expanded_list.paired.isin(['0','']) ]
        expanded_list["nts"] = expanded_list["nt1"] + expanded_list["nt2"]
        
        # Get basepair type
        expanded_list["basepair"] = np.where(expanded_list.nts.isin(["AU","UA"]), "AU",
                                        np.where(expanded_list.nts.isin(["GC","CG"]), "GC",
                                            np.where(expanded_list.nts.isin(["GU","UG"]), "Wobble","Other")
                                        )
                                    )
        expanded_list = expanded_list[["basepair", "pair_type_LW"]]

        # Update the database
        vlcnts = expanded_list.pair_type_LW.value_counts()
        sqldata.append(   ( vlcnts.at["cWW"]/2 if "cWW" in vlcnts.index else 0, 
                            vlcnts.at["cWH"] if "cWH" in vlcnts.index else 0, 
                            vlcnts.at["cWS"] if "cWS" in vlcnts.index else 0, 
                            vlcnts.at["cHH"]/2 if "cHH" in vlcnts.index else 0, 
                            vlcnts.at["cHS"] if "cHS" in vlcnts.index else 0, 
                            vlcnts.at["cSS"]/2 if "cSS" in vlcnts.index else 0, 
                            vlcnts.at["tWW"]/2 if "tWW" in vlcnts.index else 0, 
                            vlcnts.at["tWH"] if "tWH" in vlcnts.index else 0, 
                            vlcnts.at["tWS"] if "tWS" in vlcnts.index else 0, 
                            vlcnts.at["tHH"]/2 if "tHH" in vlcnts.index else 0, 
                            vlcnts.at["tHS"] if "tHS" in vlcnts.index else 0, 
                            vlcnts.at["tSS"]/2 if "tSS" in vlcnts.index else 0, 
                            int(sum(vlcnts.loc[[ str(x) for x in vlcnts.index if "." in str(x)]])/2), 
                            cid) )

        data.append(expanded_list)

    # Update the database
    with sqlite3.connect(runDir + "/results/RNANet.db", isolation_level=None) as conn:
        conn.execute('pragma journal_mode=wal') # Allow multiple other readers to ask things while we execute this writing query
        sql_execute(conn, """UPDATE chain SET pair_count_cWW = ?, pair_count_cWH = ?, pair_count_cWS = ?, pair_count_cHH = ?,
                                pair_count_cHS = ?, pair_count_cSS = ?, pair_count_tWW = ?, pair_count_tWH = ?, pair_count_tWS = ?, 
                                pair_count_tHH = ?, pair_count_tHS = ?, pair_count_tSS = ?, pair_count_other = ? WHERE chain_id = ?;""", many=True, data=sqldata, warn_every=0)

    # merge all the dataframes from all chains of the family
    expanded_list = pd.concat(data)

    # Count each pair type
    vcnts = expanded_list.pair_type_LW.value_counts()

    # Add these new counts to the family's counter
    cnt = Counter()
    cnt.update(dict(vcnts))

    # Create an output DataFrame
    f_df = pd.DataFrame([[ x for x in cnt.values() ]], columns=list(cnt), index=[f])
    f_df.to_csv(runDir + f"/data/{f}_counts.csv")
    expanded_list.to_csv(runDir + f"/data/{f}_pairs.csv")
    
    idxQueue.put(thr_idx) # replace the thread index in the queue
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")

@trace_unhandled_exceptions
def to_id_matrix(f):
    """
    Runs esl-alipid on the filtered alignment to get an identity matrix.
    """
    if path.isfile("data/"+f+".npy"):
        return 0
  
    # Get a worker number to position the progress bar
    global idxQueue
    thr_idx = idxQueue.get()

    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} to_id_matrix({f})")

    if not path.isfile(f"{path_to_seq_data}/realigned/{f}_3d_only.stk"):
        warn(f"File not found: {path_to_seq_data}/realigned/{f}_3d_only.stk")
    align = AlignIO.read(f"{path_to_seq_data}/realigned/{f}_3d_only.stk", "stockholm")
    names = [ x.id for x in align if '[' in x.id ]
    del align
    
    pbar = tqdm(total = len(names)*(len(names)-1)*0.5, position=thr_idx+1, desc=f"Worker {thr_idx+1}: {f} idty matrix", unit="comparisons", leave=False)
    pbar.update(0)
    
    # Prepare the job
    process = subprocess.Popen(shlex.split(f"esl-alipid --rna --noheader --informat stockholm {path_to_seq_data}/realigned/{f}_3d_only.stk"), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    id_matrix = np.zeros((len(names), len(names)))
    cnt = 0
    while not cnt or process.poll() is None:
        output = process.stdout.read()
        if output:
            lines = output.strip().split(b'\n')
            for l in lines:
                cnt += 1
                line = l.split()
                s1 = line[0].decode('utf-8')
                s2 = line[1].decode('utf-8')
                score = line[2].decode('utf-8')
                id1 = names.index(s1)
                id2 = names.index(s2)
                id_matrix[id1, id2] = float(score)
                pbar.update(1)
    if cnt != len(names)*(len(names)-1)*0.5:
        warn(f"{f} got {cnt} updates on {len(names)*(len(names)-1)*0.5}")
    if process.poll() != 0:
        l = process.stderr.read().strip().split(b'\n')
        warn("\n".join([ line.decode('utf-8') for line in l ]))
    pbar.close()

    np.save("data/"+f+".npy", id_matrix)

    idxQueue.put(thr_idx) # replace the thread index in the queue
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")
    return 0

@trace_unhandled_exceptions
def seq_idty():
    """Computes identity matrices for each of the RNA families.
    
    REQUIRES temporary results files in data/*.npy
    REQUIRES tables chain, family up to date."""

    # load distance matrices
    fams_to_plot = [ f for f in famlist if f not in ignored ]
    fam_arrays = []
    for f in fams_to_plot:
        if path.isfile("data/"+f+".npy"):
            fam_arrays.append(np.load("data/"+f+".npy") / 100.0)  # normalize percentages in [0,1]
        else:
            warn("data/"+f+".npy not found !")
            fam_arrays.append(np.array([]))

    # Update database with identity percentages
    conn = sqlite3.connect(runDir + "/results/RNANet.db")
    conn.execute('pragma journal_mode=wal')
    for f, D in zip(fams_to_plot, fam_arrays):
        if not len(D): continue
        if D.shape[0] > 1:
            a = np.sum(D) * 2 / D.shape[0] / (D.shape[0] - 1)    # SUM(D) / (n(n-1)/2)
        else:
            a = D[0][0]
        conn.execute(f"UPDATE family SET idty_percent = {round(float(a),2)} WHERE rfam_acc = '{f}';")
    conn.commit()
    conn.close()

    # Plots plots plots
    fig, axs = plt.subplots(4,17, figsize=(17,5.75))
    axs = axs.ravel()
    [axi.set_axis_off() for axi in axs]
    im = "" # Just to declare the variable, it will be set in the loop
    for f, D, ax in zip(fams_to_plot, fam_arrays, axs):
        D = D + D.T         # Copy the lower triangle to upper, to get a symetrical matrix
        if D.shape[0] > 2:  # Cluster only if there is more than 2 sequences to organize
            D = 1.0 - D
            np.fill_diagonal(D, 0.0)
            condensedD = squareform(D)

            # Compute basic dendrogram by Ward's method
            Y = sch.linkage(condensedD, method='ward')
            Z = sch.dendrogram(Y, orientation='left', no_plot=True)

            # Reorganize rows and cols
            idx1 = Z['leaves']
            D = D[idx1[::-1],:]
            D = D[:,idx1[::-1]]
            D = 1.0 - D
        elif D.shape[0] == 2:
            np.fill_diagonal(D, 1.0) # the diagonal has been ignored until now
        ax.text(np.floor(D.shape[0]/2.0)-(0.5 if not D.shape[0]%2 else 0), -0.5, f + "\n(" + str(D.shape[0]) + " chains)", 
                fontsize=9, horizontalalignment = 'center', verticalalignment='bottom')
        im = ax.matshow(D, vmin=0, vmax=1)

    fig.tight_layout()
    fig.subplots_adjust(hspace=0.3, wspace=0.1)
    fig.colorbar(im, ax=axs[-4], shrink=0.8)
    fig.savefig(runDir + f"/results/figures/distances_{res_thr}.png")
    print("> Computed all identity matrices and saved the figure.", flush=True)

@trace_unhandled_exceptions
def stats_pairs():
    """Counts occurrences of intra-chain base-pair types in RNA families

    Creates a temporary results file in data/pair_counts.csv, and a results file in results/pairings.csv.
    REQUIRES tables chain, nucleotide up-to-date.""" 
    
    setproctitle(f"RNANet statistics.py stats_pairs()")

    def line_format(family_data):
        return family_data.apply(partial(format_percentage, sum(family_data)))

    if not path.isfile("data/pair_counts_{res_thr}.csv"):
        results = []
        allpairs = []
        for f in famlist:
            newpairs = pd.read_csv(runDir + f"/data/{f}_pairs.csv", index_col=0)
            fam_df = pd.read_csv(runDir + f"/data/{f}_counts.csv", index_col=0)
            results.append(fam_df)
            allpairs.append(newpairs)
            subprocess.run(["rm", "-f", runDir + f"/data/{f}_pairs.csv"])
            subprocess.run(["rm", "-f", runDir + f"/data/{f}_counts.csv"])
        all_pairs = pd.concat(allpairs)
        df = pd.concat(results).fillna(0)
        df.to_csv(runDir + f"/data/pair_counts_{res_thr}.csv")
        all_pairs.to_csv(runDir + f"/data/all_pairs_{res_thr}.csv")
    else:
        df = pd.read_csv(runDir + f"/data/pair_counts_{res_thr}.csv", index_col=0)
        all_pairs = pd.read_csv(runDir + f"/data/all_pairs_{res_thr}.csv", index_col=0)

    crosstab = pd.crosstab(all_pairs.pair_type_LW, all_pairs.basepair)
    col_list = [ x for x in df.columns if '.' in x ]

    # Remove not very well defined pair types (not in the 12 LW types)
    df['other'] = df[col_list].sum(axis=1)
    df.drop(col_list, axis=1, inplace=True)
    crosstab = crosstab.append(crosstab.loc[col_list].sum(axis=0).rename("non-LW"))
    
    # drop duplicate types
    # The twelve Leontis-Westhof types are
    # cWW cWH cWS cHH cHS cSS (do not count cHW cSW and cSH, they are the same as their opposites)
    # tWW tWH tWS tHH tHS tSS (do not count tHW tSW and tSH, they are the same as their opposites)
    df = df.drop([ x for x in [ "cHW", "tHW", "cSW", "tSW", "cHS", "tHS"] if x in df.columns], axis=1)
    crosstab = crosstab.loc[[ x for x in ["cWW","cWH","cWS","cHH","cHS","cSS","tWW","tWH","tWS","tHH","tHS","tSS","non-LW"] if x in crosstab.index]]
    df.loc[:,[x for x in ["cWW", "tWW", "cHH", "tHH", "cSS", "tSS", "other"] if x in df.columns] ] /= 2
    crosstab.loc[["cWW", "tWW", "cHH", "tHH", "cSS", "tSS", "non-LW"]] /= 2

    # Compute total row
    total_series = df.sum(numeric_only=True).rename("TOTAL")
    df = df.append(total_series)

    # format as percentages
    df = df.apply(line_format, axis=1)

    # reorder columns
    df.sort_values("TOTAL", axis=1, inplace=True, ascending=False)
    crosstab = crosstab[["AU", "GC", "Wobble", "Other"]]

    # Save to CSV
    df.to_csv(runDir + "/results/pair_types.csv")

    # Plot barplot of overall types
    ax = crosstab.plot(figsize=(8,5), kind='bar', stacked=True, log=False, fontsize=13)
    ax.set_ylabel("Number of observations (millions)", fontsize=13)
    ax.set_xlabel(None)
    plt.subplots_adjust(left=0.1, bottom=0.16, top=0.95, right=0.99)
    plt.savefig(runDir + f"/results/figures/pairings_{res_thr}.png")

    notify("Computed nucleotide statistics and saved CSV and PNG file.")

@trace_unhandled_exceptions
def per_chain_stats():
    """Computes per-chain frequencies and base-pair type counts.

    REQUIRES tables chain, nucleotide up to date. """
    
    setproctitle(f"RNANet statistics.py per_chain_stats()")

    with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
        conn.execute('pragma journal_mode=wal')
        # Compute per-chain nucleotide frequencies
        df = pd.read_sql("SELECT SUM(is_A) as A, SUM(is_C) AS C, SUM(is_G) AS G, SUM(is_U) AS U, SUM(is_other) AS O, chain_id FROM nucleotide GROUP BY chain_id;", conn)
        df["total"] = pd.Series(df.A + df.C + df.G + df.U + df.O, dtype=np.float64)
        df[['A','C','G','U','O']] = df[['A','C','G','U','O']].div(df.total, axis=0)
        df = df.drop("total", axis=1)

        # Set the values
        sql_execute(conn, "UPDATE chain SET chain_freq_A = ?, chain_freq_C = ?, chain_freq_G = ?, chain_freq_U = ?, chain_freq_other = ? WHERE chain_id= ?;",
                          many=True, data=list(df.to_records(index=False)), warn_every=10)
    print("> Updated the database with per-chain base frequencies", flush=True)

@trace_unhandled_exceptions
def general_stats():
    """
    Number of structures as function of the resolution threshold
    Number of Rfam families as function of the resolution threshold
    """

    setproctitle(f"RNANet statistics.py general_stats()")

    reqs = [
        # unique unmapped chains with no issues
        """ SELECT distinct pdb_id, chain_name, exp_method, resolution
            FROM chain JOIN structure ON chain.structure_id = structure.pdb_id
            WHERE rfam_acc = 'unmappd' AND ISSUE=0;""",

        # unique mapped chains with no issues
        """ SELECT distinct pdb_id, chain_name, exp_method, resolution
            FROM chain JOIN structure ON chain.structure_id = structure.pdb_id
            WHERE rfam_acc != 'unmappd' AND ISSUE=0;""",

        # mapped chains with no issues
        """ SELECT pdb_id, chain_name, inferred, rfam_acc, pdb_start, pdb_end, exp_method, resolution
            FROM chain JOIN structure ON chain.structure_id = structure.pdb_id
            WHERE rfam_acc != 'unmappd' AND ISSUE=0;""",

        # mapped chains with no issues that are all inferred
        """ SELECT DISTINCT pdb_id, c.chain_name, exp_method, resolution
            FROM (
                SELECT inferred, rfam_acc, pdb_start, pdb_end, chain.structure_id, chain.chain_name, r.redundancy, r.inf_redundancy
                FROM chain 
                JOIN (SELECT structure_id, chain_name, COUNT(distinct rfam_acc) AS redundancy, SUM(inferred) AS inf_redundancy 
                        FROM chain 
                        WHERE rfam_acc != 'unmappd' AND issue=0 
                        GROUP BY structure_id, chain_name
                ) AS r ON chain.structure_id=r.structure_id AND chain.chain_name = r.chain_name 
                WHERE r.redundancy=r.inf_redundancy AND rfam_acc != 'unmappd' and issue=0
            ) AS c
            JOIN structure ON c.structure_id=structure.pdb_id;""",

        # Number of mapped chains (not inferred)
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 0);""",

        # Number of unique mapped chains (not inferred)
        """SELECT count(*) FROM (SELECT DISTINCT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 0);""",

        # Number of mapped chains (inferred)
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 1);""",

        # Number of unique mapped chains (inferred)
        """SELECT count(*) FROM (SELECT DISTINCT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 1);""",

        # Number of mapped chains inferred once
        """SELECT count(*) FROM (
                SELECT structure_id, chain_name, COUNT(DISTINCT rfam_acc) as c 
                FROM chain where rfam_acc!='unmappd' and inferred=1 
                GROUP BY structure_id, chain_name
            ) WHERE c=1;""",

        # Number of mapped chains inferred twice
        """select count(*) from (
                select structure_id, chain_name, count(distinct rfam_acc) as c 
                from chain where rfam_acc!='unmappd' and inferred=1 
                group by structure_id, chain_name
            ) where c=2;""",

        # Number of mapped chains inferred 3 times or more
        """select count(*) from (
                select structure_id, chain_name, count(distinct rfam_acc) as c 
                from chain where rfam_acc!='unmappd' and inferred=1 
                group by structure_id, chain_name
            ) where c>2;""",

        # Number of chains both mapped with and without inferrence
        """ SELECT COUNT(*) FROM (
                SELECT structure_id, chain_name, sum(inferred) AS s, COUNT(rfam_acc) AS c 
                FROM chain 
                WHERE rfam_acc!='unmappd' 
                GROUP BY structure_id, chain_name
            ) 
            WHERE s < c AND s > 0;""",
        
        # Number of mapped chains (total)
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd');""",

        # Number of unique mapped chains
        """SELECT count(*) FROM (SELECT DISTINCT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd');""",

        # Number of unmapped chains
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc = 'unmappd');""",
        
        # Number of mapped chains without issues (not inferred)
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 0 AND issue = 0);""",

        # Number of unique mapped chains without issues (not inferred)
        """SELECT count(*) FROM (SELECT DISTINCT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 0 AND issue = 0);""",

        # Number of mapped chains without issues (inferred)
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 1 AND issue=0);""",

        # Number of unique mapped chains without issues (inferred)
        """SELECT count(*) FROM (SELECT DISTINCT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND inferred = 1 AND issue=0);""",

        # Number of mapped chains without issues (total)
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND issue=0);""",

        # Number of unique mapped chains without issues
        """SELECT count(*) FROM (SELECT DISTINCT structure_id, chain_name FROM chain WHERE rfam_acc != 'unmappd' AND issue=0);""",

        # Number of unmapped chains without issues
        """SELECT count(*) FROM (SELECT structure_id, chain_name FROM chain WHERE rfam_acc = 'unmappd' AND issue=0);"""
    ]

    answers = []
    with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
        conn.execute('pragma journal_mode=wal')
        for r in reqs:
            answers.append(pd.read_sql(r, conn))
    df_unique = answers[0]
    df_mapped_unique = answers[1]
    df_mapped_copies = answers[2]
    df_inferred_only_unique = answers[3]
    print()
    print("> found", answers[4].iloc[0][0], f"chains ({answers[5].iloc[0][0]} unique chains) that are mapped thanks to Rfam. Removing chains with issues, only {answers[15].iloc[0][0]} ({answers[16].iloc[0][0]} unique)")
    if answers[4].iloc[0][0] != answers[5].iloc[0][0]:
        print("\t> This happens because different parts of the same chain can be mapped to different families.")
    print("> found", answers[6].iloc[0][0], f"chains ({answers[7].iloc[0][0]} unique chains) that are mapped by inferrence. Removing chains with issues, only {answers[17].iloc[0][0]} ({answers[18].iloc[0][0]} unique).")
    print("\t> ", answers[8].iloc[0][0], "chains are mapped only once,")
    print("\t> ", answers[9].iloc[0][0], "are mapped to 2 families,")
    print("\t> ", answers[10].iloc[0][0], "are mapped to 3 or more.")
    print("> Among them,", answers[11].iloc[0][0], "chains are mapped both with families found on Rfam and by inferrence.")
    if answers[11].iloc[0][0]:
        print("\t> this is normal if you used option -f (--full-inference). Otherwise, there might be a problem.")
    print("> TOTAL:", answers[12].iloc[0][0], f"chains ({answers[13].iloc[0][0]} unique chains) mapped to a family. Removing chains with issues, only {answers[19].iloc[0][0]} ({answers[20].iloc[0][0]} unique).")
    print("> TOTAL:", answers[14].iloc[0][0], f"unmapped chains. Removing chains with issues, {answers[21].iloc[0][0]}.")
    if answers[14].iloc[0][0]:
        print("\t> this is normal if you used option --no-homology. Otherwise, there might be a problem.")
    print()

    ##########################################
    # plot N = f(resolution, exp_method)
    ##########################################

    methods = df_unique.exp_method.unique()

    fig, axs = plt.subplots(1+len(methods), 3, figsize=(15,5*(1+len(methods))), sharex=True)
    df_unique.sort_values('resolution', inplace=True, ignore_index=True)
    df_mapped_unique.sort_values('resolution', inplace=True, ignore_index=True)
    df_inferred_only_unique.sort_values('resolution', inplace=True, ignore_index=True)
    df_mapped_copies.sort_values('resolution', inplace=True, ignore_index=True)
    max_res = max(df_unique.resolution)
    max_structs = max(len(df_mapped_copies.index), len(df_unique.index))
    colors = np.linspace(0,1,1+len(methods))
    plt.xticks( np.arange(0, max_res+2, 2.0).tolist(),  np.arange(0, max_res+2, 2.0).tolist() )

    axs[0][0].grid(axis='y', ls='dotted', lw=1)
    axs[0][0].hist(df_unique.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 1, colors[0], 1), label='distribution')
    axs[0][0].hist(df_unique.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 0, colors[0], 0.5), cumulative=True, label='cumulative')
    axs[0][0].text(0.95*max_res, 0.95*len(df_unique.resolution), "%d " %  len(df_unique.resolution), 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
    axs[0][0].set_ylabel("ALL", fontsize=14)
    axs[0][0].set_title("Number of unique RNA chains", fontsize=14)
    axs[0][0].set_ylim((0, max_structs * 1.05))
    axs[0][0].legend(loc="lower right", fontsize=14)

    axs[0][1].grid(axis='y', ls='dotted', lw=1)
    axs[0][1].set_yticklabels([])
    axs[0][1].hist(df_mapped_unique.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 1, colors[0], 1), label='distribution')
    axs[0][1].hist(df_mapped_unique.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 0, colors[0], 0.5), cumulative=True, label='cumulative')
    axs[0][1].hist(df_inferred_only_unique.resolution, bins=np.arange(0, max_res, 0.5), fc=(0.2, 0, colors[0], 0.5), cumulative=True, label='only by inference')
    axs[0][1].text(0.95*max_res, 0.95*len(df_mapped_unique.resolution), "%d " %  len(df_mapped_unique.resolution), 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
    axs[0][1].set_title(r"Number of unique RNA chains\nmapped to $\geq 1$ family", fontsize=14)
    axs[0][1].set_ylim((0, max_structs * 1.05))
    axs[0][1].legend(loc="upper left", fontsize=14)

    axs[0][2].grid(axis='y', ls='dotted', lw=1)
    axs[0][2].set_yticklabels([])
    axs[0][2].hist(df_mapped_copies.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 1, colors[0], 1), label='distribution')
    axs[0][2].hist(df_mapped_copies.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 0, colors[0], 0.5), cumulative=True, label='cumulative')
    axs[0][2].hist(df_mapped_copies[df_mapped_copies.inferred == 1].resolution, bins=np.arange(0, max_res, 0.5), fc=(0.2, 0, colors[0], 0.5), cumulative=True, label='inferred')
    axs[0][2].text(0.95*max_res, 0.95*len(df_mapped_copies.resolution), "%d " %  len(df_mapped_copies.resolution), 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
    axs[0][2].set_title("Number of RNA chains mapped to a\nfamily (with copies)", fontsize=14)
    axs[0][2].legend(loc="upper left", fontsize=14)
    axs[0][2].set_ylim((0, max_structs * 1.05))

    for i,m in enumerate(methods):
        df_unique_m = df_unique[df_unique.exp_method == m]
        df_mapped_unique_m = df_mapped_unique[df_mapped_unique.exp_method == m]
        df_inferred_only_unique_m = df_inferred_only_unique[df_inferred_only_unique.exp_method == m]
        df_mapped_copies_m = df_mapped_copies[ df_mapped_copies.exp_method == m]
        max_structs = max(len(df_mapped_copies_m.index), len(df_unique_m.index))
        print("> found", max_structs, "structures with method", m, flush=True)

        axs[1+i][0].grid(axis='y', ls='dotted', lw=1)
        axs[1+i][0].hist(df_unique_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 1, colors[1+i], 1), label='distribution')
        axs[1+i][0].hist(df_unique_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 0, colors[1+i], 0.5), cumulative=True, label='cumulative')
        axs[1+i][0].text(0.95*max_res, 0.95*len(df_unique_m.resolution), "%d " %  len(df_unique_m.resolution), 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
        axs[1+i][0].set_ylim((0, max_structs * 1.05))
        axs[1+i][0].set_ylabel(m, fontsize=14)
        axs[1+i][0].legend(loc="lower right", fontsize=14)

        axs[1+i][1].grid(axis='y', ls='dotted', lw=1)
        axs[1+i][1].set_yticklabels([])
        axs[1+i][1].hist(df_mapped_unique_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 1, colors[1+i], 1), label='distribution')
        axs[1+i][1].hist(df_mapped_unique_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 0, colors[1+i], 0.5), cumulative=True, label='cumulative')
        axs[1+i][1].hist(df_inferred_only_unique_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0.2, 0, colors[1+i], 0.5), cumulative=True, label='only by inference')
        axs[1+i][1].text(0.95*max_res, 0.95*len(df_mapped_unique_m.resolution), "%d " %  len(df_mapped_unique_m.resolution), 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
        axs[1+i][1].set_ylim((0, max_structs * 1.05))
        axs[1+i][1].legend(loc="upper left", fontsize=14)
        
        axs[1+i][2].grid(axis='y', ls='dotted', lw=1)
        axs[1+i][2].set_yticklabels([])
        axs[1+i][2].hist(df_mapped_copies_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 1, colors[1+i], 1), label='distribution')
        axs[1+i][2].hist(df_mapped_copies_m.resolution, bins=np.arange(0, max_res, 0.5), fc=(0, 0, colors[1+i], 0.5), cumulative=True, label='cumulative')
        axs[1+i][2].hist(df_mapped_copies_m[df_mapped_copies_m.inferred == 1].resolution, bins=np.arange(0, max_res, 0.5), fc=(0.2, 0, colors[1+i], 0.5), cumulative=True, label='inferred')
        axs[1+i][2].text(0.95*max_res, 0.95*len(df_mapped_copies_m.resolution), "%d " %  len(df_mapped_copies_m.resolution), 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
        axs[1+i][2].set_ylim((0, max_structs * 1.05))
        axs[1+i][2].legend(loc="upper left", fontsize=14)
    
    axs[-1][0].set_xlabel("Structure resolution\n(Angströms, lower is better)", fontsize=14)
    axs[-1][1].set_xlabel("Structure resolution\n(Angströms, lower is better)", fontsize=14)
    axs[-1][2].set_xlabel("Structure resolution\n(Angströms, lower is better)", fontsize=14)

    fig.suptitle("Number of RNA chains by experimental method and resolution", fontsize=16)
    fig.subplots_adjust(left=0.07, right=0.98, wspace=0.05, 
                        hspace=0.05, bottom=0.05, top=0.92)
    fig.savefig(runDir + "/results/figures/resolutions.png")
    plt.close()

    ##########################################
    # plot Nfam = f(resolution, exp_method)
    ##########################################

    df_mapped_copies['n_fam'] = [ len(df_mapped_copies.rfam_acc[:i+1].unique()) for i in range(len(df_mapped_copies.index)) ]

    fig, axs = plt.subplots(1, 1+len(methods), figsize=(5*(1+len(methods)), 5))
    max_res = max(df_mapped_copies.resolution)
    max_fams = max(df_mapped_copies.n_fam)
    colors = np.linspace(0,1,1+len(methods))
    plt.xticks( np.arange(0, max_res+2, 2.0).tolist(),  np.arange(0, max_res+2, 2.0).tolist() )

    axs[0].grid(axis='y', ls='dotted', lw=1)
    axs[0].plot(df_mapped_copies.resolution, df_mapped_copies.n_fam)
    axs[0].text(0.95*max_res, 0.95*df_mapped_copies.n_fam.iloc[-1], "%d " %  df_mapped_copies.n_fam.iloc[-1], 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
    axs[0].set_title("ALL", fontsize=14)
    axs[0].set_xlabel("Structure resolution (Angströms)", fontsize=14)
    axs[0].set_ylabel("Number of Rfam families", fontsize=14)
    axs[0].set_ylim((0, max_res * 1.05))
    axs[0].set_ylim((0, max_fams * 1.05))
    
    for i,m in enumerate(methods):
        df_mapped_copies_m = df_mapped_copies[ df_mapped_copies.exp_method == m].drop("n_fam", axis=1).copy()
        df_mapped_copies_m['n_fam'] = [ len(df_mapped_copies_m.rfam_acc[:i+1].unique()) for i in range(len(df_mapped_copies_m.index)) ]
        print(">", df_mapped_copies_m.n_fam.iloc[-1], "different RNA families have a 3D structure solved by", m)

        axs[1+i].grid(axis='y', ls='dotted', lw=1)
        axs[1+i].plot(df_mapped_copies_m.resolution, df_mapped_copies_m.n_fam, )
        axs[1+i].text(0.95*max(df_mapped_copies_m.resolution), 0.95*df_mapped_copies_m.n_fam.iloc[-1], "%d " %  df_mapped_copies_m.n_fam.iloc[-1], 
                         horizontalalignment='right', verticalalignment='top', fontsize=14)
        axs[1+i].set_xlim((0, max_res * 1.05))
        axs[1+i].set_ylim((0, max_fams * 1.05))
        axs[1+i].set_xlabel("Structure resolution (Angströms)", fontsize=14)
        axs[1+i].set_title(m, fontsize=14)
        axs[1+i].set_yticklabels([])
    
    fig.suptitle("Number of RNA families used by experimental method and resolution", fontsize=16)
    fig.subplots_adjust(left=0.05, right=0.98, wspace=0.05, 
                        hspace=0.05, bottom=0.12, top=0.84)
    fig.savefig(runDir + "/results/figures/Nfamilies.png")
    plt.close()

def par_distance_matrix(filelist, f, label, cm_coords, consider_all_atoms, s):
    
    # Identify the right 3D file
    filename = ''
    for file in filelist:
        if file.startswith(s.id.split("RF")[0].replace('-', '').replace('[', '_').replace(']', '_')):
            filename = path_to_3D_data + "rna_mapped_to_Rfam/" + file
            break
    if not len(filename):
        return None, None, None
    
    # Get the coordinates of every existing nt in the 3D file
    try:
        coordinates = nt_3d_centers(filename, consider_all_atoms)
        if not len(coordinates):
            # there is not nucleotides in the file, or no C1' atoms for example.
            warn("No C1' atoms in " + filename)
            return None, None, None
    except FileNotFoundError:
        return None, None, None


    # Get the coordinates of every position in the alignment
    nb_gap = 0
    coordinates_with_gaps = []
    for i, letter in enumerate(s.seq):
        if letter in "-.":
            nb_gap += 1
            coordinates_with_gaps.append(np.nan)
        else:
            coordinates_with_gaps.append(coordinates[i - nb_gap])
    
    # Build the pairwise distances
    d = np.zeros((len(s.seq), len(s.seq)), dtype=np.float32)
    for i in range(len(s.seq)):
        for j in range(len(s.seq)):
            if np.isnan(coordinates_with_gaps[i]).any() or np.isnan(coordinates_with_gaps[j]).any():
                d[i,j] = np.NaN
            else:
                d[i,j] = get_euclidian_distance(coordinates_with_gaps[i], coordinates_with_gaps[j])
    
    # Save the individual distance matrices
    # if f not in LSU_set and f not in SSU_set:
    np.savetxt(runDir + '/results/distance_matrices/' + f + '_'+ label + '/'+ s.id.strip("\'") + '.csv', d, delimiter=",", fmt="%.3f")
    
    # For the average and sd, we want to consider only positions of the consensus model. This means:
    #  - Add empty space when we have deletions
    #  - skip measures that correspond to insertions
    i = len(cm_coords)-1
    while cm_coords[i] is None:
        i -= 1
    family_end = int(cm_coords[i])
    i = 0
    while cm_coords[i] is None:
        i += 1
    family_start = int(cm_coords[i])
    # c = np.zeros((family_end, family_end), dtype=np.float32)    # new matrix of size of the consensus model for the family
    c = np.NaN * np.ones((family_end, family_end), dtype=np.float32)
    # set to NaN zones that never exist in the 3D data
    for i in range(family_start-1):
        for j in range(i, family_end):
            c[i,j] = np.NaN
            c[j,i] = np.NaN
    # copy the values ignoring insertions
    for i in range(len(s.seq)):
        if cm_coords[i] is None:
            continue
        for j in range(len(s.seq)):
            if j >= len(cm_coords):
                print(f"Issue with {s.id} mapped to {f} ({label}, {j}/{len(s.seq)}, {len(cm_coords)})")
            if cm_coords[j] is None:
                continue
            c[int(cm_coords[i])-1, int(cm_coords[j])-1] = d[i,j]
    # return the matrices counts, c, c^2
    return 1-np.isnan(c).astype(int), np.nan_to_num(c), np.nan_to_num(c*c)

@trace_unhandled_exceptions
def get_avg_std_distance_matrix(f, consider_all_atoms, multithread=False):
    np.seterr(divide='ignore') # ignore division by zero issues

    if consider_all_atoms:
        label = "base"
    else:
        label = "backbone"

    if not multithread:
        # This function call is for ONE worker.
        # Get a worker number for it to position the progress bar
        global idxQueue
        thr_idx = idxQueue.get()
        setproctitle(f"RNANet statistics.py Worker {thr_idx+1} {f} {label} distance matrices")

    os.makedirs(runDir + '/results/distance_matrices/' + f + '_' + label, exist_ok=True )   

    align = AlignIO.read(path_to_seq_data + f"realigned/{f}_3d_only.afa", "fasta")
    ncols = align.get_alignment_length()
    found = 0
    notfound = 0
    # retrieve the mappings between this family's alignment and the CM model:
    with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
        conn.execute('pragma journal_mode=wal')
        r = sql_ask_database(conn, f"SELECT structure_id, '_1_', chain_name, '_', CAST(pdb_start AS TEXT), '-', CAST(pdb_end AS TEXT) FROM chain WHERE rfam_acc='{f}';")
        filelist = sorted([ ''.join(list(x))+'.cif' for x in r ])
        r = sql_ask_database(conn, f"SELECT cm_coord FROM align_column WHERE rfam_acc = '{f}' AND index_ali > 0 ORDER BY index_ali ASC;")
        cm_coords = [ x[0] for x in r ] # len(cm_coords) is the number of saved columns. There are many None values in the list.
        i = len(cm_coords)-1
        while cm_coords[i] is None:
            if i == 0:
                # Issue somewhere. Abort.
                warn(f"{f} has no mapping to CM. Ignoring distance matrix.")
                if not multithread:
                    idxQueue.put(thr_idx) # replace the thread index in the queue
                    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")
                return 0
            i -= 1
        family_end = int(cm_coords[i])
    counts = np.zeros((family_end, family_end))
    avg = np.zeros((family_end, family_end))
    std = np.zeros((family_end, family_end))
    
    if not multithread:
        pbar = tqdm(total = len(align), position=thr_idx+1, desc=f"Worker {thr_idx+1}: {f} {label} distance matrices", unit="chains", leave=False)
        pbar.update(0)
        for s in align:
            contrib, d, dsquared = par_distance_matrix(filelist, f, label, cm_coords, consider_all_atoms, s)
            if d is not None:
                found += 1
                counts += contrib
                avg += d
                std += dsquared
            else:
                notfound += 1
            pbar.update(1)
        pbar.close()
    else:
        # We split the work for one family on multiple workers.
        
        p = Pool(initializer=init_worker, initargs=(tqdm.get_lock(),), processes=nworkers)
        try:
            fam_pbar = tqdm(total=len(align), desc=f"{f} {label} pair distances", position=0, unit="chain", leave=True)
            # Apply work_pssm_remap to each RNA family
            for i, (contrib, d, dsquared) in enumerate(p.imap_unordered(partial(par_distance_matrix, filelist, f, label, cm_coords, consider_all_atoms), align, chunksize=1)):
                if d is not None:
                    found += 1
                    counts += contrib
                    avg += d
                    std += dsquared
                else:
                    notfound += 1
                fam_pbar.update(1)
            fam_pbar.close()
            p.close()
            p.join()
        except KeyboardInterrupt:
            warn("KeyboardInterrupt, terminating workers.", error=True)
            fam_pbar.close()
            p.terminate()
            p.join()
            exit(1)

    # Calculation of the average matrix
    avg = np.divide(avg, counts, where=counts>0, out=np.full_like(avg, np.NaN)) # Ultrafancy way to take avg/counts or NaN if counts is 0
    np.savetxt(runDir + '/results/distance_matrices/' + f + '_'+ label + '/' + f + '_average.csv' , avg, delimiter=",", fmt="%.3f")
    
    fig, ax = plt.subplots()
    im = ax.imshow(avg)
    cbar = ax.figure.colorbar(im, ax=ax)
    cbar.ax.set_ylabel("Angströms", rotation=-90, va="bottom")
    ax.set_title(f"Average distance between {f} residues (Angströms)")
    fig.tight_layout()
    fig.savefig(runDir + '/results/distance_matrices/' + f + '_'+ label + '/' + f + '_average.png', dpi=300)
    plt.close()

    # Calculation of the standard deviation matrix by the Huygens theorem
    std = np.divide(std, counts, where=counts>0, out=np.full_like(std, np.NaN))
    mask = np.invert(np.isnan(std))
    value = std[mask] - np.power(avg[mask], 2)
    if ((value[value<0] < -1e-2).any()):
        warn("Erasing very negative variance value !")
    value[value<0] = 0.0 # floating point problems !
    std[mask] = np.sqrt(value)
    np.savetxt(runDir + '/results/distance_matrices/' + f + '_'+ label + '/' + f + '_stdev.csv' , std, delimiter=",", fmt="%.3f")
    
    fig, ax = plt.subplots()
    im = ax.imshow(std)
    cbar = ax.figure.colorbar(im, ax=ax)
    cbar.ax.set_ylabel("Angströms", rotation=-90, va="bottom")
    ax.set_title(f"Standard deviation of distances between {f} residues (Angströms)")
    fig.tight_layout()
    fig.savefig(runDir + '/results/distance_matrices/' + f + '_'+ label + '/' + f + '_std.png', dpi=300)
    plt.close()

    # Save log
    with open(runDir + '/results/distance_matrices/' + f + '_'+ label + '/' + f + '.log', 'a') as logfile:
        logfile.write(str(found)+ " chains taken into account for computation. "+ str(notfound)+ " were not found/without atoms.\n")

    # Save associated nucleotide frequencies (off-topic but convenient to do it here)
    with sqlite3.connect(runDir + "/results/RNANet.db") as conn:
        conn.execute('pragma journal_mode=wal')
        df = pd.read_sql_query(f"SELECT freq_A, freq_C, freq_G, freq_U, freq_other, gap_percent, consensus FROM align_column WHERE rfam_acc = '{f}' AND index_ali > 0 ORDER BY index_ali ASC;", conn)
        df.to_csv(runDir + '/results/distance_matrices/' + f + '_'+ label + '/' + f + '_frequencies.csv', float_format="%.3f")

    if not multithread:
        idxQueue.put(thr_idx) # replace the thread index in the queue
        setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")
    return 0

def log_to_pbar(pbar):
    def update(r):
        pbar.update(1)
    return update

def family_order(f):
    # sort the RNA families so that the plots are readable

    if f in LSU_set:
        return 4
    elif f in SSU_set:
        return 3
    elif f in ["RF00001"]:      #
        return 1                # put tRNAs and 5S rRNAs first,
    elif f in ["RF00005"]:      # because of the logarithmic scale of the lengths' figure, otherwise, they look tiny
        return 0                #
    else:
        return 2

def conversion_angles(bdd): 
    """
    Convert database torsion angles to degrees
    and put them in a list to reuse for statistics
    """
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(BASE_DIR, bdd)
    baseDeDonnees = sqlite3.connect(db_path)
    curseur = baseDeDonnees.cursor()
    curseur.execute("SELECT chain_id, nt_name, alpha, beta, gamma, delta, epsilon, zeta, chi FROM nucleotide WHERE nt_name='A' OR nt_name='C' OR nt_name='G' OR nt_name='U' ;")
    liste=[]
    for nt in curseur.fetchall(): # retrieve the angle measurements and put them in a list
        liste.append(nt)
    angles_torsion=[]
    for nt in liste :
        angles_deg=[]
        angles_deg.append(nt[0]) #chain_id
        angles_deg.append(nt[1]) #nt_name
        for i in range (2,9): # on all angles
            angle=0
            if nt[i] == None : 
                angle=None
            elif nt[i]<=np.pi: #if angle value <pi, positive
                angle=(180/np.pi)*nt[i]
            elif np.pi < nt[i] <= 2*np.pi : #if value of the angle between pi and 2pi, negative
                angle=((180/np.pi)*nt[i])-360
            else :
                angle=nt[i] # in case some angles still in degrees
            angles_deg.append(angle)
        angles_torsion.append(angles_deg)
    return angles_torsion

def conversion_eta_theta(bdd):
    """
    Convert database pseudotorsion angles to degrees
    and put them in a list to reuse for statistics
    """
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    db_path = os.path.join(BASE_DIR, bdd)
    baseDeDonnees = sqlite3.connect(db_path)
    curseur = baseDeDonnees.cursor()
    curseur.execute("SELECT chain_id, nt_name, eta, theta, eta_prime, theta_prime, eta_base, theta_base FROM nucleotide WHERE nt_name='A' OR nt_name='C' OR nt_name='G' OR nt_name='U';")
    liste=[]
    for nt in curseur.fetchall(): 
        liste.append(nt)
    angles_virtuels=[]
    for nt in liste :
        angles_deg=[]
        angles_deg.append(nt[0]) #chain_id
        angles_deg.append(nt[1]) #nt_name
        for i in range (2,8): 
            angle=0
            if nt[i] == None : 
                angle=None
            elif nt[i]<=np.pi:
                angle=(180/np.pi)*nt[i]
            elif np.pi < nt[i] <= 2*np.pi : 
                angle=((180/np.pi)*nt[i])-360
            else :
                angle=nt[i] 
            angles_deg.append(angle)
        angles_virtuels.append(angles_deg)
    return angles_virtuels

def nt_3d_centers(cif_file, consider_all_atoms):
    """Return the nucleotides' coordinates, summarizing a nucleotide by only one point.
    If consider_all_atoms : barycentre is used
    else: C1' atom is the nucleotide

    Some chains have no C1' (e.g. 4v7f-3), therefore, an empty result is returned.
    """
    result  =[]
    structure = MMCIFParser().get_structure(cif_file, cif_file)
    
    for model in structure:
        for chain in model:
            for residue in chain:
                if consider_all_atoms:
                    temp_list = []
                    for atom in residue:
                        temp_list.append(atom.get_coord())
                    lg = len(temp_list)
                    summ = np.sum(temp_list, axis = 0)
                    res_isobaricentre = [summ[0]/lg, summ[1]/lg, summ[2]/lg]
                    result.append([res_isobaricentre[0], res_isobaricentre[1], res_isobaricentre[2]])
                else:
                    coordinates = None
                    for atom in residue:
                        if atom.get_name() == "C1'":
                            coordinates = atom.get_coord()
                    if coordinates is None:
                        # Residue has no C1'
                        res = np.nan
                    else:
                        res = [coordinates[0], coordinates[1], coordinates[2]]
                    result.append(res)
    return(result)

def liste_repres(fpath):
    repres=[]
    df=pd.read_csv(os.path.abspath(fpath))
    for i in range(df.shape[0]):
        up_name=df["representative"][i]
        if '+' in up_name:
            up_name=up_name.split('+')
            for i in range(len(up_name)):
                chain=up_name[i].split('|')
                chain=chain[0].lower()+'_'+chain[1]+'_'+chain[2]
                repres.append(chain+'.cif')
        else :
            up_name=up_name.split('|')
            low_name=up_name[0].lower()+'_'+up_name[1]+'_'+up_name[2]
            repres.append(low_name+'.cif') 
        
    return repres


def get_euclidian_distance(L1, L2):
    """
    Returns the distance between two points (coordinates in lists)
    """

    if len(L1)*len(L2) == 0:
        return np.nan
    
    if len(L1) == 1:
        L1 = L1[0]
    if len(L2) == 1:
        L2 = L2[0]

    e = 0
    for i in range(len(L1)):
        try:
            e += float(L1[i] - L2[i])**2
        except TypeError:
            print("Terms: ", L1, L2)
        except IndexError:
            print("Terms: ", L1, L2)

    return np.sqrt(e)

def get_flat_angle(L1, L2, L3):
    if len(L1)*len(L2)*len(L3) == 0:
        return np.nan

    return calc_angle(Vector(L1[0]), Vector(L2[0]), Vector(L3[0]))*(180/np.pi)

def get_torsion_angle(L1, L2, L3, L4):
    if len(L1)*len(L2)*len(L3)*len(L4) == 0:
        return np.nan
    
    return calc_dihedral(Vector(L1[0]), Vector(L2[0]), Vector(L3[0]), Vector(L4[0]))*(180/np.pi)

def pos_b1(res):
    """
    Returns the coordinates of virtual atom B1 (center of the first aromatic cycle)
    """
    coordb1=[]
    somme_x_b1=0
    somme_y_b1=0
    somme_z_b1=0
    moy_x_b1=0
    moy_y_b1=0
    moy_z_b1=0
    #different cases
    #some residues have 2 aromatic cycles 
    if res.get_resname() in ['A', 'G', '2MG', '7MG', 'MA6', '6IA', 'OMG' , '2MA', 'B9B', 'A2M', '1MA', 'E7G', 'P7G', 'B8W', 'B8K', 'BGH', '6MZ', 'E6G', 'MHG', 'M7A', 'M2G', 'P5P', 'G7M', '1MG', 'T6A', 'MIA', 'YG', 'YYG', 'I', 'DG', 'N79', '574', 'DJF', 'AET', '12A', 'ANZ', 'UY4'] :  
        c=0
        names=[]
        for atom in res : 
            if (atom.get_fullname() in ['N9', 'C8', 'N7', 'C4', 'C5']) :
                c=c+1
                names.append(atom.get_name())
                coord=atom.get_vector()
                somme_x_b1=somme_x_b1+coord[0]
                somme_y_b1=somme_y_b1+coord[1]
                somme_z_b1=somme_z_b1+coord[2]
            else : 
                c=c
        #calcul coord B1
        if c != 0 :
            moy_x_b1=somme_x_b1/c
            moy_y_b1=somme_y_b1/c
            moy_z_b1=somme_z_b1/c
            coordb1.append(moy_x_b1)
            coordb1.append(moy_y_b1)
            coordb1.append(moy_z_b1)
    #others have only one cycle
    if res.get_resname() in ['C', 'U', 'AG9', '70U', '1RN', 'RSP', '3AU', 'CM0', 'U8U', 'IU', 'E3C', '4SU', '5HM', 'LV2', 'LHH', '4AC', 'CH', 'Y5P', '2MU', '4OC', 'B8T', 'JMH', 'JMC', 'DC', 'B9H', 'UR3', 'I4U', 'B8Q', 'P4U', 'OMU', 'OMC', '5MU', 'H2U', 'CBV', 'M1Y', 'B8N', '3TD', 'B8H'] :
        c=0
        for atom in res :
            if (atom.get_fullname() in ['C6', 'N3', 'N1', 'C2', 'C4', 'C5']):
                c=c+1
                coord=atom.get_vector()
                somme_x_b1=somme_x_b1+coord[0]
                somme_y_b1=somme_y_b1+coord[1]
                somme_z_b1=somme_z_b1+coord[2]
        #calcul coord B1
        if c != 0 :
            moy_x_b1=somme_x_b1/c
            moy_y_b1=somme_y_b1/c
            moy_z_b1=somme_z_b1/c
            coordb1.append(moy_x_b1)
            coordb1.append(moy_y_b1)
            coordb1.append(moy_z_b1)

    if len(coordb1):
        return [coordb1]
    else:
        return []

def pos_b2(res):
    """
    Returns the coordinates of virtual atom B2 (center of the second aromatic cycle, if exists)
    """
    coordb2=[]
    somme_x_b2=0
    somme_y_b2=0
    somme_z_b2=0
    moy_x_b2=0
    moy_y_b2=0
    moy_z_b2=0

    if res.get_resname() in ['A', 'G', '2MG', '7MG', 'MA6', '6IA', 'OMG' , '2MA', 'B9B', 'A2M', '1MA', 'E7G', 'P7G', 'B8W', 'B8K', 'BGH', '6MZ', 'E6G', 'MHG', 'M7A', 'M2G', 'P5P', 'G7M', '1MG', 'T6A', 'MIA', 'YG', 'YYG', 'I', 'DG', 'N79', '574', 'DJF', 'AET', '12A', 'ANZ', 'UY4'] :  #2 cycles aromatiques
        c=0
        for atom in res :
            if atom.get_fullname() in ['C6', 'N3', 'N1', 'C2', 'C4', 'C5'] :
                c=c+1
                coord=atom.get_vector()
                somme_x_b2=somme_x_b2+coord[0]
                somme_y_b2=somme_y_b2+coord[1]
                somme_z_b2=somme_z_b2+coord[2]
        #calcul coord B2
        if c!=0 :
            moy_x_b2=somme_x_b2/c
            moy_y_b2=somme_y_b2/c
            moy_z_b2=somme_z_b2/c
            coordb2.append(moy_x_b2)
            coordb2.append(moy_y_b2)
            coordb2.append(moy_z_b2)
    if len(coordb2):
        return [coordb2]
    else:
        return []

@trace_unhandled_exceptions
def basepair_measures(res, pair):
    """
    measurement of the flat angles describing a basepair in the HiRE-RNA model
    """
    if res.get_resname()=='C' or res.get_resname()=='U' :
        atom_c4_res = [ atom.get_coord() for atom in res if "C4'" in atom.get_fullname() ] 
        atom_c1p_res = [ atom.get_coord() for atom in res if "C1'" in atom.get_fullname() ]
        atom_b1_res = pos_b1(res)
        if not len(atom_c4_res) or not len(atom_c1p_res) or not len(atom_b1_res):
            return
        a3_res = Vector(atom_c4_res[0])
        a2_res = Vector(atom_c1p_res[0])
        a1_res = Vector(atom_b1_res[0])
    if res.get_resname()=='A' or res.get_resname()=='G' :
        atom_c1p_res = [ atom.get_coord() for atom in res if "C1'" in atom.get_fullname() ]
        atom_b1_res = pos_b1(res)
        atom_b2_res = pos_b2(res)
        if not len(atom_c1p_res) or not len(atom_b1_res) or not len(atom_b2_res): 
            return
        a3_res = Vector(atom_c1p_res[0])
        a2_res = Vector(atom_b1_res[0])
        a1_res = Vector(atom_b2_res[0])
        
    if pair.get_resname()=='C' or pair.get_resname()=='U' :
        atom_c4_pair = [ atom.get_coord() for atom in pair if "C4'" in atom.get_fullname() ]
        atom_c1p_pair = [ atom.get_coord() for atom in pair if "C1'" in atom.get_fullname() ]
        atom_b1_pair = pos_b1(pair)
        if not len(atom_c4_pair) or not len(atom_c1p_pair) or not len(atom_b1_pair):
            return
        a3_pair = Vector(atom_c4_pair[0])
        a2_pair = Vector(atom_c1p_pair[0])
        a1_pair = Vector(atom_b1_pair[0])
    if pair.get_resname()=='A' or pair.get_resname()=='G' :
        atom_c1p_pair = [ atom.get_coord() for atom in pair if "C1'" in atom.get_fullname() ]
        atom_b1_pair = pos_b1(pair)
        atom_b2_pair = pos_b2(pair)
        if not len(atom_c1p_pair) or not len(atom_b1_pair) or not len(atom_b2_pair): # No C1' atom in the paired nucleotide, skip measures.
            return
        a3_pair = Vector(atom_c1p_pair[0])
        a2_pair = Vector(atom_b1_pair[0])
        a1_pair = Vector(atom_b2_pair[0])

    # Bond vectors
    res_32 = a3_res - a2_res
    res_12 = a1_res - a2_res
    pair_32 = a3_pair - a2_pair
    pair_12 = a1_pair - a2_pair
    rho = a1_res - a1_pair # from pair to res

    # dist
    dist = rho.norm()

    # we calculate the 2 plane angles
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', RuntimeWarning)
        b = res_12.angle(rho)*(180/np.pi)   # equal to the previous implementation
        c = pair_12.angle(-rho)*(180/np.pi) #
    # a = calc_angle(a1_res, a2_res, a3_res)*(180/np.pi)    # not required
    # b = calc_angle(a2_res, a1_res, a1_pair)*(180/np.pi)
    # c = calc_angle(a1_res, a1_pair, a2_pair)*(180/np.pi)
    # d = calc_angle(a3_pair, a2_pair, a1_pair)*(180/np.pi)   # not required

    # Compute plane vectors
    n1 = (res_32**res_12).normalized() # ** between vectors, is the cross product
    n2 = (pair_32**pair_12).normalized()

    # Distances between base tip and the other base's plane (orthogonal projection)
    # if angle(rho, n) > pi/2 the distance is negative (signed following n)
    d1 = rho*n1 # projection of rho on axis n1
    d2 = rho*n2

    # Now the projection of rho in the planes. It's just a sum of the triangles' two other edges.
    p1 = (-rho+n1**d1).normalized() # between vector and scalar, ** is the multiplication by a scalar
    p2 = (rho-n2**d2).normalized()

    # Measure tau, the dihedral
    u = (res_12**rho).normalized()
    v = (rho**pair_12).normalized()
    cosTau1 = n1*u
    cosTau2 = v*n2 
    
    # cosTau is enough to compute alpha, but we can't distinguish
    # yet betwwen tau and -tau. If the full computation if required, then:
    tau1 = np.arccos(cosTau1)*(180/np.pi)
    tau2 = np.arccos(cosTau2)*(180/np.pi)
    w1 = u**n1
    w2 = v**n2
    if res_12*w1 < 0:
        tau1 = -tau1
    if pair_12*w2 < 0:
        tau2 = -tau2

    # And finally, the a1 and a2 angles between res_12 and p1 / pair_12 and p2
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', RuntimeWarning)
        a1 = (-res_12).angle(p1)*(180/np.pi)
        a2 = (-pair_12).angle(p2)*(180/np.pi)
    if cosTau1 > 0:
        # CosTau > 0 (Tau < 90 or Tau > 270) implies that alpha > 180.
        a1 = -a1
    if cosTau2 > 0:
        a2 = -a2

    return [dist, b, c, d1, d2, a1, a2, tau1, tau2]

@trace_unhandled_exceptions
def measure_from_structure(f):
    """
    Do geometric measures required on a given filename
    """

    name = f.split('.')[0]

    global idxQueue
    thr_idx = idxQueue.get()
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measure_from_structure({f})")

    # Open the structure 
    with warnings.catch_warnings():
        # Ignore the PDB problems. This mostly warns that some chain is discontinuous.
        warnings.simplefilter('ignore', Bio.PDB.PDBExceptions.PDBConstructionWarning)
        warnings.simplefilter('ignore', Bio.PDB.PDBExceptions.BiopythonWarning)
        parser=MMCIFParser()
        s = parser.get_structure(f, os.path.abspath(path_to_3D_data+ "rna_only/" + f))
    
    #pyle_measures(name, s, thr_idx)
    #measures_aa(name, s, thr_idx)
    if DO_HIRE_RNA_MEASURES:
        measures_hrna(name, s, thr_idx)
        measures_hrna_basepairs(name, s, thr_idx)
    if DO_WADLEY_ANALYSIS:
        #measures_wadley(name, s, thr_idx)
        pyle_measures(name, s, thr_idx)
    
    idxQueue.put(thr_idx) # replace the thread index in the queue
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")

@trace_unhandled_exceptions
def measures_wadley(name, s, thr_idx):
    """
    Measures the distances and plane angles involving C1' and P atoms 
    Saves the results in a dataframe
    """

    # do not recompute something already computed
    if (path.isfile(runDir + '/results/geometry/Pyle/angles/flat_angles_pyle_' + name + '.csv') and
        path.isfile(runDir + "/results/geometry/Pyle/distances/distances_wadley_" + name + ".csv")):
        return

    liste_dist = []
    liste_angl = []
    last_p = []
    last_c1p = []
    last_c4p = []

    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measures_wadley({name})")

    chain = next(s[0].get_chains())
    for res in tqdm(chain, position=thr_idx+1, desc=f"Worker {thr_idx+1}: {name} measures_wadley", unit="res", leave=False):
        p_c1p_psuiv = np.nan
        c1p_psuiv_c1psuiv = np.nan
        if res.get_resname() not in ['ATP', 'CCC', 'A3P', 'A23', 'GDP', 'RIA', "2BA"] :
            atom_p = [ atom.get_coord() for atom in res if atom.get_name() ==  "P"]
            atom_c1p = [ atom.get_coord() for atom in res if "C1'" in atom.get_fullname() ]
            atom_c4p = [ atom.get_coord() for atom in res if "C4'" in atom.get_fullname() ]
            if len(atom_c1p) > 1:
                for atom in res:
                    if "C1'" in atom.get_fullname():
                        print("\n", atom.get_fullname(), "-", res.get_resname(), "\n")

            p_c1p_psuiv = get_flat_angle(last_p, last_c1p, atom_p)
            c1p_psuiv_c1psuiv = get_flat_angle(last_c1p, atom_p, atom_c1p)
            c1p_psuiv = get_euclidian_distance(last_c1p, atom_p)
            p_c1p = get_euclidian_distance(atom_p, atom_c1p)
            c4p_psuiv = get_euclidian_distance(last_c4p, atom_p)
            p_c4p = get_euclidian_distance(atom_p, atom_c4p)

            last_p = atom_p
            last_c1p = atom_c1p
            last_c4p = atom_c4p

            liste_dist.append([res.get_resname(), c1p_psuiv, p_c1p, c4p_psuiv, p_c4p])
            liste_angl.append([res.get_resname(), p_c1p_psuiv, c1p_psuiv_c1psuiv])

    df = pd.DataFrame(liste_dist, columns=["Residu", "C1'-P", "P-C1'", "C4'-P", "P-C4'"])
    df.to_csv(runDir + "/results/geometry/Pyle/distances/distances_wadley_" + name + ".csv")
    df = pd.DataFrame(liste_angl, columns=["Residu", "P-C1'-P°", "C1'-P°-C1'°"])
    df.to_csv(runDir + "/results/geometry/Pyle/angles/flat_angles_pyle_"+name+".csv")

@trace_unhandled_exceptions
def measures_aa(name, s, thr_idx):
    """
    Measures the distance between atoms linked by covalent bonds
    """

    # do not recompute something already computed
    if path.isfile(runDir+"/results/geometry/all-atoms/distances/dist_atoms_"+name+".csv"):
        return
    
    last_o3p = [] # o3 'of the previous nucleotide linked to the P of the current nucleotide
    liste_common = []
    liste_purines = []
    liste_pyrimidines = []
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measure_aa_dists({name})")

    chain = next(s[0].get_chains()) # 1 chain per file
    residues = list(chain.get_residues())
    pbar = tqdm(total=len(residues), position=thr_idx+1, desc=f"Worker {thr_idx+1}: {name} measure_aa_dists", unit="res", leave=False)
    pbar.update(0)
    for res in chain :
        
        # for residues A, G, C, U
        op3_p=[]
        p_op1=[]
        p_op2=[]
        p_o5p=[]
        o5p_c5p=[]
        c5p_c4p=[]
        c4p_o4p=[]
        o4p_c1p=[]
        c1p_c2p=[]
        c2p_o2p=[]
        c2p_c3p=[]
        c3p_o3p=[]
        c4p_c3p=[]
        
        #if res = A or G
        c1p_n9=None
        n9_c8=None
        c8_n7=None
        n7_c5=None
        c5_c6=None
        c6_n1=None
        n1_c2=None
        c2_n3=None
        n3_c4=None
        c4_n9=None
        c4_c5=None
        #if res=G
        c6_o6=None
        c2_n2=None
        #if res = A
        c6_n6=None

        #if res = C or U
        c1p_n1=None
        n1_c6=None
        c6_c5=None
        c5_c4=None
        c4_n3=None
        n3_c2=None
        c2_n1=None
        c2_o2=None
        #if res =C
        c4_n4=None
        #if res=U
        c4_o4=None
        last_o3p_p=None


        if res.get_resname()=='A' or res.get_resname()=='G' or res.get_resname()=='C' or res.get_resname()=='U' :
            #get the coordinates of the atoms
            atom_p = [ atom.get_coord() for atom in res if atom.get_name() ==  "P"]
            atom_op3 = [ atom.get_coord() for atom in res if "OP3" in atom.get_fullname() ]
            atom_op1 = [ atom.get_coord() for atom in res if "OP1" in atom.get_fullname() ]
            atom_op2 = [ atom.get_coord() for atom in res if "OP2" in atom.get_fullname() ]
            atom_o5p= [ atom.get_coord() for atom in res if "O5'" in atom.get_fullname() ]
            atom_c5p = [ atom.get_coord() for atom in res if "C5'" in atom.get_fullname() ]
            atom_c4p = [ atom.get_coord() for atom in res if "C4'" in atom.get_fullname() ]
            atom_o4p = [ atom.get_coord() for atom in res if "O4'" in atom.get_fullname() ]
            atom_c3p = [ atom.get_coord() for atom in res if "C3'" in atom.get_fullname() ]
            atom_o3p = [ atom.get_coord() for atom in res if "O3'" in atom.get_fullname() ]
            atom_c2p = [ atom.get_coord() for atom in res if "C2'" in atom.get_fullname() ]
            atom_o2p = [ atom.get_coord() for atom in res if "O2'" in atom.get_fullname() ]
            atom_c1p = [ atom.get_coord() for atom in res if "C1'" in atom.get_fullname() ]
            atom_n9 = [ atom.get_coord() for atom in res if "N9" in atom.get_fullname() ]
            atom_c8 = [ atom.get_coord() for atom in res if "C8" in atom.get_fullname() ]
            atom_n7 = [ atom.get_coord() for atom in res if "N7" in atom.get_fullname() ]
            atom_c5 = [ atom.get_coord() for atom in res if atom.get_name() ==  "C5"]
            atom_c6 = [ atom.get_coord() for atom in res if "C6" in atom.get_fullname() ]
            atom_o6 = [ atom.get_coord() for atom in res if "O6" in atom.get_fullname() ]
            atom_n6 = [ atom.get_coord() for atom in res if "N6" in atom.get_fullname() ]
            atom_n1 = [ atom.get_coord() for atom in res if "N1" in atom.get_fullname() ]
            atom_c2 = [ atom.get_coord() for atom in res if atom.get_name() ==  "C2"]
            atom_n2 = [ atom.get_coord() for atom in res if "N2" in atom.get_fullname() ]
            atom_o2 = [ atom.get_coord() for atom in res if atom.get_name() ==  "O2"]
            atom_n3 = [ atom.get_coord() for atom in res if "N3" in atom.get_fullname() ]
            atom_c4 = [ atom.get_coord() for atom in res if atom.get_name() ==  "C4" ]
            atom_n4 = [ atom.get_coord() for atom in res if "N4" in atom.get_fullname() ]
            atom_o4 = [ atom.get_coord() for atom in res if atom.get_name() == "O4"]
            
            op3_p = get_euclidian_distance(atom_op3, atom_p)
            last_o3p_p = get_euclidian_distance(last_o3p, atom_p) # link with the previous nucleotide
            p_op1 = get_euclidian_distance(atom_op1, atom_p)
            p_op2 = get_euclidian_distance(atom_op2, atom_p)
            p_o5p = get_euclidian_distance(atom_o5p, atom_p)
            o5p_c5p = get_euclidian_distance(atom_o5p, atom_c5p)
            c5p_c4p = get_euclidian_distance(atom_c5p, atom_c4p)
            c4p_o4p = get_euclidian_distance(atom_c4p, atom_o4p)
            c4p_c3p = get_euclidian_distance(atom_c4p, atom_c3p)
            o4p_c1p = get_euclidian_distance(atom_o4p, atom_c1p)
            c1p_c2p = get_euclidian_distance(atom_c1p, atom_c2p)
            c2p_o2p = get_euclidian_distance(atom_c2p, atom_o2p)
            c2p_c3p = get_euclidian_distance(atom_c2p, atom_c3p)
            c3p_o3p = get_euclidian_distance(atom_c3p, atom_o3p)

            last_o3p=atom_o3p # o3' of this residue becomes the previous o3' of the following
            
            #different cases for the aromatic cycles
            if res.get_resname()=='A' or res.get_resname()=='G': 
                # computes the distances between atoms of aromatic cycles
                c1p_n9 = get_euclidian_distance(atom_c1p, atom_n9)
                n9_c8 = get_euclidian_distance(atom_n9, atom_c8)
                c8_n7 = get_euclidian_distance(atom_c8, atom_n7)
                n7_c5 = get_euclidian_distance(atom_n7, atom_c5)
                c5_c6 = get_euclidian_distance(atom_c5, atom_c6)
                c6_o6 = get_euclidian_distance(atom_c6, atom_o6)
                c6_n6 = get_euclidian_distance(atom_c6, atom_n6)
                c6_n1 = get_euclidian_distance(atom_c6, atom_n1)
                n1_c2 = get_euclidian_distance(atom_n1, atom_c2)
                c2_n2 = get_euclidian_distance(atom_c2, atom_n2)
                c2_n3 = get_euclidian_distance(atom_c2, atom_n3)
                n3_c4 = get_euclidian_distance(atom_n3, atom_c4)
                c4_n9 = get_euclidian_distance(atom_c4, atom_n9)
                c4_c5 = get_euclidian_distance(atom_c4, atom_c5)
            if res.get_resname()=='C' or res.get_resname()=='U' :
                c1p_n1 = get_euclidian_distance(atom_c1p, atom_n1)
                n1_c6 = get_euclidian_distance(atom_n1, atom_c6)
                c6_c5 = get_euclidian_distance(atom_c6, atom_c5)
                c5_c4 = get_euclidian_distance(atom_c5, atom_c4)
                c4_n3 = get_euclidian_distance(atom_c4, atom_n3)
                n3_c2 = get_euclidian_distance(atom_n3, atom_c2)
                c2_o2 = get_euclidian_distance(atom_c2, atom_o2)
                c2_n1 = get_euclidian_distance(atom_c2, atom_n1)
                c4_n4 = get_euclidian_distance(atom_c4, atom_n4)
                c4_o4 = get_euclidian_distance(atom_c4, atom_o4)

            liste_common.append([res.get_resname(), last_o3p_p, op3_p, p_op1, p_op2, p_o5p, o5p_c5p, c5p_c4p, c4p_o4p, c4p_c3p, o4p_c1p, c1p_c2p, c2p_o2p, c2p_c3p, c3p_o3p] )
            liste_purines.append([c1p_n9, n9_c8, c8_n7, n7_c5, c5_c6, c6_o6, c6_n6, c6_n1, n1_c2, c2_n2, c2_n3, n3_c4, c4_n9, c4_c5])
            liste_pyrimidines.append([c1p_n1, n1_c6, c6_c5, c5_c4, c4_n3, n3_c2, c2_o2, c2_n1, c4_n4, c4_o4])
            pbar.update(1)

    df_comm=pd.DataFrame(liste_common, columns=["Residu", "O3'-P", "OP3-P", "P-OP1", "P-OP2", "P-O5'", "O5'-C5'", "C5'-C4'", "C4'-O4'", "C4'-C3'", "O4'-C1'", "C1'-C2'", "C2'-O2'", "C2'-C3'", "C3'-O3'"])
    df_pur=pd.DataFrame(liste_purines, columns=["C1'-N9", "N9-C8", "C8-N7", "N7-C5", "C5-C6", "C6-O6", "C6-N6", "C6-N1", "N1-C2", "C2-N2", "C2-N3", "N3-C4", "C4-N9", "C4-C5" ])
    df_pyr=pd.DataFrame(liste_pyrimidines, columns=["C1'-N1", "N1-C6", "C6-C5", "C5-C4", "C4-N3", "N3-C2", "C2-O2", "C2-N1", "C4-N4", "C4-O4"])
    df=pd.concat([df_comm, df_pur, df_pyr], axis = 1)
    pbar.close()
    
    df.to_csv(runDir + "/results/geometry/all-atoms/distances/dist_atoms_" + name + ".csv")

@trace_unhandled_exceptions
def measures_hrna(name, s, thr_idx):
    """
    Measures the distance/angles between the atoms of the HiRE-RNA model linked by covalent bonds
    """
    
    # do not recompute something already computed
    if (path.isfile(runDir + '/results/geometry/HiRE-RNA/distances/dist_atoms_hire_RNA '+name+'.csv') and 
       path.isfile(runDir + '/results/geometry/HiRE-RNA/angles/angles_hire_RNA '+name+'.csv') and 
       path.isfile(runDir + '/results/geometry/HiRE-RNA/torsions/angles_torsion_hire_RNA '+name+'.csv')):
        return

    liste_dist=[]
    liste_angl = []
    liste_tors = []
    last_c4p = []
    last_c5p = []
    last_c1p = []
    last_o5p = []

    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measures_hrna({name})")

    chain = next(s[0].get_chains())
    residues=list(chain.get_residues())
    for res in tqdm(chain, position=thr_idx+1, desc=f"Worker {thr_idx+1}: {name} measures_hrna", unit="res", leave=False):
        # distances
        p_o5p = None
        o5p_c5p = None
        c5p_c4p = None
        c4p_c1p = None
        c1p_b1 = None
        b1_b2 = None
        last_c4p_p = np.nan
        
        # angles
        p_o5p_c5p = None
        o5p_c5p_c4p = None
        c5p_c4p_c1p = None
        c4p_c1p_b1 = None
        c1p_b1_b2 = None
        lastc4p_p_o5p = None
        lastc5p_lastc4p_p = None
        lastc1p_lastc4p_p = None

        # torsions
        p_o5_c5_c4 = np.nan
        o5_c5_c4_c1 = np.nan
        c5_c4_c1_b1 = np.nan
        c4_c1_b1_b2 = np.nan
        o5_c5_c4_psuiv = np.nan
        c5_c4_psuiv_o5suiv = np.nan
        c4_psuiv_o5suiv_c5suiv = np.nan
        c1_c4_psuiv_o5suiv = np.nan

        if res.get_resname() not in ['ATP', 'CCC', 'A3P', 'A23', 'GDP', 'RIA', "2BA"] : # several phosphate groups, ignore
            atom_p = [ atom.get_coord() for atom in res if atom.get_name() ==  "P"]
            atom_o5p= [ atom.get_coord() for atom in res if "O5'" in atom.get_fullname() ]
            atom_c5p = [ atom.get_coord() for atom in res if "C5'" in atom.get_fullname() ]
            atom_c4p = [ atom.get_coord() for atom in res if "C4'" in atom.get_fullname() ]
            atom_c1p = [ atom.get_coord() for atom in res if "C1'" in atom.get_fullname() ]
            atom_b1 = pos_b1(res) # position b1 to be calculated, depending on the case
            atom_b2 = pos_b2(res) # position b2 to be calculated only for those with 2 cycles

            # Distances. If one of the atoms is empty, the euclidian distance returns NaN.
            last_c4p_p = get_euclidian_distance(last_c4p, atom_p)
            p_o5p = get_euclidian_distance(atom_p, atom_o5p)
            o5p_c5p = get_euclidian_distance(atom_o5p, atom_c5p)
            c5p_c4p = get_euclidian_distance(atom_c5p, atom_c4p)
            c4p_c1p = get_euclidian_distance(atom_c4p, atom_c1p)
            c1p_b1 = get_euclidian_distance(atom_c1p, atom_b1)
            b1_b2 = get_euclidian_distance(atom_b1, atom_b2)

            # flat angles. Same.
            lastc4p_p_o5p = get_flat_angle(last_c4p, atom_p, atom_o5p)
            lastc1p_lastc4p_p = get_flat_angle(last_c1p, last_c4p, atom_p)
            lastc5p_lastc4p_p = get_flat_angle(last_c5p, last_c4p, atom_p)
            p_o5p_c5p = get_flat_angle(atom_p, atom_o5p, atom_c5p)
            o5p_c5p_c4p = get_flat_angle(atom_o5p, atom_c5p, atom_c4p)
            c5p_c4p_c1p = get_flat_angle(atom_c5p, atom_c4p, atom_c1p)
            c4p_c1p_b1 = get_flat_angle(atom_c4p, atom_c1p, atom_b1)
            c1p_b1_b2 = get_flat_angle(atom_c1p, atom_b1, atom_b2)

            # torsions. Idem.
            p_o5_c5_c4 = get_torsion_angle(atom_p, atom_o5p, atom_c5p, atom_c4p)
            o5_c5_c4_c1 = get_torsion_angle(atom_o5p, atom_c5p, atom_c4p, atom_c1p)
            c5_c4_c1_b1 = get_torsion_angle(atom_c5p, atom_c4p, atom_c1p, atom_b1)
            c4_c1_b1_b2 = get_torsion_angle(atom_c4p, atom_c1p, atom_b1, atom_b2)
            o5_c5_c4_psuiv = get_torsion_angle(last_o5p, last_c5p, last_c4p, atom_p)
            c5_c4_psuiv_o5suiv = get_torsion_angle(last_c5p, last_c4p, atom_p, atom_o5p)
            c4_psuiv_o5suiv_c5suiv = get_torsion_angle(last_c4p, atom_p, atom_o5p, atom_c5p)
            c1_c4_psuiv_o5suiv = get_torsion_angle(last_c1p, last_c4p, atom_p, atom_o5p)

            last_c4p = atom_c4p
            last_c5p = atom_c5p
            last_c1p = atom_c1p
            last_o5p = atom_o5p
            liste_dist.append([res.get_resname(), last_c4p_p, p_o5p, o5p_c5p, c5p_c4p, c4p_c1p, c1p_b1, b1_b2])
            liste_angl.append([res.get_resname(), lastc4p_p_o5p, lastc1p_lastc4p_p, lastc5p_lastc4p_p, p_o5p_c5p, o5p_c5p_c4p, c5p_c4p_c1p, c4p_c1p_b1, c1p_b1_b2])
            liste_tors.append([res.get_resname(), p_o5_c5_c4, o5_c5_c4_c1, c5_c4_c1_b1, c4_c1_b1_b2, o5_c5_c4_psuiv, c5_c4_psuiv_o5suiv, c4_psuiv_o5suiv_c5suiv, c1_c4_psuiv_o5suiv])
    df = pd.DataFrame(liste_dist, columns=["Residu", "C4'-P", "P-O5'", "O5'-C5'", "C5'-C4'", "C4'-C1'", "C1'-B1", "B1-B2"])
    df.to_csv(runDir + '/results/geometry/HiRE-RNA/distances/dist_atoms_hire_RNA '+name+'.csv')
    df = pd.DataFrame(liste_angl, columns=["Residu", "C4'-P-O5'", "C1'-C4'-P", "C5'-C4'-P", "P-O5'-C5'", "O5'-C5'-C4'", "C5'-C4'-C1'", "C4'-C1'-B1", "C1'-B1-B2"])
    df.to_csv(runDir + '/results/geometry/HiRE-RNA/angles/angles_hire_RNA ' + name + ".csv")
    df=pd.DataFrame(liste_tors, columns=["Residu", "P-O5'-C5'-C4'", "O5'-C5'-C4'-C1'", "C5'-C4'-C1'-B1", "C4'-C1'-B1-B2", "O5'-C5'-C4'-P°", "C5'-C4'-P°-O5'°", "C4'-P°-O5'°-C5'°", "C1'-C4'-P°-O5'°"])
    df.to_csv(runDir + '/results/geometry/HiRE-RNA/torsions/angles_torsion_hire_RNA '+name+'.csv')

@trace_unhandled_exceptions
def measures_hrna_basepairs(name, s, thr_idx):
    """
    Open a rna_only/ file, and run measures_hrna_basepairs_chain() on every chain
    """  

    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measures_hrna_basepairs({name})")
    
    l=[]
    chain = next(s[0].get_chains())
            
    # do not recompute something already computed
    if path.isfile(runDir + "/results/geometry/HiRE-RNA/basepairs/basepairs_"+name+".csv"):
        return

    df=pd.read_csv(os.path.abspath(path_to_3D_data +"datapoints/" + name))

    if df['index_chain'][0] == 1: # ignore files with numbering errors : TODO : remove when we get DSSR Pro, there should not be numbering errors anymore
        l = measures_hrna_basepairs_chain(name, chain, df, thr_idx)
    df_calc = pd.DataFrame(l, columns=["type_LW", "nt1_idx", "nt1_res", "nt2_idx", "nt2_res", "Distance", 
                                        "211_angle", "112_angle", "dB1", "dB2", "alpha1", "alpha2", "3211_torsion", "1123_torsion"])
    df_calc.to_csv(runDir + "/results/geometry/HiRE-RNA/basepairs/"+'basepairs_' + name + '.csv', float_format="%.3f")

@trace_unhandled_exceptions
def measures_hrna_basepairs_chain(name, chain, df, thr_idx):
    """
    Cleanup of the dataset
    measurements of distances and angles between paired nucleotides in the chain
    """

    results = []
    warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)

    pairs = df[['index_chain', 'old_nt_resnum', 'paired', 'pair_type_LW']] # columns we keep
    for i in range(pairs.shape[0]): # we remove the lines where no pairing (NaN in paired)
        index_with_nan = pairs.index[pairs.iloc[:,2].isnull()]
        pairs.drop(index_with_nan, 0, inplace=True)

    paired_int = []
    for i in pairs.index:   # convert values ​​from paired to integers or lists of integers
        paired = pairs.at[i, 'paired']
        if type(paired) is np.int64 or type(paired) is np.float64:
            paired_int.append(int(paired))
        else :  #strings
            if len(paired) < 3: # a single pairing
                paired_int.append(int(paired))         
            else : # several pairings
                paired = paired.split(',')
                l = [ int(i) for i in paired ]
                paired_int.append(l)

    pair_type_LW_bis = []
    for j in pairs.index:
        pair_type_LW = pairs.at[j, 'pair_type_LW']
        if len(pair_type_LW) < 4 : # a single pairing
            pair_type_LW_bis.append(pair_type_LW)
        else : # several pairings
            pair_type_LW = pair_type_LW.split(',')
            l = [ i for i in pair_type_LW ]
            pair_type_LW_bis.append(pair_type_LW)

    # addition of these new columns
    pairs.insert(4, "paired_int", paired_int, True)
    pairs.insert(5, "pair_type_LW_bis", pair_type_LW_bis, True)
    
    indexNames = pairs[pairs['paired_int'] == 0].index
    pairs.drop(indexNames, inplace=True) # deletion of lines with a 0 in paired_int (matching to another RNA chain)

    for i in tqdm(pairs.index, position=thr_idx+1, desc=f"Worker {thr_idx+1}: {name} measures_hrna_basepairs_chain", unit="res", leave=False):
        # calculations for each row of the pairs dataset
        index = pairs.at[i, 'index_chain'] 
        res1 =  chain[(' ', index, ' ')].get_resname()
        if res1 not in ['A','C','G','U']:
            continue
        type_LW = pairs.at[i, 'pair_type_LW_bis'] # pairing type
        num_paired = pairs.at[i, 'paired_int'] # number (index_chain) of the paired nucleotide
        
        if type(num_paired) is int or type(num_paired) is np.int64:
            res2 =  chain[(' ', num_paired, ' ')].get_resname()
            if res2 not in ["A","C","G","U"]:
                continue
            measures = basepair_measures(chain[(' ', index, ' ')], chain[(' ', num_paired, ' ')])
            if measures is not None:
                results.append([type_LW, index, res1, num_paired, res2] + measures)
        else:
            for j in range(len(num_paired)): # if several pairings, process them one by one
                if num_paired[j] != 0:
                    res2 =  chain[(' ', num_paired[j], ' ')].get_resname()
                    if res2 not in ["A","C","G","U"]:
                        continue
                    measures = basepair_measures(chain[(' ', index, ' ')], chain[(' ', num_paired[j], ' ')])
                    if measures is not None:
                        results.append([type_LW[j], index, res1, num_paired[j], res2] + measures)

    return results

@trace_unhandled_exceptions
def pyle_measures(name, s, thr_idx):

    if (path.isfile(runDir + '/results/geometry/Pyle/distances/distances_pyle_'+name+'.csv')):
        return

    liste_dist=[]
    #classes=[]
    #for i in range(0, 150, 5):
        #classes.append([i, i+5])
    #classes.append([150, 300])
    #occur_p_p=len(classes)*[0]
    #occur_p_c1=len(classes)*[0]
    #occur_p_c4=len(classes)*[0]
    #occur_c1_c1=len(classes)*[0]
    #occur_c4_c4=len(classes)*[0]
    #nb_occurs=[]
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} pyle_measures({name})")

    chain = next(s[0].get_chains())
    #residues=list(chain.get_residues())
    for res1 in tqdm(chain, position=thr_idx+1, desc=f"Worker {thr_idx+1}: {name} pyle_measures", unit="res", leave=False):
        #res1=chain[i]
        if res1.get_resname() in ["A", "C", "G", "U"]:
            resnum1=list(res1.get_id())[1]
            atom_p_1 = [ atom.get_coord() for atom in res1 if atom.get_name() ==  "P"]
            atom_c1p_1 = [ atom.get_coord() for atom in res1 if "C1'" in atom.get_fullname() ]
            atom_c4p_1 = [ atom.get_coord() for atom in res1 if "C4'" in atom.get_fullname() ]
            for res2 in chain:
                resnum2=list(res2.get_id())[1]
                if resnum2-resnum1 < 4 :
                    continue
                p_p=np.nan
                p_c4p=np.nan
                p_c1p=np.nan
                c4p_c4p=np.nan
                c1p_c1p=np.nan
                #res2=chain[j]
                if res2.get_resname() in ["A", "C", "G", "U"]:
                    
                    atom_p_2 = [ atom.get_coord() for atom in res2 if atom.get_name() ==  "P"]
                    atom_c1p_2 = [ atom.get_coord() for atom in res2 if "C1'" in atom.get_fullname() ]
                    atom_c4p_2 = [ atom.get_coord() for atom in res2 if "C4'" in atom.get_fullname() ]

                    p_p = get_euclidian_distance(atom_p_1, atom_p_2)
                    p_c4p= get_euclidian_distance(atom_p_1, atom_c4p_2)
                    p_c1p= get_euclidian_distance(atom_p_1, atom_c1p_2)
                    c4p_c4p= get_euclidian_distance(atom_c4p_1, atom_c4p_2)
                    c1p_c1p= get_euclidian_distance(atom_c1p_1, atom_c1p_2)

                    liste_dist.append([res1.get_resname(), int(resnum1), res2.get_resname(), int(resnum2), p_p, p_c4p, p_c1p, c4p_c4p, c1p_c1p])
                    '''
                    for x in range(len(classes)):
                        if classes[x][0] <= p_p <= classes[x][1]:
                            occur_p_p[x]=occur_p_p[x]+1
                        if classes[x][0] <= p_c4p <= classes[x][1]:
                            occur_p_c4[x]=occur_p_c4[x]+1                        
                        if classes[x][0] <= p_c1p <= classes[x][1]:
                            occur_p_c1[x]=occur_p_c1[x]+1
                        if classes[x][0] <= c4p_c4p <= classes[x][1]:
                            occur_c4_c4[x]=occur_c4_c4[x]+1
                        if classes[x][0] <= c1p_c1p <= classes[x][1]:
                            occur_c1_c1[x]=occur_c1_c1[x]+1
                    '''
    #for x in range(len(classes)):
        # for i in range(len(liste_dist)):
        #     if classes[x][0] <= liste_dist[i][4] <= classes[x][1]:
        #         occur_p_p[x]=occur_p_p[x]+1
        #     if classes[x][0] <= liste_dist[i][5] <= classes[x][1]:
        #         occur_p_c4[x]=occur_p_c4[x]+1                        
        #     if classes[x][0] <= liste_dist[i][6] <= classes[x][1]:
        #         occur_p_c1[x]=occur_p_c1[x]+1
        #     if classes[x][0] <= liste_dist[i][7] <= classes[x][1]:
        #         occur_c4_c4[x]=occur_c4_c4[x]+1
        #     if classes[x][0] <= liste_dist[i][8] <= classes[x][1]:
        #         occur_c1_c1[x]=occur_c1_c1[x]+1
        #nb_occurs.append([classes[x], occur_p_p[x], occur_p_c1[x], occur_p_c4[x], occur_c1_c1[x], occur_c4_c4[x]])
    #df = pd.DataFrame(nb_occurs, columns=["classe", "P-P", "P-C1'", "P-C4'", "C1'-C1'", "C4'-C4'"])
    # return df
    # nb_occurs.append([classes, occur_p_p, occur_p_c1, occur_p_c4, occur_c1_c1, occur_c4_c4])
    # print(nb_occurs)
    # return nb_occurs
                    

    df = pd.DataFrame(liste_dist, columns=["res1", "resnum1", "res2", "resnum2", "P-P", "P-C4'", "P-C1'", "C4'-C4'", "C1'-C1'"])
    df.to_csv(runDir + "/results/geometry/Pyle/distances/distances_pyle_" + name + ".csv")

@trace_unhandled_exceptions
def count_occur_pyle_dist(fpath):
    
    global idxQueue
    thr_idx = idxQueue.get()
    setproctitle(f"Worker {thr_idx+1} : Extract occurences of {fpath}")    

    liste=os.listdir(fpath)
    pbar = tqdm(total=len(liste), position=thr_idx, desc="Preparing ", leave=False)
    df = pd.read_csv(os.path.abspath(fpath + liste.pop()))
    occur_p_p=list(df["P-P"])
    occur_p_c1=list(df["P-C1'"])
    occur_p_c4=list(df["P-C4'"])
    occur_c1_c1=list(df["C1'-C1'"])
    occur_c4_c4=list(df["C4'-C4'"])
    nb_occurs=[]
    for f in range(len(liste)):
        df = pd.read_csv(os.path.abspath(fpath + liste.pop()))
        # print(liste[f])
        for k in range(df.shape[0]):
            occur_p_p[k]=occur_p_p[k]+df["P-P"][k]
            occur_p_c1[k]=occur_p_c1[k]+df["P-C1'"][k]
            occur_p_c4[k]=occur_p_c4[k]+df["P-C4'"][k]
            occur_c1_c1[k]=occur_c1_c1[k]+df["C1'-C1'"][k]
            occur_c4_c4[k]=occur_c4_c4[k]+df["C4'-C4'"][k]
        pbar.update(1)
    nb_occurs=[occur_p_p, occur_p_c1, occur_p_c4, occur_c1_c1, occur_c4_c4]
    # return(list(df["classe"]), occur_p_p, occur_p_c1, occur_p_c4, occur_c1_c1, occur_c4_c4)
    df = pd.DataFrame(nb_occurs, columns=list(df["classe"]))

    df.to_csv(runDir + "/results/geometry/Pyle/classes_dist/occurences_dist.csv")
    idxQueue.put(thr_idx) # replace the thread index in the queue
    setproctitle(f"RNANet statistics.py Worker {thr_idx+1} finished")


@trace_unhandled_exceptions
def GMM_histo(data_ori, name_data, toric=False, hist=True, col=None, save=True) :
    """
    Plot Gaussian-Mixture-Model (with or without histograms)
    """
    data_ori = np.array(data_ori)

    if toric:
        # Extend the data on the right and on the left (for angles)
        data = np.concatenate([data_ori, data_ori-360.0, data_ori+360.0])
    else:
        data = data_ori

    # chooses the number of components based on the maximum likelihood value (maxlogv)
    n_components_range = np.arange(8)+1
    # aic = []
    # bic = []
    maxlogv=[]
    md = np.array(data).reshape(-1,1)
    nb_components = 1
    nb_log_max = n_components_range[0]
    log_max = 0
    for n_comp in n_components_range:
        gmm = GaussianMixture(n_components=n_comp).fit(md)
        # aic.append(abs(gmm.aic(md)))
        # bic.append(abs(gmm.bic(md)))
        maxlogv.append(gmm.lower_bound_)
        if gmm.lower_bound_== max(maxlogv) : # takes the maximum
            nb_components = n_comp
            # if there is convergence, keep the first maximum found
            if abs(gmm.lower_bound_-log_max) < 0.02 : #threshold=0.02
                nb_components = nb_log_max
                break
        log_max = max(maxlogv)
        nb_log_max = n_comp

    
    # Now compute the final GMM
    obs = np.array(data).reshape(-1,1) # still on extended data
    g = GaussianMixture(n_components=nb_components)
    g.fit(obs)

    if toric:
        # Now decide which to keep
        keep = []
        weights = []
        means = []
        covariances = []
        sum_weights = 0.0
        for m in g.means_:
            keep.append(m > -180 and m <= 180)
        for i, w in enumerate(g.weights_):
            if not keep[i]:
                continue
            sum_weights += w
        for i in range(nb_components):
            if not keep[i]:
                continue
            means.append(g.means_[i])
            covariances.append(g.covariances_[i])
            weights.append(g.weights_[i]/sum_weights)
        nb_components = len(means)
    else:
        weights = g.weights_
        means = g.means_
        covariances = g.covariances_

    # plot histograms if asked, with the appropriate number of components
    if hist:
        plt.hist(data_ori, color="green", edgecolor='black', linewidth=1.2, bins=50, density=True)
    if toric:
        plt.xlabel("Angle (Degrees)")
    else:
        plt.xlabel("Distance (Angströms)")
    plt.ylabel("Density")

    # Prepare the GMM curve with some absciss points
    if toric:
        x = np.linspace(-360.0,360.0,721)
    else:
        D = obs.ravel()
        xmin = D.min()
        #xmax = min(10.0, D.max())
        xmax = D.max()
        x = np.linspace(xmin,xmax,1000)
    colors=['red', 'blue', 'gold', 'cyan', 'magenta', 'white', 'black', 'green']

    # prepare the dictionary to save the parameters
    summary_data = {}
    summary_data["measure"] = name_data
    summary_data["weights"] = []
    summary_data["means"] = []
    summary_data["std"] = []

    # plot
    curves = []
    for i in range(nb_components):

        # store the parameters
        mean = means[i]
        sigma = np.sqrt(covariances[i])
        weight = weights[i]
        summary_data["means"].append("{:.2f}".format(float(str(mean).strip("[]"))))
        summary_data["std"].append("{:.2f}".format(float(str(sigma).strip("[]"))))
        summary_data["weights"].append("{:.2f}".format(float(str(weight).strip("[]"))))

        # compute the right x and y data to plot
        y = weight*st.norm.pdf(x, mean, sigma)
        if toric:
            y_mod = (((y[0]+180.0)%360.0)-180.0)
            x_mod = (((x+180.0)%360.0)-180.0)
            s = sorted(zip(x_mod,y_mod))
            newx = []
            newy = []
            for k in range(0, len(s), 2):
                if k == 362.0:
                    continue # this value is dealt with when k = 360.0
                # print(k, "summing: ", s[k-int(k>360)], s[k+1-int(k>360)])
                newx.append(s[k-int(k>360)][0])
                if k == 360.0:
                    newy.append(s[k][1]+s[k+1][1]+s[k+2][1])
                else:
                    newy.append(s[k-int(k>360)][1]+s[k+1-int(k>360)][1])
        else:
            newx = x
            newy = y[0]

        if hist:
            # plot on top of the histograms
            plt.plot(newx, newy, c=colors[i])
        else:
            # store for later summation
            curves.append(np.array(newy))

    if hist:
        plt.title(f"Histogram of {name_data} with GMM of {nb_components} components (" + str(len(data_ori))+" values)")
        if save:
            plt.savefig(f"Histogram_{name_data}_{nb_components}_comps.png")
            plt.close()
    else:
        # Plot their sum, do not save figure yet
        try:
            plt.plot(newx, sum(curves), c=col, label=name_data)
        except TypeError:
            print("N curves:", len(curves))
            for c in curves:
                print(c)
        plt.legend()

        # Save the json
        with open(runDir + "/results/geometry/json/" +name_data + ".json", 'w', encoding='utf-8') as f:
            json.dump(summary_data, f, indent=4)

@trace_unhandled_exceptions
def gmm_aa_dists():
    """
    Draw the figures representing the data on the measurements of distances between atoms
    """

    setproctitle("GMM (all atoms, distances)")

    df=pd.read_csv(os.path.abspath(runDir + "/results/geometry/all-atoms/distances/dist_atoms.csv"))

    last_o3p_p=list(df["O3'-P"][~ np.isnan(df["O3'-P"])])
    #print(last_o3p_p)
    op3_p=list(df["OP3-P"][~ np.isnan(df["OP3-P"])])
    p_op1=list(df["P-OP1"][~ np.isnan(df["P-OP1"])])
    p_op2=list(df["P-OP2"][~ np.isnan(df["P-OP2"])])
    p_o5p=list(df["P-O5'"][~ np.isnan(df["P-O5'"])])
    o5p_c5p=list(df["O5'-C5'"][~ np.isnan(df["O5'-C5'"])])
    c5p_c4p=list(df["C5'-C4'"][~ np.isnan(df["C5'-C4'"])])
    c4p_o4p=list(df["C4'-O4'"][~ np.isnan(df["C4'-O4'"])])
    o4p_c1p=list(df["O4'-C1'"][~ np.isnan(df["O4'-C1'"])])
    c1p_c2p=list(df["C1'-C2'"][~ np.isnan(df["C1'-C2'"])])
    c2p_o2p=list(df["C2'-O2'"][~ np.isnan(df["C2'-O2'"])])
    c2p_c3p=list(df["C2'-C3'"][~ np.isnan(df["C2'-C3'"])])
    c3p_o3p=list(df["C3'-O3'"][~ np.isnan(df["C3'-O3'"])])
    c4p_c3p=list(df["C4'-C3'"][~ np.isnan(df["C4'-C3'"])])
    
    #if res = A ou G
    c1p_n9=list(df["C1'-N9"][~ np.isnan(df["C1'-N9"])])
    n9_c8=list(df["N9-C8"][~ np.isnan(df["N9-C8"])])
    c8_n7=list(df["C8-N7"][~ np.isnan(df["C8-N7"])])
    n7_c5=list(df["N7-C5"][~ np.isnan(df["N7-C5"])])
    c5_c6=list(df["C5-C6"][~ np.isnan(df["C5-C6"])])
    c6_n1=list(df["C6-N1"][~ np.isnan(df["C6-N1"])])
    n1_c2=list(df["N1-C2"][~ np.isnan(df["N1-C2"])])
    c2_n3=list(df["C2-N3"][~ np.isnan(df["C2-N3"])])
    n3_c4=list(df["N3-C4"][~ np.isnan(df["N3-C4"])])
    c4_n9=list(df["C4-N9"][~ np.isnan(df["C4-N9"])])
    c4_c5=list(df["C4-C5"][~ np.isnan(df["C4-C5"])])
    #if res=G
    c6_o6=list(df["C6-O6"][~ np.isnan(df["C6-O6"])])
    c2_n2=list(df["C2-N2"][~ np.isnan(df["C2-N2"])])
    #if res = A
    c6_n6=list(df["C6-N6"][~ np.isnan(df["C6-N6"])])

    #if res = C ou U
    c1p_n1=list(df["C1'-N1"][~ np.isnan(df["C1'-N1"])])
    n1_c6=list(df["N1-C6"][~ np.isnan(df["N1-C6"])])
    c6_c5=list(df["C6-C5"][~ np.isnan(df["C6-C5"])])
    c5_c4=list(df["C5-C4"][~ np.isnan(df["C5-C4"])])
    c4_n3=list(df["C4-N3"][~ np.isnan(df["C4-N3"])])
    n3_c2=list(df["N3-C2"][~ np.isnan(df["N3-C2"])])
    c2_n1=list(df["C2-N1"][~ np.isnan(df["C2-N1"])])
    c2_o2=list(df["C2-O2"][~ np.isnan(df["C2-O2"])])
    #if res =C
    c4_n4=list(df["C4-N4"][~ np.isnan(df["C4-N4"])])
    #if res=U
    c4_o4=list(df["C4-O4"][~ np.isnan(df["C4-O4"])])

    os.makedirs(runDir+"/results/figures/GMM/all-atoms/distances/commun/", exist_ok=True)
    os.chdir(runDir+"/results/figures/GMM/all-atoms/distances/commun/")
    # draw figures for atoms common to all nucleotides
    GMM_histo(last_o3p_p, "O3'-P")
    if len(op3_p) > 0 :
        GMM_histo(op3_p, "OP3-P")
    GMM_histo(p_op1, "P-OP1")
    GMM_histo(p_op2, "P-OP2")
    
    GMM_histo(p_o5p, "P-O5'")
    GMM_histo(o5p_c5p, "O5'-C5'")
    GMM_histo(c5p_c4p, "C5'-C4'")
    GMM_histo(c4p_o4p, "C4'-O4'")
    GMM_histo(c4p_c3p, "C4'-C3'")
    GMM_histo(c3p_o3p, "C3'-O3'")
    GMM_histo(o4p_c1p, "O4'-C1'")
    GMM_histo(c1p_c2p, "C1'-C2'")
    GMM_histo(c2p_c3p, "C2'-C3'")
    GMM_histo(c2p_o2p, "C2'-O2'")

    if len(op3_p) > 0 :
        GMM_histo(op3_p, "OP3-P", toric=False, hist=False, col= 'lightcoral')
    GMM_histo(p_op1, "P-OP1", toric=False, hist=False, col='gold')
    GMM_histo(p_op2, "P-OP2", toric=False, hist=False, col='lightseagreen')
    GMM_histo(last_o3p_p, "O3'-P", toric=False, hist=False, col='saddlebrown')
    GMM_histo(p_o5p, "P-O5'", toric=False, hist=False, col='darkturquoise')
    GMM_histo(o5p_c5p, "O5'-C5'", toric=False, hist=False, col='darkkhaki')
    GMM_histo(c5p_c4p, "C5'-C4'", toric=False, hist=False, col='indigo')
    GMM_histo(c4p_o4p, "C4'-O4'", toric=False, hist=False, col='maroon')
    GMM_histo(c4p_c3p, "C4'-C3'", toric=False, hist=False, col='burlywood')
    GMM_histo(c3p_o3p, "C3'-O3'", toric=False, hist=False, col='steelblue')
    GMM_histo(o4p_c1p, "O4'-C1'", toric=False, hist=False, col='tomato')
    GMM_histo(c1p_c2p, "C1'-C2'", toric=False, hist=False, col='darkolivegreen')
    GMM_histo(c2p_c3p, "C2'-C3'", toric=False, hist=False, col='orchid')
    GMM_histo(c2p_o2p, "C2'-O2'", toric=False, hist=False, col='deeppink')
    axes=plt.gca()
    axes.set_ylim(0, 100)
    plt.xlabel("Distance (Angströms)")
    plt.title("GMM of distances between common atoms ")
    plt.savefig(runDir + "/results/figures/GMM/all-atoms/distances/commun/" + "GMM_distances_common_atoms.png")
    plt.close()

    os.makedirs(runDir+"/results/figures/GMM/all-atoms/distances/purines/", exist_ok=True)
    os.chdir(runDir+"/results/figures/GMM/all-atoms/distances/purines/")
    # purines
    GMM_histo(c1p_n9, "C1'-N9")
    GMM_histo(n9_c8, "N9-C8")
    GMM_histo(c8_n7, "C8-N7")
    GMM_histo(n7_c5, "N7-C5")
    GMM_histo(c5_c6, "C5-C6")
    GMM_histo(c6_o6, "C6-O6")
    GMM_histo(c6_n6, "C6-N6")
    GMM_histo(c6_n1, "C6-N1")
    GMM_histo(n1_c2, "N1-C2")
    GMM_histo(c2_n2, "C2-N2")
    GMM_histo(c2_n3, "C2-N3")
    GMM_histo(n3_c4, "N3-C4")
    GMM_histo(c4_n9, "C4-N9")
    GMM_histo(c4_c5, "C4-C5")

    GMM_histo(c1p_n9, "C1'-N9", hist=False, col='lightcoral')
    GMM_histo(n9_c8, "N9-C8", hist=False, col='gold')
    GMM_histo(c8_n7, "C8-N7", hist=False, col='lightseagreen')
    GMM_histo(n7_c5, "N7-C5", hist=False, col='saddlebrown')
    GMM_histo(c5_c6, "C5-C6", hist=False, col='darkturquoise')
    GMM_histo(c6_o6, "C6-O6", hist=False, col='darkkhaki')
    GMM_histo(c6_n6, "C6-N6", hist=False, col='indigo')
    GMM_histo(c6_n1, "C6-N1", hist=False, col='maroon')
    GMM_histo(n1_c2, "N1-C2", hist=False, col='burlywood')
    GMM_histo(c2_n2, "C2-N2", hist=False, col='steelblue')
    GMM_histo(c2_n3, "C2-N3", hist=False, col='tomato')
    GMM_histo(n3_c4, "N3-C4", hist=False, col='darkolivegreen')
    GMM_histo(c4_n9, "C4-N9", hist=False, col='orchid')
    GMM_histo(c4_c5, "C4-C5", hist=False, col='deeppink')
    axes=plt.gca()
    axes.set_ylim(0, 100)
    plt.xlabel("Distance (Angströms)")
    plt.title("GMM of distances between atoms of the purine cycles", fontsize=10)
    plt.savefig(runDir+ "/results/figures/GMM/all-atoms/distances/purines/" + "GMM_distances_purine_cycles.png")
    plt.close()

    os.makedirs(runDir+"/results/figures/GMM/all-atoms/distances/pyrimidines/", exist_ok=True)
    os.chdir(runDir+"/results/figures/GMM/all-atoms/distances/pyrimidines/")
    # pyrimidines

    GMM_histo(c1p_n1, "C1'-N1")
    GMM_histo(n1_c6, "N1-C6")
    GMM_histo(c6_c5, "C6-C5")
    GMM_histo(c5_c4, "C5-C4")
    GMM_histo(c4_n3, "C4-N3")
    GMM_histo(n3_c2, "N3-C2")
    GMM_histo(c2_o2, "C2-O2")
    GMM_histo(c2_n1, "C2-N1")
    GMM_histo(c4_n4, "C4-N4")
    GMM_histo(c4_o4, "C4-O4")

    GMM_histo(c1p_n1, "C1'-N1", hist=False, col='lightcoral')
    GMM_histo(n1_c6, "N1-C6", hist=False, col='gold')
    GMM_histo(c6_c5, "C6-C5", hist=False, col='lightseagreen')
    GMM_histo(c5_c4, "C5-C4", hist=False, col='deeppink')
    GMM_histo(c4_n3, "C4-N3", hist=False, col='red')
    GMM_histo(n3_c2, "N3-C2", hist=False, col='lime')
    GMM_histo(c2_o2, "C2-O2", hist=False, col='indigo')
    GMM_histo(c2_n1, "C2-N1", hist=False, col='maroon')
    GMM_histo(c4_n4, "C4-N4", hist=False, col='burlywood')
    GMM_histo(c4_o4, "C4-O4", hist=False, col='steelblue')
    axes=plt.gca()
    #axes.set_xlim(1, 2)
    axes.set_ylim(0, 100)
    plt.xlabel("Distance (Angströms")
    plt.title("GMM of distances between atoms of the pyrimidine cycles", fontsize=10)
    plt.savefig(runDir + "/results/figures/GMM/all-atoms/distances/pyrimidines/" + "GMM_distances_pyrimidine_cycles.png")
    plt.close()

    os.chdir(runDir)
    setproctitle("GMM (all atoms, distances) finished")

@trace_unhandled_exceptions
def gmm_aa_torsions():
    """
    Separates the torsion angle measurements by angle type and plots the figures representing the data
    """
    setproctitle("GMM (all atoms, torsions)")

    # we create lists to store the values ​​of each angle
    alpha=[]
    beta=[]
    gamma=[]
    delta=[]
    epsilon=[]
    zeta=[]
    chi = []
    for angles_deg in conversion_angles(runDir + "/results/RNANet.db"): 
        alpha.append(angles_deg[2])
        beta.append(angles_deg[3])
        gamma.append(angles_deg[4])
        delta.append(angles_deg[5])
        epsilon.append(angles_deg[6])
        zeta.append(angles_deg[7])
        chi.append(angles_deg[8])

    # we remove the null values
    alpha=[i for i in alpha if i != None]
    beta=[i for i in beta if i != None]
    gamma=[i for i in gamma if i != None]
    delta=[i for i in delta if i != None]
    epsilon=[i for i in epsilon if i != None]
    zeta=[i for i in zeta if i != None]
    chi=[i for i in chi if i != None]

    os.makedirs(runDir + "/results/figures/GMM/all-atoms/torsions/", exist_ok=True)
    os.chdir(runDir + "/results/figures/GMM/all-atoms/torsions/")

    """
    We plot the GMMs with histogram for each angle
    We create the corresponding json with the means and standard deviations of each Gaussian
    We draw the figure grouping the GMMs of all angles without histogram to compare them with each other
    """

    GMM_histo(alpha, "Alpha", toric=True)
    GMM_histo(beta, "Beta", toric=True)
    GMM_histo(gamma, "Gamma", toric=True)
    GMM_histo(delta, "Delta", toric=True)
    GMM_histo(epsilon, "Epsilon", toric=True)
    GMM_histo(zeta, "Zeta", toric=True)
    GMM_histo(chi, "Xhi", toric=True)

    GMM_histo(alpha, "Alpha", toric=True, hist=False, col='red')
    GMM_histo(beta, "Beta", toric=True, hist=False, col='firebrick')
    GMM_histo(gamma, "Gamma", toric=True, hist=False, col='limegreen')
    GMM_histo(delta, "Delta", toric=True, hist=False, col='darkslateblue')
    GMM_histo(epsilon, "Epsilon", toric=True, hist=False, col='goldenrod')
    GMM_histo(zeta, "Zeta", toric=True, hist=False, col='teal')
    GMM_histo(chi, "Xhi", toric=True, hist=False, col='hotpink')
    plt.xlabel("Angle (Degrees)")
    plt.title("GMM of torsion angles")
    plt.savefig("GMM_torsions.png")
    plt.close()

    os.chdir(runDir)
    setproctitle("GMM (all atoms, torsions) finished")

@trace_unhandled_exceptions
def gmm_wadley():

    setproctitle("GMM (Pyle model)")

    # Distances
    df = pd.read_csv(os.path.abspath(runDir + "/results/geometry/Pyle/distances/distances_wadley.csv"))  

    p_c1p = list(df["C1'-P"][~ np.isnan(df["C1'-P"])])
    c1p_p = list(df["P-C1'"][~ np.isnan(df["P-C1'"])])
    p_c4p = list(df["C4'-P"][~ np.isnan(df["C4'-P"])])
    c4p_p = list(df["P-C4'"][~ np.isnan(df["P-C4'"])])

    os.makedirs(runDir + "/results/figures/GMM/Pyle/distances/", exist_ok=True)
    os.chdir(runDir + "/results/figures/GMM/Pyle/distances/")

    GMM_histo(p_c1p, "P-C1'")
    GMM_histo(c1p_p, "C1'-P")
    GMM_histo(p_c4p, "P-C4'")
    GMM_histo(c4p_p, "C4'-P")

    GMM_histo(p_c4p, "P-C4'", toric=False, hist=False, col='gold')
    GMM_histo(c4p_p, "C4'-P", toric=False, hist=False, col='indigo')
    GMM_histo(p_c1p, "P-C1'", toric=False, hist=False, col='firebrick')
    GMM_histo(c1p_p, "C1'-P", toric=False, hist=False, col='seagreen')
    plt.xlabel("Distance (Angströms)")
    plt.title("GMM of distances (Pyle model)")
    plt.savefig("GMM_distances_pyle_model.png")
    plt.close()

    # Flat Angles
    df = pd.read_csv(os.path.abspath(runDir + "/results/geometry/Pyle/angles/flat_angles_pyle.csv"))  

    p_c1p_psuiv = list(df["P-C1'-P°"][~ np.isnan(df["P-C1'-P°"])])
    c1p_psuiv_c1psuiv = list(df["C1'-P°-C1'°"][~ np.isnan(df["C1'-P°-C1'°"])])


    os.makedirs(runDir + "/results/figures/GMM/Pyle/angles/", exist_ok=True)
    os.chdir(runDir + "/results/figures/GMM/Pyle/angles/")

    GMM_histo(p_c1p_psuiv, "P-C1'-P°", toric=True)
    GMM_histo(c1p_psuiv_c1psuiv, "C1'-P°-C1'°", toric=True)

    GMM_histo(p_c1p_psuiv, "P-C1'-P°", toric=True, hist=False, col='firebrick')
    GMM_histo(c1p_psuiv_c1psuiv, "C1'-P°-C1'°", toric=True, hist=False, col='seagreen')
    plt.xlabel("Angle (Degrees)")
    plt.title("GMM of flat angles (Pyle model)")
    plt.savefig("GMM_flat_angles_pyle_model.png")
    plt.close()

    # Torsion angles    
    eta=[]
    theta=[]
    eta_prime=[]
    theta_prime=[]
    eta_base=[]
    theta_base=[]

    for angles_deg in conversion_eta_theta(runDir + "/results/RNANet.db"): 
        eta.append(angles_deg[2])
        theta.append(angles_deg[3])
        eta_prime.append(angles_deg[4])
        theta_prime.append(angles_deg[5])
        eta_base.append(angles_deg[6])
        theta_base.append(angles_deg[7])

    eta=[i for i in eta if i != None]
    theta=[i for i in theta if i != None]
    eta_prime=[i for i in eta_prime if i != None]
    theta_prime=[i for i in theta_prime if i != None]
    eta_base=[i for i in eta_base if i != None]
    theta_base=[i for i in theta_base if i != None]


    os.makedirs(runDir + "/results/figures/GMM/Pyle/pseudotorsions/", exist_ok=True)
    os.chdir(runDir + "/results/figures/GMM/Pyle/pseudotorsions/")

    GMM_histo(eta, "Eta", toric=True)
    GMM_histo(theta, "Theta", toric=True)
    GMM_histo(eta_prime, "Eta'", toric=True)
    GMM_histo(theta_prime, "Theta'", toric=True)
    GMM_histo(eta_base, "Eta''", toric=True)
    GMM_histo(theta_base, "Theta''", toric=True)

    GMM_histo(eta, "Eta", toric=True, hist=False, col='mediumaquamarine')
    GMM_histo(theta, "Theta", toric=True, hist=False, col='darkorchid')
    GMM_histo(eta_prime, "Eta'", toric=True, hist=False, col='cyan')
    GMM_histo(theta_prime, "Theta'", toric=True, hist=False, col='crimson')
    GMM_histo(eta_base, "Eta''", toric=True, hist=False, col='royalblue')
    GMM_histo(theta_base, "Theta''", toric=True, hist=False, col='palevioletred')
    plt.xlabel("Angle (Degrees)")
    plt.title("GMM of pseudo-torsion angles (Pyle Model)")
    plt.savefig("GMM_pseudotorsion_angles_pyle_model.png")
    plt.close()
    
    os.chdir(runDir)
    setproctitle("GMM (Pyle model) finished")   

def gmm_pyle_type(ntpair, data):

    setproctitle(f"GMM (Pyle {ntpair} )")
    
    os.makedirs(runDir + "/results/figures/GMM/Pyle/distances/", exist_ok=True)
    os.chdir(runDir + "/results/figures/GMM/Pyle/distances/")

    p_p=list(data["P-P"][~ np.isnan(data["P-P"])])
    p_c4p=list(data["P-C4'"][~ np.isnan(data["P-C4'"])])
    p_c1p=list(data["P-C1'"][~ np.isnan(data["P-C1'"])])
    c4p_c4p=list(data["C4'-C4'"][~ np.isnan(data["C4'-C4'"])])
    c1p_c1p=list(data["C1'-C1'"][~ np.isnan(data["C1'-C1'"])])
    print(len(p_p))
    # res2=list(data["resnum2"])
    # res1=list(data["resnum1"])
    # diff=[]
    # for i in range(len(res1)):
    #     diff.append(res2[i]-res1[i])
    # print(diff[:100])
    
    GMM_histo(p_p, f"Distance P-P between {ntpair} tips for {str(len(p_p))} values", toric=False, hist=False, col="cyan")
    GMM_histo(p_c4p, f"Distance P-C4' between {ntpair} tips", toric=False, hist=False, col="tomato")
    GMM_histo(p_c1p, f"Distance P-C1' between {ntpair} tips", toric=False, hist=False, col="goldenrod")
    GMM_histo(c4p_c4p, f"Distance C4'-C4' between {ntpair} tips", toric=False, hist=False, col="magenta")
    GMM_histo(c1p_c1p, f"Distance C1'-C1' between {ntpair} tips", toric=False, hist=False, col="black")
    # GMM_histo(diff, f"Gap between {ntpair} tips", toric=False, hist=False, col="tomato")
    plt.xlabel("Distance (Angströms)")
    
    # plt.xlabel("Number of residues")
    plt.ylabel("Distance (Angströms)")
    plt.title(f"GMM of distances for {ntpair} ", fontsize=10)

    # plt.savefig(f"Longueurs_Pyle_{ntpair}.png" )
    plt.savefig(f"Distances_Pyle_{ntpair}.png" )
    plt.close()
    setproctitle(f"GMM (Pyle {ntpair} distances) finished")

def gmm_pyle():

    setproctitle("GMM (Pyle model)")

    df = pd.read_csv(os.path.abspath(runDir + "/results/geometry/Pyle/distances/distances.csv"))

    # dist = ["P-P", "P-C4'", "P-C1'", "C4'-C4'", "C1'-C1'"]
    data=df
    if len(data):
        for b1 in ['A','C','G','U']:
            for b2 in ['A','C','G','U']:
                thisbases = data[(data.res1 == b1)&(data.res2 == b2)]
                if len(thisbases):
                    gmm_pyle_type(b1+b2, thisbases)

@trace_unhandled_exceptions
def gmm_hrna():
    """
    Draw the figures representing the data on the measurements between atoms of the HiRE-RNA model
    """

    setproctitle("GMM (HiRE-RNA)")

    # Distances
    df = pd.read_csv(os.path.abspath(runDir + "/results/geometry/HiRE-RNA/distances/dist_atoms_hire_RNA.csv"))  

    last_c4p_p = list(df["C4'-P"][~ np.isnan(df["C4'-P"])])
    p_o5p = list(df["P-O5'"][~ np.isnan(df["P-O5'"])])
    o5p_c5p = list(df["O5'-C5'"][~ np.isnan(df["O5'-C5'"])])
    c5p_c4p = list(df["C5'-C4'"][~ np.isnan(df["C5'-C4'"])])
    c4p_c1p = list(df["C4'-C1'"][~ np.isnan(df["C4'-C1'"])])
    c1p_b1 = list(df["C1'-B1"][~ np.isnan(df["C1'-B1"])])
    b1_b2 = list(df["B1-B2"][~ np.isnan(df["B1-B2"])])

    os.makedirs(runDir + "/results/figures/GMM/HiRE-RNA/distances/", exist_ok=True)
    os.chdir(runDir + "/results/figures/GMM/HiRE-RNA/distances/")

    GMM_histo(o5p_c5p, "O5'-C5'")
    GMM_histo(b1_b2, "B1-B2")
    GMM_histo(c1p_b1, "C1'-B1")
    GMM_histo(c5p_c4p, "C5'-C4'")
    GMM_histo(c4p_c1p, "C4'-C1'")
    GMM_histo(p_o5p, "P-O5'")
    GMM_histo(last_c4p_p, "C4'-P")
    
    GMM_histo(o5p_c5p, "O5'-C5'", toric=False, hist=False, col='lightcoral')
    GMM_histo(b1_b2, "B1-B2", toric=False, hist=False, col='limegreen')
    GMM_histo(c1p_b1, "C1'-B1", toric=False, hist=False, col='tomato')
    GMM_histo(c5p_c4p, "C5'-C4'", toric=False, hist=False, col='aquamarine')
    GMM_histo(c4p_c1p, "C4'-C1'", toric=False, hist=False, col='goldenrod')
    GMM_histo(p_o5p, "P-O5'", toric=False, hist=False, col='darkcyan')
    GMM_histo(last_c4p_p, "C4'-P", toric=False, hist=False, col='deeppink')
    axes = plt.gca()
    axes.set_ylim(0, 100)
    plt.xlabel("Distance (Angströms)")
    plt.title("GMM of distances between HiRE-RNA beads")
    plt.savefig(runDir + "/results/figures/GMM/HiRE-RNA/distances/GMM_distances_HiRE_RNA.png")
    plt.close()

    # Angles
    df = pd.read_csv(os.path.abspath(runDir + "/results/geometry/HiRE-RNA/angles/angles_hire_RNA.csv"))  

    lastc4p_p_o5p = list(df["C4'-P-O5'"][~ np.isnan(df["C4'-P-O5'"])])
    lastc1p_lastc4p_p = list(df["C1'-C4'-P"][~ np.isnan(df["C1'-C4'-P"])])
    lastc5p_lastc4p_p = list(df["C5'-C4'-P"][~ np.isnan(df["C5'-C4'-P"])])
    p_o5p_c5p = list(df["P-O5'-C5'"][~ np.isnan(df[