diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/config/AggregateRewritingConfig.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/config/AggregateRewritingConfig.java index 6c72fbe62..908b2b3cb 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/config/AggregateRewritingConfig.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/config/AggregateRewritingConfig.java @@ -5,7 +5,7 @@ /** * Configuration structure controlling how {@link AggregateLiteral}s are compiled during program normalization in - * {@link Alpha#normalizeProgram(at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program)}. + * {@link Alpha#normalizeProgram(at.ac.tuwien.kr.alpha.api.programs.InputProgram)}. * * Copyright (c) 2021, the Alpha Team. */ diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/InputProgram.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/InputProgram.java index f9fe5122f..7c3df5bf8 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/InputProgram.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/InputProgram.java @@ -8,9 +8,9 @@ public interface InputProgram extends Program> { - /** - * The test cases associated with this program. - */ - List getTestCases(); + /** + * The test cases associated with this program. + */ + List getTestCases(); } diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/actions/Action.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/actions/Action.java index 5b0ab32e1..240a3b232 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/actions/Action.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/actions/Action.java @@ -1,9 +1,9 @@ package at.ac.tuwien.kr.alpha.api.programs.actions; -import java.util.List; +import at.ac.tuwien.kr.alpha.api.programs.terms.ActionResultTerm; +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; -import at.ac.tuwien.kr.alpha.api.terms.ActionResultTerm; -import at.ac.tuwien.kr.alpha.api.terms.Term; +import java.util.List; /** * An action that gets executed as part of an action rule in an evolog program firing. diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/NormalRule.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/NormalRule.java index 8f2d8ebc8..92bdc6776 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/NormalRule.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/NormalRule.java @@ -14,4 +14,6 @@ default BasicAtom getHeadAtom() { return this.isConstraint() ? null : this.getHead().getAtom(); } + boolean isGround(); + } diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/RuleInstantiator.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/RuleInstantiator.java index 74646f00d..7a36f19db 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/RuleInstantiator.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/RuleInstantiator.java @@ -6,6 +6,6 @@ public interface RuleInstantiator { - BasicAtom instantiate(InstantiableHead ruleHead, Substitution substitution); + BasicAtom instantiate(InstantiableHead ruleHead, Substitution substitution); } diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/ActionHead.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/ActionHead.java index 744531317..9956ccee8 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/ActionHead.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/ActionHead.java @@ -7,10 +7,10 @@ public interface ActionHead extends NormalHead { - String getActionName(); + String getActionName(); - List getActionInputTerms(); + List getActionInputTerms(); - VariableTerm getActionOutputTerm(); + VariableTerm getActionOutputTerm(); } diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/InstantiableHead.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/InstantiableHead.java index 82aa89343..32dcca689 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/InstantiableHead.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/rules/heads/InstantiableHead.java @@ -6,6 +6,6 @@ public interface InstantiableHead extends Head { - BasicAtom instantiate(RuleInstantiator instantiator, Substitution substitution); + BasicAtom instantiate(RuleInstantiator instantiator, Substitution substitution); } diff --git a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/terms/ActionResultTerm.java b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/terms/ActionResultTerm.java index 28fc53769..5436abf0f 100644 --- a/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/terms/ActionResultTerm.java +++ b/alpha-api/src/main/java/at/ac/tuwien/kr/alpha/api/programs/terms/ActionResultTerm.java @@ -1,30 +1,30 @@ package at.ac.tuwien.kr.alpha.api.programs.terms; - /** - * A term representing the result of an evolog action (i.e. result of action function application). - * Action result terms are function terms with symbol "success" or "error" depending on whether the corresponding action was sucessful. - * There is always one argument which is either some term representing the actual function result or an error message, respectively. - */ +/** + * A term representing the result of an evolog action (i.e. result of action function application). + * Action result terms are function terms with symbol "success" or "error" depending on whether the corresponding action was sucessful. + * There is always one argument which is either some term representing the actual function result or an error message, respectively. + */ public interface ActionResultTerm extends FunctionTerm { - public static final String SUCCESS_SYMBOL = "success"; - public static final String ERROR_SYMBOL = "error"; + public static final String SUCCESS_SYMBOL = "success"; + public static final String ERROR_SYMBOL = "error"; - /** - * True if the action that generated this result was successful (i.e. executed normally). - */ - boolean isSuccess(); + /** + * True if the action that generated this result was successful (i.e. executed normally). + */ + boolean isSuccess(); - /** - * True if the action that generated this result failed (i.e. threw an error in execution). - */ - boolean isError(); + /** + * True if the action that generated this result failed (i.e. threw an error in execution). + */ + boolean isError(); - /** - * Gets the actual value wrapped in this result. - * Either a term representing the action return value or a string term representing an error - * message.s - */ - T getValue(); + /** + * Gets the actual value wrapped in this result. + * Either a term representing the action return value or a string term representing an error + * message.s + */ + T getValue(); } \ No newline at end of file diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/Externals.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/Externals.java index aa9153e95..52066fd09 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/Externals.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/Externals.java @@ -23,19 +23,7 @@ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package at.ac.tuwien.kr.alpha.core.externals; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.reflections.Reflections; -import org.reflections.scanners.MethodAnnotationsScanner; +package at.ac.tuwien.kr.alpha.commons.externals; import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; import at.ac.tuwien.kr.alpha.api.externals.Predicate; @@ -44,13 +32,11 @@ import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.BinaryPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.BindingMethodPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.IntPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.LongPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.MethodPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.SuppliedPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.UnaryPredicateInterpretation; +import org.reflections.Reflections; +import org.reflections.scanners.MethodAnnotationsScanner; + +import java.lang.reflect.Method; +import java.util.*; public final class Externals { diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/PredicateInterpretationImpl.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/PredicateInterpretationImpl.java index 8e52bfacb..5ff6c5cfe 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/PredicateInterpretationImpl.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/externals/PredicateInterpretationImpl.java @@ -1,11 +1,12 @@ package at.ac.tuwien.kr.alpha.commons.externals; +import at.ac.tuwien.kr.alpha.api.programs.terms.ConstantTerm; +import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; + import java.util.List; import java.util.Set; -import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.api.terms.ConstantTerm; -import at.ac.tuwien.kr.alpha.api.terms.Term; // TODO this looks like a duplicate public interface PredicateInterpretationImpl extends PredicateInterpretation { diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/ASPCore2ProgramImpl.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/InputProgramImpl.java similarity index 86% rename from alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/ASPCore2ProgramImpl.java rename to alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/InputProgramImpl.java index c67097ed3..64c3c5a3c 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/ASPCore2ProgramImpl.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/InputProgramImpl.java @@ -44,13 +44,13 @@ * Copyright (c) 2017-2019, the Alpha Team. */ // TODO rename this to InputProgramImpl or some such -class ASPCore2ProgramImpl extends AbstractProgram> implements InputProgram { +class InputProgramImpl extends AbstractProgram> implements InputProgram { - static final ASPCore2ProgramImpl EMPTY = new ASPCore2ProgramImpl(Collections.emptyList(), Collections.emptyList(), new InlineDirectivesImpl(), Collections.emptyList()); + static final InputProgramImpl EMPTY = new InputProgramImpl(Collections.emptyList(), Collections.emptyList(), new InlineDirectivesImpl(), Collections.emptyList()); private final List testCases; - ASPCore2ProgramImpl(List> rules, List facts, InlineDirectives inlineDirectives, List testCases) { + InputProgramImpl(List> rules, List facts, InlineDirectives inlineDirectives, List testCases) { super(rules, facts, inlineDirectives); this.testCases = testCases; } diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/Programs.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/Programs.java index 460231815..0a10b61d7 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/Programs.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/Programs.java @@ -4,9 +4,8 @@ import java.util.Collections; import java.util.List; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; -import at.ac.tuwien.kr.alpha.api.programs.InlineDirectives; import at.ac.tuwien.kr.alpha.api.programs.InputProgram; +import at.ac.tuwien.kr.alpha.api.programs.InlineDirectives; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.rules.NormalRule; @@ -22,25 +21,25 @@ private Programs() { } public static InputProgram emptyProgram() { - return ASPCore2ProgramImpl.EMPTY; + return InputProgramImpl.EMPTY; } // TODO rename method - public static InputProgram newASPCore2Program(List> rules, List facts, InlineDirectives inlineDirectives, List testCases) { - return new ASPCore2ProgramImpl(rules, facts, inlineDirectives, testCases); + public static InputProgram newInputProgram(List> rules, List facts, InlineDirectives inlineDirectives, List testCases) { + return new InputProgramImpl(rules, facts, inlineDirectives, testCases); } // TODO rename method - public static InputProgram newASPCore2Program(List> rules, List facts, InlineDirectives inlineDirectives) { - return new ASPCore2ProgramImpl(rules, facts, inlineDirectives, Collections.emptyList()); + public static InputProgram newInputProgram(List> rules, List facts, InlineDirectives inlineDirectives) { + return new InputProgramImpl(rules, facts, inlineDirectives, Collections.emptyList()); } - public static ASPCore2ProgramBuilder builder() { - return new ASPCore2ProgramBuilder(); + public static InputProgramBuilder builder() { + return new InputProgramBuilder(); } - public static ASPCore2ProgramBuilder builder(InputProgram program) { - return new ASPCore2ProgramBuilder(program); + public static InputProgramBuilder builder(InputProgram program) { + return new InputProgramBuilder(program); } public static NormalProgram newNormalProgram(List rules, List facts, InlineDirectives inlineDirectives) { @@ -60,10 +59,10 @@ public static InlineDirectives newInlineDirectives() { } /** - * Builder for more complex program construction scenarios, ensuring that an {@link ASPCore2ProgramImpl} is immutable + * Builder for more complex program construction scenarios, ensuring that an {@link InputProgramImpl} is immutable */ // TODO maybe rename - public static class ASPCore2ProgramBuilder { + public static class InputProgramBuilder { private List> rules = new ArrayList<>(); private List facts = new ArrayList<>(); @@ -71,58 +70,58 @@ public static class ASPCore2ProgramBuilder { private List testCases = new ArrayList<>(); - public ASPCore2ProgramBuilder(InputProgram prog) { + public InputProgramBuilder(InputProgram prog) { this.addRules(prog.getRules()); this.addFacts(prog.getFacts()); this.addInlineDirectives(prog.getInlineDirectives()); this.addTestCases(prog.getTestCases()); } - public ASPCore2ProgramBuilder() { + public InputProgramBuilder() { } - public ASPCore2ProgramBuilder addRules(List> rules) { + public InputProgramBuilder addRules(List> rules) { this.rules.addAll(rules); return this; } - public ASPCore2ProgramBuilder addRule(Rule r) { + public InputProgramBuilder addRule(Rule r) { this.rules.add(r); return this; } - public ASPCore2ProgramBuilder addFacts(List facts) { + public InputProgramBuilder addFacts(List facts) { this.facts.addAll(facts); return this; } - public ASPCore2ProgramBuilder addFact(Atom fact) { + public InputProgramBuilder addFact(Atom fact) { this.facts.add(fact); return this; } - public ASPCore2ProgramBuilder addInlineDirectives(InlineDirectives inlineDirectives) { + public InputProgramBuilder addInlineDirectives(InlineDirectives inlineDirectives) { this.inlineDirectives.accumulate(inlineDirectives); return this; } - public ASPCore2ProgramBuilder addTestCase(TestCase testCase) { + public InputProgramBuilder addTestCase(TestCase testCase) { this.testCases.add(testCase); return this; } - public ASPCore2ProgramBuilder addTestCases(List testCases) { + public InputProgramBuilder addTestCases(List testCases) { this.testCases.addAll(testCases); return this; } - public ASPCore2ProgramBuilder accumulate(InputProgram prog) { + public InputProgramBuilder accumulate(InputProgram prog) { return this.addRules(prog.getRules()).addFacts(prog.getFacts()).addInlineDirectives(prog.getInlineDirectives()).addTestCases(prog.getTestCases()); } public InputProgram build() { - return Programs.newASPCore2Program(this.rules, this.facts, this.inlineDirectives, this.testCases); + return Programs.newInputProgram(this.rules, this.facts, this.inlineDirectives, this.testCases); } } diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/reification/Reifier.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/reification/Reifier.java index dba92f359..c21c7e0cb 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/reification/Reifier.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/reification/Reifier.java @@ -6,8 +6,8 @@ import java.util.function.Supplier; import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; import at.ac.tuwien.kr.alpha.api.programs.InlineDirectives; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateElement; @@ -35,6 +35,7 @@ import at.ac.tuwien.kr.alpha.commons.util.IdGenerator; import at.ac.tuwien.kr.alpha.commons.util.Util; +// TODO add support for action rules public class Reifier { // Predicates describing rules. @@ -193,7 +194,7 @@ public Reifier(Supplier>> idGeneratorProvider) { this.idGeneratorProvider = idGeneratorProvider; } - public Set reifyProgram(ASPCore2Program program) { + public Set reifyProgram(InputProgram program) { ReificationContext ctx = new ReificationContext(idGeneratorProvider.get()); reifyDirectives(ctx, program.getInlineDirectives()); for (Atom fact : program.getFacts()) { diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/AbstractRule.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/AbstractRule.java index 9326cad6b..5b8e4454e 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/AbstractRule.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/AbstractRule.java @@ -26,7 +26,7 @@ public abstract class AbstractRule implements Rule { private final Set bodyLiteralsPositive; private final Set bodyLiteralsNegative; - public AbstractRule(H head, List body) { + public AbstractRule(H head, Set body) { this.head = head; Set positiveBody = new LinkedHashSet<>(); Set negativeBody = new LinkedHashSet<>(); diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/BasicRule.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/BasicRule.java index e2bd1e178..13b991506 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/BasicRule.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/BasicRule.java @@ -28,6 +28,7 @@ package at.ac.tuwien.kr.alpha.commons.programs.rules; import java.util.List; +import java.util.Set; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; import at.ac.tuwien.kr.alpha.api.programs.rules.heads.Head; @@ -38,7 +39,7 @@ */ class BasicRule extends AbstractRule { - BasicRule(Head head, List body) { + BasicRule(Head head, Set body) { super(head, body); } diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/NormalRuleImpl.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/NormalRuleImpl.java index 828560f6f..80225ef71 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/NormalRuleImpl.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/NormalRuleImpl.java @@ -1,6 +1,7 @@ package at.ac.tuwien.kr.alpha.commons.programs.rules; import java.util.List; +import java.util.Set; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; import at.ac.tuwien.kr.alpha.api.programs.rules.NormalRule; @@ -14,8 +15,21 @@ */ class NormalRuleImpl extends AbstractRule implements NormalRule { - NormalRuleImpl(NormalHead head, List body) { + NormalRuleImpl(NormalHead head, Set body) { super(head, body); } + @Override + public boolean isGround() { + if (!isConstraint() && !this.getHead().isGround()) { + return false; + } + for (Literal bodyElement : this.getBody()) { + if (!bodyElement.isGround()) { + return false; + } + } + return true; + } + } diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/Rules.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/Rules.java index 3d04c53f9..f0456caba 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/Rules.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/rules/Rules.java @@ -1,8 +1,6 @@ package at.ac.tuwien.kr.alpha.commons.programs.rules; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; @@ -19,21 +17,21 @@ private Rules() { throw new AssertionError("Cannot instantiate utility class!"); } - public static Rule newRule(Head head, List body) { + public static Rule newRule(Head head, Set body) { return new BasicRule(head, body); } public static Rule newRule(Head head, Literal... body) { - List bodyLst = new ArrayList<>(Arrays.asList(body)); + Set bodyLst = new LinkedHashSet<>(Arrays.asList(body)); return new BasicRule(head, bodyLst); } - public static NormalRule newNormalRule(NormalHead head, List body) { + public static NormalRule newNormalRule(NormalHead head, Set body) { return new NormalRuleImpl(head, body); } public static NormalRule newNormalRule(NormalHead head, Literal... body) { - List bodyLst = new ArrayList<>(Arrays.asList(body)); + Set bodyLst = new LinkedHashSet<>(Arrays.asList(body)); return new NormalRuleImpl(head, bodyLst); } @@ -45,7 +43,7 @@ public static NormalRule toNormalRule(Rule rule) { } headAtom = ((NormalHead) rule.getHead()).getAtom(); } - return new NormalRuleImpl(headAtom != null ? Heads.newNormalHead(headAtom) : null, new ArrayList<>(rule.getBody())); + return new NormalRuleImpl(headAtom != null ? Heads.newNormalHead(headAtom) : null, new LinkedHashSet<>(rule.getBody())); } } diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/AssertionImpl.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/AssertionImpl.java index b7f95a5e6..a62753c8e 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/AssertionImpl.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/AssertionImpl.java @@ -1,14 +1,14 @@ package at.ac.tuwien.kr.alpha.commons.programs.tests; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.tests.Assertion; class AssertionImpl implements Assertion { private final Mode mode; - private final ASPCore2Program verifier; + private final InputProgram verifier; - AssertionImpl(final Mode mode, final ASPCore2Program verifier) { + AssertionImpl(final Mode mode, final InputProgram verifier) { this.mode = mode; this.verifier = verifier; } @@ -19,7 +19,7 @@ public Mode getMode() { } @Override - public ASPCore2Program getVerifier() { + public InputProgram getVerifier() { return verifier; } diff --git a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/Tests.java b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/Tests.java index 3962e5684..a750dc7c4 100644 --- a/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/Tests.java +++ b/alpha-commons/src/main/java/at/ac/tuwien/kr/alpha/commons/programs/tests/Tests.java @@ -7,7 +7,7 @@ import java.util.function.IntPredicate; import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; import at.ac.tuwien.kr.alpha.api.programs.tests.Assertion; import at.ac.tuwien.kr.alpha.api.programs.tests.TestCase; @@ -24,7 +24,7 @@ public static TestCase newTestCase(final String name, final IntPredicate answerS return new TestCaseImpl(name, answerSetCountVerifier, input, assertions); } - public static Assertion newAssertion(final Assertion.Mode mode, final ASPCore2Program verifier) { + public static Assertion newAssertion(final Assertion.Mode mode, final InputProgram verifier) { return new AssertionImpl(mode, verifier); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/AbstractActionImplementationProvider.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/AbstractActionImplementationProvider.java index 22707f3ed..c23352dbd 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/AbstractActionImplementationProvider.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/AbstractActionImplementationProvider.java @@ -1,23 +1,19 @@ package at.ac.tuwien.kr.alpha.core.actions; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; +import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; +import at.ac.tuwien.kr.alpha.api.programs.actions.Action; +import at.ac.tuwien.kr.alpha.api.programs.terms.ActionResultTerm; +import at.ac.tuwien.kr.alpha.api.programs.terms.ConstantTerm; +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; +import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; +import at.ac.tuwien.kr.alpha.commons.util.IntIdGenerator; + +import java.io.*; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.api.programs.actions.Action; -import at.ac.tuwien.kr.alpha.api.terms.ActionResultTerm; -import at.ac.tuwien.kr.alpha.api.terms.ConstantTerm; -import at.ac.tuwien.kr.alpha.api.terms.Term; -import at.ac.tuwien.kr.alpha.commons.terms.Terms; -import at.ac.tuwien.kr.alpha.commons.util.IntIdGenerator; - public abstract class AbstractActionImplementationProvider implements ActionImplementationProvider { private final IntIdGenerator idGenerator = new IntIdGenerator(); diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionService.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionService.java index 5e3949519..ef5d8daa6 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionService.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionService.java @@ -1,9 +1,9 @@ package at.ac.tuwien.kr.alpha.core.actions; -import java.util.List; - +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.api.grounder.Substitution; -import at.ac.tuwien.kr.alpha.api.terms.Term; + +import java.util.List; public interface ActionExecutionService { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionServiceImpl.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionServiceImpl.java index 2952f7f26..4067e2182 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionServiceImpl.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionExecutionServiceImpl.java @@ -4,10 +4,10 @@ import java.util.List; import java.util.Map; +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; +import at.ac.tuwien.kr.alpha.api.programs.terms.FunctionTerm; import at.ac.tuwien.kr.alpha.api.grounder.Substitution; import at.ac.tuwien.kr.alpha.api.programs.actions.Action; -import at.ac.tuwien.kr.alpha.api.terms.FunctionTerm; -import at.ac.tuwien.kr.alpha.api.terms.Term; public class ActionExecutionServiceImpl implements ActionExecutionService { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionWitness.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionWitness.java index a81bf4301..265780719 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionWitness.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/actions/ActionWitness.java @@ -1,9 +1,9 @@ package at.ac.tuwien.kr.alpha.core.actions; -import java.util.List; - import at.ac.tuwien.kr.alpha.api.grounder.Substitution; -import at.ac.tuwien.kr.alpha.api.terms.Term; +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; + +import java.util.List; public class ActionWitness { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ParseTreeVisitor.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ParseTreeVisitor.java similarity index 95% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ParseTreeVisitor.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ParseTreeVisitor.java index b9e2cc758..610df11ad 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ParseTreeVisitor.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ParseTreeVisitor.java @@ -30,8 +30,8 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.ComparisonOperator; import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; import at.ac.tuwien.kr.alpha.api.programs.InlineDirectives; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.*; import at.ac.tuwien.kr.alpha.api.programs.literals.AggregateLiteral; @@ -47,7 +47,7 @@ import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.comparisons.ComparisonOperators; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.literals.Literals; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; @@ -76,8 +76,8 @@ public class ParseTreeVisitor extends ASPCore2BaseVisitor { * Therefore, have a stack onto which we "park" a program builder for the outer scope (i.e. main program) * while we parse the inner scope (i.e. test verifier). */ - private ASPCore2ProgramBuilder currentLevelProgramBuilder; - private Stack programBuilders = new Stack<>(); + private InputProgramBuilder currentLevelProgramBuilder; + private Stack programBuilders = new Stack<>(); public ParseTreeVisitor(Map externals) { this(externals, true); @@ -95,7 +95,7 @@ private UnsupportedOperationException notSupported(RuleContext ctx) { /** * Translates a program context (referring to a node in an ATN specific to ANTLR) to the internal representation of Alpha. */ - public ASPCore2Program translate(ASPCore2Parser.ProgramContext input) { + public InputProgram translate(ASPCore2Parser.ProgramContext input) { return visitProgram(input); } @@ -145,7 +145,7 @@ public String visitTerminal(TerminalNode node) { } @Override - public ASPCore2Program visitProgram(ASPCore2Parser.ProgramContext ctx) { + public InputProgram visitProgram(ASPCore2Parser.ProgramContext ctx) { // program : statements? query?; if (ctx.query() != null) { throw notSupported(ctx.query()); @@ -178,7 +178,7 @@ public Object visitStatement_fact(ASPCore2Parser.Statement_factContext ctx) { currentLevelProgramBuilder.addFact(((NormalHead) head).getAtom()); } else { // Treat facts with choice or disjunction in the head like a rule. - currentLevelProgramBuilder.addRule(Rules.newRule(head, Collections.emptyList())); + currentLevelProgramBuilder.addRule(Rules.newRule(head, Collections.emptySet())); } return null; } @@ -247,6 +247,15 @@ public Head visitChoice(ASPCore2Parser.ChoiceContext ctx) { return Heads.newChoiceHead(visitChoice_elements(ctx.choice_elements()), lt, lop, ut, uop); } + @Override + public Head visitAction(ASPCore2Parser.ActionContext ctx) { + BasicAtom atom = visitClassical_literal(ctx.classical_literal()); + VariableTerm actionResultTerm = visitVariable_term(ctx.variable_term()); + String actionId = ctx.ID().getText(); + List actionInputTerms = visitTerms(ctx.terms()); + return Heads.newActionHead(atom, actionId, actionInputTerms, actionResultTerm); + } + @Override public List visitChoice_elements(ASPCore2Parser.Choice_elementsContext ctx) { // choice_elements : choice_element (SEMICOLON choice_elements)?; @@ -312,13 +321,13 @@ public Object visitDirective_test(ASPCore2Parser.Directive_testContext ctx) { } @Override - public List visitBody(ASPCore2Parser.BodyContext ctx) { + public Set visitBody(ASPCore2Parser.BodyContext ctx) { // body : ( naf_literal | aggregate ) (COMMA body)?; if (ctx == null) { - return Collections.emptyList(); + return Collections.emptySet(); } - final List literals = new ArrayList<>(); + final Set literals = new LinkedHashSet<>(); do { if (ctx.naf_literal() != null) { literals.add(visitNaf_literal(ctx.naf_literal())); @@ -409,7 +418,7 @@ public Term visitGround_term(ASPCore2Parser.Ground_termContext ctx) { } @Override - public Term visitVariable_term(ASPCore2Parser.Variable_termContext ctx) { + public VariableTerm visitVariable_term(ASPCore2Parser.Variable_termContext ctx) { // variable_term : VARIABLE | ANONYMOUS_VARIABLE; if (ctx.VARIABLE() != null) { return Terms.newVariable(ctx.VARIABLE().getText()); @@ -698,11 +707,11 @@ public Assertion visitTestVerifier(Assertion.Mode assertionMode, ASPCore2Parser. } List stmts = ctx.statement(); programBuilders.push(currentLevelProgramBuilder); - currentLevelProgramBuilder = new ASPCore2ProgramBuilder(); + currentLevelProgramBuilder = new InputProgramBuilder(); for (ASPCore2Parser.StatementContext stmtCtx : stmts) { visit(stmtCtx); } - ASPCore2Program verifier = currentLevelProgramBuilder.build(); + InputProgram verifier = currentLevelProgramBuilder.build(); currentLevelProgramBuilder = programBuilders.pop(); return Tests.newAssertion(assertionMode, verifier); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramParserImpl.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramParserImpl.java index 64e36c247..4c4d418ce 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramParserImpl.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramParserImpl.java @@ -8,6 +8,9 @@ import java.util.Map; import at.ac.tuwien.kr.alpha.api.programs.InputProgram; +import at.ac.tuwien.kr.alpha.core.actions.ActionImplementationProvider; +import at.ac.tuwien.kr.alpha.core.antlr.ASPCore2Lexer; +import at.ac.tuwien.kr.alpha.core.antlr.ASPCore2Parser; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.CharStreams; @@ -20,8 +23,8 @@ import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; -import at.ac.tuwien.kr.alpha.core.externals.Externals; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.externals.Externals; public class ProgramParserImpl implements ProgramParser { @@ -35,6 +38,12 @@ public ProgramParserImpl(Map externals) { this(); this.preloadedExternals.putAll(externals); } + + public ProgramParserImpl(ActionImplementationProvider actionImplementationProvider, Map externals) { + this(externals); + this.preloadedExternals.put("stdin", actionImplementationProvider.getStdinTerm()); + this.preloadedExternals.put("stdout", actionImplementationProvider.getStdoutTerm()); + } @Override public InputProgram parse(String s) { @@ -141,7 +150,7 @@ public InputProgram parse(Path programPath, Map @Override public InputProgram parse(Map externalPredicateDefinitions, Path... programSources) throws IOException { - ASPCore2ProgramBuilder bld = Programs.builder(); + InputProgramBuilder bld = Programs.builder(); for (Path src : programSources) { bld.accumulate(parse(src, externalPredicateDefinitions)); } @@ -150,7 +159,7 @@ public InputProgram parse(Map externalPredicate @Override public InputProgram parse(Iterable programSources, Map externalPredicateDefinitions) throws IOException { - ASPCore2ProgramBuilder bld = Programs.builder(); + InputProgramBuilder bld = Programs.builder(); for (Path src : programSources) { bld.accumulate(parse(src, externalPredicateDefinitions)); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ProgramPartParser.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramPartParser.java similarity index 88% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ProgramPartParser.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramPartParser.java index 255a58891..14a5bc1d9 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ProgramPartParser.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/ProgramPartParser.java @@ -26,7 +26,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package at.ac.tuwien.kr.alpha.core.parser.aspcore2; +package at.ac.tuwien.kr.alpha.core.parser; import java.util.Collections; @@ -41,15 +41,14 @@ import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.core.antlr.ASPCore2Lexer; import at.ac.tuwien.kr.alpha.core.antlr.ASPCore2Parser; -import at.ac.tuwien.kr.alpha.core.parser.AbstractProgramParser; /** - * A parser that, in contrast to {@link AbstractProgramParser}, does not parse full programs but only program parts like + * A parser that, in contrast to {@link ProgramParser}, does not parse full programs but only program parts like * atoms, terms and such. */ // TODO adapt this and create evolog version -public class ASPCore2ProgramPartParser { - private final ASPCore2ParseTreeVisitor visitor = new ASPCore2ParseTreeVisitor(Collections.emptyMap(), true); +public class ProgramPartParser { + private final ParseTreeVisitor visitor = new ParseTreeVisitor(Collections.emptyMap(), true); public Term parseTerm(String s) { final ASPCore2Parser parser = getASPCore2Parser(s); diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ProgramParser.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ProgramParser.java deleted file mode 100644 index c4cd13ea7..000000000 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/aspcore2/ASPCore2ProgramParser.java +++ /dev/null @@ -1,23 +0,0 @@ -package at.ac.tuwien.kr.alpha.core.parser.aspcore2; - -import java.util.Map; - -import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.parser.AbstractProgramParser; - -public class ASPCore2ProgramParser extends AbstractProgramParser { - - public ASPCore2ProgramParser() { - super(); - } - - public ASPCore2ProgramParser(Map externals) { - super(externals); - } - - @Override - protected ASPCore2ParseTreeVisitor createParseTreeVisitor(Map externals) { - return new ASPCore2ParseTreeVisitor(externals); - } - -} diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/evolog/EvologParseTreeVisitor.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/evolog/EvologParseTreeVisitor.java deleted file mode 100644 index 2093d5da1..000000000 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/evolog/EvologParseTreeVisitor.java +++ /dev/null @@ -1,34 +0,0 @@ -package at.ac.tuwien.kr.alpha.core.parser.evolog; - -import java.util.List; -import java.util.Map; - -import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; -import at.ac.tuwien.kr.alpha.api.rules.heads.Head; -import at.ac.tuwien.kr.alpha.api.terms.Term; -import at.ac.tuwien.kr.alpha.api.terms.VariableTerm; -import at.ac.tuwien.kr.alpha.commons.rules.heads.Heads; -import at.ac.tuwien.kr.alpha.core.antlr.ASPCore2Parser; -import at.ac.tuwien.kr.alpha.core.parser.aspcore2.ASPCore2ParseTreeVisitor; - -public class EvologParseTreeVisitor extends ASPCore2ParseTreeVisitor { - - public EvologParseTreeVisitor(Map externals, boolean acceptVariables) { - super(externals, acceptVariables); - } - - public EvologParseTreeVisitor(Map externals) { - this(externals, true); - } - - @Override - public Head visitAction(ASPCore2Parser.ActionContext ctx) { - BasicAtom atom = visitClassical_literal(ctx.classical_literal()); - VariableTerm actionResultTerm = visitVariable_term(ctx.variable_term()); - String actionId = ctx.ID().getText(); - List actionInputTerms = visitTerms(ctx.terms()); - return Heads.newActionHead(atom, actionId, actionInputTerms, actionResultTerm); - } - -} diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/evolog/EvologProgramParser.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/evolog/EvologProgramParser.java deleted file mode 100644 index 3b1a9f71c..000000000 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/parser/evolog/EvologProgramParser.java +++ /dev/null @@ -1,27 +0,0 @@ -package at.ac.tuwien.kr.alpha.core.parser.evolog; - -import java.util.Collections; -import java.util.Map; - -import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.actions.ActionImplementationProvider; -import at.ac.tuwien.kr.alpha.core.parser.AbstractProgramParser; - -public class EvologProgramParser extends AbstractProgramParser { - - public EvologProgramParser(ActionImplementationProvider actionImplementationProvider, Map externals) { - super(externals); - registerExternal("stdin", actionImplementationProvider.getStdinTerm()); - registerExternal("stdout", actionImplementationProvider.getStdoutTerm()); - } - - public EvologProgramParser(ActionImplementationProvider actionImplementationProvider) { - this(actionImplementationProvider, Collections.emptyMap()); - } - - @Override - protected EvologParseTreeVisitor createParseTreeVisitor(Map externals) { - return new EvologParseTreeVisitor(externals); - } - -} diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/InternalProgram.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/InternalProgram.java index 43e69b984..afd2236ab 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/InternalProgram.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/InternalProgram.java @@ -104,7 +104,7 @@ public Map getRulesById() { public NormalProgram toNormalProgram() { List normalRules = new ArrayList<>(); for (CompiledRule rule : getRules()) { - normalRules.add(Rules.newNormalRule(rule.getHead(), new ArrayList<>(rule.getBody()))); + normalRules.add(Rules.newNormalRule(rule.getHead(), new LinkedHashSet<>(rule.getBody()))); } return Programs.newNormalProgram(normalRules, getFacts(), getInlineDirectives()); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/rules/InternalRule.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/rules/InternalRule.java index 8b57907f2..1bc31f104 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/rules/InternalRule.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/rules/InternalRule.java @@ -43,7 +43,9 @@ import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; /** * Represents a normal rule or a constraint for the semi-naive grounder. @@ -67,7 +69,7 @@ public class InternalRule extends AbstractRule implements CompiledRu * @param head the head of the rule. * @param body the list of body literals of the rule. */ - public InternalRule(NormalHead head, List body) { + public InternalRule(NormalHead head, Set body) { super(head, body); if (body.isEmpty()) { throw new IllegalArgumentException( @@ -101,7 +103,7 @@ public static void resetIdGenerator() { } public static CompiledRule fromNormalRule(Rule rule) { - return new InternalRule(rule.isConstraint() ? null : Heads.newNormalHead(rule.getHead().getAtom()), new ArrayList<>(rule.getBody())); + return new InternalRule(rule.isConstraint() ? null : Heads.newNormalHead(rule.getHead().getAtom()), new LinkedHashSet<>(rule.getBody())); } /** @@ -126,7 +128,7 @@ public InternalRule renameVariables(String newVariablePostfix) { variableReplacement.put(occurringVariable, Terms.newVariable(newVariableName)); } BasicAtom renamedHeadAtom = headAtom.substitute(variableReplacement); - ArrayList renamedBody = new ArrayList<>(this.getBody().size()); + Set renamedBody = new LinkedHashSet<>(this.getBody().size()); for (Literal literal : this.getBody()) { renamedBody.add(literal.substitute(variableReplacement)); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ArithmeticTermsRewriting.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ArithmeticTermsRewriting.java index 029123628..d7111f098 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ArithmeticTermsRewriting.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ArithmeticTermsRewriting.java @@ -1,7 +1,9 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; @@ -70,7 +72,7 @@ public NormalProgram apply(NormalProgram inputProgram) { private NormalRule rewriteRule(NormalRule inputProgramRule) { variableNumberGenerator.resetGenerator(); // Reset number of introduced variables for each rule. NormalHead rewrittenHead = null; - List rewrittenBodyLiterals = new ArrayList<>(); + Set rewrittenBodyLiterals = new LinkedHashSet<>(); // Rewrite head. if (!inputProgramRule.isConstraint()) { BasicAtom headAtom = inputProgramRule.getHeadAtom(); @@ -117,7 +119,7 @@ private boolean containsArithmeticTermsToRewrite(NormalRule inputProgramRule) { return false; } - private Term rewriteArithmeticSubterms(Term term, List bodyLiterals) { + private Term rewriteArithmeticSubterms(Term term, Set bodyLiterals) { // Keep term as-is if it contains no ArithmeticTerm. if (!containsArithmeticTerm(term)) { return term; @@ -141,7 +143,7 @@ private Term rewriteArithmeticSubterms(Term term, List bodyLiterals) { } } - private Atom rewriteAtom(Atom atomToRewrite, List bodyLiterals) { + private Atom rewriteAtom(Atom atomToRewrite, Set bodyLiterals) { if (atomToRewrite instanceof ComparisonAtom) { throw Util.oops("Trying to rewrite ComparisonAtom."); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ChoiceHeadToNormal.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ChoiceHeadToNormal.java index 486c57e12..3b167ac9f 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ChoiceHeadToNormal.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ChoiceHeadToNormal.java @@ -27,11 +27,8 @@ */ package at.ac.tuwien.kr.alpha.core.programs.transformation; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import java.util.*; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; @@ -44,7 +41,7 @@ import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; import at.ac.tuwien.kr.alpha.commons.programs.rules.heads.Heads; @@ -59,7 +56,7 @@ public class ChoiceHeadToNormal extends ProgramTransformation> additionalRules = new ArrayList<>(); List> srcRules = new ArrayList<>(inputProgram.getRules()); @@ -105,11 +102,11 @@ public InputProgram apply(InputProgram inputProgram) { BasicAtom negHead = Atoms.newBasicAtom(negPredicate, headTerms); // Construct two guessing rules. - List guessingRuleBodyWithNegHead = new ArrayList<>(ruleBody); + Set guessingRuleBodyWithNegHead = new LinkedHashSet<>(ruleBody); guessingRuleBodyWithNegHead.add(Atoms.newBasicAtom(head.getPredicate(), head.getTerms()).toLiteral(false)); additionalRules.add(Rules.newRule(Heads.newNormalHead(negHead), guessingRuleBodyWithNegHead)); - List guessingRuleBodyWithHead = new ArrayList<>(ruleBody); + Set guessingRuleBodyWithHead = new LinkedHashSet<>(ruleBody); guessingRuleBodyWithHead.add(Atoms.newBasicAtom(negPredicate, headTerms).toLiteral(false)); additionalRules.add(Rules.newRule(Heads.newNormalHead(head), guessingRuleBodyWithHead)); diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/EnumerationTransformer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/EnumerationRewriting.java similarity index 87% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/EnumerationTransformer.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/EnumerationRewriting.java index 9d20fb69f..803af1879 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/EnumerationTransformer.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/EnumerationRewriting.java @@ -1,12 +1,9 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; +import java.util.*; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; import at.ac.tuwien.kr.alpha.api.programs.InlineDirectives; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.literals.BasicLiteral; @@ -18,7 +15,7 @@ import at.ac.tuwien.kr.alpha.api.programs.terms.VariableTerm; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; import at.ac.tuwien.kr.alpha.commons.util.Util; import at.ac.tuwien.kr.alpha.core.programs.atoms.EnumerationAtom; @@ -30,10 +27,10 @@ * Copyright (c) 2017-2020, the Alpha Team. */ // TODO this should happen during/after internalization -public class EnumerationRewriting extends ProgramTransformation { +public class EnumerationRewriting extends ProgramTransformation { @Override - public ASPCore2Program apply(ASPCore2Program inputProgram) { + public InputProgram apply(InputProgram inputProgram) { // Read enumeration predicate from directive. String enumDirective = inputProgram.getInlineDirectives().getDirectiveValue(InlineDirectives.DIRECTIVE.enum_predicate_is); if (enumDirective == null) { @@ -42,7 +39,7 @@ public ASPCore2Program apply(ASPCore2Program inputProgram) { } Predicate enumPredicate = Predicates.getPredicate(enumDirective, 3); - ASPCore2ProgramBuilder programBuilder = Programs.builder().addInlineDirectives(inputProgram.getInlineDirectives()); + InputProgramBuilder programBuilder = Programs.builder().addInlineDirectives(inputProgram.getInlineDirectives()); checkFactsAreEnumerationFree(inputProgram.getFacts(), enumPredicate); programBuilder.addFacts(inputProgram.getFacts()); @@ -69,7 +66,7 @@ private List> rewriteRules(List> srcRules, Predicate enumP if (rule.getHead() != null && ((NormalHead) rule.getHead()).getAtom().getPredicate().equals(enumPredicate)) { throw Util.oops("Atom declared as enumeration atom by directive occurs in head of the rule: " + rule); } - List modifiedBodyLiterals = new ArrayList<>(rule.getBody()); + Set modifiedBodyLiterals = new LinkedHashSet<>(rule.getBody()); Iterator rit = modifiedBodyLiterals.iterator(); LinkedList rewrittenLiterals = new LinkedList<>(); while (rit.hasNext()) { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/IntervalTermTransformer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/IntervalTermToIntervalAtom.java similarity index 98% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/IntervalTermTransformer.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/IntervalTermToIntervalAtom.java index 90d532aff..9b1c69143 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/IntervalTermTransformer.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/IntervalTermToIntervalAtom.java @@ -27,10 +27,7 @@ */ package at.ac.tuwien.kr.alpha.core.programs.transformation; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; @@ -68,7 +65,7 @@ private static NormalRule rewriteIntervalSpecifications(NormalRule rule) { // Collect all intervals and replace them with variables. Map intervalReplacements = new LinkedHashMap<>(); - List rewrittenBody = new ArrayList<>(); + Set rewrittenBody = new LinkedHashSet<>(); for (Literal literal : rule.getBody()) { Literal rewrittenLiteral = rewriteLiteral(literal, intervalReplacements); diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/NormalizeProgramTransformation.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/NormalizeProgramTransformation.java index f8d3303f0..d3b5c9cc8 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/NormalizeProgramTransformation.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/NormalizeProgramTransformation.java @@ -1,7 +1,7 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation; import at.ac.tuwien.kr.alpha.api.config.AggregateRewritingConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.commons.programs.Programs; import at.ac.tuwien.kr.alpha.core.programs.atoms.EnumerationAtom; @@ -12,7 +12,7 @@ * * Copyright (c) 2019-2021, the Alpha Team. */ -public class NormalizeProgramTransformation extends ProgramTransformation { +public class NormalizeProgramTransformation extends ProgramTransformation { private final AggregateRewritingConfig aggregateRewritingCfg; @@ -21,8 +21,8 @@ public NormalizeProgramTransformation(AggregateRewritingConfig aggregateCfg) { } @Override - public NormalProgram apply(ASPCore2Program inputProgram) { - ASPCore2Program tmpPrg; + public NormalProgram apply(InputProgram inputProgram) { + InputProgram tmpPrg; // Remove variable equalities. tmpPrg = new VariableEqualityRemoval().apply(inputProgram); // Transform choice rules. diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/PredicateInternalizer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/PredicateInternalizer.java index 23b47bc83..d33962805 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/PredicateInternalizer.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/PredicateInternalizer.java @@ -1,9 +1,6 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation; -import java.util.ArrayList; -import java.util.List; - -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; @@ -14,11 +11,16 @@ import at.ac.tuwien.kr.alpha.api.programs.rules.heads.NormalHead; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; import at.ac.tuwien.kr.alpha.commons.programs.rules.heads.Heads; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + /** * * Rewrites all predicates of a given Program such that they are internal and hence hidden from answer sets. @@ -27,8 +29,8 @@ */ public class PredicateInternalizer { - public static ASPCore2Program makePrefixedPredicatesInternal(ASPCore2Program program, String prefix) { - ASPCore2ProgramBuilder prgBuilder = Programs.builder(); + public static InputProgram makePrefixedPredicatesInternal(InputProgram program, String prefix) { + InputProgramBuilder prgBuilder = Programs.builder(); for (Atom atom : program.getFacts()) { if (atom.getPredicate().getName().startsWith(prefix)) { prgBuilder.addFact(PredicateInternalizer.makePredicateInternal((BasicAtom) atom)); @@ -56,7 +58,7 @@ public static Rule makePrefixedPredicatesInternal(Rule rule, String newHead = head; } } - List newBody = new ArrayList<>(); + Set newBody = new LinkedHashSet<>(); for (Literal bodyElement : rule.getBody()) { // Only rewrite BasicAtoms. if (bodyElement instanceof BasicLiteral) { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramNormalizer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramNormalizer.java deleted file mode 100644 index 89498e3da..000000000 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramNormalizer.java +++ /dev/null @@ -1,54 +0,0 @@ -package at.ac.tuwien.kr.alpha.core.programs.transformation; - -import at.ac.tuwien.kr.alpha.api.programs.InputProgram; -import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; -import at.ac.tuwien.kr.alpha.core.atoms.EnumerationAtom; -import at.ac.tuwien.kr.alpha.core.programs.NormalProgramImpl; -import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.AggregateTransformer; - -/** - * Encapsulates all transformations necessary to transform a given program into a @{link NormalProgram} that is understood by Alpha internally - * - * Copyright (c) 2019-2021, the Alpha Team. - */ -public class ProgramNormalizer extends ProgramTransformer { - - private final VariableEqualityTransformer equalityTransformer; - private final ChoiceHeadNormalizer choiceHeadNormalizer; - private final AggregateTransformer aggregateTransformer; - private final EnumerationTransformer enumerationTransformer; - private final IntervalTermTransformer intervalTermTransformer; - private final ArithmeticTermTransformer arithmeticTermTransformer; - - public ProgramNormalizer(VariableEqualityTransformer equalityTransformer, ChoiceHeadNormalizer choiceHeadNormalizer, AggregateTransformer aggregateTransformer, EnumerationTransformer enumerationTransformer, IntervalTermTransformer intervalTermTransformer, ArithmeticTermTransformer arithmeticTermTransformer) { - this.equalityTransformer = equalityTransformer; - this.choiceHeadNormalizer = choiceHeadNormalizer; - this.aggregateTransformer = aggregateTransformer; - this.enumerationTransformer = enumerationTransformer; - this.intervalTermTransformer = intervalTermTransformer; - this.arithmeticTermTransformer = arithmeticTermTransformer; - } - - @Override - public NormalProgram transform(InputProgram inputProgram) { - InputProgram tmpPrg; - // Remove variable equalities. - tmpPrg = equalityTransformer.transform(inputProgram); - // Transform choice rules. - tmpPrg = choiceHeadNormalizer.transform(tmpPrg); - // Transform aggregates. - tmpPrg = aggregateTransformer.transform(tmpPrg); - // Transform enumeration atoms. - tmpPrg = enumerationTransformer.transform(tmpPrg); - EnumerationAtom.resetEnumerations(); - - // Construct the normal program. - NormalProgram retVal = NormalProgramImpl.fromInputProgram(tmpPrg); - // Transform intervals. - retVal = intervalTermTransformer.transform(retVal); - // Rewrite ArithmeticTerms. - retVal = arithmeticTermTransformer.transform(retVal); - return retVal; - } - -} diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformation.java similarity index 57% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformer.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformation.java index 098c10bc8..5fc28c50a 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformer.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformation.java @@ -6,8 +6,8 @@ /** * Copyright (c) 2017-2019, the Alpha Team. */ -public abstract class ProgramTransformer>, O extends Program>> { +public abstract class ProgramTransformation>, O extends Program>> { - public abstract O transform(I inputProgram); + public abstract O apply(I inputProgram); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluation.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluation.java index 34fed23dc..07bf0036e 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluation.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluation.java @@ -11,6 +11,15 @@ import java.util.Set; import java.util.Stack; +import at.ac.tuwien.kr.alpha.api.programs.rules.RuleInstantiator; +import at.ac.tuwien.kr.alpha.api.programs.rules.heads.ActionHead; +import at.ac.tuwien.kr.alpha.api.programs.rules.heads.InstantiableHead; +import at.ac.tuwien.kr.alpha.api.programs.rules.heads.NormalHead; +import at.ac.tuwien.kr.alpha.api.programs.terms.FunctionTerm; +import at.ac.tuwien.kr.alpha.api.programs.terms.Term; +import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; +import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; +import at.ac.tuwien.kr.alpha.core.programs.rules.CompiledRule; import org.apache.commons.collections4.SetUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; @@ -21,10 +30,13 @@ import at.ac.tuwien.kr.alpha.api.programs.analysis.ComponentGraph; import at.ac.tuwien.kr.alpha.api.programs.analysis.DependencyGraph; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; +import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; -import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; +import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.substitutions.BasicSubstitution; import at.ac.tuwien.kr.alpha.commons.substitutions.Instance; +import at.ac.tuwien.kr.alpha.core.actions.ActionExecutionService; +import at.ac.tuwien.kr.alpha.core.actions.ActionWitness; import at.ac.tuwien.kr.alpha.core.depgraph.StratificationAlgorithm; import at.ac.tuwien.kr.alpha.core.grounder.IndexedInstanceStorage; import at.ac.tuwien.kr.alpha.core.grounder.RuleGroundingInfo; @@ -36,14 +48,13 @@ import at.ac.tuwien.kr.alpha.core.grounder.instantiation.WorkingMemoryBasedInstantiationStrategy; import at.ac.tuwien.kr.alpha.core.programs.AnalyzedProgram; import at.ac.tuwien.kr.alpha.core.programs.InternalProgram; -import at.ac.tuwien.kr.alpha.core.programs.rules.CompiledRule; /** * Evaluates the stratifiable part of a given (analyzed) ASP program. - * + * * Copyright (c) 2019-2020, the Alpha Team. */ -public class StratifiedEvaluation extends ProgramTransformation { +public class StratifiedEvaluation extends ProgramTransformation implements RuleInstantiator { private static final Logger LOGGER = LoggerFactory.getLogger(StratifiedEvaluation.class); @@ -52,10 +63,17 @@ public class StratifiedEvaluation extends ProgramTransformation> modifiedInLastEvaluationRun = new HashMap<>(); - private List additionalFacts = new ArrayList<>(); // The additional facts derived by stratified evaluation. Note that it may contain duplicates. + private Set outputFacts = new HashSet<>(); // The additional facts derived by stratified evaluation. Note that it may contain duplicates. private Set solvedRuleIds = new HashSet<>(); // Set of rules that have been completely evaluated. private LiteralInstantiator literalInstantiator; + private ActionExecutionService actionExecutionService; + private final boolean generateActionWitnesses; + + public StratifiedEvaluation(ActionExecutionService actionExecutionService, boolean generateActionWitnesses) { + this.actionExecutionService = actionExecutionService; + this.generateActionWitnesses = generateActionWitnesses; + } @Override // Note: ideally this returns a "PartiallyEvaluatedProgram" such that the grounder can directly use the working @@ -82,6 +100,9 @@ public InternalProgram apply(AnalyzedProgram inputProgram) { workingMemory.reset(); + // Set up set of facts to which we'll add everything derived during stratified evaluation. + outputFacts = new HashSet<>(inputProgram.getFacts()); + // Set up literal instantiator. literalInstantiator = new LiteralInstantiator(new WorkingMemoryBasedInstantiationStrategy(workingMemory)); @@ -91,13 +112,12 @@ public InternalProgram apply(AnalyzedProgram inputProgram) { } // Build the program resulting from evaluating the stratified part. - additionalFacts.addAll(inputProgram.getFacts()); // Add original input facts to newly derived ones. List outputRules = new ArrayList<>(); inputProgram.getRulesById().entrySet().stream().filter((entry) -> !solvedRuleIds.contains(entry.getKey())) .forEach((entry) -> outputRules.add(entry.getValue())); // NOTE: if InternalProgram requires solved rules, they should be added here. - return new InternalProgram(outputRules, additionalFacts); + return new InternalProgram(outputRules, new ArrayList<>(outputFacts)); } private void evaluateComponent(ComponentGraph.SCComponent comp) { @@ -114,9 +134,7 @@ private void evaluateComponent(ComponentGraph.SCComponent comp) { evaluateRules(evaluationInfo.nonRecursiveRules, true); for (IndexedInstanceStorage instanceStorage : workingMemory.modified()) { // Directly record all newly derived instances as additional facts. - for (Instance recentlyAddedInstance : instanceStorage.getRecentlyAddedInstances()) { - additionalFacts.add(Atoms.newBasicAtom(instanceStorage.getPredicate(), recentlyAddedInstance.terms)); - } + recordRecentlyAddedInstances(instanceStorage); instanceStorage.markRecentlyAddedInstancesDone(); } } @@ -134,9 +152,7 @@ private void evaluateComponent(ComponentGraph.SCComponent comp) { // Since we are stratified we never have to backtrack, therefore just collect the added instances. for (IndexedInstanceStorage instanceStorage : workingMemory.modified()) { // Directly record all newly derived instances as additional facts. - for (Instance recentlyAddedInstance : instanceStorage.getRecentlyAddedInstances()) { - additionalFacts.add(Atoms.newBasicAtom(instanceStorage.getPredicate(), recentlyAddedInstance.terms)); - } + recordRecentlyAddedInstances(instanceStorage); modifiedInLastEvaluationRun.putIfAbsent(instanceStorage.getPredicate(), new LinkedHashSet<>()); modifiedInLastEvaluationRun.get(instanceStorage.getPredicate()).addAll(instanceStorage.getRecentlyAddedInstances()); instanceStorage.markRecentlyAddedInstancesDone(); @@ -149,6 +165,12 @@ private void evaluateComponent(ComponentGraph.SCComponent comp) { .forEach((rule) -> solvedRuleIds.add(rule.getRuleId())); } + private void recordRecentlyAddedInstances(IndexedInstanceStorage instanceStorage) { + for (Instance recentlyAddedInstance : instanceStorage.getRecentlyAddedInstances()) { + outputFacts.add(Atoms.newBasicAtom(instanceStorage.getPredicate(), recentlyAddedInstance.terms)); + } + } + private void evaluateRules(Set rules, boolean isInitialRun) { workingMemory.reset(); LOGGER.debug("Starting component evaluation run..."); @@ -225,7 +247,7 @@ private List calculateSatisfyingSubstitutionsForRule(CompiledRule * Use this to find initial substitutions for a starting literal when grounding a rule. * In order to avoid finding the same ground instantiations of rules again, only look at * modifiedInLastEvaluationRun to obtain instances. - * + * * @param lit the literal to substitute. * @return valid ground substitutions for the literal based on the recently added instances (i.e. instances derived in * the last evaluation run). @@ -255,7 +277,7 @@ private List calcSubstitutionsWithGroundingOrder(RuleGroundingOrde substitutionStack.push((ArrayList) startingSubstitutions); } else { substitutionStack.push(new ArrayList<>(startingSubstitutions)); // Copy startingSubstitutions into ArrayList. Note: mostly happens for empty or - // singleton lists. + // singleton lists. } int currentOrderPosition = 0; List fullSubstitutions = new ArrayList<>(); @@ -280,7 +302,7 @@ private List calcSubstitutionsWithGroundingOrder(RuleGroundingOrde } // Take one substitution from the top-list of the stack and try extending it. Substitution currentSubstitution = currentSubstitutions.remove(currentSubstitutions.size() - 1); // Work on last element (removing last element is - // O(1) for ArrayList). + // O(1) for ArrayList). LiteralInstantiationResult currentLiteralResult = literalInstantiator.instantiateLiteral(currentLiteral, currentSubstitution); if (currentLiteralResult.getType() == LiteralInstantiationResult.Type.CONTINUE) { // The currentSubstitution could be extended, push the extensions on the stack and continue working on them. @@ -297,7 +319,13 @@ private List calcSubstitutionsWithGroundingOrder(RuleGroundingOrde } private void fireRule(CompiledRule rule, Substitution substitution) { - Atom newAtom = rule.getHeadAtom().substitute(substitution); + // BasicAtom newAtom = this.instantiate(rule.getHead(), substitution); + BasicAtom newAtom; + if (rule.getHead() instanceof ActionHead) { + newAtom = instantiateActionHead((ActionHead) rule.getHead(), substitution, rule); + } else { + newAtom = instantiateNormalHead(rule.getHead(), substitution); + } if (!newAtom.isGround()) { throw new IllegalStateException("Trying to fire rule " + rule.toString() + " with incompatible substitution " + substitution.toString()); } @@ -305,6 +333,64 @@ private void fireRule(CompiledRule rule, Substitution substitution) { workingMemory.addInstance(newAtom, true); } + @Override + public BasicAtom instantiate(InstantiableHead ruleHead, Substitution substitution) { + return ruleHead.instantiate(this, substitution); + } + + // FIXME should be dispatched via visitor pattern + public BasicAtom instantiateNormalHead(NormalHead head, Substitution substitution) { + return head.getAtom().substitute(substitution); + } + + // FIXME should be dispatched via visitor pattern + public BasicAtom instantiateActionHead(ActionHead head, Substitution substitution, CompiledRule rule) { + List actionInput = head.getActionInputTerms(); + List substitutedInput = new ArrayList<>(); + // Substitute all variables in action input so that all input terms are ground. + for (Term inputTerm : actionInput) { + substitutedInput.add(inputTerm.substitute(substitution)); + } + // Delegate action execution to respective backend. + ActionWitness witness = actionExecutionService.execute(head.getActionName(), rule.getRuleId(), substitution, substitutedInput); + // If the according debug flag is set, convert witness to atom and add to facts. + if (generateActionWitnesses) { + BasicAtom witnessAtom = buildActionWitnessAtom(witness, rule); + // Note that this is a rather "sneaky" side-effect, + // but seems like overkill to do this structurally proper just for a debug feature. + workingMemory.addInstance(witnessAtom, true); + } + // We have an action result. Add it to the substitution as the substitute for the variable bound to the action so we're able to obtain the + // ground BasicAtom derived by the rule + substitution.put(head.getActionOutputTerm(), witness.getActionResult()); + return head.getAtom().substitute(substitution); + } + + private BasicAtom buildActionWitnessAtom(ActionWitness witness, CompiledRule rule) { + // Note that this methods should only ever be used for debugging! + // While action witnesses are used as a semantic concept in the evolog specification, + // they normally only exist implicitly. + + // Construct state term: create function terms from ground body literals. + List functionalizedBody = new ArrayList<>(); + for (Literal lit : rule.getBody()) { + Literal groundLit = lit.substitute(witness.getGroundSubstitution()); + FunctionTerm functionalizedLiteral = Terms.newFunctionTerm(groundLit.getPredicate().getName(), groundLit.getTerms()); + functionalizedBody.add(functionalizedLiteral); + } + FunctionTerm stateTerm = Terms.newFunctionTerm("state", functionalizedBody); + + // Construct input term: wrap action input terms into one function term. + FunctionTerm inputTerm = Terms.newFunctionTerm("input", witness.getActionInput()); + + // Return witness atom: put state and input terms together. + return Atoms.newBasicAtom(Predicates.getPredicate("action_witness", 4), + Terms.newConstant(witness.getActionName()), + stateTerm, + inputTerm, + witness.getActionResult()); + } + private ComponentEvaluationInfo getRulesToEvaluate(ComponentGraph.SCComponent comp) { Set nonRecursiveRules = new HashSet<>(); Set recursiveRules = new HashSet<>(); @@ -348,7 +434,7 @@ private ComponentEvaluationInfo getRulesToEvaluate(ComponentGraph.SCComponent co * dependency chain within that component, and non-recursive rules, i.e. rules where all body predicates occur in lower * strata. The reason for this grouping is that, when evaluating rules within a component, non-recursive rules only need * to be evaluated once, while recursive rules need to be evaluated until a fixed-point has been reached. - * + * * Copyright (c) 2020, the Alpha Team. */ private class ComponentEvaluationInfo { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/VariableEqualityTransformer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/VariableEqualityRemoval.java similarity index 91% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/VariableEqualityTransformer.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/VariableEqualityRemoval.java index 3c84b54a0..a08aac2e2 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/VariableEqualityTransformer.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/VariableEqualityRemoval.java @@ -27,17 +27,9 @@ */ package at.ac.tuwien.kr.alpha.core.programs.transformation; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; +import java.util.*; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.literals.ComparisonLiteral; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; @@ -57,15 +49,15 @@ * * Copyright (c) 2017-2021, the Alpha Team. */ -public class VariableEqualityRemoval extends ProgramTransformation { +public class VariableEqualityRemoval extends ProgramTransformation { @Override - public ASPCore2Program apply(ASPCore2Program inputProgram) { + public InputProgram apply(InputProgram inputProgram) { List> rewrittenRules = new ArrayList<>(); for (Rule rule : inputProgram.getRules()) { rewrittenRules.add(findAndReplaceVariableEquality(rule)); } - return Programs.newASPCore2Program(rewrittenRules, inputProgram.getFacts(), inputProgram.getInlineDirectives()); + return Programs.newInputProgram(rewrittenRules, inputProgram.getFacts(), inputProgram.getInlineDirectives()); } private Rule findAndReplaceVariableEquality(Rule rule) { @@ -112,7 +104,7 @@ private Rule findAndReplaceVariableEquality(Rule rule) { return rule; } - List rewrittenBody = new ArrayList<>(rule.getBody()); + Set rewrittenBody = new LinkedHashSet<>(rule.getBody()); if (!rule.isConstraint() && rule.getHead() instanceof DisjunctiveHead) { throw new UnsupportedOperationException("VariableEqualityRemoval cannot be applied to rule with DisjunctiveHead, yet."); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateLiteralSplitting.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateLiteralSplitting.java index b959269d2..ed55537b0 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateLiteralSplitting.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateLiteralSplitting.java @@ -1,8 +1,6 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.util.*; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -66,17 +64,17 @@ private static List> splitAggregatesInRule(Rule sourceRule) { } } // Second, compute rule bodies of splitting result. - List commonBody = new ArrayList<>(commonBodyLiterals); + Set commonBody = new LinkedHashSet<>(commonBodyLiterals); commonBody.addAll(twoLiteralsSplitAggregates); - List> rewrittenBodies = new ArrayList<>(); + List> rewrittenBodies = new ArrayList<>(); rewrittenBodies.add(commonBody); // Initialize list of rules with the common body. // For n twoRulesSplitAggregates we need 2^n rules, so // for each of the n pairs in twoRulesSplitAggregates we duplicate the list of rewritten bodies. for (ImmutablePair ruleSplitAggregate : twoRulesSplitAggregates) { int numBodiesBeforeDuplication = rewrittenBodies.size(); for (int i = 0; i < numBodiesBeforeDuplication; i++) { - List originalBody = rewrittenBodies.get(i); - List duplicatedBody = new ArrayList<>(originalBody); + Set originalBody = rewrittenBodies.get(i); + Set duplicatedBody = new LinkedHashSet<>(originalBody); // Extend bodies of original and duplicate with splitting results. originalBody.add(ruleSplitAggregate.left); duplicatedBody.add(ruleSplitAggregate.right); @@ -85,7 +83,7 @@ private static List> splitAggregatesInRule(Rule sourceRule) { } // Third, turn computed bodies into rules again. List> rewrittenRules = new ArrayList<>(); - for (List rewrittenBody : rewrittenBodies) { + for (Set rewrittenBody : rewrittenBodies) { rewrittenRules.add(Rules.newRule(sourceRule.getHead(), rewrittenBody)); } return rewrittenRules; diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateOperatorNormalization.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateOperatorNormalization.java index 12e3273b6..8235c1364 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateOperatorNormalization.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateOperatorNormalization.java @@ -1,8 +1,6 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.util.*; import at.ac.tuwien.kr.alpha.api.ComparisonOperator; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom; @@ -22,7 +20,7 @@ import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; /** - * Transforms an {@link AspCore2ProgramImpl} such that, for all aggregate (body-)literals, only the comparison operators "=" + * Transforms an {@link at.ac.tuwien.kr.alpha.api.programs.InputProgram} such that, for all aggregate (body-)literals, only the comparison operators "=" * and "<=" are used. * * Rewriting of "#count" and "#sum" aggregates is done using the following equivalences: @@ -41,7 +39,7 @@ * Note that input programs must only contain aggregate literals of form TERM OP #aggr{...} or #aggr{...} OP TERM, * i.e. with only * a left or right term and operator (but not both). When preprocessing programs, apply this transformation AFTER - * {@link at.ac.tuwien.kr.alpha.grounder.transformation.aggregates.AggregateLiteralSplitting}. + * {@link AggregateLiteralSplitting}. * * Copyright (c) 2020-2021, the Alpha Team. */ @@ -52,7 +50,7 @@ private AggregateOperatorNormalization() { } public static Rule normalize(Rule rule) { - List rewrittenBody = new ArrayList<>(); + Set rewrittenBody = new LinkedHashSet<>(); for (Literal lit : rule.getBody()) { rewrittenBody.addAll(rewriteLiteral(lit)); } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateTransformer.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewriting.java similarity index 84% rename from alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateTransformer.java rename to alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewriting.java index aff59e893..48d4747c9 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateTransformer.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewriting.java @@ -1,14 +1,7 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.tuple.ImmutablePair; - import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateFunctionSymbol; import at.ac.tuwien.kr.alpha.api.programs.literals.AggregateLiteral; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; @@ -16,22 +9,23 @@ import at.ac.tuwien.kr.alpha.api.programs.rules.heads.Head; import at.ac.tuwien.kr.alpha.commons.comparisons.ComparisonOperators; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.literals.Literals; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; import at.ac.tuwien.kr.alpha.core.programs.transformation.ProgramTransformation; import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.AggregateRewritingContext.AggregateInfo; import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.AbstractAggregateEncoder; -import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.CountEncoder; -import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.MinMaxEncoder; -import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.SumEncoder; +import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.AggregateEncoders; +import org.apache.commons.lang3.tuple.ImmutablePair; + +import java.util.*; /** * Rewrites {@link AggregateLiteral}s in programs to semantically equivalent, aggregate-free sub-programs. * * Copyright (c) 2020, the Alpha Team. */ -public class AggregateRewriting extends ProgramTransformation { +public class AggregateRewriting extends ProgramTransformation { private final AbstractAggregateEncoder countEqualsEncoder; private final AbstractAggregateEncoder countLessOrEqualEncoder; @@ -51,12 +45,12 @@ public class AggregateRewriting extends ProgramTransformation> outputRules = new ArrayList<>(); for (Rule inputRule : inputProgram.getRules()) { @@ -89,7 +83,7 @@ public ASPCore2Program apply(ASPCore2Program inputProgram) { } // Substitute AggregateLiterals with generated result literals. outputRules.addAll(rewriteRulesWithAggregates(ctx)); - ASPCore2ProgramBuilder resultBuilder = Programs.builder().addRules(outputRules).addFacts(inputProgram.getFacts()) + InputProgramBuilder resultBuilder = Programs.builder().addRules(outputRules).addFacts(inputProgram.getFacts()) .addInlineDirectives(inputProgram.getInlineDirectives()); // Add sub-programs deriving respective aggregate literals. for (Map.Entry, Set> aggToRewrite : ctx.getAggregateFunctionsToRewrite() @@ -138,7 +132,7 @@ private AbstractAggregateEncoder getEncoderForAggregateFunction(AggregateFunctio private static List> rewriteRulesWithAggregates(AggregateRewritingContext ctx) { List> rewrittenRules = new ArrayList<>(); for (Rule rule : ctx.getRulesWithAggregates()) { - List rewrittenBody = new ArrayList<>(); + Set rewrittenBody = new LinkedHashSet<>(); for (Literal lit : rule.getBody()) { if (lit instanceof AggregateLiteral) { AggregateInfo aggregateInfo = ctx.getAggregateInfo((AggregateLiteral) lit); diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingContext.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingContext.java index c7e3f2fc2..a1742b71d 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingContext.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingContext.java @@ -1,19 +1,5 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates; -import static at.ac.tuwien.kr.alpha.commons.util.Util.oops; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.stringtemplate.v4.ST; - import at.ac.tuwien.kr.alpha.api.ComparisonOperator; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateFunctionSymbol; @@ -28,6 +14,12 @@ import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.stringtemplate.v4.ST; + +import java.util.*; + +import static at.ac.tuwien.kr.alpha.commons.util.Util.oops; /** * Holds all information about aggregate literals that need to be rewritten within a program. diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingRuleAnalysis.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingRuleAnalysis.java index 1433f1665..9647fa444 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingRuleAnalysis.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/AggregateRewritingRuleAnalysis.java @@ -1,15 +1,5 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.collections4.SetUtils; - import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom; import at.ac.tuwien.kr.alpha.api.programs.literals.AggregateLiteral; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; @@ -18,6 +8,9 @@ import at.ac.tuwien.kr.alpha.api.programs.rules.heads.NormalHead; import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.api.programs.terms.VariableTerm; +import org.apache.commons.collections4.SetUtils; + +import java.util.*; /** * Analyses a rule and records occurring aggregates and for each aggregate its global variables and its dependencies on diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AbstractAggregateEncoder.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AbstractAggregateEncoder.java index 4b6c431b1..92a09f658 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AbstractAggregateEncoder.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AbstractAggregateEncoder.java @@ -1,13 +1,7 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import org.apache.commons.collections4.ListUtils; - import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateElement; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateFunctionSymbol; @@ -19,13 +13,20 @@ import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; import at.ac.tuwien.kr.alpha.commons.programs.rules.heads.Heads; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; import at.ac.tuwien.kr.alpha.core.programs.transformation.PredicateInternalizer; import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.AggregateRewritingContext.AggregateInfo; +import org.apache.commons.collections4.ListUtils; +import org.apache.commons.collections4.SetUtils; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; /** * Abstract base class for aggregate encoders. An aggregate encoder provides an encoding for a given aggregate literal, @@ -49,10 +50,10 @@ protected AbstractAggregateEncoder(AggregateFunctionSymbol aggregateFunctionToEn * Encodes all aggregate literals in the given set of aggregate referenced by the given {@link AggregateInfo}. * * @param aggregatesToEncode the aggregates to encode. - * @return all rules encoding the given aggregates as an {@link AspCore2ProgramImpl}. + * @return all rules encoding the given aggregates as an {@link InputProgram}. */ - public ASPCore2Program encodeAggregateLiterals(Set aggregatesToEncode) { - ASPCore2ProgramBuilder programBuilder = Programs.builder(); + public InputProgram encodeAggregateLiterals(Set aggregatesToEncode) { + InputProgramBuilder programBuilder = Programs.builder(); for (AggregateInfo aggregateInfo : aggregatesToEncode) { programBuilder.accumulate(encodeAggregateLiteral(aggregateInfo)); } @@ -65,7 +66,7 @@ public ASPCore2Program encodeAggregateLiterals(Set aggregatesToEn * @param aggregateToEncode * @return */ - public ASPCore2Program encodeAggregateLiteral(AggregateInfo aggregateToEncode) { + public InputProgram encodeAggregateLiteral(AggregateInfo aggregateToEncode) { AggregateLiteral literalToEncode = aggregateToEncode.getLiteral(); if (literalToEncode.getAtom().getAggregateFunction() != this.aggregateFunctionToEncode) { throw new IllegalArgumentException( @@ -76,13 +77,13 @@ public ASPCore2Program encodeAggregateLiteral(AggregateInfo aggregateToEncode) { + literalToEncode.getAtom().getAggregateFunction() + " with operator " + literalToEncode.getAtom().getLowerBoundOperator()); } String aggregateId = aggregateToEncode.getId(); - ASPCore2Program literalEncoding = PredicateInternalizer.makePrefixedPredicatesInternal(encodeAggregateResult(aggregateToEncode), aggregateId); + InputProgram literalEncoding = PredicateInternalizer.makePrefixedPredicatesInternal(encodeAggregateResult(aggregateToEncode), aggregateId); List> elementEncodingRules = new ArrayList<>(); for (AggregateElement elementToEncode : literalToEncode.getAtom().getAggregateElements()) { Rule elementRule = encodeAggregateElement(aggregateToEncode, elementToEncode); elementEncodingRules.add(PredicateInternalizer.makePrefixedPredicatesInternal(elementRule, aggregateId)); } - return Programs.newASPCore2Program(ListUtils.union(literalEncoding.getRules(), elementEncodingRules), literalEncoding.getFacts(), Programs.newInlineDirectives()); + return Programs.newInputProgram(ListUtils.union(literalEncoding.getRules(), elementEncodingRules), literalEncoding.getFacts(), Programs.newInlineDirectives()); } /** @@ -93,7 +94,7 @@ public ASPCore2Program encodeAggregateLiteral(AggregateInfo aggregateToEncode) { * @param aggregateToEncode * @return */ - protected abstract ASPCore2Program encodeAggregateResult(AggregateInfo aggregateToEncode); + protected abstract InputProgram encodeAggregateResult(AggregateInfo aggregateToEncode); /** * Encodes individual aggregate elements. For each aggregate element, a rule is created that fires for each tuple matching the element. @@ -105,7 +106,7 @@ public ASPCore2Program encodeAggregateLiteral(AggregateInfo aggregateToEncode) { protected Rule encodeAggregateElement(AggregateInfo aggregateInfo, AggregateElement element) { BasicAtom headAtom = buildElementRuleHead(aggregateInfo.getId(), element, aggregateInfo.getAggregateArguments()); return Rules.newRule(Heads.newNormalHead(headAtom), - ListUtils.union(element.getElementLiterals(), new ArrayList<>(aggregateInfo.getDependencies()))); + SetUtils.union(new LinkedHashSet<>(element.getElementLiterals()), new LinkedHashSet<>(aggregateInfo.getDependencies()))); } /** diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AggregateEncoders.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AggregateEncoders.java index 55d6ca6af..686fed1f6 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AggregateEncoders.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/AggregateEncoders.java @@ -9,28 +9,28 @@ private AggregateEncoders() { throw new AssertionError("Cannot instantiate utility class!"); } - public static CountEncoder newCountEqualsEncoder(ProgramParser parser) { - return CountEncoder.buildCountEqualsEncoder(parser); + public static CountEncoder newCountEqualsEncoder() { + return CountEncoder.buildCountEqualsEncoder(); } - public static CountEncoder newCountLessOrEqualEncoder(ProgramParser parser, boolean useSortingGridEncoding) { - return CountEncoder.buildCountLessOrEqualEncoder(parser, useSortingGridEncoding); + public static CountEncoder newCountLessOrEqualEncoder(boolean useSortingGridEncoding) { + return CountEncoder.buildCountLessOrEqualEncoder(useSortingGridEncoding); } - public static SumEncoder newSumEqualsEncoder(ProgramParser parser, boolean supportNegativeSumElements) { - return SumEncoder.buildSumEqualsEncoder(parser, supportNegativeSumElements); + public static SumEncoder newSumEqualsEncoder(boolean supportNegativeSumElements) { + return SumEncoder.buildSumEqualsEncoder(supportNegativeSumElements); } - public static SumEncoder newSumLessOrEqualEncoder(ProgramParser parser, boolean supportNegativeSumElements) { - return SumEncoder.buildSumLessOrEqualEncoder(parser, supportNegativeSumElements); + public static SumEncoder newSumLessOrEqualEncoder(boolean supportNegativeSumElements) { + return SumEncoder.buildSumLessOrEqualEncoder(supportNegativeSumElements); } - public static MinMaxEncoder newMinEncoder(ProgramParser parser) { - return new MinMaxEncoder(parser, AggregateFunctionSymbol.MIN); + public static MinMaxEncoder newMinEncoder() { + return new MinMaxEncoder(AggregateFunctionSymbol.MIN); } - public static MinMaxEncoder newMaxEncoder(ProgramParser parser) { - return new MinMaxEncoder(parser, AggregateFunctionSymbol.MAX); + public static MinMaxEncoder newMaxEncoder() { + return new MinMaxEncoder(AggregateFunctionSymbol.MAX); } } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/CountEncoder.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/CountEncoder.java index be64efabd..44a10a5a3 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/CountEncoder.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/CountEncoder.java @@ -18,16 +18,16 @@ public final class CountEncoder extends StringtemplateBasedAggregateEncoder { private static final ST CNT_EQ_TEMPLATE = AGGREGATE_ENCODINGS.getInstanceOf("cnt_eq"); private static final ST CNT_LE_COUNTING_GRID_TEMPLATE = AGGREGATE_ENCODINGS.getInstanceOf("cnt_le_counting_grid"); - private CountEncoder(ProgramParser parser, ComparisonOperator acceptedOperator, ST encodingTemplate) { - super(parser, AggregateFunctionSymbol.COUNT, acceptedOperator, encodingTemplate); + private CountEncoder(ComparisonOperator acceptedOperator, ST encodingTemplate) { + super(AggregateFunctionSymbol.COUNT, acceptedOperator, encodingTemplate); } - static CountEncoder buildCountLessOrEqualEncoder(ProgramParser parser, boolean useSortingGrid) { - return new CountEncoder(parser, ComparisonOperators.LE, useSortingGrid ? CNT_LE_SORTING_GRID_TEMPLATE : CNT_LE_COUNTING_GRID_TEMPLATE); + static CountEncoder buildCountLessOrEqualEncoder(boolean useSortingGrid) { + return new CountEncoder(ComparisonOperators.LE, useSortingGrid ? CNT_LE_SORTING_GRID_TEMPLATE : CNT_LE_COUNTING_GRID_TEMPLATE); } - static CountEncoder buildCountEqualsEncoder(ProgramParser parser) { - return new CountEncoder(parser, ComparisonOperators.EQ, CNT_EQ_TEMPLATE); + static CountEncoder buildCountEqualsEncoder() { + return new CountEncoder(ComparisonOperators.EQ, CNT_EQ_TEMPLATE); } } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/MinMaxEncoder.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/MinMaxEncoder.java index 179014554..242fc7719 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/MinMaxEncoder.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/MinMaxEncoder.java @@ -1,13 +1,15 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import org.apache.commons.collections4.SetUtils; import org.stringtemplate.v4.ST; import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom; @@ -24,7 +26,7 @@ import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.comparisons.ComparisonOperators; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.literals.Literals; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; @@ -72,7 +74,7 @@ public MinMaxEncoder(AggregateFunctionSymbol func) { } @Override - protected ASPCore2Program encodeAggregateResult(AggregateInfo aggregateToEncode) { + protected InputProgram encodeAggregateResult(AggregateInfo aggregateToEncode) { ST encodingTemplate = null; if (this.getAggregateFunctionToEncode() == AggregateFunctionSymbol.MAX) { encodingTemplate = new ST(MAX_LITERAL_ENCODING); @@ -112,7 +114,7 @@ protected ASPCore2Program encodeAggregateResult(AggregateInfo aggregateToEncode) */ NormalHead resultRuleHead = Heads.newNormalHead( Atoms.newBasicAtom(Predicates.getPredicate(resultName, 2), aggregateToEncode.getAggregateArguments(), atom.getLowerBoundTerm())); - List resultRuleBody = new ArrayList<>(); + Set resultRuleBody = new LinkedHashSet<>(); VariableTerm aggregateValue = Terms.newVariable("_AGG_VAL"); ComparisonLiteral aggregateValueComparison = Literals.fromAtom(Atoms.newComparisonAtom(atom.getLowerBoundTerm(), aggregateValue, cmpOp), true); Literal aggregateResult = Atoms.newBasicAtom(Predicates.getPredicate( @@ -121,7 +123,7 @@ protected ASPCore2Program encodeAggregateResult(AggregateInfo aggregateToEncode) resultRuleBody.add(aggregateResult); resultRuleBody.add(aggregateValueComparison); resultRuleBody.addAll(aggregateToEncode.getDependencies()); - ASPCore2ProgramBuilder bld = Programs.builder(parser.parse(encodingTemplate.render())); + InputProgramBuilder bld = Programs.builder(parser.parse(encodingTemplate.render())); Rule resultRule = Rules.newRule(resultRuleHead, resultRuleBody); bld.addRule(resultRule); return bld.build(); diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/StringtemplateBasedAggregateEncoder.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/StringtemplateBasedAggregateEncoder.java index 8869c66fe..a7eeb9fab 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/StringtemplateBasedAggregateEncoder.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/StringtemplateBasedAggregateEncoder.java @@ -1,13 +1,7 @@ package at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders; -import java.util.ArrayList; -import java.util.Collections; - -import org.apache.commons.collections4.ListUtils; -import org.stringtemplate.v4.ST; - import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateFunctionSymbol; import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; @@ -23,6 +17,12 @@ import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; import at.ac.tuwien.kr.alpha.core.programs.transformation.EnumerationRewriting; import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.AggregateRewritingContext.AggregateInfo; +import org.apache.commons.collections4.ListUtils; +import org.stringtemplate.v4.ST; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; /** * Abstract base class for aggregate encoders making use of stringtemplates in their rewriting workflow. @@ -53,7 +53,7 @@ protected StringtemplateBasedAggregateEncoder(AggregateFunctionSymbol aggregateF } @Override - protected ASPCore2Program encodeAggregateResult(AggregateInfo aggregateToEncode) { + protected InputProgram encodeAggregateResult(AggregateInfo aggregateToEncode) { String aggregateId = aggregateToEncode.getId(); /* @@ -81,10 +81,10 @@ protected ASPCore2Program encodeAggregateResult(AggregateInfo aggregateToEncode) String coreEncodingAsp = coreEncodingTemplate.render(); // Create the basic program - ASPCore2Program coreEncoding = new EnumerationRewriting().apply(parser.parse(coreEncodingAsp)); + InputProgram coreEncoding = new EnumerationRewriting().apply(parser.parse(coreEncodingAsp)); // Add the programatically created bound rule and return - return Programs.newASPCore2Program(ListUtils.union(coreEncoding.getRules(), Collections.singletonList(boundRule)), coreEncoding.getFacts(), + return Programs.newInputProgram(ListUtils.union(coreEncoding.getRules(), Collections.singletonList(boundRule)), coreEncoding.getFacts(), Programs.newInlineDirectives()); } @@ -95,13 +95,13 @@ private String getBoundPredicateName(String aggregateId) { private Rule buildZeroBoundRule(AggregateInfo aggregateToEncode) { BasicAtom bound = Atoms.newBasicAtom(Predicates.getPredicate(getBoundPredicateName(aggregateToEncode.getId()), 2), aggregateToEncode.getAggregateArguments(), Terms.newConstant(0)); - return Rules.newRule(Heads.newNormalHead(bound), new ArrayList<>(aggregateToEncode.getDependencies())); + return Rules.newRule(Heads.newNormalHead(bound), new LinkedHashSet<>(aggregateToEncode.getDependencies())); } private Rule buildBoundRule(AggregateInfo aggregateToEncode) { BasicAtom bound = Atoms.newBasicAtom(Predicates.getPredicate(getBoundPredicateName(aggregateToEncode.getId()), 2), aggregateToEncode.getAggregateArguments(), aggregateToEncode.getLiteral().getAtom().getLowerBoundTerm()); - return Rules.newRule(Heads.newNormalHead(bound), new ArrayList<>(aggregateToEncode.getDependencies())); + return Rules.newRule(Heads.newNormalHead(bound), new LinkedHashSet<>(aggregateToEncode.getDependencies())); } } diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/SumEncoder.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/SumEncoder.java index 1fee5aab3..0dc4a0358 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/SumEncoder.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/programs/transformation/aggregates/encoders/SumEncoder.java @@ -33,16 +33,16 @@ public final class SumEncoder extends StringtemplateBasedAggregateEncoder { private static final ST NON_NEG_ELEMENTS_SUM_LE_TEMPLATE = AGGREGATE_ENCODINGS.getInstanceOf("sum_le_no_negative_elements"); private static final ST NON_NEG_ELEMENTS_SUM_EQ_TEMPLATE = AGGREGATE_ENCODINGS.getInstanceOf("sum_eq_no_negative_elements"); - private SumEncoder(ProgramParser parser, ComparisonOperator acceptedOperator, ST encodingTemplate) { - super(parser, AggregateFunctionSymbol.SUM, acceptedOperator, encodingTemplate); + private SumEncoder(ComparisonOperator acceptedOperator, ST encodingTemplate) { + super(AggregateFunctionSymbol.SUM, acceptedOperator, encodingTemplate); } - static SumEncoder buildSumLessOrEqualEncoder(ProgramParser parser, boolean supportNegativeIntegers) { - return new SumEncoder(parser, ComparisonOperators.LE, supportNegativeIntegers ? SUM_LE_TEMPLATE : NON_NEG_ELEMENTS_SUM_LE_TEMPLATE); + static SumEncoder buildSumLessOrEqualEncoder(boolean supportNegativeIntegers) { + return new SumEncoder(ComparisonOperators.LE, supportNegativeIntegers ? SUM_LE_TEMPLATE : NON_NEG_ELEMENTS_SUM_LE_TEMPLATE); } - static SumEncoder buildSumEqualsEncoder(ProgramParser parser, boolean supportNegativeIntegers) { - return new SumEncoder(parser, ComparisonOperators.EQ, supportNegativeIntegers ? SUM_EQ_TEMPLATE : NON_NEG_ELEMENTS_SUM_EQ_TEMPLATE); + static SumEncoder buildSumEqualsEncoder(boolean supportNegativeIntegers) { + return new SumEncoder(ComparisonOperators.EQ, supportNegativeIntegers ? SUM_EQ_TEMPLATE : NON_NEG_ELEMENTS_SUM_EQ_TEMPLATE); } /** diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/rules/CompiledRules.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/rules/CompiledRules.java index baf96bfb5..a3f81eefa 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/rules/CompiledRules.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/rules/CompiledRules.java @@ -4,7 +4,9 @@ import java.util.Set; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; -import at.ac.tuwien.kr.alpha.api.rules.heads.NormalHead; +import at.ac.tuwien.kr.alpha.api.programs.rules.heads.NormalHead; +import at.ac.tuwien.kr.alpha.core.programs.rules.CompiledRule; +import at.ac.tuwien.kr.alpha.core.programs.rules.InternalRule; public final class CompiledRules { @@ -13,7 +15,7 @@ private CompiledRules() { } public static CompiledRule newCompiledRule(NormalHead head, Set body) { - return new CompiledRuleImpl(head, body); + return new InternalRule(head, body); } public static CompiledRule newCompiledRule(NormalHead head, Literal... body) { diff --git a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/TrailAssignment.java b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/TrailAssignment.java index ed7e4b1fb..47e037d87 100644 --- a/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/TrailAssignment.java +++ b/alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/TrailAssignment.java @@ -45,7 +45,6 @@ import static at.ac.tuwien.kr.alpha.core.programs.atoms.Literals.atomOf; import static at.ac.tuwien.kr.alpha.core.programs.atoms.Literals.atomToLiteral; import static at.ac.tuwien.kr.alpha.core.programs.atoms.Literals.isPositive; -import static at.ac.tuwien.kr.alpha.core.solver.Atoms.isAtom; import static at.ac.tuwien.kr.alpha.core.solver.ThriceTruth.FALSE; import static at.ac.tuwien.kr.alpha.core.solver.ThriceTruth.MBT; import static at.ac.tuwien.kr.alpha.core.solver.ThriceTruth.TRUE; @@ -338,7 +337,7 @@ private boolean assignmentsConsistent(ThriceTruth oldTruth, ThriceTruth value) { } private ConflictCause assignWithTrail(int atom, ThriceTruth value, Antecedent impliedBy) { - if (!isAtom(atom)) { + if (!AtomStore.isAtom(atom)) { throw new IllegalArgumentException("not an atom"); } if (value == null) { diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/common/RuleTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/common/RuleTest.java index 349249c17..2f2b41740 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/common/RuleTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/common/RuleTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.rules.Rule; import at.ac.tuwien.kr.alpha.api.programs.rules.heads.Head; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; @@ -35,11 +35,11 @@ public void renameVariables() { @Test public void testRulesEqual() { - ASPCore2Program p1 = parser.parse("p(X, Y) :- bla(X), blub(Y), foo(X, Y), not bar(X)."); + InputProgram p1 = parser.parse("p(X, Y) :- bla(X), blub(Y), foo(X, Y), not bar(X)."); Rule r1 = p1.getRules().get(0); - ASPCore2Program p2 = parser.parse("p(X, Y) :- bla(X), blub(Y), foo(X, Y), not bar(X)."); + InputProgram p2 = parser.parse("p(X, Y) :- bla(X), blub(Y), foo(X, Y), not bar(X)."); Rule r2 = p2.getRules().get(0); - ASPCore2Program p3 = parser.parse("p(X, Y) :- bla(X), blub(X), foo(X, X), not bar(X)."); + InputProgram p3 = parser.parse("p(X, Y) :- bla(X), blub(X), foo(X, X), not bar(X)."); Rule r3 = p3.getRules().get(0); assertTrue(r1.equals(r2)); assertTrue(r2.equals(r1)); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NaiveGrounderTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NaiveGrounderTest.java index 1f1ca1d9b..cdee89727 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NaiveGrounderTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NaiveGrounderTest.java @@ -43,7 +43,7 @@ import at.ac.tuwien.kr.alpha.api.config.GrounderHeuristicsConfiguration; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; import at.ac.tuwien.kr.alpha.api.grounder.Substitution; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.literals.Literal; @@ -100,7 +100,7 @@ public void resetRuleIdGenerator() { */ @Test public void groundRuleAlreadyGround() { - ASPCore2Program program = PROGRAM_PARSER.parse("a :- not b. " + InputProgram program = PROGRAM_PARSER.parse("a :- not b. " + "b :- not a. " + "c :- b."); NormalProgram normal = NORMALIZE_TRANSFORM.apply(program); @@ -121,7 +121,7 @@ public void groundRuleAlreadyGround() { */ @Test public void groundRuleWithLongerBodyAlreadyGround() { - ASPCore2Program program = PROGRAM_PARSER.parse("a :- not b. " + InputProgram program = PROGRAM_PARSER.parse("a :- not b. " + "b :- not a. " + "c :- b. " + "d :- b, c. "); @@ -147,7 +147,7 @@ public void groundRuleWithLongerBodyAlreadyGround() { */ @Test public void groundConstraintAlreadyGround() { - ASPCore2Program program = PROGRAM_PARSER.parse("a :- not b. " + InputProgram program = PROGRAM_PARSER.parse("a :- not b. " + "b :- not a. " + ":- b."); NormalProgram normal = NORMALIZE_TRANSFORM.apply(program); @@ -237,7 +237,7 @@ private void testDeadEnd(String predicateNameOfStartingLiteral, RuleGroundingOrd @Test public void testGroundingOfRuleSwitchedOffByFalsePositiveBody() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X). " + "b(X) :- something(X). "); testIfGrounderGroundsRule(program, 0, litAX, 1, ThriceTruth.FALSE, false); @@ -245,7 +245,7 @@ public void testGroundingOfRuleSwitchedOffByFalsePositiveBody() { @Test public void testGroundingOfRuleNotSwitchedOffByTruePositiveBody() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X). " + "b(X) :- something(X). "); testIfGrounderGroundsRule(program, 0, litAX, 1, ThriceTruth.TRUE, true); @@ -254,7 +254,7 @@ public void testGroundingOfRuleNotSwitchedOffByTruePositiveBody() { @Test @Disabled("Currently, rule grounding is not switched off by a true negative body atom") public void testGroundingOfRuleSwitchedOffByTrueNegativeBody() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), not b(X). " + "b(X) :- something(X). "); testIfGrounderGroundsRule(program, 0, litAX, 1, ThriceTruth.TRUE, false); @@ -262,7 +262,7 @@ public void testGroundingOfRuleSwitchedOffByTrueNegativeBody() { @Test public void testGroundingOfRuleNotSwitchedOffByFalseNegativeBody() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), not b(X). " + "b(X) :- something(X). "); @@ -276,7 +276,7 @@ public void testGroundingOfRuleNotSwitchedOffByFalseNegativeBody() { * {@code bTruth}. * It is asserted that ground instantiations are produced if and only if {@code expectNoGoods} is true. */ - private void testIfGrounderGroundsRule(ASPCore2Program program, int ruleID, Literal startingLiteral, int startingInstance, ThriceTruth bTruth, + private void testIfGrounderGroundsRule(InputProgram program, int ruleID, Literal startingLiteral, int startingInstance, ThriceTruth bTruth, boolean expectNoGoods) { CompiledProgram internalPrg = InternalProgram.fromNormalProgram(NORMALIZE_TRANSFORM.apply(program)); AtomStore atomStore = new AtomStoreImpl(); @@ -299,7 +299,7 @@ private void testIfGrounderGroundsRule(ASPCore2Program program, int ruleID, Lite @Test public void testPermissiveGrounderHeuristicTolerance_0_reject() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X). " + "b(X) :- something(X)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 0, false, Arrays.asList(1)); @@ -307,7 +307,7 @@ public void testPermissiveGrounderHeuristicTolerance_0_reject() { @Test public void testPermissiveGrounderHeuristicTolerance_1_accept() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X). " + "b(X) :- something(X)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 1, true, Arrays.asList(1)); @@ -315,7 +315,7 @@ public void testPermissiveGrounderHeuristicTolerance_1_accept() { @Test public void testPermissiveGrounderHeuristicTolerance_1_reject() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X), b(X+1). " + "b(X) :- something(X)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 1, false, Arrays.asList(2)); @@ -323,7 +323,7 @@ public void testPermissiveGrounderHeuristicTolerance_1_reject() { @Test public void testPermissiveGrounderHeuristicTolerance_2_accept() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X), b(X+1). " + "b(X) :- something(X)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 2, true, Arrays.asList(2)); @@ -331,7 +331,7 @@ public void testPermissiveGrounderHeuristicTolerance_2_accept() { @Test public void testPermissiveGrounderHeuristicTolerance_1_accept_two_substitutions() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X,Y). " + "b(X,Y) :- something(X,Y)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 1, new ThriceTruth[] {ThriceTruth.TRUE, ThriceTruth.TRUE }, 2, true, @@ -340,7 +340,7 @@ public void testPermissiveGrounderHeuristicTolerance_1_accept_two_substitutions( @Test public void testPermissiveGrounderHeuristicTolerance_1_accept_accept_two_substitutions_with_different_remaining_tolerances() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(1), b(X,Y). " + "b(X,Y) :- something(X,Y)."); testPermissiveGrounderHeuristicTolerance(program, 0, litA1, 1, 1, new ThriceTruth[] {null, null }, 2, true, Arrays.asList(1, 1)); @@ -348,7 +348,7 @@ public void testPermissiveGrounderHeuristicTolerance_1_accept_accept_two_substit @Test public void testPermissiveGrounderHeuristicTolerance_2_reject() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). " + "c(X) :- a(X), b(X), b(X+1), b(X+2). " + "b(X) :- something(X)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 2, false, Arrays.asList(3)); @@ -356,13 +356,13 @@ public void testPermissiveGrounderHeuristicTolerance_2_reject() { @Test public void testPermissiveGrounderHeuristicTolerance_2_accept_multiple_facts_of_same_variable() { - ASPCore2Program program = PROGRAM_PARSER.parse("a(1). b(1). " + InputProgram program = PROGRAM_PARSER.parse("a(1). b(1). " + "c(X) :- a(X), b(X), b(X+1), b(X+2). " + "b(X) :- something(X)."); testPermissiveGrounderHeuristicTolerance(program, 0, litAX, 1, 2, true, Arrays.asList(2)); } - private void testPermissiveGrounderHeuristicTolerance(ASPCore2Program program, int ruleID, Literal startingLiteral, int startingInstance, int tolerance, + private void testPermissiveGrounderHeuristicTolerance(InputProgram program, int ruleID, Literal startingLiteral, int startingInstance, int tolerance, boolean expectNoGoods, List expectedNumbersOfUnassignedPositiveBodyAtoms) { testPermissiveGrounderHeuristicTolerance(program, ruleID, startingLiteral, startingInstance, tolerance, new ThriceTruth[] {}, 1, expectNoGoods, expectedNumbersOfUnassignedPositiveBodyAtoms); @@ -386,7 +386,7 @@ private void testPermissiveGrounderHeuristicTolerance(ASPCore2Program program, i * If ground instantiations are produced, it is also asserted that the numbers of unassigned positive body atoms * determined by {@code getGroundInstantiations} match those given in {@code expectedNumbersOfUnassignedPositiveBodyAtoms}. */ - private void testPermissiveGrounderHeuristicTolerance(ASPCore2Program program, int ruleID, Literal startingLiteral, int startingInstance, int tolerance, + private void testPermissiveGrounderHeuristicTolerance(InputProgram program, int ruleID, Literal startingLiteral, int startingInstance, int tolerance, ThriceTruth[] truthsOfB, int arityOfB, boolean expectNoGoods, List expectedNumbersOfUnassignedPositiveBodyAtoms) { CompiledProgram internalPrg = InternalProgram.fromNormalProgram(NORMALIZE_TRANSFORM.apply(program)); AtomStore atomStore = new AtomStoreImpl(); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NoGoodGeneratorTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NoGoodGeneratorTest.java index 501978758..ef42a9eb7 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NoGoodGeneratorTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/NoGoodGeneratorTest.java @@ -33,7 +33,7 @@ import at.ac.tuwien.kr.alpha.api.config.SystemConfig; import at.ac.tuwien.kr.alpha.api.grounder.Substitution; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.terms.ConstantTerm; @@ -71,7 +71,7 @@ public class NoGoodGeneratorTest { */ @Test public void collectNeg_ContainsOnlyPositiveLiterals() { - ASPCore2Program input = PARSER.parse("p(a,b). " + InputProgram input = PARSER.parse("p(a,b). " + "q(a,b) :- not nq(a,b). " + "nq(a,b) :- not q(a,b)."); NormalProgram normal = NORMALIZE_TRANSFORM.apply(input); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/UnifierTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/UnifierTest.java index efae731d9..a59a958d3 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/UnifierTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/grounder/UnifierTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; @@ -78,7 +78,7 @@ public void mergeUnifierIntoLeft() { private BasicAtom parseAtom(String atom) { ProgramParser programParser = new ProgramParserImpl(); - ASPCore2Program program = programParser.parse(atom + "."); + InputProgram program = programParser.parse(atom + "."); return (BasicAtom) program.getFacts().get(0); } } diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/AspCore2ParserTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/AspCore2ParserTest.java index fd40c3db6..7b96f4f92 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/AspCore2ParserTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/AspCore2ParserTest.java @@ -1,11 +1,11 @@ package at.ac.tuwien.kr.alpha.core.parser; -import at.ac.tuwien.kr.alpha.core.parser.aspcore2.ASPCore2ProgramParser; +import at.ac.tuwien.kr.alpha.core.parser.aspcore2.InputProgramParser; public class AspCore2ParserTest extends ParserTest { protected AspCore2ParserTest() { - super(new ASPCore2ProgramParser()); + super(new InputProgramParser()); } } diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/ParserTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/ParserTest.java index 3c4da3aaa..3557a6fa0 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/ParserTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/parser/ParserTest.java @@ -46,7 +46,7 @@ import org.antlr.v4.runtime.CharStreams; import org.junit.jupiter.api.Test; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.InlineDirectives; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; @@ -91,7 +91,7 @@ public class ParserTest { @Test public void parseFact() { - ASPCore2Program parsedProgram = parser.parse("p(a,b)."); + InputProgram parsedProgram = parser.parse("p(a,b)."); assertEquals(1, parsedProgram.getFacts().size(), "Program contains one fact."); assertEquals("p", parsedProgram.getFacts().get(0).getPredicate().getName(), "Predicate name of fact is p."); @@ -102,7 +102,7 @@ public void parseFact() { @Test public void parseFactWithFunctionTerms() { - ASPCore2Program parsedProgram = parser.parse("p(f(a),g(h(Y)))."); + InputProgram parsedProgram = parser.parse("p(f(a),g(h(Y)))."); assertEquals(1, parsedProgram.getFacts().size(), "Program contains one fact."); assertEquals("p", parsedProgram.getFacts().get(0).getPredicate().getName(), "Predicate name of fact is p."); @@ -113,7 +113,7 @@ public void parseFactWithFunctionTerms() { @Test public void parseSmallProgram() { - ASPCore2Program parsedProgram = parser.parse( + InputProgram parsedProgram = parser.parse( "a :- b, not d." + System.lineSeparator() + "c(X) :- p(X,a,_), q(Xaa,xaa)." + System.lineSeparator() + ":- f(Y)."); @@ -130,7 +130,7 @@ public void parseBadSyntax() { @Test public void parseBuiltinAtom() { - ASPCore2Program parsedProgram = parser.parse("a :- p(X), X != Y, q(Y)."); + InputProgram parsedProgram = parser.parse("a :- p(X), X != Y, q(Y)."); assertEquals(1, parsedProgram.getRules().size()); assertEquals(3, parsedProgram.getRules().get(0).getBody().size()); } @@ -145,7 +145,7 @@ public void parseProgramWithDisjunctionInHead() { @Test public void parseInterval() { - ASPCore2Program parsedProgram = parser.parse("fact(2..5). p(X) :- q(a, 3 .. X)."); + InputProgram parsedProgram = parser.parse("fact(2..5). p(X) :- q(a, 3 .. X)."); IntervalTerm factInterval = (IntervalTerm) parsedProgram.getFacts().get(0).getTerms().get(0); assertTrue(factInterval.equals(Terms.newIntervalTerm(Terms.newConstant(2), Terms.newConstant(5)))); IntervalTerm bodyInterval = (IntervalTerm) parsedProgram.getRules().get(0).getBody().stream().findFirst().get().getTerms().get(1); @@ -154,7 +154,7 @@ public void parseInterval() { @Test public void parseChoiceRule() { - ASPCore2Program parsedProgram = parser.parse("dom(1). dom(2). { a ; b } :- dom(X)."); + InputProgram parsedProgram = parser.parse("dom(1). dom(2). { a ; b } :- dom(X)."); ChoiceHead choiceHead = (ChoiceHead) parsedProgram.getRules().get(0).getHead(); assertEquals(2, choiceHead.getChoiceElements().size()); assertTrue(choiceHead.getChoiceElements().get(0).getChoiceAtom().toString().equals("a")); @@ -165,7 +165,7 @@ public void parseChoiceRule() { @Test public void parseChoiceRuleBounded() { - ASPCore2Program parsedProgram = parser.parse("dom(1). dom(2). 1 < { a: p(v,w), not r; b } <= 13 :- dom(X). foo."); + InputProgram parsedProgram = parser.parse("dom(1). dom(2). 1 < { a: p(v,w), not r; b } <= 13 :- dom(X). foo."); ChoiceHead choiceHead = (ChoiceHead) parsedProgram.getRules().get(0).getHead(); assertEquals(2, choiceHead.getChoiceElements().size()); assertTrue(choiceHead.getChoiceElements().get(0).getChoiceAtom().toString().equals("a")); @@ -215,7 +215,7 @@ public void testMissingDotNotIgnored() { @Test public void parseEnumerationDirective() { - ASPCore2Program parsedProgram = parser.parse("p(a,1)." + + InputProgram parsedProgram = parser.parse("p(a,1)." + "# enumeration_predicate_is mune." + "r(X) :- p(X), mune(X)." + "p(b,2)."); @@ -225,7 +225,7 @@ public void parseEnumerationDirective() { @Test public void cardinalityAggregate() { - ASPCore2Program parsedProgram = parser.parse("num(K) :- K <= #count {X,Y,Z : p(X,Y,Z) }, dom(K)."); + InputProgram parsedProgram = parser.parse("num(K) :- K <= #count {X,Y,Z : p(X,Y,Z) }, dom(K)."); Optional optionalBodyElement = parsedProgram.getRules().get(0).getBody().stream().filter((lit) -> lit instanceof AggregateLiteral).findFirst(); assertTrue(optionalBodyElement.isPresent()); Literal bodyElement = optionalBodyElement.get(); @@ -244,7 +244,7 @@ public void cardinalityAggregate() { @Test public void stringWithEscapedQuotes() throws IOException { CharStream stream = CharStreams.fromStream(ParserTest.class.getResourceAsStream("/escaped_quotes.asp")); - ASPCore2Program prog = parser.parse(stream); + InputProgram prog = parser.parse(stream); assertEquals(1, prog.getFacts().size()); Atom stringAtom = prog.getFacts().get(0); String stringWithQuotes = stringAtom.getTerms().get(0).toString(); @@ -253,7 +253,7 @@ public void stringWithEscapedQuotes() throws IOException { @Test public void unitTestExpectUnsat() { - ASPCore2Program prog = parser.parse(UNIT_TEST_EXPECT_UNSAT); + InputProgram prog = parser.parse(UNIT_TEST_EXPECT_UNSAT); assertEquals(1, prog.getTestCases().size()); TestCase tc = prog.getTestCases().get(0); assertEquals("expected_unsat", tc.getName()); @@ -263,7 +263,7 @@ public void unitTestExpectUnsat() { @Test public void unitTestBasicTest() { - ASPCore2Program prog = parser.parse(UNIT_TEST_BASIC_TEST); + InputProgram prog = parser.parse(UNIT_TEST_BASIC_TEST); assertEquals(1, prog.getTestCases().size()); TestCase tc = prog.getTestCases().get(0); assertEquals("ensure_a", tc.getName()); @@ -274,7 +274,7 @@ public void unitTestBasicTest() { @Test public void unitTestMultipleAsserts() { - ASPCore2Program prog = parser.parse(UNIT_TEST_MORE_ASSERTIONS); + InputProgram prog = parser.parse(UNIT_TEST_MORE_ASSERTIONS); assertEquals(1, prog.getTestCases().size()); TestCase tc = prog.getTestCases().get(0); assertEquals("ensure_a", tc.getName()); @@ -286,7 +286,7 @@ public void unitTestMultipleAsserts() { @Test public void unitTestMoreTCs() { - ASPCore2Program prog = parser.parse(UNIT_TEST_MORE_TCS); + InputProgram prog = parser.parse(UNIT_TEST_MORE_TCS); assertEquals(2, prog.getTestCases().size()); TestCase tc1 = prog.getTestCases().get(0); assertEquals("ensure_a", tc1.getName()); @@ -296,7 +296,7 @@ public void unitTestMoreTCs() { @Test public void unitTestKeywordsAsIds() { - ASPCore2Program prog = parser.parse(UNIT_TEST_KEYWORDS_AS_IDS); + InputProgram prog = parser.parse(UNIT_TEST_KEYWORDS_AS_IDS); assertEquals(1, prog.getTestCases().size()); TestCase tc = prog.getTestCases().get(0); assertEquals("test", tc.getName()); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/atoms/AtomsTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/atoms/AtomsTest.java index 1c0c26b57..d202e579c 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/atoms/AtomsTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/atoms/AtomsTest.java @@ -15,7 +15,7 @@ import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; import at.ac.tuwien.kr.alpha.api.externals.Predicate; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; @@ -58,35 +58,35 @@ public static final Set>> extWithOutput(int in) { @Test public void testIsBasicAtomGround() { - ASPCore2Program p = parser.parse("bla(blubb, foo(bar))."); + InputProgram p = parser.parse("bla(blubb, foo(bar))."); Atom a = p.getFacts().get(0); assertBasicAtomGround(a, true); - ASPCore2Program p1 = parser.parse("foo(1, 2, 3, \"bar\")."); + InputProgram p1 = parser.parse("foo(1, 2, 3, \"bar\")."); Atom a1 = p1.getFacts().get(0); assertBasicAtomGround(a1, true); - ASPCore2Program p2 = parser.parse("foo(BAR)."); + InputProgram p2 = parser.parse("foo(BAR)."); Atom a2 = p2.getFacts().get(0); assertBasicAtomGround(a2, false); - ASPCore2Program p3 = parser.parse("foo(b, a, r(\"bla\", BLUBB))."); + InputProgram p3 = parser.parse("foo(b, a, r(\"bla\", BLUBB))."); Atom a3 = p3.getFacts().get(0); assertBasicAtomGround(a3, false); } @Test public void testAreBasicAtomsEqual() { - ASPCore2Program p1 = parser.parse("bla(blubb, foo(bar)). bla(blubb, foo(bar))."); + InputProgram p1 = parser.parse("bla(blubb, foo(bar)). bla(blubb, foo(bar))."); Atom a1 = p1.getFacts().get(0); Atom a2 = p1.getFacts().get(1); assertEquals(a1, a2); - ASPCore2Program p2 = parser.parse("foo(1, 2, 3, \"bar\"). foo(1, 2, 3, \"bar\")."); + InputProgram p2 = parser.parse("foo(1, 2, 3, \"bar\"). foo(1, 2, 3, \"bar\")."); Atom a3 = p2.getFacts().get(0); Atom a4 = p2.getFacts().get(1); assertEquals(a3, a4); - ASPCore2Program p3 = parser.parse("foo(BAR). foo(BAR)."); + InputProgram p3 = parser.parse("foo(BAR). foo(BAR)."); Atom a5 = p3.getFacts().get(0); Atom a6 = p3.getFacts().get(1); assertEquals(a5, a6); - ASPCore2Program p4 = parser.parse("foo(b, a, r(\"bla\", BLUBB)). foo(b, a, r(\"bla\", BLUBB))."); + InputProgram p4 = parser.parse("foo(b, a, r(\"bla\", BLUBB)). foo(b, a, r(\"bla\", BLUBB))."); Atom a7 = p4.getFacts().get(0); Atom a8 = p4.getFacts().get(1); assertEquals(a7, a8); @@ -101,13 +101,13 @@ public void testAreBasicAtomsEqual() { @Test public void testIsExternalAtomGround() { - ASPCore2Program p1 = parser.parse("a :- &isFoo[1].", externals); + InputProgram 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); + InputProgram 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); + InputProgram p3 = parser.parse("a :- &isFoo[BLA].", externals); Atom ext3 = p3.getRules().get(0).getBody().stream().findFirst().get().getAtom(); assertExternalAtomGround(ext3, false); } @@ -115,9 +115,9 @@ public void testIsExternalAtomGround() { @Test @SuppressWarnings("unlikely-arg-type") public void testAreExternalAtomsEqual() { - ASPCore2Program p1 = parser.parse("a :- &isFoo[1].", externals); + InputProgram p1 = parser.parse("a :- &isFoo[1].", externals); Atom ext1 = p1.getRules().get(0).getBody().stream().findFirst().get().getAtom(); - ASPCore2Program p2 = parser.parse("a :- &isFoo[1].", externals); + InputProgram p2 = parser.parse("a :- &isFoo[1].", externals); Atom ext2 = p2.getRules().get(0).getBody().stream().findFirst().get().getAtom(); assertEquals(ext1, ext2); assertEquals(ext2, ext1); @@ -129,7 +129,7 @@ public void testAreExternalAtomsEqual() { @Test public void testExternalHasOutput() { - ASPCore2Program p = parser.parse("a:- &extWithOutput[1](OUT).", externals); + InputProgram p = parser.parse("a:- &extWithOutput[1](OUT).", externals); Atom ext = p.getRules().get(0).getBody().stream().findFirst().get().getAtom(); assertExternalAtomGround(ext, false); assertTrue(((ExternalAtom) ext).hasOutput()); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformationTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformationTest.java index d7ff68a37..79ae8be23 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformationTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/ProgramTransformationTest.java @@ -12,7 +12,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Program; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.commons.programs.Programs; @@ -44,11 +44,11 @@ private static String readTestResource(String resource) throws IOException { } private , O extends Program> void genericTransformationTest(ProgramTransformation transform, - Function prepareFunc, String resourceSet) { + Function prepareFunc, String resourceSet) { try { String inputCode = ProgramTransformationTest.readTestResource(resourceSet + ".in"); String expectedResult = ProgramTransformationTest.readTestResource(resourceSet + ".out"); - ASPCore2Program inputProg = PARSER.parse(inputCode, Externals.scan(ProgramTransformationTest.class)); + InputProgram inputProg = PARSER.parse(inputCode, Externals.scan(ProgramTransformationTest.class)); I transformInput = prepareFunc.apply(inputProg); String beforeTransformProg = transformInput.toString(); O transformedProg = transform.apply(transformInput); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluationRegressionTest.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluationRegressionTest.java index 8715675b0..383cf8ac0 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluationRegressionTest.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/programs/transformation/StratifiedEvaluationRegressionTest.java @@ -18,7 +18,7 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.commons.Predicates; @@ -105,7 +105,7 @@ public static List params() { public void runTest(String aspString, Consumer programVerifier, Consumer> resultVerifier) { // Parse and pre-evaulate program ProgramParser parser = new ProgramParserImpl(); - ASPCore2Program prog = parser.parse(aspString); + InputProgram prog = parser.parse(aspString); AnalyzedProgram analyzed = AnalyzedProgram .analyzeNormalProgram(new NormalizeProgramTransformation(SystemConfig.DEFAULT_AGGREGATE_REWRITING_CONFIG).apply(prog)); CompiledProgram evaluated = new StratifiedEvaluation().apply(analyzed); diff --git a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/solver/ChoiceManagerTests.java b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/solver/ChoiceManagerTests.java index fe0bd40b0..23eff4511 100644 --- a/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/solver/ChoiceManagerTests.java +++ b/alpha-core/src/test/java/at/ac/tuwien/kr/alpha/core/solver/ChoiceManagerTests.java @@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.core.common.AtomStore; import at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl; import at.ac.tuwien.kr.alpha.core.common.NoGood; @@ -54,7 +54,7 @@ public class ChoiceManagerTests { @BeforeEach public void setUp() { String testProgram = "h :- b1, b2, not b3, not b4."; - ASPCore2Program parsedProgram = new ProgramParserImpl().parse(testProgram); + InputProgram parsedProgram = new ProgramParserImpl().parse(testProgram); CompiledProgram internalProgram = InternalProgram.fromNormalProgram(new NormalizeProgramTransformation(SystemConfig.DEFAULT_AGGREGATE_REWRITING_CONFIG).apply(parsedProgram)); atomStore = new AtomStoreImpl(); grounder = new NaiveGrounder(internalProgram, atomStore, true); diff --git a/alpha-core/src/testFixtures/java/at/ac/tuwien/kr/alpha/test/AlphaAssertions.java b/alpha-core/src/testFixtures/java/at/ac/tuwien/kr/alpha/test/AlphaAssertions.java index 7de3ef84d..8c45bf662 100644 --- a/alpha-core/src/testFixtures/java/at/ac/tuwien/kr/alpha/test/AlphaAssertions.java +++ b/alpha-core/src/testFixtures/java/at/ac/tuwien/kr/alpha/test/AlphaAssertions.java @@ -1,18 +1,19 @@ package at.ac.tuwien.kr.alpha.test; -import static java.util.Collections.emptySet; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import at.ac.tuwien.kr.alpha.api.AnswerSet; +import at.ac.tuwien.kr.alpha.api.impl.AnswerSetsParser; +import at.ac.tuwien.kr.alpha.api.programs.Program; +import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import java.util.StringJoiner; -import at.ac.tuwien.kr.alpha.api.AnswerSet; -import at.ac.tuwien.kr.alpha.api.programs.Program; -import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; +import static java.util.Collections.emptySet; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class AlphaAssertions { diff --git a/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaFactory.java b/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaFactory.java index b3c014c13..53d5eb323 100644 --- a/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaFactory.java +++ b/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaFactory.java @@ -1,5 +1,6 @@ package at.ac.tuwien.kr.alpha.api.impl; +import java.util.Collections; import java.util.function.Supplier; import at.ac.tuwien.kr.alpha.api.Alpha; @@ -9,43 +10,26 @@ import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; +import at.ac.tuwien.kr.alpha.commons.programs.reification.Reifier; +import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; +import at.ac.tuwien.kr.alpha.commons.util.IdGenerator; +import at.ac.tuwien.kr.alpha.commons.util.IntIdGenerator; import at.ac.tuwien.kr.alpha.core.actions.ActionExecutionServiceImpl; import at.ac.tuwien.kr.alpha.core.actions.ActionImplementationProvider; import at.ac.tuwien.kr.alpha.core.actions.DefaultActionImplementationProvider; import at.ac.tuwien.kr.alpha.core.grounder.GrounderFactory; -import at.ac.tuwien.kr.alpha.core.parser.aspcore2.ASPCore2ProgramParser; -import at.ac.tuwien.kr.alpha.core.parser.evolog.EvologProgramParser; -import at.ac.tuwien.kr.alpha.core.programs.transformation.ArithmeticTermTransformer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.ChoiceHeadNormalizer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.EnumerationTransformer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.IntervalTermTransformer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.ProgramNormalizer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.ProgramTransformer; +import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; +import at.ac.tuwien.kr.alpha.core.programs.transformation.NormalizeProgramTransformation; +import at.ac.tuwien.kr.alpha.core.programs.transformation.ProgramTransformation; import at.ac.tuwien.kr.alpha.core.programs.transformation.StratifiedEvaluation; -import at.ac.tuwien.kr.alpha.core.programs.transformation.VariableEqualityTransformer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.AggregateTransformer; -import at.ac.tuwien.kr.alpha.core.programs.transformation.aggregates.encoders.AggregateEncoders; import at.ac.tuwien.kr.alpha.core.solver.SolverConfig; import at.ac.tuwien.kr.alpha.core.solver.SolverFactory; import at.ac.tuwien.kr.alpha.core.solver.heuristics.HeuristicsConfiguration; public class AlphaFactory { - protected ProgramTransformer newProgramNormalizer(ProgramParser parser, - AggregateRewritingConfig aggregateCfg) { - return new ProgramNormalizer( - new VariableEqualityTransformer(), - new ChoiceHeadNormalizer(), - new AggregateTransformer( - AggregateEncoders.newCountEqualsEncoder(parser), - AggregateEncoders.newCountLessOrEqualEncoder(parser, aggregateCfg.isUseSortingGridEncoding()), - AggregateEncoders.newSumEqualsEncoder(parser, aggregateCfg.isSupportNegativeValuesInSums()), - AggregateEncoders.newSumLessOrEqualEncoder(parser, aggregateCfg.isSupportNegativeValuesInSums()), - AggregateEncoders.newMinEncoder(parser), - AggregateEncoders.newMaxEncoder(parser)), - new EnumerationTransformer(), - new IntervalTermTransformer(), - new ArithmeticTermTransformer()); + protected ProgramTransformation newProgramNormalizer(AggregateRewritingConfig aggregateCfg) { + return new NormalizeProgramTransformation(aggregateCfg); } protected Supplier newStratifiedEvaluationFactory(ActionImplementationProvider actionImplementationProvider, @@ -83,15 +67,8 @@ protected ActionImplementationProvider newActionImplementationProvider() { public Alpha newAlpha(SystemConfig cfg) { ActionImplementationProvider actionImplementationProvider = newActionImplementationProvider(); - ProgramParser parser; - if (cfg.isAcceptEvologPrograms()) { - parser = new EvologProgramParser(actionImplementationProvider); // TODO need to give stdin/stdout definitions to parser (pass in implementation - // provider) - } else { - parser = new ASPCore2ProgramParser(); - } - ProgramTransformer programNormalizer = newProgramNormalizer(parser, - cfg.getAggregateRewritingConfig()); + ProgramParser parser = new ProgramParserImpl(actionImplementationProvider, Collections.emptyMap()); + ProgramTransformation programNormalizer = new NormalizeProgramTransformation(cfg.getAggregateRewritingConfig()); // Stratified evaluation factory - since every instance of stratified evaluation is only good for one program, we need a factory. Supplier stratifiedEvaluationFactory = newStratifiedEvaluationFactory(actionImplementationProvider, cfg.isDebugInternalChecks()); @@ -103,7 +80,10 @@ public Alpha newAlpha(SystemConfig cfg) { SolverFactory solverFactory = newSolverFactory(cfg); // Now that all dependencies are taken care of, build new Alpha instance. - return new AlphaImpl(parser, programNormalizer, stratifiedEvaluationFactory, grounderFactory, solverFactory, cfg.isSortAnswerSets()); + return new AlphaImpl(parser, programNormalizer, stratifiedEvaluationFactory, grounderFactory, solverFactory, new Reifier(() -> { + IdGenerator idGen = new IntIdGenerator(0); + return () -> Terms.newConstant(idGen.getNextId()); + }), cfg.isSortAnswerSets()); } // Create Alpha instance with default config. diff --git a/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImpl.java b/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImpl.java index 8534b91b4..78631d11b 100644 --- a/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImpl.java +++ b/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImpl.java @@ -32,10 +32,8 @@ import at.ac.tuwien.kr.alpha.api.DebugSolvingContext; import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; -import at.ac.tuwien.kr.alpha.api.config.GrounderHeuristicsConfiguration; import at.ac.tuwien.kr.alpha.api.config.InputConfig; -import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; @@ -44,21 +42,17 @@ import at.ac.tuwien.kr.alpha.api.programs.atoms.BasicAtom; import at.ac.tuwien.kr.alpha.api.programs.tests.TestResult; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.reification.Reifier; -import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; -import at.ac.tuwien.kr.alpha.commons.util.IdGenerator; -import at.ac.tuwien.kr.alpha.commons.util.IntIdGenerator; import at.ac.tuwien.kr.alpha.commons.util.Util; import at.ac.tuwien.kr.alpha.core.common.AtomStore; import at.ac.tuwien.kr.alpha.core.common.AtomStoreImpl; import at.ac.tuwien.kr.alpha.core.grounder.Grounder; import at.ac.tuwien.kr.alpha.core.grounder.GrounderFactory; -import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; import at.ac.tuwien.kr.alpha.core.programs.AnalyzedProgram; import at.ac.tuwien.kr.alpha.core.programs.CompiledProgram; import at.ac.tuwien.kr.alpha.core.programs.InternalProgram; -import at.ac.tuwien.kr.alpha.core.programs.transformation.NormalizeProgramTransformation; +import at.ac.tuwien.kr.alpha.core.programs.transformation.ProgramTransformation; import at.ac.tuwien.kr.alpha.core.programs.transformation.StratifiedEvaluation; import at.ac.tuwien.kr.alpha.core.solver.SolverFactory; import com.google.common.annotations.VisibleForTesting; @@ -76,6 +70,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -83,29 +78,37 @@ public class AlphaImpl implements Alpha { private static final Logger LOGGER = LoggerFactory.getLogger(AlphaImpl.class); - private final SystemConfig config; // Config is initialized with default values. - private final ProgramParser parser = new ProgramParserImpl(); - - private final TestRunner testRunner; - private final Reifier reifier = new Reifier(() -> { - IdGenerator idGen = new IntIdGenerator(0); - return () -> Terms.newConstant(idGen.getNextId()); - }); + private final ProgramParser parser; + private final ProgramTransformation programNormalization; - public AlphaImpl(SystemConfig cfg) { - this.config = cfg; + private final Supplier stratifiedEvaluationFactory; + private final GrounderFactory grounderFactory; + private final SolverFactory solverFactory; + private final TestRunner testRunner; + private final Reifier reifier; + private final boolean sortAnswerSets; + + AlphaImpl(ProgramParser parser, ProgramTransformation programNormalization, + Supplier stratifiedEvaluationFactory, + GrounderFactory grounderFactory, + SolverFactory solverFactory, + Reifier reifier, + boolean sortAnswerSets) { + this.parser = parser; + this.programNormalization = programNormalization; + this.stratifiedEvaluationFactory = stratifiedEvaluationFactory; + this.grounderFactory = grounderFactory; + this.solverFactory = solverFactory; + this.reifier = reifier; this.testRunner = new TestRunner(this); - } - - public AlphaImpl() { - this(new SystemConfig()); + this.sortAnswerSets = sortAnswerSets; } @Override - public ASPCore2Program readProgram(InputConfig cfg) throws IOException { - ASPCore2ProgramBuilder prgBuilder = Programs.builder(); - ASPCore2Program tmpProg; + public InputProgram readProgram(InputConfig cfg) throws IOException { + InputProgramBuilder prgBuilder = Programs.builder(); + InputProgram tmpProg; if (!cfg.getFiles().isEmpty()) { tmpProg = readProgramFiles(cfg.isLiterate(), cfg.getPredicateMethods(), cfg.getFiles()); prgBuilder.accumulate(tmpProg); @@ -118,14 +121,14 @@ public ASPCore2Program readProgram(InputConfig cfg) throws IOException { } @Override - public ASPCore2Program readProgramFiles(boolean literate, Map externals, List paths) throws IOException { + public InputProgram readProgramFiles(boolean literate, Map externals, List paths) throws IOException { return readProgramFiles(literate, externals, paths.stream().map(Paths::get).collect(Collectors.toList()).toArray(new Path[] {})); } @Override - public ASPCore2Program readProgramFiles(boolean literate, Map externals, Path... paths) throws IOException { - ASPCore2ProgramBuilder prgBuilder = Programs.builder(); - ASPCore2Program tmpProg; + public InputProgram readProgramFiles(boolean literate, Map externals, Path... paths) throws IOException { + InputProgramBuilder prgBuilder = Programs.builder(); + InputProgram tmpProg; for (Path path : paths) { InputStream stream; if (!literate) { @@ -140,28 +143,37 @@ public ASPCore2Program readProgramFiles(boolean literate, Map externals) { + public InputProgram readProgramString(String aspString, Map externals) { return parser.parse(aspString, externals); } @Override - public ASPCore2Program readProgramString(String aspString) { + public InputProgram readProgramString(String aspString) { return readProgramString(aspString, Collections.emptyMap()); } @Override - public NormalProgram normalizeProgram(ASPCore2Program program) { - return new NormalizeProgramTransformation(config.getAggregateRewritingConfig()).apply(program); + public InputProgram readProgramStream(InputStream is) throws IOException { + return parser.parse(is); + } + + @Override + public InputProgram readProgramStream(InputStream is, Map externals) throws IOException { + return parser.parse(is, externals); + } + + @Override + public NormalProgram normalizeProgram(InputProgram program) { + return programNormalization.apply(program); } @VisibleForTesting InternalProgram performProgramPreprocessing(NormalProgram program) { + LOGGER.debug("Preprocessing InternalProgram!"); LOGGER.debug("Preprocessing InternalProgram!"); InternalProgram retVal = InternalProgram.fromNormalProgram(program); - if (config.isEvaluateStratifiedPart()) { - AnalyzedProgram analyzed = new AnalyzedProgram(retVal.getRules(), retVal.getFacts()); - retVal = new StratifiedEvaluation().apply(analyzed); - } + AnalyzedProgram analyzed = new AnalyzedProgram(retVal.getRules(), retVal.getFacts()); + retVal = stratifiedEvaluationFactory.get().apply(analyzed); return retVal; } @@ -170,7 +182,7 @@ InternalProgram performProgramPreprocessing(NormalProgram program) { * program analysis and normalization aren't of interest. */ @Override - public Stream solve(ASPCore2Program program) { + public Stream solve(InputProgram program) { return solve(program, InputConfig.DEFAULT_FILTER); } @@ -179,7 +191,7 @@ public Stream solve(ASPCore2Program program) { * details of the program analysis and normalization aren't of interest. */ @Override - public Stream solve(ASPCore2Program program, java.util.function.Predicate filter) { + public Stream solve(InputProgram program, java.util.function.Predicate filter) { NormalProgram normalized = normalizeProgram(program); return solve(normalized, filter); } @@ -203,12 +215,12 @@ public Stream solve(NormalProgram program, java.util.function.Predica * Solves the given program and filters answer sets based on the passed predicate. * * @param program an {@link InternalProgram} to solve - * @param filter {@link Predicate} filtering {@at.ac.tuwien.kr.alpha.common.Predicate}s in the returned answer sets + * @param filter {@link Predicate} filtering {@link at.ac.tuwien.kr.alpha.api.programs.Predicate}s in the returned answer sets * @return a Stream of answer sets representing stable models of the given program */ private Stream solve(CompiledProgram program, java.util.function.Predicate filter) { Stream retVal = prepareSolverFor(program, filter).stream(); - return config.isSortAnswerSets() ? retVal.sorted() : retVal; + return sortAnswerSets ? retVal.sorted() : retVal; } /** @@ -221,21 +233,13 @@ private Stream solve(CompiledProgram program, java.util.function.Pred * @return a solver (and accompanying grounder) instance pre-loaded with the given program. */ private Solver prepareSolverFor(CompiledProgram program, java.util.function.Predicate filter) { - String grounderName = config.getGrounderName(); - boolean doDebugChecks = config.isDebugInternalChecks(); - - GrounderHeuristicsConfiguration grounderHeuristicConfiguration = GrounderHeuristicsConfiguration - .getInstance(config.getGrounderToleranceConstraints(), config.getGrounderToleranceRules()); - grounderHeuristicConfiguration.setAccumulatorEnabled(config.isGrounderAccumulatorEnabled()); - AtomStore atomStore = new AtomStoreImpl(); - Grounder grounder = GrounderFactory.getInstance(grounderName, program, atomStore, filter, grounderHeuristicConfiguration, doDebugChecks); - - return SolverFactory.getInstance(config, atomStore, grounder); + Grounder grounder = grounderFactory.createGrounder(program, atomStore, filter); + return solverFactory.createSolver(grounder, atomStore); } @Override - public DebugSolvingContext prepareDebugSolve(ASPCore2Program program) { + public DebugSolvingContext prepareDebugSolve(InputProgram program) { return prepareDebugSolve(program, InputConfig.DEFAULT_FILTER); } @@ -245,7 +249,7 @@ public DebugSolvingContext prepareDebugSolve(NormalProgram program) { } @Override - public DebugSolvingContext prepareDebugSolve(final ASPCore2Program program, java.util.function.Predicate filter) { + public DebugSolvingContext prepareDebugSolve(final InputProgram program, java.util.function.Predicate filter) { return prepareDebugSolve(normalizeProgram(program), filter); } @@ -255,11 +259,7 @@ public DebugSolvingContext prepareDebugSolve(final NormalProgram program, java.u final ComponentGraph compGraph; final AnalyzedProgram analyzed = AnalyzedProgram.analyzeNormalProgram(program); final NormalProgram preprocessed; - if (this.config.isEvaluateStratifiedPart()) { - preprocessed = new StratifiedEvaluation().apply(analyzed).toNormalProgram(); - } else { - preprocessed = program; - } + preprocessed = stratifiedEvaluationFactory.get().apply(analyzed).toNormalProgram(); depGraph = analyzed.getDependencyGraph(); compGraph = analyzed.getComponentGraph(); final Solver solver = prepareSolverFor(analyzed, filter); @@ -294,7 +294,7 @@ public ComponentGraph getComponentGraph() { } @Override - public Solver prepareSolverFor(ASPCore2Program program, java.util.function.Predicate filter) { + public Solver prepareSolverFor(InputProgram program, java.util.function.Predicate filter) { return prepareSolverFor(normalizeProgram(program), filter); } @@ -304,12 +304,12 @@ public Solver prepareSolverFor(NormalProgram program, java.util.function.Predica } @Override - public Set reify(ASPCore2Program program) { + public Set reify(InputProgram program) { return reifier.reifyProgram(program); } @Override - public TestResult test(ASPCore2Program program) { + public TestResult test(InputProgram program) { return testRunner.test(program); } diff --git a/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/TestRunner.java b/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/TestRunner.java index 2ac4bce95..1b408270e 100644 --- a/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/TestRunner.java +++ b/alpha-solver/src/main/java/at/ac/tuwien/kr/alpha/api/impl/TestRunner.java @@ -2,7 +2,7 @@ import at.ac.tuwien.kr.alpha.api.Alpha; import at.ac.tuwien.kr.alpha.api.AnswerSet; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.tests.Assertion; @@ -27,7 +27,7 @@ class TestRunner { this.alpha = alpha; } - TestResult test(ASPCore2Program program) { + TestResult test(InputProgram program) { LOGGER.info("Running unit tests.."); NormalProgram programUnderTest = alpha.normalizeProgram(program); List testCaseResults = program.getTestCases().stream() @@ -103,7 +103,7 @@ private List evaluateAssertion(Set answerSets, Assertion asse } private boolean answerSetSatisfiesAssertion(AnswerSet as, Assertion assertion) { - ASPCore2Program verifierWithInput = Programs.builder(assertion.getVerifier()).addFacts(new ArrayList<>(as.asFacts())).build(); + InputProgram verifierWithInput = Programs.builder(assertion.getVerifier()).addFacts(new ArrayList<>(as.asFacts())).build(); return alpha.solve(verifierWithInput).findAny().isPresent(); } diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/ActionsTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/ActionsTest.java index 1ddfaa7cc..c00df590d 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/ActionsTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/ActionsTest.java @@ -1,7 +1,19 @@ package at.ac.tuwien.kr.alpha; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import at.ac.tuwien.kr.alpha.api.Alpha; +import at.ac.tuwien.kr.alpha.api.AnswerSet; +import at.ac.tuwien.kr.alpha.api.config.SystemConfig; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; +import at.ac.tuwien.kr.alpha.api.programs.terms.ConstantTerm; +import at.ac.tuwien.kr.alpha.api.programs.terms.FunctionTerm; +import at.ac.tuwien.kr.alpha.commons.Predicates; +import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; +import at.ac.tuwien.kr.alpha.core.actions.ActionImplementationProvider; +import at.ac.tuwien.kr.alpha.core.actions.OutputStreamHandle; +import at.ac.tuwien.kr.alpha.test.util.MockedActionsAlphaFactory; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.OutputStream; @@ -10,21 +22,8 @@ import java.util.Set; import java.util.stream.Collectors; -import at.ac.tuwien.kr.alpha.api.terms.ConstantTerm; -import at.ac.tuwien.kr.alpha.api.terms.FunctionTerm; -import at.ac.tuwien.kr.alpha.commons.Predicates; -import at.ac.tuwien.kr.alpha.commons.util.AnswerSetQueryImpl; -import at.ac.tuwien.kr.alpha.core.actions.ActionImplementationProvider; -import at.ac.tuwien.kr.alpha.core.actions.OutputStreamHandle; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.ac.tuwien.kr.alpha.api.Alpha; -import at.ac.tuwien.kr.alpha.api.AnswerSet; -import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.InputProgram; -import at.ac.tuwien.kr.alpha.test.util.MockedActionsAlphaFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * End-to-end tests covering Evolog action support. @@ -72,7 +71,7 @@ public void writeToFile() { * Note: We have to check answer set content here because we have no way of constructing an equal instance for * the outputStreamHandle that is constructed when execution the "fileOutputStream" action. * */ - assertEquals(1, answerSet.query(AnswerSetQueryImpl.forPredicate(Predicates.getPredicate("outfile_open_result", 2)) + assertEquals(1, answerSet.query(Atoms.query(Predicates.getPredicate("outfile_open_result", 2)) .withFilter(0, term -> term instanceof ConstantTerm && ((ConstantTerm) term).getObject().endsWith("dummy.file")) .withFunctionTerm(1, "success", 1) .withFilter(1, (term) -> { @@ -83,7 +82,7 @@ public void writeToFile() { return streamTerm.getObject() instanceof OutputStreamHandle; }) ).size()); - assertEquals(1, answerSet.query(AnswerSetQueryImpl.forPredicate(Predicates.getPredicate("outfile_write_result", 2)) + assertEquals(1, answerSet.query(Atoms.query(Predicates.getPredicate("outfile_write_result", 2)) .withFilter(0, term -> term instanceof ConstantTerm && ((ConstantTerm) term).getObject().endsWith("dummy.file")) .withFunctionTerm(1, "success", 1) .withFilter(1, (term) -> { @@ -92,7 +91,7 @@ public void writeToFile() { return funcTerm.getTerms().get(0) instanceof ConstantTerm && ((ConstantTerm) funcTerm.getTerms().get(0)).getObject().equals("ok"); }) ).size()); - assertEquals(1, answerSet.query(AnswerSetQueryImpl.forPredicate(Predicates.getPredicate("outfile_close_result", 2)) + assertEquals(1, answerSet.query(Atoms.query(Predicates.getPredicate("outfile_close_result", 2)) .withFilter(0, term -> term instanceof ConstantTerm && ((ConstantTerm) term).getObject().endsWith("dummy.file")) .withFunctionTerm(1, "success", 1) .withFilter(1, (term) -> { diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingContextTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingContextTest.java index 969f26412..a4805b8b3 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingContextTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingContextTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test; import at.ac.tuwien.kr.alpha.api.ComparisonOperator; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.AggregateAtom.AggregateFunctionSymbol; import at.ac.tuwien.kr.alpha.api.programs.rules.Rule; import at.ac.tuwien.kr.alpha.api.programs.rules.heads.Head; @@ -58,7 +58,7 @@ public class AggregateRewritingContextTest { //@formatter:on private static final AggregateRewritingContext rewritingContextForAspString(String asp) { - ASPCore2Program program = new ProgramParserImpl().parse(asp); + InputProgram program = new ProgramParserImpl().parse(asp); AggregateRewritingContext ctx = new AggregateRewritingContext(); for (Rule rule : program.getRules()) { ctx.registerRule(rule); diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingTest.java index 288b52fbd..1d11e89d4 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/AggregateRewritingTest.java @@ -12,7 +12,7 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; @@ -34,7 +34,7 @@ public class AggregateRewritingTest { private static final ProgramParser PARSER = new ProgramParserImpl(); private static final Function> NORMALIZE_AND_SOLVE = (str) -> { SystemConfig cfg = new SystemConfig(); - ASPCore2Program prog = PARSER.parse(str); + InputProgram prog = PARSER.parse(str); NormalProgram normalized = new NormalizeProgramTransformation(cfg.getAggregateRewritingConfig()).apply(prog); CompiledProgram compiled = InternalProgram.fromNormalProgram(normalized); AtomStore atomStore = new AtomStoreImpl(); diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleParser.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleParser.java index 5381de504..ee00c7c4b 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleParser.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleParser.java @@ -1,6 +1,6 @@ package at.ac.tuwien.kr.alpha.core.test.util; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.rules.Rule; import at.ac.tuwien.kr.alpha.api.programs.rules.heads.Head; @@ -10,7 +10,7 @@ public class RuleParser { public static Rule parse(String str) { ProgramParser parser = new ProgramParserImpl(); - ASPCore2Program prog = parser.parse(str); + InputProgram prog = parser.parse(str); if (!prog.getFacts().isEmpty()) { throw new IllegalArgumentException("Expected exactly one rule and no facts!"); } diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleToStringTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleToStringTest.java index 828f6f922..7b075979e 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleToStringTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/RuleToStringTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.rules.Rule; import at.ac.tuwien.kr.alpha.api.programs.rules.heads.Head; @@ -97,7 +97,7 @@ private void constructNonGroundRuleAndCheckToString(String textualRule) { } private Rule parseSingleRule(String rule) { - ASPCore2Program program = parser.parse(rule); + InputProgram program = parser.parse(rule); List> rules = program.getRules(); assertEquals(1, rules.size(), "Number of rules"); return rules.get(0); diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/StratifiedEvaluationTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/StratifiedEvaluationTest.java index 2cf6b1337..6c6def131 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/StratifiedEvaluationTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/StratifiedEvaluationTest.java @@ -43,7 +43,7 @@ import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.common.fixedinterpretations.PredicateInterpretation; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; @@ -179,7 +179,7 @@ public void testNegatedExternalLiteral() throws Exception { */ @Test public void testPartnerUnitsProblemTopologicalOrder() throws IOException { - ASPCore2Program prg = parser.parse(StratifiedEvaluationTest.class.getResourceAsStream("/partial-eval/pup_topological_order.asp")); + InputProgram prg = parser.parse(StratifiedEvaluationTest.class.getResourceAsStream("/partial-eval/pup_topological_order.asp")); CompiledProgram evaluated = new StratifiedEvaluation().apply(AnalyzedProgram.analyzeNormalProgram(normalizer.apply(prg))); assertTrue(evaluated.getRules().isEmpty(), "Not all rules eliminated by stratified evaluation"); assertEquals(57, evaluated.getFacts().size()); @@ -200,7 +200,7 @@ public void testNegatedLiteralInRecursiveRule() throws IOException { + "inc_value(4), inc_value(5), inc_value(6), inc_value(7), " + "inc_value(8)"; //@formatter:on - ASPCore2Program prog = new ProgramParserImpl().parse( + InputProgram prog = new ProgramParserImpl().parse( StratifiedEvaluationTest.class.getResourceAsStream("/partial-eval/recursive_w_negated_condition.asp"), new HashMap<>()); diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImplTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImplTest.java index 9a774a18b..0e4086ea9 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImplTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/api/impl/AlphaImplTest.java @@ -32,7 +32,7 @@ import at.ac.tuwien.kr.alpha.api.config.Heuristic; import at.ac.tuwien.kr.alpha.api.config.InputConfig; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.NormalProgram; import at.ac.tuwien.kr.alpha.api.programs.ProgramParser; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; @@ -43,16 +43,16 @@ import at.ac.tuwien.kr.alpha.api.programs.tests.TestResult; import at.ac.tuwien.kr.alpha.commons.AnswerSetBuilder; import at.ac.tuwien.kr.alpha.commons.Predicates; +import at.ac.tuwien.kr.alpha.commons.externals.AspStandardLibrary; +import at.ac.tuwien.kr.alpha.commons.externals.Externals; +import at.ac.tuwien.kr.alpha.commons.externals.MethodPredicateInterpretation; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.literals.Literals; import at.ac.tuwien.kr.alpha.commons.programs.rules.Rules; import at.ac.tuwien.kr.alpha.commons.programs.rules.heads.Heads; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; -import at.ac.tuwien.kr.alpha.core.common.fixedinterpretations.MethodPredicateInterpretation; -import at.ac.tuwien.kr.alpha.core.externals.AspStandardLibrary; -import at.ac.tuwien.kr.alpha.core.externals.Externals; import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; import at.ac.tuwien.kr.alpha.core.programs.CompiledProgram; import org.junit.jupiter.api.Disabled; @@ -147,10 +147,10 @@ public static boolean thinger(Thingy thingy) { @Test public void withExternal() throws Exception { - Alpha alpha = new AlphaImpl(); + Alpha alpha = new AlphaFactory().newAlpha(); InputConfig inputCfg = InputConfig.forString("a :- &isOne[1]."); inputCfg.addPredicateMethod("isOne", Externals.processPredicateMethod(this.getClass().getMethod("isOne", int.class))); - ASPCore2Program program = alpha.readProgram(inputCfg); + InputProgram program = alpha.readProgram(inputCfg); Set actual = alpha.solve(program).collect(Collectors.toSet()); Set expected = new HashSet<>(singletonList(new AnswerSetBuilder().predicate("a").build())); assertEquals(expected, actual); @@ -158,11 +158,11 @@ public void withExternal() throws Exception { @Test public void addsFacts() { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); Thingy a = new Thingy(); Thingy b = new Thingy(); List things = asList(a, b); - ASPCore2Program program = Programs.builder().addFacts(Externals.asFacts(Thingy.class, things)).build(); + InputProgram program = Programs.builder().addFacts(Externals.asFacts(Thingy.class, things)).build(); Set actual = system.solve(program).collect(Collectors.toSet()); Set expected = new HashSet<>(singletonList(new AnswerSetBuilder().predicate("thingy").instance(a).instance(b).build())); assertEquals(expected, actual); @@ -171,7 +171,7 @@ public void addsFacts() { @Test public void withExternalTypeConflict() { assertThrows(IllegalArgumentException.class, () -> { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig inputCfg = InputConfig.forString("a :- &isFoo[\"adsfnfdsf\"]."); inputCfg.addPredicateMethod("isFoo", Externals.processPredicateMethod(this.getClass().getMethod("isFoo", Integer.class))); Set actual = system.solve(system.readProgram(inputCfg)).collect(Collectors.toSet()); @@ -182,26 +182,26 @@ public void withExternalTypeConflict() { @Test public void smallGraph() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig inputCfg = InputConfig.forString("node(1). node(2). node(3). a :- &connected[1,2]."); inputCfg.addPredicateMethod("connected", Externals.processPredicate((Integer a, Integer b) -> (a == 1 && b == 2) || (b == 2 || b == 3))); - ASPCore2Program program = system.readProgram(inputCfg); + InputProgram program = system.readProgram(inputCfg); Set actual = system.solve(program).collect(Collectors.toSet()); - Set expected = AnswerSetsParser.parse("{ a, node(1), node(2), node(3) }"); + Set expected = at.ac.tuwien.kr.alpha.api.impl.AnswerSetsParser.parse("{ a, node(1), node(2), node(3) }"); assertEquals(expected, actual); } @Test public void filterOutput() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig inputCfg = InputConfig.forString("node(1). node(2). outgoing13(X) :- node(X), &getLargeGraphEdges(13,X)."); inputCfg.addPredicateMethod("getLargeGraphEdges", Externals.processPredicate(() -> new HashSet<>(asList(asList(Terms.newConstant(1), Terms.newConstant(2)), asList(Terms.newConstant(2), Terms.newConstant(1)), asList(Terms.newConstant(13), Terms.newConstant(1)))))); - ASPCore2Program program = system.readProgram(inputCfg); + InputProgram program = system.readProgram(inputCfg); Set actual = system.solve(program).collect(Collectors.toSet()); - Set expected = AnswerSetsParser.parse("{ node(1), node(2), outgoing13(1) }"); + Set expected = at.ac.tuwien.kr.alpha.api.impl.AnswerSetsParser.parse("{ node(1), node(2), outgoing13(1) }"); assertEquals(expected, actual); } @@ -210,7 +210,7 @@ public void supplier() throws Exception { Alpha system = new AlphaImpl(); InputConfig cfg = InputConfig.forString("node(1). a :- &bestNode(X), node(X)."); cfg.addPredicateMethod("bestNode", Externals.processPredicate(() -> singleton(singletonList(Terms.newConstant(1))))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set expected = AnswerSetsParser.parse("{ node(1), a }"); Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -227,7 +227,7 @@ public void noInput() throws Exception { Alpha system = new AlphaImpl(); InputConfig cfg = InputConfig.forString("node(1). a :- &bestNode(X), node(X)."); cfg.addPredicateMethod("bestNode", Externals.processPredicateMethod(this.getClass().getMethod("bestNode"))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set expected = AnswerSetsParser.parse("{ node(1), a }"); Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -237,10 +237,10 @@ public void noInput() throws Exception { @Test public void smallGraphWithWrongType() { assertThrows(IllegalArgumentException.class, () -> { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("a :- &connected[\"hello\",2]."); cfg.addPredicateMethod("connected", Externals.processPredicate((Integer a, Integer b) -> (a == 1 && b == 2) || (b == 2 || b == 3))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); system.solve(prog).collect(Collectors.toSet()); }); @@ -263,10 +263,10 @@ public static Set>> coolNode(int node) { @Test @Disabled("Test program is not safe (external lacking output variables). This should throw some exception.") public void smallGraphNoNeighbors() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("noNeighbors(2) :- not &neighbors[2]."); cfg.addPredicateMethod("neighbors", Externals.processPredicateMethod(this.getClass().getMethod("neighbors", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set expected = AnswerSetsParser.parse("{ noNeighbors(2) }"); Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -275,10 +275,10 @@ public void smallGraphNoNeighbors() throws Exception { @Test public void smallGraphCoolNode() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("node(1..2). in(X) :- node(X), &coolNode[X]."); cfg.addPredicateMethod("coolNode", Externals.processPredicateMethod(this.getClass().getMethod("coolNode", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set actual = system.solve(prog).collect(Collectors.toSet()); Set expected = AnswerSetsParser.parse("{ in(1), node(1), node(2) }"); @@ -287,10 +287,10 @@ public void smallGraphCoolNode() throws Exception { @Test public void smallGraphSingleNeighbor() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("node(1..3). in(1,X) :- &neighbors[1](X), node(X)."); cfg.addPredicateMethod("neighbors", Externals.processPredicateMethod(this.getClass().getMethod("neighbors", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set expected = AnswerSetsParser.parse("{ in(1,2), in(1,3), node(1), node(2), node(3) }"); Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -300,10 +300,10 @@ public void smallGraphSingleNeighbor() throws Exception { @Test @Disabled("Test program is not safe (external lacking output variables). This should throw some exception.") public void smallGraphSingleNeighborNoTerm() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("success :- &neighbors[1], not &neighbors[2]."); cfg.addPredicateMethod("neighbors", Externals.processPredicateMethod(this.getClass().getMethod("neighbors", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set expected = AnswerSetsParser.parse("{ success }"); Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -335,9 +335,9 @@ public void withExternalSubtype() throws Exception { new MethodPredicateInterpretation(this.getClass().getMethod("thinger", Thingy.class)), singletonList(Terms.newConstant(thingy)), emptyList()), true))); - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); - ASPCore2Program prog = Programs.newASPCore2Program(singletonList(rule), emptyList(), Programs.newInlineDirectives()); + InputProgram prog = Programs.newInputProgram(singletonList(rule), emptyList(), Programs.newInlineDirectives()); Set actual = system.solve(prog).collect(Collectors.toSet()); Set expected = new HashSet<>(singletonList(new AnswerSetBuilder().predicate("p").instance("x").build())); @@ -346,10 +346,10 @@ public void withExternalSubtype() throws Exception { @Test public void withExternalViaAnnotation() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("a :- &isOne[1]."); cfg.addPredicateMethods(Externals.scan(this.getClass())); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set actual = system.solve(prog).collect(Collectors.toSet()); Set expected = new HashSet<>(singletonList(new AnswerSetBuilder().predicate("a").build())); @@ -372,10 +372,10 @@ public void errorDuplicateExternal() { @Test public void withNativeExternal() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("a :- &isTwo[2]."); cfg.addPredicateMethod("isTwo", Externals.processPredicate((Integer t) -> t == 2)); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); Set actual = system.solve(prog).collect(Collectors.toSet()); Set expected = new HashSet<>(singletonList(new AnswerSetBuilder().predicate("a").build())); @@ -385,10 +385,10 @@ public void withNativeExternal() throws Exception { @Test @Disabled("External atom has state, which is not allowed. Caching of calls makes the number of invocations wrong.") public void withExternalInvocationCounted1() throws Exception { - Alpha system = new AlphaImpl(); + Alpha system = new AlphaFactory().newAlpha(); InputConfig cfg = InputConfig.forString("a :- &isOne[1], &isOne[1]."); cfg.addPredicateMethod("isOne", Externals.processPredicateMethod(this.getClass().getMethod("isOne", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); int before = invocations; Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -406,7 +406,7 @@ public void withExternalInvocationCounted2() throws Exception { Alpha system = new AlphaImpl(); InputConfig cfg = InputConfig.forString("a. b :- &isOne[1], &isOne[2]."); cfg.addPredicateMethod("isOne", Externals.processPredicateMethod(this.getClass().getMethod("isOne", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); int before = invocations; Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -424,7 +424,7 @@ public void withExternalInvocationCounted3() throws Exception { Alpha system = new AlphaImpl(); InputConfig cfg = InputConfig.forString("a :- &isOne[1], not &isOne[2]."); cfg.addPredicateMethod("isOne", Externals.processPredicateMethod(this.getClass().getMethod("isOne", int.class))); - ASPCore2Program prog = system.readProgram(cfg); + InputProgram prog = system.readProgram(cfg); int before = invocations; Set actual = system.solve(prog).collect(Collectors.toSet()); @@ -440,7 +440,7 @@ public void withExternalInvocationCounted3() throws Exception { @SuppressWarnings("unchecked") public void programWithExternalStringStuff() throws IOException { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgram(InputConfig.forString(STRINGSTUFF_ASP)); + InputProgram prog = alpha.readProgram(InputConfig.forString(STRINGSTUFF_ASP)); Set answerSets = alpha.solve(prog).collect(Collectors.toSet()); // Verify every result string has length 6 and contains "foo" for (AnswerSet as : answerSets) { @@ -456,7 +456,7 @@ public void programWithExternalStringStuff() throws IOException { @SuppressWarnings("unchecked") public void withNegatedExternal() throws IOException { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgram(InputConfig.forString(NEGATED_EXTERNAL_ASP)); + InputProgram prog = alpha.readProgram(InputConfig.forString(NEGATED_EXTERNAL_ASP)); Set answerSets = alpha.solve(prog).collect(Collectors.toSet()); assertEquals(31, answerSets.size()); // Verify every result string has length 6 and contains "foo" @@ -474,7 +474,7 @@ public void withNegatedExternal() throws IOException { public void reifyInput() { String aspInput = "p(X) :- q(X), not r(X)."; Alpha system = new AlphaImpl(); - ASPCore2Program input = system.readProgramString(aspInput); + InputProgram input = system.readProgramString(aspInput); Set reified = system.reify(input); Set reifiedPredicates = reified.stream() @@ -514,7 +514,7 @@ public void basicUsageWithString() throws Exception { public void filterTest() { String progstr = "a. b. c. d :- c. e(a, b) :- d."; Alpha system = new AlphaImpl(); - ASPCore2Program prog = system.readProgramString(progstr); + InputProgram prog = system.readProgramString(progstr); Set actual = system.solve(prog, (p) -> p.equals(Predicates.getPredicate("a", 0)) || p.equals(Predicates.getPredicate("e", 2))) .collect(Collectors.toSet()); Set expected = new HashSet<>(singletonList(new AnswerSetBuilder().predicate("a").predicate("e").symbolicInstance("a", "b").build())); @@ -531,7 +531,7 @@ public void disableStratifiedEvalTest() { SystemConfig cfg = new SystemConfig(); cfg.setEvaluateStratifiedPart(false); AlphaImpl system = new AlphaImpl(cfg); - ASPCore2Program input = system.readProgramString(progstr); + InputProgram input = system.readProgramString(progstr); NormalProgram normal = system.normalizeProgram(input); CompiledProgram preprocessed = system.performProgramPreprocessing(normal); assertFalse(preprocessed.getFacts().contains(Atoms.newBasicAtom(Predicates.getPredicate("q", 1), Terms.newSymbolicConstant("a"))), @@ -547,7 +547,7 @@ public void enableStratifiedEvalTest() { String progstr = "p(a). q(X) :- p(X)."; SystemConfig cfg = new SystemConfig(); AlphaImpl system = new AlphaImpl(cfg); - ASPCore2Program input = system.readProgramString(progstr); + InputProgram input = system.readProgramString(progstr); NormalProgram normal = system.normalizeProgram(input); CompiledProgram preprocessed = system.performProgramPreprocessing(normal); assertTrue(preprocessed.getFacts().contains(Atoms.newBasicAtom(Predicates.getPredicate("q", 1), Terms.newSymbolicConstant("a"))), @@ -557,7 +557,7 @@ public void enableStratifiedEvalTest() { @Test public void passingUnitTestExpectUnsat() { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgramString(UNIT_TEST_EXPECT_UNSAT); + InputProgram prog = alpha.readProgramString(UNIT_TEST_EXPECT_UNSAT); TestResult testResult = alpha.test(prog); assertTrue(testResult.isSuccess()); } @@ -565,7 +565,7 @@ public void passingUnitTestExpectUnsat() { @Test public void passingUnitTestBasicTest() { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgramString(UNIT_TEST_BASIC_TEST); + InputProgram prog = alpha.readProgramString(UNIT_TEST_BASIC_TEST); TestResult testResult = alpha.test(prog); assertTrue(testResult.isSuccess()); assertEquals(1, testResult.getTestCaseResults().size()); @@ -580,7 +580,7 @@ public void passingUnitTestBasicTest() { @Test public void passingUnitTestMultipleAssertions() { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgramString(UNIT_TEST_MORE_ASSERTIONS); + InputProgram prog = alpha.readProgramString(UNIT_TEST_MORE_ASSERTIONS); TestResult testResult = alpha.test(prog); assertTrue(testResult.isSuccess()); assertEquals(1, testResult.getTestCaseResults().size()); @@ -595,7 +595,7 @@ public void passingUnitTestMultipleAssertions() { @Test public void passingUnitTestMultipleTestCases() { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgramString(UNIT_TEST_MORE_TCS); + InputProgram prog = alpha.readProgramString(UNIT_TEST_MORE_TCS); TestResult testResult = alpha.test(prog); assertTrue(testResult.isSuccess()); assertEquals(2, testResult.getTestCaseResults().size()); @@ -604,7 +604,7 @@ public void passingUnitTestMultipleTestCases() { @Test public void failingAssertionUnitTest() { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgramString(UNIT_TEST_FAILING_ASSERTION); + InputProgram prog = alpha.readProgramString(UNIT_TEST_FAILING_ASSERTION); TestResult testResult = alpha.test(prog); assertFalse(testResult.isSuccess()); assertEquals(1, testResult.getTestCaseResults().size()); @@ -619,7 +619,7 @@ public void failingAssertionUnitTest() { @Test public void failingAnswerSetCountUnitTest() { Alpha alpha = new AlphaImpl(); - ASPCore2Program prog = alpha.readProgramString(UNIT_TEST_FAILING_COUNT); + InputProgram prog = alpha.readProgramString(UNIT_TEST_FAILING_COUNT); TestResult testResult = alpha.test(prog); assertFalse(testResult.isSuccess()); assertEquals(1, testResult.getTestCaseResults().size()); @@ -690,7 +690,7 @@ public void problematicRun_3col_1119718541727902_sorted_400() throws IOException List files = new ArrayList<>(); files.add(path.toString()); inputCfg.setFiles(files); - ASPCore2Program prog = system.readProgram(inputCfg); + InputProgram prog = system.readProgram(inputCfg); assertFalse(system.solve(prog).sorted().limit(400).collect(Collectors.toList()).isEmpty()); } @@ -708,7 +708,7 @@ private void problematicRun(String program, long seed, int limit) throws IOExcep List files = new ArrayList<>(); files.add(base.resolve(program).toString()); inputCfg.setFiles(files); - ASPCore2Program prog = system.readProgram(inputCfg); + InputProgram prog = system.readProgram(inputCfg); assertFalse(system.solve(prog).limit(limit).collect(Collectors.toList()).isEmpty()); } @@ -716,11 +716,11 @@ private void problematicRun(String program, long seed, int limit) throws IOExcep @Test public void testLearnedUnaryNoGoodCausingOutOfOrderLiteralsConflict() throws IOException { final ProgramParser parser = new ProgramParserImpl(); - ASPCore2ProgramBuilder bld = Programs.builder(); + InputProgramBuilder bld = Programs.builder(); bld.accumulate(parser.parse(Files.newInputStream(Paths.get("src", "test", "resources", "HanoiTower_Alpha.asp"), StandardOpenOption.READ))); bld.accumulate( parser.parse(Files.newInputStream(Paths.get("src", "test", "resources", "HanoiTower_instances", "simple.asp"), StandardOpenOption.READ))); - ASPCore2Program parsedProgram = bld.build(); + InputProgram parsedProgram = bld.build(); SystemConfig config = new SystemConfig(); config.setSolverName("default"); diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HanoiTowerTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HanoiTowerTest.java index 23457da10..7657b7d40 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HanoiTowerTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HanoiTowerTest.java @@ -39,7 +39,7 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.terms.Term; @@ -101,7 +101,7 @@ private void testHanoiTower(int instance, RegressionTestConfig cfg) throws IOExc } private void testHanoiTower(String instance, RegressionTestConfig cfg) throws IOException { - ASPCore2Program prog = new ProgramParserImpl().parse( + InputProgram prog = new ProgramParserImpl().parse( Paths.get("src", "test", "resources", "HanoiTower_Alpha.asp"), Paths.get("src", "test", "resources", "HanoiTower_instances", instance + ".asp")); Solver solver = TestUtils.buildSolverForRegressionTest(prog, cfg); @@ -115,7 +115,7 @@ private void testHanoiTower(String instance, RegressionTestConfig cfg) throws IO * for every goal/3 * fact in the input there is a corresponding on/3 atom in the output. */ - private void checkGoal(ASPCore2Program parsedProgram, AnswerSet answerSet) { + private void checkGoal(InputProgram parsedProgram, AnswerSet answerSet) { Predicate ongoal = Predicates.getPredicate("ongoal", 2); Predicate on = Predicates.getPredicate("on", 3); int steps = getSteps(parsedProgram); @@ -131,7 +131,7 @@ private void checkGoal(ASPCore2Program parsedProgram, AnswerSet answerSet) { } } - private int getSteps(ASPCore2Program parsedProgram) { + private int getSteps(InputProgram parsedProgram) { Predicate steps = Predicates.getPredicate("steps", 1); for (Atom atom : parsedProgram.getFacts()) { if (atom.getPredicate().getName().equals(steps.getName()) && atom.getPredicate().getArity() == steps.getArity()) { diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HeadBodyTransformationTests.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HeadBodyTransformationTests.java index da9238e66..2f2b91204 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HeadBodyTransformationTests.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/HeadBodyTransformationTests.java @@ -42,7 +42,7 @@ import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; import at.ac.tuwien.kr.alpha.api.programs.InputProgram; -import at.ac.tuwien.kr.alpha.core.parser.aspcore2.ASPCore2ProgramParser; +import at.ac.tuwien.kr.alpha.core.parser.aspcore2.InputProgramParser; import at.ac.tuwien.kr.alpha.regressiontests.util.RegressionTest; /** * Tests rule transformations described in the following research paper, and their effects on performance: @@ -246,7 +246,7 @@ private InputProgram constructProgramA_TransformationA(int n) { private InputProgram checkNumberOfRulesAndParse(List strRules, int numberOfRules) { assertEquals(numberOfRules, strRules.size()); String strProgram = strRules.stream().collect(Collectors.joining(System.lineSeparator())); - InputProgram parsedProgram = new ASPCore2ProgramParser().parse(strProgram); + InputProgram parsedProgram = new InputProgramParser().parse(strProgram); assertEquals(numberOfRules, parsedProgram.getRules().size()); return parsedProgram; } diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/OmigaBenchmarksTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/OmigaBenchmarksTest.java index a8d9d79d0..171e0c514 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/OmigaBenchmarksTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/OmigaBenchmarksTest.java @@ -41,7 +41,7 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.core.parser.aspcore2.ASPCore2ProgramParser; +import at.ac.tuwien.kr.alpha.core.parser.aspcore2.InputProgramParser; import at.ac.tuwien.kr.alpha.regressiontests.util.RegressionTest; /** @@ -112,7 +112,7 @@ public void testReach_4(SystemConfig cfg) { private void test(String folder, String aspFileName, SystemConfig cfg) throws IOException { @SuppressWarnings("unused") Optional answerSet = buildSolverForRegressionTest( - new ASPCore2ProgramParser().parse(Files.newInputStream(Paths.get("benchmarks", "omiga", "omiga-testcases", folder, aspFileName))), cfg) + new InputProgramParser().parse(Files.newInputStream(Paths.get("benchmarks", "omiga", "omiga-testcases", folder, aspFileName))), cfg) .stream().findFirst(); // System.out.println(answerSet); // TODO: check correctness of answer set diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/RacksTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/RacksTest.java index 070177f4e..6303ec475 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/RacksTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/RacksTest.java @@ -39,7 +39,7 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; import at.ac.tuwien.kr.alpha.api.config.SystemConfig; -import at.ac.tuwien.kr.alpha.core.parser.aspcore2.ASPCore2ProgramParser; +import at.ac.tuwien.kr.alpha.core.parser.aspcore2.InputProgramParser; import at.ac.tuwien.kr.alpha.regressiontests.util.RegressionTest; /** @@ -61,7 +61,7 @@ public void testRacks(SystemConfig cfg) { private void test(SystemConfig cfg) throws IOException { CharStream programInputStream = CharStreams.fromPath( Paths.get("benchmarks", "siemens", "racks", "racks.lp")); - Solver solver = buildSolverForRegressionTest(new ASPCore2ProgramParser().parse(programInputStream), cfg); + Solver solver = buildSolverForRegressionTest(new InputProgramParser().parse(programInputStream), cfg); @SuppressWarnings("unused") Optional answerSet = solver.stream().findFirst(); // System.out.println(answerSet); diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/SolverTests.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/SolverTests.java index c0bfdd991..da84e80a7 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/SolverTests.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/SolverTests.java @@ -44,7 +44,7 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.terms.ConstantTerm; @@ -79,7 +79,7 @@ public void testObjectProgram(RegressionTestConfig cfg) { final Atom fact = Atoms.newBasicAtom(Predicates.getPredicate("foo", 1), Terms.newConstant(thingy)); - final ASPCore2Program program = Programs.newASPCore2Program( + final InputProgram program = Programs.newInputProgram( Collections.emptyList(), Collections.singletonList(fact), Programs.newInlineDirectives() diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringRandomGraphTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringRandomGraphTest.java index b39232c8c..9c8388297 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringRandomGraphTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringRandomGraphTest.java @@ -36,12 +36,12 @@ import org.junit.jupiter.api.Disabled; import at.ac.tuwien.kr.alpha.api.AnswerSet; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; @@ -99,17 +99,17 @@ public void testV300E300(RegressionTestConfig cfg) { } private void testThreeColouring(int nVertices, int nEdges, RegressionTestConfig cfg) { - ASPCore2Program tmpPrg = new ProgramParserImpl().parse( + InputProgram tmpPrg = new ProgramParserImpl().parse( "blue(N) :- v(N), not red(N), not green(N)." + "red(N) :- v(N), not blue(N), not green(N)." + "green(N) :- v(N), not red(N), not blue(N)." + ":- e(N1,N2), blue(N1), blue(N2)." + ":- e(N1,N2), red(N1), red(N2)." + ":- e(N1,N2), green(N1), green(N2)."); - ASPCore2ProgramBuilder prgBuilder = Programs.builder(tmpPrg); + InputProgramBuilder prgBuilder = Programs.builder(tmpPrg); prgBuilder.addFacts(createVertices(nVertices)); prgBuilder.addFacts(createEdges(nVertices, nEdges)); - ASPCore2Program program = prgBuilder.build(); + InputProgram program = prgBuilder.build(); maybeShuffle(program); @SuppressWarnings("unused") @@ -120,7 +120,7 @@ private void testThreeColouring(int nVertices, int nEdges, RegressionTestConfig } @SuppressWarnings("unused") - private void maybeShuffle(ASPCore2Program program) { + private void maybeShuffle(InputProgram program) { // TODO: switch on if different rule orderings in the encoding are desired (e.g. for benchmarking purposes) // FIXME since InputProgram is immutable this needs to be reworked a bit if used diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringTestWithRandom.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringTestWithRandom.java index e0ff335a6..8f0c32c05 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringTestWithRandom.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringTestWithRandom.java @@ -38,13 +38,13 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; @@ -185,13 +185,13 @@ public void testN101(RegressionTestConfig cfg) { } private void testThreeColouring(int n, boolean shuffle, int seed, RegressionTestConfig cfg) { - ASPCore2Program tmpPrg = new ProgramParserImpl() + InputProgram tmpPrg = new ProgramParserImpl() .parse("col(V,C) :- v(V), c(C), not ncol(V,C)." + "ncol(V,C) :- col(V,D), c(C), C != D." + ":- e(V,U), col(V,C), col(U,C)."); - ASPCore2ProgramBuilder prgBuilder = Programs.builder().accumulate(tmpPrg); + InputProgramBuilder prgBuilder = Programs.builder().accumulate(tmpPrg); prgBuilder.addFacts(createColors("1", "2", "3")); prgBuilder.addFacts(createVertices(n)); prgBuilder.addFacts(createEdges(n, shuffle, seed)); - ASPCore2Program program = prgBuilder.build(); + InputProgram program = prgBuilder.build(); Solver solver = buildSolverForRegressionTest(program, cfg); @SuppressWarnings("unused") diff --git a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringWheelTest.java b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringWheelTest.java index 370e6fbd0..1470708ca 100644 --- a/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringWheelTest.java +++ b/alpha-solver/src/test/java/at/ac/tuwien/kr/alpha/regressiontests/ThreeColouringWheelTest.java @@ -36,13 +36,13 @@ import at.ac.tuwien.kr.alpha.api.AnswerSet; import at.ac.tuwien.kr.alpha.api.Solver; -import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program; +import at.ac.tuwien.kr.alpha.api.programs.InputProgram; import at.ac.tuwien.kr.alpha.api.programs.Predicate; import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom; import at.ac.tuwien.kr.alpha.api.programs.terms.Term; import at.ac.tuwien.kr.alpha.commons.Predicates; import at.ac.tuwien.kr.alpha.commons.programs.Programs; -import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder; +import at.ac.tuwien.kr.alpha.commons.programs.Programs.InputProgramBuilder; import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms; import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms; import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl; @@ -99,15 +99,15 @@ public void testN11(RegressionTestConfig cfg) { } private void testThreeColouring(int n, RegressionTestConfig cfg) { - ASPCore2Program tmpPrg = new ProgramParserImpl().parse( + InputProgram tmpPrg = new ProgramParserImpl().parse( "col(V,C) :- v(V), c(C), not ncol(V,C)." + "ncol(V,C) :- col(V,D), c(C), C != D." + ":- e(V,U), col(V,C), col(U,C)."); - ASPCore2ProgramBuilder prgBuilder = Programs.builder(tmpPrg); + InputProgramBuilder prgBuilder = Programs.builder(tmpPrg); prgBuilder.addFacts(createColors("red", "blue", "green")); prgBuilder.addFacts(createVertices(n)); prgBuilder.addFacts(createEdges(n)); - ASPCore2Program program = prgBuilder.build(); + InputProgram program = prgBuilder.build(); maybeShuffle(program); @@ -121,7 +121,7 @@ private void testThreeColouring(int n, RegressionTestConfig cfg) { } @SuppressWarnings("unused") - private void maybeShuffle(ASPCore2Program program) { + private void maybeShuffle(InputProgram program) { // FIXME since InputProgram is immutable this needs to be reworked a bit if used // No shuffling here. }