Search in sources :

Example 41 with Atom

use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.

the class AnswerSetQueryTest method matchString.

@Test
public void matchString() {
    AnswerSetBuilder bld = new AnswerSetBuilder();
    bld.predicate("p").symbolicInstance("a").instance("a");
    AnswerSet as = bld.build();
    AnswerSetQueryImpl stringQuery = AnswerSetQueryImpl.forPredicate(Predicates.getPredicate("p", 1)).withStringEquals(0, "a");
    List<Atom> queryResult = as.query(stringQuery);
    assertEquals(1, queryResult.size());
}
Also used : AnswerSet(at.ac.tuwien.kr.alpha.api.AnswerSet) AnswerSetBuilder(at.ac.tuwien.kr.alpha.commons.AnswerSetBuilder) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) Test(org.junit.jupiter.api.Test)

Example 42 with Atom

use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom 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 43 with Atom

use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.

the class AnalyzeUnjustified method analyze.

public Set<Literal> analyze(int atomToJustify, Assignment currentAssignment) {
    padDepth = 0;
    Atom atom = atomStore.get(atomToJustify);
    if (!(atom instanceof BasicAtom)) {
        throw oops("Starting atom must be a BasicAtom, but received: " + atom + " of type: " + atom.getClass());
    }
    // @formatter:off
    // Calling code must make sure it is a BasicAtom and take precautions.
    // Potential solutions:
    // If atom instanceof RuleAtom and atom is MBT, then the corresponding rule body has a BasicAtom that is MBT.
    // If atom instanceof ChoiceAtom and atom is MBT, then the corresponding rule body has a BasicAtom that is MBT.
    // If atom instanceof RuleAtom and atom is FALSE, then this comes from a violated constraint in the end and the corresponding rule body can be taken as the single rule deriving the RuleAtom.
    // @formatter:on
    assignedAtoms = new LinkedHashMap<>();
    for (int i = 1; i <= atomStore.getMaxAtomId(); i++) {
        ThriceTruth truth = currentAssignment.getTruth(i);
        if (truth == null) {
            continue;
        }
        Atom assignedAtom = atomStore.get(i);
        assignedAtoms.putIfAbsent(assignedAtom.getPredicate(), new ArrayList<>());
        assignedAtoms.get(assignedAtom.getPredicate()).add(assignedAtom);
    }
    return analyze((BasicAtom) atom, currentAssignment);
}
Also used : ThriceTruth(at.ac.tuwien.kr.alpha.core.solver.ThriceTruth) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)

Example 44 with Atom

use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom in project Alpha by alpha-asp.

the class AnalyzeUnjustified method unjustCover.

