Search in sources :

Example 41 with NoGood

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

the class NaiveGrounder method bootstrap.

/**
 * Prepares facts of the input program for joining and derives all NoGoods representing ground rules. May only be called once.
 *
 * @return
 */
protected HashMap<Integer, NoGood> bootstrap() {
    final HashMap<Integer, NoGood> groundNogoods = new LinkedHashMap<>();
    for (Predicate predicate : factsFromProgram.keySet()) {
        // Instead of generating NoGoods, add instance to working memories directly.
        workingMemory.addInstances(predicate, true, factsFromProgram.get(predicate));
    }
    for (CompiledRule nonGroundRule : fixedRules) {
        // Generate NoGoods for all rules that have a fixed grounding.
        RuleGroundingOrder groundingOrder = nonGroundRule.getGroundingInfo().getFixedGroundingOrder();
        BindingResult bindingResult = getGroundInstantiations(nonGroundRule, groundingOrder, new BasicSubstitution(), null);
        groundAndRegister(nonGroundRule, bindingResult.getGeneratedSubstitutions(), groundNogoods);
    }
    fixedRules = null;
    return groundNogoods;
}
Also used : BindingResult(at.ac.tuwien.kr.alpha.core.grounder.instantiation.BindingResult) NoGood(at.ac.tuwien.kr.alpha.core.common.NoGood) CompiledRule(at.ac.tuwien.kr.alpha.core.rules.CompiledRule) BasicSubstitution(at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution) LinkedHashMap(java.util.LinkedHashMap) Predicate(at.ac.tuwien.kr.alpha.api.programs.Predicate)

Example 42 with NoGood

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

the class NaiveGrounder method groundAndRegister.

/**
 * Grounds the given {@code nonGroundRule} by applying the given {@code substitutions} and registers the nogoods generated during that
 * process.
 *
 * @param nonGroundRule the rule to be grounded.
 * @param substitutions the substitutions to be applied.
 * @param newNoGoods    a set of nogoods to which newly generated nogoods will be added.
 */
private void groundAndRegister(final CompiledRule nonGroundRule, final List<Substitution> substitutions, final Map<Integer, NoGood> newNoGoods) {
    for (Substitution substitution : substitutions) {
        List<NoGood> generatedNoGoods = noGoodGenerator.generateNoGoodsFromGroundSubstitution(nonGroundRule, substitution);
        registry.register(generatedNoGoods, newNoGoods);
    }
}
Also used : Substitution(at.ac.tuwien.kr.alpha.api.grounder.Substitution) BasicSubstitution(at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution) NoGood(at.ac.tuwien.kr.alpha.core.common.NoGood)

Example 43 with NoGood

use of at.ac.tuwien.kr.alpha.core.common.NoGood 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 44 with NoGood

use of at.ac.tuwien.kr.alpha.core.common.NoGood 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 45 with NoGood

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

the class NoGoodStoreAlphaRoamingTest method naryNoGoodViolatedAfterAddition.

@Test
public void naryNoGoodViolatedAfterAddition() {
    NoGood noGood = new NoGood(fromOldLiterals(1, 2, 3));
    assertNull(store.add(11, noGood));
    assertNull(assignment.assign(1, MBT));
    assertNull(assignment.assign(2, MBT));
    assertNull(assignment.assign(3, MBT));
    assertNotNull(store.propagate());
}
Also used : NoGood(at.ac.tuwien.kr.alpha.core.common.NoGood) Test(org.junit.jupiter.api.Test)

Aggregations

NoGood (at.ac.tuwien.kr.alpha.core.common.NoGood)91 Test (org.junit.jupiter.api.Test)73 Disabled (org.junit.jupiter.api.Disabled)10 TrailAssignment (at.ac.tuwien.kr.alpha.core.solver.TrailAssignment)4 LinkedHashMap (java.util.LinkedHashMap)4 Substitution (at.ac.tuwien.kr.alpha.api.grounder.Substitution)3 ASPCore2Program (at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program)3 NormalProgram (at.ac.tuwien.kr.alpha.api.programs.NormalProgram)3 Atom (at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)3 BasicSubstitution (at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution)3 RuleAtom (at.ac.tuwien.kr.alpha.core.atoms.RuleAtom)3 AtomStore (at.ac.tuwien.kr.alpha.core.common.AtomStore)3 AtomStoreImpl (at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl)3 StratifiedEvaluation (at.ac.tuwien.kr.alpha.core.programs.transformation.StratifiedEvaluation)3 CompiledRule (at.ac.tuwien.kr.alpha.core.rules.CompiledRule)3 ConflictAnalysisResult (at.ac.tuwien.kr.alpha.core.solver.learning.GroundConflictNoGoodLearner.ConflictAnalysisResult)3 Predicate (at.ac.tuwien.kr.alpha.api.programs.Predicate)2 Literal (at.ac.tuwien.kr.alpha.api.programs.literals.Literal)2 Literals.atomToLiteral (at.ac.tuwien.kr.alpha.core.atoms.Literals.atomToLiteral)2 Literals.atomToNegatedLiteral (at.ac.tuwien.kr.alpha.core.atoms.Literals.atomToNegatedLiteral)2