Exemple #1
0
void cmsat_add(CMSolver *solver, int32_t lit)
{
  if (lit == 0)
    {
      solver->cmsolver->add_clause(*(solver->adds));
      delete solver->adds;
      solver->adds = new std::vector<Lit>;
    }
  else
    {
      int32_t litnum;

      if (lit < 0)
        litnum = -lit;
      else
        litnum = lit;

      // do we need to allocate new variables?
      if (litnum >= solver->nVars)
        {
          int32_t new_vars = litnum - solver->cmsolver->nVars();
          solver->cmsolver->new_vars(new_vars + 1);
          solver->nVars = solver->cmsolver->nVars();
        }
      if (lit < 0)
        solver->adds->push_back(Lit(litnum, true));
      else
        solver->adds->push_back(Lit(litnum, false));
    }
}
Exemple #2
0
void cmsat_assume(CMSolver *solver, int32_t lit)
{
  if (lit < 0)
    solver->assumptions->push_back(Lit(-lit, true));
  else
    solver->assumptions->push_back(Lit(lit, false));
}
void SimpSMTSolver::initialize( )
{
  CoreSMTSolver::initialize( );

#ifdef PRODUCE_PROOF
  if ( config.sat_preprocess_booleans != 0
    || config.sat_preprocess_theory != 0 ) 
  {
    opensmt_warning( "disabling SATElite preprocessing to track proof" );
    use_simplification = false;
    config.sat_preprocess_booleans = 0;
    config.sat_preprocess_theory = 0;
  }
#else
  use_simplification = config.sat_preprocess_booleans != 0;
#endif

  // Add clauses for true/false
  // Useful for expressing TAtoms that are constantly true/false

  const Var var_True = newVar( );
  const Var var_False = newVar( );

  setFrozen( var_True, true );
  setFrozen( var_False, true );

  vec< Lit > clauseTrue, clauseFalse;
  clauseTrue.push( Lit( var_True ) );
  addClause( clauseTrue );
  clauseFalse.push( Lit( var_False, true ) );
  addClause( clauseFalse );

  theory_handler = new THandler( egraph, config, *this, trail, level, assigns, var_True, var_False );
}
Exemple #4
0
//
// Return the conflict generated by a theory solver
//
void THandler::getConflict ( vec< Lit > & conflict, int & max_decision_level )
{
  // First of all, the explanation in a tsolver is
  // stored as conjunction of enodes e1,...,en
  // with associated polarities p1,...,pn. Since the sat-solver
  // wants a clause we store it in the form ( l1 | ... | ln )
  // where li is the literal corresponding with ei with polarity !pi
  vector< Enode * > & explanation = core_solver.getConflict( );
  assert( !explanation.empty( ) );

  if ( config.certification_level > 0 )
    verifyExplanationWithExternalTool( explanation );

#ifdef PRODUCE_PROOF
  max_decision_level = -1;
  for ( vector< Enode * >::iterator it = explanation.begin( )
      ; it != explanation.end( )
      ; ++ it )
  {
    Enode * ei  = *it;
    assert( ei->hasPolarity( ) );
    assert( ei->getPolarity( ) == l_True
         || ei->getPolarity( ) == l_False );
    bool negate = ei->getPolarity( ) == l_False;

    Var v = enodeToVar( ei );
#if PEDANTIC_DEBUG
    assert( isOnTrail( Lit( v, negate ) ) );
#endif
    Lit l = Lit( v, !negate );
    conflict.push( l );

    if ( max_decision_level < level[ v ] )
      max_decision_level = level[ v ];
  }
  if ( config.produce_inter == 0 )
    explanation.clear( );
#else
  max_decision_level = -1;
  while ( !explanation.empty( ) )
  {
    Enode * ei  = explanation.back( );
    explanation.pop_back( );
    assert( ei->hasPolarity( ) );
    assert( ei->getPolarity( ) == l_True
         || ei->getPolarity( ) == l_False );
    bool negate = ei->getPolarity( ) == l_False;

    Var v = enodeToVar( ei );
#if PEDANTIC_DEBUG
    assert( isOnTrail( Lit( v, negate ) ) );
#endif
    Lit l = Lit( v, !negate );
    conflict.push( l );

    if ( max_decision_level < level[ v ] )
      max_decision_level = level[ v ];
  }
#endif
}
Exemple #5
0
void array_var_bool_element(IntVar* _x, vec<BoolView>& a, BoolView y, int offset) {
	_x->specialiseToEL();
	IntView<4> x(_x, 1, -offset);
	vec<Lit> ps1(a.size()+1);
	vec<Lit> ps2(a.size()+1);
	// Add clause !y \/ c_1 \/ ... \/ c_n
	// Add clause y \/ d_1 \/ ... \/ d_n
	ps1[0] = ~y;
	ps2[0] = y;
	for (int i = 0; i < a.size(); i++) {
		BoolView c_i(Lit(sat.newVar(),1));
		BoolView d_i(Lit(sat.newVar(),1));
		sat.addClause(~c_i, x = i);
		sat.addClause(~c_i, a[i]);
		sat.addClause(~d_i, x = i);
		sat.addClause(~d_i, ~a[i]);
		vec<Lit> ps3(3), ps4(3);
		ps3[0] = y; ps3[1] = ~a[i]; ps3[2] = (x != i);
		sat.addClause(ps3);
		ps4[0] = ~y; ps4[1] = a[i]; ps4[2] = (x != i);
		sat.addClause(ps4);
		ps1[i+1] = c_i;
		ps2[i+1] = d_i;
	}
	sat.addClause(ps1);
	sat.addClause(ps2);
}
Exemple #6
0
int getPredecessors(Solver& S, int attr_number, int num_var, int curr_depth) {
    vec<Lit> lits;

    int nBasins = 0;

    int i = num_var;
    
    while (i--){
      lits.push((global_var.Attractors[attr_number].states[0].c_str()[i]=='1')? Lit(i) : ~Lit(i));
      S.addClause(lits);
      lits.clear();
    }

    
    i = num_var;
    while (i--){
        lits.push((global_var.Attractors[attr_number].states[0].c_str()[i]=='1')? ~Lit(i+num_var) : Lit(i+num_var));
    }
    S.addClause(lits);
    lits.clear();
    
    while (1){
      if (!S.solve()) break;

      constrain_state(curr_depth-1, S.model, curr_depth-1, S, num_var);

      nBasins++;
    }

    return nBasins;
}
Exemple #7
0
/*Make state with index a from the stats_sequance not allowed in future solutions of S in position with index b */
void constrain_state(unsigned a, vec<lbool>& stats_sequance, unsigned b, Solver &S, unsigned number_var ){

  vec<Lit> lits;
  int a_tmp=a*number_var;
  int b_tmp=b*number_var;

  ASSERT( a_tmp+number_var <= stats_sequance.size() );
  ASSERT( b_tmp+number_var <= S.nVars() );

  while(number_var--){
    if (stats_sequance[a_tmp] != l_Undef){

#ifdef PRINT_STATE
	//printf( "%s", (stats_sequance[a_tmp]==l_True)?"1":"0");
#endif 
	
	    lits.push((stats_sequance[a_tmp]==l_True)?~Lit( b_tmp ):Lit( b_tmp ));
    }else{
	//printf("-");
    }
    a_tmp++;
    b_tmp++;
  }
  S.addClause(lits);

#ifdef PRINT_STATE
    //puts(" ");
#endif  
}
Exemple #8
0
      void constraints() {
        OKLIB_MODELS_CONCEPT_TAG(Lit, Literals);

        OKLIB_MODELS_CONCEPT_REQUIRES(Lit, BasicRequirements);
        OKLIB_MODELS_CONCEPT_TAG(Lit, BasicRequirements);
        OKLIB_MODELS_CONCEPT_REQUIRES(Lit, FullyConstructible);
        OKLIB_MODELS_CONCEPT_TAG(Lit, FullyConstructible);
        OKLIB_MODELS_CONCEPT_REQUIRES(Lit, EqualitySubstitutable);
        OKLIB_MODELS_CONCEPT_TAG(Lit, EqualitySubstitutable);
        OKLIB_MODELS_CONCEPT_REQUIRES(Lit, LinearOrder);
        OKLIB_MODELS_CONCEPT_TAG(Lit, LinearOrder);

        OKLIB_MODELS_CONCEPT_REQUIRES(var_type, Concepts::Variables);
        OKLIB_MODELS_CONCEPT_TAG(var_type, Concepts::Variables);
        OKLIB_MODELS_CONCEPT_REQUIRES(cond_type, Concepts::AtomicCondition);
        OKLIB_MODELS_CONCEPT_TAG(cond_type, Concepts::AtomicCondition);
        
        static_cast<var_type>(OKlib::Literals::var(lc));
        static_cast<var_type>(OKlib::Literals::var(l));

        static_cast<cond_type>(OKlib::Literals::cond(lc));

        OKlib::Literals::set_cond(l, c);

        dummy_use(Lit(v));
      }
