AbcGlucose.cpp 49.4 KB
Newer Older
1 2 3 4 5 6
/**CFile****************************************************************

  FileName    [AbcGlucose.cpp]

  SystemName  [ABC: Logic synthesis and verification system.]

7
  PackageName [SAT solver Glucose 3.0 by Gilles Audemard and Laurent Simon.]
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

  Synopsis    [Interface to Glucose.]

  Author      [Alan Mishchenko]
  
  Affiliation [UC Berkeley]

  Date        [Ver. 1.0. Started - September 6, 2017.]

  Revision    [$Id: AbcGlucose.cpp,v 1.00 2005/06/20 00:00:00 alanmi Exp $]

***********************************************************************/

#include "sat/glucose/System.h"
#include "sat/glucose/ParseUtils.h"
#include "sat/glucose/Options.h"
#include "sat/glucose/Dimacs.h"
#include "sat/glucose/SimpSolver.h"

#include "sat/glucose/AbcGlucose.h"

29
#include "base/abc/abc.h"
30 31
#include "aig/gia/gia.h"
#include "sat/cnf/cnf.h"
32
#include "misc/extra/extra.h"
33 34 35

ABC_NAMESPACE_IMPL_START

36
using namespace Gluco;
37 38 39 40 41

////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////

42
#define USE_SIMP_SOLVER 1
43

44 45 46 47
////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

48 49
#ifdef USE_SIMP_SOLVER
    
50 51 52 53 54 55 56 57 58 59 60
/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
61
SimpSolver * glucose_solver_start()
62
{
63
    SimpSolver * S = new SimpSolver;
64 65 66 67
    S->setIncrementalMode();
    return S;
}

68
void glucose_solver_stop(Gluco::SimpSolver* S)
69 70 71 72
{
    delete S;
}

73 74 75 76 77
void glucose_solver_reset(Gluco::SimpSolver* S)
{
    S->reset();
}

78
int glucose_solver_addclause(Gluco::SimpSolver* S, int * plits, int nlits)
79 80 81 82 83 84 85 86 87 88 89 90 91 92
{
    vec<Lit> lits;
    for ( int i = 0; i < nlits; i++,plits++)
    {
        // note: Glucose uses the same var->lit conventiaon as ABC
        while ((*plits)/2 >= S->nVars()) S->newVar();
        assert((*plits)/2 < S->nVars()); // NOTE: since we explicitely use new function bmc_add_var
        Lit p;
        p.x = *plits;
        lits.push(p);
    }
    return S->addClause(lits); // returns 0 if the problem is UNSAT
}

93
void glucose_solver_setcallback(Gluco::SimpSolver* S, void * pman, int(*pfunc)(void*, int, int*))
94 95 96 97 98 99
{
    S->pCnfMan = pman;
    S->pCnfFunc = pfunc;
    S->nCallConfl = 1000;
}

100
int glucose_solver_solve(Gluco::SimpSolver* S, int * plits, int nlits)
101 102 103 104 105 106 107 108
{
    vec<Lit> lits;
    for (int i=0;i<nlits;i++,plits++)
    {
        Lit p;
        p.x = *plits;
        lits.push(p);
    }
109
    Gluco::lbool res = S->solveLimited(lits, 0);
110 111 112
    return (res == l_True ? 1 : res == l_False ? -1 : 0);
}

113
int glucose_solver_addvar(Gluco::SimpSolver* S)
114 115 116 117 118
{
    S->newVar();
    return S->nVars() - 1;
}

119 120 121 122 123
int * glucose_solver_read_cex(Gluco::SimpSolver* S )
{
    return S->getCex();
}

124
int glucose_solver_read_cex_varvalue(Gluco::SimpSolver* S, int ivar)
125 126 127 128
{
    return S->model[ivar] == l_True;
}

129
void glucose_solver_setstop(Gluco::SimpSolver* S, int * pstop)
130 131 132 133 134 135 136
{
    S->pstop = pstop;
}


