use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.
the class LiteralInstantiationStrategyTest method defaultLazyGroundingNoAssignmentSubstituteNonGroundLiteral.
/**
* Uses {@link DefaultLazyGroundingInstantiationStrategy} to find ground
* instances for the partially ground positive literal "q(a, X)".
*
* In this case, the instantiation strategy does not have an assignment set (as
* is the case when {@link NaiveGrounder} is in bootstrap), so we expect the
* assignment status (i.e. assignment status of the found ground instance)
* passed back with the substitution to be TRUE. Furthermore, the stale atom set
* (used by {@link NaiveGrounder} to clean up atoms that should be deleted from
* working memory) must stay empty.
*/
@Test
public void defaultLazyGroundingNoAssignmentSubstituteNonGroundLiteral() {
Predicate q = Predicates.getPredicate("q", 2);
BasicAtom nonGroundAtom = Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newVariable("X"));
WorkingMemory workingMemory = new WorkingMemory();
workingMemory.initialize(q);
workingMemory.addInstance(Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newSymbolicConstant("b")), true);
LinkedHashSet<Atom> staleSet = new LinkedHashSet<>();
DefaultLazyGroundingInstantiationStrategy strategy = new DefaultLazyGroundingInstantiationStrategy(workingMemory, new AtomStoreImpl(), Collections.emptyMap(), false);
strategy.setStaleWorkingMemoryEntries(staleSet);
strategy.setCurrentAssignment(null);
List<ImmutablePair<Substitution, AssignmentStatus>> result = strategy.getAcceptedSubstitutions(Literals.fromAtom(nonGroundAtom, true), new BasicSubstitution());
assertEquals(1, result.size());
ImmutablePair<Substitution, AssignmentStatus> substitutionInfo = result.get(0);
Substitution substitution = substitutionInfo.left;
AssignmentStatus assignmentStatus = substitutionInfo.right;
assertEquals(AssignmentStatus.TRUE, assignmentStatus);
assertTrue(substitution.isVariableSet(Terms.newVariable("X")));
assertEquals(Terms.newSymbolicConstant("b"), substitution.eval(Terms.newVariable("X")));
assertTrue(staleSet.isEmpty());
}
use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.
the class LiteralInstantiationStrategyTest method defaultLazyGroundingSubstituteNonGroundLiteralWithFalseInstance.
/**
* Uses {@link DefaultLazyGroundingInstantiationStrategy} to find the ground
* instance "q(a, b)" for the partially ground positive literal "q(a, X)".
*
* In this case, the instantiation strategy has an assignment where q(a, b) is
* assigned ThriceTruth.FALSE, so we expect an empty list from
* {@link LiteralInstantiationStrategy#getAcceptedSubstitutions(Literal, Substitution)}.
* Furthermore, we expect the atom q(a, b) to be added to the stale atom set.
*/
@Test
public void defaultLazyGroundingSubstituteNonGroundLiteralWithFalseInstance() {
Predicate q = Predicates.getPredicate("q", 2);
BasicAtom nonGroundAtom = Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newVariable("X"));
WorkingMemory workingMemory = new WorkingMemory();
workingMemory.initialize(q);
workingMemory.addInstance(Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newSymbolicConstant("b")), true);
AtomStore atomStore = new AtomStoreImpl();
WritableAssignment assignment = new TrailAssignment(atomStore);
BasicAtom groundAtom = Atoms.newBasicAtom(q, Terms.newSymbolicConstant("a"), Terms.newSymbolicConstant("b"));
atomStore.putIfAbsent(groundAtom);
assignment.growForMaxAtomId();
assignment.assign(atomStore.get(groundAtom), ThriceTruth.FALSE);
LinkedHashSet<Atom> staleSet = new LinkedHashSet<>();
DefaultLazyGroundingInstantiationStrategy strategy = new DefaultLazyGroundingInstantiationStrategy(workingMemory, atomStore, Collections.emptyMap(), false);
strategy.setStaleWorkingMemoryEntries(staleSet);
strategy.setCurrentAssignment(assignment);
List<ImmutablePair<Substitution, AssignmentStatus>> result = strategy.getAcceptedSubstitutions(Literals.fromAtom(nonGroundAtom, true), new BasicSubstitution());
assertTrue(result.isEmpty());
assertEquals(1, staleSet.size());
assertTrue(staleSet.contains(groundAtom));
}
use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.
the class DefaultSolver method treatConflictAfterClosing.
private boolean treatConflictAfterClosing(Antecedent violatedNoGood) {
if (disableJustificationAfterClosing || disableJustifications || !(grounder instanceof ProgramAnalyzingGrounder)) {
// Will not learn from violated NoGood, do simple backtrack.
LOGGER.debug("NoGood was violated after all unassigned atoms were assigned to false; will not learn from it; skipping.");
if (!backtrack()) {
logStats();
return false;
}
return true;
}
ProgramAnalyzingGrounder analyzingGrounder = (ProgramAnalyzingGrounder) grounder;
LOGGER.debug("Justifying atoms in violated nogood.");
LinkedHashSet<Integer> toJustify = new LinkedHashSet<>();
// Find those literals in violatedNoGood that were just assigned false.
for (Integer literal : violatedNoGood.getReasonLiterals()) {
if (assignment.getImpliedBy(atomOf(literal)) == TrailAssignment.CLOSING_INDICATOR_ANTECEDENT) {
toJustify.add(literal);
}
}
// Since the violatedNoGood may contain atoms other than BasicAtom, these have to be treated.
Map<Integer, NoGood> obtained = new LinkedHashMap<>();
Iterator<Integer> toJustifyIterator = toJustify.iterator();
ArrayList<Integer> ruleAtomReplacements = new ArrayList<>();
while (toJustifyIterator.hasNext()) {
Integer literal = toJustifyIterator.next();
Atom atom = atomStore.get(atomOf(literal));
if (atom instanceof BasicAtom) {
continue;
}
if (!(atom instanceof RuleAtom)) {
// Ignore atoms other than RuleAtom.
toJustifyIterator.remove();
continue;
}
// For RuleAtoms in toJustify the corresponding ground body contains BasicAtoms that have been assigned FALSE in the closing.
// First, translate RuleAtom back to NonGroundRule + Substitution.
String ruleId = (String) ((ConstantTerm<?>) atom.getTerms().get(0)).getObject();
CompiledRule nonGroundRule = analyzingGrounder.getNonGroundRule(Integer.parseInt(ruleId));
String substitution = (String) ((ConstantTerm<?>) atom.getTerms().get(1)).getObject();
Substitution groundingSubstitution = Substitutions.fromString(substitution);
// Find ground literals in the body that have been assigned false and justify those.
for (Literal bodyLiteral : nonGroundRule.getBody()) {
Atom groundAtom = bodyLiteral.getAtom().substitute(groundingSubstitution);
if (groundAtom instanceof ComparisonAtom || analyzingGrounder.isFact(groundAtom)) {
// Facts and ComparisonAtoms are always true, no justification needed.
continue;
}
int groundAtomId = atomStore.get(groundAtom);
Antecedent impliedBy = assignment.getImpliedBy(groundAtomId);
// Check if atom was assigned to FALSE during the closing.
if (impliedBy == TrailAssignment.CLOSING_INDICATOR_ANTECEDENT) {
ruleAtomReplacements.add(atomToNegatedLiteral(groundAtomId));
}
}
toJustifyIterator.remove();
}
toJustify.addAll(ruleAtomReplacements);
for (Integer literalToJustify : toJustify) {
LOGGER.debug("Searching for justification(s) of {} / {}", toJustify, atomStore.atomToString(atomOf(literalToJustify)));
Set<Literal> reasonsForUnjustified = analyzingGrounder.justifyAtom(atomOf(literalToJustify), assignment);
NoGood noGood = noGoodFromJustificationReasons(atomOf(literalToJustify), reasonsForUnjustified);
int noGoodID = grounder.register(noGood);
obtained.put(noGoodID, noGood);
LOGGER.debug("Learned NoGood is: {}", atomStore.noGoodToString(noGood));
}
// Backtrack to remove the violation.
if (!backtrack()) {
logStats();
return false;
}
// Add newly obtained noGoods.
if (!ingest(obtained)) {
logStats();
return false;
}
return true;
}
use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.
the class LitSet method computeNormalizedSubstitutions.
private Set<Unifier> computeNormalizedSubstitutions() {
Set<Unifier> ret = new LinkedHashSet<>();
for (Unifier substitution : complementSubstitutions) {
Unifier preNormalizedSubstitution = normalizeSubstitution(atom, substitution, normalizedLiteral);
// Unifier may still contain variables in the right-hand side, those have to be normalized, too.
Atom appliedSub = normalizedLiteral.substitute(preNormalizedSubstitution);
// Apply substitution and normalize all remaining variables, i.e., those appearing at the right-hand side of the substitution.
Atom normalized = computeNormalized(appliedSub, "_X");
// Compute final substitution from normalized atom to the one where also variables are normalized.
Unifier normalizedSubstitution = new Unifier(Unification.instantiate(normalizedLiteral, normalized));
ret.add(normalizedSubstitution);
}
return ret;
}
use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.
the class AtomsTest method testIsExternalAtomGround.
@Test
public void testIsExternalAtomGround() {
ASPCore2Program p1 = parser.parse("a :- &isFoo[1].", externals);
Atom ext1 = p1.getRules().get(0).getBody().stream().findFirst().get().getAtom();
assertExternalAtomGround(ext1, true);
ASPCore2Program p2 = parser.parse("a :- &isFoo[bar(1)].", externals);
Atom ext2 = p2.getRules().get(0).getBody().stream().findFirst().get().getAtom();
assertExternalAtomGround(ext2, true);
ASPCore2Program p3 = parser.parse("a :- &isFoo[BLA].", externals);
Atom ext3 = p3.getRules().get(0).getBody().stream().findFirst().get().getAtom();
assertExternalAtomGround(ext3, false);
}
Aggregations