aboutsummaryrefslogtreecommitdiffstats
path: root/include/gtest
diff options
context:
space:
mode:
Diffstat (limited to 'include/gtest')
-rw-r--r--include/gtest/internal/gtest-port.h67
1 files changed, 53 insertions, 14 deletions
diff --git a/include/gtest/internal/gtest-port.h b/include/gtest/internal/gtest-port.h
index 817ac8c5..e5a45518 100644
--- a/include/gtest/internal/gtest-port.h
+++ b/include/gtest/internal/gtest-port.h
@@ -72,6 +72,8 @@
// Test's own tr1 tuple implementation should be
// used. Unused when the user sets
// GTEST_HAS_TR1_TUPLE to 0.
+// GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test
+// is building in C++11/C++98 mode.
// GTEST_LINKED_AS_SHARED_LIBRARY
// - Define to 1 when compiling tests that use
// Google Test as a shared library (known as
@@ -259,6 +261,19 @@
# define GTEST_OS_QNX 1
#endif // __CYGWIN__
+#ifndef GTEST_LANG_CXX11
+// gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when
+// -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a
+// value for __cplusplus, and recent versions of clang, gcc, and
+// probably other compilers set that too in C++11 mode.
+# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L
+// Compiling in at least C++11 mode.
+# define GTEST_LANG_CXX11 1
+# else
+# define GTEST_LANG_CXX11 0
+# endif
+#endif
+
// Brings in definitions for functions used in the testing::internal::posix
// namespace (read, write, close, chdir, isatty, stat). We do not currently
// use them on Windows Mobile.
@@ -267,12 +282,7 @@
// is not the case, we need to include headers that provide the functions
// mentioned above.
# include <unistd.h>
-# if !GTEST_OS_NACL
-// TODO(vladl@google.com): Remove this condition when Native Client SDK adds
-// strings.h (tracked in
-// http://code.google.com/p/nativeclient/issues/detail?id=1175).
-# include <strings.h> // Native Client doesn't provide strings.h.
-# endif
+# include <strings.h>
#elif !GTEST_OS_WINDOWS_MOBILE
# include <direct.h>
# include <io.h>
@@ -466,15 +476,28 @@
// The user didn't tell us, so we need to figure it out.
// We use our own TR1 tuple if we aren't sure the user has an
-// implementation of it already. At this time, GCC 4.0.0+ and MSVC
-// 2010 are the only mainstream compilers that come with a TR1 tuple
-// implementation. NVIDIA's CUDA NVCC compiler pretends to be GCC by
-// defining __GNUC__ and friends, but cannot compile GCC's tuple
-// implementation. MSVC 2008 (9.0) provides TR1 tuple in a 323 MB
-// Feature Pack download, which we cannot assume the user has.
-// QNX's QCC compiler is a modified GCC but it doesn't support TR1 tuple.
+// implementation of it already. At this time, libstdc++ 4.0.0+ and
+// MSVC 2010 are the only mainstream standard libraries that come
+// with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler
+// pretends to be GCC by defining __GNUC__ and friends, but cannot
+// compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1
+// tuple in a 323 MB Feature Pack download, which we cannot assume the
+// user has. QNX's QCC compiler is a modified GCC but it doesn't
+// support TR1 tuple. libc++ only provides std::tuple, in C++11 mode,
+// and it can be used with some compilers that define __GNUC__.
# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \
- && !GTEST_OS_QNX) || _MSC_VER >= 1600
+ && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600
+# define GTEST_ENV_HAS_TR1_TUPLE_ 1
+# endif
+
+// C++11 specifies that <tuple> provides std::tuple. Users can't use
+// gtest in C++11 mode until their standard library is at least that
+// compliant.
+# if GTEST_LANG_CXX11
+# define GTEST_ENV_HAS_STD_TUPLE_ 1
+# endif
+
+# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_
# define GTEST_USE_OWN_TR1_TUPLE 0
# else
# define GTEST_USE_OWN_TR1_TUPLE 1
@@ -489,6 +512,22 @@
# if GTEST_USE_OWN_TR1_TUPLE
# include "gtest/internal/gtest-tuple.h"
+# elif GTEST_ENV_HAS_STD_TUPLE_
+# include <tuple>
+// C++11 puts its tuple into the ::std namespace rather than
+// ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there.
+// This causes undefined behavior, but supported compilers react in
+// the way we intend.
+namespace std {
+namespace tr1 {
+using ::std::get;
+using ::std::make_tuple;
+using ::std::tuple;
+using ::std::tuple_element;
+using ::std::tuple_size;
+}
+}
+
# elif GTEST_OS_SYMBIAN
// On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294
from pyabc import *
import pyabc_split
import redirect
import sys
import os
import time
import math
import main
import filecmp


global G_C,G_T,latches_before_abs,latches_before_pba,n_pos_before,x_factor,methods,last_winner
global last_cex,JV,JP, cex_list,max_bmc, last_cx, pord_on, trim_allowed, temp_dec, abs_ratio, ifbip
global if_no_bip

"""
The functions that are currently available from module _abc are:

int n_ands();
int n_pis();
int n_pos();
int n_latches();
int n_bmc_frames();
int prob_status(); 1 = unsat, 0 = sat, -1 = unsolved
int cex_get()
int cex_put()
int run_command(char* cmd);
int n_nodes();
int n_levels();

bool has_comb_model();
bool has_seq_model();
bool is_true_cex();
bool is_valid_cex();
  return 1 if the number of PIs in the current network and in the current counter-example are equal
int  n_cex_pis();
  return the number of PIs in the current counter-example
int  n_cex_regs();
  return the number of flops in the current counter-example
int  cex_po();
  returns the zero-based output PO number that is SAT by cex
int  cex_frame();
  return the zero-based frame number where the outputs is SAT
The last four APIs return -1, if the counter-example is not defined. 
""" 
#global variables
#________________________________________________
stackno_gabs = stackno_gore = stackno_greg= 0
STATUS_UNKNOWN = -1
STATUS_SAT = 0
STATUS_UNSAT = 1
RESULT = ('SAT' , 'SAT', 'UNSAT', 'UNDECIDED', 'UNDECIDED,', 'ERROR'  )
Sat = Sat_reg = 0
Sat_true = 1
Unsat = 2
Undecided = Undecided_reduction = 3
Undecided_no_reduction = 4
Error = 5
Restart = 6
xfi = x_factor = 1  #set this to higher for larger problems or if you want to try harder during abstraction
max_bmc = -1
last_time = 0
j_last = 0
seed = 113
init_simp = 1
temp_dec = True
ifpord1 = 1
K_backup = init_time = 0
last_verify_time = 20
last_cex = last_winner = 'None'
last_cx = 0
trim_allowed = True
pord_on = False
sec_sw = False
sec_options = ''
cex_list = []
TERM = 'USL'
ifbip = 0 # sets the abtraction method
if_no_bip = 0 #True sets it up so it can use bip and reachx commands.
abs_ratio = .5 #this controls when abstract stops
t_init = 2 #initial time for poor man's concurrency.
methods = ['PDR', 'INTRP', 'BMC',
           'SIM', 'REACHX',
           'PRE_SIMP', 'Simple_prove', 'PDRM', 'REACHM', 'BMC3','Min_Retime',
           'For_Retime','REACHP','REACHN','PDR_sd','prove_part_2',
           'prove_part_3','verify','sleep','PDRM_sd','prove_part_1',
           'run_parallel','INTRPb', 'INTRPm', 'REACHY', 'REACHYc','RareSim','simplify', 'speculate',
           'quick_sec', 'BMC_J', 'BMC2', 'extract -a', 'extract', 'PDRa']
#'0.PDR', '1.INTERPOLATION', '2.BMC', '3.SIMULATION',
#'4.REACHX', '5.PRE_SIMP', '6.SUPER_PROVE(2)', '7.PDRM', '8.REACHM', 9.BMC3'
# 10. Min_ret, 11. For_ret, 12. REACHP, 13. REACHN 14. PDRseed 15.prove_part_2,
#16.prove_part_3, 17.verify, 18.sleep, 19.PDRMm, 20.prove_part_1,
#21.run_parallel, 22.INTRP_bwd, 23. Interp_m 24. REACHY 25. REACHYc 26. Rarity Sim 27. simplify
#28. speculate, 29. quick_sec, 30 bmc3 -S, 31. BMC2 32. extract -a 33. extract 34. pdr_abstract
win_list = [(0,.1),(1,.1),(2,.1),(3,.1),(4,.1),(5,-1),(6,-1),(7,.1)]
FUNCS = ["(pyabc_split.defer(abc)('&get;,pdr -vt=%f'%t))",
         "(pyabc_split.defer(abc)('&get;,imc -vt=%f'%(t)))",
         "(pyabc_split.defer(abc)('&get;,bmc -vt=%f'%t))",
         "(pyabc_split.defer(simulate)(t))",
         "(pyabc_split.defer(abc)('reachx -t %d'%t))",
         "(pyabc_split.defer(pre_simp)())",
##         "(pyabc_split.defer(super_prove)(2))",
         "(pyabc_split.defer(simple)())",
         "(pyabc_split.defer(pdrm)(t))",
         "(pyabc_split.defer(abc)('&get;&reachm -vcs -T %d'%t))",
         "(pyabc_split.defer(abc)('bmc3 -C 1000000 -T %f'%t))",
         "(pyabc_split.defer(abc)('dr;&get;&lcorr;&dc2;&scorr;&put;dr'))",
         "(pyabc_split.defer(abc)('dr -m;&get;&lcorr;&dc2;&scorr;&put;dr'))",
         "(pyabc_split.defer(abc)('&get;&reachp -vr -T %d'%t))",
         "(pyabc_split.defer(abc)('&get;&reachn -vr -T %d'%t))",
##         "(pyabc_split.defer(abc)('&get;,pdr -vt=%f -seed=521'%t))",
         "(pyabc_split.defer(pdrseed)(t))",
         "(pyabc_split.defer(prove_part_2)())",
         "(pyabc_split.defer(prove_part_3)())",
         "(pyabc_split.defer(verify)(JV,t))",
         "(pyabc_split.defer(sleep)(t))",
         "(pyabc_split.defer(pdrmm)(t))",
         "(pyabc_split.defer(prove_part_1)())",
         "(pyabc_split.defer(run_parallel)(JP,t,'TERM'))",
         "(pyabc_split.defer(abc)('&get;,imc -bwd -vt=%f'%t))",
##         "(pyabc_split.defer(abc)('int -C 1000000 -F 10000 -K 2 -T %f'%t))",
         "(pyabc_split.defer(abc)('int -C 1000000 -F 10000 -K 1 -T %f'%t))",
         "(pyabc_split.defer(abc)('&get;&reachy -v -T %d'%t))",
         "(pyabc_split.defer(abc)('&get;&reachy -cv -T %d'%t))",
         "(pyabc_split.defer(simulate2)(t))",
         "(pyabc_split.defer(simplify)())",
         "(pyabc_split.defer(speculate)())",
         "(pyabc_split.defer(quick_sec)(t))",
         "(pyabc_split.defer(bmc_j)(t))",
         "(pyabc_split.defer(abc)('bmc2 -C 1000000 -T %f'%t))",
         "(pyabc_split.defer(extractax)('a'))",
         "(pyabc_split.defer(extractax)())",
         "(pyabc_split.defer(pdra)(t))",
         ]
##         "(pyabc_split.defer(abc)('bmc3 -C 1000000 -T %f -S %d'%(t,int(1.5*max_bmc))))"
#note: interp given 1/2 the time.
allreachs = [4,8,12,13,24,25]
reachs = [24]
##allpdrs = [14,7,34,19,0]
allpdrs = [14,7,34,19]
pdrs = [34,7,14]
allbmcs = [2,9,30,31]
exbmcs = [2,9]
bmcs = [9,30]
allintrps = [1,22,23]
bestintrps = [23]
intrps = [23]
allsims = [3,26]
sims = [26] 
allslps = [18]
slps = [18]
imc1 = [1]

JVprove = [7,23,4,24]
JV = pdrs+intrps+bmcs+sims #sets what is run in parallel '17. verify' above
JP = JV + [27] # sets what is run in  '21. run_parallel' above 27 simplify should be last because it can't time out.
#_____________________________________________________________


# Function definitions:
# simple functions: ________________________________________________________________________
# set_globals, abc, q, x, has_any_model, is_sat, is_unsat, push, pop

# ALIASES

def initialize():
    global xfi, max_bmc, last_time,j_last, seed, init_simp, K_backup, last_verify_time
    global init_time, last_cex, last_winner, trim_allowed, t_init, sec_options, sec_sw
    global n_pos_before, n_pos_proved, last_cx, pord_on, temp_dec, abs_time
    xfi = x_factor = 1  #set this to higher for larger problems or if you want to try harder during abstraction
    max_bmc = -1
    last_time = 0
    j_last = 0
    seed = 113
    init_simp = 1
    temp_dec = True
    K_backup = init_time = 0
    last_verify_time = 20
    last_cex = last_winner = 'None'
    last_cx = 0
    trim_allowed = True
    pord_on = False
    t_init = 2 #this will start sweep time in find_cex_par to 2*t_init here
    sec_sw = False
    sec_options = ''
    cex_list = []
    n_pos_before = n_pos()
    n_pos_proved = 0
    abs_time = 10000

def set_abs_method():
    """ controls the way we do abstraction, 0 = no bip, 1 = old way, 2 use new bip and -dwr
    see absab()
    """
    global ifbip
    print 'Set method of abstraction: \n0 = use vta and no bips, \n1 = old way, \nelse = use ,abs and -dwr'
    s = raw_input()
    s = remove_spaces(s)
    if s == '1':
        ifbip = 1 #old way
    elif s == '0':
        ifbip = 0 #use vta and no bip
    else:
        ifbip = 2 #use ,abc -dwr
    print 'ifbip set to %d. Note engines are set only when read_file is done'%ifbip
    
def ps():
    print_circuit_stats()

def n_real_inputs():
    """This gives the number of 'real' inputs. This is determined by trimming away inputs that
    have no connection to the logic. This is done by the ABC alias 'trm', which changes the current
    circuit. In some applications we do not want to change the circuit, but just to know how may inputs
    would go away if we did this. So the current circuit is saved and then restored afterwards."""
##    abc('w %s_savetempreal.aig; logic; trim; st ;addpi'%f_name)
    abc('w %s_savetempreal.aig'%f_name)
    with redirect.redirect( redirect.null_file, sys.stdout ):
##        with redirect.redirect( redirect.null_file, sys.stderr ):
        reparam()
    n = n_pis()
    abc('r %s_savetempreal.aig'%f_name)
    return n

def timer(t):
    btime = time.clock()
    time.sleep(t)
    print t
    return time.clock() - btime

def sleep(t):
    time.sleep(t)
    return Undecided
        
def abc(cmd):
    abc_redirect_all(cmd)

def abc_redirect( cmd, dst = redirect.null_file, src = sys.stdout ):
    """This is our main way of calling an ABC function. Redirect, means that we suppress any output from ABC"""
    with redirect.redirect( dst, src ):
        return run_command( cmd )

def abc_redirect_all( cmd ):
    """This is our main way of calling an ABC function. Redirect, means that we suppress any output from ABC, including error printouts"""
    with redirect.redirect( redirect.null_file, sys.stdout ):
        with redirect.redirect( redirect.null_file, sys.stderr ):
            return run_command( cmd )

def convert(t):
    t = int(t*100)
    return str(float(t)/100)

def set_engines(N=0):
    """
    Called only when read_file is called.
    Sets the MC engines that are used in verification according to
    if there are 4 or 8 processors. if if_no_bip = 1, we will not use any bip and reachx engines
    """
    global reachs,pdrs,sims,intrps,bmcs,n_proc,abs_ratio,ifbip
    if N == 0:
        N = n_proc = os.sysconf(os.sysconf_names["SC_NPROCESSORS_ONLN"])
    if N == 1:
        reachs = [24]
        pdrs = [7]
##        bmcs = [30]
        bmcs = [9]
        intrps = []
        sims = []
        slps = [18]
    elif N == 2:
        reachs = [24]
        pdrs = [7]
        bmcs = [30]
        intrps = []
        sims = []
        slps = [18]
    elif N == 4:
        reachs = [24]
        pdrs = [34,7]
        if if_no_bip:
            allpdrs = pdrs = [7,19]
        bmcs = [9,30]
        intrps = [23]
        sims = []
        slps = [18]
    elif N == 8:
        reachs = [24]
        pdrs = [34,7,14]
        intrps = [23,1]
        if if_no_bip:
            allpdrs = pdrs = [7,19]
            intrps = [23]
        bmcs = [9,30]
        sims = [26] #use default
        slps = [18]

def set_globals():
    """This sets global parameters that are used to limit the resources used by all the operations
    bmc, interpolation BDDs, abstract etc. There is a global factor 'x_factor' that can
    control all of the various resource limiting parameters"""
    global G_C,G_T,x_factor
    nl=n_latches()
    na=n_ands()
    np = n_pis()
    #G_C = min(500000,(3*na+500*(nl+np)))
    G_C = x_factor * min(100000,(3*na+500*(nl+np)))
    #G_T = min(250,G_C/2000)
    G_T = x_factor * min(75,G_C/2000)
    G_T = max(1,G_T)
    #print('Global values: BMC conflicts = %d, Max time = %d sec.'%(G_C,G_T))
    
def a():
    """this puts the system into direct abc input mode"""
    print "Entering ABC direct-input mode. Type q to quit ABC-mode"
    n = 0
    while True:
        print '     abc %d> '%n,
        n = n+1
        s = raw_input()
        if s == "q":
            break
        run_command(s)

def remove_spaces(s):
    y = ''
    for t in s:
        if not t == ' ':
            y = y + t
    return y

def seq_name(f):
    names = []
    f = f + '_'
    names = []
    while len(f)>0:
        j = f.find('_')
        if j == -1:
            break
        names = names + [f[:j]]
##        print names
        f = f[j+1:]
##        print f
    return names

def revert(f,n):
    l = seq_name(f)
    for j in range(n):
        if len(l)>0:
            l.pop()
    name = construct(l)
    return name

def construct(l):
    ll = l
    name = ''
    while len(l)>0:
        name = '_'+ll.pop()+name
    return name[1:]

def process_sat():
    l = seq_name(f_name)

def read_file_quiet(fname=None):
    """This is the main program used for reading in a new circuit. The global file name is stored (f_name)
    Sometimes we want to know the initial starting name. The file name can have the .aig extension left off
    and it will assume that the .aig extension is implied. This should not be used for .blif files.
    Any time we want to process a new circuit, we should use this since otherwise we would not have the
    correct f_name."""
    global max_bmc,  f_name, d_name, initial_f_name, x_factor, init_initial_f_name, win_list,seed, sec_options
    global win_list, init_simp, po_map
    abc('fraig_restore') #clear out any residual fraig_store
    set_engines() #temporary
    init_simp = 1
    win_list = [(0,.1),(1,.1),(2,.1),(3,.1),(4,.1),(5,-1),(6,-1),(7,.1)] #initialize winning engine list
    po_map = range(n_pos())
    initialize()
