summaryrefslogtreecommitdiff
path: root/src/prop/minisat/simp
diff options
context:
space:
mode:
authorDejan Jovanović <dejan.jovanovic@gmail.com>2010-08-15 21:25:21 +0000
committerDejan Jovanović <dejan.jovanovic@gmail.com>2010-08-15 21:25:21 +0000
commita6b782a6b8486689e47338c456b816c95cf67a92 (patch)
treea7f911007e1d27c2fb0e1847d9cabb1c538d65b2 /src/prop/minisat/simp
parent58ea6b0b63d2170391a61e0fe3b1a3ecf3b99fb2 (diff)
Diffstat (limited to 'src/prop/minisat/simp')
-rw-r--r--src/prop/minisat/simp/Main.cc508
-rw-r--r--src/prop/minisat/simp/Makefile11
-rw-r--r--src/prop/minisat/simp/SimpSolver.cc671
-rw-r--r--src/prop/minisat/simp/SimpSolver.h178
4 files changed, 598 insertions, 770 deletions
diff --git a/src/prop/minisat/simp/Main.cc b/src/prop/minisat/simp/Main.cc
index b6d194631..e59d73be0 100644
--- a/src/prop/minisat/simp/Main.cc
+++ b/src/prop/minisat/simp/Main.cc
@@ -1,5 +1,6 @@
-/******************************************************************************************[Main.C]
-MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+/*****************************************************************************************[Main.cc]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
@@ -17,399 +18,194 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
-#include <ctime>
-#include <cstring>
-#include <stdint.h>
#include <errno.h>
#include <signal.h>
#include <zlib.h>
-
-#include "SimpSolver.h"
-
-/*************************************************************************************/
-#ifdef _MSC_VER
-#include <ctime>
-
-static inline double cpuTime(void) {
- return (double)clock() / CLOCKS_PER_SEC; }
-#else
-
-#include <sys/time.h>
#include <sys/resource.h>
-#include <unistd.h>
-static inline double cpuTime(void) {
- struct rusage ru;
- getrusage(RUSAGE_SELF, &ru);
- return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; }
-#endif
-
-
-#if defined(__linux__)
-static inline int memReadStat(int field)
-{
- char name[256];
- pid_t pid = getpid();
- sprintf(name, "/proc/%d/statm", pid);
- FILE* in = fopen(name, "rb");
- if (in == NULL) return 0;
- int value;
- for (; field >= 0; field--)
- fscanf(in, "%d", &value);
- fclose(in);
- return value;
-}
-static inline uint64_t memUsed() { return (uint64_t)memReadStat(0) * (uint64_t)getpagesize(); }
-
-
-#elif defined(__FreeBSD__)
-static inline uint64_t memUsed(void) {
- struct rusage ru;
- getrusage(RUSAGE_SELF, &ru);
- return ru.ru_maxrss*1024; }
-
-
-#else
-static inline uint64_t memUsed() { return 0; }
-#endif
-
-#if defined(__linux__)
-#include <fpu_control.h>
-#endif
+#include "utils/System.h"
+#include "utils/ParseUtils.h"
+#include "utils/Options.h"
+#include "core/Dimacs.h"
+#include "simp/SimpSolver.h"
+using namespace Minisat;
//=================================================================================================
-// DIMACS Parser:
-
-#define CHUNK_LIMIT 1048576
-class StreamBuffer {
- gzFile in;
- char buf[CHUNK_LIMIT];
- int pos;
- int size;
- void assureLookahead() {
- if (pos >= size) {
- pos = 0;
- size = gzread(in, buf, sizeof(buf)); } }
-
-public:
- StreamBuffer(gzFile i) : in(i), pos(0), size(0) {
- assureLookahead(); }
-
- int operator * () { return (pos >= size) ? EOF : buf[pos]; }
- void operator ++ () { pos++; assureLookahead(); }
-};
-
-//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-template<class B>
-static void skipWhitespace(B& in) {
- while ((*in >= 9 && *in <= 13) || *in == 32)
- ++in; }
-
-template<class B>
-static void skipLine(B& in) {
- for (;;){
- if (*in == EOF || *in == '\0') return;
- if (*in == '\n') { ++in; return; }
- ++in; } }
-
-template<class B>
-static int parseInt(B& in) {
- int val = 0;
- bool neg = false;
- skipWhitespace(in);
- if (*in == '-') neg = true, ++in;
- else if (*in == '+') ++in;
- if (*in < '0' || *in > '9') reportf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
- while (*in >= '0' && *in <= '9')
- val = val*10 + (*in - '0'),
- ++in;
- return neg ? -val : val; }
-
-template<class B>
-static void readClause(B& in, SimpSolver& S, vec<Lit>& lits) {
- int parsed_lit, var;
- lits.clear();
- for (;;){
- parsed_lit = parseInt(in);
- if (parsed_lit == 0) break;
- var = abs(parsed_lit)-1;
- while (var >= S.nVars()) S.newVar();
- lits.push( (parsed_lit > 0) ? Lit(var) : ~Lit(var) );
- }
-}
-
-template<class B>
-static bool match(B& in, char* str) {
- for (; *str != 0; ++str, ++in)
- if (*str != *in)
- return false;
- return true;
+void printStats(Solver& solver)
+{
+ double cpu_time = cpuTime();
+ double mem_used = memUsedPeak();
+ printf("restarts : %"PRIu64"\n", solver.starts);
+ printf("conflicts : %-12"PRIu64" (%.0f /sec)\n", solver.conflicts , solver.conflicts /cpu_time);
+ printf("decisions : %-12"PRIu64" (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions /cpu_time);
+ printf("propagations : %-12"PRIu64" (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time);
+ printf("conflict literals : %-12"PRIu64" (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals);
+ if (mem_used != 0) printf("Memory used : %.2f MB\n", mem_used);
+ printf("CPU time : %g s\n", cpu_time);
}
-template<class B>
-static void parse_DIMACS_main(B& in, SimpSolver& S) {
- vec<Lit> lits;
- for (;;){
- skipWhitespace(in);
- if (*in == EOF) break;
- else if (*in == 'p'){
- if (match(in, "p cnf")){
- int vars = parseInt(in);
- int clauses = parseInt(in);
- reportf("| Number of variables: %-12d |\n", vars);
- reportf("| Number of clauses: %-12d |\n", clauses);
-
- // SATRACE'06 hack
- if (clauses > 4000000)
- S.eliminate(true);
- }else{
- reportf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
- }
- } else if (*in == 'c' || *in == 'p')
- skipLine(in);
- else{
- readClause(in, S, lits);
- S.addClause(lits); }
- }
-}
+static Solver* solver;
+// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case
+// for this feature of the Solver as it may take longer than an immediate call to '_exit()'.
+static void SIGINT_interrupt(int signum) { solver->interrupt(); }
-// Inserts problem into solver.
-//
-static void parse_DIMACS(gzFile input_stream, SimpSolver& S) {
- StreamBuffer in(input_stream);
- parse_DIMACS_main(in, S); }
-
-
-//=================================================================================================
-
-
-void printStats(Solver& S)
-{
- double cpu_time = cpuTime();
- uint64_t mem_used = memUsed();
- reportf("restarts : %lld\n", S.starts);
- reportf("conflicts : %-12lld (%.0f /sec)\n", S.conflicts , S.conflicts /cpu_time);
- reportf("decisions : %-12lld (%4.2f %% random) (%.0f /sec)\n", S.decisions, (float)S.rnd_decisions*100 / (float)S.decisions, S.decisions /cpu_time);
- reportf("propagations : %-12lld (%.0f /sec)\n", S.propagations, S.propagations/cpu_time);
- reportf("conflict literals : %-12lld (%4.2f %% deleted)\n", S.tot_literals, (S.max_literals - S.tot_literals)*100 / (double)S.max_literals);
- if (mem_used != 0) reportf("Memory used : %.2f MB\n", mem_used / 1048576.0);
- reportf("CPU time : %g s\n", cpu_time);
-}
-
-SimpSolver* solver;
-static void SIGINT_handler(int signum) {
- reportf("\n"); reportf("*** INTERRUPTED ***\n");
- printStats(*solver);
- reportf("\n"); reportf("*** INTERRUPTED ***\n");
- exit(1); }
+// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls
+// destructors and may cause deadlocks if a malloc/free function happens to be running (these
+// functions are guarded by locks for multithreaded use).
+static void SIGINT_exit(int signum) {
+ printf("\n"); printf("*** INTERRUPTED ***\n");
+ if (solver->verbosity > 0){
+ printStats(*solver);
+ printf("\n"); printf("*** INTERRUPTED ***\n"); }
+ _exit(1); }
//=================================================================================================
// Main:
-void printUsage(char** argv)
-{
- reportf("USAGE: %s [options] <input-file> <result-output-file>\n\n where input may be either in plain or gzipped DIMACS.\n\n", argv[0]);
- reportf("OPTIONS:\n\n");
- reportf(" -pre = {none,once}\n");
- reportf(" -asymm\n");
- reportf(" -rcheck\n");
- reportf(" -grow = <num> [ >0 ]\n");
- reportf(" -polarity-mode = {true,false,rnd}\n");
- reportf(" -decay = <num> [ 0 - 1 ]\n");
- reportf(" -rnd-freq = <num> [ 0 - 1 ]\n");
- reportf(" -dimacs = <output-file>\n");
- reportf(" -verbosity = {0,1,2}\n");
- reportf("\n");
-}
-
-typedef enum { pre_none, pre_once, pre_repeat } preprocessMode;
-
-const char* hasPrefix(const char* str, const char* prefix)
-{
- int len = strlen(prefix);
- if (strncmp(str, prefix, len) == 0)
- return str + len;
- else
- return NULL;
-}
-
-
int main(int argc, char** argv)
{
- reportf("This is MiniSat 2.0 beta\n");
+ try {
+ setUsageHelp("USAGE: %s [options] <input-file> <result-output-file>\n\n where input may be either in plain or gzipped DIMACS.\n");
+ // printf("This is MiniSat 2.0 beta\n");
+
#if defined(__linux__)
- fpu_control_t oldcw, newcw;
- _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
- reportf("WARNING: for repeatability, setting FPU to use double precision\n");
+ fpu_control_t oldcw, newcw;
+ _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
+ printf("WARNING: for repeatability, setting FPU to use double precision\n");
#endif
- preprocessMode pre = pre_once;
- const char* dimacs = NULL;
- const char* freeze = NULL;
- SimpSolver S;
- S.verbosity = 1;
-
- // This just grew and grew, and I didn't have time to do sensible argument parsing yet :)
- //
- int i, j;
- const char* value;
- for (i = j = 0; i < argc; i++){
- if ((value = hasPrefix(argv[i], "-polarity-mode="))){
- if (strcmp(value, "true") == 0)
- S.polarity_mode = Solver::polarity_true;
- else if (strcmp(value, "false") == 0)
- S.polarity_mode = Solver::polarity_false;
- else if (strcmp(value, "rnd") == 0)
- S.polarity_mode = Solver::polarity_rnd;
- else{
- reportf("ERROR! unknown polarity-mode %s\n", value);
- exit(0); }
-
- }else if ((value = hasPrefix(argv[i], "-rnd-freq="))){
- double rnd;
- if (sscanf(value, "%lf", &rnd) <= 0 || rnd < 0 || rnd > 1){
- reportf("ERROR! illegal rnd-freq constant %s\n", value);
- exit(0); }
- S.random_var_freq = rnd;
-
- }else if ((value = hasPrefix(argv[i], "-decay="))){
- double decay;
- if (sscanf(value, "%lf", &decay) <= 0 || decay <= 0 || decay > 1){
- reportf("ERROR! illegal decay constant %s\n", value);
- exit(0); }
- S.var_decay = 1 / decay;
-
- }else if ((value = hasPrefix(argv[i], "-verbosity="))){
- int verbosity = (int)strtol(value, NULL, 10);
- if (verbosity == 0 && errno == EINVAL){
- reportf("ERROR! illegal verbosity level %s\n", value);
- exit(0); }
- S.verbosity = verbosity;
-
- }else if ((value = hasPrefix(argv[i], "-pre="))){
- if (strcmp(value, "none") == 0)
- pre = pre_none;
- else if (strcmp(value, "once") == 0)
- pre = pre_once;
- else if (strcmp(value, "repeat") == 0){
- pre = pre_repeat;
- reportf("ERROR! preprocessing mode \"repeat\" is not supported at the moment.\n");
- exit(0);
- }else{
- reportf("ERROR! unknown preprocessing mode %s\n", value);
- exit(0); }
- }else if (strcmp(argv[i], "-asymm") == 0){
- S.asymm_mode = true;
- }else if (strcmp(argv[i], "-rcheck") == 0){
- S.redundancy_check = true;
- }else if ((value = hasPrefix(argv[i], "-grow="))){
- int grow = (int)strtol(value, NULL, 10);
- if (grow == 0 && errno == EINVAL){
- reportf("ERROR! illegal grow constant %s\n", &argv[i][6]);
- exit(0); }
- S.grow = grow;
- }else if ((value = hasPrefix(argv[i], "-dimacs="))){
- dimacs = value;
- }else if ((value = hasPrefix(argv[i], "-freeze="))){
- freeze = value;
- }else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0){
- printUsage(argv);
- exit(0);
- }else if (strncmp(argv[i], "-", 1) == 0){
- reportf("ERROR! unknown flag %s\n", argv[i]);
- exit(0);
- }else
- argv[j++] = argv[i];
- }
- argc = j;
-
- double cpu_time = cpuTime();
+ // Extra options:
+ //
+ IntOption verb ("MAIN", "verb", "Verbosity level (0=silent, 1=some, 2=more).", 1, IntRange(0, 2));
+ BoolOption pre ("MAIN", "pre", "Completely turn on/off any preprocessing.", true);
+ StringOption dimacs ("MAIN", "dimacs", "If given, stop after preprocessing and write the result to this file.");
+ IntOption cpu_lim("MAIN", "cpu-lim","Limit on CPU time allowed in seconds.\n", INT32_MAX, IntRange(0, INT32_MAX));
+ IntOption mem_lim("MAIN", "mem-lim","Limit on memory usage in megabytes.\n", INT32_MAX, IntRange(0, INT32_MAX));
+
+ parseOptions(argc, argv, true);
+
+ SimpSolver S;
+ double initial_time = cpuTime();
+
+ if (!pre) S.eliminate(true);
+
+ S.verbosity = verb;
+
+ solver = &S;
+ // Use signal handlers that forcibly quit until the solver will be able to respond to
+ // interrupts:
+ signal(SIGINT, SIGINT_exit);
+ signal(SIGXCPU,SIGINT_exit);
+
+ // Set limit on CPU-time:
+ if (cpu_lim != INT32_MAX){
+ rlimit rl;
+ getrlimit(RLIMIT_CPU, &rl);
+ if (rl.rlim_max == RLIM_INFINITY || (rlim_t)cpu_lim < rl.rlim_max){
+ rl.rlim_cur = cpu_lim;
+ if (setrlimit(RLIMIT_CPU, &rl) == -1)
+ printf("WARNING! Could not set resource limit: CPU-time.\n");
+ } }
+
+ // Set limit on virtual memory:
+ if (mem_lim != INT32_MAX){
+ rlim_t new_mem_lim = (rlim_t)mem_lim * 1024*1024;
+ rlimit rl;
+ getrlimit(RLIMIT_AS, &rl);
+ if (rl.rlim_max == RLIM_INFINITY || new_mem_lim < rl.rlim_max){
+ rl.rlim_cur = new_mem_lim;
+ if (setrlimit(RLIMIT_AS, &rl) == -1)
+ printf("WARNING! Could not set resource limit: Virtual memory.\n");
+ } }
+
+ if (argc == 1)
+ printf("Reading from standard input... Use '--help' for help.\n");
+
+ gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
+ if (in == NULL)
+ printf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);
+
+ if (S.verbosity > 0){
+ printf("============================[ Problem Statistics ]=============================\n");
+ printf("| |\n"); }
+
+ parse_DIMACS(in, S);
+ gzclose(in);
+ FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;
+
+ if (S.verbosity > 0){
+ printf("| Number of variables: %12d |\n", S.nVars());
+ printf("| Number of clauses: %12d |\n", S.nClauses()); }
+
+ double parsed_time = cpuTime();
+ if (S.verbosity > 0)
+ printf("| Parse time: %12.2f s |\n", parsed_time - initial_time);
+
+ // Change to signal-handlers that will only notify the solver and allow it to terminate
+ // voluntarily:
+ signal(SIGINT, SIGINT_interrupt);
+ signal(SIGXCPU,SIGINT_interrupt);
- if (pre == pre_none)
S.eliminate(true);
-
- solver = &S;
- signal(SIGINT,SIGINT_handler);
- signal(SIGHUP,SIGINT_handler);
-
- if (argc == 1)
- reportf("Reading from standard input... Use '-h' or '--help' for help.\n");
-
- gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
- if (in == NULL)
- reportf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);
-
- reportf("============================[ Problem Statistics ]=============================\n");
- reportf("| |\n");
-
- parse_DIMACS(in, S);
- gzclose(in);
- FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;
-
-
- double parse_time = cpuTime() - cpu_time;
- reportf("| Parsing time: %-12.2f s |\n", parse_time);
-
- /*HACK: Freeze variables*/
- if (freeze != NULL && pre != pre_none){
- int count = 0;
- FILE* in = fopen(freeze, "rb");
- for(;;){
- Var x;
- fscanf(in, "%d", &x);
- if (x == 0) break;
- x--;
-
- /**/assert(S.n_occ[toInt(Lit(x))] + S.n_occ[toInt(~Lit(x))] != 0);
- /**/assert(S.value(x) == l_Undef);
- S.setFrozen(x, true);
- count++;
+ double simplified_time = cpuTime();
+ if (S.verbosity > 0){
+ printf("| Simplification time: %12.2f s |\n", simplified_time - parsed_time);
+ printf("| |\n"); }
+
+ if (!S.okay()){
+ if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
+ if (S.verbosity > 0){
+ printf("===============================================================================\n");
+ printf("Solved by simplification\n");
+ printStats(S);
+ printf("\n"); }
+ printf("UNSATISFIABLE\n");
+ exit(20);
}
- fclose(in);
- reportf("| Frozen vars : %-12.0f |\n", (double)count);
- }
- /*END*/
-
- if (!S.simplify()){
- reportf("Solved by unit propagation\n");
- if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
- printf("UNSATISFIABLE\n");
- exit(20);
- }
- if (dimacs){
- if (pre != pre_none)
- S.eliminate(true);
- reportf("==============================[ Writing DIMACS ]===============================\n");
- S.toDimacs(dimacs);
- printStats(S);
- exit(0);
- }else{
- bool ret = S.solve(true, true);
- printStats(S);
- reportf("\n");
+ if (dimacs){
+ if (S.verbosity > 0)
+ printf("==============================[ Writing DIMACS ]===============================\n");
+ S.toDimacs((const char*)dimacs);
+ if (S.verbosity > 0)
+ printStats(S);
+ exit(0);
+ }
- printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n");
+ vec<Lit> dummy;
+ lbool ret = S.solveLimited(dummy);
+
+ if (S.verbosity > 0){
+ printStats(S);
+ printf("\n"); }
+ printf(ret == l_True ? "SATISFIABLE\n" : ret == l_False ? "UNSATISFIABLE\n" : "INDETERMINATE\n");
if (res != NULL){
- if (ret){
+ if (ret == l_True){
fprintf(res, "SAT\n");
for (int i = 0; i < S.nVars(); i++)
if (S.model[i] != l_Undef)
fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
fprintf(res, " 0\n");
- }else
+ }else if (ret == l_False)
fprintf(res, "UNSAT\n");
+ else
+ fprintf(res, "INDET\n");
fclose(res);
}
+
#ifdef NDEBUG
- exit(ret ? 10 : 20); // (faster than "return", which will invoke the destructor for 'Solver')
+ exit(ret == l_True ? 10 : ret == l_False ? 20 : 0); // (faster than "return", which will invoke the destructor for 'Solver')
+#else
+ return (ret == l_True ? 10 : ret == l_False ? 20 : 0);
#endif
+ } catch (OutOfMemoryException&){
+ printf("===============================================================================\n");
+ printf("INDETERMINATE\n");
+ exit(0);
}
-
}
diff --git a/src/prop/minisat/simp/Makefile b/src/prop/minisat/simp/Makefile
index a1db4951b..27b45f493 100644
--- a/src/prop/minisat/simp/Makefile
+++ b/src/prop/minisat/simp/Makefile
@@ -1,11 +1,4 @@
-MTL = ../mtl
-CORE = ../core
-CHDRS = $(wildcard *.h) $(wildcard $(MTL)/*.h)
EXEC = minisat
-CFLAGS = -I$(MTL) -I$(CORE) -Wall -ffloat-store
-LFLAGS = -lz
+DEPDIR = mtl utils core
-CSRCS = $(wildcard *.C)
-COBJS = $(addsuffix .o, $(basename $(CSRCS))) $(CORE)/Solver.o
-
-include ../mtl/template.mk
+include $(MROOT)/mtl/template.mk
diff --git a/src/prop/minisat/simp/SimpSolver.cc b/src/prop/minisat/simp/SimpSolver.cc
index 00f93402f..32ac223d6 100644
--- a/src/prop/minisat/simp/SimpSolver.cc
+++ b/src/prop/minisat/simp/SimpSolver.cc
@@ -1,5 +1,6 @@
-/************************************************************************************[SimpSolver.C]
-MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+/***********************************************************************************[SimpSolver.cc]
+Copyright (c) 2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
@@ -17,77 +18,94 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
-#include "Sort.h"
-#include "SimpSolver.h"
+#include "mtl/Sort.h"
+#include "simp/SimpSolver.h"
+#include "utils/System.h"
+
+using namespace Minisat;
+using namespace CVC4;
+
+//=================================================================================================
+// Options:
+
+
+static const char* _cat = "SIMP";
+
+static BoolOption opt_use_asymm (_cat, "asymm", "Shrink clauses by asymmetric branching.", false);
+static BoolOption opt_use_rcheck (_cat, "rcheck", "Check if a clause is already implied. (costly)", false);
+static BoolOption opt_use_elim (_cat, "elim", "Perform variable elimination.", true);
+static IntOption opt_grow (_cat, "grow", "Allow a variable elimination step to grow by a number of clauses.", 0);
+static IntOption opt_clause_lim (_cat, "cl-lim", "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20, IntRange(-1, INT32_MAX));
+static IntOption opt_subsumption_lim (_cat, "sub-lim", "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX));
+static DoubleOption opt_simp_garbage_frac(_cat, "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.", 0.5, DoubleRange(0, false, HUGE_VAL, false));
//=================================================================================================
// Constructor/Destructor:
-namespace CVC4 {
-namespace prop {
-namespace minisat {
-SimpSolver::SimpSolver(SatSolver* proxy, context::Context* context) :
+SimpSolver::SimpSolver(CVC4::prop::SatSolver* proxy, CVC4::context::Context* context) :
Solver(proxy, context)
- , grow (0)
- , asymm_mode (false)
- , redundancy_check (false)
+ , grow (opt_grow)
+ , clause_lim (opt_clause_lim)
+ , subsumption_lim (opt_subsumption_lim)
+ , simp_garbage_frac (opt_simp_garbage_frac)
+ , use_asymm (opt_use_asymm)
+ , use_rcheck (opt_use_rcheck)
+ , use_elim (opt_use_elim)
, merges (0)
, asymm_lits (0)
- , remembered_clauses (0)
+ , eliminated_vars (0)
, elimorder (1)
, use_simplification (true)
+ , occurs (ClauseDeleted(ca))
, elim_heap (ElimLt(n_occ))
, bwdsub_assigns (0)
+ , n_touched (0)
{
vec<Lit> dummy(1,lit_Undef);
- bwdsub_tmpunit = Clause_new(dummy);
- remove_satisfied = false;
+ ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below.
+ bwdsub_tmpunit = ca.alloc(dummy);
+ remove_satisfied = false;
}
SimpSolver::~SimpSolver()
{
- free(bwdsub_tmpunit);
-
- // NOTE: elimtable.size() might be lower than nVars() at the moment
- for (int i = 0; i < elimtable.size(); i++)
- for (int j = 0; j < elimtable[i].eliminated.size(); j++)
- free(elimtable[i].eliminated[j]);
}
Var SimpSolver::newVar(bool sign, bool dvar, bool theoryAtom) {
Var v = Solver::newVar(sign, dvar,theoryAtom);
+ frozen .push((char)theoryAtom);
+ eliminated.push((char)false);
+
if (use_simplification){
- n_occ .push(0);
- n_occ .push(0);
- occurs .push();
- frozen .push((char)theoryAtom);
- touched .push(0);
- elim_heap.insert(v);
- elimtable.push();
+ n_occ .push(0);
+ n_occ .push(0);
+ occurs .init(v);
+ touched .push(0);
+ elim_heap .insert(v);
}
return v; }
-bool SimpSolver::solve(const vec<Lit>& assumps, bool do_simp, bool turn_off_simp) {
+lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp)
+{
vec<Var> extra_frozen;
- bool result = true;
+ lbool result = l_True;
do_simp &= use_simplification;
if (do_simp){
// Assumptions must be temporarily frozen to run variable elimination:
- for (int i = 0; i < assumps.size(); i++){
- Var v = var(assumps[i]);
+ for (int i = 0; i < assumptions.size(); i++){
+ Var v = var(assumptions[i]);
// If an assumption has been eliminated, remember it.
- if (isEliminated(v))
- remember(v);
+ assert(!isEliminated(v));
if (!frozen[v]){
// Freeze and store.
@@ -95,18 +113,16 @@ bool SimpSolver::solve(const vec<Lit>& assumps, bool do_simp, bool turn_off_simp
extra_frozen.push(v);
} }
- result = eliminate(turn_off_simp);
+ result = lbool(eliminate(turn_off_simp));
}
- if (result)
- result = Solver::solve(assumps);
+ if (result == l_True)
+ result = Solver::solve_();
+ else if (verbosity >= 1)
+ printf("===============================================================================\n");
- if (result) {
+ if (result == l_True)
extendModel();
-#ifndef NDEBUG
- verifyModel();
-#endif
- }
if (do_simp)
// Unfreeze the assumptions that were frozen:
@@ -118,35 +134,39 @@ bool SimpSolver::solve(const vec<Lit>& assumps, bool do_simp, bool turn_off_simp
-bool SimpSolver::addClause(vec<Lit>& ps, ClauseType type)
+bool SimpSolver::addClause_(vec<Lit>& ps, ClauseType type)
{
+#ifndef NDEBUG
for (int i = 0; i < ps.size(); i++)
- if (isEliminated(var(ps[i])))
- remember(var(ps[i]));
+ assert(!isEliminated(var(ps[i])));
+#endif
int nclauses = clauses.size();
- if (redundancy_check && implied(ps))
+ if (use_rcheck && implied(ps))
return true;
- if (!Solver::addClause(ps, type))
+ if (!Solver::addClause_(ps, type))
return false;
if (use_simplification && clauses.size() == nclauses + 1){
- Clause& c = *clauses.last();
-
- subsumption_queue.insert(&c);
-
+ CRef cr = clauses.last();
+ const Clause& c = ca[cr];
+
+ // NOTE: the clause is added to the queue immediately and then
+ // again during 'gatherTouchedClauses()'. If nothing happens
+ // in between, it will only be checked once. Otherwise, it may
+ // be checked twice unnecessarily. This is an unfortunate
+ // consequence of how backward subsumption is used to mimic
+ // forward subsumption.
+ subsumption_queue.insert(cr);
for (int i = 0; i < c.size(); i++){
- assert(occurs.size() > var(c[i]));
- assert(!find(occurs[var(c[i])], &c));
-
- occurs[var(c[i])].push(&c);
+ occurs[var(c[i])].push(cr);
n_occ[toInt(c[i])]++;
touched[var(c[i])] = 1;
- assert(elimtable[var(c[i])].order == 0);
+ n_touched++;
if (elim_heap.inHeap(var(c[i])))
- elim_heap.increase_(var(c[i]));
+ elim_heap.increase(var(c[i]));
}
}
@@ -154,65 +174,45 @@ bool SimpSolver::addClause(vec<Lit>& ps, ClauseType type)
}
-void SimpSolver::removeClause(Clause& c)
+void SimpSolver::removeClause(CRef cr)
{
+ const Clause& c = ca[cr];
Debug("minisat") << "SimpSolver::removeClause(" << c << ")" << std::endl;
- assert(!c.learnt());
if (use_simplification)
for (int i = 0; i < c.size(); i++){
n_occ[toInt(c[i])]--;
updateElimHeap(var(c[i]));
+ occurs.smudge(var(c[i]));
}
- detachClause(c);
- c.mark(1);
+ Solver::removeClause(cr);
}
-bool SimpSolver::strengthenClause(Clause& c, Lit l)
+bool SimpSolver::strengthenClause(CRef cr, Lit l)
{
+ Clause& c = ca[cr];
assert(decisionLevel() == 0);
- assert(c.mark() == 0);
- assert(!c.learnt());
- assert(find(watches[toInt(~c[0])], &c));
- assert(find(watches[toInt(~c[1])], &c));
+ assert(use_simplification);
// FIX: this is too inefficient but would be nice to have (properly implemented)
// if (!find(subsumption_queue, &c))
- subsumption_queue.insert(&c);
-
- // If l is watched, delete it from watcher list and watch a new literal
- if (c[0] == l || c[1] == l){
- Lit other = c[0] == l ? c[1] : c[0];
- if (c.size() == 2){
- removeClause(c);
- c.strengthen(l);
- }else{
- c.strengthen(l);
- remove(watches[toInt(~l)], &c);
-
- // Add a watch for the correct literal
- watches[toInt(~(c[1] == other ? c[0] : c[1]))].push(&c);
-
- // !! this version assumes that remove does not change the order !!
- //watches[toInt(~c[1])].push(&c);
- clauses_literals -= 1;
- }
- }
- else{
- c.strengthen(l);
- clauses_literals -= 1;
- }
+ subsumption_queue.insert(cr);
- // if subsumption-indexing is active perform the necessary updates
- if (use_simplification){
- remove(occurs[var(l)], &c);
+ if (c.size() == 2){
+ removeClause(cr);
+ c.strengthen(l);
+ }else{
+ detachClause(cr, true);
+ c.strengthen(l);
+ attachClause(cr);
+ remove(occurs[var(l)], cr);
n_occ[toInt(l)]--;
updateElimHeap(var(l));
}
- return c.size() == 1 ? enqueue(c[0]) && propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) == NULL : true;
+ return c.size() == 1 ? enqueue(c[0]) && propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) == CRef_Undef : true;
}
@@ -223,18 +223,17 @@ bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& ou
out_clause.clear();
bool ps_smallest = _ps.size() < _qs.size();
- const Clause& ps = ps_smallest ? _qs : _ps;
- const Clause& qs = ps_smallest ? _ps : _qs;
+ const Clause& ps = ps_smallest ? _qs : _ps;
+ const Clause& qs = ps_smallest ? _ps : _qs;
for (int i = 0; i < qs.size(); i++){
if (var(qs[i]) != v){
for (int j = 0; j < ps.size(); j++)
- if (var(ps[j]) == var(qs[i])) {
+ if (var(ps[j]) == var(qs[i]))
if (ps[j] == ~qs[i])
return false;
else
goto next;
- }
out_clause.push(qs[i]);
}
next:;
@@ -249,25 +248,27 @@ bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& ou
// Returns FALSE if clause is always satisfied.
-bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v)
+bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size)
{
merges++;
bool ps_smallest = _ps.size() < _qs.size();
- const Clause& ps = ps_smallest ? _qs : _ps;
- const Clause& qs = ps_smallest ? _ps : _qs;
- const Lit* __ps = (const Lit*)ps;
- const Lit* __qs = (const Lit*)qs;
+ const Clause& ps = ps_smallest ? _qs : _ps;
+ const Clause& qs = ps_smallest ? _ps : _qs;
+ const Lit* __ps = (const Lit*)ps;
+ const Lit* __qs = (const Lit*)qs;
+
+ size = ps.size()-1;
for (int i = 0; i < qs.size(); i++){
if (var(__qs[i]) != v){
for (int j = 0; j < ps.size(); j++)
- if (var(__ps[j]) == var(__qs[i])) {
+ if (var(__ps[j]) == var(__qs[i]))
if (__ps[j] == ~__qs[i])
return false;
else
goto next;
- }
+ size++;
}
next:;
}
@@ -278,23 +279,29 @@ bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v)
void SimpSolver::gatherTouchedClauses()
{
- //fprintf(stderr, "Gathering clauses for backwards subsumption\n");
- int ntouched = 0;
- for (int i = 0; i < touched.size(); i++)
+ if (n_touched == 0) return;
+
+ int i,j;
+ for (i = j = 0; i < subsumption_queue.size(); i++)
+ if (ca[subsumption_queue[i]].mark() == 0)
+ ca[subsumption_queue[i]].mark(2);
+
+ for (i = 0; i < touched.size(); i++)
if (touched[i]){
- const vec<Clause*>& cs = getOccurs(i);
- ntouched++;
- for (int j = 0; j < cs.size(); j++)
- if (cs[j]->mark() == 0){
+ const vec<CRef>& cs = occurs.lookup(i);
+ for (j = 0; j < cs.size(); j++)
+ if (ca[cs[j]].mark() == 0){
subsumption_queue.insert(cs[j]);
- cs[j]->mark(2);
+ ca[cs[j]].mark(2);
}
touched[i] = 0;
}
- //fprintf(stderr, "Touched variables %d of %d yields %d clauses to check\n", ntouched, touched.size(), clauses.size());
- for (int i = 0; i < subsumption_queue.size(); i++)
- subsumption_queue[i]->mark(0);
+ for (i = 0; i < subsumption_queue.size(); i++)
+ if (ca[subsumption_queue[i]].mark() == 2)
+ ca[subsumption_queue[i]].mark(0);
+
+ n_touched = 0;
}
@@ -312,7 +319,7 @@ bool SimpSolver::implied(const vec<Lit>& c)
uncheckedEnqueue(~c[i]);
}
- bool result = propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL;
+ bool result = propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != CRef_Undef;
cancelUntil(0);
return result;
}
@@ -328,20 +335,26 @@ bool SimpSolver::backwardSubsumptionCheck(bool verbose)
while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){
+ // Empty subsumption queue and return immediately on user-interrupt:
+ if (asynch_interrupt){
+ subsumption_queue.clear();
+ bwdsub_assigns = trail.size();
+ break; }
+
// Check top-level assignments by creating a dummy clause and placing it in the queue:
if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){
Lit l = trail[bwdsub_assigns++];
- (*bwdsub_tmpunit)[0] = l;
- bwdsub_tmpunit->calcAbstraction();
- assert(bwdsub_tmpunit->mark() == 0);
+ ca[bwdsub_tmpunit][0] = l;
+ ca[bwdsub_tmpunit].calcAbstraction();
subsumption_queue.insert(bwdsub_tmpunit); }
- Clause& c = *subsumption_queue.peek(); subsumption_queue.pop();
+ CRef cr = subsumption_queue.peek(); subsumption_queue.pop();
+ Clause& c = ca[cr];
if (c.mark()) continue;
if (verbose && verbosity >= 2 && cnt++ % 1000 == 0)
- reportf("subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals);
+ printf("subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals);
assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point.
@@ -352,21 +365,21 @@ bool SimpSolver::backwardSubsumptionCheck(bool verbose)
best = var(c[i]);
// Search all candidates:
- vec<Clause*>& _cs = getOccurs(best);
- Clause** cs = (Clause**)_cs;
+ vec<CRef>& _cs = occurs.lookup(best);
+ CRef* cs = (CRef*)_cs;
for (int j = 0; j < _cs.size(); j++)
if (c.mark())
break;
- else if (!cs[j]->mark() && cs[j] != &c){
- Lit l = c.subsumes(*cs[j]);
+ else if (!ca[cs[j]].mark() && cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){
+ Lit l = c.subsumes(ca[cs[j]]);
if (l == lit_Undef)
- subsumed++, removeClause(*cs[j]);
+ subsumed++, removeClause(cs[j]);
else if (l != lit_Error){
deleted_literals++;
- if (!strengthenClause(*cs[j], ~l))
+ if (!strengthenClause(cs[j], ~l))
return false;
// Did current candidate get deleted from cs? Then check candidate at index j again:
@@ -380,8 +393,9 @@ bool SimpSolver::backwardSubsumptionCheck(bool verbose)
}
-bool SimpSolver::asymm(Var v, Clause& c)
+bool SimpSolver::asymm(Var v, CRef cr)
{
+ Clause& c = ca[cr];
assert(decisionLevel() == 0);
if (c.mark() || satisfied(c)) return true;
@@ -394,10 +408,10 @@ bool SimpSolver::asymm(Var v, Clause& c)
else
l = c[i];
- if (propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL){
+ if (propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != CRef_Undef){
cancelUntil(0);
asymm_lits++;
- if (!strengthenClause(c, l))
+ if (!strengthenClause(cr, l))
return false;
}else
cancelUntil(0);
@@ -408,304 +422,299 @@ bool SimpSolver::asymm(Var v, Clause& c)
bool SimpSolver::asymmVar(Var v)
{
- assert(!frozen[v]);
assert(use_simplification);
- vec<Clause*> pos, neg;
- const vec<Clause*>& cls = getOccurs(v);
+ const vec<CRef>& cls = occurs.lookup(v);
if (value(v) != l_Undef || cls.size() == 0)
return true;
for (int i = 0; i < cls.size(); i++)
- if (!asymm(v, *cls[i]))
+ if (!asymm(v, cls[i]))
return false;
return backwardSubsumptionCheck();
}
-void SimpSolver::verifyModel()
+static void mkElimClause(vec<uint32_t>& elimclauses, Lit x)
{
- bool failed = false;
- int cnt = 0;
- // NOTE: elimtable.size() might be lower than nVars() at the moment
- for (int i = 0; i < elimtable.size(); i++)
- if (elimtable[i].order > 0)
- for (int j = 0; j < elimtable[i].eliminated.size(); j++){
- cnt++;
- Clause& c = *elimtable[i].eliminated[j];
- for (int k = 0; k < c.size(); k++)
- if (modelValue(c[k]) == l_True)
- goto next;
-
- reportf("unsatisfied clause: ");
- printClause(*elimtable[i].eliminated[j]);
- reportf("\n");
- failed = true;
- next:;
- }
-
- assert(!failed);
- reportf("Verified %d eliminated clauses.\n", cnt);
+ elimclauses.push(toInt(x));
+ elimclauses.push(1);
}
-bool SimpSolver::eliminateVar(Var v, bool fail)
+static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c)
{
- if (!fail && asymm_mode && !asymmVar(v)) return false;
+ int first = elimclauses.size();
+ int v_pos = -1;
+
+ // Copy clause to elimclauses-vector. Remember position where the
+ // variable 'v' occurs:
+ for (int i = 0; i < c.size(); i++){
+ elimclauses.push(toInt(c[i]));
+ if (var(c[i]) == v)
+ v_pos = i + first;
+ }
+ assert(v_pos != -1);
+
+ // Swap the first literal with the 'v' literal, so that the literal
+ // containing 'v' will occur first in the clause:
+ uint32_t tmp = elimclauses[v_pos];
+ elimclauses[v_pos] = elimclauses[first];
+ elimclauses[first] = tmp;
+
+ // Store the length of the clause last:
+ elimclauses.push(c.size());
+}
+
- const vec<Clause*>& cls = getOccurs(v);
-// if (value(v) != l_Undef || cls.size() == 0) return true;
- if (value(v) != l_Undef) return true;
+bool SimpSolver::eliminateVar(Var v)
+{
+ assert(!frozen[v]);
+ assert(!isEliminated(v));
+ assert(value(v) == l_Undef);
// Split the occurrences into positive and negative:
- vec<Clause*> pos, neg;
+ //
+ const vec<CRef>& cls = occurs.lookup(v);
+ vec<CRef> pos, neg;
for (int i = 0; i < cls.size(); i++)
- (find(*cls[i], Lit(v)) ? pos : neg).push(cls[i]);
+ (find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]);
+
+ // Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no
+ // clause must exceed the limit on the maximal clause size (if it is set):
+ //
+ int cnt = 0;
+ int clause_size = 0;
- // Check if number of clauses decreases:
- int cnt = 0;
for (int i = 0; i < pos.size(); i++)
for (int j = 0; j < neg.size(); j++)
- if (merge(*pos[i], *neg[j], v) && ++cnt > cls.size() + grow)
+ if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) &&
+ (++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim)))
return true;
// Delete and store old clauses:
+ eliminated[v] = true;
setDecisionVar(v, false);
- elimtable[v].order = elimorder++;
- assert(elimtable[v].eliminated.size() == 0);
- for (int i = 0; i < cls.size(); i++){
- elimtable[v].eliminated.push(Clause_new(*cls[i]));
- removeClause(*cls[i]); }
+ eliminated_vars++;
+
+ if (pos.size() > neg.size()){
+ for (int i = 0; i < neg.size(); i++)
+ mkElimClause(elimclauses, v, ca[neg[i]]);
+ mkElimClause(elimclauses, mkLit(v));
+ }else{
+ for (int i = 0; i < pos.size(); i++)
+ mkElimClause(elimclauses, v, ca[pos[i]]);
+ mkElimClause(elimclauses, ~mkLit(v));
+ }
+
+ for (int i = 0; i < cls.size(); i++)
+ removeClause(cls[i]);
// Produce clauses in cross product:
- int top = clauses.size();
- vec<Lit> resolvent;
+ vec<Lit>& resolvent = add_tmp;
for (int i = 0; i < pos.size(); i++)
for (int j = 0; j < neg.size(); j++)
- if (merge(*pos[i], *neg[j], v, resolvent) && !addClause(resolvent, CLAUSE_CONFLICT))
+ if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent, CLAUSE_CONFLICT))
return false;
- // DEBUG: For checking that a clause set is saturated with respect to variable elimination.
- // If the clause set is expected to be saturated at this point, this constitutes an
- // error.
- if (fail){
- reportf("eliminated var %d, %d <= %d\n", v+1, cnt, cls.size());
- reportf("previous clauses:\n");
- for (int i = 0; i < cls.size(); i++){
- printClause(*cls[i]); reportf("\n"); }
- reportf("new clauses:\n");
- for (int i = top; i < clauses.size(); i++){
- printClause(*clauses[i]); reportf("\n"); }
- assert(0); }
+ // Free occurs list for this variable:
+ occurs[v].clear(true);
+
+ // Free watchers lists for this variable, if possible:
+ if (watches[ mkLit(v)].size() == 0) watches[ mkLit(v)].clear(true);
+ if (watches[~mkLit(v)].size() == 0) watches[~mkLit(v)].clear(true);
return backwardSubsumptionCheck();
}
-void SimpSolver::remember(Var v)
+bool SimpSolver::substitute(Var v, Lit x)
{
- assert(decisionLevel() == 0);
- assert(isEliminated(v));
+ assert(!frozen[v]);
+ assert(!isEliminated(v));
+ assert(value(v) == l_Undef);
- vec<Lit> clause;
+ if (!ok) return false;
- // Re-activate variable:
- elimtable[v].order = 0;
- setDecisionVar(v, true); // Not good if the variable wasn't a decision variable before. Not sure how to fix this right now.
+ eliminated[v] = true;
+ setDecisionVar(v, false);
+ const vec<CRef>& cls = occurs.lookup(v);
+
+ vec<Lit>& subst_clause = add_tmp;
+ for (int i = 0; i < cls.size(); i++){
+ Clause& c = ca[cls[i]];
- if (use_simplification)
- updateElimHeap(v);
-
- // Reintroduce all old clauses which may implicitly remember other clauses:
- for (int i = 0; i < elimtable[v].eliminated.size(); i++){
- Clause& c = *elimtable[v].eliminated[i];
- clause.clear();
- for (int j = 0; j < c.size(); j++)
- clause.push(c[j]);
-
- remembered_clauses++;
- check(addClause(clause, CLAUSE_PROBLEM));
- free(&c);
+ subst_clause.clear();
+ for (int j = 0; j < c.size(); j++){
+ Lit p = c[j];
+ subst_clause.push(var(p) == v ? x ^ sign(p) : p);
+ }
+
+ removeClause(cls[i]);
+
+ if (!addClause_(subst_clause, CLAUSE_PROBLEM))
+ return ok = false;
}
- elimtable[v].eliminated.clear();
+ return true;
}
void SimpSolver::extendModel()
{
- vec<Var> vs;
-
- // NOTE: elimtable.size() might be lower than nVars() at the moment
- for (int v = 0; v < elimtable.size(); v++)
- if (elimtable[v].order > 0)
- vs.push(v);
-
- sort(vs, ElimOrderLt(elimtable));
+ int i, j;
+ Lit x;
- for (int i = 0; i < vs.size(); i++){
- Var v = vs[i];
- Lit l = lit_Undef;
+ for (i = elimclauses.size()-1; i > 0; i -= j){
+ for (j = elimclauses[i--]; j > 1; j--, i--)
+ if (modelValue(toLit(elimclauses[i])) != l_False)
+ goto next;
- for (int j = 0; j < elimtable[v].eliminated.size(); j++){
- Clause& c = *elimtable[v].eliminated[j];
-
- for (int k = 0; k < c.size(); k++)
- if (var(c[k]) == v)
- l = c[k];
- else if (modelValue(c[k]) != l_False)
- goto next;
-
- assert(l != lit_Undef);
- model[v] = lbool(!sign(l));
- break;
-
- next:;
- }
-
- if (model[v] == l_Undef)
- model[v] = l_True;
+ x = toLit(elimclauses[i]);
+ model[var(x)] = lbool(!sign(x));
+ next:;
}
}
bool SimpSolver::eliminate(bool turn_off_elim)
{
- if (!ok || !use_simplification)
- return ok;
+ if (!simplify())
+ return false;
+ else if (!use_simplification)
+ return true;
// Main simplification loop:
- //assert(subsumption_queue.size() == 0);
- //gatherTouchedClauses();
- while (subsumption_queue.size() > 0 || elim_heap.size() > 0){
-
- //fprintf(stderr, "subsumption phase: (%d)\n", subsumption_queue.size());
- if (!backwardSubsumptionCheck(true))
- return false;
+ //
+ while (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0){
- //fprintf(stderr, "elimination phase:\n (%d)", elim_heap.size());
+ gatherTouchedClauses();
+ // printf(" ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns);
+ if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) &&
+ !backwardSubsumptionCheck(true)){
+ ok = false; goto cleanup; }
+
+ // Empty elim_heap and return immediately on user-interrupt:
+ if (asynch_interrupt){
+ assert(bwdsub_assigns == trail.size());
+ assert(subsumption_queue.size() == 0);
+ assert(n_touched == 0);
+ elim_heap.clear();
+ goto cleanup; }
+
+ // printf(" ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size());
for (int cnt = 0; !elim_heap.empty(); cnt++){
Var elim = elim_heap.removeMin();
+
+ if (asynch_interrupt) break;
- if (verbosity >= 2 && cnt % 100 == 0)
- reportf("elimination left: %10d\r", elim_heap.size());
+ if (isEliminated(elim) || value(elim) != l_Undef) continue;
- if (!frozen[elim] && !eliminateVar(elim))
- return false;
+ if (verbosity >= 2 && cnt % 100 == 0)
+ printf("elimination left: %10d\r", elim_heap.size());
+
+ if (use_asymm){
+ // Temporarily freeze variable. Otherwise, it would immediately end up on the queue again:
+ bool was_frozen = frozen[elim];
+ frozen[elim] = true;
+ if (!asymmVar(elim)){
+ ok = false; goto cleanup; }
+ frozen[elim] = was_frozen; }
+
+ // At this point, the variable may have been set by assymetric branching, so check it
+ // again. Also, don't eliminate frozen variables:
+ if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){
+ ok = false; goto cleanup; }
+
+ checkGarbage(simp_garbage_frac);
}
assert(subsumption_queue.size() == 0);
- gatherTouchedClauses();
- }
-
- // Cleanup:
- cleanUpClauses();
- order_heap.filter(VarFilter(*this));
-
-#ifdef INVARIANTS
- // Check that no more subsumption is possible:
- reportf("Checking that no more subsumption is possible\n");
- for (int i = 0; i < clauses.size(); i++){
- if (i % 1000 == 0)
- reportf("left %10d\r", clauses.size() - i);
-
- assert(clauses[i]->mark() == 0);
- for (int j = 0; j < i; j++)
- assert(clauses[i]->subsumes(*clauses[j]) == lit_Error);
}
- reportf("done.\n");
-
- // Check that no more elimination is possible:
- reportf("Checking that no more elimination is possible\n");
- for (int i = 0; i < nVars(); i++)
- if (!frozen[i]) eliminateVar(i, true);
- reportf("done.\n");
- checkLiteralCount();
-#endif
+ cleanup:
// If no more simplification is needed, free all simplification-related data structures:
if (turn_off_elim){
- use_simplification = false;
- touched.clear(true);
- occurs.clear(true);
- n_occ.clear(true);
- subsumption_queue.clear(true);
+ touched .clear(true);
+ occurs .clear(true);
+ n_occ .clear(true);
elim_heap.clear(true);
- remove_satisfied = true;
+ subsumption_queue.clear(true);
+
+ use_simplification = false;
+ remove_satisfied = true;
+ ca.extra_clause_field = false;
+
+ // Force full cleanup (this is safe and desirable since it only happens once):
+ rebuildOrderHeap();
+ garbageCollect();
+ }else{
+ // Cheaper cleanup:
+ cleanUpClauses(); // TODO: can we make 'cleanUpClauses()' not be linear in the problem size somehow?
+ checkGarbage();
}
+ if (verbosity >= 1 && elimclauses.size() > 0)
+ printf("| Eliminated clauses: %10.2f Mb |\n",
+ double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024));
- return true;
+ return ok;
}
void SimpSolver::cleanUpClauses()
{
- int i , j;
- vec<Var> dirty;
- for (i = 0; i < clauses.size(); i++)
- if (clauses[i]->mark() == 1){
- Clause& c = *clauses[i];
- for (int k = 0; k < c.size(); k++)
- if (!seen[var(c[k])]){
- seen[var(c[k])] = 1;
- dirty.push(var(c[k]));
- } }
-
- for (i = 0; i < dirty.size(); i++){
- cleanOcc(dirty[i]);
- seen[dirty[i]] = 0; }
-
+ occurs.cleanAll();
+ int i,j;
for (i = j = 0; i < clauses.size(); i++)
- if (clauses[i]->mark() == 1)
- free(clauses[i]);
- else
+ if (ca[clauses[i]].mark() == 0)
clauses[j++] = clauses[i];
clauses.shrink(i - j);
}
//=================================================================================================
-// Convert to DIMACS:
+// Garbage Collection methods:
-void SimpSolver::toDimacs(FILE* f, Clause& c)
+void SimpSolver::relocAll(ClauseAllocator& to)
{
- if (satisfied(c)) return;
+ if (!use_simplification) return;
+
+ // All occurs lists:
+ //
+ for (int i = 0; i < nVars(); i++){
+ vec<CRef>& cs = occurs[i];
+ for (int j = 0; j < cs.size(); j++)
+ ca.reloc(cs[j], to);
+ }
- for (int i = 0; i < c.size(); i++)
- if (value(c[i]) != l_False)
- fprintf(f, "%s%d ", sign(c[i]) ? "-" : "", var(c[i])+1);
- fprintf(f, "0\n");
+ // Subsumption queue:
+ //
+ for (int i = 0; i < subsumption_queue.size(); i++)
+ ca.reloc(subsumption_queue[i], to);
+
+ // Temporary clause:
+ //
+ ca.reloc(bwdsub_tmpunit, to);
}
-void SimpSolver::toDimacs(const char* file)
+void SimpSolver::garbageCollect()
{
- assert(decisionLevel() == 0);
- FILE* f = fopen(file, "wr");
- if (f != NULL){
+ // Initialize the next region to a size corresponding to the estimated utilization degree. This
+ // is not precise but should avoid some unnecessary reallocations for the new region:
+ ClauseAllocator to(ca.size() - ca.wasted());
- // Cannot use removeClauses here because it is not safe
- // to deallocate them at this point. Could be improved.
- int cnt = 0;
- for (int i = 0; i < clauses.size(); i++)
- if (!satisfied(*clauses[i]))
- cnt++;
-
- fprintf(f, "p cnf %d %d\n", nVars(), cnt);
-
- for (int i = 0; i < clauses.size(); i++)
- toDimacs(f, *clauses[i]);
-
- fprintf(stderr, "Wrote %d clauses...\n", clauses.size());
- }else
- fprintf(stderr, "could not open file %s\n", file);
+ cleanUpClauses();
+ to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields.
+ relocAll(to);
+ Solver::relocAll(to);
+ if (verbosity >= 2)
+ printf("| Garbage collection: %12d bytes => %12d bytes |\n",
+ ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
+ to.moveTo(ca);
}
-
-}/* CVC4::prop::minisat namespace */
-}/* CVC4::prop namespace */
-}/* CVC4 namespace */
diff --git a/src/prop/minisat/simp/SimpSolver.h b/src/prop/minisat/simp/SimpSolver.h
index 3da574f6c..977da46e5 100644
--- a/src/prop/minisat/simp/SimpSolver.h
+++ b/src/prop/minisat/simp/SimpSolver.h
@@ -1,5 +1,6 @@
/************************************************************************************[SimpSolver.h]
-MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
@@ -17,158 +18,187 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
-#include "cvc4_private.h"
+#ifndef Minisat_SimpSolver_h
+#define Minisat_SimpSolver_h
-#ifndef __CVC4__PROP__MINISAT__SIMP_SOLVER_H
-#define __CVC4__PROP__MINISAT__SIMP_SOLVER_H
+#include "cvc4_private.h"
-#include <cstdio>
-#include <cassert>
+#include "mtl/Queue.h"
+#include "core/Solver.h"
-#include "../mtl/Queue.h"
-#include "../core/Solver.h"
namespace CVC4 {
namespace prop {
+ class SatSolver;
+}
+}
-class SatSolver;
+namespace Minisat {
-namespace minisat {
+//=================================================================================================
class SimpSolver : public Solver {
public:
// Constructor/Destructor:
//
- SimpSolver(SatSolver* proxy, context::Context* context);
+ SimpSolver(CVC4::prop::SatSolver* proxy, CVC4::context::Context* context);
CVC4_PUBLIC ~SimpSolver();
// Problem specification:
//
Var newVar (bool polarity = true, bool dvar = true, bool theoryAtom = false);
- bool addClause (vec<Lit>& ps, ClauseType type);
+ bool addClause (const vec<Lit>& ps, ClauseType type);
+ bool addEmptyClause(ClauseType type); // Add the empty clause to the solver.
+ bool addClause (Lit p, ClauseType type); // Add a unit clause to the solver.
+ bool addClause (Lit p, Lit q, ClauseType type); // Add a binary clause to the solver.
+ bool addClause (Lit p, Lit q, Lit r, ClauseType type); // Add a ternary clause to the solver.
+ bool addClause_( vec<Lit>& ps, ClauseType type);
+ bool substitute(Var v, Lit x); // Replace all occurences of v with x (may cause a contradiction).
// Variable mode:
//
void setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated.
+ bool isEliminated(Var v) const;
// Solving:
//
- bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
- bool solve (bool do_simp = true, bool turn_off_simp = false);
- bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification.
+ bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
+ lbool solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
+ bool solve ( bool do_simp = true, bool turn_off_simp = false);
+ bool solve (Lit p , bool do_simp = true, bool turn_off_simp = false);
+ bool solve (Lit p, Lit q, bool do_simp = true, bool turn_off_simp = false);
+ bool solve (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false);
+ bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification.
+
+ // Memory managment:
+ //
+ virtual void garbageCollect();
+
// Generate a (possibly simplified) DIMACS file:
//
+#if 0
+ void toDimacs (const char* file, const vec<Lit>& assumps);
void toDimacs (const char* file);
+ void toDimacs (const char* file, Lit p);
+ void toDimacs (const char* file, Lit p, Lit q);
+ void toDimacs (const char* file, Lit p, Lit q, Lit r);
+#endif
// Mode of operation:
//
- int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero).
- bool asymm_mode; // Shrink clauses by asymmetric branching.
- bool redundancy_check; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
+ int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero).
+ int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit.
+ // -1 means no limit.
+ int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit.
+ double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').
+
+ bool use_asymm; // Shrink clauses by asymmetric branching.
+ bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
+ bool use_elim; // Perform variable elimination.
// Statistics:
//
int merges;
int asymm_lits;
- int remembered_clauses;
+ int eliminated_vars;
-// protected:
- public:
+ protected:
// Helper structures:
//
- struct ElimData {
- int order; // 0 means not eliminated, >0 gives an index in the elimination order
- vec<Clause*> eliminated;
- ElimData() : order(0) {} };
-
- struct ElimOrderLt {
- const vec<ElimData>& elimtable;
- ElimOrderLt(const vec<ElimData>& et) : elimtable(et) {}
- bool operator()(Var x, Var y) { return elimtable[x].order > elimtable[y].order; } };
-
struct ElimLt {
const vec<int>& n_occ;
- ElimLt(const vec<int>& no) : n_occ(no) {}
- int cost (Var x) const { return n_occ[toInt(Lit(x))] * n_occ[toInt(~Lit(x))]; }
- bool operator()(Var x, Var y) const { return cost(x) < cost(y); } };
-
+ explicit ElimLt(const vec<int>& no) : n_occ(no) {}
+
+ // TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating
+ // 32-bit implementation instead then, but this will have to do for now.
+ uint64_t cost (Var x) const { return (uint64_t)n_occ[toInt(mkLit(x))] * (uint64_t)n_occ[toInt(~mkLit(x))]; }
+ bool operator()(Var x, Var y) const { return cost(x) < cost(y); }
+
+ // TODO: investigate this order alternative more.
+ // bool operator()(Var x, Var y) const {
+ // int c_x = cost(x);
+ // int c_y = cost(y);
+ // return c_x < c_y || c_x == c_y && x < y; }
+ };
+
+ struct ClauseDeleted {
+ const ClauseAllocator& ca;
+ explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
+ bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } };
// Solver state:
//
int elimorder;
bool use_simplification;
- vec<ElimData> elimtable;
+ vec<uint32_t> elimclauses;
vec<char> touched;
- vec<vec<Clause*> > occurs;
+ OccLists<Var, vec<CRef>, ClauseDeleted>
+ occurs;
vec<int> n_occ;
Heap<ElimLt> elim_heap;
- Queue<Clause*> subsumption_queue;
+ Queue<CRef> subsumption_queue;
vec<char> frozen;
+ vec<char> eliminated;
int bwdsub_assigns;
+ int n_touched;
// Temporaries:
//
- Clause* bwdsub_tmpunit;
+ CRef bwdsub_tmpunit;
// Main internal methods:
//
- bool asymm (Var v, Clause& c);
+ lbool solve_ (bool do_simp = true, bool turn_off_simp = false);
+ bool asymm (Var v, CRef cr);
bool asymmVar (Var v);
void updateElimHeap (Var v);
- void cleanOcc (Var v);
- vec<Clause*>& getOccurs (Var x);
void gatherTouchedClauses ();
bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);
- bool merge (const Clause& _ps, const Clause& _qs, Var v);
+ bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size);
bool backwardSubsumptionCheck (bool verbose = false);
- bool eliminateVar (Var v, bool fail = false);
- void remember (Var v);
+ bool eliminateVar (Var v);
void extendModel ();
- void verifyModel ();
- void removeClause (Clause& c);
- bool strengthenClause (Clause& c, Lit l);
+ void removeClause (CRef cr);
+ bool strengthenClause (CRef cr, Lit l);
void cleanUpClauses ();
bool implied (const vec<Lit>& c);
- void toDimacs (FILE* f, Clause& c);
- bool isEliminated (Var v) const;
-
+ void relocAll (ClauseAllocator& to);
};
//=================================================================================================
// Implementation of inline methods:
+
+inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; }
inline void SimpSolver::updateElimHeap(Var v) {
- if (elimtable[v].order == 0)
+ assert(use_simplification);
+ // if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)
+ if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef))
elim_heap.update(v); }
-inline void SimpSolver::cleanOcc(Var v) {
- assert(use_simplification);
- Clause **begin = (Clause**)occurs[v];
- Clause **end = begin + occurs[v].size();
- Clause **i, **j;
- for (i = begin, j = end; i < j; i++)
- if ((*i)->mark() == 1){
- *i = *(--j);
- i--;
- }
- //occurs[v].shrink_(end - j); // This seems slower. Why?!
- occurs[v].shrink(end - j);
-}
-inline vec<Clause*>& SimpSolver::getOccurs(Var x) {
- cleanOcc(x); return occurs[x]; }
+inline bool SimpSolver::addClause (const vec<Lit>& ps, ClauseType type) { ps.copyTo(add_tmp); return addClause_(add_tmp, type); }
+inline bool SimpSolver::addEmptyClause(ClauseType type) { add_tmp.clear(); return addClause_(add_tmp, type); }
+inline bool SimpSolver::addClause (Lit p, ClauseType type) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp, type); }
+inline bool SimpSolver::addClause (Lit p, Lit q, ClauseType type) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp, type); }
+inline bool SimpSolver::addClause (Lit p, Lit q, Lit r, ClauseType type) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp, type); }
+inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } }
-inline bool SimpSolver::isEliminated (Var v) const { return v < elimtable.size() && elimtable[v].order != 0; }
-inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (b) { updateElimHeap(v); } }
-inline bool SimpSolver::solve (bool do_simp, bool turn_off_simp) { vec<Lit> tmp; return solve(tmp, do_simp, turn_off_simp); }
+inline bool SimpSolver::solve ( bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve (Lit p , bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve (Lit p, Lit q, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
+ budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; }
-}/* CVC4::prop::minisat namespace */
-}/* CVC4::prop namespace */
-}/* CVC4 namespace */
+inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
+ assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); }
//=================================================================================================
-#endif /* __CVC4__PROP__MINISAT__SIMP_SOLVER_H */
+}
+
+#endif
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback