Search in sources :

Example 36 with Predicate

use of at.ac.tuwien.kr.alpha.api.programs.Predicate in project Alpha by alpha-asp.

the class NaiveGrounder method getNoGoods.

@Override
public Map<Integer, NoGood> getNoGoods(Assignment currentAssignment) {
    // In first call, prepare facts and ground rules.
    final Map<Integer, NoGood> newNoGoods = fixedRules != null ? bootstrap() : new LinkedHashMap<>();
    // Compute new ground rule (evaluate joins with newly changed atoms)
    for (IndexedInstanceStorage modifiedWorkingMemory : workingMemory.modified()) {
        // Skip predicates solely used in the solver which do not occur in rules.
        Predicate workingMemoryPredicate = modifiedWorkingMemory.getPredicate();
        if (workingMemoryPredicate.isSolverInternal()) {
            continue;
        }
        // Iterate over all rules whose body contains the interpretation corresponding to the current workingMemory.
        final ArrayList<FirstBindingAtom> firstBindingAtoms = rulesUsingPredicateWorkingMemory.get(modifiedWorkingMemory);
        // Skip working memories that are not used by any rule.
        if (firstBindingAtoms == null) {
            continue;
        }
        for (FirstBindingAtom firstBindingAtom : firstBindingAtoms) {
            // Use the recently added instances from the modified working memory to construct an initial substitution
            CompiledRule nonGroundRule = firstBindingAtom.rule;
            // Generate substitutions from each recent instance.
            for (Instance instance : modifiedWorkingMemory.getRecentlyAddedInstances()) {
                // Check instance if it matches with the atom.
                final Substitution unifier = BasicSubstitution.specializeSubstitution(firstBindingAtom.startingLiteral, instance, BasicSubstitution.EMPTY_SUBSTITUTION);
                if (unifier == null) {
                    continue;
                }
                final BindingResult bindingResult = getGroundInstantiations(nonGroundRule, nonGroundRule.getGroundingInfo().orderStartingFrom(firstBindingAtom.startingLiteral), unifier, currentAssignment);
                groundAndRegister(nonGroundRule, bindingResult.getGeneratedSubstitutions(), newNoGoods);
            }
        }
        // Mark instances added by updateAssignment as done
        modifiedWorkingMemory.markRecentlyAddedInstancesDone();
    }
    workingMemory.reset();
    for (Atom removeAtom : removeAfterObtainingNewNoGoods) {
        final IndexedInstanceStorage storage = workingMemory.get(removeAtom, true);
        Instance instance = new Instance(removeAtom.getTerms());
        if (storage.containsInstance(instance)) {
            // permissive grounder heuristics may attempt to remove instances that are not yet in the working memory
            storage.removeInstance(instance);
        }
    }
    // Re-Initialize the stale working memory entries set and pass to instantiation strategy.
    removeAfterObtainingNewNoGoods = new LinkedHashSet<>();
    instantiationStrategy.setStaleWorkingMemoryEntries(removeAfterObtainingNewNoGoods);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Grounded NoGoods are:");
        for (Map.Entry<Integer, NoGood> noGoodEntry : newNoGoods.entrySet()) {
            LOGGER.debug("{} == {}", noGoodEntry.getValue(), atomStore.noGoodToString(noGoodEntry.getValue()));
        }
        LOGGER.debug("{}", choiceRecorder);
    }
    if (debugInternalChecks) {
        checkTypesOfNoGoods(newNoGoods.values());
    }
    return newNoGoods;
}
Also used : BindingResult(at.ac.tuwien.kr.alpha.core.grounder.instantiation.BindingResult) Instance(at.ac.tuwien.kr.alpha.commons.substitutions.Instance) NoGood(at.ac.tuwien.kr.alpha.core.common.NoGood) ChoiceAtom(at.ac.tuwien.kr.alpha.core.atoms.ChoiceAtom) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) RuleAtom(at.ac.tuwien.kr.alpha.core.atoms.RuleAtom) Predicate(at.ac.tuwien.kr.alpha.api.programs.Predicate) Substitution(at.ac.tuwien.kr.alpha.api.grounder.Substitution) BasicSubstitution(at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution) CompiledRule(at.ac.tuwien.kr.alpha.core.rules.CompiledRule) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 37 with Predicate

use of at.ac.tuwien.kr.alpha.api.programs.Predicate in project Alpha by alpha-asp.

the class BasicAnswerSetTest method areAnswerSetsEqual.

