Solver.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /****************************************************************************************[Solver.h]
  2. MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
  3. Copyright (c) 2007-2010, Niklas Sorensson
  4. Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
  5. Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
  6. Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
  7. Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
  8. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  9. associated documentation files (the "Software"), to deal in the Software without restriction,
  10. including without limitation the rights to use, copy, modify, merge, publish, distribute,
  11. sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all copies or
  14. substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
  16. NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
  19. OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. **************************************************************************************************/
  21. #ifndef Minisat_Solver_h
  22. #define Minisat_Solver_h
  23. #define ANTI_EXPLORATION
  24. #define BIN_DRUP
  25. #define GLUCOSE23
  26. //#define INT_QUEUE_AVG
  27. //#define LOOSE_PROP_STAT
  28. #ifdef GLUCOSE23
  29. #define INT_QUEUE_AVG
  30. #define LOOSE_PROP_STAT
  31. #endif
  32. #include "mtl/Vec.h"
  33. #include "mtl/Heap.h"
  34. #include "mtl/Alg.h"
  35. #include "utils/Options.h"
  36. #include "core/SolverTypes.h"
  37. #include "utils/ccnr.h"
  38. #include "utils/System.h"
  39. #include <vector>
  40. #include <set>
  41. // Don't change the actual numbers.
  42. #define LOCAL 0
  43. #define TIER2 2
  44. #define CORE 3
  45. namespace Minisat {
  46. //=================================================================================================
  47. // Solver -- the main class:
  48. class Solver {
  49. private:
  50. template<typename T>
  51. class MyQueue {
  52. int max_sz, q_sz;
  53. int ptr;
  54. int64_t sum;
  55. vec<T> q;
  56. public:
  57. MyQueue(int sz) : max_sz(sz), q_sz(0), ptr(0), sum(0) { assert(sz > 0); q.growTo(sz); }
  58. inline bool full () const { return q_sz == max_sz; }
  59. #ifdef INT_QUEUE_AVG
  60. inline T avg () const { assert(full()); return sum / max_sz; }
  61. #else
  62. inline double avg () const { assert(full()); return sum / (double) max_sz; }
  63. #endif
  64. inline void clear() { sum = 0; q_sz = 0; ptr = 0; }
  65. void push(T e) {
  66. if (q_sz < max_sz) q_sz++;
  67. else sum -= q[ptr];
  68. sum += e;
  69. q[ptr++] = e;
  70. if (ptr == max_sz) ptr = 0;
  71. }
  72. };
  73. public:
  74. // Constructor/Destructor:
  75. //
  76. Solver();
  77. virtual ~Solver();
  78. // Problem specification:
  79. //
  80. Var newVar (bool polarity = true, bool dvar = true); // Add a new variable with parameters specifying variable mode.
  81. bool addClause (const vec<Lit>& ps); // Add a clause to the solver.
  82. bool addEmptyClause(); // Add the empty clause, making the solver contradictory.
  83. bool addClause (Lit p); // Add a unit clause to the solver.
  84. bool addClause (Lit p, Lit q); // Add a binary clause to the solver.
  85. bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
  86. bool addClause_( vec<Lit>& ps); // Add a clause to the solver without making superflous internal copy. Will
  87. // change the passed vector 'ps'.
  88. // Solving:
  89. //
  90. bool simplify (); // Removes already satisfied clauses.
  91. bool solve (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions.
  92. lbool solveLimited (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions (With resource constraints).
  93. bool solve (); // Search without assumptions.
  94. bool solve (Lit p); // Search for a model that respects a single assumption.
  95. bool solve (Lit p, Lit q); // Search for a model that respects two assumptions.
  96. bool solve (Lit p, Lit q, Lit r); // Search for a model that respects three assumptions.
  97. bool okay () const; // FALSE means solver is in a conflicting state
  98. void toDimacs (FILE* f, const vec<Lit>& assumps); // Write CNF to file in DIMACS-format.
  99. void toDimacs (const char *file, const vec<Lit>& assumps);
  100. void toDimacs (FILE* f, Clause& c, vec<Var>& map, Var& max);
  101. // Convenience versions of 'toDimacs()':
  102. void toDimacs (const char* file);
  103. void toDimacs (const char* file, Lit p);
  104. void toDimacs (const char* file, Lit p, Lit q);
  105. void toDimacs (const char* file, Lit p, Lit q, Lit r);
  106. // Variable mode:
  107. //
  108. void setPolarity (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'.
  109. void setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic.
  110. // Read state:
  111. //
  112. lbool value (Var x) const; // The current value of a variable.
  113. lbool value (Lit p) const; // The current value of a literal.
  114. lbool modelValue (Var x) const; // The value of a variable in the last model. The last call to solve must have been satisfiable.
  115. lbool modelValue (Lit p) const; // The value of a literal in the last model. The last call to solve must have been satisfiable.
  116. int nAssigns () const; // The current number of assigned literals.
  117. int nClauses () const; // The current number of original clauses.
  118. int nLearnts () const; // The current number of learnt clauses.
  119. int nVars () const; // The current number of variables.
  120. int nFreeVars () const;
  121. // Resource contraints:
  122. //
  123. void setConfBudget(int64_t x);
  124. void setPropBudget(int64_t x);
  125. void budgetOff();
  126. void interrupt(); // Trigger a (potentially asynchronous) interruption of the solver.
  127. void clearInterrupt(); // Clear interrupt indicator flag.
  128. // Memory managment:
  129. //
  130. virtual void garbageCollect();
  131. void checkGarbage(double gf);
  132. void checkGarbage();
  133. // Extra results: (read-only member variable)
  134. //
  135. vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any).
  136. vec<Lit> conflict; // If problem is unsatisfiable (possibly under assumptions),
  137. // this vector represent the final conflict clause expressed in the assumptions.
  138. // Mode of operation:
  139. //
  140. FILE* drup_file;
  141. int verbosity;
  142. double step_size;
  143. double step_size_dec;
  144. double min_step_size;
  145. int timer;
  146. double var_decay;
  147. double clause_decay;
  148. double random_var_freq;
  149. double random_seed;
  150. bool VSIDS;
  151. int ccmin_mode; // Controls conflict clause minimization (0=none, 1=basic, 2=deep).
  152. int phase_saving; // Controls the level of phase saving (0=none, 1=limited, 2=full).
  153. bool rnd_pol; // Use random polarities for branching heuristics.
  154. bool rnd_init_act; // Initialize variable activities with a small random value.
  155. double garbage_frac; // The fraction of wasted memory allowed before a garbage collection is triggered.
  156. int restart_first; // The initial restart limit. (default 100)
  157. double restart_inc; // The factor with which the restart limit is multiplied in each restart. (default 1.5)
  158. double learntsize_factor; // The intitial limit for learnt clauses is a factor of the original clauses. (default 1 / 3)
  159. double learntsize_inc; // The limit for learnt clauses is multiplied with this factor each restart. (default 1.1)
  160. int learntsize_adjust_start_confl;
  161. double learntsize_adjust_inc;
  162. // Statistics: (read-only member variable)
  163. //
  164. uint64_t solves, starts, decisions, rnd_decisions, propagations, conflicts, conflicts_VSIDS;
  165. uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals;
  166. vec<uint32_t> picked;
  167. vec<uint32_t> conflicted;
  168. vec<uint32_t> almost_conflicted;
  169. #ifdef ANTI_EXPLORATION
  170. vec<uint32_t> canceled;
  171. #endif
  172. protected:
  173. // Helper structures:
  174. //
  175. struct VarData { CRef reason; int level; };
  176. static inline VarData mkVarData(CRef cr, int l){ VarData d = {cr, l}; return d; }
  177. struct Watcher {
  178. CRef cref;
  179. Lit blocker;
  180. Watcher(CRef cr, Lit p) : cref(cr), blocker(p) {}
  181. bool operator==(const Watcher& w) const { return cref == w.cref; }
  182. bool operator!=(const Watcher& w) const { return cref != w.cref; }
  183. };
  184. struct WatcherDeleted
  185. {
  186. const ClauseAllocator& ca;
  187. WatcherDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
  188. bool operator()(const Watcher& w) const { return ca[w.cref].mark() == 1; }
  189. };
  190. struct VarOrderLt {
  191. const vec<double>& activity;
  192. bool operator () (Var x, Var y) const { return activity[x] > activity[y]; }
  193. VarOrderLt(const vec<double>& act) : activity(act) { }
  194. };
  195. // Solver state:
  196. //
  197. bool ok; // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
  198. vec<CRef> clauses; // List of problem clauses.
  199. vec<CRef> learnts_core, // List of learnt clauses.
  200. learnts_tier2,
  201. learnts_local;
  202. double cla_inc; // Amount to bump next clause with.
  203. vec<double> activity_CHB, // A heuristic measurement of the activity of a variable.
  204. activity_VSIDS,activity_distance;
  205. double var_inc; // Amount to bump next variable with.
  206. OccLists<Lit, vec<Watcher>, WatcherDeleted>
  207. watches_bin, // Watches for binary clauses only.
  208. watches; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
  209. vec<lbool> assigns; // The current assignments.
  210. vec<char> polarity; // The preferred polarity of each variable.
  211. vec<char> decision; // Declares if a variable is eligible for selection in the decision heuristic.
  212. vec<Lit> trail; // Assignment stack; stores all assigments made in the order they were made.
  213. vec<int> trail_lim; // Separator indices for different decision levels in 'trail'.
  214. vec<VarData> vardata; // Stores reason and level for each variable.
  215. int qhead; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
  216. int simpDB_assigns; // Number of top-level assignments since last execution of 'simplify()'.
  217. int64_t simpDB_props; // Remaining number of propagations that must be made before next execution of 'simplify()'.
  218. vec<Lit> assumptions; // Current set of assumptions provided to solve by the user.
  219. Heap<VarOrderLt> order_heap_CHB, // A priority queue of variables ordered with respect to the variable activity.
  220. order_heap_VSIDS,order_heap_distance;
  221. double progress_estimate;// Set by 'search()'.
  222. bool remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'.
  223. int core_lbd_cut;
  224. float global_lbd_sum;
  225. MyQueue<int> lbd_queue; // For computing moving averages of recent LBD values.
  226. uint64_t next_T2_reduce,
  227. next_L_reduce;
  228. ClauseAllocator ca;
  229. // Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is
  230. // used, exept 'seen' wich is used in several places.
  231. //
  232. vec<char> seen;
  233. vec<Lit> analyze_stack;
  234. vec<Lit> analyze_toclear;
  235. vec<Lit> add_tmp;
  236. vec<Lit> add_oc;
  237. vec<uint64_t> seen2; // Mostly for efficient LBD computation. 'seen2[i]' will indicate if decision level or variable 'i' has been seen.
  238. uint64_t counter; // Simple counter for marking purpose with 'seen2'.
  239. double max_learnts;
  240. double learntsize_adjust_confl;
  241. int learntsize_adjust_cnt;
  242. // Resource contraints:
  243. //
  244. int64_t conflict_budget; // -1 means no budget.
  245. int64_t propagation_budget; // -1 means no budget.
  246. bool asynch_interrupt;
  247. // Main internal methods:
  248. //
  249. void insertVarOrder (Var x); // Insert a variable in the decision order priority queue.
  250. Lit pickBranchLit (); // Return the next decision variable.
  251. void newDecisionLevel (); // Begins a new decision level.
  252. void uncheckedEnqueue (Lit p, CRef from = CRef_Undef); // Enqueue a literal. Assumes value of literal is undefined.
  253. bool enqueue (Lit p, CRef from = CRef_Undef); // Test if fact 'p' contradicts current state, enqueue otherwise.
  254. CRef propagate (); // Perform unit propagation. Returns possibly conflicting clause.
  255. CRef propagateConfl ();
  256. bool propagateConflSim();
  257. void cancelUntil (int level); // Backtrack until a certain level.
  258. void analyze (CRef confl, vec<Lit>& out_learnt, int& out_btlevel, int& out_lbd); // (bt = backtrack)
  259. void analyzeFinal (Lit p, vec<Lit>& out_conflict); // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION?
  260. bool litRedundant (Lit p, uint32_t abstract_levels); // (helper method for 'analyze()')
  261. lbool search (int& nof_conflicts); // Search for a given number of conflicts.
  262. lbool solve_ (); // Main solve method (assumptions given in 'assumptions').
  263. void reduceDB (); // Reduce the set of learnt clauses.
  264. void reduceDB_Tier2 ();
  265. void removeSatisfied (vec<CRef>& cs); // Shrink 'cs' to contain only non-satisfied clauses.
  266. void safeRemoveSatisfied(vec<CRef>& cs, unsigned valid_mark);
  267. void rebuildOrderHeap ();
  268. bool binResMinimize (vec<Lit>& out_learnt); // Further learnt clause minimization by binary resolution.
  269. // Maintaining Variable/Clause activity:
  270. //
  271. void varDecayActivity (); // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead.
  272. void varBumpActivity (Var v, double mult); // Increase a variable with the current 'bump' value.
  273. void claDecayActivity (); // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead.
  274. void claBumpActivity (Clause& c); // Increase a clause with the current 'bump' value.
  275. // Operations on clauses:
  276. //
  277. void attachClause (CRef cr); // Attach a clause to watcher lists.
  278. void detachClause (CRef cr, bool strict = false); // Detach a clause to watcher lists.
  279. void removeClause (CRef cr); // Detach and free a clause.
  280. bool locked (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state.
  281. bool satisfied (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state.
  282. void relocAll (ClauseAllocator& to);
  283. // Misc:
  284. //
  285. int decisionLevel () const; // Gives the current decisionlevel.
  286. uint32_t abstractLevel (Var x) const; // Used to represent an abstraction of sets of decision levels.
  287. CRef reason (Var x) const;
  288. public:
  289. int level (Var x) const;
  290. protected:
  291. double progressEstimate () const; // DELETE THIS ?? IT'S NOT VERY USEFUL ...
  292. bool withinBudget () const;
  293. template<class V> int computeLBD(const V& c) {
  294. int lbd = 0;
  295. counter++;
  296. for (int i = 0; i < c.size(); i++){
  297. int l = level(var(c[i]));
  298. if (l != 0 && seen2[l] != counter){
  299. seen2[l] = counter;
  300. lbd++; } }
  301. return lbd;
  302. }
  303. #ifdef BIN_DRUP
  304. static int buf_len;
  305. static unsigned char drup_buf[];
  306. static unsigned char* buf_ptr;
  307. static inline void byteDRUP(Lit l){
  308. unsigned int u = 2 * (var(l) + 1) + sign(l);
  309. do{
  310. *buf_ptr++ = u & 0x7f | 0x80; buf_len++;
  311. u = u >> 7;
  312. }while (u);
  313. *(buf_ptr - 1) &= 0x7f; // End marker of this unsigned number.
  314. }
  315. template<class V>
  316. static inline void binDRUP(unsigned char op, const V& c, FILE* drup_file){
  317. assert(op == 'a' || op == 'd');
  318. *buf_ptr++ = op; buf_len++;
  319. for (int i = 0; i < c.size(); i++) byteDRUP(c[i]);
  320. *buf_ptr++ = 0; buf_len++;
  321. if (buf_len > 1048576) binDRUP_flush(drup_file);
  322. }
  323. static inline void binDRUP_strengthen(const Clause& c, Lit l, FILE* drup_file){
  324. *buf_ptr++ = 'a'; buf_len++;
  325. for (int i = 0; i < c.size(); i++)
  326. if (c[i] != l) byteDRUP(c[i]);
  327. *buf_ptr++ = 0; buf_len++;
  328. if (buf_len > 1048576) binDRUP_flush(drup_file);
  329. }
  330. static inline void binDRUP_flush(FILE* drup_file){
  331. // fwrite(drup_buf, sizeof(unsigned char), buf_len, drup_file);
  332. fwrite_unlocked(drup_buf, sizeof(unsigned char), buf_len, drup_file);
  333. buf_ptr = drup_buf; buf_len = 0;
  334. }
  335. #endif
  336. // Static helpers:
  337. //
  338. // Returns a random float 0 <= x < 1. Seed must never be 0.
  339. static inline double drand(double& seed) {
  340. seed *= 1389796;
  341. int q = (int)(seed / 2147483647);
  342. seed -= (double)q * 2147483647;
  343. return seed / 2147483647; }
  344. // Returns a random integer 0 <= x < size. Seed must never be 0.
  345. static inline int irand(double& seed, int size) {
  346. return (int)(drand(seed) * size); }
  347. // simplify
  348. //
  349. public:
  350. bool simplifyAll();
  351. void simplifyLearnt(Clause& c);
  352. bool simplifyLearnt_x(vec<CRef>& learnts_x);
  353. bool simplifyLearnt_core();
  354. bool simplifyLearnt_tier2();
  355. int trailRecord;
  356. void litsEnqueue(int cutP, Clause& c);
  357. void cancelUntilTrailRecord();
  358. void simpleUncheckEnqueue(Lit p, CRef from = CRef_Undef);
  359. CRef simplePropagate();
  360. uint64_t nbSimplifyAll;
  361. uint64_t simplified_length_record, original_length_record;
  362. uint64_t s_propagations;
  363. vec<Lit> simp_learnt_clause;
  364. vec<CRef> simp_reason_clause;
  365. void simpleAnalyze(CRef confl, vec<Lit>& out_learnt, vec<CRef>& reason_clause, bool True_confl);
  366. // in redundant
  367. bool removed(CRef cr);
  368. // adjust simplifyAll occasion
  369. long curSimplify;
  370. int nbconfbeforesimplify;
  371. int incSimplify;
  372. bool collectFirstUIP(CRef confl);
  373. vec<double> var_iLevel,var_iLevel_tmp;
  374. uint64_t nbcollectfirstuip, nblearntclause, nbDoubleConflicts, nbTripleConflicts;
  375. int uip1, uip2;
  376. vec<int> pathCs;
  377. CRef propagateLits(vec<Lit>& lits);
  378. uint64_t previousStarts;
  379. double var_iLevel_inc;
  380. vec<Lit> involved_lits;
  381. double my_var_decay;
  382. bool DISTANCE;
  383. public:
  384. //-------------------
  385. vector<lbool> result_call;
  386. vector<bool> falseModel;
  387. float conflRatio ;// = 0.90; //比率,当大于这个量的时候,ok均为true,并忽略所有的错误,一直搜到底
  388. float areaRatio ;// = 1.01; //用来限制生成的新的不完备解不与上一次的解搜索空间太近
  389. long long maxstep ;// = 20000000; //2kw 取maxstep 和 maxflipRatio之间最小的数作为上界
  390. float maxflipRatio ;// = 600.0; //不完备算法中反转次数和变量之间的比率
  391. float lastflipRatio ;// = 100.0; //初始比率
  392. float raiseFlipRatio ;// = 1.02; //每次将反转次数提高的比例
  393. //double timeLimit = 999999.0; //程序超过这个时间就会退出
  394. double timeRatio ;// = 0.35; //不完备算法求解时间最高占整体求解时间的比例
  395. double UnComTime ;// = 0.0;
  396. int callNum ;// = 0;
  397. bool solvedByUncom ;// = false;
  398. bool forceRestart ;// = false;
  399. int lastLearntNum ;// = 0;
  400. bool aspiration ;
  401. double swt_q ;
  402. double swt_threshold ;
  403. //;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  404. void getInitModelByValue();
  405. bool callUnCom();
  406. bool build_instance(ls_solver &ls_s);
  407. inline double getNowRatio(){return (0.0 + trail.size())/nVars();}
  408. //=============================================================
  409. };
  410. //=================================================================================================
  411. // Implementation of inline methods:
  412. inline CRef Solver::reason(Var x) const { return vardata[x].reason; }
  413. inline int Solver::level (Var x) const { return vardata[x].level; }
  414. inline void Solver::insertVarOrder(Var x) {
  415. // Heap<VarOrderLt>& order_heap = VSIDS ? order_heap_VSIDS : order_heap_CHB;
  416. Heap<VarOrderLt>& order_heap = DISTANCE ? order_heap_distance : ((!VSIDS)? order_heap_CHB:order_heap_VSIDS);
  417. if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); }
  418. inline void Solver::varDecayActivity() {
  419. var_inc *= (1 / var_decay); }
  420. inline void Solver::varBumpActivity(Var v, double mult) {
  421. if ( (activity_VSIDS[v] += var_inc * mult) > 1e100 ) {
  422. // Rescale:
  423. for (int i = 0; i < nVars(); i++)
  424. activity_VSIDS[i] *= 1e-100;
  425. var_inc *= 1e-100; }
  426. // Update order_heap with respect to new activity:
  427. if (order_heap_VSIDS.inHeap(v)) order_heap_VSIDS.decrease(v); }
  428. inline void Solver::claDecayActivity() { cla_inc *= (1 / clause_decay); }
  429. inline void Solver::claBumpActivity (Clause& c) {
  430. if ( (c.activity() += cla_inc) > 1e20 ) {
  431. // Rescale:
  432. for (int i = 0; i < learnts_local.size(); i++)
  433. ca[learnts_local[i]].activity() *= 1e-20;
  434. cla_inc *= 1e-20; } }
  435. inline void Solver::checkGarbage(void){ return checkGarbage(garbage_frac); }
  436. inline void Solver::checkGarbage(double gf){
  437. if (ca.wasted() > ca.size() * gf)
  438. garbageCollect(); }
  439. // NOTE: enqueue does not set the ok flag! (only public methods do)
  440. inline bool Solver::enqueue (Lit p, CRef from) { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); }
  441. inline bool Solver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); }
  442. inline bool Solver::addEmptyClause () { add_tmp.clear(); return addClause_(add_tmp); }
  443. inline bool Solver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
  444. inline bool Solver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
  445. inline bool Solver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
  446. inline bool Solver::locked (const Clause& c) const {
  447. int i = c.size() != 2 ? 0 : (value(c[0]) == l_True ? 0 : 1);
  448. return value(c[i]) == l_True && reason(var(c[i])) != CRef_Undef && ca.lea(reason(var(c[i]))) == &c;
  449. }
  450. inline void Solver::newDecisionLevel() { trail_lim.push(trail.size()); }
  451. inline int Solver::decisionLevel () const { return trail_lim.size(); }
  452. inline uint32_t Solver::abstractLevel (Var x) const { return 1 << (level(x) & 31); }
  453. inline lbool Solver::value (Var x) const { return assigns[x]; }
  454. inline lbool Solver::value (Lit p) const { return assigns[var(p)] ^ sign(p); }
  455. inline lbool Solver::modelValue (Var x) const { return model[x]; }
  456. inline lbool Solver::modelValue (Lit p) const { return model[var(p)] ^ sign(p); }
  457. inline int Solver::nAssigns () const { return trail.size(); }
  458. inline int Solver::nClauses () const { return clauses.size(); }
  459. inline int Solver::nLearnts () const { return learnts_core.size() + learnts_tier2.size() + learnts_local.size(); }
  460. inline int Solver::nVars () const { return vardata.size(); }
  461. inline int Solver::nFreeVars () const { return (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]); }
  462. inline void Solver::setPolarity (Var v, bool b) { polarity[v] = b; }
  463. inline void Solver::setDecisionVar(Var v, bool b)
  464. {
  465. if ( b && !decision[v]) dec_vars++;
  466. else if (!b && decision[v]) dec_vars--;
  467. decision[v] = b;
  468. if (b && !order_heap_CHB.inHeap(v)){
  469. order_heap_CHB.insert(v);
  470. order_heap_VSIDS.insert(v);
  471. order_heap_distance.insert(v);}
  472. }
  473. inline void Solver::setConfBudget(int64_t x){ conflict_budget = conflicts + x; }
  474. inline void Solver::setPropBudget(int64_t x){ propagation_budget = propagations + x; }
  475. inline void Solver::interrupt(){ asynch_interrupt = true; }
  476. inline void Solver::clearInterrupt(){ asynch_interrupt = false; }
  477. inline void Solver::budgetOff(){ conflict_budget = propagation_budget = -1; }
  478. inline bool Solver::withinBudget() const {
  479. return !asynch_interrupt &&
  480. (conflict_budget < 0 || conflicts < (uint64_t)conflict_budget) &&
  481. (propagation_budget < 0 || propagations < (uint64_t)propagation_budget); }
  482. // FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a
  483. // pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or
  484. // all calls to solve must return an 'lbool'. I'm not yet sure which I prefer.
  485. inline bool Solver::solve () { budgetOff(); assumptions.clear(); return solve_() == l_True; }
  486. inline bool Solver::solve (Lit p) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_() == l_True; }
  487. inline bool Solver::solve (Lit p, Lit q) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_() == l_True; }
  488. inline bool Solver::solve (Lit p, Lit q, Lit r) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_() == l_True; }
  489. inline bool Solver::solve (const vec<Lit>& assumps){ budgetOff(); assumps.copyTo(assumptions); return solve_() == l_True; }
  490. inline lbool Solver::solveLimited (const vec<Lit>& assumps){ assumps.copyTo(assumptions); return solve_(); }
  491. inline bool Solver::okay () const { return ok; }
  492. inline void Solver::toDimacs (const char* file){ vec<Lit> as; toDimacs(file, as); }
  493. inline void Solver::toDimacs (const char* file, Lit p){ vec<Lit> as; as.push(p); toDimacs(file, as); }
  494. inline void Solver::toDimacs (const char* file, Lit p, Lit q){ vec<Lit> as; as.push(p); as.push(q); toDimacs(file, as); }
  495. inline void Solver::toDimacs (const char* file, Lit p, Lit q, Lit r){ vec<Lit> as; as.push(p); as.push(q); as.push(r); toDimacs(file, as); }
  496. //=================================================================================================
  497. // Debug etc:
  498. //=================================================================================================
  499. }
  500. #endif