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