##    x_factor = 1
##    seed = 223
##    max_bmc = -1
    if fname is None:
        print 'Type in the name of the aig file to be read in'
        s = raw_input()
        s = remove_spaces(s)
##        print s
    else:
        s = fname
    if s[-4:] == '.aig':
        f_name = s[:-4]
    elif s[-5:] == '.blif':
        f_name = s[:-5]
    else:
        f_name = s
        s = s+'.aig'
##    run_command(s)
##    print s
    if s[-4:] == '.aig':
        run_command('&r %s;&put'%s) #warning: changes names to generic ones.
    else: #this is a blif file
        run_command('r %s'%s)
        abc('st;&get;&put') #changes names to generic ones for doing cec later.
        run_command('zero;w %s.aig'%f_name)
    set_globals()
    init_initial_f_name = initial_f_name = f_name
    print 'Initial f_name = %s'%f_name
    abc('addpi')
    #check_pos() #this removes constant outputs with a warning -
    #needed when using iso. Need another fix for using iso.
    run_command('fold')
    ps()
    return
        
    
def read_file():
    global win_list, init_simp, po_map
    read_file_quiet()
##    ps()
##    init_simp = 1
##    win_list = [(0,.1),(1,.1),(2,.1),(3,.1),(4,.1),(5,-1),(6,-1),(7,.1)] #initialize winning engine list
##    po_map = range(n_pos())

def rf():
##    set_engines(4) #temporary
    read_file()

def write_file(s):
    """this is the main method for writing the current circuit to an AIG file on disk.
    It manages the name of the file, by giving an extension (s). The file name 'f_name'
    keeps increasing as more extensions are written. A typical sequence is
    name, name_smp, name_smp_abs, name_smp_abs_spec, name_smp_abs_spec_final"""
    global f_name
    """Writes out the current file as an aig file using f_name appended with argument"""
    f_name = '%s_%s'%(f_name,s)
    ss = '%s.aig'%(f_name)
    print 'WRITING %s: '%ss,
    ps()
    abc('w '+ss)

def bmc_depth():
    """ Finds the number of BMC frames that the latest operation has used. The operation could be BMC, reachability
    interpolation, abstract, speculate. max_bmc is continually increased. It reflects the maximum depth of any version of the circuit
    including g ones, for which it is known that there is not cex out to that depth."""
    global max_bmc
    c = cex_frame()
    if c > 0:
        b = c-1
    else:
        b = n_bmc_frames()
    max_bmc = max(b,max_bmc)
    return max_bmc

def null_status():
    """ resets the status to the default values but note that the &space is changed"""
    abc('&get;&put')

def set_max_bmc(b):
    """ Keeps increasing max_bmc which is the maximum number of time frames for
    which the current circuit is known to be UNSAT for"""
    global max_bmc
    max_bmc = max(b,max_bmc)

def print_circuit_stats():
    """Stardard way of outputting statistice about the current circuit"""
    global max_bmc
    i = n_pis()
    o = n_pos()
    l = n_latches()
    a = n_ands()
    s='ANDs'
    if a == -1:
        a = n_nodes()
        s = 'Nodes'
    b = max(max_bmc,bmc_depth())
    c = cex_frame()
    if b>= 0:
        if c>=0:
            print 'PIs=%d,POs=%d,FF=%d,%s=%d,max depth=%d,CEX depth=%d'%(i,o,l,s,a,b,c)
        elif is_unsat():
            print 'PIs=%d,POs=%d,FF=%d,%s=%d,max depth = infinity'%(i,o,l,s,a)
        else:
            print 'PIs=%d,POs=%d,FF=%d,%s=%d,max depth=%d'%(i,o,l,s,a,b)            
    else:
        if c>=0:
            print 'PIs=%d,POs=%d,FF=%d,%s=%d,CEX depth=%d'%(i,o,l,s,a,c)
        else:
            print 'PIs=%d,POs=%d,FF=%d,%s=%d'%(i,o,l,s,a)

def q():
    exit()

def is_unsat():
    if prob_status() == 1:
        return True
    else:
        return False

def is_sat():
    if prob_status() == 0:
        return True
    else:
        return False

def wc(file):
    """writes <file> so that costraints are preserved explicitly"""
    abc('&get;&w %s'%file)

def rc(file):
    """reads <file> so that if constraints are explicit, it will preserve them"""
    abc('&r %s;&put'%file)                         

#more complex functions: ________________________________________________________
#, abstract, pba, speculate, final_verify, dprove3

def timer(s):
    btime = time.clock()
    abc(s)
    print 'time = %f'%(time.clock() - btime)

def med_simp():
    x = time.time()
    abc("&get;&scl;&dc2;&lcorr;&dc2;&scorr;&fraig;&dc2;&put;dr")
    #abc("dc2rs")
    ps()
    print 'time = %f'%(time.time() - x)

def simplify():
    """Our standard simplification of logic routine. What it does depende on the problem size.
    For large problems, we use the &methods which use a simple circuit based SAT solver. Also problem
    size dictates the level of k-step induction done in 'scorr' The stongest simplification is done if
    n_ands < 20000. Then it used the clause based solver and k-step induction where |k| depends
    on the problem size """
    set_globals()
    abc('&get;&scl;&lcorr;&put')
    p_40 = False
    n =n_ands()
    if n >= 70000:
        abc('&get;&scorr -C 0;&put')
    n =n_ands()
    if n >= 100000:
        abc('&get;&scorr -k;&put')
    if (70000 < n and n < 100000):
        p_40 = True
        abc("&get;&dc2;&put;dr;&get;&lcorr;&dc2;&put;dr;&get;&scorr;&fraig;&dc2;&put;dr")
        n = n_ands()
##        if n<60000:
        if n < 80000:
            abc("&get;&scorr -F 2;&put;dc2rs")
        else: # n between 60K and 100K
            abc("dc2rs")
    n = n_ands()
##    if (30000 < n  and n <= 40000):
    if (60000 < n  and n <= 70000):
        if not p_40:
            abc("&get;&dc2;&put;dr;&get;&lcorr;&dc2;&put;dr;&get;&scorr;&fraig;&dc2;&put;dr")
            abc("&get;&scorr -F 2;&put;dc2rs")
        else:
            abc("dc2rs")            
    n = n_ands()
##    if n <= 60000:
    if n <= 70000:
        abc('scl -m;drw;dr;lcorr;drw;dr')
        nn = max(1,n)
        m = int(min( 70000/nn, 16))
        if m >= 1:
            j = 1
            while j <= m:
                set_size()
                if j<8:
                    abc('dc2')
                else:
                    abc('dc2rs')
                abc('scorr -C 5000 -F %d'%j)
                if check_size():
                    break
                j = 2*j
                print 'ANDs=%d,'%n_ands(),
                if n_ands() >= .98 * nands:
                     break
                continue
            if not check_size():
                print '\n'
    return get_status()
            
def simulate2(t):
    """Does rarity simulation. Simulation is restricted by the amount
    of memory it might use. At first wide but shallow simulation is done, followed by
    successively more narrow but deeper simulation. 
    seed is globally initiallized to 113 when a new design is read in"""
    global x_factor, f_name, tme, seed
    btime = time.clock()
    diff = 0
    while True:
        f = 100
        w = 16
        b = 16
        r = 500
        for k in range(9): #this controls how deep we go
            f = min(f*2, 3500)
            w = max(((w+1)/2)-1,1)
            abc('sim3 -F %d -W %d -N %d -R %d -B %d'%(f,w,seed,r,b))
            seed = seed+23
            if is_sat():
                return 'SAT'
            if ((time.clock()-btime) > t):
                return 'UNDECIDED'

def simulate(t):
    abc('&get')
    result = eq_simulate(t)
    return result

def eq_simulate(t):
    """Simulation is restricted by the amount
    of memory it might use. At first wide but shallow simulation is done, followed by
    successively more narrow but deeper simulation. The aig to be simulated must be in the & space
    If there are equivalences, it will refine them. Otherwise it is a normal similation
    seed is globally initiallized to 113 when a new design is read in"""
    global x_factor, f_name, tme, seed
    btime = time.clock()
    diff = 0
    while True:
        f = 5
        w = 255
        for k in range(9):
            f = min(f *2, 3500)
            r = f/20
            w = max(((w+1)/2)-1,1)
##            abc('&sim3 -R %d -W %d -N %d'%(r,w,seed))
            abc('&sim -F %d -W %d -R %d'%(f,w,seed))
            seed = seed+23
            if is_sat():
                return 'SAT'
            if ((time.clock()-btime) > t):
                return 'UNDECIDED'

def generate_abs(n):
    """generates an abstracted  model (gabs) from the greg file. The gabs file is automatically
    generated in the & space by &abs_derive. We store it away using the f_name of the problem
    being solved at the moment. The f_name keeps changing with an extension given by the latest
    operation done - e.g. smp, abs, spec, final, group. """
    global f_name
    #we have a cex and we use this generate a new gabs file
    abc('&r %s_greg.aig; &abs_derive; &put; w %s_gabs.aig'%(f_name,f_name)) # do we still need the gabs file
    if n == 1:
        #print 'New abstraction: ',
        ps()
    return   

def refine_with_cex():
    """Refines the greg (which contains the original problem with the set of FF's that have been abstracted).
    This uses the current cex to modify the greg file to reflect which regs are in the
    new current abstraction"""
    global f_name
    #print 'CEX in frame %d for output %d'%(cex_frame(),cex_po())
    #abc('&r %s_greg.aig; &abs_refine -t; &w %s_greg.aig'%(f_name,f_name))
    abc('&r %s_greg.aig;&w %s_greg_before.aig'%(f_name,f_name))
##    run_command('&abs_refine -s -M 25; &w %s_greg.aig'%f_name)
    run_command('&abs_refine -s; &w %s_greg.aig'%f_name)
    #print ' %d FF'%n_latches()
    return

def iter_tempor():
    na = n_ands()
    while True:
        abc('w save.aig')
        npi = n_pis()
        print npi
        abc('tempor -T 5 -F 8')
        print 'tempor = ',
        ps()
        x = trim()
##        if n_pis() > 2*npi:
##            abc('r save.aig')
##            return 'UNDECIDED'  
        abc('dr')
        print 'retime = ',
        ps()
        simplify()
        trim()
        print 'simplify -> trim = ',
        ps()
        if n_ands() > na:
            abc('r save.aig')
            ps()
            print 'No improvement'
            return 'UNDECIDED'  
        na = n_ands()
        ps()
        if n_latches() == 0:
            return RESULT[check_sat()]


def abstraction_refinement(latches_before,NBF,ratio=.75):
    """Subroutine of 'abstract' which does the refinement of the abstracted model,
    using counterexamples found by BMC or BDD reachability"""
    global x_factor, f_name, last_verify_time, x, win_list, last_winner, last_cex, t_init, j_last, sweep_time
    global cex_list, last_cx
    sweep_time = 2
    if NBF == -1:
        F = 2000
    else:
        F = 2*NBF
    print '\nIterating abstraction refinement'
    J = slps+intrps+pdrs+bmcs+sims
    print sublist(methods,J)
    last_verify_time = t = x_factor*max(50,max(1,2.5*G_T))
    t = 1000 #temporary
    t = abs_time
    initial_verify_time = last_verify_time = t
    reg_verify = True
    print 'Verify time set to %d'%last_verify_time
    while True: #cex based refinement
        generate_abs(1) #generate new gabs file from refined greg file
        set_globals()
        latches_after = n_latches()
        if small_abs(ratio):
            break
        t = last_verify_time
        yy = time.time()
        abc('w %s_beforerpm.aig'%f_name)
        rep_change = reparam() #new - must do reconcile after to make cex compatible
        abc('w %s_afterrpm.aig'%f_name)
##        if reg_verify:
        status = verify(J,t)
##        else:
##            status = pord_1_2(t)
###############
        if status == Sat_true:
            print 'Found true cex'
            reconcile(rep_change)
            return Sat_true
        if status == Unsat:
            return status
        if status == Sat:
            abc('write_status %s_after.status'%f_name)
            reconcile(rep_change) # makes the cex compatible with original before reparam and puts original in work space
            abc('write_status %s_before.status'%f_name)
            refine_with_cex()
            if is_sat(): # if cex can't refine, status is set to Sat_true
                print 'Found true cex in output %d'%cex_po()
                return Sat_true
            else:
                continue
        else:
            break
    print '**** Latches reduced from %d to %d'%(latches_before, n_latches())
    return Undecided_reduction

def small_abs(ratio=.75):
    """ tests is the abstraction is too large"""
    return ((rel_cost_t([pis_before_abs,latches_before_abs, ands_before_abs])> -.1)
           or (n_latches() >= ratio*latches_before_abs))

##def abstract(if_bip=True):
##    global ratio
##    if if_bip:
##        return abstractb(True) #old method using abstraction refinement
##    else:
##        return abstractb(False) #not using bip and reachx

def abstractb():
    """ abstracts using N Een's method 3 - cex/proof based abstraction. The result is further refined using
    simulation, BMC or BDD reachability. abs_ratio is the the limit for accepting an abstraction"""
    global G_C, G_T, latches_before_abs, x_factor, last_verify_time, x, win_list, j_last, sims
    global latches_before_abs, ands_before_abs, pis_before_abs, abs_ratio
    if ifbip < 1:
        print 'using ,abs in old way'
    tt = time.time()
    j_last = 0
    set_globals()
    #win_list = []
    latches_before_abs = n_latches()
    ands_before_abs = n_ands()
    pis_before_abs = n_real_inputs()
    abc('w %s_before_abs.aig'%f_name)
    print 'Start: ',
    ps()
    funcs = [eval('(pyabc_split.defer(initial_abstract)())')]
    # fork off BMC3 and PDRm along with initial abstraction
    t = 10000 #want to run as long as initial abstract takes.
##    J = sims+pdrs+bmcs+intrps
    J = slps+pdrs+bmcs+intrps
    J = modify_methods(J,1)
##    if n_latches() < 80:
##        J = J + [4]
    funcs = create_funcs(J,t) + funcs
    mtds = sublist(methods,J) + ['initial_abstract'] #important that initial_abstract goes last
    m,result = fork_last(funcs,mtds)
    if is_sat():
        print 'Found true counterexample in frame %d'%cex_frame()
        return Sat_true
    if is_unsat():
        return Unsat
##    set_max_bmc(NBF)
    NBF = bmc_depth()
    print 'Abstraction good to %d frames'%max_bmc
    #note when things are done in parallel, the &aig is not restored!!!
    abc('&r %s_greg.aig; &w initial_greg.aig; &abs_derive; &put; w initial_gabs.aig; w %s_gabs.aig'%(f_name,f_name))
    set_max_bmc(NBF)
    print 'Initial abstraction: ',
    ps()
    abc('w %s_init_abs.aig'%f_name)
    latches_after = n_latches()
##    if latches_after >= .90*latches_before_abs: #the following should match similar statement
##    if ((rel_cost_t([pis_before_abs, latches_before_abs, ands_before_abs])> -.1) or
##        (latches_after >= .75*latches_before_abs)):
    if small_abs(abs_ratio):
        abc('r %s_before_abs.aig'%f_name)
        print "Little reduction!"
        print 'Abstract time wasted = %0.2f'%(time.time()-tt)
        return Undecided_no_reduction
    sims_old = sims
    sims=sims[:1] #make it so that rarity sim is not used since it can't find a cex
    result = abstraction_refinement(latches_before_abs, NBF,abs_ratio)
    sims = sims_old
    if result <= Unsat:
        return result
##    if n_latches() >= .90*latches_before_abs:
##    if ((rel_cost_t([pis_before_abs, latches_before_abs, ands_before_abs])> -.1) or (latches_after >= .90*latches_before_abs)):
##    if rel_cost_t([pis_before_abs,latches_before_abs, ands_before_abs])> -.1:
    if small_abs(abs_ratio): #r is ratio of final to initial latches in absstraction. If greater then True
        abc('r %s_before_abs.aig'%f_name) #restore original file before abstract.
        print "Little reduction!  ",
        print 'Abstract time wasted = %0.2f'%(time.time()-tt)
        result = Undecided_no_reduction
        return result
    #new
    else:
        write_file('abs') #this is only written if it was not solved and some change happened.
    print 'Abstract time = %0.2f'%(time.time()-tt)
    return result

def initial_abstract_old():
    global G_C, G_T, latches_before_abs, x_factor, last_verify_time, x, win_list
    set_globals()
    time = max(1,.1*G_T)
    abc('&get;,bmc -vt=%f'%time)
    set_max_bmc(bmc_depth())
    c = 2*G_C
    f = max(2*max_bmc,20)
    b = min(max(10,max_bmc),200)
    t = x_factor*max(1,2*G_T)
    s = min(max(3,c/30000),10) # stability between 3 and 10 
    cmd = '&get;,abs -bob=%d -stable=%d -timeout=%d -vt=%d -depth=%d'%(b,s,t,t,f)
##    print cmd
    print 'Running initial_abstract with bob=%d,stable=%d,time=%d,depth=%d'%(b,s,t,f)
    abc(cmd)
    abc('&w %s_greg.aig'%f_name)
##    ps()

def initial_abstract(t=100):
    global G_C, G_T, latches_before_abs, x_factor, last_verify_time, x, win_list, max_bmc, ifbip
    set_globals()
    time = max(1,.1*G_T)
    time = min(time,t)
    abc('&get;,bmc -vt=%f'%time)
    set_max_bmc(bmc_depth())
    c = 2*G_C
    f = max(2*max_bmc,20)
    b = min(max(10,max_bmc),200)
    t1 = x_factor*max(1,2*G_T)
    t = max(t1,t)
    s = min(max(3,c/30000),10) # stability between 3 and 10
    cmd = '&get;,abs -bob=%d -stable=%d -timeout=%d -vt=%d -depth=%d'%(b,s,t,t,f)
    if ifbip == 2:
        cmd = '&get;,abs -bob=%d -stable=%d -timeout=%d -vt=%d -depth=%d -dwr=%s_vabs'%(b,s,t,t,f,f_name)
        print 'Using -dwr=%s_vabs'%f_name
##    print cmd
    print 'Running initial_abstract with bob=%d,stable=%d,time=%d,depth=%d'%(b,s,t,f)
    abc(cmd)
    bmc_depth()
##    pba_loop(max_bmc+1)
    abc('&w %s_greg.aig'%f_name)
    return max_bmc

