Glucose2.cpp 59.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/***************************************************************************************[Solver.cc]
 Glucose -- Copyright (c) 2013, Gilles Audemard, Laurent Simon
                                CRIL - Univ. Artois, France
                                LRI  - Univ. Paris Sud, France
 
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).

---------------

Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
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 <math.h>

#include "sat/glucose2/Sort.h"
#include "sat/glucose2/Constants.h"
#include "sat/glucose2/System.h"
34 35 36
#include "sat/glucose2/Solver.h"

#include "sat/glucose2/CGlucose.h"
37 38 39 40 41 42 43

ABC_NAMESPACE_IMPL_START

using namespace Gluco2;

//=================================================================================================
// Options:
44
namespace Gluco2 {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
static const char* _cat = "CORE";
static const char* _cr = "CORE -- RESTART";
static const char* _cred = "CORE -- REDUCE";
static const char* _cm = "CORE -- MINIMIZE";
static const char* _certified = "CORE -- CERTIFIED UNSAT";




static BoolOption    opt_incremental              (_cat,"incremental",             "Use incremental SAT solving",                                            false);
static DoubleOption  opt_K                        (_cr, "K",                       "The constant used to force restart",                                     0.8,  DoubleRange(0, false, 1, false));           
static DoubleOption  opt_R                        (_cr, "R",                       "The constant used to block restart",                                     1.4,  DoubleRange(1, false, 5, false));           
static IntOption     opt_size_lbd_queue           (_cr, "szLBDQueue",              "The size of moving average for LBD (restarts)",                          50,   IntRange(10, INT32_MAX));
static IntOption     opt_size_trail_queue         (_cr, "szTrailQueue",            "The size of moving average for trail (block restarts)",                  5000, IntRange(10, INT32_MAX));

static IntOption     opt_first_reduce_db          (_cred, "firstReduceDB",         "The number of conflicts before the first reduce DB",                     2000, IntRange(0, INT32_MAX));
static IntOption     opt_inc_reduce_db            (_cred, "incReduceDB",           "Increment for reduce DB",                                                300,  IntRange(0, INT32_MAX));
static IntOption     opt_spec_inc_reduce_db       (_cred, "specialIncReduceDB",    "Special increment for reduce DB",                                        1000, IntRange(0, INT32_MAX));
static IntOption     opt_lb_lbd_frozen_clause     (_cred, "minLBDFrozenClause",    "Protect clauses if their LBD decrease and is lower than (for one turn)", 30,   IntRange(0, INT32_MAX));

static IntOption     opt_lb_size_minimzing_clause (_cm, "minSizeMinimizingClause", "The min size required to minimize clause",                               30, IntRange(3, INT32_MAX));
static IntOption     opt_lb_lbd_minimzing_clause  (_cm, "minLBDMinimizingClause",  "The min LBD required to minimize clause",                                6, IntRange(3, INT32_MAX));


static DoubleOption  opt_var_decay         (_cat, "var-decay",   "The variable activity decay factor",                                                       0.8,      DoubleRange(0, false, 1, false));
static DoubleOption  opt_clause_decay      (_cat, "cla-decay",   "The clause activity decay factor",                                                         0.999,    DoubleRange(0, false, 1, false));
static DoubleOption  opt_random_var_freq   (_cat, "rnd-freq",    "The frequency with which the decision heuristic tries to choose a random variable",        0, DoubleRange(0, true, 1, true));
static DoubleOption  opt_random_seed       (_cat, "rnd-seed",    "Used by the random variable selection",                                                    91648253, DoubleRange(0, false, HUGE_VAL, false));
static IntOption     opt_ccmin_mode        (_cat, "ccmin-mode",  "Controls conflict clause minimization (0=none, 1=basic, 2=deep)",                          2, IntRange(0, 2));
static IntOption     opt_phase_saving      (_cat, "phase-saving", "Controls the level of phase saving (0=none, 1=limited, 2=full)",                          2, IntRange(0, 2));
static BoolOption    opt_rnd_init_act      (_cat, "rnd-init",    "Randomize the initial activity",                                                           false);
/*
static IntOption     opt_restart_first     (_cat, "rfirst",      "The base restart interval",                                                                100, IntRange(1, INT32_MAX));
static DoubleOption  opt_restart_inc       (_cat, "rinc",        "Restart interval increase factor",                                                         2, DoubleRange(1, false, HUGE_VAL, false));
*/
static DoubleOption  opt_garbage_frac      (_cat, "gc-frac",     "The fraction of wasted memory allowed before a garbage collection is triggered",           0.20, DoubleRange(0, false, HUGE_VAL, false));


83 84 85
BoolOption    opt_certified_      (_certified, "certified",         "Certified UNSAT using DRUP format", false );
StringOption  opt_certified_file_ (_certified, "certified-output",  "Certified UNSAT output file",       "NULL");
};
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

//=================================================================================================
// Constructor/Destructor:


Solver::Solver() :

    // Parameters (user settable):
    //
    SolverType(0)
    , pCnfFunc(NULL)
    , nCallConfl(1000)
    , terminate_search_early(false)
    , pstop(NULL)
    , nRuntimeLimit(0)

    , verbosity      (0)
    , verbEveryConflicts(10000)
    , showModel      (0)
    , K              (opt_K)
    , R              (opt_R)
    , sizeLBDQueue   (opt_size_lbd_queue)
    , sizeTrailQueue   (opt_size_trail_queue)
    , firstReduceDB  (opt_first_reduce_db)
    , incReduceDB    (opt_inc_reduce_db)
    , specialIncReduceDB    (opt_spec_inc_reduce_db)
    , lbLBDFrozenClause (opt_lb_lbd_frozen_clause)
    , lbSizeMinimizingClause (opt_lb_size_minimzing_clause)
    , lbLBDMinimizingClause (opt_lb_lbd_minimzing_clause)
  , var_decay        (opt_var_decay)
  , clause_decay     (opt_clause_decay)
  , random_var_freq  (opt_random_var_freq)
  , random_seed      (opt_random_seed)
  , ccmin_mode       (opt_ccmin_mode)
  , phase_saving     (opt_phase_saving)
  , rnd_pol          (false)
  , rnd_init_act     (opt_rnd_init_act)
  , garbage_frac     (opt_garbage_frac)
  , certifiedOutput  (NULL)
125
  , certifiedUNSAT   (opt_certified_) 
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    // Statistics: (formerly in 'SolverStats')
    //
  ,  nbRemovedClauses(0),nbReducedClauses(0), nbDL2(0),nbBin(0),nbUn(0) , nbReduceDB(0)
    , solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0),conflicts(0),conflictsRestarts(0),nbstopsrestarts(0),nbstopsrestartssame(0),lastblockatrestart(0)
  , dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0)
    , curRestart(1)

  , ok                 (true)
  , cla_inc            (1)
  , var_inc            (1)
  , watches            (WatcherDeleted(ca))
  , watchesBin            (WatcherDeleted(ca))
  , qhead              (0)
  , simpDB_assigns     (-1)
  , simpDB_props       (0)
  , order_heap         (VarOrderLt(activity))
  , progress_estimate  (0)
  , remove_satisfied   (true)

    // Resource constraints:
    //
  , conflict_budget    (-1)
  , propagation_budget (-1)
  , asynch_interrupt   (false)
  , incremental(opt_incremental)
  , nbVarsInitialFormula(INT32_MAX)
