Search in sources :

Example 11 with Instance

use of at.ac.tuwien.kr.alpha.commons.substitutions.Instance in project Alpha by alpha-asp.

the class AbstractLiteralInstantiationStrategy method buildSubstitutionsFromInstances.

/**
 * Based on a list of candidate instances (see {@link AbstractLiteralInstantiationStrategy#computeCandidateInstances(Atom)}), create a list
 * of substitutions and assignment statuses such that each substitution represents a valid (according to the implementation-specific
 * definition of this instantiation strategy) ground instance of <code>atomToSubstitute</code>.
 *
 * @param atomToSubstitute
 * @param candidateInstances
 * @param partialSubstitution
 * @return
 */
protected final List<ImmutablePair<Substitution, AssignmentStatus>> buildSubstitutionsFromInstances(Atom atomToSubstitute, Iterable<Instance> candidateInstances, Substitution partialSubstitution) {
    List<ImmutablePair<Substitution, AssignmentStatus>> retVal = new ArrayList<>();
    // Filter for only instances unifying with partialSubsitution, i.e. "where all joins work out".
    Substitution currentInstanceSubstitution;
    Atom atomForCurrentInstance;
    for (Instance instance : candidateInstances) {
        currentInstanceSubstitution = BasicSubstitution.specializeSubstitution(atomToSubstitute, instance, partialSubstitution);
        if (currentInstanceSubstitution == null) {
            // Instance does not unify with partialSubstitution, move on to the next instance.
            continue;
        }
        // At this point, we know that the substitution works out.
        // Now check whether the resulting Atom has an acceptable AssignmentStatus.
        atomForCurrentInstance = Atoms.newBasicAtom(atomToSubstitute.getPredicate(), atomToSubstitute.getTerms()).substitute(currentInstanceSubstitution);
        AssignmentStatus assignmentStatus = this.getAssignmentStatusForAtom(atomForCurrentInstance);
        if (!this.assignmentStatusAccepted(assignmentStatus)) {
            // Atom has an assignment status deemed unacceptable by this instantiation strategy.
            continue;
        }
        retVal.add(new ImmutablePair<>(currentInstanceSubstitution, assignmentStatus));
    }
    return retVal;
}
Also used : 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) Instance(at.ac.tuwien.kr.alpha.commons.substitutions.Instance) ArrayList(java.util.ArrayList) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)

Example 12 with Instance

use of at.ac.tuwien.kr.alpha.commons.substitutions.Instance in project Alpha by alpha-asp.

the class IndexedInstanceStorage method getMostSelectiveGroundTermPosition.

private int getMostSelectiveGroundTermPosition(Atom atom) {
    int smallestNumberOfInstances = Integer.MAX_VALUE;
    int mostSelectiveTermPosition = -1;
    for (int i = 0; i < atom.getTerms().size(); i++) {
        Term testTerm = atom.getTerms().get(i);
        if (testTerm.isGround()) {
            ArrayList<Instance> instancesMatchingTest = indices.get(i).get(testTerm);
            if (instancesMatchingTest == null) {
                // Ground term at i matches zero instances, it is most selective.
                return i;
            }
            int numInstancesTestTerm = instancesMatchingTest.size();
            if (numInstancesTestTerm < smallestNumberOfInstances) {
                smallestNumberOfInstances = numInstancesTestTerm;
                mostSelectiveTermPosition = i;
            }
        }
    }
    return mostSelectiveTermPosition;
}
Also used : Instance(at.ac.tuwien.kr.alpha.commons.substitutions.Instance) Term(at.ac.tuwien.kr.alpha.api.terms.Term)

Example 13 with Instance

use of at.ac.tuwien.kr.alpha.commons.substitutions.Instance in project Alpha by alpha-asp.

the class IndexedInstanceStorage method addIndexPosition.

public void addIndexPosition(int position) {
    if (position < 0 || position > predicate.getArity() - 1) {
        throw new RuntimeException("Requested to create indices for attribute out of range." + "IndexedInstanceStorage: " + this + "  requested indices position: " + position);
    }
    // Add index
    indices.set(position, new LinkedHashMap<>());
    // Initialize index with all instances currently used.
    for (Instance instance : instances) {
        indices.get(position).putIfAbsent(instance.terms.get(position), new ArrayList<>());
        ArrayList<Instance> instancesAtPosition = indices.get(position).get(instance.terms.get(position));
        instancesAtPosition.add(instance);
    }
}
Also used : Instance(at.ac.tuwien.kr.alpha.commons.substitutions.Instance)

Example 14 with Instance

use of at.ac.tuwien.kr.alpha.commons.substitutions.Instance in project Alpha by alpha-asp.

the class NoGoodGenerator method collectNegLiterals.

List<Integer> collectNegLiterals(final CompiledRule nonGroundRule, final Substitution substitution) {
    final List<Integer> bodyLiteralsNegative = new ArrayList<>();
    for (Literal lit : nonGroundRule.getNegativeBody()) {
        Atom groundAtom = lit.getAtom().substitute(substitution);
        final Set<Instance> factInstances = factsFromProgram.get(groundAtom.getPredicate());
        if (factInstances != null && factInstances.contains(new Instance(groundAtom.getTerms()))) {
            // Negative atom that is always true encountered, skip whole rule as it will never fire.
            return null;
        }
        if (!existsRuleWithPredicateInHead(groundAtom.getPredicate())) {
            // Negative atom is no fact and no rule defines it, it is always false, skip it.
            continue;
        }
        bodyLiteralsNegative.add(atomToLiteral(atomStore.putIfAbsent(groundAtom)));
    }
    return bodyLiteralsNegative;
}
Also used : 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) 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 15 with Instance

use of at.ac.tuwien.kr.alpha.commons.substitutions.Instance 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)

Aggregations

Instance (at.ac.tuwien.kr.alpha.commons.substitutions.Instance)25 Atom (at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)10 Substitution (at.ac.tuwien.kr.alpha.api.grounder.Substitution)9 Literal (at.ac.tuwien.kr.alpha.api.programs.literals.Literal)9 BasicSubstitution (at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution)9 Predicate (at.ac.tuwien.kr.alpha.api.programs.Predicate)7 CompiledRule (at.ac.tuwien.kr.alpha.core.rules.CompiledRule)7 ArrayList (java.util.ArrayList)7 Map (java.util.Map)7 RuleAtom (at.ac.tuwien.kr.alpha.core.atoms.RuleAtom)5 Test (org.junit.jupiter.api.Test)5 Term (at.ac.tuwien.kr.alpha.api.terms.Term)4 AnalyzedProgram (at.ac.tuwien.kr.alpha.core.programs.AnalyzedProgram)4 CompiledProgram (at.ac.tuwien.kr.alpha.core.programs.CompiledProgram)4 InternalProgram (at.ac.tuwien.kr.alpha.core.programs.InternalProgram)4 Collections (java.util.Collections)4 List (java.util.List)4 GrounderHeuristicsConfiguration (at.ac.tuwien.kr.alpha.api.config.GrounderHeuristicsConfiguration)3 SystemConfig (at.ac.tuwien.kr.alpha.api.config.SystemConfig)3 ASPCore2Program (at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program)3