void PbSolver::propagate()
{
    if (nVars() == 0) return;
    if (occur.size() == 0) setupOccurs();

    if (opt_verbosity >= 1) reportf("  -- Unit propagations: ", constrs.size());
    bool found = false;

    while (propQ_head < trail.size()){
        //**/reportf("propagate("); dump(trail[propQ_head]); reportf(")\n");
        Var     x = var(trail[propQ_head++]);
        for (int pol = 0; pol < 2; pol++){
            vec<int>&   cs = occur[index(Lit(x,pol))];
            for (int i = 0; i < cs.size(); i++){
                if (constrs[cs[i]] == NULL) continue;
                int trail_sz = trail.size();
                if (propagate(*constrs[cs[i]]))
                    constrs[cs[i]] = NULL;
                if (opt_verbosity >= 1 && trail.size() > trail_sz) found = true, reportf("p");
                if (!ok) return;
            }
        }
    }

    if (opt_verbosity >= 1) {
        if (!found) reportf("(none)\n");
        else        reportf("\n");
    }

    occur.clear(true);
}
Exemple #10
0
 int solver_lit_value     (solver* w) { 
     Var v;
     if (w->loc->peek(w->args, w->dummy, v))
         return toInt(w->value(Lit(v, !w->sig)));
     else
         return w->sig ? l_false : l_true;;
 }