152 153

  #ifdef CGLUCOSE_EXP
154 155
  //, jheap         (JustOrderLt(this))
  , jheap         (JustOrderLt2(this))
156
  #endif
157 158
{
  MYFLAG=0;  
159

160 161 162 163 164 165 166 167 168 169
  // Initialize only first time. Useful for incremental solving, useless otherwise
  lbdQueue.initSize(sizeLBDQueue);
  trailQueue.initSize(sizeTrailQueue);
  sumLBD = 0;
  nbclausesbeforereduce = firstReduceDB;
  totalTime4Sat=0;totalTime4Unsat=0;
  nbSatCalls=0;nbUnsatCalls=0;


  if(certifiedUNSAT) {
170
    if(!strcmp(opt_certified_file_,"NULL")) {
171 172
      certifiedOutput =  fopen("/dev/stdout", "wb");
    } else {
173
      certifiedOutput =  fopen(opt_certified_file_, "wb");           
174 175 176
    }
    //    fprintf(certifiedOutput,"o proof DRUP\n");
  }
177 178

  #ifdef CGLUCOSE_EXP
179
  jhead= 0;
180
  jftr = 0;
181 182 183 184 185 186 187 188
  travId = 0;
  travId_prev = 0;

  // allocate space for clause interpretation 
  vec<Lit> tmp; tmp.growTo(3); 
  itpc = ca.alloc(tmp);
  ca[itpc].shrink( ca[itpc].size() );

189
  nSkipMark = 0;
190
  #endif
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
}


Solver::~Solver()
{
}


/****************************************************************
 Set the incremental mode
****************************************************************/

// This function set the incremental mode to true.
// You can add special code for this mode here.

void Solver::setIncrementalMode() {
  incremental = true;
}

// Number of variables without selectors
void Solver::initNbInitialVars(int nb) {
  nbVarsInitialFormula = nb;
}


//=================================================================================================
// Minor methods:


// Creates a new SAT variable in the solver. If 'decision' 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)
{
    int v = nVars();
    watches  .init(mkLit(v, false));
    watches  .init(mkLit(v, true ));
    watchesBin  .init(mkLit(v, false));
    watchesBin  .init(mkLit(v, true ));
    assigns  .push(l_Undef);
    vardata  .push(mkVarData(CRef_Undef, 0));
    //activity .push(0);
    activity .push(rnd_init_act ? drand(random_seed) * 0.00001 : 0);
    seen     .push(0);
    permDiff .push(0);
    polarity .push(sign);
    decision .push();
    trail    .capacity(v+1);
239
    
240 241 242 243

    #ifdef CGLUCOSE_EXP
    //jreason  .capacity(v+1);
    if( justUsage() ){
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        //jdata    .push(mkJustData(false));
        //jwatch   .push(mkJustWatch());

        jlevel   .push(-1);
        jnext    .push(-1);

        var2FanoutN.growTo( nVars()<<1, toLit(~0));
        //var2FanoutP.growTo( nVars()<<1, toLit(~0));
        var2Fanout0.growTo( nVars(), toLit(~0));
        var2NodeData.growTo( nVars(), mkNodeData());
        var2TravId .growTo( nVars(), 0);

        setDecisionVar(v, dvar, false);
    } else 
        setDecisionVar(v, dvar);
    #else
    setDecisionVar(v, dvar);
261 262
    #endif

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    return v;
}



bool Solver::addClause_(vec<Lit>& ps)
{
    assert(decisionLevel() == 0);
    if (!ok) return false;

    if ( 0 ) {
        for ( int i = 0; i < ps.size(); i++ )
            printf( "%s%d ", (toInt(ps[i]) & 1) ? "-":"", toInt(ps[i]) >> 1 );
        printf( "\n" );
    }

    // Check if clause is satisfied and remove false/duplicate literals:
    sort(ps);

    vec<Lit>    oc;
    oc.clear();

    Lit p; int i, j, flag = 0;
    if(certifiedUNSAT) {
      for (i = j = 0, p = lit_Undef; i < ps.size(); i++) {
        oc.push(ps[i]);
        if (value(ps[i]) == l_True || ps[i] == ~p || value(ps[i]) == l_False)
          flag = 1;
      }
    }

    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];
299
    ps.shrink_(i - j);
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506

    if ( 0 ) {
        for ( int i = 0; i < ps.size(); i++ )
            printf( "%s%d ", (toInt(ps[i]) & 1) ? "-":"", toInt(ps[i]) >> 1 );
        printf( "\n" );
    }
    
    if (flag && (certifiedUNSAT)) {
      for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
        fprintf(certifiedOutput, "%i ", (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1));
      fprintf(certifiedOutput, "0\n");

      fprintf(certifiedOutput, "d ");
      for (i = j = 0, p = lit_Undef; i < oc.size(); i++)
        fprintf(certifiedOutput, "%i ", (var(oc[i]) + 1) * (-2 * sign(oc[i]) + 1));
      fprintf(certifiedOutput, "0\n");
    }

    if (ps.size() == 0)
        return ok = false;
    else if (ps.size() == 1){
        uncheckedEnqueue(ps[0]);
        return ok = (propagate() == CRef_Undef);
    }else{
        CRef cr = ca.alloc(ps, false);
        clauses.push(cr);
        attachClause(cr);
    }

    return true;
}


void Solver::attachClause(CRef cr) {
    const Clause& c = ca[cr];

    assert(c.size() > 1);
    if(c.size()==2) {
      watchesBin[~c[0]].push(Watcher(cr, c[1]));
      watchesBin[~c[1]].push(Watcher(cr, c[0]));
    } else {
      watches[~c[0]].push(Watcher(cr, c[1]));
      watches[~c[1]].push(Watcher(cr, c[0]));
    }
    if (c.learnt()) learnts_literals += c.size();
    else            clauses_literals += c.size(); }




void Solver::detachClause(CRef cr, bool strict) {
    const Clause& c = ca[cr];
    
    assert(c.size() > 1);
    if(c.size()==2) {
      if (strict){
        remove(watchesBin[~c[0]], Watcher(cr, c[1]));
        remove(watchesBin[~c[1]], Watcher(cr, c[0]));
      }else{
        // Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
        watchesBin.smudge(~c[0]);
        watchesBin.smudge(~c[1]);
      }
    } else {
      if (strict){
        remove(watches[~c[0]], Watcher(cr, c[1]));
        remove(watches[~c[1]], Watcher(cr, c[0]));
      }else{
        // Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
        watches.smudge(~c[0]);
        watches.smudge(~c[1]);
      }
    }
    if (c.learnt()) learnts_literals -= c.size();
    else            clauses_literals -= c.size(); }