/**Function*************************************************************

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  Synopsis    [Wrapper APIs to calling from ABC.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
bmcg_sat_solver * bmcg_sat_solver_start() 
{
    return (bmcg_sat_solver *)glucose_solver_start();
}
void bmcg_sat_solver_stop(bmcg_sat_solver* s)
{
152
    glucose_solver_stop((Gluco::SimpSolver*)s);
153
}
154 155 156 157 158
void bmcg_sat_solver_reset(bmcg_sat_solver* s)
{
    glucose_solver_reset((Gluco::SimpSolver*)s);
}

159 160 161

int bmcg_sat_solver_addclause(bmcg_sat_solver* s, int * plits, int nlits)
{
162
    return glucose_solver_addclause((Gluco::SimpSolver*)s,plits,nlits);
163 164 165 166
}

void bmcg_sat_solver_setcallback(bmcg_sat_solver* s, void * pman, int(*pfunc)(void*, int, int*))
{
167
    glucose_solver_setcallback((Gluco::SimpSolver*)s,pman,pfunc);
168 169 170 171
}

int bmcg_sat_solver_solve(bmcg_sat_solver* s, int * plits, int nlits)
{
172
    return glucose_solver_solve((Gluco::SimpSolver*)s,plits,nlits);
173 174 175 176
}

int bmcg_sat_solver_final(bmcg_sat_solver* s, int ** ppArray)
{
177 178
    *ppArray = (int *)(Lit *)((Gluco::SimpSolver*)s)->conflict;
    return ((Gluco::SimpSolver*)s)->conflict.size();
179 180 181 182
}

int bmcg_sat_solver_addvar(bmcg_sat_solver* s)
{
183
    return glucose_solver_addvar((Gluco::SimpSolver*)s);
184 185 186 187 188 189 190 191 192 193 194
}

void bmcg_sat_solver_set_nvars( bmcg_sat_solver* s, int nvars )
{
    int i;
    for ( i = bmcg_sat_solver_varnum(s); i < nvars; i++ )
        bmcg_sat_solver_addvar(s);
}

int bmcg_sat_solver_eliminate( bmcg_sat_solver* s, int turn_off_elim )
{
195
//    return 1; 
196 197 198 199 200
    return ((Gluco::SimpSolver*)s)->eliminate(turn_off_elim != 0);
}

int bmcg_sat_solver_var_is_elim( bmcg_sat_solver* s, int v )
{
201
//    return 0; 
202
    return ((Gluco::SimpSolver*)s)->isEliminated(v);
203 204
}

205 206 207 208 209 210 211 212 213 214 215
void bmcg_sat_solver_var_set_frozen( bmcg_sat_solver* s, int v, int freeze )
{
    ((Gluco::SimpSolver*)s)->setFrozen(v, freeze != 0);
}

int bmcg_sat_solver_elim_varnum(bmcg_sat_solver* s)
{
//    return 0; 
    return ((Gluco::SimpSolver*)s)->eliminated_vars;
}

216 217 218 219
int * bmcg_sat_solver_read_cex(bmcg_sat_solver* s)
{
    return glucose_solver_read_cex((Gluco::SimpSolver*)s);
}
220 221
int bmcg_sat_solver_read_cex_varvalue(bmcg_sat_solver* s, int ivar)
{
222
    return glucose_solver_read_cex_varvalue((Gluco::SimpSolver*)s, ivar);
223 224
}

225
void bmcg_sat_solver_set_stop(bmcg_sat_solver* s, int * pstop)
226
{
227
    glucose_solver_setstop((Gluco::SimpSolver*)s, pstop);
228 229
}

230 231
abctime bmcg_sat_solver_set_runtime_limit(bmcg_sat_solver* s, abctime Limit)
{
232 233
    abctime nRuntimeLimit = ((Gluco::SimpSolver*)s)->nRuntimeLimit;
    ((Gluco::SimpSolver*)s)->nRuntimeLimit = Limit;
234 235 236 237 238 239
    return nRuntimeLimit;
}

void bmcg_sat_solver_set_conflict_budget(bmcg_sat_solver* s, int Limit)
{
    if ( Limit > 0 ) 
240
        ((Gluco::SimpSolver*)s)->setConfBudget( (int64_t)Limit );
241
    else 
242
        ((Gluco::SimpSolver*)s)->budgetOff();
243 244
}

245 246
int bmcg_sat_solver_varnum(bmcg_sat_solver* s)
{
247
    return ((Gluco::SimpSolver*)s)->nVars();
248 249 250
}
int bmcg_sat_solver_clausenum(bmcg_sat_solver* s)
{
251
    return ((Gluco::SimpSolver*)s)->nClauses();
252 253 254
}
int bmcg_sat_solver_learntnum(bmcg_sat_solver* s)
{
255
    return ((Gluco::SimpSolver*)s)->nLearnts();
256 257 258
}
int bmcg_sat_solver_conflictnum(bmcg_sat_solver* s)
{
259
    return ((Gluco::SimpSolver*)s)->conflicts;
260 261
}

262
int bmcg_sat_solver_minimize_assumptions( bmcg_sat_solver * s, int * plits, int nlits, int pivot )
263
{
264
    vec<int>*array = &((Gluco::SimpSolver*)s)->user_vec;
265
    int i, nlitsL, nlitsR, nresL, nresR, status;
266 267 268 269
    assert( pivot >= 0 );
//    assert( nlits - pivot >= 2 );
    assert( nlits - pivot >= 1 );
    if ( nlits - pivot == 1 )
270 271 272
    {
        // since the problem is UNSAT, we try to solve it without assuming the last literal
        // if the result is UNSAT, the last literal can be dropped; otherwise, it is needed
273 274
        status = bmcg_sat_solver_solve( s, plits, pivot );
        return status != GLUCOSE_UNSAT; // return 1 if the problem is not UNSAT
275
    }
276 277 278 279
    assert( nlits - pivot >= 2 );
    nlitsL = (nlits - pivot) / 2;
    nlitsR = (nlits - pivot) - nlitsL;
    assert( nlitsL + nlitsR == nlits - pivot );
280
    // solve with these assumptions
281 282 283
    status = bmcg_sat_solver_solve( s, plits, pivot + nlitsL );
    if ( status == GLUCOSE_UNSAT ) // these are enough
        return bmcg_sat_solver_minimize_assumptions( s, plits, pivot + nlitsL, pivot );
284 285
    // these are not enough
    // solve for the right lits
286 287
//    nResL = nLitsR == 1 ? 1 : sat_solver_minimize_assumptions( s, pLits + nLitsL, nLitsR, nConfLimit );
    nresL = nlitsR == 1 ? 1 : bmcg_sat_solver_minimize_assumptions( s, plits, nlits, pivot + nlitsL );
288 289 290
    // swap literals
    array->clear();
    for ( i = 0; i < nlitsL; i++ )
291
        array->push(plits[pivot + i]);
292
    for ( i = 0; i < nresL; i++ )
293
        plits[pivot + i] = plits[pivot + nlitsL + i];
294
    for ( i = 0; i < nlitsL; i++ )
295
        plits[pivot + nresL + i] = (*array)[i];
296
    // solve with these assumptions
297 298
    status = bmcg_sat_solver_solve( s, plits, pivot + nresL );
    if ( status == GLUCOSE_UNSAT ) // these are enough
299 300
        return nresL;
    // solve for the left lits
301 302
//    nResR = nLitsL == 1 ? 1 : sat_solver_minimize_assumptions( s, pLits + nResL, nLitsL, nConfLimit );
    nresR = nlitsL == 1 ? 1 : bmcg_sat_solver_minimize_assumptions( s, plits, pivot + nresL + nlitsL, pivot + nresL );
303 304 305
    return nresL + nresR;
}

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
int bmcg_sat_solver_add_and( bmcg_sat_solver * s, int iVar, int iVar0, int iVar1, int fCompl0, int fCompl1, int fCompl )
{
    int Lits[3];

    Lits[0] = Abc_Var2Lit( iVar, !fCompl );
    Lits[1] = Abc_Var2Lit( iVar0, fCompl0 );
    if ( !bmcg_sat_solver_addclause( s, Lits, 2 ) )
        return 0;

    Lits[0] = Abc_Var2Lit( iVar, !fCompl );
    Lits[1] = Abc_Var2Lit( iVar1, fCompl1 );
    if ( !bmcg_sat_solver_addclause( s, Lits, 2 ) )
        return 0;

    Lits[0] = Abc_Var2Lit( iVar,   fCompl );
    Lits[1] = Abc_Var2Lit( iVar0, !fCompl0 );
    Lits[2] = Abc_Var2Lit( iVar1, !fCompl1 );
    if ( !bmcg_sat_solver_addclause( s, Lits, 3 ) )
        return 0;

    return 1;
}
328

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
int bmcg_solver_add_xor( bmcg_sat_solver * pSat, int iVarA, int iVarB, int iVarC, int fCompl )
{
    int Lits[3];
    int Cid;
    assert( iVarA >= 0 && iVarB >= 0 && iVarC >= 0 );

    Lits[0] = Abc_Var2Lit( iVarA, !fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 1 );
    Lits[2] = Abc_Var2Lit( iVarC, 1 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );

    Lits[0] = Abc_Var2Lit( iVarA, !fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 0 );
    Lits[2] = Abc_Var2Lit( iVarC, 0 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );

    Lits[0] = Abc_Var2Lit( iVarA, fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 1 );
    Lits[2] = Abc_Var2Lit( iVarC, 0 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );

    Lits[0] = Abc_Var2Lit( iVarA, fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 0 );
    Lits[2] = Abc_Var2Lit( iVarC, 1 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );
    return 4;
}

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
int bmcg_sat_solver_jftr(bmcg_sat_solver* s)
{
    return ((Gluco::SimpSolver*)s)->jftr;
}

void bmcg_sat_solver_set_jftr(bmcg_sat_solver* s, int jftr)
{
    ((Gluco::SimpSolver*)s)->jftr = jftr;
}

void bmcg_sat_solver_set_var_fanin_lit(bmcg_sat_solver* s, int var, int lit0, int lit1)
{
    ((Gluco::SimpSolver*)s)->sat_solver_set_var_fanin_lit(var, lit0, lit1);
}

void bmcg_sat_solver_start_new_round(bmcg_sat_solver* s)
{
    ((Gluco::SimpSolver*)s)->sat_solver_start_new_round();
}

void bmcg_sat_solver_mark_cone(bmcg_sat_solver* s, int var)
{
    ((Gluco::SimpSolver*)s)->sat_solver_mark_cone(var);
}


387 388 389 390 391 392 393 394 395 396 397 398 399
#else

/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
400
Solver * glucose_solver_start()
401 402 403 404 405 406 407 408 409 410 411
{
    Solver * S = new Solver;
    S->setIncrementalMode();
    return S;
}

void glucose_solver_stop(Gluco::Solver* S)
{
    delete S;
}

412 413 414 415 416
void glucose_solver_reset(Gluco::Solver* S)
{
    S->reset();
}

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
int glucose_solver_addclause(Gluco::Solver* S, int * plits, int nlits)
{
    vec<Lit> lits;
    for ( int i = 0; i < nlits; i++,plits++)
    {
        // note: Glucose uses the same var->lit conventiaon as ABC
        while ((*plits)/2 >= S->nVars()) S->newVar();
        assert((*plits)/2 < S->nVars()); // NOTE: since we explicitely use new function bmc_add_var
        Lit p;
        p.x = *plits;
        lits.push(p);
    }
    return S->addClause(lits); // returns 0 if the problem is UNSAT
}

void glucose_solver_setcallback(Gluco::Solver* S, void * pman, int(*pfunc)(void*, int, int*))
{
    S->pCnfMan = pman;
    S->pCnfFunc = pfunc;
    S->nCallConfl = 1000;
}

int glucose_solver_solve(Gluco::Solver* S, int * plits, int nlits)
{
    vec<Lit> lits;
    for (int i=0;i<nlits;i++,plits++)
    {
        Lit p;
        p.x = *plits;
        lits.push(p);
    }
    Gluco::lbool res = S->solveLimited(lits);
    return (res == l_True ? 1 : res == l_False ? -1 : 0);
}

int glucose_solver_addvar(Gluco::Solver* S)
{
    S->newVar();
    return S->nVars() - 1;
}

458 459 460 461 462
int * glucose_solver_read_cex(Gluco::Solver* S )
{
    return S->getCex();
}

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
int glucose_solver_read_cex_varvalue(Gluco::Solver* S, int ivar)
{
    return S->model[ivar] == l_True;
}

void glucose_solver_setstop(Gluco::Solver* S, int * pstop)
{
    S->pstop = pstop;
}


/**Function*************************************************************

  Synopsis    [Wrapper APIs to calling from ABC.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
bmcg_sat_solver * bmcg_sat_solver_start() 
{
    return (bmcg_sat_solver *)glucose_solver_start();
}
void bmcg_sat_solver_stop(bmcg_sat_solver* s)
{
    glucose_solver_stop((Gluco::Solver*)s);
}
493 494 495 496
void bmcg_sat_solver_reset(bmcg_sat_solver* s)
{
    glucose_solver_reset((Gluco::Solver*)s);
}
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

int bmcg_sat_solver_addclause(bmcg_sat_solver* s, int * plits, int nlits)
{
    return glucose_solver_addclause((Gluco::Solver*)s,plits,nlits);
}

void bmcg_sat_solver_setcallback(bmcg_sat_solver* s, void * pman, int(*pfunc)(void*, int, int*))
{
    glucose_solver_setcallback((Gluco::Solver*)s,pman,pfunc);
}

int bmcg_sat_solver_solve(bmcg_sat_solver* s, int * plits, int nlits)
{
    return glucose_solver_solve((Gluco::Solver*)s,plits,nlits);
}

int bmcg_sat_solver_final(bmcg_sat_solver* s, int ** ppArray)
{
    *ppArray = (int *)(Lit *)((Gluco::Solver*)s)->conflict;
    return ((Gluco::Solver*)s)->conflict.size();
}

int bmcg_sat_solver_addvar(bmcg_sat_solver* s)
{
    return glucose_solver_addvar((Gluco::Solver*)s);
}

void bmcg_sat_solver_set_nvars( bmcg_sat_solver* s, int nvars )
{
    int i;
    for ( i = bmcg_sat_solver_varnum(s); i < nvars; i++ )
        bmcg_sat_solver_addvar(s);
}

int bmcg_sat_solver_eliminate( bmcg_sat_solver* s, int turn_off_elim )
{
    return 1; 
534
//    return ((Gluco::SimpSolver*)s)->eliminate(turn_off_elim != 0);
535 536 537 538 539
}

int bmcg_sat_solver_var_is_elim( bmcg_sat_solver* s, int v )
{
    return 0; 
540 541 542 543 544 545 546 547 548 549 550 551
//    return ((Gluco::SimpSolver*)s)->isEliminated(v);
}

void bmcg_sat_solver_var_set_frozen( bmcg_sat_solver* s, int v, int freeze )
{
//    ((Gluco::SimpSolver*)s)->setFrozen(v, freeze);
}

int bmcg_sat_solver_elim_varnum(bmcg_sat_solver* s)
{
    return 0;
//    return ((Gluco::SimpSolver*)s)->eliminated_vars;
552 553
}

554 555 556 557 558
int * bmcg_sat_solver_read_cex(bmcg_sat_solver* s)
{
    return glucose_solver_read_cex((Gluco::Solver*)s);
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
int bmcg_sat_solver_read_cex_varvalue(bmcg_sat_solver* s, int ivar)
{
    return glucose_solver_read_cex_varvalue((Gluco::Solver*)s, ivar);
}

void bmcg_sat_solver_set_stop(bmcg_sat_solver* s, int * pstop)
{
    glucose_solver_setstop((Gluco::Solver*)s, pstop);
}

abctime bmcg_sat_solver_set_runtime_limit(bmcg_sat_solver* s, abctime Limit)
{
    abctime nRuntimeLimit = ((Gluco::Solver*)s)->nRuntimeLimit;
    ((Gluco::Solver*)s)->nRuntimeLimit = Limit;
    return nRuntimeLimit;
}

void bmcg_sat_solver_set_conflict_budget(bmcg_sat_solver* s, int Limit)
{
    if ( Limit > 0 ) 
        ((Gluco::Solver*)s)->setConfBudget( (int64_t)Limit );
    else 
        ((Gluco::Solver*)s)->budgetOff();
}

int bmcg_sat_solver_varnum(bmcg_sat_solver* s)
{
    return ((Gluco::Solver*)s)->nVars();
}
int bmcg_sat_solver_clausenum(bmcg_sat_solver* s)
{
    return ((Gluco::Solver*)s)->nClauses();
}
int bmcg_sat_solver_learntnum(bmcg_sat_solver* s)
{
    return ((Gluco::Solver*)s)->nLearnts();
}
int bmcg_sat_solver_conflictnum(bmcg_sat_solver* s)
{
    return ((Gluco::Solver*)s)->conflicts;
}

601
int bmcg_sat_solver_minimize_assumptions( bmcg_sat_solver * s, int * plits, int nlits, int pivot )
602 603 604
{
    vec<int>*array = &((Gluco::Solver*)s)->user_vec;
    int i, nlitsL, nlitsR, nresL, nresR, status;
605 606 607 608
    assert( pivot >= 0 );
//    assert( nlits - pivot >= 2 );
    assert( nlits - pivot >= 1 );
    if ( nlits - pivot == 1 )
609 610 611
    {
        // since the problem is UNSAT, we try to solve it without assuming the last literal
        // if the result is UNSAT, the last literal can be dropped; otherwise, it is needed
612 613
        status = bmcg_sat_solver_solve( s, plits, pivot );
        return status != GLUCOSE_UNSAT; // return 1 if the problem is not UNSAT
614
    }
615 616 617 618
    assert( nlits - pivot >= 2 );
    nlitsL = (nlits - pivot) / 2;
    nlitsR = (nlits - pivot) - nlitsL;
    assert( nlitsL + nlitsR == nlits - pivot );
619
    // solve with these assumptions
620 621 622
    status = bmcg_sat_solver_solve( s, plits, pivot + nlitsL );
    if ( status == GLUCOSE_UNSAT ) // these are enough
        return bmcg_sat_solver_minimize_assumptions( s, plits, pivot + nlitsL, pivot );
623 624
    // these are not enough
    // solve for the right lits
625 626
//    nResL = nLitsR == 1 ? 1 : sat_solver_minimize_assumptions( s, pLits + nLitsL, nLitsR, nConfLimit );
    nresL = nlitsR == 1 ? 1 : bmcg_sat_solver_minimize_assumptions( s, plits, nlits, pivot + nlitsL );
627 628 629
    // swap literals
    array->clear();
    for ( i = 0; i < nlitsL; i++ )
630
        array->push(plits[pivot + i]);
631
    for ( i = 0; i < nresL; i++ )
632
        plits[pivot + i] = plits[pivot + nlitsL + i];
633
    for ( i = 0; i < nlitsL; i++ )
634
        plits[pivot + nresL + i] = (*array)[i];
635
    // solve with these assumptions
636 637
    status = bmcg_sat_solver_solve( s, plits, pivot + nresL );
    if ( status == GLUCOSE_UNSAT ) // these are enough
638 639
        return nresL;
    // solve for the left lits
640 641
//    nResR = nLitsL == 1 ? 1 : sat_solver_minimize_assumptions( s, pLits + nResL, nLitsL, nConfLimit );
    nresR = nlitsL == 1 ? 1 : bmcg_sat_solver_minimize_assumptions( s, plits, pivot + nresL + nlitsL, pivot + nresL );
642 643 644
    return nresL + nresR;
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
int bmcg_sat_solver_add_and( bmcg_sat_solver * s, int iVar, int iVar0, int iVar1, int fCompl0, int fCompl1, int fCompl )
{
    int Lits[3];

    Lits[0] = Abc_Var2Lit( iVar, !fCompl );
    Lits[1] = Abc_Var2Lit( iVar0, fCompl0 );
    if ( !bmcg_sat_solver_addclause( s, Lits, 2 ) )
        return 0;

    Lits[0] = Abc_Var2Lit( iVar, !fCompl );
    Lits[1] = Abc_Var2Lit( iVar1, fCompl1 );
    if ( !bmcg_sat_solver_addclause( s, Lits, 2 ) )
        return 0;

    Lits[0] = Abc_Var2Lit( iVar,   fCompl );
    Lits[1] = Abc_Var2Lit( iVar0, !fCompl0 );
    Lits[2] = Abc_Var2Lit( iVar1, !fCompl1 );
    if ( !bmcg_sat_solver_addclause( s, Lits, 3 ) )
        return 0;

    return 1;
}

668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
int bmcg_solver_add_xor( bmcg_sat_solver * pSat, int iVarA, int iVarB, int iVarC, int fCompl )
{
    int Lits[3];
    int Cid;
    assert( iVarA >= 0 && iVarB >= 0 && iVarC >= 0 );

    Lits[0] = Abc_Var2Lit( iVarA, !fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 1 );
    Lits[2] = Abc_Var2Lit( iVarC, 1 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );

    Lits[0] = Abc_Var2Lit( iVarA, !fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 0 );
    Lits[2] = Abc_Var2Lit( iVarC, 0 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );

    Lits[0] = Abc_Var2Lit( iVarA, fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 1 );
    Lits[2] = Abc_Var2Lit( iVarC, 0 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );

    Lits[0] = Abc_Var2Lit( iVarA, fCompl );
    Lits[1] = Abc_Var2Lit( iVarB, 0 );
    Lits[2] = Abc_Var2Lit( iVarC, 1 );
    Cid = bmcg_sat_solver_addclause( pSat, Lits, 3 );
    assert( Cid );
    return 4;
}

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
int bmcg_sat_solver_jftr(bmcg_sat_solver* s)
{
    return ((Gluco::Solver*)s)->jftr;
}

void bmcg_sat_solver_set_jftr(bmcg_sat_solver* s, int jftr)
{
    ((Gluco::Solver*)s)->jftr = jftr;
}

void bmcg_sat_solver_set_var_fanin_lit(bmcg_sat_solver* s, int var, int lit0, int lit1)
{
    ((Gluco::Solver*)s)->sat_solver_set_var_fanin_lit(var, lit0, lit1);
}

void bmcg_sat_solver_start_new_round(bmcg_sat_solver* s)
{
    ((Gluco::Solver*)s)->sat_solver_start_new_round();
}

void bmcg_sat_solver_mark_cone(bmcg_sat_solver* s, int var)
{
    ((Gluco::Solver*)s)->sat_solver_mark_cone(var);
}

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
#endif


/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void glucose_print_stats(SimpSolver& s, abctime clk)
{
    double cpu_time = (double)(unsigned)clk / CLOCKS_PER_SEC;
    double mem_used = memUsed();
    printf("c restarts              : %d (%d conflicts on average)\n",         (int)s.starts, s.starts > 0 ? (int)(s.conflicts/s.starts) : 0);
    printf("c blocked restarts      : %d (multiple: %d) \n",                   (int)s.nbstopsrestarts, (int)s.nbstopsrestartssame);
    printf("c last block at restart : %d\n",                                   (int)s.lastblockatrestart);
    printf("c nb ReduceDB           : %-12d\n",                                (int)s.nbReduceDB);
    printf("c nb removed Clauses    : %-12d\n",                                (int)s.nbRemovedClauses);
    printf("c nb learnts DL2        : %-12d\n",                                (int)s.nbDL2);
    printf("c nb learnts size 2     : %-12d\n",                                (int)s.nbBin);
    printf("c nb learnts size 1     : %-12d\n",                                (int)s.nbUn);
    printf("c conflicts             : %-12d  (%.0f /sec)\n",                   (int)s.conflicts,    s.conflicts   /cpu_time);
    printf("c decisions             : %-12d  (%4.2f %% random) (%.0f /sec)\n", (int)s.decisions,    (float)s.rnd_decisions*100 / (float)s.decisions, s.decisions   /cpu_time);
    printf("c propagations          : %-12d  (%.0f /sec)\n",                   (int)s.propagations, s.propagations/cpu_time);
    printf("c conflict literals     : %-12d  (%4.2f %% deleted)\n",            (int)s.tot_literals, (s.max_literals - s.tot_literals)*100 / (double)s.max_literals);
    printf("c nb reduced Clauses    : %-12d\n", (int)s.nbReducedClauses);
    if (mem_used != 0) printf("Memory used           : %.2f MB\n", mem_used);
    //printf("c CPU time              : %.2f sec\n", cpu_time);
}

760 761
/**Function*************************************************************

762 763 764 765 766 767 768 769 770
  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
void Glucose_ReadDimacs( char * pFileName, SimpSolver& s )
{
    vec<Lit> * lits = &s.user_lits;
    char * pBuffer = Extra_FileReadContents( pFileName );
    char * pTemp; int fComp, Var, VarMax = 0;
    lits->clear();
    for ( pTemp = pBuffer; *pTemp; pTemp++ )
    {
        if ( *pTemp == 'c' || *pTemp == 'p' ) {
            while ( *pTemp != '\n' )
                pTemp++;
            continue;
        }
        while ( *pTemp == ' ' || *pTemp == '\t' || *pTemp == '\r' || *pTemp == '\n' )
            pTemp++;
        fComp = 0;
        if ( *pTemp == '-' )
            fComp = 1, pTemp++;
        if ( *pTemp == '+' )
            pTemp++;
        Var = atoi( pTemp );
        if ( Var == 0 ) {
            if ( lits->size() > 0 ) {
                s.addVar( VarMax );
                s.addClause(*lits);
                lits->clear();
            }
        }
        else {
            Var--;
            VarMax = Abc_MaxInt( VarMax, Var );
            lits->push( toLit(Abc_Var2Lit(Var, fComp)) );
        }
        while ( *pTemp >= '0' && *pTemp <= '9' )
            pTemp++;
    }
    ABC_FREE( pBuffer );
}

/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
821
void Glucose_SolveCnf( char * pFileName, Glucose_Pars * pPars, int fDumpCnf )
822 823
{
    abctime clk = Abc_Clock();
824

825 826 827 828
    SimpSolver  S;
    S.verbosity = pPars->verb;
    S.setConfBudget( pPars->nConfls > 0 ? (int64_t)pPars->nConfls : -1 );

829 830 831 832
//    gzFile in = gzopen(pFilename, "rb");
//    parse_DIMACS(in, S);
//    gzclose(in);
    Glucose_ReadDimacs( pFileName, S );
833

834 835 836 837 838 839 840
    if ( pPars->verb )
    {
        printf("c ============================[ Problem Statistics ]=============================\n");
        printf("c |                                                                             |\n");
        printf("c |  Number of variables:  %12d                                         |\n", S.nVars());
        printf("c |  Number of clauses:    %12d                                         |\n", S.nClauses());
    }
841
    
842 843 844 845 846
    if ( pPars->pre ) 
    {
        S.eliminate(true);
        printf( "c Simplication removed %d variables and %d clauses.  ", S.eliminated_vars, S.eliminated_clauses );
        Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
847 848 849 850 851 852 853 854 855

        if ( fDumpCnf )
        {
            char * pFileCnf = Extra_FileNameGenericAppend( pFileName, "_out.cnf" );
            S.toDimacs(pFileCnf);
            printf( "Finished dumping CNF after preprocessing into file \"%s\".\n", pFileCnf );
            printf( "SAT solving is not performed.\n" );
            return;
        }
856
    }
857 858

    vec<Lit> dummy;
859
    lbool ret = S.solveLimited(dummy, 0);
860 861
    if ( pPars->verb ) glucose_print_stats(S, Abc_Clock() - clk);
    printf(ret == l_True ? "SATISFIABLE" : ret == l_False ? "UNSATISFIABLE" : "INDETERMINATE");
862
    Abc_PrintTime( 1, "      Time", Abc_Clock() - clk );
863 864 865 866 867 868 869 870 871 872 873 874 875
}

/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
876
Vec_Int_t * Glucose_SolverFromAig( Gia_Man_t * p, SimpSolver& s )
877
{
878
    abctime clk = Abc_Clock();
879
    vec<Lit> * lits = &s.user_lits;
880
    Cnf_Dat_t * pCnf = (Cnf_Dat_t *)Mf_ManGenerateCnf( p, 8 /*nLutSize*/, 0 /*fCnfObjIds*/, 1/*fAddOrCla*/, 0, 0/*verbose*/ );