def abs_m():
    set_globals()
    y = time.time()
    nl = n_abs_latches() #initial set of latches
    c = 2*G_C
    t = x_factor*max(1,2*G_T) #total time
    bmd = bmc_depth()
    if bmd < 0:
        abc('bmc3 -T 2') #get initial depth estimate
        bmd = bmc_depth()
    f = bmd
    abc('&get')
    y = time.time()
    cmd = '&abs_cba -v -C %d -T %0.2f -F %d'%(c,.8*t,bmd) #initial absraction
##    print '\n%s'%cmd
    abc(cmd)
    b_old = b = n_bmc_frames()
    f = min(2*bmd,max(bmd,1.6*b))
    print 'cba: latches = %d, depth = %d'%(n_abs_latches(),b)
##    print n_bmc_frames()
    while True:
        if (time.time() - y) > .9*t:
            break
        nal = n_abs_latches()
        cmd = '&abs_cba -v -C %d -T %0.2f -F %d'%(c,.8*t,f) #f is 2*bmd and is the maximum number of frames allowed
##        print '\n%s'%cmd
        abc(cmd)
##        print n_bmc_frames()
        b_old = b
        b = n_bmc_frames() 
        nal_old = nal 
        nal = n_abs_latches() #nal - nal_old is the number of latches added by cba
        #b - b_old is the additional time frames added by cba
        f = min(2*bmd,max(bmd,1.6*b))   #may be this should just be bmd
        f = max(f,1.5*bmd)
        print 'cba: latches = %d, depth = %d'%(nal,b)
        if ((nal == nal_old) and (b >= 1.5*b_old) and b >= 1.5*bmd):
            """
            Went at least bmd depth and saw too many frames without a cex
            (ideally should know how many frames without a cex)
            """
            print 'Too many frames without cex'
            break
        if b > b_old: #if increased depth
            continue
        if nal > .9*nl: # try to minimize latches
##            cmd = '&abs_pba -v -S %d -F %d -T %0.2f'%(b,b+2,.2*t)
            cmd = '&abs_pba -v -F %d -T %0.2f'%(b+2,.2*t)
##            print '\n%s'%cmd
            abc(cmd)
            b = n_bmc_frames()
            nal_old = nal
            nal = n_abs_latches()
            print 'pba: latches = %d, depth = %d'%(nal,b)
##            print n_bmc_frames()
            if nal_old < nal: #if latches increased there was a cex
                continue
            if nal > .9*nl: # if still too big 
                return
        continue 
##    b = n_bmc_frames()
    cmd = '&abs_pba -v -F %d -T %0.2f'%(b+2,.2*t)
##    print '\n%s'%cmd
    abc(cmd)
    b = n_bmc_frames()
    print 'pba: latches = %d, depth = %d'%(n_abs_latches(),b)
##    print n_bmc_frames()
    print 'Total time = %0.2f'%(time.time()-y)

def n_abs_latches():
    abc('&w pba_temp.aig') #save the &space
    abc('&abs_derive;&put')
    abc('&r pba_temp.aig')
    return n_latches()
        
def pba_loop(F):
    n = n_abs_latches()
    while True:
        run_command('&abs_pba -v -C 0 -F %d'%F)
        abc('&w pba_temp.aig')
        abc('&abs_derive;&put')
        abc('&r pba_temp.aig')
        N = n_latches()
##        if n == N or n == N+1:
##            break
##        elif N > n:
        if N > n:
            print 'cex found'
        break

def ssm(options=''):
    """ Now this should be the same as super_prove(1) """
    y = time.time()
    result = prove_part_1() # simplify first
    if result == 'UNDECIDED':
        result = ss(options)
    print 'Total time taken on file %s by function ssm(%s) = %d sec.'%(initial_f_name,options,(time.time() - y))
    return result

def ssmg():
    return ssm('g')
def ssmf():
    return ssm('f')


def ss(options=''):
    """
    Alias for super_sec
    This is the preferred command if the problem (miter) is suspected to be a SEC problem
    """
    global max_bmc, init_initial_f_name, initial_f_name,win_list, last_verify_time, sec_options
    sec_options = options
    print '\n*************Executing speculate************'
    y = time.time()
    abc('scl')
    result = speculate()
    # if result is 1 then it is a real SAT since we did not do anything before
    if result > 2: #save the result and read in with /rf so that files are initialized correctly
        if not '_spec' in f_name:
            write_file('spec') #make sure we do not overwrite original file
        read_file_quiet('%s'%f_name) #this resets f_name and initial_f_name etc.
        print '\n*************Executing super_prove ************'
        print 'New f_name = %s'%f_name
        result = sp()
        if result == 'SAT':
            result = 'UNDECIDED' #because speculation was done initially.
    elif result == 1:
        result = 'SAT'
    else:
        result = RESULT[result]
    print 'Total time taken on file %s by function ss(%s) = %d sec.'%(initial_f_name,options,(time.time() - y))
    return result

def quick_sec(t):
##    fb_name = f_name[:-3]+'New'
##    abc('&get;&miter -s %s.aig;&put'%fb_name)
##    abc('w %s.%s_miter.aig'%(f_name,fb_name))
    quick_simp()
    verify(slps+ pdrs+bmcs+intrps,t)
    if is_unsat():
        return 'UNSAT'
    if is_sat():
        return 'SAT'
    else:
        return'UNDECIDED'

def pre_sec():
    """ put files to be compared into Old and New aigs. Simplify, but
    turn off reparameterization so that PIs in Old and New match after simplification.
    """
    global trim_allowed
##    trim_allowed = False
##    print 'trim allowed = ',trim_allowed
    print 'First file: ',
    read_file_quiet() #note - reads into & space and then does &put
    ps()
    prs(False)
    ps()
    abc('&w Old.aig')
    print 'Second file: ',
    read_file_quiet()
    ps()
    prs(False)
    ps()
    abc('&w New.aig')
        
def cec():
    print 'Type in the name of the aig file to be compared against'
    s = raw_input()
    s = remove_spaces(s)
    if not 'aig' in s:
        s = s+'.aig'
    run_command("&get;&cec -v %s"%s)

def sec(B_part,options):
    """
    Use this for AB filtering and not sup_sec
    Use pp_sec to make easy names for A and B, namely Old and New.
    This assumes that the original aig (renamed A_name below) is already read into the working space.
    Then we form a miter using &miter between two circuits, A_name, and B_name.
    We then do speculate immediately. Optionally we could simplify A and B
    and then form the miter and start from there. The only difference in speculate
    is that &srm2 is used, which only looks at equivalences where one comes from A and
    one from B. Options are -a and -b which says use only flops in A or in B or both. The
    switch sec_sw controls what speculate does when it generates the SRM.
    """
    global f_name,sec_sw, A_name, B_name, sec_options
    yy = time.time()
    A_name = f_name # Just makes it so that we can refer to A_name later in &srm2
    B_name = B_part
    run_command('&get; &miter -s %s.aig; &put'%B_name)
##    abc('orpos')
    f_name = A_name+'_'+B_name+'_miter' # reflect that we are working on a miter.
    abc('w %s.aig'%f_name)
    print 'Miter = ',
    ps()
    sec_options = options
    if sec_options == 'ab':
        sec_options = 'l' #it will be changed to 'ab' after &equiv
    sec_sw = True 
    result = speculate() 
    sec_options = ''
    sec_sw = False
    if result <= Unsat:
        result = RESULT[result]
    else:
        result = sp()
        if result == 'SAT':
            result = 'UNDECIDED'
    print 'Total time = %d'%(time.time() - yy)
    return result

def filter(opts):
    global A_name,B_name
##    print 'Filtering with options = %s'%opts
    """ This is for filter which effectively only recognizes options -f -g"""
    if (opts == '' or opts == 'l'): #if 'l' this is used only for initial &equiv2 to get initial equiv creation
        return
    if opts == 'ab':
        print A_name ,
        print B_name
        run_command('&ps')
        run_command('&filter -f %s.aig %s.aig'%(A_name,B_name))
        return
    if not opts == 'f':
        opts = 'g'
    run_command('&filter -%s'%opts)

def check_if_spec_first():
    global sec_sw, A_name, B_name, sec_options, po_map
    set_globals()
    t = max(1,.5*G_T)
    r = max(1,int(t))
    abc('w check_save.aig')
    abc('&w check_and.aig')
    abc("&get; &equiv3 -v -F 20 -T %f -R %d"%(t,5*r))
    filter('g')
    abc("&srm; r gsrm.aig")
    print 'Estimated # POs = %d for initial speculation'%n_pos()
    result = n_pos() > max(50,.25*n_latches())
    abc('r check_save.aig')
    abc('&r check_and.aig')
    return result

def initial_speculate(sec_opt=''):
    global sec_sw, A_name, B_name, sec_options, po_map
    set_globals()
    if sec_options == '':
        sec_options = sec_opt
    t = max(1,.5*G_T)
    r = max(1,int(t))
    print 'Initial sec_options = %s'%sec_options
    if sec_options == 'l':
        cmd = "&get; &equiv3 -lv -F 20 -T %f -R %d"%(3*t,15*r)
    else:
        cmd = "&get; &equiv3 -v -F 20 -T %f -R %d"%(3*t,15*r)
    print cmd
    abc(cmd)
##    print 'AND space after &equiv3: ',
    run_command('&ps')
    if (sec_options == 'l'):
        if sec_sw:
            sec_options = 'ab'
        else:
            sec_options = 'f'
##    print 'A_name: ',
##    run_command('r %s.aig;ps'%A_name)
##    print 'B_name: ',
##    run_command('r %s.aig;ps'%B_name)
    filter(sec_options)
    abc('&w initial_gore.aig')
##    print 'Running &srm'
    if sec_sw:
        print 'miter: ',
        run_command('&ps')
        print 'A_name: ',
        run_command('r %s.aig;ps'%A_name)
        print 'B_name: ',
        run_command('r %s.aig;ps'%B_name)
        cmd = "&srm2 -%s %s.aig %s.aig; r gsrm.aig; w %s_gsrm.aig; &w %s_gore.aig"%(sec_options,A_name,B_name,f_name,f_name)
        abc(cmd)
        po_map = range(n_pos())
        return
    else:
##        abc('&r %s_gore.aig; &srm ; r gsrm.aig; w %s_gsrm.aig'%(f_name,f_name))
        cmd = "&srm; r gsrm.aig; w %s_gsrm.aig; &w %s_gore.aig"%(f_name,f_name)
##        print 'Running %s'%cmd
        abc(cmd)
        print 'done with &srm'
        po_map = range(n_pos())
        if sec_options == '':
            if n_pos() > 200:
                sec_options = 'g'
                print 'sec_options set to %s'%'g'
                abc('&r %s_gore.aig'%f_name)
                filter(sec_options)
                print 'Running &srm'
                cmd = "&srm; r gsrm.aig; ps;w %s_gsrm.aig;&ps; &w %s_gore.aig"%(f_name,f_name)
                print 'Running %s'%cmd
                abc(cmd)
                po_map = range(n_pos())
        

def test_against_original():
    '''tests whether we have a cex hitting an original PO'''
    abc('&w %s_save.aig'%f_name) #we preserve whatever was in the & space
    abc('&r %s_gore.aig'%f_name) #This is the original
    abc('testcex')
    PO = cex_po()
##    print 'test_against original gives PO = %d'%PO 
    abc('&r %s_save.aig'%f_name)
    if PO > -1:
##        print 'cex fails an original PO'
        return True
    else:
        abc('write_status %s_status.status'%f_name)
        return False

def set_cex_po(n=0):
    """
    if cex falsifies a non-real PO return that PO first,
    else see if cex_po is one of the original, then take it next
    else return -1 which means that the cex is not valid and hence an error.
    parameter n = 1 means test the &-space
    """
    global n_pos_before, n_pos_proved #these refer to real POs
    if n == 0:
        abc('testcex -a -O %d'%(n_pos_before-n_pos_proved)) #test regular AIG space
    else:
        abc('testcex -O %d'%(n_pos_before-n_pos_proved)) #test the &-AIG
    PO = cex_po()
##    print 'cex_po = %d, n_pos_before = %d, n_pos_proved = %d'%(PO, n_pos_before, n_pos_proved)
    if PO >= (n_pos_before - n_pos_proved): #cex_po is not an original
##        print '1. cex PO = %d'%PO
        return PO # after original so take it.
    if n == 0:
        abc('testcex -a') #test regular
    else:
        abc('testcex')  #test &space
    PO = cex_po()
##    print '2. cex PO = %d'%PO
    cx = cex_get()
    if PO > -1:
        if test_against_original(): #this double checks that it is really an original PO
            cex_put(cx)
##            print 'test_against_original was valid'
            return PO
        else:
            print '1. PO not valid'
            return -1 #error
    if PO < 0 or PO >= (n_pos_before - n_pos_proved): # not a valid cex because already tested outside original.
        print '2. PO is not valid'
        PO = -1 #error
##    print '3. cex PO = %d'%PO
    return PO

def speculate():
    """Main speculative reduction routine. Finds candidate sequential equivalences and refines them by simulation, BMC, or reachability
    using any cex found. """    
    global G_C,G_T,n_pos_before, x_factor, n_latches_before, last_verify_time, trim_allowed, n_pos_before
    global t_init, j_last, sec_sw, A_name, B_name, sec_options, po_map, sweep_time, sims, cex_list, n_pos_proved,ifpord1
    global last_cx
    last_cx = 0
    ifpord1 = 1
    initial_po_size = last_srm_po_size = n_pos()
    initial_sizes = [n_pis(),n_pos(),n_latches(),n_ands()]
    if sec_sw:
        print 'A_name = %s, B_name = %s, f_name = %s, sec_options = %s'%(A_name, B_name, f_name, sec_options)
    elif n_ands()> 36000 and sec_options == '':
        sec_options = 'g'
        print 'sec_options set to "g"'
        
    def refine_with_cex():
        """Refines the gore file to reflect equivalences that go away because of cex"""
        global f_name
        abc('write_status %s_before.status'%f_name)
        abc('&r %s_gore.aig; &resim -m'%f_name)
        filter(sec_options)
        run_command('&w %s_gore.aig'%f_name)
        return
    
    def set_cex(lst):
        """ assumes only one in lst """
        for j in range(len(lst)):
            cx = lst[j]
            if cx == None:
                continue
            else:
                cex_put(cx)
                break

    def generate_srm():
        """generates a speculated reduced model (srm) from the gore file"""
        global f_name, po_map, sec_sw, A_name, B_name, sec_options, n_pos_proved
##        print 'Generating'
        pos = n_pos()
        ab = n_ands()
        abc('w %s_oldsrm.aig'%f_name) #save for later purposes
        if sec_sw:
            run_command('&r %s_gore.aig; &srm2 -%s %s.aig %s.aig; r gsrm.aig; w %s_gsrm.aig'%(f_name,sec_options,A_name,B_name,f_name))
        else:
            abc('&r %s_gore.aig; &srm ; r gsrm.aig; w %s_gsrm.aig'%(f_name,f_name)) #do we still need to write the gsrm file
##        ps()
        po_map = range(n_pos())
        ps()
        n_pos_proved = 0
        return 'OK'
    
    n_pos_before = n_pos()
    n_pos_proved = 0
    n_latches_before = n_latches()    
    set_globals()
##    t = max(1,.5*G_T)#irrelevant
##    r = max(1,int(t))
    t = 1000
    j_last = 0
    J = slps+sims+pdrs+bmcs+intrps
    J = modify_methods(J,1)
    funcs = [eval('(pyabc_split.defer(initial_speculate)())')]
    funcs = create_funcs(J,10000)+funcs #want other functins to run until initial speculate stops
    mtds = sublist(methods,J) + ['initial_speculate'] #important that initial_speculate goes last
    fork_last(funcs,mtds)
##    ps()
    if is_unsat():
        return Unsat
    if is_sat():
        return Sat_true
    if n_pos_before == n_pos():
        print 'No new outputs. Quitting speculate'
        return Undecided_no_reduction # return result is unknown
##    cmd = 'lcorr;&get;&trim -i;&put;w %s_gsrm.aig'%f_name
    #print 'Executing %s'%cmd
    abc('w initial_gsrm.aig')
##    ps()
##    abc(cmd)
    print 'Initial speculation: ',
    ps()
    if n_latches() == 0:
        return check_sat()
    if sec_options == 'l' and sec_sw:
        sec_options = 'ab' #finished with initial speculate with the 'l' option
        print "sec_options set to 'ab'"
    elif sec_options == 'l':
        sec_options = 'f'
        print "sec_options set to 'f'"
    po_map = range(n_pos()) #we need this because the initial_speculate is done in parallel and po_map is not passed back.
    npi = n_pis()
    set_globals()
    if is_sat():
        return Sat_true
    simp_sw = init = True
    print '\nIterating speculation refinement'
    sims_old = sims
    sims = sims[:1] 
    J = slps+sims+pdrs+intrps+bmcs
    J = modify_methods(J)
##    print sublist(methods,J)
    t = max(50,max(1,2*G_T))
    last_verify_time = t
    print 'Verify time set to %d'%last_verify_time
    reg_verify = True
    ref_time = time.time()
    sweep_time = 2
    ifpord1=1
    while True: # refinement loop
        set_globals()
        yy = time.time()
        if not init:
            abc('r %s_gsrm.aig'%f_name) #this is done only to set the size of the previous gsrm.
            abc('w %s_gsrm_before.aig'%f_name)
            set_size()
            result = generate_srm()
            last_srm_po_size = n_pos()
            yy = time.time()
            # if the size of the gsrm did not change after generating a new gsrm
            # and if the cex is valid for the gsrm, then the only way this can happen is if
            # the cex_po is an original one.
            if check_size(): #same size before and after
                if check_cex(): #valid cex failed to refine possibly
                    if 0 <= cex_po() and cex_po() < (n_pos_before - n_pos_proved): #original PO
                        print 'Found cex in original output = %d'%cex_po()
                        print 'Refinement time = %s'%convert(time.time() - ref_time)
                        return Sat_true
                    elif check_same_gsrm(f_name): #if two gsrms are same, then failed to refine
                        print 'CEX failed to refine'
                        return Error
                else:
                    print 'not a valid cex'
                    return Error
            if n_latches() == 0:
                print 'Refinement time = %s'%convert(time.time() - ref_time)
                return check_sat()
        init = False # make it so that next time it is not the first time through
        if not t == last_verify_time: # heuristic that if increased last verify time,
                                      # then try pord_all 
            t = last_verify_time
            if reg_verify:
                t_init = (time.time() - yy)/2 #start poor man's concurrency at last cex fime found
                t_init = min(10,t_init)
##         temporary       reg_verify = False #will cause pord_all to be used next
##                print 'pord_all turned on'
                t = last_verify_time
                print 'Verify time set to %d'%t
        abc('w %s_beforerpm.aig'%f_name)
        rep_change = reparam() #must be paired with reconcile below if cex
        abc('w %s_afterrpm.aig'%f_name)
        if reg_verify:
            result = verify(J,t)
        else:
            result = pord_1_2(t)
        if result == Unsat:
            print 'UNSAT'
            print 'Refinement time = %s'%convert(time.time() - ref_time)
            return Unsat
        if result < Unsat:
            if not reg_verify:
                set_cex(cex_list)
