File size: 118,347 Bytes
c668e80 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 |
import numpy as np
from rdkit import Chem
import os
import sys
import copy
import re
from typing import List, Any
from indigo import *
indigo = Indigo()
import rdkit
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
print('rdkit version:' + rdkit.__version__)
BOND_TYPES = [None, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, \
Chem.rdchem.BondType.TRIPLE, Chem.rdchem.BondType.AROMATIC]
BOND_FLOAT_TO_TYPE = {
0.0: BOND_TYPES[0],
1.0: BOND_TYPES[1],
2.0: BOND_TYPES[2],
3.0: BOND_TYPES[3],
1.5: BOND_TYPES[4],}
def get_bond_info(mol: Chem.Mol):
"""Get information on bonds in the molecule.
Parameters
----------
mol: Chem.Mol
Molecule
"""
if mol is None:
return {}
bond_info = {}
for bond in mol.GetBonds():
a_start = bond.GetBeginAtom().GetAtomMapNum()
a_end = bond.GetEndAtom().GetAtomMapNum()
key_pair = sorted([a_start, a_end])
bond_info[tuple(key_pair)] = [bond.GetBondTypeAsDouble(), bond.GetIdx()]
return bond_info
def map_reac_and_frag(reac_mols: List[Chem.Mol], frag_mols: List[Chem.Mol]):
"""Aligns reactant and fragment mols by computing atom map overlaps.
Parameters
----------
reac_mols: List[Chem.Mol],
List of reactant mols
frag_mols: List[Chem.Mol],
List of fragment mols
"""
if len(reac_mols) != len(frag_mols):
return reac_mols, frag_mols
reac_maps = [[atom.GetAtomMapNum() for atom in mol.GetAtoms()] for mol in reac_mols]
frag_maps = [[atom.GetAtomMapNum() for atom in mol.GetAtoms()] for mol in frag_mols]
overlaps = {i: [] for i in range(len(frag_mols))}
for i, fmap in enumerate(frag_maps):
overlaps[i].extend([len(set(fmap).intersection(set(rmap))) for rmap in reac_maps])
overlaps[i] = overlaps[i].index(max(overlaps[i]))
new_frag = [Chem.Mol(mol) for mol in frag_mols]
new_reac = [Chem.Mol(reac_mols[overlaps[i]]) for i in overlaps]
return new_reac, new_frag
def remove_s_H(frag_mol):
while True:
idx = ''
for atom in frag_mol.GetAtoms():
if atom.GetAtomicNum() == 1 and atom.GetDegree() == 0:
idx= atom.GetIdx()
if idx != '' :
edit_mol = Chem.RWMol(frag_mol)
edit_mol.RemoveAtom(idx)
frag_mol = edit_mol.GetMol()
else:
break
return frag_mol
def apply_edits_to_mol_change(mol, edits):
"""Apply edits to molecular graph.
Parameters
----------
mol: Chem.Mol,
RDKit mol object
edits: Iterable[str],
Iterable of edits to apply. An edit is structured as a1:a2:b1:b2, where
a1, a2 are atom maps of participating atoms and b1, b2 are previous and
new bond orders. When a2 = 0, we update the hydrogen count.
"""
new_mol = Chem.RWMol(mol)
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in new_mol.GetAtoms()}
for edit in edits:
x, y, prev_bo, new_bo = edit.split(":")
x, y = int(x), int(y)
new_bo = float(new_bo)
bond = new_mol.GetBondBetweenAtoms(amap[x],amap[y])
if new_bo > 0:
if bond is not None:
new_mol.RemoveBond(amap[x],amap[y])
new_mol.AddBond(amap[x],amap[y],BOND_FLOAT_TO_TYPE[new_bo])
atom_x,atom_y = new_mol.GetAtomWithIdx(amap[x]),new_mol.GetAtomWithIdx(amap[y])
try:
atom_x.SetNumExplicitHs(int(atom_x.GetNumExplicitHs()+ float(prev_bo)-float(new_bo)))
except:
atom_x.SetNumExplicitHs(0)
try:
atom_y.SetNumExplicitHs(int(atom_y.GetNumExplicitHs()+ float(prev_bo)-float(new_bo)))
except:
atom_y.SetNumExplicitHs(0)
pred_mol = new_mol.GetMol()
return pred_mol
def apply_edits_to_mol_break(mol, edits):
"""Apply edits to molecular graph.
Parameters
----------
mol: Chem.Mol,
RDKit mol object
edits: Iterable[str],
Iterable of edits to apply. An edit is structured as a1:a2:b1:b2, where
a1, a2 are atom maps of participating atoms and b1, b2 are previous and
new bond orders. When a2 = 0, we update the hydrogen count.
"""
mol = Chem.AddHs(mol)
Chem.Kekulize(mol)
for atom in mol.GetAtoms():
atom.SetNoImplicit(True)
new_mol = Chem.RWMol(mol)
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in new_mol.GetAtoms()}
for edit in edits:
x, y, prev_bo, new_bo = edit.split(":")
x, y = int(x), int(y)
new_bo = float(new_bo)
if y == 0:
cent_atom = mol.GetAtomWithIdx(amap[x])
for neibor in cent_atom.GetNeighbors():
if neibor.GetAtomicNum() == 1:
new_mol.RemoveBond(amap[x],neibor.GetIdx())
break
else:
pass
elif y != 0:
bond = new_mol.GetBondBetweenAtoms(amap[x],amap[y])
if bond is not None:
new_mol.RemoveBond(amap[x],amap[y])
pred_mol = new_mol.GetMol()
pred_mol = Chem.RemoveHs(pred_mol,sanitize = False)
return pred_mol
def find_reac_edit(frag_mols_1,reac_mols_1,core_edits):
reac_mol_map_num = [i.GetAtomMapNum() for i in reac_mols_1.GetAtoms()]
frag_mol_map_num = [i.GetAtomMapNum() for i in frag_mols_1.GetAtoms()]
lg_map_num = [i for i in reac_mol_map_num if i not in frag_mol_map_num]
attach_map_num = 0
reac_edit = []
core_edits = core_edits + [':'.join([i.split(':')[1],i.split(':')[0],i.split(':')[2],i.split(':')[3]]) for i in core_edits]
for core_edit in core_edits:
core_edit_ = core_edit.split(':')
if float(core_edit_[3]) == 0 and int(core_edit_[0]) in frag_mol_map_num:
attach_map_num = int(core_edit_[0])
elif float(core_edit_[2]) - float(core_edit_[3]) > 0 and int(core_edit_[0]) in frag_mol_map_num:
attach_map_num = int(core_edit_[0])
else:
continue
if str(attach_map_num) != '0' and str(attach_map_num) != core_edit_[0]:
continue
frag_mols_1_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in frag_mols_1.GetAtoms()}
reac_mols_1_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mols_1.GetAtoms()}
frag_attach_H = frag_mols_1.GetAtomWithIdx(frag_mols_1_amap[attach_map_num]).GetNumExplicitHs()
reac_attach_H = reac_mols_1.GetAtomWithIdx(reac_mols_1_amap[attach_map_num]).GetNumExplicitHs()
frag_attach_charge = frag_mols_1.GetAtomWithIdx(frag_mols_1_amap[attach_map_num]).GetFormalCharge()
reac_attach_charge = reac_mols_1.GetAtomWithIdx(reac_mols_1_amap[attach_map_num]).GetFormalCharge()
if lg_map_num != []:
for bond in reac_mols_1.GetBonds():
EndMapNum = bond.GetEndAtom().GetAtomMapNum()
BeginMapNum = bond.GetBeginAtom().GetAtomMapNum()
if (BeginMapNum == attach_map_num) and (EndMapNum in lg_map_num):
reac_edit.append("{}:{}:{}:{}".format(BeginMapNum,EndMapNum,bond.GetBondTypeAsDouble(),0.0))
elif (EndMapNum == attach_map_num) and (BeginMapNum in lg_map_num):
reac_edit.append("{}:{}:{}:{}".format(EndMapNum,BeginMapNum,bond.GetBondTypeAsDouble(),0.0))
elif lg_map_num == []:
if Chem.MolToSmiles(reac_mols_1) == Chem.MolToSmiles(frag_mols_1):
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,0.0))
if (reac_attach_H - frag_attach_H) == 1 and (reac_attach_charge - frag_attach_charge) == 0:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,1.0,0.0))
if (reac_attach_H - frag_attach_H) == 2 and (reac_attach_charge - frag_attach_charge) == 0:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,2.0,0.0))
if (reac_attach_charge - frag_attach_charge) == -1:
if "{}:{}:{}:{}".format(attach_map_num,0,0.0,-1.0) not in reac_edit:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,-1.0))
if (reac_attach_charge - frag_attach_charge) == 1:
if "{}:{}:{}:{}".format(attach_map_num,0,0.0,1.0) not in reac_edit:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,1.0))
return reac_edit
def correct_mol_1(mol,is_nitrine_c):
mol = copy.deepcopy(mol)
for atom in mol.GetAtoms():
if is_nitrine_c == True and atom.GetAtomicNum() == 7 and sum([i.GetBondTypeAsDouble() for i in atom.GetBonds()]) == 4 and 1.5 not in [i.GetBondTypeAsDouble() for i in atom.GetBonds()] and atom.GetFormalCharge()==0: #调整N的电荷
atom.SetFormalCharge(1)
else:
pass
atom.SetNumRadicalElectrons(0)
atom.SetIsAromatic(False)
atom.SetNoImplicit(False)
return mol
def correct_mol(mol_,keep_map):
mol = copy.deepcopy(mol_)
atom_map_lis = []
idx_H_dic = {}
for atom in mol.GetAtoms():
atom_map_lis.append(atom.GetAtomMapNum())
for atom in mol.GetAtoms():
if atom.GetAtomicNum() == 7 and sum([i.GetBondTypeAsDouble() for i in atom.GetBonds()]) == 4 and 1.5 not in [i.GetBondTypeAsDouble() for i in atom.GetBonds()] and atom.GetFormalCharge()==0: #调整N的电荷
pass
elif atom.GetAtomicNum() == 15 and atom.GetExplicitValence() == 5 and 1.5 not in [i.GetBondTypeAsDouble() for i in atom.GetBonds()] and atom.GetFormalCharge()==0: #调整N的电荷
idx_H_dic[atom.GetIdx()] = atom.GetNumExplicitHs()
else:
pass
atom.SetNumRadicalElectrons(0)
atom.SetNoImplicit(False)
atom.SetAtomMapNum(0)
for atom in mol.GetAtoms():
atom.SetIsAromatic(False)
temp = Chem.MolToMolBlock(mol,kekulize = True)
mol = Chem.MolFromMolBlock(temp,removeHs = False,sanitize= False)
if keep_map:
for i in range(0,mol.GetNumAtoms()):
mol.GetAtomWithIdx(i).SetAtomMapNum(atom_map_lis[i])
if i in idx_H_dic.keys():
mol.GetAtomWithIdx(i).SetNoImplicit(True)
mol.GetAtomWithIdx(i).SetNumExplicitHs(idx_H_dic[i])
for i in range(0,mol.GetNumAtoms()):
mol.GetAtomWithIdx(i).SetChiralTag(mol_.GetAtomWithIdx(i).GetChiralTag())
n_Chirals = Chem.FindMolChiralCenters(mol)
return mol
def get_atom_map_chai_dic(mol):
dic = {}
for idx,chiral in Chem.FindMolChiralCenters(mol):
atom_map = mol.GetAtomWithIdx(idx).GetAtomMapNum()
dic[atom_map] = chiral
return dic
def get_atom_map_stereo_dic(mol):
map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in mol.GetAtoms()}
stereo_dic = {}
for bond in mol.GetBonds():
b_map,e_map = map_a[bond.GetBeginAtomIdx()],map_a[bond.GetEndAtomIdx()]
stereo_dic[tuple(sorted([b_map,e_map]))] = bond.GetStereo()
return stereo_dic
def cano_smiles_map(smiles):
atom_map_lis = []
mol = Chem.MolFromSmiles(smiles,sanitize = False)
for atom in mol.GetAtoms():
atom_map_lis.append(atom.GetAtomMapNum())
atom.SetAtomMapNum(0)
smiles = Chem.MolToSmiles(mol,canonical = False,kekuleSmiles=True)
mol = Chem.MolFromSmiles(smiles,sanitize = False)
for atom in mol.GetAtoms():
atom.SetAtomMapNum(atom_map_lis[atom.GetIdx()])
smiles = Chem.MolToSmiles(mol,canonical = False,kekuleSmiles=True)
return smiles
def get_stereo_edit_mine(reac_mol,prod_mol):
reac_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in reac_mol.GetAtoms()}
prod_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in prod_mol.GetAtoms()}
for atom in reac_mol.GetAtoms():
atom.SetAtomMapNum(0)
r_rank = list(Chem.CanonicalRankAtoms(reac_mol, breakTies=False))
r_idx = [i for i in range(reac_mol.GetNumAtoms())]
dic_idx_rank = dict(zip(r_idx,r_rank))
p_stereo_dic = {}
for bond in prod_mol.GetBonds():
b_map,e_map = prod_map_a[bond.GetBeginAtomIdx()],prod_map_a[bond.GetEndAtomIdx()]
p_stereo_dic[tuple(sorted([b_map,e_map]))] = bond.GetStereo()
r_stereo_dic = {}
for bond in reac_mol.GetBonds():
if bond.GetBondTypeAsDouble() == 2.0:
b_atom,e_atom = bond.GetBeginAtom(),bond.GetEndAtom()
b_neis = b_atom.GetNeighbors()
b_neis = [i for i in b_neis if i.GetIdx() != e_atom.GetIdx()]
b_neis_rank = [dic_idx_rank[i.GetIdx()] for i in b_neis]
e_neis = e_atom.GetNeighbors()
e_neis = [i for i in e_neis if i.GetIdx() != b_atom.GetIdx()]
e_neis_rank = [dic_idx_rank[i.GetIdx()] for i in e_neis]
b_neis_rank = b_neis_rank + ['H'] * (2 - len(b_neis_rank))
e_neis_rank = e_neis_rank + ['H'] * (2 - len(e_neis_rank))
if len(b_neis_rank) == len(set(b_neis_rank)) and len(e_neis_rank) == len(set(e_neis_rank)):
b_map,e_map = reac_map_a[bond.GetBeginAtomIdx()],reac_map_a[bond.GetEndAtomIdx()]
r_stereo_dic[tuple(sorted([b_map,e_map]))] = bond.GetStereo()
else:
pass
stereo_edits = []
for atom_pair,stereo in r_stereo_dic.items():
if atom_pair in p_stereo_dic.keys() and stereo != p_stereo_dic[atom_pair]:
if stereo == Chem.rdchem.BondStereo.STEREONONE:
stereo = 'a'
elif stereo == Chem.rdchem.BondStereo.STEREOE:
stereo = 'e'
elif stereo == Chem.rdchem.BondStereo.STEREOZ:
stereo = 'z'
stereo_edits.append('{}:{}:{}:{}'.format(atom_pair[0],atom_pair[1],0,stereo))
return stereo_edits
def apply_stereo_change(prod_mol,stereo_edits):
p_amap_idx = {atom.GetAtomMapNum(): atom.GetIdx() for atom in prod_mol.GetAtoms()}
prod_mol = copy.deepcopy(prod_mol)
prod_mol_t = copy.deepcopy(prod_mol)
for stereo_edit in stereo_edits:
b_map = int(stereo_edit.split(':')[0])
e_map = int(stereo_edit.split(':')[1])
b_n = prod_mol.GetAtomWithIdx(p_amap_idx[b_map]).GetNeighbors()
b_n = [i.GetAtomMapNum() for i in b_n]
b_n = [i for i in b_n if i not in [b_map,e_map]]
e_n = prod_mol.GetAtomWithIdx(p_amap_idx[e_map]).GetNeighbors()
e_n = [i.GetAtomMapNum() for i in e_n]
e_n = [i for i in e_n if i not in [b_map,e_map]]
f_b_n = b_n[0]
m_cip_rank = 0
for i in b_n[:]:
c_cip_rank = int(prod_mol_t.GetAtomWithIdx(p_amap_idx[i]).GetProp('_CIPRank'))
if c_cip_rank >= m_cip_rank:
f_b_n = i
m_cip_rank = c_cip_rank
f_e_n = e_n[0]
m_cip_rank = 0
for i in e_n[:]:
c_cip_rank = int(prod_mol_t.GetAtomWithIdx(p_amap_idx[i]).GetProp('_CIPRank'))
if c_cip_rank >= m_cip_rank:
f_e_n = i
m_cip_rank = c_cip_rank
if stereo_edit[-2:] == ':e':
bond = prod_mol.GetBondBetweenAtoms(p_amap_idx[b_map],p_amap_idx[e_map])
bond.SetStereo(Chem.rdchem.BondStereo.STEREOE)
try:
bond.SetStereoAtoms(p_amap_idx[f_b_n],p_amap_idx[f_e_n])
except:
bond.SetStereoAtoms(p_amap_idx[f_e_n],p_amap_idx[f_b_n])
if stereo_edit[-2:] == ':z':
bond = prod_mol.GetBondBetweenAtoms(p_amap_idx[b_map],p_amap_idx[e_map])
bond.SetStereo(Chem.rdchem.BondStereo.STEREOZ)
try:
bond.SetStereoAtoms(p_amap_idx[f_b_n],p_amap_idx[f_e_n])
except:
bond.SetStereoAtoms(p_amap_idx[f_e_n],p_amap_idx[f_b_n])
elif stereo_edit[-2:] == ':a':
bond = prod_mol.GetBondBetweenAtoms(p_amap_idx[b_map],p_amap_idx[e_map])
bond.SetStereo(Chem.rdchem.BondStereo.STEREOANY)
return prod_mol
def add_Cl(mol):
add_Cl_atom_idx = []
for atom in mol.GetAtoms():
Double_O_count = 0
if atom.GetAtomicNum() == 16 and sorted([i.GetBondTypeAsDouble() for i in atom.GetBonds()]) == [1,2,2]:
neibors = atom.GetNeighbors()
for neibor in neibors:
if neibor.GetAtomicNum() == 8:
bond = mol.GetBondBetweenAtoms(atom.GetIdx(),neibor.GetIdx())
if bond.GetBondTypeAsDouble() == 2:
Double_O_count += 1
else:
pass
else:
pass
if Double_O_count == 2:
add_Cl_atom_idx.append(atom.GetIdx())
if len(add_Cl_atom_idx) == 1:
map_lis = [i.GetAtomMapNum() for i in mol.GetAtoms()]
mw = Chem.RWMol(mol)
mw.AddAtom(Chem.Atom(17))
mw.GetAtomWithIdx(len(map_lis)).SetAtomMapNum(max(map_lis)+1)
mw.AddBond(add_Cl_atom_idx[0],len(map_lis), BOND_FLOAT_TO_TYPE[1])
mol = mw.GetMol()
return mol
def neu_sulf_charge(mol):
for atom in mol.GetAtoms():
if atom.GetAtomicNum() == 8 and atom.GetFormalCharge() == -1:
neibors = atom.GetNeighbors()
if len(neibors) == 1 and neibors[0].GetAtomicNum() == 16 and neibors[0].GetExplicitValence() == 4:
atom.SetFormalCharge(0)
else:
pass
return mol
def align_kekule_pairs(r: str, p: str) :
"""Aligns kekule pairs to ensure unchanged bonds have same bond order in
previously aromatic rings.
Parameters
----------
r: str,
SMILES string representing the reactants
p: str,
SMILES string representing the product
"""
reac_mol = Chem.MolFromSmiles(r)
max_amap = max([atom.GetAtomMapNum() for atom in reac_mol.GetAtoms()])
for atom in reac_mol.GetAtoms():
if atom.GetAtomMapNum() == 0:
atom.SetAtomMapNum(max_amap + 1)
max_amap = max_amap + 1
prod_mol = Chem.MolFromSmiles(p)
prod_prev = get_bond_info(prod_mol)
Chem.Kekulize(prod_mol)
prod_new = get_bond_info(prod_mol)
reac_prev = get_bond_info(reac_mol)
Chem.Kekulize(reac_mol)
reac_new = get_bond_info(reac_mol)
reac_edit = {}
for bond in prod_new:
if bond in reac_new and (prod_prev[bond][0] == reac_prev[bond][0]):
if reac_new[bond][0] != prod_new[bond][0] or reac_prev[bond][0] == 1.5:
reac_new[bond][0] = prod_new[bond][0]
reac_edit[bond] = reac_new[bond]
reac_mol = Chem.RWMol(reac_mol)
amap_idx = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mol.GetAtoms()}
for bond in reac_edit:
idx1, idx2 = amap_idx[bond[0]], amap_idx[bond[1]]
bo = reac_new[bond][0]
reac_mol.RemoveBond(idx1, idx2)
reac_mol.AddBond(idx1, idx2, BOND_FLOAT_TO_TYPE[bo])
return reac_mol.GetMol(), prod_mol
def count_kekule_d(r,p):
prod_mol = Chem.MolFromSmiles(p)
prod_s = get_bond_info(prod_mol)
prod_mol = Chem.MolFromSmiles(p,sanitize = False)
prod_k = get_bond_info(prod_mol)
reac_mol = Chem.MolFromSmiles(r)
reac_s = get_bond_info(reac_mol)
reac_mol = Chem.MolFromSmiles(r,sanitize = False)
reac_k = get_bond_info(reac_mol)
d_count = 0
for pair in reac_s.keys():
if pair in prod_s.keys():
if reac_s[pair][0] == prod_s[pair][0]:
if reac_k[pair][0] != prod_k[pair][0]:
d_count += 1
return d_count
def get_kekule_aligned_r(r,p):
if count_kekule_d(r,p) == 0:
return r
else:
min_r_s_lis = []
for r_s in r.split('.'):
min_count = 1000
min_r_s = ''
mol = Chem.MolFromSmiles(r_s)
suppl = Chem.ResonanceMolSupplier(mol, Chem.KEKULE_ALL)
for i in range(len(suppl)):
r_s = Chem.MolToSmiles(suppl[i],kekuleSmiles = True)
count = count_kekule_d(r_s,p)
if count <= min_count:
min_r_s = r_s
min_count = count
min_r_s_lis.append(min_r_s)
return '.'.join(min_r_s_lis)
def apply_edits_to_mol_connect(mol, edits):
"""Apply edits to molecular graph.
Parameters
----------
mol: Chem.Mol,
RDKit mol object
edits: Iterable[str],
Iterable of edits to apply. An edit is structured as a1:a2:b1:b2, where
a1, a2 are atom maps of participating atoms and b1, b2 are previous and
new bond orders. When a2 = 0, we update the hydrogen count.
"""
new_mol = Chem.RWMol(mol)
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in new_mol.GetAtoms()}
for edit in edits:
x, y, prev_bo, new_bo = edit.split(":")
x, y = int(x), int(y)
new_bo = float(new_bo)
new_mol.AddBond(amap[x],amap[y],BOND_FLOAT_TO_TYPE[new_bo])
pred_mol = new_mol.GetMol()
return pred_mol
def get_charge_edit_mine(reac_mol, prod_mol,core_edits):
lg_site_lis = []
for core_edit in core_edits:
x,y,bo,n_bo = core_edit.split(':')
if float(bo) - float(n_bo) > 0:
lg_site_lis.append(int(x))
lg_site_lis.append(int(y))
lg_site_lis = [i for i in lg_site_lis if i != 0]
dict_reac_charges = {}
for atom in reac_mol.GetAtoms():
dict_reac_charges[atom.GetAtomMapNum()] = atom.GetFormalCharge()
dict_prod_charges = {}
for atom in prod_mol.GetAtoms():
dict_prod_charges[atom.GetAtomMapNum()] = atom.GetFormalCharge()
charge_edits = []
for atom_map, charge in dict_prod_charges.items():
if atom_map in dict_reac_charges.keys():
if dict_reac_charges[atom_map] != charge and atom_map not in lg_site_lis:
edit = f"{atom_map}:{0}:{0}:{dict_reac_charges[atom_map]}"
charge_edits.append(edit)
return charge_edits
def get_atom_map_charge_dic(mol):
dic = {}
for atom in mol.GetAtoms():
dic[atom.GetAtomMapNum()] = atom.GetFormalCharge()
return dic
def apply_charge_change(mol,charge_edits):
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in mol.GetAtoms()}
for edit in charge_edits:
x, y, prev_charge, new_charge = edit.split(":")
mol.GetAtomWithIdx(amap[int(x)]).SetFormalCharge(int(new_charge))
return mol
def get_core_edit_mine(reac_mol, prod_mol):
prod_bonds = get_bond_info(prod_mol)
reac_bonds = get_bond_info(reac_mol)
rxn_core_break = set()
rxn_core_lack = set()
rxn_core = set()
core_edits = []
p_amap_idx = {atom.GetAtomMapNum(): atom.GetIdx() for atom in prod_mol.GetAtoms()}
reac_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mol.GetAtoms()}
for bond in prod_bonds:
if bond in reac_bonds and prod_bonds[bond][0] != reac_bonds[bond][0]:
a_start, a_end = bond
prod_bo, reac_bo = prod_bonds[bond][0], reac_bonds[bond][0]
a_start, a_end = sorted([a_start, a_end])
edit = f"{a_start}:{a_end}:{prod_bo}:{reac_bo}"
core_edits.append(edit)
rxn_core.update([a_start, a_end])
if bond not in reac_bonds:
a_start, a_end = bond
reac_bo = 0.0
prod_bo = prod_bonds[bond][0]
start, end = sorted([a_start, a_end])
edit = f"{a_start}:{a_end}:{prod_bo}:{reac_bo}"
core_edits.append(edit)
rxn_core.update([a_start, a_end])
rxn_core_break.update([a_start, a_end])
for bond in reac_bonds:
if bond not in prod_bonds:
amap1, amap2 = bond
rxn_core_lack.update([amap1, amap2])
if (amap1 in p_amap_idx) and (amap2 in p_amap_idx):
a_start, a_end = sorted([amap1, amap2])
reac_bo = reac_bonds[bond][0]
edit = f"{a_start}:{a_end}:{0.0}:{reac_bo}"
core_edits.append(edit)
rxn_core.update([a_start, a_end])
if True:
reac_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mol.GetAtoms()}
for atom in prod_mol.GetAtoms():
amap_num = atom.GetAtomMapNum()
if (amap_num in rxn_core_break) or (amap_num not in rxn_core_lack):
pass
else:
amap_num = atom.GetAtomMapNum()
numHs_prod = atom.GetTotalNumHs()
numHs_reac = reac_mol.GetAtomWithIdx(reac_amap[amap_num]).GetTotalNumHs()
if numHs_prod != numHs_reac:
edit = f"{amap_num}:{0}:{1.0}:{0.0}"
core_edits.append(edit)
rxn_core.add(amap_num)
return core_edits
def get_chai_edit_mine(reac_mol, prod_mol):
reac_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in reac_mol.GetAtoms()}
prod_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in prod_mol.GetAtoms()}
reac_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(reac_mol,includeUnassigned=True):
reac_ChiralCenters.append((reac_map_a[ChiralCenters[0]],ChiralCenters[1]))
prod_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(prod_mol,includeUnassigned=True):
prod_ChiralCenters.append((prod_map_a[ChiralCenters[0]],ChiralCenters[1]))
dict_reac_ChiralCenters = dict(reac_ChiralCenters)
dict_prod_ChiralCenters = dict(prod_ChiralCenters)
chai_edits = []
for amap_num,chiral in dict_prod_ChiralCenters.items():
if amap_num in dict_reac_ChiralCenters.keys():
if chiral != dict_reac_ChiralCenters[amap_num]:
edit = f"{amap_num}:{0}:{0}:{dict_reac_ChiralCenters[amap_num]}"
chai_edits.append(edit)
else:
pass
for amap_num,chiral in dict_reac_ChiralCenters.items():
if (amap_num not in dict_prod_ChiralCenters.keys()) and (amap_num in prod_map_a.values()) and chiral != '?':
edit = f"{amap_num}:{0}:{0}:{chiral}"
chai_edits.append(edit)
return chai_edits
def get_chai_edit_mine(reac_mol, prod_mol):
reac_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in reac_mol.GetAtoms()}
prod_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in prod_mol.GetAtoms()}
reac_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(reac_mol,includeUnassigned=True):
reac_ChiralCenters.append((reac_map_a[ChiralCenters[0]],ChiralCenters[1]))
prod_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(prod_mol,includeUnassigned=True):
prod_ChiralCenters.append((prod_map_a[ChiralCenters[0]],ChiralCenters[1]))
dict_reac_ChiralCenters = dict(reac_ChiralCenters)
dict_prod_ChiralCenters = dict(prod_ChiralCenters)
chai_edits = []
for amap_num,chiral in dict_prod_ChiralCenters.items():
if amap_num in dict_reac_ChiralCenters.keys():
if chiral != dict_reac_ChiralCenters[amap_num]:
edit = f"{amap_num}:{0}:{0}:{dict_reac_ChiralCenters[amap_num]}"
chai_edits.append(edit)
else:
pass
for amap_num,chiral in dict_reac_ChiralCenters.items():
if (amap_num not in dict_prod_ChiralCenters.keys())and (amap_num in prod_map_a.values()):
edit = f"{amap_num}:{0}:{0}:{chiral}"
chai_edits.append(edit)
return chai_edits
def get_chai_edit_mine(reac_mol, prod_mol):
reac_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in reac_mol.GetAtoms()}
prod_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in prod_mol.GetAtoms()}
reac_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(reac_mol,includeUnassigned=True):
reac_ChiralCenters.append((reac_map_a[ChiralCenters[0]],ChiralCenters[1]))
prod_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(prod_mol,includeUnassigned=True):
prod_ChiralCenters.append((prod_map_a[ChiralCenters[0]],ChiralCenters[1]))
dict_reac_ChiralCenters = dict(reac_ChiralCenters)
dict_prod_ChiralCenters = dict(prod_ChiralCenters)
chai_edits = []
for amap_num,chiral in dict_prod_ChiralCenters.items():
if amap_num in dict_reac_ChiralCenters.keys():
if chiral != dict_reac_ChiralCenters[amap_num]:
edit = f"{amap_num}:{0}:{0}:{dict_reac_ChiralCenters[amap_num]}"
chai_edits.append(edit)
else:
pass
for amap_num,chiral in dict_reac_ChiralCenters.items():
if (amap_num not in dict_prod_ChiralCenters.keys()) and (amap_num in prod_map_a.values()) and chiral != '?':
edit = f"{amap_num}:{0}:{0}:{chiral}"
chai_edits.append(edit)
return chai_edits
def get_lg_map_lis(frag_mols,reac_mols,core_edits,prod_mol):
lg_map_lis = []
prod_map_num_lis = [i.GetAtomMapNum() for i in prod_mol.GetAtoms()]
for frag_mols_1,reac_mols_1 in zip(frag_mols[:],reac_mols[:]):
reac_edits = find_reac_edit(frag_mols_1,reac_mols_1,core_edits)
reac_edits_a = []
reac_edits_b = []
for reac_edit in reac_edits:
if reac_edit[:3] == '0:0':
reac_edits_a.append(reac_edit)
elif reac_edit[-7:] == '0.0:0.0':
reac_edits_a.append(reac_edit)
elif reac_edit[-10:] == '0:0.0:-1.0':
reac_edits_a.append(reac_edit)
elif reac_edit[-9:] == '0:0.0:1.0':
reac_edits_a.append(reac_edit)
else:
reac_edits_b.append(reac_edit)
for reac_edit in reac_edits_a:
if reac_edit[:3] == '0:0':
pass
elif reac_edit[-7:] == '0.0:0.0':
pass
elif reac_edit[-10:] == '0:0.0:-1.0':
edit_map_num_lis = reac_edit.split(':')[:2]
attach_map_num_1 = [int(i) for i in edit_map_num_lis if int(i) in prod_map_num_lis]
lg_smiles = '-1.0'
lg_map_lis.append((lg_smiles,attach_map_num_1))
elif reac_edit[-9:] == '0:0.0:1.0':
edit_map_num_lis = reac_edit.split(':')[:2]
attach_map_num_1 = [int(i) for i in edit_map_num_lis if int(i) in prod_map_num_lis]
lg_smiles = '1.0'
lg_map_lis.append((lg_smiles,attach_map_num_1))
frag_1_map_num_lis = [i.GetAtomMapNum() for i in frag_mols_1.GetAtoms() if i.GetAtomMapNum() != 0]
reac_frag_mol = apply_edits_to_mol_break(reac_mols_1 , reac_edits_b)
reac_frag_mols = Chem.GetMolFrags(reac_frag_mol,asMols=True,sanitizeFrags = False)
reac_edit_added = []
for reac_frag_mol in reac_frag_mols[:]:
reac_frag_map_num_lis = [i.GetAtomMapNum() for i in reac_frag_mol.GetAtoms() if i.GetAtomMapNum() != 0]
if set(reac_frag_map_num_lis) == set(frag_1_map_num_lis):
pass
else:
attach_map_num_1 = []
for reac_edit in reac_edits:
if reac_edit in reac_edit_added:
continue
else:
pass
b,e = int(reac_edit.split(':')[0]),int(reac_edit.split(':')[1])
if e in reac_frag_map_num_lis and b in frag_1_map_num_lis:
for atom in reac_frag_mol.GetAtoms():
if atom.GetAtomMapNum() == int(e):
atom.SetAtomMapNum(500+atom.GetAtomMapNum())
break
else:
pass
reac_edit_added.append(reac_edit)
if len(attach_map_num_1) == 1:
if [str(attach_map_num_1[0]),str(atom.GetAtomMapNum()-500)] in [i.split(':')[:2] for i in reac_edits ]: #上一个合成子上的连接点和本离去基团的连接点配对
if atom.GetAtomMapNum() == max([i.GetAtomMapNum() for i in reac_frag_mol.GetAtoms()]):
attach_map_num_1 = [b] + attach_map_num_1
else:
attach_map_num_1.append(b)
else:
if atom.GetAtomMapNum() == max([i.GetAtomMapNum() for i in reac_frag_mol.GetAtoms()]):
attach_map_num_1.append(b)
else:
attach_map_num_1 = [b] + attach_map_num_1
elif len(attach_map_num_1) == 0:
attach_map_num_1.append(b)
else:
pass
if reac_frag_mol.GetAtomWithIdx(0).GetAtomicNum() == 1 and len(attach_map_num_1) == 1:
break
lg_smiles = Chem.MolToSmiles(reac_frag_mol,kekuleSmiles = True)
lg = Chem.MolFromSmiles(lg_smiles)
Chem.Kekulize(lg)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() >= 500:
atom.SetAtomMapNum(1)
pass
else:
atom.SetAtomMapNum(0)
lg_smiles = Chem.MolToSmiles(lg,canonical = False,kekuleSmiles = True)
if attach_map_num_1 != []:
lg_map_lis.append((lg_smiles,attach_map_num_1))
return lg_map_lis
def get_core_edit_mine(reac_mol, prod_mol):
prod_bonds = get_bond_info(prod_mol)
reac_bonds = get_bond_info(reac_mol)
rxn_core_break = set()
rxn_core_lack = set()
rxn_core = set()
core_edits = []
p_amap_idx = {atom.GetAtomMapNum(): atom.GetIdx() for atom in prod_mol.GetAtoms()}
reac_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mol.GetAtoms()}
for bond in prod_bonds:
if bond in reac_bonds and prod_bonds[bond][0] != reac_bonds[bond][0]:
a_start, a_end = bond
prod_bo, reac_bo = prod_bonds[bond][0], reac_bonds[bond][0]
a_start, a_end = sorted([a_start, a_end])
edit = f"{a_start}:{a_end}:{prod_bo}:{reac_bo}"
core_edits.append(edit)
rxn_core.update([a_start, a_end])
if bond not in reac_bonds:
a_start, a_end = bond
reac_bo = 0.0
prod_bo = prod_bonds[bond][0]
start, end = sorted([a_start, a_end])
edit = f"{a_start}:{a_end}:{prod_bo}:{reac_bo}"
core_edits.append(edit)
rxn_core.update([a_start, a_end])
rxn_core_break.update([a_start, a_end])
for bond in reac_bonds:
if bond not in prod_bonds:
amap1, amap2 = bond
rxn_core_lack.update([amap1, amap2])
if (amap1 in p_amap_idx) and (amap2 in p_amap_idx):
a_start, a_end = sorted([amap1, amap2])
reac_bo = reac_bonds[bond][0]
edit = f"{a_start}:{a_end}:{0.0}:{reac_bo}"
core_edits.append(edit)
rxn_core.update([a_start, a_end])
reac_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mol.GetAtoms()}
for atom in prod_mol.GetAtoms():
amap_num = atom.GetAtomMapNum()
if (amap_num in rxn_core_break) or (amap_num not in rxn_core_lack):
pass
else:
amap_num = atom.GetAtomMapNum()
numHs_prod = atom.GetTotalNumHs()
numHs_reac = reac_mol.GetAtomWithIdx(reac_amap[amap_num]).GetTotalNumHs()
if numHs_prod != numHs_reac:
edit = f"{amap_num}:{0}:{1.0}:{0.0}"
core_edits.append(edit)
rxn_core.add(amap_num)
for atom in prod_mol.GetAtoms():
amap_num = atom.GetAtomMapNum()
if amap_num in rxn_core:
pass
else:
amap_num = atom.GetAtomMapNum()
Degree_prod = atom.GetDegree()
Degree_reac = reac_mol.GetAtomWithIdx(reac_amap[amap_num]).GetDegree()
if Degree_prod - Degree_reac == -1:
edit = f"{amap_num}:{0}:{1.0}:{0.0}"
core_edits.append(edit)
rxn_core.add(amap_num)
return core_edits
def find_reac_edit(frag_mols_1,reac_mols_1,core_edits):
reac_mol_map_num = [i.GetAtomMapNum() for i in reac_mols_1.GetAtoms()]
frag_mol_map_num = [i.GetAtomMapNum() for i in frag_mols_1.GetAtoms()]
lg_map_num = [i for i in reac_mol_map_num if i not in frag_mol_map_num]
attach_map_num = 0
reac_edit = []
core_edits = core_edits + [':'.join([i.split(':')[1],i.split(':')[0],i.split(':')[2],i.split(':')[3]]) for i in core_edits]
for core_edit in core_edits:
core_edit_ = core_edit.split(':')
if float(core_edit_[3]) == 0 and int(core_edit_[0]) in frag_mol_map_num:
attach_map_num = int(core_edit_[0])
elif float(core_edit_[2]) - float(core_edit_[3]) > 0 and int(core_edit_[0]) in frag_mol_map_num:
attach_map_num = int(core_edit_[0])
else:
continue
if str(attach_map_num) != '0' and str(attach_map_num) != core_edit_[0]:
continue
frag_mols_1_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in frag_mols_1.GetAtoms()}
reac_mols_1_amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in reac_mols_1.GetAtoms()}
frag_attach_H = frag_mols_1.GetAtomWithIdx(frag_mols_1_amap[attach_map_num]).GetNumExplicitHs()
reac_attach_H = reac_mols_1.GetAtomWithIdx(reac_mols_1_amap[attach_map_num]).GetNumExplicitHs()
frag_attach_charge = frag_mols_1.GetAtomWithIdx(frag_mols_1_amap[attach_map_num]).GetFormalCharge()
reac_attach_charge = reac_mols_1.GetAtomWithIdx(reac_mols_1_amap[attach_map_num]).GetFormalCharge()
if lg_map_num != []:
for bond in reac_mols_1.GetBonds():
EndMapNum = bond.GetEndAtom().GetAtomMapNum()
BeginMapNum = bond.GetBeginAtom().GetAtomMapNum()
if (BeginMapNum == attach_map_num) and (EndMapNum in lg_map_num):
reac_edit.append("{}:{}:{}:{}".format(BeginMapNum,EndMapNum,bond.GetBondTypeAsDouble(),0.0))
elif (EndMapNum == attach_map_num) and (BeginMapNum in lg_map_num):
reac_edit.append("{}:{}:{}:{}".format(EndMapNum,BeginMapNum,bond.GetBondTypeAsDouble(),0.0))
elif lg_map_num == []:
if Chem.MolToSmiles(reac_mols_1) == Chem.MolToSmiles(frag_mols_1):
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,0.0))
if (reac_attach_H - frag_attach_H) == 1 and (reac_attach_charge - frag_attach_charge) == 0:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,1.0,0.0))
if (reac_attach_H - frag_attach_H) == 2 and (reac_attach_charge - frag_attach_charge) == 0:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,2.0,0.0))
if (reac_attach_charge - frag_attach_charge) == -1:
if "{}:{}:{}:{}".format(attach_map_num,0,0.0,-1.0) not in reac_edit:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,-1.0))
if (reac_attach_charge - frag_attach_charge) == 1:
if "{}:{}:{}:{}".format(attach_map_num,0,0.0,1.0) not in reac_edit:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,1.0))
if (reac_attach_charge - frag_attach_charge) == 2:
if "{}:{}:{}:{}".format(attach_map_num,0,0.0,2.0) not in reac_edit:
reac_edit.append("{}:{}:{}:{}".format(attach_map_num,0,0.0,2.0))
return reac_edit
def get_lg_map_lis(frag_mols,reac_mols,core_edits,prod_mol):
lg_map_lis = []
prod_map_num_lis = [i.GetAtomMapNum() for i in prod_mol.GetAtoms()]
for frag_mols_1,reac_mols_1 in zip(frag_mols[:],reac_mols[:]):
reac_edits = find_reac_edit(frag_mols_1,reac_mols_1,core_edits)
reac_edits_a = []
reac_edits_b = []
for reac_edit in reac_edits:
if reac_edit[:3] == '0:0':
reac_edits_a.append(reac_edit)
elif reac_edit[-7:] == '0.0:0.0':
reac_edits_a.append(reac_edit)
elif reac_edit[-10:] == '0:0.0:-1.0':
reac_edits_a.append(reac_edit)
elif reac_edit[-9:] == '0:0.0:1.0':
reac_edits_a.append(reac_edit)
elif reac_edit[-9:] == '0:0.0:2.0':
reac_edits_a.append(reac_edit)
else:
reac_edits_b.append(reac_edit)
for reac_edit in reac_edits_a:
if reac_edit[:3] == '0:0':
pass
elif reac_edit[-7:] == '0.0:0.0':
pass
elif reac_edit[-10:] == '0:0.0:-1.0':
edit_map_num_lis = reac_edit.split(':')[:2]
attach_map_num_1 = [int(i) for i in edit_map_num_lis if int(i) in prod_map_num_lis]
lg_smiles = '-1'
lg_map_lis.append((lg_smiles,attach_map_num_1))
elif reac_edit[-9:] == '0:0.0:1.0':
edit_map_num_lis = reac_edit.split(':')[:2]
attach_map_num_1 = [int(i) for i in edit_map_num_lis if int(i) in prod_map_num_lis]
lg_smiles = '1'
lg_map_lis.append((lg_smiles,attach_map_num_1))
elif reac_edit[-9:] == '0:0.0:2.0':
edit_map_num_lis = reac_edit.split(':')[:2]
attach_map_num_1 = [int(i) for i in edit_map_num_lis if int(i) in prod_map_num_lis]
lg_smiles = '2'
lg_map_lis.append((lg_smiles,attach_map_num_1))
frag_1_map_num_lis = [i.GetAtomMapNum() for i in frag_mols_1.GetAtoms() if i.GetAtomMapNum() != 0]
reac_frag_mol = apply_edits_to_mol_break(reac_mols_1 , reac_edits_b)
reac_frag_mols = Chem.GetMolFrags(reac_frag_mol,asMols=True,sanitizeFrags = False)
reac_edit_added = []
for reac_frag_mol in reac_frag_mols[:]:
reac_frag_map_num_lis = [i.GetAtomMapNum() for i in reac_frag_mol.GetAtoms() if i.GetAtomMapNum() != 0]
if set(reac_frag_map_num_lis) == set(frag_1_map_num_lis):
pass
else:
attach_map_num_1 = []
for reac_edit in reac_edits:
if reac_edit in reac_edit_added:
continue
else:
pass
b,e = int(reac_edit.split(':')[0]),int(reac_edit.split(':')[1])
if e in reac_frag_map_num_lis and b in frag_1_map_num_lis:
for atom in reac_frag_mol.GetAtoms():
if atom.GetAtomMapNum() == int(e):
atom.SetAtomMapNum(500+atom.GetAtomMapNum())
break
else:
pass
reac_edit_added.append(reac_edit)
if len(attach_map_num_1) == 1:
if [str(attach_map_num_1[0]),str(atom.GetAtomMapNum()-500)] in [i.split(':')[:2] for i in reac_edits ]: #上一个合成子上的连接点和本离去基团的连接点配对
if atom.GetAtomMapNum() == max([i.GetAtomMapNum() for i in reac_frag_mol.GetAtoms()]):
attach_map_num_1 = [b] + attach_map_num_1
else:
attach_map_num_1.append(b)
else:
if atom.GetAtomMapNum() == max([i.GetAtomMapNum() for i in reac_frag_mol.GetAtoms()]):
attach_map_num_1.append(b)
else:
attach_map_num_1 = [b] + attach_map_num_1
elif len(attach_map_num_1) == 0:
attach_map_num_1.append(b)
else:
pass
if reac_frag_mol.GetAtomWithIdx(0).GetAtomicNum() == 1 and len(attach_map_num_1) == 1:
break
lg_smiles = Chem.MolToSmiles(reac_frag_mol,kekuleSmiles = True)
lg = Chem.MolFromSmiles(lg_smiles)
Chem.Kekulize(lg)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() >= 500:
atom.SetAtomMapNum(1)
pass
else:
atom.SetAtomMapNum(0)
lg_smiles = Chem.MolToSmiles(lg,canonical = False,kekuleSmiles = True)
if attach_map_num_1 != []:
lg_map_lis.append((lg_smiles,attach_map_num_1))
return lg_map_lis
def get_chai_edit_mine(reac_mol, prod_mol):
reac_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in reac_mol.GetAtoms()}
prod_map_a = {atom.GetIdx(): atom.GetAtomMapNum() for atom in prod_mol.GetAtoms()}
reac_mol_= copy.deepcopy(reac_mol)
prod_mol_= copy.deepcopy(prod_mol)
for atom in reac_mol_.GetAtoms():
atom.SetAtomMapNum(0)
for atom in prod_mol_.GetAtoms():
atom.SetAtomMapNum(0)
reac_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(Chem.MolFromMolBlock(Chem.MolToMolBlock(reac_mol_)),includeUnassigned=True):
reac_ChiralCenters.append((reac_map_a[ChiralCenters[0]],ChiralCenters[1]))
prod_ChiralCenters = []
for ChiralCenters in Chem.FindMolChiralCenters(Chem.MolFromMolBlock(Chem.MolToMolBlock(prod_mol_)),includeUnassigned=True):
prod_ChiralCenters.append((prod_map_a[ChiralCenters[0]],ChiralCenters[1]))
dict_reac_ChiralCenters = dict(reac_ChiralCenters)
dict_prod_ChiralCenters = dict(prod_ChiralCenters)
chai_edits = []
for amap_num,chiral in dict_prod_ChiralCenters.items():
if amap_num in dict_reac_ChiralCenters.keys():
if chiral != dict_reac_ChiralCenters[amap_num]:
edit = f"{amap_num}:{0}:{0}:{dict_reac_ChiralCenters[amap_num]}"
chai_edits.append(edit)
else:
pass
for amap_num,chiral in dict_reac_ChiralCenters.items():
if (amap_num not in dict_prod_ChiralCenters.keys()) and (amap_num in prod_map_a.values()) and chiral != '?':
edit = f"{amap_num}:{0}:{0}:{chiral}"
chai_edits.append(edit)
return chai_edits
def get_original_chair_edit(p,b):
b = copy.deepcopy(b)
for atom in b.GetAtoms():
atom.SetAtomMapNum(0)
b_dic = dict(Chem.FindMolChiralCenters(Chem.MolFromMolBlock(Chem.MolToMolBlock(b)),includeUnassigned=True))
temp_p = Chem.MolFromSmiles(p)
for atom in temp_p.GetAtoms():
atom.SetAtomMapNum(0)
temp_dic = dict(Chem.FindMolChiralCenters(Chem.MolFromMolBlock(Chem.MolToMolBlock(temp_p)),includeUnassigned=True))
out = []
for i,j in temp_dic.items():
if i in b_dic:
out.append('{}:0:0:{}'.format(i+1,j))
return out
def apply_chirality_change(prod_mol,chai_edits):
p_amap_idx = {atom.GetAtomMapNum(): atom.GetIdx() for atom in prod_mol.GetAtoms()}
prod_mol = copy.deepcopy(prod_mol)
for chai_edit in chai_edits:
amap = int(chai_edit.split(':')[0])
if chai_edit[-2:] == ':R':
atom = prod_mol.GetAtomWithIdx(p_amap_idx[amap])
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CCW)
temp_mol_dic = get_chair_dict_without_atom_map(prod_mol)
if temp_mol_dic[atom.GetIdx()] == 'R':
pass
else:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CW)
elif chai_edit[-2:] == ':S':
atom = prod_mol.GetAtomWithIdx(p_amap_idx[amap])
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CCW)
temp_mol_dic = get_chair_dict_without_atom_map(prod_mol)
if temp_mol_dic[atom.GetIdx()] == 'S':
pass
else:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CW)
temp_mol_dic = dict(Chem.FindMolChiralCenters(Chem.MolFromMolBlock(Chem.MolToMolBlock(prod_mol)),includeUnassigned=True))
elif chai_edit[-2:] == ':?':
atom = prod_mol.GetAtomWithIdx(p_amap_idx[amap])
atom.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED)
return prod_mol
def get_chair_dict_without_atom_map(temp_p):
temp_p = copy.deepcopy(temp_p)
for atom in temp_p.GetAtoms():
atom.SetAtomMapNum(0)
temp_dic = dict(Chem.FindMolChiralCenters(Chem.MolFromMolBlock(Chem.MolToMolBlock(temp_p)),includeUnassigned=True))
return temp_dic
def run_get_p_b_l(rxn_smi):
try:
r, p = rxn_smi.split(">>")
if Chem.MolFromSmiles(p).GetNumAtoms() >= 150 or Chem.MolFromSmiles(r).GetNumAtoms() >= 150:
print('error type 3')
return 'error type 3'
else:
pass
r,p = cano_smiles_map(r),cano_smiles_map(p)
reac_mol, prod_mol = align_kekule_pairs(r, p)
reac_mol = Chem.MolFromSmiles(Chem.MolToSmiles(reac_mol,kekuleSmiles = True),sanitize = False)
reac_smiles_temp = Chem.MolToSmiles(reac_mol,kekuleSmiles = True)
reac_mol_temp = Chem.MolFromSmiles(reac_smiles_temp)
if reac_mol_temp != None and Chem.MolToSmiles(reac_mol_temp) == Chem.MolToSmiles(Chem.MolFromSmiles(r)):
pass
else:
r_k = get_kekule_aligned_r(r,p)
if count_kekule_d(r_k,p) == 0:
reac_mol, prod_mol = Chem.MolFromSmiles(r_k),Chem.MolFromSmiles(p)
Chem.Kekulize(reac_mol)
Chem.Kekulize(prod_mol)
else:
reac_mol, prod_mol = Chem.MolFromSmiles(r_k),Chem.MolFromSmiles(p)
Chem.Kekulize(reac_mol)
Chem.Kekulize(prod_mol)
core_edits_add = [i for i in core_edits if (float(i.split(':')[2]) == 0) and (float(i.split(':')[1]) != 0)]
core_edits = [i for i in core_edits if i not in core_edits_add]
edit_c = [i for i in core_edits if (float(i.split(':')[-1]) > 0)]
edit_b = [i for i in core_edits if (float(i.split(':')[-1]) == 0)]
chai_edits = get_chai_edit_mine(Chem.MolFromSmiles(r), Chem.MolFromSmiles(p))
stereo_edits = get_stereo_edit_mine(Chem.MolFromSmiles(r), Chem.MolFromSmiles(p))
charge_edits = get_charge_edit_mine(reac_mol, prod_mol,core_edits)
o_p_Chiral_dic = get_atom_map_chai_dic(Chem.MolFromSmiles(p))
o_p_Stereo_dic = get_atom_map_stereo_dic(Chem.MolFromSmiles(p))
frag_mol = apply_edits_to_mol_break(prod_mol,edit_b)
frag_mol = apply_edits_to_mol_change(frag_mol,edit_c)
frag_mol = apply_edits_to_mol_connect(frag_mol, core_edits_add)
frag_mol = remove_s_H(frag_mol)
reac_mols = Chem.GetMolFrags(reac_mol,asMols=True,sanitizeFrags = False)
frag_mols = Chem.GetMolFrags(frag_mol,asMols=True,sanitizeFrags = False)
if len(reac_mols) != len(frag_mols):
frag_mols = [frag_mol for frag_mol in frag_mols if Chem.MolToSmiles(frag_mol) != '[H]']
else:
pass
if len(reac_mols) != len(frag_mols):
frag_mols = [frag_mol]
else:
pass
if len(reac_mols) == len(frag_mols):
reac_mols, frag_mols = map_reac_and_frag(reac_mols,frag_mols)
else:
print('error type 0')
lg_map_lis_temp = get_lg_map_lis(frag_mols[:],reac_mols[:],core_edits,prod_mol)
lg_map_lis = []
for lg, map_ in lg_map_lis_temp:
lg, map_ = copy.deepcopy(lg),copy.deepcopy(map_)
map_new = []
if lg.count(':') > 1:
lg = Chem.MolFromSmiles(lg)
Chem.Kekulize(lg)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 0:
map_new.append('*')
else:
map_new.append(map_.pop(0))
lg_smiles = Chem.MolToSmiles(lg,kekuleSmiles = True)
rank = list(Chem.CanonicalRankAtoms(lg, breakTies=False))
map_new = sorted(map_new, key=lambda x: rank[map_new.index(x)])
map_new = [i for i in map_new if i != '*']
lg_map_lis.append((lg_smiles,map_new))
else:
lg_map_lis.append((lg, map_ ))
total_mol = frag_mol
for lg_smile,map_nums in lg_map_lis[:]:
if lg_smile not in ['-1.0','1.0','2.0']:
lg = Chem.MolFromSmiles(lg_smile)
total_mol_map_num_lis = [i.GetAtomMapNum() for i in total_mol.GetAtoms()]
max_map = max(total_mol_map_num_lis)
count = 1
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 1:
atom.SetAtomMapNum(max_map + count)
count += 1
else:
pass
total_mol_map_num_lis = [i.GetAtomMapNum() for i in total_mol.GetAtoms()]
max_map = max(total_mol_map_num_lis)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 0:
atom.SetAtomMapNum(max_map + count)
count += 1
else:
pass
total_mol = Chem.CombineMols(total_mol,lg)
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in total_mol.GetAtoms()}
new_mol = Chem.RWMol(total_mol)
is_multi_bond = 0
for idx in range(len(map_nums)):
map_num = map_nums[idx]
if lg_smile.count(':') == len(map_nums):
lg_map = max_map + 1 + idx
atom = total_mol.GetAtomWithIdx(amap[lg_map])
is_multi_bond = 0
else:
lg_map = max_map + 1
atom = total_mol.GetAtomWithIdx(amap[lg_map])
is_multi_bond= 1
if atom.GetSymbol() == 'O' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'S' and atom.GetTotalValence() in [0,2,4] and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'S' and atom.GetTotalValence() ==1 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'P' and atom.GetTotalValence() == 3 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == -1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Se' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Si' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Mn' and atom.GetTotalValence() == 5 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Cr' and atom.GetTotalValence() == 4 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'O' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 3.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 3.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == -1 and is_multi_bond == 0:
bond_float = 3.0
else:
bond_float = 1.0
new_mol.AddBond(amap[map_num],amap[lg_map],BOND_FLOAT_TO_TYPE[bond_float])
total_mol = new_mol.GetMol()
else:
map_num = map_nums[0]
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in total_mol.GetAtoms()}
atom = total_mol.GetAtomWithIdx(amap[map_num])
atom.SetNumRadicalElectrons(0)
atom.SetFormalCharge(int(atom.GetFormalCharge()+float(lg_smile)))
total_mol = correct_mol_1(total_mol,is_nitrine_c = True)
b = correct_mol(total_mol,keep_map = True)
b_Chiral_dic = get_atom_map_chai_dic(b)
b_Stereo_dic = get_atom_map_stereo_dic(b)
dic_map_idx = dict([(i.GetAtomMapNum(),i.GetIdx()) for i in b.GetAtoms()])
act = 0
for b_map,Chiral in b_Chiral_dic.items():
if b_map not in o_p_Chiral_dic.keys():
pass
elif b_map in o_p_Chiral_dic.keys() and b_Chiral_dic[b_map] != o_p_Chiral_dic[b_map] and b_map not in [int(i.split(':')[0]) for i in chai_edits]:
act =1
atom = b.GetAtomWithIdx(dic_map_idx[b_map])
if atom.GetChiralTag() == Chem.ChiralType.CHI_TETRAHEDRAL_CCW:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CW)
elif atom.GetChiralTag() == Chem.ChiralType.CHI_TETRAHEDRAL_CW:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CCW)
if act == 1:
pass
for b_map,Stereo in b_Stereo_dic.items():
if b_map not in o_p_Stereo_dic.keys():
pass
elif b_map in o_p_Stereo_dic.keys() and Stereo != o_p_Stereo_dic[b_map] and b_map not in [tuple([int(i) for i in i.split(':')[:2]]) for i in stereo_edits]:
bond = b.GetBondBetweenAtoms(dic_map_idx[b_map[0]],dic_map_idx[b_map[1]])
bond.SetStereo(o_p_Stereo_dic[b_map])
b = apply_charge_change(b,charge_edits)
if chai_edits == []:
o_chai_edits = get_original_chair_edit(p,b)
b = apply_chirality_change(b,o_chai_edits)
else:
b = apply_chirality_change(b,chai_edits)
b = Chem.MolFromSmiles(Chem.MolToSmiles(b,canonical = False))
b = apply_stereo_change(b,stereo_edits)
for atom in b.GetAtoms():
atom.SetAtomMapNum(0)
for bond in b.GetBonds():
if bond.GetStereo() == Chem.rdchem.BondStereo.STEREONONE:
bond.SetStereo(Chem.rdchem.BondStereo.STEREOANY)
else:
pass
pre_smiles = Chem.MolToSmiles(b)
pre_smiles = pre_smiles.replace('[H]/C=C/','C=C').replace('[H]/C=C(\\','C=C(').replace('[H]/C=C(/','C=C(').replace('[MgH2]','[Mg]').replace('/C=N\\','C=C')
pre_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(pre_smiles))
reac_mol = Chem.MolFromSmiles(r)
for atom in reac_mol.GetAtoms():
atom.SetAtomMapNum(0)
reac_mol_smiles = Chem.MolToSmiles(reac_mol)
reac_mol_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(reac_mol_smiles))
if [float(i[-3:]) for i in core_edits_add] == []:
max_add = 0
elif max([float(i[-3:]) for i in core_edits_add]) == 1:
max_add = 1
else:
max_add = 2
charges = [int(i[-1]) for i in charge_edits] + [0]
if pre_smiles == reac_mol_smiles and len(core_edits_add) <= 1 and max_add <=1 and max(charges)<=1 and min(charges)>=-1:
return ([p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis])
else:
print(pre_smiles,reac_mol_smiles,chai_edits,stereo_edits)
return 'error type 1'
except:
print('error type 2')
return 'error type 2'
def run_get_p_b_l_forward(rxn_smi):
try:
r, p = rxn_smi.split(">>")
if Chem.MolFromSmiles(p).GetNumAtoms() >= 150 or Chem.MolFromSmiles(r).GetNumAtoms() >= 150:
return 'error type 1'
else:
pass
r,p = cano_smiles_map(r),cano_smiles_map(p)
reac_mol, prod_mol = align_kekule_pairs(r, p)
reac_mol = Chem.MolFromSmiles(Chem.MolToSmiles(reac_mol,kekuleSmiles = True),sanitize = False)
reac_smiles_temp = Chem.MolToSmiles(reac_mol,kekuleSmiles = True)
reac_mol_temp = Chem.MolFromSmiles(reac_smiles_temp)
if reac_mol_temp != None and Chem.MolToSmiles(reac_mol_temp) == Chem.MolToSmiles(Chem.MolFromSmiles(r)):
pass
else:
r_k = get_kekule_aligned_r(r,p)
if count_kekule_d(r_k,p) == 0:
reac_mol, prod_mol = Chem.MolFromSmiles(r_k),Chem.MolFromSmiles(p)
Chem.Kekulize(reac_mol)
Chem.Kekulize(prod_mol)
else:
reac_mol, prod_mol = Chem.MolFromSmiles(r_k),Chem.MolFromSmiles(p)
Chem.Kekulize(reac_mol)
Chem.Kekulize(prod_mol)
core_edits= get_core_edit_mine(reac_mol,prod_mol)
core_edits_add = [i for i in core_edits if (float(i.split(':')[2]) == 0) and (float(i.split(':')[1]) != 0)]
core_edits = [i for i in core_edits if i not in core_edits_add]
edit_c = [i for i in core_edits if (float(i.split(':')[-1]) > 0)]
edit_b = [i for i in core_edits if (float(i.split(':')[-1]) == 0)]
chai_edits = get_chai_edit_mine(Chem.MolFromSmiles(r), Chem.MolFromSmiles(p))
stereo_edits = get_stereo_edit_mine(Chem.MolFromSmiles(r), Chem.MolFromSmiles(p))
charge_edits = get_charge_edit_mine(reac_mol, prod_mol,core_edits)
o_p_Chiral_dic = get_atom_map_chai_dic(Chem.MolFromSmiles(p))
o_p_Stereo_dic = get_atom_map_stereo_dic(Chem.MolFromSmiles(p))
frag_mol = apply_edits_to_mol_break(prod_mol,edit_b)
frag_mol = apply_edits_to_mol_change(frag_mol,edit_c)
frag_mol = apply_edits_to_mol_connect(frag_mol, core_edits_add)
frag_mol = remove_s_H(frag_mol)
reac_mols = Chem.GetMolFrags(reac_mol,asMols=True,sanitizeFrags = False)
frag_mols = Chem.GetMolFrags(frag_mol,asMols=True,sanitizeFrags = False)
if len(reac_mols) != len(frag_mols):
frag_mols = [frag_mol for frag_mol in frag_mols if Chem.MolToSmiles(frag_mol) != '[H]']
else:
pass
if len(reac_mols) != len(frag_mols):
frag_mols = [frag_mol]
else:
pass
if len(reac_mols) == len(frag_mols):
reac_mols, frag_mols = map_reac_and_frag(reac_mols,frag_mols)
else:
pass
lg_map_lis_temp = get_lg_map_lis(frag_mols[:],reac_mols[:],core_edits,prod_mol)
lg_map_lis = []
for lg, map_ in lg_map_lis_temp:
lg, map_ = copy.deepcopy(lg),copy.deepcopy(map_)
map_new = []
if lg.count(':') > 1:
lg = Chem.MolFromSmiles(lg)
Chem.Kekulize(lg)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 0:
map_new.append('*')
else:
map_new.append(map_.pop(0))
lg_smiles = Chem.MolToSmiles(lg,kekuleSmiles = True)
rank = list(Chem.CanonicalRankAtoms(lg, breakTies=False))
map_new = sorted(map_new, key=lambda x: rank[map_new.index(x)])
map_new = [i for i in map_new if i != '*']
lg_map_lis.append((lg_smiles,map_new))
else:
lg_map_lis.append((lg, map_ ))
return ([p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis])
except:
return 'error type 2'
def run_get_p_b_l_backward(p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis):
prod_mol = Chem.MolFromSmiles(p)
core_edits = [i for i in core_edits if i not in core_edits_add]
edit_c = [i for i in core_edits if (float(i.split(':')[-1]) > 0)]
edit_b = [i for i in core_edits if (float(i.split(':')[-1]) == 0)]
o_p_Chiral_dic = get_atom_map_chai_dic(Chem.MolFromSmiles(p)) #
o_p_Stereo_dic = get_atom_map_stereo_dic(Chem.MolFromSmiles(p))
frag_mol = apply_edits_to_mol_break(prod_mol,edit_b)
frag_mol = apply_edits_to_mol_change(frag_mol,edit_c)
frag_mol = apply_edits_to_mol_connect(frag_mol, core_edits_add)
frag_mol = remove_s_H(frag_mol)
total_mol = frag_mol
for lg_smile,map_nums in lg_map_lis[:]:
if lg_smile not in ['-1','1','2']:
lg = Chem.MolFromSmiles(lg_smile)
total_mol_map_num_lis = [i.GetAtomMapNum() for i in total_mol.GetAtoms()]
max_map = max(total_mol_map_num_lis)
count = 1
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 1:
atom.SetAtomMapNum(max_map + count)
count += 1
else:
pass
total_mol_map_num_lis = [i.GetAtomMapNum() for i in total_mol.GetAtoms()]
max_map = max(total_mol_map_num_lis)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 0:
atom.SetAtomMapNum(max_map + count)
count += 1
else:
pass
total_mol = Chem.CombineMols(total_mol,lg)
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in total_mol.GetAtoms()}
new_mol = Chem.RWMol(total_mol)
is_multi_bond = 0
for idx in range(len(map_nums)):
map_num = map_nums[idx]
if lg_smile.count(':') == len(map_nums):
lg_map = max_map + 1 + idx
atom = total_mol.GetAtomWithIdx(amap[lg_map])
is_multi_bond = 0
else:
lg_map = max_map + 1
atom = total_mol.GetAtomWithIdx(amap[lg_map])
is_multi_bond= 1
if atom.GetSymbol() == 'O' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'S' and atom.GetTotalValence() in [0,2,4] and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'S' and atom.GetTotalValence() ==1 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'P' and atom.GetTotalValence() == 3 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == -1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Se' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Si' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Mn' and atom.GetTotalValence() == 5 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Cr' and atom.GetTotalValence() == 4 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'O' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 3.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 3.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == -1 and is_multi_bond == 0:
bond_float = 3.0
else:
bond_float = 1.0
new_mol.AddBond(amap[map_num],amap[lg_map],BOND_FLOAT_TO_TYPE[bond_float])
total_mol = new_mol.GetMol()
else:
map_num = map_nums[0]
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in total_mol.GetAtoms()}
atom = total_mol.GetAtomWithIdx(amap[map_num])
atom.SetNumRadicalElectrons(0)
atom.SetFormalCharge(int(atom.GetFormalCharge()+float(lg_smile)))
total_mol = correct_mol_1(total_mol,is_nitrine_c = True)
b = correct_mol(total_mol,keep_map = True)
b_Chiral_dic = get_atom_map_chai_dic(b)
b_Stereo_dic = get_atom_map_stereo_dic(b)
dic_map_idx = dict([(i.GetAtomMapNum(),i.GetIdx()) for i in b.GetAtoms()])
act = 0
for b_map,Chiral in b_Chiral_dic.items():
if b_map not in o_p_Chiral_dic.keys():
pass
elif b_map in o_p_Chiral_dic.keys() and b_Chiral_dic[b_map] != o_p_Chiral_dic[b_map] and b_map not in [int(i.split(':')[0]) for i in chai_edits]:
act =1
atom = b.GetAtomWithIdx(dic_map_idx[b_map])
if atom.GetChiralTag() == Chem.ChiralType.CHI_TETRAHEDRAL_CCW:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CW)
elif atom.GetChiralTag() == Chem.ChiralType.CHI_TETRAHEDRAL_CW:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CCW)
if act == 1:
pass
for b_map,Stereo in b_Stereo_dic.items():
if b_map not in o_p_Stereo_dic.keys():
pass
elif b_map in o_p_Stereo_dic.keys() and Stereo != o_p_Stereo_dic[b_map] and b_map not in [tuple([int(i) for i in i.split(':')[:2]]) for i in stereo_edits]:
bond = b.GetBondBetweenAtoms(dic_map_idx[b_map[0]],dic_map_idx[b_map[1]])
bond.SetStereo(o_p_Stereo_dic[b_map])
b = apply_charge_change(b,charge_edits)
if chai_edits == []:
o_chai_edits = get_original_chair_edit(p,b)
b = apply_chirality_change(b,o_chai_edits)
else:
b = apply_chirality_change(b,chai_edits)
b = Chem.MolFromSmiles(Chem.MolToSmiles(b,canonical = False))
b = apply_stereo_change(b,stereo_edits)
for atom in b.GetAtoms():
atom.SetAtomMapNum(0)
for bond in b.GetBonds():
if bond.GetStereo() == Chem.rdchem.BondStereo.STEREONONE:
bond.SetStereo(Chem.rdchem.BondStereo.STEREOANY)
else:
pass
pre_smiles = Chem.MolToSmiles(b)
pre_smiles = pre_smiles.replace('[H]/C=C/','C=C').replace('[H]/C=C(\\','C=C(').replace('[H]/C=C(/','C=C(').replace('[MgH2]','[Mg]').replace('/C=N\\','C=C')
pre_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(pre_smiles))
return pre_smiles
def run_get_p_b_l_backward_with_mapping(p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis):
prod_mol = Chem.MolFromSmiles(p)
core_edits = [i for i in core_edits if i not in core_edits_add]
edit_c = [i for i in core_edits if (float(i.split(':')[-1]) > 0)]
edit_b = [i for i in core_edits if (float(i.split(':')[-1]) == 0)]
o_p_Chiral_dic = get_atom_map_chai_dic(Chem.MolFromSmiles(p)) #
o_p_Stereo_dic = get_atom_map_stereo_dic(Chem.MolFromSmiles(p))
frag_mol = apply_edits_to_mol_break(prod_mol,edit_b)
frag_mol = apply_edits_to_mol_change(frag_mol,edit_c)
frag_mol = apply_edits_to_mol_connect(frag_mol, core_edits_add)
frag_mol = remove_s_H(frag_mol)
total_mol = frag_mol
for lg_smile,map_nums in lg_map_lis[:]:
if lg_smile not in ['-1','1','2']:
lg = Chem.MolFromSmiles(lg_smile)
total_mol_map_num_lis = [i.GetAtomMapNum() for i in total_mol.GetAtoms()]
max_map = max(total_mol_map_num_lis)
count = 1
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 1:
atom.SetAtomMapNum(max_map + count)
count += 1
else:
pass
total_mol_map_num_lis = [i.GetAtomMapNum() for i in total_mol.GetAtoms()]
max_map = max(total_mol_map_num_lis)
for atom in lg.GetAtoms():
if atom.GetAtomMapNum() == 0:
atom.SetAtomMapNum(max_map + count)
count += 1
else:
pass
total_mol = Chem.CombineMols(total_mol,lg)
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in total_mol.GetAtoms()}
new_mol = Chem.RWMol(total_mol)
is_multi_bond = 0
for idx in range(len(map_nums)):
map_num = map_nums[idx]
if lg_smile.count(':') == len(map_nums):
lg_map = max_map + 1 + idx
atom = total_mol.GetAtomWithIdx(amap[lg_map])
is_multi_bond = 0
else:
lg_map = max_map + 1
atom = total_mol.GetAtomWithIdx(amap[lg_map])
is_multi_bond= 1
if atom.GetSymbol() == 'O' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'S' and atom.GetTotalValence() in [0,2,4] and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'S' and atom.GetTotalValence() ==1 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'P' and atom.GetTotalValence() == 3 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == -1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Se' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Si' and atom.GetTotalValence() == 2 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Mn' and atom.GetTotalValence() == 5 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'Cr' and atom.GetTotalValence() == 4 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'O' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 1 and is_multi_bond == 0:
bond_float = 2.0
elif atom.GetSymbol() == 'N' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 3.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 1 and atom.GetFormalCharge() == 0 and is_multi_bond == 0:
bond_float = 3.0
elif atom.GetSymbol() == 'C' and atom.GetTotalValence() == 0 and atom.GetFormalCharge() == -1 and is_multi_bond == 0:
bond_float = 3.0
else:
bond_float = 1.0
new_mol.AddBond(amap[map_num],amap[lg_map],BOND_FLOAT_TO_TYPE[bond_float])
total_mol = new_mol.GetMol()
else:
map_num = map_nums[0]
amap = {atom.GetAtomMapNum(): atom.GetIdx() for atom in total_mol.GetAtoms()}
atom = total_mol.GetAtomWithIdx(amap[map_num])
atom.SetNumRadicalElectrons(0)
atom.SetFormalCharge(int(atom.GetFormalCharge()+float(lg_smile)))
total_mol = correct_mol_1(total_mol,is_nitrine_c = True)
b = correct_mol(total_mol,keep_map = True)
b_Chiral_dic = get_atom_map_chai_dic(b)
b_Stereo_dic = get_atom_map_stereo_dic(b)
dic_map_idx = dict([(i.GetAtomMapNum(),i.GetIdx()) for i in b.GetAtoms()])
act = 0
for b_map,Chiral in b_Chiral_dic.items():
if b_map not in o_p_Chiral_dic.keys():
pass
elif b_map in o_p_Chiral_dic.keys() and b_Chiral_dic[b_map] != o_p_Chiral_dic[b_map] and b_map not in [int(i.split(':')[0]) for i in chai_edits]:
act =1
atom = b.GetAtomWithIdx(dic_map_idx[b_map])
if atom.GetChiralTag() == Chem.ChiralType.CHI_TETRAHEDRAL_CCW:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CW)
elif atom.GetChiralTag() == Chem.ChiralType.CHI_TETRAHEDRAL_CW:
atom.SetChiralTag(Chem.ChiralType.CHI_TETRAHEDRAL_CCW)
if act == 1:
pass
for b_map,Stereo in b_Stereo_dic.items():
if b_map not in o_p_Stereo_dic.keys():
pass
elif b_map in o_p_Stereo_dic.keys() and Stereo != o_p_Stereo_dic[b_map] and b_map not in [tuple([int(i) for i in i.split(':')[:2]]) for i in stereo_edits]:
bond = b.GetBondBetweenAtoms(dic_map_idx[b_map[0]],dic_map_idx[b_map[1]])
bond.SetStereo(o_p_Stereo_dic[b_map])
b = apply_charge_change(b,charge_edits)
if chai_edits == []:
o_chai_edits = get_original_chair_edit(p,b)
b = apply_chirality_change(b,o_chai_edits)
else:
b = apply_chirality_change(b,chai_edits)
b = Chem.MolFromSmiles(Chem.MolToSmiles(b,canonical = False))
b = apply_stereo_change(b,stereo_edits)
# for atom in b.GetAtoms():
# atom.SetAtomMapNum(0)
for bond in b.GetBonds():
if bond.GetStereo() == Chem.rdchem.BondStereo.STEREONONE:
bond.SetStereo(Chem.rdchem.BondStereo.STEREOANY)
else:
pass
pre_smiles = Chem.MolToSmiles(b)
# pre_smiles = pre_smiles.replace('[H]/C=C/','C=C').replace('[H]/C=C(\\','C=C(').replace('[H]/C=C(/','C=C(').replace('[MgH2]','[Mg]').replace('/C=N\\','C=C')
# pre_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(pre_smiles))
return pre_smiles
def run_get_p_b_l_check(rxn):
try:
p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis = run_get_p_b_l_forward(rxn)
except:
return 'error type 3'
try:
pre_smiles = run_get_p_b_l_backward(p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis) # 加个5
except:
return 'error type 5'
r = rxn.split('>>')[0]
reac_mol = Chem.MolFromSmiles(r)
for atom in reac_mol.GetAtoms():
atom.SetAtomMapNum(0)
reac_mol_smiles = Chem.MolToSmiles(reac_mol)
reac_mol_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(reac_mol_smiles))
if [float(i[-3:]) for i in core_edits_add] == []:
max_add = 0
elif max([float(i[-3:]) for i in core_edits_add]) == 1:
max_add = 1
else:
max_add = 2
charges = [int(i[-1]) for i in charge_edits] + [0]
if pre_smiles == reac_mol_smiles and len(core_edits_add) <= 1 and max_add <=1 and max(charges)<=1 and min(charges)>=-1:
return p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis
else:
return 'error type 4'
def get_atom_pair_bond_idx_dic(concise_smiles):
mol_indigo = indigo.loadMolecule(concise_smiles)
mol_block_indigo = mol_indigo.molfile()
mol = Chem.MolFromSmiles(concise_smiles,sanitize = False)
atom_num = len(mol.GetAtoms())
bond_num = len(mol.GetBonds())
mol_block_lis = mol_block_indigo.split('\n')
bond_line_lis = mol_block_lis[4+atom_num:4+atom_num+bond_num]
atom_pair_bond_idx_dic = {}
count = 0
for bond_line in bond_line_lis:
s_atom = int(bond_line[:3])
e_atom = int(bond_line[3:6])
min_atom = min((s_atom,e_atom))
max_atom = max((s_atom,e_atom))
atom_pair_bond_idx_dic[(min_atom,max_atom)] = count
count += 1
return atom_pair_bond_idx_dic
def get_rm_token_lis(concise_smiles,detailed_smiles):
detailed_smiles_length = len(detailed_smiles)
idx = 0
rm_token_lis = []
for _ in range(len(detailed_smiles)):
if detailed_smiles[idx] != concise_smiles[idx]:
rm_token_lis.append(detailed_smiles[idx])
detailed_smiles = detailed_smiles[:idx] + detailed_smiles[idx+1:]
else:
idx += 1
rm_token_lis.append(' ')
if detailed_smiles == concise_smiles and len(rm_token_lis) == detailed_smiles_length:
return rm_token_lis
else:
print('error')
pass
def get_bond_token_lis(detailed_smiles):
bond_token_lis = []
for i in range(len(detailed_smiles)):
if detailed_smiles[i] in ['-','=','#',':','/','\\'] and detailed_smiles[i+1] != ']':
bond_token_lis.append(detailed_smiles[i])
else:
bond_token_lis.append(' ')
pass
return bond_token_lis
def get_bond_token_idx_dic(bond_token_lis):
bond_token_idx_dic = {}
bond_idx = 0
token_idx = 0
for i in bond_token_lis:
token_idx += 1
if i != ' ':
bond_idx += 1
else:
pass
bond_token_idx_dic[bond_idx] = token_idx
return bond_token_idx_dic
def rerank_special_bond(mol_block_indigo_lis,bond_idx):
mol = Chem.MolFromMolBlock('\n'.join(mol_block_indigo_lis),removeHs = False)
q = mol_block_indigo_lis[mol.GetNumAtoms()+ 4 +bond_idx][:3]
h = mol_block_indigo_lis[mol.GetNumAtoms()+ 4 +bond_idx][3:6]
mol_block_indigo_lis[mol.GetNumAtoms()+ 4 +bond_idx] = h + q + mol_block_indigo_lis[mol.GetNumAtoms()+ 4 +bond_idx][6:]
return mol_block_indigo_lis
def get_caption_r(caption):
words = re.findall(r'[{](.*?)[}]', caption)
words = ['{' + i + '}' for i in words ]
caption_r = caption
count = 400
for i in words:
count += 1
caption_r = caption_r.replace(i,'[{}Au]'.format(count),1)
return caption_r,words
def get_b_smiles_detailed_smiles(caption_r,smiles):
b_smiles = caption_r
b_smiles = b_smiles.replace('/','/-').replace('\\','\\-')
b_smiles = b_smiles.replace('-!','!').replace('-?','?')
mol_tmp = Chem.MolFromSmiles(smiles,sanitize = False)
detailed_smiles = Chem.MolToSmiles(mol_tmp,canonical = False,allBondsExplicit = True)
detailed_smiles = detailed_smiles.replace('/','/-').replace('\\','\\-') #
for i in range(len(detailed_smiles)):
if detailed_smiles[i] != b_smiles[i]:
if b_smiles[i] in ['!','_',';','^','&','{','}','。','《','》']:
pass
else:
b_smiles = b_smiles[:i] + detailed_smiles[i] + b_smiles[i:]
else:
pass
return b_smiles,detailed_smiles
def get_bond_dic(b_smiles,detailed_smiles):
b_smiles = b_smiles.replace('-]',']')
detailed_smiles = detailed_smiles.replace('-]',']')
count = 0
bond_dic = {}
for i,j in zip(detailed_smiles,b_smiles):
if i != j:
bond_dic[count] = j
if i in ['-','=','#',':']:
count += 1
return bond_dic
def get_t_smiles(e_smiles,o_smiles):
e_smiles_r = e_smiles.replace('!','-').replace('_','-').replace(';','-').replace('^','-').replace('&','=').replace('{','=').replace('}','=').replace('。','=').replace('《','=').replace('》','=')
mol_r = Chem.MolFromSmiles(e_smiles_r,sanitize = False)
a = Chem.MolFromSmiles(o_smiles,sanitize = False)
for atom in a.GetAtoms():
atom.SetAtomMapNum(0)
for atom in mol_r.GetAtoms():
if atom.GetIsotope() != 0:
a.GetAtomWithIdx(atom.GetIdx()).SetIsotope(atom.GetIsotope())
t_smiles = Chem.MolToSmiles(a,canonical = False)
return t_smiles
def get_b_smiles(p_b):
o_smiles = p_b[0]
core_edits = p_b[1]
chai_edits = p_b[2]
stereo_edits = p_b[3]
charge_edits = p_b[4]
core_edits_add = p_b[5]
atom_idx_mark_dic = {}
for edit in core_edits:
b = int(edit.split(':')[0])
e = int(edit.split(':')[1])
new_b = edit.split(':')[3]
if min([b,e]) == 0:
atom_map = max([b,e])
if new_b == '0.0':
atom_idx_mark_dic[atom_map] = 9
else:
pass
for edit in chai_edits:
edit_l = edit.split(':')
if edit_l[3] == 'R':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 10
else:
atom_idx_mark_dic[int(edit_l[0])] = 10 + atom_idx_mark_dic[int(edit_l[0])]
elif edit_l[3] == 'S':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 20
else:
atom_idx_mark_dic[int(edit_l[0])] = 20 + atom_idx_mark_dic[int(edit_l[0])]
elif edit_l[3] == '?':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 30
else:
atom_idx_mark_dic[int(edit_l[0])] = 30 + atom_idx_mark_dic[int(edit_l[0])]
for edit in charge_edits:
edit_l = edit.split(':')
if edit_l[3] == '1':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 200
else:
atom_idx_mark_dic[int(edit_l[0])] = 200 + atom_idx_mark_dic[int(edit_l[0])]
pass
elif edit_l[3] == '0':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 400
else:
atom_idx_mark_dic[int(edit_l[0])] = 400 + atom_idx_mark_dic[int(edit_l[0])]
elif edit_l[3] == '-1':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 600
else:
atom_idx_mark_dic[int(edit_l[0])] = 600 + atom_idx_mark_dic[int(edit_l[0])]
for edit in core_edits_add:
edit_l = edit.split(':')
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 100
else:
atom_idx_mark_dic[int(edit_l[0])] = 100 + atom_idx_mark_dic[int(edit_l[0])]
if int(edit_l[1]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[1])] = 100
else:
atom_idx_mark_dic[int(edit_l[1])] = 100 + atom_idx_mark_dic[int(edit_l[1])]
a = Chem.MolFromSmiles(o_smiles,sanitize = False)
for atom in a.GetAtoms():
if atom.GetAtomMapNum() in atom_idx_mark_dic.keys():
atom_map = atom.GetAtomMapNum()
atom.SetIsotope(atom_idx_mark_dic[atom_map])
else:
pass
atom.SetAtomMapNum(0)
mol = copy.deepcopy(a)
detailed_smiles = Chem.MolToSmiles(mol,canonical = False,allBondsExplicit = True,kekuleSmiles=True)
concise_smiles = Chem.MolToSmiles(mol,canonical = False,kekuleSmiles=True)
concise_smiles_no_chirality = Chem.MolToSmiles(mol,canonical = False,isomericSmiles = False,kekuleSmiles=True)
atom_pair_bond_idx_dic = get_atom_pair_bond_idx_dic(concise_smiles_no_chirality)
rm_token_lis = get_rm_token_lis(concise_smiles,detailed_smiles)
bond_token_lis = get_bond_token_lis(detailed_smiles)
bond_token_idx_dic = get_bond_token_idx_dic(bond_token_lis)
bond_idx_mark_dic = {}
for edit in core_edits:
b = int(edit.split(':')[0])
e = int(edit.split(':')[1])
org_b = edit.split(':')[2]
new_b = edit.split(':')[3]
if min([b,e]) != 0:
bond_idx = atom_pair_bond_idx_dic[min([b,e]),max([b,e])]
if new_b == '0.0':
mark = '!'
elif new_b == '1.0':
mark = '_'
elif new_b == '2.0':
mark = ';'
elif new_b == '3.0':
mark = '^'
bond_idx_mark_dic[bond_idx] = mark
else:
pass
for edit in stereo_edits:
b = int(edit.split(':')[0])
e = int(edit.split(':')[1])
new_b = edit.split(':')[3]
if min([b,e]) != 0:
bond_idx = atom_pair_bond_idx_dic[min([b,e]),max([b,e])]
if bond_idx not in bond_idx_mark_dic.keys():
if new_b == 'a':
mark = '&'
elif new_b == 'e':
mark = '{'
elif new_b == 'z':
mark = '}'
bond_idx_mark_dic[bond_idx] = mark
else:
bond_idx in bond_idx_mark_dic.keys()
if new_b == 'a':
mark = '。'
elif new_b == 'e':
mark = '《'
elif new_b == 'z':
mark = '》'
bond_idx_mark_dic[bond_idx] = mark
else:
pass
for bond_idx,mark in bond_idx_mark_dic.items():
token_idx = bond_token_idx_dic[bond_idx]
rm_token_lis[token_idx] = mark
new_smiles_lis = []
for i in range(len(rm_token_lis)):
if rm_token_lis[i] == ' ':
new_smiles_lis.append(detailed_smiles[i])
elif rm_token_lis[i][-1] in ['!','_',';','^','&','{','}','。','《','》']:
new_smiles_lis.append(rm_token_lis[i])
else:
pass
caption = ''.join(new_smiles_lis)
out_b_smiles_lis.append(caption)
caption_r = caption
t_smiles = get_t_smiles(caption_r,o_smiles)
b_smiles,detailed_smiles = get_b_smiles_detailed_smiles(caption_r,t_smiles)
bond_dic = get_bond_dic(b_smiles,detailed_smiles)
atom_pair_bond_idx = {}
for atom_pair,bond_idx in get_atom_pair_bond_idx_dic(o_smiles).items():
atom_pair_bond_idx[bond_idx] = atom_pair
mol = Chem.MolFromSmiles(t_smiles)
Chem.Kekulize(mol)
core_edits_ = []
chai_edits_ = []
stereo_edits_ = []
charge_edits_ = []
core_edits_add_ = []
for bond_idx,mark in bond_dic.items():
b,e = atom_pair_bond_idx[bond_idx]
o_bond = mol.GetBondBetweenAtoms(b-1,e-1).GetBondTypeAsDouble()
if mark == '!':
n_bond = '0.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == '_':
n_bond = '1.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == ';':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == '^':
n_bond = '3.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == '&':
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'a'))
elif mark == '{':
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'e'))
elif mark == '}':
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'z'))
elif mark == '。':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'a'))
elif mark == '《':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'e'))
elif mark == '》':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'z'))
core_edits_add_atom_lis = []
for atom in mol.GetAtoms():
Isotope = atom.GetIsotope()
g_w = Isotope % 10
s_w = Isotope % 100 //10
b_w = Isotope // 100
if g_w == 9:
core_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'1.0','0.0'))
else:
pass
if s_w == 1:
chai_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0','R'))
elif s_w == 2:
chai_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0','S'))
elif s_w == 3:
chai_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0','?'))
if b_w == 2 or b_w == 3:
charge_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0',1))
elif b_w == 4 or b_w == 5:
charge_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0',0))
elif b_w == 6 or b_w == 7:
charge_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0',-1))
if b_w % 2 == 1:
core_edits_add_atom_lis.append(atom.GetIdx()+1)
if core_edits_add_atom_lis != []:
core_edits_add_.append('{}:{}:{}:{}'.format(core_edits_add_atom_lis[0],core_edits_add_atom_lis[1],'0.0','1.0'))
else:
pass
if sorted(core_edits_) != sorted(core_edits) or sorted(chai_edits_) != sorted(chai_edits) or sorted(stereo_edits_) != sorted(stereo_edits) or sorted(charge_edits_) != sorted(charge_edits) or sorted(core_edits_add_) != sorted(core_edits_add):
print(core_edits_,core_edits)
print(chai_edits_,chai_edits)
print(core_edits_add_,core_edits_add)
return 'error'
else:
return caption
pass
def get_b_smiles_forward(p_b):
o_smiles = p_b[0]
core_edits = p_b[1]
chai_edits = p_b[2]
stereo_edits = p_b[3]
charge_edits = p_b[4]
core_edits_add = p_b[5]
atom_idx_mark_dic = {}
for edit in core_edits:
b = int(edit.split(':')[0])
e = int(edit.split(':')[1])
new_b = edit.split(':')[3]
if min([b,e]) == 0:
atom_map = max([b,e])
if new_b == '0.0':
atom_idx_mark_dic[atom_map] = 9
else:
pass
for edit in chai_edits:
edit_l = edit.split(':')
if edit_l[3] == 'R':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 10
else:
atom_idx_mark_dic[int(edit_l[0])] = 10 + atom_idx_mark_dic[int(edit_l[0])]
elif edit_l[3] == 'S':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 20
else:
atom_idx_mark_dic[int(edit_l[0])] = 20 + atom_idx_mark_dic[int(edit_l[0])]
elif edit_l[3] == '?':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 30
else:
atom_idx_mark_dic[int(edit_l[0])] = 30 + atom_idx_mark_dic[int(edit_l[0])]
for edit in charge_edits:
edit_l = edit.split(':')
if edit_l[3] == '1':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 200
else:
atom_idx_mark_dic[int(edit_l[0])] = 200 + atom_idx_mark_dic[int(edit_l[0])]
pass
elif edit_l[3] == '0':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 400
else:
atom_idx_mark_dic[int(edit_l[0])] = 400 + atom_idx_mark_dic[int(edit_l[0])]
elif edit_l[3] == '-1':
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 600
else:
atom_idx_mark_dic[int(edit_l[0])] = 600 + atom_idx_mark_dic[int(edit_l[0])]
for edit in core_edits_add:
edit_l = edit.split(':')
if int(edit_l[0]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[0])] = 100
else:
atom_idx_mark_dic[int(edit_l[0])] = 100 + atom_idx_mark_dic[int(edit_l[0])]
if int(edit_l[1]) not in atom_idx_mark_dic.keys():
atom_idx_mark_dic[int(edit_l[1])] = 100
else:
atom_idx_mark_dic[int(edit_l[1])] = 100 + atom_idx_mark_dic[int(edit_l[1])]
a = Chem.MolFromSmiles(o_smiles,sanitize = False)
for atom in a.GetAtoms():
if atom.GetAtomMapNum() in atom_idx_mark_dic.keys():
atom_map = atom.GetAtomMapNum()
atom.SetIsotope(atom_idx_mark_dic[atom_map])
else:
pass
atom.SetAtomMapNum(0)
mol = copy.deepcopy(a)
detailed_smiles = Chem.MolToSmiles(mol,canonical = False,allBondsExplicit = True,kekuleSmiles=True)
concise_smiles = Chem.MolToSmiles(mol,canonical = False,kekuleSmiles=True)
concise_smiles_no_chirality = Chem.MolToSmiles(mol,canonical = False,isomericSmiles = False,kekuleSmiles=True)
atom_pair_bond_idx_dic = get_atom_pair_bond_idx_dic(concise_smiles_no_chirality)
rm_token_lis = get_rm_token_lis(concise_smiles,detailed_smiles)
bond_token_lis = get_bond_token_lis(detailed_smiles)
bond_token_idx_dic = get_bond_token_idx_dic(bond_token_lis)
bond_idx_mark_dic = {}
for edit in core_edits:
b = int(edit.split(':')[0])
e = int(edit.split(':')[1])
org_b = edit.split(':')[2]
new_b = edit.split(':')[3]
if min([b,e]) != 0:
bond_idx = atom_pair_bond_idx_dic[min([b,e]),max([b,e])]
if new_b == '0.0':
mark = '!'
elif new_b == '1.0':
mark = '_'
elif new_b == '2.0':
mark = ';'
elif new_b == '3.0':
mark = '^'
bond_idx_mark_dic[bond_idx] = mark
else:
pass
for edit in stereo_edits:
b = int(edit.split(':')[0])
e = int(edit.split(':')[1])
new_b = edit.split(':')[3]
if min([b,e]) != 0:
bond_idx = atom_pair_bond_idx_dic[min([b,e]),max([b,e])]
if bond_idx not in bond_idx_mark_dic.keys():
if new_b == 'a':
mark = '&'
elif new_b == 'e':
mark = '{'
elif new_b == 'z':
mark = '}'
bond_idx_mark_dic[bond_idx] = mark
else:
bond_idx in bond_idx_mark_dic.keys()
if new_b == 'a':
mark = '。'
elif new_b == 'e':
mark = '《'
elif new_b == 'z':
mark = '》'
bond_idx_mark_dic[bond_idx] = mark
else:
pass
for bond_idx,mark in bond_idx_mark_dic.items():
token_idx = bond_token_idx_dic[bond_idx]
rm_token_lis[token_idx] = mark
new_smiles_lis = []
for i in range(len(rm_token_lis)):
if rm_token_lis[i] == ' ':
new_smiles_lis.append(detailed_smiles[i])
elif rm_token_lis[i][-1] in ['!','_',';','^','&','{','}','。','《','》']:
new_smiles_lis.append(rm_token_lis[i])
else:
pass
return ''.join(new_smiles_lis)
def get_b_smiles_backward(caption_r,o_smiles):
t_smiles = get_t_smiles(caption_r,o_smiles)
b_smiles,detailed_smiles = get_b_smiles_detailed_smiles(caption_r,t_smiles)
bond_dic = get_bond_dic(b_smiles,detailed_smiles)
atom_pair_bond_idx = {}
for atom_pair,bond_idx in get_atom_pair_bond_idx_dic(o_smiles).items():
atom_pair_bond_idx[bond_idx] = atom_pair
mol = Chem.MolFromSmiles(t_smiles)
Chem.Kekulize(mol)
core_edits_ = []
chai_edits_ = []
stereo_edits_ = []
charge_edits_ = []
core_edits_add_ = []
for bond_idx,mark in bond_dic.items():
b,e = atom_pair_bond_idx[bond_idx]
o_bond = mol.GetBondBetweenAtoms(b-1,e-1).GetBondTypeAsDouble()
if mark == '!':
n_bond = '0.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == '_':
n_bond = '1.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == ';':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == '^':
n_bond = '3.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
elif mark == '&':
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'a'))
elif mark == '{':
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'e'))
elif mark == '}':
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'z'))
elif mark == '。':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'a')) #any
elif mark == '《':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'e'))
elif mark == '》':
n_bond = '2.0'
core_edits_.append('{}:{}:{}:{}'.format(b,e,o_bond,n_bond))
stereo_edits_.append('{}:{}:{}:{}'.format(b,e,0,'z'))
core_edits_add_atom_lis = []
for atom in mol.GetAtoms():
Isotope = atom.GetIsotope()
g_w = Isotope % 10
s_w = Isotope % 100 //10
b_w = Isotope // 100
if g_w == 9:
core_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'1.0','0.0'))
else:
pass
if s_w == 1:
chai_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0','R'))
elif s_w == 2:
chai_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0','S'))
elif s_w == 3:
chai_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0','?'))
if b_w == 2 or b_w == 3:
charge_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0',1))
elif b_w == 4 or b_w == 5:
charge_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0',0))
elif b_w == 6 or b_w == 7:
charge_edits_.append('{}:{}:{}:{}'.format(atom.GetIdx()+1,0,'0',-1))
if b_w % 2 == 1:
core_edits_add_atom_lis.append(atom.GetIdx()+1)
if core_edits_add_atom_lis != []:
core_edits_add_.append('{}:{}:{}:{}'.format(core_edits_add_atom_lis[0],core_edits_add_atom_lis[1],'0.0','1.0'))
else:
pass
return core_edits_,chai_edits_,stereo_edits_,charge_edits_,core_edits_add_
def get_b_smiles_check(p_b):
p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis = p_b
b_smiles = get_b_smiles_forward(p_b)
core_edits_,chai_edits_,stereo_edits_,charge_edits_,core_edits_add_ = get_b_smiles_backward(b_smiles,p_b[0])
if sorted(core_edits_) != sorted(core_edits) or sorted(chai_edits_) != sorted(chai_edits) or sorted(stereo_edits_) != sorted(stereo_edits) or sorted(charge_edits_) != sorted(charge_edits) or sorted(core_edits_add_) != sorted(core_edits_add):
print(core_edits_,core_edits)
print(chai_edits_,chai_edits)
print(core_edits_add_,core_edits_add)
return 'error'
else:
return b_smiles
import re
def replacenth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n-1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted, 1)
newString = before + after
return newString
def cano_smiles_map(smiles):
atom_map_lis = []
mol = Chem.MolFromSmiles(smiles,sanitize = False)
for atom in mol.GetAtoms():
atom_map_lis.append(atom.GetAtomMapNum())
atom.SetAtomMapNum(0)
smiles = Chem.MolToSmiles(mol,canonical = False,kekuleSmiles=True)
mol = Chem.MolFromSmiles(smiles,sanitize = False)
for atom in mol.GetAtoms():
atom.SetAtomMapNum(atom_map_lis[atom.GetIdx()])
smiles = Chem.MolToSmiles(mol,canonical = False,kekuleSmiles=True)
return smiles
def get_lg_forward(core_edits,lg_map):
attach_idx = []
for core_edit in core_edits:
core_edit = core_edit.split(':')
if float(core_edit[2])-float(core_edit[3]) > 0:
attach_idx.append(int(core_edit[0]))
attach_idx.append(int(core_edit[1]))
attach_idx = sorted(list(set(attach_idx)))
attach_idx = [i for i in attach_idx if i != 0]
lg_lis = [()]*len(attach_idx)
for lg,map_lis in lg_map:
if len(map_lis) == 1:
map_ = map_lis[0]
id_ = attach_idx.index(map_)
lg_lis[id_] = tuple(list(lg_lis[id_]) +[lg])
elif len(map_lis) != 1 and len(set(map_lis)) == 1:
map_ = map_lis[0]
id_ = attach_idx.index(map_)
lg_lis[id_] = tuple(list(lg_lis[id_]) +[lg])
elif len(map_lis) != 1 and len(set(map_lis)) != 1 and lg.count(':') == 1:
for map_ in map_lis:
id_ = attach_idx.index(map_)
lg_lis[id_] = tuple(list(lg_lis[id_]) +[lg + "*"])
elif len(map_lis) != 1 and len(set(map_lis)) != 1 and lg.count(':') == 2:
if map_lis[0]<map_lis[1]:
lg = replacenth(lg, ':1',':2',2)
else:
lg = lg.replace(':1',':2',1)
for map_ in map_lis:
id_ = attach_idx.index(map_)
lg_lis[id_] = tuple(list(lg_lis[id_]) +[lg + "*"])
else:
print('error')
return [tuple(sorted(i)) for i in lg_lis]
def get_lg_backward(core_edits_,lg_lis):
attach_idx = []
for core_edit in core_edits_:
core_edit = core_edit.split(':')
if float(core_edit[2])-float(core_edit[3]) > 0:
attach_idx.append(int(core_edit[0]))
attach_idx.append(int(core_edit[1]))
attach_idx = [i for i in attach_idx if i != 0]
attach_idx = sorted(list(set(attach_idx)))
lg_map_new = []
for id_,lg_ in zip(attach_idx,lg_lis):
for lg in list(lg_):
if lg.count(':') > 1:
lg_map_new.append((lg,[id_]*lg.count(':')))
else:
lg_map_new.append((lg,[id_]))
dic_t = {}
for i,j in lg_map_new:
if '*' in i:
dic_t.setdefault(i,[]).append(j[0])
else:
pass
lg_map_new_k =[]
for i,j in lg_map_new:
if '*' not in i:
lg_map_new_k.append((i,j))
else:
pass
for i,j in dic_t.items():
if ':2' not in i:
lg_map_new_k.append((i.replace('*',''),j))
elif i.index(':1') <= i.index(':2'):
lg_map_new_k.append((i.replace('*','').replace(':2',':1'),j))
else:
j.reverse()
lg_map_new_k.append((i.replace('*','').replace(':2',':1'),j))
lg_map_new = lg_map_new_k
return lg_map_new
dic_str_to_num = {}
for l in range(4,0,-1):
for a,i in zip([0,200,400,600,100,300,500,700],['','α','β','γ','δ','αδ','βδ','γδ']):
for b,j in zip([0,10,20,30],['','r','s','?']):
for c,k in zip([0,9],['','~']):
if len(k+j+i) == l:
dic_str_to_num[k+j+i] = str(a+b+c)
dic_num_to_str = {}
for l in range(3,0,-1):
for a,i in zip([0,200,400,600,100,300,500,700],['','α','β','γ','δ','αδ','βδ','γδ']):
for b,j in zip([0,10,20,30],['','r','s','?']):
for c,k in zip([0,9],['','~']):
if len(str(a+b+c)) == l and len(k+j+i) != 0:
dic_num_to_str[str(a+b+c)] = k+j+i
def iso_to_symbo(txt,dic_num_to_str):
for i,j in dic_num_to_str.items():
i = '[' + i
j = '[' + j
txt = txt.replace(i,j)
txt = txt.replace('。',';&').replace('》',';}').replace('《',';{')
return txt
def symbo_to_iso(txt,dic_str_to_num):
for i,j in dic_str_to_num.items():
i = '[' + i
j = '[' + j
txt = txt.replace(i,j)
txt = txt.replace(';&','。').replace(';}','》').replace(';{','《')
return txt
def merge_smiles_only(text):
text = symbo_to_iso(text,dic_str_to_num)
o_smiles = text.split('>>>')[0]
b_smiles = text.split('>>>')[1].split('<')[0]
lg_lis = []
for i in re.findall(r"[<](.*?)[>]", text):
if i == '':
lg_lis.append(tuple())
else:
lg_lis.append(tuple(i.split(',')))
core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add = get_b_smiles_backward(b_smiles,o_smiles)
lg_map_lis = get_lg_backward(core_edits,lg_lis)
p = Chem.MolFromSmiles(o_smiles,sanitize = False)
for atom in p.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx()+1)
p = Chem.MolToSmiles(p)
pre_smiles = run_get_p_b_l_backward(p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis)
return pre_smiles
def merge_smiles_with_mapping_only(text):
text = symbo_to_iso(text,dic_str_to_num)
o_smiles = text.split('>>>')[0]
b_smiles = text.split('>>>')[1].split('<')[0]
lg_lis = []
for i in re.findall(r"[<](.*?)[>]", text):
if i == '':
lg_lis.append(tuple())
else:
lg_lis.append(tuple(i.split(',')))
core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add = get_b_smiles_backward(b_smiles,o_smiles)
lg_map_lis = get_lg_backward(core_edits,lg_lis)
p = Chem.MolFromSmiles(o_smiles,sanitize = False)
for atom in p.GetAtoms():
atom.SetAtomMapNum(atom.GetIdx()+1)
p = Chem.MolToSmiles(p)
pre_smiles = run_get_p_b_l_backward_with_mapping(p,core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis)
return pre_smiles
def merge_smiles(text):
try:
return merge_smiles_only(text)
except:
return ""
def merge_smiles_with_mapping(text):
try:
return merge_smiles_with_mapping_only(text)
except:
return ""
def get_e_smiles(rxn):
p_b = run_get_p_b_l_forward(rxn)
b_smiles = get_b_smiles_check(p_b)
lg_lis = get_lg_forward(p_b[1],p_b[6])
k = p_b
b = b_smiles
c = lg_lis
a = Chem.MolFromSmiles(k[0],sanitize = False)
for atom in a.GetAtoms():
atom.SetAtomMapNum(0)
a = Chem.MolToSmiles(a,canonical = False)
str_ = ''
for i in c:
str_ = str_ + '<{}>'.format(','.join(i))
txt = a +'>>>'+ b+str_
return iso_to_symbo(txt,dic_num_to_str)
def get_e_smiles_with_check(rxn):
p_b = run_get_p_b_l_check(rxn)
b_smiles = get_b_smiles_check(p_b)
lg_lis = get_lg_forward(p_b[1],p_b[6])
k = p_b
b = b_smiles
c = lg_lis
a = Chem.MolFromSmiles(k[0],sanitize = False)
for atom in a.GetAtoms():
atom.SetAtomMapNum(0)
a = Chem.MolToSmiles(a,canonical = False)
str_ = ''
for i in c:
str_ = str_ + '<{}>'.format(','.join(i))
txt = a +'>>>'+ b+str_
return iso_to_symbo(txt,dic_num_to_str)
def get_edit_from_e_smiles(text):
text = symbo_to_iso(text,dic_str_to_num)
o_smiles = text.split('>>>')[0]
b_smiles = text.split('>>>')[1].split('<')[0]
lg_lis = []
for i in re.findall(r"[<](.*?)[>]", text):
if i == '':
lg_lis.append(tuple())
else:
lg_lis.append(tuple(i.split(',')))
core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add = get_b_smiles_backward(b_smiles,o_smiles)
lg_map_lis = get_lg_backward(core_edits,lg_lis)
return core_edits,chai_edits,stereo_edits,charge_edits,core_edits_add,lg_map_lis |