Search in sources :

Example 21 with AnswerSet

use of at.ac.tuwien.kr.alpha.common.AnswerSet in project Alpha by alpha-asp.

the class DefaultSolver method tryAdvance.

@Override
protected boolean tryAdvance(Consumer<? super AnswerSet> action) {
    // Initially, get NoGoods from grounder.
    if (initialize) {
        if (!obtainNoGoodsFromGrounder()) {
            logSizeOfSearchTree();
            return false;
        }
        initialize = false;
    } else {
        // Create enumeration NoGood to avoid finding the same Answer-Set twice.
        if (!isSearchSpaceExhausted()) {
            NoGood enumerationNoGood = createEnumerationNoGood();
            int backjumpLevel = computeMinimumConflictLevel(enumerationNoGood);
            if (backjumpLevel == -1) {
                throw new RuntimeException("Enumeration NoGood is currently not violated. Should not happen.");
            }
            if (backjumpLevel == 0) {
                // Search space exhausted (only happens if first guess is for TRUE at decision level 1 for an atom that was MBT at decision level 0 already).
                return false;
            }
            // Backjump instead of backtrack, enumerationNoGood will invert lass guess.
            doBackjump(backjumpLevel - 1);
            LOGGER.debug("Adding enumeration NoGood: {}", enumerationNoGood);
            NoGoodStore.ConflictCause conflictCause = store.add(grounder.registerOutsideNoGood(enumerationNoGood), enumerationNoGood);
            if (conflictCause != null) {
                throw new RuntimeException("Adding enumeration NoGood causes conflicts after backjump. Should not happen.");
            }
        } else {
            logSizeOfSearchTree();
            return false;
        }
    }
    int nextChoice;
    boolean afterAllAtomsAssigned = false;
    // Try all assignments until grounder reports no more NoGoods and all of them are satisfied
    while (true) {
        didChange |= store.propagate();
        LOGGER.trace("Assignment after propagation is: {}", assignment);
        if (store.getViolatedNoGood() != null) {
            // Learn from conflict.
            NoGood violatedNoGood = store.getViolatedNoGood();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("NoGood violated ({}) by wrong choices ({} violated): {}", grounder.noGoodToString(violatedNoGood), choiceStack);
            }
            LOGGER.debug("Violating assignment is: {}", assignment);
            branchingHeuristic.violatedNoGood(violatedNoGood);
            if (!afterAllAtomsAssigned) {
                if (!learnBackjumpAddFromConflict()) {
                    logSizeOfSearchTree();
                    return false;
                }
            } else {
                // Will not learn from violated NoGood, do simple backtrack.
                LOGGER.debug("NoGood was violated after all unassigned atoms were assigned to false; will not learn from it; skipping.");
                doBacktrack();
                afterAllAtomsAssigned = false;
                if (isSearchSpaceExhausted()) {
                    logSizeOfSearchTree();
                    return false;
                }
            }
        } else if (!propagationFixpointReached()) {
            // Ask the grounder for new NoGoods, then propagate (again).
            LOGGER.trace("Doing propagation step.");
            updateGrounderAssignment();
            if (!obtainNoGoodsFromGrounder()) {
                logSizeOfSearchTree();
                return false;
            }
        } else if ((nextChoice = computeChoice()) != 0) {
            LOGGER.debug("Doing choice.");
            doChoice(nextChoice);
        } else if (!allAtomsAssigned()) {
            LOGGER.debug("Closing unassigned known atoms (assigning FALSE).");
            assignUnassignedToFalse();
            afterAllAtomsAssigned = true;
        } else if (assignment.getMBTCount() == 0) {
            AnswerSet as = translate(assignment.getTrueAssignments());
            LOGGER.debug("Answer-Set found: {}", as);
            LOGGER.debug("Choices of Answer-Set were: {}", choiceStack);
            action.accept(as);
            logSizeOfSearchTree();
            return true;
        } else {
            LOGGER.debug("Backtracking from wrong choices ({} MBTs): {}", assignment.getMBTCount(), choiceStack);
            counters.remainingMBTAtFixpointCounter++;
            doBacktrack();
            afterAllAtomsAssigned = false;
            if (isSearchSpaceExhausted()) {
                logSizeOfSearchTree();
                return false;
            }
        }
    }
}
Also used : NoGood(at.ac.tuwien.kr.alpha.common.NoGood) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet)

Example 22 with AnswerSet

use of at.ac.tuwien.kr.alpha.common.AnswerSet in project Alpha by alpha-asp.

