use of at.ac.tuwien.kr.alpha.api.rules.heads.ChoiceHead.ChoiceElement in project Alpha by alpha-asp.
the class ChoiceHeadToNormal method apply.
@Override
public ASPCore2Program apply(ASPCore2Program inputProgram) {
InputProgram.Builder programBuilder = InputProgram.builder();
List<Rule<Head>> additionalRules = new ArrayList<>();
List<Rule<Head>> srcRules = new ArrayList<>(inputProgram.getRules());
Iterator<Rule<Head>> ruleIterator = srcRules.iterator();
while (ruleIterator.hasNext()) {
Rule<Head> rule = ruleIterator.next();
Head ruleHead = rule.getHead();
if (!(ruleHead instanceof ChoiceHead)) {
// Rule is constraint or without choice in the head. Leave as is.
continue;
}
// Remove this rule, as it will be transformed.
ruleIterator.remove();
ChoiceHead choiceHead = (ChoiceHead) ruleHead;
// Choice rules with boundaries are not yet supported.
if (choiceHead.getLowerBound() != null || choiceHead.getUpperBound() != null) {
throw new UnsupportedOperationException("Found choice rule with bounds, which are not yet supported. Rule is: " + rule);
}
// Only rewrite rules with a choice in their head.
for (ChoiceElement choiceElement : choiceHead.getChoiceElements()) {
// Create two guessing rules for each choiceElement.
// Construct common body to both rules.
BasicAtom head = choiceElement.getChoiceAtom();
List<Literal> ruleBody = new ArrayList<>(rule.getBody());
ruleBody.addAll(choiceElement.getConditionLiterals());
if (containsIntervalTerms(head)) {
throw new RuntimeException("Program contains a choice rule with interval terms in its head. This is not supported (yet).");
}
// Construct head atom for the choice.
Predicate headPredicate = head.getPredicate();
Predicate negPredicate = Predicates.getPredicate(PREDICATE_NEGATION_PREFIX + headPredicate.getName(), headPredicate.getArity() + 1, true);
List<Term> headTerms = new ArrayList<>(head.getTerms());
// FIXME: when introducing classical negation, this is 1 for classical positive atoms and 0 for
headTerms.add(0, Terms.newConstant("1"));
// classical negative atoms.
BasicAtom negHead = Atoms.newBasicAtom(negPredicate, headTerms);
// Construct two guessing rules.
List<Literal> guessingRuleBodyWithNegHead = new ArrayList<>(ruleBody);
guessingRuleBodyWithNegHead.add(Atoms.newBasicAtom(head.getPredicate(), head.getTerms()).toLiteral(false));
additionalRules.add(new BasicRule(Heads.newNormalHead(negHead), guessingRuleBodyWithNegHead));
List<Literal> guessingRuleBodyWithHead = new ArrayList<>(ruleBody);
guessingRuleBodyWithHead.add(Atoms.newBasicAtom(negPredicate, headTerms).toLiteral(false));
additionalRules.add(new BasicRule(Heads.newNormalHead(head), guessingRuleBodyWithHead));
// TODO: when cardinality constraints are possible, process the boundaries by adding a constraint with a cardinality check.
}
}
return programBuilder.addRules(srcRules).addRules(additionalRules).addFacts(inputProgram.getFacts()).addInlineDirectives(inputProgram.getInlineDirectives()).build();
}
Aggregations