Search in sources :

Example 1 with TimeoutException

use of org.sat4j.specs.TimeoutException in project abstools by abstools.

the class SatGenerator method generate.

public Map<LocationTypeVariable, LocationType> generate() {
    long startNanos = System.nanoTime();
    Map<LocationTypeVariable, LocationType> tvl = new HashMap<>();
    for (Constraint c : constraints) {
        if (enableDebug)
            System.out.println(c);
        List<List<Integer>> gen = c.generateSat(e);
        output.addAll(gen);
        c.variables(vars);
    }
    long genNanos = System.nanoTime();
    if (enableStats) {
        System.out.println("Constraint generation time: " + (genNanos - startNanos) / 1000000);
    }
    StringBuilder weights = new StringBuilder();
    int countNiceConstraints = 0;
    for (LocationTypeVariable tv : vars) {
        if (tv.getNode() != null) {
            countNiceConstraints++;
            weights.append(Constraint.NICE_TO_HAVE);
            weights.append(" ");
            weights.append(e.get(tv, LocationType.NEAR));
            weights.append(" ");
            weights.append(e.get(tv, LocationType.FAR));
            weights.append(" ");
            for (LocationType lt : tv.parametricFarTypes()) {
                weights.append(e.get(tv, lt));
                weights.append(" ");
            }
            weights.append("0\n");
        }
    }
    StringBuilder sb = new StringBuilder();
    int nbclauses = output.size() + countNiceConstraints;
    int nbvars = e.current;
    addInitLine(sb, nbclauses, nbvars);
    // update should_have
    int newShouldHave = countNiceConstraints * Constraint.NICE_TO_HAVE + 1;
    for (List<Integer> line : output) {
        if (line.get(0).equals(Constraint.SHOULD_HAVE)) {
            line.set(0, newShouldHave);
        }
    }
    // System.out.println("SHOULD_HAVE value: "+ newShouldHave);
    try {
        for (List<Integer> line : output) {
            for (Integer i : line) {
                sb.append(i);
                sb.append(" ");
            }
            sb.append("0\n");
        }
    } catch (Exception e) {
        System.out.println(sb.length());
        throw e;
    }
    sb.append(weights);
    if (enableStats) {
        System.out.println("Number of variables: " + nbvars);
        System.out.println("Number of clauses: " + nbclauses);
    }
    // System.out.println(sb);
    // instance().defaultSolver();
    IPBSolver solver = org.sat4j.maxsat.SolverFactory.newDefault();
    // IPBSolver solver = org.sat4j.pb.SolverFactory.newBoth();
    // System.exit(0);
    WeightedMaxSatDecorator wmsd = new WeightedMaxSatDecorator(solver);
    WDimacsReader reader = new WDimacsReader(wmsd);
    try {
        InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
        IProblem problem = reader.parseInstance(is);
        long parseNanos = System.nanoTime();
        if (enableStats) {
            System.out.println("Parsing time: " + (parseNanos - genNanos) / 1000000);
        }
        if (enableStats) {
            System.gc();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.gc();
        }
        OptToPBSATAdapter opt = new OptToPBSATAdapter(wmsd);
        opt.setVerbose(false);
        // opt.setTimeoutMs(10000);
        // parseNanos = System.nanoTime();
        // opt.setTimeout(arg0)
        parseNanos = System.nanoTime();
        if (opt.isSatisfiable()) {
            int[] model = opt.model();
            long solveNanos = System.nanoTime();
            if (enableStats) {
                System.out.println("Solving time: " + (solveNanos - parseNanos) / 1000000);
                System.out.println("Total time: " + (solveNanos - startNanos) / 1000000);
            }
            // System.out.println(Arrays.toString(model));
            for (int i : model) {
                if (i > 0) /*&& i <= nbvars*/
                {
                    TypedVar tv = e.vars().get(i - 1);
                    // System.out.println(tv.v + " : " + tv.t);
                    tvl.put(tv.v, tv.t);
                }
            }
            if (enableDebug)
                System.out.println("Solution: " + tvl);
            if (enableStats) {
                int fars = 0;
                int sws = 0;
                int nears = 0;
                int paramfars = 0;
                for (Entry<LocationTypeVariable, LocationType> e : tvl.entrySet()) {
                    if (e.getKey().getNode() != null) {
                        LocationType t = e.getValue();
                        if (t.isFar())
                            fars++;
                        if (t.isParametricFar())
                            paramfars++;
                        if (t.isNear())
                            nears++;
                        if (t.isSomewhere())
                            sws++;
                    }
                }
                System.out.println("Fars: " + fars);
                System.out.println("Somewheres: " + sws);
                System.out.println("Nears: " + nears);
                System.out.println("Parametric Fars: " + paramfars);
                System.out.println("Total: " + (fars + sws + nears + paramfars));
            }
        } else {
            return null;
        }
        return tvl;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ContradictionException e) {
    // TODO Auto-generated catch block
    // e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
Also used : IPBSolver(org.sat4j.pb.IPBSolver) WDimacsReader(org.sat4j.maxsat.reader.WDimacsReader) HashMap(java.util.HashMap) ContradictionException(org.sat4j.specs.ContradictionException) FileNotFoundException(java.io.FileNotFoundException) ParseFormatException(org.sat4j.reader.ParseFormatException) SemanticConditionList(abs.frontend.analyser.SemanticConditionList) ArrayList(java.util.ArrayList) List(java.util.List) TimeoutException(org.sat4j.specs.TimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) WeightedMaxSatDecorator(org.sat4j.maxsat.WeightedMaxSatDecorator) IProblem(org.sat4j.specs.IProblem) ContradictionException(org.sat4j.specs.ContradictionException) IOException(java.io.IOException) ParseFormatException(org.sat4j.reader.ParseFormatException) FileNotFoundException(java.io.FileNotFoundException) TimeoutException(org.sat4j.specs.TimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) OptToPBSATAdapter(org.sat4j.pb.OptToPBSATAdapter) LocationType(abs.frontend.typechecker.locationtypes.LocationType)

Example 2 with TimeoutException

use of org.sat4j.specs.TimeoutException in project spoon by INRIA.

the class Solver method isSatisfiable.

public boolean isSatisfiable(IVecInt assumps, boolean global) throws TimeoutException {
    Lbool status = Lbool.UNDEFINED;
    boolean alreadylaunched = this.conflictCount != null;
    final int howmany = this.voc.nVars();
    if (this.mseen.length <= howmany) {
        this.mseen = new boolean[howmany + 1];
    }
    this.trail.ensure(howmany);
    this.trailLim.ensure(howmany);
    this.learnedLiterals.ensure(howmany);
    this.decisions.clear();
    this.implied.clear();
    this.slistener.init(this);
    this.slistener.start();
    // forget about previous model
    this.model = null;
    this.userbooleanmodel = null;
    this.prime = null;
    this.unsatExplanationInTermsOfAssumptions = null;
    if (!alreadylaunched || !this.keepHot) {
        this.order.init();
    }
    this.learnedConstraintsDeletionStrategy.init();
    int learnedLiteralsLimit = this.trail.size();
    // Fix for Bug SAT37
    this.qhead = 0;
    // again now that qhead is 0.
    for (int i = learnedLiteralsLimit - 1; i >= 0; i--) {
        int p = this.trail.get(i);
        IVec<Undoable> undos = this.voc.undos(p);
        assert undos != null;
        for (int size = undos.size(); size > 0; size--) {
            undos.last().undo(p);
            undos.pop();
        }
    }
    // push previously learned literals
    for (IteratorInt iterator = this.learnedLiterals.iterator(); iterator.hasNext(); ) {
        enqueue(iterator.next());
    }
    // propagate constraints
    Constr confl = propagate();
    if (confl != null) {
        analyzeAtRootLevel(confl);
        this.slistener.conflictFound(confl, 0, 0);
        this.slistener.end(Lbool.FALSE);
        cancelUntil(0);
        cancelLearntLiterals(learnedLiteralsLimit);
        return false;
    }
    // push incremental assumptions
    for (IteratorInt iterator = assumps.iterator(); iterator.hasNext(); ) {
        int assump = iterator.next();
        int p = this.voc.getFromPool(assump);
        if (!this.voc.isSatisfied(p) && !assume(p) || (confl = propagate()) != null) {
            if (confl == null) {
                this.slistener.conflictFound(p);
                this.unsatExplanationInTermsOfAssumptions = analyzeFinalConflictInTermsOfAssumptions(null, assumps, p);
                this.unsatExplanationInTermsOfAssumptions.push(assump);
            } else {
                this.slistener.conflictFound(confl, decisionLevel(), this.trail.size());
                this.unsatExplanationInTermsOfAssumptions = analyzeFinalConflictInTermsOfAssumptions(confl, assumps, ILits.UNDEFINED);
            }
            this.slistener.end(Lbool.FALSE);
            cancelUntil(0);
            cancelLearntLiterals(learnedLiteralsLimit);
            return false;
        }
    }
    this.rootLevel = decisionLevel();
    // assumptions.
    if (!alreadylaunched || !this.keepHot) {
        // duplicated on purpose
        this.order.init();
    }
    this.learner.init();
    if (!alreadylaunched) {
        this.conflictCount = new ConflictTimerContainer();
        this.conflictCount.add(this.restarter);
        this.conflictCount.add(this.learnedConstraintsDeletionStrategy.getTimer());
    }
    boolean firstTimeGlobal = false;
    if (this.timeBasedTimeout) {
        if (!global || this.timer == null) {
            firstTimeGlobal = true;
            this.undertimeout = true;
            TimerTask stopMe = new TimerTask() {

                @Override
                public void run() {
                    Solver.this.undertimeout = false;
                }
            };
            this.timer = new Timer(true);
            this.timer.schedule(stopMe, this.timeout);
        }
    } else {
        if (!global || !alreadylaunched) {
            firstTimeGlobal = true;
            this.undertimeout = true;
            ConflictTimer conflictTimeout = new ConflictTimerAdapter((int) this.timeout) {

                private static final long serialVersionUID = 1L;

                @Override
                public void run() {
                    Solver.this.undertimeout = false;
                }
            };
            this.conflictCount.add(conflictTimeout);
        }
    }
    if (!global || firstTimeGlobal) {
        this.restarter.init(this.params, this.stats);
        this.timebegin = System.currentTimeMillis();
    }
    this.needToReduceDB = false;
    // this is used to allow the solver to be incomplete,
    // when using a heuristics limited to a subset of variables
    this.lastConflictMeansUnsat = true;
    // Solve
    while (status == Lbool.UNDEFINED && this.undertimeout && this.lastConflictMeansUnsat) {
        int before = this.trail.size();
        unitClauseProvider.provideUnitClauses(this);
        this.stats.importedUnits += this.trail.size() - before;
        status = search(assumps);
        if (status == Lbool.UNDEFINED) {
            this.restarter.onRestart();
            this.slistener.restarting();
        }
    }
    cancelUntil(0);
    cancelLearntLiterals(learnedLiteralsLimit);
    if (!global && this.timeBasedTimeout && this.timer != null) {
        this.timer.cancel();
        this.timer = null;
    }
    this.slistener.end(status);
    if (!this.undertimeout) {
        String message = " Timeout (" + this.timeout + (this.timeBasedTimeout ? "s" : " conflicts") + ") exceeded";
        throw new TimeoutException(message);
    }
    if (status == Lbool.UNDEFINED && !this.lastConflictMeansUnsat) {
        throw new TimeoutException("Cannot decide the satisfiability");
    }
    // (the last one)
    return model != null;
}
Also used : IteratorInt(org.sat4j.specs.IteratorInt) Lbool(org.sat4j.specs.Lbool) IConstr(org.sat4j.specs.IConstr) TimerTask(java.util.TimerTask) Timer(java.util.Timer) TimeoutException(org.sat4j.specs.TimeoutException)

Example 3 with TimeoutException

use of org.sat4j.specs.TimeoutException in project spoon by INRIA.

the class Solver method search.

Lbool search(IVecInt assumps) {
    assert this.rootLevel == decisionLevel();
    this.stats.starts++;
    int backjumpLevel;
    // varDecay = 1 / params.varDecay;
    this.order.setVarDecay(1 / this.params.getVarDecay());
    this.claDecay = 1 / this.params.getClaDecay();
    do {
        this.slistener.beginLoop();
        // propagate unit clauses and other constraints
        Constr confl = propagate();
        assert this.trail.size() == this.qhead;
        if (confl == null) {
            // No conflict found
            if (decisionLevel() == 0 && this.isDBSimplificationAllowed) {
                this.stats.rootSimplifications++;
                boolean ret = simplifyDB();
                assert ret;
            }
            assert nAssigns() <= this.voc.realnVars();
            if (nAssigns() == this.voc.realnVars()) {
                modelFound();
                this.slistener.solutionFound((this.fullmodel != null) ? this.fullmodel : this.model, this);
                if (this.sharedConflict == null) {
                    cancelUntil(this.rootLevel);
                    return Lbool.TRUE;
                } else {
                    confl = this.sharedConflict;
                }
            } else {
                if (this.restarter.shouldRestart()) {
                    cancelUntil(this.rootLevel);
                    return Lbool.UNDEFINED;
                }
                if (this.needToReduceDB) {
                    reduceDB();
                    this.needToReduceDB = false;
                }
                if (this.sharedConflict == null) {
                    // New variable decision
                    this.stats.decisions++;
                    int p = this.order.select();
                    if (p == ILits.UNDEFINED) {
                        confl = preventTheSameDecisionsToBeMade();
                        this.lastConflictMeansUnsat = false;
                    } else {
                        assert p > 1;
                        this.slistener.assuming(toDimacs(p));
                        boolean ret = assume(p);
                        assert ret;
                    }
                } else {
                    confl = this.sharedConflict;
                }
            }
        }
        if (confl != null) {
            // conflict found
            this.stats.conflicts++;
            this.slistener.conflictFound(confl, decisionLevel(), this.trail.size());
            this.conflictCount.newConflict();
            if (decisionLevel() == this.rootLevel) {
                if (this.lastConflictMeansUnsat) {
                    // conflict at root level, the formula is inconsistent
                    this.unsatExplanationInTermsOfAssumptions = analyzeFinalConflictInTermsOfAssumptions(confl, assumps, ILits.UNDEFINED);
                    return Lbool.FALSE;
                }
                return Lbool.UNDEFINED;
            }
            int conflictTrailLevel = this.trail.size();
            // analyze conflict
            try {
                analyze(confl, this.analysisResult);
            } catch (TimeoutException e) {
                return Lbool.UNDEFINED;
            }
            assert this.analysisResult.backtrackLevel < decisionLevel();
            backjumpLevel = Math.max(this.analysisResult.backtrackLevel, this.rootLevel);
            this.slistener.backjump(backjumpLevel);
            cancelUntil(backjumpLevel);
            if (backjumpLevel == this.rootLevel) {
                this.restarter.onBackjumpToRootLevel();
            }
            if (confl == this.sharedConflict) {
                this.sharedConflict.assertConstraintIfNeeded(this);
                this.sharedConflict = null;
            }
            assert decisionLevel() >= this.rootLevel && decisionLevel() >= this.analysisResult.backtrackLevel;
            if (this.analysisResult.reason == null) {
                return Lbool.FALSE;
            }
            record(this.analysisResult.reason);
            this.restarter.newLearnedClause(this.analysisResult.reason, conflictTrailLevel);
            this.analysisResult.reason = null;
            decayActivities();
        }
    } while (this.undertimeout);
    // timeout occured
    return Lbool.UNDEFINED;
}
Also used : IConstr(org.sat4j.specs.IConstr) TimeoutException(org.sat4j.specs.TimeoutException)

Aggregations

TimeoutException (org.sat4j.specs.TimeoutException)3 IConstr (org.sat4j.specs.IConstr)2 SemanticConditionList (abs.frontend.analyser.SemanticConditionList)1 LocationType (abs.frontend.typechecker.locationtypes.LocationType)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 WeightedMaxSatDecorator (org.sat4j.maxsat.WeightedMaxSatDecorator)1 WDimacsReader (org.sat4j.maxsat.reader.WDimacsReader)1 IPBSolver (org.sat4j.pb.IPBSolver)1 OptToPBSATAdapter (org.sat4j.pb.OptToPBSATAdapter)1 ParseFormatException (org.sat4j.reader.ParseFormatException)1 ContradictionException (org.sat4j.specs.ContradictionException)1 IProblem (org.sat4j.specs.IProblem)1