@Test
public void areAnswerSetsEqual() {
    Predicate a = Predicates.getPredicate("a", 0);
    Predicate foo = Predicates.getPredicate("foo", 1);
    SortedSet<Predicate> fooAndA = new TreeSet<>(asList(foo, a));
    Predicate q = Predicates.getPredicate("q", 0);
    Predicate p = Predicates.getPredicate("p", 1);
    SortedSet<Predicate> qAndP = new TreeSet<>(asList(q, p));
    ConstantTerm<?> bar = Terms.newConstant("bar");
    ConstantTerm<?> baz = Terms.newConstant("baz");
    Map<Predicate, SortedSet<Atom>> inst1 = new HashMap<>();
    inst1.put(a, new TreeSet<>(singleton(Atoms.newBasicAtom(a))));
    inst1.put(foo, new TreeSet<>(asList(Atoms.newBasicAtom(foo, bar), Atoms.newBasicAtom(foo, baz))));
    // as1 = { a, foo(bar), foo(baz) }
    Map<Predicate, SortedSet<Atom>> inst2 = new HashMap<>();
    inst2.put(a, new TreeSet<>(singleton(Atoms.newBasicAtom(a))));
    inst2.put(foo, new TreeSet<>(asList(Atoms.newBasicAtom(foo, baz), Atoms.newBasicAtom(foo, bar))));
    // as1 = { a, foo(baz), foo(bar) }
    Map<Predicate, SortedSet<Atom>> inst3 = new HashMap<>();
    inst3.put(q, new TreeSet<>(singleton(Atoms.newBasicAtom(q))));
    inst3.put(p, new TreeSet<>(asList(Atoms.newBasicAtom(p, bar), Atoms.newBasicAtom(p, baz))));
    // as3 = { q, p(bar), p(baz) }
    Map<Predicate, SortedSet<Atom>> inst4 = new HashMap<>();
    inst4.put(a, new TreeSet<>(singleton(Atoms.newBasicAtom(a))));
    inst4.put(foo, new TreeSet<>(asList(Atoms.newBasicAtom(foo, bar), Atoms.newBasicAtom(foo, baz), Atoms.newBasicAtom(foo, Terms.newConstant("batsinga")))));
    // as4 = { a, foo(bar), foo(baz), foo(batsinga) }
    final List<AnswerSet> answerSets = asList(new BasicAnswerSet(fooAndA, inst1), new BasicAnswerSet(fooAndA, inst2), new BasicAnswerSet(qAndP, inst3), new BasicAnswerSet(fooAndA, inst4));
    assertEquals(answerSets.get(0), answerSets.get(1));
    assertEquals(answerSets.get(1), answerSets.get(0));
    assertNotEquals(answerSets.get(0), answerSets.get(2));
    assertNotEquals(answerSets.get(0), answerSets.get(3));
}
Also used : HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) AnswerSet(at.ac.tuwien.kr.alpha.api.AnswerSet) SortedSet(java.util.SortedSet) Predicate(at.ac.tuwien.kr.alpha.api.programs.Predicate) Test(org.junit.jupiter.api.Test)

Example 38 with Predicate

use of at.ac.tuwien.kr.alpha.api.programs.Predicate in project Alpha by alpha-asp.

the class LiteralInstantiationStrategyTest method defaultLazyGroundingSubstituteNonGroundLiteralWithTrueInstance.

/**
 * Uses {@link DefaultLazyGroundingInstantiationStrategy} to find the ground
 * instance "q(a, b)" for the partially ground positive literal "q(a, X)".
 *
 * In this case, the instantiation strategy has an assignment where q(a, b) is
 * assigned ThriceTruth.TRUE, so we expect the assignment status (i.e.
 * assignment status of the found ground instance) passed back with the
 * substitution to be TRUE. Furthermore, we expect the stale atom set to stay
 * empty.
 */