881
    for ( int i = 0; i < pCnf->nClauses; i++ )
882
    {
883 884 885 886
        lits->clear();
        for ( int * pLit = pCnf->pClauses[i]; pLit < pCnf->pClauses[i+1]; pLit++ )
            lits->push( toLit(*pLit) ), s.addVar( *pLit >> 1 );
        s.addClause(*lits);
887 888
    }
    Vec_Int_t * vCnfIds = Vec_IntAllocArrayCopy(pCnf->pVarNums,pCnf->nVars);
889 890 891 892 893 894 895 896 897 898 899 900 901 902
    printf( "CNF stats: Vars = %6d. Clauses = %7d. Literals = %8d. ", pCnf->nVars, pCnf->nClauses, pCnf->nLiterals );
    Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
    Cnf_DataFree(pCnf);
    return vCnfIds;
}

// procedure below does not work because glucose_solver_addclause() expects Solver
Vec_Int_t * Glucose_SolverFromAig2( Gia_Man_t * p, SimpSolver& S ) 
{
    Cnf_Dat_t * pCnf = (Cnf_Dat_t *)Mf_ManGenerateCnf( p, 8 /*nLutSize*/, 0 /*fCnfObjIds*/, 1/*fAddOrCla*/, 0, 0/*verbose*/ );
    for ( int i = 0; i < pCnf->nClauses; i++ )
        if ( !glucose_solver_addclause( &S, pCnf->pClauses[i], pCnf->pClauses[i+1]-pCnf->pClauses[i] ) )
            assert( 0 );
    Vec_Int_t * vCnfIds = Vec_IntAllocArrayCopy(pCnf->pVarNums,pCnf->nVars);
903 904 905 906 907 908
    //printf( "CNF stats: Vars = %6d. Clauses = %7d. Literals = %8d. ", pCnf->nVars, pCnf->nClauses, pCnf->nLiterals );
    //Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
    Cnf_DataFree(pCnf);
    return vCnfIds;
}

