Search in sources :

Example 46 with Atom

use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom 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 47 with Atom

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

the class NoGoodGenerator method collectPosLiterals.

private List<Integer> collectPosLiterals(final CompiledRule nonGroundRule, final Substitution substitution) {
    final List<Integer> bodyLiteralsPositive = new ArrayList<>();
    for (Literal lit : nonGroundRule.getPositiveBody()) {
        if (lit instanceof FixedInterpretationLiteral) {
            // FixedInterpretationAtoms need not be shown to the solver, skip it.
            continue;
        }
        final Atom atom = lit.getAtom();
        // Skip the special enumeration atom.
        if (atom instanceof EnumerationAtom) {
            continue;
        }
        final Atom groundAtom = atom.substitute(substitution);
        // Consider facts to eliminate ground atoms from the generated nogoods that are always true
        // and eliminate nogoods that are always satisfied due to facts.
        Set<Instance> factInstances = factsFromProgram.get(groundAtom.getPredicate());
        if (factInstances != null && factInstances.contains(new Instance(groundAtom.getTerms()))) {
            // Skip positive atoms that are always true.
            continue;
        }
        if (!existsRuleWithPredicateInHead(groundAtom.getPredicate())) {
            // Atom is no fact and no rule defines it, it cannot be derived (i.e., is always false), skip whole rule as it will never fire.
            return null;
        }
        bodyLiteralsPositive.add(atomToLiteral(atomStore.putIfAbsent(groundAtom)));
    }
    return bodyLiteralsPositive;
}
Also used : FixedInterpretationLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.FixedInterpretationLiteral) Instance(at.ac.tuwien.kr.alpha.commons.substitutions.Instance) FixedInterpretationLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.FixedInterpretationLiteral) Literals.negateLiteral(at.ac.tuwien.kr.alpha.core.atoms.Literals.negateLiteral) Literal(at.ac.tuwien.kr.alpha.api.programs.literals.Literal) Literals.atomToLiteral(at.ac.tuwien.kr.alpha.core.atoms.Literals.atomToLiteral) ArrayList(java.util.ArrayList) EnumerationAtom(at.ac.tuwien.kr.alpha.core.atoms.EnumerationAtom) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) EnumerationAtom(at.ac.tuwien.kr.alpha.core.atoms.EnumerationAtom) RuleAtom(at.ac.tuwien.kr.alpha.core.atoms.RuleAtom)

Example 48 with Atom

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

the class NoGoodGenerator method generateNoGoodsFromGroundSubstitution.

/**
 * Generates all NoGoods resulting from a non-ground rule and a variable substitution.
 *
 * @param nonGroundRule
 *          the non-ground rule.
 * @param substitution
 *          the grounding substitution, i.e., applying substitution to nonGroundRule results in a ground rule.
 *          Assumption: atoms with fixed interpretation evaluate to true under the substitution.
 * @return a list of the NoGoods corresponding to the ground rule.
 */
List<NoGood> generateNoGoodsFromGroundSubstitution(final CompiledRule nonGroundRule, final Substitution substitution) {
    final List<Integer> posLiterals = collectPosLiterals(nonGroundRule, substitution);
    final List<Integer> negLiterals = collectNegLiterals(nonGroundRule, substitution);
    if (posLiterals == null || negLiterals == null) {
        return emptyList();
    }
    // A constraint is represented by exactly one nogood.
    if (nonGroundRule.isConstraint()) {
        return singletonList(NoGood.fromConstraint(posLiterals, negLiterals));
    }
    final List<NoGood> result = new ArrayList<>();
    final Atom groundHeadAtom = nonGroundRule.getHeadAtom().substitute(substitution);
    final int headId = atomStore.putIfAbsent(groundHeadAtom);
    // Prepare atom representing the rule body.
    final RuleAtom bodyAtom = new RuleAtom(nonGroundRule, substitution);
    // body representing atom already has an id.
    if (atomStore.contains(bodyAtom)) {
        // therefore all nogoods have already been created.
        return emptyList();
    }
    final int bodyRepresentingLiteral = atomToLiteral(atomStore.putIfAbsent(bodyAtom));
    final int headLiteral = atomToLiteral(atomStore.putIfAbsent(nonGroundRule.getHeadAtom().substitute(substitution)));
    choiceRecorder.addHeadToBody(headId, atomOf(bodyRepresentingLiteral));
    // Create a nogood for the head.
    result.add(NoGood.headFirst(negateLiteral(headLiteral), bodyRepresentingLiteral));
    final NoGood ruleBody = NoGood.fromBody(posLiterals, negLiterals, bodyRepresentingLiteral);
    result.add(ruleBody);
    // Nogoods such that the atom representing the body is true iff the body is true.
    for (int j = 1; j < ruleBody.size(); j++) {
        result.add(new NoGood(bodyRepresentingLiteral, negateLiteral(ruleBody.getLiteral(j))));
    }
    // If the rule head is unique, add support.
    if (uniqueGroundRulePerGroundHead.contains(nonGroundRule)) {
        result.add(NoGood.support(headLiteral, bodyRepresentingLiteral));
    }
    // If the body of the rule contains negation, add choices.
    if (!negLiterals.isEmpty()) {
        result.addAll(choiceRecorder.generateChoiceNoGoods(posLiterals, negLiterals, bodyRepresentingLiteral));
    }
    return result;
}
Also used : NoGood(at.ac.tuwien.kr.alpha.core.common.NoGood) ArrayList(java.util.ArrayList) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) EnumerationAtom(at.ac.tuwien.kr.alpha.core.atoms.EnumerationAtom) RuleAtom(at.ac.tuwien.kr.alpha.core.atoms.RuleAtom) RuleAtom(at.ac.tuwien.kr.alpha.core.atoms.RuleAtom)

