Search in sources :

Example 6 with Head

use of at.ac.tuwien.kr.alpha.api.rules.heads.Head in project Alpha by alpha-asp.

the class RuleTest method renameVariables.

@Test
public void renameVariables() {
    String originalRule = "p(X,Y) :- a, f(Z) = 1, q(X,g(Y),Z), dom(A).";
    Rule<Head> rule = parser.parse(originalRule).getRules().get(0);
    CompiledRule normalRule = InternalRule.fromNormalRule(NormalRuleImpl.fromBasicRule(rule));
    CompiledRule renamedRule = normalRule.renameVariables("_13");
    Rule<Head> expectedRenamedRule = parser.parse("p(X_13, Y_13) :- a, f(Z_13) = 1, q(X_13, g(Y_13), Z_13), dom(A_13).").getRules().get(0);
    CompiledRule expectedRenamedNormalRule = InternalRule.fromNormalRule(NormalRuleImpl.fromBasicRule(expectedRenamedRule));
    assertEquals(expectedRenamedNormalRule.toString(), renamedRule.toString());
}
Also used : Head(at.ac.tuwien.kr.alpha.api.rules.heads.Head) CompiledRule(at.ac.tuwien.kr.alpha.core.rules.CompiledRule) Test(org.junit.jupiter.api.Test)

Example 7 with Head

use of at.ac.tuwien.kr.alpha.api.rules.heads.Head in project Alpha by alpha-asp.

the class AggregateRewritingContextTest method rewritingContextForAspString.

// @formatter:on
private static final AggregateRewritingContext rewritingContextForAspString(String asp) {
    ASPCore2Program program = new ProgramParserImpl().parse(asp);
    AggregateRewritingContext ctx = new AggregateRewritingContext();
    for (Rule<Head> rule : program.getRules()) {
        ctx.registerRule(rule);
    }
    return ctx;
}
Also used : ASPCore2Program(at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program) Head(at.ac.tuwien.kr.alpha.api.rules.heads.Head) ProgramParserImpl(at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl)

Example 8 with Head

use of at.ac.tuwien.kr.alpha.api.rules.heads.Head in project Alpha by alpha-asp.

the class PredicateInternalizer method makePrefixedPredicatesInternal.

public static Rule<Head> makePrefixedPredicatesInternal(Rule<Head> rule, String prefix) {
    Head newHead = null;
    if (rule.getHead() != null) {
        if (!(rule.getHead() instanceof NormalHead)) {
            throw new UnsupportedOperationException("Cannot make predicates in rules internal whose head is not normal.");
        }
        NormalHead head = (NormalHead) rule.getHead();
        if (head.getAtom().getPredicate().getName().startsWith(prefix)) {
            newHead = Heads.newNormalHead(makePredicateInternal(head.getAtom()));
        } else {
            newHead = head;
        }
    }
    List<Literal> newBody = new ArrayList<>();
    for (Literal bodyElement : rule.getBody()) {
        // Only rewrite BasicAtoms.
        if (bodyElement instanceof BasicLiteral) {
            if (bodyElement.getAtom().getPredicate().getName().startsWith(prefix)) {
                newBody.add(makePredicateInternal((BasicAtom) bodyElement.getAtom()).toLiteral(!bodyElement.isNegated()));
            } else {
                newBody.add(bodyElement);
            }
        } else {
            // Keep other body element as is.
            newBody.add(bodyElement);
        }
    }
    return new BasicRule(newHead, newBody);
}
Also used : BasicRule(at.ac.tuwien.kr.alpha.core.rules.BasicRule) BasicLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.BasicLiteral) Head(at.ac.tuwien.kr.alpha.api.rules.heads.Head) NormalHead(at.ac.tuwien.kr.alpha.api.rules.heads.NormalHead) NormalHead(at.ac.tuwien.kr.alpha.api.rules.heads.NormalHead) Literal(at.ac.tuwien.kr.alpha.api.programs.literals.Literal) BasicLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.BasicLiteral) ArrayList(java.util.ArrayList)