##        if reg_verify: 
            reconcile(rep_change) #end of pairing with reparam()
            assert (npi == n_cex_pis()),'ERROR: #pi = %d, #cex_pi = %d'%(npi,n_cex_pis())
            abc('&r %s_gore.aig;&w %s_gore_before.aig'%(f_name,f_name)) #we are making sure that none of the original POs fail
            if reg_verify:
                PO = set_cex_po(0) #testing the regular space
            else:
                abc('&r %s_gsrm.aig'%f_name)
                PO = set_cex_po(1) # test against the &space.
            print 'cex_PO is %d'%PO
            if (-1 < PO and PO < (n_pos_before-n_pos_proved)):
                print 'Found cex in original output = %d'%cex_po()
                print 'Refinement time = %s'%convert(time.time() - ref_time)
                return Sat_true
            if PO == -1:
                return Error
            refine_with_cex()    #change the number of equivalences
            continue
        elif (is_unsat() or n_pos() == 0):
            print 'UNSAT'
            print 'Refinement time = %s'%convert(time.time() - ref_time)
            return Unsat
        else: #if undecided, record last verification time
            print 'Refinement returned undecided in %d sec.'%t
            last_verify_time = t
            #########################added
            if reg_verify: #try one last time with parallel POs cex detection (find_cex_par) if not already tried
                abc('r %s_beforerpm.aig'%f_name) # to continue refinement, need to restore original
                t_init = min(last_verify_time,(time.time() - yy)/2) #start poor man's concurrency at last cex fime found
                t_init = min(10,t_init)
                reg_verify = False
                t = last_verify_time # = 2*last_verify_time
                abc('w %s_beforerpm.aig'%f_name)
                rep_change = reparam() #must be paired with reconcile()below
                abc('w %s_afterrpm.aig'%f_name)
                result = pord_1_2(t) #main call to verification
                if result == Unsat:
                    print 'UNSAT'
                    print 'Refinement time = %s'%convert(time.time() - ref_time)
                    return Unsat
                if is_sat():
                    assert result == get_status(),'result: %d, status: %d'%(result,get_status())
                    set_cex(cex_list)
                    reconcile(rep_change)
                    abc('&r %s_gsrm.aig'%f_name)
                    PO = set_cex_po(1) #testing the & space
                    if (-1 < PO and PO < (n_pos_before-n_pos_proved)):
                        print 'Found cex in original output = %d'%cex_po()
                        print 'Refinement time = %s'%convert(time.time() - ref_time)
                        return Sat_true
                    if PO == -1:
                        return Error
                    refine_with_cex()    #change the number of equivalences
                    continue
                elif is_unsat():
                    print 'UNSAT'
                    print 'Refinement time = %s'%convert(time.time() - ref_time)
                    return Unsat
                else: #if undecided, record last verification time
                    last_verify_time = t
                    print 'UNDECIDED'
                    break
            ################### added
            else:
                break
    sims = sims_old
    print 'UNDECIDED'
    print 'Refinement time = %s'%convert(time.time() - ref_time)
##    if last_srm_po_size == initial_po_size: #essentially nothing happened. last_srm_po_size will be # POs in last srm.
    if initial_sizes == [n_pis(),n_pos(),n_latches(),n_ands()]:
        return Undecided_no_reduction #thus do not write spec file
    else: #file was changed, so some speculation happened. If we find a cex later, need to know this.
        write_file('spec')
        return Undecided_reduction

def simple_sat(t=10000):
    y = time.time()
    J = [14,2,7,9,30,31,26,5] #5 is pre_simp
    funcs = create_funcs(J,t)
    mtds =sublist(methods,J)
    fork_last(funcs,mtds)
    result = get_status()
    if result > Unsat:
        write_file('smp')
        result = verify(slps+[14,2,3,7,9,30,31,26],t)
    print 'Time for simple_sat = %0.2f'%(time.time()-y)
    return RESULT[result]     

def simple(t=10000):
    y = time.time()
##    J = [14,1,2,7,9,23,30,5] #5 is pre_simp
##    funcs = create_funcs(J,t)
##    mtds =sublist(methods,J)
##    fork_last(funcs,mtds)
##    result = get_status()
##    if result > Unsat:
##        write_file('smp')
##        J = slps+bmcs+pdrs+intrps
##        J = modify_methods(J)
##        result = verify(J,t)
    J = slps+bmcs+pdrs+intrps
    J = modify_methods(J)
    result = verify(J,t)
##    print 'Time for simple = %0.2f'%(time.time()-y)
    return RESULT[result] 


def simple_bip(t=1000):
    y = time.time()
    J = [14,1,2,30,5] #5 is pre_simp
    funcs = create_funcs(J,t)
    mtds =sublist(methods,J)
    fork_last(funcs,mtds)
    result = get_status()
    if result > Unsat:
        write_file('smp')
        result = verify(slps+[14,1,2,30],t)
    print 'Time for simple_bip = %0.2f'%(time.time()-y)
    return RESULT[result] 

def simple_prove(t=1000):
    y = time.time()
    J = [7,9,23,30,5]
    funcs = create_funcs(J,t)
    mtds =sublist(methods,J)
    fork_last(funcs,mtds)
    result = get_status()
    if result > Unsat:
        write_file('smp')
        result = verify(slps+[7,9,23,30],t)
    print 'Time for simple_prove = %0.2f'%(time.time()-y)
    return RESULT[result] 

def check_same_gsrm(f):
##    return False #disable the temporarily until can figure out why this is there
    """checks gsrm miters before and after refinement and if equal there is an error"""
    global f_name
    abc('r %s_gsrm.aig'%f)
##    ps()
    run_command('miter -c %s_gsrm_before.aig'%f)
##    ps()
    abc('&get; ,bmc -timeout=5')
    result = True #if the same
    if is_sat(): #if different
        result = False
    abc('r %s_gsrm.aig'%f)
##    ps()
    return result

def check_cex():
    """ check if the last cex still asserts one of the outputs.
    If it does then we have an error"""
    global f_name
    abc('read_status %s_before.status'%f_name)
    abc('&r %s_gsrm_before.aig'%f_name)
##    abc('&r %s_gsrm.aig'%f_name)
    run_command('testcex')
    print 'cex po = %d'%cex_po()
    return cex_po() >=0

def set_size():
    """Stores  the problem size of the current design.
    Size is defined as (PIs, POs, ANDS, FF)""" 
    global npi, npo, nands, nff, nmd
    npi = n_pis()
    npo = n_pos()
    nands = n_ands()
    nff = n_latches()
    nmd = max_bmc
    #print npi,npo,nands,nff

def check_size():
    """Assumes the problem size has been set by set_size before some operation.
    This checks if the size was changed
    Size is defined as (PIs, POs, ANDS, FF, max_bmc)
    Returns TRUE is size is the same""" 
    global npi, npo, nands, nff, nmd
    #print n_pis(),n_pos(),n_ands(),n_latches()
    result = ((npi == n_pis()) and (npo == n_pos()) and (nands == n_ands()) and (nff == n_latches()) )
    return result

def inferior_size():
    """Assumes the problem size has been set by set_size beore some operation.
    This checks if the new size is inferior (larger) to the old one 
    Size is defined as (PIs, POs, ANDS, FF)""" 
    global npi, npo, nands, nff
    result = ((npi < n_pis()) or (npo < n_pos()) or (nands < n_ands()) )
    return result

def quick_verify(n):
    """Low resource version of final_verify n = 1 means to do an initial
    simplification first. Also more time is allocated if n =1"""
    global last_verify_time
    trim()
    if n == 1:
        simplify()
        if n_latches == 0:
            return check_sat()
        trim()
        if is_sat():
            return Sat_true
    #print 'After trimming: ',
    #ps()
    set_globals()
    last_verify_time = t = max(1,.4*G_T)
    if n == 1:
        last_verify_time = t = max(1,2*G_T)
    print 'Verify time set to %d '%last_verify_time
    J = [18] + intrps+bmcs+pdrs+sims
    status = verify(J,t)
    return status

def process_status(status):
    """ if there are no FF, the problem is combinational and we still have to check if UNSAT"""
    if n_latches() == 0:
        return check_sat()
    return status
    
def get_status():
    """this simply translates the problem status encoding done by ABC
    (-1,0,1)=(undecided,SAT,UNSAT) into the status code used by our
    python code. -1,0,1 => 3,0,2
    """
    if n_latches() == 0:
        return check_sat()
    status = prob_status() #interrogates ABC for the current status of the problem.
    # 0 = SAT i.e. Sat_reg = 0 so does not have to be changed.
    if status == 1:
        status = Unsat
    if status == -1: #undecided
        status = Undecided
    return status

def reparam():
    """eliminates PIs which if used in abstraction or speculation must be restored by
    reconcile and the cex made compatible with file beforerpm"""
##    return
    rep_change = False
    n = n_pis()
##    abc('w t1.aig')
    abc('&get;,reparam -aig=%s_rpm.aig; r %s_rpm.aig'%(f_name,f_name))
##    abc('w t2.aig')
##    abc('testcex')
    if n_pis() == 0:
        print 'Number of PIs reduced to 0. Added a dummy PI'
        abc('addpi')
    nn = n_pis()
    if nn < n:
        print 'Reparam: PIs %d => %d'%(n,nn)
        rep_change = True
    return rep_change

def reconcile(rep_change):
    """used to make current cex compatible with file before reparam() was done.
    However, the cex may have come
    from extracting a single output and verifying this.
    Then the cex_po is 0 but the PO it fails could be anything.
    So testcex rectifies this."""
    global n_pos_before, n_pos_proved
##    print 'rep_change = %s'%rep_change
    if rep_change == False:
        return
    abc('&r %s_beforerpm.aig; &w tt_before.aig'%f_name)
    abc('write_status %s_after.status;write_status tt_after.status'%f_name)
    abc('&r %s_afterrpm.aig;&w tt_after.aig'%f_name)
    POa = set_cex_po(1)   #this should set cex_po() to correct PO. A 1 here means it uses &space to check
    abc('reconcile %s_beforerpm.aig %s_afterrpm.aig'%(f_name,f_name))
    # reconcile modifies cex and restores work AIG to beforerpm
    abc('write_status %s_before.status;write_status tt_before.status'%f_name)
    POb = set_cex_po()
    if POa != POb:
        abc('&r %s_beforerpm.aig; &w tt_before.aig'%f_name)
        abc('&r %s_afterrpm.aig; &w tt_after.aig'%f_name)
        print 'cex PO afterrpm = %d not = cex PO beforerpm = %d'%(POa,POb)
    assert POa > -1, 'cex did not assert any output'

def reconcile_all(lst, rep_change):
    """reconciles the list of cex's"""
    global f_name, n_pos_before, n_pos_proved
    if rep_change == False:
        return lst
    list = []
    for j in range(len(lst)):
        cx = lst[j]
        if cx == None:
            continue
        cex_put(cx)
        reconcile(rep_change)
        list = list + [cex_get()]
    return list
    

def try_rpm():
    """rpm is a cheap way of doing reparameterization and is an abstraction method, so may introduce false cex's.
    It finds a minimum cut between the PIs and the main sequential logic and replaces this cut by free inputs.
    A quick BMC is then done, and if no cex is found, we assume the abstraction is valid. Otherwise we revert back
    to the original problem before rpm was tried."""
    global x_factor
    if n_ands() > 30000:
        return
    set_globals()
    pis_before = n_pis()
    abc('w %s_savetemp.aig'%f_name)
    abc('rpm')
    result = 0
    if n_pis() < .5*pis_before:
        bmc_before = bmc_depth()
        #print 'running quick bmc to see if rpm is OK'
        t = max(1,.1*G_T)
        #abc('bmc3 -C %d, -T %f'%(.1*G_C, t))
        abc('&get;,bmc -vt=%f'%t)
        if is_sat(): #rpm made it sat by bmc test, so undo rpm
            abc('r %s_savetemp.aig'%f_name)
        else:
            trim()
            print 'WARNING: rpm reduced PIs to %d. May make SAT.'%n_pis()
            result = 1
    else:
        abc('r %s_savetemp.aig'%f_name)
    return result
            
def verify(J,t):
    """This method is used for finding a cex during refinement, but can also
    be used for proving the property. t is the maximum time to be used by
    each engine J is the list of methods to run in parallel. See FUNCS for list"""
    global x_factor, final_verify_time, last_verify_time, methods
    set_globals()
    t = int(max(1,t))
    J = modify_methods(J)
    mtds = sublist(methods,J)
    print mtds
    #print J,t
    F = create_funcs(J,t)
    (m,result) = fork_break(F,mtds,'US') #FORK here
    assert result == get_status(),'result: %d, status: %d'%(result,get_status())
    return result

def dsat_all(t=100,c=100000):
    print 't=%d,c=%d'%(t,c)
    N = n_pos()
    abc('&get')
    J = range(N)
    ttt = time.time()
    J.reverse()
    abc('w %s_temp.aig'%f_name)
    for j in J:
        tt = time.time()
        abc('r %s_temp.aig'%f_name)
        run_command('cone -O %d; dc2; dsat -C %d'%(j,c))
        if is_unsat():
            print 'Output %d is %s'%(j,RESULT[2]),
        else:
            print 'Output %d is %s'%(j,RESULT[3]),
        T = time.time() -tt
        print 'time = %0.2f'%T
        if time.time() - tt > t:
            break
    print 'Total time = %0.2f'%(time.time() - ttt)
            
def check_sat():
    """This is called if all the FF have disappeared, but there is still some logic left. In this case,
    the remaining logic may be UNSAT, which is usually the case, but this has to be proved. The ABC command 'dsat' is used fro combinational problems"""
    if not n_latches() == 0:
        print 'circuit is not combinational'
        return Undecided
##    print 'Circuit is combinational - checking with dsat'
    abc('&get') #save the current circuit
    abc('orpos;dsat -C %d'%G_C)
    if is_sat():
        abc('&put')
        if n_pos() == 1:
            return Sat_true
        else:
            return Undecided_no_reduction #some POs could be unsat.
    elif is_unsat():
        return Unsat
    else:
        abc('&put') #restore
        return Undecided_no_reduction

def try_era(s):
    """era is explicit state enumeration that ABC has. It only works if the number of PIs is small,
    but there are cases where it works and nothing else does"""
    if n_pis() > 12:
        return
    cmd = '&get;&era -mv -S %d;&put'%s
    print 'Running %s'%cmd
    run_command(cmd)

def try_induction(C):
    """Sometimes proving the property directly using induction works but not very often.
    For 'ind' to work, it must have only 1 output, so all outputs are or'ed together temporarily"""
    return Undecided_reduction
    print '\n***Running induction'
    abc('w %s_temp.aig'%f_name)
    abc('orpos; ind -uv -C %d -F 10'%C)
    abc('r %s_savetemp.aig'%f_name)
    status = prob_status()
    if not status == 1:
        return Undecided_reduction
    print 'Induction succeeded'
    return Unsat

##def final_verify_recur(K):
##    """During prove we make backups as we go. These backups have increasing abstractions done, which can cause
##    non-verification by allowing false counterexamples. If an abstraction fails with a cex, we can back up to
##    the previous design before the last abstraction and try to proceed from there. K is the backup number we
##    start with and this decreases as the backups fails. For each backup, we just try final_verify.
##    If ever we back up to 0, which is the backup just after simplify, we then try speculate on this. This often works
##    well if the problem is a SEC problem where there are a lot of equivalences across the two designs."""
##    global last_verify_time
##    #print 'Proving final_verify_recur(%d)'%K
##    last_verify_time = 2*last_verify_time
##    print 'Verify time increased to %d'%last_verify_time
##    for j in range(K):
##        i = K-(j+1)
##        abc('r %s_backup_%d.aig'%(initial_f_name,i))
##        if ((i == 0) or (i ==2)): #don't try final verify on original last one
##            status = prob_status()
##            break
##        print '\nVerifying backup number %d:'%i,
##        #abc('r %s_backup_%d.aig'%(initial_f_name,i))
##        ps()
##        #J = [18,0,1,2,3,7,14]
##        J = slps+sims+intrps+bmcs+pdrs
##        t = last_verify_time
##        status = verify(J,t)
##        if status >= Unsat:
##            return status
##        if  i > 0:
##            print 'SAT returned, Running less abstract backup'
##            continue
##        break
##    if ((i == 0) and (status > Unsat) and (n_ands() > 0)):
##        print '\n***Running speculate on initial backup number %d:'%i,
##        abc('r %s_backup_%d.aig'%(initial_f_name,i))
##        ps()
##        if n_ands() < 20000:
####            pre_simp()
##            status = speculate()
##            if ((status <= Unsat) or (status == Error)):
##                return status
##        #J = [18,0,1,2,3,7,14]
##        J = slps+sims+intrps+bmcs+pdrs
##        t = 2*last_verify_time
##        print 'Verify time increased to %d'%last_verify_time
##        status = verify(J,t)
##    if status == Unsat:
##        return status
##    else:
##        return Undecided_reduction
        
def smp():
    abc('smp')
    write_file('smp')

def dprove():
    abc('dprove -cbjupr')

def trim():
    global trim_allowed
    if not trim_allowed:
        return
##    abc('trm;addpi')
    reparam()
##    print 'exiting trim'

def prs(x=True):
    global trim_allowed
    """ If x is set to False, no reparameterization will be done in pre_simp"""
    trim_allowed = x
    print 'trim_allowed = ',trim_allowed
    y = time.clock()
    pre_simp()
    print 'Time = %s'%convert(time.clock() - y)
    write_file('smp')

def pre_simp():
    """This uses a set of simplification algorithms which preprocesses a design.
    Includes forward retiming, quick simp, signal correspondence with constraints, trimming away
    PIs, and strong simplify"""
    global trim_allowed, temp_dec
    tt = time.time()
    set_globals()
    abc('&get; &scl; &put')
    if (n_ands() > 200000 or n_latches() > 50000 or n_pis() > 40000):
        print 'Problem too large, simplification skipped'
        return 'Undecided'
    if ((n_ands() > 0) or (n_latches()>0)):
        trim()
##        ps()
    if n_latches() == 0:
        return check_sat()
##    if n_ands()<70000:
##        abs('scorr -C 5000')
    best_fwrd_min([10,11])
    ps()
    status = try_scorr_constr()
    if ((n_ands() > 0) or (n_latches()>0)):
        trim()
    if n_latches() == 0:
        return check_sat()
    status = process_status(status)
    if status <= Unsat:
        return status
    simplify()
    print 'Simplify: ',
    ps()
    if n_latches() == 0:
        return check_sat()
    if trim_allowed:
        t = min(15,.3*G_T)
        if not '_smp' in f_name: #try this only once on a design
            try_temps(15)
            if n_latches() == 0:
                return check_sat()
            try_phase()
            if n_latches() == 0:
                return check_sat()
        if ((n_ands() > 0) or (n_latches()>0)):
            trim()
    status = process_status(status)
    print 'Simplification time = %0.2f'%(time.time()-tt)
    return status