@Test
public void defaultLazyGroundingSubstituteNonGroundLiteralWithTrueInstance() {
    Predicate q = Predicates.getPredicate("q", 2);
    BasicAtom nonGroundAtom = Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newVariable("X"));
    WorkingMemory workingMemory = new WorkingMemory();
    workingMemory.initialize(q);
    workingMemory.addInstance(Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newSymbolicConstant("b")), true);
    AtomStore atomStore = new AtomStoreImpl();
    WritableAssignment assignment = new TrailAssignment(atomStore);
    BasicAtom groundAtom = Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newSymbolicConstant("b"));
    atomStore.putIfAbsent(groundAtom);
    assignment.growForMaxAtomId();
    assignment.assign(atomStore.get(groundAtom), ThriceTruth.TRUE);
    LinkedHashSet<Atom> staleSet = new LinkedHashSet<>();
    DefaultLazyGroundingInstantiationStrategy strategy = new DefaultLazyGroundingInstantiationStrategy(workingMemory, atomStore, Collections.emptyMap(), false);
    strategy.setStaleWorkingMemoryEntries(staleSet);
    strategy.setCurrentAssignment(assignment);
    List<ImmutablePair<Substitution, AssignmentStatus>> result = strategy.getAcceptedSubstitutions(Literals.fromAtom(nonGroundAtom, true), new BasicSubstitution());
    assertEquals(1, result.size());
    ImmutablePair<Substitution, AssignmentStatus> substitutionInfo = result.get(0);
    Substitution substitution = substitutionInfo.left;
    AssignmentStatus assignmentStatus = substitutionInfo.right;
    assertEquals(AssignmentStatus.TRUE, assignmentStatus);
    assertTrue(substitution.isVariableSet(Terms.newVariable("X")));
    assertEquals(Terms.newSymbolicConstant("b"), substitution.eval(Terms.newVariable("X")));
    assertTrue(staleSet.isEmpty());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) WorkingMemory(at.ac.tuwien.kr.alpha.core.grounder.WorkingMemory) BasicSubstitution(at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution) AtomStoreImpl(at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl) TrailAssignment(at.ac.tuwien.kr.alpha.core.solver.TrailAssignment) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) Predicate(at.ac.tuwien.kr.alpha.api.programs.Predicate) AtomStore(at.ac.tuwien.kr.alpha.core.common.AtomStore) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Substitution(at.ac.tuwien.kr.alpha.api.grounder.Substitution) BasicSubstitution(at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution) WritableAssignment(at.ac.tuwien.kr.alpha.core.solver.WritableAssignment) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) Test(org.junit.jupiter.api.Test)

Example 39 with Predicate

use of at.ac.tuwien.kr.alpha.api.programs.Predicate in project Alpha by alpha-asp.

the class AnalyzeUnjustifiedTest method justifyMultipleReasons.

@Test
public void justifyMultipleReasons() {
    String program = "n(a). n(b). n(c). n(d). n(e)." + "s(a,b). s(b,c). s(c,d). s(d,e)." + "{ q(X) } :- n(X)." + "p(X) :- q(X)." + "p(X) :- p(Y), s(Y,X)." + ":- not p(c).";
    CompiledProgram internalProgram = parseAndPreprocess.apply(program);
    AtomStore atomStore = new AtomStoreImpl();
    NaiveGrounder grounder = new NaiveGrounder(internalProgram, atomStore, true);
    grounder.getNoGoods(null);
    TrailAssignment assignment = new TrailAssignment(atomStore);
    Atom qa = parser.parse("q(a).").getFacts().get(0);
    Atom qb = parser.parse("q(b).").getFacts().get(0);
    Atom qc = parser.parse("q(c).").getFacts().get(0);
    Atom qd = parser.parse("q(d).").getFacts().get(0);
    Atom qe = parser.parse("q(e).").getFacts().get(0);
    int qaId = atomStore.get(qa);
    int qbId = atomStore.get(qb);
    int qcId = atomStore.get(qc);
    int qdId = atomStore.get(qd);
    int qeId = atomStore.get(qe);
    assignment.growForMaxAtomId();
    assignment.assign(qaId, ThriceTruth.FALSE);
    assignment.assign(qbId, ThriceTruth.FALSE);
    assignment.assign(qcId, ThriceTruth.FALSE);
    assignment.assign(qdId, ThriceTruth.FALSE);
    assignment.assign(qeId, ThriceTruth.FALSE);
    Predicate nq = Predicates.getPredicate("_nq", 2, true);
    Atom nqa = Atoms.newBasicAtom(nq, Arrays.asList(Terms.newConstant("1"), Terms.newSymbolicConstant("a")));
    Atom nqb = Atoms.newBasicAtom(nq, Arrays.asList(Terms.newConstant("1"), Terms.newSymbolicConstant("b")));
    Atom nqc = Atoms.newBasicAtom(nq, Arrays.asList(Terms.newConstant("1"), Terms.newSymbolicConstant("c")));
    Atom nqd = Atoms.newBasicAtom(nq, Arrays.asList(Terms.newConstant("1"), Terms.newSymbolicConstant("d")));
    Atom nqe = Atoms.newBasicAtom(nq, Arrays.asList(Terms.newConstant("1"), Terms.newSymbolicConstant("e")));
    int nqaId = atomStore.get(nqa);
    int nqbId = atomStore.get(nqb);
    int nqcId = atomStore.get(nqc);
    int nqdId = atomStore.get(nqd);
    int nqeId = atomStore.get(nqe);
    assignment.growForMaxAtomId();
    assignment.assign(nqaId, ThriceTruth.TRUE);
    assignment.assign(nqbId, ThriceTruth.TRUE);
    assignment.assign(nqcId, ThriceTruth.TRUE);
    assignment.assign(nqdId, ThriceTruth.TRUE);
    assignment.assign(nqeId, ThriceTruth.TRUE);
    Atom pc = parser.parse("p(c).").getFacts().get(0);
    Set<Literal> reasons = grounder.justifyAtom(atomStore.get(pc), assignment);
    assertFalse(reasons.isEmpty());
}
Also used : NaiveGrounder(at.ac.tuwien.kr.alpha.core.grounder.NaiveGrounder) AtomStore(at.ac.tuwien.kr.alpha.core.common.AtomStore) Literal(at.ac.tuwien.kr.alpha.api.programs.literals.Literal) AtomStoreImpl(at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl) CompiledProgram(at.ac.tuwien.kr.alpha.core.programs.CompiledProgram) TrailAssignment(at.ac.tuwien.kr.alpha.core.solver.TrailAssignment) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) Predicate(at.ac.tuwien.kr.alpha.api.programs.Predicate) Test(org.junit.jupiter.api.Test)