909 910 911 912 913 914 915 916 917 918 919 920 921


/**Function*************************************************************

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
922
Vec_Str_t * Glucose_GenerateCubes( bmcg_sat_solver * pSat[2], Vec_Int_t * vCiSatVars, Vec_Int_t * vVar2Index, int CubeLimit )
923
{
924
    int fCreatePrime = 1;
925
    int nCubes, nSupp = Vec_IntSize(vCiSatVars);
926
    Vec_Str_t * vSop  = Vec_StrAlloc( 1000 );
927 928 929
    Vec_Int_t * vLits = Vec_IntAlloc( nSupp );
    Vec_Str_t * vCube = Vec_StrAlloc( nSupp + 4 );
    Vec_StrFill( vCube, nSupp, '-' );
930
    Vec_StrPrintF( vCube, " 1\n\0" );
931
    for ( nCubes = 0; !CubeLimit || nCubes < CubeLimit; nCubes++ )
932
    {
933
        int * pFinal, nFinal, iVar, i, k = 0;
934 935
        // generate onset minterm
        int status = bmcg_sat_solver_solve( pSat[1], NULL, 0 );
936
        if ( status == GLUCOSE_UNSAT )
937
            break;
938
        assert( status == GLUCOSE_SAT );
939
        Vec_IntClear( vLits );
940
        Vec_IntForEachEntry( vCiSatVars, iVar, i )
941
            Vec_IntPush( vLits, Abc_Var2Lit(iVar, !bmcg_sat_solver_read_cex_varvalue(pSat[1], iVar)) );
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
        // expand against offset
        if ( fCreatePrime )
        {
            nFinal = bmcg_sat_solver_minimize_assumptions( pSat[0], Vec_IntArray(vLits), Vec_IntSize(vLits), 0 );
            Vec_IntShrink( vLits, nFinal );
            pFinal = Vec_IntArray( vLits );
            for ( i = 0; i < nFinal; i++ )
                pFinal[i] = Abc_LitNot(pFinal[i]);
        }
        else
        {
            status = bmcg_sat_solver_solve( pSat[0], Vec_IntArray(vLits), Vec_IntSize(vLits) );
            assert( status == GLUCOSE_UNSAT );
            nFinal = bmcg_sat_solver_final( pSat[0], &pFinal );
        }
957
        // print cube
958
        Vec_StrFill( vCube, nSupp, '-' );
959
        for ( i = 0; i < nFinal; i++ )
960
        {
961 962
            int Index = Vec_IntEntry(vVar2Index, Abc_Lit2Var(pFinal[i]));
            if ( Index == -1 )
963 964
                continue;
            pFinal[k++] = pFinal[i];
965 966
            assert( Index >= 0 && Index < nSupp );
            Vec_StrWriteEntry( vCube, Index, (char)('0' + Abc_LitIsCompl(pFinal[i])) );
967
        }
968
        nFinal = k;
969
        Vec_StrAppend( vSop, Vec_StrArray(vCube) );
970
        //printf( "%s\n", Vec_StrArray(vCube) );
971 972 973 974 975 976
        // add blocking clause
        if ( !bmcg_sat_solver_addclause( pSat[1], pFinal, nFinal ) )
            break;
    }
    Vec_IntFree( vLits );
    Vec_StrFree( vCube );
977 978 979
    Vec_StrPush( vSop, '\0' );
    return vSop;
}
980
Vec_Str_t * bmcg_sat_solver_sop( Gia_Man_t * p, int CubeLimit )
981 982 983 984 985
{
    bmcg_sat_solver * pSat[2] = { bmcg_sat_solver_start(), bmcg_sat_solver_start() };

    // generate CNF for the on-set and off-set
    Cnf_Dat_t * pCnf = (Cnf_Dat_t *)Mf_ManGenerateCnf( p, 8 /*nLutSize*/, 0 /*fCnfObjIds*/, 0/*fAddOrCla*/, 0, 0/*verbose*/ );