def pre_simp2():
    """This uses a set of simplification algorithms which preprocesses a design.
    Includes forward retiming, quick simp, signal correspondence with constraints, trimming away
    PIs, and strong simplify"""
    global trim_allowed, temp_dec
    tt = time.time()
    set_globals()
    abc('&get; &scl; &put')
    if (n_ands() > 200000 or n_latches() > 50000 or n_pis() > 40000):
        print 'Problem too large, simplification skipped'
        return 'Undecided'
    if ((n_ands() > 0) or (n_latches()>0)):
        trim()
##        ps()
    if n_latches() == 0:
        return check_sat()
    if n_ands()<70000:
        abc('scorr -C 5000')
    best_fwrd_min([10,11])
    ps()
    status = try_scorr_constr()
    if ((n_ands() > 0) or (n_latches()>0)):
        trim()
    if n_latches() == 0:
        return check_sat()
    status = process_status(status)
    if status <= Unsat:
        return status
    simplify()
    print 'Simplify: ',
    ps()
    if n_latches() == 0:
        return check_sat()
    if trim_allowed:
        t = min(15,.3*G_T)
        if not '_smp' in f_name: #try this only once on a design
            try_temps(15)
            if n_latches() == 0:
                return check_sat()
            try_phase()
            if n_latches() == 0:
                return check_sat()
        if ((n_ands() > 0) or (n_latches()>0)):
            trim()
    status = process_status(status)
    print 'Simplification time = %0.2f'%(time.time()-tt)
    return status


def try_scorr_constr():
    set_size()
    abc('w %s_savetemp.aig'%f_name)
    status = scorr_constr()
    if inferior_size():
        abc('r %s_savetemp.aig'%f_name)
    return status

def factors(n):
    l = [1,]
    nn = n
    while n > 1:
        for i in (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53):
            if not i <nn:
                break
            if n%i == 0:
                l = l + [i,]
                n = n/i
        if not n == 1:
            l = l + [n,]
        break
    return sorted(l)

def select(x,y):
    z = []
    for i in range(len(x)):
        if x[i]:
            z = z + [y[i],]
    return z
    
def ok_phases(n):
    """ only try those where the resulting n_ands does not exceed 60000"""
    f = factors(n)
    sp = subproducts(f)
    s = map(lambda m:m*n_ands()< 90000,sp)
    z = select(s,sp)
    return z

def subproducts(ll):
    ss = (product(ll),)
    #print ll
    n = len(ll)
    if n == 1:
        return ss
    for i in range(n):
        kk = drop(i,ll)
        #print kk
        ss = ss+(product(kk),)
        #print ss
        ss = ss+subproducts(kk)
        #print ss
    result =tuple(set(ss))
    #result.sort()
    return tuple(sorted(result))

def product(ll):
    n = len(ll)
    p = 1
    if n == 1:
        return ll[0]
    for i in range(n):
        p = p*ll[i]
    return p

def drop(i,ll):
    return ll[:i]+ll[i+1:]

def try_phase():
    """Tries phase abstraction. ABC returns the maximum clock phase it found using n_phases.
    Then unnrolling is tried up to that phase and the unrolled model is quickly
    simplified (with retiming to see if there is a significant reduction.
    If not, then revert back to original"""
    global init_simp
    trim()
    n = n_phases()
##    if ((n == 1) or (n_ands() > 45000) or init_simp == 0):
    if ((n == 1) or (n_ands() > 45000)):
        return
##    init_simp = 0
    print 'Trying phase abstraction - Max phase = %d'%n,
    abc('w %s_phase_temp.aig'%f_name)
    na = n_ands()
    nl = n_latches()
    ni = n_pis()
    no = n_pos()
    z = ok_phases(n)
    print z,
    if len(z) == 1:
        return
    #p = choose_phase()
    p = z[1]
    abc('phase -F %d'%p)
    if no == n_pos(): #nothing happened because p is not mod period
        print 'Phase %d is incompatible'%p
        abc('r %s_phase_temp.aig'%f_name)
        if len(z)< 3:
            return
        else:
            p = z[2]
            #print 'Trying phase = %d:  '%p,
            abc('phase -F %d'%p)
            if no == n_pos(): #nothing happened because p is not mod period
                print 'Phase %d is incompatible'%p
                abc('r %s_phase_temp.aig'%f_name)
                return
    print 'Simplifying with %d phases: => '%p,
    simplify()
    trim()
    ps()
    cost = rel_cost([ni,nl,na])
    print 'New relative cost = %f'%(cost)
    if cost <  -.01:
        abc('w %s_phase_temp.aig'%f_name)
        if ((n_latches() == 0) or (n_ands() == 0)):
            return
        if n_phases() == 1: #this bombs out if no latches
            return
        else:
            try_phase()
            return
    elif len(z)>2: #Try the next eligible phase.
        abc('r %s_phase_temp.aig'%f_name)
        if p == z[2]: #already tried this
            return
        p = z[2]
        print 'Trying phase = %d: => '%p,
        abc('phase -F %d'%p)
        if no == n_pos(): #nothing happened because p is not mod period
            print 'Phase = %d is not compatible'%p
            return
        ps()
        print 'Simplify with %d phases: '%p,
        simplify()
        trim()
        ps()
        cost = rel_cost([ni,nl,na])
        print 'New relative cost = %f'%(cost)
        if cost < -.01:
            print 'Phase abstraction with %d phases obtained:'%p,
            print_circuit_stats()
            abc('w %s_phase_temp.aig'%f_name)
            if ((n_latches() == 0) or (n_ands() == 0)):
                return
            if n_phases() == 1: # this bombs out if no latches
                return
            else:
                try_phase()
                return
    abc('r %s_phase_temp.aig'%f_name)
    return

def try_temp(t=15):
    btime = time.clock()
    trim()
    print'Trying temporal decomposition - for max %s sec. '%convert(t),
    abc('w %s_best.aig'%f_name)
    ni = n_pis()
    nl = n_latches()
    na = n_ands()
    best = [ni,nl,na]
    F = create_funcs([18],t) #create a timer function
##    F = F + [eval('(pyabc_split.defer(abc)("tempor -s; trm; scr; trm; tempor; trm; scr; trm"))')]
    F = F + [eval('(pyabc_split.defer(abc)("tempor -s; &get; &trim -o; &put; scr; &get; &trim -o; &put; tempor; &get; &trim -o; &put; scr; &get; &trim -o; &put"))')]    
    for i,res in pyabc_split.abc_split_all(F):
        break
    cost = rel_cost(best)
    print 'cost = %0.2f'%cost
    if cost < .01:
        ps()
        return
    else:
        abc('r %s_best.aig'%f_name)

def try_temps(t=15):
    best = (n_pis(),n_latches(),n_ands())
    while True:
        try_temp(t)
        if ((best == (n_pis(),n_latches(),n_ands())) or n_ands() > .9 * best[2] ):
            break
        elif n_latches() == 0:
            break
        else:
            best = (n_pis(),n_latches(),n_ands())
        

def rel_cost_t(J):
    """ weighted relative costs versus previous stats."""
    if (n_latches() == 0 and J[1]>0):
        return -10
    nli = J[0]+J[1]
    na = J[2]
    if ((nli == 0) or (na == 0)):
        return 100
    nri = n_real_inputs()
    #ri = (float(nri)-float(ni))/float(ni)
    rli = (float(n_latches()+nri)-float(nli))/float(nli)
    ra = (float(n_ands())-float(na))/float(na)
    cost = 10*rli + .5*ra
    return cost    

def rel_cost(J):
    """ weighted relative costs versus previous stats."""
    global f_name
    if (n_latches() == 0 and J[1]>0):
        return -10
    nri = n_real_inputs()
    ni = J[0]
    nl = J[1]
    na = J[2]
    if (ni == 0 or na == 0 or nl == 0):
        return 100
    ri = (float(nri)-float(ni))/float(ni)
    rl = (float(n_latches())-float(nl))/float(nl)
    ra = (float(n_ands())-float(na))/float(na)
    cost = 1*ri + 5*rl + .2*ra
##    print 'Relative cost = %0.2f'%cost
    return cost

def best_fwrd_min(J):
    global f_name, methods
    mtds = sublist(methods,J)
    F = create_funcs(J,0)
    (m,result) = fork_best(F,mtds) #FORK here
    print '%s: '%mtds[m],
    
def try_forward():
    """Attempts most forward retiming, and latch correspondence there. If attempt fails to help simplify, then we revert back to the original design
    This can be effective for equivalence checking problems where synthesis used retiming"""
    abc('w %s_savetemp.aig'%f_name)
    if n_ands() < 30000:
        abc('dr')
        abc('lcorr')
        nl = n_latches()
        na = n_ands()
        abc('w %s_savetemp0.aig'%f_name)
        abc('r %s_savetemp.aig'%f_name) 
        abc('dr -m')
        abc('lcorr')
        abc('dr')
        if ((n_latches() <= nl) and (n_ands() < na)):
            print 'Forward retiming reduced size to: ',
            print_circuit_stats()
            return
        else:
            abc('r %s_savetemp0.aig'%f_name)
            return
    return

def quick_simp():
    """A few quick ways to simplify a problem before more expensive methods are applied.
    Uses & commands if problem is large. These commands use the new circuit based SAT solver"""
    na = n_ands()
    if na < 60000:
        abc('scl -m;lcorr;drw')
    else:
        abc('&get;&scl;&lcorr;&put;drw')
    print 'Using quick simplification',
    status = process_status(get_status())
    if status <= Unsat:
        result = RESULT[status]
    else:
        ps()
##        write_file('smp')
####            K_backup = K = K+1
        result = 'UNDECIDED'
    return result

def scorr_constr():
    """Extracts implicit constraints and uses them in signal correspondence
    Constraints that are found are folded back when done"""
    na = max(1,n_ands())
    n_pos_before = n_pos()
    if ((na > 40000) or n_pos()>1):
        return Undecided_no_reduction
    abc('w %s_savetemp.aig'%f_name)
    na = max(1,n_ands())
##    f = 1
    f = 18000/na  #**** THIS can create a bug 10/15/11
    f = min(f,4)
    f = max(1,f)
    if n_ands() > 18000:
        cmd = 'unfold -s -F 2'
    else:
        cmd = 'unfold -F %d -C 5000'%f
    abc(cmd)
    if n_pos() == n_pos_before:
        print 'No constraints found'
        return Undecided_no_reduction
    if (n_ands() > na): #no constraints found
        abc('r %s_savetemp.aig'%f_name)
        return Undecided_no_reduction
    na = max(1,n_ands())
    f = 1
    print 'Number of constraints = %d'%((n_pos() - n_pos_before))
    abc('scorr -c -F %d'%f)
    abc('fold')
    trim()
    print 'Constrained simplification: ',
    ps()
    return Undecided_no_reduction

def try_scorr_c(f):
    """ Trying multiple frames because current version has a bug."""
    set_globals()
    abc('unfold -F %d'%f)
    abc('scorr -c -F %d'%f)
    abc('fold')
    t = max(1,.1*G_T)
    abc('&get;,bmc3 -vt=%f'%t)
    if is_sat(): 
        return 0
    else:
        trim()
        return 1
    

def input_x_factor():
    """Sets the global x_factor according to user input"""
    global x_factor, xfi
    print 'Type in x_factor:',
    xfi = x_factor = input()
    print 'x_factor set to %f'%x_factor


def prove(a):
    """Proves all the outputs together. If ever an abstraction
        was done then if SAT is returned,
        we make RESULT return "undecided".
        is a == 0 do smp and abs first
        If a == 1 do smp and spec first 
        if a == 2 do quick simplification instead of full simplification, then abs first, spec second"""
    global x_factor,xfi,f_name, last_verify_time,K_backup, t_init, sec_options, spec_found_cex
    spec_first = False
    max_bmc = -1
    abs_found_cex_after_spec = spec_found_cex_after_abs = False
    if not '_smp' in f_name: #if already simplified, then don't do again
        if a == 2 : #do quick simplification
            result = quick_simp() #does not write 'smp' file
##            print result
        else :
            result = prove_part_1() #do full simplification here
        if ((result == 'SAT') or (result == 'UNSAT')):
            return result
    if a == 1:
        spec_first = True
    t_init = 2
    abs_found_cex_before_spec = spec_found_cex_before_abs = False
##    First phase
    if spec_first:
        result = prove_part_3() #speculation done here first
    else:
        result = prove_part_2() #abstraction done here first
    if ((result == 'SAT') or (result == 'UNSAT')):
        return result
##    Second phase
    if spec_first: #did spec already in first phase
        t_init = 2
        result = prove_part_2() #abstraction done here second
        if result == 'SAT':
            abs_found_cex_after_spec = True
    else:
        result = prove_part_3()  #speculation done here second
        if result == 'SAT':
            spec_found_cex_after_abs = True
    if result == 'UNSAT': 
        return result
    status = get_status()
    if result == 'ERROR':
        status = Error
    if ('_abs' in f_name and spec_found_cex_after_abs): #spec file should not have been written in speculate
        f_name = revert(f_name,1) #it should be as if we never did abstraction.
        print 'f_name = %s'%f_name
        abc('r %s.aig'%f_name) #restore previous
        t_init = 2
        if not '_rev' in f_name:
            print 'proving speculation first'
            write_file('rev') #maybe can get by with just changing f_name
            print 'f_name = %s'%f_name
            result = prove(1) #1 here means do smp and then spec 
            if ((result == 'SAT') or (result == 'UNSAT')):
                return result
    elif ('_spec' in f_name and abs_found_cex_after_spec): #abs file should not have been written in abstract
        f_name = revert(f_name,1) #it should be as if we never did speculation.
        abc('r %s.aig'%f_name) #restore previous 
        t_init = 2
        if not '_rev' in f_name:
            print 'proving abstraction first'
            write_file('rev') #maybe can get by with just changing f_name
            result = prove(0)
            if ((result == 'SAT') or (result == 'UNSAT')):
                return result
    else:
        return 'UNDECIDED'

def prove_part_1():
    global x_factor,xfi,f_name, last_verify_time,K_backup
    print 'Initial: ',
    ps()
    x_factor = xfi
    print '\n***Running pre_simp'
    set_globals()
    if n_latches() > 0:
        status = run_par_simplify()
    else:
        status = check_sat()
    if ((status <= Unsat) or (n_latches() == 0)):
        return RESULT[status]
    trim()
    write_file('smp') #need to check that this was not written in pre_simp
    set_globals()
    return RESULT[status]

def run_par_simplify():
    set_globals()
    t = 1000
    funcs = [eval('(pyabc_split.defer(pre_simp)())')]
    J = pdrs+bmcs+intrps
    J = modify_methods(J,1)
    funcs = create_funcs(J,t)+ funcs #important that pre_simp goes last
    mtds =sublist(methods,J) + ['pre_simp']
    fork_last(funcs,mtds)
    status = get_status()
    return status
    
def prove_part_2(ratio=.75):
    """does the abstraction part of prove"""
    global x_factor,xfi,f_name, last_verify_time,K_backup, trim_allowed,ifbip
    print'\n***Running abstract'
##    print 'ifbip = %d'%ifbip
    status = abstract(ifbip) #ABSTRACTION done here
    status = process_status(status)
    print 'abstract done, status is %d'%status
    result = RESULT[status]
    if status < Unsat:
        print 'CEX in frame %d'%cex_frame()
        return result #if we found a cex we do not want to trim.
    trim() 
    return result
    
def prove_part_3():
    """does the speculation part of prove"""
    global x_factor,xfi,f_name, last_verify_time,init_initial_f_name
    global max_bmc, sec_options
    if ((n_ands() > 36000) and sec_options == ''):
        sec_options = 'g'
        print 'sec_options set to "g"'
    print '\n***Running speculate'
    status = speculate() #SPECULATION done here
    status = process_status(status)
    print 'speculate done, status is %d'%status
    result = RESULT[status]
    if status < Unsat:
        print 'CEX in frame %d'%cex_frame()
        return result
    trim() #if cex is found we doo not want to trim.
    return result

def prove_all(dir,t):
    """Prove all aig files in this directory using super_prove and record the results in results.txt
    Not called from any subroutine
    """
##    t = 1000 #This is the timeoout value
    xtime = time.time()
##    dir = main.list_aig('')
    results = []
    f =open('results_%d.txt'%len(dir), 'w')
    for name in dir:
        read_file_quiet(name)
        print '\n         **** %s:'%name,
        ps()
        F = create_funcs([18,6],t) #create timer function as i = 0 Here is the timer
        for i,res in pyabc_split.abc_split_all(F):
            break
        tt = time.time()
        if i == 0:
            res = 'Timeout'
        str = '%s: %s, time = %s'%(name,res,convert(tt-xtime))
        if res == 'SAT':
            str = str + ', cex_frame = %d'%cex_frame()
        str = str +'\n'
        f.write(str)
        f.flush()
        results = results + ['%s: %s, time = %s'%(name,res,convert(tt-xtime))]
        xtime = tt
##    print results
    f.close()
    return results  

def remove_pos(lst):
    """Takes a list of pairs where the first part of a pair is the PO number and
    the second is the result 1 = disproved, 2 = proved, 3 = unresolved. Then removes
    the proved and disproved outputs and returns the aig with the unresolved
    outputs"""
    proved = disproved = unresolved = []
    for j in range(len(lst)):
        jj = lst[j]
        if jj[1] == 2:
            proved = proved + [jj[0]]
        if (jj[1] == 1 or (jj[1] == 0)):
            disproved = disproved +[jj[0]]
        if jj[1] > 2:
            unresolved = unresolved +[jj[0]]
    print '%d outputs proved'%len(proved)
    if not proved == []:
        if ((max(proved)>n_pos()-1) or min(proved)< 0):
            print proved
        remove(proved)
            

#functions for proving multiple outputs in parallel
#__________________________________________________

def prove_only(j):
    """ extract the jth output and try to prove it"""
    global max_bmc, init_initial_f_name, initial_f_name, f_name,x
    #abc('w %s__xsavetemp.aig'%f_name)
    extract(j,j)
    set_globals()
    ps()
    print '\nProving output %d'%(j)
    f_name = f_name + '_%d'%j
    result = prove_1()
    #abc('r %s__xsavetemp.aig'%f_name)
    if result == 'UNSAT':
        print '********  PROVED OUTPUT %d  ******** '%(j)
        return Unsat
    if result == 'SAT':
        print '********  DISPROVED OUTPUT %d  ******** '%(j)
        return Sat
    else:
        print '********  UNDECIDED on OUTPUT %d  ******** '%(j)
        return Undecided

