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;
}
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;
}
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);
}
}
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;
}
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;
}
Aggregations