void convert(const bvt &bv, vec<Lit> &dest)
{
  dest.growTo(bv.size());
  
  for(unsigned i=0; i<bv.size(); i++)
    dest[i]=Lit(bv[i].var_no(), bv[i].sign());
}
Exemple #12
0
  Lit heuristic::getSuggestion(){
  DREAL_LOG_INFO << "heuristic::getSuggestion()";
 
  if(!m_is_initialized)
    return lit_Undef;

  if (trail->size() > lastTrailEnd){
    pushTrailOnStack();
    //}

    //if (!m_is_initialized ||  backtracked){
    getSuggestions();
    backtracked = false;
  }
  if (!m_suggestions.empty()){
      std::pair<Enode *, bool> *s = m_suggestions.back();
      m_suggestions.pop_back();
      Enode *e = s->first;


    if ( e == NULL )
      return lit_Undef;



    DREAL_LOG_INFO << "heuristic::getSuggestion() " << e << " = " << s->second;
    if (theory_handler == NULL)
      DREAL_LOG_INFO << "heuristic::getSuggestion() NULL";
    Var v = theory_handler->enodeToVar(e);
    delete s;
    return Lit( v, !s->second );
    } else {
      return lit_Undef;
    }
  }
Exemple #13
0
Lit Solver::pickBranchLit(int polarity_mode, double random_var_freq)
{
    Var next = var_Undef;

    // Random decision:
    if (drand(random_seed) < random_var_freq && !order_heap.empty()){
        next = order_heap[irand(random_seed,order_heap.size())];
        if (toLbool(assigns[next]) == l_Undef && decision_var[next])
            rnd_decisions++; }

    // Activity based decision:
    while (next == var_Undef || toLbool(assigns[next]) != l_Undef || !decision_var[next])
        if (order_heap.empty()){
            next = var_Undef;
            break;
        }else
            next = order_heap.removeMin();

    bool sign = false;
    switch (polarity_mode){
    case polarity_true:  sign = false; break;
    case polarity_false: sign = true;  break;
    case polarity_user:  sign = polarity[next]; break;
    case polarity_rnd:   sign = irand(random_seed, 2); break;
    default: assert(false); }

    return next == var_Undef ? lit_Undef : Lit(next, sign);
}
Exemple #14
0
bool SimpSMTSolver::eliminateVar(Var v, bool fail)
{
  if (!fail && asymm_mode && !asymmVar(v))    return false;

  const vec<Clause*>& cls = getOccurs(v);

  //  if (value(v) != l_Undef || cls.size() == 0) return true;
  if (value(v) != l_Undef) return true;

  // Split the occurrences into positive and negative:
  vec<Clause*>  pos, neg;
  for (int i = 0; i < cls.size(); i++)
    (find(*cls[i], Lit(v)) ? pos : neg).push(cls[i]);

  // Check if number of clauses decreases:
  int cnt = 0;
  for (int i = 0; i < pos.size(); i++)
    for (int j = 0; j < neg.size(); j++)
      if (merge(*pos[i], *neg[j], v) && ++cnt > cls.size() + grow)
	return true;
#ifdef PEDANTIC_DEBUG
  cerr << "XXY gonna-remove" << endl;
#endif
  // Delete and store old clauses:
  setDecisionVar(v, false);
  elimtable[v].order = elimorder++;
  assert(elimtable[v].eliminated.size() == 0);
  for (int i = 0; i < cls.size(); i++)
  {
    elimtable[v].eliminated.push(Clause_new(*cls[i]));
    removeClause(*cls[i]);
  }

  // Produce clauses in cross product:
  int top = clauses.size();
  vec<Lit> resolvent;
  for (int i = 0; i < pos.size(); i++)
    for (int j = 0; j < neg.size(); j++)
      if (merge(*pos[i], *neg[j], v, resolvent) && !addClause(resolvent))
	return false;

  // DEBUG: For checking that a clause set is saturated with respect to variable elimination.
  //        If the clause set is expected to be saturated at this point, this constitutes an
  //        error.
  if (fail){
    reportf("eliminated var %d, %d <= %d\n", v+1, cnt, cls.size());
    reportf("previous clauses:\n");
    for (int i = 0; i < cls.size(); i++){
      printClause(*cls[i]); reportf("\n"); }
    reportf("new clauses:\n");
    for (int i = top; i < clauses.size(); i++){
      printClause(*clauses[i]); reportf("\n"); }
    assert(0); }

    return backwardSubsumptionCheck();
}
Exemple #15
0
Lit Solver::pickBranchLit(int polarity_mode, double random_var_freq)
{
    Var next = var_Undef;
    /*if (backup.stage == 0) {
        assert(order_heap.heapProperty());
        for(int i = 0; i < std::min(order_heap.size(), 10); i++) {
            printf("order_heap %d has var %d, has activity %lf\n", i, order_heap[i], activity[order_heap[i]]);
        }
    }*/

    // Random decision:
    if (drand(random_seed) < random_var_freq
        && !order_heap.empty()
    ){
        next = order_heap[irand(random_seed,order_heap.size())];
        if (toLbool(assigns[next]) == l_Undef && decision_var[next])
            rnd_decisions++;
    }

    // Activity based decision:
    while (next == var_Undef || toLbool(assigns[next]) != l_Undef || !decision_var[next])
      if (order_heap.empty()){
            next = var_Undef;
            break;
        }else
            next = order_heap.removeMin();

    bool sign = false;
    switch (polarity_mode){
    case polarity_true:  sign = false; break;
    case polarity_false: sign = true;  break;
    case polarity_user:  if(next!=var_Undef) sign = polarity[next]; break;
    case polarity_rnd:   sign = irand(random_seed, 2); break;
    default: assert(false); }

    #ifdef RESTORE
    if (backup.stage == 0) {
        printf("--> Picking decision lit "); printLit(Lit(next, sign)); printf(" at decision level: %d, sublevel: %d\n", decisionLevel(), trail.size());
    }
    #endif

    return next == var_Undef ? lit_Undef : Lit(next, sign);
}
Exemple #16
0
static void readClause(char*& in, VSolver& S, vec<Lit>& lits) {
    int     parsed_lit, var;
    lits.clear();
    for (;;){
        parsed_lit = parseInt(in);
        if (parsed_lit == 0) break;
        var = abs(parsed_lit)-1;
        lits.push( (parsed_lit > 0) ? Lit(var) : ~Lit(var) );
    }
}
Exemple #17
0
//
// Return the MiniSAT literal corresponding to
// the input enode literal. Creates the correspondence
// by adding a new MiniSAT variable, if it doesn't exists
//
Lit THandler::enodeToLit( Enode * elit )
{
  assert( elit );
  assert( elit->isLit( ) );

  bool negated = elit->isNot( );
  Enode * atm = negated ? elit->getCdr( )->getCar( ) : elit;
  Var v = enodeToVar( atm );
  return Lit( v, negated );
}
Exemple #18
0
static void readClause(B& in, Solver& S, vec<Lit>& lits) {
    int     parsed_lit, var;
    lits.clear();
    for (;;){
        parsed_lit = parseInt(in);
        if (parsed_lit == 0) break;
        var = abs(parsed_lit)-1;
        while (var >= S.nVars()) S.newVar();
        lits.push( (parsed_lit > 0) ? Lit(var) : ~Lit(var) );
    }
}
Exemple #19
0
Lit THandler::getSuggestion( )
{
  Enode * e = core_solver.getSuggestion( );

  if ( e == NULL )
    return lit_Undef;

  bool negate = e->getDecPolarity( ) == l_False;
  Var v = enodeToVar( e );
  return Lit( v, negate );
}
Exemple #20
0
SAT::SAT() :
		lit_sort(trailpos)
	, pushback_time(0)
	, trail(1)
	, qhead(1,0)
	, rtrail(1)
	, confl(NULL)
	, var_inc(1)
        , maxActivity(0)
	, cla_inc(1)
	, order_heap(VarOrderLt(activity))
	, bin_clauses(0)
	, tern_clauses(0)
	, long_clauses(0)
	, learnt_clauses(0)
	, propagations(0)
	, back_jumps(0)
	, nrestarts(0)
	, next_simp_db(100000)
	, clauses_literals(0)
	, learnts_literals(0)
	, max_literals(0)
	, tot_literals(0)
	, avg_depth(100)
	, confl_rate(1000)
	, ll_time(wallClockTime())
	, ll_inc(1)
	, learnt_len_el(10)
	, learnt_len_occ(MAX_SHARE_LEN,learnt_len_el*1000/MAX_SHARE_LEN)
{
	newVar(); enqueue(Lit(0,1));
	newVar(); enqueue(Lit(1,0));
	temp_sc = (SClause*) malloc(TEMP_SC_LEN * sizeof(int));
	short_expl = (Clause*) malloc(sizeof(Clause) + 3 * sizeof(Lit));
	short_confl = (Clause*) malloc(sizeof(Clause) + 2 * sizeof(Lit));
	short_expl->clearFlags();
	short_confl->clearFlags();
	short_confl->sz = 2;
}
Exemple #21
0
static Int readClauseCnf(B& in,  mS& S, vec<Lit>& lits,bool wcnf) {
    int     parsed_lit, var;
    Int weight=1;
    if(wcnf) weight = parseIntCnf(in);
    lits.clear();
    for (;;){
        parsed_lit = toint(parseIntCnf(in));
        if (parsed_lit == 0) break;
        var = abs(parsed_lit)-1;
        while (var >= S.nVars()) S.newVar();
        lits.push( (parsed_lit > 0) ? Lit(var) : ~Lit(var) );
    }
    return weight;
}
Exemple #22
0
Lit THandler::getDeduction( )
{
  Enode * e = core_solver.getDeduction( );

  if ( e == NULL )
    return lit_Undef;

  if ( config.certification_level > 1 )
    verifyDeductionWithExternalTool( e );

  assert( e->isDeduced( ) );
  assert( e->getDeduced( ) == l_False
       || e->getDeduced( ) == l_True );
  bool negate = e->getDeduced( ) == l_False;
  Var v = enodeToVar( e );
  return Lit( v, negate );
}
Exemple #23
0
void parseExpr(B& in, S& solver, vec<Lit>& out_ps, vec<Int>& out_Cs, vec<char>& tmp)
    // NOTE! only uses "getVar()" method of solver; doesn't add anything.
    // 'tmp' is a tempory, passed to avoid frequent memory reallocation.
{
    bool empty = true;
    for(;;){
        skipWhitespace(in);
        if ((*in < '0' || *in > '9') && *in != '+' && *in != '-') break;
        out_Cs.push(parseInt(in));
        skipWhitespace(in);
        if (*in != '*') throw xstrdup("Missing '*' after coefficient.");
        ++in;
        out_ps.push(Lit(solver.getVar(parseIdent(in, tmp))));
        empty = false;
    }
    if (empty) throw xstrdup("Empty expression.");
}
Exemple #24
0
Lit Solver::pickBranchLit(int polarity_mode, double random_var_freq)
{
  Var next = var_Undef;

  // Random decision:
  /*  if (drand(random_seed) < random_var_freq && !order_heap.empty()){
    next = order_heap[irand(random_seed,order_heap.size())];
    if (toLbool(assigns[next]) == l_Undef && decision_var[next])
      rnd_decisions++; }
  */

  // Activity based decision:
  while (next == var_Undef || toLbool(assigns[next]) != l_Undef || !decision_var[next]) {
    if (order_heap.empty()){
      next = var_Undef;
      break;
    }else
      next = order_heap.removeMin();
  }

  if (next == var_Undef) return lit_Undef;

  bool sign = false;

  
  switch (polarity_mode){
  case polarity_true:  sign = false; break;
  case polarity_false: sign = true;  break;
  case polarity_user:  sign = polarity[next]; break;
  case polarity_rnd:   sign = irand(random_seed, 2); break;
  }

  sign = !polarity[next];

  //  do {
  //    int var;
  //    std::cin >> var;
  //    sign = !(var > 0);
  //    next = Var(abs(var) - 1);
  //  } while(toLbool(assigns[next]) != l_Undef);

  //  std::cout << "var: " << var << " sign: " << sign << std::endl;

  return next == var_Undef ? lit_Undef : Lit(next, sign);
}
Exemple #25
0
void read_minterm_file_to_solver(char * fileName, Solver &S,int *input_array,int input_array_size , Lit output_lit){

  char temp[MAX_LENGTH];
  FILE *fp;
  vec<Lit> lits;
  int i;


  //printf("%d ",toInt(output_lit));
  //getchar();
  lits.clear();

  if ((fp = fopen(fileName, "r")) == NULL) {
    fprintf(stderr, "Couldn't open file: %s\n", fileName);
    exit (1);
  }

  while(!feof(fp)) {
    fgets(temp,MAX_LENGTH, fp);
    if( temp[0]=='0' || temp[0]=='1' || temp[0]=='-'){
      break;
    }
  }

  for(i=0;i<input_array_size;i++){
    //PRINT(input_array[i]);
  }
  while(temp[0]!='.'){
    //puts(temp);
    for(i=0;i<input_array_size;i++){
      if(temp[i]=='-')
	    continue;
      lits.push( (temp[i]=='1') ? ~Lit( input_array[i] - INDEX_OF_FIRST_VARIABLE ) : Lit(input_array[i] - INDEX_OF_FIRST_VARIABLE ) );
      //printf("%d:%d ",i,toInt(lits[lits.size()-1]));
    }
    //puts(" ");
    lits.push( output_lit );
    S.addClause(lits);
    lits.clear();
    
    fgets(temp,MAX_LENGTH, fp);
  }

  fclose(fp);
}
Exemple #26
0
Re_node mk_leaf(short opval, short type, char ch, Ch_Set cset)
{
    Re_node node;
    Re_Lit l;

    l = (Re_Lit) new_node(l);
    node = (Re_node) new_node(node);
    if (l == NULL || node == NULL) return NULL;
    lit_type(l) = type;
    lit_pos(l)  = pos_cnt++;
    if (type == C_SET) lit_cset(l) = cset;
    else lit_char(l) = ch;			/* type == C_LIT */
    Op(node) = opval;
    Lit(node) = l;
    Nullable(node) = FALSE;
    Firstpos(node) = create_pos(lit_pos(l));
    Lastpos(node) = Firstpos(node);
    return node;
}
Exemple #27
0
/*_________________________________________________________________________________________________
|
|  search : (nof_conflicts : int) (nof_learnts : int) (params : const SearchParams&)  ->  [lbool]
|  
|  Description:
|    Search for a model the specified number of conflicts, keeping the number of learnt clauses
|    below the provided limit. NOTE! Use negative value for 'nof_conflicts' or 'nof_learnts' to
|    indicate infinity.
|  
|  Output:
|    'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If
|    all variables are decision variables, this means that the clause set is satisfiable. 'l_False'
|    if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached.
|________________________________________________________________________________________________@*/
lbool Solver::search(int nof_conflicts, int nof_learnts, const SearchParams& params)
{
    if (!ok) return l_False;    // GUARD (public method)
    assert(root_level == decisionLevel);

    stats.starts++;
    int     conflictC = 0;
    var_decay = 1 / params.var_decay;
    cla_decay = 1 / params.clause_decay;
    model.clear();

    for (;;){
 		Constr* confl = propagate();
        if (confl != NULL){
            // CONFLICT

            //if (verbosity >= 2) printf(L_IND"**CONFLICT**\n", L_ind);

            stats.conflicts++; conflictC++;
            vec<Lit>    learnt_clause;
            int         backtrack_level;

            if (decisionLevel == root_level) {
				if (doDeriv) {
					analyzeFinalDeriv(confl);
				}
                return l_False;
			}

			Deriv* deriv = new Deriv();
			derivs.push_back(deriv);
            analyze(confl, learnt_clause, backtrack_level, deriv);
            cancelUntil(max(backtrack_level, root_level));
            record(learnt_clause, deriv);

            varDecayActivity(); claDecayActivity();

        }else{
            // NO CONFLICT

            if (nof_conflicts >= 0 && conflictC >= nof_conflicts){
                // Reached bound on number of conflicts:
                progress_estimate = progressEstimate();
                propQ.clear();
                cancelUntil(root_level);
                return l_Undef; }

            if (decisionLevel == 0)
                // Simplify the set of problem clauses:
                simplifyDB(), assert(ok);

            if (nof_learnts >= 0 && learnts.size()-nAssigns() >= nof_learnts)
                // Reduce the set of learnt clauses:
                reduceDB();

            // New variable decision:
            stats.decisions++;
            Var next = order.select(params.random_var_freq);

            if (next == var_Undef){
                // Model found:
                model.growTo(nVars);
                for (int i = 0; i < nVars; i++) model[i] = (value(i) == l_True);
                cancelUntil(root_level);
                return l_True;
            }

			// VERY important for the Y-variables to try positive polarity first
			//   - follows the value ordering heuristic of aiming for solutions (as opposed to fail-first var order)
            check(assume(Lit(next)));
            //check(assume(~Lit(next)));
        }
    }
}
Exemple #28
0
/* Read in NET file and returns 2^n transition function*/
void
ReadNET(char *fileName, Solver& S)
{

  char temp[MAX_LENGTH];
  char slask[MAX_LENGTH];
  int i , k , tmp_1;

  int input_array[MAX_NUMBER_OF_INPUTS];
  int number_of_inputs,current_number_of_inputs=0;
  int current_var;
  FILE *fp,*fp_temp;      
  vec<Lit> lits;
  std::vector<Lit> lits_std;

  unsigned line_count=0;

//the following allows counting of line
#define fgets(X,Y,Z);  fgets((X),(Y),(Z));line_count++;  

  /* Open NET file for reading */
  if ((fp = fopen(fileName, "r")) == NULL) {
    fprintf(stderr, "Couldn't open NET file: %s\n", fileName);
    exit (1);
  }

  /* Reading number of non-redundent var*/
  while(!feof(fp)) {
    fgets(temp,MAX_LENGTH, fp);
    if (strncmp(temp,".v",2)==0) {
      /* Find size of the cubes */
      sscanf(temp, "%s %i", slask, &number_of_var);
      break;
    }
  }
  var2red_var=(int*) calloc(number_of_var+1, sizeof(int));

  size_nonred_array=number_of_var;

  redunt_number_of_var=number_of_var;
  redunt_var2var=(int*) calloc(redunt_number_of_var+1, sizeof(int));

  number_print_var=number_of_var;

  int count_nodes;
  for(count_nodes=1; count_nodes<=number_of_var; count_nodes++ ){
    redunt_var2var[count_nodes]=count_nodes;
    var2red_var[count_nodes]=count_nodes;
  }

 
  if(feof(fp)) {
    fprintf(stderr, "Wrong format of input file. End of file is reached but no node function is red" );
    exit(1);
  }
  
  k=number_of_var;
  while(k--){
    S.newVar();S.newVar();
  }
  
  //RBN_init_global_var(bdd_manager);

  /*-------------------- Filling information about nodes  -------------------*/
  while(!feof(fp)){
    fgets(temp,MAX_LENGTH, fp);
  next_vertex:
    if (strncmp(temp,".n",2)==0) {
      /* Find size of the cubes */

      i=3;
      sscanf(&temp[i],"%d",&current_var);

      if( current_var < 0 || current_var >redunt_number_of_var){
	    fprintf(stderr, "Wrong format of input file in line %d.The varible %d in string:\n %s exceeds number of declared variables.\n",line_count, current_var,temp);
	    exit (1);
      }
      
      i++;
      /* go to first space */
      while(temp[i]!=' '){
	    if(temp[i]=='\n'){
	      fprintf(stderr, "Wrong format of input file in line %d. Wrong format of the string: %s\n",line_count, temp );
	      exit (1);
	    }
	    i++;
      }
      i++;
      /* go to the end of sequense of spaces */
      while(temp[i]==' '){
	    i++;
      }
      if(temp[i]=='\n'){
	    fprintf(stderr, "Wrong format of input file in line %d. Wrong format of the string: %s\n",line_count, temp );
	    exit (1);
      }
      sscanf(&temp[i],"%d",&number_of_inputs);

      if(number_of_inputs > MAX_NUMBER_OF_INPUTS){
	    fprintf(stderr, "Wrong format of input file in line %d . Number of inputs exceeds allowed number of inputs %s\n",line_count, temp  );
	    exit (1);
      }
      
      while(1){
	    i++;
	    while(temp[i]!=' '){
	      if(temp[i]=='\n'){
	        goto end_loops;
	      }
	      i++;
	    }
	    i++;
	/* go to the end of sequense of spaces */
	    while(temp[i]==' '){
	      i++;
	    }
	    if(temp[i]=='\n'){
	      goto end_loops;
	    }
	    sscanf(&temp[i],"%d",&tmp_1);

	    if( tmp_1 < 0 || tmp_1 >redunt_number_of_var){
	      fprintf(stderr,"Wrong format of input file in line %d. The varible %d in string:\n %s exceeds number of declared variables.\n",line_count, tmp_1,temp);
	      exit (1);
	    }
	
	    if( redunt_var2var[tmp_1] == 0){
	      fprintf(stderr, "Wrong format of input file in line %d. One of the input was not declared in list of inputs %s\n",line_count, temp  );
	      exit (1);
	    }

	    input_array[current_number_of_inputs++]= redunt_var2var[tmp_1];
      }
    
    end_loops:
      if(current_number_of_inputs!=number_of_inputs){
	    fprintf(stderr, "Wrong format of input file in line %d. Declared number of inputs is not equal to actual number of input %s\n",line_count, temp  );
	    exit (1);
      }

      if(number_of_inputs==0){
	    fgets(temp,MAX_LENGTH, fp);
	  
	    if( temp[0]=='1'){
	      lits.push( Lit( current_var - INDEX_OF_FIRST_VARIABLE ) );
	      S.addClause(lits);
	      lits.clear();
	    }else{
	      if( temp[0]!='0'){
	        printf("Node %d assumed to be constant 0\n",current_var);
	      }
	      lits.push( ~Lit( current_var - INDEX_OF_FIRST_VARIABLE ) );
	      S.addClause(lits);
	      lits.clear();
	    }
	    goto next_vertex;
      }

      /*---------------  Reading in the function of the node ---------------*/

      current_number_of_inputs=0;

      while(!feof(fp)){
	    fgets(temp,MAX_LENGTH, fp);
	    if( temp[0]=='0' || temp[0]=='1' || temp[0]=='-'){

	      for(i=0;i<number_of_inputs;i++){
	        if(temp[i]=='-')
	          continue;
            //PRINT(input_array[i]);
	        lits.push( (temp[i]=='1') ? ~Lit( number_of_var + input_array[i] - INDEX_OF_FIRST_VARIABLE) : Lit(number_of_var + input_array[i] - INDEX_OF_FIRST_VARIABLE) );

	        if(temp[i]!='1' && temp[i]!='0'){
	          fprintf(stderr, "Wrong format of input file in line %d. Wrong line:%s\n",line_count, temp  );
	          exit (1);	
	        }      
	      }

	      ASSERT((number_of_var + current_var - INDEX_OF_FIRST_VARIABLE) < S.nVars());

	      i++;
	      if(temp[i]=='1'){
	        lits.push( Lit(  current_var - INDEX_OF_FIRST_VARIABLE ) );
	      }else{
	        if(temp[i]=='0'){
	          lits.push( ~Lit( current_var - INDEX_OF_FIRST_VARIABLE ) );
	        }else{
	          fprintf(stderr, "Wrong format of input file in line %d. Unexpected charecter in output of minterm in line:%s\n",line_count, temp  );
	          exit (1);	
	        }
	      }
	      S.addClause(lits);
          
          //PRINT(current_var);
          for (int x=0; x<lits.size();x++) {
            //PRINT(toInt(lits[x]));  
          }

	      if(lits.size()==2){
	     //PRINT(lits.size());
            for(int j=0; j<lits.size();j++){
           	//PRINT(toInt(lits[j]));
              lits_std.push_back(lits[j]);
        	}
            (*global_var.orig_clauses).push_back( lits_std );
            lits_std.clear();
	      }
	      lits.clear();	 
	    }else{

	      if( redunt_var2var[current_var] == 0){
	        fprintf(stderr, "Wrong format of input file.The node:%d was not declared \n", current_var  );
	        exit (1);
	      }
	  
	      break; 
	    }	
      }
	  
      if(!feof(fp)){
	    goto next_vertex;
      }

      /*We are here after we reach the end of the file*/
      if( redunt_var2var[current_var] == 0){
	    fprintf(stderr, "Wrong format of input file.The node:%d was not declared \n", current_var  );
	    exit (1);
      }
    }/* -------- end processing input informaition of a vertex ------------*/
  }
/*end processing the file*/
  
  fclose(fp);
  
#undef fgets(X,Y,Z);

}
Exemple #29
0
int 
main(int argc, char *argv[]) 
{

  int i,j,n;
  Solver      S;
  unsigned atractor_count=0;
  unsigned atractor_stats_count=0;
  std::vector<Lit> lits;
  char command[100];
  float avg_length = 0;

  std::vector< std::vector<Lit> > orig_clauses;
  global_var.orig_clauses = &orig_clauses;

  ReadNET(argv[1], S); //ckhong: read networks and then make transition relations with depth 2 by using update functions
    
  //PRINT(orig_clauses.size());

  vec<Clause*>* orig_clauses_pr = S.Clauses();

  lits.clear();  

  i=(*orig_clauses_pr).size();
  //PRINT(i);
  
  while(i--){
    int j=(*((*orig_clauses_pr)[i])).size(); //ckhong: j has the number of literals in each clause

    while(j--){
      lits.push_back((*((*orig_clauses_pr)[i]))[j]);
    }

    orig_clauses.push_back( lits ); 
    lits.clear();
  }

  /*Handle assignments of variables made in solver*/ 
  /*ckhong: what is this for ?*/ 
  /*ckhong: initial state value setting ?*/
  i=number_of_var;
  while(i--){
    if(S.value(i)!= l_Undef){
      lits.push_back((S.value(i)==l_True)? Lit(i) : ~Lit(i));
      orig_clauses.push_back( lits );
      lits.clear();
    }
  }
 
  //PRINT(orig_clauses.size());

  global_var.S = &S;
  global_var.number_of_var = number_of_var;
  global_var.depth=2;


  if(number_of_var<100){ //ckhong: make n-length formula
    construct_depth(number_of_var);
  }else{
    construct_depth(100);
  }

  //puts("Start searching...");
  while(1){

    if (!S.solve()) break;
    /*ckhong: found valid path*/

    for( i=1; i<global_var.depth; i++ ){
      if(compare_states(0,i,number_of_var,S.model )){
    	atractor_count++;
    	atractor_stats_count+=i;
    	//PRINT(atractor_stats_count);
    	//constrain all states of atractor sequence on 0 index variable
        
        //char temp_attr[i*number_of_var];
    	char tState[number_of_var];
        Attractor tAttr; 
        tAttr.length = i;

        for( j = 0; j < i; j++ ){
	      constrain_state(j, S.model, 0, S, number_of_var );
#ifdef PRINT_STATE 
          /*ckhong: attractor state print out*/
    	  int a_tmp=j*number_of_var;	  
          int b_tmp=0;
	      int counter=number_of_var;
	      while(counter--){
	        if(S.model[a_tmp] != l_Undef){
		      //printf( "%s", (S.model[a_tmp]==l_True)?"1":"0");
              //sprintf(temp_attr+a_tmp, "%s", (S.model[a_tmp]==l_True)?"1":"0");
              sprintf(tState+b_tmp, "%s", (S.model[a_tmp]==l_True)?"1":"0");
	        }else{
		      //printf("-");
              //sprintf(temp_attr+a_tmp, "-");
              sprintf(tState+b_tmp, "-");
	        }
	        a_tmp++;
            b_tmp++;
	      }
          tAttr.states.push_back(tState);
          //printf("\n");
#endif 
	    }
        //results.push_back(temp_attr);
        //results.push_back("\n");
        global_var.Attractors.push_back(tAttr);
	    //printf("Attractor %d is of length %d\n\n",atractor_count,i);
	    //avg_length = avg_length + i;
	    break;
      }
    }

    if(global_var.depth == i){
      construct_depth( global_var.depth << 1 ); //ckhong: depth = depth * 2
      printf("Depth of unfolding transition relation is increased to %d\n",global_var.depth);
    }
  }

  printf("Total number of attractors is %d\n",atractor_count);
  printf("Average length of attractors is %0.2f\n",avg_length/(float)atractor_count);

  for (int i=0; i<global_var.Attractors.size(); i++) {
    std::cout << "Attractor " << i << "\n";
    for (int j=0; j<global_var.Attractors[i].length; j++)
        std::cout << global_var.Attractors[i].states[j] << " " ;
    std::cout << "\n";
  }

  int MAX_DEPTH = global_var.depth;

/* ####### Basin Analysis ####### */
  
  int total_basin_size = 1;
  int curr_depth = 0;
  int attr_num = 0;
  
  for (curr_depth=2; curr_depth<MAX_DEPTH; curr_depth++) {
    Solver S_;
    orig_clauses.clear();
    lits.clear();

    ReadNET(argv[1], S_);
    
    //PRINT(S_.nClauses());

    orig_clauses_pr = S_.Clauses();
    
    i=(*orig_clauses_pr).size();
    //PRINT(i);

    while(i--){
        int j=(*((*orig_clauses_pr)[i])).size();

        while(j--){
          lits.push_back((*((*orig_clauses_pr)[i]))[j]);
        }
        orig_clauses.push_back( lits ); 
        lits.clear();
    }
    //PRINT(orig_clauses.size());

    int count = 0;
    i=number_of_var;
    while(i--){
        if(S_.value(i)!= l_Undef){
            count++;
            lits.push_back((S_.value(i)==l_True)? Lit(i) : ~Lit(i));
            orig_clauses.push_back( lits );
            lits.clear();
        }
    }

    global_var.S = &S_;
    global_var.depth = 2;
    global_var.number_of_var = number_of_var;
    //global_var.orig_clauses = &orig_clauses;

    construct_depth(curr_depth);
    int tSize = getPredecessors(S_, attr_num, number_of_var, curr_depth);
    //printf("level %d: %d\n", curr_depth, tSize);
    total_basin_size = total_basin_size + tSize;
    
    if (tSize == 0) {
        break;
    }
  }
  
  printf("Basin size for attractor %d: %d\n", attr_num, total_basin_size);

  return 0;
}
Exemple #30
0
int main(int argc, char** argv)
{
    Solver      S;
    Solver      T;
    vec<Lit> lits;
    vec<Lit> lits2;
    vec<Lit> lits3;
    vec<Lit> lits4;
    vec<Lit> lits5;
    vec<Lit> lits6;
    vec<Lit> lits0;
    lits.clear();
    lits2.clear();
    T.newVar();
    T.newVar();
    T.newVar();
    T.newVar();
    T.newVar();
    T.newVar();
    T.newVar();
    T.newVar();
    S.newVar();
    S.newVar();
    S.newVar();
    S.newVar();
    S.newVar();
    S.newVar();
    S.newVar();
    S.newVar();
    lits0.clear();
    lits0.push(Lit(0));
    unsigned int i;
    int parsed_lit = -1;
    lits.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = 1;
    lits.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    S.addClause(lits);
    T.addClause(lits);
    parsed_lit = 2;
    printf("lalla1\n");
    lits3.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = 3;
    lits3.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -4;
    lits3.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -2;
    lits4.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = 5;
    lits4.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -6;
    lits4.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = 3;
    lits5.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -5;
    lits5.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = 10;
    lits5.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -3;
    lits6.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -7;
    lits6.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -10;
    lits6.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    lits6.push( (parsed_lit > 0) 
               ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = -100;
    lits2.push( (parsed_lit > 0) ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    parsed_lit = 100;
    lits2.push( (parsed_lit > 0) ? Lit(abs(parsed_lit)-1) : ~Lit(abs(parsed_lit)-1) );
    S.addClause(lits2);
    T.addClause(lits2);
    printf("lalla2\n");
    S.addClause(lits3);
    T.addClause(lits3);
    printf("lalla3\n");
    printf("Snvas %i \n", S.nVars());
    S.addClause(lits4);
    T.addClause(lits4);
    printf("lalla4\n");
    S.addClause(lits5);
    T.addClause(lits5);
    printf("lalla5\n");
    S.addClause(lits6);
    T.addClause(lits6);
    printf("lallala\n");
    bool ret = S.solve();
    printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n");
    ret = T.solve();
    printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n");
}