From: Dejan Jovanović Date: Fri, 13 Aug 2010 17:47:56 +0000 (+0000) Subject: renaming minisat .C to .cc X-Git-Tag: cvc5-1.0.0~8893 X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=58ea6b0b63d2170391a61e0fe3b1a3ecf3b99fb2;p=cvc5.git renaming minisat .C to .cc --- diff --git a/src/prop/minisat/core/Main.C b/src/prop/minisat/core/Main.C deleted file mode 100644 index acef32cd5..000000000 --- a/src/prop/minisat/core/Main.C +++ /dev/null @@ -1,344 +0,0 @@ -/******************************************************************************************[Main.C] -MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, -including without limitation the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT -NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT -OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -**************************************************************************************************/ - -#include -#include -#include -#include - -#include -#include - -#include "Solver.h" - -/*************************************************************************************/ -#ifdef _MSC_VER -#include - -static inline double cpuTime(void) { - return (double)clock() / CLOCKS_PER_SEC; } -#else - -#include -#include -#include - -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 -#endif - -//================================================================================================= -// 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 -static void skipWhitespace(B& in) { - while ((*in >= 9 && *in <= 13) || *in == 32) - ++in; } - -template -static void skipLine(B& in) { - for (;;){ - if (*in == EOF || *in == '\0') return; - if (*in == '\n') { ++in; return; } - ++in; } } - -template -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 -static void readClause(B& in, Solver& S, vec& 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 -static bool match(B& in, char* str) { - for (; *str != 0; ++str, ++in) - if (*str != *in) - return false; - return true; -} - - -template -static void parse_DIMACS_main(B& in, Solver& S) { - vec 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); - }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); - } -} - -// Inserts problem into solver. -// -static void parse_DIMACS(gzFile input_stream, Solver& S) { - StreamBuffer in(input_stream); - parse_DIMACS_main(in, S); } - - -//================================================================================================= - - -void printStats(Solver& solver) -{ - double cpu_time = cpuTime(); - uint64_t mem_used = memUsed(); - reportf("restarts : %lld\n", solver.starts); - reportf("conflicts : %-12lld (%.0f /sec)\n", solver.conflicts , solver.conflicts /cpu_time); - reportf("decisions : %-12lld (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions /cpu_time); - reportf("propagations : %-12lld (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time); - reportf("conflict literals : %-12lld (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals); - if (mem_used != 0) reportf("Memory used : %.2f MB\n", mem_used / 1048576.0); - reportf("CPU time : %g s\n", cpu_time); -} - -Solver* solver; -static void SIGINT_handler(int signum) { - reportf("\n"); reportf("*** INTERRUPTED ***\n"); - printStats(*solver); - reportf("\n"); reportf("*** INTERRUPTED ***\n"); - exit(1); } - - -//================================================================================================= -// Main: - -void printUsage(char** argv) -{ - reportf("USAGE: %s [options] \n\n where input may be either in plain or gzipped DIMACS.\n\n", argv[0]); - reportf("OPTIONS:\n\n"); - reportf(" -polarity-mode = {true,false,rnd}\n"); - reportf(" -decay = [ 0 - 1 ]\n"); - reportf(" -rnd-freq = [ 0 - 1 ]\n"); - reportf(" -verbosity = {0,1,2}\n"); - reportf("\n"); -} - - -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) -{ - Solver S; - S.verbosity = 1; - - - 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 (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 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; - - - reportf("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"); -#endif - double cpu_time = cpuTime(); - - 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 ? "" : 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); - - if (!S.simplify()){ - reportf("Solved by unit propagation\n"); - if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res); - printf("UNSATISFIABLE\n"); - exit(20); - } - - bool ret = S.solve(); - printStats(S); - reportf("\n"); - printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n"); - if (res != NULL){ - if (ret){ - 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 - fprintf(res, "UNSAT\n"); - fclose(res); - } - -#ifdef NDEBUG - exit(ret ? 10 : 20); // (faster than "return", which will invoke the destructor for 'Solver') -#endif -} diff --git a/src/prop/minisat/core/Main.cc b/src/prop/minisat/core/Main.cc new file mode 100644 index 000000000..acef32cd5 --- /dev/null +++ b/src/prop/minisat/core/Main.cc @@ -0,0 +1,344 @@ +/******************************************************************************************[Main.C] +MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include +#include +#include +#include + +#include +#include + +#include "Solver.h" + +/*************************************************************************************/ +#ifdef _MSC_VER +#include + +static inline double cpuTime(void) { + return (double)clock() / CLOCKS_PER_SEC; } +#else + +#include +#include +#include + +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 +#endif + +//================================================================================================= +// 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 +static void skipWhitespace(B& in) { + while ((*in >= 9 && *in <= 13) || *in == 32) + ++in; } + +template +static void skipLine(B& in) { + for (;;){ + if (*in == EOF || *in == '\0') return; + if (*in == '\n') { ++in; return; } + ++in; } } + +template +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 +static void readClause(B& in, Solver& S, vec& 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 +static bool match(B& in, char* str) { + for (; *str != 0; ++str, ++in) + if (*str != *in) + return false; + return true; +} + + +template +static void parse_DIMACS_main(B& in, Solver& S) { + vec 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); + }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); + } +} + +// Inserts problem into solver. +// +static void parse_DIMACS(gzFile input_stream, Solver& S) { + StreamBuffer in(input_stream); + parse_DIMACS_main(in, S); } + + +//================================================================================================= + + +void printStats(Solver& solver) +{ + double cpu_time = cpuTime(); + uint64_t mem_used = memUsed(); + reportf("restarts : %lld\n", solver.starts); + reportf("conflicts : %-12lld (%.0f /sec)\n", solver.conflicts , solver.conflicts /cpu_time); + reportf("decisions : %-12lld (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions /cpu_time); + reportf("propagations : %-12lld (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time); + reportf("conflict literals : %-12lld (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals); + if (mem_used != 0) reportf("Memory used : %.2f MB\n", mem_used / 1048576.0); + reportf("CPU time : %g s\n", cpu_time); +} + +Solver* solver; +static void SIGINT_handler(int signum) { + reportf("\n"); reportf("*** INTERRUPTED ***\n"); + printStats(*solver); + reportf("\n"); reportf("*** INTERRUPTED ***\n"); + exit(1); } + + +//================================================================================================= +// Main: + +void printUsage(char** argv) +{ + reportf("USAGE: %s [options] \n\n where input may be either in plain or gzipped DIMACS.\n\n", argv[0]); + reportf("OPTIONS:\n\n"); + reportf(" -polarity-mode = {true,false,rnd}\n"); + reportf(" -decay = [ 0 - 1 ]\n"); + reportf(" -rnd-freq = [ 0 - 1 ]\n"); + reportf(" -verbosity = {0,1,2}\n"); + reportf("\n"); +} + + +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) +{ + Solver S; + S.verbosity = 1; + + + 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 (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 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; + + + reportf("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"); +#endif + double cpu_time = cpuTime(); + + 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 ? "" : 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); + + if (!S.simplify()){ + reportf("Solved by unit propagation\n"); + if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res); + printf("UNSATISFIABLE\n"); + exit(20); + } + + bool ret = S.solve(); + printStats(S); + reportf("\n"); + printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n"); + if (res != NULL){ + if (ret){ + 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 + fprintf(res, "UNSAT\n"); + fclose(res); + } + +#ifdef NDEBUG + exit(ret ? 10 : 20); // (faster than "return", which will invoke the destructor for 'Solver') +#endif +} diff --git a/src/prop/minisat/core/Solver.C b/src/prop/minisat/core/Solver.C deleted file mode 100644 index 1667af20d..000000000 --- a/src/prop/minisat/core/Solver.C +++ /dev/null @@ -1,899 +0,0 @@ -/****************************************************************************************[Solver.C] -MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, -including without limitation the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT -NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT -OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -**************************************************************************************************/ - -#include "Solver.h" -#include "Sort.h" -#include "prop/sat.h" -#include - -//================================================================================================= -// Constructor/Destructor: - -namespace CVC4 { -namespace prop { -namespace minisat { - -Clause* Solver::lazy_reason = reinterpret_cast(1); - -Clause* Solver::getReason(Lit l) -{ - if (reason[var(l)] != lazy_reason) return reason[var(l)]; - // Get the explanation from the theory - SatClause explanation; - if (value(l) == l_True) { - proxy->explainPropagation(l, explanation); - assert(explanation[0] == l); - } else { - proxy->explainPropagation(~l, explanation); - assert(explanation[0] == ~l); - } - Clause* real_reason = Clause_new(explanation, true); - reason[var(l)] = real_reason; - // Add it to the database - learnts.push(real_reason); - attachClause(*real_reason); - return real_reason; -} - -Solver::Solver(SatSolver* proxy, context::Context* context) : - - // SMT stuff - proxy(proxy) - , context(context) - - // Parameters: (formerly in 'SearchParams') - , var_decay(1 / 0.95), clause_decay(1 / 0.999), random_var_freq(0.02) - , restart_first(100), restart_inc(1.5), learntsize_factor((double)1/(double)3), learntsize_inc(1.1) - - // More parameters: - // - , expensive_ccmin (true) - , polarity_mode (polarity_false) - , verbosity (0) - - // Statistics: (formerly in 'SolverStats') - // - , starts(0), decisions(0), rnd_decisions(0), propagations(0), conflicts(0) - , clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0) - - , ok (true) - , cla_inc (1) - , var_inc (1) - , qhead (0) - , simpDB_assigns (-1) - , simpDB_props (0) - , order_heap (VarOrderLt(activity)) - , random_seed (91648253) - , progress_estimate(0) - , remove_satisfied (true) -{} - - -Solver::~Solver() -{ - for (int i = 0; i < learnts.size(); i++) free(learnts[i]); - for (int i = 0; i < clauses.size(); i++) free(clauses[i]); -} - - -//================================================================================================= -// Minor methods: - - -// Creates a new SAT variable in the solver. If 'decision_var' is cleared, variable will not be -// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result). -// -Var Solver::newVar(bool sign, bool dvar, bool theoryAtom) -{ - int v = nVars(); - watches .push(); // (list for positive literal) - watches .push(); // (list for negative literal) - reason .push(NULL); - assigns .push(toInt(l_Undef)); - level .push(-1); - activity .push(0); - seen .push(0); - - theory .push(theoryAtom); - - polarity .push((char)sign); - decision_var.push((char)dvar); - - insertVarOrder(v); - return v; -} - - -bool Solver::addClause(vec& ps, ClauseType type) -{ - assert(decisionLevel() == 0); - - if (!ok) - return false; - else{ - // Check if clause is satisfied and remove false/duplicate literals: - sort(ps); - Lit p; int i, j; - for (i = j = 0, p = lit_Undef; i < ps.size(); i++) - if (value(ps[i]) == l_True || ps[i] == ~p) - return true; - else if (value(ps[i]) != l_False && ps[i] != p) - ps[j++] = p = ps[i]; - ps.shrink(i - j); - } - - if (ps.size() == 0) - return ok = false; - else if (ps.size() == 1){ - assert(type != CLAUSE_LEMMA); - assert(value(ps[0]) == l_Undef); - uncheckedEnqueue(ps[0]); - return ok = (propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) == NULL); - }else{ - Clause* c = Clause_new(ps, false); - clauses.push(c); - if (type == CLAUSE_LEMMA) lemmas.push(c); - attachClause(*c); - } - - return true; - -} - - -void Solver::attachClause(Clause& c) { - assert(c.size() > 1); - watches[toInt(~c[0])].push(&c); - watches[toInt(~c[1])].push(&c); - if (c.learnt()) learnts_literals += c.size(); - else clauses_literals += c.size(); } - - -void Solver::detachClause(Clause& c) { - Debug("minisat") << "Solver::detachClause(" << c << ")" << std::endl; - assert(c.size() > 1); - assert(find(watches[toInt(~c[0])], &c)); - assert(find(watches[toInt(~c[1])], &c)); - remove(watches[toInt(~c[0])], &c); - remove(watches[toInt(~c[1])], &c); - if (c.learnt()) learnts_literals -= c.size(); - else clauses_literals -= c.size(); } - - -void Solver::removeClause(Clause& c) { - Debug("minisat") << "Solver::removeClause(" << c << ")" << std::endl; - detachClause(c); - free(&c); -} - - -bool Solver::satisfied(const Clause& c) const { - for (int i = 0; i < c.size(); i++) - if (value(c[i]) == l_True) - return true; - return false; } - - -// Revert to the state at given level (keeping all assignment at 'level' but not beyond). -// -void Solver::cancelUntil(int level) { - if (decisionLevel() > level){ - // Pop the SMT context - for (int l = trail_lim.size() - level; l > 0; --l) - context->pop(); - // Now the minisat stuff - for (int c = trail.size()-1; c >= trail_lim[level]; c--) { - Var x = var(trail[c]); - assigns[x] = toInt(l_Undef); - insertVarOrder(x); - } - qhead = trail_lim[level]; - trail.shrink(trail.size() - trail_lim[level]); - trail_lim.shrink(trail_lim.size() - level); - // We can erase the lemmas now - for (int c = lemmas.size() - 1; c >= lemmas_lim[level]; c--) { - // TODO: can_erase[lemma[c]] = true; - } - lemmas.shrink(lemmas.size() - lemmas_lim[level]); - lemmas_lim.shrink(lemmas_lim.size() - level); - } -} - - -//================================================================================================= -// Major methods: - - -Lit Solver::pickBranchLit(int polarity_mode, double random_var_freq) -{ - Var next = var_Undef; - - // Random decision: - if (drand(random_seed) < random_var_freq && !order_heap.empty()){ - next = order_heap[irand(random_seed,order_heap.size())]; - if (toLbool(assigns[next]) == l_Undef && decision_var[next]) - rnd_decisions++; } - - // Activity based decision: - while (next == var_Undef || toLbool(assigns[next]) != l_Undef || !decision_var[next]) - if (order_heap.empty()){ - next = var_Undef; - break; - }else - next = order_heap.removeMin(); - - bool sign = false; - switch (polarity_mode){ - case polarity_true: sign = false; break; - case polarity_false: sign = true; break; - case polarity_user: sign = polarity[next]; break; - case polarity_rnd: sign = irand(random_seed, 2); break; - default: assert(false); } - - return next == var_Undef ? lit_Undef : Lit(next, sign); -} - - -/*_________________________________________________________________________________________________ -| -| analyze : (confl : Clause*) (out_learnt : vec&) (out_btlevel : int&) -> [void] -| -| Description: -| Analyze conflict and produce a reason clause. -| -| Pre-conditions: -| * 'out_learnt' is assumed to be cleared. -| * Current decision level must be greater than root level. -| -| Post-conditions: -| * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'. -| -| Effect: -| Will undo part of the trail, upto but not beyond the assumption of the current decision level. -|________________________________________________________________________________________________@*/ -void Solver::analyze(Clause* confl, vec& out_learnt, int& out_btlevel) -{ - int pathC = 0; - Lit p = lit_Undef; - - // Generate conflict clause: - // - out_learnt.push(); // (leave room for the asserting literal) - int index = trail.size() - 1; - out_btlevel = 0; - - do{ - assert(confl != NULL); // (otherwise should be UIP) - Clause& c = *confl; - - if (c.learnt()) - claBumpActivity(c); - - for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){ - Lit q = c[j]; - - if (!seen[var(q)] && level[var(q)] > 0){ - varBumpActivity(var(q)); - seen[var(q)] = 1; - if (level[var(q)] >= decisionLevel()) - pathC++; - else{ - out_learnt.push(q); - if (level[var(q)] > out_btlevel) - out_btlevel = level[var(q)]; - } - } - } - - // Select next clause to look at: - while (!seen[var(trail[index--])]); - p = trail[index+1]; - confl = getReason(p); - seen[var(p)] = 0; - pathC--; - - }while (pathC > 0); - out_learnt[0] = ~p; - - // Simplify conflict clause: - // - int i, j; - if (expensive_ccmin){ - uint32_t abstract_level = 0; - for (i = 1; i < out_learnt.size(); i++) - abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict) - - out_learnt.copyTo(analyze_toclear); - for (i = j = 1; i < out_learnt.size(); i++) - if (getReason(out_learnt[i]) == NULL || !litRedundant(out_learnt[i], abstract_level)) - out_learnt[j++] = out_learnt[i]; - }else{ - out_learnt.copyTo(analyze_toclear); - for (i = j = 1; i < out_learnt.size(); i++){ - Clause& c = *getReason(out_learnt[i]); - for (int k = 1; k < c.size(); k++) - if (!seen[var(c[k])] && level[var(c[k])] > 0){ - out_learnt[j++] = out_learnt[i]; - break; } - } - } - max_literals += out_learnt.size(); - out_learnt.shrink(i - j); - tot_literals += out_learnt.size(); - - // Find correct backtrack level: - // - if (out_learnt.size() == 1) - out_btlevel = 0; - else{ - int max_i = 1; - for (int i = 2; i < out_learnt.size(); i++) - if (level[var(out_learnt[i])] > level[var(out_learnt[max_i])]) - max_i = i; - Lit p = out_learnt[max_i]; - out_learnt[max_i] = out_learnt[1]; - out_learnt[1] = p; - out_btlevel = level[var(p)]; - } - - - for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared) -} - - -// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is -// visiting literals at levels that cannot be removed later. -bool Solver::litRedundant(Lit p, uint32_t abstract_levels) -{ - analyze_stack.clear(); analyze_stack.push(p); - int top = analyze_toclear.size(); - while (analyze_stack.size() > 0){ - assert(getReason(analyze_stack.last()) != NULL); - Clause& c = *reason[var(analyze_stack.last())]; analyze_stack.pop(); - - for (int i = 1; i < c.size(); i++){ - Lit p = c[i]; - if (!seen[var(p)] && level[var(p)] > 0){ - if (getReason(p) != NULL && (abstractLevel(var(p)) & abstract_levels) != 0){ - seen[var(p)] = 1; - analyze_stack.push(p); - analyze_toclear.push(p); - }else{ - for (int j = top; j < analyze_toclear.size(); j++) - seen[var(analyze_toclear[j])] = 0; - analyze_toclear.shrink(analyze_toclear.size() - top); - return false; - } - } - } - } - - return true; -} - - -/*_________________________________________________________________________________________________ -| -| analyzeFinal : (p : Lit) -> [void] -| -| Description: -| Specialized analysis procedure to express the final conflict in terms of assumptions. -| Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and -| stores the result in 'out_conflict'. -|________________________________________________________________________________________________@*/ -void Solver::analyzeFinal(Lit p, vec& out_conflict) -{ - out_conflict.clear(); - out_conflict.push(p); - - if (decisionLevel() == 0) - return; - - seen[var(p)] = 1; - - for (int i = trail.size()-1; i >= trail_lim[0]; i--){ - Var x = var(trail[i]); - if (seen[x]){ - if (reason[x] == NULL){ - assert(level[x] > 0); - out_conflict.push(~trail[i]); - }else{ - Clause& c = *reason[x]; - for (int j = 1; j < c.size(); j++) - if (level[var(c[j])] > 0) - seen[var(c[j])] = 1; - } - seen[x] = 0; - } - } - - seen[var(p)] = 0; -} - - -void Solver::uncheckedEnqueue(Lit p, Clause* from) -{ - assert(value(p) == l_Undef); - assigns [var(p)] = toInt(lbool(!sign(p))); // <<== abstract but not uttermost efficient - level [var(p)] = decisionLevel(); - reason [var(p)] = from; - // Added for phase-caching - polarity [var(p)] = sign(p); - trail.push(p); - - if (theory[var(p)] && from != lazy_reason) { - // Enqueue to the theory - proxy->enqueueTheoryLiteral(p); - } -} - - -Clause* Solver::propagate(TheoryCheckType type) -{ - Clause* confl = NULL; - - // If this is the final check, no need for Boolean propagation and - // theory propagation - if (type == CHECK_WITHOUTH_PROPAGATION_FINAL) { - return theoryCheck(theory::Theory::FULL_EFFORT); - } - - // The effort we will be using to theory check - theory::Theory::Effort effort = type == CHECK_WITHOUTH_PROPAGATION_QUICK ? - theory::Theory::QUICK_CHECK : theory::Theory::STANDARD; - - // Keep running until we have checked everything, we - // have no conflict and no new literals have been asserted - bool new_assertions; - do { - new_assertions = false; - while(qhead < trail.size()) { - confl = propagateBool(); - if (confl != NULL) break; - confl = theoryCheck(effort); - if (confl != NULL) break; - } - - if (confl == NULL && type == CHECK_WITH_PROPAGATION_STANDARD) { - new_assertions = propagateTheory(); - if (!new_assertions) break; - } - } while (new_assertions); - - return confl; -} - -bool Solver::propagateTheory() { - std::vector propagatedLiterals; - proxy->theoryPropagate(propagatedLiterals); - const unsigned i_end = propagatedLiterals.size(); - for (unsigned i = 0; i < i_end; ++ i) { - uncheckedEnqueue(propagatedLiterals[i], lazy_reason); - } - proxy->clearPropagatedLiterals(); - return propagatedLiterals.size() > 0; -} - -/*_________________________________________________________________________________________________ -| -| theoryCheck: [void] -> [Clause*] -| -| Description: -| Checks all enqueued theory facts for satisfiability. If a conflict arises, the conflicting -| clause is returned, otherwise NULL. -| -| Note: the propagation queue might be NOT empty -|________________________________________________________________________________________________@*/ -Clause* Solver::theoryCheck(theory::Theory::Effort effort) -{ - Clause* c = NULL; - SatClause clause; - proxy->theoryCheck(effort, clause); - int clause_size = clause.size(); - Assert(clause_size != 1, "Can't handle unit clause explanations"); - if(clause_size > 0) { - // Find the max level of the conflict - int max_level = 0; - for (int i = 0; i < clause_size; ++i) { - int current_level = level[var(clause[i])]; - Debug("minisat") << "Literal: " << clause[i] << " with reason " << reason[var(clause[i])] << " at level " << current_level << std::endl; - Assert(toLbool(assigns[var(clause[i])]) != l_Undef, "Got an unassigned literal in conflict!"); - if (current_level > max_level) max_level = current_level; - } - // If smaller than the decision level then pop back so we can analyse - Debug("minisat") << "Max-level is " << max_level << " in decision level " << decisionLevel() << std::endl; - Assert(max_level <= decisionLevel(), "What is going on, can't get literals of a higher level as conflict!"); - if (max_level < decisionLevel()) { - Debug("minisat") << "Max-level is " << max_level << " in decision level " << decisionLevel() << std::endl; - cancelUntil(max_level); - } - // Create the new clause and attach all the information - c = Clause_new(clause, true); - learnts.push(c); - attachClause(*c); - } - return c; -} - -/*_________________________________________________________________________________________________ -| -| propagateBool : [void] -> [Clause*] -| -| Description: -| Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned, -| otherwise NULL. -| -| Post-conditions: -| * the propagation queue is empty, even if there was a conflict. -|________________________________________________________________________________________________@*/ -Clause* Solver::propagateBool() -{ - Clause* confl = NULL; - int num_props = 0; - - while (qhead < trail.size()){ - Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. - vec& ws = watches[toInt(p)]; - Clause **i, **j, **end; - num_props++; - - for (i = j = (Clause**)ws, end = i + ws.size(); i != end;){ - Clause& c = **i++; - - // Make sure the false literal is data[1]: - Lit false_lit = ~p; - if (c[0] == false_lit) - c[0] = c[1], c[1] = false_lit; - - assert(c[1] == false_lit); - - // If 0th watch is true, then clause is already satisfied. - Lit first = c[0]; - if (value(first) == l_True){ - *j++ = &c; - }else{ - // Look for new watch: - for (int k = 2; k < c.size(); k++) - if (value(c[k]) != l_False){ - c[1] = c[k]; c[k] = false_lit; - watches[toInt(~c[1])].push(&c); - goto FoundWatch; } - - // Did not find watch -- clause is unit under assignment: - *j++ = &c; - if (value(first) == l_False){ - confl = &c; - qhead = trail.size(); - // Copy the remaining watches: - while (i < end) - *j++ = *i++; - }else - uncheckedEnqueue(first, &c); - } - FoundWatch:; - } - ws.shrink(i - j); - } - propagations += num_props; - simpDB_props -= num_props; - - return confl; -} - -/*_________________________________________________________________________________________________ -| -| reduceDB : () -> [void] -| -| Description: -| Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked -| clauses are clauses that are reason to some assignment. Binary clauses are never removed. -|________________________________________________________________________________________________@*/ -struct reduceDB_lt { bool operator () (Clause* x, Clause* y) { return x->size() > 2 && (y->size() == 2 || x->activity() < y->activity()); } }; -void Solver::reduceDB() -{ - int i, j; - double extra_lim = cla_inc / learnts.size(); // Remove any clause below this activity - - sort(learnts, reduceDB_lt()); - for (i = j = 0; i < learnts.size() / 2; i++){ - if (learnts[i]->size() > 2 && !locked(*learnts[i])) - removeClause(*learnts[i]); - else - learnts[j++] = learnts[i]; - } - for (; i < learnts.size(); i++){ - if (learnts[i]->size() > 2 && !locked(*learnts[i]) && learnts[i]->activity() < extra_lim) - removeClause(*learnts[i]); - else - learnts[j++] = learnts[i]; - } - learnts.shrink(i - j); -} - - -void Solver::removeSatisfied(vec& cs) -{ - int i,j; - for (i = j = 0; i < cs.size(); i++){ - if (satisfied(*cs[i])) - removeClause(*cs[i]); - else - cs[j++] = cs[i]; - } - cs.shrink(i - j); -} - - -/*_________________________________________________________________________________________________ -| -| simplify : [void] -> [bool] -| -| Description: -| Simplify the clause database according to the current top-level assigment. Currently, the only -| thing done here is the removal of satisfied clauses, but more things can be put here. -|________________________________________________________________________________________________@*/ -bool Solver::simplify() -{ - assert(decisionLevel() == 0); - - if (!ok || propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL) - return ok = false; - - if (nAssigns() == simpDB_assigns || (simpDB_props > 0)) - return true; - - // Remove satisfied clauses: - removeSatisfied(learnts); - if (remove_satisfied) // Can be turned off. - removeSatisfied(clauses); - - // Remove fixed variables from the variable heap: - order_heap.filter(VarFilter(*this)); - - simpDB_assigns = nAssigns(); - simpDB_props = clauses_literals + learnts_literals; // (shouldn't depend on stats really, but it will do for now) - - return true; -} - - -/*_________________________________________________________________________________________________ -| -| search : (nof_conflicts : int) (nof_learnts : int) (params : const SearchParams&) -> [lbool] -| -| Description: -| Search for a model the specified number of conflicts, keeping the number of learnt clauses -| below the provided limit. NOTE! Use negative value for 'nof_conflicts' or 'nof_learnts' to -| indicate infinity. -| -| Output: -| 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If -| all variables are decision variables, this means that the clause set is satisfiable. 'l_False' -| if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. -|________________________________________________________________________________________________@*/ -lbool Solver::search(int nof_conflicts, int nof_learnts) -{ - assert(ok); - int backtrack_level; - int conflictC = 0; - vec learnt_clause; - - starts++; - - bool first = true; - TheoryCheckType check_type = CHECK_WITH_PROPAGATION_STANDARD; - for (;;){ - Clause* confl = propagate(check_type); - if (confl != NULL){ - // CONFLICT - conflicts++; conflictC++; - if (decisionLevel() == 0) return l_False; - - first = false; - - learnt_clause.clear(); - analyze(confl, learnt_clause, backtrack_level); - cancelUntil(backtrack_level); - assert(value(learnt_clause[0]) == l_Undef); - - if (learnt_clause.size() == 1){ - uncheckedEnqueue(learnt_clause[0]); - }else{ - Clause* c = Clause_new(learnt_clause, true); - learnts.push(c); - attachClause(*c); - claBumpActivity(*c); - uncheckedEnqueue(learnt_clause[0], c); - } - - varDecayActivity(); - claDecayActivity(); - - // We have a conflict so, we are going back to standard checks - check_type = CHECK_WITH_PROPAGATION_STANDARD; - - }else{ - // NO CONFLICT - - // If this was a final check, we are satisfiable - if (check_type == CHECK_WITHOUTH_PROPAGATION_FINAL) - return l_True; - - if (nof_conflicts >= 0 && conflictC >= nof_conflicts){ - // Reached bound on number of conflicts: - progress_estimate = progressEstimate(); - cancelUntil(0); - return l_Undef; } - - // Simplify the set of problem clauses: - if (decisionLevel() == 0 && !simplify()) - return l_False; - - if (nof_learnts >= 0 && learnts.size()-nAssigns() >= nof_learnts) - // Reduce the set of learnt clauses: - reduceDB(); - - Lit next = lit_Undef; - while (decisionLevel() < assumptions.size()){ - // Perform user provided assumption: - Lit p = assumptions[decisionLevel()]; - if (value(p) == l_True){ - // Dummy decision level: - newDecisionLevel(); - }else if (value(p) == l_False){ - analyzeFinal(~p, conflict); - return l_False; - }else{ - next = p; - break; - } - } - - if (next == lit_Undef){ - // New variable decision: - decisions++; - next = pickBranchLit(polarity_mode, random_var_freq); - - if (next == lit_Undef) { - // We need to do a full theory check to confirm - check_type = CHECK_WITHOUTH_PROPAGATION_FINAL; - continue; - } - } - - // Increase decision level and enqueue 'next' - assert(value(next) == l_Undef); - newDecisionLevel(); - uncheckedEnqueue(next); - } - } -} - - -double Solver::progressEstimate() const -{ - double progress = 0; - double F = 1.0 / nVars(); - - for (int i = 0; i <= decisionLevel(); i++){ - int beg = i == 0 ? 0 : trail_lim[i - 1]; - int end = i == decisionLevel() ? trail.size() : trail_lim[i]; - progress += pow(F, i) * (end - beg); - } - - return progress / nVars(); -} - - -bool Solver::solve(const vec& assumps) -{ - model.clear(); - conflict.clear(); - - if (!ok) return false; - - assumps.copyTo(assumptions); - - double nof_conflicts = restart_first; - double nof_learnts = nClauses() * learntsize_factor; - lbool status = l_Undef; - - if (verbosity >= 1){ - reportf("============================[ Search Statistics ]==============================\n"); - reportf("| Conflicts | ORIGINAL | LEARNT | Progress |\n"); - reportf("| | Vars Clauses Literals | Limit Clauses Lit/Cl | |\n"); - reportf("===============================================================================\n"); - } - - // Search: - while (status == l_Undef){ - if (verbosity >= 1) - reportf("| %9d | %7d %8d %8d | %8d %8d %6.0f | %6.3f %% |\n", (int)conflicts, order_heap.size(), nClauses(), (int)clauses_literals, (int)nof_learnts, nLearnts(), (double)learnts_literals/nLearnts(), progress_estimate*100), fflush(stdout); - status = search((int)nof_conflicts, (int)nof_learnts); - nof_conflicts *= restart_inc; - nof_learnts *= learntsize_inc; - } - - if (verbosity >= 1) - reportf("===============================================================================\n"); - - - if (status == l_True){ - // Extend & copy model: - model.growTo(nVars()); - for (int i = 0; i < nVars(); i++) model[i] = value(i); -#ifndef NDEBUG - verifyModel(); -#endif - }else{ - assert(status == l_False); - if (conflict.size() == 0) - ok = false; - } - - cancelUntil(0); - return status == l_True; -} - -//================================================================================================= -// Debug methods: - - -void Solver::verifyModel() -{ - bool failed = false; - for (int i = 0; i < clauses.size(); i++){ - assert(clauses[i]->mark() == 0); - Clause& c = *clauses[i]; - for (int j = 0; j < c.size(); j++) - if (modelValue(c[j]) == l_True) - goto next; - - reportf("unsatisfied clause: "); - printClause(*clauses[i]); - reportf("\n"); - failed = true; - next:; - } - - assert(!failed); - - if(verbosity >= 1) - reportf("Verified %d original clauses.\n", clauses.size()); -} - - -void Solver::checkLiteralCount() -{ - // Check that sizes are calculated correctly: - int cnt = 0; - for (int i = 0; i < clauses.size(); i++) - if (clauses[i]->mark() == 0) - cnt += clauses[i]->size(); - - if ((int)clauses_literals != cnt){ - fprintf(stderr, "literal count: %d, real value = %d\n", (int)clauses_literals, cnt); - assert((int)clauses_literals == cnt); - } -} - -}/* CVC4::prop::minisat namespace */ -}/* CVC4::prop namespace */ -}/* CVC4 namespace */ - diff --git a/src/prop/minisat/core/Solver.cc b/src/prop/minisat/core/Solver.cc new file mode 100644 index 000000000..1667af20d --- /dev/null +++ b/src/prop/minisat/core/Solver.cc @@ -0,0 +1,899 @@ +/****************************************************************************************[Solver.C] +MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include "Solver.h" +#include "Sort.h" +#include "prop/sat.h" +#include + +//================================================================================================= +// Constructor/Destructor: + +namespace CVC4 { +namespace prop { +namespace minisat { + +Clause* Solver::lazy_reason = reinterpret_cast(1); + +Clause* Solver::getReason(Lit l) +{ + if (reason[var(l)] != lazy_reason) return reason[var(l)]; + // Get the explanation from the theory + SatClause explanation; + if (value(l) == l_True) { + proxy->explainPropagation(l, explanation); + assert(explanation[0] == l); + } else { + proxy->explainPropagation(~l, explanation); + assert(explanation[0] == ~l); + } + Clause* real_reason = Clause_new(explanation, true); + reason[var(l)] = real_reason; + // Add it to the database + learnts.push(real_reason); + attachClause(*real_reason); + return real_reason; +} + +Solver::Solver(SatSolver* proxy, context::Context* context) : + + // SMT stuff + proxy(proxy) + , context(context) + + // Parameters: (formerly in 'SearchParams') + , var_decay(1 / 0.95), clause_decay(1 / 0.999), random_var_freq(0.02) + , restart_first(100), restart_inc(1.5), learntsize_factor((double)1/(double)3), learntsize_inc(1.1) + + // More parameters: + // + , expensive_ccmin (true) + , polarity_mode (polarity_false) + , verbosity (0) + + // Statistics: (formerly in 'SolverStats') + // + , starts(0), decisions(0), rnd_decisions(0), propagations(0), conflicts(0) + , clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0) + + , ok (true) + , cla_inc (1) + , var_inc (1) + , qhead (0) + , simpDB_assigns (-1) + , simpDB_props (0) + , order_heap (VarOrderLt(activity)) + , random_seed (91648253) + , progress_estimate(0) + , remove_satisfied (true) +{} + + +Solver::~Solver() +{ + for (int i = 0; i < learnts.size(); i++) free(learnts[i]); + for (int i = 0; i < clauses.size(); i++) free(clauses[i]); +} + + +//================================================================================================= +// Minor methods: + + +// Creates a new SAT variable in the solver. If 'decision_var' is cleared, variable will not be +// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result). +// +Var Solver::newVar(bool sign, bool dvar, bool theoryAtom) +{ + int v = nVars(); + watches .push(); // (list for positive literal) + watches .push(); // (list for negative literal) + reason .push(NULL); + assigns .push(toInt(l_Undef)); + level .push(-1); + activity .push(0); + seen .push(0); + + theory .push(theoryAtom); + + polarity .push((char)sign); + decision_var.push((char)dvar); + + insertVarOrder(v); + return v; +} + + +bool Solver::addClause(vec& ps, ClauseType type) +{ + assert(decisionLevel() == 0); + + if (!ok) + return false; + else{ + // Check if clause is satisfied and remove false/duplicate literals: + sort(ps); + Lit p; int i, j; + for (i = j = 0, p = lit_Undef; i < ps.size(); i++) + if (value(ps[i]) == l_True || ps[i] == ~p) + return true; + else if (value(ps[i]) != l_False && ps[i] != p) + ps[j++] = p = ps[i]; + ps.shrink(i - j); + } + + if (ps.size() == 0) + return ok = false; + else if (ps.size() == 1){ + assert(type != CLAUSE_LEMMA); + assert(value(ps[0]) == l_Undef); + uncheckedEnqueue(ps[0]); + return ok = (propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) == NULL); + }else{ + Clause* c = Clause_new(ps, false); + clauses.push(c); + if (type == CLAUSE_LEMMA) lemmas.push(c); + attachClause(*c); + } + + return true; + +} + + +void Solver::attachClause(Clause& c) { + assert(c.size() > 1); + watches[toInt(~c[0])].push(&c); + watches[toInt(~c[1])].push(&c); + if (c.learnt()) learnts_literals += c.size(); + else clauses_literals += c.size(); } + + +void Solver::detachClause(Clause& c) { + Debug("minisat") << "Solver::detachClause(" << c << ")" << std::endl; + assert(c.size() > 1); + assert(find(watches[toInt(~c[0])], &c)); + assert(find(watches[toInt(~c[1])], &c)); + remove(watches[toInt(~c[0])], &c); + remove(watches[toInt(~c[1])], &c); + if (c.learnt()) learnts_literals -= c.size(); + else clauses_literals -= c.size(); } + + +void Solver::removeClause(Clause& c) { + Debug("minisat") << "Solver::removeClause(" << c << ")" << std::endl; + detachClause(c); + free(&c); +} + + +bool Solver::satisfied(const Clause& c) const { + for (int i = 0; i < c.size(); i++) + if (value(c[i]) == l_True) + return true; + return false; } + + +// Revert to the state at given level (keeping all assignment at 'level' but not beyond). +// +void Solver::cancelUntil(int level) { + if (decisionLevel() > level){ + // Pop the SMT context + for (int l = trail_lim.size() - level; l > 0; --l) + context->pop(); + // Now the minisat stuff + for (int c = trail.size()-1; c >= trail_lim[level]; c--) { + Var x = var(trail[c]); + assigns[x] = toInt(l_Undef); + insertVarOrder(x); + } + qhead = trail_lim[level]; + trail.shrink(trail.size() - trail_lim[level]); + trail_lim.shrink(trail_lim.size() - level); + // We can erase the lemmas now + for (int c = lemmas.size() - 1; c >= lemmas_lim[level]; c--) { + // TODO: can_erase[lemma[c]] = true; + } + lemmas.shrink(lemmas.size() - lemmas_lim[level]); + lemmas_lim.shrink(lemmas_lim.size() - level); + } +} + + +//================================================================================================= +// Major methods: + + +Lit Solver::pickBranchLit(int polarity_mode, double random_var_freq) +{ + Var next = var_Undef; + + // Random decision: + if (drand(random_seed) < random_var_freq && !order_heap.empty()){ + next = order_heap[irand(random_seed,order_heap.size())]; + if (toLbool(assigns[next]) == l_Undef && decision_var[next]) + rnd_decisions++; } + + // Activity based decision: + while (next == var_Undef || toLbool(assigns[next]) != l_Undef || !decision_var[next]) + if (order_heap.empty()){ + next = var_Undef; + break; + }else + next = order_heap.removeMin(); + + bool sign = false; + switch (polarity_mode){ + case polarity_true: sign = false; break; + case polarity_false: sign = true; break; + case polarity_user: sign = polarity[next]; break; + case polarity_rnd: sign = irand(random_seed, 2); break; + default: assert(false); } + + return next == var_Undef ? lit_Undef : Lit(next, sign); +} + + +/*_________________________________________________________________________________________________ +| +| analyze : (confl : Clause*) (out_learnt : vec&) (out_btlevel : int&) -> [void] +| +| Description: +| Analyze conflict and produce a reason clause. +| +| Pre-conditions: +| * 'out_learnt' is assumed to be cleared. +| * Current decision level must be greater than root level. +| +| Post-conditions: +| * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'. +| +| Effect: +| Will undo part of the trail, upto but not beyond the assumption of the current decision level. +|________________________________________________________________________________________________@*/ +void Solver::analyze(Clause* confl, vec& out_learnt, int& out_btlevel) +{ + int pathC = 0; + Lit p = lit_Undef; + + // Generate conflict clause: + // + out_learnt.push(); // (leave room for the asserting literal) + int index = trail.size() - 1; + out_btlevel = 0; + + do{ + assert(confl != NULL); // (otherwise should be UIP) + Clause& c = *confl; + + if (c.learnt()) + claBumpActivity(c); + + for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){ + Lit q = c[j]; + + if (!seen[var(q)] && level[var(q)] > 0){ + varBumpActivity(var(q)); + seen[var(q)] = 1; + if (level[var(q)] >= decisionLevel()) + pathC++; + else{ + out_learnt.push(q); + if (level[var(q)] > out_btlevel) + out_btlevel = level[var(q)]; + } + } + } + + // Select next clause to look at: + while (!seen[var(trail[index--])]); + p = trail[index+1]; + confl = getReason(p); + seen[var(p)] = 0; + pathC--; + + }while (pathC > 0); + out_learnt[0] = ~p; + + // Simplify conflict clause: + // + int i, j; + if (expensive_ccmin){ + uint32_t abstract_level = 0; + for (i = 1; i < out_learnt.size(); i++) + abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict) + + out_learnt.copyTo(analyze_toclear); + for (i = j = 1; i < out_learnt.size(); i++) + if (getReason(out_learnt[i]) == NULL || !litRedundant(out_learnt[i], abstract_level)) + out_learnt[j++] = out_learnt[i]; + }else{ + out_learnt.copyTo(analyze_toclear); + for (i = j = 1; i < out_learnt.size(); i++){ + Clause& c = *getReason(out_learnt[i]); + for (int k = 1; k < c.size(); k++) + if (!seen[var(c[k])] && level[var(c[k])] > 0){ + out_learnt[j++] = out_learnt[i]; + break; } + } + } + max_literals += out_learnt.size(); + out_learnt.shrink(i - j); + tot_literals += out_learnt.size(); + + // Find correct backtrack level: + // + if (out_learnt.size() == 1) + out_btlevel = 0; + else{ + int max_i = 1; + for (int i = 2; i < out_learnt.size(); i++) + if (level[var(out_learnt[i])] > level[var(out_learnt[max_i])]) + max_i = i; + Lit p = out_learnt[max_i]; + out_learnt[max_i] = out_learnt[1]; + out_learnt[1] = p; + out_btlevel = level[var(p)]; + } + + + for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared) +} + + +// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is +// visiting literals at levels that cannot be removed later. +bool Solver::litRedundant(Lit p, uint32_t abstract_levels) +{ + analyze_stack.clear(); analyze_stack.push(p); + int top = analyze_toclear.size(); + while (analyze_stack.size() > 0){ + assert(getReason(analyze_stack.last()) != NULL); + Clause& c = *reason[var(analyze_stack.last())]; analyze_stack.pop(); + + for (int i = 1; i < c.size(); i++){ + Lit p = c[i]; + if (!seen[var(p)] && level[var(p)] > 0){ + if (getReason(p) != NULL && (abstractLevel(var(p)) & abstract_levels) != 0){ + seen[var(p)] = 1; + analyze_stack.push(p); + analyze_toclear.push(p); + }else{ + for (int j = top; j < analyze_toclear.size(); j++) + seen[var(analyze_toclear[j])] = 0; + analyze_toclear.shrink(analyze_toclear.size() - top); + return false; + } + } + } + } + + return true; +} + + +/*_________________________________________________________________________________________________ +| +| analyzeFinal : (p : Lit) -> [void] +| +| Description: +| Specialized analysis procedure to express the final conflict in terms of assumptions. +| Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and +| stores the result in 'out_conflict'. +|________________________________________________________________________________________________@*/ +void Solver::analyzeFinal(Lit p, vec& out_conflict) +{ + out_conflict.clear(); + out_conflict.push(p); + + if (decisionLevel() == 0) + return; + + seen[var(p)] = 1; + + for (int i = trail.size()-1; i >= trail_lim[0]; i--){ + Var x = var(trail[i]); + if (seen[x]){ + if (reason[x] == NULL){ + assert(level[x] > 0); + out_conflict.push(~trail[i]); + }else{ + Clause& c = *reason[x]; + for (int j = 1; j < c.size(); j++) + if (level[var(c[j])] > 0) + seen[var(c[j])] = 1; + } + seen[x] = 0; + } + } + + seen[var(p)] = 0; +} + + +void Solver::uncheckedEnqueue(Lit p, Clause* from) +{ + assert(value(p) == l_Undef); + assigns [var(p)] = toInt(lbool(!sign(p))); // <<== abstract but not uttermost efficient + level [var(p)] = decisionLevel(); + reason [var(p)] = from; + // Added for phase-caching + polarity [var(p)] = sign(p); + trail.push(p); + + if (theory[var(p)] && from != lazy_reason) { + // Enqueue to the theory + proxy->enqueueTheoryLiteral(p); + } +} + + +Clause* Solver::propagate(TheoryCheckType type) +{ + Clause* confl = NULL; + + // If this is the final check, no need for Boolean propagation and + // theory propagation + if (type == CHECK_WITHOUTH_PROPAGATION_FINAL) { + return theoryCheck(theory::Theory::FULL_EFFORT); + } + + // The effort we will be using to theory check + theory::Theory::Effort effort = type == CHECK_WITHOUTH_PROPAGATION_QUICK ? + theory::Theory::QUICK_CHECK : theory::Theory::STANDARD; + + // Keep running until we have checked everything, we + // have no conflict and no new literals have been asserted + bool new_assertions; + do { + new_assertions = false; + while(qhead < trail.size()) { + confl = propagateBool(); + if (confl != NULL) break; + confl = theoryCheck(effort); + if (confl != NULL) break; + } + + if (confl == NULL && type == CHECK_WITH_PROPAGATION_STANDARD) { + new_assertions = propagateTheory(); + if (!new_assertions) break; + } + } while (new_assertions); + + return confl; +} + +bool Solver::propagateTheory() { + std::vector propagatedLiterals; + proxy->theoryPropagate(propagatedLiterals); + const unsigned i_end = propagatedLiterals.size(); + for (unsigned i = 0; i < i_end; ++ i) { + uncheckedEnqueue(propagatedLiterals[i], lazy_reason); + } + proxy->clearPropagatedLiterals(); + return propagatedLiterals.size() > 0; +} + +/*_________________________________________________________________________________________________ +| +| theoryCheck: [void] -> [Clause*] +| +| Description: +| Checks all enqueued theory facts for satisfiability. If a conflict arises, the conflicting +| clause is returned, otherwise NULL. +| +| Note: the propagation queue might be NOT empty +|________________________________________________________________________________________________@*/ +Clause* Solver::theoryCheck(theory::Theory::Effort effort) +{ + Clause* c = NULL; + SatClause clause; + proxy->theoryCheck(effort, clause); + int clause_size = clause.size(); + Assert(clause_size != 1, "Can't handle unit clause explanations"); + if(clause_size > 0) { + // Find the max level of the conflict + int max_level = 0; + for (int i = 0; i < clause_size; ++i) { + int current_level = level[var(clause[i])]; + Debug("minisat") << "Literal: " << clause[i] << " with reason " << reason[var(clause[i])] << " at level " << current_level << std::endl; + Assert(toLbool(assigns[var(clause[i])]) != l_Undef, "Got an unassigned literal in conflict!"); + if (current_level > max_level) max_level = current_level; + } + // If smaller than the decision level then pop back so we can analyse + Debug("minisat") << "Max-level is " << max_level << " in decision level " << decisionLevel() << std::endl; + Assert(max_level <= decisionLevel(), "What is going on, can't get literals of a higher level as conflict!"); + if (max_level < decisionLevel()) { + Debug("minisat") << "Max-level is " << max_level << " in decision level " << decisionLevel() << std::endl; + cancelUntil(max_level); + } + // Create the new clause and attach all the information + c = Clause_new(clause, true); + learnts.push(c); + attachClause(*c); + } + return c; +} + +/*_________________________________________________________________________________________________ +| +| propagateBool : [void] -> [Clause*] +| +| Description: +| Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned, +| otherwise NULL. +| +| Post-conditions: +| * the propagation queue is empty, even if there was a conflict. +|________________________________________________________________________________________________@*/ +Clause* Solver::propagateBool() +{ + Clause* confl = NULL; + int num_props = 0; + + while (qhead < trail.size()){ + Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. + vec& ws = watches[toInt(p)]; + Clause **i, **j, **end; + num_props++; + + for (i = j = (Clause**)ws, end = i + ws.size(); i != end;){ + Clause& c = **i++; + + // Make sure the false literal is data[1]: + Lit false_lit = ~p; + if (c[0] == false_lit) + c[0] = c[1], c[1] = false_lit; + + assert(c[1] == false_lit); + + // If 0th watch is true, then clause is already satisfied. + Lit first = c[0]; + if (value(first) == l_True){ + *j++ = &c; + }else{ + // Look for new watch: + for (int k = 2; k < c.size(); k++) + if (value(c[k]) != l_False){ + c[1] = c[k]; c[k] = false_lit; + watches[toInt(~c[1])].push(&c); + goto FoundWatch; } + + // Did not find watch -- clause is unit under assignment: + *j++ = &c; + if (value(first) == l_False){ + confl = &c; + qhead = trail.size(); + // Copy the remaining watches: + while (i < end) + *j++ = *i++; + }else + uncheckedEnqueue(first, &c); + } + FoundWatch:; + } + ws.shrink(i - j); + } + propagations += num_props; + simpDB_props -= num_props; + + return confl; +} + +/*_________________________________________________________________________________________________ +| +| reduceDB : () -> [void] +| +| Description: +| Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked +| clauses are clauses that are reason to some assignment. Binary clauses are never removed. +|________________________________________________________________________________________________@*/ +struct reduceDB_lt { bool operator () (Clause* x, Clause* y) { return x->size() > 2 && (y->size() == 2 || x->activity() < y->activity()); } }; +void Solver::reduceDB() +{ + int i, j; + double extra_lim = cla_inc / learnts.size(); // Remove any clause below this activity + + sort(learnts, reduceDB_lt()); + for (i = j = 0; i < learnts.size() / 2; i++){ + if (learnts[i]->size() > 2 && !locked(*learnts[i])) + removeClause(*learnts[i]); + else + learnts[j++] = learnts[i]; + } + for (; i < learnts.size(); i++){ + if (learnts[i]->size() > 2 && !locked(*learnts[i]) && learnts[i]->activity() < extra_lim) + removeClause(*learnts[i]); + else + learnts[j++] = learnts[i]; + } + learnts.shrink(i - j); +} + + +void Solver::removeSatisfied(vec& cs) +{ + int i,j; + for (i = j = 0; i < cs.size(); i++){ + if (satisfied(*cs[i])) + removeClause(*cs[i]); + else + cs[j++] = cs[i]; + } + cs.shrink(i - j); +} + + +/*_________________________________________________________________________________________________ +| +| simplify : [void] -> [bool] +| +| Description: +| Simplify the clause database according to the current top-level assigment. Currently, the only +| thing done here is the removal of satisfied clauses, but more things can be put here. +|________________________________________________________________________________________________@*/ +bool Solver::simplify() +{ + assert(decisionLevel() == 0); + + if (!ok || propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL) + return ok = false; + + if (nAssigns() == simpDB_assigns || (simpDB_props > 0)) + return true; + + // Remove satisfied clauses: + removeSatisfied(learnts); + if (remove_satisfied) // Can be turned off. + removeSatisfied(clauses); + + // Remove fixed variables from the variable heap: + order_heap.filter(VarFilter(*this)); + + simpDB_assigns = nAssigns(); + simpDB_props = clauses_literals + learnts_literals; // (shouldn't depend on stats really, but it will do for now) + + return true; +} + + +/*_________________________________________________________________________________________________ +| +| search : (nof_conflicts : int) (nof_learnts : int) (params : const SearchParams&) -> [lbool] +| +| Description: +| Search for a model the specified number of conflicts, keeping the number of learnt clauses +| below the provided limit. NOTE! Use negative value for 'nof_conflicts' or 'nof_learnts' to +| indicate infinity. +| +| Output: +| 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If +| all variables are decision variables, this means that the clause set is satisfiable. 'l_False' +| if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. +|________________________________________________________________________________________________@*/ +lbool Solver::search(int nof_conflicts, int nof_learnts) +{ + assert(ok); + int backtrack_level; + int conflictC = 0; + vec learnt_clause; + + starts++; + + bool first = true; + TheoryCheckType check_type = CHECK_WITH_PROPAGATION_STANDARD; + for (;;){ + Clause* confl = propagate(check_type); + if (confl != NULL){ + // CONFLICT + conflicts++; conflictC++; + if (decisionLevel() == 0) return l_False; + + first = false; + + learnt_clause.clear(); + analyze(confl, learnt_clause, backtrack_level); + cancelUntil(backtrack_level); + assert(value(learnt_clause[0]) == l_Undef); + + if (learnt_clause.size() == 1){ + uncheckedEnqueue(learnt_clause[0]); + }else{ + Clause* c = Clause_new(learnt_clause, true); + learnts.push(c); + attachClause(*c); + claBumpActivity(*c); + uncheckedEnqueue(learnt_clause[0], c); + } + + varDecayActivity(); + claDecayActivity(); + + // We have a conflict so, we are going back to standard checks + check_type = CHECK_WITH_PROPAGATION_STANDARD; + + }else{ + // NO CONFLICT + + // If this was a final check, we are satisfiable + if (check_type == CHECK_WITHOUTH_PROPAGATION_FINAL) + return l_True; + + if (nof_conflicts >= 0 && conflictC >= nof_conflicts){ + // Reached bound on number of conflicts: + progress_estimate = progressEstimate(); + cancelUntil(0); + return l_Undef; } + + // Simplify the set of problem clauses: + if (decisionLevel() == 0 && !simplify()) + return l_False; + + if (nof_learnts >= 0 && learnts.size()-nAssigns() >= nof_learnts) + // Reduce the set of learnt clauses: + reduceDB(); + + Lit next = lit_Undef; + while (decisionLevel() < assumptions.size()){ + // Perform user provided assumption: + Lit p = assumptions[decisionLevel()]; + if (value(p) == l_True){ + // Dummy decision level: + newDecisionLevel(); + }else if (value(p) == l_False){ + analyzeFinal(~p, conflict); + return l_False; + }else{ + next = p; + break; + } + } + + if (next == lit_Undef){ + // New variable decision: + decisions++; + next = pickBranchLit(polarity_mode, random_var_freq); + + if (next == lit_Undef) { + // We need to do a full theory check to confirm + check_type = CHECK_WITHOUTH_PROPAGATION_FINAL; + continue; + } + } + + // Increase decision level and enqueue 'next' + assert(value(next) == l_Undef); + newDecisionLevel(); + uncheckedEnqueue(next); + } + } +} + + +double Solver::progressEstimate() const +{ + double progress = 0; + double F = 1.0 / nVars(); + + for (int i = 0; i <= decisionLevel(); i++){ + int beg = i == 0 ? 0 : trail_lim[i - 1]; + int end = i == decisionLevel() ? trail.size() : trail_lim[i]; + progress += pow(F, i) * (end - beg); + } + + return progress / nVars(); +} + + +bool Solver::solve(const vec& assumps) +{ + model.clear(); + conflict.clear(); + + if (!ok) return false; + + assumps.copyTo(assumptions); + + double nof_conflicts = restart_first; + double nof_learnts = nClauses() * learntsize_factor; + lbool status = l_Undef; + + if (verbosity >= 1){ + reportf("============================[ Search Statistics ]==============================\n"); + reportf("| Conflicts | ORIGINAL | LEARNT | Progress |\n"); + reportf("| | Vars Clauses Literals | Limit Clauses Lit/Cl | |\n"); + reportf("===============================================================================\n"); + } + + // Search: + while (status == l_Undef){ + if (verbosity >= 1) + reportf("| %9d | %7d %8d %8d | %8d %8d %6.0f | %6.3f %% |\n", (int)conflicts, order_heap.size(), nClauses(), (int)clauses_literals, (int)nof_learnts, nLearnts(), (double)learnts_literals/nLearnts(), progress_estimate*100), fflush(stdout); + status = search((int)nof_conflicts, (int)nof_learnts); + nof_conflicts *= restart_inc; + nof_learnts *= learntsize_inc; + } + + if (verbosity >= 1) + reportf("===============================================================================\n"); + + + if (status == l_True){ + // Extend & copy model: + model.growTo(nVars()); + for (int i = 0; i < nVars(); i++) model[i] = value(i); +#ifndef NDEBUG + verifyModel(); +#endif + }else{ + assert(status == l_False); + if (conflict.size() == 0) + ok = false; + } + + cancelUntil(0); + return status == l_True; +} + +//================================================================================================= +// Debug methods: + + +void Solver::verifyModel() +{ + bool failed = false; + for (int i = 0; i < clauses.size(); i++){ + assert(clauses[i]->mark() == 0); + Clause& c = *clauses[i]; + for (int j = 0; j < c.size(); j++) + if (modelValue(c[j]) == l_True) + goto next; + + reportf("unsatisfied clause: "); + printClause(*clauses[i]); + reportf("\n"); + failed = true; + next:; + } + + assert(!failed); + + if(verbosity >= 1) + reportf("Verified %d original clauses.\n", clauses.size()); +} + + +void Solver::checkLiteralCount() +{ + // Check that sizes are calculated correctly: + int cnt = 0; + for (int i = 0; i < clauses.size(); i++) + if (clauses[i]->mark() == 0) + cnt += clauses[i]->size(); + + if ((int)clauses_literals != cnt){ + fprintf(stderr, "literal count: %d, real value = %d\n", (int)clauses_literals, cnt); + assert((int)clauses_literals == cnt); + } +} + +}/* CVC4::prop::minisat namespace */ +}/* CVC4::prop namespace */ +}/* CVC4 namespace */ + diff --git a/src/prop/minisat/simp/Main.C b/src/prop/minisat/simp/Main.C deleted file mode 100644 index b6d194631..000000000 --- a/src/prop/minisat/simp/Main.C +++ /dev/null @@ -1,415 +0,0 @@ -/******************************************************************************************[Main.C] -MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, -including without limitation the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT -NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT -OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -**************************************************************************************************/ - -#include -#include -#include -#include - -#include -#include - -#include "SimpSolver.h" - -/*************************************************************************************/ -#ifdef _MSC_VER -#include - -static inline double cpuTime(void) { - return (double)clock() / CLOCKS_PER_SEC; } -#else - -#include -#include -#include - -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 -#endif - - -//================================================================================================= -// 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 -static void skipWhitespace(B& in) { - while ((*in >= 9 && *in <= 13) || *in == 32) - ++in; } - -template -static void skipLine(B& in) { - for (;;){ - if (*in == EOF || *in == '\0') return; - if (*in == '\n') { ++in; return; } - ++in; } } - -template -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 -static void readClause(B& in, SimpSolver& S, vec& 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 -static bool match(B& in, char* str) { - for (; *str != 0; ++str, ++in) - if (*str != *in) - return false; - return true; -} - - -template -static void parse_DIMACS_main(B& in, SimpSolver& S) { - vec 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); } - } -} - -// 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); } - - -//================================================================================================= -// Main: - -void printUsage(char** argv) -{ - reportf("USAGE: %s [options] \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 = [ >0 ]\n"); - reportf(" -polarity-mode = {true,false,rnd}\n"); - reportf(" -decay = [ 0 - 1 ]\n"); - reportf(" -rnd-freq = [ 0 - 1 ]\n"); - reportf(" -dimacs = \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"); -#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"); -#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(); - - 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 ? "" : 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++; - } - 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"); - - printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n"); - if (res != NULL){ - if (ret){ - 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 - fprintf(res, "UNSAT\n"); - fclose(res); - } -#ifdef NDEBUG - exit(ret ? 10 : 20); // (faster than "return", which will invoke the destructor for 'Solver') -#endif - } - -} diff --git a/src/prop/minisat/simp/Main.cc b/src/prop/minisat/simp/Main.cc new file mode 100644 index 000000000..b6d194631 --- /dev/null +++ b/src/prop/minisat/simp/Main.cc @@ -0,0 +1,415 @@ +/******************************************************************************************[Main.C] +MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include +#include +#include +#include + +#include +#include + +#include "SimpSolver.h" + +/*************************************************************************************/ +#ifdef _MSC_VER +#include + +static inline double cpuTime(void) { + return (double)clock() / CLOCKS_PER_SEC; } +#else + +#include +#include +#include + +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 +#endif + + +//================================================================================================= +// 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 +static void skipWhitespace(B& in) { + while ((*in >= 9 && *in <= 13) || *in == 32) + ++in; } + +template +static void skipLine(B& in) { + for (;;){ + if (*in == EOF || *in == '\0') return; + if (*in == '\n') { ++in; return; } + ++in; } } + +template +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 +static void readClause(B& in, SimpSolver& S, vec& 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 +static bool match(B& in, char* str) { + for (; *str != 0; ++str, ++in) + if (*str != *in) + return false; + return true; +} + + +template +static void parse_DIMACS_main(B& in, SimpSolver& S) { + vec 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); } + } +} + +// 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); } + + +//================================================================================================= +// Main: + +void printUsage(char** argv) +{ + reportf("USAGE: %s [options] \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 = [ >0 ]\n"); + reportf(" -polarity-mode = {true,false,rnd}\n"); + reportf(" -decay = [ 0 - 1 ]\n"); + reportf(" -rnd-freq = [ 0 - 1 ]\n"); + reportf(" -dimacs = \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"); +#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"); +#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(); + + 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 ? "" : 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++; + } + 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"); + + printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n"); + if (res != NULL){ + if (ret){ + 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 + fprintf(res, "UNSAT\n"); + fclose(res); + } +#ifdef NDEBUG + exit(ret ? 10 : 20); // (faster than "return", which will invoke the destructor for 'Solver') +#endif + } + +} diff --git a/src/prop/minisat/simp/SimpSolver.C b/src/prop/minisat/simp/SimpSolver.C deleted file mode 100644 index 00f93402f..000000000 --- a/src/prop/minisat/simp/SimpSolver.C +++ /dev/null @@ -1,711 +0,0 @@ -/************************************************************************************[SimpSolver.C] -MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, -including without limitation the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT -NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT -OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -**************************************************************************************************/ - -#include "Sort.h" -#include "SimpSolver.h" - - -//================================================================================================= -// Constructor/Destructor: - -namespace CVC4 { -namespace prop { -namespace minisat { - -SimpSolver::SimpSolver(SatSolver* proxy, context::Context* context) : - Solver(proxy, context) - , grow (0) - , asymm_mode (false) - , redundancy_check (false) - , merges (0) - , asymm_lits (0) - , remembered_clauses (0) - , elimorder (1) - , use_simplification (true) - , elim_heap (ElimLt(n_occ)) - , bwdsub_assigns (0) -{ - vec dummy(1,lit_Undef); - bwdsub_tmpunit = Clause_new(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); - - 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(); - } - return v; } - - - -bool SimpSolver::solve(const vec& assumps, bool do_simp, bool turn_off_simp) { - vec extra_frozen; - bool result = 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]); - - // If an assumption has been eliminated, remember it. - if (isEliminated(v)) - remember(v); - - if (!frozen[v]){ - // Freeze and store. - setFrozen(v, true); - extra_frozen.push(v); - } } - - result = eliminate(turn_off_simp); - } - - if (result) - result = Solver::solve(assumps); - - if (result) { - extendModel(); -#ifndef NDEBUG - verifyModel(); -#endif - } - - if (do_simp) - // Unfreeze the assumptions that were frozen: - for (int i = 0; i < extra_frozen.size(); i++) - setFrozen(extra_frozen[i], false); - - return result; -} - - - -bool SimpSolver::addClause(vec& ps, ClauseType type) -{ - for (int i = 0; i < ps.size(); i++) - if (isEliminated(var(ps[i]))) - remember(var(ps[i])); - - int nclauses = clauses.size(); - - if (redundancy_check && implied(ps)) - return true; - - if (!Solver::addClause(ps, type)) - return false; - - if (use_simplification && clauses.size() == nclauses + 1){ - Clause& c = *clauses.last(); - - subsumption_queue.insert(&c); - - 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); - n_occ[toInt(c[i])]++; - touched[var(c[i])] = 1; - assert(elimtable[var(c[i])].order == 0); - if (elim_heap.inHeap(var(c[i]))) - elim_heap.increase_(var(c[i])); - } - } - - return true; -} - - -void SimpSolver::removeClause(Clause& c) -{ - 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])); - } - - detachClause(c); - c.mark(1); -} - - -bool SimpSolver::strengthenClause(Clause& c, Lit l) -{ - assert(decisionLevel() == 0); - assert(c.mark() == 0); - assert(!c.learnt()); - assert(find(watches[toInt(~c[0])], &c)); - assert(find(watches[toInt(~c[1])], &c)); - - // 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; - } - - // if subsumption-indexing is active perform the necessary updates - if (use_simplification){ - remove(occurs[var(l)], &c); - n_occ[toInt(l)]--; - updateElimHeap(var(l)); - } - - return c.size() == 1 ? enqueue(c[0]) && propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) == NULL : true; -} - - -// Returns FALSE if clause is always satisfied ('out_clause' should not be used). -bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec& out_clause) -{ - merges++; - out_clause.clear(); - - bool ps_smallest = _ps.size() < _qs.size(); - 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 (ps[j] == ~qs[i]) - return false; - else - goto next; - } - out_clause.push(qs[i]); - } - next:; - } - - for (int i = 0; i < ps.size(); i++) - if (var(ps[i]) != v) - out_clause.push(ps[i]); - - return true; -} - - -// Returns FALSE if clause is always satisfied. -bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v) -{ - 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; - - 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 (__ps[j] == ~__qs[i]) - return false; - else - goto next; - } - } - next:; - } - - return true; -} - - -void SimpSolver::gatherTouchedClauses() -{ - //fprintf(stderr, "Gathering clauses for backwards subsumption\n"); - int ntouched = 0; - for (int i = 0; i < touched.size(); i++) - if (touched[i]){ - const vec& cs = getOccurs(i); - ntouched++; - for (int j = 0; j < cs.size(); j++) - if (cs[j]->mark() == 0){ - subsumption_queue.insert(cs[j]); - 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); -} - - -bool SimpSolver::implied(const vec& c) -{ - assert(decisionLevel() == 0); - - trail_lim.push(trail.size()); - for (int i = 0; i < c.size(); i++) - if (value(c[i]) == l_True){ - cancelUntil(0); - return false; - }else if (value(c[i]) != l_False){ - assert(value(c[i]) == l_Undef); - uncheckedEnqueue(~c[i]); - } - - bool result = propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL; - cancelUntil(0); - return result; -} - - -// Backward subsumption + backward subsumption resolution -bool SimpSolver::backwardSubsumptionCheck(bool verbose) -{ - int cnt = 0; - int subsumed = 0; - int deleted_literals = 0; - assert(decisionLevel() == 0); - - while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){ - - // 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); - subsumption_queue.insert(bwdsub_tmpunit); } - - Clause& c = *subsumption_queue.peek(); subsumption_queue.pop(); - - 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); - - assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point. - - // Find best variable to scan: - Var best = var(c[0]); - for (int i = 1; i < c.size(); i++) - if (occurs[var(c[i])].size() < occurs[best].size()) - best = var(c[i]); - - // Search all candidates: - vec& _cs = getOccurs(best); - Clause** cs = (Clause**)_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]); - - if (l == lit_Undef) - subsumed++, removeClause(*cs[j]); - else if (l != lit_Error){ - deleted_literals++; - - if (!strengthenClause(*cs[j], ~l)) - return false; - - // Did current candidate get deleted from cs? Then check candidate at index j again: - if (var(l) == best) - j--; - } - } - } - - return true; -} - - -bool SimpSolver::asymm(Var v, Clause& c) -{ - assert(decisionLevel() == 0); - - if (c.mark() || satisfied(c)) return true; - - trail_lim.push(trail.size()); - Lit l = lit_Undef; - for (int i = 0; i < c.size(); i++) - if (var(c[i]) != v && value(c[i]) != l_False) - uncheckedEnqueue(~c[i]); - else - l = c[i]; - - if (propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL){ - cancelUntil(0); - asymm_lits++; - if (!strengthenClause(c, l)) - return false; - }else - cancelUntil(0); - - return true; -} - - -bool SimpSolver::asymmVar(Var v) -{ - assert(!frozen[v]); - assert(use_simplification); - - vec pos, neg; - const vec& cls = getOccurs(v); - - if (value(v) != l_Undef || cls.size() == 0) - return true; - - for (int i = 0; i < cls.size(); i++) - if (!asymm(v, *cls[i])) - return false; - - return backwardSubsumptionCheck(); -} - - -void SimpSolver::verifyModel() -{ - 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); -} - - -bool SimpSolver::eliminateVar(Var v, bool fail) -{ - if (!fail && asymm_mode && !asymmVar(v)) return false; - - const vec& cls = getOccurs(v); - -// if (value(v) != l_Undef || cls.size() == 0) return true; - if (value(v) != l_Undef) return true; - - // Split the occurrences into positive and negative: - vec pos, neg; - for (int i = 0; i < cls.size(); i++) - (find(*cls[i], Lit(v)) ? pos : neg).push(cls[i]); - - // 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) - return true; - - // Delete and store old clauses: - 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]); } - - // Produce clauses in cross product: - int top = clauses.size(); - vec resolvent; - 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)) - 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); } - - return backwardSubsumptionCheck(); -} - - -void SimpSolver::remember(Var v) -{ - assert(decisionLevel() == 0); - assert(isEliminated(v)); - - vec clause; - - // 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. - - 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); - } - - elimtable[v].eliminated.clear(); -} - - -void SimpSolver::extendModel() -{ - vec 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)); - - for (int i = 0; i < vs.size(); i++){ - Var v = vs[i]; - Lit l = lit_Undef; - - 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; - } -} - - -bool SimpSolver::eliminate(bool turn_off_elim) -{ - if (!ok || !use_simplification) - return ok; - - // 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; - - //fprintf(stderr, "elimination phase:\n (%d)", elim_heap.size()); - for (int cnt = 0; !elim_heap.empty(); cnt++){ - Var elim = elim_heap.removeMin(); - - if (verbosity >= 2 && cnt % 100 == 0) - reportf("elimination left: %10d\r", elim_heap.size()); - - if (!frozen[elim] && !eliminateVar(elim)) - return false; - } - - 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 - - // 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); - elim_heap.clear(true); - remove_satisfied = true; - } - - - return true; -} - - -void SimpSolver::cleanUpClauses() -{ - int i , j; - vec 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; } - - for (i = j = 0; i < clauses.size(); i++) - if (clauses[i]->mark() == 1) - free(clauses[i]); - else - clauses[j++] = clauses[i]; - clauses.shrink(i - j); -} - - -//================================================================================================= -// Convert to DIMACS: - - -void SimpSolver::toDimacs(FILE* f, Clause& c) -{ - if (satisfied(c)) return; - - 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"); -} - - -void SimpSolver::toDimacs(const char* file) -{ - assert(decisionLevel() == 0); - FILE* f = fopen(file, "wr"); - if (f != NULL){ - - // 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); -} - -}/* CVC4::prop::minisat namespace */ -}/* CVC4::prop namespace */ -}/* CVC4 namespace */ diff --git a/src/prop/minisat/simp/SimpSolver.cc b/src/prop/minisat/simp/SimpSolver.cc new file mode 100644 index 000000000..00f93402f --- /dev/null +++ b/src/prop/minisat/simp/SimpSolver.cc @@ -0,0 +1,711 @@ +/************************************************************************************[SimpSolver.C] +MiniSat -- Copyright (c) 2003-2006, Niklas Een, 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, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include "Sort.h" +#include "SimpSolver.h" + + +//================================================================================================= +// Constructor/Destructor: + +namespace CVC4 { +namespace prop { +namespace minisat { + +SimpSolver::SimpSolver(SatSolver* proxy, context::Context* context) : + Solver(proxy, context) + , grow (0) + , asymm_mode (false) + , redundancy_check (false) + , merges (0) + , asymm_lits (0) + , remembered_clauses (0) + , elimorder (1) + , use_simplification (true) + , elim_heap (ElimLt(n_occ)) + , bwdsub_assigns (0) +{ + vec dummy(1,lit_Undef); + bwdsub_tmpunit = Clause_new(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); + + 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(); + } + return v; } + + + +bool SimpSolver::solve(const vec& assumps, bool do_simp, bool turn_off_simp) { + vec extra_frozen; + bool result = 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]); + + // If an assumption has been eliminated, remember it. + if (isEliminated(v)) + remember(v); + + if (!frozen[v]){ + // Freeze and store. + setFrozen(v, true); + extra_frozen.push(v); + } } + + result = eliminate(turn_off_simp); + } + + if (result) + result = Solver::solve(assumps); + + if (result) { + extendModel(); +#ifndef NDEBUG + verifyModel(); +#endif + } + + if (do_simp) + // Unfreeze the assumptions that were frozen: + for (int i = 0; i < extra_frozen.size(); i++) + setFrozen(extra_frozen[i], false); + + return result; +} + + + +bool SimpSolver::addClause(vec& ps, ClauseType type) +{ + for (int i = 0; i < ps.size(); i++) + if (isEliminated(var(ps[i]))) + remember(var(ps[i])); + + int nclauses = clauses.size(); + + if (redundancy_check && implied(ps)) + return true; + + if (!Solver::addClause(ps, type)) + return false; + + if (use_simplification && clauses.size() == nclauses + 1){ + Clause& c = *clauses.last(); + + subsumption_queue.insert(&c); + + 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); + n_occ[toInt(c[i])]++; + touched[var(c[i])] = 1; + assert(elimtable[var(c[i])].order == 0); + if (elim_heap.inHeap(var(c[i]))) + elim_heap.increase_(var(c[i])); + } + } + + return true; +} + + +void SimpSolver::removeClause(Clause& c) +{ + 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])); + } + + detachClause(c); + c.mark(1); +} + + +bool SimpSolver::strengthenClause(Clause& c, Lit l) +{ + assert(decisionLevel() == 0); + assert(c.mark() == 0); + assert(!c.learnt()); + assert(find(watches[toInt(~c[0])], &c)); + assert(find(watches[toInt(~c[1])], &c)); + + // 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; + } + + // if subsumption-indexing is active perform the necessary updates + if (use_simplification){ + remove(occurs[var(l)], &c); + n_occ[toInt(l)]--; + updateElimHeap(var(l)); + } + + return c.size() == 1 ? enqueue(c[0]) && propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) == NULL : true; +} + + +// Returns FALSE if clause is always satisfied ('out_clause' should not be used). +bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec& out_clause) +{ + merges++; + out_clause.clear(); + + bool ps_smallest = _ps.size() < _qs.size(); + 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 (ps[j] == ~qs[i]) + return false; + else + goto next; + } + out_clause.push(qs[i]); + } + next:; + } + + for (int i = 0; i < ps.size(); i++) + if (var(ps[i]) != v) + out_clause.push(ps[i]); + + return true; +} + + +// Returns FALSE if clause is always satisfied. +bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v) +{ + 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; + + 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 (__ps[j] == ~__qs[i]) + return false; + else + goto next; + } + } + next:; + } + + return true; +} + + +void SimpSolver::gatherTouchedClauses() +{ + //fprintf(stderr, "Gathering clauses for backwards subsumption\n"); + int ntouched = 0; + for (int i = 0; i < touched.size(); i++) + if (touched[i]){ + const vec& cs = getOccurs(i); + ntouched++; + for (int j = 0; j < cs.size(); j++) + if (cs[j]->mark() == 0){ + subsumption_queue.insert(cs[j]); + 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); +} + + +bool SimpSolver::implied(const vec& c) +{ + assert(decisionLevel() == 0); + + trail_lim.push(trail.size()); + for (int i = 0; i < c.size(); i++) + if (value(c[i]) == l_True){ + cancelUntil(0); + return false; + }else if (value(c[i]) != l_False){ + assert(value(c[i]) == l_Undef); + uncheckedEnqueue(~c[i]); + } + + bool result = propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL; + cancelUntil(0); + return result; +} + + +// Backward subsumption + backward subsumption resolution +bool SimpSolver::backwardSubsumptionCheck(bool verbose) +{ + int cnt = 0; + int subsumed = 0; + int deleted_literals = 0; + assert(decisionLevel() == 0); + + while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){ + + // 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); + subsumption_queue.insert(bwdsub_tmpunit); } + + Clause& c = *subsumption_queue.peek(); subsumption_queue.pop(); + + 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); + + assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point. + + // Find best variable to scan: + Var best = var(c[0]); + for (int i = 1; i < c.size(); i++) + if (occurs[var(c[i])].size() < occurs[best].size()) + best = var(c[i]); + + // Search all candidates: + vec& _cs = getOccurs(best); + Clause** cs = (Clause**)_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]); + + if (l == lit_Undef) + subsumed++, removeClause(*cs[j]); + else if (l != lit_Error){ + deleted_literals++; + + if (!strengthenClause(*cs[j], ~l)) + return false; + + // Did current candidate get deleted from cs? Then check candidate at index j again: + if (var(l) == best) + j--; + } + } + } + + return true; +} + + +bool SimpSolver::asymm(Var v, Clause& c) +{ + assert(decisionLevel() == 0); + + if (c.mark() || satisfied(c)) return true; + + trail_lim.push(trail.size()); + Lit l = lit_Undef; + for (int i = 0; i < c.size(); i++) + if (var(c[i]) != v && value(c[i]) != l_False) + uncheckedEnqueue(~c[i]); + else + l = c[i]; + + if (propagate(CHECK_WITHOUTH_PROPAGATION_QUICK) != NULL){ + cancelUntil(0); + asymm_lits++; + if (!strengthenClause(c, l)) + return false; + }else + cancelUntil(0); + + return true; +} + + +bool SimpSolver::asymmVar(Var v) +{ + assert(!frozen[v]); + assert(use_simplification); + + vec pos, neg; + const vec& cls = getOccurs(v); + + if (value(v) != l_Undef || cls.size() == 0) + return true; + + for (int i = 0; i < cls.size(); i++) + if (!asymm(v, *cls[i])) + return false; + + return backwardSubsumptionCheck(); +} + + +void SimpSolver::verifyModel() +{ + 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); +} + + +bool SimpSolver::eliminateVar(Var v, bool fail) +{ + if (!fail && asymm_mode && !asymmVar(v)) return false; + + const vec& cls = getOccurs(v); + +// if (value(v) != l_Undef || cls.size() == 0) return true; + if (value(v) != l_Undef) return true; + + // Split the occurrences into positive and negative: + vec pos, neg; + for (int i = 0; i < cls.size(); i++) + (find(*cls[i], Lit(v)) ? pos : neg).push(cls[i]); + + // 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) + return true; + + // Delete and store old clauses: + 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]); } + + // Produce clauses in cross product: + int top = clauses.size(); + vec resolvent; + 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)) + 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); } + + return backwardSubsumptionCheck(); +} + + +void SimpSolver::remember(Var v) +{ + assert(decisionLevel() == 0); + assert(isEliminated(v)); + + vec clause; + + // 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. + + 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); + } + + elimtable[v].eliminated.clear(); +} + + +void SimpSolver::extendModel() +{ + vec 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)); + + for (int i = 0; i < vs.size(); i++){ + Var v = vs[i]; + Lit l = lit_Undef; + + 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; + } +} + + +bool SimpSolver::eliminate(bool turn_off_elim) +{ + if (!ok || !use_simplification) + return ok; + + // 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; + + //fprintf(stderr, "elimination phase:\n (%d)", elim_heap.size()); + for (int cnt = 0; !elim_heap.empty(); cnt++){ + Var elim = elim_heap.removeMin(); + + if (verbosity >= 2 && cnt % 100 == 0) + reportf("elimination left: %10d\r", elim_heap.size()); + + if (!frozen[elim] && !eliminateVar(elim)) + return false; + } + + 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 + + // 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); + elim_heap.clear(true); + remove_satisfied = true; + } + + + return true; +} + + +void SimpSolver::cleanUpClauses() +{ + int i , j; + vec 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; } + + for (i = j = 0; i < clauses.size(); i++) + if (clauses[i]->mark() == 1) + free(clauses[i]); + else + clauses[j++] = clauses[i]; + clauses.shrink(i - j); +} + + +//================================================================================================= +// Convert to DIMACS: + + +void SimpSolver::toDimacs(FILE* f, Clause& c) +{ + if (satisfied(c)) return; + + 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"); +} + + +void SimpSolver::toDimacs(const char* file) +{ + assert(decisionLevel() == 0); + FILE* f = fopen(file, "wr"); + if (f != NULL){ + + // 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); +} + +}/* CVC4::prop::minisat namespace */ +}/* CVC4::prop namespace */ +}/* CVC4 namespace */