satSolver.c 50.5 KB
Newer Older
Alan Mishchenko committed
1 2 3 4
/**************************************************************************************************
MiniSat -- Copyright (c) 2005, Niklas Sorensson
http://www.cs.chalmers.se/Cs/Research/FormalMethods/MiniSat/

5
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
Alan Mishchenko committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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.
**************************************************************************************************/
// Modified to compile with MS Visual Studio 6.0 by Alan Mishchenko

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <math.h>

#include "satSolver.h"
28 29 30
#include "satStore.h"

ABC_NAMESPACE_IMPL_START
31 32 33

#define SAT_USE_ANALYZE_FINAL

34 35 36 37 38 39 40 41 42 43 44 45
/*
extern int Sto_ManAddClause( void * p, lit * pBeg, lit * pEnd );
extern int Sto_ManAddClause( void * p, lit * pBeg, lit * pEnd );
extern int Sto_ManAddClause( void * p, lit * pBeg, lit * pEnd );
extern int Sto_ManAddClause( void * p, lit * pBeg, lit * pEnd );
extern void * Sto_ManAlloc();
extern void Sto_ManDumpClauses( void * p, char * pFileName );
extern void Sto_ManFree( void * p );
extern int Sto_ManChangeLastClause( void * p );
extern void Sto_ManMarkRoots( void * p );
extern void Sto_ManMarkClausesA( void * p );
*/
46

Alan Mishchenko committed
47
//#define SAT_USE_SYSTEM_MEMORY_MANAGEMENT
Alan Mishchenko committed
48

49

Alan Mishchenko committed
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 83 84 85 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
//=================================================================================================
// Debug:

//#define VERBOSEDEBUG

// For derivation output (verbosity level 2)
#define L_IND    "%-*d"
#define L_ind    sat_solver_dlevel(s)*3+3,sat_solver_dlevel(s)
#define L_LIT    "%sx%d"
#define L_lit(p) lit_sign(p)?"~":"", (lit_var(p))

// Just like 'assert()' but expression will be evaluated in the release version as well.
static inline void check(int expr) { assert(expr); }

static void printlits(lit* begin, lit* end)
{
    int i;
    for (i = 0; i < end - begin; i++)
        printf(L_LIT" ",L_lit(begin[i]));
}

//=================================================================================================
// Random numbers:


// Returns a random float 0 <= x < 1. Seed must never be 0.
static inline double drand(double* seed) {
    int q;
    *seed *= 1389796;
    q = (int)(*seed / 2147483647);
    *seed -= (double)q * 2147483647;
    return *seed / 2147483647; }


// Returns a random integer 0 <= x < size. Seed must never be 0.
static inline int irand(double* seed, int size) {
    return (int)(drand(seed) * size); }


//=================================================================================================
// Predeclarations:

static void sat_solver_sort(void** array, int size, int(*comp)(const void *, const void *));

//=================================================================================================
// Clause datatype + minor functions:

struct clause_t
{
    int size_learnt;
    lit lits[0];
};

static inline int   clause_size       (clause* c)          { return c->size_learnt >> 1; }
static inline lit*  clause_begin      (clause* c)          { return c->lits; }
static inline int   clause_learnt     (clause* c)          { return c->size_learnt & 1; }
static inline float clause_activity   (clause* c)          { return *((float*)&c->lits[c->size_learnt>>1]); }
static inline void  clause_setactivity(clause* c, float a) { *((float*)&c->lits[c->size_learnt>>1]) = a; }

//=================================================================================================
// Encode literals in clause pointers:

Alan Mishchenko committed
112
static inline clause* clause_from_lit (lit l)     { return (clause*)((ABC_PTRUINT_T)l + (ABC_PTRUINT_T)l + 1); }
113
static inline int     clause_is_lit   (clause* c) { return ((ABC_PTRUINT_T)c & 1);                              }
Alan Mishchenko committed
114
static inline lit     clause_read_lit (clause* c) { return (lit)((ABC_PTRUINT_T)c >> 1);                        }
Alan Mishchenko committed
115 116 117 118 119 120 121 122 123 124 125 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 152 153 154 155 156 157 158 159 160 161 162 163 164 165

//=================================================================================================
// Simple helpers:

static inline int     sat_solver_dlevel(sat_solver* s)            { return veci_size(&s->trail_lim); }
static inline vecp*   sat_solver_read_wlist(sat_solver* s, lit l) { return &s->wlists[l]; }
static inline void    vecp_remove(vecp* v, void* e)
{
    void** ws = vecp_begin(v);
    int    j  = 0;
    for (; ws[j] != e  ; j++);
    assert(j < vecp_size(v));
    for (; j < vecp_size(v)-1; j++) ws[j] = ws[j+1];
    vecp_resize(v,vecp_size(v)-1);
}

//=================================================================================================
// Variable order functions:

static inline void order_update(sat_solver* s, int v) // updateorder
{
    int*    orderpos = s->orderpos;
    double* activity = s->activity;
    int*    heap     = veci_begin(&s->order);
    int     i        = orderpos[v];
    int     x        = heap[i];
    int     parent   = (i - 1) / 2;

    assert(s->orderpos[v] != -1);

    while (i != 0 && activity[x] > activity[heap[parent]]){
        heap[i]           = heap[parent];
        orderpos[heap[i]] = i;
        i                 = parent;
        parent            = (i - 1) / 2;
    }
    heap[i]     = x;
    orderpos[x] = i;
}

static inline void order_assigned(sat_solver* s, int v) 
{
}

static inline void order_unassigned(sat_solver* s, int v) // undoorder
{
    int* orderpos = s->orderpos;
    if (orderpos[v] == -1){
        orderpos[v] = veci_size(&s->order);
        veci_push(&s->order,v);
        order_update(s,v);
Alan Mishchenko committed
166
//printf( "+%d ", v );
Alan Mishchenko committed
167 168 169
    }
}

Alan Mishchenko committed
170
static inline int  order_select(sat_solver* s, float random_var_freq) // selectvar
Alan Mishchenko committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 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
{
    int*    heap;
    double* activity;
    int*    orderpos;

    lbool* values = s->assigns;

    // Random decision:
    if (drand(&s->random_seed) < random_var_freq){
        int next = irand(&s->random_seed,s->size);
        assert(next >= 0 && next < s->size);
        if (values[next] == l_Undef)
            return next;
    }

    // Activity based decision:

    heap     = veci_begin(&s->order);
    activity = s->activity;
    orderpos = s->orderpos;


    while (veci_size(&s->order) > 0){
        int    next  = heap[0];
        int    size  = veci_size(&s->order)-1;
        int    x     = heap[size];

        veci_resize(&s->order,size);

        orderpos[next] = -1;

        if (size > 0){
            double act   = activity[x];

            int    i     = 0;
            int    child = 1;


            while (child < size){
                if (child+1 < size && activity[heap[child]] < activity[heap[child+1]])
                    child++;

                assert(child < size);

                if (act >= activity[heap[child]])
                    break;

                heap[i]           = heap[child];
                orderpos[heap[i]] = i;
                i                 = child;
                child             = 2 * child + 1;
            }
            heap[i]           = x;
            orderpos[heap[i]] = i;
        }

Alan Mishchenko committed
227
//printf( "-%d ", next );
Alan Mishchenko committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        if (values[next] == l_Undef)
            return next;
    }

    return var_Undef;
}

//=================================================================================================
// Activity functions:

static inline void act_var_rescale(sat_solver* s) {
    double* activity = s->activity;
    int i;
    for (i = 0; i < s->size; i++)
        activity[i] *= 1e-100;
    s->var_inc *= 1e-100;
}

