1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
|
//
// Copyright (C) 2002-2021 Greg Landrum and other RDKit contributors
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/BoostStartInclude.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/format.hpp>
#include <RDGeneral/BoostEndInclude.h>
#include "FileParsers.h"
#include "FileParserUtils.h"
#include "MolSGroupParsing.h"
#include <GraphMol/FileParsers/MolFileStereochem.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/RDKitQueries.h>
#include <GraphMol/StereoGroup.h>
#include <GraphMol/SubstanceGroup.h>
#include <GraphMol/Atropisomers.h>
#include <RDGeneral/StreamOps.h>
#include <RDGeneral/RDLog.h>
#include <GraphMol/GenericGroups/GenericGroups.h>
#include <GraphMol/QueryOps.h>
#include <GraphMol/Chirality.h>
#include <fstream>
#include <RDGeneral/FileParseException.h>
#include <RDGeneral/BadFileException.h>
#include <RDGeneral/LocaleSwitcher.h>
#include <typeinfo>
#include <exception>
#include <charconv>
#include <regex>
#include <sstream>
#include <locale>
#include <cstdlib>
#include <cstdio>
#include <string_view>
using namespace RDKit::SGroupParsing;
using std::regex;
using std::regex_match;
using std::smatch;
namespace RDKit {
namespace FileParserUtils {
int toInt(const std::string_view input, bool acceptSpaces) {
// don't need to worry about locale stuff here because
// we're not going to have delimiters
// sanity check on the input since strtol doesn't do it for us:
const char *txt = input.data();
for (size_t i = 0u; i < input.size() && *txt != '\x00'; ++i) {
if ((*txt >= '0' && *txt <= '9') || (acceptSpaces && *txt == ' ') ||
*txt == '+' || *txt == '-') {
++txt;
} else {
throw boost::bad_lexical_cast();
}
}
// remove leading spaces
txt = input.data();
unsigned int sz = input.size();
if (acceptSpaces) {
while (*txt == ' ') {
++txt;
--sz;
// have we run off the end of the view?
if (sz < 1U) {
return 0;
}
}
}
int res = 0;
std::from_chars(txt, txt + sz, res);
return res;
}
int toInt(const std::string &input, bool acceptSpaces) {
return toInt(std::string_view(input.c_str()), acceptSpaces);
}
unsigned int toUnsigned(const std::string_view input, bool acceptSpaces) {
// don't need to worry about locale stuff here because
// we're not going to have delimiters
// sanity check on the input since strtol doesn't do it for us:
const char *txt = input.data();
for (size_t i = 0u; i < input.size() && *txt != '\x00'; ++i) {
if ((*txt >= '0' && *txt <= '9') || (acceptSpaces && *txt == ' ') ||
*txt == '+') {
++txt;
} else {
throw boost::bad_lexical_cast();
}
}
// remove leading spaces
txt = input.data();
unsigned int sz = input.size();
if (acceptSpaces) {
while (*txt == ' ') {
++txt;
--sz;
// have we run off the end of the view?
if (sz < 1U) {
return 0;
}
}
}
unsigned int res = 0;
std::from_chars(txt, txt + sz, res);
return res;
}
unsigned int toUnsigned(const std::string &input, bool acceptSpaces) {
return toUnsigned(std::string_view(input.c_str()), acceptSpaces);
}
double toDouble(const std::string_view input, bool acceptSpaces) {
// sanity check on the input since strtol doesn't do it for us:
const char *txt = input.data();
for (size_t i = 0u; i < input.size() && *txt != '\x00'; ++i) {
// check for ',' and '.' because locale
if ((*txt >= '0' && *txt <= '9') || (acceptSpaces && *txt == ' ') ||
*txt == '+' || *txt == '-' || *txt == ',' || *txt == '.') {
++txt;
} else {
throw boost::bad_lexical_cast();
}
}
// unfortunately from_chars() with doubles didn't work on g++ until v11.1
// and the status with clang is hard to figure out... we remain old-school
// remove leading spaces
double res = atof(input.data());
return res;
}
double toDouble(const std::string &input, bool acceptSpaces) {
return toDouble(std::string_view(input.c_str()), acceptSpaces);
}
std::string getV3000Line(std::istream *inStream, unsigned int &line) {
// FIX: technically V3K blocks are case-insensitive. We should really be
// up-casing everything here.
PRECONDITION(inStream, "bad stream");
std::string res;
++line;
auto inl = getLine(inStream);
std::string_view tempStr = inl;
if (tempStr.size() < 7 || tempStr.substr(0, 7) != "M V30 ") {
std::ostringstream errout;
errout << "Line " << line << " does not start with 'M V30 '" << std::endl;
throw FileParseException(errout.str());
}
// FIX: do we need to handle trailing whitespace after a -?
while (tempStr.back() == '-') {
// continuation character, append what we read:
res += tempStr.substr(7, tempStr.length() - 8);
// and then read another line:
++line;
inl = getLine(inStream);
tempStr = inl;
if (tempStr.size() < 7 || tempStr.substr(0, 7) != "M V30 ") {
std::ostringstream errout;
errout << "Line " << line << " does not start with 'M V30 '"
<< std::endl;
throw FileParseException(errout.str());
}
}
res += tempStr.substr(7, tempStr.length() - 7);
return res;
}
Atom *replaceAtomWithQueryAtom(RWMol *mol, Atom *atom) {
return QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
} // namespace FileParserUtils
using RDKit::FileParserUtils::getV3000Line;
namespace {
bool startsWith(const std::string &haystack, const char *needle, size_t size) {
return haystack.compare(0u, size, needle, size) == 0;
}
//! parse a collection block to find enhanced stereo groups
std::string parseEnhancedStereo(std::istream *inStream, unsigned int &line,
RWMol *mol) {
// Lines like (absolute, relative, racemic):
// M V30 MDLV30/STEABS ATOMS=(2 2 3)
// M V30 MDLV30/STEREL1 ATOMS=(1 12)
// M V30 MDLV30/STERAC1 ATOMS=(1 12)
const regex stereo_label(
R"regex(MDLV30/STE(...)([0-9]*) +ATOMS=\(([0-9]+) +(.*)\) *)regex");
smatch match;
std::vector<StereoGroup> groups;
// Read the collection until the end
auto tempStr = getV3000Line(inStream, line);
boost::to_upper(tempStr);
while (!startsWith(tempStr, "END", 3)) {
// If this line in the collection is part of a stereo group
if (regex_match(tempStr, match, stereo_label)) {
StereoGroupType grouptype = RDKit::StereoGroupType::STEREO_ABSOLUTE;
unsigned groupid = 0;
if (match[1] == "ABS") {
grouptype = RDKit::StereoGroupType::STEREO_ABSOLUTE;
} else if (match[1] == "REL") {
grouptype = RDKit::StereoGroupType::STEREO_OR;
groupid = FileParserUtils::toUnsigned(match[2], true);
} else if (match[1] == "RAC") {
grouptype = RDKit::StereoGroupType::STEREO_AND;
groupid = FileParserUtils::toUnsigned(match[2], true);
} else {
std::ostringstream errout;
errout << "Unrecognized stereogroup type : '" << tempStr << "' on line"
<< line;
throw FileParseException(errout.str());
}
const unsigned int count = FileParserUtils::toUnsigned(match[3], true);
std::vector<Atom *> atoms;
std::stringstream ss(match[4]);
unsigned int index;
for (size_t i = 0; i < count; ++i) {
ss >> index;
// atoms are 1 indexed in molfiles
atoms.push_back(mol->getAtomWithIdx(index - 1));
}
std::vector<Bond *> newBonds;
groups.emplace_back(grouptype, std::move(atoms), std::move(newBonds),
groupid);
} else {
// skip collection types we don't know how to read. Only one documented
// is MDLV30/HILITE
BOOST_LOG(rdWarningLog) << "Skipping unrecognized collection type at "
"line "
<< line << ": " << tempStr << std::endl;
}
tempStr = getV3000Line(inStream, line);
}
if (!groups.empty()) {
mol->setStereoGroups(std::move(groups));
}
tempStr = getV3000Line(inStream, line);
return tempStr;
}
//*************************************
//
// Every effort has been made to adhere to MDL's standard
// for mol files
//
//*************************************
void ParseOldAtomList(RWMol *mol, const std::string_view &text,
unsigned int line) {
PRECONDITION(mol, "bad mol");
unsigned int idx;
try {
idx = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(0, 3)) -
1;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(0, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
URANGE_CHECK(idx, mol->getNumAtoms());
QueryAtom a(*(mol->getAtomWithIdx(idx)));
auto *q = new ATOM_OR_QUERY;
q->setDescription("AtomOr");
switch (text[4]) {
case 'T':
q->setNegation(true);
break;
case 'F':
q->setNegation(false);
break;
default:
delete q;
std::ostringstream errout;
errout << "Unrecognized atom-list query modifier: '" << text[4]
<< "' on line " << line;
throw FileParseException(errout.str());
}
int nQueries;
try {
nQueries = FileParserUtils::toInt(text.substr(9, 1));
} catch (const std::out_of_range &) {
delete q;
std::ostringstream errout;
errout << "Cannot convert position 9 of '" << text << "' to int on line "
<< line;
throw FileParseException(errout.str());
} catch (boost::bad_lexical_cast &) {
delete q;
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(9, 1) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
RANGE_CHECK(0, nQueries, 5);
for (int i = 0; i < nQueries; i++) {
int pos = 11 + i * 4;
int atNum;
try {
atNum = FileParserUtils::toInt(text.substr(pos, 3));
} catch (const std::out_of_range &) {
delete q;
std::ostringstream errout;
errout << "Cannot convert position " << pos << " of '" << text
<< "' to int on line " << line;
throw FileParseException(errout.str());
} catch (boost::bad_lexical_cast &) {
delete q;
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(pos, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
RANGE_CHECK(0, atNum, 200); // goofy!
q->addChild(
QueryAtom::QUERYATOM_QUERY::CHILD_TYPE(makeAtomNumQuery(atNum)));
if (!i) {
a.setAtomicNum(atNum);
}
}
a.setQuery(q);
a.setProp(common_properties::_MolFileAtomQuery, 1);
mol->replaceAtom(idx, &a);
}
void ParseChargeLine(RWMol *mol, const std::string &text, bool firstCall,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M CHG"), "bad charge line");
// if this line is specified all the atom other than those specified
// here should carry a charge of 0; but we should only do this once:
if (firstCall) {
for (ROMol::AtomIterator ai = mol->beginAtoms(); ai != mol->endAtoms();
++ai) {
(*ai)->setFormalCharge(0);
}
}
int ie, nent;
try {
nent = FileParserUtils::toInt(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
int spos = 9;
for (ie = 0; ie < nent; ie++) {
int aid, chg;
try {
aid = FileParserUtils::toInt(text.substr(spos, 4));
spos += 4;
chg = FileParserUtils::toInt(text.substr(spos, 4));
spos += 4;
mol->getAtomWithIdx(aid - 1)->setFormalCharge(chg);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseRadicalLine(RWMol *mol, const std::string &text, bool firstCall,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M RAD"), "bad charge line");
// if this line is specified all the atom other than those specified
// here should carry a charge of 0; but we should only do this once:
if (firstCall) {
for (ROMol::AtomIterator ai = mol->beginAtoms(); ai != mol->endAtoms();
++ai) {
(*ai)->setFormalCharge(0);
}
}
int ie, nent;
try {
nent = FileParserUtils::toInt(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
int spos = 9;
for (ie = 0; ie < nent; ie++) {
int aid, rad;
std::ostringstream errout;
try {
aid = FileParserUtils::toInt(text.substr(spos, 4));
spos += 4;
rad = FileParserUtils::toInt(text.substr(spos, 4));
spos += 4;
switch (rad) {
case 0:
// This shouldn't be required, but let's make sure.
mol->getAtomWithIdx(aid - 1)->setNumRadicalElectrons(0);
break;
case 1:
mol->getAtomWithIdx(aid - 1)->setNumRadicalElectrons(2);
break;
case 2:
mol->getAtomWithIdx(aid - 1)->setNumRadicalElectrons(1);
break;
case 3:
mol->getAtomWithIdx(aid - 1)->setNumRadicalElectrons(2);
break;
default:
errout << "Unrecognized radical value " << rad << " for atom "
<< aid - 1 << " on line " << line << std::endl;
throw FileParseException(errout.str());
}
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParsePXALine(RWMol *mol, const std::string &text, unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == "M PXA", "bad PXA line");
unsigned int pos = 7;
try {
auto atIdx =
FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(pos, 3));
pos += 3;
mol->getAtomWithIdx(atIdx - 1)->setProp(
"_MolFile_PXA", text.substr(pos, text.length() - pos));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(pos, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
}
void ParseIsotopeLine(RWMol *mol, const std::string &text, unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M ISO"), "bad isotope line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
Atom *atom = mol->getAtomWithIdx(aid - 1);
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
int isotope = FileParserUtils::toInt(text.substr(spos, 4));
if (isotope < 0) {
BOOST_LOG(rdErrorLog)
<< " atom " << aid
<< " has a negative isotope value. line: " << line << std::endl;
} else {
atom->setIsotope(isotope);
}
}
spos += 4;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseSubstitutionCountLine(RWMol *mol, const std::string &text,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M SUB"), "bad SUB line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid;
int count = 0;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
Atom *atom = mol->getAtomWithIdx(aid - 1);
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
count = FileParserUtils::toInt(text.substr(spos, 4));
}
spos += 4;
if (count == 0) {
continue;
}
ATOM_EQUALS_QUERY *q = makeAtomExplicitDegreeQuery(0);
switch (count) {
case -1:
q->setVal(0);
break;
case -2:
q->setVal(atom->getDegree());
break;
case 1:
case 2:
case 3:
case 4:
case 5:
q->setVal(count);
break;
case 6:
BOOST_LOG(rdWarningLog) << " atom degree query with value 6 found. "
"This will not match degree >6. The MDL "
"spec says it should. line: "
<< line;
q->setVal(6);
break;
default:
std::ostringstream errout;
errout << "Value " << count
<< " is not supported as a degree query. line: " << line;
throw FileParseException(errout.str());
}
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
atom->expandQuery(q, Queries::COMPOSITE_AND);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseUnsaturationLine(RWMol *mol, const std::string &text,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M UNS"), "bad UNS line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid;
int count = 0;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
Atom *atom = mol->getAtomWithIdx(aid - 1);
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
count = FileParserUtils::toInt(text.substr(spos, 4));
}
spos += 4;
if (count == 0) {
continue;
} else if (count == 1) {
ATOM_EQUALS_QUERY *q = makeAtomUnsaturatedQuery();
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
atom->expandQuery(q, Queries::COMPOSITE_AND);
} else {
std::ostringstream errout;
errout << "Value " << count
<< " is not supported as an unsaturation "
"query (only 0 and 1 are allowed). "
"line: "
<< line;
throw FileParseException(errout.str());
}
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseRingBondCountLine(RWMol *mol, const std::string &text,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M RBC"), "bad RBC line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid;
int count = 0;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
Atom *atom = mol->getAtomWithIdx(aid - 1);
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
count = FileParserUtils::toInt(text.substr(spos, 4));
}
spos += 4;
if (count == 0) {
continue;
}
ATOM_EQUALS_QUERY *q = makeAtomRingBondCountQuery(0);
switch (count) {
case -1:
q->setVal(0);
break;
case -2:
q->setVal(0xDEADBEEF);
mol->setProp(common_properties::_NeedsQueryScan, 1);
break;
case 1:
case 2:
case 3:
q->setVal(count);
break;
case 4:
delete q;
q = static_cast<ATOM_EQUALS_QUERY *>(new ATOM_LESSEQUAL_QUERY);
q->setVal(4);
q->setDescription("AtomRingBondCount");
q->setDataFunc(queryAtomRingBondCount);
break;
default:
std::ostringstream errout;
errout << "Value " << count
<< " is not supported as a ring-bond count query. line: "
<< line;
throw FileParseException(errout.str());
}
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
atom->expandQuery(q, Queries::COMPOSITE_AND);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseZCHLine(RWMol *mol, const std::string &text, unsigned int line) {
// part of Alex Clark's ZBO proposal
// from JCIM 51:3149-57 (2011)
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M ZCH"), "bad ZCH line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid = 0;
int val = 0;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
val = FileParserUtils::stripSpacesAndCast<int>(text.substr(spos, 4));
}
if (!aid || aid > mol->getNumAtoms()) {
std::ostringstream errout;
errout << "Bad ZCH specification on line " << line;
throw FileParseException(errout.str());
}
spos += 4;
--aid;
Atom *atom = mol->getAtomWithIdx(aid);
if (!atom) {
std::ostringstream errout;
errout << "Atom " << aid << " from ZCH specification on line " << line
<< " not found";
throw FileParseException(errout.str());
} else {
atom->setFormalCharge(val);
}
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseHYDLine(RWMol *mol, const std::string &text, unsigned int line) {
// part of Alex Clark's ZBO proposal
// from JCIM 51:3149-57 (2011)
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M HYD"), "bad HYD line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid = 0;
int val = -1;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
val = FileParserUtils::stripSpacesAndCast<int>(text.substr(spos, 4));
}
if (!aid || aid > mol->getNumAtoms()) {
std::ostringstream errout;
errout << "Bad HYD specification on line " << line;
throw FileParseException(errout.str());
}
spos += 4;
--aid;
Atom *atom = mol->getAtomWithIdx(aid);
if (!atom) {
std::ostringstream errout;
errout << "Atom " << aid << " from HYD specification on line " << line
<< " not found";
throw FileParseException(errout.str());
} else {
if (val >= 0) {
atom->setProp("_ZBO_H", true);
atom->setNumExplicitHs(val);
}
}
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseZBOLine(RWMol *mol, const std::string &text, unsigned int line) {
// part of Alex Clark's ZBO proposal
// from JCIM 51:3149-57 (2011)
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M ZBO"), "bad ZBO line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int bid = 0;
unsigned int order = 0;
try {
bid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
order = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
}
if (!bid || bid > mol->getNumBonds()) {
std::ostringstream errout;
errout << "Bad ZBO specification on line " << line;
throw FileParseException(errout.str());
}
spos += 4;
--bid;
Bond *bnd = mol->getBondWithIdx(bid);
if (!bnd) {
std::ostringstream errout;
errout << "Bond " << bid << " from ZBO specification on line " << line
<< " not found";
throw FileParseException(errout.str());
} else {
if (order == 0) {
bnd->setBondType(Bond::ZERO);
} else {
bnd->setBondType(static_cast<Bond::BondType>(order));
}
}
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
void ParseMarvinSmartsLine(RWMol *mol, const std::string &text,
unsigned int line) {
const unsigned int atomNumStart = 10;
const unsigned int smartsStart = 15;
// M MRV SMA 1 [*;A]
// 01234567890123456789
// 1111111111
if (text.substr(0, 10) != "M MRV SMA") {
return;
}
unsigned int idx;
std::string idxTxt = text.substr(atomNumStart, smartsStart - atomNumStart);
try {
idx = FileParserUtils::stripSpacesAndCast<unsigned int>(idxTxt) - 1;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << idxTxt << "' to an atom index on line "
<< line;
throw FileParseException(errout.str());
}
URANGE_CHECK(idx, mol->getNumAtoms());
// Should we check the validity of the marvin line here? Should we
// automatically
// Add these as recursive smarts? I tend to think so...
std::string sma = text.substr(smartsStart);
Atom *at = mol->getAtomWithIdx(idx);
at->setProp(common_properties::MRV_SMA, sma);
RWMol *m = nullptr;
try {
m = SmartsToMol(sma);
} catch (...) {
// Is this ever used?
}
if (m) {
QueryAtom::QUERYATOM_QUERY *query = new RecursiveStructureQuery(m);
if (!at->hasQuery()) {
QueryAtom qAt(*at);
int oidx = at->getIdx();
mol->replaceAtom(oidx, &qAt);
at = mol->getAtomWithIdx(oidx);
}
at->expandQuery(query, Queries::COMPOSITE_AND);
at->setProp(common_properties::_MolFileAtomQuery, 1);
} else {
std::ostringstream errout;
errout << "Cannot parse smarts: '" << sma << "' on line " << line;
throw FileParseException(errout.str());
}
}
void ParseAttachPointLine(RWMol *mol, const std::string &text,
unsigned int line, bool strictParsing) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M APO"), "bad APO line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
unsigned int aid = 0;
int val = 0;
try {
aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
val = FileParserUtils::stripSpacesAndCast<int>(text.substr(spos, 4));
}
if (!aid || aid > mol->getNumAtoms()) {
std::ostringstream errout;
errout << "Bad APO specification on line " << line;
throw FileParseException(errout.str());
}
spos += 4;
--aid;
Atom *atom = mol->getAtomWithIdx(aid);
if (!atom) {
std::ostringstream errout;
errout << "Atom " << aid << " from APO specification on line " << line
<< " not found";
throw FileParseException(errout.str());
} else {
if (val < 0 || val > 3) {
std::ostringstream errout;
errout << "Value " << val << " from APO specification on line "
<< line << " is invalid";
throw FileParseException(errout.str());
} else if (val) {
if (val == 3) {
// this is -1 in v3k mol blocks, so use that:
val = -1;
}
if (atom->hasProp(common_properties::molAttachPoint)) {
std::ostringstream errout;
errout << "Multiple ATTCHPT values for atom " << atom->getIdx() + 1
<< " on line " << line;
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
} else {
atom->setProp(common_properties::molAttachPoint, val);
}
}
}
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
}
}
// the format differs between V2000 and V3000, so we have to do a bit of
// translation here
void ParseLinkNodeLine(RWMol *mol, const std::string &text, unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M LIN"), "bad LIN line");
unsigned int nent;
try {
nent = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
std::string propVal = "";
unsigned int spos = 9;
for (unsigned int ie = 0; ie < nent; ie++) {
try {
auto aid = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
if (!aid || aid > mol->getNumAtoms()) {
std::ostringstream errout;
errout << "LIN specification has bad atom idx on line " << line;
throw FileParseException(errout.str());
}
spos += 4;
if (text.size() < spos + 4 || text.substr(spos, 4) == " ") {
std::ostringstream errout;
errout << "LIN specification missing repeat count on line " << line;
throw FileParseException(errout.str());
}
auto repeatCount = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
spos += 4;
if (repeatCount < 2) {
std::ostringstream errout;
errout << "LIN specification: repeat count must be >=2 on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int substB = 0;
unsigned int substC = 0;
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
substB = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
}
spos += 4;
if (text.size() >= spos + 4 && text.substr(spos, 4) != " ") {
substC = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(spos, 4));
}
spos += 4;
if (!substB || substB > mol->getNumAtoms() ||
substC > mol->getNumAtoms()) {
std::ostringstream errout;
errout << "LIN specification has bad substituent idx on line " << line;
throw FileParseException(errout.str());
}
boost::format formatter;
if (substC) {
formatter = boost::format("1 %1% 2 %2% %3% %2% %4%") % repeatCount %
aid % substB % substC;
} else {
formatter = boost::format("1 %1% 1 %2% %3%") % repeatCount % aid %
substB % substC;
}
if (!propVal.empty()) {
propVal += "|";
}
propVal += formatter.str();
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 4)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
mol->setProp(common_properties::molFileLinkNodes, propVal);
}
}
// Recursively populates queryVect with COMPOSITE_AND queries
// present in the input query. If the logic of the input query
// is more complex, it returns nullptr and empty set.
// The returned ptr should only be checked for not being null
// and not used for any other purposes, as the actual result is
// the queryVect
const QueryAtom::QUERYATOM_QUERY *getAndQueries(
const QueryAtom::QUERYATOM_QUERY *q,
std::vector<const QueryAtom::QUERYATOM_QUERY *> &queryVect) {
if (q) {
auto qOrig = q;
for (auto cq = qOrig->beginChildren(); cq != qOrig->endChildren(); ++cq) {
if (q == qOrig && q->getDescription() != "AtomAnd") {
q = nullptr;
break;
}
q = getAndQueries(cq->get(), queryVect);
}
if (q == qOrig) {
queryVect.push_back(q);
}
}
if (!q) {
queryVect.clear();
}
return q;
}
void ParseNewAtomList(RWMol *mol, const std::string &text, unsigned int line) {
if (text.size() < 15) {
std::ostringstream errout;
errout << "Atom list line too short: '" << text << "'";
throw FileParseException(errout.str());
}
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M ALS"),
"bad atom list line");
unsigned int idx;
try {
idx = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(7, 3)) -
1;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(7, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
URANGE_CHECK(idx, mol->getNumAtoms());
int nQueries;
try {
nQueries = FileParserUtils::toInt(text.substr(10, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(10, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
if (!nQueries) {
BOOST_LOG(rdWarningLog) << "Empty atom list: '" << text << "' on line "
<< line << "." << std::endl;
return;
}
if (nQueries < 0) {
std::ostringstream errout;
errout << "negative length atom list: '" << text << "' on line " << line
<< "." << std::endl;
throw FileParseException(errout.str());
}
QueryAtom *a = nullptr;
QueryAtom *qaOrig = nullptr;
QueryAtom::QUERYATOM_QUERY *qOrig = nullptr;
Atom *aOrig = mol->getAtomWithIdx(idx);
for (unsigned int i = 0; i < static_cast<unsigned int>(nQueries); i++) {
unsigned int pos = 16 + i * 4;
if (text.size() < pos + 4) {
std::ostringstream errout;
errout << "Atom list line too short: '" << text << "' on line " << line;
throw FileParseException(errout.str());
}
std::string atSymb = text.substr(pos, 4);
atSymb.erase(atSymb.find(' '), atSymb.size());
int atNum = PeriodicTable::getTable()->getAtomicNumber(atSymb);
if (!i) {
if (aOrig->hasQuery()) {
qaOrig = dynamic_cast<QueryAtom *>(aOrig);
if (qaOrig) {
qOrig = qaOrig->getQuery();
}
}
a = new QueryAtom(*aOrig);
a->setAtomicNum(atNum);
if (!qOrig) {
qOrig = a->getQuery()->copy();
}
a->setQuery(makeAtomNumQuery(atNum));
} else {
a->expandQuery(makeAtomNumQuery(atNum), Queries::COMPOSITE_OR, true);
// For COMPOSITE_OR query atoms, reset atomic num to 0 such that they are
// exported as "*" in SMILES
a->setAtomicNum(0);
}
}
ASSERT_INVARIANT(a, "no atom built");
if (qOrig) {
std::vector<const QueryAtom::QUERYATOM_QUERY *> queryVect;
if (getAndQueries(qOrig, queryVect)) {
for (const auto &q : queryVect) {
if (q->getDescription() != "AtomAtomicNum") {
a->expandQuery(q->copy(), Queries::COMPOSITE_AND, true);
}
}
}
if (!qaOrig) {
delete qOrig;
}
}
a->setProp(common_properties::_MolFileAtomQuery, 1);
switch (text[14]) {
case 'T':
a->getQuery()->setNegation(true);
break;
case 'F':
a->getQuery()->setNegation(false);
break;
default:
std::ostringstream errout;
errout << "Unrecognized atom-list query modifier: '" << text[14]
<< "' on line " << line;
delete a;
throw FileParseException(errout.str());
}
mol->replaceAtom(idx, a);
delete a;
}
void ParseV3000RGroups(RWMol *mol, Atom *&atom, std::string_view text,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(atom, "bad atom");
if (text[0] != '(' || text.back() != ')') {
std::ostringstream errout;
errout << "Bad RGROUPS specification '" << text << "' on line " << line
<< ". Missing parens.";
throw FileParseException(errout.str());
}
std::vector<std::string> splitToken;
std::string resid = std::string(text.substr(1, text.size() - 2));
boost::split(splitToken, resid, boost::is_any_of(std::string(" ")));
if (splitToken.size() < 1) {
std::ostringstream errout;
errout << "Bad RGROUPS specification '" << text << "' on line " << line
<< ". Missing values.";
throw FileParseException(errout.str());
}
unsigned int nRs;
try {
nRs = FileParserUtils::stripSpacesAndCast<unsigned int>(splitToken[0]);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << splitToken[0] << "' to int on line" << line;
throw FileParseException(errout.str());
}
if (splitToken.size() < nRs + 1) {
std::ostringstream errout;
errout << "Bad RGROUPS specification '" << text << "' on line " << line
<< ". Not enough values.";
throw FileParseException(errout.str());
}
for (unsigned int i = 0; i < nRs; ++i) {
unsigned int rLabel;
try {
rLabel =
FileParserUtils::stripSpacesAndCast<unsigned int>(splitToken[i + 1]);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << splitToken[i + 1] << "' to int on line"
<< line;
throw FileParseException(errout.str());
}
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
atom->setProp(common_properties::_MolFileRLabel, rLabel);
std::string dLabel = "R" + std::to_string(rLabel);
atom->setProp(common_properties::dummyLabel, dLabel);
atom->setIsotope(rLabel);
atom->setQuery(makeAtomNullQuery());
}
}
void ParseRGroupLabels(RWMol *mol, const std::string &text, unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 6) == std::string("M RGP"),
"bad R group label line");
int nLabels;
try {
nLabels = FileParserUtils::toInt(text.substr(6, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(6, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
for (int i = 0; i < nLabels; i++) {
int pos = 10 + i * 8;
unsigned int atIdx;
try {
atIdx = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(pos, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(pos, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
unsigned int rLabel;
try {
rLabel = FileParserUtils::stripSpacesAndCast<unsigned int>(
text.substr(pos + 4, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(pos + 4, 3)
<< "' to int on line " << line;
throw FileParseException(errout.str());
}
atIdx -= 1;
if (atIdx > mol->getNumAtoms()) {
std::ostringstream errout;
errout << "Attempt to set R group label on nonexistent atom " << atIdx
<< " on line " << line;
throw FileParseException(errout.str());
}
QueryAtom qatom(*(mol->getAtomWithIdx(atIdx)));
qatom.setProp(common_properties::_MolFileRLabel, rLabel);
// set the dummy label so that this is shown correctly
// in other pieces of the code :
// (this was sf.net issue 3316600)
std::string dLabel = "R" + std::to_string(rLabel);
qatom.setProp(common_properties::dummyLabel, dLabel);
// the CTFile spec (June 2005 version) technically only allows
// R labels up to 32. Since there are three digits, we'll accept
// anything: so long as it's positive and less than 1000:
if (rLabel > 0 && rLabel < 999) {
qatom.setIsotope(rLabel);
}
qatom.setQuery(makeAtomNullQuery());
mol->replaceAtom(atIdx, &qatom);
}
}
void ParseAtomAlias(RWMol *mol, std::string text, const std::string &nextLine,
unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 2) == std::string("A "), "bad atom alias line");
unsigned int idx;
try {
idx = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(3, 3)) -
1;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(3, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
URANGE_CHECK(idx, mol->getNumAtoms());
Atom *at = mol->getAtomWithIdx(idx);
at->setProp(common_properties::molFileAlias, nextLine);
}
void ParseAtomValue(RWMol *mol, std::string text, unsigned int line) {
PRECONDITION(mol, "bad mol");
PRECONDITION(text.substr(0, 2) == std::string("V "), "bad atom value line");
unsigned int idx;
try {
idx = FileParserUtils::stripSpacesAndCast<unsigned int>(text.substr(3, 3)) -
1;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(3, 3) << "' to int on line"
<< line;
throw FileParseException(errout.str());
}
URANGE_CHECK(idx, mol->getNumAtoms());
Atom *at = mol->getAtomWithIdx(idx);
at->setProp(common_properties::molFileValue,
text.substr(7, text.length() - 7));
}
namespace {
void setRGPProps(const std::string_view symb, Atom *res) {
PRECONDITION(res, "bad atom pointer");
// set the dummy label so that this is shown correctly
// in other pieces of the code :
std::string symbc(symb);
res->setProp(common_properties::dummyLabel, symbc);
}
void lookupAtomicNumber(Atom *res, const std::string &symb,
bool strictParsing) {
try {
res->setAtomicNum(PeriodicTable::getTable()->getAtomicNumber(symb));
} catch (const Invar::Invariant &e) {
if (strictParsing || symb.empty()) {
throw FileParseException(e.what());
} else {
res->setAtomicNum(0);
res->setProp(common_properties::dummyLabel, symb);
}
}
}
} // namespace
Atom *ParseMolFileAtomLine(const std::string_view text, RDGeom::Point3D &pos,
unsigned int line, bool strictParsing) {
std::string symb;
int massDiff, chg, hCount;
if ((strictParsing && text.size() < 34) || text.size() < 32) {
std::ostringstream errout;
errout << "Atom line too short: '" << text << "' on line " << line;
throw FileParseException(errout.str());
}
try {
pos.x = FileParserUtils::toDouble(text.substr(0, 10));
pos.y = FileParserUtils::toDouble(text.substr(10, 10));
pos.z = FileParserUtils::toDouble(text.substr(20, 10));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot process coordinates on line " << line;
throw FileParseException(errout.str());
}
symb = text.substr(31, 3);
boost::trim(symb);
// REVIEW: should we handle missing fields at the end of the line?
massDiff = 0;
if (text.size() >= 36 && text.substr(34, 2) != " 0") {
try {
massDiff = FileParserUtils::toInt(text.substr(34, 2), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(34, 2) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
}
chg = 0;
if (text.size() >= 39 && text.substr(36, 3) != " 0") {
try {
chg = FileParserUtils::toInt(text.substr(36, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(36, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
}
hCount = 0;
if (text.size() >= 45 && text.substr(42, 3) != " 0") {
try {
hCount = FileParserUtils::toInt(text.substr(42, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(42, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
}
std::unique_ptr<Atom> res(new Atom);
bool isComplexQueryName =
std::find(complexQueries.begin(), complexQueries.end(), symb) !=
complexQueries.end();
if (isComplexQueryName || symb == "L" || symb == "*" || symb == "LP" ||
symb == "R" || symb == "R#" ||
(symb[0] == 'R' && symb >= "R0" && symb <= "R99")) {
if (isComplexQueryName || symb == "*" || symb == "R") {
auto *query = new QueryAtom(0);
if (symb == "*" || symb == "R") {
// according to the MDL spec, these match anything
query->setQuery(makeAtomNullQuery());
} else if (isComplexQueryName) {
convertComplexNameToQuery(query, symb);
}
res.reset(query);
// queries have no implicit Hs:
res->setNoImplicit(true);
} else {
res->setAtomicNum(0);
}
if (massDiff == 0 && symb[0] == 'R') {
if (symb.length() > 1 && symb >= "R0" && symb <= "R99") {
std::string rlabel = "";
rlabel = symb.substr(1, symb.length() - 1);
int rnumber;
try {
rnumber = boost::lexical_cast<int>(rlabel);
} catch (boost::bad_lexical_cast &) {
rnumber = -1;
}
if (rnumber >= 0) {
res->setIsotope(rnumber);
}
}
}
if (symb[0] == 'R') {
// we used to skip R# here because that really should be handled by an
// RGP spec, but that turned out to not be permissive enough... <sigh>
setRGPProps(symb, res.get());
}
} else if (symb == "D") { // mol blocks support "D" and "T" as shorthand...
// handle that.
res->setAtomicNum(1);
res->setIsotope(2);
} else if (symb == "T") { // mol blocks support "D" and "T" as shorthand...
// handle that.
res->setAtomicNum(1);
res->setIsotope(3);
} else if (symb == "Pol" || symb == "Mod") {
res->setAtomicNum(0);
res->setProp(common_properties::dummyLabel, symb);
} else if (GenericGroups::genericMatchers.find(symb) !=
GenericGroups::genericMatchers.end()) {
res.reset(new QueryAtom(0));
res->setProp(common_properties::atomLabel, std::string(symb));
} else {
if (symb.size() == 2 && symb[1] >= 'A' && symb[1] <= 'Z') {
symb[1] = static_cast<char>(tolower(symb[1]));
}
lookupAtomicNumber(res.get(), symb, strictParsing);
}
// res->setPos(pX,pY,pZ);
if (chg != 0) {
res->setFormalCharge(4 - chg);
}
if (hCount >= 1) {
if (!res->hasQuery()) {
auto qatom = new QueryAtom(*res);
res.reset(qatom);
}
res->setNoImplicit(true);
if (hCount > 1) {
ATOM_EQUALS_QUERY *oq = makeAtomImplicitHCountQuery(hCount - 1);
auto nq = makeAtomSimpleQuery<ATOM_LESSEQUAL_QUERY>(
hCount - 1, oq->getDataFunc(),
std::string("less_") + oq->getDescription());
res->expandQuery(nq);
delete oq;
} else {
res->expandQuery(makeAtomImplicitHCountQuery(0));
}
}
if (massDiff != 0) {
int defIso =
PeriodicTable::getTable()->getMostCommonIsotope(res->getAtomicNum());
int dIso = defIso + massDiff;
if (dIso < 0) {
BOOST_LOG(rdWarningLog)
<< " atom " << res->getIdx()
<< " has a negative isotope offset. line: " << line << std::endl;
}
res->setIsotope(dIso);
}
if (text.size() >= 42 && text.substr(39, 3) != " 0") {
int parity = 0;
try {
parity = FileParserUtils::toInt(text.substr(39, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(39, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
res->setProp(common_properties::molParity, parity);
}
if (text.size() >= 48 && text.substr(45, 3) != " 0") {
int stereoCare = 0;
try {
stereoCare = FileParserUtils::toInt(text.substr(45, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(45, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
res->setProp(common_properties::molStereoCare, stereoCare);
}
if (text.size() >= 51 && text.substr(48, 3) != " 0") {
int totValence = 0;
try {
totValence = FileParserUtils::toInt(text.substr(48, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(48, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
if (totValence != 0) {
// only set if it's a non-default value
res->setProp(common_properties::molTotValence, totValence);
}
}
if (text.size() >= 57 && text.substr(54, 3) != " 0") {
int rxnRole = 0;
try {
rxnRole = FileParserUtils::toInt(text.substr(54, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(54, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
if (rxnRole != 0) {
// only set if it's a non-default value
res->setProp(common_properties::molRxnRole, rxnRole);
}
}
if (text.size() >= 60 && text.substr(57, 3) != " 0") {
int rxnComponent = 0;
try {
rxnComponent = FileParserUtils::toInt(text.substr(57, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(57, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
if (rxnComponent != 0) {
// only set if it's a non-default value
res->setProp(common_properties::molRxnComponent, rxnComponent);
}
}
if (text.size() >= 63 && text.substr(60, 3) != " 0") {
int atomMapNumber = 0;
try {
atomMapNumber = FileParserUtils::toInt(text.substr(60, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(60, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
res->setProp(common_properties::molAtomMapNumber, atomMapNumber);
}
if (text.size() >= 66 && text.substr(63, 3) != " 0") {
int inversionFlag = 0;
try {
inversionFlag = FileParserUtils::toInt(text.substr(63, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(63, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
res->setProp(common_properties::molInversionFlag, inversionFlag);
}
if (text.size() >= 69 && text.substr(66, 3) != " 0") {
int exactChangeFlag = 0;
try {
exactChangeFlag = FileParserUtils::toInt(text.substr(66, 3), true);
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(66, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
res->setProp("molExactChangeFlag", exactChangeFlag);
}
return res.release();
}
Bond *ParseMolFileBondLine(const std::string_view text, unsigned int line) {
unsigned int idx1, idx2, bType, stereo;
int spos = 0;
if (text.size() < 9) {
std::ostringstream errout;
errout << "Bond line too short: '" << text << "' on line " << line;
throw FileParseException(errout.str());
}
try {
idx1 = FileParserUtils::toUnsigned(text.substr(spos, 3));
spos += 3;
idx2 = FileParserUtils::toUnsigned(text.substr(spos, 3));
spos += 3;
bType = FileParserUtils::toUnsigned(text.substr(spos, 3));
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << text.substr(spos, 3) << "' to int on line "
<< line;
throw FileParseException(errout.str());
}
// adjust the numbering
idx1--;
idx2--;
Bond::BondType type;
Bond *res = nullptr;
switch (bType) {
case 1:
type = Bond::SINGLE;
res = new Bond;
break;
case 2:
type = Bond::DOUBLE;
res = new Bond;
break;
case 3:
type = Bond::TRIPLE;
res = new Bond;
break;
case 4:
type = Bond::AROMATIC;
res = new Bond;
break;
case 9:
type = Bond::DATIVE;
res = new Bond;
break;
case 0:
type = Bond::UNSPECIFIED;
res = new Bond;
BOOST_LOG(rdWarningLog)
<< "bond with order 0 found on line " << line
<< ". This is not part of the MDL specification." << std::endl;
break;
default:
type = Bond::UNSPECIFIED;
// it's a query bond of some type
res = new QueryBond;
if (bType == 8) {
BOND_NULL_QUERY *q;
q = makeBondNullQuery();
res->setQuery(q);
} else if (bType == 5) {
res->setQuery(makeSingleOrDoubleBondQuery());
res->setProp(common_properties::_MolFileBondQuery, 1);
} else if (bType == 6) {
res->setQuery(makeSingleOrAromaticBondQuery());
res->setProp(common_properties::_MolFileBondQuery, 1);
} else if (bType == 7) {
res->setQuery(makeDoubleOrAromaticBondQuery());
res->setProp(common_properties::_MolFileBondQuery, 1);
} else {
BOND_NULL_QUERY *q;
q = makeBondNullQuery();
res->setQuery(q);
BOOST_LOG(rdWarningLog)
<< "unrecognized query bond type, " << bType << ", found on line "
<< line << ". Using an \"any\" query." << std::endl;
}
break;
}
res->setBeginAtomIdx(idx1);
res->setEndAtomIdx(idx2);
res->setBondType(type);
res->setProp(common_properties::_MolFileBondType, bType);
if (text.size() >= 12 && text.substr(9, 3) != " 0") {
try {
stereo = FileParserUtils::toUnsigned(text.substr(9, 3));
switch (stereo) {
case 0:
res->setBondDir(Bond::NONE);
break;
case 1:
res->setBondDir(Bond::BEGINWEDGE);
break;
case 6:
res->setBondDir(Bond::BEGINDASH);
break;
case 3: // "either" double bond
res->setBondDir(Bond::EITHERDOUBLE);
res->setStereo(Bond::STEREOANY);
break;
case 4: // "either" single bond
res->setBondDir(Bond::UNKNOWN);
break;
}
res->setProp(common_properties::_MolFileBondStereo, stereo);
} catch (boost::bad_lexical_cast &) {
;
}
}
if (text.size() >= 18 && text.substr(15, 3) != " 0") {
try {
int topology = FileParserUtils::toInt(text.substr(15, 3));
if (topology) {
if (!res->hasQuery()) {
auto *qBond = new QueryBond(*res);
delete res;
res = qBond;
}
BOND_EQUALS_QUERY *q = makeBondIsInRingQuery();
switch (topology) {
case 1:
break;
case 2:
q->setNegation(true);
break;
default:
std::ostringstream errout;
errout << "Unrecognized bond topology specifier: " << topology
<< " on line " << line;
throw FileParseException(errout.str());
}
res->expandQuery(q);
}
} catch (boost::bad_lexical_cast &) {
;
}
}
if (text.size() >= 21 && text.substr(18, 3) != " 0") {
try {
int reactStatus = FileParserUtils::toInt(text.substr(18, 3));
res->setProp("molReactStatus", reactStatus);
} catch (boost::bad_lexical_cast &) {
;
}
}
return res;
} // namespace
void ParseMolBlockAtoms(std::istream *inStream, unsigned int &line,
unsigned int nAtoms, RWMol *mol, Conformer *conf,
bool strictParsing) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(mol, "bad molecule");
PRECONDITION(conf, "bad conformer");
for (unsigned int i = 1; i <= nAtoms; ++i) {
++line;
std::string tempStr = getLine(inStream);
if (inStream->eof()) {
throw FileParseException("EOF hit while reading atoms");
}
RDGeom::Point3D pos;
Atom *atom = ParseMolFileAtomLine(tempStr, pos, line, strictParsing);
unsigned int aid = mol->addAtom(atom, false, true);
conf->setAtomPos(aid, pos);
mol->setAtomBookmark(atom, i);
}
}
void ParseMolBlockBonds(std::istream *inStream, unsigned int &line,
unsigned int nBonds, RWMol *mol,
bool &chiralityPossible) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(mol, "bad molecule");
for (unsigned int i = 1; i <= nBonds; ++i) {
++line;
std::string tempStr = getLine(inStream);
if (inStream->eof()) {
throw FileParseException("EOF hit while reading bonds");
}
Bond *bond = ParseMolFileBondLine(tempStr, line);
// if we got an aromatic bond set the flag on the bond and the connected
// atoms
if (bond->getBondType() == Bond::AROMATIC) {
bond->setIsAromatic(true);
}
// if the bond might have chirality info associated with it, set a flag:
if (bond->getBondDir() != Bond::NONE &&
bond->getBondDir() != Bond::UNKNOWN) {
chiralityPossible = true;
}
// v2k has no way to set stereoCare on bonds, so set the property if both
// the beginning and end atoms have it set:
int care1 = 0;
int care2 = 0;
if (!bond->hasProp(common_properties::molStereoCare) &&
mol->getAtomWithIdx(bond->getBeginAtomIdx())
->getPropIfPresent(common_properties::molStereoCare, care1) &&
mol->getAtomWithIdx(bond->getEndAtomIdx())
->getPropIfPresent(common_properties::molStereoCare, care2)) {
if (care1 && care2) {
bond->setProp(common_properties::molStereoCare, 1);
}
}
mol->addBond(bond, true);
mol->setBondBookmark(bond, i);
}
}
bool checkAttachmentPointsAreValid(
const RWMol *mol, std::pair<const int, SubstanceGroup> &sgroup) {
bool res = true;
int nAtoms = static_cast<int>(mol->getNumAtoms());
std::vector<SubstanceGroup::AttachPoint> &attachPoints =
sgroup.second.getAttachPoints();
for (auto &attachPoint : attachPoints) {
if (attachPoint.lvIdx == nAtoms) {
const std::vector<unsigned int> &bonds = sgroup.second.getBonds();
if (bonds.size() == 1) {
const auto bond = mol->getBondWithIdx(bonds.front());
if (bond->getBeginAtomIdx() == attachPoint.aIdx ||
bond->getEndAtomIdx() == attachPoint.aIdx) {
attachPoint.lvIdx = bond->getOtherAtomIdx(attachPoint.aIdx);
}
}
}
if (attachPoint.lvIdx == nAtoms) {
BOOST_LOG(rdWarningLog)
<< "Could not infer missing lvIdx on malformed SAP line for SGroup "
<< sgroup.first << std::endl;
res = false;
}
}
return res;
}
bool ParseMolBlockProperties(std::istream *inStream, unsigned int &line,
RWMol *mol, bool strictParsing) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(mol, "bad molecule");
// older mol files can have an atom list block here
std::string tempStr = getLine(inStream);
++line;
// there is apparently some software out there that puts a
// blank line in mol blocks before the "M END". If we aren't
// doing strict parsing, deal with that here.
if (!tempStr.size()) {
if (!strictParsing) {
tempStr = getLine(inStream);
++line;
} else {
std::ostringstream errout;
errout << "Problems encountered parsing Mol data, unexpected blank line "
"found at line "
<< line;
throw FileParseException(errout.str());
}
} else {
if (tempStr[0] != 'M' && tempStr[0] != 'A' && tempStr[0] != 'V' &&
tempStr[0] != 'G' && tempStr[0] != 'S') {
ParseOldAtomList(mol, std::string_view(tempStr.c_str()), line);
}
}
IDX_TO_SGROUP_MAP sGroupMap;
IDX_TO_STR_VECT_MAP dataFieldsMap;
bool fileComplete = false;
bool firstChargeLine = true;
unsigned int SCDcounter = 0;
unsigned int lastDataSGroup = 0;
std::ostringstream currentDataField;
std::string lineBeg = tempStr.substr(0, 6);
while (!inStream->eof() && !inStream->fail() && lineBeg != "M END" &&
tempStr.substr(0, 4) != "$$$$") {
if (tempStr[0] == 'A') {
line++;
std::string nextLine = getLine(inStream);
if (lineBeg != "M END") {
ParseAtomAlias(mol, tempStr, nextLine, line);
}
} else if (tempStr[0] == 'G') {
BOOST_LOG(rdWarningLog)
<< " deprecated group abbreviation ignored on line " << line
<< std::endl;
// we need to skip the next line, which holds the abbreviation:
line++;
tempStr = getLine(inStream);
} else if (tempStr[0] == 'V') {
ParseAtomValue(mol, tempStr, line);
} else if (lineBeg == "S SKP") {
int nToSkip = FileParserUtils::toInt(tempStr.substr(6, 3));
if (nToSkip < 0) {
std::ostringstream errout;
errout << "negative skip value " << nToSkip << " on line " << line;
throw FileParseException(errout.str());
}
for (unsigned int i = 0; i < static_cast<unsigned int>(nToSkip); ++i) {
++line;
tempStr = getLine(inStream);
}
} else if (lineBeg == "M ALS") {
ParseNewAtomList(mol, tempStr, line);
} else if (lineBeg == "M ISO") {
ParseIsotopeLine(mol, tempStr, line);
} else if (lineBeg == "M RGP") {
ParseRGroupLabels(mol, tempStr, line);
} else if (lineBeg == "M RBC") {
ParseRingBondCountLine(mol, tempStr, line);
} else if (lineBeg == "M SUB") {
ParseSubstitutionCountLine(mol, tempStr, line);
} else if (lineBeg == "M UNS") {
ParseUnsaturationLine(mol, tempStr, line);
} else if (lineBeg == "M CHG") {
ParseChargeLine(mol, tempStr, firstChargeLine, line);
firstChargeLine = false;
} else if (lineBeg == "M RAD") {
ParseRadicalLine(mol, tempStr, firstChargeLine, line);
firstChargeLine = false;
} else if (lineBeg == "M PXA") {
ParsePXALine(mol, tempStr, line);
/* SGroup parsing start */
} else if (lineBeg == "M STY") {
ParseSGroupV2000STYLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SST") {
ParseSGroupV2000SSTLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SLB") {
ParseSGroupV2000SLBLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SCN") {
ParseSGroupV2000SCNLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SDS") {
ParseSGroupV2000SDSLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SAL" || lineBeg == "M SBL" ||
lineBeg == "M SPA") {
ParseSGroupV2000VectorDataLine(sGroupMap, mol, tempStr, line,
strictParsing);
} else if (lineBeg == "M SMT") {
ParseSGroupV2000SMTLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SDI") {
ParseSGroupV2000SDILine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M CRS") {
std::ostringstream errout;
errout << "Unsupported SGroup subtype '" << lineBeg << "' on line "
<< line;
throw FileParseException(errout.str());
} else if (lineBeg == "M SBV") {
ParseSGroupV2000SBVLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SDT") {
ParseSGroupV2000SDTLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SDD") {
ParseSGroupV2000SDDLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SCD" || lineBeg == "M SED") {
ParseSGroupV2000SCDSEDLine(sGroupMap, dataFieldsMap, mol, tempStr, line,
strictParsing, SCDcounter, lastDataSGroup,
currentDataField);
} else if (lineBeg == "M SPL") {
ParseSGroupV2000SPLLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SNC") {
ParseSGroupV2000SNCLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SAP") {
ParseSGroupV2000SAPLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SCL") {
ParseSGroupV2000SCLLine(sGroupMap, mol, tempStr, line, strictParsing);
} else if (lineBeg == "M SBT") {
ParseSGroupV2000SBTLine(sGroupMap, mol, tempStr, line, strictParsing);
/* SGroup parsing end */
} else if (lineBeg == "M ZBO") {
ParseZBOLine(mol, tempStr, line);
} else if (lineBeg == "M ZCH") {
ParseZCHLine(mol, tempStr, line);
} else if (lineBeg == "M HYD") {
ParseHYDLine(mol, tempStr, line);
} else if (lineBeg == "M MRV") {
ParseMarvinSmartsLine(mol, tempStr, line);
} else if (lineBeg == "M APO") {
ParseAttachPointLine(mol, tempStr, line, strictParsing);
} else if (lineBeg == "M LIN") {
ParseLinkNodeLine(mol, tempStr, line);
}
line++;
tempStr = getLine(inStream);
lineBeg = tempStr.substr(0, 6);
}
if (tempStr[0] == 'M' && tempStr.substr(0, 6) == "M END") {
// All went well, make final updates to SGroups, and add them to Mol
for (auto &sgroup : sGroupMap) {
if (sgroup.second.getIsValid()) {
sgroup.second.setProp("DATAFIELDS", dataFieldsMap[sgroup.first]);
sgroup.second.setIsValid(checkAttachmentPointsAreValid(mol, sgroup));
}
if (sgroup.second.getIsValid()) {
addSubstanceGroup(*mol, sgroup.second);
} else {
std::ostringstream errout;
errout << "SGroup " << sgroup.first << " is invalid";
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog)
<< errout.str() << " and will be ignored" << std::endl;
}
}
}
fileComplete = true;
}
return fileComplete;
}
Atom *ParseV3000AtomSymbol(std::string_view token, unsigned int &line,
bool strictParsing) {
bool negate = false;
token = FileParserUtils::strip(token);
if (token.size() > 3 && (token[0] == 'N' || token[0] == 'n') &&
(token[1] == 'O' || token[1] == 'o') &&
(token[2] == 'T' || token[2] == 't')) {
negate = true;
token = token.substr(3, token.size() - 3);
token = FileParserUtils::strip(token);
}
std::unique_ptr<Atom> res;
if (token[0] == '[') {
// atom list:
if (token.back() != ']') {
std::ostringstream errout;
errout << "Bad atom token '" << token << "' on line: " << line;
throw FileParseException(errout.str());
}
token = token.substr(1, token.size() - 2);
std::vector<std::string> splitToken;
boost::split(splitToken, token, boost::is_any_of(","));
for (std::vector<std::string>::const_iterator stIt = splitToken.begin();
stIt != splitToken.end(); ++stIt) {
std::string_view stoken = *stIt;
std::string atSymb(FileParserUtils::strip(stoken));
if (atSymb.empty()) {
continue;
}
if (atSymb.size() == 2 && atSymb[1] >= 'A' && atSymb[1] <= 'Z') {
atSymb[1] = static_cast<char>(tolower(atSymb[1]));
}
int atNum = PeriodicTable::getTable()->getAtomicNumber(atSymb);
if (!res) {
res.reset(new QueryAtom(atNum));
} else {
res->expandQuery(makeAtomNumQuery(atNum), Queries::COMPOSITE_OR, true);
}
}
res->getQuery()->setNegation(negate);
} else {
if (negate) {
std::ostringstream errout;
errout << "NOT tokens only supported for atom lists. line " << line;
throw FileParseException(errout.str());
}
// it's a normal CTAB atom symbol:
// NOTE: "R" and "R0"-"R99" are not in the v3K CTAB spec, but we're going to
// support them anyway
bool isComplexQueryName =
std::find(complexQueries.begin(), complexQueries.end(), token) !=
complexQueries.end();
if (isComplexQueryName || token == "R" ||
(token[0] == 'R' && token >= "R0" && token <= "R99") || token == "R#" ||
token == "*") {
if (isComplexQueryName || token == "*") {
res.reset(new QueryAtom(0));
if (token == "*") {
// according to the MDL spec, these match anything
res->setQuery(makeAtomNullQuery());
} else if (isComplexQueryName) {
convertComplexNameToQuery(res.get(), token);
}
// queries have no implicit Hs:
res->setNoImplicit(true);
} else {
res.reset(new Atom(1));
res->setAtomicNum(0);
}
if (token[0] == 'R' && token >= "R0" && token <= "R99") {
auto rlabel = token.substr(1, token.length() - 1);
int rnumber;
try {
rnumber = boost::lexical_cast<int>(rlabel);
} catch (boost::bad_lexical_cast &) {
rnumber = -1;
}
if (rnumber >= 0) {
res->setIsotope(rnumber);
}
}
if (token[0] == 'R') {
// we used to skip R# here because that really should be handled by an
// RGP spec, but that turned out to not be permissive enough... <sigh>
setRGPProps(token, res.get());
}
} else if (token == "D") { // mol blocks support "D" and "T" as
// shorthand... handle that.
res.reset(new Atom(1));
res->setIsotope(2);
} else if (token == "T") { // mol blocks support "D" and "T" as
// shorthand... handle that.
res.reset(new Atom(1));
res->setIsotope(3);
} else if (token == "Pol" || token == "Mod") {
res.reset(new Atom(0));
res->setProp(common_properties::dummyLabel, std::string(token));
} else if (GenericGroups::genericMatchers.find(std::string(token)) !=
GenericGroups::genericMatchers.end()) {
res.reset(new QueryAtom(0));
res->setProp(common_properties::atomLabel, std::string(token));
} else {
std::string tcopy(token);
if (token.size() == 2 && token[1] >= 'A' && token[1] <= 'Z') {
tcopy[1] = static_cast<char>(tolower(token[1]));
}
res.reset(new Atom(0));
lookupAtomicNumber(res.get(), tcopy, strictParsing);
}
}
POSTCONDITION(res, "no atom built");
return res.release();
}
bool splitAssignToken(std::string_view token, std::string &prop,
std::string_view &val) {
auto equalsLoc = token.find("=");
if (equalsLoc == token.npos || equalsLoc != token.rfind("=")) {
return false;
}
prop = token.substr(0, equalsLoc);
boost::to_upper(prop);
val = token.substr(equalsLoc + 1);
return true;
}
template <class T>
void ParseV3000AtomProps(RWMol *mol, Atom *&atom, typename T::iterator &token,
const T &tokens, unsigned int &line,
bool strictParsing) {
PRECONDITION(mol, "bad molecule");
PRECONDITION(atom, "bad atom");
std::ostringstream errout;
while (token != tokens.end()) {
std::string prop;
std::string_view val;
if (!splitAssignToken(*token, prop, val)) {
errout << "Invalid atom property: '" << *token << "' for atom "
<< atom->getIdx() + 1 << " on line " << line << std::endl;
throw FileParseException(errout.str());
}
if (prop == "CHG") {
auto charge = FileParserUtils::toInt(val);
if (!atom->hasQuery()) {
atom->setFormalCharge(charge);
} else {
atom->expandQuery(makeAtomFormalChargeQuery(charge));
}
} else if (prop == "RAD") {
// FIX handle queries here
switch (FileParserUtils::toInt(val)) {
case 0:
break;
case 1:
atom->setNumRadicalElectrons(2);
break;
case 2:
atom->setNumRadicalElectrons(1);
break;
case 3:
atom->setNumRadicalElectrons(2);
break;
default:
errout << "Unrecognized RAD value " << val << " for atom "
<< atom->getIdx() + 1 << " on line " << line << std::endl;
throw FileParseException(errout.str());
}
} else if (prop == "MASS") {
// the documentation for V3000 CTABs says that this should contain the
// "absolute atomic weight" (whatever that means).
// Online examples seem to have integer (isotope) values and Marvin
// won't even read something that has a float. We'll go with the int
int v;
double dv;
try {
v = FileParserUtils::toInt(val);
} catch (boost::bad_lexical_cast &) {
try {
dv = FileParserUtils::toDouble(val);
v = static_cast<int>(floor(dv));
} catch (boost::bad_lexical_cast &) {
v = -1;
}
}
if (v < 0) {
errout << "Bad value for MASS :" << val << " for atom "
<< atom->getIdx() + 1 << " on line " << line << std::endl;
throw FileParseException(errout.str());
} else {
if (!atom->hasQuery()) {
atom->setIsotope(v);
} else {
atom->expandQuery(makeAtomIsotopeQuery(v));
}
}
} else if (prop == "CFG") {
auto cfg = FileParserUtils::toInt(val);
switch (cfg) {
case 0:
break;
case 1:
case 2:
case 3:
atom->setProp(common_properties::molParity, cfg);
break;
default:
errout << "Unrecognized CFG value : " << val << " for atom "
<< atom->getIdx() + 1 << " on line " << line << std::endl;
throw FileParseException(errout.str());
}
} else if (prop == "HCOUNT") {
if (val != "0") {
auto hcount = FileParserUtils::toInt(val);
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
if (hcount == -1) {
hcount = 0;
}
if (hcount > 0) {
ATOM_EQUALS_QUERY *oq = makeAtomImplicitHCountQuery(hcount);
auto nq = makeAtomSimpleQuery<ATOM_LESSEQUAL_QUERY>(
hcount, oq->getDataFunc(),
std::string("less_") + oq->getDescription());
atom->expandQuery(nq);
delete oq;
} else {
atom->expandQuery(makeAtomImplicitHCountQuery(0));
}
}
} else if (prop == "UNSAT") {
if (val == "1") {
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
atom->expandQuery(makeAtomUnsaturatedQuery());
}
} else if (prop == "RBCNT") {
if (val != "0") {
auto rbcount = FileParserUtils::toInt(val);
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
atom->setProp(common_properties::molRingBondCount, rbcount);
if (rbcount == -1) {
rbcount = 0;
} else if (rbcount == -2) {
// Ring bonds can only be counted during post processing
mol->setProp(common_properties::_NeedsQueryScan, 1);
rbcount = 0xDEADBEEF;
} else if (rbcount > 4) {
rbcount = 4;
}
atom->expandQuery(makeAtomRingBondCountQuery(rbcount));
}
} else if (prop == "VAL") {
if (val != "0") {
auto totval = FileParserUtils::toInt(val);
atom->setProp(common_properties::molTotValence, totval);
}
} else if (prop == "RGROUPS") {
ParseV3000RGroups(mol, atom, val, line);
// FIX
} else if (prop == "STBOX") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
atom->setProp(common_properties::molStereoCare, ival);
}
} else if (prop == "SUBST") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
atom->setProp(common_properties::molSubstCount, ival);
}
} else if (prop == "EXACHG") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
atom->setProp(common_properties::molRxnExactChange, ival);
}
} else if (prop == "INVRET") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
atom->setProp(common_properties::molInversionFlag, ival);
}
} else if (prop == "ATTCHPT") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
if (atom->hasProp(common_properties::molAttachPoint)) {
errout << "Multiple ATTCHPT values for atom " << atom->getIdx() + 1
<< " on line " << line;
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
errout.str(std::string());
}
} else {
atom->setProp(common_properties::molAttachPoint, ival);
}
}
} else if (prop == "ATTCHORD") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
atom->setProp(common_properties::molAttachOrder, ival);
}
} else if (prop == "CLASS") {
atom->setProp(common_properties::molAtomClass, std::string(val));
} else if (prop == "SEQID") {
if (val != "0") {
auto ival = FileParserUtils::toInt(val);
atom->setProp(common_properties::molAtomSeqId, ival);
}
}
++token;
}
}
void tokenizeV3000Line(std::string_view line,
std::vector<std::string_view> &tokens) {
tokens.clear();
bool inQuotes = false, inParens = false;
unsigned int start = 0;
unsigned int pos = 0;
while (pos < line.size()) {
if (line[pos] == ' ' || line[pos] == '\t') {
if (start == pos) {
++start;
++pos;
} else if (!inQuotes && !inParens) {
tokens.push_back(line.substr(start, pos - start));
++pos;
start = pos;
} else {
++pos;
}
} else if (line[pos] == ')' && inParens) {
tokens.push_back(line.substr(start, pos - start + 1));
inParens = false;
++pos;
start = pos;
} else if (line[pos] == '(' && !inQuotes) {
inParens = true;
++pos;
} else if (line[pos] == '"' && !inParens) {
if (pos + 1 < line.size() && line[pos + 1] == '"') {
pos += 2;
} else if (inQuotes) {
// don't push on the quotes themselves
tokens.push_back(line.substr(start + 1, pos - start - 1));
++pos;
start = pos;
inQuotes = false;
} else {
++pos;
inQuotes = true;
}
} else {
++pos;
}
}
if (start != pos) {
tokens.push_back(line.substr(start, line.size() - start));
}
#if 0
std::cerr<<"tokens: ";
std::copy(tokens.begin(),tokens.end(),std::ostream_iterator<std::string>(std::cerr,"|"));
std::cerr<<std::endl;
#endif
}
bool calculate3dFlag(const RWMol &mol, const Conformer &conf,
bool chiralityPossible) {
int marked3d = 0;
if (mol.getPropIfPresent(common_properties::_3DConf, marked3d)) {
mol.clearProp(common_properties::_3DConf);
}
bool nonzeroZ = hasNonZeroZCoords(conf);
if (!nonzeroZ && marked3d == 1) {
// If we have no Z coordinates, mark the structure 2D if we see any
// 2D stereo markers, or stay as 3D if
if (chiralityPossible) {
BOOST_LOG(rdWarningLog)
<< "Warning: molecule is tagged as 3D, but all Z coords are zero and 2D stereo "
"markers have been found, marking the mol as 2D."
<< std::endl;
return false;
}
return true;
} else if (marked3d == 0 && nonzeroZ) {
BOOST_LOG(rdWarningLog)
<< "Warning: molecule is tagged as 2D, but at least one Z coordinate is not zero. "
"Marking the mol as 3D."
<< std::endl;
return true;
}
return nonzeroZ;
}
void ParseV3000AtomBlock(std::istream *inStream, unsigned int &line,
unsigned int nAtoms, RWMol *mol, Conformer *conf,
bool strictParsing) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(nAtoms > 0, "bad atom count");
PRECONDITION(mol, "bad molecule");
PRECONDITION(conf, "bad conformer");
std::vector<std::string> splitLine;
auto inl = getV3000Line(inStream, line);
std::string_view tempStr = inl;
if (tempStr.length() < 10 || tempStr.substr(0, 10) != "BEGIN ATOM") {
std::ostringstream errout;
errout << "BEGIN ATOM line not found on line " << line;
throw FileParseException(errout.str());
}
for (unsigned int i = 0; i < nAtoms; ++i) {
inl = getV3000Line(inStream, line);
tempStr = inl;
auto trimmed = FileParserUtils::strip(tempStr);
std::vector<std::string_view> tokens;
std::vector<std::string_view>::iterator token;
tokenizeV3000Line(trimmed, tokens);
token = tokens.begin();
if (token == tokens.end()) {
std::ostringstream errout;
errout << "Bad atom line : '" << tempStr << "' on line" << line;
throw FileParseException(errout.str());
}
unsigned int molIdx = 0;
std::from_chars(token->data(), token->data() + token->size(), molIdx);
// start with the symbol:
++token;
if (token == tokens.end()) {
std::ostringstream errout;
errout << "Bad atom line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
Atom *atom = ParseV3000AtomSymbol(*token, line, strictParsing);
// now the position;
RDGeom::Point3D pos;
++token;
if (token == tokens.end()) {
delete atom;
std::ostringstream errout;
errout << "Bad atom line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
pos.x = atof(std::string(*token).c_str());
++token;
if (token == tokens.end()) {
delete atom;
std::ostringstream errout;
errout << "Bad atom line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
pos.y = atof(std::string(*token).c_str());
++token;
if (token == tokens.end()) {
delete atom;
std::ostringstream errout;
errout << "Bad atom line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
pos.z = atof(std::string(*token).c_str());
// the map number:
++token;
if (token == tokens.end()) {
delete atom;
std::ostringstream errout;
errout << "Bad atom line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
int mapNum = atoi(std::string(*token).c_str());
if (mapNum > 0) {
atom->setProp(common_properties::molAtomMapNumber, mapNum);
}
++token;
unsigned int aid = mol->addAtom(atom, false, true);
// additional properties this may change the atom,
// so be careful with it:
ParseV3000AtomProps(mol, atom, token, tokens, line, strictParsing);
mol->setAtomBookmark(atom, molIdx);
conf->setAtomPos(aid, pos);
}
inl = getV3000Line(inStream, line);
tempStr = inl;
if (tempStr.length() < 8 || tempStr.substr(0, 8) != "END ATOM") {
std::ostringstream errout;
errout << "END ATOM line not found on line " << line;
throw FileParseException(errout.str());
}
}
void ParseV3000BondBlock(std::istream *inStream, unsigned int &line,
unsigned int nBonds, RWMol *mol,
bool &chiralityPossible) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(nBonds > 0, "bad bond count");
PRECONDITION(mol, "bad molecule");
auto inl = getV3000Line(inStream, line);
std::string_view tempStr = inl;
if (tempStr.length() < 10 || tempStr.substr(0, 10) != "BEGIN BOND") {
throw FileParseException("BEGIN BOND line not found");
}
for (unsigned int i = 0; i < nBonds; ++i) {
inl = getV3000Line(inStream, line);
tempStr = inl;
tempStr = FileParserUtils::strip(tempStr);
std::vector<std::string_view> splitLine;
tokenizeV3000Line(tempStr, splitLine);
if (splitLine.size() < 4) {
std::ostringstream errout;
errout << "bond line " << line << " is too short";
throw FileParseException(errout.str());
}
Bond *bond;
unsigned int bondIdx = 0;
std::from_chars(splitLine[0].data(),
splitLine[0].data() + splitLine[0].size(), bondIdx);
unsigned int bType = 0;
std::from_chars(splitLine[1].data(),
splitLine[1].data() + splitLine[1].size(), bType);
unsigned int a1Idx = 0;
std::from_chars(splitLine[2].data(),
splitLine[2].data() + splitLine[2].size(), a1Idx);
unsigned int a2Idx = 0;
std::from_chars(splitLine[3].data(),
splitLine[3].data() + splitLine[3].size(), a2Idx);
switch (bType) {
case 1:
bond = new Bond(Bond::SINGLE);
break;
case 2:
bond = new Bond(Bond::DOUBLE);
break;
case 3:
bond = new Bond(Bond::TRIPLE);
break;
case 4:
bond = new Bond(Bond::AROMATIC);
bond->setIsAromatic(true);
break;
case 9:
bond = new Bond(Bond::DATIVE);
break;
case 10:
bond = new Bond(Bond::HYDROGEN);
break;
case 0:
bond = new Bond(Bond::UNSPECIFIED);
BOOST_LOG(rdWarningLog)
<< "bond with order 0 found on line " << line
<< ". This is not part of the MDL specification." << std::endl;
break;
default:
// it's a query bond of some type
bond = new QueryBond;
if (bType == 8) {
BOND_NULL_QUERY *q;
q = makeBondNullQuery();
bond->setQuery(q);
} else if (bType == 5) {
bond->setQuery(makeSingleOrDoubleBondQuery());
bond->setProp(common_properties::_MolFileBondQuery, 1);
} else if (bType == 6) {
bond->setQuery(makeSingleOrAromaticBondQuery());
bond->setProp(common_properties::_MolFileBondQuery, 1);
} else if (bType == 7) {
bond->setQuery(makeDoubleOrAromaticBondQuery());
bond->setProp(common_properties::_MolFileBondQuery, 1);
} else {
BOND_NULL_QUERY *q;
q = makeBondNullQuery();
bond->setQuery(q);
BOOST_LOG(rdWarningLog)
<< "unrecognized query bond type, " << bType << ", found on line "
<< line << ". Using an \"any\" query." << std::endl;
}
break;
}
bond->setProp(common_properties::_MolFileBondType, bType);
// additional bond properties:
unsigned int lPos = 4;
std::ostringstream errout;
while (lPos < splitLine.size()) {
std::string prop;
std::string_view val;
if (!splitAssignToken(splitLine[lPos], prop, val)) {
errout << "bad bond property '" << splitLine[lPos] << "' on line "
<< line;
throw FileParseException(errout.str());
}
if (prop == "CFG") {
unsigned int cfg = 0;
std::from_chars(val.data(), val.data() + val.size(), cfg);
switch (cfg) {
case 0:
break;
case 1:
bond->setBondDir(Bond::BEGINWEDGE);
chiralityPossible = true;
break;
case 2:
if (bType == 1) {
bond->setBondDir(Bond::UNKNOWN);
} else if (bType == 2) {
bond->setBondDir(Bond::EITHERDOUBLE);
bond->setStereo(Bond::STEREOANY);
}
break;
case 3:
bond->setBondDir(Bond::BEGINDASH);
chiralityPossible = true;
break;
default:
errout << "bad bond CFG " << val << "' on line " << line;
throw FileParseException(errout.str());
}
bond->setProp(common_properties::_MolFileBondCfg, cfg);
} else if (prop == "TOPO") {
if (val != "0") {
if (!bond->hasQuery()) {
auto *qBond = new QueryBond(*bond);
delete bond;
bond = qBond;
}
BOND_EQUALS_QUERY *q = makeBondIsInRingQuery();
if (val == "1") {
// nothing
} else if (val == "2") {
q->setNegation(true);
} else {
errout << "bad bond TOPO " << val << "' on line " << line;
throw FileParseException(errout.str());
}
bond->expandQuery(q);
}
} else if (prop == "RXCTR") {
int reactStatus = FileParserUtils::toInt(val);
bond->setProp(common_properties::molReactStatus, reactStatus);
} else if (prop == "STBOX") {
bond->setProp(common_properties::molStereoCare, std::string(val));
} else if (prop == "ENDPTS") {
bond->setProp(common_properties::_MolFileBondEndPts, std::string(val));
} else if (prop == "ATTACH") {
bond->setProp(common_properties::_MolFileBondAttach, std::string(val));
}
++lPos;
}
bond->setBeginAtomIdx(mol->getAtomWithBookmark(a1Idx)->getIdx());
bond->setEndAtomIdx(mol->getAtomWithBookmark(a2Idx)->getIdx());
mol->addBond(bond, true);
mol->setBondBookmark(bond, bondIdx);
// set the stereoCare property on the bond if it's not set already and
// both the beginning and end atoms have it set:
int care1 = 0;
int care2 = 0;
if (!bond->hasProp(common_properties::molStereoCare) &&
mol->getAtomWithIdx(bond->getBeginAtomIdx())
->getPropIfPresent(common_properties::molStereoCare, care1) &&
mol->getAtomWithIdx(bond->getEndAtomIdx())
->getPropIfPresent(common_properties::molStereoCare, care2)) {
if (care1 == care2) {
bond->setProp(common_properties::molStereoCare, care1);
}
}
}
inl = getV3000Line(inStream, line);
tempStr = inl;
if (tempStr.length() < 8 || tempStr.substr(0, 8) != "END BOND") {
std::ostringstream errout;
errout << "END BOND line not found at line " << line;
throw FileParseException(errout.str());
}
}
// The documentation about MRV_COORDINATE_BOND_TYPE in
// https://docs.chemaxon.com/display/docs/chemaxon-specific-information-in-mdl-mol-files.md
// seems to be wrong: it says the only data field in this group contains the
// index for the coordinate atom. But behavior in Marvin Sketch seems to
// indicate that it references the bond index instead (see
// https://github.com/rdkit/rdkit/issues/4473)
void processMrvCoordinateBond(RWMol &mol, const SubstanceGroup &sg) {
std::vector<std::string> dataFields;
if (sg.getPropIfPresent("DATAFIELDS", dataFields)) {
if (dataFields.empty()) {
BOOST_LOG(rdWarningLog)
<< "ignoring MRV_COORDINATE_BOND_TYPE SGroup without data fields."
<< std::endl;
return;
}
auto coordinate_bond_idx =
FileParserUtils::toUnsigned(dataFields[0], true) - 1;
if (dataFields.size() > 1) {
BOOST_LOG(rdWarningLog) << "ignoring extra data fields in "
"MRV_COORDINATE_BOND_TYPE SGroup for bond "
<< coordinate_bond_idx << '.' << std::endl;
}
Bond *old_bond = nullptr;
try {
old_bond = mol.getBondWithIdx(coordinate_bond_idx);
} catch (const Invar::Invariant &) {
BOOST_LOG(rdWarningLog)
<< "molecule does not contain a bond matching the "
"MRV_COORDINATE_BOND_TYPE SGroup for bond "
<< coordinate_bond_idx << ", ignoring." << std::endl;
return;
}
if (!old_bond || old_bond->getBondType() != Bond::BondType::UNSPECIFIED) {
BOOST_LOG(rdWarningLog)
<< "MRV_COORDINATE_BOND_TYPE SGroup with value "
<< coordinate_bond_idx
<< " does not reference a query bond, ignoring." << std::endl;
return;
}
Bond new_bond(Bond::BondType::DATIVE);
auto preserveProps = true;
auto keepSGroups = true;
mol.replaceBond(coordinate_bond_idx, &new_bond, preserveProps, keepSGroups);
}
}
void processSMARTSQ(RWMol &mol, const SubstanceGroup &sg) {
std::string field;
if (sg.getPropIfPresent("QUERYOP", field) && field != "=") {
BOOST_LOG(rdWarningLog) << "unrecognized QUERYOP '" << field
<< "' for SMARTSQ. Query ignored." << std::endl;
return;
}
std::vector<std::string> dataFields;
if (!sg.getPropIfPresent("DATAFIELDS", dataFields) || dataFields.empty()) {
BOOST_LOG(rdWarningLog)
<< "empty FIELDDATA for SMARTSQ. Query ignored." << std::endl;
return;
}
if (dataFields.size() > 1) {
BOOST_LOG(rdWarningLog)
<< "multiple FIELDDATA values for SMARTSQ. Taking the first."
<< std::endl;
}
const std::string &sma = dataFields[0];
if (sma.empty()) {
BOOST_LOG(rdWarningLog)
<< "Skipping empty SMARTS value for SMARTSQ." << std::endl;
return;
}
for (auto aidx : sg.getAtoms()) {
auto at = mol.getAtomWithIdx(aidx);
std::unique_ptr<RWMol> m;
try {
m.reset(SmartsToMol(sma));
} catch (...) {
// Is this ever used?
}
if (!m || !m->getNumAtoms()) {
BOOST_LOG(rdWarningLog)
<< "SMARTS for SMARTSQ '" << sma
<< "' could not be parsed or has no atoms. Ignoring it." << std::endl;
return;
}
if (!at->hasQuery()) {
QueryAtom qAt(*at);
int oidx = at->getIdx();
mol.replaceAtom(oidx, &qAt);
at = mol.getAtomWithIdx(oidx);
}
QueryAtom::QUERYATOM_QUERY *query = nullptr;
if (m->getNumAtoms() == 1) {
query = m->getAtomWithIdx(0)->getQuery()->copy();
} else {
query = new RecursiveStructureQuery(m.release());
}
at->setQuery(query);
at->setProp(common_properties::MRV_SMA, sma);
at->setProp(common_properties::_MolFileAtomQuery, 1);
}
}
void processMrvImplicitH(RWMol &mol, const SubstanceGroup &sg) {
std::vector<std::string> dataFields;
if (sg.getPropIfPresent("DATAFIELDS", dataFields)) {
for (const auto &df : dataFields) {
if (df.substr(0, 6) == "IMPL_H") {
auto val = FileParserUtils::toInt(df.substr(6));
for (auto atIdx : sg.getAtoms()) {
if (atIdx < mol.getNumAtoms()) {
// if the atom has aromatic bonds to it, then set the explicit
// value, otherwise skip it.
auto atom = mol.getAtomWithIdx(atIdx);
bool hasAromaticBonds = false;
for (auto bndI :
boost::make_iterator_range(mol.getAtomBonds(atom))) {
auto bnd = (mol)[bndI];
if (bnd->getIsAromatic() ||
bnd->getBondType() == Bond::AROMATIC) {
hasAromaticBonds = true;
break;
}
}
if (hasAromaticBonds) {
atom->setNumExplicitHs(val);
} else {
BOOST_LOG(rdWarningLog)
<< "MRV_IMPLICIT_H SGroup on atom without aromatic "
"bonds, "
<< atIdx << ", ignored." << std::endl;
}
} else {
BOOST_LOG(rdWarningLog)
<< "bad atom index, " << atIdx
<< ", found in MRV_IMPLICIT_H SGroup. Ignoring it."
<< std::endl;
}
}
}
}
}
}
void processZBO(RWMol &mol, const SubstanceGroup &sg) {
for (auto bidx : sg.getBonds()) {
auto bond = mol.getBondWithIdx(bidx);
bond->setBondType(Bond::BondType::ZERO);
}
}
void processZCH(RWMol &mol, const SubstanceGroup &sg) {
RDUNUSED_PARAM(mol);
std::vector<std::string> dataFields;
if (sg.getPropIfPresent("DATAFIELDS", dataFields)) {
if (dataFields.empty()) {
BOOST_LOG(rdWarningLog)
<< "ignoring ZCHG SGroup without data fields." << std::endl;
return;
}
for (const auto &df : dataFields) {
std::string trimmed = boost::trim_copy(df);
std::vector<std::string> splitLine;
boost::split(splitLine, trimmed, boost::is_any_of(";"),
boost::token_compress_off);
const auto &aids = sg.getAtoms();
if (splitLine.size() < aids.size()) {
BOOST_LOG(rdWarningLog)
<< "DATAFIELDS in ZCH SGroup is shorter than the number of atoms in the SGroup. Ignoring it."
<< std::endl;
continue;
}
for (auto i = 0u; i < aids.size(); ++i) {
auto aid = aids[i];
auto atom = mol.getAtomWithIdx(aid);
auto val = 0;
if (!splitLine[i].empty()) {
val = FileParserUtils::toInt(splitLine[i]);
}
atom->setFormalCharge(val);
}
}
}
}
void processHYD(RWMol &mol, const SubstanceGroup &sg) {
std::vector<std::string> dataFields;
if (sg.getPropIfPresent("DATAFIELDS", dataFields)) {
if (dataFields.empty()) {
BOOST_LOG(rdWarningLog)
<< "ignoring HYD SGroup without data fields." << std::endl;
return;
}
for (const auto &df : dataFields) {
std::string trimmed = boost::trim_copy(df);
std::vector<std::string> splitLine;
boost::split(splitLine, trimmed, boost::is_any_of(";"),
boost::token_compress_off);
const auto &aids = sg.getAtoms();
if (splitLine.size() < aids.size()) {
BOOST_LOG(rdWarningLog)
<< "DATAFIELDS in HYD SGroup is shorter than the number of atoms in the SGroup. Ignoring it."
<< std::endl;
continue;
}
for (auto i = 0u; i < aids.size(); ++i) {
auto aid = aids[i];
auto atom = mol.getAtomWithIdx(aid);
auto val = 0;
if (!splitLine[i].empty()) {
val = FileParserUtils::toInt(splitLine[i]);
}
atom->setProp("_ZBO_H", true);
atom->setNumExplicitHs(val);
}
}
}
}
// process (and remove) SGroups which modify the structure
// and which we can unambiguously apply
void processSGroups(RWMol *mol) {
std::vector<unsigned int> sgsToRemove;
unsigned int sgIdx = 0;
for (auto &sg : getSubstanceGroups(*mol)) {
if (sg.getProp<std::string>("TYPE") == "DAT") {
std::string field;
if (sg.getPropIfPresent("FIELDNAME", field)) {
if (field == "MRV_COORDINATE_BOND_TYPE") {
// V2000 support for coordinate bonds
processMrvCoordinateBond(*mol, sg);
sgsToRemove.push_back(sgIdx);
continue;
} else if (field == "MRV_IMPLICIT_H") {
// CXN extension to specify implicit Hs, used for aromatic rings
processMrvImplicitH(*mol, sg);
sgsToRemove.push_back(sgIdx);
continue;
} else if (field == "ZBO") {
// RDKit extension for zero-order bonds
processZBO(*mol, sg);
sgsToRemove.push_back(sgIdx);
continue;
} else if (field == "ZCH") {
// RDKit extension for charge on atoms involved in zero-order bonds
processZCH(*mol, sg);
sgsToRemove.push_back(sgIdx);
continue;
} else if (field == "HYD") {
// RDKit extension for hydrogen-count on atoms involved in
// zero-order bonds
processHYD(*mol, sg);
sgsToRemove.push_back(sgIdx);
continue;
}
}
if (sg.getPropIfPresent("QUERYTYPE", field) &&
(field == "SMARTSQ" || field == "SQ")) {
processSMARTSQ(*mol, sg);
sgsToRemove.push_back(sgIdx);
continue;
}
}
++sgIdx;
}
// now remove the S groups we processed, we saved indices so do this in
// backwards
auto &sgs = getSubstanceGroups(*mol);
for (auto it = sgsToRemove.rbegin(); it != sgsToRemove.rend(); ++it) {
sgs.erase(sgs.begin() + *it);
}
}
void ProcessMolProps(RWMol *mol) {
PRECONDITION(mol, "no molecule");
// we have to loop the ugly way because we may need to actually replace an
// atom
for (unsigned int aidx = 0; aidx < mol->getNumAtoms(); ++aidx) {
auto atom = mol->getAtomWithIdx(aidx);
int ival = 0;
if (atom->getPropIfPresent(common_properties::molSubstCount, ival) &&
ival != 0) {
if (!atom->hasQuery()) {
atom = QueryOps::replaceAtomWithQueryAtom(mol, atom);
}
bool gtQuery = false;
if (ival == -1) {
ival = 0;
} else if (ival == -2) {
// as drawn
ival = atom->getDegree();
} else if (ival >= 6) {
// 6 or more
gtQuery = true;
}
if (!gtQuery) {
atom->expandQuery(makeAtomExplicitDegreeQuery(ival));
} else {
// create a temp query the normal way so that we can be sure to get
// the description right
std::unique_ptr<ATOM_EQUALS_QUERY> tmp{
makeAtomExplicitDegreeQuery(ival)};
atom->expandQuery(makeAtomSimpleQuery<ATOM_LESSEQUAL_QUERY>(
ival, tmp->getDataFunc(),
std::string("less_") + tmp->getDescription()));
}
}
if (atom->getPropIfPresent(common_properties::molTotValence, ival) &&
ival != 0 && !atom->hasProp("_ZBO_H")) {
atom->setNoImplicit(true);
if (ival == 15 // V2000
|| ival == -1 // v3000
) {
atom->setNumExplicitHs(0);
} else {
if (static_cast<int>(atom->getValence(Atom::ValenceType::EXPLICIT)) >
ival) {
BOOST_LOG(rdWarningLog)
<< "atom " << atom->getIdx() << " has specified valence (" << ival
<< ") smaller than the drawn valence "
<< atom->getValence(Atom::ValenceType::EXPLICIT) << "."
<< std::endl;
atom->setNumExplicitHs(0);
} else {
atom->setNumExplicitHs(ival -
atom->getValence(Atom::ValenceType::EXPLICIT));
}
}
}
atom->clearProp(common_properties::molTotValence);
}
processSGroups(mol);
}
} // namespace
namespace FileParserUtils {
bool ParseV3000CTAB(std::istream *inStream, unsigned int &line, RWMol *mol,
Conformer *&conf, bool &chiralityPossible,
unsigned int &nAtoms, unsigned int &nBonds,
bool strictParsing, bool expectMEND) {
PRECONDITION(inStream, "bad stream");
PRECONDITION(mol, "bad molecule");
std::string tempStr;
std::vector<std::string> splitLine;
bool fileComplete = false;
tempStr = getV3000Line(inStream, line);
boost::to_upper(tempStr);
if (tempStr.length() < 10 || tempStr.substr(0, 10) != "BEGIN CTAB") {
std::ostringstream errout;
errout << "BEGIN CTAB line not found on line " << line;
throw FileParseException(errout.str());
}
tempStr = getV3000Line(inStream, line);
boost::to_upper(tempStr);
if (tempStr.size() < 8 || tempStr.substr(0, 7) != "COUNTS ") {
std::ostringstream errout;
errout << "Bad counts line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
std::string trimmed =
boost::trim_copy(tempStr.substr(7, tempStr.length() - 7));
boost::split(splitLine, trimmed, boost::is_any_of(" \t"),
boost::token_compress_on);
if (splitLine.size() < 2) {
std::ostringstream errout;
errout << "Bad counts line : '" << tempStr << "' on line " << line;
throw FileParseException(errout.str());
}
nAtoms = FileParserUtils::toUnsigned(splitLine[0]);
nBonds = FileParserUtils::toUnsigned(splitLine[1]);
conf = new Conformer(nAtoms);
unsigned int nSgroups = 0, n3DConstraints = 0, chiralFlag = 0;
if (splitLine.size() > 2) {
nSgroups = FileParserUtils::toUnsigned(splitLine[2]);
}
if (splitLine.size() > 3) {
n3DConstraints = FileParserUtils::toUnsigned(splitLine[3]);
}
if (splitLine.size() > 4) {
chiralFlag = FileParserUtils::toUnsigned(splitLine[4]);
}
mol->setProp(common_properties::_MolFileChiralFlag, chiralFlag);
if (nAtoms) {
ParseV3000AtomBlock(inStream, line, nAtoms, mol, conf, strictParsing);
}
if (nBonds) {
ParseV3000BondBlock(inStream, line, nBonds, mol, chiralityPossible);
}
tempStr = getV3000Line(inStream, line);
// do link nodes:
boost::to_upper(tempStr);
while (tempStr.length() > 8 && tempStr.substr(0, 8) == "LINKNODE") {
boost::to_upper(tempStr);
// if the line has nothing on it we just ignore it
if (tempStr.size() > 9) {
std::string existing = "";
if (mol->getPropIfPresent(common_properties::molFileLinkNodes,
existing)) {
existing += "|";
}
existing += tempStr.substr(9); // skip the "LINKNODE "
mol->setProp(common_properties::molFileLinkNodes, existing);
}
tempStr = getV3000Line(inStream, line);
}
if (nSgroups) {
boost::to_upper(tempStr);
if (tempStr.length() < 12 || tempStr.substr(0, 12) != "BEGIN SGROUP") {
std::ostringstream errout;
errout << "BEGIN SGROUP line not found on line " << line;
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
} else {
tempStr =
ParseV3000SGroupsBlock(inStream, line, nSgroups, mol, strictParsing);
boost::to_upper(tempStr);
if (tempStr.length() < 10 || tempStr.substr(0, 10) != "END SGROUP") {
std::ostringstream errout;
errout << "END SGROUP line not found on line " << line;
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
} else {
tempStr = getV3000Line(inStream, line);
}
}
}
while (tempStr.length() > 5 && tempStr.substr(0, 5) == "BEGIN") {
if (tempStr.length() > 15 && tempStr.substr(6, 10) == "COLLECTION") {
tempStr = parseEnhancedStereo(inStream, line, mol);
} else {
// skip blocks we don't know how to read
BOOST_LOG(rdWarningLog) << "skipping block at line " << line << ": '"
<< tempStr << "'" << std::endl;
while (tempStr.length() < 3 || tempStr.substr(0, 3) != "END") {
tempStr = getV3000Line(inStream, line);
}
tempStr = getV3000Line(inStream, line);
}
}
if (n3DConstraints) {
BOOST_LOG(rdWarningLog)
<< "3D constraint information in mol block ignored at line " << line
<< std::endl;
boost::to_upper(tempStr);
if (tempStr.length() < 11 || tempStr.substr(0, 11) != "BEGIN OBJ3D") {
std::ostringstream errout;
errout << "BEGIN OBJ3D line not found on line " << line;
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
}
for (unsigned int i = 0; i < n3DConstraints; ++i) {
tempStr = getV3000Line(inStream, line);
}
tempStr = getV3000Line(inStream, line);
boost::to_upper(tempStr);
if (tempStr.length() < 9 || tempStr.substr(0, 9) != "END OBJ3D") {
std::ostringstream errout;
errout << "END OBJ3D line not found on line " << line;
if (strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
} else {
tempStr = getV3000Line(inStream, line);
}
}
boost::to_upper(tempStr);
if (tempStr.length() < 8 || tempStr.substr(0, 8) != "END CTAB") {
if (strictParsing) {
throw FileParseException("END CTAB line not found");
} else {
BOOST_LOG(rdWarningLog) << "END CTAB line not found." << std::endl;
}
}
if (expectMEND) {
tempStr = getLine(inStream);
++line;
if (tempStr[0] == 'M' && tempStr.substr(0, 6) == "M END") {
fileComplete = true;
}
} else {
fileComplete = true;
}
auto is3d = calculate3dFlag(*mol, *conf, chiralityPossible);
conf->set3D(is3d);
mol->addConformer(conf, true);
conf = nullptr;
return fileComplete;
}
bool ParseV2000CTAB(std::istream *inStream, unsigned int &line, RWMol *mol,
Conformer *&conf, bool &chiralityPossible,
unsigned int &nAtoms, unsigned int &nBonds,
bool strictParsing) {
conf = new Conformer(nAtoms);
if (nAtoms == 0) {
conf->set3D(false);
} else {
ParseMolBlockAtoms(inStream, line, nAtoms, mol, conf, strictParsing);
}
ParseMolBlockBonds(inStream, line, nBonds, mol, chiralityPossible);
auto is3d = calculate3dFlag(*mol, *conf, chiralityPossible);
conf->set3D(is3d);
mol->addConformer(conf, true);
conf = nullptr;
bool fileComplete =
ParseMolBlockProperties(inStream, line, mol, strictParsing);
return fileComplete;
}
void finishMolProcessing(
RWMol *res, bool chiralityPossible,
const RDKit::v2::FileParsers::MolFileParserParams ¶ms) {
if (!res) {
return;
}
res->clearAllAtomBookmarks();
res->clearAllBondBookmarks();
if (params.expandAttachmentPoints) {
MolOps::expandAttachmentPoints(*res);
}
// calculate explicit valence on each atom:
for (auto atom : res->atoms()) {
atom->calcExplicitValence(false);
}
// postprocess mol file flags
ProcessMolProps(res);
// update the chirality and stereo-chemistry
//
// NOTE: we detect the stereochemistry before sanitizing/removing
// hydrogens because the removal of H atoms may actually remove
// the wedged bond from the molecule. This wipes out the only
// sign that chirality ever existed and makes us sad... so first
// perceive chirality, then remove the Hs and sanitize.
//
const Conformer &conf = res->getConformer();
if (chiralityPossible || conf.is3D()) {
if (!conf.is3D()) {
bool replaceExistingTags = true;
MolOps::assignChiralTypesFromBondDirs(*res, conf.getId(),
replaceExistingTags);
} else {
res->updatePropertyCache(false);
MolOps::assignChiralTypesFrom3D(*res, conf.getId(), true);
}
}
Atropisomers::detectAtropisomerChirality(*res, &conf);
// now that atom stereochem has been perceived, the wedging
// information is no longer needed, so we clear
// single bond dir flags:
MolOps::clearSingleBondDirFlags(*res);
if (params.sanitize) {
if (params.removeHs) {
// Bond stereo detection must happen before H removal, or
// else we might be removing stereogenic H atoms in double
// bonds (e.g. imines). But before we run stereo detection,
// we need to run mol cleanup so don't have trouble with
// e.g. nitro groups. Sadly, this a;; means we will find
// run both cleanup and ring finding twice (a fast find
// rings in bond stereo detection, and another in
// sanitization's SSSR symmetrization).
unsigned int failedOp = 0;
MolOps::sanitizeMol(*res, failedOp, MolOps::SANITIZE_CLEANUP);
MolOps::detectBondStereochemistry(*res);
MolOps::removeHs(*res);
} else {
MolOps::sanitizeMol(*res);
MolOps::detectBondStereochemistry(*res);
}
MolOps::assignStereochemistry(*res, true, true, true);
} else {
MolOps::detectBondStereochemistry(*res);
}
if (res->hasProp(common_properties::_NeedsQueryScan)) {
res->clearProp(common_properties::_NeedsQueryScan);
QueryOps::completeMolQueries(res);
}
}
} // namespace FileParserUtils
namespace v2 {
namespace FileParsers {
//------------------------------------------------
//
// Read a molecule from a stream
//
//------------------------------------------------
std::unique_ptr<RWMol> MolFromMolDataStream(std::istream &inStream,
unsigned int &line,
const MolFileParserParams ¶ms) {
std::string tempStr;
bool fileComplete = false;
bool chiralityPossible = false;
Utils::LocaleSwitcher ls;
// mol name
line++;
tempStr = getLine(inStream);
if (inStream.eof()) {
return nullptr;
}
auto res = std::make_unique<RWMol>();
res->setProp(common_properties::_Name, tempStr);
// info
line++;
tempStr = getLine(inStream);
res->setProp("_MolFileInfo", tempStr);
if (tempStr.length() >= 22) {
std::string dimLabel = tempStr.substr(20, 2);
// Unless labelled as 3D we assume 2D
if (dimLabel == "3d" || dimLabel == "3D") {
res->setProp(common_properties::_3DConf, 1);
}
}
// comments
line++;
tempStr = getLine(inStream);
res->setProp("_MolFileComments", tempStr);
unsigned int nAtoms = 0, nBonds = 0, nLists = 0, chiralFlag = 0, nsText = 0,
nRxnComponents = 0;
int nReactants = 0, nProducts = 0, nIntermediates = 0;
(void)nLists; // read from the file but unused
(void)nsText;
(void)nRxnComponents;
(void)nReactants;
(void)nProducts;
(void)nIntermediates;
// counts line, this is where we really get started
line++;
tempStr = getLine(inStream);
if (tempStr.size() < 6) {
if (res) {
res = nullptr;
}
std::ostringstream errout;
errout << "Counts line too short: '" << tempStr << "' on line" << line;
throw FileParseException(errout.str());
}
unsigned int spos = 0;
// this needs to go into a try block because if the lexical_cast throws an
// exception we want to catch throw a different exception
try {
nAtoms = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
spos = 3;
nBonds = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
spos = 6;
} catch (boost::bad_lexical_cast &) {
std::ostringstream errout;
errout << "Cannot convert '" << tempStr.substr(spos, 3)
<< "' to unsigned int on line " << line;
throw FileParseException(errout.str());
}
try {
spos = 6;
if (tempStr.size() >= 9) {
nLists = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
spos = 12;
if (tempStr.size() >= spos + 3) {
chiralFlag = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
spos = 15;
if (tempStr.size() >= spos + 3) {
nsText = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
spos = 18;
if (tempStr.size() >= spos + 3) {
nRxnComponents =
FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
spos = 21;
if (tempStr.size() >= spos + 3) {
nReactants = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
spos = 24;
if (tempStr.size() >= spos + 3) {
nProducts = FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
spos = 27;
if (tempStr.size() >= spos + 3) {
nIntermediates =
FileParserUtils::toUnsigned(tempStr.substr(spos, 3), true);
}
} catch (boost::bad_lexical_cast &) {
// some SD files (such as some from NCI) lack all the extra information
// on the header line, so ignore problems parsing there.
}
unsigned int ctabVersion = 2000;
if (tempStr.size() > 35) {
if (tempStr.size() < 39 || tempStr[34] != 'V') {
std::ostringstream errout;
errout << "CTAB version string invalid at line " << line;
if (params.strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
} else if (tempStr.substr(34, 5) == "V3000") {
ctabVersion = 3000;
} else if (tempStr.substr(34, 5) != "V2000") {
std::ostringstream errout;
errout << "Unsupported CTAB version: '" << tempStr.substr(34, 5)
<< "' at line " << line;
if (params.strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
}
}
res->setProp(common_properties::_MolFileChiralFlag, chiralFlag);
Conformer *conf = nullptr;
try {
if (ctabVersion == 2000) {
fileComplete = FileParserUtils::ParseV2000CTAB(
&inStream, line, res.get(), conf, chiralityPossible, nAtoms, nBonds,
params.strictParsing);
} else {
if (nAtoms != 0 || nBonds != 0) {
std::ostringstream errout;
errout << "V3000 mol blocks should have 0s in the initial counts line. "
"(line: "
<< line << ")";
if (params.strictParsing) {
throw FileParseException(errout.str());
} else {
BOOST_LOG(rdWarningLog) << errout.str() << std::endl;
}
}
fileComplete = FileParserUtils::ParseV3000CTAB(
&inStream, line, res.get(), conf, chiralityPossible, nAtoms, nBonds,
params.strictParsing);
}
} catch (MolFileUnhandledFeatureException &e) {
// unhandled mol file feature, show an error
res.reset();
delete conf;
conf = nullptr;
BOOST_LOG(rdErrorLog) << " Unhandled CTAB feature: '" << e.what()
<< "'. Molecule skipped." << std::endl;
if (!inStream.eof()) {
tempStr = getLine(inStream);
}
++line;
while (!inStream.eof() && !inStream.fail() &&
tempStr.substr(0, 6) != "M END" && tempStr.substr(0, 4) != "$$$$") {
tempStr = getLine(inStream);
++line;
}
fileComplete = !inStream.eof() || tempStr.substr(0, 6) == "M END" ||
tempStr.substr(0, 4) == "$$$$";
} catch (FileParseException &e) {
// catch our exceptions and throw them back after cleanup
delete conf;
conf = nullptr;
throw e;
}
if (!fileComplete) {
delete conf;
conf = nullptr;
std::ostringstream errout;
errout
<< "Problems encountered parsing Mol data, M END missing around line "
<< line;
throw FileParseException(errout.str());
}
if (res) {
FileParserUtils::finishMolProcessing(res.get(), chiralityPossible, params);
}
return res;
}
//------------------------------------------------
//
// Read a molecule from a string
//
//------------------------------------------------
std::unique_ptr<RWMol> MolFromMolBlock(const std::string &molBlock,
const MolFileParserParams ¶ms) {
std::istringstream inStream(molBlock);
unsigned int line = 0;
return MolFromMolDataStream(inStream, line, params);
}
//------------------------------------------------
//
// Read a molecule from a file
//
//------------------------------------------------
std::unique_ptr<RWMol> MolFromMolFile(const std::string &fName,
const MolFileParserParams ¶ms) {
std::ifstream inStream(fName.c_str());
if (!inStream || (inStream.bad())) {
std::ostringstream errout;
errout << "Bad input file " << fName;
throw BadFileException(errout.str());
}
if (!inStream.eof()) {
unsigned int line = 0;
return MolFromMolDataStream(inStream, line, params);
} else {
return std::unique_ptr<RWMol>();
}
}
} // namespace FileParsers
} // namespace v2
} // namespace RDKit
|