the class NaiveSolver method tryAdvance.

@Override
protected boolean tryAdvance(Consumer<? super AnswerSet> action) {
    // Get basic rules and facts from grounder
    if (doInit) {
        obtainNoGoodsFromGrounder();
        doInit = false;
    } else {
        // We already found one Answer-Set and are requested to find another one
        doBacktrack();
        if (isSearchSpaceExhausted()) {
            return false;
        }
    }
    // Try all assignments until grounder reports no more NoGoods and all of them are satisfied
    while (true) {
        if (!propagationFixpointReached()) {
            LOGGER.trace("Propagating.");
            // After a choice, it would be more efficient to propagate first and only then ask the grounder.
            updateGrounderAssignments();
            obtainNoGoodsFromGrounder();
            doUnitPropagation();
            doMBTPropagation();
            LOGGER.trace("Assignment after propagation is: {}", truthAssignments);
        } else if (assignmentViolatesNoGoods()) {
            LOGGER.trace("Backtracking from wrong choices:");
            LOGGER.trace("Choice stack: {}", choiceStack);
            doBacktrack();
            if (isSearchSpaceExhausted()) {
                return false;
            }
        } else if (choicesLeft()) {
            doChoice();
        } else if (!allAtomsAssigned()) {
            LOGGER.trace("Closing unassigned known atoms (assigning FALSE).");
            assignUnassignedToFalse();
            didChange = true;
        } else if (noMBTValuesReamining()) {
            AnswerSet as = getAnswerSetFromAssignment();
            LOGGER.debug("Answer-Set found: {}", as);
            LOGGER.trace("Choice stack: {}", choiceStack);
            action.accept(as);
            return true;
        } else {
            LOGGER.debug("Backtracking from wrong choices (MBT remaining):");
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Currently MBT:");
                for (Integer integer : mbtAssigned) {
                    LOGGER.trace(grounder.atomToString(integer));
                }
                LOGGER.trace("Choice stack: {}", choiceStack);
            }
            doBacktrack();
            if (isSearchSpaceExhausted()) {
                return false;
            }
        }
    }
}
Also used : AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet)

Example 23 with AnswerSet

use of at.ac.tuwien.kr.alpha.common.AnswerSet in project Alpha by alpha-asp.

the class PigeonHoleTest method testPigeonsHoles.

/**
	 * Tries to solve the problem of assigning P pigeons to H holes.
	 */
private void testPigeonsHoles(int pigeons, int holes) throws IOException {
    List<String> rules = new ArrayList<>();
    rules.add("pos(P,H) :- pigeon(P), hole(H), not negpos(P,H).");
    rules.add("negpos(P,H) :- pigeon(P), hole(H), not pos(P,H).");
    rules.add(":- pigeon(P), hole(H1), hole(H2), pos(P,H1), pos(P,H2), H1 != H2.");
    rules.add(":- pigeon(P), not hashole(P).");
    rules.add("hashole(P) :- pigeon(P), hole(H), pos(P,H).");
    rules.add(":- pigeon(P1), pigeon(P2), hole(H), pos(P1,H), pos(P2,H), P1 != P2.");
    addPigeons(rules, pigeons);
    addHoles(rules, holes);
    String testProgram = concat(rules);
    ParsedProgram parsedProgram = parseVisit(testProgram);
    NaiveGrounder grounder = new NaiveGrounder(parsedProgram);
    Solver solver = getInstance(grounder);
    Set<AnswerSet> answerSets = solver.collectSet();
    Assert.assertEquals(numberOfSolutions(pigeons, holes), answerSets.size());
    solver.stream().findAny();
}
Also used : NaiveGrounder(at.ac.tuwien.kr.alpha.grounder.NaiveGrounder) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet)

Example 24 with AnswerSet

use of at.ac.tuwien.kr.alpha.common.AnswerSet in project Alpha by alpha-asp.

the class RacksTest method test.

private void test() throws IOException {
    ANTLRFileStream programInputStream = new ANTLRFileStream(Paths.get("benchmarks", "siemens", "racks", "racks.lp").toString());
    ParsedProgram parsedProgram = parseVisit(programInputStream);
    NaiveGrounder grounder = new NaiveGrounder(parsedProgram);
    Solver solver = getInstance(grounder);
    Optional<AnswerSet> answerSet = solver.stream().findFirst();
    System.out.println(answerSet);
    // TODO: check correctness of answer set
    System.out.println(((DefaultSolver) solver).getDecisionCounter() + " choices," + ((DefaultSolver) solver).getConflictCounter() + " conflicts");
}
Also used : ANTLRFileStream(org.antlr.v4.runtime.ANTLRFileStream) NaiveGrounder(at.ac.tuwien.kr.alpha.grounder.NaiveGrounder) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet)