void Solver::removeClause(CRef cr) {

  Clause& c = ca[cr];

  if (certifiedUNSAT) {
    fprintf(certifiedOutput, "d ");
    for (int i = 0; i < c.size(); i++)
      fprintf(certifiedOutput, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
    fprintf(certifiedOutput, "0\n");
  }

  detachClause(cr);
  // Don't leave pointers to free'd memory!
  if (locked(c)) vardata[var(c[0])].reason = CRef_Undef;
  c.mark(1);
  ca.free_(cr);
}


bool Solver::satisfied(const Clause& c) const {
  if(incremental)  // Check clauses with many selectors is too time consuming
    return (value(c[0]) == l_True) || (value(c[1]) == l_True);

  // Default mode.
    for (int i = 0; i < c.size(); i++)
        if (value(c[i]) == l_True)
            return true;
    return false; 
}

/************************************************************
 * Compute LBD functions
 *************************************************************/

inline unsigned int Solver::computeLBD(const vec<Lit> & lits,int end) {
  int nblevels = 0;
  MYFLAG++;

  if(incremental) { // ----------------- INCREMENTAL MODE
    if(end==-1) end = lits.size();
    unsigned int nbDone = 0;
    for(int i=0;i<lits.size();i++) {
      if(nbDone>=end) break;
      if(isSelector(var(lits[i]))) continue;
      nbDone++;
      int l = level(var(lits[i]));
      if (permDiff[l] != MYFLAG) {
        permDiff[l] = MYFLAG;
        nblevels++;
      }
    }
  } else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ
    for(int i=0;i<lits.size();i++) {
      int l = level(var(lits[i]));
      if (permDiff[l] != MYFLAG) {
        permDiff[l] = MYFLAG;
        nblevels++;
      }
    }
  }

  return nblevels;
}

inline unsigned int Solver::computeLBD(const Clause &c) {
  int nblevels = 0;
  MYFLAG++;

  if(incremental) { // ----------------- INCREMENTAL MODE
     int nbDone = 0;
    for(int i=0;i<c.size();i++) {
      if(nbDone>=c.sizeWithoutSelectors()) break;
      if(isSelector(var(c[i]))) continue;
      nbDone++;
      int l = level(var(c[i]));
      if (permDiff[l] != MYFLAG) {
        permDiff[l] = MYFLAG;
        nblevels++;
      }
    }
  } else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ
    for(int i=0;i<c.size();i++) {
      int l = level(var(c[i]));
      if (permDiff[l] != MYFLAG) {
        permDiff[l] = MYFLAG;
        nblevels++;
      }
    }
  }
  return nblevels;
}


/******************************************************************
 * Minimisation with binary reolution
 ******************************************************************/
void Solver::minimisationWithBinaryResolution(vec<Lit> &out_learnt) {
  
  // Find the LBD measure                                                                                                         
  unsigned int lbd = computeLBD(out_learnt);
  Lit p = ~out_learnt[0];
  
  if(lbd<=lbLBDMinimizingClause){
    MYFLAG++;
    
    for(int i = 1;i<out_learnt.size();i++) {
      permDiff[var(out_learnt[i])] = MYFLAG;
    }

    vec<Watcher>&  wbin  = watchesBin[p];
    int nb = 0;
    for(int k = 0;k<wbin.size();k++) {
      Lit imp = wbin[k].blocker;
      if(permDiff[var(imp)]==MYFLAG && value(imp)==l_True) {
        nb++;
        permDiff[var(imp)]= MYFLAG-1;
      }
      }
    int l = out_learnt.size()-1;
    if(nb>0) {
      nbReducedClauses++;
      for(int i = 1;i<out_learnt.size()-nb;i++) {
        if(permDiff[var(out_learnt[i])]!=MYFLAG) {
          Lit p = out_learnt[l];
          out_learnt[l] = out_learnt[i];
          out_learnt[i] = p;
          l--;i--;
        }
      }
      
507
      out_learnt.shrink_(nb);
508 509 510 511 512 513 514 515 516
      
    }
  }
}

// Revert to the state at given level (keeping all assignment at 'level' but not beyond).
//
void Solver::cancelUntil(int level) {
    if (decisionLevel() > level){
517 518 519 520

        #ifdef CGLUCOSE_EXP
        if( 0 < justUsage() ){

521 522 523 524 525 526
            for (int c = trail.size()-1; c >= trail_lim[level]; c--){
                Var      x  = var(trail[c]);
                assigns [x] = l_Undef;
                if (phase_saving > 1 || ((phase_saving == 1) && c > trail_lim.last()))
                    polarity[x] = sign(trail[c]);
                //gateClearJwatch(x, level);
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
                var2NodeData[x].now = false;
            }
            for (int l = decisionLevel(); l > level; l -- ){
                int q = jlevel[l], k;
                jlevel[l] = -1;
                while( -1 != q ){
                    k = jnext[q];
                    jnext[q] = -1;
                    Var v = var(trail[q]);
                    if( Solver::level(v) <= level ){
                        pushJustQueue(v,q);
                    }
                    q = k;
                }
            }
        } else 
544
        #endif
545 546 547 548 549 550 551 552 553
            for (int c = trail.size()-1; c >= trail_lim[level]; c--){
                Var      x  = var(trail[c]);
                assigns [x] = l_Undef;
                if (phase_saving > 1 || ((phase_saving == 1) && c > trail_lim.last()))
                    polarity[x] = sign(trail[c]);
                insertVarOrder(x);
            }

        jhead = qhead = trail_lim[level];
554 555 556 557

        trail.shrink_(trail.size() - trail_lim[level]);
        trail_lim.shrink_(trail_lim.size() - level);
    }
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
}


//=================================================================================================
// Major methods:


Lit Solver::pickBranchLit()
{
    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 (value(next) == l_Undef && decision[next])
            rnd_decisions++; }

    // Activity based decision:
    while (next == var_Undef || value(next) != l_Undef || !decision[next])
        if (order_heap.empty()){
            next = var_Undef;
            break;
        }else
            next = order_heap.removeMin();
    
    return next == var_Undef ? lit_Undef : mkLit(next, rnd_pol ? drand(random_seed) < 0.5 : (polarity[next] != 0));
}