static inline void act_var_bump(sat_solver* s, int v) {
Alan Mishchenko committed
247 248
//    s->activity[v] += s->var_inc;
    s->activity[v] += (s->pGlobalVars? 3.0 : 1.0) * s->var_inc;
Alan Mishchenko committed
249
    if (s->activity[v] > 1e100)
Alan Mishchenko committed
250 251 252 253 254 255
        act_var_rescale(s);
    //printf("bump %d %f\n", v-1, activity[v]);
    if (s->orderpos[v] != -1)
        order_update(s,v);
}

Alan Mishchenko committed
256 257 258
static inline void act_var_bump_factor(sat_solver* s, int v) {
    s->activity[v] += (s->var_inc * s->factors[v]);
    if (s->activity[v] > 1e100)
Alan Mishchenko committed
259 260 261 262 263 264
        act_var_rescale(s);
    //printf("bump %d %f\n", v-1, activity[v]);
    if (s->orderpos[v] != -1)
        order_update(s,v);
}

Alan Mishchenko committed
265 266 267 268 269 270 271 272 273
static inline void act_var_bump_global(sat_solver* s, int v) {
    s->activity[v] += (s->var_inc * 3.0 * s->pGlobalVars[v]);
    if (s->activity[v] > 1e100)
        act_var_rescale(s);
    //printf("bump %d %f\n", v-1, activity[v]);
    if (s->orderpos[v] != -1)
        order_update(s,v);
}

Alan Mishchenko committed
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 299 300 301 302 303 304 305 306 307 308
static inline void act_var_decay(sat_solver* s) { s->var_inc *= s->var_decay; }

static inline void act_clause_rescale(sat_solver* s) {
    clause** cs = (clause**)vecp_begin(&s->learnts);
    int i;
    for (i = 0; i < vecp_size(&s->learnts); i++){
        float a = clause_activity(cs[i]);
        clause_setactivity(cs[i], a * (float)1e-20);
    }
    s->cla_inc *= (float)1e-20;
}


static inline void act_clause_bump(sat_solver* s, clause *c) {
    float a = clause_activity(c) + s->cla_inc;
    clause_setactivity(c,a);
    if (a > 1e20) act_clause_rescale(s);
}

static inline void act_clause_decay(sat_solver* s) { s->cla_inc *= s->cla_decay; }

//=================================================================================================
// Clause functions:

/* pre: size > 1 && no variable occurs twice
 */
static clause* clause_new(sat_solver* s, lit* begin, lit* end, int learnt)
{
    int size;
    clause* c;
    int i;

    assert(end - begin > 1);
    assert(learnt >= 0 && learnt < 2);
    size           = end - begin;
Alan Mishchenko committed
309
//    c              = (clause*)ABC_ALLOC( char, sizeof(clause) + sizeof(lit) * size + learnt * sizeof(float));
Alan Mishchenko committed
310
#ifdef SAT_USE_SYSTEM_MEMORY_MANAGEMENT
Alan Mishchenko committed
311
    c = (clause*)ABC_ALLOC( char, sizeof(clause) + sizeof(lit) * size + learnt * sizeof(float));
Alan Mishchenko committed
312 313 314 315
#else
    c = (clause*)Sat_MmStepEntryFetch( s->pMem, sizeof(clause) + sizeof(lit) * size + learnt * sizeof(float) );
#endif

Alan Mishchenko committed
316
    c->size_learnt = (size << 1) | learnt;
Alan Mishchenko committed
317
    assert(((ABC_PTRUINT_T)c & 1) == 0);
Alan Mishchenko committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

    for (i = 0; i < size; i++)
        c->lits[i] = begin[i];

    if (learnt)
        *((float*)&c->lits[size]) = 0.0;

    assert(begin[0] >= 0);
    assert(begin[0] < s->size*2);
    assert(begin[1] >= 0);
    assert(begin[1] < s->size*2);

    assert(lit_neg(begin[0]) < s->size*2);
    assert(lit_neg(begin[1]) < s->size*2);

    //vecp_push(sat_solver_read_wlist(s,lit_neg(begin[0])),(void*)c);
    //vecp_push(sat_solver_read_wlist(s,lit_neg(begin[1])),(void*)c);

Alan Mishchenko committed
336 337
    vecp_push(sat_solver_read_wlist(s,lit_neg(begin[0])),(void*)(size > 2 ? c : clause_from_lit(begin[1])));
    vecp_push(sat_solver_read_wlist(s,lit_neg(begin[1])),(void*)(size > 2 ? c : clause_from_lit(begin[0])));
Alan Mishchenko committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    return c;
}


static void clause_remove(sat_solver* s, clause* c)
{
    lit* lits = clause_begin(c);
    assert(lit_neg(lits[0]) < s->size*2);
    assert(lit_neg(lits[1]) < s->size*2);

    //vecp_remove(sat_solver_read_wlist(s,lit_neg(lits[0])),(void*)c);
    //vecp_remove(sat_solver_read_wlist(s,lit_neg(lits[1])),(void*)c);

    assert(lits[0] < s->size*2);
Alan Mishchenko committed
353 354
    vecp_remove(sat_solver_read_wlist(s,lit_neg(lits[0])),(void*)(clause_size(c) > 2 ? c : clause_from_lit(lits[1])));
    vecp_remove(sat_solver_read_wlist(s,lit_neg(lits[1])),(void*)(clause_size(c) > 2 ? c : clause_from_lit(lits[0])));
Alan Mishchenko committed
355 356 357 358 359 360 361 362 363

    if (clause_learnt(c)){
        s->stats.learnts--;
        s->stats.learnts_literals -= clause_size(c);
    }else{
        s->stats.clauses--;
        s->stats.clauses_literals -= clause_size(c);
    }

Alan Mishchenko committed
364
#ifdef SAT_USE_SYSTEM_MEMORY_MANAGEMENT
Alan Mishchenko committed
365
    ABC_FREE(c);
Alan Mishchenko committed
366 367 368
#else
    Sat_MmStepEntryRecycle( s->pMem, (char *)c, sizeof(clause) + sizeof(lit) * clause_size(c) + clause_learnt(c) * sizeof(float) );
#endif
Alan Mishchenko committed
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
}


static lbool clause_simplify(sat_solver* s, clause* c)
{
    lit*   lits   = clause_begin(c);
    lbool* values = s->assigns;
    int i;

    assert(sat_solver_dlevel(s) == 0);

    for (i = 0; i < clause_size(c); i++){
        lbool sig = !lit_sign(lits[i]); sig += sig - 1;
        if (values[lit_var(lits[i])] == sig)
            return l_True;
    }
    return l_False;
}

//=================================================================================================
// Minor (solver) functions:

void sat_solver_setnvars(sat_solver* s,int n)
{
    int var;

    if (s->cap < n){

        while (s->cap < n) s->cap = s->cap*2+1;

Alan Mishchenko committed
399 400 401 402 403 404 405 406 407
        s->wlists    = ABC_REALLOC(vecp,   s->wlists,   s->cap*2);
        s->activity  = ABC_REALLOC(double, s->activity, s->cap);
        s->factors   = ABC_REALLOC(double, s->factors,  s->cap);
        s->assigns   = ABC_REALLOC(lbool,  s->assigns,  s->cap);
        s->orderpos  = ABC_REALLOC(int,    s->orderpos, s->cap);
        s->reasons   = ABC_REALLOC(clause*,s->reasons,  s->cap);
        s->levels    = ABC_REALLOC(int,    s->levels,   s->cap);
        s->tags      = ABC_REALLOC(lbool,  s->tags,     s->cap);
        s->trail     = ABC_REALLOC(lit,    s->trail,    s->cap);
408
        s->polarity  = ABC_REALLOC(char,   s->polarity, s->cap);
Alan Mishchenko committed
409 410 411 412 413 414
    }

    for (var = s->size; var < n; var++){
        vecp_new(&s->wlists[2*var]);
        vecp_new(&s->wlists[2*var+1]);
        s->activity [var] = 0;
Alan Mishchenko committed
415
        s->factors  [var] = 0;
Alan Mishchenko committed
416 417 418 419 420
        s->assigns  [var] = l_Undef;
        s->orderpos [var] = veci_size(&s->order);
        s->reasons  [var] = (clause*)0;
        s->levels   [var] = 0;
        s->tags     [var] = l_Undef;
421
        s->polarity [var] = 0;
Alan Mishchenko committed
422 423 424 425 426 427 428 429 430 431 432 433
        
        /* does not hold because variables enqueued at top level will not be reinserted in the heap
           assert(veci_size(&s->order) == var); 
         */
        veci_push(&s->order,var);
        order_update(s, var);
    }

    s->size = n > s->size ? n : s->size;
}


434
static inline int enqueue(sat_solver* s, lit l, clause* from)
Alan Mishchenko committed
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
{
    lbool* values = s->assigns;
    int    v      = lit_var(l);
    lbool  val    = values[v];
#ifdef VERBOSEDEBUG
    printf(L_IND"enqueue("L_LIT")\n", L_ind, L_lit(l));
#endif

    lbool sig = !lit_sign(l); sig += sig - 1;
    if (val != l_Undef){
        return val == sig;
    }else{
        // New fact -- store it.
#ifdef VERBOSEDEBUG
        printf(L_IND"bind("L_LIT")\n", L_ind, L_lit(l));
#endif
        int*     levels  = s->levels;
        clause** reasons = s->reasons;

        values [v] = sig;
        levels [v] = sat_solver_dlevel(s);
        reasons[v] = from;
        s->trail[s->qtail++] = l;

        order_assigned(s, v);
        return true;
    }
}


465
static inline int assume(sat_solver* s, lit l){
Alan Mishchenko committed
466 467 468 469 470 471
    assert(s->qtail == s->qhead);
    assert(s->assigns[lit_var(l)] == l_Undef);
#ifdef VERBOSEDEBUG
    printf(L_IND"assume("L_LIT")\n", L_ind, L_lit(l));
#endif
    veci_push(&s->trail_lim,s->qtail);
472
    return enqueue(s,l,(clause*)0);
Alan Mishchenko committed
473 474 475
}


Alan Mishchenko committed
476
static void sat_solver_canceluntil(sat_solver* s, int level) {
Alan Mishchenko committed
477 478 479 480
    lit*     trail;   
    lbool*   values;  
    clause** reasons; 
    int      bound;
481
    int      lastLev;
Alan Mishchenko committed
482 483 484 485 486 487 488 489 490
    int      c;
    
    if (sat_solver_dlevel(s) <= level)
        return;

    trail   = s->trail;
    values  = s->assigns;
    reasons = s->reasons;
    bound   = (veci_begin(&s->trail_lim))[level];
491
    lastLev = (veci_begin(&s->trail_lim))[veci_size(&s->trail_lim)-1];
Alan Mishchenko committed
492

Alan Mishchenko committed
493 494 495 496 497 498
    ////////////////////////////////////////
    // added to cancel all assignments
//    if ( level == -1 )
//        bound = 0;
    ////////////////////////////////////////

Alan Mishchenko committed
499 500 501 502
    for (c = s->qtail-1; c >= bound; c--) {
        int     x  = lit_var(trail[c]);
        values [x] = l_Undef;
        reasons[x] = (clause*)0;
503 504
        if ( c < lastLev )
            s->polarity[x] = !lit_sign(trail[c]);
Alan Mishchenko committed
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    }

    for (c = s->qhead-1; c >= bound; c--)
        order_unassigned(s,lit_var(trail[c]));

    s->qhead = s->qtail = bound;
    veci_resize(&s->trail_lim,level);
}

static void sat_solver_record(sat_solver* s, veci* cls)
{
    lit*    begin = veci_begin(cls);
    lit*    end   = begin + veci_size(cls);
    clause* c     = (veci_size(cls) > 1) ? clause_new(s,begin,end,1) : (clause*)0;
    enqueue(s,*begin,c);

Alan Mishchenko committed
521 522 523 524
    ///////////////////////////////////
    // add clause to internal storage
    if ( s->pStore )
    {
525
        int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, begin, end );
Alan Mishchenko committed
526 527 528 529
        assert( RetValue );
    }
    ///////////////////////////////////

Alan Mishchenko committed
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
    assert(veci_size(cls) > 0);

    if (c != 0) {
        vecp_push(&s->learnts,c);
        act_clause_bump(s,c);
        s->stats.learnts++;
        s->stats.learnts_literals += veci_size(cls);
    }
}


static double sat_solver_progress(sat_solver* s)
{
    lbool*  values = s->assigns;
    int*    levels = s->levels;
    int     i;

    double  progress = 0;
    double  F        = 1.0 / s->size;
    for (i = 0; i < s->size; i++)
        if (values[i] != l_Undef)
            progress += pow(F, levels[i]);
    return progress / s->size;
}

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

558
static int sat_solver_lit_removable(sat_solver* s, lit l, int minl)
Alan Mishchenko committed
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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
{
    lbool*   tags    = s->tags;
    clause** reasons = s->reasons;
    int*     levels  = s->levels;
    int      top     = veci_size(&s->tagged);

    assert(lit_var(l) >= 0 && lit_var(l) < s->size);
    assert(reasons[lit_var(l)] != 0);
    veci_resize(&s->stack,0);
    veci_push(&s->stack,lit_var(l));

    while (veci_size(&s->stack) > 0){
        clause* c;
        int v = veci_begin(&s->stack)[veci_size(&s->stack)-1];
        assert(v >= 0 && v < s->size);
        veci_resize(&s->stack,veci_size(&s->stack)-1);
        assert(reasons[v] != 0);
        c    = reasons[v];

        if (clause_is_lit(c)){
            int v = lit_var(clause_read_lit(c));
            if (tags[v] == l_Undef && levels[v] != 0){
                if (reasons[v] != 0 && ((1 << (levels[v] & 31)) & minl)){
                    veci_push(&s->stack,v);
                    tags[v] = l_True;
                    veci_push(&s->tagged,v);
                }else{
                    int* tagged = veci_begin(&s->tagged);
                    int j;
                    for (j = top; j < veci_size(&s->tagged); j++)
                        tags[tagged[j]] = l_Undef;
                    veci_resize(&s->tagged,top);
                    return false;
                }
            }
        }else{
            lit*    lits = clause_begin(c);
            int     i, j;

            for (i = 1; i < clause_size(c); i++){
                int v = lit_var(lits[i]);
                if (tags[v] == l_Undef && levels[v] != 0){
                    if (reasons[v] != 0 && ((1 << (levels[v] & 31)) & minl)){

                        veci_push(&s->stack,lit_var(lits[i]));
                        tags[v] = l_True;
                        veci_push(&s->tagged,v);
                    }else{
                        int* tagged = veci_begin(&s->tagged);
                        for (j = top; j < veci_size(&s->tagged); j++)
                            tags[tagged[j]] = l_Undef;
                        veci_resize(&s->tagged,top);
                        return false;
                    }
                }
            }
        }
    }

    return true;
}

621 622 623 624 625 626 627 628 629 630 631

/*_________________________________________________________________________________________________
|
|  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'.
|________________________________________________________________________________________________@*/
/*
632
void Solver::analyzeFinal(Clause* confl, bool skip_first)
633
{
634 635 636 637 638 639 640 641 642 643
    // -- NOTE! This code is relatively untested. Please report bugs!
    conflict.clear();
    if (root_level == 0) return;

    vec<char>& seen  = analyze_seen;
    for (int i = skip_first ? 1 : 0; i < confl->size(); i++){
        Var x = var((*confl)[i]);
        if (level[x] > 0)
            seen[x] = 1;
    }
644

645 646 647
    int start = (root_level >= trail_lim.size()) ? trail.size()-1 : trail_lim[root_level];
    for (int i = start; i >= trail_lim[0]; i--){
        Var     x = var(trail[i]);
648
        if (seen[x]){
649 650 651 652
            GClause r = reason[x];
            if (r == GClause_NULL){
                assert(level[x] > 0);
                conflict.push(~trail[i]);
653
            }else{
654 655 656 657 658 659 660 661 662 663
                if (r.isLit()){
                    Lit p = r.lit();
                    if (level[var(p)] > 0)
                        seen[var(p)] = 1;
                }else{
                    Clause& c = *r.clause();
                    for (int j = 1; j < c.size(); j++)
                        if (level[var(c[j])] > 0)
                            seen[var(c[j])] = 1;
                }
664 665 666 667 668 669 670
            }
            seen[x] = 0;
        }
    }
}
*/

671 672 673
#ifdef SAT_USE_ANALYZE_FINAL

static void sat_solver_analyze_final(sat_solver* s, clause* conf, int skip_first)
674
{
675 676 677
    int i, j, start;
    veci_resize(&s->conf_final,0);
    if ( s->root_level == 0 )
678 679
        return;
    assert( veci_size(&s->tagged) == 0 );
680 681 682 683 684 685 686 687 688 689 690 691 692 693
//    assert( s->tags[lit_var(p)] == l_Undef );
//    s->tags[lit_var(p)] = l_True;
    for (i = skip_first ? 1 : 0; i < clause_size(conf); i++)
    {
        int x = lit_var(clause_begin(conf)[i]);
        if (s->levels[x] > 0)
        {
            s->tags[x] = l_True;
            veci_push(&s->tagged,x);
        }
    }

    start = (s->root_level >= veci_size(&s->trail_lim))? s->qtail-1 : (veci_begin(&s->trail_lim))[s->root_level];
    for (i = start; i >= (veci_begin(&s->trail_lim))[0]; i--){
694 695 696 697
        int x = lit_var(s->trail[i]);
        if (s->tags[x] == l_True){
            if (s->reasons[x] == NULL){
                assert(s->levels[x] > 0);
698
                veci_push(&s->conf_final,lit_neg(s->trail[i]));
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
            }else{
                clause* c = s->reasons[x];
                if (clause_is_lit(c)){
                    lit q = clause_read_lit(c);
                    assert(lit_var(q) >= 0 && lit_var(q) < s->size);
                    if (s->levels[lit_var(q)] > 0)
                    {
                        s->tags[lit_var(q)] = l_True;
                        veci_push(&s->tagged,lit_var(q));
                    }
                }
                else{
                    int* lits = clause_begin(c);
                    for (j = 1; j < clause_size(c); j++)
                        if (s->levels[lit_var(lits[j])] > 0)
                        {
                            s->tags[lit_var(lits[j])] = l_True;
                            veci_push(&s->tagged,lit_var(lits[j]));
                        }
                }
            }
        }
    }
    for (i = 0; i < veci_size(&s->tagged); i++)
        s->tags[veci_begin(&s->tagged)[i]] = l_Undef;
    veci_resize(&s->tagged,0);
}

727 728
#endif

729

Alan Mishchenko committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 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 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
static void sat_solver_analyze(sat_solver* s, clause* c, veci* learnt)
{
    lit*     trail   = s->trail;
    lbool*   tags    = s->tags;
    clause** reasons = s->reasons;
    int*     levels  = s->levels;
    int      cnt     = 0;
    lit      p       = lit_Undef;
    int      ind     = s->qtail-1;
    lit*     lits;
    int      i, j, minl;
    int*     tagged;

    veci_push(learnt,lit_Undef);

    do{
        assert(c != 0);

        if (clause_is_lit(c)){
            lit q = clause_read_lit(c);
            assert(lit_var(q) >= 0 && lit_var(q) < s->size);
            if (tags[lit_var(q)] == l_Undef && levels[lit_var(q)] > 0){
                tags[lit_var(q)] = l_True;
                veci_push(&s->tagged,lit_var(q));
                act_var_bump(s,lit_var(q));
                if (levels[lit_var(q)] == sat_solver_dlevel(s))
                    cnt++;
                else
                    veci_push(learnt,q);
            }
        }else{

            if (clause_learnt(c))
                act_clause_bump(s,c);

            lits = clause_begin(c);
            //printlits(lits,lits+clause_size(c)); printf("\n");
            for (j = (p == lit_Undef ? 0 : 1); j < clause_size(c); j++){
                lit q = lits[j];
                assert(lit_var(q) >= 0 && lit_var(q) < s->size);
                if (tags[lit_var(q)] == l_Undef && levels[lit_var(q)] > 0){
                    tags[lit_var(q)] = l_True;
                    veci_push(&s->tagged,lit_var(q));
                    act_var_bump(s,lit_var(q));
                    if (levels[lit_var(q)] == sat_solver_dlevel(s))
                        cnt++;
                    else
                        veci_push(learnt,q);
                }
            }
        }

        while (tags[lit_var(trail[ind--])] == l_Undef);

        p = trail[ind+1];
        c = reasons[lit_var(p)];
        cnt--;

    }while (cnt > 0);

    *veci_begin(learnt) = lit_neg(p);

    lits = veci_begin(learnt);
    minl = 0;
    for (i = 1; i < veci_size(learnt); i++){
        int lev = levels[lit_var(lits[i])];
        minl    |= 1 << (lev & 31);
    }

    // simplify (full)
    for (i = j = 1; i < veci_size(learnt); i++){
        if (reasons[lit_var(lits[i])] == 0 || !sat_solver_lit_removable(s,lits[i],minl))
            lits[j++] = lits[i];
    }

    // update size of learnt + statistics
    s->stats.max_literals += veci_size(learnt);
    veci_resize(learnt,j);
    s->stats.tot_literals += j;

    // clear tags
    tagged = veci_begin(&s->tagged);
    for (i = 0; i < veci_size(&s->tagged); i++)
        tags[tagged[i]] = l_Undef;
    veci_resize(&s->tagged,0);

#ifdef DEBUG
    for (i = 0; i < s->size; i++)
        assert(tags[i] == l_Undef);
#endif

#ifdef VERBOSEDEBUG
    printf(L_IND"Learnt {", L_ind);
    for (i = 0; i < veci_size(learnt); i++) printf(" "L_LIT, L_lit(lits[i]));
#endif
    if (veci_size(learnt) > 1){
        int max_i = 1;
        int max   = levels[lit_var(lits[1])];
        lit tmp;

        for (i = 2; i < veci_size(learnt); i++)
            if (levels[lit_var(lits[i])] > max){
                max   = levels[lit_var(lits[i])];
                max_i = i;
            }

        tmp         = lits[1];
        lits[1]     = lits[max_i];
        lits[max_i] = tmp;
    }
#ifdef VERBOSEDEBUG
    {
        int lev = veci_size(learnt) > 1 ? levels[lit_var(lits[1])] : 0;
        printf(" } at level %d\n", lev);
    }
#endif
}


clause* sat_solver_propagate(sat_solver* s)
{
    lbool*  values = s->assigns;
    clause* confl  = (clause*)0;
    lit*    lits;

    //printf("sat_solver_propagate\n");
    while (confl == 0 && s->qtail - s->qhead > 0){
        lit  p  = s->trail[s->qhead++];
        vecp* ws = sat_solver_read_wlist(s,p);
        clause **begin = (clause**)vecp_begin(ws);
        clause **end   = begin + vecp_size(ws);
        clause **i, **j;

        s->stats.propagations++;
        s->simpdb_props--;
Alan Mishchenko committed
865

Alan Mishchenko committed
866
        //printf("checking lit %d: "L_LIT"\n", veci_size(ws), L_lit(p));
Alan Mishchenko committed
867 868
        for (i = j = begin; i < end; ){
            if (clause_is_lit(*i)){
Alan Mishchenko committed
869
//                s->stats.inspects2++;
Alan Mishchenko committed
870
                *j++ = *i;
Alan Mishchenko committed
871
                if (!enqueue(s,clause_read_lit(*i),clause_from_lit(p))){
Alan Mishchenko committed
872 873 874 875
                    confl = s->binary;
                    (clause_begin(confl))[1] = lit_neg(p);
                    (clause_begin(confl))[0] = clause_read_lit(*i++);
                    // Copy the remaining watches:
Alan Mishchenko committed
876
//                    s->stats.inspects2 += end - i;
Alan Mishchenko committed
877 878 879
                    while (i < end)
                        *j++ = *i++;
                }
Alan Mishchenko committed
880 881
            }else{
                lit false_lit;
Alan Mishchenko committed
882 883 884 885
                lbool sig;

                lits = clause_begin(*i);

Alan Mishchenko committed
886
                // Make sure the false literal is data[1]:
Alan Mishchenko committed
887 888 889 890 891 892 893 894
                false_lit = lit_neg(p);
                if (lits[0] == false_lit){
                    lits[0] = lits[1];
                    lits[1] = false_lit;
                }
                assert(lits[1] == false_lit);
                //printf("checking clause: "); printlits(lits, lits+clause_size(*i)); printf("\n");

Alan Mishchenko committed
895 896 897 898 899
                // If 0th watch is true, then clause is already satisfied.
                sig = !lit_sign(lits[0]); sig += sig - 1;
                if (values[lit_var(lits[0])] == sig){
                    *j++ = *i;
                }else{
Alan Mishchenko committed
900 901 902
                    // Look for new watch:
                    lit* stop = lits + clause_size(*i);
                    lit* k;
Alan Mishchenko committed
903
                    for (k = lits + 2; k < stop; k++){
Alan Mishchenko committed
904
                        lbool sig = lit_sign(*k); sig += sig - 1;
Alan Mishchenko committed
905
                        if (values[lit_var(*k)] != sig){
Alan Mishchenko committed
906 907
                            lits[1] = *k;
                            *k = false_lit;
Alan Mishchenko committed
908 909
                            vecp_push(sat_solver_read_wlist(s,lit_neg(lits[1])),*i);
                            goto next; }
Alan Mishchenko committed
910 911 912 913
                    }

                    *j++ = *i;
                    // Clause is unit under assignment:
Alan Mishchenko committed
914
                    if (!enqueue(s,lits[0], *i)){
Alan Mishchenko committed
915 916
                        confl = *i++;
                        // Copy the remaining watches:
Alan Mishchenko committed
917
//                        s->stats.inspects2 += end - i;
Alan Mishchenko committed
918 919 920 921 922
                        while (i < end)
                            *j++ = *i++;
                    }
                }
            }
Alan Mishchenko committed
923 924
        next:
            i++;
Alan Mishchenko committed
925 926 927 928 929 930 931 932 933
        }

        s->stats.inspects += j - (clause**)vecp_begin(ws);
        vecp_resize(ws,j - (clause**)vecp_begin(ws));
    }

    return confl;
}

Alan Mishchenko committed
934
static int clause_cmp (const void* x, const void* y) {
Alan Mishchenko committed
935 936 937 938 939 940 941 942
    return clause_size((clause*)x) > 2 && (clause_size((clause*)y) == 2 || clause_activity((clause*)x) < clause_activity((clause*)y)) ? -1 : 1; }

void sat_solver_reducedb(sat_solver* s)
{
    int      i, j;
    double   extra_lim = s->cla_inc / vecp_size(&s->learnts); // Remove any clause below this activity
    clause** learnts = (clause**)vecp_begin(&s->learnts);
    clause** reasons = s->reasons;
Alan Mishchenko committed
943

Alan Mishchenko committed
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
    sat_solver_sort(vecp_begin(&s->learnts), vecp_size(&s->learnts), &clause_cmp);

    for (i = j = 0; i < vecp_size(&s->learnts) / 2; i++){
        if (clause_size(learnts[i]) > 2 && reasons[lit_var(*clause_begin(learnts[i]))] != learnts[i])
            clause_remove(s,learnts[i]);
        else
            learnts[j++] = learnts[i];
    }
    for (; i < vecp_size(&s->learnts); i++){
        if (clause_size(learnts[i]) > 2 && reasons[lit_var(*clause_begin(learnts[i]))] != learnts[i] && clause_activity(learnts[i]) < extra_lim)
            clause_remove(s,learnts[i]);
        else
            learnts[j++] = learnts[i];
    }

    //printf("reducedb deleted %d\n", vecp_size(&s->learnts) - j);


    vecp_resize(&s->learnts,j);
}

Alan Mishchenko committed
965
static lbool sat_solver_search(sat_solver* s, ABC_INT64_T nof_conflicts, ABC_INT64_T nof_learnts)
Alan Mishchenko committed
966 967 968 969 970 971
{
    int*    levels          = s->levels;
    double  var_decay       = 0.95;
    double  clause_decay    = 0.999;
    double  random_var_freq = 0.02;

Alan Mishchenko committed
972
    ABC_INT64_T  conflictC       = 0;
Alan Mishchenko committed
973
    veci    learnt_clause;
Alan Mishchenko committed
974
    int     i;
Alan Mishchenko committed
975 976 977

    assert(s->root_level == sat_solver_dlevel(s));

Alan Mishchenko committed
978
    s->nRestarts++;
Alan Mishchenko committed
979 980 981 982 983 984
    s->stats.starts++;
    s->var_decay = (float)(1 / var_decay   );
    s->cla_decay = (float)(1 / clause_decay);
    veci_resize(&s->model,0);
    veci_new(&learnt_clause);

Alan Mishchenko committed
985 986
    // use activity factors in every even restart
    if ( (s->nRestarts & 1) && veci_size(&s->act_vars) > 0 )
Alan Mishchenko committed
987
//    if ( veci_size(&s->act_vars) > 0 )
Alan Mishchenko committed
988 989 990
        for ( i = 0; i < s->act_vars.size; i++ )
            act_var_bump_factor(s, s->act_vars.ptr[i]);

Alan Mishchenko committed
991 992 993 994 995
    // use activity factors in every restart
    if ( s->pGlobalVars && veci_size(&s->act_vars) > 0 )
        for ( i = 0; i < s->act_vars.size; i++ )
            act_var_bump_global(s, s->act_vars.ptr[i]);

Alan Mishchenko committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    for (;;){
        clause* confl = sat_solver_propagate(s);
        if (confl != 0){
            // CONFLICT
            int blevel;

#ifdef VERBOSEDEBUG
            printf(L_IND"**CONFLICT**\n", L_ind);
#endif
            s->stats.conflicts++; conflictC++;
            if (sat_solver_dlevel(s) == s->root_level){
1007 1008 1009
#ifdef SAT_USE_ANALYZE_FINAL
                sat_solver_analyze_final(s, confl, 0);
#endif
Alan Mishchenko committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
                veci_delete(&learnt_clause);
                return l_False;
            }

            veci_resize(&learnt_clause,0);
            sat_solver_analyze(s, confl, &learnt_clause);
            blevel = veci_size(&learnt_clause) > 1 ? levels[lit_var(veci_begin(&learnt_clause)[1])] : s->root_level;
            blevel = s->root_level > blevel ? s->root_level : blevel;
            sat_solver_canceluntil(s,blevel);
            sat_solver_record(s,&learnt_clause);
1020 1021 1022 1023
#ifdef SAT_USE_ANALYZE_FINAL
//            if (learnt_clause.size() == 1) level[var(learnt_clause[0])] = 0;    // (this is ugly (but needed for 'analyzeFinal()') -- in future versions, we will backtrack past the 'root_level' and redo the assumptions)
            if ( learnt_clause.size == 1 ) s->levels[lit_var(learnt_clause.ptr[0])] = 0;
#endif
Alan Mishchenko committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
            act_var_decay(s);
            act_clause_decay(s);

        }else{
            // NO CONFLICT
            int next;

            if (nof_conflicts >= 0 && conflictC >= nof_conflicts){
                // Reached bound on number of conflicts:
                s->progress_estimate = sat_solver_progress(s);
                sat_solver_canceluntil(s,s->root_level);
                veci_delete(&learnt_clause);
                return l_Undef; }

Alan Mishchenko committed
1038
            if ( (s->nConfLimit && s->stats.conflicts > s->nConfLimit) ||
1039 1040
//                 (s->nInsLimit  && s->stats.inspects  > s->nInsLimit) )
                 (s->nInsLimit  && s->stats.propagations > s->nInsLimit) )
Alan Mishchenko committed
1041 1042 1043 1044 1045 1046 1047 1048
            {
                // Reached bound on number of conflicts:
                s->progress_estimate = sat_solver_progress(s);
                sat_solver_canceluntil(s,s->root_level);
                veci_delete(&learnt_clause);
                return l_Undef; 
            }

Alan Mishchenko committed
1049
            if (sat_solver_dlevel(s) == 0 && !s->fSkipSimplify)
Alan Mishchenko committed
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
                // Simplify the set of problem clauses:
                sat_solver_simplify(s);

            if (nof_learnts >= 0 && vecp_size(&s->learnts) - s->qtail >= nof_learnts)
                // Reduce the set of learnt clauses:
                sat_solver_reducedb(s);

            // New variable decision:
            s->stats.decisions++;
            next = order_select(s,(float)random_var_freq);

            if (next == var_Undef){
                // Model found:
                lbool* values = s->assigns;
                int i;
                veci_resize(&s->model, 0);
                for (i = 0; i < s->size; i++) 
                    veci_push(&s->model,(int)values[i]);
                sat_solver_canceluntil(s,s->root_level);
                veci_delete(&learnt_clause);

                /*
                veci apa; veci_new(&apa);
                for (i = 0; i < s->size; i++) 
                    veci_push(&apa,(int)(s->model.ptr[i] == l_True ? toLit(i) : lit_neg(toLit(i))));
                printf("model: "); printlits((lit*)apa.ptr, (lit*)apa.ptr + veci_size(&apa)); printf("\n");
                veci_delete(&apa);
                */

                return l_True;
            }

1082 1083 1084 1085
            if ( s->polarity[next] ) // positive polarity
                assume(s,toLit(next));
            else
                assume(s,lit_neg(toLit(next)));
Alan Mishchenko committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        }
    }

    return l_Undef; // cannot happen
}

//=================================================================================================
// External solver functions:

sat_solver* sat_solver_new(void)
{
Alan Mishchenko committed
1097
    sat_solver* s = (sat_solver*)ABC_ALLOC( char, sizeof(sat_solver));
Alan Mishchenko committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    memset( s, 0, sizeof(sat_solver) );

    // initialize vectors
    vecp_new(&s->clauses);
    vecp_new(&s->learnts);
    veci_new(&s->order);
    veci_new(&s->trail_lim);
    veci_new(&s->tagged);
    veci_new(&s->stack);
    veci_new(&s->model);
Alan Mishchenko committed
1108
    veci_new(&s->act_vars);
Alan Mishchenko committed
1109
    veci_new(&s->temp_clause);
1110
    veci_new(&s->conf_final);
Alan Mishchenko committed
1111 1112 1113 1114

    // initialize arrays
    s->wlists    = 0;
    s->activity  = 0;
Alan Mishchenko committed
1115
    s->factors   = 0;
Alan Mishchenko committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    s->assigns   = 0;
    s->orderpos  = 0;
    s->reasons   = 0;
    s->levels    = 0;
    s->tags      = 0;
    s->trail     = 0;


    // initialize other vars
    s->size                   = 0;
    s->cap                    = 0;
    s->qhead                  = 0;
    s->qtail                  = 0;
    s->cla_inc                = 1;
    s->cla_decay              = 1;
    s->var_inc                = 1;
    s->var_decay              = 1;
    s->root_level             = 0;
    s->simpdb_assigns         = 0;
    s->simpdb_props           = 0;
    s->random_seed            = 91648253;
    s->progress_estimate      = 0;
Alan Mishchenko committed
1138
    s->binary                 = (clause*)ABC_ALLOC( char, sizeof(clause) + sizeof(lit)*2);
Alan Mishchenko committed
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    s->binary->size_learnt    = (2 << 1);
    s->verbosity              = 0;

    s->stats.starts           = 0;
    s->stats.decisions        = 0;
    s->stats.propagations     = 0;
    s->stats.inspects         = 0;
    s->stats.conflicts        = 0;
    s->stats.clauses          = 0;
    s->stats.clauses_literals = 0;
    s->stats.learnts          = 0;
    s->stats.learnts_literals = 0;
    s->stats.max_literals     = 0;
    s->stats.tot_literals     = 0;

Alan Mishchenko committed
1154
#ifdef SAT_USE_SYSTEM_MEMORY_MANAGEMENT
Alan Mishchenko committed
1155 1156 1157 1158
    s->pMem = NULL;
#else
    s->pMem = Sat_MmStepStart( 10 );
#endif
Alan Mishchenko committed
1159 1160 1161 1162 1163 1164
    return s;
}


void sat_solver_delete(sat_solver* s)
{
Alan Mishchenko committed
1165

Alan Mishchenko committed
1166
#ifdef SAT_USE_SYSTEM_MEMORY_MANAGEMENT
Alan Mishchenko committed
1167 1168
    int i;
    for (i = 0; i < vecp_size(&s->clauses); i++)
Alan Mishchenko committed
1169
        ABC_FREE(vecp_begin(&s->clauses)[i]);
Alan Mishchenko committed
1170
    for (i = 0; i < vecp_size(&s->learnts); i++)
Alan Mishchenko committed
1171
        ABC_FREE(vecp_begin(&s->learnts)[i]);
Alan Mishchenko committed
1172 1173 1174
#else
    Sat_MmStepStop( s->pMem, 0 );
#endif
Alan Mishchenko committed
1175 1176 1177 1178 1179 1180 1181 1182 1183

    // delete vectors
    vecp_delete(&s->clauses);
    vecp_delete(&s->learnts);
    veci_delete(&s->order);
    veci_delete(&s->trail_lim);
    veci_delete(&s->tagged);
    veci_delete(&s->stack);
    veci_delete(&s->model);
Alan Mishchenko committed
1184
    veci_delete(&s->act_vars);
Alan Mishchenko committed
1185
    veci_delete(&s->temp_clause);
1186
    veci_delete(&s->conf_final);
Alan Mishchenko committed
1187
    ABC_FREE(s->binary);
Alan Mishchenko committed
1188 1189 1190 1191 1192 1193 1194 1195

    // delete arrays
    if (s->wlists != 0){
        int i;
        for (i = 0; i < s->size*2; i++)
            vecp_delete(&s->wlists[i]);

        // if one is different from null, all are
Alan Mishchenko committed
1196 1197 1198 1199 1200 1201 1202 1203 1204
        ABC_FREE(s->wlists   );
        ABC_FREE(s->activity );
        ABC_FREE(s->factors  );
        ABC_FREE(s->assigns  );
        ABC_FREE(s->orderpos );
        ABC_FREE(s->reasons  );
        ABC_FREE(s->levels   );
        ABC_FREE(s->trail    );
        ABC_FREE(s->tags     );
1205
        ABC_FREE(s->polarity );
Alan Mishchenko committed
1206 1207
    }

Alan Mishchenko committed
1208
    sat_solver_store_free(s);
Alan Mishchenko committed
1209
    ABC_FREE(s);
Alan Mishchenko committed
1210 1211 1212
}


1213
int sat_solver_addclause(sat_solver* s, lit* begin, lit* end)
Alan Mishchenko committed
1214 1215 1216 1217 1218 1219
{
    lit *i,*j;
    int maxvar;
    lbool* values;
    lit last;

Alan Mishchenko committed
1220 1221 1222 1223 1224 1225
    veci_resize( &s->temp_clause, 0 );
    for ( i = begin; i < end; i++ )
        veci_push( &s->temp_clause, *i );
    begin = veci_begin( &s->temp_clause );
    end = begin + veci_size( &s->temp_clause );

Alan Mishchenko committed
1226 1227
    if (begin == end) 
        return false;
Alan Mishchenko committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

    //printlits(begin,end); printf("\n");
    // insertion sort
    maxvar = lit_var(*begin);
    for (i = begin + 1; i < end; i++){
        lit l = *i;
        maxvar = lit_var(l) > maxvar ? lit_var(l) : maxvar;
        for (j = i; j > begin && *(j-1) > l; j--)
            *j = *(j-1);
        *j = l;
    }
    sat_solver_setnvars(s,maxvar+1);
Alan Mishchenko committed
1240
//    sat_solver_setnvars(s, lit_var(*(end-1))+1 );
Alan Mishchenko committed
1241

Alan Mishchenko committed
1242 1243 1244 1245
    ///////////////////////////////////
    // add clause to internal storage
    if ( s->pStore )
    {
1246
        int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, begin, end );
Alan Mishchenko committed
1247 1248 1249 1250
        assert( RetValue );
    }
    ///////////////////////////////////

Alan Mishchenko committed
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
    //printlits(begin,end); printf("\n");
    values = s->assigns;

    // delete duplicates
    last = lit_Undef;
    for (i = j = begin; i < end; i++){
        //printf("lit: "L_LIT", value = %d\n", L_lit(*i), (lit_sign(*i) ? -values[lit_var(*i)] : values[lit_var(*i)]));
        lbool sig = !lit_sign(*i); sig += sig - 1;
        if (*i == lit_neg(last) || sig == values[lit_var(*i)])
            return true;   // tautology
        else if (*i != last && values[lit_var(*i)] == l_Undef)
            last = *j++ = *i;
    }

    //printf("final: "); printlits(begin,j); printf("\n");

    if (j == begin)          // empty clause
        return false;
Alan Mishchenko committed
1269 1270

    if (j - begin == 1) // unit clause
Alan Mishchenko committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
        return enqueue(s,*begin,(clause*)0);

    // create new clause
    vecp_push(&s->clauses,clause_new(s,begin,j,0));


    s->stats.clauses++;
    s->stats.clauses_literals += j - begin;

    return true;
}


1284
int sat_solver_simplify(sat_solver* s)
Alan Mishchenko committed
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
{
    clause** reasons;
    int type;

    assert(sat_solver_dlevel(s) == 0);

    if (sat_solver_propagate(s) != 0)
        return false;

    if (s->qhead == s->simpdb_assigns || s->simpdb_props > 0)
        return true;

    reasons = s->reasons;
    for (type = 0; type < 2; type++){
        vecp*    cs  = type ? &s->learnts : &s->clauses;
        clause** cls = (clause**)vecp_begin(cs);

        int i, j;
        for (j = i = 0; i < vecp_size(cs); i++){
            if (reasons[lit_var(*clause_begin(cls[i]))] != cls[i] &&
                clause_simplify(s,cls[i]) == l_True)
                clause_remove(s,cls[i]);
            else
                cls[j++] = cls[i];
        }
        vecp_resize(cs,j);
    }

    s->simpdb_assigns = s->qhead;
    // (shouldn't depend on 'stats' really, but it will do for now)
    s->simpdb_props   = (int)(s->stats.clauses_literals + s->stats.learnts_literals);

    return true;
}

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
double luby(double y, int x)
{
    int size, seq;
    for (size = 1, seq = 0; size < x+1; seq++, size = 2*size + 1);
    while (size-1 != x){
        size = (size-1) >> 1;
        seq--;
        x = x % size;
    }
    return pow(y, (double)seq);
} 

void luby_test()
{
    int i;
    for ( i = 0; i < 20; i++ )
        printf( "%d ", (int)luby(2,i) );
    printf( "\n" );
}
Alan Mishchenko committed
1339

Alan Mishchenko committed
1340
int sat_solver_solve(sat_solver* s, lit* begin, lit* end, ABC_INT64_T nConfLimit, ABC_INT64_T nInsLimit, ABC_INT64_T nConfLimitGlobal, ABC_INT64_T nInsLimitGlobal)
Alan Mishchenko committed
1341
{
1342 1343
    int restart_iter = 0;
    ABC_INT64_T  nof_conflicts;
Alan Mishchenko committed
1344
    ABC_INT64_T  nof_learnts   = sat_solver_nclauses(s) / 3;
Alan Mishchenko committed
1345 1346 1347
    lbool   status        = l_Undef;
    lbool*  values        = s->assigns;
    lit*    i;
Alan Mishchenko committed
1348

Alan Mishchenko committed
1349 1350 1351 1352 1353
    ////////////////////////////////////////////////
    if ( s->fSolved )
    {
        if ( s->pStore )
        {
1354
            int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, NULL, NULL );
Alan Mishchenko committed
1355 1356 1357 1358 1359 1360
            assert( RetValue );
        }
        return l_False;
    }
    ////////////////////////////////////////////////

Alan Mishchenko committed
1361
    // set the external limits
Alan Mishchenko committed
1362
    s->nCalls++;
Alan Mishchenko committed
1363
    s->nRestarts  = 0;
Alan Mishchenko committed
1364 1365 1366 1367 1368
    s->nConfLimit = 0;
    s->nInsLimit  = 0;
    if ( nConfLimit )
        s->nConfLimit = s->stats.conflicts + nConfLimit;
    if ( nInsLimit )
1369 1370
//        s->nInsLimit = s->stats.inspects + nInsLimit;
        s->nInsLimit = s->stats.propagations + nInsLimit;
Alan Mishchenko committed
1371
    if ( nConfLimitGlobal && (s->nConfLimit == 0 || s->nConfLimit > nConfLimitGlobal) )
Alan Mishchenko committed
1372
        s->nConfLimit = nConfLimitGlobal;
Alan Mishchenko committed
1373
    if ( nInsLimitGlobal && (s->nInsLimit == 0 || s->nInsLimit > nInsLimitGlobal) )
Alan Mishchenko committed
1374 1375
        s->nInsLimit = nInsLimitGlobal;

1376 1377
#ifndef SAT_USE_ANALYZE_FINAL

Alan Mishchenko committed
1378 1379 1380
    //printf("solve: "); printlits(begin, end); printf("\n");
    for (i = begin; i < end; i++){
        switch (lit_sign(*i) ? -values[lit_var(*i)] : values[lit_var(*i)]){
1381
        case 1: // l_True: 
Alan Mishchenko committed
1382
            break;
1383
        case 0: // l_Undef
Alan Mishchenko committed
1384 1385 1386
            assume(s, *i);
            if (sat_solver_propagate(s) == NULL)
                break;
Alan Mishchenko committed
1387
            // fallthrough
1388
        case -1: // l_False 
Alan Mishchenko committed
1389 1390 1391 1392 1393 1394
            sat_solver_canceluntil(s, 0);
            return l_False;
        }
    }
    s->root_level = sat_solver_dlevel(s);

1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
#endif

/*
    // Perform assumptions:
    root_level = assumps.size();
    for (int i = 0; i < assumps.size(); i++){
        Lit p = assumps[i];
        assert(var(p) < nVars());
        if (!assume(p)){
            GClause r = reason[var(p)];
            if (r != GClause_NULL){
                Clause* confl;
                if (r.isLit()){
                    confl = propagate_tmpbin;
                    (*confl)[1] = ~p;
                    (*confl)[0] = r.lit();
                }else
                    confl = r.clause();
                analyzeFinal(confl, true);
                conflict.push(~p);
            }else
                conflict.clear(),
                conflict.push(~p);
            cancelUntil(0);
            return false; }
        Clause* confl = propagate();
        if (confl != NULL){
            analyzeFinal(confl), assert(conflict.size() > 0);
            cancelUntil(0);
            return false; }
    }
    assert(root_level == decisionLevel());
*/

#ifdef SAT_USE_ANALYZE_FINAL
    // Perform assumptions:
    s->root_level = end - begin;
    for ( i = begin; i < end; i++ )
    {
        lit p = *i;
        assert(lit_var(p) < s->size);
        veci_push(&s->trail_lim,s->qtail);
        if (!enqueue(s,p,(clause*)0))
        {
            clause * r = s->reasons[lit_var(p)];
            if (r != NULL)
            {
                clause* confl;
                if (clause_is_lit(r))
                {
                    confl = s->binary;
                    (clause_begin(confl))[1] = lit_neg(p);
                    (clause_begin(confl))[0] = clause_read_lit(r);
                }
                else
                    confl = r;
                sat_solver_analyze_final(s, confl, 1);
                veci_push(&s->conf_final, lit_neg(p));
            }
            else
            {
                veci_resize(&s->conf_final,0);
                veci_push(&s->conf_final, lit_neg(p));
            }
            sat_solver_canceluntil(s, 0);
            return l_False; 
        }
        else
        {
            clause* confl = sat_solver_propagate(s);
            if (confl != NULL){
                sat_solver_analyze_final(s, confl, 0);
                assert(s->conf_final.size > 0);
                sat_solver_canceluntil(s, 0);
                return l_False; }
        }
    }
    assert(s->root_level == sat_solver_dlevel(s));
#endif

    s->nCalls2++;

Alan Mishchenko committed
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    if (s->verbosity >= 1){
        printf("==================================[MINISAT]===================================\n");
        printf("| Conflicts |     ORIGINAL     |              LEARNT              | Progress |\n");
        printf("|           | Clauses Literals |   Limit Clauses Literals  Lit/Cl |          |\n");
        printf("==============================================================================\n");
    }

    while (status == l_Undef){
        double Ratio = (s->stats.learnts == 0)? 0.0 :
            s->stats.learnts_literals / (double)s->stats.learnts;

Alan Mishchenko committed
1488 1489
        if (s->verbosity >= 1)
        {
Alan Mishchenko committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
            printf("| %9.0f | %7.0f %8.0f | %7.0f %7.0f %8.0f %7.1f | %6.3f %% |\n", 
                (double)s->stats.conflicts,
                (double)s->stats.clauses, 
                (double)s->stats.clauses_literals,
                (double)nof_learnts, 
                (double)s->stats.learnts, 
                (double)s->stats.learnts_literals,
                Ratio,
                s->progress_estimate*100);
            fflush(stdout);
        }
1501 1502
        nof_conflicts = (ABC_INT64_T)( 100 * luby(2, restart_iter++) );
//printf( "%d ", (int)nof_conflicts );
Alan Mishchenko committed
1503
        status = sat_solver_search(s, nof_conflicts, nof_learnts);
1504 1505
//        nof_conflicts = nof_conflicts * 3 / 2; //*= 1.5;
        nof_learnts    = nof_learnts * 11 / 10; //*= 1.1;
Alan Mishchenko committed
1506 1507 1508 1509 1510 1511 1512

        // quit the loop if reached an external limit
        if ( s->nConfLimit && s->stats.conflicts > s->nConfLimit )
        {
//            printf( "Reached the limit on the number of conflicts (%d).\n", s->nConfLimit );
            break;
        }
1513 1514
//        if ( s->nInsLimit  && s->stats.inspects > s->nInsLimit )
        if ( s->nInsLimit  && s->stats.propagations > s->nInsLimit )
Alan Mishchenko committed
1515 1516 1517 1518
        {
//            printf( "Reached the limit on the number of implications (%d).\n", s->nInsLimit );
            break;
        }
Alan Mishchenko committed
1519 1520 1521 1522 1523
    }
    if (s->verbosity >= 1)
        printf("==============================================================================\n");

    sat_solver_canceluntil(s,0);
Alan Mishchenko committed
1524 1525

    ////////////////////////////////////////////////
Alan Mishchenko committed
1526
    if ( status == l_False && s->pStore )
Alan Mishchenko committed
1527
    {
1528
        int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, NULL, NULL );
Alan Mishchenko committed
1529 1530 1531
        assert( RetValue );
    }
    ////////////////////////////////////////////////
Alan Mishchenko committed
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
    return status;
}


int sat_solver_nvars(sat_solver* s)
{
    return s->size;
}


int sat_solver_nclauses(sat_solver* s)
{
    return vecp_size(&s->clauses);
}


int sat_solver_nconflicts(sat_solver* s)
{
    return (int)s->stats.conflicts;
}

//=================================================================================================
Alan Mishchenko committed
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
// Clause storage functions:

void sat_solver_store_alloc( sat_solver * s )
{
    assert( s->pStore == NULL );
    s->pStore = Sto_ManAlloc();
}

void sat_solver_store_write( sat_solver * s, char * pFileName )
{
1564
    if ( s->pStore ) Sto_ManDumpClauses( (Sto_Man_t *)s->pStore, pFileName );
Alan Mishchenko committed
1565 1566 1567 1568
}

void sat_solver_store_free( sat_solver * s )
{
1569
    if ( s->pStore ) Sto_ManFree( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
1570 1571
    s->pStore = NULL;
}
Alan Mishchenko committed
1572 1573 1574

int sat_solver_store_change_last( sat_solver * s )
{
1575
    if ( s->pStore ) return Sto_ManChangeLastClause( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
1576 1577
    return -1;
}
Alan Mishchenko committed
1578
 
Alan Mishchenko committed
1579 1580
void sat_solver_store_mark_roots( sat_solver * s )
{
1581
    if ( s->pStore ) Sto_ManMarkRoots( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
1582 1583 1584 1585
}

void sat_solver_store_mark_clauses_a( sat_solver * s )
{
1586
    if ( s->pStore ) Sto_ManMarkClausesA( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
}

void * sat_solver_store_release( sat_solver * s )
{
    void * pTemp;
    if ( s->pStore == NULL )
        return NULL;
    pTemp = s->pStore;
    s->pStore = NULL;
    return pTemp;
}

//=================================================================================================
Alan Mishchenko committed
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
// Sorting functions (sigh):

static inline void selectionsort(void** array, int size, int(*comp)(const void *, const void *))
{
    int     i, j, best_i;
    void*   tmp;

    for (i = 0; i < size-1; i++){
        best_i = i;
        for (j = i+1; j < size; j++){
            if (comp(array[j], array[best_i]) < 0)
                best_i = j;
        }
        tmp = array[i]; array[i] = array[best_i]; array[best_i] = tmp;
    }
}


static void sortrnd(void** array, int size, int(*comp)(const void *, const void *), double* seed)
{
    if (size <= 15)
        selectionsort(array, size, comp);

    else{
        void*       pivot = array[irand(seed, size)];
        void*       tmp;
        int         i = -1;
        int         j = size;

        for(;;){
            do i++; while(comp(array[i], pivot)<0);
            do j--; while(comp(pivot, array[j])<0);

            if (i >= j) break;

            tmp = array[i]; array[i] = array[j]; array[j] = tmp;
        }

        sortrnd(array    , i     , comp, seed);
        sortrnd(&array[i], size-i, comp, seed);
    }
}

void sat_solver_sort(void** array, int size, int(*comp)(const void *, const void *))
{
Alan Mishchenko committed
1645
//    int i;
Alan Mishchenko committed
1646 1647
    double seed = 91648253;
    sortrnd(array,size,comp,&seed);
Alan Mishchenko committed
1648 1649
//    for ( i = 1; i < size; i++ )
//        assert(comp(array[i-1], array[i])<0);
Alan Mishchenko committed
1650
}
1651 1652
ABC_NAMESPACE_IMPL_END