def verify_only(j,t):
    """ extract the jth output and try to prove it"""
    global max_bmc, init_initial_f_name, initial_f_name, f_name,x, reachs, last_cex, last_winner, methods
##    ps()
##    print 'Output = %d'%j
    extract(j,j)
##    ps()
    set_globals()
    if n_latches() == 0:
        result = check_sat()
    else:
        f_name = f_name + '_%d'%j
        # make it so that jabc is not used here
        reachs_old = reachs
        reachs = reachs[1:] #just remove jabc from this.
        res = verify(slps+sims+pdrs+bmcs+intrps,t) #keep the number running at the same time as small as possible.
##        res = verify(sims+pdrs+bmcs+intrps,t) #keep the number running at the same time as small as possible.
        reachs = reachs_old
        result = get_status()
        assert res == result,'result: %d, status: %d'%(res,get_status())
    if result > Unsat:
##        print result
##        print '******* %d is undecided ***********'%j
        return result
    elif result == Unsat:
##        print '******** PROVED OUTPUT %d  ******** '%(j)
        return result
    elif ((result < Unsat) and (not result == None)):
        print '******** %s DISPROVED OUTPUT %d  ******** '%(last_cex,j)
##        print ('writing %d.status'%j), result, get_status()
        abc('write_status %d.status'%j)
        last_winner = last_cex
        return result
    else:
        print '****** %d result is %d'%(j,result) 
        return result

def verify_range(j,k,t):
    """ extract the jth thru kth output and try to prove their OR"""
    global max_bmc, init_initial_f_name, initial_f_name, f_name,x, reachs, last_cex, last_winner, methods
    extract(j,k)
    abc('orpos')
    set_globals()
    if n_latches() == 0:
        result = check_sat()
    else:
        f_name = f_name + '_%d'%j
        # make it so that jabc is not used here
        reachs_old = reachs
        reachs = reachs[1:] #just remove jabc from this.
        res = verify(sims+pdrs+bmcs+intrps,t) #keep the number running at the sme time as small as possible.
        reachs = reachs_old
        result = get_status()
        assert res == result,'result: %d, status: %d'%(res,get_status())
    if result > Unsat:
##        print result
##        print '******* %d is undecided ***********'%j
        return result
    elif result == Unsat:
##        print '******** PROVED OUTPUT %d  ******** '%(j)
        return result
    elif ((result < Unsat) and (not result == None)):
        print '******** %s DISPROVED OUTPUT %d  ******** '%(last_cex,j)
##        print ('writing %d.status'%j), result, get_status()
        abc('write_status %d.status'%j)
        last_winner = last_cex
        return result
    else:
        print '****** %d result is %d'%(j,result) 
        return result

def prove_n_par(n,j):
    """prove n outputs in parallel starting at j"""
    F = []
    for i in range(n):
        F = F + [eval('(pyabc_split.defer(prove_only)(%s))'%(j+i))]
    #print S
    #F = eval(S)
    result = []
    print 'Proving outputs %d thru %d in parallel'%(j,j+n-1)
    for i,res in pyabc_split.abc_split_all(F):
        result = result +[(j+i,res)]
    #print result
    return result

def prove_pos_par(t,BREAK):
    """Prove all outputs in parallel and break on BREAK"""
    return run_parallel([],t,BREAK)

def prove_pos_par0(n):
    """ Group n POs grouped and prove in parallel until all outputs have been proved"""
    f_name = initial_f_name
    abc('w %s__xsavetemp.aig'%f_name)
    result = []
    j = 0
    N = n_pos()
    while j < N-n:
        abc('r %s__xsavetemp.aig'%f_name)
        result = result + prove_n_par(n,j)
        j = j+n
    if N > j:
        result = result + prove_n_par(N-j,j)
    abc('r %s__xsavetemp.aig'%initial_f_name)
    ps()
##    print result
    remove_pos(result)
    write_file('group')
    return

def prop_decomp():
    """decompose a single property into multiple ones (only for initial single output),
    by finding single and double literal primes of the outputs."""
    if n_pos()>1:
        return
    run_command('outdec -v -L 2')
    if n_pos()>1:
        ps()


def distribute(N,div):
    """
    we are going to verify outputs in groups
    """
    n = N/div
    rem = N - (div * (N/div))
    result = []
    for j in range(div):
        if rem >0:
            result = result +[n+1]
            rem = rem -1
        else:
            result = result + [n]
    return result    

####def find_cex_par(tt):
####    """prove n outputs at once and quit at first cex. Otherwise if no cex found return aig
####    with the unproved outputs"""
####    global trim_allowed,last_winner, last_cex, n_pos_before, t_init, j_last, sweep_time
####    b_time = time.time() #Wall clock time
####    n = n_pos()
####    l=remove_const_pos()
####    N = n_pos()
####    full_time = all_proc = False
####    print 'Number of POs: %d => %d'%(n,N)
####    if N == 0:
####        return Unsat
######    inc = 5  #******* increment for grouping for sweep set here *************
######    inc = min(12,max(inc, int(.1*N)))
####    inc = 1+N/100
######    if N <1.5*inc: # if near the increment for grouping try to get it below.
######        prove_all_ind()
######        N = n_pos()
####    if inc == 1:
####        prove_all_ind()
####        N = n_pos()
####    T = int(tt) #this is the total time to be taken in final verification run before quitting speculation
######    if inc == 10:
######        t_init = 10
######    t = max(t_init/2,T/20)
######    if N <= inc:
######        t = T
######    print "inc = %d, Sweep time = %s, j_group = %d"%(inc,convert(t),j_last)
####    t = sweep_time/2 #start sweeping at last time where cex was found.
######    it used to be t = 1 here but it did not make sense although seemed to work.
######    inc = 2
####    while True: #poor man's concurrency
####        N = n_pos()
####        if N == 0:
####            return Unsat
####        #sweep_time controls so that when sweep starts after a cex, it starts at the last sweep time
####        t = max(2,2*t) #double sweep time
####        if t > .75*T:
####            t = T
####            full_time = True
####        if ((N <= inc) or (N < 13)):
####            t = sweep_time = T
####            full_time = True
####            inc = 1
######            sweep_time = 2*sweep_time
####        if not t == T:
####            t= sweep_time = max(t,sweep_time)
######            t = sweep_time
######new heuristic
####        if (all_proc and sweep_time > 8): #stop poor man's concurrency and jump to full time.
####            t = sweep_time = T
####            full_time - True #this might be used to stop speculation when t = T and the last sweep
######                           found no cex and we do not prove Unsat on an output
####        abc('w %s__ysavetemp.aig'%f_name)
####        ps()
####        if N < 50:
####            inc = 1
####        print "inc = %d, Sweep time = %s, j_last = %d"%(inc,convert(t),j_last)
####        F = []
######        G = []
####        #make new lambda functions since after the last pass some of the functions may have been proved and eliminated.
####        for i in range(N):
####            F = F + [eval('(pyabc_split.defer(verify_only)(%d,%s))'%(i,convert(T)))] #make time large and let sleep timer control timeouts
######            G = G + [range(i,i+1)]
####        ######
####        result = []
####        outcome = ''
####        N = len(F)
####        rng = range(1+(N-1)/inc)
####        rng = rng[j_last:]+rng[:j_last] #pick up in range where last found cex.
######        print 'rng = ',
######        print rng
####        k = -1
####        bb_time = time.time()
####        for j in rng:
####            k = k+1 #keeps track of how many groups we have processed.
####            j_last = j
####            J = j*inc
####            JJ = J+inc
####            JJ = min(N,JJ)
####            if J == JJ-1:
####                print 'Function = %d '%J,
####            else:
####                print 'Functions = [%d,%d]'%(J,JJ-1)
####            Fj = create_funcs([18],t+1) #create timer function as i = 0 Here is the timer
####            Fj = Fj + F[J:JJ]
####            count = 0
####            fj_time = time.time()
####            abc('r %s__ysavetemp.aig'%f_name) #important need to restore aig here so the F refers to right thing when doing verify_only.
######                                             # because verify_only changes the aig.
######            ps()
####            for i,res in pyabc_split.abc_split_all(Fj):
####                count = count+1
####                Ji = J+i-1 #gives output number
####                if ((res == 0) or (res == 1)):
####                    abc('read_status %d.status'%Ji)
####                    res = get_status()
####                    outcome = 'CEX: Frame = %d, PO = %d, Time = %s'%(cex_frame(),Ji,convert((time.time() - fj_time)))
####                    break
####                if i == 0: #sleep timer expired
####                    outcome = '*** Time expired in %s sec. Next group = %d to %d ***'%(convert(time.time() - fj_time),JJ,min(N,JJ+inc))
####                    break
####                elif res == None: #this should not happen
####                    print res
####                    print Ji,RESULT[res],
####                else: # output Ji was proved
####                    result = result + [[Ji,res]]
####                    if count >= inc:
####                        outcome = '--- all group processed without cex ---'
####                        all_proc = True
####                        break
####                    continue #this can only happen if inc > 1
####            # end of for i loop
####            if ((res < Unsat) and (not res == None)): 
####                break
####            else:
####                continue # continue j loop
####        #end of for j loop
####        if k < len(rng):      
####            t_init = t/2 #next time start with this time.
####        else:
####            j_last = j_last+1 #this was last j and we did not find cex, so start at next group
####        print outcome + ' => ' ,
####        if ((res < Unsat) and (not res == None)):
####            t_init = t/2
####            abc('read_status %d.status'%Ji) #make sure we got the right status file.
####            #actually if doing abstraction we could remove proved outputs now, but we do not. -**inefficiency**
####            return res
####        else: #This implies that no outputs were disproved. Thus can remove proved outputs.
####            abc('r %s__ysavetemp.aig'%f_name) #restore original aig
####            if not result == []:
####                res = []
####                for j in range(len(result)):
####                    k = result[j]
####                    if k[1] == 2:
####                        res = res + [k[0]]
######                print res
######                result = mapp(res,G)
####                result = res
######                print result
####                remove(result) #remove the outputs that were proved UNSAT.
####                #This is OK for both abstract and speculate
####                print 'Number of POs reduced to %d'%n_pos()
####                if n_pos() == 0:
####                    return Unsat
####            if t>=T:
####                return Undecided
####            else:
####                continue
####    return Undecided

####def remap_pos():
####    """ maintains a map of current outputs to original outputs"""
####    global po_map
####    k = j = 0
####    new = []
####    assert n_pos() == len(po_map), 'length of po_map, %d, and current # POs, %d, don"t agree'%(len(po_map),n_pos())
####    for j in range(len(po_map)):
####        N = n_pos()
####        abc('removepo -N %d'%k) # this removes the output if it is 0 driven
####        if n_pos() == N:
####            new = new + [po_map[j]]
####            k = k+1
####    if len(new) < len(po_map):
######        print 'New map = ',
######        print new
####        po_map = new

####def prove_mapped():
####    """
####    assumes that srm is in workspace and takes the unsolved outputs and proves
####    them by using proved outputs as constraints.
####    """
####    global po_map
######    print po_map
####    po_map.sort() #make sure mapped outputs are in order
####    for j in po_map: #put unsolved outputs first
####        run_command('swappos -N %d'%j)
####        print j
####    N = n_pos()
####    assert N > len(po_map), 'n_pos = %d, len(po_map) = %d'%(N, len(po_map))
####    run_command('constr -N %d'%(N-len(po_map))) #make the other outputs constraints
####    run_command('fold') #fold constraints into remaining outputs.
####    ps()
####    prove_all_mtds(100)
    
####def mapp(R,G):
####    result = []
####    for j in range(len(R)):
####        result = result + G[R[j]]
####    return result
        
#_______________________________________        

    
####def prove_g_pos_split():
####    """like prove_g_pos but quits when any output is undecided"""
####    global f_name, max_bmc,x_factor,x
####    x = time.clock()
####    #input_x_factor()
####    init_f_name = f_name
####    print 'Beginning prove_g_pos_split'
####    prove_all_ind()
####    print 'Number of outputs reduced to %d by fast induction with constraints'%n_pos()
####    reparam()
######    try_rpm()
####    print '********** Proving each output separately ************'  
####    f_name = init_f_name
####    abc('w %s_osavetemp.aig'%f_name)
####    n = n_pos()
####    print 'Number of outputs = %d'%n
####    pos_proved = []
####    J = 0
####    jnext = n-1
####    while jnext >= 0:
####        max_bmc = -1
####        f_name = init_f_name
####        abc('r %s_osavetemp.aig'%f_name)
####        jnext_old = jnext
####        extract(jnext,jnext)
####        jnext = jnext -1
####        print '\nProving output %d'%(jnext_old)
####        f_name = f_name + '_%d'%jnext_old
####        result = prove_1()
####        if result == 'UNSAT':
####            if jnext_old > jnext+1:
####                print '********  PROVED OUTPUTS [%d-%d]  ******** '%(jnext+1,jnext_old)
####            else:
####                print '********  PROVED OUTPUT %d  ******** '%(jnext_old)
####            pos_proved = pos_proved + range(jnext +1,jnext_old+1)
####            continue
####        if result == 'SAT':
####            print 'One of output in (%d to %d) is SAT'%(jnext + 1,jnext_old)
####            return result
####        else:
####            print '********  UNDECIDED on OUTPUTS %d thru %d  ******** '%(jnext+1,jnext_old)
####            print 'Eliminating %d proved outputs'%(len(pos_proved))
####            # remove outputs proved and return
####            f_name = init_f_name
####            abc('r %s_osavetemp.aig'%f_name)
####            remove(pos_proved)
####            trim()
####            write_file('group')            
####            return 'UNDECIDED'
####    f_name = init_f_name
####    abc('r %s_osavetemp.aig'%f_name)
####    if not len(pos_proved) == n:
####        print 'Eliminating %d proved outputs'%(len(pos_proved))
####        remove(pos_proved)
####        trim()
####        write_file('group')
####        result = 'UNDECIDED'
####    else:
####        print 'Proved all outputs. The problem is proved UNSAT'
####        result = 'UNSAT'
####    print 'Total time = %f sec.'%(time.clock() - x)
####    return result

####def group(a,n):
####    """Groups together outputs beginning at output n and any contiguous preceeding output
####    that does not increase the latch support by a or more"""
####    global f_name, max_bmc
####    nlt = n_latches()
####    extract(n,n)
####    nli = n_latches()
####    if n == 0:
####        return n-1
####    for J in range(1,n+1):
####        abc('r %s_osavetemp.aig'%f_name)
####        j = n-J
####        #print 'Running %d to %d'%(j,n)
####        extract(j,n)
####        #print 'n_latches = %d'%n_latches()
####        #if n_latches() >= nli + (nlt - nli)/2:
####        if n_latches() == nli:
####            continue
####        if n_latches() > nli+a:
####            break
####    abc('r %s_osavetemp.aig'%f_name)
######    if j == 1:
######        j = j-1
####    print 'extracting [%d-%d]'%(j,n)
####    extract(j,n)
####    ps()
####    return j-1
        
def extract(n1,n2):
    """Extracts outputs n1 through n2"""
    no = n_pos()
    if n2 > no:
        return 'range exceeds number of POs'
    abc('cone -s -O %d -R %d'%(n1, 1+n2-n1))

def remove_intrps(J):
    global n_proc,ifbip
    npr = n_proc
    if 18 in J:
        npr = npr+1
    if len(J) <= npr:
        return J
    JJ = []
    alli = [23,1,22] # if_no_bip, then this might need to be changed
    l = len(J)-npr
    alli = alli[:l]
    for i in J:
        if i in alli:
            continue
        else:
            JJ = JJ +[i]
    return JJ
        
def remove(lst):
    """Removes outputs in list"""
    global po_map
    n_before = n_pos()
    zero(lst)
    l=remove_const_pos()
    print 'n_before = %d, n_list = %d, n_after = %d'%(n_before, len(lst), n_pos())

def check_pos():
    """ checks if any POs are 0, and removes them with a warning"""
    N = n_pos()
    l=remove_const_pos()
    if not N == n_pos():
        print 'WARNING: some POs are 0 and are rremoved'
        print '%d POs removed'%(N - n_pos())

def zero(list):
    """Zeros out POs in list"""
    for j in list:
        run_command('zeropo -N %d'%j)

def mark_const_pos(ll=[]):
    """ creates an indicator of which PO are const-0 and which are const-1
        does not change number of POs
    """
    L = range(n_pos())
    L.reverse()
    if ll == []:
        ll = [-1]*n_pos()
    ind = ll
    abc('&get') #save original
    for j in L:
        n_before = n_pos()
        abc('removepo -N %d'%j) #removes const-0 output
        if n_pos() < n_before:
            ind[j]=0
##    print sumsize(ind)
##    ps()
    abc('&put')
    for j in L:
        n_before = n_pos()
        abc('removepo -z -N %d'%j) # -z removes const-1 output
        if n_pos() < n_before:
            ind[j]=1
##    ps()
    abc('&put') #put back original
##    remove_const_pos()
    print sumsize(ind)
    return ind

def remove_const_pos():
    global po_map
    """removes the 0 pos, but no pis because we might get cexs and need the correct number of pis
    Should keep tract of if original POs are 0 and are removed.
    Can this happen outside of prove_all_ind or
    pord_all which can set proved outputs to 0???
    WARNING: This can remove constant 1 nodes too???
    """
    run_command('&get; &trim -i; &put; addpi') #adds a pi only if there are none
    po_map = range(n_pos())

def psp():
    quick_simp()
    result = run_parallel([6,21],500,'US') #runs 'run_parallel' and sp() in parallel.
##                                          run_parallel uses JP and TERM to terminate.
    return result

def sp():
    global initial_f_name
    """Alias for super_prove"""
    print 'Executing super_prove'
    result = super_prove(0)
    print '%s is done'%initial_f_name
    return result


def sumsize(L):
    d = count_less(L,0)
    u = count_less(L,1)-d
    s = count_less(L,2) - (d+u)
    return 'SAT = %d, UNSAT = %d, UNDECIDED = %d'%(s,u,d)

def unmap(L,L2,map):
    mx = max(list(map))
    assert mx <= len(L2),'max of map = %d, length of L2 = %d'%(mx,len(L))
    for j in range(len(map)):
        L[j] = L2[map[j]] #expand results of L2 into L
    return L 

def create_map(L,N):
    map = [-1]*N
    for j in range(len(L)):
        lj = L[j]
        for k in range(len(lj)):
            map[lj[k]] = j
    return map

def mp(op='sp'):
    L = multi_prove(op,900)
    return sumsize(L)