/*_________________________________________________________________________________________________
|
|  analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (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'.
|      * If out_learnt.size() > 1 then 'out_learnt[1]' has the greatest decision level of the 
|        rest of literals. There may be others from the same level though.
|  
|________________________________________________________________________________________________@*/
void Solver::analyze(CRef confl, vec<Lit>& out_learnt,vec<Lit>&selectors, int& out_btlevel,unsigned int &lbd,unsigned int &szWithoutSelectors)
{
606
    //double clk = Abc_Clock();
607
    heap_rescale = 0;
608

609 610 611 612 613 614 615
    int pathC = 0;
    Lit p     = lit_Undef;

    // Generate conflict clause:
    //
    out_learnt.push();      // (leave room for the asserting literal)
    int index   = trail.size() - 1;
616
    
617
    analyze_toclear.shrink_( analyze_toclear.size() );
618 619
    do{
        assert(confl != CRef_Undef); // (otherwise should be UIP)
620

621
        #ifdef CGLUCOSE_EXP
622
        Clause& c = ca[ lit_Undef != p ? castCRef(p): getConfClause(confl) ];
623
        #else
624
        Clause& c = ca[confl];
625
        #endif
626 627 628 629

        // Special case for binary clauses
        // The first one has to be SAT
        if( p != lit_Undef && c.size()==2 && value(c[0])==l_False) {
630 631 632 633

            assert(value(c[1])==l_True);
            Lit tmp = c[0];
            c[0] =  c[1], c[1] = tmp;
634 635 636 637 638 639 640
        }
        
        if (c.learnt()) 
            claBumpActivity(c);

#ifdef DYNAMICNBLEVEL               
        // DYNAMIC NBLEVEL trick (see competition'09 companion paper)
641
        if(c.learnt()  && c.lbd()>2) {
642 643 644 645 646 647 648
            unsigned int nblevels = computeLBD(c);
            if(nblevels+1<c.lbd() ) { // improve the LBD
                if(c.lbd()<=lbLBDFrozenClause) {
                    c.setCanBeDel(false);
                }
                // seems to be interesting : keep it for the next round
                c.setLBD(nblevels); // Update it
649 650 651 652 653 654 655
            }
        }
#endif


        for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){
            Lit q = c[j];
656
            bool fBump = 0;
657 658

            if (!seen[var(q)] && level(var(q)) > 0){
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
                if(!isSelector(var(q))){
                    fBump = 1;
                    varBumpActivity(var(q));
                }
                seen[var(q)] = 1;
                if (level(var(q)) >= decisionLevel()) {
                    if( fBump )
                        analyze_toclear.push(q);
                    pathC++;
                    #ifdef UPDATEVARACTIVITY
                    // UPDATEVARACTIVITY trick (see competition'09 companion paper)
                    #ifdef CGLUCOSE_EXP
                    if(!isSelector(var(q)) && (reason(var(q))!= CRef_Undef)  
                    && ! isGateCRef(reason(var(q))) && ca[reason(var(q))].learnt())
                        lastDecisionLevel.push(q);
                    #else
                    if(!isSelector(var(q)) && (reason(var(q))!= CRef_Undef)  && ca[reason(var(q))].learnt()) 
                        lastDecisionLevel.push(q);
                    #endif
                    #endif

                } else {
                    if(isSelector(var(q))) {
                        assert(value(q) == l_False);
                        selectors.push(q);
                    } else 
                        out_learnt.push(q);
                }
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
            }
        }
        
        // Select next clause to look at:
        while (!seen[var(trail[index--])]);
        p     = trail[index+1];
        confl = reason(var(p));
        seen[var(p)] = 0;
        pathC--;

    }while (pathC > 0);
    out_learnt[0] = ~p;

    // Simplify conflict clause:
    //
    int i, j;

704 705
    for(i = 0;i<selectors.size();i++) out_learnt.push(selectors[i]);       

706

707 708 709 710
    #ifdef CGLUCOSE_EXP
    for(i = 0;i<out_learnt.size();i++)  
        analyze_toclear.push(out_learnt[i]);
    #else
711
    out_learnt.copyTo_(analyze_toclear);
712
    #endif
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    if (ccmin_mode == 2){
        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)

        for (i = j = 1; i < out_learnt.size(); i++)
            if (reason(var(out_learnt[i])) == CRef_Undef || !litRedundant(out_learnt[i], abstract_level))
                out_learnt[j++] = out_learnt[i];
        
    }else if (ccmin_mode == 1){
        for (i = j = 1; i < out_learnt.size(); i++){
            Var x = var(out_learnt[i]);

            if (reason(x) == CRef_Undef)
                out_learnt[j++] = out_learnt[i];
            else{
729 730 731
                #ifdef CGLUCOSE_EXP
                Clause& c = ca[castCRef(out_learnt[i])];
                #else
732
                Clause& c = ca[reason(var(out_learnt[i]))];
733
                #endif
734 735 736 737 738 739 740 741 742 743 744
                // Thanks to Siert Wieringa for this bug fix!
                for (int k = ((c.size()==2) ? 0:1); k < c.size(); k++)
                    if (!seen[var(c[k])] && level(var(c[k])) > 0){
                        out_learnt[j++] = out_learnt[i];
                        break; }
            }
        }
    }else
        i = j = out_learnt.size();

    max_literals += out_learnt.size();
745
    out_learnt.shrink_(i - j);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    tot_literals += out_learnt.size();


    /* ***************************************
      Minimisation with binary clauses of the asserting clause
      First of all : we look for small clauses
      Then, we reduce clauses with small LBD.
      Otherwise, this can be useless
     */
    if(!incremental && out_learnt.size()<=lbSizeMinimizingClause) {
      minimisationWithBinaryResolution(out_learnt);
    }
    // Find correct backtrack level:
    //
    if (out_learnt.size() == 1)
        out_btlevel = 0;
    else{
        int max_i = 1;
        // Find the first literal assigned at the next-highest level:
        for (int i = 2; i < out_learnt.size(); i++)
            if (level(var(out_learnt[i])) > level(var(out_learnt[max_i])))
                max_i = i;
        // Swap-in this literal at index 1:
        Lit p             = out_learnt[max_i];
        out_learnt[max_i] = out_learnt[1];
        out_learnt[1]     = p;
        out_btlevel       = level(var(p));
    }


    // Compute the size of the clause without selectors (incremental mode)
    if(incremental) {
      szWithoutSelectors = 0;
      for(int i=0;i<out_learnt.size();i++) {
        if(!isSelector(var((out_learnt[i])))) szWithoutSelectors++; 
        else if(i>0) break;
      }
    } else 
      szWithoutSelectors = out_learnt.size();
    
    // Compute LBD
    lbd = computeLBD(out_learnt,out_learnt.size()-selectors.size());

  
#ifdef UPDATEVARACTIVITY
791 792 793 794 795 796 797 798 799 800 801
    // UPDATEVARACTIVITY trick (see competition'09 companion paper)
    if(lastDecisionLevel.size()>0) {
        for(int i = 0;i<lastDecisionLevel.size();i++) {
            Lit t = lastDecisionLevel[i];
            //assert( ca[reason(var(t))].learnt() );
            if(ca[reason(var(t))].lbd()<lbd)
                varBumpActivity(var(t));
        }
        lastDecisionLevel.shrink_( lastDecisionLevel.size() );
    } 
#endif
802 803