private Set<LitSet> unjustCover(List<Literal> vB, Set<Unifier> vY, Set<Unifier> vN, Assignment currentAssignment) {
    padDepth += 2;
    log("Begin UnjustCoverFixed()");
    log("Finding unjustified body literals in: {} / {} excluded {}", vB, vY, vN);
    Set<LitSet> ret = new LinkedHashSet<>();
    if (vB.isEmpty() || vY.isEmpty()) {
        log("End unjustCover().");
        padDepth -= 2;
        return Collections.emptySet();
    }
    int chosenLiteralPos = 0;
    // Find a body literal that is not a ComparisonLiteral, because these do not generate/have atoms assigned.
    for (int i = 0; i < vB.size(); i++) {
        if (!(vB.get(i) instanceof ComparisonLiteral)) {
            // TODO: Should this be FixedInterpretationLiteral instead??
            chosenLiteralPos = i;
            break;
        }
    }
    Atom b = vB.get(chosenLiteralPos).getAtom();
    log("Picked literal from body is: {}", b);
    for (Unifier sigmaY : vY) {
        Atom bSigmaY = b.substitute(sigmaY);
        log("Treating substitution for: {}", bSigmaY);
        Set<Unifier> vYp = new LinkedHashSet<>();
        log("Checking atoms over predicate: {}", b.getPredicate());
        AssignedAtomsIterator assignedAtomsOverPredicate = getAssignedAtomsOverPredicate(b.getPredicate());
        atomLoop: while (assignedAtomsOverPredicate.hasNext()) {
            Atom atom = assignedAtomsOverPredicate.next();
            // Check that atom is justified/true.
            log("Checking atom: {}", atom);
            if (atomStore.contains(atom)) {
                int atomId = atomStore.get(atom);
                if (currentAssignment.getTruth(atomId) != ThriceTruth.TRUE) {
                    log("Atom is not TRUE. Skipping.");
                    continue;
                }
            }
            // Note: in case the atom is not in the atomStore, it came from a fact and hence is true.
            Unifier sigma = Unification.instantiate(b, atom);
            if (sigma == null) {
                log("Atom does not unify with picked body literal.");
                continue;
            }
            Atom bSigma = b.substitute(sigma);
            if (!bSigma.isGround()) {
                throw oops("Resulting atom is not ground.");
            }
            Set<VariableTerm> variablesOccurringInSigma = sigma.getMappedVariables();
            if (Unification.instantiate(bSigmaY, bSigma) != null) {
                for (Unifier sigmaN : vN) {
                    ArrayList<Term> occurringVariables = new ArrayList<>(variablesOccurringInSigma);
                    occurringVariables.addAll(sigmaN.getMappedVariables());
                    BasicAtom genericAtom = Atoms.newBasicAtom(Predicates.getPredicate("_", occurringVariables.size(), true), occurringVariables);
                    Atom genericSubstituted = genericAtom.substitute(sigmaN).renameVariables("_analyzeTest");
                    if (Unification.instantiate(genericSubstituted, genericAtom.substitute(sigma)) != null) {
                        log("Atom {} is excluded by: {} via {}", genericSubstituted, sigmaN, sigma);
                        continue atomLoop;
                    }
                }
                log("Adding corresponding substitution to Y': {}", sigma);
                vYp.add(sigma);
            }
        }
        log("Unjustified body literals: {}", vYp);
        Set<Unifier> vYpUN = new LinkedHashSet<>();
        vYpUN.addAll(vYp);
        vYpUN.addAll(vN);
        LitSet toJustify = new LitSet(bSigmaY, vYpUN);
        if (!toJustify.coversNothing()) {
            log("New litset to do: {}", toJustify);
            ret.add(toJustify);
        } else {
            log("Generated LitSet covers nothing. Ignoring: {}", toJustify);
        }
        ArrayList<Literal> newB = new ArrayList<>(vB);
        newB.remove(chosenLiteralPos);
        ret.addAll(unjustCover(newB, vYp, vN, currentAssignment));
        log("Literal set(s) to treat: {}", ret);
    }
    log("End unjustCover().");
    padDepth -= 2;
    return ret;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) Atom(at.ac.tuwien.kr.alpha.api.programs.atoms.Atom) Literal(at.ac.tuwien.kr.alpha.api.programs.literals.Literal) ComparisonLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.ComparisonLiteral) ComparisonLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.ComparisonLiteral) BasicAtom(at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom) Unifier(at.ac.tuwien.kr.alpha.commons.substitutions.Unifier)

Example 45 with Atom

use of at.ac.tuwien.kr.alpha.api.programs.atoms.Atom 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)

Aggregations

Atom (at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)73 Test (org.junit.jupiter.api.Test)38 Predicate (at.ac.tuwien.kr.alpha.api.programs.Predicate)27 BasicAtom (at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom)27 LinkedHashSet (java.util.LinkedHashSet)16 Unifier (at.ac.tuwien.kr.alpha.commons.substitutions.Unifier)15 ArrayList (java.util.ArrayList)14 AnswerSet (at.ac.tuwien.kr.alpha.api.AnswerSet)13 Literal (at.ac.tuwien.kr.alpha.api.programs.literals.Literal)12 AtomStoreImpl (at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl)11 Instance (at.ac.tuwien.kr.alpha.commons.substitutions.Instance)9 AtomStore (at.ac.tuwien.kr.alpha.core.common.AtomStore)9 WorkingMemory (at.ac.tuwien.kr.alpha.core.grounder.WorkingMemory)9 TrailAssignment (at.ac.tuwien.kr.alpha.core.solver.TrailAssignment)9 ASPCore2Program (at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program)8 RuleAtom (at.ac.tuwien.kr.alpha.core.atoms.RuleAtom)8 WritableAssignment (at.ac.tuwien.kr.alpha.core.solver.WritableAssignment)7 Substitution (at.ac.tuwien.kr.alpha.api.grounder.Substitution)6 ExternalAtom (at.ac.tuwien.kr.alpha.api.programs.atoms.ExternalAtom)6 AnswerSetBuilder (at.ac.tuwien.kr.alpha.commons.AnswerSetBuilder)6