aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLibravatar Kristóf Marussy <marussy@mit.bme.hu>2020-11-02 02:02:40 +0100
committerLibravatar Kristóf Marussy <marussy@mit.bme.hu>2020-11-02 02:02:40 +0100
commitf06427cd7375551582461f91b3458339a8227f9b (patch)
tree97bc6ec85f4c384e5080a6611b492caf460b6ce9
parentMust unit propagation (diff)
downloadVIATRA-Generator-f06427cd7375551582461f91b3458339a8227f9b.tar.gz
VIATRA-Generator-f06427cd7375551582461f91b3458339a8227f9b.tar.zst
VIATRA-Generator-f06427cd7375551582461f91b3458339a8227f9b.zip
Optimizing generator with linear objective functions
-rw-r--r--Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbinbin1700 -> 1700 bytes
-rw-r--r--Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbinbin2525 -> 2525 bytes
-rw-r--r--Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbinbin5333 -> 5333 bytes
-rw-r--r--Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbinbin4902 -> 4902 bytes
-rw-r--r--Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore4
-rw-r--r--Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbinbin1716 -> 1716 bytes
-rw-r--r--Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore2
-rw-r--r--Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbinbin2741 -> 2741 bytes
-rw-r--r--Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore2
-rw-r--r--Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbinbin2757 -> 2757 bytes
-rw-r--r--Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore2
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF3
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml18
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql197
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend201
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend139
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend140
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend189
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend85
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore45
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java564
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java717
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java847
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java841
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java198
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java565
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java12
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java564
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java713
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbinbin0 -> 8218 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbinbin0 -> 7190 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbinbin0 -> 7395 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbinbin15038 -> 18637 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbinbin7179 -> 6927 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbinbin11735 -> 11284 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbinbin0 -> 6269 bytes
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore10
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java279
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java193
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java195
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java305
-rw-r--r--Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java117
-rw-r--r--Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF1
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF3
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend47
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend44
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend140
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend63
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend54
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend92
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend13
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF1
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend1
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend (renamed from Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend)427
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend102
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend4
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java7
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend2
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend3
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend8
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend112
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend137
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend68
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend8
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend99
-rw-r--r--Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend205
-rw-r--r--Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore1
-rw-r--r--Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore4
-rw-r--r--Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore4
-rw-r--r--Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbinbin6885 -> 6885 bytes
-rw-r--r--Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend4
-rw-r--r--Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend2
-rw-r--r--Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend2
73 files changed, 8297 insertions, 508 deletions
diff --git a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin
index e697e27d..81ae9937 100644
--- a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin
+++ b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin
Binary files differ
diff --git a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin
index ddbe1979..10371590 100644
--- a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin
+++ b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin
Binary files differ
diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin
index e1e21292..49fafab3 100644
--- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin
+++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin
Binary files differ
diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin
index b967ea7c..968ecef8 100644
--- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin
+++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin
Binary files differ
diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore
index 1764b462..61ce5bef 100644
--- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore
+++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.gitignore
@@ -1,2 +1,6 @@
1/.SolverSemanticHighlightCalculator.java._trace 1/.SolverSemanticHighlightCalculator.java._trace
2/.SolverSemanticTextAttributeProvider.java._trace 2/.SolverSemanticTextAttributeProvider.java._trace
3/.SolverSemanticHighlightCalculator.xtendbin
4/.SolverSemanticTextAttributeProvider.xtendbin
5/SolverSemanticHighlightCalculator.java
6/SolverSemanticTextAttributeProvider.java
diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin
index 2c271c98..afb2c8de 100644
--- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin
+++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin
Binary files differ
diff --git a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore
index f1cb387a..565d4b27 100644
--- a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore
+++ b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.gitignore
@@ -1 +1,3 @@
1/.SolverLanguageValidator.java._trace 1/.SolverLanguageValidator.java._trace
2/.SolverLanguageValidator.xtendbin
3/SolverLanguageValidator.java
diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin
index 40f87b4c..c1d5cb5e 100644
--- a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin
+++ b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin
Binary files differ
diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore
index 9cf14147..5fbb81c3 100644
--- a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore
+++ b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.gitignore
@@ -5,3 +5,5 @@
5/.SolverLanguageSyntheticTokenParser.java._trace 5/.SolverLanguageSyntheticTokenParser.java._trace
6/.SolverLanguageTokenSource.java._trace 6/.SolverLanguageTokenSource.java._trace
7/.SolverLanguageTokenDefInjectingParser.java._trace 7/.SolverLanguageTokenDefInjectingParser.java._trace
8/.SolverLanguageTokenDefInjectingParser.xtendbin
9/SolverLanguageTokenDefInjectingParser.java
diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin
index d0715440..7fb5f085 100644
--- a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin
+++ b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin
Binary files differ
diff --git a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore
index b8132d70..1f04090d 100644
--- a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore
+++ b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.gitignore
@@ -1 +1,3 @@
1/.SolverLanguageSyntheticTokenSyntacticSequencer.java._trace 1/.SolverLanguageSyntheticTokenSyntacticSequencer.java._trace
2/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin
3/SolverLanguageSyntheticTokenSyntacticSequencer.java
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF b/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF
index 96bd2113..8f900199 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/META-INF/MANIFEST.MF
@@ -28,7 +28,8 @@ Require-Bundle: org.eclipse.viatra.query.runtime,
28 hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 28 hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0",
29 org.eclipse.emf.ecore.xmi;bundle-version="2.16.0", 29 org.eclipse.emf.ecore.xmi;bundle-version="2.16.0",
30 hu.bme.mit.inf.dslreasoner.visualisation;bundle-version="1.0.0", 30 hu.bme.mit.inf.dslreasoner.visualisation;bundle-version="1.0.0",
31 org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0" 31 org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0",
32 org.eclipse.viatra.dse;bundle-version="0.24.0"
32Import-Package: org.apache.log4j 33Import-Package: org.apache.log4j
33Automatic-Module-Name: ca.mcgill.rtgmrt.example.modes3 34Automatic-Module-Name: ca.mcgill.rtgmrt.example.modes3
34Bundle-ActivationPolicy: lazy 35Bundle-ActivationPolicy: lazy
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml b/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml
index a105a729..f7d32541 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml
@@ -21,6 +21,24 @@
21 <query-specification fqn="modes3.queries.tooFewInputsOfTurnout"/> 21 <query-specification fqn="modes3.queries.tooFewInputsOfTurnout"/>
22 <query-specification fqn="modes3.queries.reachable"/> 22 <query-specification fqn="modes3.queries.reachable"/>
23 <query-specification fqn="modes3.queries.unreachable"/> 23 <query-specification fqn="modes3.queries.unreachable"/>
24 <query-specification fqn="modes3.queries.closeTrains_step_2"/>
25 <query-specification fqn="modes3.queries.closeTrains_step_3"/>
26 <query-specification fqn="modes3.queries.closeTrains_step_4"/>
27 <query-specification fqn="modes3.queries.closeTrains_step_5"/>
28 <query-specification fqn="modes3.queries.closeTrains_step_6"/>
29 <query-specification fqn="modes3.queries.closeTrains_step_7"/>
30 <query-specification fqn="modes3.queries.trainLocations_step_2"/>
31 <query-specification fqn="modes3.queries.trainLocations_step_3"/>
32 <query-specification fqn="modes3.queries.misalignedTurnout_step_2"/>
33 <query-specification fqn="modes3.queries.misalignedTurnout_step_3"/>
34 <query-specification fqn="modes3.queries.misalignedTurnout_step_4"/>
35 <query-specification fqn="modes3.queries.misalignedTurnout_step_5"/>
36 <query-specification fqn="modes3.queries.connectedSegmentsDirected"/>
37 <query-specification fqn="modes3.queries.endOfSiding_step_2"/>
38 <query-specification fqn="modes3.queries.endOfSiding_step_3"/>
39 <query-specification fqn="modes3.queries.endOfSiding_step_4"/>
40 <query-specification fqn="modes3.queries.endOfSiding_step_5"/>
41 <query-specification fqn="modes3.queries.multipleConnectedTo"/>
24 </group> 42 </group>
25 </extension> 43 </extension>
26</plugin> 44</plugin>
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
index b8841928..d22bdd8b 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
@@ -40,12 +40,6 @@ pattern output(S1 : Segment, S2 : Segment) {
40 find turnoutOutput(S1, S2); 40 find turnoutOutput(S1, S2);
41} 41}
42 42
43//@Constraint(message = "noInputOfSegment", severity = "error", key = { S })
44//pattern noInputOfSegment(S : Segment) {
45// neg find turnout(S);
46// neg find output(_, S);
47//}
48
49@Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) 43@Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
50pattern tooManyInputsOfSegment(S : SimpleSegment) { 44pattern tooManyInputsOfSegment(S : SimpleSegment) {
51 find output(I1, S); 45 find output(I1, S);
@@ -108,3 +102,194 @@ pattern reachable(S1 : Segment, S2 : Segment) {
108pattern unreachable(S1 : Segment, S2 : Segment) { 102pattern unreachable(S1 : Segment, S2 : Segment) {
109 neg find reachable(S1, S2); 103 neg find reachable(S1, S2);
110} 104}
105
106//
107// closeTrains
108//
109
110pattern closeTrains_step_2(in train : Train) {
111// frame->t1 = model->trains[i0];
112// frame->start = frame->t1->location;
113// if(frame->start != 0){
114// ...
115// }
116// + OUTER FOR LOOP COUNTER INCREMENT
117 Train(train);
118}
119
120pattern closeTrains_step_3(in train : Train, in start : Segment) {
121// int loop_bound1 = frame->start->connected_to_count;
122// for (int i1 = 0; i1 < loop_bound1; i1++) { LOOP COUNTER INCREMENT IS NOT INCLUDED HERE
123// ...
124// }
125 Train.location(train, start);
126}
127
128pattern closeTrains_step_4(in train : Train, in start : Segment, in middle : Segment) {
129// frame->middle = frame->start->connected_to[i1];
130// int loop_bound2 = frame->middle->connected_to_count;
131
132// for (int i2 = 0; i2 < loop_bound2; i2++) { LOOP COUNTER INCREMENT IS NOT INCLUDED HERE
133// ...
134// }
135// + OUTER FOR LOOP COUNTER INCREMENT
136 Train.location(train, start);
137 Segment.connectedTo(start, middle);
138}
139
140pattern closeTrains_step_5(in train : Train, in start : Segment, in middle : Segment, in end : Segment) {
141// frame->end = frame->middle->connected_to[i2];
142// if (frame->start != frame->end) {
143// ...
144// }
145// + OUTER FOR LOOP COUNTER INCREMENT
146 Train.location(train, start);
147 Segment.connectedTo(start, middle);
148 Segment.connectedTo(middle, end);
149}
150
151pattern closeTrains_step_6(in train : Train, in start : Segment, in middle : Segment, in end : Segment) {
152// frame->t2 = frame->end->train;
153// if (frame->t2 != 0) {
154// ...
155// }
156 Train.location(train, start);
157 Segment.connectedTo(start, middle);
158 Segment.connectedTo(middle, end);
159 start != end;
160}
161
162pattern closeTrains_step_7(in train : Train, in start : Segment, in middle : Segment, in end : Segment, in otherTrain : Train) {
163// results->matches[match_cntr].start = frame->start;
164// results->matches[match_cntr++].end = frame->end;
165 Train.location(train, start);
166 Segment.connectedTo(start, middle);
167 Segment.connectedTo(middle, end);
168 start != end;
169 Segment.occupiedBy(end, otherTrain);
170}
171
172//
173// trainLocations
174//
175
176pattern trainLocations_step_2(in train : Train) {
177// frame->train = model->trains[i0];
178// frame->location = frame->train->location;
179// if (frame->location != NULL) {
180// ...
181// }
182
183 Train(train);
184}
185
186pattern trainLocations_step_3(in train : Train, in location : Segment) {
187// results->matches[match_cntr].location = frame->location;
188// results->matches[match_cntr++].train = frame->train;
189 Train(train);
190 Train.location(train, location);
191}
192
193//
194// misalignedTurnout
195//
196
197pattern misalignedTurnout_step_2(in turnout : Turnout) {
198// frame->turnout = model->turnouts[i0];
199// frame->location = frame->turnout->straight;
200// if (frame->location != NULL) {
201// ...
202// }
203 Turnout(turnout);
204}
205
206pattern misalignedTurnout_step_3(in turnout : Turnout, in location : Segment) {
207// Segment *disconnected = ((Segment *)frame->turnout);
208// if (disconnected->connected_to[0] != frame->location &&
209// disconnected->connected_to[1] != frame->location) {
210// ...
211// }
212 Turnout(turnout);
213 Turnout.straight(turnout, location);
214}
215
216pattern misalignedTurnout_step_4(in turnout : Turnout, in location : Segment) {
217// frame->train = frame->location->train;
218// if (frame->train != NULL) {
219// ...
220// }
221 Turnout(turnout);
222 Turnout.straight(turnout, location);
223 neg find connectedSegmentsDirected(turnout, location);
224}
225
226pattern misalignedTurnout_step_5(in turnout : Turnout, in location : Segment, in train : Train) {
227// results->matches[match_cntr].start = frame->start;
228// results->matches[match_cntr++].end = frame->end;
229 Turnout(turnout);
230 Turnout.straight(turnout, location);
231 neg find connectedSegmentsDirected(turnout, location);
232 Segment.occupiedBy(location, train);
233}
234
235pattern connectedSegmentsDirected(s1 : Segment, s2 : Segment) {
236 Segment.connectedTo(s1, s2);
237}
238
239//
240// endOfSiding
241//
242
243pattern endOfSiding_step_2(in train : Train) {
244// frame->train = model->trains[i0];
245// frame->location = frame->train->location;
246// if (frame->location != NULL) {
247// ...
248// }
249
250 Train(train);
251}
252
253pattern endOfSiding_step_3(in train : Train, in location : Segment) {
254// int loop_bound1 = frame->location->connected_to_count;
255// for (int i1 = 0; i1 < loop_bound1; i1++) {
256// ...
257// }
258 Train(train);
259 Train.location(train, location);
260}
261
262pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
263// frame->end = frame->location->connected_to[i1];
264// if (frame->end != NULL &&
265// frame->end->connected_to[1] == frame->location &&
266// frame->end->connected_to[0] == NULL) {
267// ...
268// }
269// if (frame->end != NULL &&
270// frame->end->connected_to[0] == frame->location &&
271// frame->end->connected_to[1] == NULL) {
272// ...
273// }
274 Train(train);
275 Train.location(train, location);
276 Segment.connectedTo(location, end);
277}
278
279pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
280// results->matches[match_cntr].location = frame->location;
281// results->matches[match_cntr++].train = frame->train;
282// ...OR...
283// results->matches[match_cntr].location = frame->location;
284// results->matches[match_cntr++].train = frame->train;
285 Train(train);
286 Train.location(train, location);
287 Segment.connectedTo(location, end);
288 neg find multipleConnectedTo(end);
289}
290
291pattern multipleConnectedTo(s : Segment) {
292 Segment.connectedTo(s, n1);
293 Segment.connectedTo(s, n2);
294 n1 != n2;
295}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend
new file mode 100644
index 00000000..519a228a
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend
@@ -0,0 +1,201 @@
1package modes3.run
2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory
7import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch
8import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers
9import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint
10import java.util.Collection
11import java.util.Map
12import modes3.Modes3Package
13import modes3.queries.CloseTrains_step_2
14import modes3.queries.CloseTrains_step_3
15import modes3.queries.CloseTrains_step_4
16import modes3.queries.CloseTrains_step_5
17import modes3.queries.CloseTrains_step_6
18import modes3.queries.CloseTrains_step_7
19
20class CloseTrainsObjectiveHint extends CostObjectiveHint {
21 val Type segmentType
22 val Type trainType
23
24 new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) {
25 extension val Modes3Package = Modes3Package.eINSTANCE
26 segmentType = ecore2LogicTrace.TypeofEClass(segment)
27 trainType = ecore2LogicTrace.TypeofEClass(train)
28 }
29
30 override isExact() {
31 true
32 }
33
34 override createPolyhedronExtensionOperator(Map<String, CostElementMatchers> costElementMatchers) {
35 val step2 = costElementMatchers.get(CloseTrains_step_2.instance.fullyQualifiedName)
36 val step3 = costElementMatchers.get(CloseTrains_step_3.instance.fullyQualifiedName)
37 val step4 = costElementMatchers.get(CloseTrains_step_4.instance.fullyQualifiedName)
38 val step5 = costElementMatchers.get(CloseTrains_step_5.instance.fullyQualifiedName)
39 val step6 = costElementMatchers.get(CloseTrains_step_6.instance.fullyQualifiedName)
40 val step7 = costElementMatchers.get(CloseTrains_step_7.instance.fullyQualifiedName);
41
42 [
43 val objectiveBuilder = createBuilder
44
45 for (m : step2.matches) {
46 val dimension = getDimension(m.match)
47 objectiveBuilder.add(step2.weight, dimension)
48 dimension.tightenLowerBound(0)
49 if (m.multi) {
50 createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0)
51 } else {
52 dimension.tightenUpperBound(1)
53 if (m.must) {
54 dimension.tightenLowerBound(1)
55 }
56 }
57 }
58
59 val step3Matches = step3.matches
60 for (m : step3Matches) {
61 val dimension = getDimension(m.match)
62 objectiveBuilder.add(step3.weight, dimension)
63 dimension.tightenLowerBound(0)
64 if (!m.multi) {
65 dimension.tightenUpperBound(1)
66 if (m.must) {
67 dimension.tightenLowerBound(1)
68 }
69 }
70 }
71 for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) {
72 val multiplicityBuilder = createBuilder
73 for (m : pair.value) {
74 multiplicityBuilder.add(1, m.match)
75 }
76 multiplicityBuilder.add(-1, pair.key)
77 multiplicityBuilder.build.assertEqualsTo(0)
78 }
79 boundLimit(step3Matches, 2, trainType, 1)
80 boundLimit(step3Matches, 3, segmentType, 1)
81
82 val step4Matches = step4.matches
83 for (m : step4Matches) {
84 val dimension = getDimension(m.match)
85 objectiveBuilder.add(step4.weight, dimension)
86 dimension.tightenLowerBound(0)
87 if (!m.multi) {
88 dimension.tightenUpperBound(1)
89 if (m.must) {
90 dimension.tightenLowerBound(1)
91 }
92 }
93 }
94 for (pair : step4Matches.groupBy[step3.projectMayMatch(match, 2, 3)].entrySet) {
95 val multiplicityBuilder = createBuilder
96 for (m : pair.value) {
97 multiplicityBuilder.add(1, m.match)
98 }
99 multiplicityBuilder.add(-2, pair.key)
100 multiplicityBuilder.build.tightenUpperBound(0)
101 }
102 boundLimit(step4Matches, 2, trainType, 2)
103 boundLimit(step4Matches, 3, segmentType, 2)
104 boundLimit(step4Matches, 4, segmentType, 2)
105
106 val step5Matches = step5.matches
107 for (m : step5Matches) {
108 val dimension = getDimension(m.match)
109 objectiveBuilder.add(step5.weight, dimension)
110 dimension.tightenLowerBound(0)
111 if (!m.multi) {
112 dimension.tightenUpperBound(1)
113 if (m.must) {
114 dimension.tightenLowerBound(1)
115 }
116 }
117 }
118 for (pair : step5Matches.groupBy[step4.projectMayMatch(match, 2, 3, 4)].entrySet) {
119 val multiplicityBuilder = createBuilder
120 for (m : pair.value) {
121 multiplicityBuilder.add(1, m.match)
122 }
123 multiplicityBuilder.add(-2, pair.key)
124 multiplicityBuilder.build.tightenUpperBound(0)
125 }
126 boundLimit(step5Matches, 2, trainType, 4)
127 boundLimit(step5Matches, 3, segmentType, 4)
128 boundLimit(step5Matches, 4, segmentType, 4)
129 boundLimit(step5Matches, 5, segmentType, 4)
130
131 val step6Matches = step6.matches
132 for (m : step6Matches) {
133 val dimension = getDimension(m.match)
134 objectiveBuilder.add(step6.weight, dimension)
135 dimension.tightenLowerBound(0)
136 if (m.multi) {
137 if (m.match.get(3) == m.match.get(5)) {
138 createBuilder.add(2, m.match).add(-1, step5.projectMayMatch(m.match, 2, 3, 4, 5)).build.
139 assertEqualsTo(0)
140 } else {
141 createBuilder.add(1, m.match).add(-1, step5.projectMayMatch(m.match, 2, 3, 4, 5)).build.
142 assertEqualsTo(0)
143 }
144 } else {
145 dimension.tightenUpperBound(1)
146 if (m.must) {
147 dimension.tightenLowerBound(1)
148 }
149 }
150 }
151 boundLimit(step6Matches, 2, trainType, 2)
152 boundLimit(step6Matches, 3, segmentType, 2)
153 boundLimit(step6Matches, 4, segmentType, 2)
154 boundLimit(step6Matches, 5, segmentType, 2)
155
156 val step7Matches = step7.matches
157 for (m : step7Matches) {
158 val dimension = getDimension(m.match)
159 objectiveBuilder.add(step7.weight, dimension)
160 dimension.tightenLowerBound(0)
161 if (!m.multi) {
162 dimension.tightenUpperBound(1)
163 if (m.must) {
164 dimension.tightenLowerBound(1)
165 }
166 }
167 }
168 for (pair : step7Matches.groupBy[step6.projectMayMatch(match, 2, 3, 4, 5)].entrySet) {
169 val multiplicityBuilder = createBuilder
170 for (m : pair.value) {
171 multiplicityBuilder.add(1, m.match)
172 }
173 multiplicityBuilder.add(-1, pair.key)
174 multiplicityBuilder.build.tightenUpperBound(0)
175 }
176 boundLimit(step7Matches, 2, trainType, 2)
177 boundLimit(step7Matches, 3, segmentType, 2)
178 boundLimit(step7Matches, 4, segmentType, 2)
179 boundLimit(step7Matches, 5, segmentType, 2)
180 boundLimit(step7Matches, 6, trainType, 2)
181
182 objectiveBuilder.buildWithBounds
183 ]
184 }
185
186 private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory,
187 Collection<CostElementMatch> matches, int index, Type type, int count) {
188 for (pair : matches.groupBy[match.get(index)].entrySet) {
189 val multiplicityBuilder = createBuilder
190 for (m : pair.value) {
191 multiplicityBuilder.add(1, m.match)
192 }
193 if (CostElementMatchers.isMulti(pair.key)) {
194 multiplicityBuilder.add(-count, type)
195 multiplicityBuilder.build.tightenUpperBound(0)
196 } else {
197 multiplicityBuilder.build.tightenUpperBound(count)
198 }
199 }
200 }
201}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend
new file mode 100644
index 00000000..f7e23a57
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend
@@ -0,0 +1,139 @@
1package modes3.run
2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory
7import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch
8import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers
9import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint
10import java.util.Collection
11import java.util.Map
12import modes3.Modes3Package
13import modes3.queries.EndOfSiding_step_2
14import modes3.queries.EndOfSiding_step_3
15import modes3.queries.EndOfSiding_step_4
16import modes3.queries.EndOfSiding_step_5
17
18class EndOfSidingObjectiveHint extends CostObjectiveHint {
19 val Type segmentType
20 val Type trainType
21
22 new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) {
23 extension val Modes3Package = Modes3Package.eINSTANCE
24 segmentType = ecore2LogicTrace.TypeofEClass(segment)
25 trainType = ecore2LogicTrace.TypeofEClass(train)
26 }
27
28 override isExact() {
29 true
30// false
31 }
32
33 override createPolyhedronExtensionOperator(Map<String, CostElementMatchers> costElementMatchers) {
34 val step2 = costElementMatchers.get(EndOfSiding_step_2.instance.fullyQualifiedName)
35 val step3 = costElementMatchers.get(EndOfSiding_step_3.instance.fullyQualifiedName)
36 val step4 = costElementMatchers.get(EndOfSiding_step_4.instance.fullyQualifiedName)
37 val step5 = costElementMatchers.get(EndOfSiding_step_5.instance.fullyQualifiedName);
38
39 [
40 val objectiveBuilder = createBuilder
41
42 for (m : step2.matches) {
43 val dimension = getDimension(m.match)
44 objectiveBuilder.add(step2.weight, dimension)
45 dimension.tightenLowerBound(0)
46 if (m.multi) {
47 createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0)
48 } else {
49 dimension.tightenUpperBound(1)
50 if (m.must) {
51 dimension.tightenLowerBound(1)
52 }
53 }
54 }
55
56 val step3Matches = step3.matches
57 for (m : step3Matches) {
58 val dimension = getDimension(m.match)
59 objectiveBuilder.add(step3.weight, dimension)
60 dimension.tightenLowerBound(0)
61 if (!m.multi) {
62 dimension.tightenUpperBound(1)
63 if (m.must) {
64 dimension.tightenLowerBound(1)
65 }
66 }
67 }
68 for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) {
69 val multiplicityBuilder = createBuilder
70 for (m : pair.value) {
71 multiplicityBuilder.add(1, m.match)
72 }
73 multiplicityBuilder.add(-1, pair.key)
74 multiplicityBuilder.build.assertEqualsTo(0)
75 }
76 boundLimit(step3Matches, 2, trainType, 1)
77 boundLimit(step3Matches, 3, segmentType, 1)
78
79 val step4Matches = step4.matches
80 for (m : step4Matches) {
81 val dimension = getDimension(m.match)
82 objectiveBuilder.add(step4.weight, dimension)
83 dimension.tightenLowerBound(0)
84 if (!m.multi) {
85 dimension.tightenUpperBound(1)
86 if (m.must) {
87 dimension.tightenLowerBound(1)
88 }
89 }
90 }
91 for (pair : step4Matches.groupBy[step3.projectMayMatch(match, 2, 3)].entrySet) {
92 val multiplicityBuilder = createBuilder
93 for (m : pair.value) {
94 multiplicityBuilder.add(1, m.match)
95 }
96 multiplicityBuilder.add(-2, pair.key)
97 multiplicityBuilder.build.tightenUpperBound(0)
98 }
99 boundLimit(step4Matches, 2, trainType, 2)
100 boundLimit(step4Matches, 3, segmentType, 2)
101 boundLimit(step4Matches, 4, segmentType, 2)
102
103 val step5Matches = step5.matches
104 for (m : step5Matches) {
105 val dimension = getDimension(m.match)
106 objectiveBuilder.add(step5.weight, dimension)
107 dimension.tightenLowerBound(0)
108 if (!m.multi) {
109 dimension.tightenUpperBound(1)
110 if (m.must) {
111 dimension.tightenLowerBound(1)
112 }
113 }
114 createBuilder.add(1, m.match).add(-1, step4.projectMayMatch(m.match, 2, 3, 4)).build.tightenUpperBound(0)
115 }
116 boundLimit(step5Matches, 2, trainType, 1)
117 boundLimit(step5Matches, 3, segmentType, 2)
118 boundLimit(step5Matches, 4, segmentType, 1)
119
120 objectiveBuilder.buildWithBounds
121 ]
122 }
123
124 private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory,
125 Collection<CostElementMatch> matches, int index, Type type, int count) {
126 for (pair : matches.groupBy[match.get(index)].entrySet) {
127 val multiplicityBuilder = createBuilder
128 for (m : pair.value) {
129 multiplicityBuilder.add(1, m.match)
130 }
131 if (CostElementMatchers.isMulti(pair.key)) {
132 multiplicityBuilder.add(-count, type)
133 multiplicityBuilder.build.tightenUpperBound(0)
134 } else {
135 multiplicityBuilder.build.tightenUpperBound(count)
136 }
137 }
138 }
139} \ No newline at end of file
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend
new file mode 100644
index 00000000..cb014dea
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend
@@ -0,0 +1,140 @@
1package modes3.run
2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory
7import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch
8import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers
9import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint
10import java.util.Collection
11import java.util.Map
12import modes3.Modes3Package
13import modes3.queries.MisalignedTurnout_step_2
14import modes3.queries.MisalignedTurnout_step_3
15import modes3.queries.MisalignedTurnout_step_4
16import modes3.queries.MisalignedTurnout_step_5
17
18class MisalignedTurnoutObjectiveHint extends CostObjectiveHint {
19 val Type segmentType
20 val Type turnoutType
21 val Type trainType
22
23 new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) {
24 extension val Modes3Package = Modes3Package.eINSTANCE
25 segmentType = ecore2LogicTrace.TypeofEClass(segment)
26 turnoutType = ecore2LogicTrace.TypeofEClass(turnout)
27 trainType = ecore2LogicTrace.TypeofEClass(train)
28 }
29
30 override isExact() {
31 true
32// false
33 }
34
35 override createPolyhedronExtensionOperator(Map<String, CostElementMatchers> costElementMatchers) {
36 val step2 = costElementMatchers.get(MisalignedTurnout_step_2.instance.fullyQualifiedName)
37 val step3 = costElementMatchers.get(MisalignedTurnout_step_3.instance.fullyQualifiedName)
38 val step4 = costElementMatchers.get(MisalignedTurnout_step_4.instance.fullyQualifiedName)
39 val step5 = costElementMatchers.get(MisalignedTurnout_step_5.instance.fullyQualifiedName);
40
41 [
42 val objectiveBuilder = createBuilder
43
44 for (m : step2.matches) {
45 val dimension = getDimension(m.match)
46 objectiveBuilder.add(step2.weight, dimension)
47 dimension.tightenLowerBound(0)
48 if (m.multi) {
49 createBuilder.add(1, dimension).add(-1, turnoutType).build.assertEqualsTo(0)
50 } else {
51 dimension.tightenUpperBound(1)
52 if (m.must) {
53 dimension.tightenLowerBound(1)
54 }
55 }
56 }
57
58 val step3Matches = step3.matches
59 for (m : step3Matches) {
60 val dimension = getDimension(m.match)
61 objectiveBuilder.add(step3.weight, dimension)
62 dimension.tightenLowerBound(0)
63 if (!m.multi) {
64 dimension.tightenUpperBound(1)
65 if (m.must) {
66 dimension.tightenLowerBound(1)
67 }
68 }
69 }
70 for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) {
71 val multiplicityBuilder = createBuilder
72 for (m : pair.value) {
73 multiplicityBuilder.add(1, m.match)
74 }
75 multiplicityBuilder.add(-1, pair.key)
76 multiplicityBuilder.build.tightenUpperBound(0)
77 }
78 boundLimit(step3Matches, 2, turnoutType, 1)
79 boundLimit(step3Matches, 3, segmentType, 2)
80
81 val step4Matches = step4.matches
82 for (m : step4Matches) {
83 val dimension = getDimension(m.match)
84 objectiveBuilder.add(step4.weight, dimension)
85 dimension.tightenLowerBound(0)
86 if (!m.multi) {
87 dimension.tightenUpperBound(1)
88 if (m.must) {
89 dimension.tightenLowerBound(1)
90 }
91 }
92 createBuilder.add(1, m.match).add(-1, step3.projectMayMatch(m.match, 2, 3)).build.tightenUpperBound(0)
93 }
94 boundLimit(step4Matches, 2, turnoutType, 1)
95 boundLimit(step4Matches, 3, segmentType, 2)
96
97 val step5Matches = step5.matches
98 for (m : step5Matches) {
99 val dimension = getDimension(m.match)
100 objectiveBuilder.add(step5.weight, dimension)
101 dimension.tightenLowerBound(0)
102 if (!m.multi) {
103 dimension.tightenUpperBound(1)
104 if (m.must) {
105 dimension.tightenLowerBound(1)
106 }
107 }
108 }
109 for (pair : step5Matches.groupBy[step4.projectMayMatch(match, 2, 3)].entrySet) {
110 val multiplicityBuilder = createBuilder
111 for (m : pair.value) {
112 multiplicityBuilder.add(1, m.match)
113 }
114 multiplicityBuilder.add(-1, pair.key)
115 multiplicityBuilder.build.tightenUpperBound(0)
116 }
117 boundLimit(step5Matches, 2, turnoutType, 1)
118 boundLimit(step5Matches, 3, segmentType, 2)
119 boundLimit(step5Matches, 4, trainType, 2)
120
121 objectiveBuilder.buildWithBounds
122 ]
123 }
124
125 private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory,
126 Collection<CostElementMatch> matches, int index, Type type, int count) {
127 for (pair : matches.groupBy[match.get(index)].entrySet) {
128 val multiplicityBuilder = createBuilder
129 for (m : pair.value) {
130 multiplicityBuilder.add(1, m.match)
131 }
132 if (CostElementMatchers.isMulti(pair.key)) {
133 multiplicityBuilder.add(-count, type)
134 multiplicityBuilder.build.tightenUpperBound(0)
135 } else {
136 multiplicityBuilder.build.tightenUpperBound(count)
137 }
138 }
139 }
140}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend
index fac7c496..613cb3e4 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/Modes3ModelGenerator.xtend
@@ -5,6 +5,7 @@ import com.google.common.collect.ImmutableSet
5import hu.bme.mit.inf.dslreasoner.ecore2logic.EReferenceMapper_RelationsOverTypes_Trace 5import hu.bme.mit.inf.dslreasoner.ecore2logic.EReferenceMapper_RelationsOverTypes_Trace
6import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic 6import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
7import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration 7import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration
8import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
8import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor 9import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor
9import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsFactory 10import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsFactory
10import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage 11import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage
@@ -14,6 +15,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage
14import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition 15import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition
15import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage 16import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage
16import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult 17import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult
18import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore
17import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic 19import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic
18import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration 20import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration
19import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor 21import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor
@@ -25,18 +27,38 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePro
25import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic 27import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic
26import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink 28import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink
27import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation 29import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation
28import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
29import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage 30import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage
30import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml 31import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml
32import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration
33import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration
31import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy 34import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy
32import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner 35import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner
33import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration 36import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration
37import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation
38import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind
39import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold
34import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser 40import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser
35import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace 41import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace
36import java.util.List 42import java.util.List
37import modes3.Modes3Factory 43import modes3.Modes3Factory
38import modes3.Modes3Package 44import modes3.Modes3Package
45import modes3.queries.CloseTrains_step_2
46import modes3.queries.CloseTrains_step_3
47import modes3.queries.CloseTrains_step_4
48import modes3.queries.CloseTrains_step_5
49import modes3.queries.CloseTrains_step_6
50import modes3.queries.CloseTrains_step_7
51import modes3.queries.EndOfSiding_step_2
52import modes3.queries.EndOfSiding_step_3
53import modes3.queries.EndOfSiding_step_4
54import modes3.queries.EndOfSiding_step_5
55import modes3.queries.MisalignedTurnout_step_2
56import modes3.queries.MisalignedTurnout_step_3
57import modes3.queries.MisalignedTurnout_step_4
58import modes3.queries.MisalignedTurnout_step_5
39import modes3.queries.Modes3Queries 59import modes3.queries.Modes3Queries
60import modes3.queries.TrainLocations_step_2
61import modes3.queries.TrainLocations_step_3
40import org.eclipse.emf.ecore.EClass 62import org.eclipse.emf.ecore.EClass
41import org.eclipse.emf.ecore.EObject 63import org.eclipse.emf.ecore.EObject
42import org.eclipse.emf.ecore.resource.Resource 64import org.eclipse.emf.ecore.resource.Resource
@@ -92,17 +114,21 @@ class Modes3ModelGenerator {
92 minNewElements = modelSize 114 minNewElements = modelSize
93 maxNewElements = modelSize 115 maxNewElements = modelSize
94 minNewElementsByType => [ 116 minNewElementsByType => [
95// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) 117// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), modelSize / 5)
118// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), modelSize / 5)
119// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.simpleSegment), 3 * modelSize / 5)
96 ] 120 ]
97 maxNewElementsByType => [ 121 maxNewElementsByType => [
98 put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), 5) 122 put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), modelSize / 5)
99 put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) 123 put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), modelSize / 5)
124 put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.simpleSegment), 3 * modelSize / 5)
100 ] 125 ]
101 ] 126 ]
102 solutionScope => [ 127 solutionScope => [
103 numberOfRequiredSolutions = 1 128 numberOfRequiredSolutions = 1
104 ] 129 ]
105 scopeWeight = 5 130 costObjectives += getObjective(ecore2Logic, metamodelLogic.trace)
131 scopeWeight = 6
106 nameNewElements = false 132 nameNewElements = false
107 typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis 133 typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis
108 stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood 134 stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood
@@ -121,47 +147,60 @@ class Modes3ModelGenerator {
121 val solution = solver.solve(logic.output, config, workspace) 147 val solution = solver.solve(logic.output, config, workspace)
122 if (solution instanceof ModelResult) { 148 if (solution instanceof ModelResult) {
123 println("Saving generated solutions") 149 println("Saving generated solutions")
124 val representations = solution.representation 150 val logic2Ecore = new Logic2Ecore(ecore2Logic)
125 for (representationIndex : 0 ..< representations.size) { 151 val interpretations = solver.getInterpretations(solution)
126 val representation = representations.get(representationIndex) 152 for (representationIndex : 0 ..< interpretations.size) {
153 val interpretation = interpretations.get(representationIndex)
127 val representationNumber = representationIndex + 1 154 val representationNumber = representationIndex + 1
128 if (representation instanceof PartialInterpretation) { 155 if (interpretation instanceof PartialModelAsLogicInterpretation) {
156 val representation = interpretation.partialInterpretation
129 workspace.writeModel(representation, '''solution«representationNumber».partialinterpretation''') 157 workspace.writeModel(representation, '''solution«representationNumber».partialinterpretation''')
130 val partialInterpretation2GML = new PartialInterpretation2Gml 158 val partialInterpretation2GML = new PartialInterpretation2Gml
131 val gml = partialInterpretation2GML.transform(representation) 159 val gml = partialInterpretation2GML.transform(representation)
132 workspace.writeText('''solution«representationNumber».gml''', gml) 160 workspace.writeText('''solution«representationNumber».gml''', gml)
161 val model = logic2Ecore.transformInterpretation(interpretation, metamodelLogic.trace)
162 val iterator = model.eAllContents
163 var int id = 0
164 while (iterator.hasNext) {
165 val obj = iterator.next
166 val idFeature = obj.eClass.EAllAttributes.findFirst[name == 'id']
167 if (idFeature !== null) {
168 obj.eSet(idFeature, id)
169 id++
170 }
171 }
172 workspace.writeModel(model, '''solution«representationNumber».modes3''')
133 if (representation.newElements.size < 160) { 173 if (representation.newElements.size < 160) {
134 if (representation instanceof PartialInterpretation) { 174 val rootType = (representation.problem.types.findFirst [
135 val rootType = (representation.problem.types.findFirst [ 175 name == "Modes3ModelRoot class DefinedPart"
136 name == "Modes3ModelRoot class DefinedPart" 176 ] as TypeDefinition)
137 ] as TypeDefinition) 177 val rootIntepretation = representation.partialtypeinterpratation.filter(
138 val rootIntepretation = representation.partialtypeinterpratation.filter( 178 PartialComplexTypeInterpretation).findFirst [
139 PartialComplexTypeInterpretation).findFirst [ 179 interpretationOf.name == "Modes3ModelRoot class"
140 interpretationOf.name == "Modes3ModelRoot class" 180 ]
181 rootIntepretation.elements.removeAll(rootType.elements)
182 representation.problem.elements.removeAll(rootType.elements)
183 for (relationInterpretation : representation.partialrelationinterpretation) {
184 relationInterpretation.relationlinks.removeIf [ link |
185 if (link instanceof BinaryElementRelationLink) {
186 rootType.elements.contains(link.param1) ||
187 rootType.elements.contains(link.param2)
188 } else {
189 false
190 }
141 ] 191 ]
142 rootIntepretation.elements.removeAll(rootType.elements)
143 representation.problem.elements.removeAll(rootType.elements)
144 for (relationInterpretation : representation.partialrelationinterpretation) {
145 relationInterpretation.relationlinks.removeIf [ link |
146 if (link instanceof BinaryElementRelationLink) {
147 rootType.elements.contains(link.param1) || rootType.elements.contains(link.param2)
148 } else {
149 false
150 }
151 ]
152 }
153 rootType.elements.clear
154 } 192 }
193 rootType.elements.clear
155 val visualiser = new GraphvizVisualiser 194 val visualiser = new GraphvizVisualiser
156 val visualisation = visualiser.visualiseConcretization(representation) 195 val visualisation = visualiser.visualiseConcretization(representation)
157 visualisation.writeToFile(workspace, '''solution«representationNumber».png''') 196 visualisation.writeToFile(workspace, '''solution«representationNumber».png''')
158 } 197 }
159 } else { 198 } else {
160 workspace.writeText('''solution«representationNumber».txt''', representation.toString) 199 workspace.writeText('''solution«representationNumber».txt''', interpretation.toString)
161 } 200 }
162 } 201 }
163 } else { 202 } else {
164 println("Failed to solver problem") 203 println("Failed to solve problem")
165 val partial = logic.output 204 val partial = logic.output
166 workspace.writeModel(partial, "solution.partialinterpretation") 205 workspace.writeModel(partial, "solution.partialinterpretation")
167 } 206 }
@@ -198,6 +237,94 @@ class Modes3ModelGenerator {
198 ) 237 )
199 } 238 }
200 239
240 def getObjective(Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) {
241 new CostObjectiveConfiguration => [
242 switch (monitoringQuery) {
243 case closeTrains: {
244 elements += new CostObjectiveElementConfiguration => [
245 patternQualifiedName = CloseTrains_step_2.instance.fullyQualifiedName
246 weight = 14 + 53 + 11
247 ]
248 elements += new CostObjectiveElementConfiguration => [
249 patternQualifiedName = CloseTrains_step_3.instance.fullyQualifiedName
250 weight = 21 + 14
251 ]
252 elements += new CostObjectiveElementConfiguration => [
253 patternQualifiedName = CloseTrains_step_4.instance.fullyQualifiedName
254 weight = 14 + 44 + 14 + 9
255 ]
256 elements += new CostObjectiveElementConfiguration => [
257 patternQualifiedName = CloseTrains_step_5.instance.fullyQualifiedName
258 weight = 14 + 41 + 11
259 ]
260 elements += new CostObjectiveElementConfiguration => [
261 patternQualifiedName = CloseTrains_step_6.instance.fullyQualifiedName
262 weight = 27
263 ]
264 elements += new CostObjectiveElementConfiguration => [
265 patternQualifiedName = CloseTrains_step_7.instance.fullyQualifiedName
266 weight = 48
267 ]
268 hint = new CloseTrainsObjectiveHint(ecore2Logic, ecore2LogicTrace)
269 }
270 case trainLocations: {
271 elements += new CostObjectiveElementConfiguration => [
272 patternQualifiedName = TrainLocations_step_2.instance.fullyQualifiedName
273 weight = 14 + 53 + 11
274 ]
275 elements += new CostObjectiveElementConfiguration => [
276 patternQualifiedName = TrainLocations_step_3.instance.fullyQualifiedName
277 weight = 48
278 ]
279 hint = new TrainLocationsObjectiveHint(ecore2Logic, ecore2LogicTrace)
280 }
281 case misalignedTurnout: {
282 elements += new CostObjectiveElementConfiguration => [
283 patternQualifiedName = MisalignedTurnout_step_2.instance.fullyQualifiedName
284 weight = 14 + 53 + 11
285 ]
286 elements += new CostObjectiveElementConfiguration => [
287 patternQualifiedName = MisalignedTurnout_step_3.instance.fullyQualifiedName
288 weight = 108
289 ]
290 elements += new CostObjectiveElementConfiguration => [
291 patternQualifiedName = MisalignedTurnout_step_4.instance.fullyQualifiedName
292 weight = 27
293 ]
294 elements += new CostObjectiveElementConfiguration => [
295 patternQualifiedName = MisalignedTurnout_step_5.instance.fullyQualifiedName
296 weight = 48
297 ]
298 hint = new MisalignedTurnoutObjectiveHint(ecore2Logic, ecore2LogicTrace)
299 }
300 case endOfSiding: {
301 elements += new CostObjectiveElementConfiguration => [
302 patternQualifiedName = EndOfSiding_step_2.instance.fullyQualifiedName
303 weight = 14 + 53 + 11
304 ]
305 elements += new CostObjectiveElementConfiguration => [
306 patternQualifiedName = EndOfSiding_step_3.instance.fullyQualifiedName
307 weight = 21 + 14
308 ]
309 elements += new CostObjectiveElementConfiguration => [
310 patternQualifiedName = EndOfSiding_step_4.instance.fullyQualifiedName
311 weight = 14 + 35 + 21 + 15 + 14 + 21 + 15 + 11
312 ]
313 elements += new CostObjectiveElementConfiguration => [
314 patternQualifiedName = EndOfSiding_step_5.instance.fullyQualifiedName
315 weight = 48
316 ]
317 hint = new EndOfSidingObjectiveHint(ecore2Logic, ecore2LogicTrace)
318 }
319 default:
320 throw new IllegalArgumentException("Unknown monitoring query: " + monitoringQuery)
321 }
322 kind = ObjectiveKind.HIGHER_IS_BETTER
323 threshold = ObjectiveThreshold.NO_THRESHOLD
324 findExtremum = true
325 ]
326 }
327
201 def static init() { 328 def static init() {
202 EMFPatternLanguageStandaloneSetup.doSetup 329 EMFPatternLanguageStandaloneSetup.doSetup
203 ViatraQueryEngineOptions.setSystemDefaultBackends(ReteBackendFactory.INSTANCE, ReteBackendFactory.INSTANCE, 330 ViatraQueryEngineOptions.setSystemDefaultBackends(ReteBackendFactory.INSTANCE, ReteBackendFactory.INSTANCE,
@@ -223,6 +350,8 @@ class Modes3ModelGenerator {
223 350
224 private static enum MonitoringQuery { 351 private static enum MonitoringQuery {
225 closeTrains, 352 closeTrains,
353 trainLocations,
354 endOfSiding,
226 misalignedTurnout 355 misalignedTurnout
227 } 356 }
228} 357}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend
new file mode 100644
index 00000000..cc2d7925
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend
@@ -0,0 +1,85 @@
1package modes3.run
2
3import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory
7import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch
8import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers
9import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint
10import java.util.Collection
11import java.util.Map
12import modes3.Modes3Package
13import modes3.queries.TrainLocations_step_2
14import modes3.queries.TrainLocations_step_3
15
16class TrainLocationsObjectiveHint extends CostObjectiveHint {
17 val Type segmentType
18 val Type trainType
19
20 new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) {
21 extension val Modes3Package = Modes3Package.eINSTANCE
22 segmentType = ecore2LogicTrace.TypeofEClass(segment)
23 trainType = ecore2LogicTrace.TypeofEClass(train)
24 }
25
26 override isExact() {
27 true
28 }
29
30 override createPolyhedronExtensionOperator(Map<String, CostElementMatchers> costElementMatchers) {
31 val step2 = costElementMatchers.get(TrainLocations_step_2.instance.fullyQualifiedName)
32 val step3 = costElementMatchers.get(TrainLocations_step_3.instance.fullyQualifiedName);
33
34 [
35 val objectiveBuilder = createBuilder
36
37 for (m : step2.matches) {
38 val dimension = getDimension(m.match)
39 objectiveBuilder.add(step2.weight, dimension)
40 dimension.tightenLowerBound(0)
41 if (m.multi) {
42 createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0)
43 } else {
44 dimension.tightenUpperBound(1)
45 if (m.must) {
46 dimension.tightenLowerBound(1)
47 }
48 }
49 }
50
51 val step3Matches = step3.matches
52 for (m : step3Matches) {
53 val dimension = getDimension(m.match)
54 objectiveBuilder.add(step3.weight, dimension)
55 dimension.tightenLowerBound(0)
56 if (!m.multi) {
57 dimension.tightenUpperBound(1)
58 if (m.must) {
59 dimension.tightenLowerBound(1)
60 }
61 }
62 }
63 boundLimit(step3Matches, 2, trainType, 1)
64 boundLimit(step3Matches, 3, segmentType, 1)
65
66 objectiveBuilder.buildWithBounds
67 ]
68 }
69
70 private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory,
71 Collection<CostElementMatch> matches, int index, Type type, int count) {
72 for (pair : matches.groupBy[match.get(index)].entrySet) {
73 val multiplicityBuilder = createBuilder
74 for (m : pair.value) {
75 multiplicityBuilder.add(1, m.match)
76 }
77 if (CostElementMatchers.isMulti(pair.key)) {
78 multiplicityBuilder.add(-count, type)
79 multiplicityBuilder.build.tightenUpperBound(0)
80 } else {
81 multiplicityBuilder.build.tightenUpperBound(count)
82 }
83 }
84 }
85} \ No newline at end of file
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore
index b3e38571..a84c2906 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/.gitignore
@@ -31,3 +31,48 @@
31/.TooManyNonStraightInputsOfTurnout.java._trace 31/.TooManyNonStraightInputsOfTurnout.java._trace
32/.InputsOfTurnout.java._trace 32/.InputsOfTurnout.java._trace
33/.TooFewInputsOfTurnout.java._trace 33/.TooFewInputsOfTurnout.java._trace
34/.CloseTrains_step_2.java._trace
35/.CloseTrains_step_3.java._trace
36/.CloseTrains_step_4.java._trace
37/.CloseTrains_step_5.java._trace
38/.CloseTrains_step_6.java._trace
39/.CloseTrains_step_7.java._trace
40/.MisalignedTurnout_step_2.java._trace
41/.MisalignedTurnout_step_3.java._trace
42/.MisalignedTurnout_step_4.java._trace
43/.MisalignedTurnout_step_5.java._trace
44/.ConnectedSegmentsDirected.java._trace
45/Adjacent.java
46/CloseTrains_step_2.java
47/CloseTrains_step_3.java
48/CloseTrains_step_4.java
49/CloseTrains_step_5.java
50/CloseTrains_step_6.java
51/CloseTrains_step_7.java
52/ConnectedSegmentsDirected.java
53/ConnectedTo.java
54/ConnectedToNotSymmetric.java
55/ConnectedToReflexive.java
56/InputsOfTurnout.java
57/MisalignedTurnout_step_2.java
58/MisalignedTurnout_step_3.java
59/MisalignedTurnout_step_4.java
60/MisalignedTurnout_step_5.java
61/Modes3Queries.java
62/Output.java
63/OutputReflexive.java
64/Reachable.java
65/TooFewInputsOfTurnout.java
66/TooManyInputsOfSegment.java
67/TooManyInputsOfTurnout.java
68/TurnoutConnectedToBothOutputs.java
69/TurnoutOutput.java
70/TurnoutOutputsAreSame.java
71/Unreachable.java
72/.TrainLocations_step_2.java._trace
73/.TrainLocations_step_3.java._trace
74/.EndOfSiding_step_2.java._trace
75/.EndOfSiding_step_3.java._trace
76/.EndOfSiding_step_4.java._trace
77/.EndOfSiding_step_5.java._trace
78/.MultipleConnectedTo.java._trace
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java
new file mode 100644
index 00000000..a8f68dca
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java
@@ -0,0 +1,564 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Train;
17import org.apache.log4j.Logger;
18import org.eclipse.emf.ecore.EClass;
19import org.eclipse.viatra.query.runtime.api.IPatternMatch;
20import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
21import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
22import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
23import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
24import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
25import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
26import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
27import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
28import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
29import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
30import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
31import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
32import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
33import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
34import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
35import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
36import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
37import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
38
39/**
40 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
41 *
42 * <p>Original source:
43 * <code><pre>
44 * //
45 * // endOfSiding
46 * //
47 *
48 * pattern endOfSiding_step_2(in train : Train) {
49 * // frame-{@literal >}train = model-{@literal >}trains[i0];
50 * // frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
51 * // if (frame-{@literal >}location != NULL) {
52 * // ...
53 * // }
54 *
55 * Train(train);
56 * }
57 * </pre></code>
58 *
59 * @see Matcher
60 * @see Match
61 *
62 */
63@SuppressWarnings("all")
64public final class EndOfSiding_step_2 extends BaseGeneratedEMFQuerySpecification<EndOfSiding_step_2.Matcher> {
65 /**
66 * Pattern-specific match representation of the modes3.queries.endOfSiding_step_2 pattern,
67 * to be used in conjunction with {@link Matcher}.
68 *
69 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
70 * Each instance is a (possibly partial) substitution of pattern parameters,
71 * usable to represent a match of the pattern in the result of a query,
72 * or to specify the bound (fixed) input parameters when issuing a query.
73 *
74 * @see Matcher
75 *
76 */
77 public static abstract class Match extends BasePatternMatch {
78 private Train fTrain;
79
80 private static List<String> parameterNames = makeImmutableList("train");
81
82 private Match(final Train pTrain) {
83 this.fTrain = pTrain;
84 }
85
86 @Override
87 public Object get(final String parameterName) {
88 switch(parameterName) {
89 case "train": return this.fTrain;
90 default: return null;
91 }
92 }
93
94 @Override
95 public Object get(final int index) {
96 switch(index) {
97 case 0: return this.fTrain;
98 default: return null;
99 }
100 }
101
102 public Train getTrain() {
103 return this.fTrain;
104 }
105
106 @Override
107 public boolean set(final String parameterName, final Object newValue) {
108 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
109 if ("train".equals(parameterName) ) {
110 this.fTrain = (Train) newValue;
111 return true;
112 }
113 return false;
114 }
115
116 public void setTrain(final Train pTrain) {
117 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
118 this.fTrain = pTrain;
119 }
120
121 @Override
122 public String patternName() {
123 return "modes3.queries.endOfSiding_step_2";
124 }
125
126 @Override
127 public List<String> parameterNames() {
128 return EndOfSiding_step_2.Match.parameterNames;
129 }
130
131 @Override
132 public Object[] toArray() {
133 return new Object[]{fTrain};
134 }
135
136 @Override
137 public EndOfSiding_step_2.Match toImmutable() {
138 return isMutable() ? newMatch(fTrain) : this;
139 }
140
141 @Override
142 public String prettyPrint() {
143 StringBuilder result = new StringBuilder();
144 result.append("\"train\"=" + prettyPrintValue(fTrain));
145 return result.toString();
146 }
147
148 @Override
149 public int hashCode() {
150 return Objects.hash(fTrain);
151 }
152
153 @Override
154 public boolean equals(final Object obj) {
155 if (this == obj)
156 return true;
157 if (obj == null) {
158 return false;
159 }
160 if ((obj instanceof EndOfSiding_step_2.Match)) {
161 EndOfSiding_step_2.Match other = (EndOfSiding_step_2.Match) obj;
162 return Objects.equals(fTrain, other.fTrain);
163 } else {
164 // this should be infrequent
165 if (!(obj instanceof IPatternMatch)) {
166 return false;
167 }
168 IPatternMatch otherSig = (IPatternMatch) obj;
169 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
170 }
171 }
172
173 @Override
174 public EndOfSiding_step_2 specification() {
175 return EndOfSiding_step_2.instance();
176 }
177
178 /**
179 * Returns an empty, mutable match.
180 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
181 *
182 * @return the empty match.
183 *
184 */
185 public static EndOfSiding_step_2.Match newEmptyMatch() {
186 return new Mutable(null);
187 }
188
189 /**
190 * Returns a mutable (partial) match.
191 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
192 *
193 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
194 * @return the new, mutable (partial) match object.
195 *
196 */
197 public static EndOfSiding_step_2.Match newMutableMatch(final Train pTrain) {
198 return new Mutable(pTrain);
199 }
200
201 /**
202 * Returns a new (partial) match.
203 * This can be used e.g. to call the matcher with a partial match.
204 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
205 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
206 * @return the (partial) match object.
207 *
208 */
209 public static EndOfSiding_step_2.Match newMatch(final Train pTrain) {
210 return new Immutable(pTrain);
211 }
212
213 private static final class Mutable extends EndOfSiding_step_2.Match {
214 Mutable(final Train pTrain) {
215 super(pTrain);
216 }
217
218 @Override
219 public boolean isMutable() {
220 return true;
221 }
222 }
223
224 private static final class Immutable extends EndOfSiding_step_2.Match {
225 Immutable(final Train pTrain) {
226 super(pTrain);
227 }
228
229 @Override
230 public boolean isMutable() {
231 return false;
232 }
233 }
234 }
235
236 /**
237 * Generated pattern matcher API of the modes3.queries.endOfSiding_step_2 pattern,
238 * providing pattern-specific query methods.
239 *
240 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
241 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
242 *
243 * <p>Matches of the pattern will be represented as {@link Match}.
244 *
245 * <p>Original source:
246 * <code><pre>
247 * //
248 * // endOfSiding
249 * //
250 *
251 * pattern endOfSiding_step_2(in train : Train) {
252 * // frame-{@literal >}train = model-{@literal >}trains[i0];
253 * // frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
254 * // if (frame-{@literal >}location != NULL) {
255 * // ...
256 * // }
257 *
258 * Train(train);
259 * }
260 * </pre></code>
261 *
262 * @see Match
263 * @see EndOfSiding_step_2
264 *
265 */
266 public static class Matcher extends BaseMatcher<EndOfSiding_step_2.Match> {
267 /**
268 * Initializes the pattern matcher within an existing VIATRA Query engine.
269 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
270 *
271 * @param engine the existing VIATRA Query engine in which this matcher will be created.
272 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
273 *
274 */
275 public static EndOfSiding_step_2.Matcher on(final ViatraQueryEngine engine) {
276 // check if matcher already exists
277 Matcher matcher = engine.getExistingMatcher(querySpecification());
278 if (matcher == null) {
279 matcher = (Matcher)engine.getMatcher(querySpecification());
280 }
281 return matcher;
282 }
283
284 /**
285 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
286 * @return an initialized matcher
287 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
288 *
289 */
290 public static EndOfSiding_step_2.Matcher create() {
291 return new Matcher();
292 }
293
294 private static final int POSITION_TRAIN = 0;
295
296 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_2.Matcher.class);
297
298 /**
299 * Initializes the pattern matcher within an existing VIATRA Query engine.
300 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
301 *
302 * @param engine the existing VIATRA Query engine in which this matcher will be created.
303 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
304 *
305 */
306 private Matcher() {
307 super(querySpecification());
308 }
309
310 /**
311 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
312 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
313 * @return matches represented as a Match object.
314 *
315 */
316 public Collection<EndOfSiding_step_2.Match> getAllMatches(final Train pTrain) {
317 return rawStreamAllMatches(new Object[]{pTrain}).collect(Collectors.toSet());
318 }
319
320 /**
321 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
322 * </p>
323 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
324 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
325 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
326 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
327 * @return a stream of matches represented as a Match object.
328 *
329 */
330 public Stream<EndOfSiding_step_2.Match> streamAllMatches(final Train pTrain) {
331 return rawStreamAllMatches(new Object[]{pTrain});
332 }
333
334 /**
335 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
336 * Neither determinism nor randomness of selection is guaranteed.
337 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
338 * @return a match represented as a Match object, or null if no match is found.
339 *
340 */
341 public Optional<EndOfSiding_step_2.Match> getOneArbitraryMatch(final Train pTrain) {
342 return rawGetOneArbitraryMatch(new Object[]{pTrain});
343 }
344
345 /**
346 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
347 * under any possible substitution of the unspecified parameters (if any).
348 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
349 * @return true if the input is a valid (partial) match of the pattern.
350 *
351 */
352 public boolean hasMatch(final Train pTrain) {
353 return rawHasMatch(new Object[]{pTrain});
354 }
355
356 /**
357 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
358 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
359 * @return the number of pattern matches found.
360 *
361 */
362 public int countMatches(final Train pTrain) {
363 return rawCountMatches(new Object[]{pTrain});
364 }
365
366 /**
367 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
368 * Neither determinism nor randomness of selection is guaranteed.
369 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
370 * @param processor the action that will process the selected match.
371 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
372 *
373 */
374 public boolean forOneArbitraryMatch(final Train pTrain, final Consumer<? super EndOfSiding_step_2.Match> processor) {
375 return rawForOneArbitraryMatch(new Object[]{pTrain}, processor);
376 }
377
378 /**
379 * Returns a new (partial) match.
380 * This can be used e.g. to call the matcher with a partial match.
381 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
382 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
383 * @return the (partial) match object.
384 *
385 */
386 public EndOfSiding_step_2.Match newMatch(final Train pTrain) {
387 return EndOfSiding_step_2.Match.newMatch(pTrain);
388 }
389
390 /**
391 * Retrieve the set of values that occur in matches for train.
392 * @return the Set of all values or empty set if there are no matches
393 *
394 */
395 protected Stream<Train> rawStreamAllValuesOftrain(final Object[] parameters) {
396 return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast);
397 }
398
399 /**
400 * Retrieve the set of values that occur in matches for train.
401 * @return the Set of all values or empty set if there are no matches
402 *
403 */
404 public Set<Train> getAllValuesOftrain() {
405 return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet());
406 }
407
408 /**
409 * Retrieve the set of values that occur in matches for train.
410 * @return the Set of all values or empty set if there are no matches
411 *
412 */
413 public Stream<Train> streamAllValuesOftrain() {
414 return rawStreamAllValuesOftrain(emptyArray());
415 }
416
417 @Override
418 protected EndOfSiding_step_2.Match tupleToMatch(final Tuple t) {
419 try {
420 return EndOfSiding_step_2.Match.newMatch((Train) t.get(POSITION_TRAIN));
421 } catch(ClassCastException e) {
422 LOGGER.error("Element(s) in tuple not properly typed!",e);
423 return null;
424 }
425 }
426
427 @Override
428 protected EndOfSiding_step_2.Match arrayToMatch(final Object[] match) {
429 try {
430 return EndOfSiding_step_2.Match.newMatch((Train) match[POSITION_TRAIN]);
431 } catch(ClassCastException e) {
432 LOGGER.error("Element(s) in array not properly typed!",e);
433 return null;
434 }
435 }
436
437 @Override
438 protected EndOfSiding_step_2.Match arrayToMatchMutable(final Object[] match) {
439 try {
440 return EndOfSiding_step_2.Match.newMutableMatch((Train) match[POSITION_TRAIN]);
441 } catch(ClassCastException e) {
442 LOGGER.error("Element(s) in array not properly typed!",e);
443 return null;
444 }
445 }
446
447 /**
448 * @return the singleton instance of the query specification of this pattern
449 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
450 *
451 */
452 public static IQuerySpecification<EndOfSiding_step_2.Matcher> querySpecification() {
453 return EndOfSiding_step_2.instance();
454 }
455 }
456
457 private EndOfSiding_step_2() {
458 super(GeneratedPQuery.INSTANCE);
459 }
460
461 /**
462 * @return the singleton instance of the query specification
463 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
464 *
465 */
466 public static EndOfSiding_step_2 instance() {
467 try{
468 return LazyHolder.INSTANCE;
469 } catch (ExceptionInInitializerError err) {
470 throw processInitializerError(err);
471 }
472 }
473
474 @Override
475 protected EndOfSiding_step_2.Matcher instantiate(final ViatraQueryEngine engine) {
476 return EndOfSiding_step_2.Matcher.on(engine);
477 }
478
479 @Override
480 public EndOfSiding_step_2.Matcher instantiate() {
481 return EndOfSiding_step_2.Matcher.create();
482 }
483
484 @Override
485 public EndOfSiding_step_2.Match newEmptyMatch() {
486 return EndOfSiding_step_2.Match.newEmptyMatch();
487 }
488
489 @Override
490 public EndOfSiding_step_2.Match newMatch(final Object... parameters) {
491 return EndOfSiding_step_2.Match.newMatch((modes3.Train) parameters[0]);
492 }
493
494 /**
495 * Inner class allowing the singleton instance of {@link EndOfSiding_step_2} to be created
496 * <b>not</b> at the class load time of the outer class,
497 * but rather at the first call to {@link EndOfSiding_step_2#instance()}.
498 *
499 * <p> This workaround is required e.g. to support recursion.
500 *
501 */
502 private static class LazyHolder {
503 private static final EndOfSiding_step_2 INSTANCE = new EndOfSiding_step_2();
504
505 /**
506 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
507 * This initialization order is required to support indirect recursion.
508 *
509 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
510 *
511 */
512 private static final Object STATIC_INITIALIZER = ensureInitialized();
513
514 public static Object ensureInitialized() {
515 INSTANCE.ensureInitializedInternal();
516 return null;
517 }
518 }
519
520 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
521 private static final EndOfSiding_step_2.GeneratedPQuery INSTANCE = new GeneratedPQuery();
522
523 private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT);
524
525 private final List<PParameter> parameters = Arrays.asList(parameter_train);
526
527 private GeneratedPQuery() {
528 super(PVisibility.PUBLIC);
529 }
530
531 @Override
532 public String getFullyQualifiedName() {
533 return "modes3.queries.endOfSiding_step_2";
534 }
535
536 @Override
537 public List<String> getParameterNames() {
538 return Arrays.asList("train");
539 }
540
541 @Override
542 public List<PParameter> getParameters() {
543 return parameters;
544 }
545
546 @Override
547 public Set<PBody> doGetContainedBodies() {
548 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
549 Set<PBody> bodies = new LinkedHashSet<>();
550 {
551 PBody body = new PBody(this);
552 PVariable var_train = body.getOrCreateVariableByName("train");
553 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
554 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
555 new ExportedParameter(body, var_train, parameter_train)
556 ));
557 // // frame->train = model->trains[i0];// frame->location = frame->train->location;// if (frame->location != NULL) {// ...// } Train(train)
558 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
559 bodies.add(body);
560 }
561 return bodies;
562 }
563 }
564}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java
new file mode 100644
index 00000000..16b28a9f
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java
@@ -0,0 +1,717 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Segment;
17import modes3.Train;
18import org.apache.log4j.Logger;
19import org.eclipse.emf.ecore.EClass;
20import org.eclipse.viatra.query.runtime.api.IPatternMatch;
21import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
22import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
23import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
24import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
25import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
26import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
27import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
28import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey;
29import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
30import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
31import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
32import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality;
33import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
34import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
35import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
36import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
37import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
38import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
39import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
40import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
41
42/**
43 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
44 *
45 * <p>Original source:
46 * <code><pre>
47 * pattern endOfSiding_step_3(in train : Train, in location : Segment) {
48 * // int loop_bound1 = frame-{@literal >}location-{@literal >}connected_to_count;
49 * // for (int i1 = 0; i1 {@literal <} loop_bound1; i1++) {
50 * // ...
51 * // }
52 * Train(train);
53 * Train.location(train, location);
54 * }
55 * </pre></code>
56 *
57 * @see Matcher
58 * @see Match
59 *
60 */
61@SuppressWarnings("all")
62public final class EndOfSiding_step_3 extends BaseGeneratedEMFQuerySpecification<EndOfSiding_step_3.Matcher> {
63 /**
64 * Pattern-specific match representation of the modes3.queries.endOfSiding_step_3 pattern,
65 * to be used in conjunction with {@link Matcher}.
66 *
67 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
68 * Each instance is a (possibly partial) substitution of pattern parameters,
69 * usable to represent a match of the pattern in the result of a query,
70 * or to specify the bound (fixed) input parameters when issuing a query.
71 *
72 * @see Matcher
73 *
74 */
75 public static abstract class Match extends BasePatternMatch {
76 private Train fTrain;
77
78 private Segment fLocation;
79
80 private static List<String> parameterNames = makeImmutableList("train", "location");
81
82 private Match(final Train pTrain, final Segment pLocation) {
83 this.fTrain = pTrain;
84 this.fLocation = pLocation;
85 }
86
87 @Override
88 public Object get(final String parameterName) {
89 switch(parameterName) {
90 case "train": return this.fTrain;
91 case "location": return this.fLocation;
92 default: return null;
93 }
94 }
95
96 @Override
97 public Object get(final int index) {
98 switch(index) {
99 case 0: return this.fTrain;
100 case 1: return this.fLocation;
101 default: return null;
102 }
103 }
104
105 public Train getTrain() {
106 return this.fTrain;
107 }
108
109 public Segment getLocation() {
110 return this.fLocation;
111 }
112
113 @Override
114 public boolean set(final String parameterName, final Object newValue) {
115 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
116 if ("train".equals(parameterName) ) {
117 this.fTrain = (Train) newValue;
118 return true;
119 }
120 if ("location".equals(parameterName) ) {
121 this.fLocation = (Segment) newValue;
122 return true;
123 }
124 return false;
125 }
126
127 public void setTrain(final Train pTrain) {
128 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
129 this.fTrain = pTrain;
130 }
131
132 public void setLocation(final Segment pLocation) {
133 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
134 this.fLocation = pLocation;
135 }
136
137 @Override
138 public String patternName() {
139 return "modes3.queries.endOfSiding_step_3";
140 }
141
142 @Override
143 public List<String> parameterNames() {
144 return EndOfSiding_step_3.Match.parameterNames;
145 }
146
147 @Override
148 public Object[] toArray() {
149 return new Object[]{fTrain, fLocation};
150 }
151
152 @Override
153 public EndOfSiding_step_3.Match toImmutable() {
154 return isMutable() ? newMatch(fTrain, fLocation) : this;
155 }
156
157 @Override
158 public String prettyPrint() {
159 StringBuilder result = new StringBuilder();
160 result.append("\"train\"=" + prettyPrintValue(fTrain) + ", ");
161 result.append("\"location\"=" + prettyPrintValue(fLocation));
162 return result.toString();
163 }
164
165 @Override
166 public int hashCode() {
167 return Objects.hash(fTrain, fLocation);
168 }
169
170 @Override
171 public boolean equals(final Object obj) {
172 if (this == obj)
173 return true;
174 if (obj == null) {
175 return false;
176 }
177 if ((obj instanceof EndOfSiding_step_3.Match)) {
178 EndOfSiding_step_3.Match other = (EndOfSiding_step_3.Match) obj;
179 return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation);
180 } else {
181 // this should be infrequent
182 if (!(obj instanceof IPatternMatch)) {
183 return false;
184 }
185 IPatternMatch otherSig = (IPatternMatch) obj;
186 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
187 }
188 }
189
190 @Override
191 public EndOfSiding_step_3 specification() {
192 return EndOfSiding_step_3.instance();
193 }
194
195 /**
196 * Returns an empty, mutable match.
197 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
198 *
199 * @return the empty match.
200 *
201 */
202 public static EndOfSiding_step_3.Match newEmptyMatch() {
203 return new Mutable(null, null);
204 }
205
206 /**
207 * Returns a mutable (partial) match.
208 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
209 *
210 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
211 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
212 * @return the new, mutable (partial) match object.
213 *
214 */
215 public static EndOfSiding_step_3.Match newMutableMatch(final Train pTrain, final Segment pLocation) {
216 return new Mutable(pTrain, pLocation);
217 }
218
219 /**
220 * Returns a new (partial) match.
221 * This can be used e.g. to call the matcher with a partial match.
222 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
223 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
224 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
225 * @return the (partial) match object.
226 *
227 */
228 public static EndOfSiding_step_3.Match newMatch(final Train pTrain, final Segment pLocation) {
229 return new Immutable(pTrain, pLocation);
230 }
231
232 private static final class Mutable extends EndOfSiding_step_3.Match {
233 Mutable(final Train pTrain, final Segment pLocation) {
234 super(pTrain, pLocation);
235 }
236
237 @Override
238 public boolean isMutable() {
239 return true;
240 }
241 }
242
243 private static final class Immutable extends EndOfSiding_step_3.Match {
244 Immutable(final Train pTrain, final Segment pLocation) {
245 super(pTrain, pLocation);
246 }
247
248 @Override
249 public boolean isMutable() {
250 return false;
251 }
252 }
253 }
254
255 /**
256 * Generated pattern matcher API of the modes3.queries.endOfSiding_step_3 pattern,
257 * providing pattern-specific query methods.
258 *
259 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
260 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
261 *
262 * <p>Matches of the pattern will be represented as {@link Match}.
263 *
264 * <p>Original source:
265 * <code><pre>
266 * pattern endOfSiding_step_3(in train : Train, in location : Segment) {
267 * // int loop_bound1 = frame-{@literal >}location-{@literal >}connected_to_count;
268 * // for (int i1 = 0; i1 {@literal <} loop_bound1; i1++) {
269 * // ...
270 * // }
271 * Train(train);
272 * Train.location(train, location);
273 * }
274 * </pre></code>
275 *
276 * @see Match
277 * @see EndOfSiding_step_3
278 *
279 */
280 public static class Matcher extends BaseMatcher<EndOfSiding_step_3.Match> {
281 /**
282 * Initializes the pattern matcher within an existing VIATRA Query engine.
283 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
284 *
285 * @param engine the existing VIATRA Query engine in which this matcher will be created.
286 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
287 *
288 */
289 public static EndOfSiding_step_3.Matcher on(final ViatraQueryEngine engine) {
290 // check if matcher already exists
291 Matcher matcher = engine.getExistingMatcher(querySpecification());
292 if (matcher == null) {
293 matcher = (Matcher)engine.getMatcher(querySpecification());
294 }
295 return matcher;
296 }
297
298 /**
299 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
300 * @return an initialized matcher
301 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
302 *
303 */
304 public static EndOfSiding_step_3.Matcher create() {
305 return new Matcher();
306 }
307
308 private static final int POSITION_TRAIN = 0;
309
310 private static final int POSITION_LOCATION = 1;
311
312 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_3.Matcher.class);
313
314 /**
315 * Initializes the pattern matcher within an existing VIATRA Query engine.
316 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
317 *
318 * @param engine the existing VIATRA Query engine in which this matcher will be created.
319 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
320 *
321 */
322 private Matcher() {
323 super(querySpecification());
324 }
325
326 /**
327 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
328 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
329 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
330 * @return matches represented as a Match object.
331 *
332 */
333 public Collection<EndOfSiding_step_3.Match> getAllMatches(final Train pTrain, final Segment pLocation) {
334 return rawStreamAllMatches(new Object[]{pTrain, pLocation}).collect(Collectors.toSet());
335 }
336
337 /**
338 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
339 * </p>
340 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
341 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
342 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
343 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
344 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
345 * @return a stream of matches represented as a Match object.
346 *
347 */
348 public Stream<EndOfSiding_step_3.Match> streamAllMatches(final Train pTrain, final Segment pLocation) {
349 return rawStreamAllMatches(new Object[]{pTrain, pLocation});
350 }
351
352 /**
353 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
354 * Neither determinism nor randomness of selection is guaranteed.
355 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
356 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
357 * @return a match represented as a Match object, or null if no match is found.
358 *
359 */
360 public Optional<EndOfSiding_step_3.Match> getOneArbitraryMatch(final Train pTrain, final Segment pLocation) {
361 return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation});
362 }
363
364 /**
365 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
366 * under any possible substitution of the unspecified parameters (if any).
367 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
368 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
369 * @return true if the input is a valid (partial) match of the pattern.
370 *
371 */
372 public boolean hasMatch(final Train pTrain, final Segment pLocation) {
373 return rawHasMatch(new Object[]{pTrain, pLocation});
374 }
375
376 /**
377 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
378 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
379 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
380 * @return the number of pattern matches found.
381 *
382 */
383 public int countMatches(final Train pTrain, final Segment pLocation) {
384 return rawCountMatches(new Object[]{pTrain, pLocation});
385 }
386
387 /**
388 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
389 * Neither determinism nor randomness of selection is guaranteed.
390 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
391 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
392 * @param processor the action that will process the selected match.
393 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
394 *
395 */
396 public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Consumer<? super EndOfSiding_step_3.Match> processor) {
397 return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation}, processor);
398 }
399
400 /**
401 * Returns a new (partial) match.
402 * This can be used e.g. to call the matcher with a partial match.
403 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
404 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
405 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
406 * @return the (partial) match object.
407 *
408 */
409 public EndOfSiding_step_3.Match newMatch(final Train pTrain, final Segment pLocation) {
410 return EndOfSiding_step_3.Match.newMatch(pTrain, pLocation);
411 }
412
413 /**
414 * Retrieve the set of values that occur in matches for train.
415 * @return the Set of all values or empty set if there are no matches
416 *
417 */
418 protected Stream<Train> rawStreamAllValuesOftrain(final Object[] parameters) {
419 return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast);
420 }
421
422 /**
423 * Retrieve the set of values that occur in matches for train.
424 * @return the Set of all values or empty set if there are no matches
425 *
426 */
427 public Set<Train> getAllValuesOftrain() {
428 return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet());
429 }
430
431 /**
432 * Retrieve the set of values that occur in matches for train.
433 * @return the Set of all values or empty set if there are no matches
434 *
435 */
436 public Stream<Train> streamAllValuesOftrain() {
437 return rawStreamAllValuesOftrain(emptyArray());
438 }
439
440 /**
441 * Retrieve the set of values that occur in matches for train.
442 * </p>
443 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
444 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
445 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
446 *
447 * @return the Stream of all values or empty set if there are no matches
448 *
449 */
450 public Stream<Train> streamAllValuesOftrain(final EndOfSiding_step_3.Match partialMatch) {
451 return rawStreamAllValuesOftrain(partialMatch.toArray());
452 }
453
454 /**
455 * Retrieve the set of values that occur in matches for train.
456 * </p>
457 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
458 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
459 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
460 *
461 * @return the Stream of all values or empty set if there are no matches
462 *
463 */
464 public Stream<Train> streamAllValuesOftrain(final Segment pLocation) {
465 return rawStreamAllValuesOftrain(new Object[]{null, pLocation});
466 }
467
468 /**
469 * Retrieve the set of values that occur in matches for train.
470 * @return the Set of all values or empty set if there are no matches
471 *
472 */
473 public Set<Train> getAllValuesOftrain(final EndOfSiding_step_3.Match partialMatch) {
474 return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet());
475 }
476
477 /**
478 * Retrieve the set of values that occur in matches for train.
479 * @return the Set of all values or empty set if there are no matches
480 *
481 */
482 public Set<Train> getAllValuesOftrain(final Segment pLocation) {
483 return rawStreamAllValuesOftrain(new Object[]{null, pLocation}).collect(Collectors.toSet());
484 }
485
486 /**
487 * Retrieve the set of values that occur in matches for location.
488 * @return the Set of all values or empty set if there are no matches
489 *
490 */
491 protected Stream<Segment> rawStreamAllValuesOflocation(final Object[] parameters) {
492 return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast);
493 }
494
495 /**
496 * Retrieve the set of values that occur in matches for location.
497 * @return the Set of all values or empty set if there are no matches
498 *
499 */
500 public Set<Segment> getAllValuesOflocation() {
501 return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet());
502 }
503
504 /**
505 * Retrieve the set of values that occur in matches for location.
506 * @return the Set of all values or empty set if there are no matches
507 *
508 */
509 public Stream<Segment> streamAllValuesOflocation() {
510 return rawStreamAllValuesOflocation(emptyArray());
511 }
512
513 /**
514 * Retrieve the set of values that occur in matches for location.
515 * </p>
516 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
517 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
518 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
519 *
520 * @return the Stream of all values or empty set if there are no matches
521 *
522 */
523 public Stream<Segment> streamAllValuesOflocation(final EndOfSiding_step_3.Match partialMatch) {
524 return rawStreamAllValuesOflocation(partialMatch.toArray());
525 }
526
527 /**
528 * Retrieve the set of values that occur in matches for location.
529 * </p>
530 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
531 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
532 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
533 *
534 * @return the Stream of all values or empty set if there are no matches
535 *
536 */
537 public Stream<Segment> streamAllValuesOflocation(final Train pTrain) {
538 return rawStreamAllValuesOflocation(new Object[]{pTrain, null});
539 }
540
541 /**
542 * Retrieve the set of values that occur in matches for location.
543 * @return the Set of all values or empty set if there are no matches
544 *
545 */
546 public Set<Segment> getAllValuesOflocation(final EndOfSiding_step_3.Match partialMatch) {
547 return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet());
548 }
549
550 /**
551 * Retrieve the set of values that occur in matches for location.
552 * @return the Set of all values or empty set if there are no matches
553 *
554 */
555 public Set<Segment> getAllValuesOflocation(final Train pTrain) {
556 return rawStreamAllValuesOflocation(new Object[]{pTrain, null}).collect(Collectors.toSet());
557 }
558
559 @Override
560 protected EndOfSiding_step_3.Match tupleToMatch(final Tuple t) {
561 try {
562 return EndOfSiding_step_3.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION));
563 } catch(ClassCastException e) {
564 LOGGER.error("Element(s) in tuple not properly typed!",e);
565 return null;
566 }
567 }
568
569 @Override
570 protected EndOfSiding_step_3.Match arrayToMatch(final Object[] match) {
571 try {
572 return EndOfSiding_step_3.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]);
573 } catch(ClassCastException e) {
574 LOGGER.error("Element(s) in array not properly typed!",e);
575 return null;
576 }
577 }
578
579 @Override
580 protected EndOfSiding_step_3.Match arrayToMatchMutable(final Object[] match) {
581 try {
582 return EndOfSiding_step_3.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]);
583 } catch(ClassCastException e) {
584 LOGGER.error("Element(s) in array not properly typed!",e);
585 return null;
586 }
587 }
588
589 /**
590 * @return the singleton instance of the query specification of this pattern
591 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
592 *
593 */
594 public static IQuerySpecification<EndOfSiding_step_3.Matcher> querySpecification() {
595 return EndOfSiding_step_3.instance();
596 }
597 }
598
599 private EndOfSiding_step_3() {
600 super(GeneratedPQuery.INSTANCE);
601 }
602
603 /**
604 * @return the singleton instance of the query specification
605 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
606 *
607 */
608 public static EndOfSiding_step_3 instance() {
609 try{
610 return LazyHolder.INSTANCE;
611 } catch (ExceptionInInitializerError err) {
612 throw processInitializerError(err);
613 }
614 }
615
616 @Override
617 protected EndOfSiding_step_3.Matcher instantiate(final ViatraQueryEngine engine) {
618 return EndOfSiding_step_3.Matcher.on(engine);
619 }
620
621 @Override
622 public EndOfSiding_step_3.Matcher instantiate() {
623 return EndOfSiding_step_3.Matcher.create();
624 }
625
626 @Override
627 public EndOfSiding_step_3.Match newEmptyMatch() {
628 return EndOfSiding_step_3.Match.newEmptyMatch();
629 }
630
631 @Override
632 public EndOfSiding_step_3.Match newMatch(final Object... parameters) {
633 return EndOfSiding_step_3.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1]);
634 }
635
636 /**
637 * Inner class allowing the singleton instance of {@link EndOfSiding_step_3} to be created
638 * <b>not</b> at the class load time of the outer class,
639 * but rather at the first call to {@link EndOfSiding_step_3#instance()}.
640 *
641 * <p> This workaround is required e.g. to support recursion.
642 *
643 */
644 private static class LazyHolder {
645 private static final EndOfSiding_step_3 INSTANCE = new EndOfSiding_step_3();
646
647 /**
648 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
649 * This initialization order is required to support indirect recursion.
650 *
651 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
652 *
653 */
654 private static final Object STATIC_INITIALIZER = ensureInitialized();
655
656 public static Object ensureInitialized() {
657 INSTANCE.ensureInitializedInternal();
658 return null;
659 }
660 }
661
662 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
663 private static final EndOfSiding_step_3.GeneratedPQuery INSTANCE = new GeneratedPQuery();
664
665 private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT);
666
667 private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
668
669 private final List<PParameter> parameters = Arrays.asList(parameter_train, parameter_location);
670
671 private GeneratedPQuery() {
672 super(PVisibility.PUBLIC);
673 }
674
675 @Override
676 public String getFullyQualifiedName() {
677 return "modes3.queries.endOfSiding_step_3";
678 }
679
680 @Override
681 public List<String> getParameterNames() {
682 return Arrays.asList("train","location");
683 }
684
685 @Override
686 public List<PParameter> getParameters() {
687 return parameters;
688 }
689
690 @Override
691 public Set<PBody> doGetContainedBodies() {
692 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
693 Set<PBody> bodies = new LinkedHashSet<>();
694 {
695 PBody body = new PBody(this);
696 PVariable var_train = body.getOrCreateVariableByName("train");
697 PVariable var_location = body.getOrCreateVariableByName("location");
698 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
699 new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
700 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
701 new ExportedParameter(body, var_train, parameter_train),
702 new ExportedParameter(body, var_location, parameter_location)
703 ));
704 // // int loop_bound1 = frame->location->connected_to_count;// for (int i1 = 0; i1 < loop_bound1; i1++) {// ...// } Train(train)
705 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
706 // Train.location(train, location)
707 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
708 PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}");
709 new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location")));
710 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
711 new Equality(body, var__virtual_0_, var_location);
712 bodies.add(body);
713 }
714 return bodies;
715 }
716 }
717}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java
new file mode 100644
index 00000000..73df8514
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java
@@ -0,0 +1,847 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Segment;
17import modes3.Train;
18import org.apache.log4j.Logger;
19import org.eclipse.emf.ecore.EClass;
20import org.eclipse.viatra.query.runtime.api.IPatternMatch;
21import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
22import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
23import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
24import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
25import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
26import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
27import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
28import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey;
29import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
30import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
31import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
32import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality;
33import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
34import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
35import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
36import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
37import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
38import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
39import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
40import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
41
42/**
43 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
44 *
45 * <p>Original source:
46 * <code><pre>
47 * pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
48 * // frame-{@literal >}end = frame-{@literal >}location-{@literal >}connected_to[i1];
49 * // if (frame-{@literal >}end != NULL &&
50 * // frame-{@literal >}end-{@literal >}connected_to[1] == frame-{@literal >}location &&
51 * // frame-{@literal >}end-{@literal >}connected_to[0] == NULL) {
52 * // ...
53 * // }
54 * // if (frame-{@literal >}end != NULL &&
55 * // frame-{@literal >}end-{@literal >}connected_to[0] == frame-{@literal >}location &&
56 * // frame-{@literal >}end-{@literal >}connected_to[1] == NULL) {
57 * // ...
58 * // }
59 * Train(train);
60 * Train.location(train, location);
61 * Segment.connectedTo(location, end);
62 * }
63 * </pre></code>
64 *
65 * @see Matcher
66 * @see Match
67 *
68 */
69@SuppressWarnings("all")
70public final class EndOfSiding_step_4 extends BaseGeneratedEMFQuerySpecification<EndOfSiding_step_4.Matcher> {
71 /**
72 * Pattern-specific match representation of the modes3.queries.endOfSiding_step_4 pattern,
73 * to be used in conjunction with {@link Matcher}.
74 *
75 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
76 * Each instance is a (possibly partial) substitution of pattern parameters,
77 * usable to represent a match of the pattern in the result of a query,
78 * or to specify the bound (fixed) input parameters when issuing a query.
79 *
80 * @see Matcher
81 *
82 */
83 public static abstract class Match extends BasePatternMatch {
84 private Train fTrain;
85
86 private Segment fLocation;
87
88 private Segment fEnd;
89
90 private static List<String> parameterNames = makeImmutableList("train", "location", "end");
91
92 private Match(final Train pTrain, final Segment pLocation, final Segment pEnd) {
93 this.fTrain = pTrain;
94 this.fLocation = pLocation;
95 this.fEnd = pEnd;
96 }
97
98 @Override
99 public Object get(final String parameterName) {
100 switch(parameterName) {
101 case "train": return this.fTrain;
102 case "location": return this.fLocation;
103 case "end": return this.fEnd;
104 default: return null;
105 }
106 }
107
108 @Override
109 public Object get(final int index) {
110 switch(index) {
111 case 0: return this.fTrain;
112 case 1: return this.fLocation;
113 case 2: return this.fEnd;
114 default: return null;
115 }
116 }
117
118 public Train getTrain() {
119 return this.fTrain;
120 }
121
122 public Segment getLocation() {
123 return this.fLocation;
124 }
125
126 public Segment getEnd() {
127 return this.fEnd;
128 }
129
130 @Override
131 public boolean set(final String parameterName, final Object newValue) {
132 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
133 if ("train".equals(parameterName) ) {
134 this.fTrain = (Train) newValue;
135 return true;
136 }
137 if ("location".equals(parameterName) ) {
138 this.fLocation = (Segment) newValue;
139 return true;
140 }
141 if ("end".equals(parameterName) ) {
142 this.fEnd = (Segment) newValue;
143 return true;
144 }
145 return false;
146 }
147
148 public void setTrain(final Train pTrain) {
149 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
150 this.fTrain = pTrain;
151 }
152
153 public void setLocation(final Segment pLocation) {
154 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
155 this.fLocation = pLocation;
156 }
157
158 public void setEnd(final Segment pEnd) {
159 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
160 this.fEnd = pEnd;
161 }
162
163 @Override
164 public String patternName() {
165 return "modes3.queries.endOfSiding_step_4";
166 }
167
168 @Override
169 public List<String> parameterNames() {
170 return EndOfSiding_step_4.Match.parameterNames;
171 }
172
173 @Override
174 public Object[] toArray() {
175 return new Object[]{fTrain, fLocation, fEnd};
176 }
177
178 @Override
179 public EndOfSiding_step_4.Match toImmutable() {
180 return isMutable() ? newMatch(fTrain, fLocation, fEnd) : this;
181 }
182
183 @Override
184 public String prettyPrint() {
185 StringBuilder result = new StringBuilder();
186 result.append("\"train\"=" + prettyPrintValue(fTrain) + ", ");
187 result.append("\"location\"=" + prettyPrintValue(fLocation) + ", ");
188 result.append("\"end\"=" + prettyPrintValue(fEnd));
189 return result.toString();
190 }
191
192 @Override
193 public int hashCode() {
194 return Objects.hash(fTrain, fLocation, fEnd);
195 }
196
197 @Override
198 public boolean equals(final Object obj) {
199 if (this == obj)
200 return true;
201 if (obj == null) {
202 return false;
203 }
204 if ((obj instanceof EndOfSiding_step_4.Match)) {
205 EndOfSiding_step_4.Match other = (EndOfSiding_step_4.Match) obj;
206 return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation) && Objects.equals(fEnd, other.fEnd);
207 } else {
208 // this should be infrequent
209 if (!(obj instanceof IPatternMatch)) {
210 return false;
211 }
212 IPatternMatch otherSig = (IPatternMatch) obj;
213 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
214 }
215 }
216
217 @Override
218 public EndOfSiding_step_4 specification() {
219 return EndOfSiding_step_4.instance();
220 }
221
222 /**
223 * Returns an empty, mutable match.
224 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
225 *
226 * @return the empty match.
227 *
228 */
229 public static EndOfSiding_step_4.Match newEmptyMatch() {
230 return new Mutable(null, null, null);
231 }
232
233 /**
234 * Returns a mutable (partial) match.
235 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
236 *
237 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
238 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
239 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
240 * @return the new, mutable (partial) match object.
241 *
242 */
243 public static EndOfSiding_step_4.Match newMutableMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
244 return new Mutable(pTrain, pLocation, pEnd);
245 }
246
247 /**
248 * Returns a new (partial) match.
249 * This can be used e.g. to call the matcher with a partial match.
250 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
251 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
252 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
253 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
254 * @return the (partial) match object.
255 *
256 */
257 public static EndOfSiding_step_4.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
258 return new Immutable(pTrain, pLocation, pEnd);
259 }
260
261 private static final class Mutable extends EndOfSiding_step_4.Match {
262 Mutable(final Train pTrain, final Segment pLocation, final Segment pEnd) {
263 super(pTrain, pLocation, pEnd);
264 }
265
266 @Override
267 public boolean isMutable() {
268 return true;
269 }
270 }
271
272 private static final class Immutable extends EndOfSiding_step_4.Match {
273 Immutable(final Train pTrain, final Segment pLocation, final Segment pEnd) {
274 super(pTrain, pLocation, pEnd);
275 }
276
277 @Override
278 public boolean isMutable() {
279 return false;
280 }
281 }
282 }
283
284 /**
285 * Generated pattern matcher API of the modes3.queries.endOfSiding_step_4 pattern,
286 * providing pattern-specific query methods.
287 *
288 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
289 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
290 *
291 * <p>Matches of the pattern will be represented as {@link Match}.
292 *
293 * <p>Original source:
294 * <code><pre>
295 * pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
296 * // frame-{@literal >}end = frame-{@literal >}location-{@literal >}connected_to[i1];
297 * // if (frame-{@literal >}end != NULL &&
298 * // frame-{@literal >}end-{@literal >}connected_to[1] == frame-{@literal >}location &&
299 * // frame-{@literal >}end-{@literal >}connected_to[0] == NULL) {
300 * // ...
301 * // }
302 * // if (frame-{@literal >}end != NULL &&
303 * // frame-{@literal >}end-{@literal >}connected_to[0] == frame-{@literal >}location &&
304 * // frame-{@literal >}end-{@literal >}connected_to[1] == NULL) {
305 * // ...
306 * // }
307 * Train(train);
308 * Train.location(train, location);
309 * Segment.connectedTo(location, end);
310 * }
311 * </pre></code>
312 *
313 * @see Match
314 * @see EndOfSiding_step_4
315 *
316 */
317 public static class Matcher extends BaseMatcher<EndOfSiding_step_4.Match> {
318 /**
319 * Initializes the pattern matcher within an existing VIATRA Query engine.
320 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
321 *
322 * @param engine the existing VIATRA Query engine in which this matcher will be created.
323 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
324 *
325 */
326 public static EndOfSiding_step_4.Matcher on(final ViatraQueryEngine engine) {
327 // check if matcher already exists
328 Matcher matcher = engine.getExistingMatcher(querySpecification());
329 if (matcher == null) {
330 matcher = (Matcher)engine.getMatcher(querySpecification());
331 }
332 return matcher;
333 }
334
335 /**
336 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
337 * @return an initialized matcher
338 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
339 *
340 */
341 public static EndOfSiding_step_4.Matcher create() {
342 return new Matcher();
343 }
344
345 private static final int POSITION_TRAIN = 0;
346
347 private static final int POSITION_LOCATION = 1;
348
349 private static final int POSITION_END = 2;
350
351 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_4.Matcher.class);
352
353 /**
354 * Initializes the pattern matcher within an existing VIATRA Query engine.
355 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
356 *
357 * @param engine the existing VIATRA Query engine in which this matcher will be created.
358 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
359 *
360 */
361 private Matcher() {
362 super(querySpecification());
363 }
364
365 /**
366 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
367 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
368 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
369 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
370 * @return matches represented as a Match object.
371 *
372 */
373 public Collection<EndOfSiding_step_4.Match> getAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) {
374 return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}).collect(Collectors.toSet());
375 }
376
377 /**
378 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
379 * </p>
380 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
381 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
382 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
383 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
384 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
385 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
386 * @return a stream of matches represented as a Match object.
387 *
388 */
389 public Stream<EndOfSiding_step_4.Match> streamAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) {
390 return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd});
391 }
392
393 /**
394 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
395 * Neither determinism nor randomness of selection is guaranteed.
396 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
397 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
398 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
399 * @return a match represented as a Match object, or null if no match is found.
400 *
401 */
402 public Optional<EndOfSiding_step_4.Match> getOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
403 return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd});
404 }
405
406 /**
407 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
408 * under any possible substitution of the unspecified parameters (if any).
409 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
410 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
411 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
412 * @return true if the input is a valid (partial) match of the pattern.
413 *
414 */
415 public boolean hasMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
416 return rawHasMatch(new Object[]{pTrain, pLocation, pEnd});
417 }
418
419 /**
420 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
421 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
422 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
423 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
424 * @return the number of pattern matches found.
425 *
426 */
427 public int countMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) {
428 return rawCountMatches(new Object[]{pTrain, pLocation, pEnd});
429 }
430
431 /**
432 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
433 * Neither determinism nor randomness of selection is guaranteed.
434 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
435 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
436 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
437 * @param processor the action that will process the selected match.
438 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
439 *
440 */
441 public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd, final Consumer<? super EndOfSiding_step_4.Match> processor) {
442 return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}, processor);
443 }
444
445 /**
446 * Returns a new (partial) match.
447 * This can be used e.g. to call the matcher with a partial match.
448 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
449 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
450 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
451 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
452 * @return the (partial) match object.
453 *
454 */
455 public EndOfSiding_step_4.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
456 return EndOfSiding_step_4.Match.newMatch(pTrain, pLocation, pEnd);
457 }
458
459 /**
460 * Retrieve the set of values that occur in matches for train.
461 * @return the Set of all values or empty set if there are no matches
462 *
463 */
464 protected Stream<Train> rawStreamAllValuesOftrain(final Object[] parameters) {
465 return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast);
466 }
467
468 /**
469 * Retrieve the set of values that occur in matches for train.
470 * @return the Set of all values or empty set if there are no matches
471 *
472 */
473 public Set<Train> getAllValuesOftrain() {
474 return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet());
475 }
476
477 /**
478 * Retrieve the set of values that occur in matches for train.
479 * @return the Set of all values or empty set if there are no matches
480 *
481 */
482 public Stream<Train> streamAllValuesOftrain() {
483 return rawStreamAllValuesOftrain(emptyArray());
484 }
485
486 /**
487 * Retrieve the set of values that occur in matches for train.
488 * </p>
489 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
490 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
491 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
492 *
493 * @return the Stream of all values or empty set if there are no matches
494 *
495 */
496 public Stream<Train> streamAllValuesOftrain(final EndOfSiding_step_4.Match partialMatch) {
497 return rawStreamAllValuesOftrain(partialMatch.toArray());
498 }
499
500 /**
501 * Retrieve the set of values that occur in matches for train.
502 * </p>
503 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
504 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
505 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
506 *
507 * @return the Stream of all values or empty set if there are no matches
508 *
509 */
510 public Stream<Train> streamAllValuesOftrain(final Segment pLocation, final Segment pEnd) {
511 return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd});
512 }
513
514 /**
515 * Retrieve the set of values that occur in matches for train.
516 * @return the Set of all values or empty set if there are no matches
517 *
518 */
519 public Set<Train> getAllValuesOftrain(final EndOfSiding_step_4.Match partialMatch) {
520 return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet());
521 }
522
523 /**
524 * Retrieve the set of values that occur in matches for train.
525 * @return the Set of all values or empty set if there are no matches
526 *
527 */
528 public Set<Train> getAllValuesOftrain(final Segment pLocation, final Segment pEnd) {
529 return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}).collect(Collectors.toSet());
530 }
531
532 /**
533 * Retrieve the set of values that occur in matches for location.
534 * @return the Set of all values or empty set if there are no matches
535 *
536 */
537 protected Stream<Segment> rawStreamAllValuesOflocation(final Object[] parameters) {
538 return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast);
539 }
540
541 /**
542 * Retrieve the set of values that occur in matches for location.
543 * @return the Set of all values or empty set if there are no matches
544 *
545 */
546 public Set<Segment> getAllValuesOflocation() {
547 return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet());
548 }
549
550 /**
551 * Retrieve the set of values that occur in matches for location.
552 * @return the Set of all values or empty set if there are no matches
553 *
554 */
555 public Stream<Segment> streamAllValuesOflocation() {
556 return rawStreamAllValuesOflocation(emptyArray());
557 }
558
559 /**
560 * Retrieve the set of values that occur in matches for location.
561 * </p>
562 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
563 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
564 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
565 *
566 * @return the Stream of all values or empty set if there are no matches
567 *
568 */
569 public Stream<Segment> streamAllValuesOflocation(final EndOfSiding_step_4.Match partialMatch) {
570 return rawStreamAllValuesOflocation(partialMatch.toArray());
571 }
572
573 /**
574 * Retrieve the set of values that occur in matches for location.
575 * </p>
576 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
577 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
578 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
579 *
580 * @return the Stream of all values or empty set if there are no matches
581 *
582 */
583 public Stream<Segment> streamAllValuesOflocation(final Train pTrain, final Segment pEnd) {
584 return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd});
585 }
586
587 /**
588 * Retrieve the set of values that occur in matches for location.
589 * @return the Set of all values or empty set if there are no matches
590 *
591 */
592 public Set<Segment> getAllValuesOflocation(final EndOfSiding_step_4.Match partialMatch) {
593 return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet());
594 }
595
596 /**
597 * Retrieve the set of values that occur in matches for location.
598 * @return the Set of all values or empty set if there are no matches
599 *
600 */
601 public Set<Segment> getAllValuesOflocation(final Train pTrain, final Segment pEnd) {
602 return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}).collect(Collectors.toSet());
603 }
604
605 /**
606 * Retrieve the set of values that occur in matches for end.
607 * @return the Set of all values or empty set if there are no matches
608 *
609 */
610 protected Stream<Segment> rawStreamAllValuesOfend(final Object[] parameters) {
611 return rawStreamAllValues(POSITION_END, parameters).map(Segment.class::cast);
612 }
613
614 /**
615 * Retrieve the set of values that occur in matches for end.
616 * @return the Set of all values or empty set if there are no matches
617 *
618 */
619 public Set<Segment> getAllValuesOfend() {
620 return rawStreamAllValuesOfend(emptyArray()).collect(Collectors.toSet());
621 }
622
623 /**
624 * Retrieve the set of values that occur in matches for end.
625 * @return the Set of all values or empty set if there are no matches
626 *
627 */
628 public Stream<Segment> streamAllValuesOfend() {
629 return rawStreamAllValuesOfend(emptyArray());
630 }
631
632 /**
633 * Retrieve the set of values that occur in matches for end.
634 * </p>
635 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
636 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
637 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
638 *
639 * @return the Stream of all values or empty set if there are no matches
640 *
641 */
642 public Stream<Segment> streamAllValuesOfend(final EndOfSiding_step_4.Match partialMatch) {
643 return rawStreamAllValuesOfend(partialMatch.toArray());
644 }
645
646 /**
647 * Retrieve the set of values that occur in matches for end.
648 * </p>
649 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
650 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
651 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
652 *
653 * @return the Stream of all values or empty set if there are no matches
654 *
655 */
656 public Stream<Segment> streamAllValuesOfend(final Train pTrain, final Segment pLocation) {
657 return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null});
658 }
659
660 /**
661 * Retrieve the set of values that occur in matches for end.
662 * @return the Set of all values or empty set if there are no matches
663 *
664 */
665 public Set<Segment> getAllValuesOfend(final EndOfSiding_step_4.Match partialMatch) {
666 return rawStreamAllValuesOfend(partialMatch.toArray()).collect(Collectors.toSet());
667 }
668
669 /**
670 * Retrieve the set of values that occur in matches for end.
671 * @return the Set of all values or empty set if there are no matches
672 *
673 */
674 public Set<Segment> getAllValuesOfend(final Train pTrain, final Segment pLocation) {
675 return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}).collect(Collectors.toSet());
676 }
677
678 @Override
679 protected EndOfSiding_step_4.Match tupleToMatch(final Tuple t) {
680 try {
681 return EndOfSiding_step_4.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION), (Segment) t.get(POSITION_END));
682 } catch(ClassCastException e) {
683 LOGGER.error("Element(s) in tuple not properly typed!",e);
684 return null;
685 }
686 }
687
688 @Override
689 protected EndOfSiding_step_4.Match arrayToMatch(final Object[] match) {
690 try {
691 return EndOfSiding_step_4.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]);
692 } catch(ClassCastException e) {
693 LOGGER.error("Element(s) in array not properly typed!",e);
694 return null;
695 }
696 }
697
698 @Override
699 protected EndOfSiding_step_4.Match arrayToMatchMutable(final Object[] match) {
700 try {
701 return EndOfSiding_step_4.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]);
702 } catch(ClassCastException e) {
703 LOGGER.error("Element(s) in array not properly typed!",e);
704 return null;
705 }
706 }
707
708 /**
709 * @return the singleton instance of the query specification of this pattern
710 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
711 *
712 */
713 public static IQuerySpecification<EndOfSiding_step_4.Matcher> querySpecification() {
714 return EndOfSiding_step_4.instance();
715 }
716 }
717
718 private EndOfSiding_step_4() {
719 super(GeneratedPQuery.INSTANCE);
720 }
721
722 /**
723 * @return the singleton instance of the query specification
724 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
725 *
726 */
727 public static EndOfSiding_step_4 instance() {
728 try{
729 return LazyHolder.INSTANCE;
730 } catch (ExceptionInInitializerError err) {
731 throw processInitializerError(err);
732 }
733 }
734
735 @Override
736 protected EndOfSiding_step_4.Matcher instantiate(final ViatraQueryEngine engine) {
737 return EndOfSiding_step_4.Matcher.on(engine);
738 }
739
740 @Override
741 public EndOfSiding_step_4.Matcher instantiate() {
742 return EndOfSiding_step_4.Matcher.create();
743 }
744
745 @Override
746 public EndOfSiding_step_4.Match newEmptyMatch() {
747 return EndOfSiding_step_4.Match.newEmptyMatch();
748 }
749
750 @Override
751 public EndOfSiding_step_4.Match newMatch(final Object... parameters) {
752 return EndOfSiding_step_4.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1], (modes3.Segment) parameters[2]);
753 }
754
755 /**
756 * Inner class allowing the singleton instance of {@link EndOfSiding_step_4} to be created
757 * <b>not</b> at the class load time of the outer class,
758 * but rather at the first call to {@link EndOfSiding_step_4#instance()}.
759 *
760 * <p> This workaround is required e.g. to support recursion.
761 *
762 */
763 private static class LazyHolder {
764 private static final EndOfSiding_step_4 INSTANCE = new EndOfSiding_step_4();
765
766 /**
767 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
768 * This initialization order is required to support indirect recursion.
769 *
770 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
771 *
772 */
773 private static final Object STATIC_INITIALIZER = ensureInitialized();
774
775 public static Object ensureInitialized() {
776 INSTANCE.ensureInitializedInternal();
777 return null;
778 }
779 }
780
781 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
782 private static final EndOfSiding_step_4.GeneratedPQuery INSTANCE = new GeneratedPQuery();
783
784 private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT);
785
786 private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
787
788 private final PParameter parameter_end = new PParameter("end", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
789
790 private final List<PParameter> parameters = Arrays.asList(parameter_train, parameter_location, parameter_end);
791
792 private GeneratedPQuery() {
793 super(PVisibility.PUBLIC);
794 }
795
796 @Override
797 public String getFullyQualifiedName() {
798 return "modes3.queries.endOfSiding_step_4";
799 }
800
801 @Override
802 public List<String> getParameterNames() {
803 return Arrays.asList("train","location","end");
804 }
805
806 @Override
807 public List<PParameter> getParameters() {
808 return parameters;
809 }
810
811 @Override
812 public Set<PBody> doGetContainedBodies() {
813 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
814 Set<PBody> bodies = new LinkedHashSet<>();
815 {
816 PBody body = new PBody(this);
817 PVariable var_train = body.getOrCreateVariableByName("train");
818 PVariable var_location = body.getOrCreateVariableByName("location");
819 PVariable var_end = body.getOrCreateVariableByName("end");
820 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
821 new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
822 new TypeConstraint(body, Tuples.flatTupleOf(var_end), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
823 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
824 new ExportedParameter(body, var_train, parameter_train),
825 new ExportedParameter(body, var_location, parameter_location),
826 new ExportedParameter(body, var_end, parameter_end)
827 ));
828 // // frame->end = frame->location->connected_to[i1];// if (frame->end != NULL &&// frame->end->connected_to[1] == frame->location &&// frame->end->connected_to[0] == NULL) {// ...// } // if (frame->end != NULL &&// frame->end->connected_to[0] == frame->location &&// frame->end->connected_to[1] == NULL) {// ...// } Train(train)
829 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
830 // Train.location(train, location)
831 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
832 PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}");
833 new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location")));
834 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
835 new Equality(body, var__virtual_0_, var_location);
836 // Segment.connectedTo(location, end)
837 new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
838 PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}");
839 new TypeConstraint(body, Tuples.flatTupleOf(var_location, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo")));
840 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
841 new Equality(body, var__virtual_1_, var_end);
842 bodies.add(body);
843 }
844 return bodies;
845 }
846 }
847}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java
new file mode 100644
index 00000000..48a2697d
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java
@@ -0,0 +1,841 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Segment;
17import modes3.Train;
18import modes3.queries.MultipleConnectedTo;
19import org.apache.log4j.Logger;
20import org.eclipse.emf.ecore.EClass;
21import org.eclipse.viatra.query.runtime.api.IPatternMatch;
22import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
23import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
24import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
25import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
26import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
27import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
28import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
29import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey;
30import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
31import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
32import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
33import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality;
34import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
35import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall;
36import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
37import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
38import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
39import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
40import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
41import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
42import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
43
44/**
45 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
46 *
47 * <p>Original source:
48 * <code><pre>
49 * pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
50 * // results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
51 * // results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
52 * // ...OR...
53 * // results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
54 * // results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
55 * Train(train);
56 * Train.location(train, location);
57 * Segment.connectedTo(location, end);
58 * neg find multipleConnectedTo(end);
59 * }
60 * </pre></code>
61 *
62 * @see Matcher
63 * @see Match
64 *
65 */
66@SuppressWarnings("all")
67public final class EndOfSiding_step_5 extends BaseGeneratedEMFQuerySpecification<EndOfSiding_step_5.Matcher> {
68 /**
69 * Pattern-specific match representation of the modes3.queries.endOfSiding_step_5 pattern,
70 * to be used in conjunction with {@link Matcher}.
71 *
72 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
73 * Each instance is a (possibly partial) substitution of pattern parameters,
74 * usable to represent a match of the pattern in the result of a query,
75 * or to specify the bound (fixed) input parameters when issuing a query.
76 *
77 * @see Matcher
78 *
79 */
80 public static abstract class Match extends BasePatternMatch {
81 private Train fTrain;
82
83 private Segment fLocation;
84
85 private Segment fEnd;
86
87 private static List<String> parameterNames = makeImmutableList("train", "location", "end");
88
89 private Match(final Train pTrain, final Segment pLocation, final Segment pEnd) {
90 this.fTrain = pTrain;
91 this.fLocation = pLocation;
92 this.fEnd = pEnd;
93 }
94
95 @Override
96 public Object get(final String parameterName) {
97 switch(parameterName) {
98 case "train": return this.fTrain;
99 case "location": return this.fLocation;
100 case "end": return this.fEnd;
101 default: return null;
102 }
103 }
104
105 @Override
106 public Object get(final int index) {
107 switch(index) {
108 case 0: return this.fTrain;
109 case 1: return this.fLocation;
110 case 2: return this.fEnd;
111 default: return null;
112 }
113 }
114
115 public Train getTrain() {
116 return this.fTrain;
117 }
118
119 public Segment getLocation() {
120 return this.fLocation;
121 }
122
123 public Segment getEnd() {
124 return this.fEnd;
125 }
126
127 @Override
128 public boolean set(final String parameterName, final Object newValue) {
129 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
130 if ("train".equals(parameterName) ) {
131 this.fTrain = (Train) newValue;
132 return true;
133 }
134 if ("location".equals(parameterName) ) {
135 this.fLocation = (Segment) newValue;
136 return true;
137 }
138 if ("end".equals(parameterName) ) {
139 this.fEnd = (Segment) newValue;
140 return true;
141 }
142 return false;
143 }
144
145 public void setTrain(final Train pTrain) {
146 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
147 this.fTrain = pTrain;
148 }
149
150 public void setLocation(final Segment pLocation) {
151 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
152 this.fLocation = pLocation;
153 }
154
155 public void setEnd(final Segment pEnd) {
156 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
157 this.fEnd = pEnd;
158 }
159
160 @Override
161 public String patternName() {
162 return "modes3.queries.endOfSiding_step_5";
163 }
164
165 @Override
166 public List<String> parameterNames() {
167 return EndOfSiding_step_5.Match.parameterNames;
168 }
169
170 @Override
171 public Object[] toArray() {
172 return new Object[]{fTrain, fLocation, fEnd};
173 }
174
175 @Override
176 public EndOfSiding_step_5.Match toImmutable() {
177 return isMutable() ? newMatch(fTrain, fLocation, fEnd) : this;
178 }
179
180 @Override
181 public String prettyPrint() {
182 StringBuilder result = new StringBuilder();
183 result.append("\"train\"=" + prettyPrintValue(fTrain) + ", ");
184 result.append("\"location\"=" + prettyPrintValue(fLocation) + ", ");
185 result.append("\"end\"=" + prettyPrintValue(fEnd));
186 return result.toString();
187 }
188
189 @Override
190 public int hashCode() {
191 return Objects.hash(fTrain, fLocation, fEnd);
192 }
193
194 @Override
195 public boolean equals(final Object obj) {
196 if (this == obj)
197 return true;
198 if (obj == null) {
199 return false;
200 }
201 if ((obj instanceof EndOfSiding_step_5.Match)) {
202 EndOfSiding_step_5.Match other = (EndOfSiding_step_5.Match) obj;
203 return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation) && Objects.equals(fEnd, other.fEnd);
204 } else {
205 // this should be infrequent
206 if (!(obj instanceof IPatternMatch)) {
207 return false;
208 }
209 IPatternMatch otherSig = (IPatternMatch) obj;
210 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
211 }
212 }
213
214 @Override
215 public EndOfSiding_step_5 specification() {
216 return EndOfSiding_step_5.instance();
217 }
218
219 /**
220 * Returns an empty, mutable match.
221 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
222 *
223 * @return the empty match.
224 *
225 */
226 public static EndOfSiding_step_5.Match newEmptyMatch() {
227 return new Mutable(null, null, null);
228 }
229
230 /**
231 * Returns a mutable (partial) match.
232 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
233 *
234 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
235 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
236 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
237 * @return the new, mutable (partial) match object.
238 *
239 */
240 public static EndOfSiding_step_5.Match newMutableMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
241 return new Mutable(pTrain, pLocation, pEnd);
242 }
243
244 /**
245 * Returns a new (partial) match.
246 * This can be used e.g. to call the matcher with a partial match.
247 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
248 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
249 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
250 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
251 * @return the (partial) match object.
252 *
253 */
254 public static EndOfSiding_step_5.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
255 return new Immutable(pTrain, pLocation, pEnd);
256 }
257
258 private static final class Mutable extends EndOfSiding_step_5.Match {
259 Mutable(final Train pTrain, final Segment pLocation, final Segment pEnd) {
260 super(pTrain, pLocation, pEnd);
261 }
262
263 @Override
264 public boolean isMutable() {
265 return true;
266 }
267 }
268
269 private static final class Immutable extends EndOfSiding_step_5.Match {
270 Immutable(final Train pTrain, final Segment pLocation, final Segment pEnd) {
271 super(pTrain, pLocation, pEnd);
272 }
273
274 @Override
275 public boolean isMutable() {
276 return false;
277 }
278 }
279 }
280
281 /**
282 * Generated pattern matcher API of the modes3.queries.endOfSiding_step_5 pattern,
283 * providing pattern-specific query methods.
284 *
285 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
286 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
287 *
288 * <p>Matches of the pattern will be represented as {@link Match}.
289 *
290 * <p>Original source:
291 * <code><pre>
292 * pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
293 * // results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
294 * // results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
295 * // ...OR...
296 * // results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
297 * // results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
298 * Train(train);
299 * Train.location(train, location);
300 * Segment.connectedTo(location, end);
301 * neg find multipleConnectedTo(end);
302 * }
303 * </pre></code>
304 *
305 * @see Match
306 * @see EndOfSiding_step_5
307 *
308 */
309 public static class Matcher extends BaseMatcher<EndOfSiding_step_5.Match> {
310 /**
311 * Initializes the pattern matcher within an existing VIATRA Query engine.
312 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
313 *
314 * @param engine the existing VIATRA Query engine in which this matcher will be created.
315 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
316 *
317 */
318 public static EndOfSiding_step_5.Matcher on(final ViatraQueryEngine engine) {
319 // check if matcher already exists
320 Matcher matcher = engine.getExistingMatcher(querySpecification());
321 if (matcher == null) {
322 matcher = (Matcher)engine.getMatcher(querySpecification());
323 }
324 return matcher;
325 }
326
327 /**
328 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
329 * @return an initialized matcher
330 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
331 *
332 */
333 public static EndOfSiding_step_5.Matcher create() {
334 return new Matcher();
335 }
336
337 private static final int POSITION_TRAIN = 0;
338
339 private static final int POSITION_LOCATION = 1;
340
341 private static final int POSITION_END = 2;
342
343 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_5.Matcher.class);
344
345 /**
346 * Initializes the pattern matcher within an existing VIATRA Query engine.
347 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
348 *
349 * @param engine the existing VIATRA Query engine in which this matcher will be created.
350 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
351 *
352 */
353 private Matcher() {
354 super(querySpecification());
355 }
356
357 /**
358 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
359 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
360 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
361 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
362 * @return matches represented as a Match object.
363 *
364 */
365 public Collection<EndOfSiding_step_5.Match> getAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) {
366 return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}).collect(Collectors.toSet());
367 }
368
369 /**
370 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
371 * </p>
372 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
373 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
374 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
375 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
376 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
377 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
378 * @return a stream of matches represented as a Match object.
379 *
380 */
381 public Stream<EndOfSiding_step_5.Match> streamAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) {
382 return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd});
383 }
384
385 /**
386 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
387 * Neither determinism nor randomness of selection is guaranteed.
388 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
389 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
390 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
391 * @return a match represented as a Match object, or null if no match is found.
392 *
393 */
394 public Optional<EndOfSiding_step_5.Match> getOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
395 return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd});
396 }
397
398 /**
399 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
400 * under any possible substitution of the unspecified parameters (if any).
401 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
402 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
403 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
404 * @return true if the input is a valid (partial) match of the pattern.
405 *
406 */
407 public boolean hasMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
408 return rawHasMatch(new Object[]{pTrain, pLocation, pEnd});
409 }
410
411 /**
412 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
413 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
414 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
415 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
416 * @return the number of pattern matches found.
417 *
418 */
419 public int countMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) {
420 return rawCountMatches(new Object[]{pTrain, pLocation, pEnd});
421 }
422
423 /**
424 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
425 * Neither determinism nor randomness of selection is guaranteed.
426 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
427 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
428 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
429 * @param processor the action that will process the selected match.
430 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
431 *
432 */
433 public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd, final Consumer<? super EndOfSiding_step_5.Match> processor) {
434 return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}, processor);
435 }
436
437 /**
438 * Returns a new (partial) match.
439 * This can be used e.g. to call the matcher with a partial match.
440 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
441 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
442 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
443 * @param pEnd the fixed value of pattern parameter end, or null if not bound.
444 * @return the (partial) match object.
445 *
446 */
447 public EndOfSiding_step_5.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) {
448 return EndOfSiding_step_5.Match.newMatch(pTrain, pLocation, pEnd);
449 }
450
451 /**
452 * Retrieve the set of values that occur in matches for train.
453 * @return the Set of all values or empty set if there are no matches
454 *
455 */
456 protected Stream<Train> rawStreamAllValuesOftrain(final Object[] parameters) {
457 return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast);
458 }
459
460 /**
461 * Retrieve the set of values that occur in matches for train.
462 * @return the Set of all values or empty set if there are no matches
463 *
464 */
465 public Set<Train> getAllValuesOftrain() {
466 return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet());
467 }
468
469 /**
470 * Retrieve the set of values that occur in matches for train.
471 * @return the Set of all values or empty set if there are no matches
472 *
473 */
474 public Stream<Train> streamAllValuesOftrain() {
475 return rawStreamAllValuesOftrain(emptyArray());
476 }
477
478 /**
479 * Retrieve the set of values that occur in matches for train.
480 * </p>
481 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
482 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
483 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
484 *
485 * @return the Stream of all values or empty set if there are no matches
486 *
487 */
488 public Stream<Train> streamAllValuesOftrain(final EndOfSiding_step_5.Match partialMatch) {
489 return rawStreamAllValuesOftrain(partialMatch.toArray());
490 }
491
492 /**
493 * Retrieve the set of values that occur in matches for train.
494 * </p>
495 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
496 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
497 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
498 *
499 * @return the Stream of all values or empty set if there are no matches
500 *
501 */
502 public Stream<Train> streamAllValuesOftrain(final Segment pLocation, final Segment pEnd) {
503 return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd});
504 }
505
506 /**
507 * Retrieve the set of values that occur in matches for train.
508 * @return the Set of all values or empty set if there are no matches
509 *
510 */
511 public Set<Train> getAllValuesOftrain(final EndOfSiding_step_5.Match partialMatch) {
512 return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet());
513 }
514
515 /**
516 * Retrieve the set of values that occur in matches for train.
517 * @return the Set of all values or empty set if there are no matches
518 *
519 */
520 public Set<Train> getAllValuesOftrain(final Segment pLocation, final Segment pEnd) {
521 return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}).collect(Collectors.toSet());
522 }
523
524 /**
525 * Retrieve the set of values that occur in matches for location.
526 * @return the Set of all values or empty set if there are no matches
527 *
528 */
529 protected Stream<Segment> rawStreamAllValuesOflocation(final Object[] parameters) {
530 return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast);
531 }
532
533 /**
534 * Retrieve the set of values that occur in matches for location.
535 * @return the Set of all values or empty set if there are no matches
536 *
537 */
538 public Set<Segment> getAllValuesOflocation() {
539 return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet());
540 }
541
542 /**
543 * Retrieve the set of values that occur in matches for location.
544 * @return the Set of all values or empty set if there are no matches
545 *
546 */
547 public Stream<Segment> streamAllValuesOflocation() {
548 return rawStreamAllValuesOflocation(emptyArray());
549 }
550
551 /**
552 * Retrieve the set of values that occur in matches for location.
553 * </p>
554 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
555 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
556 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
557 *
558 * @return the Stream of all values or empty set if there are no matches
559 *
560 */
561 public Stream<Segment> streamAllValuesOflocation(final EndOfSiding_step_5.Match partialMatch) {
562 return rawStreamAllValuesOflocation(partialMatch.toArray());
563 }
564
565 /**
566 * Retrieve the set of values that occur in matches for location.
567 * </p>
568 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
569 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
570 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
571 *
572 * @return the Stream of all values or empty set if there are no matches
573 *
574 */
575 public Stream<Segment> streamAllValuesOflocation(final Train pTrain, final Segment pEnd) {
576 return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd});
577 }
578
579 /**
580 * Retrieve the set of values that occur in matches for location.
581 * @return the Set of all values or empty set if there are no matches
582 *
583 */
584 public Set<Segment> getAllValuesOflocation(final EndOfSiding_step_5.Match partialMatch) {
585 return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet());
586 }
587
588 /**
589 * Retrieve the set of values that occur in matches for location.
590 * @return the Set of all values or empty set if there are no matches
591 *
592 */
593 public Set<Segment> getAllValuesOflocation(final Train pTrain, final Segment pEnd) {
594 return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}).collect(Collectors.toSet());
595 }
596
597 /**
598 * Retrieve the set of values that occur in matches for end.
599 * @return the Set of all values or empty set if there are no matches
600 *
601 */
602 protected Stream<Segment> rawStreamAllValuesOfend(final Object[] parameters) {
603 return rawStreamAllValues(POSITION_END, parameters).map(Segment.class::cast);
604 }
605
606 /**
607 * Retrieve the set of values that occur in matches for end.
608 * @return the Set of all values or empty set if there are no matches
609 *
610 */
611 public Set<Segment> getAllValuesOfend() {
612 return rawStreamAllValuesOfend(emptyArray()).collect(Collectors.toSet());
613 }
614
615 /**
616 * Retrieve the set of values that occur in matches for end.
617 * @return the Set of all values or empty set if there are no matches
618 *
619 */
620 public Stream<Segment> streamAllValuesOfend() {
621 return rawStreamAllValuesOfend(emptyArray());
622 }
623
624 /**
625 * Retrieve the set of values that occur in matches for end.
626 * </p>
627 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
628 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
629 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
630 *
631 * @return the Stream of all values or empty set if there are no matches
632 *
633 */
634 public Stream<Segment> streamAllValuesOfend(final EndOfSiding_step_5.Match partialMatch) {
635 return rawStreamAllValuesOfend(partialMatch.toArray());
636 }
637
638 /**
639 * Retrieve the set of values that occur in matches for end.
640 * </p>
641 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
642 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
643 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
644 *
645 * @return the Stream of all values or empty set if there are no matches
646 *
647 */
648 public Stream<Segment> streamAllValuesOfend(final Train pTrain, final Segment pLocation) {
649 return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null});
650 }
651
652 /**
653 * Retrieve the set of values that occur in matches for end.
654 * @return the Set of all values or empty set if there are no matches
655 *
656 */
657 public Set<Segment> getAllValuesOfend(final EndOfSiding_step_5.Match partialMatch) {
658 return rawStreamAllValuesOfend(partialMatch.toArray()).collect(Collectors.toSet());
659 }
660
661 /**
662 * Retrieve the set of values that occur in matches for end.
663 * @return the Set of all values or empty set if there are no matches
664 *
665 */
666 public Set<Segment> getAllValuesOfend(final Train pTrain, final Segment pLocation) {
667 return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}).collect(Collectors.toSet());
668 }
669
670 @Override
671 protected EndOfSiding_step_5.Match tupleToMatch(final Tuple t) {
672 try {
673 return EndOfSiding_step_5.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION), (Segment) t.get(POSITION_END));
674 } catch(ClassCastException e) {
675 LOGGER.error("Element(s) in tuple not properly typed!",e);
676 return null;
677 }
678 }
679
680 @Override
681 protected EndOfSiding_step_5.Match arrayToMatch(final Object[] match) {
682 try {
683 return EndOfSiding_step_5.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]);
684 } catch(ClassCastException e) {
685 LOGGER.error("Element(s) in array not properly typed!",e);
686 return null;
687 }
688 }
689
690 @Override
691 protected EndOfSiding_step_5.Match arrayToMatchMutable(final Object[] match) {
692 try {
693 return EndOfSiding_step_5.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]);
694 } catch(ClassCastException e) {
695 LOGGER.error("Element(s) in array not properly typed!",e);
696 return null;
697 }
698 }
699
700 /**
701 * @return the singleton instance of the query specification of this pattern
702 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
703 *
704 */
705 public static IQuerySpecification<EndOfSiding_step_5.Matcher> querySpecification() {
706 return EndOfSiding_step_5.instance();
707 }
708 }
709
710 private EndOfSiding_step_5() {
711 super(GeneratedPQuery.INSTANCE);
712 }
713
714 /**
715 * @return the singleton instance of the query specification
716 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
717 *
718 */
719 public static EndOfSiding_step_5 instance() {
720 try{
721 return LazyHolder.INSTANCE;
722 } catch (ExceptionInInitializerError err) {
723 throw processInitializerError(err);
724 }
725 }
726
727 @Override
728 protected EndOfSiding_step_5.Matcher instantiate(final ViatraQueryEngine engine) {
729 return EndOfSiding_step_5.Matcher.on(engine);
730 }
731
732 @Override
733 public EndOfSiding_step_5.Matcher instantiate() {
734 return EndOfSiding_step_5.Matcher.create();
735 }
736
737 @Override
738 public EndOfSiding_step_5.Match newEmptyMatch() {
739 return EndOfSiding_step_5.Match.newEmptyMatch();
740 }
741
742 @Override
743 public EndOfSiding_step_5.Match newMatch(final Object... parameters) {
744 return EndOfSiding_step_5.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1], (modes3.Segment) parameters[2]);
745 }
746
747 /**
748 * Inner class allowing the singleton instance of {@link EndOfSiding_step_5} to be created
749 * <b>not</b> at the class load time of the outer class,
750 * but rather at the first call to {@link EndOfSiding_step_5#instance()}.
751 *
752 * <p> This workaround is required e.g. to support recursion.
753 *
754 */
755 private static class LazyHolder {
756 private static final EndOfSiding_step_5 INSTANCE = new EndOfSiding_step_5();
757
758 /**
759 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
760 * This initialization order is required to support indirect recursion.
761 *
762 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
763 *
764 */
765 private static final Object STATIC_INITIALIZER = ensureInitialized();
766
767 public static Object ensureInitialized() {
768 INSTANCE.ensureInitializedInternal();
769 return null;
770 }
771 }
772
773 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
774 private static final EndOfSiding_step_5.GeneratedPQuery INSTANCE = new GeneratedPQuery();
775
776 private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT);
777
778 private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
779
780 private final PParameter parameter_end = new PParameter("end", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
781
782 private final List<PParameter> parameters = Arrays.asList(parameter_train, parameter_location, parameter_end);
783
784 private GeneratedPQuery() {
785 super(PVisibility.PUBLIC);
786 }
787
788 @Override
789 public String getFullyQualifiedName() {
790 return "modes3.queries.endOfSiding_step_5";
791 }
792
793 @Override
794 public List<String> getParameterNames() {
795 return Arrays.asList("train","location","end");
796 }
797
798 @Override
799 public List<PParameter> getParameters() {
800 return parameters;
801 }
802
803 @Override
804 public Set<PBody> doGetContainedBodies() {
805 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
806 Set<PBody> bodies = new LinkedHashSet<>();
807 {
808 PBody body = new PBody(this);
809 PVariable var_train = body.getOrCreateVariableByName("train");
810 PVariable var_location = body.getOrCreateVariableByName("location");
811 PVariable var_end = body.getOrCreateVariableByName("end");
812 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
813 new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
814 new TypeConstraint(body, Tuples.flatTupleOf(var_end), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
815 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
816 new ExportedParameter(body, var_train, parameter_train),
817 new ExportedParameter(body, var_location, parameter_location),
818 new ExportedParameter(body, var_end, parameter_end)
819 ));
820 // // results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train;// ...OR...// results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train; Train(train)
821 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
822 // Train.location(train, location)
823 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
824 PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}");
825 new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location")));
826 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
827 new Equality(body, var__virtual_0_, var_location);
828 // Segment.connectedTo(location, end)
829 new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
830 PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}");
831 new TypeConstraint(body, Tuples.flatTupleOf(var_location, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo")));
832 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
833 new Equality(body, var__virtual_1_, var_end);
834 // neg find multipleConnectedTo(end)
835 new NegativePatternCall(body, Tuples.flatTupleOf(var_end), MultipleConnectedTo.instance().getInternalQueryRepresentation());
836 bodies.add(body);
837 }
838 return bodies;
839 }
840 }
841}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java
index 6e244430..d1238d61 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/Modes3Queries.java
@@ -4,16 +4,34 @@
4package modes3.queries; 4package modes3.queries;
5 5
6import modes3.queries.Adjacent; 6import modes3.queries.Adjacent;
7import modes3.queries.CloseTrains_step_2;
8import modes3.queries.CloseTrains_step_3;
9import modes3.queries.CloseTrains_step_4;
10import modes3.queries.CloseTrains_step_5;
11import modes3.queries.CloseTrains_step_6;
12import modes3.queries.CloseTrains_step_7;
13import modes3.queries.ConnectedSegmentsDirected;
7import modes3.queries.ConnectedTo; 14import modes3.queries.ConnectedTo;
8import modes3.queries.ConnectedToNotSymmetric; 15import modes3.queries.ConnectedToNotSymmetric;
9import modes3.queries.ConnectedToReflexive; 16import modes3.queries.ConnectedToReflexive;
17import modes3.queries.EndOfSiding_step_2;
18import modes3.queries.EndOfSiding_step_3;
19import modes3.queries.EndOfSiding_step_4;
20import modes3.queries.EndOfSiding_step_5;
10import modes3.queries.InputsOfTurnout; 21import modes3.queries.InputsOfTurnout;
22import modes3.queries.MisalignedTurnout_step_2;
23import modes3.queries.MisalignedTurnout_step_3;
24import modes3.queries.MisalignedTurnout_step_4;
25import modes3.queries.MisalignedTurnout_step_5;
26import modes3.queries.MultipleConnectedTo;
11import modes3.queries.Output; 27import modes3.queries.Output;
12import modes3.queries.OutputReflexive; 28import modes3.queries.OutputReflexive;
13import modes3.queries.Reachable; 29import modes3.queries.Reachable;
14import modes3.queries.TooFewInputsOfTurnout; 30import modes3.queries.TooFewInputsOfTurnout;
15import modes3.queries.TooManyInputsOfSegment; 31import modes3.queries.TooManyInputsOfSegment;
16import modes3.queries.TooManyInputsOfTurnout; 32import modes3.queries.TooManyInputsOfTurnout;
33import modes3.queries.TrainLocations_step_2;
34import modes3.queries.TrainLocations_step_3;
17import modes3.queries.TurnoutConnectedToBothOutputs; 35import modes3.queries.TurnoutConnectedToBothOutputs;
18import modes3.queries.TurnoutOutput; 36import modes3.queries.TurnoutOutput;
19import modes3.queries.TurnoutOutputsAreSame; 37import modes3.queries.TurnoutOutputsAreSame;
@@ -44,6 +62,24 @@ import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup;
44 * <li>tooFewInputsOfTurnout</li> 62 * <li>tooFewInputsOfTurnout</li>
45 * <li>reachable</li> 63 * <li>reachable</li>
46 * <li>unreachable</li> 64 * <li>unreachable</li>
65 * <li>closeTrains_step_2</li>
66 * <li>closeTrains_step_3</li>
67 * <li>closeTrains_step_4</li>
68 * <li>closeTrains_step_5</li>
69 * <li>closeTrains_step_6</li>
70 * <li>closeTrains_step_7</li>
71 * <li>trainLocations_step_2</li>
72 * <li>trainLocations_step_3</li>
73 * <li>misalignedTurnout_step_2</li>
74 * <li>misalignedTurnout_step_3</li>
75 * <li>misalignedTurnout_step_4</li>
76 * <li>misalignedTurnout_step_5</li>
77 * <li>connectedSegmentsDirected</li>
78 * <li>endOfSiding_step_2</li>
79 * <li>endOfSiding_step_3</li>
80 * <li>endOfSiding_step_4</li>
81 * <li>endOfSiding_step_5</li>
82 * <li>multipleConnectedTo</li>
47 * </ul> 83 * </ul>
48 * 84 *
49 * @see IQueryGroup 85 * @see IQueryGroup
@@ -83,6 +119,24 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup {
83 querySpecifications.add(TooFewInputsOfTurnout.instance()); 119 querySpecifications.add(TooFewInputsOfTurnout.instance());
84 querySpecifications.add(Reachable.instance()); 120 querySpecifications.add(Reachable.instance());
85 querySpecifications.add(Unreachable.instance()); 121 querySpecifications.add(Unreachable.instance());
122 querySpecifications.add(CloseTrains_step_2.instance());
123 querySpecifications.add(CloseTrains_step_3.instance());
124 querySpecifications.add(CloseTrains_step_4.instance());
125 querySpecifications.add(CloseTrains_step_5.instance());
126 querySpecifications.add(CloseTrains_step_6.instance());
127 querySpecifications.add(CloseTrains_step_7.instance());
128 querySpecifications.add(TrainLocations_step_2.instance());
129 querySpecifications.add(TrainLocations_step_3.instance());
130 querySpecifications.add(MisalignedTurnout_step_2.instance());
131 querySpecifications.add(MisalignedTurnout_step_3.instance());
132 querySpecifications.add(MisalignedTurnout_step_4.instance());
133 querySpecifications.add(MisalignedTurnout_step_5.instance());
134 querySpecifications.add(ConnectedSegmentsDirected.instance());
135 querySpecifications.add(EndOfSiding_step_2.instance());
136 querySpecifications.add(EndOfSiding_step_3.instance());
137 querySpecifications.add(EndOfSiding_step_4.instance());
138 querySpecifications.add(EndOfSiding_step_5.instance());
139 querySpecifications.add(MultipleConnectedTo.instance());
86 } 140 }
87 141
88 public ConnectedTo getConnectedTo() { 142 public ConnectedTo getConnectedTo() {
@@ -204,4 +258,148 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup {
204 public Unreachable.Matcher getUnreachable(final ViatraQueryEngine engine) { 258 public Unreachable.Matcher getUnreachable(final ViatraQueryEngine engine) {
205 return Unreachable.Matcher.on(engine); 259 return Unreachable.Matcher.on(engine);
206 } 260 }
261
262 public CloseTrains_step_2 getCloseTrains_step_2() {
263 return CloseTrains_step_2.instance();
264 }
265
266 public CloseTrains_step_2.Matcher getCloseTrains_step_2(final ViatraQueryEngine engine) {
267 return CloseTrains_step_2.Matcher.on(engine);
268 }
269
270 public CloseTrains_step_3 getCloseTrains_step_3() {
271 return CloseTrains_step_3.instance();
272 }
273
274 public CloseTrains_step_3.Matcher getCloseTrains_step_3(final ViatraQueryEngine engine) {
275 return CloseTrains_step_3.Matcher.on(engine);
276 }
277
278 public CloseTrains_step_4 getCloseTrains_step_4() {
279 return CloseTrains_step_4.instance();
280 }
281
282 public CloseTrains_step_4.Matcher getCloseTrains_step_4(final ViatraQueryEngine engine) {
283 return CloseTrains_step_4.Matcher.on(engine);
284 }
285
286 public CloseTrains_step_5 getCloseTrains_step_5() {
287 return CloseTrains_step_5.instance();
288 }
289
290 public CloseTrains_step_5.Matcher getCloseTrains_step_5(final ViatraQueryEngine engine) {
291 return CloseTrains_step_5.Matcher.on(engine);
292 }
293
294 public CloseTrains_step_6 getCloseTrains_step_6() {
295 return CloseTrains_step_6.instance();
296 }
297
298 public CloseTrains_step_6.Matcher getCloseTrains_step_6(final ViatraQueryEngine engine) {
299 return CloseTrains_step_6.Matcher.on(engine);
300 }
301
302 public CloseTrains_step_7 getCloseTrains_step_7() {
303 return CloseTrains_step_7.instance();
304 }
305
306 public CloseTrains_step_7.Matcher getCloseTrains_step_7(final ViatraQueryEngine engine) {
307 return CloseTrains_step_7.Matcher.on(engine);
308 }
309
310 public TrainLocations_step_2 getTrainLocations_step_2() {
311 return TrainLocations_step_2.instance();
312 }
313
314 public TrainLocations_step_2.Matcher getTrainLocations_step_2(final ViatraQueryEngine engine) {
315 return TrainLocations_step_2.Matcher.on(engine);
316 }
317
318 public TrainLocations_step_3 getTrainLocations_step_3() {
319 return TrainLocations_step_3.instance();
320 }
321
322 public TrainLocations_step_3.Matcher getTrainLocations_step_3(final ViatraQueryEngine engine) {
323 return TrainLocations_step_3.Matcher.on(engine);
324 }
325
326 public MisalignedTurnout_step_2 getMisalignedTurnout_step_2() {
327 return MisalignedTurnout_step_2.instance();
328 }
329
330 public MisalignedTurnout_step_2.Matcher getMisalignedTurnout_step_2(final ViatraQueryEngine engine) {
331 return MisalignedTurnout_step_2.Matcher.on(engine);
332 }
333
334 public MisalignedTurnout_step_3 getMisalignedTurnout_step_3() {
335 return MisalignedTurnout_step_3.instance();
336 }
337
338 public MisalignedTurnout_step_3.Matcher getMisalignedTurnout_step_3(final ViatraQueryEngine engine) {
339 return MisalignedTurnout_step_3.Matcher.on(engine);
340 }
341
342 public MisalignedTurnout_step_4 getMisalignedTurnout_step_4() {
343 return MisalignedTurnout_step_4.instance();
344 }
345
346 public MisalignedTurnout_step_4.Matcher getMisalignedTurnout_step_4(final ViatraQueryEngine engine) {
347 return MisalignedTurnout_step_4.Matcher.on(engine);
348 }
349
350 public MisalignedTurnout_step_5 getMisalignedTurnout_step_5() {
351 return MisalignedTurnout_step_5.instance();
352 }
353
354 public MisalignedTurnout_step_5.Matcher getMisalignedTurnout_step_5(final ViatraQueryEngine engine) {
355 return MisalignedTurnout_step_5.Matcher.on(engine);
356 }
357
358 public ConnectedSegmentsDirected getConnectedSegmentsDirected() {
359 return ConnectedSegmentsDirected.instance();
360 }
361
362 public ConnectedSegmentsDirected.Matcher getConnectedSegmentsDirected(final ViatraQueryEngine engine) {
363 return ConnectedSegmentsDirected.Matcher.on(engine);
364 }
365
366 public EndOfSiding_step_2 getEndOfSiding_step_2() {
367 return EndOfSiding_step_2.instance();
368 }
369
370 public EndOfSiding_step_2.Matcher getEndOfSiding_step_2(final ViatraQueryEngine engine) {
371 return EndOfSiding_step_2.Matcher.on(engine);
372 }
373
374 public EndOfSiding_step_3 getEndOfSiding_step_3() {
375 return EndOfSiding_step_3.instance();
376 }
377
378 public EndOfSiding_step_3.Matcher getEndOfSiding_step_3(final ViatraQueryEngine engine) {
379 return EndOfSiding_step_3.Matcher.on(engine);
380 }
381
382 public EndOfSiding_step_4 getEndOfSiding_step_4() {
383 return EndOfSiding_step_4.instance();
384 }
385
386 public EndOfSiding_step_4.Matcher getEndOfSiding_step_4(final ViatraQueryEngine engine) {
387 return EndOfSiding_step_4.Matcher.on(engine);
388 }
389
390 public EndOfSiding_step_5 getEndOfSiding_step_5() {
391 return EndOfSiding_step_5.instance();
392 }
393
394 public EndOfSiding_step_5.Matcher getEndOfSiding_step_5(final ViatraQueryEngine engine) {
395 return EndOfSiding_step_5.Matcher.on(engine);
396 }
397
398 public MultipleConnectedTo getMultipleConnectedTo() {
399 return MultipleConnectedTo.instance();
400 }
401
402 public MultipleConnectedTo.Matcher getMultipleConnectedTo(final ViatraQueryEngine engine) {
403 return MultipleConnectedTo.Matcher.on(engine);
404 }
207} 405}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java
new file mode 100644
index 00000000..277006c9
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java
@@ -0,0 +1,565 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Segment;
17import org.apache.log4j.Logger;
18import org.eclipse.emf.ecore.EClass;
19import org.eclipse.viatra.query.runtime.api.IPatternMatch;
20import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
21import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
22import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
23import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
24import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
25import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
26import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
27import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey;
28import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
29import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
30import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
31import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality;
32import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
33import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality;
34import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
35import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
36import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
37import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
38import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
39import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
40import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
41
42/**
43 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
44 *
45 * <p>Original source:
46 * <code><pre>
47 * pattern multipleConnectedTo(s : Segment) {
48 * Segment.connectedTo(s, n1);
49 * Segment.connectedTo(s, n2);
50 * n1 != n2;
51 * }
52 * </pre></code>
53 *
54 * @see Matcher
55 * @see Match
56 *
57 */
58@SuppressWarnings("all")
59public final class MultipleConnectedTo extends BaseGeneratedEMFQuerySpecification<MultipleConnectedTo.Matcher> {
60 /**
61 * Pattern-specific match representation of the modes3.queries.multipleConnectedTo pattern,
62 * to be used in conjunction with {@link Matcher}.
63 *
64 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
65 * Each instance is a (possibly partial) substitution of pattern parameters,
66 * usable to represent a match of the pattern in the result of a query,
67 * or to specify the bound (fixed) input parameters when issuing a query.
68 *
69 * @see Matcher
70 *
71 */
72 public static abstract class Match extends BasePatternMatch {
73 private Segment fS;
74
75 private static List<String> parameterNames = makeImmutableList("s");
76
77 private Match(final Segment pS) {
78 this.fS = pS;
79 }
80
81 @Override
82 public Object get(final String parameterName) {
83 switch(parameterName) {
84 case "s": return this.fS;
85 default: return null;
86 }
87 }
88
89 @Override
90 public Object get(final int index) {
91 switch(index) {
92 case 0: return this.fS;
93 default: return null;
94 }
95 }
96
97 public Segment getS() {
98 return this.fS;
99 }
100
101 @Override
102 public boolean set(final String parameterName, final Object newValue) {
103 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
104 if ("s".equals(parameterName) ) {
105 this.fS = (Segment) newValue;
106 return true;
107 }
108 return false;
109 }
110
111 public void setS(final Segment pS) {
112 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
113 this.fS = pS;
114 }
115
116 @Override
117 public String patternName() {
118 return "modes3.queries.multipleConnectedTo";
119 }
120
121 @Override
122 public List<String> parameterNames() {
123 return MultipleConnectedTo.Match.parameterNames;
124 }
125
126 @Override
127 public Object[] toArray() {
128 return new Object[]{fS};
129 }
130
131 @Override
132 public MultipleConnectedTo.Match toImmutable() {
133 return isMutable() ? newMatch(fS) : this;
134 }
135
136 @Override
137 public String prettyPrint() {
138 StringBuilder result = new StringBuilder();
139 result.append("\"s\"=" + prettyPrintValue(fS));
140 return result.toString();
141 }
142
143 @Override
144 public int hashCode() {
145 return Objects.hash(fS);
146 }
147
148 @Override
149 public boolean equals(final Object obj) {
150 if (this == obj)
151 return true;
152 if (obj == null) {
153 return false;
154 }
155 if ((obj instanceof MultipleConnectedTo.Match)) {
156 MultipleConnectedTo.Match other = (MultipleConnectedTo.Match) obj;
157 return Objects.equals(fS, other.fS);
158 } else {
159 // this should be infrequent
160 if (!(obj instanceof IPatternMatch)) {
161 return false;
162 }
163 IPatternMatch otherSig = (IPatternMatch) obj;
164 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
165 }
166 }
167
168 @Override
169 public MultipleConnectedTo specification() {
170 return MultipleConnectedTo.instance();
171 }
172
173 /**
174 * Returns an empty, mutable match.
175 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
176 *
177 * @return the empty match.
178 *
179 */
180 public static MultipleConnectedTo.Match newEmptyMatch() {
181 return new Mutable(null);
182 }
183
184 /**
185 * Returns a mutable (partial) match.
186 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
187 *
188 * @param pS the fixed value of pattern parameter s, or null if not bound.
189 * @return the new, mutable (partial) match object.
190 *
191 */
192 public static MultipleConnectedTo.Match newMutableMatch(final Segment pS) {
193 return new Mutable(pS);
194 }
195
196 /**
197 * Returns a new (partial) match.
198 * This can be used e.g. to call the matcher with a partial match.
199 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
200 * @param pS the fixed value of pattern parameter s, or null if not bound.
201 * @return the (partial) match object.
202 *
203 */
204 public static MultipleConnectedTo.Match newMatch(final Segment pS) {
205 return new Immutable(pS);
206 }
207
208 private static final class Mutable extends MultipleConnectedTo.Match {
209 Mutable(final Segment pS) {
210 super(pS);
211 }
212
213 @Override
214 public boolean isMutable() {
215 return true;
216 }
217 }
218
219 private static final class Immutable extends MultipleConnectedTo.Match {
220 Immutable(final Segment pS) {
221 super(pS);
222 }
223
224 @Override
225 public boolean isMutable() {
226 return false;
227 }
228 }
229 }
230
231 /**
232 * Generated pattern matcher API of the modes3.queries.multipleConnectedTo pattern,
233 * providing pattern-specific query methods.
234 *
235 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
236 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
237 *
238 * <p>Matches of the pattern will be represented as {@link Match}.
239 *
240 * <p>Original source:
241 * <code><pre>
242 * pattern multipleConnectedTo(s : Segment) {
243 * Segment.connectedTo(s, n1);
244 * Segment.connectedTo(s, n2);
245 * n1 != n2;
246 * }
247 * </pre></code>
248 *
249 * @see Match
250 * @see MultipleConnectedTo
251 *
252 */
253 public static class Matcher extends BaseMatcher<MultipleConnectedTo.Match> {
254 /**
255 * Initializes the pattern matcher within an existing VIATRA Query engine.
256 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
257 *
258 * @param engine the existing VIATRA Query engine in which this matcher will be created.
259 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
260 *
261 */
262 public static MultipleConnectedTo.Matcher on(final ViatraQueryEngine engine) {
263 // check if matcher already exists
264 Matcher matcher = engine.getExistingMatcher(querySpecification());
265 if (matcher == null) {
266 matcher = (Matcher)engine.getMatcher(querySpecification());
267 }
268 return matcher;
269 }
270
271 /**
272 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
273 * @return an initialized matcher
274 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
275 *
276 */
277 public static MultipleConnectedTo.Matcher create() {
278 return new Matcher();
279 }
280
281 private static final int POSITION_S = 0;
282
283 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(MultipleConnectedTo.Matcher.class);
284
285 /**
286 * Initializes the pattern matcher within an existing VIATRA Query engine.
287 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
288 *
289 * @param engine the existing VIATRA Query engine in which this matcher will be created.
290 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
291 *
292 */
293 private Matcher() {
294 super(querySpecification());
295 }
296
297 /**
298 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
299 * @param pS the fixed value of pattern parameter s, or null if not bound.
300 * @return matches represented as a Match object.
301 *
302 */
303 public Collection<MultipleConnectedTo.Match> getAllMatches(final Segment pS) {
304 return rawStreamAllMatches(new Object[]{pS}).collect(Collectors.toSet());
305 }
306
307 /**
308 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
309 * </p>
310 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
311 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
312 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
313 * @param pS the fixed value of pattern parameter s, or null if not bound.
314 * @return a stream of matches represented as a Match object.
315 *
316 */
317 public Stream<MultipleConnectedTo.Match> streamAllMatches(final Segment pS) {
318 return rawStreamAllMatches(new Object[]{pS});
319 }
320
321 /**
322 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
323 * Neither determinism nor randomness of selection is guaranteed.
324 * @param pS the fixed value of pattern parameter s, or null if not bound.
325 * @return a match represented as a Match object, or null if no match is found.
326 *
327 */
328 public Optional<MultipleConnectedTo.Match> getOneArbitraryMatch(final Segment pS) {
329 return rawGetOneArbitraryMatch(new Object[]{pS});
330 }
331
332 /**
333 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
334 * under any possible substitution of the unspecified parameters (if any).
335 * @param pS the fixed value of pattern parameter s, or null if not bound.
336 * @return true if the input is a valid (partial) match of the pattern.
337 *
338 */
339 public boolean hasMatch(final Segment pS) {
340 return rawHasMatch(new Object[]{pS});
341 }
342
343 /**
344 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
345 * @param pS the fixed value of pattern parameter s, or null if not bound.
346 * @return the number of pattern matches found.
347 *
348 */
349 public int countMatches(final Segment pS) {
350 return rawCountMatches(new Object[]{pS});
351 }
352
353 /**
354 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
355 * Neither determinism nor randomness of selection is guaranteed.
356 * @param pS the fixed value of pattern parameter s, or null if not bound.
357 * @param processor the action that will process the selected match.
358 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
359 *
360 */
361 public boolean forOneArbitraryMatch(final Segment pS, final Consumer<? super MultipleConnectedTo.Match> processor) {
362 return rawForOneArbitraryMatch(new Object[]{pS}, processor);
363 }
364
365 /**
366 * Returns a new (partial) match.
367 * This can be used e.g. to call the matcher with a partial match.
368 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
369 * @param pS the fixed value of pattern parameter s, or null if not bound.
370 * @return the (partial) match object.
371 *
372 */
373 public MultipleConnectedTo.Match newMatch(final Segment pS) {
374 return MultipleConnectedTo.Match.newMatch(pS);
375 }
376
377 /**
378 * Retrieve the set of values that occur in matches for s.
379 * @return the Set of all values or empty set if there are no matches
380 *
381 */
382 protected Stream<Segment> rawStreamAllValuesOfs(final Object[] parameters) {
383 return rawStreamAllValues(POSITION_S, parameters).map(Segment.class::cast);
384 }
385
386 /**
387 * Retrieve the set of values that occur in matches for s.
388 * @return the Set of all values or empty set if there are no matches
389 *
390 */
391 public Set<Segment> getAllValuesOfs() {
392 return rawStreamAllValuesOfs(emptyArray()).collect(Collectors.toSet());
393 }
394
395 /**
396 * Retrieve the set of values that occur in matches for s.
397 * @return the Set of all values or empty set if there are no matches
398 *
399 */
400 public Stream<Segment> streamAllValuesOfs() {
401 return rawStreamAllValuesOfs(emptyArray());
402 }
403
404 @Override
405 protected MultipleConnectedTo.Match tupleToMatch(final Tuple t) {
406 try {
407 return MultipleConnectedTo.Match.newMatch((Segment) t.get(POSITION_S));
408 } catch(ClassCastException e) {
409 LOGGER.error("Element(s) in tuple not properly typed!",e);
410 return null;
411 }
412 }
413
414 @Override
415 protected MultipleConnectedTo.Match arrayToMatch(final Object[] match) {
416 try {
417 return MultipleConnectedTo.Match.newMatch((Segment) match[POSITION_S]);
418 } catch(ClassCastException e) {
419 LOGGER.error("Element(s) in array not properly typed!",e);
420 return null;
421 }
422 }
423
424 @Override
425 protected MultipleConnectedTo.Match arrayToMatchMutable(final Object[] match) {
426 try {
427 return MultipleConnectedTo.Match.newMutableMatch((Segment) match[POSITION_S]);
428 } catch(ClassCastException e) {
429 LOGGER.error("Element(s) in array not properly typed!",e);
430 return null;
431 }
432 }
433
434 /**
435 * @return the singleton instance of the query specification of this pattern
436 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
437 *
438 */
439 public static IQuerySpecification<MultipleConnectedTo.Matcher> querySpecification() {
440 return MultipleConnectedTo.instance();
441 }
442 }
443
444 private MultipleConnectedTo() {
445 super(GeneratedPQuery.INSTANCE);
446 }
447
448 /**
449 * @return the singleton instance of the query specification
450 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
451 *
452 */
453 public static MultipleConnectedTo instance() {
454 try{
455 return LazyHolder.INSTANCE;
456 } catch (ExceptionInInitializerError err) {
457 throw processInitializerError(err);
458 }
459 }
460
461 @Override
462 protected MultipleConnectedTo.Matcher instantiate(final ViatraQueryEngine engine) {
463 return MultipleConnectedTo.Matcher.on(engine);
464 }
465
466 @Override
467 public MultipleConnectedTo.Matcher instantiate() {
468 return MultipleConnectedTo.Matcher.create();
469 }
470
471 @Override
472 public MultipleConnectedTo.Match newEmptyMatch() {
473 return MultipleConnectedTo.Match.newEmptyMatch();
474 }
475
476 @Override
477 public MultipleConnectedTo.Match newMatch(final Object... parameters) {
478 return MultipleConnectedTo.Match.newMatch((modes3.Segment) parameters[0]);
479 }
480
481 /**
482 * Inner class allowing the singleton instance of {@link MultipleConnectedTo} to be created
483 * <b>not</b> at the class load time of the outer class,
484 * but rather at the first call to {@link MultipleConnectedTo#instance()}.
485 *
486 * <p> This workaround is required e.g. to support recursion.
487 *
488 */
489 private static class LazyHolder {
490 private static final MultipleConnectedTo INSTANCE = new MultipleConnectedTo();
491
492 /**
493 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
494 * This initialization order is required to support indirect recursion.
495 *
496 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
497 *
498 */
499 private static final Object STATIC_INITIALIZER = ensureInitialized();
500
501 public static Object ensureInitialized() {
502 INSTANCE.ensureInitializedInternal();
503 return null;
504 }
505 }
506
507 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
508 private static final MultipleConnectedTo.GeneratedPQuery INSTANCE = new GeneratedPQuery();
509
510 private final PParameter parameter_s = new PParameter("s", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
511
512 private final List<PParameter> parameters = Arrays.asList(parameter_s);
513
514 private GeneratedPQuery() {
515 super(PVisibility.PUBLIC);
516 }
517
518 @Override
519 public String getFullyQualifiedName() {
520 return "modes3.queries.multipleConnectedTo";
521 }
522
523 @Override
524 public List<String> getParameterNames() {
525 return Arrays.asList("s");
526 }
527
528 @Override
529 public List<PParameter> getParameters() {
530 return parameters;
531 }
532
533 @Override
534 public Set<PBody> doGetContainedBodies() {
535 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
536 Set<PBody> bodies = new LinkedHashSet<>();
537 {
538 PBody body = new PBody(this);
539 PVariable var_s = body.getOrCreateVariableByName("s");
540 PVariable var_n1 = body.getOrCreateVariableByName("n1");
541 PVariable var_n2 = body.getOrCreateVariableByName("n2");
542 new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
543 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
544 new ExportedParameter(body, var_s, parameter_s)
545 ));
546 // Segment.connectedTo(s, n1)
547 new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
548 PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}");
549 new TypeConstraint(body, Tuples.flatTupleOf(var_s, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo")));
550 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
551 new Equality(body, var__virtual_0_, var_n1);
552 // Segment.connectedTo(s, n2)
553 new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
554 PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}");
555 new TypeConstraint(body, Tuples.flatTupleOf(var_s, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo")));
556 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
557 new Equality(body, var__virtual_1_, var_n2);
558 // n1 != n2
559 new Inequality(body, var_n1, var_n2);
560 bodies.add(body);
561 }
562 return bodies;
563 }
564 }
565}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java
index ff82dda1..d12ec23e 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TooManyInputsOfSegment.java
@@ -46,12 +46,6 @@ import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
46 * 46 *
47 * <p>Original source: 47 * <p>Original source:
48 * <code><pre> 48 * <code><pre>
49 * //{@literal @}Constraint(message = "noInputOfSegment", severity = "error", key = { S })
50 * //pattern noInputOfSegment(S : Segment) {
51 * // neg find turnout(S);
52 * // neg find output(_, S);
53 * //}
54 *
55 * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) 49 * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
56 * pattern tooManyInputsOfSegment(S : SimpleSegment) { 50 * pattern tooManyInputsOfSegment(S : SimpleSegment) {
57 * find output(I1, S); 51 * find output(I1, S);
@@ -251,12 +245,6 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica
251 * 245 *
252 * <p>Original source: 246 * <p>Original source:
253 * <code><pre> 247 * <code><pre>
254 * //{@literal @}Constraint(message = "noInputOfSegment", severity = "error", key = { S })
255 * //pattern noInputOfSegment(S : Segment) {
256 * // neg find turnout(S);
257 * // neg find output(_, S);
258 * //}
259 *
260 * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) 248 * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
261 * pattern tooManyInputsOfSegment(S : SimpleSegment) { 249 * pattern tooManyInputsOfSegment(S : SimpleSegment) {
262 * find output(I1, S); 250 * find output(I1, S);
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java
new file mode 100644
index 00000000..5bf153c3
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java
@@ -0,0 +1,564 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Train;
17import org.apache.log4j.Logger;
18import org.eclipse.emf.ecore.EClass;
19import org.eclipse.viatra.query.runtime.api.IPatternMatch;
20import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
21import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
22import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
23import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
24import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
25import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
26import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
27import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
28import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
29import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
30import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
31import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
32import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
33import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
34import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
35import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
36import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
37import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
38
39/**
40 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
41 *
42 * <p>Original source:
43 * <code><pre>
44 * //
45 * // trainLocations
46 * //
47 *
48 * pattern trainLocations_step_2(in train : Train) {
49 * // frame-{@literal >}train = model-{@literal >}trains[i0];
50 * // frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
51 * // if (frame-{@literal >}location != NULL) {
52 * // ...
53 * // }
54 *
55 * Train(train);
56 * }
57 * </pre></code>
58 *
59 * @see Matcher
60 * @see Match
61 *
62 */
63@SuppressWarnings("all")
64public final class TrainLocations_step_2 extends BaseGeneratedEMFQuerySpecification<TrainLocations_step_2.Matcher> {
65 /**
66 * Pattern-specific match representation of the modes3.queries.trainLocations_step_2 pattern,
67 * to be used in conjunction with {@link Matcher}.
68 *
69 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
70 * Each instance is a (possibly partial) substitution of pattern parameters,
71 * usable to represent a match of the pattern in the result of a query,
72 * or to specify the bound (fixed) input parameters when issuing a query.
73 *
74 * @see Matcher
75 *
76 */
77 public static abstract class Match extends BasePatternMatch {
78 private Train fTrain;
79
80 private static List<String> parameterNames = makeImmutableList("train");
81
82 private Match(final Train pTrain) {
83 this.fTrain = pTrain;
84 }
85
86 @Override
87 public Object get(final String parameterName) {
88 switch(parameterName) {
89 case "train": return this.fTrain;
90 default: return null;
91 }
92 }
93
94 @Override
95 public Object get(final int index) {
96 switch(index) {
97 case 0: return this.fTrain;
98 default: return null;
99 }
100 }
101
102 public Train getTrain() {
103 return this.fTrain;
104 }
105
106 @Override
107 public boolean set(final String parameterName, final Object newValue) {
108 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
109 if ("train".equals(parameterName) ) {
110 this.fTrain = (Train) newValue;
111 return true;
112 }
113 return false;
114 }
115
116 public void setTrain(final Train pTrain) {
117 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
118 this.fTrain = pTrain;
119 }
120
121 @Override
122 public String patternName() {
123 return "modes3.queries.trainLocations_step_2";
124 }
125
126 @Override
127 public List<String> parameterNames() {
128 return TrainLocations_step_2.Match.parameterNames;
129 }
130
131 @Override
132 public Object[] toArray() {
133 return new Object[]{fTrain};
134 }
135
136 @Override
137 public TrainLocations_step_2.Match toImmutable() {
138 return isMutable() ? newMatch(fTrain) : this;
139 }
140
141 @Override
142 public String prettyPrint() {
143 StringBuilder result = new StringBuilder();
144 result.append("\"train\"=" + prettyPrintValue(fTrain));
145 return result.toString();
146 }
147
148 @Override
149 public int hashCode() {
150 return Objects.hash(fTrain);
151 }
152
153 @Override
154 public boolean equals(final Object obj) {
155 if (this == obj)
156 return true;
157 if (obj == null) {
158 return false;
159 }
160 if ((obj instanceof TrainLocations_step_2.Match)) {
161 TrainLocations_step_2.Match other = (TrainLocations_step_2.Match) obj;
162 return Objects.equals(fTrain, other.fTrain);
163 } else {
164 // this should be infrequent
165 if (!(obj instanceof IPatternMatch)) {
166 return false;
167 }
168 IPatternMatch otherSig = (IPatternMatch) obj;
169 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
170 }
171 }
172
173 @Override
174 public TrainLocations_step_2 specification() {
175 return TrainLocations_step_2.instance();
176 }
177
178 /**
179 * Returns an empty, mutable match.
180 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
181 *
182 * @return the empty match.
183 *
184 */
185 public static TrainLocations_step_2.Match newEmptyMatch() {
186 return new Mutable(null);
187 }
188
189 /**
190 * Returns a mutable (partial) match.
191 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
192 *
193 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
194 * @return the new, mutable (partial) match object.
195 *
196 */
197 public static TrainLocations_step_2.Match newMutableMatch(final Train pTrain) {
198 return new Mutable(pTrain);
199 }
200
201 /**
202 * Returns a new (partial) match.
203 * This can be used e.g. to call the matcher with a partial match.
204 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
205 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
206 * @return the (partial) match object.
207 *
208 */
209 public static TrainLocations_step_2.Match newMatch(final Train pTrain) {
210 return new Immutable(pTrain);
211 }
212
213 private static final class Mutable extends TrainLocations_step_2.Match {
214 Mutable(final Train pTrain) {
215 super(pTrain);
216 }
217
218 @Override
219 public boolean isMutable() {
220 return true;
221 }
222 }
223
224 private static final class Immutable extends TrainLocations_step_2.Match {
225 Immutable(final Train pTrain) {
226 super(pTrain);
227 }
228
229 @Override
230 public boolean isMutable() {
231 return false;
232 }
233 }
234 }
235
236 /**
237 * Generated pattern matcher API of the modes3.queries.trainLocations_step_2 pattern,
238 * providing pattern-specific query methods.
239 *
240 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
241 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
242 *
243 * <p>Matches of the pattern will be represented as {@link Match}.
244 *
245 * <p>Original source:
246 * <code><pre>
247 * //
248 * // trainLocations
249 * //
250 *
251 * pattern trainLocations_step_2(in train : Train) {
252 * // frame-{@literal >}train = model-{@literal >}trains[i0];
253 * // frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
254 * // if (frame-{@literal >}location != NULL) {
255 * // ...
256 * // }
257 *
258 * Train(train);
259 * }
260 * </pre></code>
261 *
262 * @see Match
263 * @see TrainLocations_step_2
264 *
265 */
266 public static class Matcher extends BaseMatcher<TrainLocations_step_2.Match> {
267 /**
268 * Initializes the pattern matcher within an existing VIATRA Query engine.
269 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
270 *
271 * @param engine the existing VIATRA Query engine in which this matcher will be created.
272 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
273 *
274 */
275 public static TrainLocations_step_2.Matcher on(final ViatraQueryEngine engine) {
276 // check if matcher already exists
277 Matcher matcher = engine.getExistingMatcher(querySpecification());
278 if (matcher == null) {
279 matcher = (Matcher)engine.getMatcher(querySpecification());
280 }
281 return matcher;
282 }
283
284 /**
285 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
286 * @return an initialized matcher
287 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
288 *
289 */
290 public static TrainLocations_step_2.Matcher create() {
291 return new Matcher();
292 }
293
294 private static final int POSITION_TRAIN = 0;
295
296 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TrainLocations_step_2.Matcher.class);
297
298 /**
299 * Initializes the pattern matcher within an existing VIATRA Query engine.
300 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
301 *
302 * @param engine the existing VIATRA Query engine in which this matcher will be created.
303 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
304 *
305 */
306 private Matcher() {
307 super(querySpecification());
308 }
309
310 /**
311 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
312 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
313 * @return matches represented as a Match object.
314 *
315 */
316 public Collection<TrainLocations_step_2.Match> getAllMatches(final Train pTrain) {
317 return rawStreamAllMatches(new Object[]{pTrain}).collect(Collectors.toSet());
318 }
319
320 /**
321 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
322 * </p>
323 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
324 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
325 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
326 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
327 * @return a stream of matches represented as a Match object.
328 *
329 */
330 public Stream<TrainLocations_step_2.Match> streamAllMatches(final Train pTrain) {
331 return rawStreamAllMatches(new Object[]{pTrain});
332 }
333
334 /**
335 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
336 * Neither determinism nor randomness of selection is guaranteed.
337 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
338 * @return a match represented as a Match object, or null if no match is found.
339 *
340 */
341 public Optional<TrainLocations_step_2.Match> getOneArbitraryMatch(final Train pTrain) {
342 return rawGetOneArbitraryMatch(new Object[]{pTrain});
343 }
344
345 /**
346 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
347 * under any possible substitution of the unspecified parameters (if any).
348 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
349 * @return true if the input is a valid (partial) match of the pattern.
350 *
351 */
352 public boolean hasMatch(final Train pTrain) {
353 return rawHasMatch(new Object[]{pTrain});
354 }
355
356 /**
357 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
358 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
359 * @return the number of pattern matches found.
360 *
361 */
362 public int countMatches(final Train pTrain) {
363 return rawCountMatches(new Object[]{pTrain});
364 }
365
366 /**
367 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
368 * Neither determinism nor randomness of selection is guaranteed.
369 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
370 * @param processor the action that will process the selected match.
371 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
372 *
373 */
374 public boolean forOneArbitraryMatch(final Train pTrain, final Consumer<? super TrainLocations_step_2.Match> processor) {
375 return rawForOneArbitraryMatch(new Object[]{pTrain}, processor);
376 }
377
378 /**
379 * Returns a new (partial) match.
380 * This can be used e.g. to call the matcher with a partial match.
381 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
382 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
383 * @return the (partial) match object.
384 *
385 */
386 public TrainLocations_step_2.Match newMatch(final Train pTrain) {
387 return TrainLocations_step_2.Match.newMatch(pTrain);
388 }
389
390 /**
391 * Retrieve the set of values that occur in matches for train.
392 * @return the Set of all values or empty set if there are no matches
393 *
394 */
395 protected Stream<Train> rawStreamAllValuesOftrain(final Object[] parameters) {
396 return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast);
397 }
398
399 /**
400 * Retrieve the set of values that occur in matches for train.
401 * @return the Set of all values or empty set if there are no matches
402 *
403 */
404 public Set<Train> getAllValuesOftrain() {
405 return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet());
406 }
407
408 /**
409 * Retrieve the set of values that occur in matches for train.
410 * @return the Set of all values or empty set if there are no matches
411 *
412 */
413 public Stream<Train> streamAllValuesOftrain() {
414 return rawStreamAllValuesOftrain(emptyArray());
415 }
416
417 @Override
418 protected TrainLocations_step_2.Match tupleToMatch(final Tuple t) {
419 try {
420 return TrainLocations_step_2.Match.newMatch((Train) t.get(POSITION_TRAIN));
421 } catch(ClassCastException e) {
422 LOGGER.error("Element(s) in tuple not properly typed!",e);
423 return null;
424 }
425 }
426
427 @Override
428 protected TrainLocations_step_2.Match arrayToMatch(final Object[] match) {
429 try {
430 return TrainLocations_step_2.Match.newMatch((Train) match[POSITION_TRAIN]);
431 } catch(ClassCastException e) {
432 LOGGER.error("Element(s) in array not properly typed!",e);
433 return null;
434 }
435 }
436
437 @Override
438 protected TrainLocations_step_2.Match arrayToMatchMutable(final Object[] match) {
439 try {
440 return TrainLocations_step_2.Match.newMutableMatch((Train) match[POSITION_TRAIN]);
441 } catch(ClassCastException e) {
442 LOGGER.error("Element(s) in array not properly typed!",e);
443 return null;
444 }
445 }
446
447 /**
448 * @return the singleton instance of the query specification of this pattern
449 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
450 *
451 */
452 public static IQuerySpecification<TrainLocations_step_2.Matcher> querySpecification() {
453 return TrainLocations_step_2.instance();
454 }
455 }
456
457 private TrainLocations_step_2() {
458 super(GeneratedPQuery.INSTANCE);
459 }
460
461 /**
462 * @return the singleton instance of the query specification
463 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
464 *
465 */
466 public static TrainLocations_step_2 instance() {
467 try{
468 return LazyHolder.INSTANCE;
469 } catch (ExceptionInInitializerError err) {
470 throw processInitializerError(err);
471 }
472 }
473
474 @Override
475 protected TrainLocations_step_2.Matcher instantiate(final ViatraQueryEngine engine) {
476 return TrainLocations_step_2.Matcher.on(engine);
477 }
478
479 @Override
480 public TrainLocations_step_2.Matcher instantiate() {
481 return TrainLocations_step_2.Matcher.create();
482 }
483
484 @Override
485 public TrainLocations_step_2.Match newEmptyMatch() {
486 return TrainLocations_step_2.Match.newEmptyMatch();
487 }
488
489 @Override
490 public TrainLocations_step_2.Match newMatch(final Object... parameters) {
491 return TrainLocations_step_2.Match.newMatch((modes3.Train) parameters[0]);
492 }
493
494 /**
495 * Inner class allowing the singleton instance of {@link TrainLocations_step_2} to be created
496 * <b>not</b> at the class load time of the outer class,
497 * but rather at the first call to {@link TrainLocations_step_2#instance()}.
498 *
499 * <p> This workaround is required e.g. to support recursion.
500 *
501 */
502 private static class LazyHolder {
503 private static final TrainLocations_step_2 INSTANCE = new TrainLocations_step_2();
504
505 /**
506 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
507 * This initialization order is required to support indirect recursion.
508 *
509 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
510 *
511 */
512 private static final Object STATIC_INITIALIZER = ensureInitialized();
513
514 public static Object ensureInitialized() {
515 INSTANCE.ensureInitializedInternal();
516 return null;
517 }
518 }
519
520 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
521 private static final TrainLocations_step_2.GeneratedPQuery INSTANCE = new GeneratedPQuery();
522
523 private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT);
524
525 private final List<PParameter> parameters = Arrays.asList(parameter_train);
526
527 private GeneratedPQuery() {
528 super(PVisibility.PUBLIC);
529 }
530
531 @Override
532 public String getFullyQualifiedName() {
533 return "modes3.queries.trainLocations_step_2";
534 }
535
536 @Override
537 public List<String> getParameterNames() {
538 return Arrays.asList("train");
539 }
540
541 @Override
542 public List<PParameter> getParameters() {
543 return parameters;
544 }
545
546 @Override
547 public Set<PBody> doGetContainedBodies() {
548 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
549 Set<PBody> bodies = new LinkedHashSet<>();
550 {
551 PBody body = new PBody(this);
552 PVariable var_train = body.getOrCreateVariableByName("train");
553 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
554 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
555 new ExportedParameter(body, var_train, parameter_train)
556 ));
557 // // frame->train = model->trains[i0];// frame->location = frame->train->location;// if (frame->location != NULL) {// ...// } Train(train)
558 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
559 bodies.add(body);
560 }
561 return bodies;
562 }
563 }
564}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java
new file mode 100644
index 00000000..edbd4af3
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java
@@ -0,0 +1,713 @@
1/**
2 * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
3 */
4package modes3.queries;
5
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.LinkedHashSet;
9import java.util.List;
10import java.util.Objects;
11import java.util.Optional;
12import java.util.Set;
13import java.util.function.Consumer;
14import java.util.stream.Collectors;
15import java.util.stream.Stream;
16import modes3.Segment;
17import modes3.Train;
18import org.apache.log4j.Logger;
19import org.eclipse.emf.ecore.EClass;
20import org.eclipse.viatra.query.runtime.api.IPatternMatch;
21import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
22import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
23import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
24import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
25import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
26import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
27import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
28import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey;
29import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
30import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
31import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
32import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality;
33import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
34import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
35import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
36import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
37import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
38import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
39import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
40import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
41
42/**
43 * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
44 *
45 * <p>Original source:
46 * <code><pre>
47 * pattern trainLocations_step_3(in train : Train, in location : Segment) {
48 * // results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
49 * // results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
50 * Train(train);
51 * Train.location(train, location);
52 * }
53 * </pre></code>
54 *
55 * @see Matcher
56 * @see Match
57 *
58 */
59@SuppressWarnings("all")
60public final class TrainLocations_step_3 extends BaseGeneratedEMFQuerySpecification<TrainLocations_step_3.Matcher> {
61 /**
62 * Pattern-specific match representation of the modes3.queries.trainLocations_step_3 pattern,
63 * to be used in conjunction with {@link Matcher}.
64 *
65 * <p>Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned.
66 * Each instance is a (possibly partial) substitution of pattern parameters,
67 * usable to represent a match of the pattern in the result of a query,
68 * or to specify the bound (fixed) input parameters when issuing a query.
69 *
70 * @see Matcher
71 *
72 */
73 public static abstract class Match extends BasePatternMatch {
74 private Train fTrain;
75
76 private Segment fLocation;
77
78 private static List<String> parameterNames = makeImmutableList("train", "location");
79
80 private Match(final Train pTrain, final Segment pLocation) {
81 this.fTrain = pTrain;
82 this.fLocation = pLocation;
83 }
84
85 @Override
86 public Object get(final String parameterName) {
87 switch(parameterName) {
88 case "train": return this.fTrain;
89 case "location": return this.fLocation;
90 default: return null;
91 }
92 }
93
94 @Override
95 public Object get(final int index) {
96 switch(index) {
97 case 0: return this.fTrain;
98 case 1: return this.fLocation;
99 default: return null;
100 }
101 }
102
103 public Train getTrain() {
104 return this.fTrain;
105 }
106
107 public Segment getLocation() {
108 return this.fLocation;
109 }
110
111 @Override
112 public boolean set(final String parameterName, final Object newValue) {
113 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
114 if ("train".equals(parameterName) ) {
115 this.fTrain = (Train) newValue;
116 return true;
117 }
118 if ("location".equals(parameterName) ) {
119 this.fLocation = (Segment) newValue;
120 return true;
121 }
122 return false;
123 }
124
125 public void setTrain(final Train pTrain) {
126 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
127 this.fTrain = pTrain;
128 }
129
130 public void setLocation(final Segment pLocation) {
131 if (!isMutable()) throw new java.lang.UnsupportedOperationException();
132 this.fLocation = pLocation;
133 }
134
135 @Override
136 public String patternName() {
137 return "modes3.queries.trainLocations_step_3";
138 }
139
140 @Override
141 public List<String> parameterNames() {
142 return TrainLocations_step_3.Match.parameterNames;
143 }
144
145 @Override
146 public Object[] toArray() {
147 return new Object[]{fTrain, fLocation};
148 }
149
150 @Override
151 public TrainLocations_step_3.Match toImmutable() {
152 return isMutable() ? newMatch(fTrain, fLocation) : this;
153 }
154
155 @Override
156 public String prettyPrint() {
157 StringBuilder result = new StringBuilder();
158 result.append("\"train\"=" + prettyPrintValue(fTrain) + ", ");
159 result.append("\"location\"=" + prettyPrintValue(fLocation));
160 return result.toString();
161 }
162
163 @Override
164 public int hashCode() {
165 return Objects.hash(fTrain, fLocation);
166 }
167
168 @Override
169 public boolean equals(final Object obj) {
170 if (this == obj)
171 return true;
172 if (obj == null) {
173 return false;
174 }
175 if ((obj instanceof TrainLocations_step_3.Match)) {
176 TrainLocations_step_3.Match other = (TrainLocations_step_3.Match) obj;
177 return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation);
178 } else {
179 // this should be infrequent
180 if (!(obj instanceof IPatternMatch)) {
181 return false;
182 }
183 IPatternMatch otherSig = (IPatternMatch) obj;
184 return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray());
185 }
186 }
187
188 @Override
189 public TrainLocations_step_3 specification() {
190 return TrainLocations_step_3.instance();
191 }
192
193 /**
194 * Returns an empty, mutable match.
195 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
196 *
197 * @return the empty match.
198 *
199 */
200 public static TrainLocations_step_3.Match newEmptyMatch() {
201 return new Mutable(null, null);
202 }
203
204 /**
205 * Returns a mutable (partial) match.
206 * Fields of the mutable match can be filled to create a partial match, usable as matcher input.
207 *
208 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
209 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
210 * @return the new, mutable (partial) match object.
211 *
212 */
213 public static TrainLocations_step_3.Match newMutableMatch(final Train pTrain, final Segment pLocation) {
214 return new Mutable(pTrain, pLocation);
215 }
216
217 /**
218 * Returns a new (partial) match.
219 * This can be used e.g. to call the matcher with a partial match.
220 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
221 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
222 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
223 * @return the (partial) match object.
224 *
225 */
226 public static TrainLocations_step_3.Match newMatch(final Train pTrain, final Segment pLocation) {
227 return new Immutable(pTrain, pLocation);
228 }
229
230 private static final class Mutable extends TrainLocations_step_3.Match {
231 Mutable(final Train pTrain, final Segment pLocation) {
232 super(pTrain, pLocation);
233 }
234
235 @Override
236 public boolean isMutable() {
237 return true;
238 }
239 }
240
241 private static final class Immutable extends TrainLocations_step_3.Match {
242 Immutable(final Train pTrain, final Segment pLocation) {
243 super(pTrain, pLocation);
244 }
245
246 @Override
247 public boolean isMutable() {
248 return false;
249 }
250 }
251 }
252
253 /**
254 * Generated pattern matcher API of the modes3.queries.trainLocations_step_3 pattern,
255 * providing pattern-specific query methods.
256 *
257 * <p>Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)},
258 * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}.
259 *
260 * <p>Matches of the pattern will be represented as {@link Match}.
261 *
262 * <p>Original source:
263 * <code><pre>
264 * pattern trainLocations_step_3(in train : Train, in location : Segment) {
265 * // results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
266 * // results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
267 * Train(train);
268 * Train.location(train, location);
269 * }
270 * </pre></code>
271 *
272 * @see Match
273 * @see TrainLocations_step_3
274 *
275 */
276 public static class Matcher extends BaseMatcher<TrainLocations_step_3.Match> {
277 /**
278 * Initializes the pattern matcher within an existing VIATRA Query engine.
279 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
280 *
281 * @param engine the existing VIATRA Query engine in which this matcher will be created.
282 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
283 *
284 */
285 public static TrainLocations_step_3.Matcher on(final ViatraQueryEngine engine) {
286 // check if matcher already exists
287 Matcher matcher = engine.getExistingMatcher(querySpecification());
288 if (matcher == null) {
289 matcher = (Matcher)engine.getMatcher(querySpecification());
290 }
291 return matcher;
292 }
293
294 /**
295 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
296 * @return an initialized matcher
297 * @noreference This method is for internal matcher initialization by the framework, do not call it manually.
298 *
299 */
300 public static TrainLocations_step_3.Matcher create() {
301 return new Matcher();
302 }
303
304 private static final int POSITION_TRAIN = 0;
305
306 private static final int POSITION_LOCATION = 1;
307
308 private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TrainLocations_step_3.Matcher.class);
309
310 /**
311 * Initializes the pattern matcher within an existing VIATRA Query engine.
312 * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned.
313 *
314 * @param engine the existing VIATRA Query engine in which this matcher will be created.
315 * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation
316 *
317 */
318 private Matcher() {
319 super(querySpecification());
320 }
321
322 /**
323 * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters.
324 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
325 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
326 * @return matches represented as a Match object.
327 *
328 */
329 public Collection<TrainLocations_step_3.Match> getAllMatches(final Train pTrain, final Segment pLocation) {
330 return rawStreamAllMatches(new Object[]{pTrain, pLocation}).collect(Collectors.toSet());
331 }
332
333 /**
334 * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
335 * </p>
336 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
337 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
338 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
339 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
340 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
341 * @return a stream of matches represented as a Match object.
342 *
343 */
344 public Stream<TrainLocations_step_3.Match> streamAllMatches(final Train pTrain, final Segment pLocation) {
345 return rawStreamAllMatches(new Object[]{pTrain, pLocation});
346 }
347
348 /**
349 * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
350 * Neither determinism nor randomness of selection is guaranteed.
351 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
352 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
353 * @return a match represented as a Match object, or null if no match is found.
354 *
355 */
356 public Optional<TrainLocations_step_3.Match> getOneArbitraryMatch(final Train pTrain, final Segment pLocation) {
357 return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation});
358 }
359
360 /**
361 * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match,
362 * under any possible substitution of the unspecified parameters (if any).
363 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
364 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
365 * @return true if the input is a valid (partial) match of the pattern.
366 *
367 */
368 public boolean hasMatch(final Train pTrain, final Segment pLocation) {
369 return rawHasMatch(new Object[]{pTrain, pLocation});
370 }
371
372 /**
373 * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
374 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
375 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
376 * @return the number of pattern matches found.
377 *
378 */
379 public int countMatches(final Train pTrain, final Segment pLocation) {
380 return rawCountMatches(new Object[]{pTrain, pLocation});
381 }
382
383 /**
384 * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
385 * Neither determinism nor randomness of selection is guaranteed.
386 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
387 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
388 * @param processor the action that will process the selected match.
389 * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked
390 *
391 */
392 public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Consumer<? super TrainLocations_step_3.Match> processor) {
393 return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation}, processor);
394 }
395
396 /**
397 * Returns a new (partial) match.
398 * This can be used e.g. to call the matcher with a partial match.
399 * <p>The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object.
400 * @param pTrain the fixed value of pattern parameter train, or null if not bound.
401 * @param pLocation the fixed value of pattern parameter location, or null if not bound.
402 * @return the (partial) match object.
403 *
404 */
405 public TrainLocations_step_3.Match newMatch(final Train pTrain, final Segment pLocation) {
406 return TrainLocations_step_3.Match.newMatch(pTrain, pLocation);
407 }
408
409 /**
410 * Retrieve the set of values that occur in matches for train.
411 * @return the Set of all values or empty set if there are no matches
412 *
413 */
414 protected Stream<Train> rawStreamAllValuesOftrain(final Object[] parameters) {
415 return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast);
416 }
417
418 /**
419 * Retrieve the set of values that occur in matches for train.
420 * @return the Set of all values or empty set if there are no matches
421 *
422 */
423 public Set<Train> getAllValuesOftrain() {
424 return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet());
425 }
426
427 /**
428 * Retrieve the set of values that occur in matches for train.
429 * @return the Set of all values or empty set if there are no matches
430 *
431 */
432 public Stream<Train> streamAllValuesOftrain() {
433 return rawStreamAllValuesOftrain(emptyArray());
434 }
435
436 /**
437 * Retrieve the set of values that occur in matches for train.
438 * </p>
439 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
440 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
441 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
442 *
443 * @return the Stream of all values or empty set if there are no matches
444 *
445 */
446 public Stream<Train> streamAllValuesOftrain(final TrainLocations_step_3.Match partialMatch) {
447 return rawStreamAllValuesOftrain(partialMatch.toArray());
448 }
449
450 /**
451 * Retrieve the set of values that occur in matches for train.
452 * </p>
453 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
454 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
455 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
456 *
457 * @return the Stream of all values or empty set if there are no matches
458 *
459 */
460 public Stream<Train> streamAllValuesOftrain(final Segment pLocation) {
461 return rawStreamAllValuesOftrain(new Object[]{null, pLocation});
462 }
463
464 /**
465 * Retrieve the set of values that occur in matches for train.
466 * @return the Set of all values or empty set if there are no matches
467 *
468 */
469 public Set<Train> getAllValuesOftrain(final TrainLocations_step_3.Match partialMatch) {
470 return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet());
471 }
472
473 /**
474 * Retrieve the set of values that occur in matches for train.
475 * @return the Set of all values or empty set if there are no matches
476 *
477 */
478 public Set<Train> getAllValuesOftrain(final Segment pLocation) {
479 return rawStreamAllValuesOftrain(new Object[]{null, pLocation}).collect(Collectors.toSet());
480 }
481
482 /**
483 * Retrieve the set of values that occur in matches for location.
484 * @return the Set of all values or empty set if there are no matches
485 *
486 */
487 protected Stream<Segment> rawStreamAllValuesOflocation(final Object[] parameters) {
488 return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast);
489 }
490
491 /**
492 * Retrieve the set of values that occur in matches for location.
493 * @return the Set of all values or empty set if there are no matches
494 *
495 */
496 public Set<Segment> getAllValuesOflocation() {
497 return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet());
498 }
499
500 /**
501 * Retrieve the set of values that occur in matches for location.
502 * @return the Set of all values or empty set if there are no matches
503 *
504 */
505 public Stream<Segment> streamAllValuesOflocation() {
506 return rawStreamAllValuesOflocation(emptyArray());
507 }
508
509 /**
510 * Retrieve the set of values that occur in matches for location.
511 * </p>
512 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
513 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
514 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
515 *
516 * @return the Stream of all values or empty set if there are no matches
517 *
518 */
519 public Stream<Segment> streamAllValuesOflocation(final TrainLocations_step_3.Match partialMatch) {
520 return rawStreamAllValuesOflocation(partialMatch.toArray());
521 }
522
523 /**
524 * Retrieve the set of values that occur in matches for location.
525 * </p>
526 * <strong>NOTE</strong>: It is important not to modify the source model while the stream is being processed.
527 * If the match set of the pattern changes during processing, the contents of the stream is <strong>undefined</strong>.
528 * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code.
529 *
530 * @return the Stream of all values or empty set if there are no matches
531 *
532 */
533 public Stream<Segment> streamAllValuesOflocation(final Train pTrain) {
534 return rawStreamAllValuesOflocation(new Object[]{pTrain, null});
535 }
536
537 /**
538 * Retrieve the set of values that occur in matches for location.
539 * @return the Set of all values or empty set if there are no matches
540 *
541 */
542 public Set<Segment> getAllValuesOflocation(final TrainLocations_step_3.Match partialMatch) {
543 return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet());
544 }
545
546 /**
547 * Retrieve the set of values that occur in matches for location.
548 * @return the Set of all values or empty set if there are no matches
549 *
550 */
551 public Set<Segment> getAllValuesOflocation(final Train pTrain) {
552 return rawStreamAllValuesOflocation(new Object[]{pTrain, null}).collect(Collectors.toSet());
553 }
554
555 @Override
556 protected TrainLocations_step_3.Match tupleToMatch(final Tuple t) {
557 try {
558 return TrainLocations_step_3.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION));
559 } catch(ClassCastException e) {
560 LOGGER.error("Element(s) in tuple not properly typed!",e);
561 return null;
562 }
563 }
564
565 @Override
566 protected TrainLocations_step_3.Match arrayToMatch(final Object[] match) {
567 try {
568 return TrainLocations_step_3.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]);
569 } catch(ClassCastException e) {
570 LOGGER.error("Element(s) in array not properly typed!",e);
571 return null;
572 }
573 }
574
575 @Override
576 protected TrainLocations_step_3.Match arrayToMatchMutable(final Object[] match) {
577 try {
578 return TrainLocations_step_3.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]);
579 } catch(ClassCastException e) {
580 LOGGER.error("Element(s) in array not properly typed!",e);
581 return null;
582 }
583 }
584
585 /**
586 * @return the singleton instance of the query specification of this pattern
587 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
588 *
589 */
590 public static IQuerySpecification<TrainLocations_step_3.Matcher> querySpecification() {
591 return TrainLocations_step_3.instance();
592 }
593 }
594
595 private TrainLocations_step_3() {
596 super(GeneratedPQuery.INSTANCE);
597 }
598
599 /**
600 * @return the singleton instance of the query specification
601 * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded
602 *
603 */
604 public static TrainLocations_step_3 instance() {
605 try{
606 return LazyHolder.INSTANCE;
607 } catch (ExceptionInInitializerError err) {
608 throw processInitializerError(err);
609 }
610 }
611
612 @Override
613 protected TrainLocations_step_3.Matcher instantiate(final ViatraQueryEngine engine) {
614 return TrainLocations_step_3.Matcher.on(engine);
615 }
616
617 @Override
618 public TrainLocations_step_3.Matcher instantiate() {
619 return TrainLocations_step_3.Matcher.create();
620 }
621
622 @Override
623 public TrainLocations_step_3.Match newEmptyMatch() {
624 return TrainLocations_step_3.Match.newEmptyMatch();
625 }
626
627 @Override
628 public TrainLocations_step_3.Match newMatch(final Object... parameters) {
629 return TrainLocations_step_3.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1]);
630 }
631
632 /**
633 * Inner class allowing the singleton instance of {@link TrainLocations_step_3} to be created
634 * <b>not</b> at the class load time of the outer class,
635 * but rather at the first call to {@link TrainLocations_step_3#instance()}.
636 *
637 * <p> This workaround is required e.g. to support recursion.
638 *
639 */
640 private static class LazyHolder {
641 private static final TrainLocations_step_3 INSTANCE = new TrainLocations_step_3();
642
643 /**
644 * Statically initializes the query specification <b>after</b> the field {@link #INSTANCE} is assigned.
645 * This initialization order is required to support indirect recursion.
646 *
647 * <p> The static initializer is defined using a helper field to work around limitations of the code generator.
648 *
649 */
650 private static final Object STATIC_INITIALIZER = ensureInitialized();
651
652 public static Object ensureInitialized() {
653 INSTANCE.ensureInitializedInternal();
654 return null;
655 }
656 }
657
658 private static class GeneratedPQuery extends BaseGeneratedEMFPQuery {
659 private static final TrainLocations_step_3.GeneratedPQuery INSTANCE = new GeneratedPQuery();
660
661 private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT);
662
663 private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT);
664
665 private final List<PParameter> parameters = Arrays.asList(parameter_train, parameter_location);
666
667 private GeneratedPQuery() {
668 super(PVisibility.PUBLIC);
669 }
670
671 @Override
672 public String getFullyQualifiedName() {
673 return "modes3.queries.trainLocations_step_3";
674 }
675
676 @Override
677 public List<String> getParameterNames() {
678 return Arrays.asList("train","location");
679 }
680
681 @Override
682 public List<PParameter> getParameters() {
683 return parameters;
684 }
685
686 @Override
687 public Set<PBody> doGetContainedBodies() {
688 setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED));
689 Set<PBody> bodies = new LinkedHashSet<>();
690 {
691 PBody body = new PBody(this);
692 PVariable var_train = body.getOrCreateVariableByName("train");
693 PVariable var_location = body.getOrCreateVariableByName("location");
694 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
695 new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
696 body.setSymbolicParameters(Arrays.<ExportedParameter>asList(
697 new ExportedParameter(body, var_train, parameter_train),
698 new ExportedParameter(body, var_location, parameter_location)
699 ));
700 // // results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train; Train(train)
701 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
702 // Train.location(train, location)
703 new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train")));
704 PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}");
705 new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location")));
706 new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment")));
707 new Equality(body, var__virtual_0_, var_location);
708 bodies.add(body);
709 }
710 return bodies;
711 }
712 }
713}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin
new file mode 100644
index 00000000..87975792
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin
new file mode 100644
index 00000000..f243e180
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin
new file mode 100644
index 00000000..cdef4dc7
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin
index 77f1ea6e..759ac9e4 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin
index 4fdbb71b..386baeda 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin
index e5e1b63e..79059b7f 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin
new file mode 100644
index 00000000..3c3a380e
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin
Binary files differ
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore
index fb94df96..1a7df1d9 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.gitignore
@@ -1,3 +1,13 @@
1/.Modes3ModelGenerator.java._trace 1/.Modes3ModelGenerator.java._trace
2/.Modes3UnitPropagationGenerator.java._trace 2/.Modes3UnitPropagationGenerator.java._trace
3/.Modes3TypeScopeHint.java._trace 3/.Modes3TypeScopeHint.java._trace
4/.Modes3TypeScopeHint.xtendbin
5/.Modes3UnitPropagationGenerator.xtendbin
6/Modes3TypeScopeHint.java
7/.Modes3ModelGenerator.xtendbin
8/Modes3ModelGenerator.java
9/Modes3UnitPropagationGenerator.java
10/.CloseTrainsObjectiveHint.java._trace
11/.TrainLocationsObjectiveHint.java._trace
12/.MisalignedTurnoutObjectiveHint.java._trace
13/.EndOfSidingObjectiveHint.java._trace
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java
new file mode 100644
index 00000000..babfa7e1
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java
@@ -0,0 +1,279 @@
1package modes3.run;
2
3import com.google.common.base.Objects;
4import com.google.common.collect.ImmutableList;
5import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic;
6import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace;
7import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type;
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension;
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder;
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory;
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator;
12import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch;
13import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers;
14import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint;
15import java.util.Collection;
16import java.util.List;
17import java.util.Map;
18import java.util.Set;
19import modes3.Modes3Package;
20import modes3.queries.CloseTrains_step_2;
21import modes3.queries.CloseTrains_step_3;
22import modes3.queries.CloseTrains_step_4;
23import modes3.queries.CloseTrains_step_5;
24import modes3.queries.CloseTrains_step_6;
25import modes3.queries.CloseTrains_step_7;
26import org.eclipse.viatra.query.runtime.api.IPatternMatch;
27import org.eclipse.xtext.xbase.lib.Extension;
28import org.eclipse.xtext.xbase.lib.Functions.Function1;
29import org.eclipse.xtext.xbase.lib.IterableExtensions;
30
31@SuppressWarnings("all")
32public class CloseTrainsObjectiveHint extends CostObjectiveHint {
33 private final Type segmentType;
34
35 private final Type trainType;
36
37 public CloseTrainsObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) {
38 @Extension
39 final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE;
40 this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment());
41 this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain());
42 }
43
44 @Override
45 public boolean isExact() {
46 return true;
47 }
48
49 @Override
50 public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map<String, CostElementMatchers> costElementMatchers) {
51 PolyhedronExtensionOperator _xblockexpression = null;
52 {
53 final CostElementMatchers step2 = costElementMatchers.get(CloseTrains_step_2.instance().getFullyQualifiedName());
54 final CostElementMatchers step3 = costElementMatchers.get(CloseTrains_step_3.instance().getFullyQualifiedName());
55 final CostElementMatchers step4 = costElementMatchers.get(CloseTrains_step_4.instance().getFullyQualifiedName());
56 final CostElementMatchers step5 = costElementMatchers.get(CloseTrains_step_5.instance().getFullyQualifiedName());
57 final CostElementMatchers step6 = costElementMatchers.get(CloseTrains_step_6.instance().getFullyQualifiedName());
58 final CostElementMatchers step7 = costElementMatchers.get(CloseTrains_step_7.instance().getFullyQualifiedName());
59 final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> {
60 final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder();
61 ImmutableList<CostElementMatch> _matches = step2.getMatches();
62 for (final CostElementMatch m : _matches) {
63 {
64 final Dimension dimension = it.getDimension(m.getMatch());
65 objectiveBuilder.add(step2.getWeight(), dimension);
66 dimension.tightenLowerBound(Integer.valueOf(0));
67 boolean _isMulti = m.isMulti();
68 if (_isMulti) {
69 it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0);
70 } else {
71 dimension.tightenUpperBound(Integer.valueOf(1));
72 boolean _isMust = m.isMust();
73 if (_isMust) {
74 dimension.tightenLowerBound(Integer.valueOf(1));
75 }
76 }
77 }
78 }
79 final ImmutableList<CostElementMatch> step3Matches = step3.getMatches();
80 for (final CostElementMatch m_1 : step3Matches) {
81 {
82 final Dimension dimension = it.getDimension(m_1.getMatch());
83 objectiveBuilder.add(step3.getWeight(), dimension);
84 dimension.tightenLowerBound(Integer.valueOf(0));
85 boolean _isMulti = m_1.isMulti();
86 boolean _not = (!_isMulti);
87 if (_not) {
88 dimension.tightenUpperBound(Integer.valueOf(1));
89 boolean _isMust = m_1.isMust();
90 if (_isMust) {
91 dimension.tightenLowerBound(Integer.valueOf(1));
92 }
93 }
94 }
95 }
96 final Function1<CostElementMatch, IPatternMatch> _function_1 = (CostElementMatch it_1) -> {
97 return step2.projectMayMatch(it_1.getMatch(), 2);
98 };
99 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step3Matches, _function_1).entrySet();
100 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair : _entrySet) {
101 {
102 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
103 List<CostElementMatch> _value = pair.getValue();
104 for (final CostElementMatch m_2 : _value) {
105 multiplicityBuilder.add(1, m_2.getMatch());
106 }
107 multiplicityBuilder.add((-1), pair.getKey());
108 multiplicityBuilder.build().assertEqualsTo(0);
109 }
110 }
111 CloseTrainsObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1);
112 CloseTrainsObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1);
113 final ImmutableList<CostElementMatch> step4Matches = step4.getMatches();
114 for (final CostElementMatch m_2 : step4Matches) {
115 {
116 final Dimension dimension = it.getDimension(m_2.getMatch());
117 objectiveBuilder.add(step4.getWeight(), dimension);
118 dimension.tightenLowerBound(Integer.valueOf(0));
119 boolean _isMulti = m_2.isMulti();
120 boolean _not = (!_isMulti);
121 if (_not) {
122 dimension.tightenUpperBound(Integer.valueOf(1));
123 boolean _isMust = m_2.isMust();
124 if (_isMust) {
125 dimension.tightenLowerBound(Integer.valueOf(1));
126 }
127 }
128 }
129 }
130 final Function1<CostElementMatch, IPatternMatch> _function_2 = (CostElementMatch it_1) -> {
131 return step3.projectMayMatch(it_1.getMatch(), 2, 3);
132 };
133 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet_1 = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step4Matches, _function_2).entrySet();
134 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair_1 : _entrySet_1) {
135 {
136 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
137 List<CostElementMatch> _value = pair_1.getValue();
138 for (final CostElementMatch m_3 : _value) {
139 multiplicityBuilder.add(1, m_3.getMatch());
140 }
141 multiplicityBuilder.add((-2), pair_1.getKey());
142 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
143 }
144 }
145 CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 2, this.trainType, 2);
146 CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2);
147 CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 4, this.segmentType, 2);
148 final ImmutableList<CostElementMatch> step5Matches = step5.getMatches();
149 for (final CostElementMatch m_3 : step5Matches) {
150 {
151 final Dimension dimension = it.getDimension(m_3.getMatch());
152 objectiveBuilder.add(step5.getWeight(), dimension);
153 dimension.tightenLowerBound(Integer.valueOf(0));
154 boolean _isMulti = m_3.isMulti();
155 boolean _not = (!_isMulti);
156 if (_not) {
157 dimension.tightenUpperBound(Integer.valueOf(1));
158 boolean _isMust = m_3.isMust();
159 if (_isMust) {
160 dimension.tightenLowerBound(Integer.valueOf(1));
161 }
162 }
163 }
164 }
165 final Function1<CostElementMatch, IPatternMatch> _function_3 = (CostElementMatch it_1) -> {
166 return step4.projectMayMatch(it_1.getMatch(), 2, 3, 4);
167 };
168 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet_2 = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step5Matches, _function_3).entrySet();
169 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair_2 : _entrySet_2) {
170 {
171 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
172 List<CostElementMatch> _value = pair_2.getValue();
173 for (final CostElementMatch m_4 : _value) {
174 multiplicityBuilder.add(1, m_4.getMatch());
175 }
176 multiplicityBuilder.add((-2), pair_2.getKey());
177 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
178 }
179 }
180 CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 2, this.trainType, 4);
181 CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 4);
182 CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 4, this.segmentType, 4);
183 CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 5, this.segmentType, 4);
184 final ImmutableList<CostElementMatch> step6Matches = step6.getMatches();
185 for (final CostElementMatch m_4 : step6Matches) {
186 {
187 final Dimension dimension = it.getDimension(m_4.getMatch());
188 objectiveBuilder.add(step6.getWeight(), dimension);
189 dimension.tightenLowerBound(Integer.valueOf(0));
190 boolean _isMulti = m_4.isMulti();
191 if (_isMulti) {
192 Object _get = m_4.getMatch().get(3);
193 Object _get_1 = m_4.getMatch().get(5);
194 boolean _equals = Objects.equal(_get, _get_1);
195 if (_equals) {
196 it.createBuilder().add(2, m_4.getMatch()).add((-1), step5.projectMayMatch(m_4.getMatch(), 2, 3, 4, 5)).build().assertEqualsTo(0);
197 } else {
198 it.createBuilder().add(1, m_4.getMatch()).add((-1), step5.projectMayMatch(m_4.getMatch(), 2, 3, 4, 5)).build().assertEqualsTo(0);
199 }
200 } else {
201 dimension.tightenUpperBound(Integer.valueOf(1));
202 boolean _isMust = m_4.isMust();
203 if (_isMust) {
204 dimension.tightenLowerBound(Integer.valueOf(1));
205 }
206 }
207 }
208 }
209 CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 2, this.trainType, 2);
210 CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 3, this.segmentType, 2);
211 CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 4, this.segmentType, 2);
212 CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 5, this.segmentType, 2);
213 final ImmutableList<CostElementMatch> step7Matches = step7.getMatches();
214 for (final CostElementMatch m_5 : step7Matches) {
215 {
216 final Dimension dimension = it.getDimension(m_5.getMatch());
217 objectiveBuilder.add(step7.getWeight(), dimension);
218 dimension.tightenLowerBound(Integer.valueOf(0));
219 boolean _isMulti = m_5.isMulti();
220 boolean _not = (!_isMulti);
221 if (_not) {
222 dimension.tightenUpperBound(Integer.valueOf(1));
223 boolean _isMust = m_5.isMust();
224 if (_isMust) {
225 dimension.tightenLowerBound(Integer.valueOf(1));
226 }
227 }
228 }
229 }
230 final Function1<CostElementMatch, IPatternMatch> _function_4 = (CostElementMatch it_1) -> {
231 return step6.projectMayMatch(it_1.getMatch(), 2, 3, 4, 5);
232 };
233 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet_3 = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step7Matches, _function_4).entrySet();
234 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair_3 : _entrySet_3) {
235 {
236 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
237 List<CostElementMatch> _value = pair_3.getValue();
238 for (final CostElementMatch m_6 : _value) {
239 multiplicityBuilder.add(1, m_6.getMatch());
240 }
241 multiplicityBuilder.add((-1), pair_3.getKey());
242 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
243 }
244 }
245 CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 2, this.trainType, 2);
246 CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 3, this.segmentType, 2);
247 CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 4, this.segmentType, 2);
248 CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 5, this.segmentType, 2);
249 CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 6, this.trainType, 2);
250 this.buildWithBounds(objectiveBuilder);
251 };
252 _xblockexpression = _function;
253 }
254 return _xblockexpression;
255 }
256
257 private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection<CostElementMatch> matches, final int index, final Type type, final int count) {
258 final Function1<CostElementMatch, Object> _function = (CostElementMatch it) -> {
259 return it.getMatch().get(index);
260 };
261 Set<Map.Entry<Object, List<CostElementMatch>>> _entrySet = IterableExtensions.<Object, CostElementMatch>groupBy(matches, _function).entrySet();
262 for (final Map.Entry<Object, List<CostElementMatch>> pair : _entrySet) {
263 {
264 final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder();
265 List<CostElementMatch> _value = pair.getValue();
266 for (final CostElementMatch m : _value) {
267 multiplicityBuilder.add(1, m.getMatch());
268 }
269 boolean _isMulti = CostElementMatchers.isMulti(pair.getKey());
270 if (_isMulti) {
271 multiplicityBuilder.add((-count), type);
272 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
273 } else {
274 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count));
275 }
276 }
277 }
278 }
279}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java
new file mode 100644
index 00000000..77c513e1
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java
@@ -0,0 +1,193 @@
1package modes3.run;
2
3import com.google.common.collect.ImmutableList;
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic;
5import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace;
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type;
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension;
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder;
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory;
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator;
11import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch;
12import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers;
13import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint;
14import java.util.Collection;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import modes3.Modes3Package;
19import modes3.queries.EndOfSiding_step_2;
20import modes3.queries.EndOfSiding_step_3;
21import modes3.queries.EndOfSiding_step_4;
22import modes3.queries.EndOfSiding_step_5;
23import org.eclipse.viatra.query.runtime.api.IPatternMatch;
24import org.eclipse.xtext.xbase.lib.Extension;
25import org.eclipse.xtext.xbase.lib.Functions.Function1;
26import org.eclipse.xtext.xbase.lib.IterableExtensions;
27
28@SuppressWarnings("all")
29public class EndOfSidingObjectiveHint extends CostObjectiveHint {
30 private final Type segmentType;
31
32 private final Type trainType;
33
34 public EndOfSidingObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) {
35 @Extension
36 final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE;
37 this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment());
38 this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain());
39 }
40
41 @Override
42 public boolean isExact() {
43 return true;
44 }
45
46 @Override
47 public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map<String, CostElementMatchers> costElementMatchers) {
48 PolyhedronExtensionOperator _xblockexpression = null;
49 {
50 final CostElementMatchers step2 = costElementMatchers.get(EndOfSiding_step_2.instance().getFullyQualifiedName());
51 final CostElementMatchers step3 = costElementMatchers.get(EndOfSiding_step_3.instance().getFullyQualifiedName());
52 final CostElementMatchers step4 = costElementMatchers.get(EndOfSiding_step_4.instance().getFullyQualifiedName());
53 final CostElementMatchers step5 = costElementMatchers.get(EndOfSiding_step_5.instance().getFullyQualifiedName());
54 final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> {
55 final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder();
56 ImmutableList<CostElementMatch> _matches = step2.getMatches();
57 for (final CostElementMatch m : _matches) {
58 {
59 final Dimension dimension = it.getDimension(m.getMatch());
60 objectiveBuilder.add(step2.getWeight(), dimension);
61 dimension.tightenLowerBound(Integer.valueOf(0));
62 boolean _isMulti = m.isMulti();
63 if (_isMulti) {
64 it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0);
65 } else {
66 dimension.tightenUpperBound(Integer.valueOf(1));
67 boolean _isMust = m.isMust();
68 if (_isMust) {
69 dimension.tightenLowerBound(Integer.valueOf(1));
70 }
71 }
72 }
73 }
74 final ImmutableList<CostElementMatch> step3Matches = step3.getMatches();
75 for (final CostElementMatch m_1 : step3Matches) {
76 {
77 final Dimension dimension = it.getDimension(m_1.getMatch());
78 objectiveBuilder.add(step3.getWeight(), dimension);
79 dimension.tightenLowerBound(Integer.valueOf(0));
80 boolean _isMulti = m_1.isMulti();
81 boolean _not = (!_isMulti);
82 if (_not) {
83 dimension.tightenUpperBound(Integer.valueOf(1));
84 boolean _isMust = m_1.isMust();
85 if (_isMust) {
86 dimension.tightenLowerBound(Integer.valueOf(1));
87 }
88 }
89 }
90 }
91 final Function1<CostElementMatch, IPatternMatch> _function_1 = (CostElementMatch it_1) -> {
92 return step2.projectMayMatch(it_1.getMatch(), 2);
93 };
94 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step3Matches, _function_1).entrySet();
95 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair : _entrySet) {
96 {
97 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
98 List<CostElementMatch> _value = pair.getValue();
99 for (final CostElementMatch m_2 : _value) {
100 multiplicityBuilder.add(1, m_2.getMatch());
101 }
102 multiplicityBuilder.add((-1), pair.getKey());
103 multiplicityBuilder.build().assertEqualsTo(0);
104 }
105 }
106 EndOfSidingObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1);
107 EndOfSidingObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1);
108 final ImmutableList<CostElementMatch> step4Matches = step4.getMatches();
109 for (final CostElementMatch m_2 : step4Matches) {
110 {
111 final Dimension dimension = it.getDimension(m_2.getMatch());
112 objectiveBuilder.add(step4.getWeight(), dimension);
113 dimension.tightenLowerBound(Integer.valueOf(0));
114 boolean _isMulti = m_2.isMulti();
115 boolean _not = (!_isMulti);
116 if (_not) {
117 dimension.tightenUpperBound(Integer.valueOf(1));
118 boolean _isMust = m_2.isMust();
119 if (_isMust) {
120 dimension.tightenLowerBound(Integer.valueOf(1));
121 }
122 }
123 }
124 }
125 final Function1<CostElementMatch, IPatternMatch> _function_2 = (CostElementMatch it_1) -> {
126 return step3.projectMayMatch(it_1.getMatch(), 2, 3);
127 };
128 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet_1 = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step4Matches, _function_2).entrySet();
129 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair_1 : _entrySet_1) {
130 {
131 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
132 List<CostElementMatch> _value = pair_1.getValue();
133 for (final CostElementMatch m_3 : _value) {
134 multiplicityBuilder.add(1, m_3.getMatch());
135 }
136 multiplicityBuilder.add((-2), pair_1.getKey());
137 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
138 }
139 }
140 EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 2, this.trainType, 2);
141 EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2);
142 EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 4, this.segmentType, 2);
143 final ImmutableList<CostElementMatch> step5Matches = step5.getMatches();
144 for (final CostElementMatch m_3 : step5Matches) {
145 {
146 final Dimension dimension = it.getDimension(m_3.getMatch());
147 objectiveBuilder.add(step5.getWeight(), dimension);
148 dimension.tightenLowerBound(Integer.valueOf(0));
149 boolean _isMulti = m_3.isMulti();
150 boolean _not = (!_isMulti);
151 if (_not) {
152 dimension.tightenUpperBound(Integer.valueOf(1));
153 boolean _isMust = m_3.isMust();
154 if (_isMust) {
155 dimension.tightenLowerBound(Integer.valueOf(1));
156 }
157 }
158 it.createBuilder().add(1, m_3.getMatch()).add((-1), step4.projectMayMatch(m_3.getMatch(), 2, 3, 4)).build().tightenUpperBound(Integer.valueOf(0));
159 }
160 }
161 EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 2, this.trainType, 1);
162 EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 2);
163 EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 4, this.segmentType, 1);
164 this.buildWithBounds(objectiveBuilder);
165 };
166 _xblockexpression = _function;
167 }
168 return _xblockexpression;
169 }
170
171 private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection<CostElementMatch> matches, final int index, final Type type, final int count) {
172 final Function1<CostElementMatch, Object> _function = (CostElementMatch it) -> {
173 return it.getMatch().get(index);
174 };
175 Set<Map.Entry<Object, List<CostElementMatch>>> _entrySet = IterableExtensions.<Object, CostElementMatch>groupBy(matches, _function).entrySet();
176 for (final Map.Entry<Object, List<CostElementMatch>> pair : _entrySet) {
177 {
178 final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder();
179 List<CostElementMatch> _value = pair.getValue();
180 for (final CostElementMatch m : _value) {
181 multiplicityBuilder.add(1, m.getMatch());
182 }
183 boolean _isMulti = CostElementMatchers.isMulti(pair.getKey());
184 if (_isMulti) {
185 multiplicityBuilder.add((-count), type);
186 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
187 } else {
188 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count));
189 }
190 }
191 }
192 }
193}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java
new file mode 100644
index 00000000..835a6559
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java
@@ -0,0 +1,195 @@
1package modes3.run;
2
3import com.google.common.collect.ImmutableList;
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic;
5import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace;
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type;
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension;
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder;
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory;
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator;
11import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch;
12import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers;
13import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint;
14import java.util.Collection;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import modes3.Modes3Package;
19import modes3.queries.MisalignedTurnout_step_2;
20import modes3.queries.MisalignedTurnout_step_3;
21import modes3.queries.MisalignedTurnout_step_4;
22import modes3.queries.MisalignedTurnout_step_5;
23import org.eclipse.viatra.query.runtime.api.IPatternMatch;
24import org.eclipse.xtext.xbase.lib.Extension;
25import org.eclipse.xtext.xbase.lib.Functions.Function1;
26import org.eclipse.xtext.xbase.lib.IterableExtensions;
27
28@SuppressWarnings("all")
29public class MisalignedTurnoutObjectiveHint extends CostObjectiveHint {
30 private final Type segmentType;
31
32 private final Type turnoutType;
33
34 private final Type trainType;
35
36 public MisalignedTurnoutObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) {
37 @Extension
38 final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE;
39 this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment());
40 this.turnoutType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTurnout());
41 this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain());
42 }
43
44 @Override
45 public boolean isExact() {
46 return true;
47 }
48
49 @Override
50 public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map<String, CostElementMatchers> costElementMatchers) {
51 PolyhedronExtensionOperator _xblockexpression = null;
52 {
53 final CostElementMatchers step2 = costElementMatchers.get(MisalignedTurnout_step_2.instance().getFullyQualifiedName());
54 final CostElementMatchers step3 = costElementMatchers.get(MisalignedTurnout_step_3.instance().getFullyQualifiedName());
55 final CostElementMatchers step4 = costElementMatchers.get(MisalignedTurnout_step_4.instance().getFullyQualifiedName());
56 final CostElementMatchers step5 = costElementMatchers.get(MisalignedTurnout_step_5.instance().getFullyQualifiedName());
57 final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> {
58 final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder();
59 ImmutableList<CostElementMatch> _matches = step2.getMatches();
60 for (final CostElementMatch m : _matches) {
61 {
62 final Dimension dimension = it.getDimension(m.getMatch());
63 objectiveBuilder.add(step2.getWeight(), dimension);
64 dimension.tightenLowerBound(Integer.valueOf(0));
65 boolean _isMulti = m.isMulti();
66 if (_isMulti) {
67 it.createBuilder().add(1, dimension).add((-1), this.turnoutType).build().assertEqualsTo(0);
68 } else {
69 dimension.tightenUpperBound(Integer.valueOf(1));
70 boolean _isMust = m.isMust();
71 if (_isMust) {
72 dimension.tightenLowerBound(Integer.valueOf(1));
73 }
74 }
75 }
76 }
77 final ImmutableList<CostElementMatch> step3Matches = step3.getMatches();
78 for (final CostElementMatch m_1 : step3Matches) {
79 {
80 final Dimension dimension = it.getDimension(m_1.getMatch());
81 objectiveBuilder.add(step3.getWeight(), dimension);
82 dimension.tightenLowerBound(Integer.valueOf(0));
83 boolean _isMulti = m_1.isMulti();
84 boolean _not = (!_isMulti);
85 if (_not) {
86 dimension.tightenUpperBound(Integer.valueOf(1));
87 boolean _isMust = m_1.isMust();
88 if (_isMust) {
89 dimension.tightenLowerBound(Integer.valueOf(1));
90 }
91 }
92 }
93 }
94 final Function1<CostElementMatch, IPatternMatch> _function_1 = (CostElementMatch it_1) -> {
95 return step2.projectMayMatch(it_1.getMatch(), 2);
96 };
97 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step3Matches, _function_1).entrySet();
98 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair : _entrySet) {
99 {
100 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
101 List<CostElementMatch> _value = pair.getValue();
102 for (final CostElementMatch m_2 : _value) {
103 multiplicityBuilder.add(1, m_2.getMatch());
104 }
105 multiplicityBuilder.add((-1), pair.getKey());
106 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
107 }
108 }
109 MisalignedTurnoutObjectiveHint.boundLimit(it, step3Matches, 2, this.turnoutType, 1);
110 MisalignedTurnoutObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 2);
111 final ImmutableList<CostElementMatch> step4Matches = step4.getMatches();
112 for (final CostElementMatch m_2 : step4Matches) {
113 {
114 final Dimension dimension = it.getDimension(m_2.getMatch());
115 objectiveBuilder.add(step4.getWeight(), dimension);
116 dimension.tightenLowerBound(Integer.valueOf(0));
117 boolean _isMulti = m_2.isMulti();
118 boolean _not = (!_isMulti);
119 if (_not) {
120 dimension.tightenUpperBound(Integer.valueOf(1));
121 boolean _isMust = m_2.isMust();
122 if (_isMust) {
123 dimension.tightenLowerBound(Integer.valueOf(1));
124 }
125 }
126 it.createBuilder().add(1, m_2.getMatch()).add((-1), step3.projectMayMatch(m_2.getMatch(), 2, 3)).build().tightenUpperBound(Integer.valueOf(0));
127 }
128 }
129 MisalignedTurnoutObjectiveHint.boundLimit(it, step4Matches, 2, this.turnoutType, 1);
130 MisalignedTurnoutObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2);
131 final ImmutableList<CostElementMatch> step5Matches = step5.getMatches();
132 for (final CostElementMatch m_3 : step5Matches) {
133 {
134 final Dimension dimension = it.getDimension(m_3.getMatch());
135 objectiveBuilder.add(step5.getWeight(), dimension);
136 dimension.tightenLowerBound(Integer.valueOf(0));
137 boolean _isMulti = m_3.isMulti();
138 boolean _not = (!_isMulti);
139 if (_not) {
140 dimension.tightenUpperBound(Integer.valueOf(1));
141 boolean _isMust = m_3.isMust();
142 if (_isMust) {
143 dimension.tightenLowerBound(Integer.valueOf(1));
144 }
145 }
146 }
147 }
148 final Function1<CostElementMatch, IPatternMatch> _function_2 = (CostElementMatch it_1) -> {
149 return step4.projectMayMatch(it_1.getMatch(), 2, 3);
150 };
151 Set<Map.Entry<IPatternMatch, List<CostElementMatch>>> _entrySet_1 = IterableExtensions.<IPatternMatch, CostElementMatch>groupBy(step5Matches, _function_2).entrySet();
152 for (final Map.Entry<IPatternMatch, List<CostElementMatch>> pair_1 : _entrySet_1) {
153 {
154 final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder();
155 List<CostElementMatch> _value = pair_1.getValue();
156 for (final CostElementMatch m_4 : _value) {
157 multiplicityBuilder.add(1, m_4.getMatch());
158 }
159 multiplicityBuilder.add((-1), pair_1.getKey());
160 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
161 }
162 }
163 MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 2, this.turnoutType, 1);
164 MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 2);
165 MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 4, this.trainType, 2);
166 this.buildWithBounds(objectiveBuilder);
167 };
168 _xblockexpression = _function;
169 }
170 return _xblockexpression;
171 }
172
173 private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection<CostElementMatch> matches, final int index, final Type type, final int count) {
174 final Function1<CostElementMatch, Object> _function = (CostElementMatch it) -> {
175 return it.getMatch().get(index);
176 };
177 Set<Map.Entry<Object, List<CostElementMatch>>> _entrySet = IterableExtensions.<Object, CostElementMatch>groupBy(matches, _function).entrySet();
178 for (final Map.Entry<Object, List<CostElementMatch>> pair : _entrySet) {
179 {
180 final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder();
181 List<CostElementMatch> _value = pair.getValue();
182 for (final CostElementMatch m : _value) {
183 multiplicityBuilder.add(1, m.getMatch());
184 }
185 boolean _isMulti = CostElementMatchers.isMulti(pair.getKey());
186 if (_isMulti) {
187 multiplicityBuilder.add((-count), type);
188 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
189 } else {
190 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count));
191 }
192 }
193 }
194 }
195}
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java
index f32a7172..16db7053 100644
--- a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/Modes3ModelGenerator.java
@@ -13,6 +13,7 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logic
13import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage; 13import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage;
14import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion; 14import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion;
15import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; 15import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel;
16import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicModelInterpretation;
16import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicProblemBuilder; 17import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicProblemBuilder;
17import hu.bme.mit.inf.dslreasoner.logic.model.builder.SolutionScope; 18import hu.bme.mit.inf.dslreasoner.logic.model.builder.SolutionScope;
18import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput; 19import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput;
@@ -32,6 +33,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem;
32import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage; 33import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage;
33import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; 34import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult;
34import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; 35import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult;
36import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore;
35import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic; 37import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic;
36import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration; 38import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration;
37import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicTrace; 39import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicTrace;
@@ -50,10 +52,15 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par
50import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RelationLink; 52import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RelationLink;
51import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml; 53import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml;
52import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; 54import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation;
55import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration;
56import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration;
53import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration; 57import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration;
54import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy; 58import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy;
55import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner; 59import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner;
56import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; 60import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration;
61import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation;
62import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind;
63import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold;
57import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser; 64import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser;
58import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace; 65import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace;
59import java.util.Collections; 66import java.util.Collections;
@@ -64,10 +71,31 @@ import java.util.function.Predicate;
64import modes3.Modes3Factory; 71import modes3.Modes3Factory;
65import modes3.Modes3ModelRoot; 72import modes3.Modes3ModelRoot;
66import modes3.Modes3Package; 73import modes3.Modes3Package;
74import modes3.queries.CloseTrains_step_2;
75import modes3.queries.CloseTrains_step_3;
76import modes3.queries.CloseTrains_step_4;
77import modes3.queries.CloseTrains_step_5;
78import modes3.queries.CloseTrains_step_6;
79import modes3.queries.CloseTrains_step_7;
80import modes3.queries.EndOfSiding_step_2;
81import modes3.queries.EndOfSiding_step_3;
82import modes3.queries.EndOfSiding_step_4;
83import modes3.queries.EndOfSiding_step_5;
84import modes3.queries.MisalignedTurnout_step_2;
85import modes3.queries.MisalignedTurnout_step_3;
86import modes3.queries.MisalignedTurnout_step_4;
87import modes3.queries.MisalignedTurnout_step_5;
67import modes3.queries.Modes3Queries; 88import modes3.queries.Modes3Queries;
89import modes3.queries.TrainLocations_step_2;
90import modes3.queries.TrainLocations_step_3;
91import modes3.run.CloseTrainsObjectiveHint;
92import modes3.run.EndOfSidingObjectiveHint;
93import modes3.run.MisalignedTurnoutObjectiveHint;
68import modes3.run.Modes3TypeScopeHint; 94import modes3.run.Modes3TypeScopeHint;
69import modes3.run.Modes3UnitPropagationGenerator; 95import modes3.run.Modes3UnitPropagationGenerator;
96import modes3.run.TrainLocationsObjectiveHint;
70import org.eclipse.emf.common.util.EList; 97import org.eclipse.emf.common.util.EList;
98import org.eclipse.emf.common.util.TreeIterator;
71import org.eclipse.emf.common.util.URI; 99import org.eclipse.emf.common.util.URI;
72import org.eclipse.emf.ecore.EAttribute; 100import org.eclipse.emf.ecore.EAttribute;
73import org.eclipse.emf.ecore.EClass; 101import org.eclipse.emf.ecore.EClass;
@@ -102,6 +130,10 @@ public class Modes3ModelGenerator {
102 private enum MonitoringQuery { 130 private enum MonitoringQuery {
103 closeTrains, 131 closeTrains,
104 132
133 trainLocations,
134
135 endOfSiding,
136
105 misalignedTurnout; 137 misalignedTurnout;
106 } 138 }
107 139
@@ -183,8 +215,9 @@ public class Modes3ModelGenerator {
183 ObjectExtensions.<Map<Type, Integer>>operator_doubleArrow( 215 ObjectExtensions.<Map<Type, Integer>>operator_doubleArrow(
184 it_1.minNewElementsByType, _function_4); 216 it_1.minNewElementsByType, _function_4);
185 final Procedure1<Map<Type, Integer>> _function_5 = (Map<Type, Integer> it_2) -> { 217 final Procedure1<Map<Type, Integer>> _function_5 = (Map<Type, Integer> it_2) -> {
186 it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf(5)); 218 it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf((this.modelSize / 5)));
187 it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf(5)); 219 it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf((this.modelSize / 5)));
220 it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getSimpleSegment()), Integer.valueOf(((3 * this.modelSize) / 5)));
188 }; 221 };
189 ObjectExtensions.<Map<Type, Integer>>operator_doubleArrow( 222 ObjectExtensions.<Map<Type, Integer>>operator_doubleArrow(
190 it_1.maxNewElementsByType, _function_5); 223 it_1.maxNewElementsByType, _function_5);
@@ -196,7 +229,9 @@ public class Modes3ModelGenerator {
196 }; 229 };
197 ObjectExtensions.<SolutionScope>operator_doubleArrow( 230 ObjectExtensions.<SolutionScope>operator_doubleArrow(
198 it.solutionScope, _function_4); 231 it.solutionScope, _function_4);
199 it.scopeWeight = 5; 232 CostObjectiveConfiguration _objective = this.getObjective(this.ecore2Logic, metamodelLogic.getTrace());
233 it.costObjectives.add(_objective);
234 it.scopeWeight = 6;
200 it.nameNewElements = false; 235 it.nameNewElements = false;
201 it.typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis; 236 it.typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis;
202 it.stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood; 237 it.stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood;
@@ -224,80 +259,103 @@ public class Modes3ModelGenerator {
224 URI _xifexpression = null; 259 URI _xifexpression = null;
225 if ((solution instanceof ModelResult)) { 260 if ((solution instanceof ModelResult)) {
226 InputOutput.<String>println("Saving generated solutions"); 261 InputOutput.<String>println("Saving generated solutions");
227 final EList<Object> representations = ((ModelResult)solution).getRepresentation(); 262 final Logic2Ecore logic2Ecore = new Logic2Ecore(this.ecore2Logic);
228 int _size = representations.size(); 263 final List<? extends LogicModelInterpretation> interpretations = this.solver.getInterpretations(((ModelResult)solution));
264 int _size = interpretations.size();
229 ExclusiveRange _doubleDotLessThan = new ExclusiveRange(0, _size, true); 265 ExclusiveRange _doubleDotLessThan = new ExclusiveRange(0, _size, true);
230 for (final Integer representationIndex : _doubleDotLessThan) { 266 for (final Integer representationIndex : _doubleDotLessThan) {
231 { 267 {
232 final Object representation = representations.get((representationIndex).intValue()); 268 final LogicModelInterpretation interpretation = interpretations.get((representationIndex).intValue());
233 final int representationNumber = ((representationIndex).intValue() + 1); 269 final int representationNumber = ((representationIndex).intValue() + 1);
234 if ((representation instanceof PartialInterpretation)) { 270 if ((interpretation instanceof PartialModelAsLogicInterpretation)) {
271 final PartialInterpretation representation = ((PartialModelAsLogicInterpretation)interpretation).getPartialInterpretation();
235 StringConcatenation _builder_1 = new StringConcatenation(); 272 StringConcatenation _builder_1 = new StringConcatenation();
236 _builder_1.append("solution"); 273 _builder_1.append("solution");
237 _builder_1.append(representationNumber); 274 _builder_1.append(representationNumber);
238 _builder_1.append(".partialinterpretation"); 275 _builder_1.append(".partialinterpretation");
239 workspace.writeModel(((EObject)representation), _builder_1.toString()); 276 workspace.writeModel(representation, _builder_1.toString());
240 final PartialInterpretation2Gml partialInterpretation2GML = new PartialInterpretation2Gml(); 277 final PartialInterpretation2Gml partialInterpretation2GML = new PartialInterpretation2Gml();
241 final String gml = partialInterpretation2GML.transform(((PartialInterpretation)representation)); 278 final String gml = partialInterpretation2GML.transform(representation);
242 StringConcatenation _builder_2 = new StringConcatenation(); 279 StringConcatenation _builder_2 = new StringConcatenation();
243 _builder_2.append("solution"); 280 _builder_2.append("solution");
244 _builder_2.append(representationNumber); 281 _builder_2.append(representationNumber);
245 _builder_2.append(".gml"); 282 _builder_2.append(".gml");
246 workspace.writeText(_builder_2.toString(), gml); 283 workspace.writeText(_builder_2.toString(), gml);
247 int _size_1 = ((PartialInterpretation)representation).getNewElements().size(); 284 final EObject model = logic2Ecore.transformInterpretation(interpretation, metamodelLogic.getTrace());
248 boolean _lessThan = (_size_1 < 160); 285 final TreeIterator<EObject> iterator = model.eAllContents();
249 if (_lessThan) { 286 int id = 0;
250 if ((representation instanceof PartialInterpretation)) { 287 while (iterator.hasNext()) {
251 final Function1<Type, Boolean> _function_3 = (Type it) -> { 288 {
289 final EObject obj = iterator.next();
290 final Function1<EAttribute, Boolean> _function_3 = (EAttribute it) -> {
252 String _name_2 = it.getName(); 291 String _name_2 = it.getName();
253 return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart")); 292 return Boolean.valueOf(Objects.equal(_name_2, "id"));
254 }; 293 };
255 Type _findFirst = IterableExtensions.<Type>findFirst(((PartialInterpretation)representation).getProblem().getTypes(), _function_3); 294 final EAttribute idFeature = IterableExtensions.<EAttribute>findFirst(obj.eClass().getEAllAttributes(), _function_3);
256 final TypeDefinition rootType = ((TypeDefinition) _findFirst); 295 if ((idFeature != null)) {
257 final Function1<PartialComplexTypeInterpretation, Boolean> _function_4 = (PartialComplexTypeInterpretation it) -> { 296 obj.eSet(idFeature, Integer.valueOf(id));
258 String _name_2 = it.getInterpretationOf().getName(); 297 id++;
259 return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class"));
260 };
261 final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.<PartialComplexTypeInterpretation>findFirst(Iterables.<PartialComplexTypeInterpretation>filter(((PartialInterpretation)representation).getPartialtypeinterpratation(),
262 PartialComplexTypeInterpretation.class), _function_4);
263 rootIntepretation.getElements().removeAll(rootType.getElements());
264 ((PartialInterpretation)representation).getProblem().getElements().removeAll(rootType.getElements());
265 EList<PartialRelationInterpretation> _partialrelationinterpretation = ((PartialInterpretation)representation).getPartialrelationinterpretation();
266 for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) {
267 final Predicate<RelationLink> _function_5 = (RelationLink link) -> {
268 boolean _xifexpression_1 = false;
269 if ((link instanceof BinaryElementRelationLink)) {
270 _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) || rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2()));
271 } else {
272 _xifexpression_1 = false;
273 }
274 return _xifexpression_1;
275 };
276 relationInterpretation.getRelationlinks().removeIf(_function_5);
277 } 298 }
278 rootType.getElements().clear();
279 } 299 }
300 }
301 StringConcatenation _builder_3 = new StringConcatenation();
302 _builder_3.append("solution");
303 _builder_3.append(representationNumber);
304 _builder_3.append(".modes3");
305 workspace.writeModel(model, _builder_3.toString());
306 int _size_1 = representation.getNewElements().size();
307 boolean _lessThan = (_size_1 < 160);
308 if (_lessThan) {
309 final Function1<Type, Boolean> _function_3 = (Type it) -> {
310 String _name_2 = it.getName();
311 return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart"));
312 };
313 Type _findFirst = IterableExtensions.<Type>findFirst(representation.getProblem().getTypes(), _function_3);
314 final TypeDefinition rootType = ((TypeDefinition) _findFirst);
315 final Function1<PartialComplexTypeInterpretation, Boolean> _function_4 = (PartialComplexTypeInterpretation it) -> {
316 String _name_2 = it.getInterpretationOf().getName();
317 return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class"));
318 };
319 final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.<PartialComplexTypeInterpretation>findFirst(Iterables.<PartialComplexTypeInterpretation>filter(representation.getPartialtypeinterpratation(),
320 PartialComplexTypeInterpretation.class), _function_4);
321 rootIntepretation.getElements().removeAll(rootType.getElements());
322 representation.getProblem().getElements().removeAll(rootType.getElements());
323 EList<PartialRelationInterpretation> _partialrelationinterpretation = representation.getPartialrelationinterpretation();
324 for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) {
325 final Predicate<RelationLink> _function_5 = (RelationLink link) -> {
326 boolean _xifexpression_1 = false;
327 if ((link instanceof BinaryElementRelationLink)) {
328 _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) ||
329 rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2()));
330 } else {
331 _xifexpression_1 = false;
332 }
333 return _xifexpression_1;
334 };
335 relationInterpretation.getRelationlinks().removeIf(_function_5);
336 }
337 rootType.getElements().clear();
280 final GraphvizVisualiser visualiser = new GraphvizVisualiser(); 338 final GraphvizVisualiser visualiser = new GraphvizVisualiser();
281 final PartialInterpretationVisualisation visualisation = visualiser.visualiseConcretization(((PartialInterpretation)representation)); 339 final PartialInterpretationVisualisation visualisation = visualiser.visualiseConcretization(representation);
282 StringConcatenation _builder_3 = new StringConcatenation(); 340 StringConcatenation _builder_4 = new StringConcatenation();
283 _builder_3.append("solution"); 341 _builder_4.append("solution");
284 _builder_3.append(representationNumber); 342 _builder_4.append(representationNumber);
285 _builder_3.append(".png"); 343 _builder_4.append(".png");
286 visualisation.writeToFile(workspace, _builder_3.toString()); 344 visualisation.writeToFile(workspace, _builder_4.toString());
287 } 345 }
288 } else { 346 } else {
289 StringConcatenation _builder_4 = new StringConcatenation(); 347 StringConcatenation _builder_5 = new StringConcatenation();
290 _builder_4.append("solution"); 348 _builder_5.append("solution");
291 _builder_4.append(representationNumber); 349 _builder_5.append(representationNumber);
292 _builder_4.append(".txt"); 350 _builder_5.append(".txt");
293 workspace.writeText(_builder_4.toString(), representation.toString()); 351 workspace.writeText(_builder_5.toString(), interpretation.toString());
294 } 352 }
295 } 353 }
296 } 354 }
297 } else { 355 } else {
298 URI _xblockexpression_1 = null; 356 URI _xblockexpression_1 = null;
299 { 357 {
300 InputOutput.<String>println("Failed to solver problem"); 358 InputOutput.<String>println("Failed to solve problem");
301 final LogicProblem partial = logic.getOutput(); 359 final LogicProblem partial = logic.getOutput();
302 _xblockexpression_1 = workspace.writeModel(partial, "solution.partialinterpretation"); 360 _xblockexpression_1 = workspace.writeModel(partial, "solution.partialinterpretation");
303 } 361 }
@@ -354,6 +412,153 @@ public class Modes3ModelGenerator {
354 return _xblockexpression; 412 return _xblockexpression;
355 } 413 }
356 414
415 public CostObjectiveConfiguration getObjective(final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) {
416 CostObjectiveConfiguration _costObjectiveConfiguration = new CostObjectiveConfiguration();
417 final Procedure1<CostObjectiveConfiguration> _function = (CostObjectiveConfiguration it) -> {
418 final Modes3ModelGenerator.MonitoringQuery monitoringQuery = this.monitoringQuery;
419 if (monitoringQuery != null) {
420 switch (monitoringQuery) {
421 case closeTrains:
422 CostObjectiveElementConfiguration _costObjectiveElementConfiguration = new CostObjectiveElementConfiguration();
423 final Procedure1<CostObjectiveElementConfiguration> _function_1 = (CostObjectiveElementConfiguration it_1) -> {
424 it_1.patternQualifiedName = CloseTrains_step_2.instance().getFullyQualifiedName();
425 it_1.weight = ((14 + 53) + 11);
426 };
427 CostObjectiveElementConfiguration _doubleArrow = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration, _function_1);
428 it.elements.add(_doubleArrow);
429 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_1 = new CostObjectiveElementConfiguration();
430 final Procedure1<CostObjectiveElementConfiguration> _function_2 = (CostObjectiveElementConfiguration it_1) -> {
431 it_1.patternQualifiedName = CloseTrains_step_3.instance().getFullyQualifiedName();
432 it_1.weight = (21 + 14);
433 };
434 CostObjectiveElementConfiguration _doubleArrow_1 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_1, _function_2);
435 it.elements.add(_doubleArrow_1);
436 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_2 = new CostObjectiveElementConfiguration();
437 final Procedure1<CostObjectiveElementConfiguration> _function_3 = (CostObjectiveElementConfiguration it_1) -> {
438 it_1.patternQualifiedName = CloseTrains_step_4.instance().getFullyQualifiedName();
439 it_1.weight = (((14 + 44) + 14) + 9);
440 };
441 CostObjectiveElementConfiguration _doubleArrow_2 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_2, _function_3);
442 it.elements.add(_doubleArrow_2);
443 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_3 = new CostObjectiveElementConfiguration();
444 final Procedure1<CostObjectiveElementConfiguration> _function_4 = (CostObjectiveElementConfiguration it_1) -> {
445 it_1.patternQualifiedName = CloseTrains_step_5.instance().getFullyQualifiedName();
446 it_1.weight = ((14 + 41) + 11);
447 };
448 CostObjectiveElementConfiguration _doubleArrow_3 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_3, _function_4);
449 it.elements.add(_doubleArrow_3);
450 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_4 = new CostObjectiveElementConfiguration();
451 final Procedure1<CostObjectiveElementConfiguration> _function_5 = (CostObjectiveElementConfiguration it_1) -> {
452 it_1.patternQualifiedName = CloseTrains_step_6.instance().getFullyQualifiedName();
453 it_1.weight = 27;
454 };
455 CostObjectiveElementConfiguration _doubleArrow_4 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_4, _function_5);
456 it.elements.add(_doubleArrow_4);
457 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_5 = new CostObjectiveElementConfiguration();
458 final Procedure1<CostObjectiveElementConfiguration> _function_6 = (CostObjectiveElementConfiguration it_1) -> {
459 it_1.patternQualifiedName = CloseTrains_step_7.instance().getFullyQualifiedName();
460 it_1.weight = 48;
461 };
462 CostObjectiveElementConfiguration _doubleArrow_5 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_5, _function_6);
463 it.elements.add(_doubleArrow_5);
464 CloseTrainsObjectiveHint _closeTrainsObjectiveHint = new CloseTrainsObjectiveHint(ecore2Logic, ecore2LogicTrace);
465 it.hint = _closeTrainsObjectiveHint;
466 break;
467 case trainLocations:
468 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_6 = new CostObjectiveElementConfiguration();
469 final Procedure1<CostObjectiveElementConfiguration> _function_7 = (CostObjectiveElementConfiguration it_1) -> {
470 it_1.patternQualifiedName = TrainLocations_step_2.instance().getFullyQualifiedName();
471 it_1.weight = ((14 + 53) + 11);
472 };
473 CostObjectiveElementConfiguration _doubleArrow_6 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_6, _function_7);
474 it.elements.add(_doubleArrow_6);
475 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_7 = new CostObjectiveElementConfiguration();
476 final Procedure1<CostObjectiveElementConfiguration> _function_8 = (CostObjectiveElementConfiguration it_1) -> {
477 it_1.patternQualifiedName = TrainLocations_step_3.instance().getFullyQualifiedName();
478 it_1.weight = 48;
479 };
480 CostObjectiveElementConfiguration _doubleArrow_7 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_7, _function_8);
481 it.elements.add(_doubleArrow_7);
482 TrainLocationsObjectiveHint _trainLocationsObjectiveHint = new TrainLocationsObjectiveHint(ecore2Logic, ecore2LogicTrace);
483 it.hint = _trainLocationsObjectiveHint;
484 break;
485 case misalignedTurnout:
486 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_8 = new CostObjectiveElementConfiguration();
487 final Procedure1<CostObjectiveElementConfiguration> _function_9 = (CostObjectiveElementConfiguration it_1) -> {
488 it_1.patternQualifiedName = MisalignedTurnout_step_2.instance().getFullyQualifiedName();
489 it_1.weight = ((14 + 53) + 11);
490 };
491 CostObjectiveElementConfiguration _doubleArrow_8 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_8, _function_9);
492 it.elements.add(_doubleArrow_8);
493 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_9 = new CostObjectiveElementConfiguration();
494 final Procedure1<CostObjectiveElementConfiguration> _function_10 = (CostObjectiveElementConfiguration it_1) -> {
495 it_1.patternQualifiedName = MisalignedTurnout_step_3.instance().getFullyQualifiedName();
496 it_1.weight = 108;
497 };
498 CostObjectiveElementConfiguration _doubleArrow_9 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_9, _function_10);
499 it.elements.add(_doubleArrow_9);
500 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_10 = new CostObjectiveElementConfiguration();
501 final Procedure1<CostObjectiveElementConfiguration> _function_11 = (CostObjectiveElementConfiguration it_1) -> {
502 it_1.patternQualifiedName = MisalignedTurnout_step_4.instance().getFullyQualifiedName();
503 it_1.weight = 27;
504 };
505 CostObjectiveElementConfiguration _doubleArrow_10 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_10, _function_11);
506 it.elements.add(_doubleArrow_10);
507 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_11 = new CostObjectiveElementConfiguration();
508 final Procedure1<CostObjectiveElementConfiguration> _function_12 = (CostObjectiveElementConfiguration it_1) -> {
509 it_1.patternQualifiedName = MisalignedTurnout_step_5.instance().getFullyQualifiedName();
510 it_1.weight = 48;
511 };
512 CostObjectiveElementConfiguration _doubleArrow_11 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_11, _function_12);
513 it.elements.add(_doubleArrow_11);
514 MisalignedTurnoutObjectiveHint _misalignedTurnoutObjectiveHint = new MisalignedTurnoutObjectiveHint(ecore2Logic, ecore2LogicTrace);
515 it.hint = _misalignedTurnoutObjectiveHint;
516 break;
517 case endOfSiding:
518 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_12 = new CostObjectiveElementConfiguration();
519 final Procedure1<CostObjectiveElementConfiguration> _function_13 = (CostObjectiveElementConfiguration it_1) -> {
520 it_1.patternQualifiedName = EndOfSiding_step_2.instance().getFullyQualifiedName();
521 it_1.weight = ((14 + 53) + 11);
522 };
523 CostObjectiveElementConfiguration _doubleArrow_12 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_12, _function_13);
524 it.elements.add(_doubleArrow_12);
525 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_13 = new CostObjectiveElementConfiguration();
526 final Procedure1<CostObjectiveElementConfiguration> _function_14 = (CostObjectiveElementConfiguration it_1) -> {
527 it_1.patternQualifiedName = EndOfSiding_step_3.instance().getFullyQualifiedName();
528 it_1.weight = (21 + 14);
529 };
530 CostObjectiveElementConfiguration _doubleArrow_13 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_13, _function_14);
531 it.elements.add(_doubleArrow_13);
532 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_14 = new CostObjectiveElementConfiguration();
533 final Procedure1<CostObjectiveElementConfiguration> _function_15 = (CostObjectiveElementConfiguration it_1) -> {
534 it_1.patternQualifiedName = EndOfSiding_step_4.instance().getFullyQualifiedName();
535 it_1.weight = (((((((14 + 35) + 21) + 15) + 14) + 21) + 15) + 11);
536 };
537 CostObjectiveElementConfiguration _doubleArrow_14 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_14, _function_15);
538 it.elements.add(_doubleArrow_14);
539 CostObjectiveElementConfiguration _costObjectiveElementConfiguration_15 = new CostObjectiveElementConfiguration();
540 final Procedure1<CostObjectiveElementConfiguration> _function_16 = (CostObjectiveElementConfiguration it_1) -> {
541 it_1.patternQualifiedName = EndOfSiding_step_5.instance().getFullyQualifiedName();
542 it_1.weight = 48;
543 };
544 CostObjectiveElementConfiguration _doubleArrow_15 = ObjectExtensions.<CostObjectiveElementConfiguration>operator_doubleArrow(_costObjectiveElementConfiguration_15, _function_16);
545 it.elements.add(_doubleArrow_15);
546 EndOfSidingObjectiveHint _endOfSidingObjectiveHint = new EndOfSidingObjectiveHint(ecore2Logic, ecore2LogicTrace);
547 it.hint = _endOfSidingObjectiveHint;
548 break;
549 default:
550 throw new IllegalArgumentException(("Unknown monitoring query: " + this.monitoringQuery));
551 }
552 } else {
553 throw new IllegalArgumentException(("Unknown monitoring query: " + this.monitoringQuery));
554 }
555 it.kind = ObjectiveKind.HIGHER_IS_BETTER;
556 it.threshold = ObjectiveThreshold.NO_THRESHOLD;
557 it.findExtremum = true;
558 };
559 return ObjectExtensions.<CostObjectiveConfiguration>operator_doubleArrow(_costObjectiveConfiguration, _function);
560 }
561
357 public static Object init() { 562 public static Object init() {
358 Object _xblockexpression = null; 563 Object _xblockexpression = null;
359 { 564 {
diff --git a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java
new file mode 100644
index 00000000..570f9deb
--- /dev/null
+++ b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java
@@ -0,0 +1,117 @@
1package modes3.run;
2
3import com.google.common.collect.ImmutableList;
4import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic;
5import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace;
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type;
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension;
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder;
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory;
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator;
11import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch;
12import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers;
13import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint;
14import java.util.Collection;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import modes3.Modes3Package;
19import modes3.queries.TrainLocations_step_2;
20import modes3.queries.TrainLocations_step_3;
21import org.eclipse.xtext.xbase.lib.Extension;
22import org.eclipse.xtext.xbase.lib.Functions.Function1;
23import org.eclipse.xtext.xbase.lib.IterableExtensions;
24
25@SuppressWarnings("all")
26public class TrainLocationsObjectiveHint extends CostObjectiveHint {
27 private final Type segmentType;
28
29 private final Type trainType;
30
31 public TrainLocationsObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) {
32 @Extension
33 final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE;
34 this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment());
35 this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain());
36 }
37
38 @Override
39 public boolean isExact() {
40 return true;
41 }
42
43 @Override
44 public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map<String, CostElementMatchers> costElementMatchers) {
45 PolyhedronExtensionOperator _xblockexpression = null;
46 {
47 final CostElementMatchers step2 = costElementMatchers.get(TrainLocations_step_2.instance().getFullyQualifiedName());
48 final CostElementMatchers step3 = costElementMatchers.get(TrainLocations_step_3.instance().getFullyQualifiedName());
49 final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> {
50 final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder();
51 ImmutableList<CostElementMatch> _matches = step2.getMatches();
52 for (final CostElementMatch m : _matches) {
53 {
54 final Dimension dimension = it.getDimension(m.getMatch());
55 objectiveBuilder.add(step2.getWeight(), dimension);
56 dimension.tightenLowerBound(Integer.valueOf(0));
57 boolean _isMulti = m.isMulti();
58 if (_isMulti) {
59 it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0);
60 } else {
61 dimension.tightenUpperBound(Integer.valueOf(1));
62 boolean _isMust = m.isMust();
63 if (_isMust) {
64 dimension.tightenLowerBound(Integer.valueOf(1));
65 }
66 }
67 }
68 }
69 final ImmutableList<CostElementMatch> step3Matches = step3.getMatches();
70 for (final CostElementMatch m_1 : step3Matches) {
71 {
72 final Dimension dimension = it.getDimension(m_1.getMatch());
73 objectiveBuilder.add(step3.getWeight(), dimension);
74 dimension.tightenLowerBound(Integer.valueOf(0));
75 boolean _isMulti = m_1.isMulti();
76 boolean _not = (!_isMulti);
77 if (_not) {
78 dimension.tightenUpperBound(Integer.valueOf(1));
79 boolean _isMust = m_1.isMust();
80 if (_isMust) {
81 dimension.tightenLowerBound(Integer.valueOf(1));
82 }
83 }
84 }
85 }
86 TrainLocationsObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1);
87 TrainLocationsObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1);
88 this.buildWithBounds(objectiveBuilder);
89 };
90 _xblockexpression = _function;
91 }
92 return _xblockexpression;
93 }
94
95 private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection<CostElementMatch> matches, final int index, final Type type, final int count) {
96 final Function1<CostElementMatch, Object> _function = (CostElementMatch it) -> {
97 return it.getMatch().get(index);
98 };
99 Set<Map.Entry<Object, List<CostElementMatch>>> _entrySet = IterableExtensions.<Object, CostElementMatch>groupBy(matches, _function).entrySet();
100 for (final Map.Entry<Object, List<CostElementMatch>> pair : _entrySet) {
101 {
102 final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder();
103 List<CostElementMatch> _value = pair.getValue();
104 for (final CostElementMatch m : _value) {
105 multiplicityBuilder.add(1, m.getMatch());
106 }
107 boolean _isMulti = CostElementMatchers.isMulti(pair.getKey());
108 if (_isMulti) {
109 multiplicityBuilder.add((-count), type);
110 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0));
111 } else {
112 multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count));
113 }
114 }
115 }
116 }
117}
diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF b/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF
index 5fb85170..cc71bd06 100644
--- a/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF
+++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.alloyexamples/META-INF/MANIFEST.MF
@@ -15,7 +15,6 @@ Require-Bundle: org.eclipse.viatra.addon.querybasedfeatures.runtime,
15 org.eclipse.viatra.query.runtime, 15 org.eclipse.viatra.query.runtime,
16 org.eclipse.core.runtime, 16 org.eclipse.core.runtime,
17 org.eclipse.emf.ecore;visibility:=reexport, 17 org.eclipse.emf.ecore;visibility:=reexport,
18 org.eclipse.emf.emfstore.common,
19 com.google.guava, 18 com.google.guava,
20 org.eclipse.xtext.xbase.lib, 19 org.eclipse.xtext.xbase.lib,
21 org.eclipse.xtend.lib, 20 org.eclipse.xtend.lib,
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF
index b9da0f0b..ec1557e8 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/META-INF/MANIFEST.MF
@@ -8,7 +8,8 @@ Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra,
8 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval, 8 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval,
9 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators, 9 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators,
10 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns, 10 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns,
11 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries 11 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries,
12 hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules
12Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0", 13Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0",
13 hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage;bundle-version="1.0.0", 14 hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage;bundle-version="1.0.0",
14 hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 15 hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0",
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend
new file mode 100644
index 00000000..bd5bf807
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend
@@ -0,0 +1,47 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra
2
3class ModelGenerationStatistics {
4 public var long transformationExecutionTime = 0
5
6 synchronized def addExecutionTime(long amount) {
7 transformationExecutionTime += amount
8 }
9
10 public var long scopePropagationTime = 0
11
12 synchronized def addScopePropagationTime(long amount) {
13 scopePropagationTime += amount
14 }
15
16 public var long mustRelationPropagationTime = 0
17
18 synchronized def addMustRelationPropagationTime(long amount) {
19 mustRelationPropagationTime += amount
20 }
21
22 public var long preliminaryTypeAnalisisTime = 0
23
24 public var int decisionsTried = 0
25
26 synchronized def incrementDecisionCount() {
27 decisionsTried++
28 }
29
30 public var int transformationInvocations
31
32 synchronized def incrementTransformationCount() {
33 transformationInvocations++
34 }
35
36 public var int scopePropagatorInvocations
37
38 synchronized def incrementScopePropagationCount() {
39 scopePropagatorInvocations++
40 }
41
42 public var int scopePropagatorSolverInvocations
43
44 synchronized def incrementScopePropagationSolverCount() {
45 scopePropagatorSolverInvocations++
46 }
47}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend
new file mode 100644
index 00000000..9296a0be
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend
@@ -0,0 +1,44 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra
2
3import com.google.common.collect.ImmutableMap
4import com.google.common.collect.ImmutableSet
5import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel
6import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
7import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CachingSimplePolyhedronScopePropagatorStrategy
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator
12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator
14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator
17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver
18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns
19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries
20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider
21import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator
22import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider
23import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider
24import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
25import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
26import java.util.Collection
27import java.util.List
28import java.util.Map
29import java.util.Set
30import org.eclipse.viatra.query.runtime.api.GenericQueryGroup
31import org.eclipse.viatra.query.runtime.api.IPatternMatch
32import org.eclipse.viatra.query.runtime.api.IQuerySpecification
33import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine
34import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
35import org.eclipse.viatra.query.runtime.emf.EMFScope
36import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
37import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
38import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule
39import org.eclipse.xtend.lib.annotations.Data
40
41enum TypeInferenceMethod {
42 Generic,
43 PreliminaryAnalysis
44} \ No newline at end of file
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend
new file mode 100644
index 00000000..6054affe
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend
@@ -0,0 +1,140 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.google.common.collect.ImmutableList
4import com.google.common.collect.ImmutableMap
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
6import java.util.ArrayList
7import java.util.HashMap
8import java.util.HashSet
9import java.util.List
10import java.util.Map
11import java.util.Set
12import org.eclipse.viatra.query.runtime.api.IPatternMatch
13import org.eclipse.xtend.lib.annotations.Accessors
14import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
15
16interface BoundSaturationListener {
17 def void boundsSaturated(Integer lower, Integer upper)
18}
19
20interface ExtendedLinearExpressionBuilderFactory {
21 def ExtendedLinearExpressionBuilder createBuilder()
22
23 def Dimension getDimension(IPatternMatch patternMatch)
24}
25
26interface ExtendedLinearExpressionBuilder extends LinearTypeExpressionBuilder {
27 override ExtendedLinearExpressionBuilder add(int scale, Type type)
28
29 def ExtendedLinearExpressionBuilder add(int scale, IPatternMatch patternMatch)
30
31 def ExtendedLinearExpressionBuilder add(int scale, Dimension dimension)
32
33 def LinearBoundedExpression build(BoundSaturationListener listener)
34}
35
36class ExtendedPolyhedronBuilder implements ExtendedLinearExpressionBuilderFactory {
37 val Map<Type, LinearBoundedExpression> typeBounds
38 val Map<Map<Dimension, Integer>, LinearBoundedExpression> expressionsCache
39
40 val ImmutableList.Builder<Dimension> dimensions = ImmutableList.builder
41 val Set<LinearConstraint> constraints = new HashSet
42 val Set<LinearBoundedExpression> expressionsToSaturate = new HashSet
43 val Map<IPatternMatch, Dimension> patternMatchCounts = new HashMap
44 @Accessors(PUBLIC_GETTER) val List<Pair<LinearBoundedExpression, BoundSaturationListener>> saturationListeners = new ArrayList
45
46 new(Polyhedron polyhedron, Map<Type, LinearBoundedExpression> typeBounds,
47 Map<Map<Dimension, Integer>, LinearBoundedExpression> initialExpressionsCache) {
48 this.typeBounds = typeBounds
49 this.expressionsCache = new HashMap(initialExpressionsCache)
50 dimensions.addAll(polyhedron.dimensions)
51 constraints.addAll(polyhedron.constraints)
52 expressionsToSaturate.addAll(polyhedron.expressionsToSaturate)
53 }
54
55 override createBuilder() {
56 new ExtendedLinearExpressionBuilderImpl(this)
57 }
58
59 override getDimension(IPatternMatch patternMatch) {
60 patternMatchCounts.computeIfAbsent(patternMatch) [ key |
61 val dimension = new Dimension(key.toString, 0, null)
62 dimensions.add(dimension)
63 dimension
64 ]
65 }
66
67 def buildPolyhedron() {
68 new Polyhedron(
69 dimensions.build,
70 ImmutableList.copyOf(constraints),
71 ImmutableList.copyOf(expressionsToSaturate)
72 )
73 }
74
75 @FinalFieldsConstructor
76 private static class ExtendedLinearExpressionBuilderImpl implements ExtendedLinearExpressionBuilder {
77 val ExtendedPolyhedronBuilder polyhedronBuilder
78
79 val Map<Dimension, Integer> coefficients = new HashMap
80
81 override add(int scale, Type type) {
82 val expression = polyhedronBuilder.typeBounds.get(type)
83 if (expression === null) {
84 throw new IllegalArgumentException("Unknown Type: " + type)
85 }
86 add(scale, expression)
87 }
88
89 override add(int scale, IPatternMatch patternMatch) {
90 val dimension = polyhedronBuilder.getDimension(patternMatch)
91 add(scale, dimension)
92 }
93
94 private def add(int scale, LinearBoundedExpression expression) {
95 switch (expression) {
96 Dimension: add(scale, expression)
97 LinearConstraint: add(scale, expression.coefficients)
98 default: throw new IllegalArgumentException("Unknown LinearBoundedExpression: " + expression)
99 }
100 }
101
102 private def add(int scale, Map<Dimension, Integer> coefficients) {
103 for (pair : coefficients.entrySet) {
104 add(scale * pair.value, pair.key)
105 }
106 this
107 }
108
109 override add(int scale, Dimension dimension) {
110 coefficients.merge(dimension, scale)[a, b|a + b]
111 this
112 }
113
114 override build() {
115 val filteredCoefficients = ImmutableMap.copyOf(coefficients.filter [ _, coefficient |
116 coefficient != 0
117 ])
118 polyhedronBuilder.expressionsCache.computeIfAbsent(filteredCoefficients) [ map |
119 if (map.size == 1) {
120 val pair = map.entrySet.head
121 if (pair.value == 1) {
122 return pair.key
123 }
124 }
125 val constraint = new LinearConstraint(map)
126 polyhedronBuilder.constraints.add(constraint)
127 constraint
128 ]
129 }
130
131 override build(BoundSaturationListener listener) {
132 val expression = build()
133 if (listener !== null) {
134 polyhedronBuilder.expressionsToSaturate.add(expression)
135 polyhedronBuilder.saturationListeners.add(expression -> listener)
136 }
137 expression
138 }
139 }
140}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend
new file mode 100644
index 00000000..32923396
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend
@@ -0,0 +1,63 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
5import java.util.Collection
6import java.util.Map
7import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
8
9interface PolyhedronExtensionOperator {
10 def void extendPolyhedron(ExtendedLinearExpressionBuilderFactory factory)
11}
12
13class ExtendedPolyhedronScopePropagatorStrategy extends PolyhedronScopePropagatorStrategy {
14 val PolyhedronSolver solver
15 val Collection<PolyhedronExtensionOperator> extensionOperators
16
17 var Map<Type, LinearBoundedExpression> typeBounds
18 var Map<Map<Dimension, Integer>, LinearBoundedExpression> initialExpressionsCache
19
20 new(PolyhedronSolver solver, Collection<PolyhedronExtensionOperator> extensionOperators,
21 ModelGenerationStatistics statistics) {
22 super(statistics)
23 this.solver = solver
24 this.extensionOperators = extensionOperators
25 }
26
27 override setPolyhedron(Polyhedron polyhedron, Map<Type, LinearBoundedExpression> typeBounds,
28 Map<Map<Dimension, Integer>, LinearBoundedExpression> initialExpressionsCache) {
29 super.setPolyhedron(polyhedron, typeBounds, initialExpressionsCache)
30 this.typeBounds = typeBounds
31 this.initialExpressionsCache = initialExpressionsCache
32 }
33
34 override isRelevantRelation(Relation relation) {
35 true
36 }
37
38 override protected doSaturate() {
39 val builder = new ExtendedPolyhedronBuilder(polyhedron, typeBounds, initialExpressionsCache)
40 for (extensionOperator : extensionOperators) {
41 extensionOperator.extendPolyhedron(builder)
42 }
43 val extendedPolyhedron = builder.buildPolyhedron()
44 val saturationOperator = solver.createSaturationOperator(extendedPolyhedron)
45 val result = try {
46 saturationOperator.saturate()
47 } finally {
48 saturationOperator.close()
49 }
50 if (result == PolyhedronSaturationResult.EMPTY) {
51 // The partial model cannot be refined any more, we can't provide objective bounds.
52 for (pair : builder.saturationListeners) {
53 pair.value.boundsSaturated(null, null)
54 }
55 return false
56 }
57 for (pair : builder.saturationListeners) {
58 val expression = pair.key
59 pair.value.boundsSaturated(expression.lowerBound, expression.upperBound)
60 }
61 true
62 }
63}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend
index c28d4caa..ad8f94ab 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagator.xtend
@@ -1,7 +1,5 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality 1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2 2
3import com.google.common.cache.Cache
4import com.google.common.cache.CacheBuilder
5import com.google.common.collect.ImmutableList 3import com.google.common.collect.ImmutableList
6import com.google.common.collect.ImmutableMap 4import com.google.common.collect.ImmutableMap
7import com.google.common.collect.ImmutableSet 5import com.google.common.collect.ImmutableSet
@@ -23,7 +21,6 @@ import java.util.HashSet
23import java.util.List 21import java.util.List
24import java.util.Map 22import java.util.Map
25import java.util.Set 23import java.util.Set
26import javax.naming.OperationNotSupportedException
27import org.eclipse.viatra.query.runtime.api.IPatternMatch 24import org.eclipse.viatra.query.runtime.api.IPatternMatch
28import org.eclipse.viatra.query.runtime.api.IQuerySpecification 25import org.eclipse.viatra.query.runtime.api.IQuerySpecification
29import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine 26import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine
@@ -32,31 +29,29 @@ import org.eclipse.viatra.query.runtime.emf.EMFScope
32import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor 29import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
33 30
34class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { 31class PolyhedronScopePropagator extends TypeHierarchyScopePropagator {
35 static val CACHE_SIZE = 10000
36
37 val boolean updateHeuristic 32 val boolean updateHeuristic
38 val Map<Scope, LinearBoundedExpression> scopeBounds 33 val Map<Scope, LinearBoundedExpression> scopeBounds
39 val LinearBoundedExpression topLevelBounds 34 val LinearBoundedExpression topLevelBounds
40 val Polyhedron polyhedron 35 val Polyhedron polyhedron
41 val PolyhedronSaturationOperator operator 36 val PolyhedronScopePropagatorStrategy strategy
42 val Set<Relation> relevantRelations 37 val Set<Relation> relevantRelations
43 val Cache<PolyhedronSignature, PolyhedronSignature> cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build
44 List<RelationConstraintUpdater> updaters = emptyList 38 List<RelationConstraintUpdater> updaters = emptyList
45 39
46 new(PartialInterpretation p, ModelGenerationStatistics statistics, Set<? extends Type> possibleNewDynamicTypes, 40 new(PartialInterpretation p, ModelGenerationStatistics statistics, Set<? extends Type> possibleNewDynamicTypes,
47 Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> unfinishedMultiplicityQueries, 41 Map<RelationMultiplicityConstraint, UnifinishedMultiplicityQueries> unfinishedMultiplicityQueries,
48 IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery, 42 IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> hasElementInContainmentQuery,
49 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatternsByName, 43 Map<String, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatternsByName,
50 Collection<LinearTypeConstraintHint> hints, PolyhedronSolver solver, boolean propagateRelations, 44 Collection<LinearTypeConstraintHint> hints, PolyhedronScopePropagatorStrategy strategy,
51 boolean updateHeuristic) { 45 boolean propagateRelations, boolean updateHeuristic) {
52 super(p, statistics) 46 super(p, statistics)
53 this.updateHeuristic = updateHeuristic 47 this.updateHeuristic = updateHeuristic
48 this.strategy = strategy
54 val builder = new PolyhedronBuilder(p) 49 val builder = new PolyhedronBuilder(p)
55 builder.buildPolyhedron(possibleNewDynamicTypes) 50 builder.buildPolyhedron(possibleNewDynamicTypes)
56 scopeBounds = builder.scopeBounds 51 scopeBounds = builder.scopeBounds
57 topLevelBounds = builder.topLevelBounds 52 topLevelBounds = builder.topLevelBounds
58 polyhedron = builder.polyhedron 53 polyhedron = builder.polyhedron
59 operator = solver.createSaturationOperator(polyhedron) 54 strategy.setPolyhedron(polyhedron, builder.typeBounds, builder.expressionsCache)
60 propagateAllScopeConstraints() 55 propagateAllScopeConstraints()
61 if (propagateRelations) { 56 if (propagateRelations) {
62 val maximumNumberOfNewNodes = topLevelBounds.upperBound 57 val maximumNumberOfNewNodes = topLevelBounds.upperBound
@@ -80,30 +75,10 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator {
80 resetBounds() 75 resetBounds()
81 populatePolyhedronFromScope() 76 populatePolyhedronFromScope()
82// println(polyhedron) 77// println(polyhedron)
83 val signature = polyhedron.createSignature 78 if (strategy.saturate) {
84 val cachedSignature = cache.getIfPresent(signature) 79 populateScopesFromPolyhedron()
85 switch (cachedSignature) { 80 } else {
86 case null: { 81 setScopesInvalid()
87 statistics.incrementScopePropagationSolverCount
88 val result = operator.saturate()
89 if (result == PolyhedronSaturationResult.EMPTY) {
90 cache.put(signature, PolyhedronSignature.EMPTY)
91// println("INVALID")
92 setScopesInvalid()
93 } else {
94 val resultSignature = polyhedron.createSignature
95 cache.put(signature, resultSignature)
96 populateScopesFromPolyhedron()
97 }
98 }
99 case PolyhedronSignature.EMPTY:
100 setScopesInvalid()
101 PolyhedronSignature.Bounds: {
102 polyhedron.applySignature(signature)
103 populateScopesFromPolyhedron()
104 }
105 default:
106 throw new IllegalStateException("Unknown polyhedron signature: " + signature)
107 } 82 }
108// println(polyhedron) 83// println(polyhedron)
109 if (updateHeuristic) { 84 if (updateHeuristic) {
@@ -112,9 +87,9 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator {
112 } 87 }
113 88
114 override isPropagationNeededAfterAdditionToRelation(Relation r) { 89 override isPropagationNeededAfterAdditionToRelation(Relation r) {
115 relevantRelations.contains(r) || super.isPropagationNeededAfterAdditionToRelation(r) 90 relevantRelations.contains(r) || strategy.isRelevantRelation(r) || super.isPropagationNeededAfterAdditionToRelation(r)
116 } 91 }
117 92
118 override isQueryEngineFlushRequiredBeforePropagation() { 93 override isQueryEngineFlushRequiredBeforePropagation() {
119 true 94 true
120 } 95 }
@@ -253,7 +228,10 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator {
253 } 228 }
254 buildRelevantRelations(constraints.keySet) 229 buildRelevantRelations(constraints.keySet)
255 for (hint : hints) { 230 for (hint : hints) {
256 updatersBuilder.add(hint.createConstraintUpdater(this)) 231 val updater = hint.createConstraintUpdater(this)
232 if (updater !== null) {
233 updatersBuilder.add(updater)
234 }
257 } 235 }
258 updaters = updatersBuilder.build 236 updaters = updatersBuilder.build
259 addCachedConstraintsToPolyhedron() 237 addCachedConstraintsToPolyhedron()
@@ -410,7 +388,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator {
410 for (scope : p.scopes) { 388 for (scope : p.scopes) {
411 switch (targetTypeInterpretation : scope.targetTypeInterpretation) { 389 switch (targetTypeInterpretation : scope.targetTypeInterpretation) {
412 PartialPrimitiveInterpretation: 390 PartialPrimitiveInterpretation:
413 throw new OperationNotSupportedException("Primitive type scopes are not yet implemented") 391 throw new IllegalStateException("Primitive type scopes are not yet implemented")
414 PartialComplexTypeInterpretation: { 392 PartialComplexTypeInterpretation: {
415 val complexType = targetTypeInterpretation.interpretationOf 393 val complexType = targetTypeInterpretation.interpretationOf
416 val typeBound = typeBounds.get(complexType) 394 val typeBound = typeBounds.get(complexType)
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend
new file mode 100644
index 00000000..f93dcd18
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend
@@ -0,0 +1,92 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality
2
3import com.google.common.cache.Cache
4import com.google.common.cache.CacheBuilder
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
8import java.util.Map
9import org.eclipse.xtend.lib.annotations.Accessors
10import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor
11
12@FinalFieldsConstructor
13abstract class PolyhedronScopePropagatorStrategy {
14 val ModelGenerationStatistics statistics
15
16 @Accessors(PUBLIC_GETTER) var Polyhedron polyhedron
17
18 def void setPolyhedron(Polyhedron polyhedron, Map<Type, LinearBoundedExpression> typeBounds,
19 Map<Map<Dimension, Integer>, LinearBoundedExpression> initialExpressionsCache) {
20 if (this.polyhedron !== null) {
21 throw new IllegalStateException("polyhedron was already set")
22 }
23 this.polyhedron = polyhedron
24 initialize()
25 }
26
27 def boolean saturate() {
28 if (polyhedron === null) {
29 throw new IllegalStateException("polyhedron was not set")
30 }
31 doSaturate()
32 }
33
34 def boolean isRelevantRelation(Relation relation) {
35 false
36 }
37
38 protected def incrementScopePropagationSolverCount() {
39 statistics.incrementScopePropagationSolverCount()
40 }
41
42 protected def void initialize() {
43 }
44
45 protected def boolean doSaturate()
46}
47
48@FinalFieldsConstructor
49class CachingSimplePolyhedronScopePropagatorStrategy extends PolyhedronScopePropagatorStrategy {
50 static val CACHE_SIZE = 10000
51
52 val PolyhedronSolver solver
53
54 val Cache<PolyhedronSignature, PolyhedronSignature> cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build
55 var PolyhedronSaturationOperator operator
56
57 new(PolyhedronSolver solver, ModelGenerationStatistics statistics) {
58 super(statistics)
59 this.solver = solver
60 }
61
62 override protected initialize() {
63 operator = solver.createSaturationOperator(polyhedron)
64 }
65
66 override protected doSaturate() {
67 val signature = polyhedron.createSignature
68 val cachedSignature = cache.getIfPresent(signature)
69 switch (cachedSignature) {
70 case null: {
71 incrementScopePropagationSolverCount()
72 val result = operator.saturate()
73 if (result == PolyhedronSaturationResult.EMPTY) {
74 cache.put(signature, PolyhedronSignature.EMPTY)
75 false
76 } else {
77 val resultSignature = polyhedron.createSignature
78 cache.put(signature, resultSignature)
79 true
80 }
81 }
82 case PolyhedronSignature.EMPTY:
83 false
84 PolyhedronSignature.Bounds: {
85 polyhedron.applySignature(signature)
86 true
87 }
88 default:
89 throw new IllegalStateException("Unknown polyhedron signature: " + signature)
90 }
91 }
92}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend
index 4e046190..21bd2d9e 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronSolver.xtend
@@ -116,7 +116,7 @@ abstract class PolyhedronSignature {
116} 116}
117 117
118@Accessors 118@Accessors
119abstract class LinearBoundedExpression { 119class Bounds {
120 var Integer lowerBound 120 var Integer lowerBound
121 var Integer upperBound 121 var Integer upperBound
122 122
@@ -132,12 +132,19 @@ abstract class LinearBoundedExpression {
132 } 132 }
133 } 133 }
134 134
135 def void assertBetween(Integer tighterLowerBound, Integer tighterUpperBound) {
136 tightenLowerBound(tighterLowerBound)
137 tightenUpperBound(tighterUpperBound)
138 }
139
135 def void assertEqualsTo(int bound) { 140 def void assertEqualsTo(int bound) {
136 tightenLowerBound(bound) 141 assertBetween(bound, bound)
137 tightenUpperBound(bound)
138 } 142 }
139} 143}
140 144
145abstract class LinearBoundedExpression extends Bounds {
146}
147
141@Accessors 148@Accessors
142class Dimension extends LinearBoundedExpression { 149class Dimension extends LinearBoundedExpression {
143 val String name 150 val String name
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF
index 4ad61ccb..402a0b7d 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/META-INF/MANIFEST.MF
@@ -4,6 +4,7 @@ Bundle-Name: Reasoner
4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 4Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
5Bundle-Version: 1.0.0.qualifier 5Bundle-Version: 1.0.0.qualifier
6Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner, 6Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner,
7 hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse,
7 hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization 8 hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
8Require-Bundle: hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 9Require-Bundle: hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0",
9 hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0", 10 hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0",
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend
index 9ef5e091..691e0645 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodBasedGlobalConstraint.xtend
@@ -1,7 +1,6 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
2 2
3import org.eclipse.viatra.dse.objectives.IGlobalConstraint 3import org.eclipse.viatra.dse.objectives.IGlobalConstraint
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
5 4
6abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint { 5abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint {
7 val protected ModelGenerationMethod method 6 val protected ModelGenerationMethod method
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend
index 3bcd9116..25137eba 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend
@@ -1,226 +1,201 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
2 2
3import com.google.common.collect.ImmutableMap 3import com.google.common.collect.ImmutableMap
4import com.google.common.collect.ImmutableSet 4import com.google.common.collect.ImmutableSet
5import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel 5import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel
6import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem 6import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
7import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery 7import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver 8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint 9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CachingSimplePolyhedronScopePropagatorStrategy
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator 10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver
11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator 11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator 12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator 13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator
14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy 14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator 15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator
16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver 16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator
17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns 17import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries 18import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator
19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider 19import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver
20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator 20import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns
21import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider 21import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries
22import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider 22import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider
23import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 23import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider
24import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace 24import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider
25import java.util.Collection 25import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
26import java.util.List 26import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker
27import java.util.Map 27import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver
28import java.util.Set 28import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjectiveProvider
29import org.eclipse.viatra.query.runtime.api.GenericQueryGroup 29import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
30import org.eclipse.viatra.query.runtime.api.IPatternMatch 30import java.util.Collection
31import org.eclipse.viatra.query.runtime.api.IQuerySpecification 31import java.util.List
32import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine 32import java.util.Map
33import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher 33import java.util.Set
34import org.eclipse.viatra.query.runtime.emf.EMFScope 34import org.eclipse.viatra.dse.objectives.IObjective
35import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint 35import org.eclipse.viatra.query.runtime.api.GenericQueryGroup
36import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery 36import org.eclipse.viatra.query.runtime.api.IPatternMatch
37import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule 37import org.eclipse.viatra.query.runtime.api.IQuerySpecification
38import org.eclipse.xtend.lib.annotations.Data 38import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine
39 39import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
40class ModelGenerationStatistics { 40import org.eclipse.viatra.query.runtime.emf.EMFScope
41 public var long transformationExecutionTime = 0 41import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint
42 42import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
43 synchronized def addExecutionTime(long amount) { 43import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule
44 transformationExecutionTime += amount 44import org.eclipse.xtend.lib.annotations.Data
45 } 45import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedPolyhedronScopePropagatorStrategy
46 46
47 public var long scopePropagationTime = 0 47@Data class ModelGenerationMethod {
48 48 ModelGenerationStatistics statistics
49 synchronized def addScopePropagationTime(long amount) { 49
50 scopePropagationTime += amount 50 Collection<? extends BatchTransformationRule<?, ?>> objectRefinementRules
51 } 51 Collection<? extends BatchTransformationRule<?, ?>> relationRefinementRules
52 52
53 public var long mustRelationPropagationTime = 0 53 List<MultiplicityGoalConstraintCalculator> unfinishedMultiplicities
54 54
55 synchronized def addMustRelationPropagationTime(long amount) { 55 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF
56 mustRelationPropagationTime += amount 56
57 } 57 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWF
58 58
59 public var long preliminaryTypeAnalisisTime = 0 59 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditions
60 60 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditions
61 public var int decisionsTried = 0 61
62 62 Map<String, ModalPatternQueries> modalRelationQueries
63 synchronized def incrementDecisionCount() { 63
64 decisionsTried++ 64 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatterns
65 } 65
66 66 Collection<IObjective> costObjectives
67 public var int transformationInvocations 67 boolean optimizationProblem
68 68 ViatraReasonerSolutionSaver solutionSaver
69 synchronized def incrementTransformationCount() { 69}
70 transformationInvocations++ 70
71 } 71class ModelGenerationMethodProvider {
72 72 val PatternProvider patternProvider = new PatternProvider
73 public var int scopePropagatorInvocations 73 val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider
74 74 val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider
75 synchronized def incrementScopePropagationCount() { 75 val relationConstraintCalculator = new RelationConstraintCalculator
76 scopePropagatorInvocations++ 76
77 } 77 def ModelGenerationMethod createModelGenerationMethod(
78 78 LogicProblem logicProblem,
79 public var int scopePropagatorSolverInvocations 79 PartialInterpretation emptySolution,
80 80 ReasonerWorkspace workspace,
81 synchronized def incrementScopePropagationSolverCount() { 81 ViatraReasonerConfiguration config
82 scopePropagatorSolverInvocations++ 82 ) {
83 } 83 val statistics = new ModelGenerationStatistics
84} 84 val debugLevel = config.documentationLevel
85 85 val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL)
86@Data class ModelGenerationMethod { 86
87 ModelGenerationStatistics statistics 87 val Set<PQuery> existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery).
88 88 map[it.patternPQuery as PQuery].toSet
89 Collection<? extends BatchTransformationRule<?, ?>> objectRefinementRules 89
90 Collection<? extends BatchTransformationRule<?, ?>> relationRefinementRules 90 val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem)
91 91 val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries,
92 List<MultiplicityGoalConstraintCalculator> unfinishedMultiplicities 92 workspace, config.typeInferenceMethod, config.scopePropagatorStrategy, relationConstraints, config.hints,
93 93 config.unitPropagationPatternGenerators, writeFiles)
94 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF 94
95 95 val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries,
96 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidWF 96 config.calculateObjectCreationCosts)
97 97 val unfinishedWF = queries.getUnfinishedWFQueries.values
98 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> mustUnitPropagationPreconditions 98 val modalRelationQueriesBuilder = ImmutableMap.builder
99 Map<PConstraint, IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> currentUnitPropagationPreconditions 99 for (entry : queries.modalRelationQueries.entrySet) {
100 100 val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head
101 Map<String, ModalPatternQueries> modalRelationQueries 101 if (annotation !== null) {
102 102 modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value)
103 Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> allPatterns 103 }
104} 104 }
105 105 val modalRelationQueries = modalRelationQueriesBuilder.build
106enum TypeInferenceMethod { 106 val invalidWF = queries.getInvalidWFQueries.values
107 Generic, 107 val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns
108 PreliminaryAnalysis 108 val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns
109} 109 val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll(
110 110 queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll(
111class ModelGenerationMethodProvider { 111 queries.mustRelationPropagationQueries.values).addAll(queries.multiplicityConstraintQueries.values.flatMap [
112 val PatternProvider patternProvider = new PatternProvider 112 allQueries
113 val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider 113 ]).addAll(queries.unfinishedWFQueries.values).addAll(queries.invalidWFQueries.values).addAll(
114 val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider 114 queries.mustUnitPropagationPreconditionPatterns.values).addAll(
115 val relationConstraintCalculator = new RelationConstraintCalculator 115 queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build
116 116 val queryEngine = ViatraQueryEngine.on(new EMFScope(emptySolution))
117 def ModelGenerationMethod createModelGenerationMethod( 117 GenericQueryGroup.of(queriesToPrepare).prepare(queryEngine)
118 LogicProblem logicProblem, 118
119 PartialInterpretation emptySolution, 119 val objectiveProvider = new ThreeValuedCostObjectiveProvider(queryEngine, emptySolution, modalRelationQueries)
120 ReasonerWorkspace workspace, 120 val transformedObjectives = objectiveProvider.getCostObjectives(config.costObjectives)
121 boolean nameNewElements, 121
122 TypeInferenceMethod typeInferenceMethod, 122 val solutionSaver = new ViatraReasonerSolutionSaver(transformedObjectives.leveledExtremalObjectives,
123 boolean calculateObjectCreationCosts, 123 config.solutionScope.numberOfRequiredSolutions, DiversityChecker.of(config.diversityRequirement))
124 ScopePropagatorStrategy scopePropagatorStrategy, 124
125 Collection<LinearTypeConstraintHint> hints, 125 val allHints = ImmutableSet.builder
126 Collection<UnitPropagationPatternGenerator> unitPropagationPatternGenerators, 126 allHints.addAll(config.hints)
127 DocumentationLevel debugLevel 127 for (hint : transformedObjectives.hints) {
128 ) { 128 hint.boundsProvider = solutionSaver
129 val statistics = new ModelGenerationStatistics 129 allHints.add(hint)
130 val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL) 130 }
131 131
132 val Set<PQuery> existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery). 132 val scopePropagator = createScopePropagator(config.scopePropagatorStrategy, emptySolution, allHints.build,
133 map[it.patternPQuery as PQuery].toSet 133 transformedObjectives.extensionOperators, queries, statistics)
134 134 scopePropagator.propagateAllScopeConstraints
135 val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem) 135 val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, queries,
136 val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries, 136 scopePropagator, statistics)
137 workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, 137 val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution,
138 unitPropagationPatternGenerators, writeFiles) 138 queries, unitRulePropagator, config.nameNewElements, statistics)
139 139 val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator,
140 val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) 140 statistics)
141 scopePropagator.propagateAllScopeConstraints 141
142 val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, 142 return new ModelGenerationMethod(
143 queries, scopePropagator, statistics) 143 statistics,
144 val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, 144 objectRefinementRules.values,
145 queries, unitRulePropagator, nameNewElements, statistics) 145 relationRefinementRules.values,
146 val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator, 146 unfinishedMultiplicities,
147 statistics) 147 unfinishedWF,
148 148 invalidWF,
149 val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries, 149 mustUnitPropagationPreconditions,
150 calculateObjectCreationCosts) 150 currentUnitPropagationPreconditions,
151 151 modalRelationQueries,
152 val unfinishedWF = queries.getUnfinishedWFQueries.values 152 queries.allQueries,
153 153 transformedObjectives.objectives,
154 val modalRelationQueriesBuilder = ImmutableMap.builder 154 transformedObjectives.optimizationProblem,
155 for (entry : queries.modalRelationQueries.entrySet) { 155 solutionSaver
156 val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head 156 )
157 if (annotation !== null) { 157 }
158 modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value) 158
159 } 159 private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy,
160 } 160 PartialInterpretation emptySolution, Collection<LinearTypeConstraintHint> hints,
161 val modalRelationQueries = modalRelationQueriesBuilder.build 161 Collection<PolyhedronExtensionOperator> extensionOperators, GeneratedPatterns queries,
162 162 ModelGenerationStatistics statistics) {
163 val invalidWF = queries.getInvalidWFQueries.values 163 if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) {
164 164 throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.")
165 val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns 165 }
166 val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns 166 switch (scopePropagatorStrategy) {
167 167 case ScopePropagatorStrategy.None,
168 val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll( 168 case ScopePropagatorStrategy.Basic:
169 queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll(queries. 169 new ScopePropagator(emptySolution, statistics)
170 multiplicityConstraintQueries.values.flatMap[allQueries]).addAll(queries.unfinishedWFQueries.values).addAll( 170 case ScopePropagatorStrategy.BasicTypeHierarchy:
171 queries.invalidWFQueries.values).addAll(queries.mustUnitPropagationPreconditionPatterns.values).addAll( 171 new TypeHierarchyScopePropagator(emptySolution, statistics)
172 queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build 172 ScopePropagatorStrategy.Polyhedral: {
173 val queryEngine = ViatraQueryEngine.on(new EMFScope(emptySolution)) 173 val types = queries.refineObjectQueries.keySet.map[newType].toSet
174 GenericQueryGroup.of(queriesToPrepare).prepare(queryEngine) 174 val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName]
175 175 val solver = switch (scopePropagatorStrategy.solver) {
176 return new ModelGenerationMethod( 176 case Z3Integer:
177 statistics, 177 new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds)
178 objectRefinementRules.values, 178 case Z3Real:
179 relationRefinementRules.values, 179 new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds)
180 unfinishedMultiplicities, 180 case Cbc:
181 unfinishedWF, 181 new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true)
182 invalidWF, 182 case Clp:
183 mustUnitPropagationPreconditions, 183 new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true)
184 currentUnitPropagationPreconditions, 184 default:
185 modalRelationQueries, 185 throw new IllegalArgumentException("Unknown polyhedron solver: " +
186 queries.allQueries 186 scopePropagatorStrategy.solver)
187 ) 187 }
188 } 188 val strategy = if (extensionOperators.empty) {
189 189 new CachingSimplePolyhedronScopePropagatorStrategy(solver, statistics)
190 private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy, 190 } else {
191 PartialInterpretation emptySolution, Collection<LinearTypeConstraintHint> hints, GeneratedPatterns queries, 191 new ExtendedPolyhedronScopePropagatorStrategy(solver, extensionOperators, statistics)
192 ModelGenerationStatistics statistics) { 192 }
193 if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) { 193 new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries,
194 throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.") 194 queries.hasElementInContainmentQuery, allPatternsByName, hints, strategy,
195 } 195 scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic)
196 switch (scopePropagatorStrategy) { 196 }
197 case ScopePropagatorStrategy.None, 197 default:
198 case ScopePropagatorStrategy.Basic: 198 throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy)
199 new ScopePropagator(emptySolution, statistics) 199 }
200 case ScopePropagatorStrategy.BasicTypeHierarchy: 200 }
201 new TypeHierarchyScopePropagator(emptySolution, statistics) 201}
202 ScopePropagatorStrategy.Polyhedral: {
203 val types = queries.refineObjectQueries.keySet.map[newType].toSet
204 val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName]
205 val solver = switch (scopePropagatorStrategy.solver) {
206 case Z3Integer:
207 new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds)
208 case Z3Real:
209 new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds)
210 case Cbc:
211 new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true)
212 case Clp:
213 new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true)
214 default:
215 throw new IllegalArgumentException("Unknown polyhedron solver: " +
216 scopePropagatorStrategy.solver)
217 }
218 new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries,
219 queries.hasElementInContainmentQuery, allPatternsByName, hints, solver,
220 scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic)
221 }
222 default:
223 throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy)
224 }
225 }
226}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend
index 8e05665c..8e992741 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasoner.xtend
@@ -1,7 +1,5 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner
2 2
3import com.google.common.collect.ImmutableList
4import com.google.common.collect.Lists
5import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel 3import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel
6import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner 4import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner
7import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException 5import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException
@@ -11,7 +9,6 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
11import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage 9import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage
12import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory 10import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory
13import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult 11import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult
14import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy 12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
16import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser 13import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser
17import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 14import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
@@ -22,7 +19,6 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.sta
22import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.PairwiseNeighbourhoodBasedStateCoderFactory 19import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.PairwiseNeighbourhoodBasedStateCoderFactory
23import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BasicScopeGlobalConstraint 20import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BasicScopeGlobalConstraint
24import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration 21import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration
25import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker
26import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.InconsistentScopeGlobalConstraint 22import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.InconsistentScopeGlobalConstraint
27import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.LoggerSolutionFoundHandler 23import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.LoggerSolutionFoundHandler
28import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective 24import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective
@@ -32,11 +28,8 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PunishSizeObjective
32import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective 28import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective
33import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.SurelyViolatedObjectiveGlobalConstraint 29import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.SurelyViolatedObjectiveGlobalConstraint
34import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective 30import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective
35import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver
36import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter 31import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter
37import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind 32import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind
38import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostElement
39import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjective
40import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace 33import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
41import java.util.List 34import java.util.List
42import java.util.Map 35import java.util.Map
@@ -86,13 +79,7 @@ class ViatraReasoner extends LogicReasoner {
86 problem, 79 problem,
87 emptySolution, 80 emptySolution,
88 workspace, 81 workspace,
89 viatraConfig.nameNewElements, 82 viatraConfig
90 viatraConfig.typeInferenceMethod,
91 viatraConfig.calculateObjectCreationCosts,
92 viatraConfig.scopePropagatorStrategy,
93 viatraConfig.hints,
94 viatraConfig.unitPropagationPatternGenerators,
95 viatraConfig.documentationLevel
96 ) 83 )
97 84
98 val compositeObjective = new ModelGenerationCompositeObjective( 85 val compositeObjective = new ModelGenerationCompositeObjective(
@@ -112,45 +99,21 @@ class ViatraReasoner extends LogicReasoner {
112 dse.addObjective(punishObjective) 99 dse.addObjective(punishObjective)
113 } 100 }
114 101
115 val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) 102 for (costObjective : method.costObjectives) {
116 for (entry : viatraConfig.costObjectives.indexed) {
117 val objectiveName = '''costObjective«entry.key»'''
118 val objectiveConfig = entry.value
119 val elementsBuilder = ImmutableList.builder
120 for (elementConfig : objectiveConfig.elements) {
121 val relationName = elementConfig.patternQualifiedName
122 val modalQueries = method.modalRelationQueries.get(relationName)
123 if (modalQueries === null) {
124 throw new IllegalArgumentException("Unknown relation: " + relationName)
125 }
126 elementsBuilder.add(new ThreeValuedCostElement(
127 modalQueries.currentQuery,
128 modalQueries.mayQuery,
129 modalQueries.mustQuery,
130 elementConfig.weight
131 ))
132 }
133 val costElements = elementsBuilder.build
134 val costObjective = new ThreeValuedCostObjective(objectiveName, costElements, objectiveConfig.kind,
135 objectiveConfig.threshold, 3)
136 dse.addObjective(costObjective) 103 dse.addObjective(costObjective)
137 if (objectiveConfig.findExtremum) {
138 extremalObjectives += costObjective
139 }
140 } 104 }
141
142 val numberOfRequiredSolutions = configuration.solutionScope.numberOfRequiredSolutions 105 val numberOfRequiredSolutions = configuration.solutionScope.numberOfRequiredSolutions
143 val solutionStore = if (extremalObjectives.empty) { 106 val solutionStore = if (method.optimizationProblem) {
144 new SolutionStore(numberOfRequiredSolutions)
145 } else {
146 new SolutionStore() 107 new SolutionStore()
108 } else {
109 new SolutionStore(numberOfRequiredSolutions)
147 } 110 }
148 solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) 111 solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig))
149 val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement)
150 val numericSolver = new NumericSolver(method, viatraConfig.runIntermediateNumericalConsistencyChecks, false) 112 val numericSolver = new NumericSolver(method, viatraConfig.runIntermediateNumericalConsistencyChecks, false)
151 val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions, 113 val solutionSaver = method.solutionSaver
152 diversityChecker, numericSolver) 114 solutionSaver.numericSolver = numericSolver
153 val solutionCopier = solutionSaver.solutionCopier 115 val solutionCopier = solutionSaver.solutionCopier
116 val diversityChecker = solutionSaver.diversityChecker
154 solutionStore.withSolutionSaver(solutionSaver) 117 solutionStore.withSolutionSaver(solutionSaver)
155 dse.solutionStore = solutionStore 118 dse.solutionStore = solutionStore
156 119
@@ -185,7 +148,8 @@ class ViatraReasoner extends LogicReasoner {
185 dse.addTransformationRule(rule) 148 dse.addTransformationRule(rule)
186 } 149 }
187 150
188 val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, numericSolver) 151 val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver,
152 numericSolver)
189 viatraConfig.progressMonitor.workedForwardTransformation 153 viatraConfig.progressMonitor.workedForwardTransformation
190 val transformationFinished = System.nanoTime 154 val transformationFinished = System.nanoTime
191 val transformationTime = transformationFinished - transformationStartTime 155 val transformationTime = transformationFinished - transformationStartTime
@@ -211,14 +175,15 @@ class ViatraReasoner extends LogicReasoner {
211 it.value = (pair.value / 1000000) as int 175 it.value = (pair.value / 1000000) as int
212 ] 176 ]
213 } 177 }
214 for(x: 0..<strategy.times.size) { 178 for (x : 0 ..< strategy.times.size) {
215 it.entries += createStringStatisticEntry => [ 179 it.entries += createStringStatisticEntry => [
216 it.name = '''Solution«x+1»DetailedStatistics''' 180 it.name = '''Solution«x+1»DetailedStatistics'''
217 it.value = strategy.times.get(x) 181 it.value = strategy.times.get(x)
218 ] 182 ]
219 } 183 }
220 it.entries += createIntStatisticEntry => [ 184 it.entries += createIntStatisticEntry => [
221 it.name = "ExplorationInitializationTime" it.value = ((strategy.explorationStarted-transformationFinished)/1000000) as int 185 it.name = "ExplorationInitializationTime"
186 it.value = ((strategy.explorationStarted - transformationFinished) / 1000000) as int
222 ] 187 ]
223 it.entries += createIntStatisticEntry => [ 188 it.entries += createIntStatisticEntry => [
224 it.name = "TransformationExecutionTime" 189 it.name = "TransformationExecutionTime"
@@ -253,22 +218,28 @@ class ViatraReasoner extends LogicReasoner {
253 it.value = dse.numberOfStates as int 218 it.value = dse.numberOfStates as int
254 ] 219 ]
255 it.entries += createIntStatisticEntry => [ 220 it.entries += createIntStatisticEntry => [
256 it.name = "ForwardTime" it.value = (strategy.forwardTime/1000000) as int 221 it.name = "ForwardTime"
222 it.value = (strategy.forwardTime / 1000000) as int
257 ] 223 ]
258 it.entries += createIntStatisticEntry => [ 224 it.entries += createIntStatisticEntry => [
259 it.name = "BacktrackingTime" it.value = (strategy.backtrackingTime/1000000) as int 225 it.name = "BacktrackingTime"
226 it.value = (strategy.backtrackingTime / 1000000) as int
260 ] 227 ]
261 it.entries += createIntStatisticEntry => [ 228 it.entries += createIntStatisticEntry => [
262 it.name = "GlobalConstraintEvaluationTime" it.value = (strategy.globalConstraintEvaluationTime/1000000) as int 229 it.name = "GlobalConstraintEvaluationTime"
230 it.value = (strategy.globalConstraintEvaluationTime / 1000000) as int
263 ] 231 ]
264 it.entries += createIntStatisticEntry => [ 232 it.entries += createIntStatisticEntry => [
265 it.name = "FitnessCalculationTime" it.value = (strategy.fitnessCalculationTime/1000000) as int 233 it.name = "FitnessCalculationTime"
234 it.value = (strategy.fitnessCalculationTime / 1000000) as int
266 ] 235 ]
267 it.entries += createIntStatisticEntry => [ 236 it.entries += createIntStatisticEntry => [
268 it.name = "SolutionCopyTime" it.value = (solutionSaver.totalCopierRuntime/1000000) as int 237 it.name = "SolutionCopyTime"
238 it.value = (solutionSaver.totalCopierRuntime / 1000000) as int
269 ] 239 ]
270 it.entries += createIntStatisticEntry => [ 240 it.entries += createIntStatisticEntry => [
271 it.name = "ActivationSelectionTime" it.value = (strategy.activationSelector.runtime/1000000) as int 241 it.name = "ActivationSelectionTime"
242 it.value = (strategy.activationSelector.runtime / 1000000) as int
272 ] 243 ]
273 it.entries += createIntStatisticEntry => [ 244 it.entries += createIntStatisticEntry => [
274 it.name = "Decisions" 245 it.name = "Decisions"
@@ -287,27 +258,34 @@ class ViatraReasoner extends LogicReasoner {
287 it.value = method.statistics.scopePropagatorSolverInvocations 258 it.value = method.statistics.scopePropagatorSolverInvocations
288 ] 259 ]
289 it.entries += createIntStatisticEntry => [ 260 it.entries += createIntStatisticEntry => [
290 it.name = "NumericalSolverSumTime" it.value = (strategy.numericSolver.runtime/1000000) as int 261 it.name = "NumericalSolverSumTime"
262 it.value = (strategy.numericSolver.runtime / 1000000) as int
291 ] 263 ]
292 it.entries += createIntStatisticEntry => [ 264 it.entries += createIntStatisticEntry => [
293 it.name = "NumericalSolverProblemFormingTime" it.value = (strategy.numericSolver.solverFormingProblem/1000000) as int 265 it.name = "NumericalSolverProblemFormingTime"
266 it.value = (strategy.numericSolver.solverFormingProblem / 1000000) as int
294 ] 267 ]
295 it.entries += createIntStatisticEntry => [ 268 it.entries += createIntStatisticEntry => [
296 it.name = "NumericalSolverSolvingTime" it.value = (strategy.numericSolver.solverSolvingProblem/1000000) as int 269 it.name = "NumericalSolverSolvingTime"
270 it.value = (strategy.numericSolver.solverSolvingProblem / 1000000) as int
297 ] 271 ]
298 it.entries += createIntStatisticEntry => [ 272 it.entries += createIntStatisticEntry => [
299 it.name = "NumericalSolverInterpretingSolution" it.value = (strategy.numericSolver.solverSolution/1000000) as int 273 it.name = "NumericalSolverInterpretingSolution"
274 it.value = (strategy.numericSolver.solverSolution / 1000000) as int
300 ] 275 ]
301 it.entries += createIntStatisticEntry => [ 276 it.entries += createIntStatisticEntry => [
302 it.name = "NumericalSolverCachingTime" it.value = (strategy.numericSolver.cachingTime/1000000) as int 277 it.name = "NumericalSolverCachingTime"
278 it.value = (strategy.numericSolver.cachingTime / 1000000) as int
303 ] 279 ]
304 it.entries += createIntStatisticEntry => [ 280 it.entries += createIntStatisticEntry => [
305 it.name = "NumericalSolverCallNumber" it.value = strategy.numericSolver.numberOfSolverCalls 281 it.name = "NumericalSolverCallNumber"
282 it.value = strategy.numericSolver.numberOfSolverCalls
306 ] 283 ]
307 it.entries += createIntStatisticEntry => [ 284 it.entries += createIntStatisticEntry => [
308 it.name = "NumericalSolverCachedAnswerNumber" it.value = strategy.numericSolver.numberOfCachedSolverCalls 285 it.name = "NumericalSolverCachedAnswerNumber"
286 it.value = strategy.numericSolver.numberOfCachedSolverCalls
309 ] 287 ]
310 if(diversityChecker.active) { 288 if (diversityChecker.active) {
311 it.entries += createIntStatisticEntry => [ 289 it.entries += createIntStatisticEntry => [
312 it.name = "SolutionDiversityCheckTime" 290 it.name = "SolutionDiversityCheckTime"
313 it.value = (diversityChecker.totalRuntime / 1000000) as int 291 it.value = (diversityChecker.totalRuntime / 1000000) as int
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend
index a2ed6016..fbe6da9d 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ViatraReasonerConfiguration.xtend
@@ -4,7 +4,6 @@ import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner
4import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration 4import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration
5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration 5import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration 6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod 7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod
9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint 8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
10import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorConstraints 9import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorConstraints
@@ -12,6 +11,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Polyhedr
12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy 11import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy
13import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator 12import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator
14import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser 13import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser
14import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint
15import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind 15import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind
16import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold 16import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold
17import java.util.LinkedList 17import java.util.LinkedList
@@ -114,9 +114,11 @@ class CostObjectiveConfiguration {
114 public var ObjectiveKind kind 114 public var ObjectiveKind kind
115 public var ObjectiveThreshold threshold 115 public var ObjectiveThreshold threshold
116 public var boolean findExtremum 116 public var boolean findExtremum
117 public var CostObjectiveHint hint
117} 118}
118 119
119class CostObjectiveElementConfiguration { 120class CostObjectiveElementConfiguration {
120 public var String patternQualifiedName 121 public var String patternQualifiedName
121 public var int weight 122 public var int weight
122} 123}
124
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java
index 4800f71d..4b7cead1 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BestFirstStrategyForModelGeneration.java
@@ -28,8 +28,6 @@ import org.eclipse.viatra.dse.objectives.Fitness;
28import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; 28import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
29import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler; 29import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler;
30import org.eclipse.viatra.dse.solutionstore.SolutionStore; 30import org.eclipse.viatra.dse.solutionstore.SolutionStore;
31import org.eclipse.viatra.query.runtime.api.IPatternMatch;
32import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher;
33 31
34import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; 32import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel;
35import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; 33import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner;
@@ -37,12 +35,11 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem;
37import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; 35import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult;
38import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; 36import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult;
39import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; 37import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult;
40import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod;
41import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; 38import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic;
42import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; 39import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation;
43import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder;
44import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; 40import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation;
45import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; 41import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser;
42import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod;
46import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; 43import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration;
47import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; 44import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace;
48 45
@@ -301,7 +298,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy {
301 return activationIds; 298 return activationIds;
302 } 299 }
303 300
304 private void checkForSolution(final Fitness fittness) { 301 private void checkForSolution(final Fitness fitness) {
305 solutionStore.newSolution(context); 302 solutionStore.newSolution(context);
306 } 303 }
307 304
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend
index 066040a0..70e8e9c2 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/NumericSolver.xtend
@@ -1,13 +1,13 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator 3import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement 4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement
6import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement 5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement
7import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 6import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
8import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement 7import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement
9import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement 8import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement
10import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement 9import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement
10import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod
11import java.math.BigDecimal 11import java.math.BigDecimal
12import java.util.HashMap 12import java.util.HashMap
13import java.util.LinkedHashMap 13import java.util.LinkedHashMap
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend
index cfd11816..b48d0831 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PartialModelAsLogicInterpretation.xtend
@@ -22,12 +22,13 @@ import java.util.List
22import java.util.Map 22import java.util.Map
23import java.util.TreeSet 23import java.util.TreeSet
24import org.eclipse.emf.ecore.EObject 24import org.eclipse.emf.ecore.EObject
25import org.eclipse.xtend.lib.annotations.Accessors
25import org.eclipse.xtext.xbase.lib.Functions.Function1 26import org.eclipse.xtext.xbase.lib.Functions.Function1
26 27
27import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* 28import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.*
28 29
29class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ 30class PartialModelAsLogicInterpretation implements LogicModelInterpretation{
30 val PartialInterpretation partialInterpretation 31 @Accessors val PartialInterpretation partialInterpretation
31 val Map<EObject, EObject> trace; 32 val Map<EObject, EObject> trace;
32 val Map<TypeDeclaration,PartialComplexTypeInterpretation> type2Interpretation 33 val Map<TypeDeclaration,PartialComplexTypeInterpretation> type2Interpretation
33 val Map<RelationDeclaration,PartialRelationInterpretation> relation2Interpretation 34 val Map<RelationDeclaration,PartialRelationInterpretation> relation2Interpretation
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend
index 38c8f5a1..33b69436 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend
@@ -26,16 +26,12 @@ class CopiedSolution {
26 * using the supplied {@link NumericSolver}. 26 * using the supplied {@link NumericSolver}.
27 */ 27 */
28class SolutionCopier { 28class SolutionCopier {
29 val NumericSolver numericSolver
30 val copiedSolutions = new LinkedHashMap<Object, CopiedSolution> 29 val copiedSolutions = new LinkedHashMap<Object, CopiedSolution>
31 30
31 @Accessors NumericSolver numericSolver
32 long startTime = System.nanoTime 32 long startTime = System.nanoTime
33 @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0 33 @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0
34 34
35 new(NumericSolver numericSolver) {
36 this.numericSolver = numericSolver
37 }
38
39 def void copySolution(ThreadContext context, Object solutionId) { 35 def void copySolution(ThreadContext context, Object solutionId) {
40 val existingCopy = copiedSolutions.get(solutionId) 36 val existingCopy = copiedSolutions.get(solutionId)
41 if (existingCopy === null) { 37 if (existingCopy === null) {
@@ -47,7 +43,7 @@ class SolutionCopier {
47 totalCopierRuntime += System.nanoTime - copyStart 43 totalCopierRuntime += System.nanoTime - copyStart
48 val copierRuntime = System.nanoTime - startTime 44 val copierRuntime = System.nanoTime - startTime
49 val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime) 45 val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime)
50 numericSolver.fillSolutionCopy(copiedSolution.trace) 46 numericSolver?.fillSolutionCopy(copiedSolution.trace)
51 copiedSolutions.put(solutionId, copiedSolution) 47 copiedSolutions.put(solutionId, copiedSolution)
52 } else { 48 } else {
53 existingCopy.current = true 49 existingCopy.current = true
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend
index c0b5008c..e00f76ff 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend
@@ -1,5 +1,9 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse
2 2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds
4import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.DirectionalThresholdObjective
5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IObjectiveBoundsProvider
6import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold
3import java.util.HashMap 7import java.util.HashMap
4import java.util.Map 8import java.util.Map
5import org.eclipse.viatra.dse.api.DSEException 9import org.eclipse.viatra.dse.api.DSEException
@@ -18,24 +22,32 @@ import org.eclipse.xtend.lib.annotations.Accessors
18 * Will also automatically fill any missing numerical values in the saved solutions 22 * Will also automatically fill any missing numerical values in the saved solutions
19 * using the supplied {@link NumericSolver}. 23 * using the supplied {@link NumericSolver}.
20 */ 24 */
21class ViatraReasonerSolutionSaver implements ISolutionSaver { 25class ViatraReasonerSolutionSaver implements ISolutionSaver, IObjectiveBoundsProvider {
26 static val TOLERANCE = 1e-10
27
22 @Accessors val SolutionCopier solutionCopier 28 @Accessors val SolutionCopier solutionCopier
23 val NumericSolver numericSolver
24 @Accessors val DiversityChecker diversityChecker 29 @Accessors val DiversityChecker diversityChecker
30 val IObjective[][] leveledExtremalObjectives
25 val boolean hasExtremalObjectives 31 val boolean hasExtremalObjectives
26 val int numberOfRequiredSolutions 32 val int numberOfRequiredSolutions
27 val ObjectiveComparatorHelper comparatorHelper 33 val ObjectiveComparatorHelper comparatorHelper
28 val Map<SolutionTrajectory, Fitness> trajectories = new HashMap 34 val Map<SolutionTrajectory, Fitness> trajectories = new HashMap
29 35
30 @Accessors(PUBLIC_SETTER) var Map<Object, Solution> solutionsCollection 36 @Accessors var NumericSolver numericSolver
37 @Accessors var Map<Object, Solution> solutionsCollection
31 38
32 new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker, NumericSolver numericSolver) { 39 new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker) {
33 this.diversityChecker = diversityChecker 40 this.diversityChecker = diversityChecker
34 comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) 41 comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives)
42 this.leveledExtremalObjectives = leveledExtremalObjectives
35 hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] 43 hasExtremalObjectives = leveledExtremalObjectives.exists[!empty]
36 this.numberOfRequiredSolutions = numberOfRequiredSolutions 44 this.numberOfRequiredSolutions = numberOfRequiredSolutions
37 this.solutionCopier = new SolutionCopier(numericSolver) 45 this.solutionCopier = new SolutionCopier
46 }
47
48 def setNumericSolver(NumericSolver numericSolver) {
38 this.numericSolver = numericSolver 49 this.numericSolver = numericSolver
50 solutionCopier.numericSolver = numericSolver
39 } 51 }
40 52
41 override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { 53 override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) {
@@ -51,6 +63,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver {
51 if (!shouldSaveSolution(fitness, context)) { 63 if (!shouldSaveSolution(fitness, context)) {
52 return false 64 return false
53 } 65 }
66 println("Found: " + fitness)
54 val dominatedTrajectories = newArrayList 67 val dominatedTrajectories = newArrayList
55 for (entry : trajectories.entrySet) { 68 for (entry : trajectories.entrySet) {
56 val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value) 69 val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value)
@@ -99,7 +112,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver {
99 } 112 }
100 113
101 private def shouldSaveSolution(Fitness fitness, ThreadContext context) { 114 private def shouldSaveSolution(Fitness fitness, ThreadContext context) {
102 return fitness.satisifiesHardObjectives && numericSolver.currentSatisfiable 115 fitness.satisifiesHardObjectives && (numericSolver === null || numericSolver.currentSatisfiable)
103 } 116 }
104 117
105 private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, 118 private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory,
@@ -145,8 +158,93 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver {
145 } 158 }
146 solutionsCollection.size < numberOfRequiredSolutions 159 solutionsCollection.size < numberOfRequiredSolutions
147 } 160 }
148 161
149 def getTotalCopierRuntime() { 162 def getTotalCopierRuntime() {
150 solutionCopier.totalCopierRuntime 163 solutionCopier.totalCopierRuntime
151 } 164 }
165
166 override computeRequiredBounds(IObjective objective, Bounds bounds) {
167 if (!hasExtremalObjectives) {
168 return
169 }
170 if (objective instanceof DirectionalThresholdObjective) {
171 switch (threshold : objective.threshold) {
172 case ObjectiveThreshold.NO_THRESHOLD: {
173 // No threshold to set.
174 }
175 ObjectiveThreshold.Exclusive: {
176 switch (kind : objective.kind) {
177 case HIGHER_IS_BETTER:
178 bounds.tightenLowerBound(Math.floor(threshold.threshold + 1) as int)
179 case LOWER_IS_BETTER:
180 bounds.tightenUpperBound(Math.ceil(threshold.threshold - 1) as int)
181 default:
182 throw new IllegalArgumentException("Unknown objective kind" + kind)
183 }
184 if (threshold.clampToThreshold) {
185 return
186 }
187 }
188 ObjectiveThreshold.Inclusive: {
189 switch (kind : objective.kind) {
190 case HIGHER_IS_BETTER:
191 bounds.tightenLowerBound(Math.ceil(threshold.threshold) as int)
192 case LOWER_IS_BETTER:
193 bounds.tightenUpperBound(Math.floor(threshold.threshold) as int)
194 default:
195 throw new IllegalArgumentException("Unknown objective kind" + kind)
196 }
197 if (threshold.clampToThreshold) {
198 return
199 }
200 }
201 default:
202 throw new IllegalArgumentException("Unknown threshold: " + threshold)
203 }
204 for (level : leveledExtremalObjectives) {
205 switch (level.size) {
206 case 0: {
207 // Nothing to do, wait for the next level.
208 }
209 case 1: {
210 val primaryObjective = level.get(0)
211 if (primaryObjective != objective) {
212 // There are no worst-case bounds for secondary objectives.
213 return
214 }
215 }
216 default:
217 // There are no worst-case bounds for Pareto front calculation.
218 return
219 }
220 }
221 val fitnessIterator = trajectories.values.iterator
222 if (!fitnessIterator.hasNext) {
223 return
224 }
225 val fitness = fitnessIterator.next.get(objective.name)
226 while (fitnessIterator.hasNext) {
227 val otherFitness = fitnessIterator.next.get(objective.name)
228 if (Math.abs(fitness - otherFitness) > TOLERANCE) {
229 throw new IllegalStateException("Inconsistent fitness: " + objective.name)
230 }
231 }
232 switch (kind : objective.kind) {
233 case HIGHER_IS_BETTER:
234 if (needsMoreSolutionsWithSameFitness) {
235 bounds.tightenLowerBound(Math.floor(fitness) as int)
236 } else {
237 bounds.tightenLowerBound(Math.floor(fitness + 1) as int)
238 }
239 case LOWER_IS_BETTER:
240 if (needsMoreSolutionsWithSameFitness) {
241 bounds.tightenUpperBound(Math.ceil(fitness) as int)
242 } else {
243 bounds.tightenUpperBound(Math.ceil(fitness - 1) as int)
244 }
245 default:
246 throw new IllegalArgumentException("Unknown objective kind" + kind)
247 }
248 }
249 }
152} 250}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend
new file mode 100644
index 00000000..885b14e8
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend
@@ -0,0 +1,137 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import com.google.common.collect.ImmutableList
4import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage
5import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage
6import java.util.List
7import org.eclipse.emf.ecore.EObject
8import org.eclipse.viatra.query.runtime.api.IPatternMatch
9import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
10import org.eclipse.xtend.lib.annotations.Data
11import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem
12import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
13
14@FunctionalInterface
15interface ParameterScopeBound {
16 def double getUpperBound()
17}
18
19@Data
20class CostElementMatch {
21 val IPatternMatch match
22 val boolean must
23
24 def isMulti() {
25 CostElementMatchers.isMultiMatch(match)
26 }
27}
28
29@Data
30class CostElementMatchers {
31 val ViatraQueryMatcher<? extends IPatternMatch> currentMatcher
32 val ViatraQueryMatcher<? extends IPatternMatch> mayMatcher
33 val ViatraQueryMatcher<? extends IPatternMatch> mustMatcher
34 val List<ParameterScopeBound> parameterScopeBounds
35 val int weight
36
37 def getCurrentNumberOfMatches() {
38 currentMatcher.countMatches
39 }
40
41 def getMinimumNumberOfMatches() {
42 mustMatcher.countMatches
43 }
44
45 def getMaximumNumberOfMatches() {
46 var double sum = 0
47 val iterator = mayMatcher.streamAllMatches.iterator
48 while (iterator.hasNext) {
49 val match = iterator.next
50 var double product = 1
51 val numberOfParameters = parameterScopeBounds.size
52 for (var int i = 0; i < numberOfParameters; i++) {
53 if (isMulti(match.get(i + 2))) {
54 val scopeBound = parameterScopeBounds.get(i)
55 product *= scopeBound.upperBound
56 }
57
58 }
59 sum += product
60 }
61 sum
62 }
63
64 def getMatches() {
65 ImmutableList.copyOf(mayMatcher.streamAllMatches.iterator.map [ match |
66 new CostElementMatch(match, mustMatcher.isMatch(match))
67 ])
68 }
69
70 def projectMayMatch(IPatternMatch match, int... indices) {
71 mayMatcher.projectMatch(match, indices)
72 }
73
74 private static def <T extends IPatternMatch> projectMatch(ViatraQueryMatcher<T> matcher, IPatternMatch match, int... indices) {
75 checkMatch(match)
76 val n = matcher.specification.parameters.length - 2
77 if (indices.length != n) {
78 throw new IllegalArgumentException("Invalid number of projection indices")
79 }
80 val newMatch = matcher.newEmptyMatch
81 newMatch.set(0, match.get(0))
82 newMatch.set(1, match.get(1))
83 for (var int i = 0; i < n; i++) {
84 newMatch.set(i + 2, match.get(indices.get(i)))
85 }
86 if (!matcher.hasMatch(newMatch)) {
87 throw new IllegalArgumentException("Projected match does not exist")
88 }
89 return newMatch
90 }
91
92 private static def <T extends IPatternMatch> isMatch(ViatraQueryMatcher<T> matcher, IPatternMatch match) {
93 val n = matcher.specification.parameters.length
94 if (n != match.specification.parameters.length) {
95 throw new IllegalArgumentException("Invalid number of match arguments")
96 }
97 val newMatch = matcher.newEmptyMatch
98 for (var int i = 0; i < n; i++) {
99 newMatch.set(i, match.get(i))
100 }
101 return matcher.hasMatch(newMatch)
102 }
103
104 static def isMulti(Object o) {
105 if (o instanceof EObject) {
106 switch (feature : o.eContainmentFeature) {
107 case LogicproblemPackage.eINSTANCE.logicProblem_Elements,
108 case PartialinterpretationPackage.eINSTANCE.partialInterpretation_NewElements:
109 false
110 case PartialinterpretationPackage.eINSTANCE.partialInterpretation_OpenWorldElements:
111 true
112 default:
113 throw new IllegalStateException("Unknown containment feature for element: " + feature)
114 }
115 } else {
116 false
117 }
118 }
119
120 static def isMultiMatch(IPatternMatch match) {
121 checkMatch(match)
122 val n = match.specification.parameters.length
123 for (var int i = 2; i < n; i++) {
124 if (isMulti(match.get(i))) {
125 return true
126 }
127 }
128 false
129 }
130
131 private static def checkMatch(IPatternMatch match) {
132 val n = match.specification.parameters.length
133 if (n < 2 || !(match.get(0) instanceof LogicProblem) || !(match.get(1) instanceof PartialInterpretation)) {
134 throw new IllegalArgumentException("Match is not from the partial interpretation")
135 }
136 }
137}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend
new file mode 100644
index 00000000..2434073d
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend
@@ -0,0 +1,68 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener
4import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder
5import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory
7import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator
8import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator
9import java.util.Map
10import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery
11import org.eclipse.xtend.lib.annotations.Accessors
12
13abstract class CostObjectiveHint implements LinearTypeConstraintHint, BoundSaturationListener {
14 @Accessors ThreeValuedCostObjective objective
15 @Accessors IObjectiveBoundsProvider boundsProvider
16
17 Integer bestUpper = null
18
19 override getAdditionalPatterns(PatternGenerator patternGenerator, Map<String, PQuery> fqnToPQuery) {
20 ''''''
21 }
22
23 override createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory) {
24 null
25 }
26
27 def isExact() {
28 false
29 }
30
31 def PolyhedronExtensionOperator createPolyhedronExtensionOperator(
32 Map<String, CostElementMatchers> costElementMatchers) {
33 null
34 }
35
36 def setObjective(ThreeValuedCostObjective objective) {
37 if (this.objective !== null) {
38 throw new IllegalStateException("Objective was already set")
39 }
40 this.objective = objective
41 }
42
43 def setBoundsProvider(IObjectiveBoundsProvider boundsProvider) {
44 if (this.boundsProvider !== null) {
45 throw new IllegalStateException("Objective bounds provider was already set")
46 }
47 this.boundsProvider = boundsProvider
48 }
49
50 protected def buildWithBounds(ExtendedLinearExpressionBuilder builder) {
51 val bounds = builder.build(this)
52 if (objective !== null && boundsProvider !== null) {
53 boundsProvider.computeRequiredBounds(objective, bounds)
54 }
55 if (exact && bestUpper !== null) {
56 bounds.tightenLowerBound(bestUpper)
57 }
58 bounds
59 }
60
61 override boundsSaturated(Integer lower, Integer upper) {
62 if (upper !== null && (bestUpper === null || bestUpper < upper)) {
63 bestUpper = upper
64 }
65 objective?.boundsSaturated(lower, upper)
66 }
67
68}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend
new file mode 100644
index 00000000..3c4d36a5
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend
@@ -0,0 +1,8 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds
4import org.eclipse.viatra.dse.objectives.IObjective
5
6interface IObjectiveBoundsProvider {
7 def void computeRequiredBounds(IObjective objective, Bounds bounds)
8}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend
index 0a6fd55b..9b1a7e9f 100644
--- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjective.xtend
@@ -1,85 +1,80 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization 1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2 2
3import com.google.common.collect.ImmutableList 3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener
4import java.util.Collection 4import java.util.Map
5import org.eclipse.viatra.dse.base.ThreadContext 5import org.eclipse.viatra.dse.base.ThreadContext
6import org.eclipse.viatra.query.runtime.api.IPatternMatch 6import org.eclipse.xtend.lib.annotations.Accessors
7import org.eclipse.viatra.query.runtime.api.IQuerySpecification
8import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
9import org.eclipse.xtend.lib.annotations.Data
10 7
11@Data 8class ThreeValuedCostObjective extends AbstractThreeValuedObjective implements BoundSaturationListener {
12class ThreeValuedCostElement { 9 @Accessors val Map<String, CostElementMatchers> matchers
13 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> currentMatchQuery 10 double lowerBoundHint = Double.NEGATIVE_INFINITY
14 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> mayMatchQuery 11 double upperBoundHint = Double.POSITIVE_INFINITY
15 val IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> mustMatchQuery
16 val int weight
17}
18
19class ThreeValuedCostObjective extends AbstractThreeValuedObjective {
20 val Collection<ThreeValuedCostElement> costElements
21 Collection<CostElementMatchers> matchers
22 12
23 new(String name, Collection<ThreeValuedCostElement> costElements, ObjectiveKind kind, ObjectiveThreshold threshold, 13 new(String name, Map<String, CostElementMatchers> matchers, ObjectiveKind kind, ObjectiveThreshold threshold,
24 int level) { 14 int level) {
25 super(name, kind, threshold, level) 15 super(name, kind, threshold, level)
26 this.costElements = costElements 16 this.matchers = matchers
27 } 17 }
28 18
29 override createNew() { 19 override createNew() {
30 new ThreeValuedCostObjective(name, costElements, kind, threshold, level) 20 // new ThreeValuedCostObjective(name, matchers, kind, threshold, level)
21 throw new UnsupportedOperationException("ThreeValuedCostObjective can only be used from a single thread")
31 } 22 }
32 23
33 override init(ThreadContext context) { 24 override init(ThreadContext context) {
34 val queryEngine = context.queryEngine
35 matchers = ImmutableList.copyOf(costElements.map [ element |
36 new CostElementMatchers(
37 queryEngine.getMatcher(element.currentMatchQuery),
38 queryEngine.getMatcher(element.mayMatchQuery),
39 queryEngine.getMatcher(element.mustMatchQuery),
40 element.weight
41 )
42 ])
43 } 25 }
44 26
45 override getRawFitness(ThreadContext context) { 27 override getRawFitness(ThreadContext context) {
46 var int cost = 0 28 var double cost = 0
47 for (matcher : matchers) { 29 for (matcher : matchers.values) {
48 cost += matcher.weight * matcher.currentMatcher.countMatches 30 cost += matcher.weight * matcher.currentNumberOfMatches
49 } 31 }
50 cost as double 32 cost
51 } 33 }
52 34
53 override getLowestPossibleFitness(ThreadContext threadContext) { 35 override getLowestPossibleFitness(ThreadContext threadContext) {
54 var int cost = 0 36 var double cost = 0
55 for (matcher : matchers) { 37 for (matcher : matchers.values) {
56 if (matcher.weight >= 0) { 38 if (matcher.weight >= 0) {
57 cost += matcher.weight * matcher.mustMatcher.countMatches 39 cost += matcher.weight * matcher.minimumNumberOfMatches
58 } else if (matcher.mayMatcher.countMatches > 0) { 40 } else {
59 // TODO Count may matches. 41 cost += matcher.weight * matcher.maximumNumberOfMatches
60 return Double.NEGATIVE_INFINITY
61 } 42 }
62 } 43 }
63 cost as double 44 val boundWithHint = Math.max(lowerBoundHint, cost)
45 if (boundWithHint > upperBoundHint) {
46 throw new IllegalStateException("Inconsistent cost bounds")
47 }
48 boundWithHint
64 } 49 }
65 50
66 override getHighestPossibleFitness(ThreadContext threadContext) { 51 override getHighestPossibleFitness(ThreadContext threadContext) {
67 var int cost = 0 52 var double cost = 0
68 for (matcher : matchers) { 53 for (matcher : matchers.values) {
69 if (matcher.weight <= 0) { 54 if (matcher.weight <= 0) {
70 cost += matcher.weight * matcher.mustMatcher.countMatches 55 cost += matcher.weight * matcher.minimumNumberOfMatches
71 } else if (matcher.mayMatcher.countMatches > 0) { 56 } else {
72 return Double.POSITIVE_INFINITY 57 cost += matcher.weight * matcher.maximumNumberOfMatches
73 } 58 }
74 } 59 }
75 cost as double 60 val boundWithHint = Math.min(upperBoundHint, cost)
61 if (boundWithHint < lowerBoundHint) {
62 throw new IllegalStateException("Inconsistent cost bounds")
63 }
64 boundWithHint
76 } 65 }
77 66
78 @Data 67 override boundsSaturated(Integer lower, Integer upper) {
79 private static class CostElementMatchers { 68 lowerBoundHint = if (lower === null) {
80 val ViatraQueryMatcher<? extends IPatternMatch> currentMatcher 69 Double.NEGATIVE_INFINITY
81 val ViatraQueryMatcher<? extends IPatternMatch> mayMatcher 70 } else {
82 val ViatraQueryMatcher<? extends IPatternMatch> mustMatcher 71 lower
83 val int weight 72 }
73 upperBoundHint = if (upper === null) {
74 Double.POSITIVE_INFINITY
75 } else {
76 upper
77 }
78 println('''Bounds saturated: «lower»..«upper»''')
84 } 79 }
85} 80}
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend
new file mode 100644
index 00000000..c2750acd
--- /dev/null
+++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend
@@ -0,0 +1,205 @@
1package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization
2
3import com.google.common.collect.ImmutableList
4import com.google.common.collect.ImmutableMap
5import com.google.common.collect.Lists
6import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference
7import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference
8import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference
9import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference
10import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation
11import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference
12import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration
13import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeReference
14import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator
16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries
17import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialBooleanInterpretation
18import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation
19import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialIntegerInterpretation
20import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
21import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRealInterpretation
22import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialStringInterpretation
23import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope
24import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration
25import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration
26import java.util.Collection
27import java.util.Map
28import org.eclipse.viatra.dse.objectives.IObjective
29import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine
30import org.eclipse.xtend.lib.annotations.Data
31
32@Data
33class ThreeValuedCostObjectiveProviderResult {
34 val Collection<IObjective> objectives
35 val Collection<CostObjectiveHint> hints
36 val Collection<PolyhedronExtensionOperator> extensionOperators
37 val IObjective[][] leveledExtremalObjectives
38 val boolean optimizationProblem
39}
40
41class ThreeValuedCostObjectiveProvider {
42 static val COST_OBJECTIVE_LEVEL = 3
43
44 val ViatraQueryEngine queryEngine
45 val Map<String, ModalPatternQueries> modalRelationQueries
46 val Map<String, Relation> qualifiedNameToRelationMap
47 val ParameterScopeBound defaultBounds
48 val ParameterScopeBound booleanBounds
49 val ParameterScopeBound integerBounds
50 val ParameterScopeBound realBounds
51 val ParameterScopeBound stringBounds
52 val Map<TypeDeclaration, ParameterScopeBound> typeDeclarationToBoundsMap
53
54 new(ViatraQueryEngine queryEngine, PartialInterpretation interpretation,
55 Map<String, ModalPatternQueries> modalRelationQueries) {
56 this.queryEngine = queryEngine
57 this.modalRelationQueries = modalRelationQueries
58 qualifiedNameToRelationMap = ImmutableMap.copyOf(
59 interpretation.problem.annotations.filter(TransfomedViatraQuery).
60 toMap([patternFullyQualifiedName], [target]))
61 defaultBounds = new PartialInterpretationBasedParameterScopeBound(interpretation)
62 var ParameterScopeBound booleanBounds = null
63 var ParameterScopeBound integerBounds = null
64 var ParameterScopeBound realBounds = null
65 var ParameterScopeBound stringBounds = null
66 val typeDeclarationToBoundsMapBuilder = ImmutableMap.builder
67 for (scope : interpretation.scopes) {
68 val bounds = new ScopeBasedParameterScopeBound(scope)
69 switch (typeInterpretation : scope.targetTypeInterpretation) {
70 PartialBooleanInterpretation:
71 if (booleanBounds === null) {
72 booleanBounds = bounds
73 } else {
74 throw new IllegalStateException("Duplicate partial boolean interpretation")
75 }
76 PartialIntegerInterpretation:
77 if (integerBounds === null) {
78 integerBounds = bounds
79 } else {
80 throw new IllegalStateException("Duplicate partial integer interpretation")
81 }
82 PartialRealInterpretation:
83 if (realBounds === null) {
84 realBounds = bounds
85 } else {
86 throw new IllegalStateException("Duplicate partial real interpretation")
87 }
88 PartialStringInterpretation:
89 if (stringBounds === null) {
90 stringBounds = bounds
91 } else {
92 throw new IllegalStateException("Duplicate partial string interpretation")
93 }
94 PartialComplexTypeInterpretation:
95 typeDeclarationToBoundsMapBuilder.put(typeInterpretation.interpretationOf, bounds)
96 }
97 }
98 this.booleanBounds = booleanBounds ?: defaultBounds
99 this.integerBounds = integerBounds ?: defaultBounds
100 this.realBounds = realBounds ?: defaultBounds
101 this.stringBounds = stringBounds ?: defaultBounds
102 typeDeclarationToBoundsMap = typeDeclarationToBoundsMapBuilder.build
103 }
104
105 def getCostObjectives(Collection<CostObjectiveConfiguration> costObjectives) {
106 val objectives = ImmutableList.<IObjective>builder
107 val hints = ImmutableList.<CostObjectiveHint>builder
108 val extensionOperators = ImmutableList.<PolyhedronExtensionOperator>builder
109 val extremalObjectives = Lists.newArrayListWithExpectedSize(costObjectives.size)
110 for (entry : costObjectives.indexed) {
111 val objectiveName = '''costObjective«entry.key»'''
112 val objectiveConfig = entry.value
113 val costObjective = transformCostObjective(objectiveConfig, objectiveName)
114 objectives.add(costObjective)
115 if (objectiveConfig.findExtremum) {
116 extremalObjectives += costObjective
117 }
118 val hint = objectiveConfig.hint
119 if (hint !== null) {
120 hints.add(hint)
121 hint.objective = costObjective
122 val extensionOperator = hint.createPolyhedronExtensionOperator(costObjective.matchers)
123 if (extensionOperator !== null) {
124 extensionOperators.add(extensionOperator)
125 }
126 }
127 }
128 new ThreeValuedCostObjectiveProviderResult(
129 objectives.build,
130 hints.build,
131 extensionOperators.build,
132 newArrayList(extremalObjectives),
133 !extremalObjectives.empty
134 )
135 }
136
137 private def transformCostObjective(CostObjectiveConfiguration configuration, String name) {
138 val costElements = ImmutableMap.copyOf(configuration.elements.toMap([patternQualifiedName], [
139 transformCostElement
140 ]))
141 new ThreeValuedCostObjective(name, costElements, configuration.kind, configuration.threshold,
142 COST_OBJECTIVE_LEVEL)
143 }
144
145 private def transformCostElement(CostObjectiveElementConfiguration elementConfig) {
146 val relationName = elementConfig.patternQualifiedName
147 val modalQueries = modalRelationQueries.get(relationName)
148 if (modalQueries === null) {
149 throw new IllegalArgumentException("Unknown relation queries: " + relationName)
150 }
151 val relation = qualifiedNameToRelationMap.get(relationName)
152 if (relation === null) {
153 throw new IllegalArgumentException("Unknown transformed relation: " + relationName)
154 }
155 val parameterBounds = ImmutableList.copyOf(relation.parameters.map[parameterBound])
156 new CostElementMatchers(
157 queryEngine.getMatcher(modalQueries.currentQuery),
158 queryEngine.getMatcher(modalQueries.mayQuery),
159 queryEngine.getMatcher(modalQueries.mustQuery),
160 parameterBounds,
161 elementConfig.weight
162 )
163 }
164
165 private def getParameterBound(TypeReference typeReference) {
166 switch (typeReference) {
167 BoolTypeReference: booleanBounds
168 IntTypeReference: integerBounds
169 RealTypeReference: realBounds
170 StringTypeReference: stringBounds
171 ComplexTypeReference: typeDeclarationToBoundsMap.getOrDefault(typeReference.referred, defaultBounds)
172 }
173 }
174
175 private static abstract class AbstractParameterScopeBound implements ParameterScopeBound {
176 override getUpperBound() {
177 val rawValue = rawUpperBound
178 if (rawValue < 0) {
179 Double.POSITIVE_INFINITY
180 } else {
181 rawValue
182 }
183 }
184
185 protected def int getRawUpperBound()
186 }
187
188 @Data
189 private static class ScopeBasedParameterScopeBound extends AbstractParameterScopeBound {
190 val Scope scope
191
192 override protected getRawUpperBound() {
193 scope.maxNewElements
194 }
195 }
196
197 @Data
198 private static class PartialInterpretationBasedParameterScopeBound extends AbstractParameterScopeBound {
199 val PartialInterpretation interpretation
200
201 override protected getRawUpperBound() {
202 interpretation.maxNewElements
203 }
204 }
205}
diff --git a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore
new file mode 100644
index 00000000..7050a7e3
--- /dev/null
+++ b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore
@@ -0,0 +1 @@
/queries/
diff --git a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore
index 3b9ccef7..19bc3cc8 100644
--- a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore
+++ b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/queries/.gitignore
@@ -7,3 +7,7 @@
7/.MemberHasParent.java._trace 7/.MemberHasParent.java._trace
8/.TwoMembersHaveNoParent.java._trace 8/.TwoMembersHaveNoParent.java._trace
9/.NegativeAge.java._trace 9/.NegativeAge.java._trace
10/MemberHasParent.java
11/NegativeAge.java
12/ParentTooYoung.java
13/TwoMembersHaveNoParent.java
diff --git a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore
index 3b9ccef7..19bc3cc8 100644
--- a/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore
+++ b/Tests/MODELS2020-CaseStudies/case.study.familyTree.run/src-gen/queries/.gitignore
@@ -7,3 +7,7 @@
7/.MemberHasParent.java._trace 7/.MemberHasParent.java._trace
8/.TwoMembersHaveNoParent.java._trace 8/.TwoMembersHaveNoParent.java._trace
9/.NegativeAge.java._trace 9/.NegativeAge.java._trace
10/MemberHasParent.java
11/NegativeAge.java
12/ParentTooYoung.java
13/TwoMembersHaveNoParent.java
diff --git a/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin b/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin
index 5c5071cc..23513b51 100644
--- a/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin
+++ b/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin
Binary files differ
diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend
index f4f36951..9cc6e415 100644
--- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend
+++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/FileSystemInconsistencyDetector.xtend
@@ -1,10 +1,10 @@
1package hu.bme.mit.inf.dslreasoner.run 1package hu.bme.mit.inf.dslreasoner.run
2 2
3import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 3import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
4import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod
5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint 5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint
6import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
7import org.eclipse.viatra.dse.base.ThreadContext 6import org.eclipse.viatra.dse.base.ThreadContext
7import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher
8 8
9class FileSystemInconsistencyDetector extends ModelGenerationMethodBasedGlobalConstraint { 9class FileSystemInconsistencyDetector extends ModelGenerationMethodBasedGlobalConstraint {
10 var PartialInterpretation partialInterpretation 10 var PartialInterpretation partialInterpretation
diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend
index bf9ca274..cbc692b3 100644
--- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend
+++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/MetamodelLoader.xtend
@@ -12,8 +12,8 @@ import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace
12import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor 12import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor
13import hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.Patterns 13import hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.Patterns
14import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor 14import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor
15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
16import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint 15import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint
16import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod
17import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint 17import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint
18import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace 18import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace
19import java.util.Collection 19import java.util.Collection
diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend
index 22addd3d..b8167566 100644
--- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend
+++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphInconsistencyDetector.xtend
@@ -1,7 +1,7 @@
1package hu.bme.mit.inf.dslreasoner.run 1package hu.bme.mit.inf.dslreasoner.run
2 2
3import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod
4import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation 3import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation
4import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod
5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint 5import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint
6import org.eclipse.viatra.dse.base.ThreadContext 6import org.eclipse.viatra.dse.base.ThreadContext
7import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher 7import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher