satSolver.c 76.6 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
#define SAT_USE_ANALYZE_FINAL
33

Alan Mishchenko committed
34 35 36 37 38 39 40
//=================================================================================================
// Debug:

//#define VERBOSEDEBUG

// For derivation output (verbosity level 2)
#define L_IND    "%-*d"
41
#define L_ind    sat_solver_dl(s)*2+2,sat_solver_dl(s)
Alan Mishchenko committed
42 43 44 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
#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); }


//=================================================================================================
74 75 76 77 78 79 80 81 82 83 84 85 86 87
// Variable datatype + minor functions:

static const int var0  = 1;
static const int var1  = 0;
static const int varX  = 3;

struct varinfo_t
{
    unsigned val    :  2;  // variable value 
    unsigned pol    :  1;  // last polarity
    unsigned tag    :  1;  // conflict analysis tag
    unsigned lev    : 28;  // variable level
};

88 89
static inline int     var_level     (sat_solver* s, int v)            { return s->levels[v];   }
static inline int     var_value     (sat_solver* s, int v)            { return s->assigns[v];  }
90 91
static inline int     var_polar     (sat_solver* s, int v)            { return s->polarity[v]; }

92 93
static inline void    var_set_level (sat_solver* s, int v, int lev)   { s->levels[v] = lev;    }
static inline void    var_set_value (sat_solver* s, int v, int val)   { s->assigns[v] = val;   }
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 125 126 127
static inline void    var_set_polar (sat_solver* s, int v, int pol)   { s->polarity[v] = pol;  }

// variable tags
static inline int     var_tag       (sat_solver* s, int v)            { return s->tags[v]; }
static inline void    var_set_tag   (sat_solver* s, int v, int tag)   { 
    assert( tag > 0 && tag < 16 );
    if ( s->tags[v] == 0 )
        veci_push( &s->tagged, v );
    s->tags[v] = tag;                           
}
static inline void    var_add_tag   (sat_solver* s, int v, int tag)   { 
    assert( tag > 0 && tag < 16 );
    if ( s->tags[v] == 0 )
        veci_push( &s->tagged, v );
    s->tags[v] |= tag;                           
}
static inline void    solver2_clear_tags(sat_solver* s, int start)    { 
    int i, * tagged = veci_begin(&s->tagged);
    for (i = start; i < veci_size(&s->tagged); i++)
        s->tags[tagged[i]] = 0;
    veci_resize(&s->tagged,start);
}

int sat_solver_get_var_value(sat_solver* s, int v)
{
    if ( var_value(s, v) == var0 )
        return l_False;
    if ( var_value(s, v) == var1 )
        return l_True;
    if ( var_value(s, v) == varX )
        return l_Undef;
    assert( 0 );
    return 0;
}
Alan Mishchenko committed
128 129 130 131

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

132 133
static inline int      sat_solver_dl(sat_solver* s)                { return veci_size(&s->trail_lim); }
static inline veci*    sat_solver_read_wlist(sat_solver* s, lit l) { return &s->wlists[l];            }
Alan Mishchenko committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147

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

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

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

148
    while (i != 0 && s->activity[x] > s->activity[heap[parent]]){
Alan Mishchenko committed
149 150 151 152 153
        heap[i]           = heap[parent];
        orderpos[heap[i]] = i;
        i                 = parent;
        parent            = (i - 1) / 2;
    }
154

Alan Mishchenko committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    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
170
//printf( "+%d ", v );
Alan Mishchenko committed
171 172 173
    }
}

Alan Mishchenko committed
174
static inline int  order_select(sat_solver* s, float random_var_freq) // selectvar
Alan Mishchenko committed
175
{
176 177
    int*      heap     = veci_begin(&s->order);
    int*      orderpos = s->orderpos;
Alan Mishchenko committed
178 179 180 181
    // Random decision:
    if (drand(&s->random_seed) < random_var_freq){
        int next = irand(&s->random_seed,s->size);
        assert(next >= 0 && next < s->size);
182
        if (var_value(s, next) == varX)
Alan Mishchenko committed
183 184 185 186 187 188 189 190 191 192 193 194 195
            return next;
    }
    // Activity based decision:
    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){
            int    i     = 0;
            int    child = 1;
            while (child < size){
196

197
                if (child+1 < size && s->activity[heap[child]] < s->activity[heap[child+1]])
Alan Mishchenko committed
198 199
                    child++;
                assert(child < size);
200
                if (s->activity[x] >= s->activity[heap[child]])
Alan Mishchenko committed
201
                    break;
202

Alan Mishchenko committed
203 204 205 206 207 208 209 210
                heap[i]           = heap[child];
                orderpos[heap[i]] = i;
                i                 = child;
                child             = 2 * child + 1;
            }
            heap[i]           = x;
            orderpos[heap[i]] = i;
        }
211
        if (var_value(s, next) == varX)
Alan Mishchenko committed
212 213 214 215 216
            return next;
    }
    return var_Undef;
}

217 218 219 220 221
void sat_solver_set_var_activity(sat_solver* s, int * pVars, int nVars) 
{
    int i;
    for (i = 0; i < s->size; i++)
        s->activity[i] = 0;
222 223 224 225 226 227 228 229 230 231 232 233 234
    if ( s->VarActType == 0 )
    {
        s->var_inc            = (1 <<  5);
        s->var_decay          = -1;
        for ( i = 0; i < nVars; i++ )
        {
            int iVar = pVars ? pVars[i] : i;
            s->activity[iVar] = s->var_inc*(nVars-i);
            if (s->orderpos[iVar] != -1)
                order_update( s, iVar );
        }
    }
    else if ( s->VarActType == 1 )
235
    {
236 237 238 239 240 241 242 243
        s->var_inc = Abc_Dbl2Word(1);
        for ( i = 0; i < nVars; i++ )
        {
            int iVar = pVars ? pVars[i] : i;
            s->activity[iVar] = Abc_Dbl2Word(nVars-i);
            if (s->orderpos[iVar] != -1)
                order_update( s, iVar );
        }
244
    }
245
    else assert( 0 );
246 247
}

Alan Mishchenko committed
248
//=================================================================================================
249
// variable activities
250

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
static inline void solver_init_activities(sat_solver* s)  
{
    // variable activities
    s->VarActType             = 0;
    if ( s->VarActType == 0 )
    {
        s->var_inc            = (1 <<  5);
        s->var_decay          = -1;
    }
    else if ( s->VarActType == 1 )
    {
        s->var_inc            = Abc_Dbl2Word(1.0);
        s->var_decay          = Abc_Dbl2Word(1.0 / 0.95);
    }
    else if ( s->VarActType == 2 )
    {
        s->var_inc            = Xdbl_FromDouble(1.0);
        s->var_decay          = Xdbl_FromDouble(1.0 / 0.950);
    }
    else assert(0);
271

272 273 274 275 276 277 278 279 280 281 282 283
    // clause activities
    s->ClaActType             = 0;
    if ( s->ClaActType == 0 )
    {
        s->cla_inc            = (1 << 11);
        s->cla_decay          = -1;
    }
    else
    {
        s->cla_inc            = 1;
        s->cla_decay          = (float)(1 / 0.999);
    }
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 309 310 311 312 313 314
static inline void act_var_rescale(sat_solver* s)  
{
    if ( s->VarActType == 0 )
    {
        word* activity = s->activity;
        int i;
        for (i = 0; i < s->size; i++)
            activity[i] >>= 19;
        s->var_inc >>= 19;
        s->var_inc = Abc_MaxInt( (unsigned)s->var_inc, (1<<4) );
    }
    else if ( s->VarActType == 1 )
    {
        double* activity = (double*)s->activity;
        int i;
        for (i = 0; i < s->size; i++)
            activity[i] *= 1e-100;
        s->var_inc = Abc_Dbl2Word( Abc_Word2Dbl(s->var_inc) * 1e-100 );
        //printf( "Rescaling var activity...\n" ); 
    }
    else if ( s->VarActType == 2 )
    {
        xdbl * activity = s->activity;
        int i;
        for (i = 0; i < s->size; i++)
            activity[i] = Xdbl_Div( activity[i], 200 ); // activity[i] / 2^200
        s->var_inc = Xdbl_Div( s->var_inc, 200 ); 
    }
    else assert(0);
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
static inline void act_var_bump(sat_solver* s, int v) 
{
    if ( s->VarActType == 0 )
    {
        s->activity[v] += s->var_inc;
        if ((unsigned)s->activity[v] & 0x80000000)
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else if ( s->VarActType == 1 )
    {
        double act = Abc_Word2Dbl(s->activity[v]) + Abc_Word2Dbl(s->var_inc);
        s->activity[v] = Abc_Dbl2Word(act);
        if (act > 1e100)
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else if ( s->VarActType == 2 )
    {
        s->activity[v] = Xdbl_Add( s->activity[v], s->var_inc );
        if (s->activity[v] > ABC_CONST(0x014c924d692ca61b))
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else assert(0);
Alan Mishchenko committed
344
}
345 346
static inline void act_var_bump_global(sat_solver* s, int v) 
{
347
    if ( !s->pGlobalVars || !s->pGlobalVars[v] )
348 349 350
        return;
    if ( s->VarActType == 0 )
    {
351
        s->activity[v] += (int)((unsigned)s->var_inc * 3);
352 353 354 355 356 357 358
        if (s->activity[v] & 0x80000000)
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else if ( s->VarActType == 1 )
    {
359 360 361 362 363 364 365 366 367 368 369
        double act = Abc_Word2Dbl(s->activity[v]) + Abc_Word2Dbl(s->var_inc) * 3.0;
        s->activity[v] = Abc_Dbl2Word(act);
        if ( act > 1e100)
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else if ( s->VarActType == 2 )
    {
        s->activity[v] = Xdbl_Add( s->activity[v], Xdbl_Mul(s->var_inc, Xdbl_FromDouble(3.0)) );
        if (s->activity[v] > ABC_CONST(0x014c924d692ca61b))
370 371 372 373 374
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else assert( 0 );
Alan Mishchenko committed
375
}
376 377
static inline void act_var_bump_factor(sat_solver* s, int v) 
{
378 379 380 381 382 383 384 385 386 387 388 389
    if ( !s->factors )
        return;
    if ( s->VarActType == 0 )
    {
        s->activity[v] += (int)((unsigned)s->var_inc * (float)s->factors[v]);
        if (s->activity[v] & 0x80000000)
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else if ( s->VarActType == 1 )
    {
390 391 392 393 394 395 396 397 398 399 400
        double act = Abc_Word2Dbl(s->activity[v]) + Abc_Word2Dbl(s->var_inc) * s->factors[v];
        s->activity[v] = Abc_Dbl2Word(act);
        if ( act > 1e100)
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else if ( s->VarActType == 2 )
    {
        s->activity[v] = Xdbl_Add( s->activity[v], Xdbl_Mul(s->var_inc, Xdbl_FromDouble(s->factors[v])) );
        if (s->activity[v] > ABC_CONST(0x014c924d692ca61b))
401 402 403 404 405
            act_var_rescale(s);
        if (s->orderpos[v] != -1)
            order_update(s,v);
    }
    else assert( 0 );
Alan Mishchenko committed
406
}
407

408 409 410 411 412 413 414 415 416
static inline void act_var_decay(sat_solver* s)    
{ 
    if ( s->VarActType == 0 )
        s->var_inc += (s->var_inc >>  4); 
    else if ( s->VarActType == 1 )
        s->var_inc = Abc_Dbl2Word( Abc_Word2Dbl(s->var_inc) * Abc_Word2Dbl(s->var_decay) );
    else if ( s->VarActType == 2 )
        s->var_inc = Xdbl_Mul(s->var_inc, s->var_decay); 
    else assert(0);
Alan Mishchenko committed
417
}
418

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
// clause activities
static inline void act_clause_rescale(sat_solver* s) 
{
    if ( s->ClaActType == 0 )
    {
        unsigned* activity = (unsigned *)veci_begin(&s->act_clas);
        int i;
        for (i = 0; i < veci_size(&s->act_clas); i++)
            activity[i] >>= 14;
        s->cla_inc >>= 14;
        s->cla_inc = Abc_MaxInt( s->cla_inc, (1<<10) );
    }
    else
    {
        float* activity = (float *)veci_begin(&s->act_clas);
        int i;
        for (i = 0; i < veci_size(&s->act_clas); i++)
            activity[i] *= (float)1e-20;
        s->cla_inc *= (float)1e-20;
    }
439
}
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
static inline void act_clause_bump(sat_solver* s, clause *c) 
{
    if ( s->ClaActType == 0 )
    {
        unsigned* act = (unsigned *)veci_begin(&s->act_clas) + c->lits[c->size];
        *act += s->cla_inc;
        if ( *act & 0x80000000 )
            act_clause_rescale(s);
    }
    else
    {
        float* act = (float *)veci_begin(&s->act_clas) + c->lits[c->size];
        *act += s->cla_inc;
        if (*act > 1e20) 
            act_clause_rescale(s);
    }
456
}
457 458 459 460 461 462
static inline void act_clause_decay(sat_solver* s)    
{ 
    if ( s->ClaActType == 0 )
        s->cla_inc += (s->cla_inc >> 10);
    else
        s->cla_inc *= s->cla_decay;
463
}
464

Alan Mishchenko committed
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 507 508 509
// 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);
    }
}

//=================================================================================================
Alan Mishchenko committed
510 511
// Clause functions:

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
static inline int sat_clause_compute_lbd( sat_solver* s, clause* c )
{
    int i, lev, minl = 0, lbd = 0;
    for (i = 0; i < (int)c->size; i++)
    {
        lev = var_level(s, lit_var(c->lits[i]));
        if ( !(minl & (1 << (lev & 31))) )
        {
            minl |= 1 << (lev & 31);
            lbd++;
//            printf( "%d ", lev );
        }
    }
//    printf( " -> %d\n", lbd );
    return lbd;
}

Alan Mishchenko committed
529 530
/* pre: size > 1 && no variable occurs twice
 */
531
int sat_solver_clause_new(sat_solver* s, lit* begin, lit* end, int learnt)
Alan Mishchenko committed
532
{
533
    int fUseBinaryClauses = 1;
Alan Mishchenko committed
534 535
    int size;
    clause* c;
536
    int h;
Alan Mishchenko committed
537 538 539 540

    assert(end - begin > 1);
    assert(learnt >= 0 && learnt < 2);
    size           = end - begin;
541 542

    // do not allocate memory for the two-literal problem clause
543
    if ( fUseBinaryClauses && size == 2 && !learnt )
544
    {
545 546
        veci_push(sat_solver_read_wlist(s,lit_neg(begin[0])),(clause_from_lit(begin[1])));
        veci_push(sat_solver_read_wlist(s,lit_neg(begin[1])),(clause_from_lit(begin[0])));
547 548
        s->stats.clauses++;
        s->stats.clauses_literals += size;
549
        return 0;
550 551
    }

552
    // create new clause
553
//    h = Vec_SetAppend( &s->Mem, NULL, size + learnt + 1 + 1 ) << 1;
554
    h = Sat_MemAppend( &s->Mem, begin, size, learnt, 0 );
555 556 557
    assert( !(h & 1) );
    if ( s->hLearnts == -1 && learnt )
        s->hLearnts = h;
Alan Mishchenko committed
558
    if (learnt)
559 560 561 562 563 564
    {
        c = clause_read( s, h );
        c->lbd = sat_clause_compute_lbd( s, c );
        assert( clause_id(c) == veci_size(&s->act_clas) );
//        veci_push(&s->learned, h);
//        act_clause_bump(s,clause_read(s, h));
565 566 567 568
        if ( s->ClaActType == 0 )
            veci_push(&s->act_clas, (1<<10));
        else
            veci_push(&s->act_clas, s->cla_inc);
569 570 571 572 573 574 575 576
        s->stats.learnts++;
        s->stats.learnts_literals += size;
    }
    else
    {
        s->stats.clauses++;
        s->stats.clauses_literals += size;
    }
Alan Mishchenko committed
577 578 579 580 581 582 583 584 585

    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);

586 587 588 589
    //veci_push(sat_solver_read_wlist(s,lit_neg(begin[0])),c);
    //veci_push(sat_solver_read_wlist(s,lit_neg(begin[1])),c);
    veci_push(sat_solver_read_wlist(s,lit_neg(begin[0])),(size > 2 ? h : clause_from_lit(begin[1])));
    veci_push(sat_solver_read_wlist(s,lit_neg(begin[1])),(size > 2 ? h : clause_from_lit(begin[0])));
Alan Mishchenko committed
590

591
    return h;
Alan Mishchenko committed
592 593 594 595 596 597
}


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

598
static inline int sat_solver_enqueue(sat_solver* s, lit l, int from)
Alan Mishchenko committed
599
{
600
    int v  = lit_var(l);
601 602 603 604 605 606
    if ( s->pFreqs[v] == 0 )
//    {
        s->pFreqs[v] = 1;
//        s->nVarUsed++;
//    }

Alan Mishchenko committed
607 608 609
#ifdef VERBOSEDEBUG
    printf(L_IND"enqueue("L_LIT")\n", L_ind, L_lit(l));
#endif
610 611 612
    if (var_value(s, v) != varX)
        return var_value(s, v) == lit_sign(l);
    else{
613
/*
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
        if ( s->pCnfFunc )
        {
            if ( lit_sign(l) )
            {
                if ( (s->loads[v] & 1) == 0 )
                {
                    s->loads[v] ^= 1;
                    s->pCnfFunc( s->pCnfMan, l );
                }
            }
            else
            {
                if ( (s->loads[v] & 2) == 0 )
                {
                    s->loads[v] ^= 2;
                    s->pCnfFunc( s->pCnfMan, l );
                }
            }
        }
633
*/
Alan Mishchenko committed
634 635 636 637
        // New fact -- store it.
#ifdef VERBOSEDEBUG
        printf(L_IND"bind("L_LIT")\n", L_ind, L_lit(l));
#endif
638 639 640
        var_set_value(s, v, lit_sign(l));
        var_set_level(s, v, sat_solver_dl(s));
        s->reasons[v] = from;
Alan Mishchenko committed
641 642 643 644 645 646 647
        s->trail[s->qtail++] = l;
        order_assigned(s, v);
        return true;
    }
}


648
static inline int sat_solver_decision(sat_solver* s, lit l){
Alan Mishchenko committed
649
    assert(s->qtail == s->qhead);
650
    assert(var_value(s, lit_var(l)) == varX);
Alan Mishchenko committed
651
#ifdef VERBOSEDEBUG
652 653
    printf(L_IND"assume("L_LIT")  ", L_ind, L_lit(l));
    printf( "act = %.20f\n", s->activity[lit_var(l)] );
Alan Mishchenko committed
654 655
#endif
    veci_push(&s->trail_lim,s->qtail);
656
    return sat_solver_enqueue(s,l,0);
Alan Mishchenko committed
657 658 659
}


Alan Mishchenko committed
660
static void sat_solver_canceluntil(sat_solver* s, int level) {
Alan Mishchenko committed
661
    int      bound;
662
    int      lastLev;
Alan Mishchenko committed
663 664
    int      c;
    
665
    if (sat_solver_dl(s) <= level)
Alan Mishchenko committed
666 667
        return;

668
    assert( veci_size(&s->trail_lim) > 0 );
Alan Mishchenko committed
669
    bound   = (veci_begin(&s->trail_lim))[level];
670
    lastLev = (veci_begin(&s->trail_lim))[veci_size(&s->trail_lim)-1];
Alan Mishchenko committed
671

Alan Mishchenko committed
672 673 674 675 676 677
    ////////////////////////////////////////
    // added to cancel all assignments
//    if ( level == -1 )
//        bound = 0;
    ////////////////////////////////////////

Alan Mishchenko committed
678
    for (c = s->qtail-1; c >= bound; c--) {
679 680 681
        int     x  = lit_var(s->trail[c]);
        var_set_value(s, x, varX);
        s->reasons[x] = 0;
682
        if ( c < lastLev )
683
            var_set_polar( s, x, !lit_sign(s->trail[c]) );
Alan Mishchenko committed
684
    }
685
    //printf( "\n" );
Alan Mishchenko committed
686 687

    for (c = s->qhead-1; c >= bound; c--)
688
        order_unassigned(s,lit_var(s->trail[c]));
Alan Mishchenko committed
689 690 691 692 693

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

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
static void sat_solver_canceluntil_rollback(sat_solver* s, int NewBound) {
    int      c, x;
   
    assert( sat_solver_dl(s) == 0 );
    assert( s->qtail == s->qhead );
    assert( s->qtail >= NewBound );

    for (c = s->qtail-1; c >= NewBound; c--) 
    {
        x = lit_var(s->trail[c]);
        var_set_value(s, x, varX);
        s->reasons[x] = 0;
    }

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

    s->qhead = s->qtail = NewBound;
}

Alan Mishchenko committed
714 715 716 717
static void sat_solver_record(sat_solver* s, veci* cls)
{
    lit*    begin = veci_begin(cls);
    lit*    end   = begin + veci_size(cls);
718
    int     h     = (veci_size(cls) > 1) ? sat_solver_clause_new(s,begin,end,1) : 0;
719
    sat_solver_enqueue(s,*begin,h);
720
    assert(veci_size(cls) > 0);
721 722
    if ( h == 0 )
        veci_push( &s->unit_lits, *begin );
Alan Mishchenko committed
723

Alan Mishchenko committed
724 725 726 727
    ///////////////////////////////////
    // add clause to internal storage
    if ( s->pStore )
    {
728
        int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, begin, end );
Alan Mishchenko committed
729
        assert( RetValue );
Alan Mishchenko committed
730
        (void) RetValue;
Alan Mishchenko committed
731 732
    }
    ///////////////////////////////////
733
/*
734
    if (h != 0) {
735
        act_clause_bump(s,clause_read(s, h));
Alan Mishchenko committed
736 737 738
        s->stats.learnts++;
        s->stats.learnts_literals += veci_size(cls);
    }
739
*/
Alan Mishchenko committed
740 741
}

742 743 744 745 746 747 748 749 750 751
int sat_solver_count_assigned(sat_solver* s)
{
    // count top-level assignments
    int i, Count = 0;
    assert(sat_solver_dl(s) == 0);
    for ( i = 0; i < s->size; i++ )
        if (var_value(s, i) != varX)
            Count++;
    return Count;
}
Alan Mishchenko committed
752 753 754 755 756 757 758

static double sat_solver_progress(sat_solver* s)
{
    int     i;
    double  progress = 0;
    double  F        = 1.0 / s->size;
    for (i = 0; i < s->size; i++)
759 760
        if (var_value(s, i) != varX)
            progress += pow(F, var_level(s, i));
Alan Mishchenko committed
761 762 763 764 765 766
    return progress / s->size;
}

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

767
static int sat_solver_lit_removable(sat_solver* s, int x, int minl)
Alan Mishchenko committed
768 769 770
{
    int      top     = veci_size(&s->tagged);

771
    assert(s->reasons[x] != 0);
Alan Mishchenko committed
772
    veci_resize(&s->stack,0);
773 774 775 776 777 778 779 780 781
    veci_push(&s->stack,x);

    while (veci_size(&s->stack)){
        int v = veci_pop(&s->stack);
        assert(s->reasons[v] != 0);
        if (clause_is_lit(s->reasons[v])){
            v = lit_var(clause_read_lit(s->reasons[v]));
            if (!var_tag(s,v) && var_level(s, v)){
                if (s->reasons[v] != 0 && ((1 << (var_level(s, v) & 31)) & minl)){
Alan Mishchenko committed
782
                    veci_push(&s->stack,v);
783
                    var_set_tag(s, v, 1);
Alan Mishchenko committed
784
                }else{
785 786
                    solver2_clear_tags(s, top);
                    return 0;
Alan Mishchenko committed
787 788 789
                }
            }
        }else{
790 791 792
            clause* c = clause_read(s, s->reasons[v]);
            lit* lits = clause_begin(c);
            int  i;
793
            for (i = 1; i < clause_size(c); i++){
Alan Mishchenko committed
794
                int v = lit_var(lits[i]);
795 796
                if (!var_tag(s,v) && var_level(s, v)){
                    if (s->reasons[v] != 0 && ((1 << (var_level(s, v) & 31)) & minl)){
Alan Mishchenko committed
797
                        veci_push(&s->stack,lit_var(lits[i]));
798
                        var_set_tag(s, v, 1);
Alan Mishchenko committed
799
                    }else{
800 801
                        solver2_clear_tags(s, top);
                        return 0;
Alan Mishchenko committed
802 803 804 805 806
                    }
                }
            }
        }
    }
807
    return 1;
Alan Mishchenko committed
808 809
}

810 811 812 813 814 815 816 817 818 819 820

/*_________________________________________________________________________________________________
|
|  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'.
|________________________________________________________________________________________________@*/
/*
821
void Solver::analyzeFinal(Clause* confl, bool skip_first)
822
{
823 824 825 826 827 828 829 830 831 832
    // -- 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;
    }
833

834 835 836
    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]);
837
        if (seen[x]){
838 839 840 841
            GClause r = reason[x];
            if (r == GClause_NULL){
                assert(level[x] > 0);
                conflict.push(~trail[i]);
842
            }else{
843 844 845 846 847 848 849 850 851 852
                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;
                }
853 854 855 856 857 858 859
            }
            seen[x] = 0;
        }
    }
}
*/

860 861
#ifdef SAT_USE_ANALYZE_FINAL

862
static void sat_solver_analyze_final(sat_solver* s, int hConf, int skip_first)
863
{
864
    clause* conf = clause_read(s, hConf);
865 866 867
    int i, j, start;
    veci_resize(&s->conf_final,0);
    if ( s->root_level == 0 )
868 869
        return;
    assert( veci_size(&s->tagged) == 0 );
870 871
//    assert( s->tags[lit_var(p)] == l_Undef );
//    s->tags[lit_var(p)] = l_True;
872
    for (i = skip_first ? 1 : 0; i < clause_size(conf); i++)
873 874
    {
        int x = lit_var(clause_begin(conf)[i]);
875 876
        if (var_level(s, x) > 0)
            var_set_tag(s, x, 1);
877 878 879 880
    }

    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--){
881
        int x = lit_var(s->trail[i]);
882 883 884
        if (var_tag(s,x)){
            if (s->reasons[x] == 0){
                assert(var_level(s, x) > 0);
885
                veci_push(&s->conf_final,lit_neg(s->trail[i]));
886
            }else{
887 888
                if (clause_is_lit(s->reasons[x])){
                    lit q = clause_read_lit(s->reasons[x]);
889
                    assert(lit_var(q) >= 0 && lit_var(q) < s->size);
890 891
                    if (var_level(s, lit_var(q)) > 0)
                        var_set_tag(s, lit_var(q), 1);
892 893
                }
                else{
894
                    clause* c = clause_read(s, s->reasons[x]);
895
                    int* lits = clause_begin(c);
896
                    for (j = 1; j < clause_size(c); j++)
897 898
                        if (var_level(s, lit_var(lits[j])) > 0)
                            var_set_tag(s, lit_var(lits[j]), 1);
899 900 901 902
                }
            }
        }
    }
903
    solver2_clear_tags(s,0);
904 905
}

906 907
#endif

908
static void sat_solver_analyze(sat_solver* s, int h, veci* learnt)
Alan Mishchenko committed
909 910 911 912 913 914
{
    lit*     trail   = s->trail;
    int      cnt     = 0;
    lit      p       = lit_Undef;
    int      ind     = s->qtail-1;
    lit*     lits;
915
    int      i, j, minl;
Alan Mishchenko committed
916 917
    veci_push(learnt,lit_Undef);
    do{
918 919 920 921 922 923 924
        assert(h != 0);
        if (clause_is_lit(h)){
            int x = lit_var(clause_read_lit(h));
            if (var_tag(s, x) == 0 && var_level(s, x) > 0){
                var_set_tag(s, x, 1);
                act_var_bump(s,x);
                if (var_level(s, x) == sat_solver_dl(s))
Alan Mishchenko committed
925 926
                    cnt++;
                else
927
                    veci_push(learnt,clause_read_lit(h));
Alan Mishchenko committed
928 929
            }
        }else{
930
            clause* c = clause_read(s, h);
931
            
932 933
            if (clause_learnt(c))
                act_clause_bump(s,c);
Alan Mishchenko committed
934
            lits = clause_begin(c);
935 936
            //printlits(lits,lits+clause_size(c)); printf("\n");
            for (j = (p == lit_Undef ? 0 : 1); j < clause_size(c); j++){
937 938 939 940
                int x = lit_var(lits[j]);
                if (var_tag(s, x) == 0 && var_level(s, x) > 0){
                    var_set_tag(s, x, 1);
                    act_var_bump(s,x);
941 942 943
                    // bump variables propaged by the LBD=2 clause
//                    if ( s->reasons[x] && clause_read(s, s->reasons[x])->lbd <= 2 )
//                        act_var_bump(s,x);
944
                    if (var_level(s,x) == sat_solver_dl(s))
Alan Mishchenko committed
945 946
                        cnt++;
                    else
947
                        veci_push(learnt,lits[j]);
Alan Mishchenko committed
948 949 950 951
                }
            }
        }

952
        while ( !var_tag(s, lit_var(trail[ind--])) );
Alan Mishchenko committed
953 954

        p = trail[ind+1];
955
        h = s->reasons[lit_var(p)];
Alan Mishchenko committed
956 957 958 959 960 961 962 963 964
        cnt--;

    }while (cnt > 0);

    *veci_begin(learnt) = lit_neg(p);

    lits = veci_begin(learnt);
    minl = 0;
    for (i = 1; i < veci_size(learnt); i++){
965
        int lev = var_level(s, lit_var(lits[i]));
Alan Mishchenko committed
966 967 968 969 970
        minl    |= 1 << (lev & 31);
    }

    // simplify (full)
    for (i = j = 1; i < veci_size(learnt); i++){
971
        if (s->reasons[lit_var(lits[i])] == 0 || !sat_solver_lit_removable(s,lit_var(lits[i]),minl))
Alan Mishchenko committed
972 973 974 975 976 977 978
            lits[j++] = lits[i];
    }

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

979

Alan Mishchenko committed
980
    // clear tags
981
    solver2_clear_tags(s,0);
Alan Mishchenko committed
982 983 984

#ifdef DEBUG
    for (i = 0; i < s->size; i++)
985
        assert(!var_tag(s, i));
Alan Mishchenko committed
986 987 988 989 990 991 992 993
#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;
994
        int max   = var_level(s, lit_var(lits[1]));
Alan Mishchenko committed
995 996 997
        lit tmp;

        for (i = 2; i < veci_size(learnt); i++)
998 999
            if (var_level(s, lit_var(lits[i])) > max){
                max   = var_level(s, lit_var(lits[i]));
Alan Mishchenko committed
1000 1001 1002 1003 1004 1005 1006 1007 1008
                max_i = i;
            }

        tmp         = lits[1];
        lits[1]     = lits[max_i];
        lits[max_i] = tmp;
    }
#ifdef VERBOSEDEBUG
    {
1009
        int lev = veci_size(learnt) > 1 ? var_level(s, lit_var(lits[1])) : 0;
Alan Mishchenko committed
1010 1011 1012 1013 1014
        printf(" } at level %d\n", lev);
    }
#endif
}

1015
//#define TEST_CNF_LOAD
Alan Mishchenko committed
1016

1017
int sat_solver_propagate(sat_solver* s)
Alan Mishchenko committed
1018
{
1019
    int     hConfl = 0;
Alan Mishchenko committed
1020
    lit*    lits;
1021
    lit false_lit;
Alan Mishchenko committed
1022 1023

    //printf("sat_solver_propagate\n");
1024
    while (hConfl == 0 && s->qtail - s->qhead > 0){
1025
        lit p = s->trail[s->qhead++];
1026 1027

#ifdef TEST_CNF_LOAD
1028
        int v = lit_var(p);
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        if ( s->pCnfFunc )
        {
            if ( lit_sign(p) )
            {
                if ( (s->loads[v] & 1) == 0 )
                {
                    s->loads[v] ^= 1;
                    s->pCnfFunc( s->pCnfMan, p );
                }
            }
            else
            {
                if ( (s->loads[v] & 2) == 0 )
                {
                    s->loads[v] ^= 2;
                    s->pCnfFunc( s->pCnfMan, p );
                }
            }
        }
        {
#endif

1051 1052 1053 1054
        veci* ws    = sat_solver_read_wlist(s,p);
        int*  begin = veci_begin(ws);
        int*  end   = begin + veci_size(ws);
        int*i, *j;
Alan Mishchenko committed
1055 1056

        s->stats.propagations++;
1057
//        s->simpdb_props--;
Alan Mishchenko committed
1058

Alan Mishchenko committed
1059
        //printf("checking lit %d: "L_LIT"\n", veci_size(ws), L_lit(p));
Alan Mishchenko committed
1060 1061
        for (i = j = begin; i < end; ){
            if (clause_is_lit(*i)){
1062 1063

                int Lit = clause_read_lit(*i);
1064
                if (var_value(s, lit_var(Lit)) == lit_sign(Lit)){
1065 1066 1067 1068
                    *j++ = *i++;
                    continue;
                }

Alan Mishchenko committed
1069
                *j++ = *i;
1070
                if (!sat_solver_enqueue(s,clause_read_lit(*i),clause_from_lit(p))){
1071 1072 1073
                    hConfl = s->hBinary;
                    (clause_begin(s->binary))[1] = lit_neg(p);
                    (clause_begin(s->binary))[0] = clause_read_lit(*i++);
Alan Mishchenko committed
1074 1075 1076 1077
                    // Copy the remaining watches:
                    while (i < end)
                        *j++ = *i++;
                }
Alan Mishchenko committed
1078
            }else{
Alan Mishchenko committed
1079

1080 1081
                clause* c = clause_read(s,*i);
                lits = clause_begin(c);
Alan Mishchenko committed
1082

Alan Mishchenko committed
1083
                // Make sure the false literal is data[1]:
Alan Mishchenko committed
1084 1085 1086 1087 1088 1089 1090
                false_lit = lit_neg(p);
                if (lits[0] == false_lit){
                    lits[0] = lits[1];
                    lits[1] = false_lit;
                }
                assert(lits[1] == false_lit);

Alan Mishchenko committed
1091
                // If 0th watch is true, then clause is already satisfied.
1092
                if (var_value(s, lit_var(lits[0])) == lit_sign(lits[0]))
Alan Mishchenko committed
1093
                    *j++ = *i;
1094
                else{
Alan Mishchenko committed
1095
                    // Look for new watch:
1096
                    lit* stop = lits + clause_size(c);
Alan Mishchenko committed
1097
                    lit* k;
Alan Mishchenko committed
1098
                    for (k = lits + 2; k < stop; k++){
1099
                        if (var_value(s, lit_var(*k)) != !lit_sign(*k)){
Alan Mishchenko committed
1100 1101
                            lits[1] = *k;
                            *k = false_lit;
1102
                            veci_push(sat_solver_read_wlist(s,lit_neg(lits[1])),*i);
Alan Mishchenko committed
1103
                            goto next; }
Alan Mishchenko committed
1104 1105 1106 1107
                    }

                    *j++ = *i;
                    // Clause is unit under assignment:
1108 1109
                    if ( c->lrn )
                        c->lbd = sat_clause_compute_lbd(s, c);
1110
                    if (!sat_solver_enqueue(s,lits[0], *i)){
1111
                        hConfl = *i++;
Alan Mishchenko committed
1112 1113 1114 1115 1116 1117
                        // Copy the remaining watches:
                        while (i < end)
                            *j++ = *i++;
                    }
                }
            }
Alan Mishchenko committed
1118 1119
        next:
            i++;
Alan Mishchenko committed
1120 1121
        }

1122 1123
        s->stats.inspects += j - veci_begin(ws);
        veci_resize(ws,j - veci_begin(ws));
1124 1125 1126
#ifdef TEST_CNF_LOAD
        }
#endif
Alan Mishchenko committed
1127 1128
    }

1129
    return hConfl;
Alan Mishchenko committed
1130 1131 1132 1133 1134 1135 1136
}

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

sat_solver* sat_solver_new(void)
{
1137 1138
    sat_solver* s = (sat_solver*)ABC_CALLOC( char, sizeof(sat_solver));

1139
//    Vec_SetAlloc_(&s->Mem, 15);
1140
    Sat_MemAlloc_(&s->Mem, 17);
1141
    s->hLearnts = -1;
1142
    s->hBinary = Sat_MemAppend( &s->Mem, NULL, 2, 0, 0 );
1143
    s->binary = clause_read( s, s->hBinary );
1144

1145 1146 1147 1148
    s->nLearntStart = LEARNT_MAX_START_DEFAULT;  // starting learned clause limit
    s->nLearntDelta = LEARNT_MAX_INCRE_DEFAULT;  // delta of learned clause limit
    s->nLearntRatio = LEARNT_MAX_RATIO_DEFAULT;  // ratio of learned clause limit
    s->nLearntMax   = s->nLearntStart;
Alan Mishchenko committed
1149 1150 1151 1152 1153

    // initialize vectors
    veci_new(&s->order);
    veci_new(&s->trail_lim);
    veci_new(&s->tagged);
1154 1155
//    veci_new(&s->learned);
    veci_new(&s->act_clas);
Alan Mishchenko committed
1156
    veci_new(&s->stack);
1157
//    veci_new(&s->model);
1158
    veci_new(&s->unit_lits);
Alan Mishchenko committed
1159
    veci_new(&s->temp_clause);
1160
    veci_new(&s->conf_final);
Alan Mishchenko committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

    // initialize arrays
    s->wlists    = 0;
    s->activity  = 0;
    s->orderpos  = 0;
    s->reasons   = 0;
    s->trail     = 0;

    // initialize other vars
    s->size                   = 0;
    s->cap                    = 0;
    s->qhead                  = 0;
    s->qtail                  = 0;
1174 1175 1176 1177

    solver_init_activities(s);
    veci_new(&s->act_vars);

Alan Mishchenko committed
1178
    s->root_level             = 0;
1179 1180
//    s->simpdb_assigns         = 0;
//    s->simpdb_props           = 0;
Alan Mishchenko committed
1181 1182
    s->random_seed            = 91648253;
    s->progress_estimate      = 0;
1183 1184
//    s->binary                 = (clause*)ABC_ALLOC( char, sizeof(clause) + sizeof(lit)*2);
//    s->binary->size_learnt    = (2 << 1);
Alan Mishchenko committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    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.tot_literals     = 0;
    return s;
}

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
sat_solver* zsat_solver_new_seed(double seed)
{
    sat_solver* s = (sat_solver*)ABC_CALLOC( char, sizeof(sat_solver));

//    Vec_SetAlloc_(&s->Mem, 15);
    Sat_MemAlloc_(&s->Mem, 15);
    s->hLearnts = -1;
    s->hBinary = Sat_MemAppend( &s->Mem, NULL, 2, 0, 0 );
    s->binary = clause_read( s, s->hBinary );

    s->nLearntStart = LEARNT_MAX_START_DEFAULT;  // starting learned clause limit
    s->nLearntDelta = LEARNT_MAX_INCRE_DEFAULT;  // delta of learned clause limit
    s->nLearntRatio = LEARNT_MAX_RATIO_DEFAULT;  // ratio of learned clause limit
    s->nLearntMax   = s->nLearntStart;

    // initialize vectors
    veci_new(&s->order);
    veci_new(&s->trail_lim);
    veci_new(&s->tagged);
//    veci_new(&s->learned);
    veci_new(&s->act_clas);
    veci_new(&s->stack);
//    veci_new(&s->model);
    veci_new(&s->unit_lits);
    veci_new(&s->temp_clause);
    veci_new(&s->conf_final);

    // initialize arrays
    s->wlists    = 0;
    s->activity  = 0;
    s->orderpos  = 0;
    s->reasons   = 0;
    s->trail     = 0;

    // initialize other vars
    s->size                   = 0;
    s->cap                    = 0;
    s->qhead                  = 0;
    s->qtail                  = 0;
1239 1240 1241 1242

    solver_init_activities(s);
    veci_new(&s->act_vars);

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    s->root_level             = 0;
//    s->simpdb_assigns         = 0;
//    s->simpdb_props           = 0;
    s->random_seed            = seed;
    s->progress_estimate      = 0;
//    s->binary                 = (clause*)ABC_ALLOC( char, sizeof(clause) + sizeof(lit)*2);
//    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.tot_literals     = 0;
    return s;
}

1265 1266 1267 1268 1269
int sat_solver_addvar(sat_solver* s)
{
    sat_solver_setnvars(s, s->size+1);
    return s->size-1;
}
1270 1271 1272 1273 1274
void sat_solver_setnvars(sat_solver* s,int n)
{
    int var;

    if (s->cap < n){
1275
        int old_cap = s->cap;
1276
        while (s->cap < n) s->cap = s->cap*2+1;
1277 1278
        if ( s->cap < 50000 )
            s->cap = 50000;
1279

1280 1281 1282 1283 1284 1285
        s->wlists    = ABC_REALLOC(veci,   s->wlists,   s->cap*2);
//        s->vi        = ABC_REALLOC(varinfo,s->vi,       s->cap);
        s->levels    = ABC_REALLOC(int,    s->levels,   s->cap);
        s->assigns   = ABC_REALLOC(char,   s->assigns,  s->cap);
        s->polarity  = ABC_REALLOC(char,   s->polarity, s->cap);
        s->tags      = ABC_REALLOC(char,   s->tags,     s->cap);
1286
        s->loads     = ABC_REALLOC(char,   s->loads,    s->cap);
1287 1288
        s->activity  = ABC_REALLOC(word,   s->activity, s->cap);
        s->activity2 = ABC_REALLOC(word,   s->activity2,s->cap);
1289
        s->pFreqs    = ABC_REALLOC(char,   s->pFreqs,   s->cap);
1290

1291
        if ( s->factors )
1292 1293
        s->factors   = ABC_REALLOC(double, s->factors,  s->cap);
        s->orderpos  = ABC_REALLOC(int,    s->orderpos, s->cap);
1294
        s->reasons   = ABC_REALLOC(int,    s->reasons,  s->cap);
1295
        s->trail     = ABC_REALLOC(lit,    s->trail,    s->cap);
1296
        s->model     = ABC_REALLOC(int,    s->model,    s->cap);
1297 1298
        memset( s->wlists + 2*old_cap, 0, 2*(s->cap-old_cap)*sizeof(veci) );
    } 
1299 1300

    for (var = s->size; var < n; var++){
1301 1302 1303
        assert(!s->wlists[2*var].size);
        assert(!s->wlists[2*var+1].size);
        if ( s->wlists[2*var].ptr == NULL )
1304
            veci_new(&s->wlists[2*var]);
1305
        if ( s->wlists[2*var+1].ptr == NULL )
1306
            veci_new(&s->wlists[2*var+1]);
1307 1308 1309 1310 1311 1312

        if ( s->VarActType == 0 )
            s->activity[var] = (1<<10);
        else if ( s->VarActType == 1 )
            s->activity[var] = 0;
        else if ( s->VarActType == 2 )
1313
            s->activity[var] = 0;
1314 1315
        else assert(0);

1316
        s->pFreqs[var]   = 0;
1317 1318 1319 1320 1321 1322 1323
        if ( s->factors )
        s->factors [var] = 0;
//        *((int*)s->vi + var) = 0; s->vi[var].val = varX;
        s->levels  [var] = 0;
        s->assigns [var] = varX;
        s->polarity[var] = 0;
        s->tags    [var] = 0;
1324
        s->loads   [var] = 0;
1325 1326
        s->orderpos[var] = veci_size(&s->order);
        s->reasons [var] = 0;
1327
        s->model   [var] = 0; 
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
        
        /* 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;
}
Alan Mishchenko committed
1338 1339 1340

void sat_solver_delete(sat_solver* s)
{
1341 1342
//    Vec_SetFree_( &s->Mem );
    Sat_MemFree_( &s->Mem );
Alan Mishchenko committed
1343 1344 1345 1346 1347

    // delete vectors
    veci_delete(&s->order);
    veci_delete(&s->trail_lim);
    veci_delete(&s->tagged);
1348 1349
//    veci_delete(&s->learned);
    veci_delete(&s->act_clas);
Alan Mishchenko committed
1350
    veci_delete(&s->stack);
1351
//    veci_delete(&s->model);
Alan Mishchenko committed
1352
    veci_delete(&s->act_vars);
1353
    veci_delete(&s->unit_lits);
1354
    veci_delete(&s->pivot_vars);
Alan Mishchenko committed
1355
    veci_delete(&s->temp_clause);
1356
    veci_delete(&s->conf_final);
Alan Mishchenko committed
1357

1358 1359 1360
    veci_delete(&s->user_vars);
    veci_delete(&s->user_values);

Alan Mishchenko committed
1361
    // delete arrays
1362
    if (s->reasons != 0){
Alan Mishchenko committed
1363
        int i;
1364
        for (i = 0; i < s->cap*2; i++)
1365
            veci_delete(&s->wlists[i]);
Alan Mishchenko committed
1366
        ABC_FREE(s->wlists   );
1367 1368 1369 1370 1371
//        ABC_FREE(s->vi       );
        ABC_FREE(s->levels   );
        ABC_FREE(s->assigns  );
        ABC_FREE(s->polarity );
        ABC_FREE(s->tags     );
1372
        ABC_FREE(s->loads    );
Alan Mishchenko committed
1373
        ABC_FREE(s->activity );
1374
        ABC_FREE(s->activity2);
1375
        ABC_FREE(s->pFreqs   );
Alan Mishchenko committed
1376 1377 1378 1379
        ABC_FREE(s->factors  );
        ABC_FREE(s->orderpos );
        ABC_FREE(s->reasons  );
        ABC_FREE(s->trail    );
1380
        ABC_FREE(s->model    );
Alan Mishchenko committed
1381 1382
    }

Alan Mishchenko committed
1383
    sat_solver_store_free(s);
Alan Mishchenko committed
1384
    ABC_FREE(s);
Alan Mishchenko committed
1385 1386
}

1387
void sat_solver_restart( sat_solver* s )
1388 1389
{
    int i;
1390
    Sat_MemRestart( &s->Mem );
1391
    s->hLearnts = -1;
1392
    s->hBinary = Sat_MemAppend( &s->Mem, NULL, 2, 0, 0 );
1393 1394
    s->binary = clause_read( s, s->hBinary );

1395 1396 1397 1398 1399
    veci_resize(&s->trail_lim, 0);
    veci_resize(&s->order, 0);
    for ( i = 0; i < s->size*2; i++ )
        s->wlists[i].size = 0;

1400
    s->nDBreduces = 0;
1401

1402 1403 1404 1405 1406
    // initialize other vars
    s->size                   = 0;
//    s->cap                    = 0;
    s->qhead                  = 0;
    s->qtail                  = 0;
1407 1408 1409 1410 1411 1412 1413


    // variable activities
    solver_init_activities(s);
    veci_resize(&s->act_clas, 0);


1414
    s->root_level             = 0;
1415 1416
//    s->simpdb_assigns         = 0;
//    s->simpdb_props           = 0;
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
    s->random_seed            = 91648253;
    s->progress_estimate      = 0;
    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.tot_literals     = 0;
}

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
void zsat_solver_restart_seed( sat_solver* s, double seed )
{
    int i;
    Sat_MemRestart( &s->Mem );
    s->hLearnts = -1;
    s->hBinary = Sat_MemAppend( &s->Mem, NULL, 2, 0, 0 );
    s->binary = clause_read( s, s->hBinary );

    veci_resize(&s->trail_lim, 0);
    veci_resize(&s->order, 0);
    for ( i = 0; i < s->size*2; i++ )
        s->wlists[i].size = 0;

    s->nDBreduces = 0;

    // initialize other vars
    s->size                   = 0;
//    s->cap                    = 0;
    s->qhead                  = 0;
    s->qtail                  = 0;
1453 1454 1455 1456

    solver_init_activities(s);
    veci_resize(&s->act_clas, 0);

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    s->root_level             = 0;
//    s->simpdb_assigns         = 0;
//    s->simpdb_props           = 0;
    s->random_seed            = seed;
    s->progress_estimate      = 0;
    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.tot_literals     = 0;
}

1476
// returns memory in bytes used by the SAT solver
1477
double sat_solver_memory( sat_solver* s )
1478
{
1479 1480
    int i;
    double Mem = sizeof(sat_solver);
1481 1482 1483 1484 1485 1486 1487
    for (i = 0; i < s->cap*2; i++)
        Mem += s->wlists[i].cap * sizeof(int);
    Mem += s->cap * sizeof(veci);     // ABC_FREE(s->wlists   );
    Mem += s->cap * sizeof(int);      // ABC_FREE(s->levels   );
    Mem += s->cap * sizeof(char);     // ABC_FREE(s->assigns  );
    Mem += s->cap * sizeof(char);     // ABC_FREE(s->polarity );
    Mem += s->cap * sizeof(char);     // ABC_FREE(s->tags     );
1488
    Mem += s->cap * sizeof(char);     // ABC_FREE(s->loads    );
1489
    Mem += s->cap * sizeof(word);     // ABC_FREE(s->activity );
1490
    if ( s->activity2 )
1491
    Mem += s->cap * sizeof(word);     // ABC_FREE(s->activity );
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
    if ( s->factors )
    Mem += s->cap * sizeof(double);   // ABC_FREE(s->factors  );
    Mem += s->cap * sizeof(int);      // ABC_FREE(s->orderpos );
    Mem += s->cap * sizeof(int);      // ABC_FREE(s->reasons  );
    Mem += s->cap * sizeof(lit);      // ABC_FREE(s->trail    );
    Mem += s->cap * sizeof(int);      // ABC_FREE(s->model    );

    Mem += s->order.cap * sizeof(int);
    Mem += s->trail_lim.cap * sizeof(int);
    Mem += s->tagged.cap * sizeof(int);
1502
//    Mem += s->learned.cap * sizeof(int);
1503 1504
    Mem += s->stack.cap * sizeof(int);
    Mem += s->act_vars.cap * sizeof(int);
1505
    Mem += s->unit_lits.cap * sizeof(int);
1506
    Mem += s->act_clas.cap * sizeof(int);
1507 1508
    Mem += s->temp_clause.cap * sizeof(int);
    Mem += s->conf_final.cap * sizeof(int);
1509
    Mem += Sat_MemMemoryAll( &s->Mem );
1510 1511 1512
    return Mem;
}

1513
int sat_solver_simplify(sat_solver* s)
1514
{
1515 1516 1517 1518
    assert(sat_solver_dl(s) == 0);
    if (sat_solver_propagate(s) != 0)
        return false;
    return true;
1519 1520
}

1521
void sat_solver_reducedb(sat_solver* s)
1522
{
1523 1524
    static abctime TimeTotal = 0;
    abctime clk = Abc_Clock();
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    Sat_Mem_t * pMem = &s->Mem;
    int nLearnedOld = veci_size(&s->act_clas);
    int * act_clas = veci_begin(&s->act_clas);
    int * pPerm, * pArray, * pSortValues, nCutoffValue;
    int i, k, j, Id, Counter, CounterStart, nSelected;
    clause * c;

    assert( s->nLearntMax > 0 );
    assert( nLearnedOld == Sat_MemEntryNum(pMem, 1) );
    assert( nLearnedOld == (int)s->stats.learnts );

    s->nDBreduces++;

1538
    //printf( "Calling reduceDB with %d learned clause limit.\n", s->nLearntMax );
1539
    s->nLearntMax = s->nLearntStart + s->nLearntDelta * s->nDBreduces;
1540 1541 1542 1543 1544 1545 1546 1547
//    return;

    // create sorting values
    pSortValues = ABC_ALLOC( int, nLearnedOld );
    Sat_MemForEachLearned( pMem, c, i, k )
    {
        Id = clause_id(c);
//        pSortValues[Id] = act[Id];
1548 1549 1550 1551
        if ( s->ClaActType == 0 )
            pSortValues[Id] = ((7 - Abc_MinInt(c->lbd, 7)) << 28) | (act_clas[Id] >> 4);
        else
            pSortValues[Id] = ((7 - Abc_MinInt(c->lbd, 7)) << 28);// | (act_clas[Id] >> 4);
1552
        assert( pSortValues[Id] >= 0 );
1553 1554
    }

1555 1556
    // preserve 1/20 of last clauses
    CounterStart  = nLearnedOld - (s->nLearntMax / 20);
1557

1558
    // preserve 3/4 of most active clauses
1559
    nSelected = nLearnedOld*s->nLearntRatio/100;
1560

1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
    // find non-decreasing permutation
    pPerm = Abc_MergeSortCost( pSortValues, nLearnedOld );
    assert( pSortValues[pPerm[0]] <= pSortValues[pPerm[nLearnedOld-1]] );
    nCutoffValue = pSortValues[pPerm[nLearnedOld-nSelected]];
    ABC_FREE( pPerm );
//    ActCutOff = ABC_INFINITY;

    // mark learned clauses to remove
    Counter = j = 0;
    Sat_MemForEachLearned( pMem, c, i, k )
    {
        assert( c->mark == 0 );
        if ( Counter++ > CounterStart || clause_size(c) < 3 || pSortValues[clause_id(c)] > nCutoffValue || s->reasons[lit_var(c->lits[0])] == Sat_MemHand(pMem, i, k) )
            act_clas[j++] = act_clas[clause_id(c)];
        else // delete
        {
            c->mark = 1;
            s->stats.learnts_literals -= clause_size(c);
            s->stats.learnts--;
1580 1581
        }
    }
1582 1583 1584 1585
    assert( s->stats.learnts == (unsigned)j );
    assert( Counter == nLearnedOld );
    veci_resize(&s->act_clas,j);
    ABC_FREE( pSortValues );
1586

1587 1588 1589
    // update ID of each clause to be its new handle
    Counter = Sat_MemCompactLearned( pMem, 0 );
    assert( Counter == (int)s->stats.learnts );
1590

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    // update reasons
    for ( i = 0; i < s->size; i++ )
    {
        if ( !s->reasons[i] ) // no reason
            continue;
        if ( clause_is_lit(s->reasons[i]) ) // 2-lit clause
            continue;
        if ( !clause_learnt_h(pMem, s->reasons[i]) ) // problem clause
            continue;
        c = clause_read( s, s->reasons[i] );
        assert( c->mark == 0 );
        s->reasons[i] = clause_id(c); // updating handle here!!!
    }
1604

1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    // update watches
    for ( i = 0; i < s->size*2; i++ )
    {
        pArray = veci_begin(&s->wlists[i]);
        for ( j = k = 0; k < veci_size(&s->wlists[i]); k++ )
        {
            if ( clause_is_lit(pArray[k]) ) // 2-lit clause
                pArray[j++] = pArray[k];
            else if ( !clause_learnt_h(pMem, pArray[k]) ) // problem clause
                pArray[j++] = pArray[k];
            else 
            {
                c = clause_read(s, pArray[k]);
                if ( !c->mark ) // useful learned clause
                   pArray[j++] = clause_id(c); // updating handle here!!!
            }
        }
        veci_resize(&s->wlists[i],j);
1623
    }
1624 1625 1626 1627 1628 1629

    // perform final move of the clauses
    Counter = Sat_MemCompactLearned( pMem, 1 );
    assert( Counter == (int)s->stats.learnts );

    // report the results
1630
    TimeTotal += Abc_Clock() - clk;
1631
    if ( s->fVerbose )
1632 1633 1634 1635
    {
    Abc_Print(1, "reduceDB: Keeping %7d out of %7d clauses (%5.2f %%)  ",
        s->stats.learnts, nLearnedOld, 100.0 * s->stats.learnts / nLearnedOld );
    Abc_PrintTime( 1, "Time", TimeTotal );
1636 1637 1638
    }
}

1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656

// reverses to the previously bookmarked point
void sat_solver_rollback( sat_solver* s )
{
    Sat_Mem_t * pMem = &s->Mem;
    int i, k, j;
    static int Count = 0;
    Count++;
    assert( s->iVarPivot >= 0 && s->iVarPivot <= s->size );
    assert( s->iTrailPivot >= 0 && s->iTrailPivot <= s->qtail );
    // reset implication queue
    sat_solver_canceluntil_rollback( s, s->iTrailPivot );
    // update order 
    if ( s->iVarPivot < s->size )
    { 
        if ( s->activity2 )
        {
            s->var_inc = s->var_inc2;
1657
            memcpy( s->activity, s->activity2, sizeof(word) * s->iVarPivot );
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
        }
        veci_resize(&s->order, 0);
        for ( i = 0; i < s->iVarPivot; i++ )
        {
            if ( var_value(s, i) != varX )
                continue;
            s->orderpos[i] = veci_size(&s->order);
            veci_push(&s->order,i);
            order_update(s, i);
        }
    }
    // compact watches
    for ( i = 0; i < s->iVarPivot*2; i++ )
    {
        cla* pArray = veci_begin(&s->wlists[i]);
        for ( j = k = 0; k < veci_size(&s->wlists[i]); k++ )
1674 1675 1676 1677 1678 1679 1680
        {
            if ( clause_is_lit(pArray[k]) )
            {
                if ( clause_read_lit(pArray[k]) < s->iVarPivot*2 )
                    pArray[j++] = pArray[k];
            }
            else if ( Sat_MemClauseUsed(pMem, pArray[k]) )
1681
                pArray[j++] = pArray[k];
1682
        }
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
        veci_resize(&s->wlists[i],j);
    }
    // reset watcher lists
    for ( i = 2*s->iVarPivot; i < 2*s->size; i++ )
        s->wlists[i].size = 0;

    // reset clause counts
    s->stats.clauses = pMem->BookMarkE[0];
    s->stats.learnts = pMem->BookMarkE[1];
    // rollback clauses
    Sat_MemRollBack( pMem );

    // resize learned arrays
    veci_resize(&s->act_clas,  s->stats.learnts);

    // initialize other vars
    s->size = s->iVarPivot;
    if ( s->size == 0 )
    {
    //    s->size                   = 0;
    //    s->cap                    = 0;
        s->qhead                  = 0;
        s->qtail                  = 0;
1706 1707 1708

        solver_init_activities(s);

1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
        s->root_level             = 0;
        s->random_seed            = 91648253;
        s->progress_estimate      = 0;
        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.tot_literals     = 0;

        // initialize rollback
        s->iVarPivot              =  0; // the pivot for variables
        s->iTrailPivot            =  0; // the pivot for trail
        s->hProofPivot            =  1; // the pivot for proof records
    }
}


1733
int sat_solver_addclause(sat_solver* s, lit* begin, lit* end)
Alan Mishchenko committed
1734 1735 1736 1737
{
    lit *i,*j;
    int maxvar;
    lit last;
1738
    assert( begin < end );
1739
    if ( s->fPrintClause )
1740 1741 1742 1743 1744
    {
        for ( i = begin; i < end; i++ )
            printf( "%s%d ", (*i)&1 ? "!":"", (*i)>>1 );
        printf( "\n" );
    }
Alan Mishchenko committed
1745

Alan Mishchenko committed
1746 1747 1748 1749 1750 1751
    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
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
    // 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
1763 1764 1765 1766
    ///////////////////////////////////
    // add clause to internal storage
    if ( s->pStore )
    {
1767
        int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, begin, end );
Alan Mishchenko committed
1768
        assert( RetValue );
Alan Mishchenko committed
1769
        (void) RetValue;
Alan Mishchenko committed
1770 1771 1772
    }
    ///////////////////////////////////

Alan Mishchenko committed
1773 1774 1775
    // delete duplicates
    last = lit_Undef;
    for (i = j = begin; i < end; i++){
1776 1777
        //printf("lit: "L_LIT", value = %d\n", L_lit(*i), (lit_sign(*i) ? -s->assignss[lit_var(*i)] : s->assignss[lit_var(*i)]));
        if (*i == lit_neg(last) || var_value(s, lit_var(*i)) == lit_sign(*i))
Alan Mishchenko committed
1778
            return true;   // tautology
1779
        else if (*i != last && var_value(s, lit_var(*i)) == varX)
Alan Mishchenko committed
1780 1781
            last = *j++ = *i;
    }
1782
//    j = i;
Alan Mishchenko committed
1783 1784 1785

    if (j == begin)          // empty clause
        return false;
Alan Mishchenko committed
1786 1787

    if (j - begin == 1) // unit clause
1788
        return sat_solver_enqueue(s,*begin,0);
Alan Mishchenko committed
1789 1790

    // create new clause
1791
    sat_solver_clause_new(s,begin,j,0);
Alan Mishchenko committed
1792 1793 1794
    return true;
}

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
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
1814

1815
static lbool sat_solver_search(sat_solver* s, ABC_INT64_T nof_conflicts)
1816
{
1817 1818
//    double  var_decay       = 0.95;
//    double  clause_decay    = 0.999;
1819
    double  random_var_freq = s->fNotUseRandom ? 0.0 : 0.02;
1820
    ABC_INT64_T  conflictC  = 0;
1821 1822 1823
    veci    learnt_clause;
    int     i;

1824
    assert(s->root_level == sat_solver_dl(s));
1825 1826 1827 1828 1829

    s->nRestarts++;
    s->stats.starts++;
//    s->var_decay = (float)(1 / var_decay   );  // move this to sat_solver_new()
//    s->cla_decay = (float)(1 / clause_decay);  // move this to sat_solver_new()
1830
//    veci_resize(&s->model,0);
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
    veci_new(&learnt_clause);

    // use activity factors in every even restart
    if ( (s->nRestarts & 1) && veci_size(&s->act_vars) > 0 )
//    if ( veci_size(&s->act_vars) > 0 )
        for ( i = 0; i < s->act_vars.size; i++ )
            act_var_bump_factor(s, s->act_vars.ptr[i]);

    // 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]);

    for (;;){
1845 1846
        int hConfl = sat_solver_propagate(s);
        if (hConfl != 0){
1847 1848 1849 1850 1851 1852 1853
            // CONFLICT
            int blevel;

#ifdef VERBOSEDEBUG
            printf(L_IND"**CONFLICT**\n", L_ind);
#endif
            s->stats.conflicts++; conflictC++;
1854
            if (sat_solver_dl(s) == s->root_level){
1855
#ifdef SAT_USE_ANALYZE_FINAL
1856
                sat_solver_analyze_final(s, hConfl, 0);
1857 1858 1859 1860 1861 1862
#endif
                veci_delete(&learnt_clause);
                return l_False;
            }

            veci_resize(&learnt_clause,0);
1863 1864
            sat_solver_analyze(s, hConfl, &learnt_clause);
            blevel = veci_size(&learnt_clause) > 1 ? var_level(s, lit_var(veci_begin(&learnt_clause)[1])) : s->root_level;
1865 1866 1867 1868 1869
            blevel = s->root_level > blevel ? s->root_level : blevel;
            sat_solver_canceluntil(s,blevel);
            sat_solver_record(s,&learnt_clause);
#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)
1870 1871
            if ( learnt_clause.size == 1 ) 
                var_set_level(s, lit_var(learnt_clause.ptr[0]), 0);
1872 1873
#endif
            act_var_decay(s);
1874
            act_clause_decay(s);
1875 1876 1877 1878 1879

        }else{
            // NO CONFLICT
            int next;

1880
            // Reached bound on number of conflicts:
1881
            if ( (!s->fNoRestarts && nof_conflicts >= 0 && conflictC >= nof_conflicts) || (s->nRuntimeLimit && (s->stats.conflicts & 63) == 0 && Abc_Clock() > s->nRuntimeLimit)){
1882 1883 1884 1885 1886 1887
                s->progress_estimate = sat_solver_progress(s);
                sat_solver_canceluntil(s,s->root_level);
                veci_delete(&learnt_clause);
                return l_Undef; }

            // Reached bound on number of conflicts:
1888 1889 1890 1891 1892 1893 1894 1895 1896
            if ( (s->nConfLimit && s->stats.conflicts > s->nConfLimit) ||
                 (s->nInsLimit  && s->stats.propagations > s->nInsLimit) )
            {
                s->progress_estimate = sat_solver_progress(s);
                sat_solver_canceluntil(s,s->root_level);
                veci_delete(&learnt_clause);
                return l_Undef; 
            }

1897
            // Simplify the set of problem clauses:
1898
            if (sat_solver_dl(s) == 0 && !s->fSkipSimplify)
1899 1900
                sat_solver_simplify(s);

1901 1902 1903 1904
            // Reduce the set of learnt clauses:
//            if (s->nLearntMax && veci_size(&s->learned) - s->qtail >= s->nLearntMax)
            if (s->nLearntMax && veci_size(&s->act_clas) >= s->nLearntMax)
                sat_solver_reducedb(s);
1905 1906 1907

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

            if (next == var_Undef){
                // Model found:
                int i;
1913 1914
                for (i = 0; i < s->size; i++)
                    s->model[i] = (var_value(s,i)==var1 ? l_True : l_False);
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
                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;
            }

1929
            if ( var_polar(s, next) ) // positive polarity
1930
                sat_solver_decision(s,toLit(next));
1931
            else
1932
                sat_solver_decision(s,lit_neg(toLit(next)));
1933 1934 1935 1936 1937 1938
        }
    }

    return l_Undef; // cannot happen
}

1939 1940
// internal call to the SAT solver
int sat_solver_solve_internal(sat_solver* s)
Alan Mishchenko committed
1941
{
1942
    lbool status = l_Undef;
1943
    int restart_iter = 0;
1944
    veci_resize(&s->unit_lits, 0);
Alan Mishchenko committed
1945
    s->nCalls++;
1946

Alan Mishchenko committed
1947 1948 1949 1950 1951 1952 1953 1954
    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){
1955
        ABC_INT64_T nof_conflicts;
Alan Mishchenko committed
1956 1957
        double Ratio = (s->stats.learnts == 0)? 0.0 :
            s->stats.learnts_literals / (double)s->stats.learnts;
1958
        if ( s->nRuntimeLimit && Abc_Clock() > s->nRuntimeLimit )
Alan Mishchenko committed
1959
            break;
Alan Mishchenko committed
1960 1961
        if (s->verbosity >= 1)
        {
Alan Mishchenko committed
1962 1963 1964 1965
            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,
1966
                (double)0, 
Alan Mishchenko committed
1967 1968 1969 1970 1971 1972
                (double)s->stats.learnts, 
                (double)s->stats.learnts_literals,
                Ratio,
                s->progress_estimate*100);
            fflush(stdout);
        }
1973
        nof_conflicts = (ABC_INT64_T)( 100 * luby(2, restart_iter++) );
1974
        status = sat_solver_search(s, nof_conflicts);
Alan Mishchenko committed
1975 1976 1977
        // quit the loop if reached an external limit
        if ( s->nConfLimit && s->stats.conflicts > s->nConfLimit )
            break;
1978
        if ( s->nInsLimit  && s->stats.propagations > s->nInsLimit )
Alan Mishchenko committed
1979
            break;
1980
        if ( s->nRuntimeLimit && Abc_Clock() > s->nRuntimeLimit )
1981
            break;
1982 1983
        if ( s->pFuncStop && s->pFuncStop(s->RunId) )
            break;
Alan Mishchenko committed
1984 1985 1986 1987
    }
    if (s->verbosity >= 1)
        printf("==============================================================================\n");

1988
    sat_solver_canceluntil(s,s->root_level);
1989 1990 1991 1992 1993 1994 1995
    // save variable values
    if ( status == l_True && s->user_vars.size )
    {
        int v;
        for ( v = 0; v < s->user_vars.size; v++ )
            veci_push(&s->user_values, sat_solver_var_value(s, s->user_vars.ptr[v]));
    }
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
    return status;
}

// pushing one assumption to the stack of assumptions
int sat_solver_push(sat_solver* s, int p)
{
    assert(lit_var(p) < s->size);
    veci_push(&s->trail_lim,s->qtail);
    s->root_level++;
    if (!sat_solver_enqueue(s,p,0))
    {
        int h = s->reasons[lit_var(p)];
        if (h)
        {
            if (clause_is_lit(h))
            {
                (clause_begin(s->binary))[1] = lit_neg(p);
                (clause_begin(s->binary))[0] = clause_read_lit(h);
                h = s->hBinary;
            }
            sat_solver_analyze_final(s, h, 1);
            veci_push(&s->conf_final, lit_neg(p));
        }
        else
        {
            veci_resize(&s->conf_final,0);
            veci_push(&s->conf_final, lit_neg(p));
            // the two lines below are a bug fix by Siert Wieringa 
            if (var_level(s, lit_var(p)) > 0)
                veci_push(&s->conf_final, p);
        }
        //sat_solver_canceluntil(s, 0);
        return false; 
    }
    else
    {
        int fConfl = sat_solver_propagate(s);
        if (fConfl){
            sat_solver_analyze_final(s, fConfl, 0);
            //assert(s->conf_final.size > 0);
            //sat_solver_canceluntil(s, 0);
            return false; }
    }
    return true;
}

// removing one assumption from the stack of assumptions
void sat_solver_pop(sat_solver* s)
{
    assert( sat_solver_dl(s) > 0 );
    sat_solver_canceluntil(s, --s->root_level);
}

void sat_solver_set_resource_limits(sat_solver* s, ABC_INT64_T nConfLimit, ABC_INT64_T nInsLimit, ABC_INT64_T nConfLimitGlobal, ABC_INT64_T nInsLimitGlobal)
{
    // set the external limits
    s->nRestarts  = 0;
    s->nConfLimit = 0;
    s->nInsLimit  = 0;
    if ( nConfLimit )
        s->nConfLimit = s->stats.conflicts + nConfLimit;
    if ( nInsLimit )
//        s->nInsLimit = s->stats.inspects + nInsLimit;
        s->nInsLimit = s->stats.propagations + nInsLimit;
    if ( nConfLimitGlobal && (s->nConfLimit == 0 || s->nConfLimit > nConfLimitGlobal) )
        s->nConfLimit = nConfLimitGlobal;
    if ( nInsLimitGlobal && (s->nInsLimit == 0 || s->nInsLimit > nInsLimitGlobal) )
        s->nInsLimit = nInsLimitGlobal;
}

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)
{
    lbool status;
    lit * i;
    ////////////////////////////////////////////////
    if ( s->fSolved )
    {
        if ( s->pStore )
        {
            int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, NULL, NULL );
            assert( RetValue );
            (void) RetValue;
        }
        return l_False;
    }
    ////////////////////////////////////////////////

    if ( s->fVerbose )
        printf( "Running SAT solver with parameters %d and %d and %d.\n", s->nLearntStart, s->nLearntDelta, s->nLearntRatio );

    sat_solver_set_resource_limits( s, nConfLimit, nInsLimit, nConfLimitGlobal, nInsLimitGlobal );

#ifdef SAT_USE_ANALYZE_FINAL
    // Perform assumptions:
    s->root_level = 0;
    for ( i = begin; i < end; i++ )
        if ( !sat_solver_push(s, *i) )
        {
            sat_solver_canceluntil(s,0);
            s->root_level = 0;
            return l_False;
        }
    assert(s->root_level == sat_solver_dl(s));
#else
    //printf("solve: "); printlits(begin, end); printf("\n");
    for (i = begin; i < end; i++){
//        switch (lit_sign(*i) ? -s->assignss[lit_var(*i)] : s->assignss[lit_var(*i)]){
        switch (var_value(s, *i)) {
        case var1: // l_True: 
            break;
        case varX: // l_Undef
            sat_solver_decision(s, *i);
            if (sat_solver_propagate(s) == 0)
                break;
            // fallthrough
        case var0: // l_False 
            sat_solver_canceluntil(s, 0);
            return l_False;
        }
    }
    s->root_level = sat_solver_dl(s);
#endif

    status = sat_solver_solve_internal(s);

Alan Mishchenko committed
2121
    sat_solver_canceluntil(s,0);
2122
    s->root_level = 0;
Alan Mishchenko committed
2123 2124

    ////////////////////////////////////////////////
Alan Mishchenko committed
2125
    if ( status == l_False && s->pStore )
Alan Mishchenko committed
2126
    {
2127
        int RetValue = Sto_ManAddClause( (Sto_Man_t *)s->pStore, NULL, NULL );
Alan Mishchenko committed
2128
        assert( RetValue );
Alan Mishchenko committed
2129
        (void) RetValue;
Alan Mishchenko committed
2130 2131
    }
    ////////////////////////////////////////////////
Alan Mishchenko committed
2132 2133 2134
    return status;
}

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
// This LEXSAT procedure should be called with a set of literals (pLits, nLits),
// which defines both (1) variable order, and (2) assignment to begin search from.
// It retuns the LEXSAT assigment that is the same or larger than the given one.
// (It assumes that there is no smaller assignment than the one given!)
// The resulting assignment is returned in the same set of literals (pLits, nLits).
// It pushes/pops assumptions internally and will undo them before terminating.
int sat_solver_solve_lexsat( sat_solver* s, int * pLits, int nLits )
{
    int i, iLitFail = -1;
    lbool status;
    assert( nLits > 0 );
    // help the SAT solver by setting desirable polarity
    sat_solver_set_literal_polarity( s, pLits, nLits );
    // check if there exists a satisfying assignment
    status = sat_solver_solve_internal( s );
    if ( status != l_True ) // no assignment
        return status;
    // there is at least one satisfying assignment
    assert( status == l_True );
    // find the first mismatching literal
    for ( i = 0; i < nLits; i++ )
        if ( pLits[i] != sat_solver_var_literal(s, Abc_Lit2Var(pLits[i])) )
            break;
    if ( i == nLits ) // no mismatch - the current assignment is the minimum one!
        return l_True;
    // mismatch happens in literal i
    iLitFail = i;
    // create assumptions up to this literal (as in pLits) - including this literal!
    for ( i = 0; i <= iLitFail; i++ )
        if ( !sat_solver_push(s, pLits[i]) ) // can become UNSAT while adding the last assumption
            break;
    if ( i < iLitFail + 1 ) // the solver became UNSAT while adding assumptions
        status = l_False;
    else // solve under the assumptions
        status = sat_solver_solve_internal( s );
    if ( status == l_True )
    {
        // we proved that there is a sat assignment with literal (iLitFail) having polarity as in pLits
        // continue solving recursively
        if ( iLitFail + 1 < nLits )
            status = sat_solver_solve_lexsat( s, pLits + iLitFail + 1, nLits - iLitFail - 1 );
    }
    else if ( status == l_False )
    {
        // we proved that there is no assignment with iLitFail having polarity as in pLits
        assert( Abc_LitIsCompl(pLits[iLitFail]) ); // literal is 0 
        // (this assert may fail only if there is a sat assignment smaller than one originally given in pLits)
        // now we flip this literal (make it 1), change the last assumption
        // and contiue looking for the 000...0-assignment of other literals
        sat_solver_pop( s );
        pLits[iLitFail] = Abc_LitNot(pLits[iLitFail]);
        if ( !sat_solver_push(s, pLits[iLitFail]) )
            printf( "sat_solver_solve_lexsat(): A satisfying assignment should exist.\n" ); // because we know that the problem is satisfiable
        // update other literals to be 000...0
        for ( i = iLitFail + 1; i < nLits; i++ )
            pLits[i] = Abc_LitNot( Abc_LitRegular(pLits[i]) );
        // continue solving recursively
        if ( iLitFail + 1 < nLits )
            status = sat_solver_solve_lexsat( s, pLits + iLitFail + 1, nLits - iLitFail - 1 );
        else
            status = l_True;
    }
    // undo the assumptions
    for ( i = iLitFail; i >= 0; i-- )
        sat_solver_pop( s );
    return status;
}

2203 2204 2205 2206 2207 2208
// This procedure is called on a set of assumptions to minimize their number.
// The procedure relies on the fact that the current set of assumptions is UNSAT.  
// It receives and returns SAT solver without assumptions. It returns the number 
// of assumptions after minimization. The set of assumptions is returned in pLits.
int sat_solver_minimize_assumptions( sat_solver* s, int * pLits, int nLits, int nConfLimit )
{
2209
    int i, k, nLitsL, nLitsR, nResL, nResR, status;
2210 2211 2212
    if ( nLits == 1 )
    {
        // since the problem is UNSAT, we will try to solve it without assuming the last literal
2213
        // if the result is UNSAT, the last literal can be dropped; otherwise, it is needed
2214
        if ( nConfLimit ) s->nConfLimit = s->stats.conflicts + nConfLimit;
2215
        status = sat_solver_solve_internal( s );
2216
        //printf( "%c", status == l_False ? 'u' : 's' );
2217 2218 2219
        return (int)(status != l_False); // return 1 if the problem is not UNSAT
    }
    assert( nLits >= 2 );
2220 2221
    nLitsL = nLits / 2;
    nLitsR = nLits - nLitsL;
2222 2223 2224 2225 2226 2227 2228 2229
    // assume the left lits
    for ( i = 0; i < nLitsL; i++ )
        if ( !sat_solver_push(s, pLits[i]) )
        {
            for ( k = i; k >= 0; k-- )
                sat_solver_pop(s);
            return sat_solver_minimize_assumptions( s, pLits, i+1, nConfLimit );
        }
2230 2231 2232 2233 2234 2235 2236 2237 2238
    // solve with these assumptions
    if ( nConfLimit ) s->nConfLimit = s->stats.conflicts + nConfLimit;
    status = sat_solver_solve_internal( s );
    if ( status == l_False ) // these are enough
    {
        for ( i = 0; i < nLitsL; i++ )
            sat_solver_pop(s);
        return sat_solver_minimize_assumptions( s, pLits, nLitsL, nConfLimit );
    }
2239
    // solve for the right lits
2240
    nResL = nLitsR == 1 ? 1 : sat_solver_minimize_assumptions( s, pLits + nLitsL, nLitsR, nConfLimit );
2241 2242 2243
    for ( i = 0; i < nLitsL; i++ )
        sat_solver_pop(s);
    // swap literals
2244
//    assert( nResL <= nLitsL );
2245 2246 2247 2248 2249
//    for ( i = 0; i < nResL; i++ )
//        ABC_SWAP( int, pLits[i], pLits[nLitsL+i] );
    veci_resize( &s->temp_clause, 0 );
    for ( i = 0; i < nLitsL; i++ )
        veci_push( &s->temp_clause, pLits[i] );
2250
    for ( i = 0; i < nResL; i++ )
2251 2252 2253
        pLits[i] = pLits[nLitsL+i];
    for ( i = 0; i < nLitsL; i++ )
        pLits[nResL+i] = veci_begin(&s->temp_clause)[i];
2254 2255 2256 2257 2258 2259 2260 2261
    // assume the right lits
    for ( i = 0; i < nResL; i++ )
        if ( !sat_solver_push(s, pLits[i]) )
        {
            for ( k = i; k >= 0; k-- )
                sat_solver_pop(s);
            return sat_solver_minimize_assumptions( s, pLits, i+1, nConfLimit );
        }
2262 2263 2264 2265 2266 2267 2268 2269 2270
    // solve with these assumptions
    if ( nConfLimit ) s->nConfLimit = s->stats.conflicts + nConfLimit;
    status = sat_solver_solve_internal( s );
    if ( status == l_False ) // these are enough
    {
        for ( i = 0; i < nResL; i++ )
            sat_solver_pop(s);
        return nResL;
    }
2271
    // solve for the left lits
2272
    nResR = nLitsL == 1 ? 1 : sat_solver_minimize_assumptions( s, pLits + nResL, nLitsL, nConfLimit );
2273 2274 2275 2276 2277
    for ( i = 0; i < nResL; i++ )
        sat_solver_pop(s);
    return nResL + nResR;
}

2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
// This is a specialized version of the above procedure with several custom changes:
// - makes sure that at least one of the marked literals is preserved in the clause
// - sets literals to zero when they do not have to be used
// - sets literals to zero for disproved variables
int sat_solver_minimize_assumptions2( sat_solver* s, int * pLits, int nLits, int nConfLimit )
{
    int i, k, nLitsL, nLitsR, nResL, nResR;
    if ( nLits == 1 )
    {
        // since the problem is UNSAT, we will try to solve it without assuming the last literal
        // if the result is UNSAT, the last literal can be dropped; otherwise, it is needed
        int RetValue = 1, LitNot = Abc_LitNot(pLits[0]);
        int status = l_False;
        int Temp = s->nConfLimit; 
        s->nConfLimit = nConfLimit;

        RetValue = sat_solver_push( s, LitNot ); assert( RetValue );
        status = sat_solver_solve_internal( s );
        sat_solver_pop( s );

        // if the problem is UNSAT, add clause
        if ( status == l_False )
        {
            RetValue = sat_solver_addclause( s, &LitNot, &LitNot+1 );
            assert( RetValue );
        }

        s->nConfLimit = Temp;
        return (int)(status != l_False); // return 1 if the problem is not UNSAT
    }
    assert( nLits >= 2 );
    nLitsL = nLits / 2;
    nLitsR = nLits - nLitsL;
    // assume the left lits
    for ( i = 0; i < nLitsL; i++ )
        if ( !sat_solver_push(s, pLits[i]) )
        {
            for ( k = i; k >= 0; k-- )
                sat_solver_pop(s);

            // add clauses for these literal
            for ( k = i+1; k > nLitsL; k++ )
            {
                int LitNot = Abc_LitNot(pLits[i]);
                int RetValue = sat_solver_addclause( s, &LitNot, &LitNot+1 );
                assert( RetValue );
            }

            return sat_solver_minimize_assumptions2( s, pLits, i+1, nConfLimit );
        }
    // solve for the right lits
    nResL = sat_solver_minimize_assumptions2( s, pLits + nLitsL, nLitsR, nConfLimit );
    for ( i = 0; i < nLitsL; i++ )
        sat_solver_pop(s);
    // swap literals
//    assert( nResL <= nLitsL );
    veci_resize( &s->temp_clause, 0 );
    for ( i = 0; i < nLitsL; i++ )
        veci_push( &s->temp_clause, pLits[i] );
    for ( i = 0; i < nResL; i++ )
        pLits[i] = pLits[nLitsL+i];
    for ( i = 0; i < nLitsL; i++ )
        pLits[nResL+i] = veci_begin(&s->temp_clause)[i];
    // assume the right lits
    for ( i = 0; i < nResL; i++ )
        if ( !sat_solver_push(s, pLits[i]) )
        {
            for ( k = i; k >= 0; k-- )
                sat_solver_pop(s);

            // add clauses for these literal
            for ( k = i+1; k > nResL; k++ )
            {
                int LitNot = Abc_LitNot(pLits[i]);
                int RetValue = sat_solver_addclause( s, &LitNot, &LitNot+1 );
                assert( RetValue );
            }

            return sat_solver_minimize_assumptions2( s, pLits, i+1, nConfLimit );
        }
    // solve for the left lits
    nResR = sat_solver_minimize_assumptions2( s, pLits + nResL, nLitsL, nConfLimit );
    for ( i = 0; i < nResL; i++ )
        sat_solver_pop(s);
    return nResL + nResR;
}


Alan Mishchenko committed
2366 2367 2368 2369 2370 2371 2372 2373 2374

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


int sat_solver_nclauses(sat_solver* s)
{
2375
    return s->stats.clauses;
Alan Mishchenko committed
2376 2377 2378 2379 2380 2381 2382 2383 2384
}


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

//=================================================================================================
Alan Mishchenko committed
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
// 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 )
{
2395
    if ( s->pStore ) Sto_ManDumpClauses( (Sto_Man_t *)s->pStore, pFileName );
Alan Mishchenko committed
2396 2397 2398 2399
}

void sat_solver_store_free( sat_solver * s )
{
2400
    if ( s->pStore ) Sto_ManFree( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
2401 2402
    s->pStore = NULL;
}
Alan Mishchenko committed
2403 2404 2405

int sat_solver_store_change_last( sat_solver * s )
{
2406
    if ( s->pStore ) return Sto_ManChangeLastClause( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
2407 2408
    return -1;
}
Alan Mishchenko committed
2409
 
Alan Mishchenko committed
2410 2411
void sat_solver_store_mark_roots( sat_solver * s )
{
2412
    if ( s->pStore ) Sto_ManMarkRoots( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
2413 2414 2415 2416
}

void sat_solver_store_mark_clauses_a( sat_solver * s )
{
2417
    if ( s->pStore ) Sto_ManMarkClausesA( (Sto_Man_t *)s->pStore );
Alan Mishchenko committed
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
}

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
2430

2431 2432
ABC_NAMESPACE_IMPL_END