Example 25 with AnswerSet

use of at.ac.tuwien.kr.alpha.common.AnswerSet in project Alpha by alpha-asp.

the class SolverTests method guessingProgramConstraint.

@Test
public void guessingProgramConstraint() throws IOException {
    String testProgram = "eq(1,1).\n" + "eq(2,2).\n" + "eq(3,3).\n" + "var(1).\n" + "var(2).\n" + "var(3).\n" + "val(VAR,1):-var(VAR),not val(VAR,2),not val(VAR,3).\n" + "val(VAR,2):-var(VAR),not val(VAR,1),not val(VAR,3).\n" + "val(VAR,3):-var(VAR),not val(VAR,1),not val(VAR,2).\n" + "%:- val(VAR1,VAL1), val(VAR2,VAL2), eq(VAL1,VAL2), not eq(VAR1,VAR2).\n" + ":- eq(VAL1,VAL2), not eq(VAR1,VAR2), val(VAR1,VAL1), val(VAR2,VAL2).";
    ParsedProgram parsedProgram = parseVisit(testProgram);
    NaiveGrounder grounder = new NaiveGrounder(parsedProgram);
    Solver solver = getInstance(grounder);
    final BasicAnswerSet.Builder base = new BasicAnswerSet.Builder().predicate("eq").instance("1", "1").instance("2", "2").instance("3", "3").predicate("var").instance("1").instance("2").instance("3");
    Set<AnswerSet> expected = new HashSet<>(Arrays.asList(new BasicAnswerSet.Builder(base).predicate("val").instance("1", "1").instance("2", "2").instance("3", "3").build(), new BasicAnswerSet.Builder(base).predicate("val").instance("1", "1").instance("3", "2").instance("2", "3").build(), new BasicAnswerSet.Builder(base).predicate("val").instance("2", "1").instance("1", "2").instance("3", "3").build(), new BasicAnswerSet.Builder(base).predicate("val").instance("2", "1").instance("3", "2").instance("1", "3").build(), new BasicAnswerSet.Builder(base).predicate("val").instance("3", "1").instance("1", "2").instance("2", "3").build(), new BasicAnswerSet.Builder(base).predicate("val").instance("3", "1").instance("2", "2").instance("1", "3").build()));
    Set<AnswerSet> answerSets = solver.collectSet();
    assertEquals(expected, answerSets);
}
Also used : BasicAnswerSet(at.ac.tuwien.kr.alpha.common.BasicAnswerSet) NaiveGrounder(at.ac.tuwien.kr.alpha.grounder.NaiveGrounder) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) BasicAnswerSet(at.ac.tuwien.kr.alpha.common.BasicAnswerSet) AnswerSet(at.ac.tuwien.kr.alpha.common.AnswerSet) Test(org.junit.Test)

Aggregations

AnswerSet (at.ac.tuwien.kr.alpha.common.AnswerSet)34 NaiveGrounder (at.ac.tuwien.kr.alpha.grounder.NaiveGrounder)31 ParsedProgram (at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram)28 BasicAnswerSet (at.ac.tuwien.kr.alpha.common.BasicAnswerSet)24 Test (org.junit.Test)24 Grounder (at.ac.tuwien.kr.alpha.grounder.Grounder)7 ChoiceGrounder (at.ac.tuwien.kr.alpha.grounder.ChoiceGrounder)6 DummyGrounder (at.ac.tuwien.kr.alpha.grounder.DummyGrounder)6 ANTLRFileStream (org.antlr.v4.runtime.ANTLRFileStream)2 ASPCore2Lexer (at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer)1 ASPCore2Parser (at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser)1 NoGood (at.ac.tuwien.kr.alpha.common.NoGood)1 Predicate (at.ac.tuwien.kr.alpha.common.Predicate)1 GrounderFactory (at.ac.tuwien.kr.alpha.grounder.GrounderFactory)1 ParsedTreeVisitor (at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor)1 IdentityProgramTransformation (at.ac.tuwien.kr.alpha.grounder.transformation.IdentityProgramTransformation)1 Solver (at.ac.tuwien.kr.alpha.solver.Solver)1 SolverFactory (at.ac.tuwien.kr.alpha.solver.SolverFactory)1 Heuristic (at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic)1 java.io (java.io)1