Example 40 with Predicate

use of at.ac.tuwien.kr.alpha.api.programs.Predicate in project Alpha by alpha-asp.

the class StratifiedEvaluationRegressionTest method verifyProgramPositiveRecursive.

private static void verifyProgramPositiveRecursive(CompiledProgram evaluated) {
    Predicate num = Predicates.getPredicate("num", 1);
    TestUtils.assertFactsContainedInProgram(evaluated, Atoms.newBasicAtom(Predicates.getPredicate("max_num", 1), Terms.newConstant(10)), Atoms.newBasicAtom(num, Terms.newConstant(0)), Atoms.newBasicAtom(num, Terms.newConstant(1)), Atoms.newBasicAtom(num, Terms.newConstant(2)), Atoms.newBasicAtom(num, Terms.newConstant(3)), Atoms.newBasicAtom(num, Terms.newConstant(4)), Atoms.newBasicAtom(num, Terms.newConstant(5)), Atoms.newBasicAtom(num, Terms.newConstant(6)), Atoms.newBasicAtom(num, Terms.newConstant(7)), Atoms.newBasicAtom(num, Terms.newConstant(8)), Atoms.newBasicAtom(num, Terms.newConstant(9)), Atoms.newBasicAtom(num, Terms.newConstant(10)));
    LOGGER.debug("Recursive program evaluated is:\n{}", evaluated.toString());
    assertEquals(0, evaluated.getRules().size());
}
Also used : Predicate(at.ac.tuwien.kr.alpha.api.programs.Predicate)

Aggregations

Predicate (at.ac.tuwien.kr.alpha.api.programs.Predicate)69 Test (org.junit.jupiter.api.Test)37 Atom (at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)27 BasicAtom (at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom)19 WorkingMemory (at.ac.tuwien.kr.alpha.core.grounder.WorkingMemory)15 Literal (at.ac.tuwien.kr.alpha.api.programs.literals.Literal)14 AnswerSet (at.ac.tuwien.kr.alpha.api.AnswerSet)13 BasicSubstitution (at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution)13 LinkedHashSet (java.util.LinkedHashSet)13 Substitution (at.ac.tuwien.kr.alpha.api.grounder.Substitution)11 AtomStoreImpl (at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl)10 ArrayList (java.util.ArrayList)10 DependencyGraph (at.ac.tuwien.kr.alpha.api.programs.analysis.DependencyGraph)9 ComponentGraph (at.ac.tuwien.kr.alpha.api.programs.analysis.ComponentGraph)8 Term (at.ac.tuwien.kr.alpha.api.terms.Term)8 AtomStore (at.ac.tuwien.kr.alpha.core.common.AtomStore)8 AnalyzedProgram (at.ac.tuwien.kr.alpha.core.programs.AnalyzedProgram)8 CompiledRule (at.ac.tuwien.kr.alpha.core.rules.CompiledRule)8 TrailAssignment (at.ac.tuwien.kr.alpha.core.solver.TrailAssignment)8 HashMap (java.util.HashMap)8