804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    if( justUsage() ){
        if( heap_rescale )
        {
            for (j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0;

            analyze_toclear.shrink_( analyze_toclear.size() );
            for (j = 0; j < jheap.size(); j++){
                Var x = jheap[j];
                if( var2NodeData[x].now )
                    analyze_toclear.push(mkLit(x));
            }
            for (j = 0; j < analyze_toclear.size(); j++){
                Var x = var(analyze_toclear[j]);
//                jdata[x].act_fanin = activity[getFaninVar0(x)] > activity[getFaninVar1(x)]? activity[getFaninVar0(x)]: activity[getFaninVar1(x)];
//                jheap.update(x);
                if( activity[getFaninVar1(x)] > activity[getFaninVar0(x)] )
                    jheap.update( JustKey( activity[getFaninVar1(x)], x, jheap.data_attr(x) ) );
                else
                    jheap.update( JustKey( activity[getFaninVar0(x)], x, jheap.data_attr(x) ) );
            }
824

825
        } else {
826

827 828 829 830 831 832 833 834 835
            for (j = 0; j < analyze_toclear.size(); j++)
            {
                seen[var(analyze_toclear[j])] = 0;
                updateJustActivity(var(analyze_toclear[j]));
            }
        }
    } else
        for (j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0;    // ('seen[]' is now cleared)
    for(j = 0 ; j<selectors.size() ; j++) seen[var(selectors[j])] = 0;
836 837 838 839 840 841 842
}


// 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)
{
843
    analyze_stack.shrink_( analyze_stack.size() ); analyze_stack.push(p);
844 845 846
    int top = analyze_toclear.size();
    while (analyze_stack.size() > 0){
        assert(reason(var(analyze_stack.last())) != CRef_Undef);
847 848 849
        #ifdef CGLUCOSE_EXP
        Clause& c = ca[castCRef(analyze_stack.last())]; analyze_stack.pop();
        #else
850
        Clause& c = ca[reason(var(analyze_stack.last()))]; analyze_stack.pop();
851
        #endif
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
        if(c.size()==2 && value(c[0])==l_False) {
          assert(value(c[1])==l_True);
          Lit tmp = c[0];
          c[0] =  c[1], c[1] = tmp;
        }

        for (int i = 1; i < c.size(); i++){
            Lit p  = c[i];
            if (!seen[var(p)] && level(var(p)) > 0){
                if (reason(var(p)) != CRef_Undef && (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;
868
                    analyze_toclear.shrink_(analyze_toclear.size() - top);
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
                    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<Lit>& out_conflict)
{
890
    out_conflict.shrink_( out_conflict.size() );
891 892 893 894 895 896 897 898 899 900 901 902 903 904
    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) == CRef_Undef){
                assert(level(x) > 0);
                out_conflict.push(~trail[i]);
            }else{
905 906 907
              #ifdef CGLUCOSE_EXP
                Clause& c = ca[castCRef(trail[i])];
              #else
908
                Clause& c = ca[reason(x)];
909
              #endif
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
                //                for (int j = 1; j < c.size(); j++) Minisat (glucose 2.0) loop 
                // Bug in case of assumptions due to special data structures for Binary.
                // Many thanks to Sam Bayless (sbayless@cs.ubc.ca) for discover this bug.
                for (int j = ((c.size()==2) ? 0: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, CRef from)
{
927 928
    if( justUsage() && !isRoundWatch(var(p)) )
        return;
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
    assert(value(p) == l_Undef);
    assigns[var(p)] = lbool(!sign(p));
    vardata[var(p)] = mkVarData(from, decisionLevel());
    trail.push_(p);
}


/*_________________________________________________________________________________________________
|
|  propagate : [void]  ->  [Clause*]
|  
|  Description:
|    Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned,
|    otherwise CRef_Undef.
|  
|    Post-conditions:
|      * the propagation queue is empty, even if there was a conflict.
|________________________________________________________________________________________________@*/
CRef Solver::propagate()
{
    CRef    confl     = CRef_Undef;
    int     num_props = 0;
    watches.cleanAll();
    watchesBin.cleanAll();
    while (qhead < trail.size()){
        Lit            p   = trail[qhead++];     // 'p' is enqueued fact to propagate.
        vec<Watcher>&  ws  = watches[p];
        Watcher        *i, *j, *end;
        num_props++;
958 959 960

        #ifdef CGLUCOSE_EXP
        if( 2 <= justUsage() ){
961 962 963 964 965
            CRef stats;
            if( CRef_Undef != (stats = gatePropagate(p)) ){
                confl = stats;
                if( l_True == value(var(p)) ) return confl;
            }
966 967 968
        }
        #endif

969 970 971 972 973 974 975 976 977 978 979 980
        // First, Propagate binary clauses 
        vec<Watcher>&  wbin  = watchesBin[p];
        for(int k = 0;k<wbin.size();k++) {
          Lit imp = wbin[k].blocker;
          if(value(imp) == l_False) {
            return wbin[k].cref;
          }
          if(value(imp) == l_Undef) {
            uncheckedEnqueue(imp,wbin[k].cref);
          }
        }

981 982


983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        for (i = j = (Watcher*)ws, end = i + ws.size();  i != end;){
            // Try to avoid inspecting the clause:
            Lit blocker = i->blocker;
            if (value(blocker) == l_True){
                *j++ = *i++; continue; }

            // Make sure the false literal is data[1]:
            CRef     cr        = i->cref;
            Clause&  c         = ca[cr];
            Lit      false_lit = ~p;
            if (c[0] == false_lit)
                c[0] = c[1], c[1] = false_lit;
            assert(c[1] == false_lit);
            i++;

            // If 0th watch is true, then clause is already satisfied.
            Lit     first = c[0];
            Watcher w     = Watcher(cr, first);
            if (first != blocker && value(first) == l_True){
              *j++ = w; continue; }

            // Look for new watch:
            if(incremental) { // ----------------- INCREMENTAL MODE
              int choosenPos = -1;
              for (int k = 2; k < c.size(); k++) {
                
                if (value(c[k]) != l_False){
                  if(decisionLevel()>assumptions.size()) {
                    choosenPos = k;
                    break;
                  } else {
                    choosenPos = k;
                    
                    if(value(c[k])==l_True || !isSelector(var(c[k]))) {
                      break;
                    }
                  }

                }
              }
              if(choosenPos!=-1) {
                c[1] = c[choosenPos]; c[choosenPos] = false_lit;
                watches[~c[1]].push(w);
                goto NextClause; }
            } else {  // ----------------- DEFAULT  MODE (NOT INCREMENTAL)
              for (int k = 2; k < c.size(); k++) {
                
                if (value(c[k]) != l_False){
                  c[1] = c[k]; c[k] = false_lit;
                  watches[~c[1]].push(w);
                  goto NextClause; }
              }
            }

            // Did not find watch -- clause is unit under assignment:
            *j++ = w;
            if (value(first) == l_False){
                confl = cr;
                qhead = trail.size();
                // Copy the remaining watches:
                while (i < end)
                    *j++ = *i++;
            }else {
                uncheckedEnqueue(first, cr);
          
                
            }
        NextClause:;
        }
1052
        ws.shrink_(i - j);
1053 1054 1055
    }
    propagations += num_props;
    simpDB_props -= num_props;
1056

1057 1058 1059 1060
    return confl;
}


1061 1062 1063 1064




1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
/*_________________________________________________________________________________________________
|
|  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 { 
    ClauseAllocator& ca;
    reduceDB_lt(ClauseAllocator& ca_) : ca(ca_) {}
    bool operator () (CRef x, CRef y) { 
 
    // Main criteria... Like in MiniSat we keep all binary clauses
    if(ca[x].size()> 2 && ca[y].size()==2) return 1;
    
    if(ca[y].size()> 2 && ca[x].size()==2) return 0;
    if(ca[x].size()==2 && ca[y].size()==2) return 0;
    
    // Second one  based on literal block distance
    if(ca[x].lbd()> ca[y].lbd()) return 1;
    if(ca[x].lbd()< ca[y].lbd()) return 0;    
    
    // Finally we can use old activity or size, we choose the last one
    return ca[x].activity() < ca[y].activity();
    //return x->size() < y->size();
    //return ca[x].size() > 2 && (ca[y].size() == 2 || ca[x].activity() < ca[y].activity()); } 
    }    
};

void Solver::reduceDB()
{ 
  int i, j;
  nbReduceDB++;
  sort(learnts, reduceDB_lt(ca));

  // We have a lot of "good" clauses, it is difficult to compare them. Keep more !
  if(ca[learnts[learnts.size() / RATIOREMOVECLAUSES]].lbd()<=3) nbclausesbeforereduce +=specialIncReduceDB; 
  // Useless :-)
  if(ca[learnts.last()].lbd()<=5)  nbclausesbeforereduce +=specialIncReduceDB;   
  
  // Don't delete binary or locked clauses. From the rest, delete clauses from the first half
  // Keep clauses which seem to be usefull (their lbd was reduce during this sequence)

  int limit = learnts.size() / 2;
  for (i = j = 0; i < learnts.size(); i++){
    Clause& c = ca[learnts[i]];
    if (c.lbd()>2 && c.size() > 2 && c.canBeDel() &&  !locked(c) && (i < limit)) {
      removeClause(learnts[i]);
      nbRemovedClauses++;
    }
    else {
      if(!c.canBeDel()) limit++; //we keep c, so we can delete an other clause
      c.setCanBeDel(true);       // At the next step, c can be delete
      learnts[j++] = learnts[i];
    }
  }
1122
  learnts.shrink_(i - j);
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  checkGarbage();
}


void Solver::removeSatisfied(vec<CRef>& cs)
{
    int i, j;
    for (i = j = 0; i < cs.size(); i++){
        Clause& c = ca[cs[i]];
        if (satisfied(c)) 
            removeClause(cs[i]);
        else
            cs[j++] = cs[i];
    }
1137
    cs.shrink_(i - j);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
}


void Solver::rebuildOrderHeap()
{
    vec<Var> vs;
    for (Var v = 0; v < nVars(); v++)
        if (decision[v] && value(v) == l_Undef)
            vs.push(v);
    order_heap.build(vs);
}


/*_________________________________________________________________________________________________
|
|  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() != CRef_Undef)
        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);

    checkGarbage();

1176 1177 1178 1179
    #ifdef CGLUCOSE_EXP
    if( !justUsage() )
    #endif
        rebuildOrderHeap();
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209

    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) (params : const SearchParams&)  ->  [lbool]
|  
|  Description:
|    Search for a model the specified number of conflicts. 
|    NOTE! Use negative value for 'nof_conflicts' 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)
{
    assert(ok);
    int         backtrack_level;
    int         conflictC = 0;
    vec<Lit>    learnt_clause,selectors;
    unsigned int nblevels,szWoutSelectors;
    bool blocked=false;
    starts++;
1210

1211 1212
    for (;;){
        CRef confl = propagate();
1213 1214 1215 1216 1217 1218 1219

        // exact conflict limit
        if ( !withinBudget() && confl != CRef_Undef ) {
          lbdQueue.fastclear();
          cancelUntil(0);
          return l_Undef; }

1220
        if (confl != CRef_Undef){
1221

1222 1223 1224 1225 1226 1227
            // CONFLICT
          conflicts++; conflictC++;conflictsRestarts++;
          if(conflicts%5000==0 && var_decay<0.95)
            var_decay += 0.01;

          if (verbosity >= 1 && conflicts%verbEveryConflicts==0){
1228
            printf("c | %8d   %7d    %5d | %7d %8d %8d | %5d %8d   %6d %8d | %6.3f %% \n", 
1229 1230 1231 1232
                   (int)starts,(int)nbstopsrestarts, (int)(conflicts/starts), 
                   (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]), nClauses(), (int)clauses_literals, 
                   (int)nbReduceDB, nLearnts(), (int)nbDL2,(int)nbRemovedClauses, progressEstimate()*100);
          }
1233
          if (decisionLevel() == 0) 
1234
            return l_False;
1235

1236 1237 1238 1239 1240 1241 1242 1243 1244

          trailQueue.push(trail.size());
          // BLOCK RESTART (CP 2012 paper)
          if( conflictsRestarts>LOWER_BOUND_FOR_BLOCKING_RESTART && lbdQueue.isvalid()  && trail.size()>R*trailQueue.getavg()) {
            lbdQueue.fastclear();
            nbstopsrestarts++;
            if(!blocked) {lastblockatrestart=starts;nbstopsrestartssame++;blocked=true;}
          }

1245 1246
            learnt_clause.shrink_( learnt_clause.size() );
            selectors    .shrink_( selectors.size() );
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
            analyze(confl, learnt_clause, selectors,backtrack_level,nblevels,szWoutSelectors);

            lbdQueue.push(nblevels);
            sumLBD += nblevels;
            cancelUntil(backtrack_level);
            if (certifiedUNSAT) {
              for (int i = 0; i < learnt_clause.size(); i++)
                fprintf(certifiedOutput, "%i " , (var(learnt_clause[i]) + 1) *
                            (-2 * sign(learnt_clause[i]) + 1) );
              fprintf(certifiedOutput, "0\n");
            }

            if (learnt_clause.size() == 1){
              uncheckedEnqueue(learnt_clause[0]);nbUn++;
            }else{
                CRef cr = ca.alloc(learnt_clause, true);
                ca[cr].setLBD(nblevels); 
                ca[cr].setSizeWithoutSelectors(szWoutSelectors);
                if(nblevels<=2) nbDL2++; // stats
                if(ca[cr].size()==2) nbBin++; // stats
                learnts.push(cr);
                attachClause(cr);

                claBumpActivity(ca[cr]);
                uncheckedEnqueue(learnt_clause[0], cr);
            }
            varDecayActivity();
            claDecayActivity();

        }else{
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
            // Our dynamic restart, see the SAT09 competition compagnion paper 
            if ( (conflictsRestarts && lbdQueue.isvalid() && lbdQueue.getavg()*K > sumLBD/conflictsRestarts) || (pstop && *pstop) ) {
                lbdQueue.fastclear();
                progress_estimate = progressEstimate();
                int bt = 0;
                if(incremental) { // DO NOT BACKTRACK UNTIL 0.. USELESS
                    bt = (decisionLevel()<assumptions.size()) ? decisionLevel() : assumptions.size();
                }
                cancelUntil(bt);
                return l_Undef; 
1287 1288
            }

1289 1290 1291 1292
            // Simplify the set of problem clauses:
            if (decisionLevel() == 0 && !simplify()) {
                return l_False;
            }
1293
            // Perform clause database reduction !
1294 1295
            if(conflicts>=curRestart* nbclausesbeforereduce)
            {
1296 1297 1298 1299
                assert(learnts.size()>0);
                curRestart = (conflicts/ nbclausesbeforereduce)+1;
                reduceDB();
                nbclausesbeforereduce += incReduceDB;
1300
            }
1301 1302 1303 1304 1305 1306 1307 1308

            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();
1309
                } else if (value(p) == l_False){
1310 1311
                    analyzeFinal(~p, conflict);
                    return l_False;
1312
                } else {
1313 1314 1315 1316 1317
                    next = p;
                    break;
                }
            }

1318 1319
            #ifdef CGLUCOSE_EXP
            // pick from JustQueue
1320

1321 1322
            if (0 < justUsage())
            if ( next == lit_Undef ){
1323 1324 1325 1326 1327 1328 1329 1330
                int index = -1;
                decisions++;
                next = pickJustLit( index );
                if(next == lit_Undef)
                    return l_True;
                //addJwatch(var(next), j_reason);
                jnext[index] = jlevel[decisionLevel()+1];
                jlevel[decisionLevel()+1] = index;
1331 1332 1333
            }
            #endif

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
            if (next == lit_Undef){
                // New variable decision:
                decisions++;
                next = pickBranchLit();

                if (next == lit_Undef){
                  // Model found:
                  return l_True;
                }
            }

            // Increase decision level and enqueue 'next'
            newDecisionLevel();
            uncheckedEnqueue(next);
        }
    }
}


1353

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
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();
}

void Solver::printIncrementalStats() {

  printf("c---------- Glucose Stats -------------------------\n");
  printf("c restarts              : %ld\n", starts);
  printf("c nb ReduceDB           : %ld\n", nbReduceDB);
  printf("c nb removed Clauses    : %ld\n", nbRemovedClauses);
  printf("c nb learnts DL2        : %ld\n", nbDL2);
  printf("c nb learnts size 2     : %ld\n", nbBin);
  printf("c nb learnts size 1     : %ld\n", nbUn);

  printf("c conflicts             : %ld\n", conflicts);
  printf("c decisions             : %ld\n", decisions);
  printf("c propagations          : %ld\n", propagations);

  printf("c SAT Calls             : %d in %g seconds\n", nbSatCalls,   totalTime4Sat);
  printf("c UNSAT Calls           : %d in %g seconds\n", nbUnsatCalls, totalTime4Unsat);
  printf("c--------------------------------------------------\n");


}


// NOTE: assumptions passed in member-variable 'assumptions'.
lbool Solver::solve_()
{

1394 1395 1396 1397
    #ifdef CGLUCOSE_EXP
    ResetJustData(false);
    #endif

1398 1399 1400 1401 1402
    if(incremental && certifiedUNSAT) {
        printf("Can not use incremental and certified unsat in the same time\n");
        exit(-1);
    }

1403 1404 1405 1406 1407
    conflict.shrink_(conflict.size());
    if (!ok){
      travId_prev = travId;
      return l_False;
    }
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    double curTime = cpuTime();
    
    solves++;
    
    lbool   status        = l_Undef;
    if(!incremental && verbosity>=1) {
      printf("c ========================================[ MAGIC CONSTANTS ]==============================================\n");
      printf("c | Constants are supposed to work well together :-)                                                      |\n");
      printf("c | however, if you find better choices, please let us known...                                           |\n");
      printf("c |-------------------------------------------------------------------------------------------------------|\n");
    printf("c |                                |                                |                                     |\n"); 
    printf("c | - Restarts:                    | - Reduce Clause DB:            | - Minimize Asserting:               |\n");
    printf("c |   * LBD Queue    : %6d      |   * First     : %6d         |    * size < %3d                     |\n",lbdQueue.maxSize(),nbclausesbeforereduce,lbSizeMinimizingClause);
    printf("c |   * Trail  Queue : %6d      |   * Inc       : %6d         |    * lbd  < %3d                     |\n",trailQueue.maxSize(),incReduceDB,lbLBDMinimizingClause);
    printf("c |   * K            : %6.2f      |   * Special   : %6d         |                                     |\n",K,specialIncReduceDB);
    printf("c |   * R            : %6.2f      |   * Protected :  (lbd)< %2d     |                                     |\n",R,lbLBDFrozenClause);
    printf("c |                                |                                |                                     |\n"); 
printf("c ==================================[ Search Statistics (every %6d conflicts) ]=========================\n",verbEveryConflicts);
      printf("c |                                                                                                       |\n"); 

      printf("c |          RESTARTS           |          ORIGINAL         |              LEARNT              | Progress |\n");
1429
      printf("c |       NB   Blocked  Avg Cfc |    Vars  Clauses Literals |   Red   Learnts    LBD2  Removed |          | pol-inconsist\n");
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
      printf("c =========================================================================================================\n");
    }

    // Search:
    int curr_restarts = 0;
    while (status == l_Undef){
      status = search(0); // the parameter is useless in glucose, kept to allow modifications
        if (!withinBudget() || terminate_search_early || (pstop && *pstop)) break;
        if (nRuntimeLimit && Abc_Clock() > nRuntimeLimit)                   break;
        curr_restarts++;
    }

    if (!incremental && verbosity >= 1)
      printf("c =========================================================================================================\n");


    if (certifiedUNSAT){ // Want certified output
      if (status == l_False)
        fprintf(certifiedOutput, "0\n");
      fclose(certifiedOutput);
    }


    if (status == l_True){
1454

1455
        if( justUsage() ){
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
            if( nSkipMark ){
                loadJust();
            } else {
                JustModel.shrink_(JustModel.size());
                assert(jheap.empty());
                //JustModel.growTo(nVars());
                int i = 0, j = 0;
                JustModel.push(toLit(0));
                for (; i < trail.size(); i++) 
                    if( isRoundWatch(var(trail[i])) && !isTwoFanin(var(trail[i])) )
                        JustModel.push(trail[i]), j++;
                JustModel[0] = toLit(j);
            }
            
1470
        } else {
1471 1472 1473 1474
            // Extend & copy model:
            model.shrink_(model.size());
            model.growTo(nVars());
            for (int i = 0; i < trail.size(); i++) model[ var(trail[i]) ] = value(var(trail[i]));
1475
        }
1476 1477 1478
    }else if (status == l_False && conflict.size() == 0)
        ok = false;

1479 1480 1481 1482 1483
    //#ifdef CGLUCOSE_EXP
    //if(status == l_True && 0 < justUsage())
    //  justCheck();
    //#endif

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
    cancelUntil(0);

    double finalTime = cpuTime();
    if(status==l_True) {
      nbSatCalls++; 
      totalTime4Sat +=(finalTime-curTime);
    }
    if(status==l_False) {
      nbUnsatCalls++; 
      totalTime4Unsat +=(finalTime-curTime);
    }

    // ABC callback
    if (pCnfFunc && !terminate_search_early) {// hack to avoid calling callback twise if the solver was terminated early
        int * pCex = NULL;
        int message = (status == l_True ? 1 : status == l_False ? 0 : -1);
        if (status == l_True) {
            pCex = new int[nVars()];
            for (int i = 0; i < nVars(); i++)
                pCex[i] = (model[i] == l_True);
        }
        
        int callback_result = pCnfFunc(pCnfMan, message, pCex);
        assert(callback_result == 0);
    }
    else if (pCnfFunc)
        terminate_search_early = false; // for next run

1512
    travId_prev = travId;
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
    return status;
}

//=================================================================================================
// Writing CNF to DIMACS:
// 
// FIXME: this needs to be rewritten completely.

static Var mapVar(Var x, vec<Var>& map, Var& max)
{
    if (map.size() <= x || map[x] == -1){
        map.growTo(x+1, -1);
        map[x] = max++;
    }
    return map[x];
}


void Solver::toDimacs(FILE* f, Clause& c, vec<Var>& map, Var& max)
{
    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]) ? "-" : "", mapVar(var(c[i]), map, max)+1);
    fprintf(f, "0\n");
}


void Solver::toDimacs(const char *file, const vec<Lit>& assumps)
{
1544
    FILE* f = fopen(file, "wb");
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    if (f == NULL)
        fprintf(stderr, "could not open file %s\n", file), exit(1);
    toDimacs(f, assumps);
    fclose(f);
}


void Solver::toDimacs(FILE* f, const vec<Lit>& assumps)
{
    // Handle case when solver is in contradictory state:
    if (!ok){
        fprintf(f, "p cnf 1 2\n1 0\n-1 0\n");
        return; }

    vec<Var> map; Var max = 0;

    // Cannot use removeClauses here because it is not safe
    // to deallocate them at this point. Could be improved.
    int i, cnt = 0;
    for (i = 0; i < clauses.size(); i++)
        if (!satisfied(ca[clauses[i]]))
            cnt++;
        
    for (i = 0; i < clauses.size(); i++)
        if (!satisfied(ca[clauses[i]])){
            Clause& c = ca[clauses[i]];
            for (int j = 0; j < c.size(); j++)
                if (value(c[j]) != l_False)
                    mapVar(var(c[j]), map, max);
        }

    // Assumptions are added as unit clauses:
    cnt += assumptions.size();

    fprintf(f, "p cnf %d %d\n", max, cnt);

    for (i = 0; i < assumptions.size(); i++){
        assert(value(assumptions[i]) != l_False);
        fprintf(f, "%s%d 0\n", sign(assumptions[i]) ? "-" : "", mapVar(var(assumptions[i]), map, max)+1);
    }

    for (i = 0; i < clauses.size(); i++)
        toDimacs(f, ca[clauses[i]], map, max);

    if (verbosity > 0)
        printf("Wrote %d clauses with %d variables.\n", cnt, max);
}


//=================================================================================================
// Garbage Collection methods:

void Solver::relocAll(ClauseAllocator& to)
{
1599 1600 1601 1602 1603 1604
    #ifdef CGLUCOSE_EXP
    if( CRef_Undef != itpc ){
      setItpcSize(3);
      ca.reloc(itpc, to);
    }
    #endif
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
    int v, s, i, j;
    // All watchers:
    //
    // for (int i = 0; i < watches.size(); i++)
    watches.cleanAll();
    watchesBin.cleanAll();
    for (v = 0; v < nVars(); v++)
        for (s = 0; s < 2; s++){
            Lit p = mkLit(v, s != 0);
            // printf(" >>> RELOCING: %s%d\n", sign(p)?"-":"", var(p)+1);
            vec<Watcher>& ws = watches[p];
            for (j = 0; j < ws.size(); j++)
                ca.reloc(ws[j].cref, to);
            vec<Watcher>& ws2 = watchesBin[p];
            for (j = 0; j < ws2.size(); j++)
                ca.reloc(ws2[j].cref, to);
        }

    // All reasons:
    //
    for (i = 0; i < trail.size(); i++){
        Var v = var(trail[i]);

1628 1629 1630 1631
        #ifdef CGLUCOSE_EXP
        if( isGateCRef(reason(v)) )
          continue;
        #endif
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
        if (reason(v) != CRef_Undef && (ca[reason(v)].reloced() || locked(ca[reason(v)])))
            ca.reloc(vardata[v].reason, to);
    }

    // All learnt:
    //
    for (i = 0; i < learnts.size(); i++)
        ca.reloc(learnts[i], to);

    // All original:
    //
    for (i = 0; i < clauses.size(); i++)
        ca.reloc(clauses[i], to);
}


void Solver::garbageCollect()
{
    // Initialize the next region to a size corresponding to the estimated utilization degree. This
    // is not precise but should avoid some unnecessary reallocations for the new region:
    ClauseAllocator to(ca.size() - ca.wasted()); 

    relocAll(to);
    if (verbosity >= 2)
        printf("|  Garbage collection:   %12d bytes => %12d bytes             |\n", 
               ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
    to.moveTo(ca);
}

void Solver::reset() 
{
    // Reset everything
    ok = true;
    K = (double)opt_K;
    R = (double)opt_R;
    firstReduceDB = opt_first_reduce_db;
    var_decay = (double)opt_var_decay;
    //max_var_decay = opt_max_var_decay;
    solves = starts = decisions = propagations = conflicts = conflictsRestarts = 0;
    curRestart = 1;
    cla_inc = var_inc = 1;
    watches.clear(false); // We don't free the memory, new calls should be of the same size order.
    watchesBin.clear(false); 
    //unaryWatches.clear(false);
    qhead = 0;
    simpDB_assigns = -1;
    simpDB_props = 0;
    order_heap.clear(false);
    progress_estimate = 0;
    //lastLearntClause = CRef_Undef;
    conflict_budget = -1;
    propagation_budget = -1;
    nbVarsInitialFormula = INT32_MAX;
    totalTime4Sat = 0.;
    totalTime4Unsat = 0.;
    nbSatCalls = nbUnsatCalls = 0;
    MYFLAG = 0;
    lbdQueue.clear(false);
    lbdQueue.initSize(sizeLBDQueue);
    trailQueue.clear(false);
    trailQueue.initSize(sizeTrailQueue);
    sumLBD = 0;
    nbclausesbeforereduce = firstReduceDB;
    //stats.clear();
    //stats.growTo(coreStatsSize, 0);
    clauses.clear(false);
    learnts.clear(false);
    //permanentLearnts.clear(false);
    //unaryWatchedClauses.clear(false);
1701 1702 1703 1704 1705
    model   .shrink_(model   .size());
    conflict.shrink_(conflict.size());
    activity.shrink_(activity.size());
    assigns .shrink_(assigns .size());
    polarity.shrink_(polarity.size());
1706
    //forceUNSAT.clear(false);
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
    decision   .shrink_(decision   .size());
    trail      .shrink_(trail      .size());
    trail_lim  .shrink_(trail_lim  .size());
    vardata    .shrink_(vardata    .size());
    assumptions.shrink_(assumptions.size());
    nbpos      .shrink_(nbpos      .size());
    permDiff   .shrink_(permDiff   .size());
    #ifdef UPDATEVARACTIVITY
    lastDecisionLevel.shrink_(lastDecisionLevel.size());
    #endif
1717
    ca.clear();
1718 1719 1720
    seen           .shrink_(seen.size());
    analyze_stack  .shrink_(analyze_stack  .size());
    analyze_toclear.shrink_(analyze_toclear.size());
1721 1722 1723
    add_tmp.clear(false);
    assumptionPositions.clear(false);
    initialPositions.clear(false);
1724 1725 1726 1727 1728

    #ifdef CGLUCOSE_EXP

    ResetJustData(false);

1729 1730
    //jwatch.shrink_(jwatch.size());
    //jdata .shrink_(jdata .size());
1731

1732
    jhead  = 0;
1733 1734 1735 1736
    travId = 0;
    travId_prev = 0;
    var2TravId   .shrink_(var2TravId.size());
    JustModel    .shrink_(JustModel .size());
1737 1738
    jlevel       .shrink_(jlevel.size());
    jnext        .shrink_(jnext.size());
1739

1740 1741
    //var2FaninLits.shrink_(var2FaninLits.size());
    var2NodeData .shrink_(var2NodeData .size());
1742 1743 1744 1745
    var2Fanout0  .shrink_(var2Fanout0  .size());
    var2FanoutN  .shrink_(var2FanoutN  .size());
    //var2FanoutP.clear(false);
    if( CRef_Undef != itpc ){
1746 1747 1748 1749 1750
        itpc = CRef_Undef;       // clause allocator has been cleared, do not worry 
        // allocate space for clause interpretation 
        vec<Lit> tmp; tmp.growTo(3); 
        itpc = ca.alloc(tmp);
        ca[itpc].shrink( ca[itpc].size() );
1751
    }
1752 1753 1754

    vMarked.shrink_( vMarked.size() );
    nSkipMark = 0;
1755
    #endif
1756 1757 1758
}

ABC_NAMESPACE_IMPL_END