Example 9 with Head

use of at.ac.tuwien.kr.alpha.api.rules.heads.Head in project Alpha by alpha-asp.

the class AggregateRewriting method apply.

/**
 * Rewrites all {@link AggregateLiteral}s in the given program.
 * The transformation workflow is split into a preprocessing- and an encoding phase.
 * During preprocessing, all aggregate literals with two comparison operators are split into two aggregate literals with
 * only a "lower bound" term and operator. After literal splitting, operators are normalized, i.e. all "count" and "sum"
 * literals are rewritten to use either "<=" or "=" as comparison operator.
 *
 * Rules containing {@link AggregateLiteral}s are registered in an {@link AggregateRewritingContext} during
 * preprocessing. After preprocessing, for each rule in the context, aggregate literals in the rule body are substituted
 * with normal literals of form "$id$_aggregate_result(...)". For each literal substituted this way, a set of rules
 * deriving the result literal is added that is semantically equivalent to the replaced aggregate literal.
 */
@Override
public ASPCore2Program apply(ASPCore2Program inputProgram) {
    AggregateRewritingContext ctx = new AggregateRewritingContext();
    List<Rule<Head>> outputRules = new ArrayList<>();
    for (Rule<Head> inputRule : inputProgram.getRules()) {
        // Split literals with two operators.
        for (Rule<Head> splitRule : AggregateLiteralSplitting.split(inputRule)) {
            // Normalize operators on aggregate literals after splitting.
            Rule<Head> operatorNormalizedRule = AggregateOperatorNormalization.normalize(splitRule);
            boolean hasAggregate = ctx.registerRule(operatorNormalizedRule);
            // Only keep rules without aggregates. The ones with aggregates are registered in the context and taken care of later.
            if (!hasAggregate) {
                outputRules.add(operatorNormalizedRule);
            }
        }
    }
    // Substitute AggregateLiterals with generated result literals.
    outputRules.addAll(rewriteRulesWithAggregates(ctx));
    InputProgram.Builder resultBuilder = InputProgram.builder().addRules(outputRules).addFacts(inputProgram.getFacts()).addInlineDirectives(inputProgram.getInlineDirectives());
    // Add sub-programs deriving respective aggregate literals.
    for (Map.Entry<ImmutablePair<AggregateFunctionSymbol, ComparisonOperator>, Set<AggregateInfo>> aggToRewrite : ctx.getAggregateFunctionsToRewrite().entrySet()) {
        ImmutablePair<AggregateFunctionSymbol, ComparisonOperator> func = aggToRewrite.getKey();
        AbstractAggregateEncoder encoder = getEncoderForAggregateFunction(func.left, func.right);
        resultBuilder.accumulate(encoder.encodeAggregateLiterals(aggToRewrite.getValue()));
    }
    return resultBuilder.build();
}
Also used : AbstractAggregateEncoder(at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.AbstractAggregateEncoder) Head(at.ac.tuwien.kr.alpha.api.rules.heads.Head) ComparisonOperator(at.ac.tuwien.kr.alpha.api.ComparisonOperator) Set(java.util.Set) ArrayList(java.util.ArrayList) AggregateFunctionSymbol(at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateFunctionSymbol) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Rule(at.ac.tuwien.kr.alpha.api.rules.Rule) BasicRule(at.ac.tuwien.kr.alpha.core.rules.BasicRule) Map(java.util.Map) InputProgram(at.ac.tuwien.kr.alpha.core.programs.InputProgram)

Example 10 with Head

use of at.ac.tuwien.kr.alpha.api.rules.heads.Head in project Alpha by alpha-asp.

the class AbstractAggregateEncoder method encodeAggregateLiteral.

/**
 * Encodes the aggregate literal referenced by the given {@link AggregateInfo}.
 *
 * @param aggregateToEncode
 * @return
 */