def multi_prove(op='sp',tt=900):
    """two phase prove process for multiple output functions"""
    global max_bmc, init_initial_f_name, initial_f_name,win_list, last_verify_time
    global f_name_save,name_save
    x_init = time.time()
    N = n_pos()
    L = [-1]*N
    print 'Mapping for isomorphism: '
    iso() #reduces number of POs
    map = create_map(iso_eq_classes(),N) #creates map into original
    N = n_pos()
    r = pre_simp() #pre_simp
    write_file('smp')
    NP = n_pos()/N #if NP > 1 then NP unrollings were done.
    if n_pos() > N:
        assert NP>=2, 'NP not 2, n_pos = %d, N = %d, NP = %d'%(n_pos(),N,NP)
    print 'pre_simp done. NP = %d\n\n'%NP
    #WARNING: if phase abstraction done, then number of POs changed.
    if r == Unsat:
        L = [0]*N #all outputs are UNSAT
        print sumsize(L)
        return L
    f_name_save = f_name
    name_save = '%s_initial_save.aig'%f_name
    abc('w %s'%name_save)
    L1 = [-1]*n_pos() # L1 has length after pre_simp
##    L1= mark_const_pos(L1) #puts const values in L1 
##    print sumsize(L1)
    #########do second iso here
    N = n_pos()
    print 'Mapping for isomorphism: '
    iso() #second iso - changes number of POs
    map2 = create_map(iso_eq_classes(),N) #creates map into previous
    L2 = [-1]*n_pos()
    L2 = mark_const_pos(L2) #populates L2 with constants
    print sumsize(L2)
    #########second iso done
    abc('r %s'%name_save)
    L2 = mprove(L2,op,10) #populates L2 with results
    print sumsize(L2)
    time_left = tt - (time.time()-x_init)
    print '\n\n\n*********time left = %d ********\n\n\n'%time_left
    N = count_less(L2,0)
    if N > 0:
        t = max(100,time_left/N)
        L2 = mprove(L2,op,t) #populates L2 with more results
    S = sumsize(L2)
    T = '%.2f'%(time.time() - x_init)
    print '%s in time = %s'%(S,T)
    ########undo second iso
    L1 = unmap(L1,L2,map2)
    print 'unmapping for iso: ',
    print sumsize(L1)
    #############
    if NP > 1: #an unrolling was done
        L1 = check_L(NP,L1) #map into reduced size before unrolling was done.
        print 'unmapping for unrolling.',
        print sumsize(L1)
    L = unmap(L,L1,map)
    print 'unmapping for iso',
    print sumsize(L)
    return L

def check_L(NP,L):
    """This happens when an unrolling creates additional POs
    We want to check that L[j] = L[j+N] etc to make sure the PO results agree
    in all phases, i.e. sat, unsat, or undecided
    """
    N = len(L)/NP #original number of POs
    for j in range(N):
        for k in range(NP)[1:]: #k = 1,2,...,NP-1
            if (L[j] == 1):
                break
            elif L[j+k*N] == 1:
                L[j] = 1
                break
            elif L[j] == -1:
                continue #we have to continue to look for a 1
            elif L[j] == 0:
                if L[j+k*N] == -1:
                    L[j] = -1
                    break
            continue #have to make sure that all phases are 0
    return L[:N]


def mprove(L,op='sp',tt=1000):
    """ 0 = unsat, 1 = sat, -1 = undecided"""
    global max_bmc, init_initial_f_name, initial_f_name,win_list, last_verify_time
    global f_name_save,name_save,temp_dec
    N = len(L)
    t = tt #controls the amount of time spent on each cone
    funcs = [eval('(pyabc_split.defer(%s)())'%op)]
    funcs = create_funcs(slps,t)+funcs
    mtds =sublist(methods,slps) + [op]
    res = L
    for j in range(N):
        if L[j] > -1:
            continue #already solved
        abc('r %s'%name_save) #restore original function
        x = time.time()
        name = '%s_cone_%d'%(f_name_save,j)
        abc('cone -s -O %d'%j)
        abc('w %s.aig'%name)
        print '\n********************************************'
        read_file_quiet(name)
        print '________%s(%s)__________'%(op,name)
        temp_dec = False
        fork_last(funcs,mtds)
        T = '%.2f'%(time.time() - x)
        out = get_status()
        if out == Unsat:
            res[j] = 0
        if out < Unsat:
            res[j] = 1
        print '\n%s: %s in time = %s'%(name,RESULT[out],T)
    return res

def sp1(options = ''):
    global sec_options
    sec_options = options
    return super_prove(1)

def super_prove(n=0):
    """Main proof technique now. Does original prove and if after speculation there are multiple output left
    if will try to prove each output separately, in reverse order. It will quit at the first output that fails
    to be proved, or any output that is proved SAT
    n controls call to prove(n)
    is n == 0 do smp and abs first, then spec
    if n == 1 do smp and spec first then abs
    if n == 2 just do quick simplification instead of full simplification, then abs first, spec second
    """
    global max_bmc, init_initial_f_name, initial_f_name,win_list, last_verify_time, f_name
    init_initial_f_name = initial_f_name
    if x_factor > 1:
        print 'x_factor = %f'%x_factor
        input_x_factor()
    max_bmc = -1
    x = time.time()
##    if n == 2:
##        result = prove(2)
##    else:
##        result = prove(0)
    result = prove(n)
    if ((result == 'SAT') or (result == 'UNSAT')):
        print '%s: total clock time taken by super_prove = %f sec.'%(result,(time.time() - x))
        return result
    elif ((result == 'UNDECIDED') and (n_latches() == 0)):
        return result
    print '%s: total clock time taken by super_prove so far = %f sec.'%(result,(time.time() - x))
    y = time.time()
    if n == 2:
        print 'Entering BMC_VER()'
        result = BMC_VER() #n=2 is only called from sp2, a super_prove run in parallel.
        if ((result == 'SAT') and (('_abs' in f_name)or '_spec' in f_name)): #this is because we have done an abstraction and cex is invalid.
            result = 'UNDECIDED'
    else:
        print 'Entering BMC_VER_result'
        result = BMC_VER_result() #this does backing up if cex is found
    print 'Total clock time taken by last gasp verification = %f sec.'%(time.time() - y)
    print 'Total clock time for %s = %f sec.'%(init_initial_f_name,(time.time() - x))
    return result

def reachm(t):
    x = time.clock()
    abc('&get;&reachm -vcs -T %d'%t)
    print 'reachm done in time = %f'%(time.clock() - x)
    return get_status()

def reachp(t):
    x = time.clock()
    abc('&get;&reachp -rv -T %d'%t)
    print 'reachm2 done in time = %f'%(time.clock() - x)
    return get_status()

def scorr():
    run_command('scorr')
    ps()

def select_undecided(L):
    res = []
    for j in range(len(L)):
        l = L[j]
        if l[1] == 'UNDECIDED':
            res = res + [l[0]]
    return res
        
####def execute(L,t):
####    """
####    run the files in the list L using ss, sp, ssm each for max time = t
####    """
####    funcs1 = [eval('(pyabc_split.defer(ss)())')]
####    funcs1 = create_funcs(slps,t)+funcs1
####    mtds1 =sublist(methods,slps) + ['ss']
####    funcs2 = [eval('(pyabc_split.defer(sp)())')]
####    funcs2 = create_funcs(slps,t)+funcs2
####    mtds2 =sublist(methods,slps) + ['sp']
####    funcs3 = [eval('(pyabc_split.defer(ssm)())')]
####    funcs3 = create_funcs(slps,t)+funcs3
####    mtds3 =sublist(methods,slps) + ['ssm']
####    for j in range(len(L)):
####        name = L[j]
####        print '\n\n\n\n________ss__________'
####        read_file_quiet(name)
####        print '****ss****'
####        fork_last(funcs1,mtds1)
####        print '***Done with ss on %s\n'%name
####        print '\n\n******ssm************'
####        read_file_quiet(name)
####        print '****ssm****'
####        fork_last(funcs3,mtds3)
####        print '***Done with ssm on %s \n'%name

def execute_op(op,L,t):
    """
    run the files in the list L using operation "op", each for max time = t
    """
    funcs = [eval('(pyabc_split.defer(%s)())'%op)]
    funcs = create_funcs(slps,t)+funcs
    mtds =sublist(methods,slps) + [op]
    res = []
    for j in range(len(L)):
        x = time.time()
        name = L[j]
        print '\n\n\n\n________%s__________'%op
        read_file_quiet(name)
        m,result = fork_last(funcs,mtds)
        if result == Undecided:
            result = RESULT[result]
        T = '%.2f'%(time.time() - x)
        new_res = [name,result,T]
        res = res + [new_res]
        print '\n%s'%new_res
    return res

def x_ops(ops,L,t):
    """ execute each op in the set of ops on each file in the set of files of L, each for time t"""
    result = []
    for j in range(len(ops)):
        op = ops[j]
        result.append('Result of %s'%op)
        result.append(execute_op(op,L,t))
    return result

def iso(n=0):
    if n == 0:
        run_command('&get;&iso;&put')
    else:
        run_command('&get;&iso;iso;&put')

def check_iso(N):
    ans = get_large_po()
    if ans == -1:
        return 'no output found'
    n_iso = count_iso(N)
    return n_iso

def count_iso(N):
    abc('&get;write_aiger -u file1.aig') #put this cone in & space and write file1
##    print 'PO %d is used'%i
    n_iso = 0 #start count
    for i in range(N):
        abc('permute;write_aiger -u file2.aig')
        n = filecmp.cmp('file1.aig','file2.aig')
        print n,
        n_iso = n_iso+n
    print 'the number of isomorphisms was %d out of %d'%(n_iso,N)
    return n_iso

def get_large_po():
##    remove_const_pos() #get rid of constant POs
    NL = n_latches()
    NO = n_pos()
    abc('&get') #put the in & space
    n_latches_max = 0
    nl = imax = -1
    for i in range(NO): #look for a big enough PO
        abc('&put;cone -s -O %d;scl'%i)
        nl = n_latches()
        if nl >.15*NL:
            imax = i
##            print 'cone %d has %d FF'%(i,nl)
            break
        if nl> n_latches_max:
            n_latches_max = nl
            imax = i
            print i,nl
        if i == NO-1:
            print 'no PO is big enough'
            return -1
    print 'PO_cone = %d, n_latches = %d'%(imax,nl)

def scorro():
    run_command('scorr -o')
    l = remove_const_pos()
    ps()

def drw():
    run_command('drw')
    ps()

def dc2rs():
    abc('dc2rs')
    ps()
    

def reachn(t):
    x = time.clock()
    abc('&get;&reachn -rv -T %d'%t)
    print 'reachm3 done in time = %f'%(time.clock() - x)
    return get_status()
    
def reachx(t):
    x = time.time()
    abc('reachx -t %d'%t)
    print 'reachx  done in time = %f'%(time.time() - x)
    return get_status()

def reachy(t):
    x = time.clock()
    abc('&get;&reachy -v -T %d'%t)
    print 'reachy done in time = %f'%(time.clock() - x)
    return get_status()
    
def create_funcs(J,t):
    """evaluates strings indexed by J in methods given by FUNCS
    Returns a list of lambda functions for the strings in FUNCs
    If J = [], then create provers for all POs"""
    funcs = []
    for j in range(len(J)):
        k=J[j]
        funcs = funcs + [eval(FUNCS[k])]
    return funcs

def check_abs():
    global init_initial_f_name
    abc('w %s_save.aig'%init_initial_f_name)
    ni = n_pis()
    nl = n_latches()
    na = n_ands()
    abc('r %s_smp_abs.aig'%init_initial_f_name)
    if ((ni == n_pis()) and (nl == n_latches()) and (na == n_ands())):
        return True
    else:
        abc('r %s_save.aig'%init_initial_f_name)
        return False

def modify_methods(J,dec=0):
    """ adjusts the engines to reflect number of processors"""
    N = bmc_depth()
    L = n_latches()
    I = n_real_inputs()
    npr = n_proc -dec
    if 18 in J: #if sleep in J add 1 more processor
        npr = npr+1
    if ( ((I+L<350)&(N>100))  or  (I+L<260) or (L<80) ):
        if not 24 in J: #24 is reachs
            J = J+[24] # add all reach methods
            if len(J)>npr:
                J = remove_intrps(J) #removes only if len(J)<n_processes
    if len(J)< npr: #if not using all processors, add in pdrs
        #modify allpdrs to reflect ifbip (see set_engines)
        for j in range(len(allpdrs)):
            if allpdrs[j] in J: #leave it in
                continue
            else: #add it in
                J = J + [allpdrs[j]]
                if len(J) == npr:
                    break            
##        if L < 80:
##            if ((not 4 in J) and len(J) < n_proc):
##                J = J + [4]
    return J

def BMC_VER():
    """ a special version of BMC_VER_result that just works on the current network
    Just runs engines in parallel - no backing up
    """
    global init_initial_f_name, methods, last_verify_time, n_proc
    xt = time.time()
    result = 5
    t = max(2*last_verify_time,10000)  ####
    print 'Verify time set to %d'%t
    J = slps + pdrs + bmcs + intrps
    J = modify_methods(J)
    F = create_funcs(J,t)
    mtds = sublist(methods,J)
    print mtds
    (m,result) = fork_break(F,mtds,'US')
    result = RESULT[result]
    print 'BMC_VER result = %s'%result
    return result

        
def BMC_VER_result():
    global init_initial_f_name, methods, last_verify_time,f_name
    xt = time.time()
    result = 5
    abc('r %s.aig'%f_name)
    print '\n***Running proof on %s :'%f_name,
    ps()
    t = max(2*last_verify_time,10000) #each time a new time-out is set t at least 1000 sec.
    print 'Verify time set to %d'%t
    X = pyabc_split.defer(abc)
    J = slps + pdrs + bmcs + intrps
    last_name = seq_name(f_name).pop()
    if 'smp' == last_name: # then we try harder to prove it.
        J = slps + intrps + allpdrs + [2]
    J = modify_methods(J) #if # processors is enough and problem is small enough then add in reachs
    F = create_funcs(J,t)
    mtds = sublist(methods,J)
    print '%s'%mtds
    (m,result) = fork(F,mtds)
    result = get_status()
    if result == Unsat:
        return 'UNSAT'
    if last_name == 'smp' :   # can't backup so just return result
        if result < Unsat:
            return 'SAT'
        if result > Unsat: #still undefined
            return 'UNDECIDED'
    else:    # (last_name == 'spec' or last_name == 'abs') - the last thing we did was an "abstraction"
        if result < Unsat:
            f_name = revert(f_name,1) # revert the f_name back to previous
            abc('r %s.aig'%f_name)
            return BMC_VER_result() #recursion here.
            
def try_split():
    abc('w %s_savetemp.aig'%f_name)
    na = n_ands()
    split(3)
    if n_ands()> 2*na:
        abc('r %s_savetemp.aig'%f_name)
    
def time_diff():
    global last_time
    new_time = time.clock()
    diff = new_time - last_time
    last_time = new_time
    result = 'Lapsed time = %.2f sec.'%diff
    return result

def prove_all_ind():
    """Tries to prove output k by induction, using other outputs as constraints.
    If ever an output is proved
    it is set to 0 so it can't be used in proving another output to break circularity.
    Finally all zero'ed outputs are removed.
    Prints out unproved outputs Finally removes 0 outputs
    """
    global n_pos_proved, n_pos_before
    print 'n_pos_proved = %d'%n_pos_proved
    n_proved = 0
    N = n_pos()
##    l=remove_const_pos()
##    print '0 valued output removal changed POs from %d to %d'%(N,n_pos())
    if n_pos() == 1:
        return
    abc('w %s_osavetemp.aig'%f_name)
    lst = range(n_pos())
##    list.reverse()
##    for j in list[1:]:
    for j in lst:
##        abc('zeropo -N 0')
        abc('swappos -N %d'%j)
##        l=remove_const_pos() #may not have to do this if constr works well with 0'ed outputs
        abc('constr -N %d'%(n_pos()-1))
        abc('fold')
        n = max(1,n_ands())
        f = max(1,min(40000/n,16))
        f = int(f)
##        abc('ind -C 10000 -F %d'%f)
        abc('ind -C 1000 -F %d'%f)
##        run_command('print_status')
        status = get_status()
        abc('r %s_osavetemp.aig'%f_name) #have to restore original here
        if status == Unsat:
##            print '+',
            abc('zeropo -N %d'%j)
            abc('w %s_osavetemp.aig'%f_name) #if changed, store it permanently
            if j < n_pos_before - n_pos_proved:
                n_proved = n_proved + 1 # keeps track of real POs proved.
        elif status < Unsat:
            print '-%d'%j,
        else:
            print '*%d'%j,
    l=remove_const_pos()
    n_pos_proved = n_pos_proved + n_proved 
    print '\nThe number of POs reduced from %d to %d'%(N,n_pos())
    print 'n_pos_proved = %d'%n_pos_proved
    #return status

def remove_iso(L):
    global n_pos_proved, n_pos_before
    lst = []
    for j in range(len(L)):
        ll = L[j][1:]
        if len(ll) == 0:
            continue
        else:
            lst = lst + ll
    zero(lst)
    n_pos_proved = n_pos_proved + count_less(lst,n_pos_before - n_pos_proved)
    print 'The number of POs removed by iso was %d'%len(lst)
    l=remove_const_pos() #can an original PO be zero?

def prove_all_iso():
    """Tries to prove output k by isomorphism. Gets number of iso-eq_classes as an array of lists.
    Updates n_pos_proved
    """
    global n_pos_proved, n_pos_before
    n_proved = 0
    N = n_pos()
    if n_pos() == 1:
        return
    print 'n_pos_proved = %d'%n_pos_proved
##    run_command('&get;&iso;&put')
    abc('&get;&iso')
    L = iso_eq_classes()
##    print L
    remove_iso(L)
##    lim = n_pos_before - n_pos_proved
##    for j in range(len(L)):
##        ll = L[j]
##        if len(ll) == 1:
##            continue
##        if not ll[0] < lim:
##            continue
##        else:
##            n = count_less(ll[1:], lim) #drop the first since it is the representative.
##            print n
##            n_proved = n_proved + n
##            print n, n_proved
##    n_pos_proved = n_pos_proved + n_proved 
    print '\nThe number of POs reduced by iso was from %d to %d'%(N,n_pos())

def count_less(L,n):
    count = 0
    for j in range(len(L)):
        if L[j] < n:
            count = count + 1
    return count

def prove_all_mtds(t):
    """
    Tries to prove output k  with multiple methods in parallel,
    using other outputs as constraints. If ever an output is proved
    it is set to 0 so it can't be used in proving another output to break circularity.
    Finally all zero'ed ooutputs are removed.
    """
    N = n_pos()
##    l=remove_const_pos()
##    print '0 valued output removal changed POs from %d to %d'%(N,n_pos())
    abc('w %s_osavetemp.aig'%f_name)
    list = range(n_pos())
    for j in list:
        run_command('swappos -N %d'%j)
##        l=remove_const_pos() #may not have to do this if constr works well with 0'ed outputs
        abc('constr -N %d'%(n_pos()-1))
        abc('fold')