986
    int i, n, nVars = Gia_ManCiNum(p), Lit;//, Count = 0;
987 988 989 990 991 992 993 994 995 996
    int iFirstVar = pCnf->nVars - nVars;
    assert( Gia_ManCoNum(p) == 1 );
    for ( n = 0; n < 2; n++ )
    {
        bmcg_sat_solver_set_nvars( pSat[n], pCnf->nVars );
        Lit = Abc_Var2Lit( 1, !n );  // output variable is 1
        for ( i = 0; i < pCnf->nClauses; i++ )
            if ( !bmcg_sat_solver_addclause( pSat[n], pCnf->pClauses[i], pCnf->pClauses[i+1]-pCnf->pClauses[i] ) )
                assert( 0 );
        if ( !bmcg_sat_solver_addclause( pSat[n], &Lit, 1 ) )
997 998 999 1000 1001 1002
        {
            Vec_Str_t * vSop = Vec_StrAlloc( 10 );
            Vec_StrPrintF( vSop, " %d\n\0", !n );
            Cnf_DataFree( pCnf );
            return vSop;
        }
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    }
    Cnf_DataFree( pCnf );

    // collect cube vars and map SAT vars into them
    Vec_Int_t * vVars = Vec_IntAlloc( 100 ); 
    Vec_Int_t * vVarMap = Vec_IntStartFull( iFirstVar + nVars ); 
    for ( i = 0; i < nVars; i++ )
    {
        Vec_IntPush( vVars, iFirstVar+i );
        Vec_IntWriteEntry( vVarMap, iFirstVar+i, i );
    }

1015
    Vec_Str_t * vSop = Glucose_GenerateCubes( pSat, vVars, vVarMap, CubeLimit );
1016 1017 1018
    Vec_IntFree( vVarMap );
    Vec_IntFree( vVars );

1019 1020 1021 1022
    bmcg_sat_solver_stop( pSat[0] );
    bmcg_sat_solver_stop( pSat[1] );
    return vSop;
}
1023
void bmcg_sat_solver_print_sop( Gia_Man_t * p )
1024
{
1025
    Vec_Str_t * vSop = bmcg_sat_solver_sop( p, 0 );
1026 1027
    printf( "%s", Vec_StrArray(vSop) );
    Vec_StrFree( vSop );
1028
}
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
void bmcg_sat_solver_print_sop_lit( Gia_Man_t * p, int Lit )
{
    Vec_Int_t * vCisUsed = Vec_IntAlloc( 100 );
    int i, ObjId, iNode = Abc_Lit2Var( Lit );
    Gia_ManCollectCis( p, &iNode, 1, vCisUsed );
    Vec_IntSort( vCisUsed, 0 );
    Vec_IntForEachEntry( vCisUsed, ObjId, i )
        Vec_IntWriteEntry( vCisUsed, i, Gia_ManIdToCioId(p, ObjId) );
    Vec_IntPrint( vCisUsed );
    Gia_Man_t * pNew = Gia_ManDupConeSupp( p, Lit, vCisUsed );
    Vec_IntFree( vCisUsed );
    bmcg_sat_solver_print_sop( pNew );
    Gia_ManStop( pNew );
    printf( "\n" );
}
1044