public ASPCore2Program encodeAggregateLiteral(AggregateInfo aggregateToEncode) {
    AggregateLiteral literalToEncode = aggregateToEncode.getLiteral();
    if (literalToEncode.getAtom().getAggregateFunction() != this.aggregateFunctionToEncode) {
        throw new IllegalArgumentException("Encoder " + this.getClass().getSimpleName() + " cannot encode aggregate function " + literalToEncode.getAtom().getAggregateFunction());
    }
    if (!this.acceptedOperators.contains(literalToEncode.getAtom().getLowerBoundOperator())) {
        throw new IllegalArgumentException("Encoder " + this.getClass().getSimpleName() + " cannot encode aggregate function " + literalToEncode.getAtom().getAggregateFunction() + " with operator " + literalToEncode.getAtom().getLowerBoundOperator());
    }
    String aggregateId = aggregateToEncode.getId();
    ASPCore2Program literalEncoding = PredicateInternalizer.makePrefixedPredicatesInternal(encodeAggregateResult(aggregateToEncode), aggregateId);
    List<Rule<Head>> elementEncodingRules = new ArrayList<>();
    for (AggregateElement elementToEncode : literalToEncode.getAtom().getAggregateElements()) {
        Rule<Head> elementRule = encodeAggregateElement(aggregateToEncode, elementToEncode);
        elementEncodingRules.add(PredicateInternalizer.makePrefixedPredicatesInternal(elementRule, aggregateId));
    }
    return new InputProgram(ListUtils.union(literalEncoding.getRules(), elementEncodingRules), literalEncoding.getFacts(), new InlineDirectivesImpl());
}
Also used : ASPCore2Program(at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program) Head(at.ac.tuwien.kr.alpha.api.rules.heads.Head) AggregateLiteral(at.ac.tuwien.kr.alpha.api.programs.literals.AggregateLiteral) AggregateElement(at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateElement) ArrayList(java.util.ArrayList) Rule(at.ac.tuwien.kr.alpha.api.rules.Rule) BasicRule(at.ac.tuwien.kr.alpha.core.rules.BasicRule) InlineDirectivesImpl(at.ac.tuwien.kr.alpha.core.parser.InlineDirectivesImpl) InputProgram(at.ac.tuwien.kr.alpha.core.programs.InputProgram)

Aggregations

Head (at.ac.tuwien.kr.alpha.api.rules.heads.Head)21 Literal (at.ac.tuwien.kr.alpha.api.programs.literals.Literal)12 Test (org.junit.jupiter.api.Test)12 Rule (at.ac.tuwien.kr.alpha.api.rules.Rule)6 BasicRule (at.ac.tuwien.kr.alpha.core.rules.BasicRule)6 ArrayList (java.util.ArrayList)6 InputProgram (at.ac.tuwien.kr.alpha.core.programs.InputProgram)5 ASPCore2Program (at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program)4 NormalHead (at.ac.tuwien.kr.alpha.api.rules.heads.NormalHead)3 CompiledRule (at.ac.tuwien.kr.alpha.core.rules.CompiledRule)3 Substitution (at.ac.tuwien.kr.alpha.api.grounder.Substitution)2 Atom (at.ac.tuwien.kr.alpha.api.programs.atoms.Atom)2 BasicAtom (at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom)2 AggregateLiteral (at.ac.tuwien.kr.alpha.api.programs.literals.AggregateLiteral)2 BasicLiteral (at.ac.tuwien.kr.alpha.api.programs.literals.BasicLiteral)2 Term (at.ac.tuwien.kr.alpha.api.terms.Term)2 VariableTerm (at.ac.tuwien.kr.alpha.api.terms.VariableTerm)2 BasicSubstitution (at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution)2 InlineDirectivesImpl (at.ac.tuwien.kr.alpha.core.parser.InlineDirectivesImpl)2 ProgramParserImpl (at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl)2