sat-solver/SatSolver.h
00001 /****************************************************************************************[Solver.h]
00002 MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
00003 
00004 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
00005 associated documentation files (the "Software"), to deal in the Software without restriction,
00006 including without limitation the rights to use, copy, modify, merge, publish, distribute,
00007 sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
00008 furnished to do so, subject to the following conditions:
00009 
00010 The above copyright notice and this permission notice shall be included in all copies or
00011 substantial portions of the Software.
00012 
00013 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
00014 NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
00015 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
00016 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
00017 OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00018 **************************************************************************************************/
00019 
00020 #ifndef Solver_h
00021 #define Solver_h
00022 
00023 #include <cstdio>
00024 #include <string>
00025 
00026 using namespace std;
00027 
00028 #include "Vec.h"
00029 #include "Heap.h"
00030 #include "Alg.h"
00031 
00032 #include "SolverTypes.h"
00033 
00034 
00035 //=================================================================================================
00036 // Solver -- the main class:
00037 
00038 namespace minisat
00039 {
00040 
00041 
00042 class Solver {
00043 
00044         friend class SkeletonSolver;
00045 
00046 public:
00047 
00048     // Constructor/Destructor:
00049     //
00050     Solver();
00051     ~Solver();
00052 
00053 
00054 
00055     // Problem specification:
00056     //
00057     Var     newVar    (bool polarity = true, bool dvar = true);
00058     // Add a new variable with parameters specifying variable mode.
00059 
00060     void reserveVars(int num_vars);
00061 
00062     bool    addClause (vec<Lit>& ps);
00063     // Add a clause to the solver. NOTE! 'ps' may be shrunk by this method!
00064 
00065 
00066 
00067     // Solving:
00068     //
00069     bool    simplify     ();                        // Removes already satisfied clauses.
00070     bool    solve        (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions.
00071     bool    solve        ();                        // Search without assumptions.
00072     bool    okay         () const;                  // FALSE means solver is in a conflicting state
00073 
00074     // Variable mode:
00075     //
00076     void    setPolarity    (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'.
00077     void    setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic.
00078 
00079     // Read state:
00080     //
00081     lbool   value      (Var x) const;       // The current value of a variable.
00082     lbool   value      (Lit p) const;       // The current value of a literal.
00083     lbool   modelValue (Lit p) const;       // The value of a literal in the last model. The last call to solve must have been satisfiable.
00084     int     nAssigns   ()      const;       // The current number of assigned literals.
00085     int     nClauses   ()      const;       // The current number of original clauses.
00086     int     nLearnts   ()      const;       // The current number of learnt clauses.
00087     int     nVars      ()      const;       // The current number of variables.
00088 
00089     // Extra results: (read-only member variable)
00090     //
00091     vec<lbool> model;             // If problem is satisfiable, this vector contains the model (if any).
00092     vec<Lit>   conflict;          // If problem is unsatisfiable (possibly under assumptions),
00093                                   // this vector represent the final conflict clause expressed in the assumptions.
00094 
00095     // Mode of operation:
00096     //
00097     double    var_decay;          // Inverse of the variable activity decay factor.                                            (default 1 / 0.95)
00098     double    clause_decay;       // Inverse of the clause activity decay factor.                                              (1 / 0.999)
00099     double    random_var_freq;    // The frequency with which the decision heuristic tries to choose a random variable.        (default 0.02)
00100     int       restart_first;      // The initial restart limit.                                                                (default 100)
00101     double    restart_inc;        // The factor with which the restart limit is multiplied in each restart.                    (default 1.5)
00102     double    learntsize_factor;  // The intitial limit for learnt clauses is a factor of the original clauses.                (default 1 / 3)
00103     double    learntsize_inc;     // The limit for learnt clauses is multiplied with this factor each restart.                 (default 1.1)
00104     bool      expensive_ccmin;    // Controls conflict clause minimization.                                                    (default TRUE)
00105     int       polarity_mode;      // Controls which polarity the decision heuristic chooses. See enum below for allowed modes. (default polarity_false)
00106     int       verbosity;          // Verbosity level. 0=silent, 1=some progress report                                         (default 0)
00107 
00108     enum { polarity_true = 0, polarity_false = 1, polarity_user = 2, polarity_rnd = 3 };
00109 
00110     // Statistics: (read-only member variable)
00111     //
00112     uint64_t starts, decisions, rnd_decisions, propagations, conflicts;
00113     uint64_t clauses_literals, learnts_literals, max_literals, tot_literals;
00114 
00115 
00116     // Helper structures:
00117     //
00118     struct VarOrderLt {
00119         const vec<double>&  activity;
00120         bool operator () (Var x, Var y) const { return activity[x] > activity[y]; }
00121         VarOrderLt(const vec<double>&  act) : activity(act) { }
00122     };
00123 
00124     friend class VarFilter;
00125     struct VarFilter {
00126         const Solver& s;
00127         VarFilter(const Solver& _s) : s(_s) {}
00128         bool operator()(Var v) const { return toLbool(s.assigns[v]) == l_Undef && s.decision_var[v]; }
00129     };
00130 
00131     // Solver state:
00132     //
00133     bool                ok;               // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
00134     vec<Clause*>        clauses;          // List of problem clauses.
00135     vec<Clause*>        learnts;          // List of learnt clauses.
00136     double              cla_inc;          // Amount to bump next clause with.
00137     vec<double>         activity;         // A heuristic measurement of the activity of a variable.
00138     double              var_inc;          // Amount to bump next variable with.
00139     vec<vec<Clause*> >  watches;          // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
00140     vec<char>           assigns;          // The current assignments (lbool:s stored as char:s).
00141     vec<char>           polarity;         // The preferred polarity of each variable.
00142     vec<char>           decision_var;     // Declares if a variable is eligible for selection in the decision heuristic.
00143     vec<Lit>            trail;            // Assignment stack; stores all assigments made in the order they were made.
00144     vec<int>            trail_lim;        // Separator indices for different decision levels in 'trail'.
00145     vec<Clause*>        reason;           // 'reason[var]' is the clause that implied the variables current value, or 'NULL' if none.
00146     vec<int>            level;            // 'level[var]' contains the level at which the assignment was made.
00147     int                 qhead;            // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
00148     int                 simpDB_assigns;   // Number of top-level assignments since last execution of 'simplify()'.
00149     int64_t             simpDB_props;     // Remaining number of propagations that must be made before next execution of 'simplify()'.
00150     vec<Lit>            assumptions;      // Current set of assumptions provided to solve by the user.
00151     Heap<VarOrderLt>    order_heap;       // A priority queue of variables ordered with respect to the variable activity.
00152     double              random_seed;      // Used by the random variable selection.
00153     double              progress_estimate;// Set by 'search()'.
00154     bool                remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'.
00155 
00156     // Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is
00157     // used, exept 'seen' wich is used in several places.
00158     //
00159     vec<char>           seen;
00160     vec<Lit>            analyze_stack;
00161     vec<Lit>            analyze_toclear;
00162     vec<Lit>            add_tmp;
00163 
00164     // Main internal methods:
00165     //
00166     void     insertVarOrder   (Var x);                                                 // Insert a variable in the decision order priority queue.
00167     Lit      pickBranchLit    (int polarity_mode, double random_var_freq);             // Return the next decision variable.
00168     void     newDecisionLevel ();                                                      // Begins a new decision level.
00169     void     uncheckedEnqueue (Lit p, Clause* from = NULL);                            // Enqueue a literal. Assumes value of literal is undefined.
00170     bool     enqueue          (Lit p, Clause* from = NULL);                            // Test if fact 'p' contradicts current state, enqueue otherwise.
00171     Clause*  propagate        ();                                                      // Perform unit propagation. Returns possibly conflicting clause.
00172     void     cancelUntil      (int level);                                             // Backtrack until a certain level.
00173     void     analyze          (Clause* confl, vec<Lit>& out_learnt, int& out_btlevel); // (bt = backtrack)
00174     void     analyzeFinal     (Lit p, vec<Lit>& out_conflict);                         // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION?
00175     bool     litRedundant     (Lit p, uint32_t abstract_levels);                       // (helper method for 'analyze()')
00176     lbool    search           (int nof_conflicts, int nof_learnts);                    // Search for a given number of conflicts.
00177     void     reduceDB         ();                                                      // Reduce the set of learnt clauses.
00178     void     removeSatisfied  (vec<Clause*>& cs);                                      // Shrink 'cs' to contain only non-satisfied clauses.
00179 
00180     // Maintaining Variable/Clause activity:
00181     //
00182     void     varDecayActivity ();                      // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead.
00183     void     varBumpActivity  (Var v);                 // Increase a variable with the current 'bump' value.
00184     void     claDecayActivity ();                      // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead.
00185     void     claBumpActivity  (Clause& c);             // Increase a clause with the current 'bump' value.
00186 
00187     // Operations on clauses:
00188     //
00189     void     attachClause     (Clause& c);             // Attach a clause to watcher lists.
00190     void     detachClause     (Clause& c);             // Detach a clause to watcher lists.
00191     void     removeClause     (Clause& c);             // Detach and free a clause.
00192     bool     locked           (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state.
00193     bool     satisfied        (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state.
00194 
00195     // Misc:
00196     //
00197     int      decisionLevel    ()      const; // Gives the current decisionlevel.
00198     uint32_t abstractLevel    (Var x) const; // Used to represent an abstraction of sets of decision levels.
00199     double   progressEstimate ()      const; // DELETE THIS ?? IT'S NOT VERY USEFUL ...
00200 
00201     // Debug:
00202     void     printLit         (Lit l);
00203     template<class C>
00204     void     printClause      (const C& c);
00205     void     verifyModel      ();
00206     void     checkLiteralCount();
00207     string clause_to_string(Clause& c);
00208 
00209     // Static helpers:
00210     //
00211 
00212     // Returns a random float 0 <= x < 1. Seed must never be 0.
00213     static inline double drand(double& seed) {
00214         seed *= 1389796;
00215         int q = (int)(seed / 2147483647);
00216         seed -= (double)q * 2147483647;
00217         return seed / 2147483647; }
00218 
00219     // Returns a random integer 0 <= x < size. Seed must never be 0.
00220     static inline int irand(double& seed, int size) {
00221         return (int)(drand(seed) * size); }
00222 };
00223 
00224 
00225 //=================================================================================================
00226 // Implementation of inline methods:
00227 
00228 
00229 inline void Solver::insertVarOrder(Var x) {
00230     if (!order_heap.inHeap(x) && decision_var[x]) order_heap.insert(x); }
00231 
00232 inline void Solver::varDecayActivity() { var_inc *= var_decay; }
00233 inline void Solver::varBumpActivity(Var v) {
00234     if ( (activity[v] += var_inc) > 1e100 ) {
00235         // Rescale:
00236         for (int i = 0; i < nVars(); i++)
00237             activity[i] *= 1e-100;
00238         var_inc *= 1e-100; }
00239 
00240     // Update order_heap with respect to new activity:
00241     if (order_heap.inHeap(v))
00242         order_heap.decrease(v); }
00243 
00244 inline void Solver::claDecayActivity() { cla_inc *= clause_decay; }
00245 inline void Solver::claBumpActivity (Clause& c) {
00246         if ( (c.activity() += cla_inc) > 1e20 ) {
00247             // Rescale:
00248             for (int i = 0; i < learnts.size(); i++)
00249                 learnts[i]->activity() *= 1e-20;
00250             cla_inc *= 1e-20; } }
00251 
00252 inline bool     Solver::enqueue         (Lit p, Clause* from)   { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); }
00253 inline bool     Solver::locked          (const Clause& c) const { return reason[var(c[0])] == &c && value(c[0]) == l_True; }
00254 inline void     Solver::newDecisionLevel()                      { trail_lim.push(trail.size()); }
00255 
00256 inline int      Solver::decisionLevel ()      const   { return trail_lim.size(); }
00257 inline uint32_t Solver::abstractLevel (Var x) const   { return 1 << (level[x] & 31); }
00258 inline lbool    Solver::value         (Var x) const   { return toLbool(assigns[x]); }
00259 inline lbool    Solver::value         (Lit p) const   { return toLbool(assigns[var(p)]) ^ sign(p); }
00260 inline lbool    Solver::modelValue    (Lit p) const   { return model[var(p)] ^ sign(p); }
00261 inline int      Solver::nAssigns      ()      const   { return trail.size(); }
00262 inline int      Solver::nClauses      ()      const   { return clauses.size(); }
00263 inline int      Solver::nLearnts      ()      const   { return learnts.size(); }
00264 inline int      Solver::nVars         ()      const   { return assigns.size(); }
00265 inline void     Solver::setPolarity   (Var v, bool b) { polarity    [v] = (char)b; }
00266 inline void     Solver::setDecisionVar(Var v, bool b) { decision_var[v] = (char)b; if (b) { insertVarOrder(v); } }
00267 inline bool     Solver::solve         ()              { vec<Lit> tmp; return solve(tmp); }
00268 inline bool     Solver::okay          ()      const   { return ok; }
00269 
00270 
00271 
00272 //=================================================================================================
00273 // Debug + etc:
00274 
00275 
00276 #define reportf(format, args...) ( fflush(stdout), fprintf(stderr, format, ## args), fflush(stderr) )
00277 
00278 static inline void logLit(FILE* f, Lit l)
00279 {
00280     fprintf(f, "%sx%d", sign(l) ? "~" : "", var(l)+1);
00281 }
00282 
00283 static inline void logLits(FILE* f, const vec<Lit>& ls)
00284 {
00285     fprintf(f, "[ ");
00286     if (ls.size() > 0){
00287         logLit(f, ls[0]);
00288         for (int i = 1; i < ls.size(); i++){
00289             fprintf(f, ", ");
00290             logLit(f, ls[i]);
00291         }
00292     }
00293     fprintf(f, "] ");
00294 }
00295 
00296 static inline const char* showBool(bool b) { return b ? "true" : "false"; }
00297 
00298 
00299 // Just like 'assert()' but expression will be evaluated in the release version as well.
00300 static inline void check(bool expr) { assert(expr); }
00301 
00302 
00303 inline void Solver::printLit(Lit l)
00304 {
00305     reportf("%s%d:%c", sign(l) ? "-" : "", var(l)+1, value(l) == l_True ? '1' : (value(l) == l_False ? '0' : 'X'));
00306 }
00307 
00308 
00309 template<class C>
00310 inline void Solver::printClause(const C& c)
00311 {
00312     for (int i = 0; i < c.size(); i++){
00313         printLit(c[i]);
00314         fprintf(stderr, " ");
00315     }
00316 }
00317 }
00318 
00319 //=================================================================================================
00320 #endif