1045 1046
/**Function*************************************************************

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
  Synopsis    [Computing d-literals.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
#define Gia_CubeForEachVar( pCube, Value, i )                                                      \
    for ( i = 0; (pCube[i] != ' ') && (Value = pCube[i]); i++ )           
#define Gia_SopForEachCube( pSop, nFanins, pCube )                                                 \
    for ( pCube = (pSop); *pCube; pCube += (nFanins) + 3 )

void bmcg_sat_generate_dvars( Vec_Int_t * vCiVars, Vec_Str_t * vSop, Vec_Int_t * vDLits )
{
    int i, Lit, Counter, nCubes = 0;
    char Value, * pCube, * pSop = Vec_StrArray( vSop );
    Vec_Int_t * vCounts = Vec_IntStart( 2*Vec_IntSize(vCiVars) );
    Vec_IntClear( vDLits );
    Gia_SopForEachCube( pSop, Vec_IntSize(vCiVars), pCube )
    {
        nCubes++;
        Gia_CubeForEachVar( pCube, Value, i )
        {
            if ( Value == '1' )
                Vec_IntAddToEntry( vCounts, 2*i, 1 );
            else if ( Value == '0' )
                Vec_IntAddToEntry( vCounts, 2*i+1, 1 );
        }
    }
    Vec_IntForEachEntry( vCounts, Counter, Lit )
        if ( Counter == nCubes )
            Vec_IntPush( vDLits, Abc_Var2Lit(Vec_IntEntry(vCiVars, Abc_Lit2Var(Lit)), Abc_LitIsCompl(Lit)) );
    Vec_IntSort( vDLits, 0 );
    Vec_IntFree( vCounts );
}

/**Function*************************************************************

1087 1088 1089 1090 1091 1092 1093 1094 1095
  Synopsis    [Performs SAT-based quantification.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1096
int bmcg_sat_solver_quantify2( Gia_Man_t * p, int iLit, int fHash, int(*pFuncCiToKeep)(void *, int), void * pData, Vec_Int_t * vDLits )
1097
{
1098
    int fSynthesize = 0;
1099 1100
    extern Gia_Man_t * Abc_SopSynthesizeOne( char * pSop, int fClp );
    Gia_Man_t * pMan, * pNew, * pTemp;  Vec_Str_t * vSop;
1101
    int i, CiId, ObjId, Res, nCubes = 0, nNodes, Count = 0, iNode = Abc_Lit2Var(iLit);
1102 1103
    Vec_Int_t * vCisUsed = Vec_IntAlloc( 100 );
    Gia_ManCollectCis( p, &iNode, 1, vCisUsed );
1104 1105 1106 1107
    Vec_IntSort( vCisUsed, 0 );
    if ( vDLits ) Vec_IntClear( vDLits );
    if ( iLit < 2 )
        return iLit;
1108 1109 1110 1111 1112 1113
    // remap into CI Ids
    Vec_IntForEachEntry( vCisUsed, ObjId, i )
        Vec_IntWriteEntry( vCisUsed, i, Gia_ManIdToCioId(p, ObjId) );
    // duplicate cone
    pNew = Gia_ManDupConeSupp( p, iLit, vCisUsed );
    assert( Gia_ManCiNum(pNew) == Vec_IntSize(vCisUsed) );
1114
    nNodes = Gia_ManAndNum(pNew);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

    // perform quantification one CI at a time
    assert( pFuncCiToKeep );
    Vec_IntForEachEntry( vCisUsed, CiId, i )
        if ( !pFuncCiToKeep( pData, CiId ) )
        {
            //printf( "Quantifying %d.\n", CiId );
            pNew = Gia_ManDupExist( pTemp = pNew, i );
            Gia_ManStop( pTemp );
            Count++;
        }
    if ( Gia_ManPoIsConst(pNew, 0) )
    {
        int RetValue = Gia_ManPoIsConst1(pNew, 0);
        Vec_IntFree( vCisUsed );
        Gia_ManStop( pNew );
        return RetValue;
    }

1134
    if ( fSynthesize )
1135
    {
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        vSop = bmcg_sat_solver_sop( pNew, 0 );
        Gia_ManStop( pNew );
        pMan = Abc_SopSynthesizeOne( Vec_StrArray(vSop), 1 );
        nCubes = Vec_StrCountEntry(vSop, '\n');
        if ( vDLits )
        {
            // convert into object IDs
            Vec_Int_t * vCisObjs = Vec_IntAlloc( Vec_IntSize(vCisUsed) );
            Vec_IntForEachEntry( vCisUsed, CiId, i )
                Vec_IntPush( vCisObjs, CiId + 1 );
            bmcg_sat_generate_dvars( vCisObjs, vSop, vDLits );
            Vec_IntFree( vCisObjs );
        }
        Vec_StrFree( vSop );

        if ( Gia_ManPoIsConst(pMan, 0) )
        {
            int RetValue = Gia_ManPoIsConst1(pMan, 0);
            Vec_IntFree( vCisUsed );
            Gia_ManStop( pMan );
            return RetValue;
        }
1158
    }
1159
    else
1160
    {
1161
        pMan = pNew;
1162 1163 1164
    }

    Res = Gia_ManDupConeBack( p, pMan, vCisUsed );
1165 1166

    // report the result
1167 1168 1169
    //printf( "Performed quantification with %5d nodes, %3d keep-vars, %3d quant-vars, resulting in %5d cubes and %5d nodes. ", 
    //    nNodes, Vec_IntSize(vCisUsed) - Count, Count, nCubes, Gia_ManAndNum(pMan) );
    //Abc_PrintTime( 1, "Time", Abc_Clock() - clkAll );
1170

1171 1172 1173
    Vec_IntFree( vCisUsed );
    Gia_ManStop( pMan );
    return Res;
1174 1175
}

1176

1177 1178
/**Function*************************************************************

1179 1180 1181 1182 1183 1184 1185 1186 1187
  Synopsis    [Performs SAT-based quantification.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1188
int Gia_ManSatAndCollect_rec( Gia_Man_t * p, int iObj, Vec_Int_t * vObjsUsed, Vec_Int_t * vCiVars )
1189 1190
{
    Gia_Obj_t * pObj; int iVar;
1191
    if ( (iVar = Gia_ObjCopyArray(p, iObj)) >= 0 )
1192 1193 1194 1195 1196
        return iVar;
    pObj = Gia_ManObj( p, iObj );
    assert( Gia_ObjIsCand(pObj) );
    if ( Gia_ObjIsAnd(pObj) )
    {
1197 1198
        Gia_ManSatAndCollect_rec( p, Gia_ObjFaninId0(pObj, iObj), vObjsUsed, vCiVars );
        Gia_ManSatAndCollect_rec( p, Gia_ObjFaninId1(pObj, iObj), vObjsUsed, vCiVars );
1199
    }
1200 1201 1202 1203 1204
    iVar = Vec_IntSize( vObjsUsed );
    Vec_IntPush( vObjsUsed, iObj );
    Gia_ObjSetCopyArray( p, iObj, iVar );
    if ( vCiVars && Gia_ObjIsCi(pObj) )
        Vec_IntPush( vCiVars, iVar );
1205 1206
    return iVar;
}                             
1207
void Gia_ManQuantLoadCnf( Gia_Man_t * p, Vec_Int_t * vObjsUsed, bmcg_sat_solver * pSats[] )
1208 1209
{
    Gia_Obj_t * pObj; int i;
1210 1211 1212
    bmcg_sat_solver_reset( pSats[0] );
    if ( pSats[1] )
    bmcg_sat_solver_reset( pSats[1] );
1213
    bmcg_sat_solver_set_nvars( pSats[0], Vec_IntSize(vObjsUsed) );
1214
    if ( pSats[1] )
1215 1216 1217 1218 1219 1220 1221 1222 1223
    bmcg_sat_solver_set_nvars( pSats[1], Vec_IntSize(vObjsUsed) );
    Gia_ManForEachObjVec( vObjsUsed, p, pObj, i ) 
        if ( Gia_ObjIsAnd(pObj) )
        {
            int iObj  = Gia_ObjId( p, pObj );
            int iVar  = Gia_ObjCopyArray(p, iObj);
            int iVar0 = Gia_ObjCopyArray(p, Gia_ObjFaninId0(pObj, iObj));
            int iVar1 = Gia_ObjCopyArray(p, Gia_ObjFaninId1(pObj, iObj));
            bmcg_sat_solver_add_and( pSats[0], iVar, iVar0, iVar1, Gia_ObjFaninC0(pObj), Gia_ObjFaninC1(pObj), 0 );
1224
            if ( pSats[1] )
1225 1226
            bmcg_sat_solver_add_and( pSats[1], iVar, iVar0, iVar1, Gia_ObjFaninC0(pObj), Gia_ObjFaninC1(pObj), 0 );
        }
1227 1228 1229 1230 1231 1232 1233 1234 1235
        else if ( Gia_ObjIsConst0(pObj) )
        {
            int Lit = Abc_Var2Lit( Gia_ObjCopyArray(p, 0), 1 );
            int RetValue = bmcg_sat_solver_addclause( pSats[0], &Lit, 1 );
            assert( RetValue );
            if ( pSats[1] )
            bmcg_sat_solver_addclause( pSats[1], &Lit, 1 );
            assert( Lit == 1 );
        }
1236 1237 1238
}
int Gia_ManFactorSop( Gia_Man_t * p, Vec_Int_t * vCiObjIds, Vec_Str_t * vSop, int fHash )
{
1239 1240
    extern Gia_Man_t * Abc_SopSynthesizeOne( char * pSop, int fClp );
    Gia_Man_t * pMan = Abc_SopSynthesizeOne( Vec_StrArray(vSop), 1 );
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    Gia_Obj_t * pObj; int i, Result;
    assert( Gia_ManPiNum(pMan) == Vec_IntSize(vCiObjIds) );
    Gia_ManConst0(pMan)->Value = 0;
    Gia_ManForEachPi( pMan, pObj, i )
        pObj->Value = Abc_Var2Lit( Vec_IntEntry(vCiObjIds, i), 0 );
    Gia_ManForEachAnd( pMan, pObj, i )
        if ( fHash )
            pObj->Value = Gia_ManHashAnd( p, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
        else
            pObj->Value = Gia_ManAppendAnd( p, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
    pObj = Gia_ManPo(pMan, 0);
    Result = Gia_ObjFanin0Copy(pObj);
    Gia_ManStop( pMan );
    return Result;
}
1256
int bmcg_sat_solver_quantify( bmcg_sat_solver * pSats[], Gia_Man_t * p, int iLit, int fHash, int(*pFuncCiToKeep)(void *, int), void * pData, Vec_Int_t * vDLits )
1257 1258 1259
{
    Vec_Int_t * vObjsUsed = Vec_IntAlloc( 100 ); // GIA objs
    Vec_Int_t * vCiVars = Vec_IntAlloc( 100 );   // CI SAT vars
1260
    Vec_Int_t * vVarMap = NULL; Vec_Str_t * vSop = NULL; 
1261
    int i, iVar, iVarLast, Lit, RetValue, Count = 0, Result = -1;
1262 1263 1264
    if ( vDLits ) Vec_IntClear( vDLits );
    if ( iLit < 2 )
        return iLit;
1265 1266 1267 1268
    if ( Vec_IntSize(&p->vCopies) < Gia_ManObjNum(p) )
        Vec_IntFillExtra( &p->vCopies, Gia_ManObjNum(p), -1 );
    // assign variable number 0 to const0 node
    iVar = Vec_IntSize(vObjsUsed); 
1269
    Vec_IntPush( vObjsUsed, 0 );
1270 1271
    Gia_ObjSetCopyArray( p, 0, iVar );
    assert( iVar == 0 );    
1272

1273 1274
    // collect other variables
    iVarLast = Gia_ManSatAndCollect_rec( p, Abc_Lit2Var(iLit), vObjsUsed, vCiVars );
1275
    Gia_ManQuantLoadCnf( p, vObjsUsed, pSats );
1276

1277 1278 1279
    // check constants
    Lit = Abc_Var2Lit( iVarLast, !Abc_LitIsCompl(iLit) ); 
    RetValue = bmcg_sat_solver_addclause( pSats[0], &Lit, 1 ); // offset
1280 1281 1282 1283 1284 1285
    if ( !RetValue || bmcg_sat_solver_solve(pSats[0], NULL, 0) == GLUCOSE_UNSAT )
    {
        Result = 1;
        goto cleanup;
    }
    Lit = Abc_Var2Lit( iVarLast, Abc_LitIsCompl(iLit) );
1286
    RetValue = bmcg_sat_solver_addclause( pSats[1], &Lit, 1 ); // onset
1287 1288 1289 1290 1291
    if ( !RetValue || bmcg_sat_solver_solve(pSats[1], NULL, 0) == GLUCOSE_UNSAT )
    {
        Result = 0;
        goto cleanup;
    }
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
/*
    // reorder CI SAT variables to have keep-vars first
    Vec_Int_t * vCiVars2 = Vec_IntAlloc( 100 );   // CI SAT vars
    Vec_IntForEachEntry( vCiVars, iVar, i )
    {
        Gia_Obj_t * pObj = Gia_ManObj( p, Vec_IntEntry(vObjsUsed, iVar) );
        assert( Gia_ObjIsCi(pObj) );
        if ( pFuncCiToKeep(pData, Gia_ObjCioId(pObj)) )
            Vec_IntPush( vCiVars2, iVar );
    }
    Vec_IntForEachEntry( vCiVars, iVar, i )
    {
        Gia_Obj_t * pObj = Gia_ManObj( p, Vec_IntEntry(vObjsUsed, iVar) );
        assert( Gia_ObjIsCi(pObj) );
        if ( !pFuncCiToKeep(pData, Gia_ObjCioId(pObj)) )
            Vec_IntPush( vCiVars2, iVar );
    }
    ABC_SWAP( Vec_Int_t *, vCiVars2, vCiVars );
    Vec_IntFree( vCiVars2 );
*/
1312
    // map CI SAT variables into their indexes used in the cubes