Example 49 with Atom

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

the class AnswerSetQueryTest method matchSymbolicConstant.

@Test
public void matchSymbolicConstant() {
    AnswerSetBuilder bld = new AnswerSetBuilder();
    bld.predicate("p").symbolicInstance("a").instance("a");
    AnswerSet as = bld.build();
    AnswerSetQueryImpl constantQuery = AnswerSetQueryImpl.forPredicate(Predicates.getPredicate("p", 1)).withConstantEquals(0, "a");
    List<Atom> queryResult = as.query(constantQuery);
    assertEquals(1, queryResult.size());
}
Also used : AnswerSet(at.ac.tuwien.kr.alpha.api.AnswerSet) AnswerSetBuilder(at.ac.tuwien.kr.alpha.commons.AnswerSetBuilder) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) Test(org.junit.jupiter.api.Test)

Example 50 with Atom

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

the class AnswerSetQueryTest method matchTerm.

@Test
public void matchTerm() {
    AnswerSetBuilder bld = new AnswerSetBuilder();
    bld.predicate("p").instance(1).instance(2).instance(3).instance(4).instance(5).instance("bla").symbolicInstance("blubb");
    AnswerSet as = bld.build();
    AnswerSetQueryImpl equalTerm = AnswerSetQueryImpl.forPredicate(Predicates.getPredicate("p", 1)).withTermEquals(0, Terms.newConstant(1));
    List<Atom> queryResult = as.query(equalTerm);
    assertEquals(1, queryResult.size());
    Atom retrievedAtom = queryResult.get(0);
    assertTrue(retrievedAtom.getTerms().get(0).equals(Terms.newConstant(1)));
}
Also used : AnswerSet(at.ac.tuwien.kr.alpha.api.AnswerSet) AnswerSetBuilder(at.ac.tuwien.kr.alpha.commons.AnswerSetBuilder) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) Test(org.junit.jupiter.api.Test)

Aggregations

Atom (at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)73 Test (org.junit.jupiter.api.Test)38 Predicate (at.ac.tuwien.kr.alpha.api.programs.Predicate)27 BasicAtom (at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom)27 LinkedHashSet (java.util.LinkedHashSet)16 Unifier (at.ac.tuwien.kr.alpha.commons.substitutions.Unifier)15 ArrayList (java.util.ArrayList)14 AnswerSet (at.ac.tuwien.kr.alpha.api.AnswerSet)13 Literal (at.ac.tuwien.kr.alpha.api.programs.literals.Literal)12 AtomStoreImpl (at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl)11 Instance (at.ac.tuwien.kr.alpha.commons.substitutions.Instance)9 AtomStore (at.ac.tuwien.kr.alpha.core.common.AtomStore)9 WorkingMemory (at.ac.tuwien.kr.alpha.core.grounder.WorkingMemory)9 TrailAssignment (at.ac.tuwien.kr.alpha.core.solver.TrailAssignment)9 ASPCore2Program (at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program)8 RuleAtom (at.ac.tuwien.kr.alpha.core.atoms.RuleAtom)8 WritableAssignment (at.ac.tuwien.kr.alpha.core.solver.WritableAssignment)7 Substitution (at.ac.tuwien.kr.alpha.api.grounder.Substitution)6 ExternalAtom (at.ac.tuwien.kr.alpha.api.programs.atoms.ExternalAtom)6 AnswerSetBuilder (at.ac.tuwien.kr.alpha.commons.AnswerSetBuilder)6