##        cmd = '&get;,pdr -vt=%d'%t #put in parallel.
##        abc(cmd)
        verify(pdrs+bmcs+intrps+sims,t)
        status = get_status()
        abc('r %s_osavetemp.aig'%f_name)
        if status == Unsat:
            print '+',
            abc('zeropo -N %d'%j)
            abc('w %s_osavetemp.aig'%f_name) #if changed, store it permanently
        print '%d'%j,
    assert not is_sat(), 'one of the POs is SAT' #we can do better than this
    l=remove_const_pos()
    print '\nThe number of POs reduced from %d to %d'%(N,n_pos())
    #return status

def prove_all_pdr(t):
    """Tries to prove output k by pdr, using other outputs as constraints. If ever an output is proved
    it is set to 0 so it can't be used in proving another output to break circularity.
    Finally all zero'ed ooutputs are removed. """
    N = n_pos()
##    l=remove_const_pos()
    print '0 valued output removal changed POs from %d to %d'%(N,n_pos())
    abc('w %s_osavetemp.aig'%f_name)
    list = range(n_pos())
    for j in list:
        abc('swappos -N %d'%j)
##        l=remove_const_pos() #may not have to do this if constr works well with 0'ed outputs
        abc('constr -N %d'%(n_pos()-1))
        abc('fold')
        cmd = '&get;,pdr -vt=%d'%t #put in parallel.
        abc(cmd)
        status = get_status()
        abc('r %s_osavetemp.aig'%f_name)
        if status == Unsat:
            print '+',
            abc('zeropo -N %d'%j)
            abc('w %s_osavetemp.aig'%f_name) #if changed, store it permanently
        print '%d'%j,
    l=remove_const_pos()
    print '\nThe number of POs reduced from %d to %d'%(N,n_pos())
    #return status

def prove_each_ind():
    """Tries to prove output k by induction,  """
    N = n_pos()
    l=remove_const_pos()
    print '0 valued output removal changed POs from %d to %d'%(N,n_pos())
    abc('w %s_osavetemp.aig'%f_name)
    list = range(n_pos())
    for j in list:
        abc('cone -s -O %d'%j)
        n = max(1,n_ands())
        f = max(1,min(40000/n,16))
        f = int(f)
        abc('ind -u -C 10000 -F %d'%f)
        status = get_status()
        abc('r %s_osavetemp.aig'%f_name)
        if status == Unsat:
            print '+',
            abc('zeropo -N %d'%j)
            abc('w %s_osavetemp.aig'%f_name) #if changed, store it permanently
        print '%d'%j,
    l=remove_const_pos()
    print '\nThe number of POs reduced from %d to %d'%(N,n_pos())
    #return status

def prove_each_pdr(t):
    """Tries to prove output k by PDR. If ever an output is proved
    it is set to 0. Finally all zero'ed ooutputs are removed. """
    N = n_pos()
    l=remove_const_pos()
    print '0 valued output removal changed POs from %d to %d'%(N,n_pos())
    abc('w %s_osavetemp.aig'%f_name)
    list = range(n_pos())
    for j in list:
        abc('cone -O %d -s'%j)
        abc('scl -m')
        abc('&get;,pdr -vt=%d'%t)
        status = get_status()
        abc('r %s_osavetemp.aig'%f_name)
        if status == Unsat:
            print '+',
            abc('zeropo -N %d'%j)
            abc('w %s_osavetemp.aig'%f_name) #if changed, store it permanently
        print '%d'%j,
    l=remove_const_pos()
    print '\nThe number of POs reduced from %d to %d'%(N,n_pos())
    #return status

def disprove_each_bmc(t):
    """Tries to prove output k by PDR. If ever an output is proved
    it is set to 0. Finally all zero'ed ooutputs are removed. """
    N = n_pos()
    l=remove_const_pos()
    print '0 valued output removal changed POs from %d to %d'%(N,n_pos())
    abc('w %s_osavetemp.aig'%f_name)
    list = range(n_pos())
    for j in list:
        abc('cone -O %d -s'%j)
        abc('scl -m')
        abc('bmc3 -T %d'%t)
        status = get_status()
        abc('r %s_osavetemp.aig'%f_name)
        if status == Sat:
            print '+',
            abc('zeropo -N %d'%j)
            abc('w %s_osavetemp.aig'%f_name) #if changed, store it permanently
        print '%d'%j,
    l=remove_const_pos()
    print '\nThe number of POs reduced from %d to %d'%(N,n_pos())
    #return status

def pord_1_2(t):
    """ two phase pord. First one tries with 10% of the time. If not solved then try with full time"""
    global n_pos_proved, ifpord1, pord_on
    pord_on = True # make sure that we do not reparameterize after abstract in prove_2
    n_pos_proved = 0
    if n_pos()<4:
        return Undecided
    if ifpord1:
        print 'Trying each output for %0.2f sec'%(.1*t)
        result = pord_all(.1*t) #we want to make sure that there is no easy cex.
        if (result <= Unsat):
            return result
    ifpord1 = 0
    print 'Trying each output for %0.2f sec'%t
    #might consider using iso before the second pass of pord_all
    result = pord_all(t+2*G_T) #make sure there is enough time to abstract
    pord_on = False #done with pord
    return result

def pord_all(t):
    """Tries to prove or disprove each output j by PDRM BMC3 or SIM. in time t"""
    global cex_list, n_pos_proved, last_cx, pord_on, ifpord1
    print 'last_cx = %d'%last_cx
    btime = time.time()
    N = n_pos()
    prove_all_ind() ############ change this to keep track of n_pos_proved
    nn = n_pos()
    abc('w %s_osavetemp.aig'%f_name)
    if nn < 4: #Just cut to the chase immediately.
        return Undecided
    lst = range(n_pos())
    proved = disproved = []
    abc('&get') #using this space to save original file.
    ### Be careful that & space is not changed.
##    with redirect.redirect( redirect.null_file, sys.stdout ):
##        with redirect.redirect( redirect.null_file, sys.stderr ):
    cx_list = []
    n_proved = 0
    lcx = last_cx + 1
    lst = lst[lcx:]+lst[:lcx]
    lst.reverse()
    n_und = 0
    for j in lst:
        print '\ncone %s. '%j,
        abc('&put; cone -s -O %d'%j) #puts the &space into reg-space and extracts cone j
        #requires that &space is not changed. &put resets status. Use &put -s to keep status
        abc('scl -m')
        ps()
##        print 'running sp2'
        ###
        result = run_sp2_par(t)
##        J = slps+JV
##        result = verify(J,t)
##        result = RESULT[result]
##        ###
##        print 'run_sp2_par result is %s'%result
        if result == 'UNDECIDED':
            n_und = n_und + 1
            status = Undecided
            if ((n_und > 1) and not ifpord1):
                break
        elif result == 'SAT':
            status = Sat
            disproved = disproved + [j]
            last_cx = j
            cx = cex_get()
            cx_list = cx_list + [cx]
            assert len(cx_list) == len(disproved), cx_list
            if len(cx_list) > 0:
                break
        else: #is unsat here
            status = Unsat
            proved = proved + [j]
            if j < n_pos_before - n_pos_proved:
                n_proved = n_proved +1
##    n_pos_proved = n_pos_proved + n_proved. #this should not be here because we should start fresh
    print '\nProved %d outputs'%len(proved)
    print 'Disproved %d outputs'%len(disproved)
    print 'Time for pord_all was %0.2f'%(time.time() - btime)
    NN = len(proved+disproved)
    cex_list = cx_list
    if len(disproved)>0:
        assert status == Sat, 'status = %d'%status
        n_pos_proved = 0 #we want to reset this because of a bad speculation
        return Sat
    else:
        n_pos_proved = n_pos_proved + n_proved
        abc('r %s_osavetemp.aig'%f_name)
##        abc('&put') # returning original to work spece
        remove(proved)
        print '\nThe number of unproved POs reduced from %d to %d'%(N,n_pos()),
        ps()
        if n_pos() > 0:
            return Undecided
        else:
            return Unsat

def bmc_ss(t):
    """
    finds a set cexs in t seconds starting at 2*N where N is depth of bmc -T 1
    The cexs are put in the global cex_list
    """
    global cex_list
    x = time.time()
    tt = min(10,max(1,.05*t))
    abc('bmc3 -T %0.2f'%tt)
    N = n_bmc_frames()
    if N <= max_bmc:
        return Undecided
##    print bmc_depth()
##    abc('bmc3 -C 1000000 -T %f -S %d'%(t,int(1.5*max(3,max_bmc))))
    run_command('bmc3 -vs -C 1000000 -T %f -S %d'%(t,2*N))
    if is_sat():
        cex_list = cex_get_vector() #does this get returned from a concurrent process?
        n = count_non_None(cex_list)
        print '%d cexs found in %0.2f sec at frame %d'%(n,(time.time()-x),cex_frame())
    return get_status()

def list_non_None(lst):
    """ return [i for i,s in enumerate(cex_list) if not s == None]"""
    L = []
    for i in range(len(lst)):
        if not lst[i] == None:
            L = L + [i]
    return L

def count_non_None(lst):
    #return len([i for i,s in enumerate(cex_list) if not s == None]
    count = 0
    for i in range(len(lst)):
        if not lst[i] == None:
            count = count + 1
    return count

def remove_disproved_pos(lst):
    for i in range(len(lst)):
        if not lst[i] == None:
            abc('zeropo -N %d'%i)
    l=remove_const_pos()
        
def bmc_j(t):
    """ finds a cex in t seconds starting at 2*N where N is depth of bmc -T 1"""
    x = time.time()
    tt = min(5,max(1,.05*t))
    abc('bmc3 -T %0.2f'%tt)
    if is_sat():
        print 'cex found in %0.2f sec at frame %d'%((time.time()-x),cex_frame())
        return get_status()
##    abc('bmc3 -T 1')
    N = n_bmc_frames()
    N = max(1,N)
##    print bmc_depth()
##    abc('bmc3 -C 1000000 -T %f -S %d'%(t,int(1.5*max(3,max_bmc))))
    cmd = 'bmc3 -J 2 -D 4000 -C 1000000 -T %f -S %d'%(t,2*N)
##    print cmd
    abc(cmd)
    if is_sat():
        print 'cex found in %0.2f sec at frame %d'%((time.time()-x),cex_frame())
    return get_status()

def pdrseed(t):
    """uses the abstracted version now"""
##    abc('&get;,treb -rlim=60 -coi=3 -te=1 -vt=%f -seed=521'%t)
    abc('&get;,treb -rlim=100 -vt=%f -seed=521'%t)


def pdrold(t):
    abc('&get; ,pdr -vt=%f'%t)

def pdr(t):
    abc('&get; ,treb -vt=%f'%t)
    return RESULT[get_status()]

def pdra(t):
##    abc('&get; ,treb -rlim=100 -ssize -pre-cubes=3 -vt=%f'%t)
    abc('&get; ,treb -abs -rlim=100 -gen-cex -vt=%f'%t)
    return RESULT[get_status()]

def pdrm(t):
    abc('pdr -C 0 -T %f'%t)
    return RESULT[get_status()]

def pdrmm(t):
    abc('pdr -C 0 -M 298 -T %f'%t)
    return RESULT[get_status()]

def split(n):
    abc('orpos;&get')
    abc('&posplit -v -N %d;&put;dc2'%n)
    trim()

def keep_splitting():
    for j in range(5):
        split(5+j)
        no = n_pos()
        status = prove_g_pos_split()
        if status <= Unsat:
            return status
        if no == n_pos():
            return Undecided

def drill(n):
    run_command('&get; &reachm -vcs -H 5 -S %d -T 50 -C 40'%n)

def prove_1(ratio=.75):
    """
    A version of prove called from prove_pos, prove_g_pos, prove_only, prove_g_pos_split when we
    have speculated and produced multiple outputs. 
    Proves all the outputs together. If ever an abstraction was done then
    if SAT is returned,we make RESULT return "undecided".
    """
    global x_factor,xfi,f_name,x, initial_f_name
    x = time.time()
    max_bmc = -1
    print 'Initial: ',
    ps()
    x_factor = xfi
    initial_f_name_save = initial_f_name #needed because we are making local backups here.
    initial_f_name = '%s_temp'%initial_f_name
    set_globals()
    print'\n***Running abstract'
    status = abstract(ifbip)
    trim()
    status = process_status(status)
    if ((status <= Unsat)  or  status == Error):
        if  status < Unsat:
            print 'CEX in frame %d'%cex_frame(),
            print 'abstract found a cex in initial circuit'
            print 'Time for proof = %f sec.'%(time.time() - x)
            initial_f_name = initial_f_name_save
            return RESULT[status]
        print 'Time for proof = %f sec.'%(time.time() - x)
        initial_f_name = initial_f_name_save
        return RESULT[status]
    #undecided here
    print 'Entering direct verificationb'
####    status = final_verify_recur(2)
    status = BMC_VER()
    return status
    
    trim()
####    write_file('final')
    print 'Time for proof = %f sec.'%(time.time() - x)
    initial_f_name = initial_f_name_save
    return RESULT[status]
    
def pre_reduce():
    x = time.clock()
    pre_simp()
    write_file('smp')
    abstract(ifbip)
####    write_file('abs')
    print 'Time = %f'%(time.clock() - x)

def sublist(L,I):
    # return [s for i,s in enumerate(L) if i in I]
    z = []
    for i in range(len(I)):
        s = L[I[i]],
        s = list(s)
        z = z + s
    return z

#PARALLEL FUNCTIONS
"""  funcs should look like
funcs = [pyabc_split.defer(abc)('&get;,bmc -vt=50;&put'),pyabc_split.defer(super_prove)()]
After this is executed funcs becomes a special list of lambda functions
which are given to abc_split_all to be executed as in below.
It has been set up so that each of the functions works on the current aig and
possibly transforms it. The new aig and status is always read into the master when done
"""


def tf():
    result = top_fork()
    return result

def top_fork(J,t):
    global x_factor, final_verify_time, last_verify_time, methods
    set_globals()
    mtds = sublist(methods,J)
    F = create_funcs(J,t)
    print 'Running %s in parallel for max %d sec.'%(mtds,t)
    (m,result) = fork_last(F,mtds) #FORK here
    return get_status()

def run_sp2_par(t):
    """ Runs the single method simple, timed for t seconds."""
    global cex_list,methods
    J = slps+[6]
    print sublist(methods,J)
    funcs = create_funcs(J,t) 
    y = time.time()
    for i,res in pyabc_split.abc_split_all(funcs):
##        print 'i,res = %d,%s'%(i,res)
        t = time.time()-y
        if i == 0:
            print 'sleep timer expired in %0.2f'%t
            return 'UNDECIDED'
        else:
##            print i,res
            if res == 'UNSAT':
                print 'Simple_prove proved UNSAT in %0.2f sec.'%t
                return 'UNSAT'
            elif res == 'UNDECIDED':
                print 'Simple_prove proved UNDECIDED in %0.2f sec.'%t
                return 'UNDECIDED'
            else:
                print 'Simple_prove found cex in %0.2f sec.'%t
                return 'SAT'
            

def run_parallel(J,t,BREAK):
    """ Runs the listed methods J, each for time = t, in parallel and
    breaks according to BREAK = subset of '?USLB'"""
    global cex_list,  methods
    mtds = sublist(methods,J)
    F = create_funcs(J,t) #if J = [] we are going to create functions that process each output separately.
                            #if 18, then these are run in parallel with sleep
    if ((J == []) ):
        result = fork_break(F,mtds,BREAK)
##        #redirect here to suppress printouts.
##        with redirect.redirect( redirect.null_file, sys.stdout ):
##            with redirect.redirect( redirect.null_file, sys.stderr ):
##                result = fork_break(F,mtds,BREAK)
    elif 'L' in BREAK:
        result = fork_last(F,mtds)
    elif 'B' in BREAK:
        result = fork_best(F,mtds)
    else:
        result = fork_break(F,mtds,BREAK)
    return result

def fork_all(funcs,mtds):
    """Runs funcs in parallel and continue running until all are done"""
    global methods
    y = time.time()
    for i,res in pyabc_split.abc_split_all(funcs):
        status = prob_status()
        t = time.time()-y
        if not status == -1: #solved here
            if status == 1: #unsat
                print '%s proved UNSAT in %f sec.'%(mtds[i],t)
            else:
                print '%s found cex in %f sec. - '%(mtds[i],t),
                if not mtds[i] == 'REACHM':
                    print 'cex depth at %d'%cex_frame()
                else:
                    print ' '
            continue
        else:
            print '%s was undecided in %f sec. '%(mtds[i],t)
    return i,res

def fork_break(funcs,mtds,BREAK):
    """
    Runs funcs in parallel and breaks according to BREAK <= '?US'
    If mtds = 'sleep' or [], we are proving outputs in parallel
    Saves cex's found in cex_list in case we are proving POs.
    """
    global methods,last_verify_time,seed,cex_list,last_winner,last_cex
    seed = seed + 3 # since parallel processes do not chenge the seed in the prime process, we need to change it here
    cex_list = lst = []
    y = time.time() #use wall clock time because parent fork process does not use up compute time.
    for i,res in pyabc_split.abc_split_all(funcs):
        status = get_status()
        t = time.time()-y
        lm = len(mtds)
        if ((lm < 2) and not i == 0): # the only single mtds case is where it is 'sleep'
            M = 'Output %d'%(i-lm)
        else:
            M = mtds[i]
            last_winner = M
        if M == 'sleep':
            print 'sleep: time expired in %s sec.'%convert(t)
            assert status >= Unsat,'status = %d'%status
            break
        if ((status > Unsat) and '?' in BREAK): #undecided
                break
        elif status == Unsat: #unsat
            print '%s: UNSAT in %s sec.'%(M,convert(t))
            if 'U' in BREAK:
                break
        elif status < Unsat: #status == 0 - cex found
            if M in methods:                
                if methods.index(M) in exbmcs+allreachs+allpdrs+[1]: #set the known best depth so far. [1] is interp
                    set_max_bmc(n_bmc_frames())
            last_cex = M
            print '%s: -- cex in %0.2f sec. at depth %d => '%(M,t,cex_frame()),
            cex_list = cex_list+[cex_get()] #accumulates multiple cex's and puts them on list.
            if len(cex_list)>1:
                print 'len(cex_list): %d'%len(cex_list)
            if 'S' in BREAK:
                break
        else:
            continue
    return i,status

def fork_best(funcs,mts):
    """ fork the functions, If not solved, take the best result in terms of AIG size"""
    global f_name
    n = len(mts)-1
    y = time.time()
    m_best = -1
    best_size = [n_pis(),n_latches(),n_ands()]
##    print best_size
    abc('w %s_best_aig.aig'%f_name)
    for i,res in pyabc_split.abc_split_all(funcs):
        status = prob_status()
##        print i,
##        ps()
##        print i,res,
        #ps()
        if not status == -1: #solved here
            m = i
            t = time.time()-y
            if status == 1: #unsat
                print '%s proved UNSAT in %f sec.'%(mtds[i],t)