1313
    vVarMap = Vec_IntStartFull( Vec_IntSize(vObjsUsed) );
1314 1315 1316 1317 1318 1319 1320
    Vec_IntForEachEntry( vCiVars, iVar, i )
    {
        Gia_Obj_t * pObj = Gia_ManObj( p, Vec_IntEntry(vObjsUsed, iVar) );
        assert( Gia_ObjIsCi(pObj) );
        if ( pFuncCiToKeep(pData, Gia_ObjCioId(pObj)) )
            Vec_IntWriteEntry( vVarMap, iVar, i ), Count++;
    }
1321 1322 1323 1324 1325
    if ( Count == 0 || Count == Vec_IntSize(vCiVars) )
    {
        Result = Count == 0 ? 1 : iLit;
        goto cleanup;
    }
1326
    // generate cubes
1327
    vSop = Glucose_GenerateCubes( pSats, vCiVars, vVarMap, 0 );
1328 1329 1330 1331
    //printf( "%s", Vec_StrArray(vSop) );
    // convert into object IDs
    Vec_IntForEachEntry( vCiVars, iVar, i )
        Vec_IntWriteEntry( vCiVars, i, Vec_IntEntry(vObjsUsed, iVar) );
1332 1333 1334
    // generate unate variables
    if ( vDLits )
        bmcg_sat_generate_dvars( vCiVars, vSop, vDLits );
1335
    // convert into an AIG
1336
    RetValue = Gia_ManAndNum(p);
1337
    Result = Gia_ManFactorSop( p, vCiVars, vSop, fHash );
1338 1339

    // report the result
1340 1341 1342
//    printf( "Performed quantification with %5d nodes, %3d keep-vars, %3d quant-vars, resulting in %5d cubes and %5d nodes. ", 
//        Vec_IntSize(vObjsUsed), Count, Vec_IntSize(vCiVars) - Count, Vec_StrCountEntry(vSop, '\n'), Gia_ManAndNum(p)-RetValue );
//    Abc_PrintTime( 1, "Time", Abc_Clock() - clkAll );
1343

1344 1345 1346 1347
cleanup:
    Vec_IntForEachEntry( vObjsUsed, iVar, i )
        Gia_ObjSetCopyArray( p, iVar, -1 );
    Vec_IntFree( vObjsUsed );
1348
    Vec_IntFree( vCiVars );
1349 1350
    Vec_IntFreeP( &vVarMap );
    Vec_StrFreeP( &vSop );
1351
    return Result;
1352
}
1353
int Gia_ManCiIsToKeep( void * pData, int i )
1354
{
1355
    return i % 5 != 0;
1356 1357 1358
}
void Glucose_QuantifyAigTest( Gia_Man_t * p )
{
1359 1360 1361
    bmcg_sat_solver * pSats[3] = { bmcg_sat_solver_start(), bmcg_sat_solver_start(), bmcg_sat_solver_start() };

    abctime clk1 = Abc_Clock();
1362
    int iRes1 = bmcg_sat_solver_quantify( pSats, p, Gia_ObjFaninLit0p(p, Gia_ManPo(p, 0)), 0, Gia_ManCiIsToKeep, NULL, NULL );
1363 1364 1365
    abctime clk1d = Abc_Clock()-clk1;

    abctime clk2 = Abc_Clock();
1366
    int iRes2 = bmcg_sat_solver_quantify2( p, Gia_ObjFaninLit0p(p, Gia_ManPo(p, 0)), 0, Gia_ManCiIsToKeep, NULL, NULL );
1367
    abctime clk2d = Abc_Clock()-clk2;
1368

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    Abc_PrintTime( 1, "Time1", clk1d );
    Abc_PrintTime( 1, "Time2", clk2d );

    if ( bmcg_sat_solver_equiv_overlap_check( pSats[2], p, iRes1, iRes2, 1 ) )
        printf( "Verification passed.\n" );
    else
        printf( "Verification FAILED.\n" );

    Gia_ManAppendCo( p, iRes1 );
    Gia_ManAppendCo( p, iRes2 );
1379 1380 1381

    bmcg_sat_solver_stop( pSats[0] );
    bmcg_sat_solver_stop( pSats[1] );
1382
    bmcg_sat_solver_stop( pSats[2] );
1383
}
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
int bmcg_sat_solver_quantify_test( bmcg_sat_solver * pSats[], Gia_Man_t * p, int iLit, int fHash, int(*pFuncCiToKeep)(void *, int), void * pData, Vec_Int_t * vDLits )
{
    extern int Gia_ManQuantExist( Gia_Man_t * p, int iLit, int(*pFuncCiToKeep)(void *, int), void * pData );
    int Res1 = Gia_ManQuantExist( p, iLit, pFuncCiToKeep, pData );
    int Res2 = bmcg_sat_solver_quantify2( p, iLit, 1, pFuncCiToKeep, pData, NULL );

    bmcg_sat_solver * pSat = bmcg_sat_solver_start();
    if ( bmcg_sat_solver_equiv_overlap_check( pSat, p, Res1, Res2, 1 ) )
        printf( "Verification passed.\n" );
    else
    {
        printf( "Verification FAILED.\n" );
        bmcg_sat_solver_print_sop_lit( p, Res1 );
        bmcg_sat_solver_print_sop_lit( p, Res2 );
        printf( "\n" );
    }
    return Res1;
}
1402

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
/**Function*************************************************************

  Synopsis    [Checks equivalence or intersection of two nodes.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int bmcg_sat_solver_equiv_overlap_check( bmcg_sat_solver * pSat, Gia_Man_t * p, int iLit0, int iLit1, int fEquiv )
{
    bmcg_sat_solver * pSats[2] = { pSat, NULL };
    Vec_Int_t * vObjsUsed = Vec_IntAlloc( 100 ); 
    int i, iVar, iSatVar[2], iSatLit[2], Lits[2], status;
1419 1420 1421 1422 1423
    if ( Vec_IntSize(&p->vCopies) < Gia_ManObjNum(p) )
        Vec_IntFillExtra( &p->vCopies, Gia_ManObjNum(p), -1 );

    // assign const0 variable number 0
    iVar = Vec_IntSize(vObjsUsed);
1424
    Vec_IntPush( vObjsUsed, 0 );
1425 1426 1427 1428 1429
    Gia_ObjSetCopyArray( p, 0, iVar );
    assert( iVar == 0 );

    iSatVar[0] = Gia_ManSatAndCollect_rec( p, Abc_Lit2Var(iLit0), vObjsUsed, NULL );
    iSatVar[1] = Gia_ManSatAndCollect_rec( p, Abc_Lit2Var(iLit1), vObjsUsed, NULL );
1430

1431 1432 1433 1434 1435 1436
    iSatLit[0] = Abc_Var2Lit( iSatVar[0], Abc_LitIsCompl(iLit0) );
    iSatLit[1] = Abc_Var2Lit( iSatVar[1], Abc_LitIsCompl(iLit1) );
    Gia_ManQuantLoadCnf( p, vObjsUsed, pSats );
    Vec_IntForEachEntry( vObjsUsed, iVar, i )
        Gia_ObjSetCopyArray( p, iVar, -1 );
    Vec_IntFree( vObjsUsed );
1437

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    if ( fEquiv )
    {
        Lits[0] = iSatLit[0];
        Lits[1] = Abc_LitNot(iSatLit[1]);
        status  = bmcg_sat_solver_solve( pSats[0], Lits, 2 );
        if ( status == GLUCOSE_UNSAT )
        {
            Lits[0] = Abc_LitNot(iSatLit[0]);
            Lits[1] = iSatLit[1];
            status  = bmcg_sat_solver_solve( pSats[0], Lits, 2 );
        }
        return status == GLUCOSE_UNSAT;
    }
    else
    {
        Lits[0] = iSatLit[0];
        Lits[1] = iSatLit[1];
        status  = bmcg_sat_solver_solve( pSats[0], Lits, 2 );
        return status == GLUCOSE_SAT;
    }
}
void Glucose_CheckTwoNodesTest( Gia_Man_t * p )
{
    int n, Res;
    bmcg_sat_solver * pSat = bmcg_sat_solver_start();
    for ( n = 0; n < 2; n++ )
    {
        Res = bmcg_sat_solver_equiv_overlap_check( 
            pSat, p, 
            Gia_ObjFaninLit0p(p, Gia_ManPo(p, 0)), 
            Gia_ObjFaninLit0p(p, Gia_ManPo(p, 1)), 
            n );
        bmcg_sat_solver_reset( pSat );
        printf( "%s %s.\n", n ? "Equivalence" : "Overlap", Res ? "holds" : "fails" );
    }
    bmcg_sat_solver_stop( pSat );
}
1475 1476 1477

/**Function*************************************************************

1478 1479 1480 1481 1482 1483 1484 1485 1486
  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1487
int Glucose_SolveAig(Gia_Man_t * p, Glucose_Pars * pPars)
1488 1489 1490 1491 1492 1493 1494
{  
    abctime clk = Abc_Clock();

    SimpSolver S;
    S.verbosity = pPars->verb;
    S.verbEveryConflicts = 50000;
    S.showModel = false;
1495
    //S.verbosity = 2;
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    S.setConfBudget( pPars->nConfls > 0 ? (int64_t)pPars->nConfls : -1 );

    S.parsing = 1;
    Vec_Int_t * vCnfIds = Glucose_SolverFromAig(p,S);
    S.parsing = 0;

    if (pPars->verb)
    {
        printf("c ============================[ Problem Statistics ]=============================\n");
        printf("c |                                                                             |\n");
        printf("c |  Number of variables:  %12d                                         |\n", S.nVars());
        printf("c |  Number of clauses:    %12d                                         |\n", S.nClauses());
    }

    if (pPars->pre) 
1511
    {
1512
        S.eliminate(true);
1513 1514 1515
        printf( "c Simplication removed %d variables and %d clauses.  ", S.eliminated_vars, S.eliminated_clauses );
        Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
    }
1516 1517
    
    vec<Lit> dummy;
1518
    lbool ret = S.solveLimited(dummy, 0);
1519 1520 1521

    if ( pPars->verb ) glucose_print_stats(S, Abc_Clock() - clk);
    printf(ret == l_True ? "SATISFIABLE" : ret == l_False ? "UNSATISFIABLE" : "INDETERMINATE");
1522
    Abc_PrintTime( 1, "      Time", Abc_Clock() - clk );
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544

    // port counterexample
    if (ret == l_True)
    {
        Gia_Obj_t * pObj;  int i;
        p->pCexComb = Abc_CexAlloc(0,Gia_ManCiNum(p),1);
        Gia_ManForEachCi( p, pObj, i )
        {
            assert(Vec_IntEntry(vCnfIds,Gia_ObjId(p, pObj))!=-1);
            if (S.model[Vec_IntEntry(vCnfIds,Gia_ObjId(p, pObj))] == l_True)
                Abc_InfoSetBit( p->pCexComb->pData, i);
        }
    }
    Vec_IntFree(vCnfIds);
    return (ret == l_True ? 10 : ret == l_False ? 20 : 0);
}

////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////

ABC_NAMESPACE_IMPL_END