From 3f9b1c92cc35fa4ed9672a2b8601f4c22af24921 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Sun, 7 Apr 2019 13:46:36 +0200 Subject: Infrastructure for objective functions --- .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 99 ++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend') 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 new file mode 100644 index 00000000..5877778e --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend @@ -0,0 +1,99 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse + +import java.util.HashMap +import java.util.Map +import org.eclipse.viatra.dse.api.DSEException +import org.eclipse.viatra.dse.api.Solution +import org.eclipse.viatra.dse.api.SolutionTrajectory +import org.eclipse.viatra.dse.base.ThreadContext +import org.eclipse.viatra.dse.objectives.Fitness +import org.eclipse.viatra.dse.objectives.IObjective +import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper +import org.eclipse.viatra.dse.solutionstore.SolutionStore.ISolutionSaver +import org.eclipse.xtend.lib.annotations.Accessors + +/** + * Based on {@link org.eclipse.viatra.dse.solutionstore.SolutionStore.BestSolutionSaver}. + */ +class ViatraReasonerSolutionSaver implements ISolutionSaver { + @Accessors val solutionCopier = new SolutionCopier + val boolean hasExtremalObjectives + val ObjectiveComparatorHelper comparatorHelper + val Map trajectories = new HashMap + + @Accessors(PUBLIC_SETTER) var Map solutionsCollection + + new(IObjective[][] leveledExtremalObjectives) { + comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) + hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] + } + + override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { + if (hasExtremalObjectives) { + saveBestSolutionOnly(context, id, solutionTrajectory) + } else { + basicSaveSolution(context, id, solutionTrajectory) + } + } + + private def saveBestSolutionOnly(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { + val fitness = context.lastFitness + val dominatedTrajectories = newArrayList + for (entry : trajectories.entrySet) { + val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value) + if (isLastFitnessBetter < 0) { + // Found a trajectory that dominates the current one, no need to save + return false + } + if (isLastFitnessBetter > 0) { + dominatedTrajectories += entry.key + } + } + // We must save the new trajectory before removing dominated trajectories + // to avoid removing the current solution when it is reachable only via dominated trajectories. + val solutionSaved = basicSaveSolution(context, id, solutionTrajectory) + for (dominatedTrajectory : dominatedTrajectories) { + trajectories -= dominatedTrajectory + val dominatedSolution = dominatedTrajectory.solution + if (!dominatedSolution.trajectories.remove(dominatedTrajectory)) { + throw new DSEException( + "Dominated solution is not reachable from dominated trajectory. This should never happen!") + } + if (dominatedSolution.trajectories.empty) { + val dominatedSolutionId = dominatedSolution.stateCode + solutionCopier.markAsObsolete(dominatedSolutionId) + solutionsCollection -= dominatedSolutionId + } + } + solutionSaved + } + + private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { + val fitness = context.lastFitness + var boolean solutionSaved = false + var dseSolution = solutionsCollection.get(id) + if (dseSolution === null) { + solutionCopier.copySolution(context, id) + dseSolution = new Solution(id, solutionTrajectory) + solutionsCollection.put(id, dseSolution) + solutionSaved = true + } else { + solutionSaved = dseSolution.trajectories.add(solutionTrajectory) + } + if (solutionSaved) { + solutionTrajectory.solution = dseSolution + trajectories.put(solutionTrajectory, fitness) + } + solutionSaved + } + + def isFitnessDominated(Fitness fitness) { + for (existingFitness : trajectories.values) { + val isNewFitnessBetter = comparatorHelper.compare(fitness, existingFitness) + if (isNewFitnessBetter < 0) { + return true + } + } + false + } +} -- cgit v1.2.3-54-g00ecf From d239ff5d82587220c7e157d18936351256bccffe Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Mon, 8 Apr 2019 23:19:31 +0200 Subject: Fix solution store for optimization --- .../application/execution/SolverLoader.xtend | 1 + .../viatrasolver/reasoner/ViatraReasoner.xtend | 13 +++++++--- .../SurelyViolatedObjectiveGlobalConstraint.xtend | 2 +- .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 30 ++++++++++++++++++---- .../optimization/ThreeValuedCostObjective.xtend | 1 - .../configs/generation.vsconfig | 4 +-- .../inputs/FamPatterns.vql | 4 +-- 7 files changed, 40 insertions(+), 15 deletions(-) (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend') diff --git a/Application/hu.bme.mit.inf.dslreasoner.application/src/hu/bme/mit/inf/dslreasoner/application/execution/SolverLoader.xtend b/Application/hu.bme.mit.inf.dslreasoner.application/src/hu/bme/mit/inf/dslreasoner/application/execution/SolverLoader.xtend index f769d46f..1139080b 100644 --- a/Application/hu.bme.mit.inf.dslreasoner.application/src/hu/bme/mit/inf/dslreasoner/application/execution/SolverLoader.xtend +++ b/Application/hu.bme.mit.inf.dslreasoner.application/src/hu/bme/mit/inf/dslreasoner/application/execution/SolverLoader.xtend @@ -150,6 +150,7 @@ class SolverLoader { } else { packageName + "." + pattern.name } + element.weight = costEntry.weight costObjectiveConfig.elements += element } } else { 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 6898550d..c022beac 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 @@ -88,7 +88,7 @@ class ViatraReasoner extends LogicReasoner { wf2ObjectiveConverter.createCompletenessObjective(method.unfinishedWF) )) - val extermalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) + val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) for (entry : viatraConfig.costObjectives.indexed) { val objectiveName = '''costObjective«entry.key»''' val objectiveConfig = entry.value @@ -111,13 +111,18 @@ class ViatraReasoner extends LogicReasoner { objectiveConfig.threshold, 3) dse.addObjective(costObjective) if (objectiveConfig.findExtremum) { - extermalObjectives += costObjective + extremalObjectives += costObjective } } - val solutionStore = new SolutionStore(configuration.solutionScope.numberOfRequiredSolutions) + val numberOfRequiredSolutions = configuration.solutionScope.numberOfRequiredSolutions + val solutionStore = if (extremalObjectives.empty) { + new SolutionStore(numberOfRequiredSolutions) + } else { + new SolutionStore() + } solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) - val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extermalObjectives)) + val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions) val solutionCopier = solutionSaver.solutionCopier solutionStore.withSolutionSaver(solutionSaver) dse.solutionStore = solutionStore diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend index 7fd494a0..f54a31ca 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend @@ -24,6 +24,6 @@ class SurelyViolatedObjectiveGlobalConstraint implements IGlobalConstraint { override checkGlobalConstraint(ThreadContext context) { val bestFitness = DseUtils.caclulateBestPossibleFitness(context) - bestFitness.satisifiesHardObjectives && !solutionSaver.isFitnessDominated(bestFitness) + bestFitness.satisifiesHardObjectives && solutionSaver.fitnessMayBeSaved(bestFitness) } } 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 5877778e..17df6c55 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 @@ -18,14 +18,16 @@ import org.eclipse.xtend.lib.annotations.Accessors class ViatraReasonerSolutionSaver implements ISolutionSaver { @Accessors val solutionCopier = new SolutionCopier val boolean hasExtremalObjectives + val int numberOfRequiredSolutions val ObjectiveComparatorHelper comparatorHelper val Map trajectories = new HashMap @Accessors(PUBLIC_SETTER) var Map solutionsCollection - new(IObjective[][] leveledExtremalObjectives) { + new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions) { comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] + this.numberOfRequiredSolutions = numberOfRequiredSolutions } override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { @@ -49,6 +51,9 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { dominatedTrajectories += entry.key } } + if (dominatedTrajectories.size == 0 && !needsMoreSolutionsWithSameFitness) { + return false + } // We must save the new trajectory before removing dominated trajectories // to avoid removing the current solution when it is reachable only via dominated trajectories. val solutionSaved = basicSaveSolution(context, id, solutionTrajectory) @@ -86,14 +91,29 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { } solutionSaved } - - def isFitnessDominated(Fitness fitness) { + + def fitnessMayBeSaved(Fitness fitness) { + if (!hasExtremalObjectives) { + return true + } + var boolean mayDominate for (existingFitness : trajectories.values) { val isNewFitnessBetter = comparatorHelper.compare(fitness, existingFitness) if (isNewFitnessBetter < 0) { - return true + return false } + if (isNewFitnessBetter > 0) { + mayDominate = true + } + } + mayDominate || needsMoreSolutionsWithSameFitness + } + + private def boolean needsMoreSolutionsWithSameFitness() { + if (solutionsCollection === null) { + // The solutions collection will only be initialized upon saving the first solution. + return true } - false + solutionsCollection.size < numberOfRequiredSolutions } } 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 362ef4a3..e2585c83 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 @@ -69,7 +69,6 @@ class ThreeValuedCostObjective extends AbstractThreeValuedObjective { if (matcher.weight <= 0) { cost += matcher.weight * matcher.mustMatcher.countMatches } else if (matcher.mayMatcher.countMatches > 0) { - // TODO Count may matches. return Double.POSITIVE_INFINITY } } diff --git a/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/configs/generation.vsconfig b/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/configs/generation.vsconfig index c29d234a..72def8c5 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/configs/generation.vsconfig +++ b/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/configs/generation.vsconfig @@ -7,11 +7,11 @@ generate { partial-model = { "inputs/FamInstance.xmi"} solver = ViatraSolver scope = { - #node = 5 + #node = 10 } objectives = { minimize cost { - hu.bme.mit.inf.dslreasoner.domains.fam::informationLink = 1 + hu.bme.mit.inf.dslreasoner.domains.fam::functionalOutput = 1 } } diff --git a/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/inputs/FamPatterns.vql b/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/inputs/FamPatterns.vql index 31b9286e..96bb5f3a 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/inputs/FamPatterns.vql +++ b/Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/inputs/FamPatterns.vql @@ -11,6 +11,6 @@ pattern terminatorAndInformation(T : FAMTerminator, I : InformationLink) = { FunctionalInput.terminator(In,T); } -pattern informationLink(I : InformationLink) { - InformationLink(I); +pattern functionalOutput(O : FunctionalOutput) { + FunctionalOutput(O); } -- cgit v1.2.3-54-g00ecf From ec11efe9e0c3863be32e740b28e124499ad653f9 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Tue, 9 Apr 2019 23:11:20 +0200 Subject: Make diversity checking work with optimization Proof of concept implementation, mixing diversity checking and optimization may not be very effective in practice --- .../viatrasolver/reasoner/ViatraReasoner.xtend | 11 +- .../dse/BestFirstStrategyForModelGeneration.java | 19 +-- .../reasoner/dse/DiversityChecker.xtend | 184 +++++++++++++++++++++ .../dse/SolutionStoreWithDiversityDescriptor.xtend | 120 -------------- .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 28 +++- 5 files changed, 216 insertions(+), 146 deletions(-) create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend delete mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend') 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 c022beac..edcca676 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 @@ -19,6 +19,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.IdentifierBasedStateCoderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedStateCoderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.LoggerSolutionFoundHandler import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation @@ -122,7 +123,9 @@ class ViatraReasoner extends LogicReasoner { new SolutionStore() } solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) - val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions) + val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement) + val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions, + diversityChecker) val solutionCopier = solutionSaver.solutionCopier solutionStore.withSolutionSaver(solutionSaver) dse.solutionStore = solutionStore @@ -197,14 +200,14 @@ class ViatraReasoner extends LogicReasoner { it.name = "SolutionCopyTime" it.value = (solutionCopier.getTotalCopierRuntime / 1000000) as int ] - if (strategy.solutionStoreWithDiversityDescriptor.isActive) { + if (diversityChecker.isActive) { it.entries += createIntStatisticEntry => [ it.name = "SolutionDiversityCheckTime" - it.value = (strategy.solutionStoreWithDiversityDescriptor.sumRuntime / 1000000) as int + it.value = (diversityChecker.totalRuntime / 1000000) as int ] it.entries += createRealStatisticEntry => [ it.name = "SolutionDiversitySuccessRate" - it.value = strategy.solutionStoreWithDiversityDescriptor.successRate + it.value = diversityChecker.successRate ] } ] 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 1234d54b..6ff867d7 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 @@ -75,7 +75,6 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { // Running private PriorityQueue trajectoiresToExplore; private SolutionStore solutionStore; - private SolutionStoreWithDiversityDescriptor solutionStoreWithDiversityDescriptor; private volatile boolean isInterrupted = false; private ModelResult modelResultByInternalSolver = null; private Random random = new Random(); @@ -96,9 +95,6 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { this.method = method; } - public SolutionStoreWithDiversityDescriptor getSolutionStoreWithDiversityDescriptor() { - return solutionStoreWithDiversityDescriptor; - } public int getNumberOfStatecoderFail() { return numberOfStatecoderFail; } @@ -117,8 +113,6 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { matchers.add(matcher); } - this.solutionStoreWithDiversityDescriptor = new SolutionStoreWithDiversityDescriptor(configuration.diversityRequirement); - final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); this.comparator = new Comparator() { @Override @@ -142,7 +136,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { } final Fitness firstfitness = context.calculateFitness(); - checkForSolution(firstfitness); + solutionStore.newSolution(context); final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]); @@ -215,7 +209,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { context.backtrack(); } else { final Fitness nextFitness = context.calculateFitness(); - checkForSolution(nextFitness); + solutionStore.newSolution(context); if (context.getDepth() > configuration.searchSpaceConstraints.maxDepth) { logger.debug("Reached max depth."); context.backtrack(); @@ -264,15 +258,6 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { return activationIds; } - private void checkForSolution(final Fitness fitness) { - if (fitness.isSatisifiesHardObjectives()) { - if (solutionStoreWithDiversityDescriptor.isDifferent(context)) { - solutionStoreWithDiversityDescriptor.newSolution(context); - solutionStore.newSolution(context); - } - } - } - @Override public void interruptStrategy() { isInterrupted = true; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend new file mode 100644 index 00000000..fb1b2066 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DiversityChecker.xtend @@ -0,0 +1,184 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse + +import com.google.common.collect.HashMultiset +import com.google.common.collect.ImmutableSet +import com.google.common.collect.Multiset +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.AbstractNodeDescriptor +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.NeighbourhoodWithTraces +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.PartialInterpretation2ImmutableTypeLattice +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor +import java.util.Collection +import java.util.HashSet +import java.util.Map +import java.util.Set +import org.eclipse.viatra.dse.base.ThreadContext +import org.eclipse.xtend.lib.annotations.Accessors + +interface DiversityChecker { + public static val NO_DIVERSITY_CHECKER = new DiversityChecker { + override isActive() { + false + } + + override getTotalRuntime() { + 0 + } + + override getSuccessRate() { + 1.0 + } + + override newSolution(ThreadContext threadContext, Object solutionId, Collection dominatedSolutionIds) { + true + } + } + + def boolean isActive() + + def long getTotalRuntime() + + def double getSuccessRate() + + def boolean newSolution(ThreadContext threadContext, Object solutionId, Collection dominatedSolutionIds) + + static def of(DiversityDescriptor descriptor) { + if (descriptor.ensureDiversity) { + new NodewiseDiversityChecker(descriptor) + } else { + NO_DIVERSITY_CHECKER + } + } +} + +abstract class AbstractDiversityChecker implements DiversityChecker { + val DiversityDescriptor descriptor + val PartialInterpretation2ImmutableTypeLattice solutionCoder = new PartialInterpretation2ImmutableTypeLattice + + @Accessors(PUBLIC_GETTER) var long totalRuntime = 0 + var int allCheckCount = 0 + var int successfulCheckCount = 0 + + protected new(DiversityDescriptor descriptor) { + if (!descriptor.ensureDiversity) { + throw new IllegalArgumentException( + "Diversity description should enforce diversity or NO_DIVERSITY_CHECKER should be used instead.") + } + this.descriptor = descriptor + } + + override isActive() { + true + } + + override getTotalRuntime() { + throw new UnsupportedOperationException("TODO: auto-generated method stub") + } + + override getSuccessRate() { + (allCheckCount as double) / (successfulCheckCount as double) + } + + override newSolution(ThreadContext threadContext, Object solutionId, Collection dominatedSolutionIds) { + val start = System.nanoTime + val model = threadContext.model as PartialInterpretation + val representation = solutionCoder.createRepresentation(model, descriptor.range, descriptor.parallels, + descriptor.maxNumber, descriptor.relevantTypes, descriptor.relevantRelations) + val isDifferent = internalNewSolution(representation, solutionId, dominatedSolutionIds) + totalRuntime += System.nanoTime - start + allCheckCount++ + if (isDifferent) { + successfulCheckCount++ + } + isDifferent + } + + protected abstract def boolean internalNewSolution( + NeighbourhoodWithTraces, AbstractNodeDescriptor> representation, + Object solutionId, Collection dominatedSolutionIds) +} + +class NodewiseDiversityChecker extends AbstractDiversityChecker { + var Multiset nodeCodes = HashMultiset.create + val Map> tracedNodeCodes = newHashMap + + new(DiversityDescriptor descriptor) { + super(descriptor) + } + + override protected internalNewSolution( + NeighbourhoodWithTraces, AbstractNodeDescriptor> representation, + Object solutionId, Collection dominatedSolutionIds) { + val nodeCodesInSolution = ImmutableSet.copyOf(representation.modelRepresentation.keySet.map[hashCode]) + val remainingNodeCodes = if (dominatedSolutionIds.empty) { + nodeCodes + } else { + getRemainingNodeCodes(dominatedSolutionIds) + } + val hasNewCode = nodeCodesInSolution.exists[!remainingNodeCodes.contains(it)] + if (hasNewCode) { + nodeCodes = remainingNodeCodes + nodeCodes.addAll(nodeCodesInSolution) + for (dominatedSolutionId : dominatedSolutionIds) { + tracedNodeCodes.remove(dominatedSolutionId) + } + tracedNodeCodes.put(solutionId, nodeCodesInSolution) + } + hasNewCode + } + + private def getRemainingNodeCodes(Collection dominatedSolutionIds) { + // TODO Optimize multiset operations. + val copyOfNodeCodes = HashMultiset.create(nodeCodes) + for (dominatedSolutionId : dominatedSolutionIds) { + val dominatedModelCode = tracedNodeCodes.get(dominatedSolutionId) + if (dominatedModelCode === null) { + throw new IllegalArgumentException("Unknown dominated solution: " + dominatedSolutionId) + } + copyOfNodeCodes.removeAll(dominatedModelCode) + } + copyOfNodeCodes + } +} + +class GraphwiseDiversityChecker extends AbstractDiversityChecker { + var Set modelCodes = newHashSet + val Map tracedModelCodes = newHashMap + + new(DiversityDescriptor descriptor) { + super(descriptor) + } + + override protected internalNewSolution( + NeighbourhoodWithTraces, AbstractNodeDescriptor> representation, + Object solutionId, Collection dominatedSolutionIds) { + val modelCodeOfSolution = representation.modelRepresentation.hashCode + val remainingModelCodes = if (dominatedSolutionIds.empty) { + modelCodes + } else { + getRemainingModelCodes(dominatedSolutionIds) + } + val isNewCode = !remainingModelCodes.contains(modelCodeOfSolution) + if (isNewCode) { + modelCodes = remainingModelCodes + modelCodes += modelCodeOfSolution + for (dominatedSolutionId : dominatedSolutionIds) { + tracedModelCodes.remove(dominatedSolutionId) + } + tracedModelCodes.put(solutionId, modelCodeOfSolution) + } + isNewCode + } + + private def getRemainingModelCodes(Collection dominatedSolutionIds) { + val copyOfModelCodes = new HashSet(modelCodes) + for (dominatedSolutionId : dominatedSolutionIds) { + val dominatedModelCode = tracedModelCodes.get(dominatedSolutionId) + if (dominatedModelCode === null) { + throw new IllegalArgumentException("Unknown dominated solution: " + dominatedSolutionId) + } + copyOfModelCodes -= dominatedModelCode + } + copyOfModelCodes + } +} diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend deleted file mode 100644 index 1e7f18a8..00000000 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithDiversityDescriptor.xtend +++ /dev/null @@ -1,120 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse - -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.PartialInterpretation2ImmutableTypeLattice -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor -import java.util.LinkedList -import java.util.List -import org.eclipse.viatra.dse.base.ThreadContext -import java.util.HashSet -import java.util.Set - -enum DiversityGranularity { - Nodewise, Graphwise -} - -class SolutionStoreWithDiversityDescriptor { - val DiversityDescriptor descriptor - DiversityGranularity granularity - val PartialInterpretation2ImmutableTypeLattice solutionCoder = new PartialInterpretation2ImmutableTypeLattice - val Set solutionCodeList = new HashSet - - var long runtime - var int allCheck - var int successfulCheck - - new(DiversityDescriptor descriptor) { - if(descriptor.ensureDiversity) { - this.descriptor = descriptor - this.granularity = DiversityGranularity::Nodewise - } else { - this.descriptor = null - this.granularity = DiversityGranularity::Nodewise - } - } - - def public isActive() { - descriptor!==null - } - - def getSumRuntime() { - return runtime - } - def getSuccessRate() { - return successfulCheck as double / allCheck - } - - def isDifferent(ThreadContext context) { - if(active) { - val start = System.nanoTime - val model = context.model as PartialInterpretation - var boolean isDifferent - if(this.granularity == DiversityGranularity::Graphwise) { - val code = solutionCoder.createRepresentation(model, - descriptor.range, - descriptor.parallels, - descriptor.maxNumber, - descriptor.relevantTypes, - descriptor.relevantRelations).modelRepresentation.hashCode - - isDifferent = !solutionCodeList.contains(code) - } else if(this.granularity == DiversityGranularity::Nodewise){ - val codes = solutionCoder.createRepresentation(model, - descriptor.range, - descriptor.parallels, - descriptor.maxNumber, - descriptor.relevantTypes, - descriptor.relevantRelations).modelRepresentation.keySet.map[hashCode].toList - val differentCodes = codes.filter[!solutionCodeList.contains(it)] - //println(differentCodes.size) - - isDifferent = differentCodes.size>=1 - } else { - throw new UnsupportedOperationException('''Unsupported diversity type: «this.granularity»''') - } - - runtime += System.nanoTime - start - allCheck++ - if(isDifferent) { successfulCheck++ } - return isDifferent - } else { - allCheck++ - successfulCheck++ - return true - } - } - - def canBeDifferent(ThreadContext context) { - return true - } - - def newSolution(ThreadContext context) { - if(active) { - val start = System.nanoTime - val model = context.model as PartialInterpretation - if(this.granularity == DiversityGranularity::Graphwise) { - val code = solutionCoder.createRepresentation(model, - descriptor.range, - descriptor.parallels, - descriptor.maxNumber, - descriptor.relevantTypes, - descriptor.relevantRelations).modelRepresentation.hashCode - - solutionCodeList += code.hashCode - } else if(this.granularity == DiversityGranularity::Nodewise){ - val codes = solutionCoder.createRepresentation(model, - descriptor.range, - descriptor.parallels, - descriptor.maxNumber, - descriptor.relevantTypes, - descriptor.relevantRelations).modelRepresentation.keySet.map[hashCode].toList - - solutionCodeList += codes.map[it.hashCode] - } else { - throw new UnsupportedOperationException('''Unsupported diversity type: «this.granularity»''') - } - - runtime += System.nanoTime - start - } - } -} \ No newline at end of file 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 17df6c55..6bffeb59 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 @@ -13,10 +13,11 @@ import org.eclipse.viatra.dse.solutionstore.SolutionStore.ISolutionSaver import org.eclipse.xtend.lib.annotations.Accessors /** - * Based on {@link org.eclipse.viatra.dse.solutionstore.SolutionStore.BestSolutionSaver}. + * Based on {@link SolutionStore.BestSolutionSaver}. */ class ViatraReasonerSolutionSaver implements ISolutionSaver { @Accessors val solutionCopier = new SolutionCopier + @Accessors val DiversityChecker diversityChecker val boolean hasExtremalObjectives val int numberOfRequiredSolutions val ObjectiveComparatorHelper comparatorHelper @@ -24,7 +25,8 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { @Accessors(PUBLIC_SETTER) var Map solutionsCollection - new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions) { + new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker) { + this.diversityChecker = diversityChecker comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] this.numberOfRequiredSolutions = numberOfRequiredSolutions @@ -34,12 +36,15 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { if (hasExtremalObjectives) { saveBestSolutionOnly(context, id, solutionTrajectory) } else { - basicSaveSolution(context, id, solutionTrajectory) + saveAnyDiverseSolution(context, id, solutionTrajectory) } } private def saveBestSolutionOnly(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { val fitness = context.lastFitness + if (!fitness.satisifiesHardObjectives) { + return false + } val dominatedTrajectories = newArrayList for (entry : trajectories.entrySet) { val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value) @@ -54,9 +59,12 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { if (dominatedTrajectories.size == 0 && !needsMoreSolutionsWithSameFitness) { return false } + if (!diversityChecker.newSolution(context, id, dominatedTrajectories.map[solution.stateCode])) { + return false + } // We must save the new trajectory before removing dominated trajectories // to avoid removing the current solution when it is reachable only via dominated trajectories. - val solutionSaved = basicSaveSolution(context, id, solutionTrajectory) + val solutionSaved = basicSaveSolution(context, id, solutionTrajectory, fitness) for (dominatedTrajectory : dominatedTrajectories) { trajectories -= dominatedTrajectory val dominatedSolution = dominatedTrajectory.solution @@ -73,8 +81,18 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { solutionSaved } - private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { + private def saveAnyDiverseSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { val fitness = context.lastFitness + if (!fitness.satisifiesHardObjectives) { + return false + } + if (!diversityChecker.newSolution(context, id, emptyList)) { + return false + } + basicSaveSolution(context, id, solutionTrajectory, fitness) + } + + private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, Fitness fitness) { var boolean solutionSaved = false var dseSolution = solutionsCollection.get(id) if (dseSolution === null) { -- cgit v1.2.3-54-g00ecf From fc84d3fe670331bc89fb1e4c44104bc1fc811438 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Wed, 14 Aug 2019 18:26:33 +0200 Subject: Measurements WIP --- .../.ApplicationConfigurationIdeModule.xtendbin | Bin 1701 -> 1701 bytes .../ide/.ApplicationConfigurationIdeSetup.xtendbin | Bin 2570 -> 2570 bytes .../domains/transima/fam/FamPatterns.vql | 2 +- .../domains/cps/dse/RuleBasedCpsSolver.xtend | 6 +- .../.classpath | 7 +- .../.project | 1 + .../.settings/org.eclipse.core.resources.prefs | 3 - .../META-INF/MANIFEST.MF | 16 +- .../configs/generation.vsconfig | 2 +- .../ecore-gen/satellite/CommSubsystem.java | 20 +- .../ecore-gen/satellite/ConstellationMission.java | 2 +- .../ecore-gen/satellite/InterferometryMission.java | 28 -- .../ecore-gen/satellite/SatellitePackage.java | 88 +----- .../satellite/impl/CommSubsystemImpl.java | 115 +------ .../satellite/impl/InterferometryMissionImpl.java | 130 -------- .../satellite/impl/SatellitePackageImpl.java | 37 +-- .../inputs/SatelliteInstance.xmi | 9 +- .../model/satellite.ecore | 12 +- .../model/satellite.genmodel | 5 +- .../model/satellite.henshin | 61 ---- .../model/satellite.henshin_diagram | 131 -------- .../model/satellite_fixup.henshin | 61 ---- .../plugin.xml | 1 + .../representations.aird | 2 + .../domains/satellite/mdeo/CostObjective.xtend | 13 - .../satellite/mdeo/LocalSearchEngineManager.xtend | 31 -- .../mdeo/MetricBasedGuidanceFunction.xtend | 47 --- .../satellite/mdeo/PatternMatchConstraint.xtend | 29 -- .../satellite/mdeo/SatelliteMdeOptimiserMain.xtend | 51 --- .../domains/satellite/mdeo/satellite.mopt | 36 --- .../domains/satellite/queries/SatelliteQueries.vql | 11 +- .../META-INF/MANIFEST.MF | 3 +- .../plugin.xml | 74 +---- .../yakindu/mutated/mutated.vql | 270 ---------------- .../partialsnapshot_mavo/yakindu/patterns.vql | 64 ++-- .../ModelGenerationMethodProvider.xtend | 35 +- .../cardinality/LinearTypeConstraintHint.xtend | 30 ++ .../cardinality/PolyhedronScopePropagator.xtend | 106 +++++-- .../cardinality/PolyhedronSolver.xtend | 72 ++++- .../cardinality/RelationConstraintCalculator.xtend | 5 +- .../logic2viatra/cardinality/ScopePropagator.xtend | 25 +- .../cardinality/ScopePropagatorStrategy.xtend | 11 +- .../cardinality/TypeHierarchyScopePropagator.xtend | 20 +- .../cardinality/Z3PolyhedronSolver.xtend | 32 +- .../logic2viatra/patterns/PatternGenerator.xtend | 18 +- .../logic2viatra/patterns/PatternProvider.xtend | 6 +- .../patterns/RelationRefinementGenerator.xtend | 2 +- .../logic2viatra/patterns/UnfinishedIndexer.xtend | 26 +- .../rules/RefinementRuleProvider.xtend | 15 +- .../PartialInterpretation.java | 24 ++ .../PartialinterpretationPackage.java | 60 +++- .../partialinterpretation/Scope.java | 24 ++ .../impl/BinaryElementRelationLinkImpl.java | 4 + .../impl/BooleanElementImpl.java | 4 +- .../impl/IntegerElementImpl.java | 4 +- .../impl/NaryRelationLinkElementImpl.java | 6 +- .../impl/NaryRelationLinkImpl.java | 1 + .../impl/PartialComplexTypeInterpretationImpl.java | 3 + .../impl/PartialConstantInterpretationImpl.java | 2 + .../impl/PartialFunctionInterpretationImpl.java | 2 + .../impl/PartialInterpretationImpl.java | 73 ++++- .../impl/PartialRelationInterpretationImpl.java | 7 + .../impl/PartialTypeInterpratationImpl.java | 2 + .../impl/PartialinterpretationFactoryImpl.java | 19 ++ .../impl/PartialinterpretationPackageImpl.java | 88 +++++- .../impl/PrimitiveElementImpl.java | 4 +- .../impl/RealElementImpl.java | 4 +- .../partialinterpretation/impl/ScopeImpl.java | 64 +++- .../impl/StringElementImpl.java | 4 +- .../impl/UnaryElementRelationLinkImpl.java | 2 + .../model/PartialInterpretation.ecore | 6 + .../model/PartialInterpretation.genmodel | 14 +- .../neighbourhood/Descriptor.xtend | 8 + .../neighbourhood/NeighbourhoodOptions.xtend | 4 +- .../neighbourhood/PartialInterpretation2Hash.xtend | 2 +- ...nterpretation2NeighbourhoodRepresentation.xtend | 4 +- .../NeighbourhoodBasedStateCoderFactory.xtend | 29 +- .../viatrasolver/reasoner/ViatraReasoner.xtend | 25 +- .../reasoner/ViatraReasonerConfiguration.xtend | 3 + .../reasoner/dse/BasicScopeGlobalConstraint.xtend | 103 ++++++ .../dse/BestFirstStrategyForModelGeneration.java | 2 +- .../dse/ModelGenerationCompositeObjective.xtend | 2 +- .../viatrasolver/reasoner/dse/ScopeObjective.xtend | 4 +- .../reasoner/dse/UnfinishedWFObjective.xtend | 34 +- .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 11 +- .../META-INF/MANIFEST.MF | 8 +- ..._ViatraSolver_polyhedral_typeHierarchy_Clp.json | 13 + ..._ViatraSolver_polyhedral_typeHierarchy_Clp.json | 16 + ..._ViatraSolver_polyhedral_typeHierarchy_Clp.json | 15 + ..._ViatraSolver_polyhedral_typeHierarchy_Clp.json | 15 + ..._ViatraSolver_polyhedral_typeHierarchy_Clp.json | 17 + .../initialModels/satellite.xmi | 14 + .../bme/mit/inf/dslreasoner/run/CountMatches.xtend | 176 ----------- .../run/Ecore2LogicTraceBasedHint.xtend | 56 ++++ .../mit/inf/dslreasoner/run/MetamodelLoader.xtend | 302 +++++++++++++----- .../bme/mit/inf/dslreasoner/run/SGraphHint.xtend | 46 +++ .../mit/inf/dslreasoner/run/SatelliteHint.xtend | 86 +++++ .../run/TypeDistributionCalculator.xtend | 35 ++ .../dslreasoner/run/script/MeasurementScript.xtend | 70 ++++ .../run/script/MeasurementScriptRunner.xtend | 351 +++++++++++++++++++++ 100 files changed, 1976 insertions(+), 1667 deletions(-) delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.settings/org.eclipse.core.resources.prefs delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin_diagram delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite_fixup.henshin create mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/representations.aird delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/CostObjective.xtend delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/LocalSearchEngineManager.xtend delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/MetricBasedGuidanceFunction.xtend delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/PatternMatchConstraint.xtend delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/SatelliteMdeOptimiserMain.xtend delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/satellite.mopt delete mode 100644 Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/mutated/mutated.vql create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/configs/FAM_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/configs/Yakindu_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/configs/ecore_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/configs/fs_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/configs/satellite_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/initialModels/satellite.xmi delete mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/CountMatches.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/Ecore2LogicTraceBasedHint.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/TypeDistributionCalculator.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScript.xtend create mode 100644 Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScriptRunner.xtend (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend') 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 069bd953..22db4093 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin 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 624846d6..3ad5d167 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin differ diff --git a/Domains/Examples/ModelGenExampleFAM_plugin/src/hu/bme/mit/inf/dslreasoner/domains/transima/fam/FamPatterns.vql b/Domains/Examples/ModelGenExampleFAM_plugin/src/hu/bme/mit/inf/dslreasoner/domains/transima/fam/FamPatterns.vql index f0e48d42..1d9a6b6d 100644 --- a/Domains/Examples/ModelGenExampleFAM_plugin/src/hu/bme/mit/inf/dslreasoner/domains/transima/fam/FamPatterns.vql +++ b/Domains/Examples/ModelGenExampleFAM_plugin/src/hu/bme/mit/inf/dslreasoner/domains/transima/fam/FamPatterns.vql @@ -10,7 +10,7 @@ pattern terminatorAndInformation(T : FAMTerminator, I : InformationLink) = { InformationLink.to(I,In); FunctionalInput.terminator(In,T); } - +/* @QueryBasedFeature pattern type(This : Function, Target : FunctionType) = { find rootElements(_Model, This); diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.cps/src/hu/bme/mit/inf/dslreasoner/domains/cps/dse/RuleBasedCpsSolver.xtend b/Domains/hu.bme.mit.inf.dslreasoner.domains.cps/src/hu/bme/mit/inf/dslreasoner/domains/cps/dse/RuleBasedCpsSolver.xtend index e4c758f0..503c06ea 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.cps/src/hu/bme/mit/inf/dslreasoner/domains/cps/dse/RuleBasedCpsSolver.xtend +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.cps/src/hu/bme/mit/inf/dslreasoner/domains/cps/dse/RuleBasedCpsSolver.xtend @@ -35,18 +35,18 @@ class RuleBasedCpsSolver { val dse = new DesignSpaceExplorer dse.addMetaModelPackage(CpsPackage.eINSTANCE) dse.initialModel = problem.eResource.resourceSet - dse.addTransformationRule(createRule(RequirementNotSatisfied.instance).action [ + dse.addTransformationRule(createRule.precondition(RequirementNotSatisfied.instance).action [ val app = createApplicationInstance req.type.instances += app req.instances += app ].build) - dse.addTransformationRule(createRule(Allocate.instance).action [ + dse.addTransformationRule(createRule.precondition(Allocate.instance).action [ app.allocatedTo = host ].build) // dse.addTransformationRule(createRule(UnallocateAppInstance.instance).action [ // app.allocatedTo = null // ].build) - dse.addTransformationRule(createRule(CreateHostInstance.instance).action [ + dse.addTransformationRule(createRule.precondition(CreateHostInstance.instance).action [ hostType.instances += createHostInstance ].build) // dse.addTransformationRule(createRule(RemoveHostInstance.instance).action [ diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.classpath b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.classpath index e5e58475..6781ea8f 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.classpath +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.classpath @@ -3,9 +3,12 @@ - + + + + + - diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.project b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.project index 16db5fc5..e594a173 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.project +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.project @@ -32,6 +32,7 @@ + org.eclipse.sirius.nature.modelingproject org.eclipse.jdt.core.javanature org.eclipse.pde.PluginNature org.eclipse.viatra.query.projectnature diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.settings/org.eclipse.core.resources.prefs b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 4a3e59e4..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -encoding//model/satellite.henshin=UTF-8 -encoding//model/satellite.henshin_diagram=UTF-8 diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/META-INF/MANIFEST.MF b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/META-INF/MANIFEST.MF index 36d729b4..966fc660 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/META-INF/MANIFEST.MF +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/META-INF/MANIFEST.MF @@ -7,6 +7,7 @@ Bundle-ClassPath: . Bundle-Vendor: %providerName Bundle-Localization: plugin Export-Package: hu.bme.mit.inf.dslreasoner.domains.satellite.queries, + hu.bme.mit.inf.dslreasoner.domains.satellite.queries.internal, satellite, satellite.impl, satellite.util @@ -22,20 +23,7 @@ Require-Bundle: org.eclipse.viatra.addon.querybasedfeatures.runtime, org.eclipse.viatra.dse.genetic, hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner;bundle-version="1.0.0", org.eclipse.emf.ecore.xmi;bundle-version="2.15.0", - uk.ac.kcl.inf.mdeoptimiser.libraries.core;bundle-version="1.0.0", - uk.ac.kcl.inf.mdeoptimiser.interfaces.cli;bundle-version="1.0.0", - org.eclipse.emf.henshin.interpreter;bundle-version="1.5.0", - uk.ac.kcl.inf.mdeoptimiser.libraries.rulegen;bundle-version="1.0.0", - org.sidiff.common;bundle-version="1.0.0", - org.sidiff.common.emf;bundle-version="1.0.0", - org.sidiff.common.emf.extensions;bundle-version="1.0.0", - org.moeaframework;bundle-version="2.13.0", - org.apache.commons.math3;bundle-version="3.6.1", - org.apache.commons.lang3;bundle-version="3.8.1", - com.google.inject;bundle-version="3.0.0", - org.sidiff.common.henshin;bundle-version="1.0.0", - org.sidiff.serge;bundle-version="1.0.0", - org.eclipse.viatra.query.runtime.rete;bundle-version="2.2.0" + org.eclipse.viatra.query.runtime.rete;bundle-version="2.0.0" Import-Package: org.apache.log4j Automatic-Module-Name: hu.bme.mit.inf.dslreasoner.domains.satellite Bundle-ActivationPolicy: lazy diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/configs/generation.vsconfig b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/configs/generation.vsconfig index 66c468d0..2fb246c9 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/configs/generation.vsconfig +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/configs/generation.vsconfig @@ -2,7 +2,7 @@ import epackage "model/satellite.ecore" import viatra "src/hu/bme/mit/inf/dslreasoner/domains/satellite/queries/SatelliteQueries.vql" generate { - metamodel = { package satellite excluding { InterferometryMission.observationTime } } + metamodel = { package satellite } constraints = { package hu.bme.mit.inf.dslreasoner.domains.satellite.queries } partial-model = { "inputs/SatelliteInstance.xmi"} solver = ViatraSolver diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/CommSubsystem.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/CommSubsystem.java index 90bca78c..3b9d7ecf 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/CommSubsystem.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/CommSubsystem.java @@ -2,7 +2,6 @@ */ package satellite; -import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** @@ -15,7 +14,6 @@ import org.eclipse.emf.ecore.EObject; *

*
    *
  • {@link satellite.CommSubsystem#getTarget Target}
  • - *
  • {@link satellite.CommSubsystem#getSource Source}
  • *
* * @see satellite.SatellitePackage#getCommSubsystem() @@ -26,14 +24,12 @@ public interface CommSubsystem extends EObject { /** * Returns the value of the 'Target' reference. - * It is bidirectional and its opposite is '{@link satellite.CommSubsystem#getSource Source}'. * * * @return the value of the 'Target' reference. * @see #setTarget(CommSubsystem) * @see satellite.SatellitePackage#getCommSubsystem_Target() - * @see satellite.CommSubsystem#getSource - * @model opposite="source" + * @model * @generated */ CommSubsystem getTarget(); @@ -48,18 +44,4 @@ public interface CommSubsystem extends EObject { */ void setTarget(CommSubsystem value); - /** - * Returns the value of the 'Source' reference list. - * The list contents are of type {@link satellite.CommSubsystem}. - * It is bidirectional and its opposite is '{@link satellite.CommSubsystem#getTarget Target}'. - * - * - * @return the value of the 'Source' reference list. - * @see satellite.SatellitePackage#getCommSubsystem_Source() - * @see satellite.CommSubsystem#getTarget - * @model opposite="target" - * @generated - */ - EList getSource(); - } // CommSubsystem diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/ConstellationMission.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/ConstellationMission.java index 6182d7ad..8ff69955 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/ConstellationMission.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/ConstellationMission.java @@ -53,7 +53,7 @@ public interface ConstellationMission extends EObject { * * @return the value of the 'Spacecraft' containment reference list. * @see satellite.SatellitePackage#getConstellationMission_Spacecraft() - * @model containment="true" lower="2" upper="50" + * @model containment="true" lower="2" * @generated */ EList getSpacecraft(); diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/InterferometryMission.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/InterferometryMission.java index eb4ea064..4e28df38 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/InterferometryMission.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/InterferometryMission.java @@ -7,39 +7,11 @@ package satellite; * A representation of the model object 'Interferometry Mission'. * * - *

- * The following features are supported: - *

- *
    - *
  • {@link satellite.InterferometryMission#getObservationTime Observation Time}
  • - *
* * @see satellite.SatellitePackage#getInterferometryMission() * @model * @generated */ public interface InterferometryMission extends ConstellationMission { - /** - * Returns the value of the 'Observation Time' attribute. - * The default value is "2.0". - * - * - * @return the value of the 'Observation Time' attribute. - * @see #setObservationTime(float) - * @see satellite.SatellitePackage#getInterferometryMission_ObservationTime() - * @model default="2.0" required="true" - * @generated - */ - float getObservationTime(); - - /** - * Sets the value of the '{@link satellite.InterferometryMission#getObservationTime Observation Time}' attribute. - * - * - * @param value the new value of the 'Observation Time' attribute. - * @see #getObservationTime() - * @generated - */ - void setObservationTime(float value); } // InterferometryMission diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/SatellitePackage.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/SatellitePackage.java index 7be4ef84..9ca99311 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/SatellitePackage.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/SatellitePackage.java @@ -2,7 +2,6 @@ */ package satellite; -import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; @@ -130,15 +129,6 @@ public interface SatellitePackage extends EPackage { */ int INTERFEROMETRY_MISSION__SPACECRAFT = CONSTELLATION_MISSION__SPACECRAFT; - /** - * The feature id for the 'Observation Time' attribute. - * - * - * @generated - * @ordered - */ - int INTERFEROMETRY_MISSION__OBSERVATION_TIME = CONSTELLATION_MISSION_FEATURE_COUNT + 0; - /** * The number of structural features of the 'Interferometry Mission' class. * @@ -146,7 +136,7 @@ public interface SatellitePackage extends EPackage { * @generated * @ordered */ - int INTERFEROMETRY_MISSION_FEATURE_COUNT = CONSTELLATION_MISSION_FEATURE_COUNT + 1; + int INTERFEROMETRY_MISSION_FEATURE_COUNT = CONSTELLATION_MISSION_FEATURE_COUNT + 0; /** * The number of operations of the 'Interferometry Mission' class. @@ -296,15 +286,6 @@ public interface SatellitePackage extends EPackage { */ int COMM_SUBSYSTEM__TARGET = 0; - /** - * The feature id for the 'Source' reference list. - * - * - * @generated - * @ordered - */ - int COMM_SUBSYSTEM__SOURCE = 1; - /** * The number of structural features of the 'Comm Subsystem' class. * @@ -312,7 +293,7 @@ public interface SatellitePackage extends EPackage { * @generated * @ordered */ - int COMM_SUBSYSTEM_FEATURE_COUNT = 2; + int COMM_SUBSYSTEM_FEATURE_COUNT = 1; /** * The number of operations of the 'Comm Subsystem' class. @@ -582,15 +563,6 @@ public interface SatellitePackage extends EPackage { */ int UHF_COMM_SUBSYSTEM__TARGET = COMM_SUBSYSTEM__TARGET; - /** - * The feature id for the 'Source' reference list. - * - * - * @generated - * @ordered - */ - int UHF_COMM_SUBSYSTEM__SOURCE = COMM_SUBSYSTEM__SOURCE; - /** * The number of structural features of the 'UHF Comm Subsystem' class. * @@ -628,15 +600,6 @@ public interface SatellitePackage extends EPackage { */ int XCOMM_SUBSYSTEM__TARGET = COMM_SUBSYSTEM__TARGET; - /** - * The feature id for the 'Source' reference list. - * - * - * @generated - * @ordered - */ - int XCOMM_SUBSYSTEM__SOURCE = COMM_SUBSYSTEM__SOURCE; - /** * The number of structural features of the 'XComm Subsystem' class. * @@ -674,15 +637,6 @@ public interface SatellitePackage extends EPackage { */ int KA_COMM_SUBSYSTEM__TARGET = COMM_SUBSYSTEM__TARGET; - /** - * The feature id for the 'Source' reference list. - * - * - * @generated - * @ordered - */ - int KA_COMM_SUBSYSTEM__SOURCE = COMM_SUBSYSTEM__SOURCE; - /** * The number of structural features of the 'Ka Comm Subsystem' class. * @@ -743,17 +697,6 @@ public interface SatellitePackage extends EPackage { */ EClass getInterferometryMission(); - /** - * Returns the meta object for the attribute '{@link satellite.InterferometryMission#getObservationTime Observation Time}'. - * - * - * @return the meta object for the attribute 'Observation Time'. - * @see satellite.InterferometryMission#getObservationTime() - * @see #getInterferometryMission() - * @generated - */ - EAttribute getInterferometryMission_ObservationTime(); - /** * Returns the meta object for class '{@link satellite.CommunicatingElement Communicating Element}'. * @@ -827,17 +770,6 @@ public interface SatellitePackage extends EPackage { */ EReference getCommSubsystem_Target(); - /** - * Returns the meta object for the reference list '{@link satellite.CommSubsystem#getSource Source}'. - * - * - * @return the meta object for the reference list 'Source'. - * @see satellite.CommSubsystem#getSource() - * @see #getCommSubsystem() - * @generated - */ - EReference getCommSubsystem_Source(); - /** * Returns the meta object for class '{@link satellite.Payload Payload}'. * @@ -988,14 +920,6 @@ public interface SatellitePackage extends EPackage { */ EClass INTERFEROMETRY_MISSION = eINSTANCE.getInterferometryMission(); - /** - * The meta object literal for the 'Observation Time' attribute feature. - * - * - * @generated - */ - EAttribute INTERFEROMETRY_MISSION__OBSERVATION_TIME = eINSTANCE.getInterferometryMission_ObservationTime(); - /** * The meta object literal for the '{@link satellite.impl.CommunicatingElementImpl Communicating Element}' class. * @@ -1060,14 +984,6 @@ public interface SatellitePackage extends EPackage { */ EReference COMM_SUBSYSTEM__TARGET = eINSTANCE.getCommSubsystem_Target(); - /** - * The meta object literal for the 'Source' reference list feature. - * - * - * @generated - */ - EReference COMM_SUBSYSTEM__SOURCE = eINSTANCE.getCommSubsystem_Source(); - /** * The meta object literal for the '{@link satellite.impl.PayloadImpl Payload}' class. * diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/CommSubsystemImpl.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/CommSubsystemImpl.java index 21e385a8..d39abd4d 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/CommSubsystemImpl.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/CommSubsystemImpl.java @@ -2,16 +2,11 @@ */ package satellite.impl; -import java.util.Collection; import org.eclipse.emf.common.notify.Notification; -import org.eclipse.emf.common.notify.NotificationChain; -import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; -import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; -import org.eclipse.emf.ecore.util.InternalEList; import satellite.CommSubsystem; import satellite.SatellitePackage; @@ -24,7 +19,6 @@ import satellite.SatellitePackage; *

*
    *
  • {@link satellite.impl.CommSubsystemImpl#getTarget Target}
  • - *
  • {@link satellite.impl.CommSubsystemImpl#getSource Source}
  • *
* * @generated @@ -40,16 +34,6 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp */ protected CommSubsystem target; - /** - * The cached value of the '{@link #getSource() Source}' reference list. - * - * - * @see #getSource() - * @generated - * @ordered - */ - protected EList source; - /** * * @@ -97,25 +81,6 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp return target; } - /** - * - * - * @generated - */ - public NotificationChain basicSetTarget(CommSubsystem newTarget, NotificationChain msgs) { - CommSubsystem oldTarget = target; - target = newTarget; - if (eNotificationRequired()) { - ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, - SatellitePackage.COMM_SUBSYSTEM__TARGET, oldTarget, newTarget); - if (msgs == null) - msgs = notification; - else - msgs.add(notification); - } - return msgs; - } - /** * * @@ -123,70 +88,11 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp */ @Override public void setTarget(CommSubsystem newTarget) { - if (newTarget != target) { - NotificationChain msgs = null; - if (target != null) - msgs = ((InternalEObject) target).eInverseRemove(this, SatellitePackage.COMM_SUBSYSTEM__SOURCE, - CommSubsystem.class, msgs); - if (newTarget != null) - msgs = ((InternalEObject) newTarget).eInverseAdd(this, SatellitePackage.COMM_SUBSYSTEM__SOURCE, - CommSubsystem.class, msgs); - msgs = basicSetTarget(newTarget, msgs); - if (msgs != null) - msgs.dispatch(); - } else if (eNotificationRequired()) - eNotify(new ENotificationImpl(this, Notification.SET, SatellitePackage.COMM_SUBSYSTEM__TARGET, newTarget, - newTarget)); - } - - /** - * - * - * @generated - */ - @Override - public EList getSource() { - if (source == null) { - source = new EObjectWithInverseResolvingEList(CommSubsystem.class, this, - SatellitePackage.COMM_SUBSYSTEM__SOURCE, SatellitePackage.COMM_SUBSYSTEM__TARGET); - } - return source; - } - - /** - * - * - * @generated - */ - @SuppressWarnings("unchecked") - @Override - public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { - switch (featureID) { - case SatellitePackage.COMM_SUBSYSTEM__TARGET: - if (target != null) - msgs = ((InternalEObject) target).eInverseRemove(this, SatellitePackage.COMM_SUBSYSTEM__SOURCE, - CommSubsystem.class, msgs); - return basicSetTarget((CommSubsystem) otherEnd, msgs); - case SatellitePackage.COMM_SUBSYSTEM__SOURCE: - return ((InternalEList) (InternalEList) getSource()).basicAdd(otherEnd, msgs); - } - return super.eInverseAdd(otherEnd, featureID, msgs); - } - - /** - * - * - * @generated - */ - @Override - public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { - switch (featureID) { - case SatellitePackage.COMM_SUBSYSTEM__TARGET: - return basicSetTarget(null, msgs); - case SatellitePackage.COMM_SUBSYSTEM__SOURCE: - return ((InternalEList) getSource()).basicRemove(otherEnd, msgs); - } - return super.eInverseRemove(otherEnd, featureID, msgs); + CommSubsystem oldTarget = target; + target = newTarget; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, SatellitePackage.COMM_SUBSYSTEM__TARGET, oldTarget, + target)); } /** @@ -201,8 +107,6 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp if (resolve) return getTarget(); return basicGetTarget(); - case SatellitePackage.COMM_SUBSYSTEM__SOURCE: - return getSource(); } return super.eGet(featureID, resolve, coreType); } @@ -219,10 +123,6 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp case SatellitePackage.COMM_SUBSYSTEM__TARGET: setTarget((CommSubsystem) newValue); return; - case SatellitePackage.COMM_SUBSYSTEM__SOURCE: - getSource().clear(); - getSource().addAll((Collection) newValue); - return; } super.eSet(featureID, newValue); } @@ -238,9 +138,6 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp case SatellitePackage.COMM_SUBSYSTEM__TARGET: setTarget((CommSubsystem) null); return; - case SatellitePackage.COMM_SUBSYSTEM__SOURCE: - getSource().clear(); - return; } super.eUnset(featureID); } @@ -255,8 +152,6 @@ public abstract class CommSubsystemImpl extends MinimalEObjectImpl.Container imp switch (featureID) { case SatellitePackage.COMM_SUBSYSTEM__TARGET: return target != null; - case SatellitePackage.COMM_SUBSYSTEM__SOURCE: - return source != null && !source.isEmpty(); } return super.eIsSet(featureID); } diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/InterferometryMissionImpl.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/InterferometryMissionImpl.java index 3401ad51..450f8a9a 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/InterferometryMissionImpl.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/InterferometryMissionImpl.java @@ -2,12 +2,7 @@ */ package satellite.impl; -import org.eclipse.emf.common.notify.Notification; - import org.eclipse.emf.ecore.EClass; - -import org.eclipse.emf.ecore.impl.ENotificationImpl; - import satellite.InterferometryMission; import satellite.SatellitePackage; @@ -15,36 +10,10 @@ import satellite.SatellitePackage; * * An implementation of the model object 'Interferometry Mission'. * - *

- * The following features are implemented: - *

- *
    - *
  • {@link satellite.impl.InterferometryMissionImpl#getObservationTime Observation Time}
  • - *
* * @generated */ public class InterferometryMissionImpl extends ConstellationMissionImpl implements InterferometryMission { - /** - * The default value of the '{@link #getObservationTime() Observation Time}' attribute. - * - * - * @see #getObservationTime() - * @generated - * @ordered - */ - protected static final float OBSERVATION_TIME_EDEFAULT = 2.0F; - - /** - * The cached value of the '{@link #getObservationTime() Observation Time}' attribute. - * - * - * @see #getObservationTime() - * @generated - * @ordered - */ - protected float observationTime = OBSERVATION_TIME_EDEFAULT; - /** * * @@ -64,103 +33,4 @@ public class InterferometryMissionImpl extends ConstellationMissionImpl implemen return SatellitePackage.Literals.INTERFEROMETRY_MISSION; } - /** - * - * - * @generated - */ - @Override - public float getObservationTime() { - return observationTime; - } - - /** - * - * - * @generated - */ - @Override - public void setObservationTime(float newObservationTime) { - float oldObservationTime = observationTime; - observationTime = newObservationTime; - if (eNotificationRequired()) - eNotify(new ENotificationImpl(this, Notification.SET, - SatellitePackage.INTERFEROMETRY_MISSION__OBSERVATION_TIME, oldObservationTime, observationTime)); - } - - /** - * - * - * @generated - */ - @Override - public Object eGet(int featureID, boolean resolve, boolean coreType) { - switch (featureID) { - case SatellitePackage.INTERFEROMETRY_MISSION__OBSERVATION_TIME: - return getObservationTime(); - } - return super.eGet(featureID, resolve, coreType); - } - - /** - * - * - * @generated - */ - @Override - public void eSet(int featureID, Object newValue) { - switch (featureID) { - case SatellitePackage.INTERFEROMETRY_MISSION__OBSERVATION_TIME: - setObservationTime((Float) newValue); - return; - } - super.eSet(featureID, newValue); - } - - /** - * - * - * @generated - */ - @Override - public void eUnset(int featureID) { - switch (featureID) { - case SatellitePackage.INTERFEROMETRY_MISSION__OBSERVATION_TIME: - setObservationTime(OBSERVATION_TIME_EDEFAULT); - return; - } - super.eUnset(featureID); - } - - /** - * - * - * @generated - */ - @Override - public boolean eIsSet(int featureID) { - switch (featureID) { - case SatellitePackage.INTERFEROMETRY_MISSION__OBSERVATION_TIME: - return observationTime != OBSERVATION_TIME_EDEFAULT; - } - return super.eIsSet(featureID); - } - - /** - * - * - * @generated - */ - @Override - public String toString() { - if (eIsProxy()) - return super.toString(); - - StringBuilder result = new StringBuilder(super.toString()); - result.append(" (observationTime: "); - result.append(observationTime); - result.append(')'); - return result.toString(); - } - } //InterferometryMissionImpl diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/SatellitePackageImpl.java b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/SatellitePackageImpl.java index 17212a96..f6dc1e30 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/SatellitePackageImpl.java +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/ecore-gen/satellite/impl/SatellitePackageImpl.java @@ -2,7 +2,6 @@ */ package satellite.impl; -import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; @@ -242,16 +241,6 @@ public class SatellitePackageImpl extends EPackageImpl implements SatellitePacka return interferometryMissionEClass; } - /** - * - * - * @generated - */ - @Override - public EAttribute getInterferometryMission_ObservationTime() { - return (EAttribute) interferometryMissionEClass.getEStructuralFeatures().get(0); - } - /** * * @@ -322,16 +311,6 @@ public class SatellitePackageImpl extends EPackageImpl implements SatellitePacka return (EReference) commSubsystemEClass.getEStructuralFeatures().get(0); } - /** - * - * - * @generated - */ - @Override - public EReference getCommSubsystem_Source() { - return (EReference) commSubsystemEClass.getEStructuralFeatures().get(1); - } - /** * * @@ -457,7 +436,6 @@ public class SatellitePackageImpl extends EPackageImpl implements SatellitePacka createEReference(constellationMissionEClass, CONSTELLATION_MISSION__SPACECRAFT); interferometryMissionEClass = createEClass(INTERFEROMETRY_MISSION); - createEAttribute(interferometryMissionEClass, INTERFEROMETRY_MISSION__OBSERVATION_TIME); communicatingElementEClass = createEClass(COMMUNICATING_ELEMENT); createEReference(communicatingElementEClass, COMMUNICATING_ELEMENT__COMM_SUBSYSTEM); @@ -469,7 +447,6 @@ public class SatellitePackageImpl extends EPackageImpl implements SatellitePacka commSubsystemEClass = createEClass(COMM_SUBSYSTEM); createEReference(commSubsystemEClass, COMM_SUBSYSTEM__TARGET); - createEReference(commSubsystemEClass, COMM_SUBSYSTEM__SOURCE); payloadEClass = createEClass(PAYLOAD); @@ -537,15 +514,12 @@ public class SatellitePackageImpl extends EPackageImpl implements SatellitePacka initEReference(getConstellationMission_GroundStationNetwork(), this.getGroundStationNetwork(), null, "groundStationNetwork", null, 1, 1, ConstellationMission.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); - initEReference(getConstellationMission_Spacecraft(), this.getSpacecraft(), null, "spacecraft", null, 2, 50, + initEReference(getConstellationMission_Spacecraft(), this.getSpacecraft(), null, "spacecraft", null, 2, -1, ConstellationMission.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(interferometryMissionEClass, InterferometryMission.class, "InterferometryMission", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); - initEAttribute(getInterferometryMission_ObservationTime(), ecorePackage.getEFloat(), "observationTime", "2.0", - 1, 1, InterferometryMission.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, - IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(communicatingElementEClass, CommunicatingElement.class, "CommunicatingElement", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); @@ -564,12 +538,9 @@ public class SatellitePackageImpl extends EPackageImpl implements SatellitePacka initEClass(commSubsystemEClass, CommSubsystem.class, "CommSubsystem", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); - initEReference(getCommSubsystem_Target(), this.getCommSubsystem(), this.getCommSubsystem_Source(), "target", - null, 0, 1, CommSubsystem.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, - IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); - initEReference(getCommSubsystem_Source(), this.getCommSubsystem(), this.getCommSubsystem_Target(), "source", - null, 0, -1, CommSubsystem.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, - IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); + initEReference(getCommSubsystem_Target(), this.getCommSubsystem(), null, "target", null, 0, 1, + CommSubsystem.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, + !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(payloadEClass, Payload.class, "Payload", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/inputs/SatelliteInstance.xmi b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/inputs/SatelliteInstance.xmi index 7b8e355a..3d07a199 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/inputs/SatelliteInstance.xmi +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/inputs/SatelliteInstance.xmi @@ -4,11 +4,4 @@ xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:satellite="http://www.example.org/satellite" - xsi:schemaLocation="http://www.example.org/satellite ../model/satellite.ecore"> - - - - - + xsi:schemaLocation="http://www.example.org/satellite ../model/satellite.ecore"/> diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.ecore b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.ecore index 1685c756..9f17d43c 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.ecore +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.ecore @@ -5,12 +5,9 @@ - - - + upperBound="-1" eType="#//Spacecraft" containment="true"/> + @@ -21,10 +18,7 @@ containment="true"/> - - + diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.genmodel b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.genmodel index 09b5f64c..bc98abd6 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.genmodel +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.genmodel @@ -15,9 +15,7 @@ - - - + @@ -27,7 +25,6 @@ - diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin deleted file mode 100644 index 33059424..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin_diagram b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin_diagram deleted file mode 100644 index a5c675d8..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite.henshin_diagram +++ /dev/null @@ -1,131 +0,0 @@ - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite_fixup.henshin b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite_fixup.henshin deleted file mode 100644 index 224ced8f..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/model/satellite_fixup.henshin +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/plugin.xml b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/plugin.xml index a07867dc..b0b77996 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/plugin.xml +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/plugin.xml @@ -8,6 +8,7 @@ + diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/representations.aird b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/representations.aird new file mode 100644 index 00000000..efa8e366 --- /dev/null +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/representations.aird @@ -0,0 +1,2 @@ + + diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/CostObjective.xtend b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/CostObjective.xtend deleted file mode 100644 index 43b2902f..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/CostObjective.xtend +++ /dev/null @@ -1,13 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo - -//import hu.bme.mit.inf.dslreasoner.domains.satellite.queries.CostMetric -// -//class CostObjective extends MetricBasedGuidanceFunction { -// new() { -// super(CostMetric.instance) -// } -// -// override getName() { -// "Cost" -// } -//} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/LocalSearchEngineManager.xtend b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/LocalSearchEngineManager.xtend deleted file mode 100644 index ee7f0060..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/LocalSearchEngineManager.xtend +++ /dev/null @@ -1,31 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo - -import hu.bme.mit.inf.dslreasoner.domains.satellite.queries.SatelliteQueries -import java.util.WeakHashMap -import org.eclipse.emf.ecore.EObject -import org.eclipse.viatra.query.runtime.api.AdvancedViatraQueryEngine -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngineOptions -import org.eclipse.viatra.query.runtime.emf.EMFScope -import org.eclipse.viatra.query.runtime.localsearch.matcher.integration.LocalSearchHints - -class LocalSearchEngineManager { - public static val INSTANCE = new LocalSearchEngineManager - - val WeakHashMap engineMap = new WeakHashMap - - private new() { - } - - def getEngine(EObject eObject) { - engineMap.computeIfAbsent(eObject) [ - val scope = new EMFScope(it) - val localSearchHints = LocalSearchHints.^default.build - val options = ViatraQueryEngineOptions.defineOptions.withDefaultHint(localSearchHints).withDefaultBackend( - localSearchHints.queryBackendFactory).build - val engine = AdvancedViatraQueryEngine.on(scope, options) - SatelliteQueries.instance.prepare(engine) - engine - ] - } -} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/MetricBasedGuidanceFunction.xtend b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/MetricBasedGuidanceFunction.xtend deleted file mode 100644 index 1529794f..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/MetricBasedGuidanceFunction.xtend +++ /dev/null @@ -1,47 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo - -import org.eclipse.viatra.query.runtime.api.IPatternMatch -import org.eclipse.viatra.query.runtime.api.IQuerySpecification -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -import uk.ac.kcl.inf.mdeoptimiser.libraries.core.optimisation.IGuidanceFunction -import uk.ac.kcl.inf.mdeoptimiser.libraries.core.optimisation.interpreter.guidance.Solution - -abstract class MetricBasedGuidanceFunction implements IGuidanceFunction { - val IQuerySpecification> querySpecification - - protected new(IQuerySpecification> querySpecification) { - this.querySpecification = querySpecification - if (querySpecification.parameters.size != 1) { - throw new IllegalArgumentException("Metric must have a single parameter") - } - } - - override computeFitness(Solution model) { - val value = getMetricValue(model) - computeFitness(value) - } - - protected def double computeFitness(double metricValue) { - metricValue - } - - private def getMetricValue(Solution solution) { - val model = solution.model - val queryEngine = LocalSearchEngineManager.INSTANCE.getEngine(model) - val matcher = querySpecification.getMatcher(queryEngine) - val iterator = matcher.allMatches.iterator - if (!iterator.hasNext) { - throw new IllegalStateException("Too few matches") - } - val objectValue = iterator.next.get(0) - if (objectValue instanceof Number) { - val doubleValue = objectValue.doubleValue - if (iterator.hasNext) { - throw new IllegalStateException("Too many matches") - } - doubleValue - } else { - throw new IllegalStateException("Metric value must be a number") - } - } -} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/PatternMatchConstraint.xtend b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/PatternMatchConstraint.xtend deleted file mode 100644 index b238e64f..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/PatternMatchConstraint.xtend +++ /dev/null @@ -1,29 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo - -import com.google.common.collect.ImmutableList -import hu.bme.mit.inf.dslreasoner.domains.satellite.queries.SatelliteQueries -import uk.ac.kcl.inf.mdeoptimiser.libraries.core.optimisation.IGuidanceFunction -import uk.ac.kcl.inf.mdeoptimiser.libraries.core.optimisation.interpreter.guidance.Solution - -class PatternMatchConstraint implements IGuidanceFunction { - static val CONSTRAINT_ANNOTATION_NAME = "Constraint" - - val queries = ImmutableList.copyOf(SatelliteQueries.instance.specifications.filter [ - allAnnotations.exists[name == CONSTRAINT_ANNOTATION_NAME] - ]) - - override getName() { - "PatternMatch" - } - - override computeFitness(Solution solution) { - val model = solution.model - val queryEngine = LocalSearchEngineManager.INSTANCE.getEngine(model) - var int matchCount = 0 - for (query : queries) { - val matcher = query.getMatcher(queryEngine) - matchCount += matcher.countMatches - } - matchCount - } -} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/SatelliteMdeOptimiserMain.xtend b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/SatelliteMdeOptimiserMain.xtend deleted file mode 100644 index 58034c43..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/SatelliteMdeOptimiserMain.xtend +++ /dev/null @@ -1,51 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo - -import java.io.BufferedReader -import java.io.BufferedWriter -import java.io.FileReader -import java.io.FileWriter -import java.util.Map -import org.eclipse.emf.ecore.EPackage -import org.eclipse.emf.ecore.resource.Resource -import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl -import satellite.SatellitePackage -import uk.ac.kcl.inf.mdeoptimiser.interfaces.cli.Run - -class SatelliteMdeOptimiserMain { - static val PROJECT_PATH = "." - static val MOPT_PATH = "src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/satellite.mopt" - - private new() { - new IllegalStateException("This is a static utility class and should not be instantiated directly.") - } - - public static def void main(String[] args) { - Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put(Resource.Factory.Registry.DEFAULT_EXTENSION, - new XMIResourceFactoryImpl) - EPackage.Registry.INSTANCE.put(SatellitePackage.eNS_URI, SatellitePackage.eINSTANCE) - fixupHenshinModel("model/satellite.henshin", "model/satellite_fixup.henshin", - #{"satellite.ecore" -> SatellitePackage.eNS_URI}) - Run.main(#["-p", PROJECT_PATH, "-m", MOPT_PATH]) - } - - private def static void fixupHenshinModel(String originalPath, String outputPath, Map remapMap) { - val reader = new BufferedReader(new FileReader(originalPath)) - try { - val writer = new BufferedWriter(new FileWriter(outputPath)) - try { - var String line - while ((line = reader.readLine) !== null) { - for (entry : remapMap.entrySet) { - line = line.replace(entry.key, entry.value) - } - writer.write(line) - writer.write("\n") - } - } finally { - writer.close - } - } finally { - reader.close - } - } -} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/satellite.mopt b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/satellite.mopt deleted file mode 100644 index e9bd1a64..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/mdeo/satellite.mopt +++ /dev/null @@ -1,36 +0,0 @@ -problem { - basepath - metamodel - model <../inputs/SatelliteInstance.xmi> -} - -goal { - objective Cost minimise java { "hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo.CostObjective" } - constraint PatternMatch java { "hu.bme.mit.inf.dslreasoner.domains.satellite.mdeo.PatternMatchConstraint" } -} - -search { -// mutate using unit "addCubeSat3U" - mutate { "CubeSat3U" } - mutate { "CubeSat6U" } - mutate { "SmallSat" } - mutate { "InterferometryPayload" } - mutate { "UHFCommSubsystem" } - mutate { "XCommSubsystem" } - mutate { "KaCommSubsystem" } -} - -solver { - optimisation provider moea algorithm NSGAII { - variation: mutation - population: 25 - mutation.step: 3 - mutation.strategy: random - } - - termination { - time: 120 - } - - batches 1 -} \ No newline at end of file diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/queries/SatelliteQueries.vql b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/queries/SatelliteQueries.vql index c1d3f7d3..1f83a3b0 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/queries/SatelliteQueries.vql +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.satellite/src/hu/bme/mit/inf/dslreasoner/domains/satellite/queries/SatelliteQueries.vql @@ -21,6 +21,13 @@ pattern transmittingGroundStationNetwork(Station : GroundStationNetwork) { find transmittingCommSubsystem(Station, _); } +@Constraint(severity = "error", key = {Station}, + message = "The ground station network may not have UHF communication subsystems.") +pattern roundStationNetworkUHF(Station : GroundStationNetwork) { + CommunicatingElement.commSubsystem(Station, Comm); + UHFCommSubsystem(Comm); +} + // At least two spacecraft must have the interferometry payload configured @Constraint(severity = "error", key = {Mission}, @@ -97,10 +104,6 @@ private pattern cubeSat3U(Sat : CubeSat3U) { CubeSat3U(Sat); } -private pattern cubeSat6U(Sat : CubeSat6U) { - CubeSat6U(Sat); -} - // No communication loops may exist // No spacecraft may directly communicate with itself diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/META-INF/MANIFEST.MF b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/META-INF/MANIFEST.MF index 81ee8677..2666dc5e 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/META-INF/MANIFEST.MF +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/META-INF/MANIFEST.MF @@ -9,8 +9,7 @@ Bundle-Localization: plugin Export-Package: hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph.yakindumm, hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph.yakindumm.impl, hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph.yakindumm.util, - hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu, - hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.mutated + hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu Require-Bundle: org.eclipse.viatra.query.runtime, org.eclipse.core.runtime, org.eclipse.emf.ecore;visibility:=reexport, diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml index 993ec75d..7bf4a20b 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/plugin.xml @@ -9,6 +9,8 @@ + + @@ -21,10 +23,14 @@ + + + + @@ -32,72 +38,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/mutated/mutated.vql b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/mutated/mutated.vql deleted file mode 100644 index 58f66fe2..00000000 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/mutated/mutated.vql +++ /dev/null @@ -1,270 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.mutated - -import epackage "hu.bme.mit.inf.yakindumm" - -///////// -// Entry -///////// - -pattern entryInRegion_M0(r1 : Region, e1 : Entry) { - Region.vertices(r1, e1); -} -pattern entryInRegion_M1(r1 : Region, e1) { - Region.vertices(r1, e1); -} -pattern entryInRegion_M2(r1 : Region, e1: Entry) { - // For positive constraint - Region(r1);Entry(e1); -} - - -//@Constraint(severity="error", message="error", key = {r1}) -pattern noEntryInRegion_M0(r1 : Region) { - neg find entryInRegion_M0(r1, _); -} -pattern noEntryInRegion_M1(r1 : Region) { - neg find entryInRegion_M1(r1, _); -} -pattern noEntryInRegion_M2(r1 : Region) { - neg find entryInRegion_M2(r1, _); -} -pattern noEntryInRegion_M3(r1 : Region) { - find entryInRegion_M0(r1, _); -} -pattern noEntryInRegion_M4(r1 : Region) { - find entryInRegion_M1(r1, _); -} -pattern noEntryInRegion_M5(r1 : Region) { - find entryInRegion_M2(r1, _); -} - -//@Constraint(severity="error", message="error", key = {r}) -pattern multipleEntryInRegion_M0(r : Region) { - find entryInRegion_M0(r, e1); - find entryInRegion_M0(r, e2); - e1 != e2; -} -pattern multipleEntryInRegion_M1(r : Region) { - find entryInRegion_M1(r, e1); - find entryInRegion_M0(r, e2); - e1 != e2; -} -pattern multipleEntryInRegion_M2(r : Region) { - find entryInRegion_M2(r, e1); - find entryInRegion_M0(r, e2); - e1 != e2; -} -pattern multipleEntryInRegion_M3(r : Region) { - find entryInRegion_M0(r, e1); - find entryInRegion_M1(r, e2); - e1 != e2; -} -pattern multipleEntryInRegion_M4(r : Region) { - find entryInRegion_M2(r, e1); - find entryInRegion_M2(r, e2); - e1 != e2; -} -pattern multipleEntryInRegion_M5(r : Region) { - find entryInRegion_M0(r, e1); - find entryInRegion_M0(r, e2); -} - - -pattern transition_M0(t : Transition, src : Vertex, trg : Vertex) { - Transition.source(t, src); - Transition.target(t, trg); -} -pattern transition_M1(t : Transition, src : Vertex, trg : Vertex) { - Transition.source(t, src); - Vertex(trg); -} -pattern transition_M2(t : Transition, src : Vertex, trg : Vertex) { - Vertex(src); - Transition.target(t, trg); -} -pattern transition_M3(t : Transition, src : Vertex, trg : Vertex) { - Transition.source(t_x, src); - Transition.target(t, trg); -} -pattern transition_M4(t : Transition, src : Vertex, trg : Vertex) { - Transition.source(t, src); - Transition.target(t_x, trg); -} - -//@Constraint(severity="error", message="error", key = {e}) -pattern incomingToEntry_M0(t : Transition, e : Entry) { - find transition_M0(t, _, e); -} -pattern incomingToEntry_1(t : Transition, e) { - find transition_M0(t, _, e); -} -pattern incomingToEntry_2(t : Transition, e : Entry) { - find transition_M1(t, _, e); -} -pattern incomingToEntry_3(t : Transition, e : Entry) { - find transition_M2(t, _, e); -} -pattern incomingToEntry_4(t : Transition, e : Entry) { - find transition_M3(t, _, e); -} -pattern incomingToEntry_5(t : Transition, e : Entry) { - find transition_M4(t, _, e); -} - -pattern noOutgoingTransitionFromEntry_M0(e : Entry) { - neg find transition_M0(_, e, _); -} - -pattern noOutgoingTransitionFromEntry_M1(e) { - Vertex(e); - neg find transition_M0(_, e, _); -} -pattern noOutgoingTransitionFromEntry_M2(e : Entry) { - neg find transition_M1(_, e, _); -} -pattern noOutgoingTransitionFromEntry_M3(e : Entry) { - neg find transition_M2(_, e, _); -} -pattern noOutgoingTransitionFromEntry_M4(e : Entry) { - neg find transition_M3(_, e, _); -} -pattern noOutgoingTransitionFromEntry_M5(e : Entry) { - neg find transition_M4(_, e, _); -} - - -//@Constraint(severity="error", message="error", key = {e}) -pattern multipleTransitionFromEntry_M0(e : Entry, t1 : Transition, t2: Transition) { - Entry.outgoingTransitions(e,t1); - Entry.outgoingTransitions(e,t2); - t1!=t2; -} -pattern multipleTransitionFromEntry_M1(e, t1 : Transition, t2: Transition) { - Entry.outgoingTransitions(e,t1); - Entry.outgoingTransitions(e,t2); - t1!=t2; -} -pattern multipleTransitionFromEntry_M2(e : Entry, t1 : Transition, t2: Transition) { - Transition(t1); - Entry.outgoingTransitions(e,t2); - t1!=t2; -} -pattern multipleTransitionFromEntry_M3(e : Entry, t1 : Transition, t2: Transition) { - Entry.outgoingTransitions(e,t1); - Transition(t2); - t1!=t2; -} -pattern multipleTransitionFromEntry_M4(e : Entry, t1 : Transition, t2: Transition) { - Entry.outgoingTransitions(e,t1); - Entry.outgoingTransitions(e,t2); -} - -///////// -// Exit -///////// - -//@Constraint(severity="error", message="error", key = {e}) -pattern outgoingFromExit_M0(t : Transition, e : Exit) { - Exit.outgoingTransitions(e,t); -} -pattern outgoingFromExit_M1(t : Transition, e) { - Vertex.outgoingTransitions(e,t); -} -pattern outgoingFromExit_M2(t : Transition, e : Exit) { - Transition(t); - Exit(e); -} - -///////// -// Final -///////// - -//@Constraint(severity="error", message="error", key = {f}) -pattern outgoingFromFinal_M0(t : Transition, f : FinalState) { - FinalState.outgoingTransitions(f,t); -} -pattern outgoingFromFinal_M1(t : Transition, f) { - Vertex.outgoingTransitions(f,t); -} -pattern outgoingFromFinal_M2(t : Transition, f : FinalState) { - Transition(t); - FinalState(f); -} - -///////// -// State vs Region -///////// - -//@Constraint(severity="error", message="error", key = {region}) -pattern noStateInRegion_M0(region: Region) { - neg find StateInRegion_M0(region,_); -} -pattern noStateInRegion_M1(region: Region) { - neg find StateInRegion_M1(region,_); -} -pattern noStateInRegion_M2(region: Region) { - neg find StateInRegion_M2(region,_); -} -pattern noStateInRegion_M3(region: Region) { - find StateInRegion_M0(region,_); -} - -pattern StateInRegion_M0(region: Region, state: State) { - Region.vertices(region,state); -} -pattern StateInRegion_M1(region: Region, state) { - Region.vertices(region,state); -} -pattern StateInRegion_M2(region: Region, state:State) { - Region(region);State(state); -} - -///////// -// Choice -///////// - -@Constraint(severity="error", message="error", key = {c}) -pattern choiceHasNoOutgoing_M0(c : Choice) { - neg find transition_M0(_, c, _); -} -pattern choiceHasNoOutgoing_M1(c:Vertex) { - neg find transition_M0(_, c, _); -} -pattern choiceHasNoOutgoing_M2(c : Choice) { - neg find transition_M1(_, c, _); -} -pattern choiceHasNoOutgoing_M3(c : Choice) { - neg find transition_M2(_, c, _); -} -pattern choiceHasNoOutgoing_M4(c : Choice) { - neg find transition_M3(_, c, _); -} -pattern choiceHasNoOutgoing_M5(c : Choice) { - neg find transition_M4(_, c, _); -} -pattern choiceHasNoOutgoing_M6(c : Choice) { - find transition_M0(_, c, _); -} - -@Constraint(severity="error", message="error", key = {c}) -pattern choiceHasNoIncoming_M0(c: Choice) { - neg find transition_M0(_, _, c); -} -pattern choiceHasNoIncoming_M1(c:Vertex) { - neg find transition_M0(_, _, c); -} -pattern choiceHasNoIncoming_M2(c: Choice) { - neg find transition_M1(_, _, c); -} -pattern choiceHasNoIncoming_M3(c: Choice) { - neg find transition_M2(_, _, c); -} -pattern choiceHasNoIncoming_M4(c: Choice) { - neg find transition_M3(_, _, c); -} -pattern choiceHasNoIncoming_M5(c: Choice) { - neg find transition_M4(_, _, c); -} -pattern choiceHasNoIncoming_M6(c: Choice) { - find transition_M0(_, _, c); -} diff --git a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/patterns.vql b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/patterns.vql index f4bfa3c1..98a10cde 100644 --- a/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/patterns.vql +++ b/Domains/hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph/queries/hu/bme/mit/inf/dslreasoner/partialsnapshot_mavo/yakindu/patterns.vql @@ -27,14 +27,22 @@ pattern transition(t : Transition, src : Vertex, trg : Vertex) { Transition.target(t, trg); } +pattern transitionFrom(t : Transition, src : Vertex) { + Transition.source(t, src); +} + +pattern transitionTo(t : Transition, trg : Vertex) { + Transition.target(t, trg); +} + @Constraint(severity="error", message="error", key = {e}) pattern incomingToEntry(t : Transition, e : Entry) { - find transition(t, _, e); + find transitionTo(t, e); } @Constraint(severity="error", message="error", key = {e}) pattern noOutgoingTransitionFromEntry(e : Entry) { - neg find transition(_, e, _); + neg find transitionFrom(_, e); } @Constraint(severity="error", message="error", key = {e}) @@ -80,12 +88,12 @@ pattern StateInRegion(region: Region, state: State) { @Constraint(severity="error", message="error", key = {c}) pattern choiceHasNoOutgoing(c : Choice) { - neg find transition(_, c, _); + neg find transitionFrom(_, c); } @Constraint(severity="error", message="error", key = {c}) pattern choiceHasNoIncoming(c: Choice) { - neg find transition(_, _, c); + neg find transitionTo(_, c); } ///////// @@ -94,27 +102,33 @@ pattern choiceHasNoIncoming(c: Choice) { @Constraint(severity="error", message="error", key = {s}) pattern synchHasNoOutgoing(s : Synchronization) { - neg find transition(_, s, _); + neg find transitionFrom(_, s); } @Constraint(severity="error", message="error", key = {s}) pattern synchHasNoIncoming(s : Synchronization) { - neg find transition(_, _, s); + neg find transitionTo(_, s); } @Constraint(severity="error", message="error", key = {s}) -pattern SynchronizedIncomingInSameRegion(s : Synchronization, v1 : Vertex, v2 : Vertex) { - find transition(t1, v1, s); - find transition(t2, v2, s); +pattern SynchronizedIncomingInSameRegion(s : Synchronization, t1 : Transition, t2 : Transition) { + find SynchronizedIncomingInSameRegionHelper1(r, s, t1); + find SynchronizedIncomingInSameRegionHelper1(r, s, t2); t1!=t2; - Region.vertices(r, v1); - Region.vertices(r, v2); } or { - find transition(t1, s, v1); - find transition(t2, s, v2); + find SynchronizedIncomingInSameRegionHelper2(r, s, t1); + find SynchronizedIncomingInSameRegionHelper2(r, s, t2); t1!=t2; +} + +pattern SynchronizedIncomingInSameRegionHelper1(r : Region, s : Synchronization, t1 : Transition) { + find transition(t1, v1, s); + Region.vertices(r, v1); +} + +pattern SynchronizedIncomingInSameRegionHelper2(r : Region, s : Synchronization, t1 : Transition) { + find transition(t1, s, v1); Region.vertices(r, v1); - Region.vertices(r, v2); } @Constraint(severity="error", message="error", key = {s}) @@ -136,18 +150,24 @@ pattern hasMultipleIncomingTrainsition(v : Synchronization) { } @Constraint(severity="error", message="error", key = {s}) -pattern SynchronizedRegionsAreNotSiblings(s : Synchronization, v1 : Vertex, v2 : Vertex) { - find transition(_, v1, s); - find transition(_, v2, s); - CompositeElement.regions.vertices(r1, v1); - CompositeElement.regions.vertices(r2, v2); +pattern SynchronizedRegionsAreNotSiblings(s : Synchronization, r1 : CompositeElement, r2 : CompositeElement) { + find SynchronizedRegionsAreNotSiblingsHelper1(s, r1); + find SynchronizedRegionsAreNotSiblingsHelper1(s, r2); r1 != r2; } or { + find SynchronizedRegionsAreNotSiblingsHelper2(s, r1); + find SynchronizedRegionsAreNotSiblingsHelper2(s, r2); + r1 != r2; +} + +pattern SynchronizedRegionsAreNotSiblingsHelper1(s : Synchronization, r1 : CompositeElement) { find transition(_, s, v1); - find transition(_, s, v2); CompositeElement.regions.vertices(r1, v1); - CompositeElement.regions.vertices(r2, v2); - r1 != r2; +} + +pattern SynchronizedRegionsAreNotSiblingsHelper2(s : Synchronization, r1 : CompositeElement) { + find transition(_, v1, s); + CompositeElement.regions.vertices(r1, v1); } /////////////////////////////// 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.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend index 23632d4d..e45ec1c8 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.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend @@ -5,6 +5,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator @@ -46,16 +47,28 @@ class ModelGenerationStatistics { public var long preliminaryTypeAnalisisTime = 0 public var int decisionsTried = 0 - + synchronized def incrementDecisionCount() { decisionsTried++ } + + public var int transformationInvocations + synchronized def incrementTransformationCount() { + transformationInvocations++ + } + public var int scopePropagatorInvocations - + synchronized def incrementScopePropagationCount() { scopePropagatorInvocations++ } + + public var int scopePropagatorSolverInvocations + + synchronized def incrementScopePropagationSolverCount() { + scopePropagatorSolverInvocations++ + } } @Data class ModelGenerationMethod { @@ -93,6 +106,7 @@ class ModelGenerationMethodProvider { boolean nameNewElements, TypeInferenceMethod typeInferenceMethod, ScopePropagatorStrategy scopePropagatorStrategy, + Collection hints, DocumentationLevel debugLevel ) { val statistics = new ModelGenerationStatistics @@ -103,8 +117,8 @@ class ModelGenerationMethodProvider { val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem) val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries, - workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, writeFiles) - val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, queries, statistics) + workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, writeFiles) + val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) scopePropagator.propagateAllScopeConstraints val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(queries, scopePropagator, nameNewElements, statistics) @@ -138,14 +152,20 @@ class ModelGenerationMethodProvider { } private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy, - PartialInterpretation emptySolution, GeneratedPatterns queries, ModelGenerationStatistics statistics) { + PartialInterpretation emptySolution, Collection hints, GeneratedPatterns queries, + ModelGenerationStatistics statistics) { + if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) { + throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.") + } switch (scopePropagatorStrategy) { - case ScopePropagatorStrategy.Count: + case ScopePropagatorStrategy.None, + case ScopePropagatorStrategy.Basic: new ScopePropagator(emptySolution, statistics) case ScopePropagatorStrategy.BasicTypeHierarchy: new TypeHierarchyScopePropagator(emptySolution, statistics) ScopePropagatorStrategy.Polyhedral: { val types = queries.refineObjectQueries.keySet.map[newType].toSet + val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName] val solver = switch (scopePropagatorStrategy.solver) { case Z3Integer: new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds) @@ -160,7 +180,8 @@ class ModelGenerationMethodProvider { scopePropagatorStrategy.solver) } new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries, - queries.hasElementInContainmentQuery, solver, scopePropagatorStrategy.requiresUpperBoundIndexing) + queries.hasElementInContainmentQuery, allPatternsByName, hints, solver, + scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic) } default: throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy) diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend new file mode 100644 index 00000000..8c21ca1d --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/LinearTypeConstraintHint.xtend @@ -0,0 +1,30 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher + +interface LinearTypeExpressionBuilderFactory { + def ViatraQueryMatcher createMatcher(String queryName) + + def LinearTypeExpressionBuilder createBuilder() +} + +interface LinearTypeExpressionBuilder { + def LinearTypeExpressionBuilder add(int scale, Type type) + + def LinearBoundedExpression build() +} + +@FunctionalInterface +interface RelationConstraintUpdater { + def void update(PartialInterpretation p) +} + +interface LinearTypeConstraintHint { + def CharSequence getAdditionalPatterns(PatternGenerator patternGenerator) + + def RelationConstraintUpdater createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory) +} 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 7c05e818..51dba244 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,5 +1,7 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality +import com.google.common.cache.Cache +import com.google.common.cache.CacheBuilder import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableSet @@ -15,6 +17,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope import java.util.ArrayDeque import java.util.ArrayList +import java.util.Collection import java.util.HashMap import java.util.HashSet import java.util.List @@ -29,26 +32,33 @@ import org.eclipse.viatra.query.runtime.emf.EMFScope import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { + static val CACHE_SIZE = 10000 + + val boolean updateHeuristic val Map scopeBounds val LinearBoundedExpression topLevelBounds val Polyhedron polyhedron val PolyhedronSaturationOperator operator val Set relevantRelations + val Cache cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build List updaters = emptyList new(PartialInterpretation p, ModelGenerationStatistics statistics, Set possibleNewDynamicTypes, Map unfinishedMultiplicityQueries, IQuerySpecification> hasElementInContainmentQuery, - PolyhedronSolver solver, boolean propagateRelations) { + Map>> allPatternsByName, + Collection hints, PolyhedronSolver solver, boolean propagateRelations, + boolean updateHeuristic) { super(p, statistics) + this.updateHeuristic = updateHeuristic val builder = new PolyhedronBuilder(p) builder.buildPolyhedron(possibleNewDynamicTypes) scopeBounds = builder.scopeBounds topLevelBounds = builder.topLevelBounds polyhedron = builder.polyhedron operator = solver.createSaturationOperator(polyhedron) + propagateAllScopeConstraints() if (propagateRelations) { - propagateAllScopeConstraints() val maximumNumberOfNewNodes = topLevelBounds.upperBound if (maximumNumberOfNewNodes === null) { throw new IllegalStateException("Could not determine maximum number of new nodes, it may be unbounded") @@ -57,7 +67,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { throw new IllegalStateException("Maximum number of new nodes is not positive") } builder.buildMultiplicityConstraints(unfinishedMultiplicityQueries, hasElementInContainmentQuery, - maximumNumberOfNewNodes) + allPatternsByName, hints, maximumNumberOfNewNodes) relevantRelations = builder.relevantRelations updaters = builder.updaters } else { @@ -66,21 +76,40 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } override void doPropagateAllScopeConstraints() { + super.doPropagateAllScopeConstraints() resetBounds() populatePolyhedronFromScope() // println(polyhedron) - val result = operator.saturate() -// println(polyhedron) - if (result == PolyhedronSaturationResult.EMPTY) { - setScopesInvalid() - } else { - populateScopesFromPolyhedron() - if (result != PolyhedronSaturationResult.SATURATED) { - super.propagateAllScopeConstraints() + val signature = polyhedron.createSignature + val cachedSignature = cache.getIfPresent(signature) + switch (cachedSignature) { + case null: { + statistics.incrementScopePropagationSolverCount + val result = operator.saturate() + if (result == PolyhedronSaturationResult.EMPTY) { + cache.put(signature, PolyhedronSignature.EMPTY) + setScopesInvalid() + } else { + val resultSignature = polyhedron.createSignature + cache.put(signature, resultSignature) + populateScopesFromPolyhedron() + } } + case PolyhedronSignature.EMPTY: + setScopesInvalid() + PolyhedronSignature.Bounds: { + polyhedron.applySignature(signature) + populateScopesFromPolyhedron() + } + default: + throw new IllegalStateException("Unknown polyhedron signature: " + signature) + } +// println(polyhedron) + if (updateHeuristic) { + copyScopeBoundsToHeuristic() } } - + override propagateAdditionToRelation(Relation r) { super.propagateAdditionToRelation(r) if (relevantRelations.contains(r)) { @@ -186,7 +215,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } @FinalFieldsConstructor - private static class PolyhedronBuilder { + private static class PolyhedronBuilder implements LinearTypeExpressionBuilderFactory { static val INFINITY_SCALE = 10 val PartialInterpretation p @@ -197,6 +226,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { Map typeBounds int infinity ViatraQueryEngine queryEngine + Map>> allPatternsByName ImmutableList.Builder updatersBuilder Map scopeBounds @@ -222,9 +252,11 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { def buildMultiplicityConstraints( Map constraints, IQuerySpecification> hasElementInContainmentQuery, - int maximumNuberOfNewNodes) { + Map>> allPatternsByName, + Collection hints, int maximumNuberOfNewNodes) { infinity = maximumNuberOfNewNodes * INFINITY_SCALE queryEngine = ViatraQueryEngine.on(new EMFScope(p)) + this.allPatternsByName = allPatternsByName updatersBuilder = ImmutableList.builder val containmentConstraints = constraints.entrySet.filter[key.containment].groupBy[key.targetType] for (pair : containmentConstraints.entrySet) { @@ -238,10 +270,13 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } } buildRelevantRelations(constraints.keySet) + for (hint : hints) { + updatersBuilder.add(hint.createConstraintUpdater(this)) + } updaters = updatersBuilder.build addCachedConstraintsToPolyhedron() } - + private def buildRelevantRelations(Set constraints) { val builder = ImmutableSet.builder for (constraint : constraints) { @@ -345,7 +380,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } } - private def addCoefficients(Map accumulator, int scale, Map a) { + private static def addCoefficients(Map accumulator, int scale, Map a) { for (pair : a.entrySet) { val dimension = pair.key val currentValue = accumulator.get(pair.key) ?: 0 @@ -411,14 +446,41 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } scopeBoundsBuilder.build } + + override createMatcher(String queryName) { + val querySpecification = allPatternsByName.get(queryName) + if (querySpecification === null) { + throw new IllegalArgumentException("Unknown pattern: " + queryName) + } + querySpecification.getMatcher(queryEngine) + } + + override createBuilder() { + new PolyhedronBuilderLinearTypeExpressionBuilder(this) + } } - private static interface RelationConstraintUpdater { - def void update(PartialInterpretation p) + @FinalFieldsConstructor + private static class PolyhedronBuilderLinearTypeExpressionBuilder implements LinearTypeExpressionBuilder { + val PolyhedronBuilder polyhedronBuilder + val Map coefficients = new HashMap + + override add(int scale, Type type) { + val typeCoefficients = polyhedronBuilder.subtypeDimensions.get(type) + if (typeCoefficients === null) { + throw new IllegalArgumentException("Unknown type: " + type) + } + PolyhedronBuilder.addCoefficients(coefficients, scale, typeCoefficients) + this + } + + override build() { + polyhedronBuilder.toExpression(coefficients) + } } @FinalFieldsConstructor - static class ContainmentConstraintUpdater implements RelationConstraintUpdater { + private static class ContainmentConstraintUpdater implements RelationConstraintUpdater { val String name val LinearBoundedExpression orphansLowerBound val LinearBoundedExpression orphansUpperBound @@ -460,7 +522,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } @FinalFieldsConstructor - static class ContainmentRootConstraintUpdater implements RelationConstraintUpdater { + private static class ContainmentRootConstraintUpdater implements RelationConstraintUpdater { val LinearBoundedExpression typeCardinality val ViatraQueryMatcher hasElementInContainmentMatcher @@ -479,7 +541,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } @FinalFieldsConstructor - static class UnfinishedMultiplicityConstraintUpdater implements RelationConstraintUpdater { + private static class UnfinishedMultiplicityConstraintUpdater implements RelationConstraintUpdater { val String name val LinearBoundedExpression availableMultiplicityExpression val ViatraQueryMatcher unfinishedMultiplicityMatcher @@ -500,7 +562,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } @FinalFieldsConstructor - static class UnrepairableMultiplicityConstraintUpdater implements RelationConstraintUpdater { + private static class UnrepairableMultiplicityConstraintUpdater implements RelationConstraintUpdater { val String name val LinearBoundedExpression targetCardinalityExpression val ViatraQueryMatcher unrepairableMultiplicityMatcher 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 9c6cb82e..4e046190 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 @@ -3,6 +3,7 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality import java.util.List import java.util.Map import org.eclipse.xtend.lib.annotations.Accessors +import org.eclipse.xtend.lib.annotations.Data import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor interface PolyhedronSolver { @@ -52,16 +53,66 @@ class Polyhedron { val List expressionsToSaturate override toString() ''' - Dimensions: - «FOR dimension : dimensions» - «dimension» - «ENDFOR» - Constraints: - «FOR constraint : constraints» - «constraint» - «ENDFOR» + Dimensions: + «FOR dimension : dimensions» + «dimension» + «ENDFOR» + Constraints: + «FOR constraint : constraints» + «constraint» + «ENDFOR» ''' + def createSignature() { + val size = dimensions.size + constraints.size + val lowerBounds = newArrayOfSize(size) + val upperBounds = newArrayOfSize(size) + var int i = 0 + for (dimension : dimensions) { + lowerBounds.set(i, dimension.lowerBound) + upperBounds.set(i, dimension.upperBound) + i++ + } + for (constraint : constraints) { + lowerBounds.set(i, constraint.lowerBound) + upperBounds.set(i, constraint.upperBound) + i++ + } + new PolyhedronSignature.Bounds(lowerBounds, upperBounds) + } + + def applySignature(PolyhedronSignature.Bounds signature) { + val lowerBounds = signature.lowerBounds + val upperBounds = signature.upperBounds + var int i = 0 + for (dimension : dimensions) { + dimension.lowerBound = lowerBounds.get(i) + dimension.upperBound = upperBounds.get(i) + i++ + } + for (constraint : constraints) { + constraint.lowerBound = lowerBounds.get(i) + constraint.upperBound = upperBounds.get(i) + i++ + } + } +} + +abstract class PolyhedronSignature { + public static val EMPTY = new PolyhedronSignature { + override toString() { + "PolyhedronSignature.EMPTY" + } + } + + private new() { + } + + @Data + static class Bounds extends PolyhedronSignature { + val Integer[] lowerBounds + val Integer[] upperBounds + } } @Accessors @@ -80,6 +131,11 @@ abstract class LinearBoundedExpression { upperBound = tighterBound } } + + def void assertEqualsTo(int bound) { + tightenLowerBound(bound) + tightenUpperBound(bound) + } } @Accessors diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend index 52a390a8..013e53e1 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/RelationConstraintCalculator.xtend @@ -117,9 +117,12 @@ class RelationConstraintCalculator { var inverseUpperMultiplicity = -1 val inverseRelation = inverseRelations.get(relation) if (inverseRelation !== null) { - inverseUpperMultiplicity = upperMultiplicities.get(relation) + inverseUpperMultiplicity = upperMultiplicities.get(inverseRelation) container = containmentRelations.contains(inverseRelation) } + if (containment) { + inverseUpperMultiplicity = 1 + } val constraint = new RelationMultiplicityConstraint(relation, inverseRelation, containment, container, lowerMultiplicity, upperMultiplicity, inverseUpperMultiplicity) if (constraint.isActive) { diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend index 0bdb202e..2376fb38 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagator.xtend @@ -14,7 +14,7 @@ import org.eclipse.xtend.lib.annotations.Accessors class ScopePropagator { @Accessors(PROTECTED_GETTER) val PartialInterpretation partialInterpretation - val ModelGenerationStatistics statistics + @Accessors(PROTECTED_GETTER) val ModelGenerationStatistics statistics val Map type2Scope @Accessors(PROTECTED_GETTER) val Map> superScopes @Accessors(PROTECTED_GETTER) val Map> subScopes @@ -59,12 +59,21 @@ class ScopePropagator { } } } while (changed) + + copyScopeBoundsToHeuristic() } def propagateAllScopeConstraints() { statistics.incrementScopePropagationCount() doPropagateAllScopeConstraints() } + + protected def copyScopeBoundsToHeuristic() { + partialInterpretation.minNewElementsHeuristic = partialInterpretation.minNewElements + for (scope : partialInterpretation.scopes) { + scope.minNewElementsHeuristic = scope.minNewElements + } + } protected def void doPropagateAllScopeConstraints() { // Nothing to propagate. @@ -73,12 +82,17 @@ class ScopePropagator { def propagateAdditionToType(PartialTypeInterpratation t) { // println('''Adding to «(t as PartialComplexTypeInterpretation).interpretationOf.name»''') val targetScope = type2Scope.get(t) - targetScope.removeOne - val sups = superScopes.get(targetScope) - sups.forEach[removeOne] + if (targetScope !== null) { + targetScope.removeOne + val sups = superScopes.get(targetScope) + sups.forEach[removeOne] + } if (this.partialInterpretation.minNewElements > 0) { this.partialInterpretation.minNewElements = this.partialInterpretation.minNewElements - 1 } + if (this.partialInterpretation.minNewElementsHeuristic > 0) { + this.partialInterpretation.minNewElementsHeuristic = this.partialInterpretation.minNewElementsHeuristic - 1 + } if (this.partialInterpretation.maxNewElements > 0) { this.partialInterpretation.maxNewElements = this.partialInterpretation.maxNewElements - 1 } else if (this.partialInterpretation.maxNewElements === 0) { @@ -105,5 +119,8 @@ class ScopePropagator { if (scope.minNewElements > 0) { scope.minNewElements = scope.minNewElements - 1 } + if (scope.minNewElementsHeuristic > 0) { + scope.minNewElementsHeuristic = scope.minNewElementsHeuristic - 1 + } } } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend index b0ed75cb..3165917a 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ScopePropagatorStrategy.xtend @@ -16,7 +16,9 @@ enum PolyhedralScopePropagatorSolver { } abstract class ScopePropagatorStrategy { - public static val Count = new Simple("Count") + public static val None = new Simple("None") + + public static val Basic = new Simple("Basic") public static val BasicTypeHierarchy = new Simple("BasicTypeHierarchy") @@ -47,14 +49,19 @@ abstract class ScopePropagatorStrategy { val PolyhedralScopePropagatorConstraints constraints val PolyhedralScopePropagatorSolver solver + val boolean updateHeuristic val double timeoutSeconds @FinalFieldsConstructor new() { } + new(PolyhedralScopePropagatorConstraints constraints, PolyhedralScopePropagatorSolver solver, boolean updateHeuristic) { + this(constraints, solver, updateHeuristic, UNLIMITED_TIME) + } + new(PolyhedralScopePropagatorConstraints constraints, PolyhedralScopePropagatorSolver solver) { - this(constraints, solver, UNLIMITED_TIME) + this(constraints, solver, true) } override requiresUpperBoundIndexing() { diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend index be8ef00a..d1704b39 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/TypeHierarchyScopePropagator.xtend @@ -27,12 +27,16 @@ class TypeHierarchyScopePropagator extends ScopePropagator { } private def propagateLowerLimitUp(Scope subScope, Scope superScope) { + var changed = false if (subScope.minNewElements > superScope.minNewElements) { superScope.minNewElements = subScope.minNewElements - return true - } else { - return false + changed = true + } + if (subScope.minNewElementsHeuristic > superScope.minNewElementsHeuristic) { + superScope.minNewElementsHeuristic = subScope.minNewElementsHeuristic + changed = true } + changed } private def propagateUpperLimitDown(Scope subScope, Scope superScope) { @@ -50,16 +54,20 @@ class TypeHierarchyScopePropagator extends ScopePropagator { } private def propagateLowerLimitUp(Scope subScope, PartialInterpretation p) { + var changed = false if (subScope.minNewElements > p.minNewElements) { // println(''' // «(subScope.targetTypeInterpretation as PartialComplexTypeInterpretation).interpretationOf.name» -> nodes // p.minNewElements «p.minNewElements» = subScope.minNewElements «subScope.minNewElements» // ''') p.minNewElements = subScope.minNewElements - return true - } else { - return false + changed = true + } + if (subScope.minNewElementsHeuristic > p.minNewElementsHeuristic) { + p.minNewElementsHeuristic = subScope.minNewElementsHeuristic + changed = true } + changed } private def propagateUpperLimitDown(Scope subScope, PartialInterpretation p) { diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend index 23444956..3b831433 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/Z3PolyhedronSolver.xtend @@ -13,6 +13,7 @@ import java.math.BigDecimal import java.math.MathContext import java.math.RoundingMode import java.util.Map +import org.eclipse.xtend.lib.annotations.Accessors import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor class Z3PolyhedronSolver implements PolyhedronSolver { @@ -28,10 +29,33 @@ class Z3PolyhedronSolver implements PolyhedronSolver { } override createSaturationOperator(Polyhedron polyhedron) { + new DisposingZ3SaturationOperator(this, polyhedron) + } + + def createPersistentSaturationOperator(Polyhedron polyhedron) { new Z3SaturationOperator(polyhedron, lpRelaxation, timeoutSeconds) } } +@FinalFieldsConstructor +class DisposingZ3SaturationOperator implements PolyhedronSaturationOperator { + val Z3PolyhedronSolver solver + @Accessors val Polyhedron polyhedron + + override saturate() { + val persistentOperator = solver.createPersistentSaturationOperator(polyhedron) + try { + persistentOperator.saturate + } finally { + persistentOperator.close + } + } + + override close() throws Exception { + // Nothing to close. + } +} + class Z3SaturationOperator extends AbstractPolyhedronSaturationOperator { static val INFINITY_SYMBOL_NAME = "oo" static val MULT_SYMBOL_NAME = "*" @@ -106,9 +130,9 @@ class Z3SaturationOperator extends AbstractPolyhedronSaturationOperator { IntNum: resultExpr.getInt() RatNum: - floor(resultExpr) + ceil(resultExpr) AlgebraicNum: - floor(resultExpr.toLower(ALGEBRAIC_NUMBER_ROUNDING)) + ceil(resultExpr.toUpper(ALGEBRAIC_NUMBER_ROUNDING)) default: if (isNegativeInfinity(resultExpr)) { null @@ -136,9 +160,9 @@ class Z3SaturationOperator extends AbstractPolyhedronSaturationOperator { IntNum: resultExpr.getInt() RatNum: - ceil(resultExpr) + floor(resultExpr) AlgebraicNum: - ceil(resultExpr.toUpper(ALGEBRAIC_NUMBER_ROUNDING)) + floor(resultExpr.toLower(ALGEBRAIC_NUMBER_ROUNDING)) default: if (isPositiveInfinity(resultExpr)) { null diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend index 1b0db90e..5c35fb54 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternGenerator.xtend @@ -16,8 +16,11 @@ import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.Transform import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeAnalysisResult import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraints +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import java.util.Collection import java.util.HashMap import java.util.Map import org.eclipse.emf.ecore.EAttribute @@ -26,7 +29,6 @@ import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery import org.eclipse.xtend.lib.annotations.Accessors import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy class PatternGenerator { @Accessors(PUBLIC_GETTER) val TypeIndexer typeIndexer // = new TypeIndexer(this) @@ -104,7 +106,9 @@ class PatternGenerator { } def isRepresentative(Relation relation, Relation inverse) { - if (inverse === null) { + if (relation === null) { + return false + } else if (inverse === null) { return true } else { relation.name.compareTo(inverse.name) < 1 @@ -144,7 +148,8 @@ class PatternGenerator { PartialInterpretation emptySolution, Map fqn2PQuery, TypeAnalysisResult typeAnalysisResult, - RelationConstraints constraints + RelationConstraints constraints, + Collection hints ) { return ''' @@ -294,6 +299,13 @@ class PatternGenerator { // 4.3 Relation refinement ////////// «relationRefinementGenerator.generateRefineReference(problem)» + + ////////// + // 5 Hints + ////////// + «FOR hint : hints» + «hint.getAdditionalPatterns(this)» + «ENDFOR» ''' } } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend index eadf0ae0..f5c85524 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/PatternProvider.xtend @@ -26,6 +26,7 @@ import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery import org.eclipse.xtend.lib.annotations.Data import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint @Data class GeneratedPatterns { @@ -62,7 +63,8 @@ class PatternProvider { def generateQueries(LogicProblem problem, PartialInterpretation emptySolution, ModelGenerationStatistics statistics, Set existingQueries, ReasonerWorkspace workspace, TypeInferenceMethod typeInferenceMethod, - ScopePropagatorStrategy scopePropagatorStrategy, RelationConstraints relationConstraints, boolean writeToFile) { + ScopePropagatorStrategy scopePropagatorStrategy, RelationConstraints relationConstraints, + Collection hints, boolean writeToFile) { val fqn2Query = existingQueries.toMap[it.fullyQualifiedName] val PatternGenerator patternGenerator = new PatternGenerator(typeInferenceMethod, scopePropagatorStrategy) val typeAnalysisResult = if (patternGenerator.requiresTypeAnalysis) { @@ -75,7 +77,7 @@ class PatternProvider { null } val baseIndexerFile = patternGenerator.transformBaseProperties(problem, emptySolution, fqn2Query, - typeAnalysisResult, relationConstraints) + typeAnalysisResult, relationConstraints, hints) if (writeToFile) { workspace.writeText('''generated3valued.vql_deactivated''', baseIndexerFile) } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend index fa73c861..d915d47e 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/RelationRefinementGenerator.xtend @@ -44,7 +44,7 @@ class RelationRefinementGenerator { def referRefinementQuery(RelationDeclaration relation, Relation inverseRelation, String relInterpretationName, String inverseInterpretationName, String sourceName, - String targetName) '''find «this.relationRefinementQueryName(relation,inverseRelation)»(problem, interpretation, «relInterpretationName», «IF inverseRelation !== null»inverseInterpretationName, «ENDIF»«sourceName», «targetName»);''' + String targetName) '''find «this.relationRefinementQueryName(relation,inverseRelation)»(problem, interpretation, «relInterpretationName», «IF inverseRelation !== null»«inverseInterpretationName», «ENDIF»«sourceName», «targetName»);''' def getRefineRelationQueries(LogicProblem p) { // val containmentRelations = p.containmentHierarchies.map[containmentRelations].flatten.toSet diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend index 15b5a047..a8a07756 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/patterns/UnfinishedIndexer.xtend @@ -1,5 +1,6 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationMultiplicityConstraint @@ -76,21 +77,26 @@ class UnfinishedIndexer { «IF indexUpperMultiplicities» «IF constraint.constrainsUnrepairable || constraint.constrainsRemainingInverse» private pattern «repairMatchName(constraint)»(problem:LogicProblem, interpretation:PartialInterpretation, source:DefinedElement, target:DefinedElement) { - find interpretation(problem,interpretation); - find mustExist(problem,interpretation,source); - «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"source")» - find mustExist(problem,interpretation,target); - «base.typeIndexer.referInstanceOf(constraint.targetType,Modality::MUST,"target")» - neg «base.referRelation(constraint.relation,"source","target",Modality.MUST,fqn2PQuery)» - «base.referRelation(constraint.relation,"source","target",Modality.MAY,fqn2PQuery)» + «IF base.isRepresentative(constraint.relation, constraint.inverseRelation) && constraint.relation instanceof RelationDeclaration» + «base.relationRefinementGenerator.referRefinementQuery(constraint.relation as RelationDeclaration, constraint.inverseRelation, "_", "_", "source", "target")» + «ELSE» + «IF base.isRepresentative(constraint.inverseRelation, constraint.relation) && constraint.inverseRelation instanceof RelationDeclaration» + «base.relationRefinementGenerator.referRefinementQuery(constraint.inverseRelation as RelationDeclaration, constraint.relation, "_", "_", "target", "source")» + «ELSE» + find interpretation(problem,interpretation); + find mustExist(problem,interpretation,source); + «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"source")» + find mustExist(problem,interpretation,target); + «base.typeIndexer.referInstanceOf(constraint.targetType,Modality::MUST,"target")» + neg «base.referRelation(constraint.relation,"source","target",Modality.MUST,fqn2PQuery)» + «base.referRelation(constraint.relation,"source","target",Modality.MAY,fqn2PQuery)» + «ENDIF» + «ENDIF» } «ENDIF» «IF constraint.constrainsUnrepairable» private pattern «unrepairableMultiplicityName(constraint)»_helper(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement, unrepairableMultiplicity:java Integer) { - find interpretation(problem,interpretation); - find mustExist(problem,interpretation,object); - «base.typeIndexer.referInstanceOf(constraint.sourceType,Modality::MUST,"object")» find «unfinishedMultiplicityName(constraint)»_helper(problem, interpretation, object, missingMultiplicity); numberOfRepairMatches == count find «repairMatchName(constraint)»(problem, interpretation, object, _); check(numberOfRepairMatches < missingMultiplicity); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend index bf816de9..7891ebd8 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/rules/RefinementRuleProvider.xtend @@ -67,7 +67,8 @@ class RefinementRuleProvider { if(containmentRelation != null) { if(inverseRelation!= null) { ruleBuilder.action[match | - //println(name) + statistics.incrementTransformationCount +// println(name) val startTime = System.nanoTime //val problem = match.get(0) as LogicProblem val interpretation = match.get(1) as PartialInterpretation @@ -107,7 +108,8 @@ class RefinementRuleProvider { ] } else { ruleBuilder.action[match | - //println(name) + statistics.incrementTransformationCount +// println(name) val startTime = System.nanoTime //val problem = match.get(0) as LogicProblem val interpretation = match.get(1) as PartialInterpretation @@ -144,6 +146,9 @@ class RefinementRuleProvider { } } else { ruleBuilder.action[match | + statistics.incrementTransformationCount +// println(name) + val startTime = System.nanoTime //val problem = match.get(0) as LogicProblem val interpretation = match.get(1) as PartialInterpretation @@ -198,8 +203,9 @@ class RefinementRuleProvider { .precondition(lhs) if (inverseRelation == null) { ruleBuilder.action [ match | + statistics.incrementTransformationCount val startTime = System.nanoTime - //println(name) +// println(name) // val problem = match.get(0) as LogicProblem // val interpretation = match.get(1) as PartialInterpretation val relationInterpretation = match.get(2) as PartialRelationInterpretation @@ -217,8 +223,9 @@ class RefinementRuleProvider { ] } else { ruleBuilder.action [ match | + statistics.incrementTransformationCount val startTime = System.nanoTime - //println(name) +// println(name) // val problem = match.get(0) as LogicProblem // val interpretation = match.get(1) as PartialInterpretation val relationInterpretation = match.get(2) as PartialRelationInterpretation diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java index 098cc15b..9d0c3fea 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialInterpretation.java @@ -30,6 +30,7 @@ import org.eclipse.emf.ecore.EObject; *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getScopes Scopes}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElements Min New Elements}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMaxNewElements Max New Elements}
  • + *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic Min New Elements Heuristic}
  • * * * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getPartialInterpretation() @@ -255,4 +256,27 @@ public interface PartialInterpretation extends EObject { */ void setMaxNewElements(int value); + /** + * Returns the value of the 'Min New Elements Heuristic' attribute. + * The default value is "0". + * + * + * @return the value of the 'Min New Elements Heuristic' attribute. + * @see #setMinNewElementsHeuristic(int) + * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getPartialInterpretation_MinNewElementsHeuristic() + * @model default="0" required="true" + * @generated + */ + int getMinNewElementsHeuristic(); + + /** + * Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic Min New Elements Heuristic}' attribute. + * + * + * @param value the new value of the 'Min New Elements Heuristic' attribute. + * @see #getMinNewElementsHeuristic() + * @generated + */ + void setMinNewElementsHeuristic(int value); + } // PartialInterpretation diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java index 4f34b9b7..f462ebe4 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/PartialinterpretationPackage.java @@ -166,6 +166,15 @@ public interface PartialinterpretationPackage extends EPackage { */ int PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS = 10; + /** + * The feature id for the 'Min New Elements Heuristic' attribute. + * + * + * @generated + * @ordered + */ + int PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC = 11; + /** * The number of structural features of the 'Partial Interpretation' class. * @@ -173,7 +182,7 @@ public interface PartialinterpretationPackage extends EPackage { * @generated * @ordered */ - int PARTIAL_INTERPRETATION_FEATURE_COUNT = 11; + int PARTIAL_INTERPRETATION_FEATURE_COUNT = 12; /** * The number of operations of the 'Partial Interpretation' class. @@ -912,6 +921,15 @@ public interface PartialinterpretationPackage extends EPackage { */ int SCOPE__TARGET_TYPE_INTERPRETATION = 2; + /** + * The feature id for the 'Min New Elements Heuristic' attribute. + * + * + * @generated + * @ordered + */ + int SCOPE__MIN_NEW_ELEMENTS_HEURISTIC = 3; + /** * The number of structural features of the 'Scope' class. * @@ -919,7 +937,7 @@ public interface PartialinterpretationPackage extends EPackage { * @generated * @ordered */ - int SCOPE_FEATURE_COUNT = 3; + int SCOPE_FEATURE_COUNT = 4; /** * The number of operations of the 'Scope' class. @@ -1357,6 +1375,17 @@ public interface PartialinterpretationPackage extends EPackage { */ EAttribute getPartialInterpretation_MaxNewElements(); + /** + * Returns the meta object for the attribute '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic Min New Elements Heuristic}'. + * + * + * @return the meta object for the attribute 'Min New Elements Heuristic'. + * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation#getMinNewElementsHeuristic() + * @see #getPartialInterpretation() + * @generated + */ + EAttribute getPartialInterpretation_MinNewElementsHeuristic(); + /** * Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialConstantInterpretation Partial Constant Interpretation}'. * @@ -1749,6 +1778,17 @@ public interface PartialinterpretationPackage extends EPackage { */ EReference getScope_TargetTypeInterpretation(); + /** + * Returns the meta object for the attribute '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic Min New Elements Heuristic}'. + * + * + * @return the meta object for the attribute 'Min New Elements Heuristic'. + * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic() + * @see #getScope() + * @generated + */ + EAttribute getScope_MinNewElementsHeuristic(); + /** * Returns the meta object for class '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialPrimitiveInterpretation Partial Primitive Interpretation}'. * @@ -1952,6 +1992,14 @@ public interface PartialinterpretationPackage extends EPackage { */ EAttribute PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS = eINSTANCE.getPartialInterpretation_MaxNewElements(); + /** + * The meta object literal for the 'Min New Elements Heuristic' attribute feature. + * + * + * @generated + */ + EAttribute PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC = eINSTANCE.getPartialInterpretation_MinNewElementsHeuristic(); + /** * The meta object literal for the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialConstantInterpretationImpl Partial Constant Interpretation}' class. * @@ -2278,6 +2326,14 @@ public interface PartialinterpretationPackage extends EPackage { */ EReference SCOPE__TARGET_TYPE_INTERPRETATION = eINSTANCE.getScope_TargetTypeInterpretation(); + /** + * The meta object literal for the 'Min New Elements Heuristic' attribute feature. + * + * + * @generated + */ + EAttribute SCOPE__MIN_NEW_ELEMENTS_HEURISTIC = eINSTANCE.getScope_MinNewElementsHeuristic(); + /** * The meta object literal for the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialPrimitiveInterpretationImpl Partial Primitive Interpretation}' class. * diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java index 155b9f00..a0b58615 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/Scope.java @@ -16,6 +16,7 @@ import org.eclipse.emf.ecore.EObject; *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElements Min New Elements}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMaxNewElements Max New Elements}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getTargetTypeInterpretation Target Type Interpretation}
  • + *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic Min New Elements Heuristic}
  • * * * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getScope() @@ -105,4 +106,27 @@ public interface Scope extends EObject { */ void setTargetTypeInterpretation(PartialTypeInterpratation value); + /** + * Returns the value of the 'Min New Elements Heuristic' attribute. + * The default value is "0". + * + * + * @return the value of the 'Min New Elements Heuristic' attribute. + * @see #setMinNewElementsHeuristic(int) + * @see hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage#getScope_MinNewElementsHeuristic() + * @model default="0" required="true" + * @generated + */ + int getMinNewElementsHeuristic(); + + /** + * Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope#getMinNewElementsHeuristic Min New Elements Heuristic}' attribute. + * + * + * @param value the new value of the 'Min New Elements Heuristic' attribute. + * @see #getMinNewElementsHeuristic() + * @generated + */ + void setMinNewElementsHeuristic(int value); + } // Scope diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java index f5efe02a..ca33dd65 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BinaryElementRelationLinkImpl.java @@ -73,6 +73,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B * * @generated */ + @Override public DefinedElement getParam1() { if (param1 != null && param1.eIsProxy()) { InternalEObject oldParam1 = (InternalEObject)param1; @@ -99,6 +100,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B * * @generated */ + @Override public void setParam1(DefinedElement newParam1) { DefinedElement oldParam1 = param1; param1 = newParam1; @@ -111,6 +113,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B * * @generated */ + @Override public DefinedElement getParam2() { if (param2 != null && param2.eIsProxy()) { InternalEObject oldParam2 = (InternalEObject)param2; @@ -137,6 +140,7 @@ public class BinaryElementRelationLinkImpl extends RelationLinkImpl implements B * * @generated */ + @Override public void setParam2(DefinedElement newParam2) { DefinedElement oldParam2 = param2; param2 = newParam2; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java index e906e07d..5f12d9e4 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/BooleanElementImpl.java @@ -69,6 +69,7 @@ public class BooleanElementImpl extends PrimitiveElementImpl implements BooleanE * * @generated */ + @Override public boolean isValue() { return value; } @@ -78,6 +79,7 @@ public class BooleanElementImpl extends PrimitiveElementImpl implements BooleanE * * @generated */ + @Override public void setValue(boolean newValue) { boolean oldValue = value; value = newValue; @@ -152,7 +154,7 @@ public class BooleanElementImpl extends PrimitiveElementImpl implements BooleanE public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java index ef1a4b96..c8fbe1dd 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/IntegerElementImpl.java @@ -69,6 +69,7 @@ public class IntegerElementImpl extends PrimitiveElementImpl implements IntegerE * * @generated */ + @Override public int getValue() { return value; } @@ -78,6 +79,7 @@ public class IntegerElementImpl extends PrimitiveElementImpl implements IntegerE * * @generated */ + @Override public void setValue(int newValue) { int oldValue = value; value = newValue; @@ -152,7 +154,7 @@ public class IntegerElementImpl extends PrimitiveElementImpl implements IntegerE public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java index 749a03c5..c319a3f4 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkElementImpl.java @@ -83,6 +83,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im * * @generated */ + @Override public int getIndex() { return index; } @@ -92,6 +93,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im * * @generated */ + @Override public void setIndex(int newIndex) { int oldIndex = index; index = newIndex; @@ -104,6 +106,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im * * @generated */ + @Override public DefinedElement getParam() { if (param != null && param.eIsProxy()) { InternalEObject oldParam = (InternalEObject)param; @@ -130,6 +133,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im * * @generated */ + @Override public void setParam(DefinedElement newParam) { DefinedElement oldParam = param; param = newParam; @@ -215,7 +219,7 @@ public class NaryRelationLinkElementImpl extends MinimalEObjectImpl.Container im public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (index: "); result.append(index); result.append(')'); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java index f387ee06..9f7628cf 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/NaryRelationLinkImpl.java @@ -66,6 +66,7 @@ public class NaryRelationLinkImpl extends RelationLinkImpl implements NaryRelati * * @generated */ + @Override public EList getElements() { if (elements == null) { elements = new EObjectContainmentEList(NaryRelationLinkElement.class, this, PartialinterpretationPackage.NARY_RELATION_LINK__ELEMENTS); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java index 07ee282d..c00b4278 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialComplexTypeInterpretationImpl.java @@ -79,6 +79,7 @@ public class PartialComplexTypeInterpretationImpl extends PartialTypeInterpratat * * @generated */ + @Override public EList getSupertypeInterpretation() { if (supertypeInterpretation == null) { supertypeInterpretation = new EObjectResolvingEList(PartialComplexTypeInterpretation.class, this, PartialinterpretationPackage.PARTIAL_COMPLEX_TYPE_INTERPRETATION__SUPERTYPE_INTERPRETATION); @@ -91,6 +92,7 @@ public class PartialComplexTypeInterpretationImpl extends PartialTypeInterpratat * * @generated */ + @Override public TypeDeclaration getInterpretationOf() { if (interpretationOf != null && interpretationOf.eIsProxy()) { InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; @@ -117,6 +119,7 @@ public class PartialComplexTypeInterpretationImpl extends PartialTypeInterpratat * * @generated */ + @Override public void setInterpretationOf(TypeDeclaration newInterpretationOf) { TypeDeclaration oldInterpretationOf = interpretationOf; interpretationOf = newInterpretationOf; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java index 81b2ce8d..6d51f0db 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialConstantInterpretationImpl.java @@ -63,6 +63,7 @@ public class PartialConstantInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public ConstantDeclaration getInterpretationOf() { if (interpretationOf != null && interpretationOf.eIsProxy()) { InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; @@ -89,6 +90,7 @@ public class PartialConstantInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public void setInterpretationOf(ConstantDeclaration newInterpretationOf) { ConstantDeclaration oldInterpretationOf = interpretationOf; interpretationOf = newInterpretationOf; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java index 2d361e8e..855c4abc 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialFunctionInterpretationImpl.java @@ -63,6 +63,7 @@ public class PartialFunctionInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public FunctionDeclaration getInterpretationOf() { if (interpretationOf != null && interpretationOf.eIsProxy()) { InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; @@ -89,6 +90,7 @@ public class PartialFunctionInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public void setInterpretationOf(FunctionDeclaration newInterpretationOf) { FunctionDeclaration oldInterpretationOf = interpretationOf; interpretationOf = newInterpretationOf; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java index bce3e2e0..9afdd8d2 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialInterpretationImpl.java @@ -47,6 +47,7 @@ import org.eclipse.emf.ecore.util.InternalEList; *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getScopes Scopes}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMinNewElements Min New Elements}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMaxNewElements Max New Elements}
  • + *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.PartialInterpretationImpl#getMinNewElementsHeuristic Min New Elements Heuristic}
  • * * * @generated @@ -182,6 +183,26 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl */ protected int maxNewElements = MAX_NEW_ELEMENTS_EDEFAULT; + /** + * The default value of the '{@link #getMinNewElementsHeuristic() Min New Elements Heuristic}' attribute. + * + * + * @see #getMinNewElementsHeuristic() + * @generated + * @ordered + */ + protected static final int MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT = 0; + + /** + * The cached value of the '{@link #getMinNewElementsHeuristic() Min New Elements Heuristic}' attribute. + * + * + * @see #getMinNewElementsHeuristic() + * @generated + * @ordered + */ + protected int minNewElementsHeuristic = MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT; + /** * * @@ -206,6 +227,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public LogicProblem getProblem() { if (problem != null && problem.eIsProxy()) { InternalEObject oldProblem = (InternalEObject)problem; @@ -232,6 +254,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public void setProblem(LogicProblem newProblem) { LogicProblem oldProblem = problem; problem = newProblem; @@ -244,6 +267,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getPartialconstantinterpretation() { if (partialconstantinterpretation == null) { partialconstantinterpretation = new EObjectContainmentEList(PartialConstantInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALCONSTANTINTERPRETATION); @@ -256,6 +280,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getPartialrelationinterpretation() { if (partialrelationinterpretation == null) { partialrelationinterpretation = new EObjectContainmentEList(PartialRelationInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALRELATIONINTERPRETATION); @@ -268,6 +293,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getPartialfunctioninterpretation() { if (partialfunctioninterpretation == null) { partialfunctioninterpretation = new EObjectContainmentEList(PartialFunctionInterpretation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALFUNCTIONINTERPRETATION); @@ -280,6 +306,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getNewElements() { if (newElements == null) { newElements = new EObjectContainmentEList(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__NEW_ELEMENTS); @@ -292,6 +319,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getPartialtypeinterpratation() { if (partialtypeinterpratation == null) { partialtypeinterpratation = new EObjectContainmentEList(PartialTypeInterpratation.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__PARTIALTYPEINTERPRATATION); @@ -304,6 +332,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getOpenWorldElements() { if (openWorldElements == null) { openWorldElements = new EObjectContainmentEList(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__OPEN_WORLD_ELEMENTS); @@ -316,6 +345,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public LogicProblem getProblemConainer() { return problemConainer; } @@ -340,6 +370,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public void setProblemConainer(LogicProblem newProblemConainer) { if (newProblemConainer != problemConainer) { NotificationChain msgs = null; @@ -359,6 +390,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public EList getScopes() { if (scopes == null) { scopes = new EObjectContainmentEList(Scope.class, this, PartialinterpretationPackage.PARTIAL_INTERPRETATION__SCOPES); @@ -371,6 +403,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public int getMinNewElements() { return minNewElements; } @@ -380,6 +413,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public void setMinNewElements(int newMinNewElements) { int oldMinNewElements = minNewElements; minNewElements = newMinNewElements; @@ -392,6 +426,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public int getMaxNewElements() { return maxNewElements; } @@ -401,6 +436,7 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl * * @generated */ + @Override public void setMaxNewElements(int newMaxNewElements) { int oldMaxNewElements = maxNewElements; maxNewElements = newMaxNewElements; @@ -408,6 +444,29 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl eNotify(new ENotificationImpl(this, Notification.SET, PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS, oldMaxNewElements, maxNewElements)); } + /** + * + * + * @generated + */ + @Override + public int getMinNewElementsHeuristic() { + return minNewElementsHeuristic; + } + + /** + * + * + * @generated + */ + @Override + public void setMinNewElementsHeuristic(int newMinNewElementsHeuristic) { + int oldMinNewElementsHeuristic = minNewElementsHeuristic; + minNewElementsHeuristic = newMinNewElementsHeuristic; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC, oldMinNewElementsHeuristic, minNewElementsHeuristic)); + } + /** * * @@ -467,6 +526,8 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl return getMinNewElements(); case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: return getMaxNewElements(); + case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC: + return getMinNewElementsHeuristic(); } return super.eGet(featureID, resolve, coreType); } @@ -520,6 +581,9 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: setMaxNewElements((Integer)newValue); return; + case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC: + setMinNewElementsHeuristic((Integer)newValue); + return; } super.eSet(featureID, newValue); } @@ -565,6 +629,9 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: setMaxNewElements(MAX_NEW_ELEMENTS_EDEFAULT); return; + case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC: + setMinNewElementsHeuristic(MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT); + return; } super.eUnset(featureID); } @@ -599,6 +666,8 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl return minNewElements != MIN_NEW_ELEMENTS_EDEFAULT; case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS: return maxNewElements != MAX_NEW_ELEMENTS_EDEFAULT; + case PartialinterpretationPackage.PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC: + return minNewElementsHeuristic != MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT; } return super.eIsSet(featureID); } @@ -612,11 +681,13 @@ public class PartialInterpretationImpl extends MinimalEObjectImpl.Container impl public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (minNewElements: "); result.append(minNewElements); result.append(", maxNewElements: "); result.append(maxNewElements); + result.append(", minNewElementsHeuristic: "); + result.append(minNewElementsHeuristic); result.append(')'); return result.toString(); } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java index 71aef9af..7ad06504 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialRelationInterpretationImpl.java @@ -106,6 +106,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public RelationDeclaration getInterpretationOf() { if (interpretationOf != null && interpretationOf.eIsProxy()) { InternalEObject oldInterpretationOf = (InternalEObject)interpretationOf; @@ -132,6 +133,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public void setInterpretationOf(RelationDeclaration newInterpretationOf) { RelationDeclaration oldInterpretationOf = interpretationOf; interpretationOf = newInterpretationOf; @@ -144,6 +146,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public EList getRelationlinks() { if (relationlinks == null) { relationlinks = new EObjectContainmentEList(RelationLink.class, this, PartialinterpretationPackage.PARTIAL_RELATION_INTERPRETATION__RELATIONLINKS); @@ -156,6 +159,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public TypeReference getParam1() { if (param1 != null && param1.eIsProxy()) { InternalEObject oldParam1 = (InternalEObject)param1; @@ -182,6 +186,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public void setParam1(TypeReference newParam1) { TypeReference oldParam1 = param1; param1 = newParam1; @@ -194,6 +199,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public TypeReference getParam2() { if (param2 != null && param2.eIsProxy()) { InternalEObject oldParam2 = (InternalEObject)param2; @@ -220,6 +226,7 @@ public class PartialRelationInterpretationImpl extends MinimalEObjectImpl.Contai * * @generated */ + @Override public void setParam2(TypeReference newParam2) { TypeReference oldParam2 = param2; param2 = newParam2; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java index da9b1472..51eabd2c 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialTypeInterpratationImpl.java @@ -76,6 +76,7 @@ public abstract class PartialTypeInterpratationImpl extends MinimalEObjectImpl.C * * @generated */ + @Override public EList getElements() { if (elements == null) { elements = new EObjectResolvingEList(DefinedElement.class, this, PartialinterpretationPackage.PARTIAL_TYPE_INTERPRATATION__ELEMENTS); @@ -88,6 +89,7 @@ public abstract class PartialTypeInterpratationImpl extends MinimalEObjectImpl.C * * @generated */ + @Override public EList getScopes() { if (scopes == null) { scopes = new EObjectWithInverseResolvingEList(Scope.class, this, PartialinterpretationPackage.PARTIAL_TYPE_INTERPRATATION__SCOPES, PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java index af1db8a1..06ca4e37 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationFactoryImpl.java @@ -84,6 +84,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialInterpretation createPartialInterpretation() { PartialInterpretationImpl partialInterpretation = new PartialInterpretationImpl(); return partialInterpretation; @@ -94,6 +95,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialConstantInterpretation createPartialConstantInterpretation() { PartialConstantInterpretationImpl partialConstantInterpretation = new PartialConstantInterpretationImpl(); return partialConstantInterpretation; @@ -104,6 +106,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialRelationInterpretation createPartialRelationInterpretation() { PartialRelationInterpretationImpl partialRelationInterpretation = new PartialRelationInterpretationImpl(); return partialRelationInterpretation; @@ -114,6 +117,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialFunctionInterpretation createPartialFunctionInterpretation() { PartialFunctionInterpretationImpl partialFunctionInterpretation = new PartialFunctionInterpretationImpl(); return partialFunctionInterpretation; @@ -124,6 +128,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public UnaryElementRelationLink createUnaryElementRelationLink() { UnaryElementRelationLinkImpl unaryElementRelationLink = new UnaryElementRelationLinkImpl(); return unaryElementRelationLink; @@ -134,6 +139,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public BinaryElementRelationLink createBinaryElementRelationLink() { BinaryElementRelationLinkImpl binaryElementRelationLink = new BinaryElementRelationLinkImpl(); return binaryElementRelationLink; @@ -144,6 +150,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public NaryRelationLink createNaryRelationLink() { NaryRelationLinkImpl naryRelationLink = new NaryRelationLinkImpl(); return naryRelationLink; @@ -154,6 +161,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public NaryRelationLinkElement createNaryRelationLinkElement() { NaryRelationLinkElementImpl naryRelationLinkElement = new NaryRelationLinkElementImpl(); return naryRelationLinkElement; @@ -164,6 +172,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public BooleanElement createBooleanElement() { BooleanElementImpl booleanElement = new BooleanElementImpl(); return booleanElement; @@ -174,6 +183,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public IntegerElement createIntegerElement() { IntegerElementImpl integerElement = new IntegerElementImpl(); return integerElement; @@ -184,6 +194,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public RealElement createRealElement() { RealElementImpl realElement = new RealElementImpl(); return realElement; @@ -194,6 +205,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public StringElement createStringElement() { StringElementImpl stringElement = new StringElementImpl(); return stringElement; @@ -204,6 +216,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public Scope createScope() { ScopeImpl scope = new ScopeImpl(); return scope; @@ -214,6 +227,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialBooleanInterpretation createPartialBooleanInterpretation() { PartialBooleanInterpretationImpl partialBooleanInterpretation = new PartialBooleanInterpretationImpl(); return partialBooleanInterpretation; @@ -224,6 +238,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialIntegerInterpretation createPartialIntegerInterpretation() { PartialIntegerInterpretationImpl partialIntegerInterpretation = new PartialIntegerInterpretationImpl(); return partialIntegerInterpretation; @@ -234,6 +249,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialRealInterpretation createPartialRealInterpretation() { PartialRealInterpretationImpl partialRealInterpretation = new PartialRealInterpretationImpl(); return partialRealInterpretation; @@ -244,6 +260,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialStringInterpretation createPartialStringInterpretation() { PartialStringInterpretationImpl partialStringInterpretation = new PartialStringInterpretationImpl(); return partialStringInterpretation; @@ -254,6 +271,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialComplexTypeInterpretation createPartialComplexTypeInterpretation() { PartialComplexTypeInterpretationImpl partialComplexTypeInterpretation = new PartialComplexTypeInterpretationImpl(); return partialComplexTypeInterpretation; @@ -264,6 +282,7 @@ public class PartialinterpretationFactoryImpl extends EFactoryImpl implements Pa * * @generated */ + @Override public PartialinterpretationPackage getPartialinterpretationPackage() { return (PartialinterpretationPackage)getEPackage(); } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java index a21dc306..1ea3a11d 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PartialinterpretationPackageImpl.java @@ -227,7 +227,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa /** * Creates, registers, and initializes the Package for this model, and for any others upon which it depends. - * + * *

    This method is used to initialize {@link PartialinterpretationPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * @@ -241,7 +241,8 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa if (isInited) return (PartialinterpretationPackage)EPackage.Registry.INSTANCE.getEPackage(PartialinterpretationPackage.eNS_URI); // Obtain or create and register package - PartialinterpretationPackageImpl thePartialinterpretationPackage = (PartialinterpretationPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof PartialinterpretationPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new PartialinterpretationPackageImpl()); + Object registeredPartialinterpretationPackage = EPackage.Registry.INSTANCE.get(eNS_URI); + PartialinterpretationPackageImpl thePartialinterpretationPackage = registeredPartialinterpretationPackage instanceof PartialinterpretationPackageImpl ? (PartialinterpretationPackageImpl)registeredPartialinterpretationPackage : new PartialinterpretationPackageImpl(); isInited = true; @@ -258,7 +259,6 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa // Mark meta-data to indicate it can't be changed thePartialinterpretationPackage.freeze(); - // Update the registry and return the package EPackage.Registry.INSTANCE.put(PartialinterpretationPackage.eNS_URI, thePartialinterpretationPackage); return thePartialinterpretationPackage; @@ -269,6 +269,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialInterpretation() { return partialInterpretationEClass; } @@ -278,6 +279,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_Problem() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(0); } @@ -287,6 +289,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_Partialconstantinterpretation() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(1); } @@ -296,6 +299,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_Partialrelationinterpretation() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(2); } @@ -305,6 +309,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_Partialfunctioninterpretation() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(3); } @@ -314,6 +319,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_NewElements() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(4); } @@ -323,6 +329,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_Partialtypeinterpratation() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(5); } @@ -332,6 +339,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_OpenWorldElements() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(6); } @@ -341,6 +349,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_ProblemConainer() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(7); } @@ -350,6 +359,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialInterpretation_Scopes() { return (EReference)partialInterpretationEClass.getEStructuralFeatures().get(8); } @@ -359,6 +369,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getPartialInterpretation_MinNewElements() { return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(9); } @@ -368,6 +379,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getPartialInterpretation_MaxNewElements() { return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(10); } @@ -377,6 +389,17 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override + public EAttribute getPartialInterpretation_MinNewElementsHeuristic() { + return (EAttribute)partialInterpretationEClass.getEStructuralFeatures().get(11); + } + + /** + * + * + * @generated + */ + @Override public EClass getPartialConstantInterpretation() { return partialConstantInterpretationEClass; } @@ -386,6 +409,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialConstantInterpretation_InterpretationOf() { return (EReference)partialConstantInterpretationEClass.getEStructuralFeatures().get(0); } @@ -395,6 +419,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialRelationInterpretation() { return partialRelationInterpretationEClass; } @@ -404,6 +429,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialRelationInterpretation_InterpretationOf() { return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(0); } @@ -413,6 +439,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialRelationInterpretation_Relationlinks() { return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(1); } @@ -422,6 +449,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialRelationInterpretation_Param1() { return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(2); } @@ -431,6 +459,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialRelationInterpretation_Param2() { return (EReference)partialRelationInterpretationEClass.getEStructuralFeatures().get(3); } @@ -440,6 +469,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialFunctionInterpretation() { return partialFunctionInterpretationEClass; } @@ -449,6 +479,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialFunctionInterpretation_InterpretationOf() { return (EReference)partialFunctionInterpretationEClass.getEStructuralFeatures().get(0); } @@ -458,6 +489,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialTypeInterpratation() { return partialTypeInterpratationEClass; } @@ -467,6 +499,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialTypeInterpratation_Elements() { return (EReference)partialTypeInterpratationEClass.getEStructuralFeatures().get(0); } @@ -476,6 +509,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialTypeInterpratation_Scopes() { return (EReference)partialTypeInterpratationEClass.getEStructuralFeatures().get(1); } @@ -485,6 +519,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getRelationLink() { return relationLinkEClass; } @@ -494,6 +529,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getUnaryElementRelationLink() { return unaryElementRelationLinkEClass; } @@ -503,6 +539,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getUnaryElementRelationLink_Param1() { return (EReference)unaryElementRelationLinkEClass.getEStructuralFeatures().get(0); } @@ -512,6 +549,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getBinaryElementRelationLink() { return binaryElementRelationLinkEClass; } @@ -521,6 +559,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getBinaryElementRelationLink_Param1() { return (EReference)binaryElementRelationLinkEClass.getEStructuralFeatures().get(0); } @@ -530,6 +569,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getBinaryElementRelationLink_Param2() { return (EReference)binaryElementRelationLinkEClass.getEStructuralFeatures().get(1); } @@ -539,6 +579,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getNaryRelationLink() { return naryRelationLinkEClass; } @@ -548,6 +589,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getNaryRelationLink_Elements() { return (EReference)naryRelationLinkEClass.getEStructuralFeatures().get(0); } @@ -557,6 +599,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getNaryRelationLinkElement() { return naryRelationLinkElementEClass; } @@ -566,6 +609,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getNaryRelationLinkElement_Index() { return (EAttribute)naryRelationLinkElementEClass.getEStructuralFeatures().get(0); } @@ -575,6 +619,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getNaryRelationLinkElement_Param() { return (EReference)naryRelationLinkElementEClass.getEStructuralFeatures().get(1); } @@ -584,6 +629,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPrimitiveElement() { return primitiveElementEClass; } @@ -593,6 +639,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getPrimitiveElement_ValueSet() { return (EAttribute)primitiveElementEClass.getEStructuralFeatures().get(0); } @@ -602,6 +649,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getBooleanElement() { return booleanElementEClass; } @@ -611,6 +659,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getBooleanElement_Value() { return (EAttribute)booleanElementEClass.getEStructuralFeatures().get(0); } @@ -620,6 +669,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getIntegerElement() { return integerElementEClass; } @@ -629,6 +679,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getIntegerElement_Value() { return (EAttribute)integerElementEClass.getEStructuralFeatures().get(0); } @@ -638,6 +689,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getRealElement() { return realElementEClass; } @@ -647,6 +699,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getRealElement_Value() { return (EAttribute)realElementEClass.getEStructuralFeatures().get(0); } @@ -656,6 +709,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getStringElement() { return stringElementEClass; } @@ -665,6 +719,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getStringElement_Value() { return (EAttribute)stringElementEClass.getEStructuralFeatures().get(0); } @@ -674,6 +729,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getScope() { return scopeEClass; } @@ -683,6 +739,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getScope_MinNewElements() { return (EAttribute)scopeEClass.getEStructuralFeatures().get(0); } @@ -692,6 +749,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EAttribute getScope_MaxNewElements() { return (EAttribute)scopeEClass.getEStructuralFeatures().get(1); } @@ -701,6 +759,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getScope_TargetTypeInterpretation() { return (EReference)scopeEClass.getEStructuralFeatures().get(2); } @@ -710,6 +769,17 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override + public EAttribute getScope_MinNewElementsHeuristic() { + return (EAttribute)scopeEClass.getEStructuralFeatures().get(3); + } + + /** + * + * + * @generated + */ + @Override public EClass getPartialPrimitiveInterpretation() { return partialPrimitiveInterpretationEClass; } @@ -719,6 +789,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialBooleanInterpretation() { return partialBooleanInterpretationEClass; } @@ -728,6 +799,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialIntegerInterpretation() { return partialIntegerInterpretationEClass; } @@ -737,6 +809,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialRealInterpretation() { return partialRealInterpretationEClass; } @@ -746,6 +819,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialStringInterpretation() { return partialStringInterpretationEClass; } @@ -755,6 +829,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EClass getPartialComplexTypeInterpretation() { return partialComplexTypeInterpretationEClass; } @@ -764,6 +839,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialComplexTypeInterpretation_SupertypeInterpretation() { return (EReference)partialComplexTypeInterpretationEClass.getEStructuralFeatures().get(0); } @@ -773,6 +849,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public EReference getPartialComplexTypeInterpretation_InterpretationOf() { return (EReference)partialComplexTypeInterpretationEClass.getEStructuralFeatures().get(1); } @@ -782,6 +859,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa * * @generated */ + @Override public PartialinterpretationFactory getPartialinterpretationFactory() { return (PartialinterpretationFactory)getEFactoryInstance(); } @@ -817,6 +895,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa createEReference(partialInterpretationEClass, PARTIAL_INTERPRETATION__SCOPES); createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS); createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MAX_NEW_ELEMENTS); + createEAttribute(partialInterpretationEClass, PARTIAL_INTERPRETATION__MIN_NEW_ELEMENTS_HEURISTIC); partialConstantInterpretationEClass = createEClass(PARTIAL_CONSTANT_INTERPRETATION); createEReference(partialConstantInterpretationEClass, PARTIAL_CONSTANT_INTERPRETATION__INTERPRETATION_OF); @@ -869,6 +948,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa createEAttribute(scopeEClass, SCOPE__MIN_NEW_ELEMENTS); createEAttribute(scopeEClass, SCOPE__MAX_NEW_ELEMENTS); createEReference(scopeEClass, SCOPE__TARGET_TYPE_INTERPRETATION); + createEAttribute(scopeEClass, SCOPE__MIN_NEW_ELEMENTS_HEURISTIC); partialPrimitiveInterpretationEClass = createEClass(PARTIAL_PRIMITIVE_INTERPRETATION); @@ -945,6 +1025,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa initEReference(getPartialInterpretation_Scopes(), this.getScope(), null, "scopes", null, 0, -1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getPartialInterpretation_MinNewElements(), ecorePackage.getEInt(), "minNewElements", "0", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getPartialInterpretation_MaxNewElements(), ecorePackage.getEInt(), "maxNewElements", "-1", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); + initEAttribute(getPartialInterpretation_MinNewElementsHeuristic(), ecorePackage.getEInt(), "minNewElementsHeuristic", "0", 1, 1, PartialInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(partialConstantInterpretationEClass, PartialConstantInterpretation.class, "PartialConstantInterpretation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getPartialConstantInterpretation_InterpretationOf(), theLogiclanguagePackage.getConstantDeclaration(), null, "interpretationOf", null, 1, 1, PartialConstantInterpretation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); @@ -997,6 +1078,7 @@ public class PartialinterpretationPackageImpl extends EPackageImpl implements Pa initEAttribute(getScope_MinNewElements(), ecorePackage.getEInt(), "minNewElements", "0", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getScope_MaxNewElements(), ecorePackage.getEInt(), "maxNewElements", "-1", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getScope_TargetTypeInterpretation(), this.getPartialTypeInterpratation(), this.getPartialTypeInterpratation_Scopes(), "targetTypeInterpretation", null, 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); + initEAttribute(getScope_MinNewElementsHeuristic(), ecorePackage.getEInt(), "minNewElementsHeuristic", "0", 1, 1, Scope.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(partialPrimitiveInterpretationEClass, PartialPrimitiveInterpretation.class, "PartialPrimitiveInterpretation", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java index 29a1e1be..a8ef81b0 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/PrimitiveElementImpl.java @@ -71,6 +71,7 @@ public abstract class PrimitiveElementImpl extends DefinedElementImpl implements * * @generated */ + @Override public boolean isValueSet() { return valueSet; } @@ -80,6 +81,7 @@ public abstract class PrimitiveElementImpl extends DefinedElementImpl implements * * @generated */ + @Override public void setValueSet(boolean newValueSet) { boolean oldValueSet = valueSet; valueSet = newValueSet; @@ -154,7 +156,7 @@ public abstract class PrimitiveElementImpl extends DefinedElementImpl implements public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (valueSet: "); result.append(valueSet); result.append(')'); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java index 0361a3e9..67cff5a2 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/RealElementImpl.java @@ -71,6 +71,7 @@ public class RealElementImpl extends PrimitiveElementImpl implements RealElement * * @generated */ + @Override public BigDecimal getValue() { return value; } @@ -80,6 +81,7 @@ public class RealElementImpl extends PrimitiveElementImpl implements RealElement * * @generated */ + @Override public void setValue(BigDecimal newValue) { BigDecimal oldValue = value; value = newValue; @@ -154,7 +156,7 @@ public class RealElementImpl extends PrimitiveElementImpl implements RealElement public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java index d8ade871..a1b6de35 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/ScopeImpl.java @@ -26,6 +26,7 @@ import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; *

  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMinNewElements Min New Elements}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMaxNewElements Max New Elements}
  • *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getTargetTypeInterpretation Target Type Interpretation}
  • + *
  • {@link hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.impl.ScopeImpl#getMinNewElementsHeuristic Min New Elements Heuristic}
  • * * * @generated @@ -81,6 +82,26 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { */ protected PartialTypeInterpratation targetTypeInterpretation; + /** + * The default value of the '{@link #getMinNewElementsHeuristic() Min New Elements Heuristic}' attribute. + * + * + * @see #getMinNewElementsHeuristic() + * @generated + * @ordered + */ + protected static final int MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT = 0; + + /** + * The cached value of the '{@link #getMinNewElementsHeuristic() Min New Elements Heuristic}' attribute. + * + * + * @see #getMinNewElementsHeuristic() + * @generated + * @ordered + */ + protected int minNewElementsHeuristic = MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT; + /** * * @@ -105,6 +126,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { * * @generated */ + @Override public int getMinNewElements() { return minNewElements; } @@ -114,6 +136,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { * * @generated */ + @Override public void setMinNewElements(int newMinNewElements) { int oldMinNewElements = minNewElements; minNewElements = newMinNewElements; @@ -126,6 +149,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { * * @generated */ + @Override public int getMaxNewElements() { return maxNewElements; } @@ -135,6 +159,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { * * @generated */ + @Override public void setMaxNewElements(int newMaxNewElements) { int oldMaxNewElements = maxNewElements; maxNewElements = newMaxNewElements; @@ -147,6 +172,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { * * @generated */ + @Override public PartialTypeInterpratation getTargetTypeInterpretation() { if (targetTypeInterpretation != null && targetTypeInterpretation.eIsProxy()) { InternalEObject oldTargetTypeInterpretation = (InternalEObject)targetTypeInterpretation; @@ -188,6 +214,7 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { * * @generated */ + @Override public void setTargetTypeInterpretation(PartialTypeInterpratation newTargetTypeInterpretation) { if (newTargetTypeInterpretation != targetTypeInterpretation) { NotificationChain msgs = null; @@ -202,6 +229,29 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { eNotify(new ENotificationImpl(this, Notification.SET, PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION, newTargetTypeInterpretation, newTargetTypeInterpretation)); } + /** + * + * + * @generated + */ + @Override + public int getMinNewElementsHeuristic() { + return minNewElementsHeuristic; + } + + /** + * + * + * @generated + */ + @Override + public void setMinNewElementsHeuristic(int newMinNewElementsHeuristic) { + int oldMinNewElementsHeuristic = minNewElementsHeuristic; + minNewElementsHeuristic = newMinNewElementsHeuristic; + if (eNotificationRequired()) + eNotify(new ENotificationImpl(this, Notification.SET, PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC, oldMinNewElementsHeuristic, minNewElementsHeuristic)); + } + /** * * @@ -247,6 +297,8 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: if (resolve) return getTargetTypeInterpretation(); return basicGetTargetTypeInterpretation(); + case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC: + return getMinNewElementsHeuristic(); } return super.eGet(featureID, resolve, coreType); } @@ -268,6 +320,9 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: setTargetTypeInterpretation((PartialTypeInterpratation)newValue); return; + case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC: + setMinNewElementsHeuristic((Integer)newValue); + return; } super.eSet(featureID, newValue); } @@ -289,6 +344,9 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: setTargetTypeInterpretation((PartialTypeInterpratation)null); return; + case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC: + setMinNewElementsHeuristic(MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT); + return; } super.eUnset(featureID); } @@ -307,6 +365,8 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { return maxNewElements != MAX_NEW_ELEMENTS_EDEFAULT; case PartialinterpretationPackage.SCOPE__TARGET_TYPE_INTERPRETATION: return targetTypeInterpretation != null; + case PartialinterpretationPackage.SCOPE__MIN_NEW_ELEMENTS_HEURISTIC: + return minNewElementsHeuristic != MIN_NEW_ELEMENTS_HEURISTIC_EDEFAULT; } return super.eIsSet(featureID); } @@ -320,11 +380,13 @@ public class ScopeImpl extends MinimalEObjectImpl.Container implements Scope { public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (minNewElements: "); result.append(minNewElements); result.append(", maxNewElements: "); result.append(maxNewElements); + result.append(", minNewElementsHeuristic: "); + result.append(minNewElementsHeuristic); result.append(')'); return result.toString(); } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java index f207401d..0242c9b2 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/StringElementImpl.java @@ -69,6 +69,7 @@ public class StringElementImpl extends PrimitiveElementImpl implements StringEle * * @generated */ + @Override public String getValue() { return value; } @@ -78,6 +79,7 @@ public class StringElementImpl extends PrimitiveElementImpl implements StringEle * * @generated */ + @Override public void setValue(String newValue) { String oldValue = value; value = newValue; @@ -152,7 +154,7 @@ public class StringElementImpl extends PrimitiveElementImpl implements StringEle public String toString() { if (eIsProxy()) return super.toString(); - StringBuffer result = new StringBuffer(super.toString()); + StringBuilder result = new StringBuilder(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java index 2cb56323..e76a89b7 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/ecore-gen/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/partialinterpretation/impl/UnaryElementRelationLinkImpl.java @@ -62,6 +62,7 @@ public class UnaryElementRelationLinkImpl extends RelationLinkImpl implements Un * * @generated */ + @Override public DefinedElement getParam1() { if (param1 != null && param1.eIsProxy()) { InternalEObject oldParam1 = (InternalEObject)param1; @@ -88,6 +89,7 @@ public class UnaryElementRelationLinkImpl extends RelationLinkImpl implements Un * * @generated */ + @Override public void setParam1(DefinedElement newParam1) { DefinedElement oldParam1 = param1; param1 = newParam1; diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore index acf82a3f..47d54258 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.ecore @@ -27,6 +27,9 @@ eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EInt" defaultValueLiteral="0"/> + + diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel index 2ac0a4f3..daeaf594 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/model/PartialInterpretation.genmodel @@ -18,7 +18,10 @@ - + + + + @@ -33,9 +36,8 @@ - - + @@ -50,6 +52,7 @@ + @@ -70,11 +73,16 @@ + + + + + diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/Descriptor.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/Descriptor.xtend index c7c1ad77..e4bdb086 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/Descriptor.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/Descriptor.xtend @@ -60,6 +60,10 @@ import org.eclipse.xtend2.lib.StringConcatenationClient return this.dataHash.hashCode } + override equals(Object other) { + other.class == LocalNodeDescriptor && (other as AbstractNodeDescriptor).hashCode == hashCode + } + override protected prettyPrint() { '''(«dataHash»)[«IF id !== null»id = "«id»"«IF types === null || !types.empty», «ENDIF»«ENDIF»«IF types === null»TYPES = null«ELSE»«FOR type : types SEPARATOR ", "»«type»«ENDFOR»«ENDIF»]''' } @@ -143,6 +147,10 @@ import org.eclipse.xtend2.lib.StringConcatenationClient return this.dataHash.hashCode } + override equals(Object other) { + other.class == FurtherNodeDescriptor && (other as AbstractNodeDescriptor).hashCode == hashCode + } + override prettyPrint() { ''' («dataHash»)[ diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/NeighbourhoodOptions.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/NeighbourhoodOptions.xtend index efc89803..c6e03f75 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/NeighbourhoodOptions.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/NeighbourhoodOptions.xtend @@ -7,12 +7,12 @@ import org.eclipse.xtend.lib.annotations.Data @Data class NeighbourhoodOptions { - public static val FixPointRage = -1 + public static val FixPointRange = -1 public static val GraphWidthRange = -2 public static val FullParallels = Integer.MAX_VALUE public static val MaxNumbers = Integer.MAX_VALUE - public static val DEFAULT = new NeighbourhoodOptions(GraphWidthRange, FullParallels, MaxNumbers, null, null) + public static val DEFAULT = new NeighbourhoodOptions(FixPointRange, FullParallels, MaxNumbers, null, null) val int range val int parallels diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2Hash.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2Hash.xtend index d474877d..ddf7d712 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2Hash.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2Hash.xtend @@ -5,7 +5,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.DefinedElement class PartialInterpretation2Hash extends PartialInterpretation2NeighbourhoodRepresentation{ - protected new() { + new() { super(false, true) } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2NeighbourhoodRepresentation.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2NeighbourhoodRepresentation.xtend index a0382e8e..3048167e 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2NeighbourhoodRepresentation.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage/src/hu/bme/mit/inf/dslreasoner/viatrasolver/partialinterpretationlanguage/neighbourhood/PartialInterpretation2NeighbourhoodRepresentation.xtend @@ -25,7 +25,7 @@ abstract class PartialInterpretation2NeighbourhoodRepresentation nodeRepresentations = null - var Map modelRepresentation = null +class NeighbourhoodBasedHashStateCoderFactory extends AbstractNeighbourhoodBasedStateCoderFactory { + new() { + } new(NeighbourhoodOptions options) { super(options) } + override protected doCreateStateCoder(NeighbourhoodOptions options) { + new NeighbourhoodBasedPartialInterpretationStateCoder(new PartialInterpretation2Hash, options) + } +} + +class NeighbourhoodBasedPartialInterpretationStateCoder extends AbstractNeighbourhoodBasedPartialInterpretationStateCoder { + val PartialInterpretation2NeighbourhoodRepresentation calculator + var Map nodeRepresentations = null + var ModelRep modelRepresentation = null + + new(PartialInterpretation2NeighbourhoodRepresentation calculator, NeighbourhoodOptions options) { + super(options) + this.calculator = calculator + } + override protected isRefreshNeeded() { nodeRepresentations === null || modelRepresentation === null } 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 1abde0a8..aa02cd30 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 @@ -12,12 +12,15 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.AbstractNeighbourhoodBasedStateCoderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.IdentifierBasedStateCoderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedHashStateCoderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.PairwiseNeighbourhoodBasedStateCoderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BasicScopeGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.InconsistentScopeGlobalConstraint @@ -39,7 +42,6 @@ import org.eclipse.viatra.dse.api.DesignSpaceExplorer import org.eclipse.viatra.dse.api.DesignSpaceExplorer.DseLoggingLevel import org.eclipse.viatra.dse.solutionstore.SolutionStore import org.eclipse.viatra.dse.statecode.IStateCoderFactory -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedStateCoderFactory class ViatraReasoner extends LogicReasoner { val PartialInterpretationInitialiser initialiser = new PartialInterpretationInitialiser() @@ -71,6 +73,11 @@ class ViatraReasoner extends LogicReasoner { workspace.writeModel(emptySolution, "init.partialmodel") } emptySolution.problemConainer = problem + var BasicScopeGlobalConstraint basicScopeGlobalConstraint = null + if (viatraConfig.scopePropagatorStrategy == ScopePropagatorStrategy.None) { + basicScopeGlobalConstraint = new BasicScopeGlobalConstraint(emptySolution) + emptySolution.scopes.clear + } val method = modelGenerationMethodProvider.createModelGenerationMethod( problem, @@ -79,11 +86,12 @@ class ViatraReasoner extends LogicReasoner { viatraConfig.nameNewElements, viatraConfig.typeInferenceMethod, viatraConfig.scopePropagatorStrategy, + viatraConfig.hints, viatraConfig.documentationLevel ) dse.addObjective(new ModelGenerationCompositeObjective( - new ScopeObjective, + basicScopeGlobalConstraint ?: new ScopeObjective, method.unfinishedMultiplicities.map[new UnfinishedMultiplicityObjective(it)], wf2ObjectiveConverter.createCompletenessObjective(method.unfinishedWF) )) @@ -132,6 +140,9 @@ class ViatraReasoner extends LogicReasoner { dse.addGlobalConstraint(wf2ObjectiveConverter.createInvalidationGlobalConstraint(method.invalidWF)) dse.addGlobalConstraint(new SurelyViolatedObjectiveGlobalConstraint(solutionSaver)) dse.addGlobalConstraint(new InconsistentScopeGlobalConstraint) + if (basicScopeGlobalConstraint !== null) { + dse.addGlobalConstraint(basicScopeGlobalConstraint) + } for (additionalConstraint : viatraConfig.searchSpaceConstraints.additionalGlobalConstraints) { dse.addGlobalConstraint(additionalConstraint.apply(method)) } @@ -140,7 +151,7 @@ class ViatraReasoner extends LogicReasoner { val IStateCoderFactory statecoder = switch (viatraConfig.stateCoderStrategy) { case Neighbourhood: - new NeighbourhoodBasedStateCoderFactory + new NeighbourhoodBasedHashStateCoderFactory case PairwiseNeighbourhood: new PairwiseNeighbourhoodBasedStateCoderFactory default: @@ -215,10 +226,18 @@ class ViatraReasoner extends LogicReasoner { it.name = "Decisions" it.value = method.statistics.decisionsTried ] + it.entries += createIntStatisticEntry => [ + it.name = "Transformations" + it.value = method.statistics.transformationInvocations + ] it.entries += createIntStatisticEntry => [ it.name = "ScopePropagations" it.value = method.statistics.scopePropagatorInvocations ] + it.entries += createIntStatisticEntry => [ + it.name = "ScopePropagationsSolverCalls" + it.value = method.statistics.scopePropagatorSolverInvocations + ] if (diversityChecker.isActive) { it.entries += createIntStatisticEntry => [ it.name = "SolutionDiversityCheckTime" 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 a5f42a5f..6f38d261 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 @@ -16,6 +16,7 @@ import java.util.LinkedList import java.util.List import java.util.Set import org.eclipse.xtext.xbase.lib.Functions.Function1 +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint enum StateCoderStrategy { Neighbourhood, @@ -56,6 +57,8 @@ class ViatraReasonerConfiguration extends LogicSolverConfiguration { public var ScopePropagatorStrategy scopePropagatorStrategy = new ScopePropagatorStrategy.Polyhedral( PolyhedralScopePropagatorConstraints.Relational, PolyhedralScopePropagatorSolver.Clp) + + public var List hints = newArrayList public var List costObjectives = newArrayList } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend new file mode 100644 index 00000000..67f447ed --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/BasicScopeGlobalConstraint.xtend @@ -0,0 +1,103 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse + +import com.google.common.collect.ImmutableList +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation +import java.util.Comparator +import java.util.List +import org.eclipse.viatra.dse.base.ThreadContext +import org.eclipse.viatra.dse.objectives.Comparators +import org.eclipse.viatra.dse.objectives.IGlobalConstraint +import org.eclipse.viatra.dse.objectives.IObjective +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor + +class BasicScopeGlobalConstraint implements IGlobalConstraint, IObjective { + val PartialInterpretation p + val List assertions + + new(PartialInterpretation p) { + this.p = p + assertions = ImmutableList.copyOf(p.scopes.map [ + val currentSize = targetTypeInterpretation.elements.size + val minElements = minNewElements + currentSize + val maxElements = if (maxNewElements < 0) { + -1 + } else { + maxNewElements + currentSize + } + new ScopeAssertion(minElements, maxElements, targetTypeInterpretation) + ]) + } + + override init(ThreadContext context) { + if (context.model != p) { + throw new IllegalArgumentException( + "Partial model must be passed to the constructor of BasicScopeGlobalConstraint") + } + } + + override checkGlobalConstraint(ThreadContext context) { + assertions.forall[upperBoundSatisfied] + } + + override getFitness(ThreadContext context) { + var double fitness = p.minNewElements + for (assertion : assertions) { + if (!assertion.lowerBoundSatisfied) { + fitness += 1 + } + } + fitness + } + + override satisifiesHardObjective(Double fitness) { + fitness <= 0.01 + } + + override BasicScopeGlobalConstraint createNew() { + this + } + + override getName() { + class.name + } + + override getComparator() { + Comparators.LOWER_IS_BETTER + } + + override getLevel() { + 2 + } + + override isHardObjective() { + true + } + + override setComparator(Comparator comparator) { + throw new UnsupportedOperationException + } + + override setLevel(int level) { + throw new UnsupportedOperationException + } + + @FinalFieldsConstructor + private static class ScopeAssertion { + val int lowerBound + val int upperBound + val PartialTypeInterpratation typeDefinitions + + private def getCount() { + typeDefinitions.elements.size + } + + private def isLowerBoundSatisfied() { + count >= lowerBound + } + + private def isUpperBoundSatisfied() { + upperBound < 0 || count <= upperBound + } + } +} 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 5af7fc69..081e48fa 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 @@ -255,7 +255,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { activationIds = new ArrayList(context.getUntraversedActivationIds()); Collections.shuffle(activationIds); } catch (NullPointerException e) { - logger.warn("Unexpected state code: " + context.getDesignSpaceManager().getCurrentState()); +// logger.warn("Unexpected state code: " + context.getDesignSpaceManager().getCurrentState()); numberOfStatecoderFail++; activationIds = Collections.emptyList(); } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend index 9a33753c..2976bebe 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ModelGenerationCompositeObjective.xtend @@ -59,7 +59,7 @@ class ModelGenerationCompositeObjective implements IThreeValuedObjective { } sum += multiplicity sum += unfinishedWFsFitness // *0.5 - // println('''Sum=«sum»|Scope=«scopeFitnes»|Multiplicity=«multiplicity»|WFs=«unfinishedWFsFitness»''') +// println('''Sum=«sum»|Scope=«scopeFitnes»|Multiplicity=«multiplicity»|WFs=«unfinishedWFsFitness»''') return sum } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend index 69efe0d7..e7967b00 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ScopeObjective.xtend @@ -23,9 +23,9 @@ class ScopeObjective implements IObjective{ override getFitness(ThreadContext context) { val interpretation = context.model as PartialInterpretation - var res = interpretation.minNewElements.doubleValue + var res = interpretation.minNewElementsHeuristic.doubleValue for(scope : interpretation.scopes) { - res += scope.minNewElements*2 + res += scope.minNewElementsHeuristic*2 } return res } diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend index bf34aeeb..1b61ffa5 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedWFObjective.xtend @@ -14,41 +14,51 @@ import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher class UnfinishedWFObjective implements IObjective { Collection>> unfinishedWFs val List> matchers - - new(Collection>> unfinishedWFs) { + + new( + Collection>> unfinishedWFs) { this.unfinishedWFs = unfinishedWFs matchers = new ArrayList(unfinishedWFs.size) } + override getName() '''unfinishedWFs''' + override createNew() { return new UnfinishedWFObjective(unfinishedWFs) } + override init(ThreadContext context) { - val engine = context.queryEngine//ViatraQueryEngine.on(new EMFScope(context.model)) - for(unfinishedWF : unfinishedWFs) { + val engine = context.queryEngine // ViatraQueryEngine.on(new EMFScope(context.model)) + for (unfinishedWF : unfinishedWFs) { matchers += unfinishedWF.getMatcher(engine) } } - + override getComparator() { Comparators.LOWER_IS_BETTER } + override getFitness(ThreadContext context) { var sumOfMatches = 0 - for(matcher : matchers) { + for (matcher : matchers) { val number = matcher.countMatches - //println('''«matcher.patternName» = «number»''') - sumOfMatches+=number +// if (number > 0) { +// println('''«matcher.patternName» = «number»''') +// } + sumOfMatches += number } return sumOfMatches.doubleValue } - + override getLevel() { 2 } + override isHardObjective() { true } - override satisifiesHardObjective(Double fitness) { return fitness <=0.01 } - + + override satisifiesHardObjective(Double fitness) { return fitness <= 0.01 } + override setComparator(Comparator comparator) { throw new UnsupportedOperationException() } + override setLevel(int level) { throw new UnsupportedOperationException() } -} \ No newline at end of file +} 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 6bffeb59..74500cc2 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 @@ -42,7 +42,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { private def saveBestSolutionOnly(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { val fitness = context.lastFitness - if (!fitness.satisifiesHardObjectives) { + if (!shouldSaveSolution(fitness, context)) { return false } val dominatedTrajectories = newArrayList @@ -83,7 +83,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { private def saveAnyDiverseSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { val fitness = context.lastFitness - if (!fitness.satisifiesHardObjectives) { + if (!shouldSaveSolution(fitness, context)) { return false } if (!diversityChecker.newSolution(context, id, emptyList)) { @@ -92,7 +92,12 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { basicSaveSolution(context, id, solutionTrajectory, fitness) } - private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, Fitness fitness) { + private def shouldSaveSolution(Fitness fitness, ThreadContext context) { + return fitness.satisifiesHardObjectives + } + + private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, + Fitness fitness) { var boolean solutionSaved = false var dseSolution = solutionsCollection.get(id) if (dseSolution === null) { diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/META-INF/MANIFEST.MF b/Tests/hu.bme.mit.inf.dslreasoner.run/META-INF/MANIFEST.MF index cc274c7c..fe223d4a 100644 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/META-INF/MANIFEST.MF +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/META-INF/MANIFEST.MF @@ -28,8 +28,10 @@ Require-Bundle: hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlan hu.bme.mit.inf.dslreasoner.visualisation;bundle-version="1.0.0", hu.bme.mit.inf.dslreasoner.domains.alloyexamples;bundle-version="1.0.0", org.eclipse.collections;bundle-version="9.2.0", - org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.2.0", - org.eclipse.viatra.query.runtime.rete;bundle-version="2.2.0", - org.objectweb.asm;bundle-version="7.0.0" + org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.0.0", + org.eclipse.viatra.query.runtime.rete;bundle-version="2.0.0", + org.objectweb.asm;bundle-version="7.0.0", + com.google.gson;bundle-version="2.8.2", + hu.bme.mit.inf.dslreasoner.domains.satellite;bundle-version="0.1.0" Import-Package: org.apache.log4j Bundle-RequiredExecutionEnvironment: JavaSE-1.8 diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/configs/FAM_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/FAM_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json new file mode 100644 index 00000000..26df3c74 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/FAM_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json @@ -0,0 +1,13 @@ +{ + "inputPath": "initialModels", + "outputPath": "outputModels", + "timeout": 1200, + "saveModels": true, + "warmupIterations": 0, + "iterations": 1, + "domain": "FAM", + "scope": "none", + "sizes": [500], + "solver": "ViatraSolver", + "scopePropagator": "basic" +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/configs/Yakindu_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/Yakindu_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json new file mode 100644 index 00000000..5f8a01b1 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/Yakindu_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json @@ -0,0 +1,16 @@ +{ + "inputPath": "initialModels", + "outputPath": "outputModels", + "timeout": 1200, + "saveModels": false, + "warmupIterations": 0, + "iterations": 5, + "domain": "Yakindu", + "scope": "quantiles", + "sizes": [100], + "solver": "ViatraSolver", + "scopePropagator": "polyhedral", + "propagatedConstraints": "hints", + "polyhedronSolver": "Clp", + "scopeHeuristic": "basic" +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/configs/ecore_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/ecore_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json new file mode 100644 index 00000000..42073422 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/ecore_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json @@ -0,0 +1,15 @@ +{ + "inputPath": "initialModels", + "outputPath": "outputModels", + "timeout": 1200, + "saveModels": true, + "warmupIterations": 0, + "iterations": 5, + "domain": "ecore", + "scope": "quantiles", + "sizes": [100], + "solver": "ViatraSolver", + "scopePropagator": "polyhedral", + "propagatedConstraints": "relations", + "polyhedronSolver": "Clp" +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/configs/fs_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/fs_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json new file mode 100644 index 00000000..d7955ddd --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/fs_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json @@ -0,0 +1,15 @@ +{ + "inputPath": "initialModels", + "outputPath": "outputModels", + "timeout": 1200, + "saveModels": true, + "warmupIterations": 1, + "iterations": 1, + "domain": "fs", + "scope": "useful", + "sizes": [50, 100, 150, 200, 250, 300, 350, 400, 450, 500], + "solver": "ViatraSolver", + "scopePropagator": "polyhedral", + "propagatedConstraints": "relations", + "polyhedronSolver": "Clp" +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/configs/satellite_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/satellite_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json new file mode 100644 index 00000000..474962e7 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/configs/satellite_useful_ViatraSolver_polyhedral_typeHierarchy_Clp.json @@ -0,0 +1,17 @@ +{ + "inputPath": "initialModels", + "outputPath": "outputModels", + "timeout": 1200, + "saveModels": true, + "saveTemporaryFiles": true, + "warmupIterations": 0, + "iterations": 1, + "domain": "satellite", + "scope": "quantiles", + "sizes": [50], + "solver": "ViatraSolver", + "scopePropagator": "polyhedral", + "propagatedConstraints": "hints", + "polyhedronSolver": "Clp", + "scopeHeuristic": "polyhedral" +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/initialModels/satellite.xmi b/Tests/hu.bme.mit.inf.dslreasoner.run/initialModels/satellite.xmi new file mode 100644 index 00000000..77f6ecfd --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/initialModels/satellite.xmi @@ -0,0 +1,14 @@ + + + + + + + diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/CountMatches.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/CountMatches.xtend deleted file mode 100644 index 02caf9dd..00000000 --- a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/CountMatches.xtend +++ /dev/null @@ -1,176 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.run - -import hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph.yakindumm.YakindummPackage -import hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.mutated.Mutated -import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace -import java.io.File -import java.util.ArrayList -import java.util.Collection -import java.util.Comparator -import java.util.HashMap -import java.util.List -import java.util.Map -import java.util.TreeSet -import org.eclipse.emf.ecore.EObject -import org.eclipse.emf.ecore.resource.Resource -import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl -import org.eclipse.viatra.query.runtime.api.IPatternMatch -import org.eclipse.viatra.query.runtime.api.IQuerySpecification -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine -import org.eclipse.viatra.query.runtime.emf.EMFScope - -class QueryComparator implements Comparator>{ - - override compare(IQuerySpecification arg0, IQuerySpecification arg1) { - arg0.fullyQualifiedName.compareTo(arg1.fullyQualifiedName) - } -} - -class CountMatches { - var static List> wfPatterns; - var static Map,IQuerySpecification> query2Reference - - def static void main(String[] args) { - YakindummPackage.eINSTANCE.eClass - Resource.Factory.Registry.INSTANCE.extensionToFactoryMap.put("*",new XMIResourceFactoryImpl) - - wfPatterns = Mutated.instance.specifications.toList; - //wfPatterns = wfPatterns.filter[it.allAnnotations.exists[it.name == "Constraint"]].toList - wfPatterns.sort(new QueryComparator) - - val groupName2Representant = new HashMap - query2Reference = new HashMap - for(wfPattern : wfPatterns) { - val groupName = wfPattern.groupName - if(groupName2Representant.containsKey(groupName)) { - val representant = groupName2Representant.get(groupName) - query2Reference.put(wfPattern,representant) - } else { - groupName2Representant.put(groupName,wfPattern) - } - } - - - println('''modelpath;run;model;« - FOR wfPattern:wfPatterns SEPARATOR ";"»#(« - wfPattern.fullyQualifiedName.split("\\.").last»);hash(« - wfPattern.fullyQualifiedName.split("\\.").last»)«ENDFOR»;« - FOR mutant : wfPatterns.filter[query2Reference.keySet.contains(it)] SEPARATOR ';'»diff(« - mutant.fullyQualifiedName.split("\\.").last»)«ENDFOR»''' - ) - countMatches('''D:/FASE18Meas/RemoHF''') - } - - def private static simpleName(IQuerySpecification wfPattern) { - wfPattern.fullyQualifiedName.split("\\.").last - } - def private static groupName(IQuerySpecification wfPattern) { - wfPattern.simpleName.split('_').head - } - - def static void countMatches(String path) { - val file = new File(path) - if(file.isDirectory) { - for(subFileName : file.list) { - (path + "/" + subFileName).countMatches - } - } else if(file.isFile) { - if(path.endsWith("xmi")) { - countMatches(file,path) - } - } - } - - def static void countMatches(File file, String path) { - - - val pathSegments = path.split("/") - val groupName = pathSegments.get(pathSegments.size-2).split("\\.").last.split("_").get(0) - print(groupName +";") - val nameExtension = pathSegments.get(pathSegments.size-1).split("\\.").get(0).split("_") - try{ - val runNumber = nameExtension.get(1) - val modelNumber = nameExtension.get(2) - print('''«runNumber»;«modelNumber»''') - } catch(Exception e) { - print('''«file.name»;0''') - } - - val parent = file.parent - val workspace = new FileSystemWorkspace(parent,"") - val model = workspace.readModel(EObject,file.name) - - val engine = ViatraQueryEngine.on(new EMFScope(model)) - val objectCode = model.eResource.calculateObjectCode - - val pattern2Hash = new HashMap - for(pattern : wfPatterns) { - val matcher = pattern.getMatcher(engine) - val matches = matcher.allMatches - val hash = matches.getMatchSetDescriptor(objectCode) - pattern2Hash.put(pattern,hash) - print(''';«matcher.countMatches»;«hash»''') - } - var mutantsKilled = 0 - for(mutant : wfPatterns.filter[query2Reference.keySet.contains(it)]) { - val equals = pattern2Hash.get(mutant) == pattern2Hash.get(query2Reference.get(mutant)) - print(''';''') - if(equals) { - print('0') - } else { - print('1') - mutantsKilled++ - } - } - //print(''';«mutantsKilled»''') - println() - } - - def static Map calculateObjectCode(Resource resource) { - val res = new HashMap - val iterator = resource.allContents - var index = 1 - while(iterator.hasNext) { - res.put(iterator.next,index++) - } - return res - } - - def static getMatchSetDescriptor(Collection matchSet, Map objectCode) { - val set = new TreeSet(new ArrayComparator) - for(match: matchSet) { - val size = match.parameterNames.size - val idArray = new ArrayList(size) - for(i:0..> { - - override compare(List arg0, List arg1) { - if(arg0.size === arg1.size) { - for(i : 0.. nameToType + val Map> nameToRelation + + protected new(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { + nameToType = ImmutableMap.copyOf(ecore2Logic.allClassesInScope(trace).toMap[name].mapValues [ eClass | + ecore2Logic.TypeofEClass(trace, eClass) + ]) + nameToRelation = ImmutableMap.copyOf(ecore2Logic.allReferencesInScope(trace).groupBy[EContainingClass.name]. + mapValues [ references | + ImmutableMap.copyOf(references.toMap[name].mapValues [ reference | + ecore2Logic.relationOfReference(trace, reference) + ]) + ]) + } + + protected def getType(String name) { + nameToType.get(name) + } + + protected def relation(String typeName, String relationName) { + nameToRelation.get(typeName).get(relationName) + } + + protected static def int countMatches(ViatraQueryMatcher matcher, PartialInterpretation p) { + val match = matcher.newEmptyMatch + match.set(0, p.problem) + match.set(1, p) + matcher.countMatches(match) + } + + protected static def int getCount(ViatraQueryMatcher matcher, PartialInterpretation p) { + val match = matcher.newEmptyMatch + match.set(0, p.problem) + match.set(1, p) + val realMatch = matcher.getOneArbitraryMatch(match) + if (realMatch.present) { + realMatch.get.get(2) as Integer + } else { + 0 + } + } +} 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 34f3c267..54724226 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 @@ -4,18 +4,23 @@ import functionalarchitecture.FunctionalarchitecturePackage import hu.bme.mit.inf.dslreasoner.domains.alloyexamples.Ecore import hu.bme.mit.inf.dslreasoner.domains.alloyexamples.FileSystem import hu.bme.mit.inf.dslreasoner.domains.alloyexamples.Filesystem.FilesystemPackage +import hu.bme.mit.inf.dslreasoner.domains.satellite.queries.internal.SatelliteQueriesAll import hu.bme.mit.inf.dslreasoner.domains.transima.fam.FamPatterns import hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph.yakindumm.YakindummPackage +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor import hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.Patterns import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace import java.util.Collection import java.util.HashMap import java.util.LinkedHashMap import java.util.List +import java.util.Map import java.util.Set import org.eclipse.emf.ecore.EAttribute import org.eclipse.emf.ecore.EClass @@ -24,60 +29,83 @@ import org.eclipse.emf.ecore.EEnumLiteral import org.eclipse.emf.ecore.EObject import org.eclipse.emf.ecore.EReference import org.eclipse.emf.ecore.EcorePackage +import org.eclipse.xtend.lib.annotations.Data import org.eclipse.xtext.xbase.lib.Functions.Function1 -import hu.bme.mit.inf.dslreasoner.domains.transima.fam.Type -import hu.bme.mit.inf.dslreasoner.domains.transima.fam.Model +import satellite.SatellitePackage + +@Data +class TypeQuantiles { + double low + double high +} abstract class MetamodelLoader { protected val ReasonerWorkspace workspace + new(ReasonerWorkspace workspace) { this.workspace = workspace - } + } + def EcoreMetamodelDescriptor loadMetamodel() + def Set getRelevantTypes(EcoreMetamodelDescriptor descriptor) + def Set getRelevantReferences(EcoreMetamodelDescriptor descriptor) + def ViatraQuerySetDescriptor loadQueries(EcoreMetamodelDescriptor metamodel) + def List loadPartialModel() - - def List> additionalConstraints() - - def filterByNames(Iterable collection, Function1 nameExtractor, Collection requiredNames) { + + def List> additionalConstraints() + + def Map getTypeQuantiles() { + emptyMap + } + + def List getHints(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { + emptyList + } + + def filterByNames(Iterable collection, Function1 nameExtractor, + Collection requiredNames) { val res = collection.filter[requiredNames.contains(nameExtractor.apply(it))] if(res.size != requiredNames.size) throw new IllegalArgumentException return res.toSet } } -class FAMLoader extends MetamodelLoader{ - +class FAMLoader extends MetamodelLoader { + new(ReasonerWorkspace workspace) { super(workspace) } - + override loadMetamodel() { val package = FunctionalarchitecturePackage.eINSTANCE val List classes = package.EClassifiers.filter(EClass).toList val List enums = package.EClassifiers.filter(EEnum).toList val List literals = enums.map[ELiterals].flatten.toList - val List references = classes.map[EReferences].flatten.toList + val List references = classes.map[EReferences].flatten.filter[name != "type" && name != "model"]. + toList val List attributes = classes.map[EAttributes].flatten.toList - return new EcoreMetamodelDescriptor(classes,#{},false,enums,literals,references,attributes) + return new EcoreMetamodelDescriptor(classes, #{}, false, enums, literals, references, attributes) } - - override getRelevantTypes(EcoreMetamodelDescriptor descriptor) { - return descriptor.classes.filterByNames([it.name],#["FunctionalElement"]) + + override getRelevantTypes(EcoreMetamodelDescriptor descriptor) { + return descriptor.classes.filterByNames([it.name], #["FunctionalElement"]) } + override getRelevantReferences(EcoreMetamodelDescriptor descriptor) { - return descriptor.references.filterByNames([it.name],#["subElements"]) + return descriptor.references.filterByNames([it.name], #["subElements"]) } - + override loadQueries(EcoreMetamodelDescriptor metamodel) { val i = FamPatterns.instance val patterns = i.specifications.toList - val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name== "Constraint"]].toSet + val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name == "Constraint"]].toSet val derivedFeatures = new LinkedHashMap - derivedFeatures.put(Type.instance,metamodel.attributes.filter[it.name == "type"].head) - derivedFeatures.put(Model.instance,metamodel.references.filter[it.name == "model"].head) +// derivedFeatures.put(Type.instance,metamodel.attributes.filter[it.name == "type"].head) +// derivedFeatures.put(Model.instance,metamodel.references.filter[it.name == "model"].head) val res = new ViatraQuerySetDescriptor( patterns, wfPatterns, @@ -85,65 +113,67 @@ class FAMLoader extends MetamodelLoader{ ) return res } + override loadPartialModel() { - this.workspace.readModel(EObject,"FAM.xmi").eResource.allContents.toList + this.workspace.readModel(EObject, "FAM.xmi").eResource.allContents.toList } - + override additionalConstraints() { #[] } } -class YakinduLoader extends MetamodelLoader{ - +class YakinduLoader extends MetamodelLoader { + var useSynchronization = true; - var useComplexStates = false; - public static val patternsWithSynchronization = #[ - "synchHasNoOutgoing", "synchHasNoIncoming", "SynchronizedIncomingInSameRegion", "notSynchronizingStates", - "hasMultipleOutgoingTrainsition", "hasMultipleIncomingTrainsition", "SynchronizedRegionsAreNotSiblings", - "SynchronizedRegionDoesNotHaveMultipleRegions", "synchThree", "twoSynch","noSynch2","synch","noSynch4","noSynch3","noSynch"] - public static val patternsWithComplexStates =#["outgoingFromExit","outgoingFromFinal","choiceHasNoOutgoing","choiceHasNoIncoming"] + var useComplexStates = false; + public static val patternsWithSynchronization = #["synchHasNoOutgoing", "synchHasNoIncoming", + "SynchronizedIncomingInSameRegion", "SynchronizedIncomingInSameRegionHelper1", + "SynchronizedIncomingInSameRegionHelper2", "notSynchronizingStates", "hasMultipleOutgoingTrainsition", + "hasMultipleIncomingTrainsition", "SynchronizedRegionsAreNotSiblings", + "SynchronizedRegionsAreNotSiblingsHelper1", "SynchronizedRegionsAreNotSiblingsHelper2", + "SynchronizedRegionDoesNotHaveMultipleRegions", "synchThree", "twoSynch", "noSynch2", "synch", "noSynch4", + "noSynch3", "noSynch"] + public static val patternsWithComplexStates = #["outgoingFromExit", "outgoingFromFinal", "choiceHasNoOutgoing", + "choiceHasNoIncoming"] + new(ReasonerWorkspace workspace) { super(workspace) YakindummPackage.eINSTANCE.eClass } - + def setUseSynchronization(boolean useSynchronization) { this.useSynchronization = useSynchronization } + def setUseComplexStates(boolean useComplexStates) { this.useComplexStates = useComplexStates } - + override loadMetamodel() { val useSynchInThisLoad = this.useSynchronization val useComplexStates = this.useComplexStates - + val package = YakindummPackage.eINSTANCE - val List classes = package.EClassifiers.filter(EClass) - .filter[useSynchInThisLoad || (it.name != "Synchronization")] - .filter[useComplexStates || (it.name != "Choice" && it.name != "Exit" && it.name != "FinalState")] - .toList + val List classes = package.EClassifiers.filter(EClass).filter [ + useSynchInThisLoad || (it.name != "Synchronization") + ].filter[useComplexStates || (it.name != "Choice" && it.name != "Exit" && it.name != "FinalState")].toList val List enums = package.EClassifiers.filter(EEnum).toList val List literals = enums.map[ELiterals].flatten.toList val List references = classes.map[EReferences].flatten.toList val List attributes = classes.map[EAttributes].flatten.toList - return new EcoreMetamodelDescriptor(classes,#{},false,enums,literals,references,attributes) + return new EcoreMetamodelDescriptor(classes, #{}, false, enums, literals, references, attributes) } + override loadQueries(EcoreMetamodelDescriptor metamodel) { val useSynchInThisLoad = this.useSynchronization - + val i = Patterns.instance - val patterns = i.specifications - .filter[spec | - useSynchInThisLoad || - !patternsWithSynchronization.exists[spec.fullyQualifiedName.endsWith(it)] - ] - .filter[spec | - useComplexStates || - !patternsWithComplexStates.exists[spec.fullyQualifiedName.endsWith(it)] - ] - .toList - val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name== "Constraint"]].toSet + val patterns = i.specifications.filter [ spec | + useSynchInThisLoad || !patternsWithSynchronization.exists[spec.fullyQualifiedName.endsWith(it)] + ].filter [ spec | + useComplexStates || !patternsWithComplexStates.exists[spec.fullyQualifiedName.endsWith(it)] + ].toList + val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name == "Constraint"]].toSet val derivedFeatures = new LinkedHashMap val res = new ViatraQuerySetDescriptor( patterns, @@ -152,53 +182,71 @@ class YakinduLoader extends MetamodelLoader{ ) return res } + override getRelevantTypes(EcoreMetamodelDescriptor descriptor) { - descriptor.classes.filterByNames([it.name],#["Vertex","Transition","Synchronization"]) + descriptor.classes.filterByNames([it.name], #["Vertex", "Transition", "Synchronization"]) } - + override getRelevantReferences(EcoreMetamodelDescriptor descriptor) { - descriptor.references.filterByNames([it.name],#["source","target"]) + descriptor.references.filterByNames([it.name], #["source", "target"]) } - + override loadPartialModel() { - this.workspace.readModel(EObject,"Yakindu.xmi").eResource.allContents.toList + this.workspace.readModel(EObject, "Yakindu.xmi").eResource.allContents.toList } - - override additionalConstraints() { //#[] - #[[method | new SGraphInconsistencyDetector(method)]] + + override additionalConstraints() { // #[] + #[[method|new SGraphInconsistencyDetector(method)]] + } + + override getTypeQuantiles() { + #{ + "Choice" -> new TypeQuantiles(0.118279569892473, 0.154020979020979), + "Entry" -> new TypeQuantiles(0.0283018867924528, 0.0620167525773196), + "Exit" -> new TypeQuantiles(0, 0), + "FinalState" -> new TypeQuantiles(0, 0), + "Region" -> new TypeQuantiles(0.0294117647058824, 0.0633258678611422), + "State" -> new TypeQuantiles(0.132023636740618, 0.175925925925926), +// "Statechart" -> new TypeQuantiles(0.00961538461538462, 0.010752688172043), + "Transition" -> new TypeQuantiles(0.581632653061224, 0.645161290322581) + } + } + + override getHints(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { + #[new SGraphHint(ecore2Logic, trace)] } } -class FileSystemLoader extends MetamodelLoader{ - +class FileSystemLoader extends MetamodelLoader { + new(ReasonerWorkspace workspace) { super(workspace) } - + override loadMetamodel() { val package = FilesystemPackage.eINSTANCE val List classes = package.EClassifiers.filter(EClass).toList val List enums = package.EClassifiers.filter(EEnum).toList val List literals = enums.map[ELiterals].flatten.toList - val List references = classes.map[EReferences].flatten.toList + val List references = classes.map[EReferences].flatten.filter[name != "live"].toList val List attributes = classes.map[EAttributes].flatten.toList - return new EcoreMetamodelDescriptor(classes,#{},false,enums,literals,references,attributes) + return new EcoreMetamodelDescriptor(classes, #{}, false, enums, literals, references, attributes) } - + override getRelevantTypes(EcoreMetamodelDescriptor descriptor) { return null } - + override getRelevantReferences(EcoreMetamodelDescriptor descriptor) { null } - + override loadQueries(EcoreMetamodelDescriptor metamodel) { val patternGroup = FileSystem.instance val patterns = patternGroup.specifications.toList val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name == "Constraint"]].toSet val derivedFeatures = new HashMap - derivedFeatures.put(patternGroup.live,metamodel.references.filter[it.name == "live"].head) +// derivedFeatures.put(patternGroup.live,metamodel.references.filter[it.name == "live"].head) return new ViatraQuerySetDescriptor( patterns, wfPatterns, @@ -206,41 +254,46 @@ class FileSystemLoader extends MetamodelLoader{ ) } - + override loadPartialModel() { - this.workspace.readModel(EObject,"fs.xmi").eResource.allContents.toList + this.workspace.readModel(EObject, "fs.xmi").eResource.allContents.toList } - + override additionalConstraints() { - #[[method | new FileSystemInconsistencyDetector(method)]] + #[[method|new FileSystemInconsistencyDetector(method)]] } - + } class EcoreLoader extends MetamodelLoader { - + new(ReasonerWorkspace workspace) { super(workspace) } - + override loadMetamodel() { val package = EcorePackage.eINSTANCE - val List classes = package.EClassifiers.filter(EClass).filter[it.name!="EFactory"].toList + val List classes = package.EClassifiers.filter(EClass).filter [ + it.name != "EFactory" && it.name != "EObject" && it.name != "EResource" + ].toList val List enums = package.EClassifiers.filter(EEnum).toList val List literals = enums.map[ELiterals].flatten.toList - val List references = classes.map[EReferences].flatten.filter[it.name!="eFactoryInstance"].filter[!it.derived].toList - val List attributes = #[] //classes.map[EAttributes].flatten.toList - return new EcoreMetamodelDescriptor(classes,#{},false,enums,literals,references,attributes) + val List references = classes.map[EReferences].flatten.filter [ + it.name != "eFactoryInstance" && it.name != "contents" && it.name != "references" && + it.name != "eGenericType" && it.name != "eGenericSuperTypes" + ].filter[!it.derived].toList + val List attributes = #[] // classes.map[EAttributes].flatten.toList + return new EcoreMetamodelDescriptor(classes, #{}, false, enums, literals, references, attributes) } - + override getRelevantTypes(EcoreMetamodelDescriptor descriptor) { return null } - + override getRelevantReferences(EcoreMetamodelDescriptor descriptor) { null } - + override loadQueries(EcoreMetamodelDescriptor metamodel) { val patternGroup = Ecore.instance val patterns = patternGroup.specifications.toList @@ -253,13 +306,92 @@ class EcoreLoader extends MetamodelLoader { ) } - + override loadPartialModel() { - this.workspace.readModel(EObject,"ecore.xmi").eResource.allContents.toList + this.workspace.readModel(EObject, "ecore.xmi").eResource.allContents.toList } - + override additionalConstraints() { #[] } + + override getTypeQuantiles() { + #{ + "EAnnotation" -> new TypeQuantiles(0, 0), + "EAttribute" -> new TypeQuantiles(0.14, 0.300943396226415), + "EClass" -> new TypeQuantiles(0.224014336917563, 0.372881355932203), + "EDataType" -> new TypeQuantiles(0, 0), + "EEnum" -> new TypeQuantiles(0, 0.0275208638045255), + "EEnumLiteral" -> new TypeQuantiles(0, 0.105204907665065), + "EGenericType" -> new TypeQuantiles(0, 0), + "EOperation" -> new TypeQuantiles(0, 0), + "EPackage" -> new TypeQuantiles(0.0119047619047619, 0.0192307692307692), + "EParameter" -> new TypeQuantiles(0, 0), + "EReference" -> new TypeQuantiles(0.217599234815878, 0.406779661016949), + "EStringToStringMapEntry" -> new TypeQuantiles(0, 0), + "ETypeParameter" -> new TypeQuantiles(0, 0) + } + } + +} + +class SatelliteLoader extends MetamodelLoader { + + new(ReasonerWorkspace workspace) { + super(workspace) + } + + override loadMetamodel() { + val package = SatellitePackage.eINSTANCE + val List classes = package.EClassifiers.filter(EClass).toList + val List enums = package.EClassifiers.filter(EEnum).toList + val List literals = enums.map[ELiterals].flatten.toList + val List references = classes.map[EReferences].flatten.toList + val List attributes = classes.map[EAttributes].flatten.toList + return new EcoreMetamodelDescriptor(classes, #{}, false, enums, literals, references, attributes) + } + + override getRelevantTypes(EcoreMetamodelDescriptor descriptor) { + null + } + + override getRelevantReferences(EcoreMetamodelDescriptor descriptor) { + null + } + + override loadQueries(EcoreMetamodelDescriptor metamodel) { + val i = SatelliteQueriesAll.instance + val patterns = i.specifications.toList + val wfPatterns = patterns.filter[it.allAnnotations.exists[it.name == "Constraint"]].toSet + val derivedFeatures = new LinkedHashMap + val res = new ViatraQuerySetDescriptor( + patterns, + wfPatterns, + derivedFeatures + ) + return res + } + + override loadPartialModel() { + this.workspace.readModel(EObject, "satellite.xmi").eResource.allContents.toList + } + + override additionalConstraints() { #[] } + + override getHints(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { + #[new SatelliteHint(ecore2Logic, trace)] + } + + override getTypeQuantiles() { + #{ + "CubeSat3U" -> new TypeQuantiles(0.1, 0.25), + "CubeSat6U" -> new TypeQuantiles(0, 0.25), + "SmallSat" -> new TypeQuantiles(0, 0.15), + "UHFCommSubsystem" -> new TypeQuantiles(0.08, 0.25), + "XCommSubsystem" -> new TypeQuantiles(0.08, 0.25), + "KaCommSubsystem" -> new TypeQuantiles(0, 0.1), + "InterferometryPayload" -> new TypeQuantiles(0.15, 0.25) + } + } -} \ No newline at end of file +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend new file mode 100644 index 00000000..97ce4ee6 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SGraphHint.xtend @@ -0,0 +1,46 @@ +package hu.bme.mit.inf.dslreasoner.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator + +class SGraphHint extends Ecore2LogicTraceBasedHint { + new(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { + super(ecore2Logic, trace) + } + + override getAdditionalPatterns(extension PatternGenerator patternGenerator) { + "" + } + + override createConstraintUpdater(LinearTypeExpressionBuilderFactory it) { + val newEntriesWithoutRegionCount = createBuilder.add(1, "Entry".type).add(-1, "Region".type).build + val newStatesWithoutRegionCount = createBuilder.add(1, "State".type).add(-1, "Region".type).build + val newTransitionWithoutNeedsOutgoingCount = createBuilder.add(1, "Transition".type).add(-1, "Entry".type). + add(-1, "Choice".type).build + val newTransitionWithoutNeedsIncomingCount = createBuilder.add(1, "Transition".type).add(-1, "Choice".type). + build + + val regionsWithoutEntryMatcher = createMatcher( + "unfinishedBy_pattern_hu_bme_mit_inf_dslreasoner_partialsnapshot_mavo_yakindu_noEntryInRegion") + val regionsWithoutStateMatcher = createMatcher( + "unfinishedBy_pattern_hu_bme_mit_inf_dslreasoner_partialsnapshot_mavo_yakindu_noStateInRegion") + val entryHasNoOutgoingMatcher = createMatcher( + "unfinishedBy_pattern_hu_bme_mit_inf_dslreasoner_partialsnapshot_mavo_yakindu_noOutgoingTransitionFromEntry") + val choiceHasNoOutgoingMatcher = createMatcher( + "unfinishedBy_pattern_hu_bme_mit_inf_dslreasoner_partialsnapshot_mavo_yakindu_choiceHasNoOutgoing") + val choiceHasNoIncomingMatcher = createMatcher( + "unfinishedBy_pattern_hu_bme_mit_inf_dslreasoner_partialsnapshot_mavo_yakindu_choiceHasNoIncoming") + val transitionWithoutTargetMatcher = createMatcher("unfinishedLowerMultiplicity_target_reference_Transition") + + return [ p | + newEntriesWithoutRegionCount.assertEqualsTo(regionsWithoutEntryMatcher.countMatches(p)) + newStatesWithoutRegionCount.tightenLowerBound(regionsWithoutStateMatcher.countMatches(p)) + newTransitionWithoutNeedsOutgoingCount.tightenLowerBound( + entryHasNoOutgoingMatcher.countMatches(p) + choiceHasNoOutgoingMatcher.countMatches(p)) + newTransitionWithoutNeedsIncomingCount.tightenLowerBound( + choiceHasNoIncomingMatcher.countMatches(p) - transitionWithoutTargetMatcher.getCount(p)) + ] + } +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend new file mode 100644 index 00000000..e95c0c64 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/SatelliteHint.xtend @@ -0,0 +1,86 @@ +package hu.bme.mit.inf.dslreasoner.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.Modality +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator + +class SatelliteHint extends Ecore2LogicTraceBasedHint { + static val INTERFEROMETY_PAYLOAD = "hint_interferometryPayload" + static val REMAINING_CONTENTS_KA_COMM_SUBSYSTEM = "hint_kaCommSubsystem" + static val HINT_SPACECRAFT_UHF_POSSIBLE_LINK = "hint_spacecraftWithUhfPossibleLink" + static val HINT_SPACECRAFT_UHF_ONLY_NO_LINK = "hint_spacecraftUhfOnlyNoLink" + + new(Ecore2Logic ecore2Logic, Ecore2Logic_Trace trace) { + super(ecore2Logic, trace) + } + + override getAdditionalPatterns(PatternGenerator it) ''' + pattern «INTERFEROMETY_PAYLOAD»(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, object); + «typeIndexer.referInstanceOf("InterferometryPayload".type, Modality.MUST, "object")» + } + + private pattern «REMAINING_CONTENTS_KA_COMM_SUBSYSTEM»_helper(problem:LogicProblem, interpretation:PartialInterpretation, object:DefinedElement, remainingContents:java Integer) { + find remainingContents_commSubsystem_reference_CommunicatingElement_helper(problem, interpretation, object, remainingContents); + «typeIndexer.referInstanceOf("SmallSat".type, Modality.MUST, "object")» + } + + pattern «REMAINING_CONTENTS_KA_COMM_SUBSYSTEM»(problem:LogicProblem, interpretation:PartialInterpretation, remainingContents:java Integer) { + find interpretation(problem, interpretation); + remainingContents == sum find «REMAINING_CONTENTS_KA_COMM_SUBSYSTEM»_helper(problem, interpretation, _, #_); + } + + private pattern hint_spacecraftNotUhfOnly(problem:LogicProblem, interpretation:PartialInterpretation, spacecraft:DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, spacecraft); + «typeIndexer.referInstanceOf("Spacecraft".type, Modality.MUST, "spacecraft")» + «relationDeclarationIndexer.referRelation("CommunicatingElement".relation("commSubsystem"), "spacecraft", "comm", Modality.MAY)» + neg «typeIndexer.referInstanceOf("UHFCommSubsystem".type, Modality.MUST, "comm")» + } + + private pattern hint_spacecraftWithUhf(problem:LogicProblem, interpretation:PartialInterpretation, spacecraft:DefinedElement) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, spacecraft); + «typeIndexer.referInstanceOf("Spacecraft".type, Modality.MUST, "spacecraft")» + «relationDeclarationIndexer.referRelation("CommunicatingElement".relation("commSubsystem"), "spacecraft", "comm", Modality.MUST)» + «typeIndexer.referInstanceOf("UHFCommSubsystem".type, Modality.MUST, "comm")» + } + + pattern «HINT_SPACECRAFT_UHF_POSSIBLE_LINK»(problem:LogicProblem, interpretation:PartialInterpretation) { + find hint_spacecraftWithUhf(problem, interpretation, spacecraft); + find hint_spacecraftNotUhfOnly(problem, interpretation, spacecraft); + } + + pattern «HINT_SPACECRAFT_UHF_ONLY_NO_LINK»(problem:LogicProblem, interpretation:PartialInterpretation) { + find interpretation(problem, interpretation); + find mustExist(problem, interpretation, spacecraft); + «typeIndexer.referInstanceOf("Spacecraft".type, Modality.MUST, "spacecraft")» + neg find hint_spacecraftNotUhfOnly(problem, interpretation, spacecraft); + find currentInRelation_pattern_hu_bme_mit_inf_dslreasoner_domains_satellite_queries_noLinkToGroundStation(problem, interpretation, spacecraft); + } + ''' + + override createConstraintUpdater(LinearTypeExpressionBuilderFactory it) { + val interferometryPayloadCount = createBuilder.add(1, "InterferometryPayload".type).build + val kaCommSubsystemWithoutSmallSatCount = createBuilder.add(1, "KaCommSubsystem".type).add(-2, "SmallSat".type). + build + val uhfCommSubsystemCount = createBuilder.add(1, "UHFCommSubsystem".type).build + + val interferometryPayloadMatcher = createMatcher(INTERFEROMETY_PAYLOAD) + val kaCommSubsystemRemainingContentsMatcher = createMatcher(REMAINING_CONTENTS_KA_COMM_SUBSYSTEM) + val uhfPossibleLinkMatcher = createMatcher(HINT_SPACECRAFT_UHF_POSSIBLE_LINK) + val uhfNoLinkMatcher = createMatcher(HINT_SPACECRAFT_UHF_ONLY_NO_LINK) + + return [ p | + interferometryPayloadCount.tightenLowerBound(2 - interferometryPayloadMatcher.countMatches(p)) + kaCommSubsystemWithoutSmallSatCount.tightenUpperBound(kaCommSubsystemRemainingContentsMatcher.getCount(p)) + if (uhfPossibleLinkMatcher.countMatches(p) == 0 && uhfNoLinkMatcher.countMatches(p) >= 1) { + uhfCommSubsystemCount.tightenLowerBound(1) + } + ] + } + +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/TypeDistributionCalculator.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/TypeDistributionCalculator.xtend new file mode 100644 index 00000000..e2d6e6ca --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/TypeDistributionCalculator.xtend @@ -0,0 +1,35 @@ +package hu.bme.mit.inf.dslreasoner.run + +import hu.bme.mit.inf.dslreasoner.domains.yakindu.sgraph.yakindumm.YakindummPackage +import java.io.File +import org.eclipse.emf.common.util.URI +import org.eclipse.emf.ecore.EPackage +import org.eclipse.emf.ecore.EcorePackage +import org.eclipse.emf.ecore.resource.Resource +import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl +import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl + +class TypeDistributionCalculator { + public static def void main(String[] args) { + Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl) + EPackage.Registry.INSTANCE.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE) + EPackage.Registry.INSTANCE.put(YakindummPackage.eNS_URI, YakindummPackage.eINSTANCE) + + println("model,className,count") + val directory = new File(args.get(0)) + for (file : directory.listFiles) { + val modelName = file.name + val resourceSet = new ResourceSetImpl + val resource = resourceSet.getResource(URI.createFileURI(file.absolutePath), true) + val objectsByTypeName = resource.allContents.filter [ obj | + val featureName = obj.eContainingFeature?.name + // Filter out "derived containment" references in Ecore. + // See https://stackoverflow.com/a/46340165 + featureName != "eGenericType" && featureName != "eGenericSuperTypes" + ].groupBy[eClass.name] + for (pair : objectsByTypeName.entrySet) { + println('''«modelName»,«pair.key»,«pair.value.size»''') + } + } + } +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScript.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScript.xtend new file mode 100644 index 00000000..5abff962 --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScript.xtend @@ -0,0 +1,70 @@ +package hu.bme.mit.inf.dslreasoner.run.script + +import java.util.List +import org.eclipse.xtend.lib.annotations.Accessors + +@Accessors +class MeasurementScript { + String inputPath + String outputPath + int timeout + boolean saveModels + boolean saveTemporaryFiles + int warmupIterations + int iterations + Domain domain + Scope scope + List sizes + Solver solver + ScopePropagator scopePropagator + ScopeConstraints propagatedConstraints + PolyhedronSolver polyhedronSolver + ScopeHeuristic scopeHeuristic + + def toCsvHeader() { + '''«domain»,«scope»,«solver»,«scopePropagator ?: "NULL"»,«propagatedConstraints ?: "NULL"»,«polyhedronSolver ?: "NULL"»''' + } +} + +enum Domain { + fs, + ecore, + Yakindu, + FAM, + satellite +} + +enum Scope { + none, + quantiles +} + +enum Solver { + ViatraSolver, + AlloySolver +} + +enum ScopePropagator { + none, + basic, + polyhedral +} + +enum ScopeConstraints { + none, + typeHierarchy, + relations, + hints +} + +enum PolyhedronSolver { + Z3Integer, + Z3Real, + Cbc, + Clp +} + +enum ScopeHeuristic { + basic, + polyhedral +} diff --git a/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScriptRunner.xtend b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScriptRunner.xtend new file mode 100644 index 00000000..48e750cb --- /dev/null +++ b/Tests/hu.bme.mit.inf.dslreasoner.run/src/hu/bme/mit/inf/dslreasoner/run/script/MeasurementScriptRunner.xtend @@ -0,0 +1,351 @@ +package hu.bme.mit.inf.dslreasoner.run.script + +import com.google.gson.Gson +import hu.bme.mit.inf.dslreasoner.ecore2logic.EClassMapper +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel +import hu.bme.mit.inf.dslreasoner.logic.model.builder.TypeScopes +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.DefinedElement +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntLiteral +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealLiteral +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringLiteral +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.IntStatisticEntry +import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory +import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult +import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.RealStatisticEntry +import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.Statistics +import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.StringStatisticEntry +import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore +import hu.bme.mit.inf.dslreasoner.run.EcoreLoader +import hu.bme.mit.inf.dslreasoner.run.FAMLoader +import hu.bme.mit.inf.dslreasoner.run.FileSystemLoader +import hu.bme.mit.inf.dslreasoner.run.MetamodelLoader +import hu.bme.mit.inf.dslreasoner.run.SatelliteLoader +import hu.bme.mit.inf.dslreasoner.run.YakinduLoader +import hu.bme.mit.inf.dslreasoner.util.CollectionsUtil +import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic +import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorConstraints +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partial2logicannotations.PartialModelRelation2Assertion +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration +import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace +import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace +import java.io.FileReader +import java.util.HashMap +import java.util.HashSet +import java.util.Map +import java.util.Set +import org.eclipse.emf.ecore.EObject +import org.eclipse.emf.ecore.resource.Resource +import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl +import org.eclipse.viatra.query.patternlanguage.emf.EMFPatternLanguageStandaloneSetup +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngineOptions +import org.eclipse.viatra.query.runtime.rete.matcher.ReteBackendFactory +import org.eclipse.xtend.lib.annotations.Data + +class MeasurementScriptRunner { + static val MODEL_SIZE_GAP = 0 + static val SCOPE_PROPAGATOR_TIMEOUT = 10 + static val USEC_TO_MSEC = 1000000 + + static extension val LogicresultFactory = LogicresultFactory.eINSTANCE + + val MeasurementScript script + val ReasonerWorkspace inputWorkspace + val ReasonerWorkspace outputWorkspace + val MetamodelLoader metamodelLoader + + new(MeasurementScript script) { + this.script = script + inputWorkspace = new FileSystemWorkspace(script.inputPath + "/", "") + outputWorkspace = new FileSystemWorkspace(script.outputPath + + "/", '''«script.domain»_«script.solver»_«script.scope»_«script.scopePropagator ?: "na"»_«script.propagatedConstraints ?: "na"»_«script.polyhedronSolver ?: "na"»_''') + metamodelLoader = switch (script.domain) { + case fs: new FileSystemLoader(inputWorkspace) + case ecore: new EcoreLoader(inputWorkspace) + case Yakindu: new YakinduLoader(inputWorkspace) => [useSynchronization = false; useComplexStates = true] + case FAM: new FAMLoader(inputWorkspace) + case satellite: new SatelliteLoader(inputWorkspace) + default: throw new IllegalArgumentException("Unsupported domain: " + script.domain) + } + } + + def run() { + if (script.sizes.empty) { + return + } + val start = System.currentTimeMillis + val warmupSize = script.sizes.head + for (var int i = 0; i < script.warmupIterations; i++) { + System.err.println('''Warmup «i + 1»/«script.warmupIterations»...''') + runExperiment(warmupSize) + } + val warmupEnd = System.currentTimeMillis + System.err.println('''Warmup completed in «(warmupEnd - start) / 1000» seconds''') + for (size : script.sizes) { + var int failures = 0 + for (var int i = 0; i < script.iterations; i++) { + System.err.println("Running GC...") + runGc() + System.err.println('''Iteration «i + 1»/«script.iterations» of size «size»...''') + val startTime = System.currentTimeMillis + val result = runExperiment(size) + val headerPrefix = '''«script.toCsvHeader»,«size»,«i + 1»,«result.resultName»''' + println('''«headerPrefix»,startTime,«startTime»''') + println('''«headerPrefix»,logic2SolverTransformationTime,«result.statistics.transformationTime»''') + println('''«headerPrefix»,solverTime,«result.statistics.solverTime»''') + for (statistic : result.statistics.entries) { + val valueString = switch (statistic) { + IntStatisticEntry: statistic.value.toString + RealStatisticEntry: statistic.value.toString + StringStatisticEntry: statistic.value.toString + default: statistic.toString + } + println('''«headerPrefix»,«statistic.name»,«valueString»''') + } + if (script.saveModels && result.model !== null) { + outputWorkspace.writeModel(result.model, '''«size»_«i + 1».xmi''') + } + if (result.resultName === "InsuficientResourcesResultImpl") { + failures++ + } + System.out.flush + } + if (failures == script.iterations) { + System.err.println("All measurements failed") + return + } + } + val end = System.currentTimeMillis + System.err.println('''Measurement completed in «(end - start) / 1000» seconds''') + } + + private static def void runGc() { + System.gc + Thread.sleep(100) + System.gc + Thread.sleep(100) + System.gc + Thread.sleep(800) + } + + private def runExperiment(int modelSize) { + if (script.solver != Solver.ViatraSolver) { + throw new IllegalArgumentException("Only VIATRA-Generator is supported") + } + val config = new ViatraReasonerConfiguration + config.solutionScope.numberOfRequiredSolutions = 1 + config.scopePropagatorStrategy = switch (script.scopePropagator) { + case none: + ScopePropagatorStrategy.None + case basic: + switch (script.propagatedConstraints) { + case none: + ScopePropagatorStrategy.Basic + case typeHierarchy: + ScopePropagatorStrategy.BasicTypeHierarchy + case relations, + case hints: + throw new IllegalArgumentException( + "Basic scope propagator does not support relational and hint constraints") + default: + throw new IllegalArgumentException("Unknown scope constraints: " + script.propagatedConstraints) + } + case polyhedral: { + val constraints = switch (script.propagatedConstraints) { + case none: + throw new IllegalArgumentException( + "Polyhedral scope propagator needs at least type hierarchy constraints") + case typeHierarchy: + PolyhedralScopePropagatorConstraints.TypeHierarchy + case relations, + case hints: + PolyhedralScopePropagatorConstraints.Relational + default: + throw new IllegalArgumentException("Unknown scope constraints: " + script.propagatedConstraints) + } + val polyhedronSolver = switch (script.polyhedronSolver) { + case Z3Integer: PolyhedralScopePropagatorSolver.Z3Integer + case Z3Real: PolyhedralScopePropagatorSolver.Z3Real + case Cbc: PolyhedralScopePropagatorSolver.Cbc + case Clp: PolyhedralScopePropagatorSolver.Clp + default: throw new IllegalArgumentException("Unknown polyhedron solver: " + script.polyhedronSolver) + } + val updateHeuristic = script.scopeHeuristic != ScopeHeuristic.basic + new ScopePropagatorStrategy.Polyhedral(constraints, polyhedronSolver, updateHeuristic, + SCOPE_PROPAGATOR_TIMEOUT) + } + default: + throw new IllegalArgumentException("Unknown scope propagator: " + script.scopePropagator) + } + config.runtimeLimit = script.timeout + config.documentationLevel = if(script.saveTemporaryFiles) DocumentationLevel.NORMAL else DocumentationLevel.NONE + config.debugConfiguration.partialInterpretatioVisualiser = null + config.searchSpaceConstraints.additionalGlobalConstraints += metamodelLoader.additionalConstraints + + val modelLoadingStart = System.nanoTime + val metamodelDescriptor = metamodelLoader.loadMetamodel + val partialModelDescriptor = metamodelLoader.loadPartialModel + val queryDescriptor = metamodelLoader.loadQueries(metamodelDescriptor) + val modelLoadingTime = System.nanoTime - modelLoadingStart + + val domain2LogicTransformationStart = System.nanoTime + val Ecore2Logic ecore2Logic = new Ecore2Logic + val Viatra2Logic viatra2Logic = new Viatra2Logic(ecore2Logic) + val InstanceModel2Logic instanceModel2Logic = new InstanceModel2Logic + var modelGeneration = ecore2Logic.transformMetamodel(metamodelDescriptor, new Ecore2LogicConfiguration()) + var problem = modelGeneration.output + problem = instanceModel2Logic.transform( + modelGeneration, + partialModelDescriptor + ).output + problem = viatra2Logic.transformQueries( + queryDescriptor, + modelGeneration, + new Viatra2LogicConfiguration + ).output + initializeScope(config, modelSize, problem, ecore2Logic, modelGeneration.trace) + if (script.propagatedConstraints == ScopeConstraints.hints) { + config.hints = metamodelLoader.getHints(ecore2Logic, modelGeneration.trace) + } + val domain2LogicTransformationTime = System.nanoTime - domain2LogicTransformationStart + + if (config.documentationLevel != DocumentationLevel.NONE) { + outputWorkspace.writeModel(problem, "initial.logicproblem") + } + + val solver = new ViatraReasoner + val result = solver.solve(problem, config, outputWorkspace) + val statistics = result.statistics + statistics.entries += createIntStatisticEntry => [ + name = "modelLoadingTime" + value = (modelLoadingTime / USEC_TO_MSEC) as int + ] + statistics.entries += createIntStatisticEntry => [ + name = "domain2LogicTransformationTime" + value = (domain2LogicTransformationTime / USEC_TO_MSEC) as int + ] + var EObject modelResult = null + if (result instanceof ModelResult) { + val intepretations = solver.getInterpretations(result) + if (intepretations.size != 1) { + throw new IllegalStateException("Expected 1 interpretation, got " + intepretations.size) + } + var resultTransformationStart = System.nanoTime + val logic2Ecore = new Logic2Ecore(ecore2Logic) + modelResult = logic2Ecore.transformInterpretation(intepretations.head, modelGeneration.trace) + val resultTransformationTime = System.nanoTime - resultTransformationStart + statistics.entries += createIntStatisticEntry => [ + name = "ecore2LogicTransformationTime" + value = (resultTransformationTime / USEC_TO_MSEC) as int + ] + } + + new ExperimentResult(result.class.simpleName, statistics, modelResult) + } + + private def initializeScope(ViatraReasonerConfiguration config, int modelSize, LogicProblem problem, + EClassMapper eClassMapper, Ecore2Logic_Trace trace) { + val knownElements = initializeKnownElements(problem, config.typeScopes) + if (modelSize < 0) { + config.typeScopes.minNewElements = 0 + config.typeScopes.maxNewElements = TypeScopes.Unlimited + } else { + val numberOfKnownElements = knownElements.values.flatten.toSet.size + val newElementCount = modelSize - numberOfKnownElements + config.typeScopes.minNewElements = newElementCount + config.typeScopes.maxNewElements = newElementCount + MODEL_SIZE_GAP + } + switch (script.scope) { + case none: + return + case quantiles: { + val quantiles = metamodelLoader.typeQuantiles + for (eClassInScope : eClassMapper.allClassesInScope(trace)) { + val quantile = quantiles.get(eClassInScope.name) + if (quantile !== null) { + val type = eClassMapper.TypeofEClass(trace, eClassInScope) + val knownInstances = knownElements.get(type) + val currentCount = if(knownInstances === null) 0 else knownInstances.size + val lowCount = Math.floor(modelSize * quantile.low) as int + val highCount = Math.ceil((modelSize + MODEL_SIZE_GAP) * quantile.high) as int + config.typeScopes.minNewElementsByType.put(type, lowCount - currentCount) + config.typeScopes.maxNewElementsByType.put(type, highCount - currentCount) + } + } + } + default: + throw new IllegalArgumentException("Unknown scope: " + script.scope) + } + } + + /* + * Copied from hu.bme.mit.inf.dslreasoner.application.execution.ScopeLoader.initialiseknownElements(LogicProblem, TypeScopes) + */ + private static def initializeKnownElements(LogicProblem p, TypeScopes s) { + val Map> res = new HashMap + + // 1. fill map with every types + for (t : p.types) { + res.put(t, new HashSet) + } + + // 2. fill map with every objects + for (definedType : p.types.filter(TypeDefinition)) { + val supertypes = CollectionsUtil.transitiveClosureStar(definedType)[supertypes] + for (supertype : supertypes) { + for (element : definedType.elements) { + res.get(supertype).add(element) + } + } + } + val partialModelContents = p.annotations.filter(PartialModelRelation2Assertion).map[target].toList.map [ + eAllContents.toIterable + ].flatten.toList + s.knownIntegers += partialModelContents.filter(IntLiteral).map[it.value] + s.knownReals += partialModelContents.filter(RealLiteral).map[it.value] + s.knownStrings += partialModelContents.filter(StringLiteral).map[it.value] + + res + } + + public static def void main(String[] args) { + if (args.length != 1) { + System.err.println("Missing measurement script name.") + System.exit(-1) + } + EMFPatternLanguageStandaloneSetup.doSetup + ViatraQueryEngineOptions.setSystemDefaultBackends(ReteBackendFactory.INSTANCE, ReteBackendFactory.INSTANCE, + ReteBackendFactory.INSTANCE) + Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl) + val config = readConfig(args.get(0)) + val runnner = new MeasurementScriptRunner(config) + runnner.run() + } + + static def readConfig(String scriptPath) { + val gson = new Gson + val reader = new FileReader(scriptPath) + try { + gson.fromJson(reader, MeasurementScript) + } finally { + reader.close + } + } + + @Data + private static class ExperimentResult { + String resultName + Statistics statistics + EObject model + } +} -- cgit v1.2.3-54-g00ecf From 454dc3d1d54e943970db4c6794cca9acac272459 Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Thu, 16 Jul 2020 00:23:40 +0200 Subject: Fix numeric-solver-at-end --- .../ide/.ApplicationConfigurationIdeModule.xtendbin | Bin 1701 -> 1701 bytes .../ide/.ApplicationConfigurationIdeSetup.xtendbin | Bin 2526 -> 2526 bytes .../.SolverSemanticHighlightCalculator.xtendbin | Bin 5334 -> 5334 bytes .../.SolverSemanticTextAttributeProvider.xtendbin | Bin 4902 -> 4902 bytes .../validation/.SolverLanguageValidator.xtendbin | Bin 1717 -> 1717 bytes .../.SolverLanguageTokenDefInjectingParser.xtendbin | Bin 2742 -> 2742 bytes ...rLanguageSyntheticTokenSyntacticSequencer.xtendbin | Bin 2758 -> 2758 bytes .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 4 +++- 8 files changed, 3 insertions(+), 1 deletion(-) (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend') 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 35e3fe34..96d7f77b 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin 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 b597e715..85768640 100644 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin 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 5d90d470..287aa50d 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin 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 f054d52c..e9b25b0a 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin differ 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 faaea19c..79d18e32 100644 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin differ 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 704006b4..c529b829 100644 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin differ 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 76be2b25..9ff56ed9 100644 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin differ 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 d879d4cc..c0b5008c 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 @@ -20,6 +20,7 @@ import org.eclipse.xtend.lib.annotations.Accessors */ class ViatraReasonerSolutionSaver implements ISolutionSaver { @Accessors val SolutionCopier solutionCopier + val NumericSolver numericSolver @Accessors val DiversityChecker diversityChecker val boolean hasExtremalObjectives val int numberOfRequiredSolutions @@ -34,6 +35,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] this.numberOfRequiredSolutions = numberOfRequiredSolutions this.solutionCopier = new SolutionCopier(numericSolver) + this.numericSolver = numericSolver } override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { @@ -97,7 +99,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { } private def shouldSaveSolution(Fitness fitness, ThreadContext context) { - return fitness.satisifiesHardObjectives + return fitness.satisifiesHardObjectives && numericSolver.currentSatisfiable } private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, -- cgit v1.2.3-54-g00ecf From f06427cd7375551582461f91b3458339a8227f9b Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Mon, 2 Nov 2020 02:02:40 +0100 Subject: Optimizing generator with linear objective functions --- .../.ApplicationConfigurationIdeModule.xtendbin | Bin 1700 -> 1700 bytes .../ide/.ApplicationConfigurationIdeSetup.xtendbin | Bin 2525 -> 2525 bytes .../.SolverSemanticHighlightCalculator.xtendbin | Bin 5333 -> 5333 bytes .../.SolverSemanticTextAttributeProvider.xtendbin | Bin 4902 -> 4902 bytes .../solver/language/ui/syntaxcoloring/.gitignore | 4 + .../validation/.SolverLanguageValidator.xtendbin | Bin 1716 -> 1716 bytes .../viatra/solver/language/validation/.gitignore | 2 + ....SolverLanguageTokenDefInjectingParser.xtendbin | Bin 2741 -> 2741 bytes .../viatra/solver/language/parser/antlr/.gitignore | 2 + ...nguageSyntheticTokenSyntacticSequencer.xtendbin | Bin 2757 -> 2757 bytes .../viatra/solver/language/serializer/.gitignore | 2 + .../META-INF/MANIFEST.MF | 3 +- Domains/ca.mcgill.rtgmrt.example.modes3/plugin.xml | 18 + .../src/modes3/queries/Modes3Queries.vql | 197 ++++- .../src/modes3/run/CloseTrainsObjectiveHint.xtend | 201 +++++ .../src/modes3/run/EndOfSidingObjectiveHint.xtend | 139 ++++ .../run/MisalignedTurnoutObjectiveHint.xtend | 140 ++++ .../src/modes3/run/Modes3ModelGenerator.xtend | 189 ++++- .../modes3/run/TrainLocationsObjectiveHint.xtend | 85 +++ .../vql-gen/modes3/queries/.gitignore | 45 ++ .../vql-gen/modes3/queries/EndOfSiding_step_2.java | 564 ++++++++++++++ .../vql-gen/modes3/queries/EndOfSiding_step_3.java | 717 +++++++++++++++++ .../vql-gen/modes3/queries/EndOfSiding_step_4.java | 847 +++++++++++++++++++++ .../vql-gen/modes3/queries/EndOfSiding_step_5.java | 841 ++++++++++++++++++++ .../vql-gen/modes3/queries/Modes3Queries.java | 198 +++++ .../modes3/queries/MultipleConnectedTo.java | 565 ++++++++++++++ .../modes3/queries/TooManyInputsOfSegment.java | 12 - .../modes3/queries/TrainLocations_step_2.java | 564 ++++++++++++++ .../modes3/queries/TrainLocations_step_3.java | 713 +++++++++++++++++ .../modes3/run/.CloseTrainsObjectiveHint.xtendbin | Bin 0 -> 8218 bytes .../modes3/run/.EndOfSidingObjectiveHint.xtendbin | Bin 0 -> 7190 bytes .../run/.MisalignedTurnoutObjectiveHint.xtendbin | Bin 0 -> 7395 bytes .../modes3/run/.Modes3ModelGenerator.xtendbin | Bin 15038 -> 18637 bytes .../modes3/run/.Modes3TypeScopeHint.xtendbin | Bin 7179 -> 6927 bytes .../run/.Modes3UnitPropagationGenerator.xtendbin | Bin 11735 -> 11284 bytes .../run/.TrainLocationsObjectiveHint.xtendbin | Bin 0 -> 6269 bytes .../xtend-gen/modes3/run/.gitignore | 10 + .../modes3/run/CloseTrainsObjectiveHint.java | 279 +++++++ .../modes3/run/EndOfSidingObjectiveHint.java | 193 +++++ .../modes3/run/MisalignedTurnoutObjectiveHint.java | 195 +++++ .../xtend-gen/modes3/run/Modes3ModelGenerator.java | 305 ++++++-- .../modes3/run/TrainLocationsObjectiveHint.java | 117 +++ .../META-INF/MANIFEST.MF | 1 - .../META-INF/MANIFEST.MF | 3 +- .../ModelGenerationMethodProvider.xtend | 226 ------ .../logic2viatra/ModelGenerationStatistics.xtend | 47 ++ .../logic2viatra/TypeInferenceMethod.xtend | 44 ++ .../ExtendedLinearExpressionBuilderFactory.xtend | 140 ++++ ...ExtendedPolyhedronScopePropagatorStrategy.xtend | 63 ++ .../cardinality/PolyhedronScopePropagator.xtend | 54 +- .../PolyhedronScopePropagatorStrategy.xtend | 92 +++ .../cardinality/PolyhedronSolver.xtend | 13 +- .../META-INF/MANIFEST.MF | 1 + ...odelGenerationMethodBasedGlobalConstraint.xtend | 1 - .../reasoner/ModelGenerationMethodProvider.xtend | 201 +++++ .../viatrasolver/reasoner/ViatraReasoner.xtend | 102 +-- .../reasoner/ViatraReasonerConfiguration.xtend | 4 +- .../dse/BestFirstStrategyForModelGeneration.java | 7 +- .../viatrasolver/reasoner/dse/NumericSolver.xtend | 2 +- .../dse/PartialModelAsLogicInterpretation.xtend | 3 +- .../viatrasolver/reasoner/dse/SolutionCopier.xtend | 8 +- .../reasoner/dse/ViatraReasonerSolutionSaver.xtend | 112 ++- .../optimization/CostElementMatchers.xtend | 137 ++++ .../reasoner/optimization/CostObjectiveHint.xtend | 68 ++ .../optimization/IObjectiveBoundsProvider.xtend | 8 + .../optimization/ThreeValuedCostObjective.xtend | 99 ++- .../ThreeValuedCostObjectiveProvider.xtend | 205 +++++ .../case.study.familyTree.run/bin/.gitignore | 1 + .../bin/queries/.gitignore | 4 + .../src-gen/queries/.gitignore | 4 + .../xtend-gen/converter/.UML2TGF.xtendbin | Bin 6885 -> 6885 bytes .../run/FileSystemInconsistencyDetector.xtend | 4 +- .../mit/inf/dslreasoner/run/MetamodelLoader.xtend | 2 +- .../run/SGraphInconsistencyDetector.xtend | 2 +- 74 files changed, 8297 insertions(+), 508 deletions(-) create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/CloseTrainsObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/EndOfSidingObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/MisalignedTurnoutObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/src/modes3/run/TrainLocationsObjectiveHint.xtend create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_2.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_3.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_4.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/EndOfSiding_step_5.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/MultipleConnectedTo.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_2.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/vql-gen/modes3/queries/TrainLocations_step_3.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/CloseTrainsObjectiveHint.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/EndOfSidingObjectiveHint.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/MisalignedTurnoutObjectiveHint.java create mode 100644 Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/TrainLocationsObjectiveHint.java delete mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationStatistics.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/TypeInferenceMethod.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedLinearExpressionBuilderFactory.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/ExtendedPolyhedronScopePropagatorStrategy.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/cardinality/PolyhedronScopePropagatorStrategy.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostElementMatchers.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/CostObjectiveHint.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/IObjectiveBoundsProvider.xtend create mode 100644 Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/optimization/ThreeValuedCostObjectiveProvider.xtend create mode 100644 Tests/MODELS2020-CaseStudies/case.study.familyTree.run/bin/.gitignore (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/ViatraReasonerSolutionSaver.xtend') 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 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeModule.xtendbin 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 Binary files a/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin and b/Application/hu.bme.mit.inf.dslreasoner.application.ide/xtend-gen/hu/bme/mit/inf/dslreasoner/application/ide/.ApplicationConfigurationIdeSetup.xtendbin 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 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticHighlightCalculator.xtendbin 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 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/ui/syntaxcoloring/.SolverSemanticTextAttributeProvider.xtendbin 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 @@ /.SolverSemanticHighlightCalculator.java._trace /.SolverSemanticTextAttributeProvider.java._trace +/.SolverSemanticHighlightCalculator.xtendbin +/.SolverSemanticTextAttributeProvider.xtendbin +/SolverSemanticHighlightCalculator.java +/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 Binary files a/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin and b/Application/org.eclipse.viatra.solver.language.ui/xtend-gen/org/eclipse/viatra/solver/language/validation/.SolverLanguageValidator.xtendbin 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 @@ /.SolverLanguageValidator.java._trace +/.SolverLanguageValidator.xtendbin +/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 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/parser/antlr/.SolverLanguageTokenDefInjectingParser.xtendbin 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 @@ /.SolverLanguageSyntheticTokenParser.java._trace /.SolverLanguageTokenSource.java._trace /.SolverLanguageTokenDefInjectingParser.java._trace +/.SolverLanguageTokenDefInjectingParser.xtendbin +/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 Binary files a/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin and b/Application/org.eclipse.viatra.solver.language/xtend-gen/org/eclipse/viatra/solver/language/serializer/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin 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 @@ /.SolverLanguageSyntheticTokenSyntacticSequencer.java._trace +/.SolverLanguageSyntheticTokenSyntacticSequencer.xtendbin +/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, hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", org.eclipse.emf.ecore.xmi;bundle-version="2.16.0", hu.bme.mit.inf.dslreasoner.visualisation;bundle-version="1.0.0", - org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0" + org.eclipse.viatra.query.patternlanguage.emf;bundle-version="2.4.0", + org.eclipse.viatra.dse;bundle-version="0.24.0" Import-Package: org.apache.log4j Automatic-Module-Name: ca.mcgill.rtgmrt.example.modes3 Bundle-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 @@ + + + + + + + + + + + + + + + + + + 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) { find turnoutOutput(S1, S2); } -//@Constraint(message = "noInputOfSegment", severity = "error", key = { S }) -//pattern noInputOfSegment(S : Segment) { -// neg find turnout(S); -// neg find output(_, S); -//} - @Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S }) pattern tooManyInputsOfSegment(S : SimpleSegment) { find output(I1, S); @@ -108,3 +102,194 @@ pattern reachable(S1 : Segment, S2 : Segment) { pattern unreachable(S1 : Segment, S2 : Segment) { neg find reachable(S1, S2); } + +// +// closeTrains +// + +pattern closeTrains_step_2(in train : Train) { +// frame->t1 = model->trains[i0]; +// frame->start = frame->t1->location; +// if(frame->start != 0){ +// ... +// } +// + OUTER FOR LOOP COUNTER INCREMENT + Train(train); +} + +pattern closeTrains_step_3(in train : Train, in start : Segment) { +// int loop_bound1 = frame->start->connected_to_count; +// for (int i1 = 0; i1 < loop_bound1; i1++) { LOOP COUNTER INCREMENT IS NOT INCLUDED HERE +// ... +// } + Train.location(train, start); +} + +pattern closeTrains_step_4(in train : Train, in start : Segment, in middle : Segment) { +// frame->middle = frame->start->connected_to[i1]; +// int loop_bound2 = frame->middle->connected_to_count; + +// for (int i2 = 0; i2 < loop_bound2; i2++) { LOOP COUNTER INCREMENT IS NOT INCLUDED HERE +// ... +// } +// + OUTER FOR LOOP COUNTER INCREMENT + Train.location(train, start); + Segment.connectedTo(start, middle); +} + +pattern closeTrains_step_5(in train : Train, in start : Segment, in middle : Segment, in end : Segment) { +// frame->end = frame->middle->connected_to[i2]; +// if (frame->start != frame->end) { +// ... +// } +// + OUTER FOR LOOP COUNTER INCREMENT + Train.location(train, start); + Segment.connectedTo(start, middle); + Segment.connectedTo(middle, end); +} + +pattern closeTrains_step_6(in train : Train, in start : Segment, in middle : Segment, in end : Segment) { +// frame->t2 = frame->end->train; +// if (frame->t2 != 0) { +// ... +// } + Train.location(train, start); + Segment.connectedTo(start, middle); + Segment.connectedTo(middle, end); + start != end; +} + +pattern closeTrains_step_7(in train : Train, in start : Segment, in middle : Segment, in end : Segment, in otherTrain : Train) { +// results->matches[match_cntr].start = frame->start; +// results->matches[match_cntr++].end = frame->end; + Train.location(train, start); + Segment.connectedTo(start, middle); + Segment.connectedTo(middle, end); + start != end; + Segment.occupiedBy(end, otherTrain); +} + +// +// trainLocations +// + +pattern trainLocations_step_2(in train : Train) { +// frame->train = model->trains[i0]; +// frame->location = frame->train->location; +// if (frame->location != NULL) { +// ... +// } + + Train(train); +} + +pattern trainLocations_step_3(in train : Train, in location : Segment) { +// results->matches[match_cntr].location = frame->location; +// results->matches[match_cntr++].train = frame->train; + Train(train); + Train.location(train, location); +} + +// +// misalignedTurnout +// + +pattern misalignedTurnout_step_2(in turnout : Turnout) { +// frame->turnout = model->turnouts[i0]; +// frame->location = frame->turnout->straight; +// if (frame->location != NULL) { +// ... +// } + Turnout(turnout); +} + +pattern misalignedTurnout_step_3(in turnout : Turnout, in location : Segment) { +// Segment *disconnected = ((Segment *)frame->turnout); +// if (disconnected->connected_to[0] != frame->location && +// disconnected->connected_to[1] != frame->location) { +// ... +// } + Turnout(turnout); + Turnout.straight(turnout, location); +} + +pattern misalignedTurnout_step_4(in turnout : Turnout, in location : Segment) { +// frame->train = frame->location->train; +// if (frame->train != NULL) { +// ... +// } + Turnout(turnout); + Turnout.straight(turnout, location); + neg find connectedSegmentsDirected(turnout, location); +} + +pattern misalignedTurnout_step_5(in turnout : Turnout, in location : Segment, in train : Train) { +// results->matches[match_cntr].start = frame->start; +// results->matches[match_cntr++].end = frame->end; + Turnout(turnout); + Turnout.straight(turnout, location); + neg find connectedSegmentsDirected(turnout, location); + Segment.occupiedBy(location, train); +} + +pattern connectedSegmentsDirected(s1 : Segment, s2 : Segment) { + Segment.connectedTo(s1, s2); +} + +// +// endOfSiding +// + +pattern endOfSiding_step_2(in train : Train) { +// frame->train = model->trains[i0]; +// frame->location = frame->train->location; +// if (frame->location != NULL) { +// ... +// } + + Train(train); +} + +pattern endOfSiding_step_3(in train : Train, in location : Segment) { +// int loop_bound1 = frame->location->connected_to_count; +// for (int i1 = 0; i1 < loop_bound1; i1++) { +// ... +// } + Train(train); + Train.location(train, location); +} + +pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) { +// 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); + Train.location(train, location); + Segment.connectedTo(location, end); +} + +pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) { +// 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); + Train.location(train, location); + Segment.connectedTo(location, end); + neg find multipleConnectedTo(end); +} + +pattern multipleConnectedTo(s : Segment) { + Segment.connectedTo(s, n1); + Segment.connectedTo(s, n2); + n1 != n2; +} 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 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.CloseTrains_step_2 +import modes3.queries.CloseTrains_step_3 +import modes3.queries.CloseTrains_step_4 +import modes3.queries.CloseTrains_step_5 +import modes3.queries.CloseTrains_step_6 +import modes3.queries.CloseTrains_step_7 + +class CloseTrainsObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(CloseTrains_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(CloseTrains_step_3.instance.fullyQualifiedName) + val step4 = costElementMatchers.get(CloseTrains_step_4.instance.fullyQualifiedName) + val step5 = costElementMatchers.get(CloseTrains_step_5.instance.fullyQualifiedName) + val step6 = costElementMatchers.get(CloseTrains_step_6.instance.fullyQualifiedName) + val step7 = costElementMatchers.get(CloseTrains_step_7.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.assertEqualsTo(0) + } + boundLimit(step3Matches, 2, trainType, 1) + boundLimit(step3Matches, 3, segmentType, 1) + + val step4Matches = step4.matches + for (m : step4Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step4.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step4Matches.groupBy[step3.projectMayMatch(match, 2, 3)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-2, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step4Matches, 2, trainType, 2) + boundLimit(step4Matches, 3, segmentType, 2) + boundLimit(step4Matches, 4, segmentType, 2) + + val step5Matches = step5.matches + for (m : step5Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step5.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step5Matches.groupBy[step4.projectMayMatch(match, 2, 3, 4)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-2, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step5Matches, 2, trainType, 4) + boundLimit(step5Matches, 3, segmentType, 4) + boundLimit(step5Matches, 4, segmentType, 4) + boundLimit(step5Matches, 5, segmentType, 4) + + val step6Matches = step6.matches + for (m : step6Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step6.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + if (m.match.get(3) == m.match.get(5)) { + createBuilder.add(2, m.match).add(-1, step5.projectMayMatch(m.match, 2, 3, 4, 5)).build. + assertEqualsTo(0) + } else { + createBuilder.add(1, m.match).add(-1, step5.projectMayMatch(m.match, 2, 3, 4, 5)).build. + assertEqualsTo(0) + } + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + boundLimit(step6Matches, 2, trainType, 2) + boundLimit(step6Matches, 3, segmentType, 2) + boundLimit(step6Matches, 4, segmentType, 2) + boundLimit(step6Matches, 5, segmentType, 2) + + val step7Matches = step7.matches + for (m : step7Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step7.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step7Matches.groupBy[step6.projectMayMatch(match, 2, 3, 4, 5)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step7Matches, 2, trainType, 2) + boundLimit(step7Matches, 3, segmentType, 2) + boundLimit(step7Matches, 4, segmentType, 2) + boundLimit(step7Matches, 5, segmentType, 2) + boundLimit(step7Matches, 6, trainType, 2) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} 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 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.EndOfSiding_step_2 +import modes3.queries.EndOfSiding_step_3 +import modes3.queries.EndOfSiding_step_4 +import modes3.queries.EndOfSiding_step_5 + +class EndOfSidingObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true +// false + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(EndOfSiding_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(EndOfSiding_step_3.instance.fullyQualifiedName) + val step4 = costElementMatchers.get(EndOfSiding_step_4.instance.fullyQualifiedName) + val step5 = costElementMatchers.get(EndOfSiding_step_5.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.assertEqualsTo(0) + } + boundLimit(step3Matches, 2, trainType, 1) + boundLimit(step3Matches, 3, segmentType, 1) + + val step4Matches = step4.matches + for (m : step4Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step4.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step4Matches.groupBy[step3.projectMayMatch(match, 2, 3)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-2, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step4Matches, 2, trainType, 2) + boundLimit(step4Matches, 3, segmentType, 2) + boundLimit(step4Matches, 4, segmentType, 2) + + val step5Matches = step5.matches + for (m : step5Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step5.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + createBuilder.add(1, m.match).add(-1, step4.projectMayMatch(m.match, 2, 3, 4)).build.tightenUpperBound(0) + } + boundLimit(step5Matches, 2, trainType, 1) + boundLimit(step5Matches, 3, segmentType, 2) + boundLimit(step5Matches, 4, segmentType, 1) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} \ 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 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.MisalignedTurnout_step_2 +import modes3.queries.MisalignedTurnout_step_3 +import modes3.queries.MisalignedTurnout_step_4 +import modes3.queries.MisalignedTurnout_step_5 + +class MisalignedTurnoutObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type turnoutType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + turnoutType = ecore2LogicTrace.TypeofEClass(turnout) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true +// false + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(MisalignedTurnout_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(MisalignedTurnout_step_3.instance.fullyQualifiedName) + val step4 = costElementMatchers.get(MisalignedTurnout_step_4.instance.fullyQualifiedName) + val step5 = costElementMatchers.get(MisalignedTurnout_step_5.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, turnoutType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step3Matches.groupBy[step2.projectMayMatch(match, 2)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step3Matches, 2, turnoutType, 1) + boundLimit(step3Matches, 3, segmentType, 2) + + val step4Matches = step4.matches + for (m : step4Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step4.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + createBuilder.add(1, m.match).add(-1, step3.projectMayMatch(m.match, 2, 3)).build.tightenUpperBound(0) + } + boundLimit(step4Matches, 2, turnoutType, 1) + boundLimit(step4Matches, 3, segmentType, 2) + + val step5Matches = step5.matches + for (m : step5Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step5.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + for (pair : step5Matches.groupBy[step4.projectMayMatch(match, 2, 3)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + multiplicityBuilder.add(-1, pair.key) + multiplicityBuilder.build.tightenUpperBound(0) + } + boundLimit(step5Matches, 2, turnoutType, 1) + boundLimit(step5Matches, 3, segmentType, 2) + boundLimit(step5Matches, 4, trainType, 2) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} 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 import hu.bme.mit.inf.dslreasoner.ecore2logic.EReferenceMapper_RelationsOverTypes_Trace import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2LogicConfiguration +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsFactory import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage @@ -14,6 +15,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.LogiclanguagePackage import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDefinition import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult +import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor @@ -25,18 +27,38 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePro import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.InstanceModel2Logic import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BinaryElementRelationLink import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace import java.util.List import modes3.Modes3Factory import modes3.Modes3Package +import modes3.queries.CloseTrains_step_2 +import modes3.queries.CloseTrains_step_3 +import modes3.queries.CloseTrains_step_4 +import modes3.queries.CloseTrains_step_5 +import modes3.queries.CloseTrains_step_6 +import modes3.queries.CloseTrains_step_7 +import modes3.queries.EndOfSiding_step_2 +import modes3.queries.EndOfSiding_step_3 +import modes3.queries.EndOfSiding_step_4 +import modes3.queries.EndOfSiding_step_5 +import modes3.queries.MisalignedTurnout_step_2 +import modes3.queries.MisalignedTurnout_step_3 +import modes3.queries.MisalignedTurnout_step_4 +import modes3.queries.MisalignedTurnout_step_5 import modes3.queries.Modes3Queries +import modes3.queries.TrainLocations_step_2 +import modes3.queries.TrainLocations_step_3 import org.eclipse.emf.ecore.EClass import org.eclipse.emf.ecore.EObject import org.eclipse.emf.ecore.resource.Resource @@ -92,17 +114,21 @@ class Modes3ModelGenerator { minNewElements = modelSize maxNewElements = modelSize minNewElementsByType => [ -// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), modelSize / 5) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), modelSize / 5) +// put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.simpleSegment), 3 * modelSize / 5) ] maxNewElementsByType => [ - put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), 5) - put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.train), modelSize / 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.turnout), modelSize / 5) + put(ecore2Logic.TypeofEClass(metamodelLogic.trace, Modes3Package.eINSTANCE.simpleSegment), 3 * modelSize / 5) ] ] solutionScope => [ numberOfRequiredSolutions = 1 ] - scopeWeight = 5 + costObjectives += getObjective(ecore2Logic, metamodelLogic.trace) + scopeWeight = 6 nameNewElements = false typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood @@ -121,47 +147,60 @@ class Modes3ModelGenerator { val solution = solver.solve(logic.output, config, workspace) if (solution instanceof ModelResult) { println("Saving generated solutions") - val representations = solution.representation - for (representationIndex : 0 ..< representations.size) { - val representation = representations.get(representationIndex) + val logic2Ecore = new Logic2Ecore(ecore2Logic) + val interpretations = solver.getInterpretations(solution) + for (representationIndex : 0 ..< interpretations.size) { + val interpretation = interpretations.get(representationIndex) val representationNumber = representationIndex + 1 - if (representation instanceof PartialInterpretation) { + if (interpretation instanceof PartialModelAsLogicInterpretation) { + val representation = interpretation.partialInterpretation workspace.writeModel(representation, '''solution«representationNumber».partialinterpretation''') val partialInterpretation2GML = new PartialInterpretation2Gml val gml = partialInterpretation2GML.transform(representation) workspace.writeText('''solution«representationNumber».gml''', gml) + val model = logic2Ecore.transformInterpretation(interpretation, metamodelLogic.trace) + val iterator = model.eAllContents + var int id = 0 + while (iterator.hasNext) { + val obj = iterator.next + val idFeature = obj.eClass.EAllAttributes.findFirst[name == 'id'] + if (idFeature !== null) { + obj.eSet(idFeature, id) + id++ + } + } + workspace.writeModel(model, '''solution«representationNumber».modes3''') if (representation.newElements.size < 160) { - if (representation instanceof PartialInterpretation) { - val rootType = (representation.problem.types.findFirst [ - name == "Modes3ModelRoot class DefinedPart" - ] as TypeDefinition) - val rootIntepretation = representation.partialtypeinterpratation.filter( - PartialComplexTypeInterpretation).findFirst [ - interpretationOf.name == "Modes3ModelRoot class" + val rootType = (representation.problem.types.findFirst [ + name == "Modes3ModelRoot class DefinedPart" + ] as TypeDefinition) + val rootIntepretation = representation.partialtypeinterpratation.filter( + PartialComplexTypeInterpretation).findFirst [ + interpretationOf.name == "Modes3ModelRoot class" + ] + rootIntepretation.elements.removeAll(rootType.elements) + representation.problem.elements.removeAll(rootType.elements) + for (relationInterpretation : representation.partialrelationinterpretation) { + relationInterpretation.relationlinks.removeIf [ link | + if (link instanceof BinaryElementRelationLink) { + rootType.elements.contains(link.param1) || + rootType.elements.contains(link.param2) + } else { + false + } ] - rootIntepretation.elements.removeAll(rootType.elements) - representation.problem.elements.removeAll(rootType.elements) - for (relationInterpretation : representation.partialrelationinterpretation) { - relationInterpretation.relationlinks.removeIf [ link | - if (link instanceof BinaryElementRelationLink) { - rootType.elements.contains(link.param1) || rootType.elements.contains(link.param2) - } else { - false - } - ] - } - rootType.elements.clear } + rootType.elements.clear val visualiser = new GraphvizVisualiser val visualisation = visualiser.visualiseConcretization(representation) visualisation.writeToFile(workspace, '''solution«representationNumber».png''') } } else { - workspace.writeText('''solution«representationNumber».txt''', representation.toString) + workspace.writeText('''solution«representationNumber».txt''', interpretation.toString) } } } else { - println("Failed to solver problem") + println("Failed to solve problem") val partial = logic.output workspace.writeModel(partial, "solution.partialinterpretation") } @@ -198,6 +237,94 @@ class Modes3ModelGenerator { ) } + def getObjective(Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + new CostObjectiveConfiguration => [ + switch (monitoringQuery) { + case closeTrains: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_3.instance.fullyQualifiedName + weight = 21 + 14 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_4.instance.fullyQualifiedName + weight = 14 + 44 + 14 + 9 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_5.instance.fullyQualifiedName + weight = 14 + 41 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_6.instance.fullyQualifiedName + weight = 27 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = CloseTrains_step_7.instance.fullyQualifiedName + weight = 48 + ] + hint = new CloseTrainsObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + case trainLocations: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = TrainLocations_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = TrainLocations_step_3.instance.fullyQualifiedName + weight = 48 + ] + hint = new TrainLocationsObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + case misalignedTurnout: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_3.instance.fullyQualifiedName + weight = 108 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_4.instance.fullyQualifiedName + weight = 27 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = MisalignedTurnout_step_5.instance.fullyQualifiedName + weight = 48 + ] + hint = new MisalignedTurnoutObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + case endOfSiding: { + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_2.instance.fullyQualifiedName + weight = 14 + 53 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_3.instance.fullyQualifiedName + weight = 21 + 14 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_4.instance.fullyQualifiedName + weight = 14 + 35 + 21 + 15 + 14 + 21 + 15 + 11 + ] + elements += new CostObjectiveElementConfiguration => [ + patternQualifiedName = EndOfSiding_step_5.instance.fullyQualifiedName + weight = 48 + ] + hint = new EndOfSidingObjectiveHint(ecore2Logic, ecore2LogicTrace) + } + default: + throw new IllegalArgumentException("Unknown monitoring query: " + monitoringQuery) + } + kind = ObjectiveKind.HIGHER_IS_BETTER + threshold = ObjectiveThreshold.NO_THRESHOLD + findExtremum = true + ] + } + def static init() { EMFPatternLanguageStandaloneSetup.doSetup ViatraQueryEngineOptions.setSystemDefaultBackends(ReteBackendFactory.INSTANCE, ReteBackendFactory.INSTANCE, @@ -223,6 +350,8 @@ class Modes3ModelGenerator { private static enum MonitoringQuery { closeTrains, + trainLocations, + endOfSiding, misalignedTurnout } } 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 @@ +package modes3.run + +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint +import java.util.Collection +import java.util.Map +import modes3.Modes3Package +import modes3.queries.TrainLocations_step_2 +import modes3.queries.TrainLocations_step_3 + +class TrainLocationsObjectiveHint extends CostObjectiveHint { + val Type segmentType + val Type trainType + + new(extension Ecore2Logic ecore2Logic, Ecore2Logic_Trace ecore2LogicTrace) { + extension val Modes3Package = Modes3Package.eINSTANCE + segmentType = ecore2LogicTrace.TypeofEClass(segment) + trainType = ecore2LogicTrace.TypeofEClass(train) + } + + override isExact() { + true + } + + override createPolyhedronExtensionOperator(Map costElementMatchers) { + val step2 = costElementMatchers.get(TrainLocations_step_2.instance.fullyQualifiedName) + val step3 = costElementMatchers.get(TrainLocations_step_3.instance.fullyQualifiedName); + + [ + val objectiveBuilder = createBuilder + + for (m : step2.matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step2.weight, dimension) + dimension.tightenLowerBound(0) + if (m.multi) { + createBuilder.add(1, dimension).add(-1, trainType).build.assertEqualsTo(0) + } else { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + + val step3Matches = step3.matches + for (m : step3Matches) { + val dimension = getDimension(m.match) + objectiveBuilder.add(step3.weight, dimension) + dimension.tightenLowerBound(0) + if (!m.multi) { + dimension.tightenUpperBound(1) + if (m.must) { + dimension.tightenLowerBound(1) + } + } + } + boundLimit(step3Matches, 2, trainType, 1) + boundLimit(step3Matches, 3, segmentType, 1) + + objectiveBuilder.buildWithBounds + ] + } + + private static def boundLimit(extension ExtendedLinearExpressionBuilderFactory factory, + Collection matches, int index, Type type, int count) { + for (pair : matches.groupBy[match.get(index)].entrySet) { + val multiplicityBuilder = createBuilder + for (m : pair.value) { + multiplicityBuilder.add(1, m.match) + } + if (CostElementMatchers.isMulti(pair.key)) { + multiplicityBuilder.add(-count, type) + multiplicityBuilder.build.tightenUpperBound(0) + } else { + multiplicityBuilder.build.tightenUpperBound(count) + } + } + } +} \ 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 @@ /.TooManyNonStraightInputsOfTurnout.java._trace /.InputsOfTurnout.java._trace /.TooFewInputsOfTurnout.java._trace +/.CloseTrains_step_2.java._trace +/.CloseTrains_step_3.java._trace +/.CloseTrains_step_4.java._trace +/.CloseTrains_step_5.java._trace +/.CloseTrains_step_6.java._trace +/.CloseTrains_step_7.java._trace +/.MisalignedTurnout_step_2.java._trace +/.MisalignedTurnout_step_3.java._trace +/.MisalignedTurnout_step_4.java._trace +/.MisalignedTurnout_step_5.java._trace +/.ConnectedSegmentsDirected.java._trace +/Adjacent.java +/CloseTrains_step_2.java +/CloseTrains_step_3.java +/CloseTrains_step_4.java +/CloseTrains_step_5.java +/CloseTrains_step_6.java +/CloseTrains_step_7.java +/ConnectedSegmentsDirected.java +/ConnectedTo.java +/ConnectedToNotSymmetric.java +/ConnectedToReflexive.java +/InputsOfTurnout.java +/MisalignedTurnout_step_2.java +/MisalignedTurnout_step_3.java +/MisalignedTurnout_step_4.java +/MisalignedTurnout_step_5.java +/Modes3Queries.java +/Output.java +/OutputReflexive.java +/Reachable.java +/TooFewInputsOfTurnout.java +/TooManyInputsOfSegment.java +/TooManyInputsOfTurnout.java +/TurnoutConnectedToBothOutputs.java +/TurnoutOutput.java +/TurnoutOutputsAreSame.java +/Unreachable.java +/.TrainLocations_step_2.java._trace +/.TrainLocations_step_3.java._trace +/.EndOfSiding_step_2.java._trace +/.EndOfSiding_step_3.java._trace +/.EndOfSiding_step_4.java._trace +/.EndOfSiding_step_5.java._trace +/.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 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         //
    + *         // endOfSiding
    + *         //
    + *         
    + *         pattern endOfSiding_step_2(in train : Train) {
    + *         //   frame-{@literal >}train = model-{@literal >}trains[i0];
    + *         //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
    + *         //   if (frame-{@literal >}location != NULL) {
    + *         //     ...
    + *         //   }
    + *         
    + *         	Train(train);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_2 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_2 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private static List parameterNames = makeImmutableList("train"); + + private Match(final Train pTrain) { + this.fTrain = pTrain; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_2"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_2.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain}; + } + + @Override + public EndOfSiding_step_2.Match toImmutable() { + return isMutable() ? newMatch(fTrain) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_2.Match)) { + EndOfSiding_step_2.Match other = (EndOfSiding_step_2.Match) obj; + return Objects.equals(fTrain, other.fTrain); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_2 specification() { + return EndOfSiding_step_2.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_2.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_2.Match newMutableMatch(final Train pTrain) { + return new Mutable(pTrain); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_2.Match newMatch(final Train pTrain) { + return new Immutable(pTrain); + } + + private static final class Mutable extends EndOfSiding_step_2.Match { + Mutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_2.Match { + Immutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_2 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * //
    +   * // endOfSiding
    +   * //
    +   * 
    +   * pattern endOfSiding_step_2(in train : Train) {
    +   * //   frame-{@literal >}train = model-{@literal >}trains[i0];
    +   * //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
    +   * //   if (frame-{@literal >}location != NULL) {
    +   * //     ...
    +   * //   }
    +   * 
    +   * 	Train(train);
    +   * }
    +   * 
    + * + * @see Match + * @see EndOfSiding_step_2 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_2.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_2.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_2.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain) { + return rawGetOneArbitraryMatch(new Object[]{pTrain}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain) { + return rawHasMatch(new Object[]{pTrain}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain) { + return rawCountMatches(new Object[]{pTrain}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_2.Match newMatch(final Train pTrain) { + return EndOfSiding_step_2.Match.newMatch(pTrain); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + @Override + protected EndOfSiding_step_2.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_2.Match.newMatch((Train) t.get(POSITION_TRAIN)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_2.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_2.Match.newMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_2.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_2.Match.newMutableMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_2.instance(); + } + } + + private EndOfSiding_step_2() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_2 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_2.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_2.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_2.Matcher instantiate() { + return EndOfSiding_step_2.Matcher.create(); + } + + @Override + public EndOfSiding_step_2.Match newEmptyMatch() { + return EndOfSiding_step_2.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_2.Match newMatch(final Object... parameters) { + return EndOfSiding_step_2.Match.newMatch((modes3.Train) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_2} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_2#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_2 INSTANCE = new EndOfSiding_step_2(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_2.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_2"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train) + )); + // // frame->train = model->trains[i0];// frame->location = frame->train->location;// if (frame->location != NULL) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + bodies.add(body); + } + return bodies; + } + } +} 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 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern endOfSiding_step_3(in train : Train, in location : Segment) {
    + *         //     int loop_bound1 = frame-{@literal >}location-{@literal >}connected_to_count;
    + *         //     for (int i1 = 0; i1 {@literal <} loop_bound1; i1++) {
    + *         //       ...
    + *         //     }
    + *         	Train(train);
    + *             Train.location(train, location);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_3 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_3 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private static List parameterNames = makeImmutableList("train", "location"); + + private Match(final Train pTrain, final Segment pLocation) { + this.fTrain = pTrain; + this.fLocation = pLocation; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_3"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_3.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation}; + } + + @Override + public EndOfSiding_step_3.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_3.Match)) { + EndOfSiding_step_3.Match other = (EndOfSiding_step_3.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_3 specification() { + return EndOfSiding_step_3.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_3.Match newEmptyMatch() { + return new Mutable(null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_3.Match newMutableMatch(final Train pTrain, final Segment pLocation) { + return new Mutable(pTrain, pLocation); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return new Immutable(pTrain, pLocation); + } + + private static final class Mutable extends EndOfSiding_step_3.Match { + Mutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_3.Match { + Immutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_3 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern endOfSiding_step_3(in train : Train, in location : Segment) {
    +   * //     int loop_bound1 = frame-{@literal >}location-{@literal >}connected_to_count;
    +   * //     for (int i1 = 0; i1 {@literal <} loop_bound1; i1++) {
    +   * //       ...
    +   * //     }
    +   * 	Train(train);
    +   *     Train.location(train, location);
    +   * }
    +   * 
    + * + * @see Match + * @see EndOfSiding_step_3 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_3.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_3.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_3.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation) { + return rawHasMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation) { + return rawCountMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return EndOfSiding_step_3.Match.newMatch(pTrain, pLocation); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final EndOfSiding_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}).collect(Collectors.toSet()); + } + + @Override + protected EndOfSiding_step_3.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_3.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_3.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_3.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_3.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_3.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_3.instance(); + } + } + + private EndOfSiding_step_3() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_3 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_3.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_3.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_3.Matcher instantiate() { + return EndOfSiding_step_3.Matcher.create(); + } + + @Override + public EndOfSiding_step_3.Match newEmptyMatch() { + return EndOfSiding_step_3.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_3.Match newMatch(final Object... parameters) { + return EndOfSiding_step_3.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_3} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_3#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_3 INSTANCE = new EndOfSiding_step_3(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_3.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_3"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location) + )); + // // int loop_bound1 = frame->location->connected_to_count;// for (int i1 = 0; i1 < loop_bound1; i1++) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + bodies.add(body); + } + return bodies; + } + } +} 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 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
    + *         //       frame-{@literal >}end = frame-{@literal >}location-{@literal >}connected_to[i1];
    + *         //       if (frame-{@literal >}end != NULL &&
    + *         //			 frame-{@literal >}end-{@literal >}connected_to[1] == frame-{@literal >}location &&
    + *         //           frame-{@literal >}end-{@literal >}connected_to[0] == NULL) {
    + *         //         ...
    + *         //       } 
    + *         //     	 if (frame-{@literal >}end != NULL &&
    + *         //			 frame-{@literal >}end-{@literal >}connected_to[0] == frame-{@literal >}location &&
    + *         //           frame-{@literal >}end-{@literal >}connected_to[1] == NULL) {
    + *         //         ...
    + *         //       }
    + *         	Train(train);
    + *             Train.location(train, location);
    + *             Segment.connectedTo(location, end);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_4 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_4 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private Segment fEnd; + + private static List parameterNames = makeImmutableList("train", "location", "end"); + + private Match(final Train pTrain, final Segment pLocation, final Segment pEnd) { + this.fTrain = pTrain; + this.fLocation = pLocation; + this.fEnd = pEnd; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + case "end": return this.fEnd; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + case 2: return this.fEnd; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + public Segment getEnd() { + return this.fEnd; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + if ("end".equals(parameterName) ) { + this.fEnd = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + public void setEnd(final Segment pEnd) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fEnd = pEnd; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_4"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_4.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation, fEnd}; + } + + @Override + public EndOfSiding_step_4.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation, fEnd) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation) + ", "); + result.append("\"end\"=" + prettyPrintValue(fEnd)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation, fEnd); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_4.Match)) { + EndOfSiding_step_4.Match other = (EndOfSiding_step_4.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation) && Objects.equals(fEnd, other.fEnd); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_4 specification() { + return EndOfSiding_step_4.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_4.Match newEmptyMatch() { + return new Mutable(null, null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_4.Match newMutableMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Mutable(pTrain, pLocation, pEnd); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_4.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Immutable(pTrain, pLocation, pEnd); + } + + private static final class Mutable extends EndOfSiding_step_4.Match { + Mutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_4.Match { + Immutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_4 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern endOfSiding_step_4(in train : Train, in location : Segment, in end : Segment) {
    +   * //       frame-{@literal >}end = frame-{@literal >}location-{@literal >}connected_to[i1];
    +   * //       if (frame-{@literal >}end != NULL &&
    +   * //			 frame-{@literal >}end-{@literal >}connected_to[1] == frame-{@literal >}location &&
    +   * //           frame-{@literal >}end-{@literal >}connected_to[0] == NULL) {
    +   * //         ...
    +   * //       } 
    +   * //     	 if (frame-{@literal >}end != NULL &&
    +   * //			 frame-{@literal >}end-{@literal >}connected_to[0] == frame-{@literal >}location &&
    +   * //           frame-{@literal >}end-{@literal >}connected_to[1] == NULL) {
    +   * //         ...
    +   * //       }
    +   * 	Train(train);
    +   *     Train.location(train, location);
    +   *     Segment.connectedTo(location, end);
    +   * }
    +   * 
    + * + * @see Match + * @see EndOfSiding_step_4 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_4.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_4.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final int POSITION_END = 2; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_4.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawHasMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawCountMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_4.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return EndOfSiding_step_4.Match.newMatch(pTrain, pLocation, pEnd); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfend(final Object[] parameters) { + return rawStreamAllValues(POSITION_END, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final EndOfSiding_step_4.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}).collect(Collectors.toSet()); + } + + @Override + protected EndOfSiding_step_4.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_4.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION), (Segment) t.get(POSITION_END)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_4.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_4.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_4.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_4.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_4.instance(); + } + } + + private EndOfSiding_step_4() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_4 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_4.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_4.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_4.Matcher instantiate() { + return EndOfSiding_step_4.Matcher.create(); + } + + @Override + public EndOfSiding_step_4.Match newEmptyMatch() { + return EndOfSiding_step_4.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_4.Match newMatch(final Object... parameters) { + return EndOfSiding_step_4.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1], (modes3.Segment) parameters[2]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_4} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_4#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_4 INSTANCE = new EndOfSiding_step_4(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_4.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final PParameter parameter_end = new PParameter("end", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location, parameter_end); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_4"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location","end"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + PVariable var_end = body.getOrCreateVariableByName("end"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_end), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location), + new ExportedParameter(body, var_end, parameter_end) + )); + // // 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) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + // Segment.connectedTo(location, end) + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_location, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_1_, var_end); + bodies.add(body); + } + return bodies; + } + } +} 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 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import modes3.queries.MultipleConnectedTo; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.NegativePatternCall; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
    + *         //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    + *         //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    + *         //         ...OR...
    + *         //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    + *         //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    + *         	Train(train);
    + *             Train.location(train, location);
    + *             Segment.connectedTo(location, end);
    + *         	neg find multipleConnectedTo(end);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class EndOfSiding_step_5 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.endOfSiding_step_5 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private Segment fEnd; + + private static List parameterNames = makeImmutableList("train", "location", "end"); + + private Match(final Train pTrain, final Segment pLocation, final Segment pEnd) { + this.fTrain = pTrain; + this.fLocation = pLocation; + this.fEnd = pEnd; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + case "end": return this.fEnd; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + case 2: return this.fEnd; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + public Segment getEnd() { + return this.fEnd; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + if ("end".equals(parameterName) ) { + this.fEnd = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + public void setEnd(final Segment pEnd) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fEnd = pEnd; + } + + @Override + public String patternName() { + return "modes3.queries.endOfSiding_step_5"; + } + + @Override + public List parameterNames() { + return EndOfSiding_step_5.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation, fEnd}; + } + + @Override + public EndOfSiding_step_5.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation, fEnd) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation) + ", "); + result.append("\"end\"=" + prettyPrintValue(fEnd)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation, fEnd); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof EndOfSiding_step_5.Match)) { + EndOfSiding_step_5.Match other = (EndOfSiding_step_5.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation) && Objects.equals(fEnd, other.fEnd); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public EndOfSiding_step_5 specification() { + return EndOfSiding_step_5.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static EndOfSiding_step_5.Match newEmptyMatch() { + return new Mutable(null, null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static EndOfSiding_step_5.Match newMutableMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Mutable(pTrain, pLocation, pEnd); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public static EndOfSiding_step_5.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return new Immutable(pTrain, pLocation, pEnd); + } + + private static final class Mutable extends EndOfSiding_step_5.Match { + Mutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends EndOfSiding_step_5.Match { + Immutable(final Train pTrain, final Segment pLocation, final Segment pEnd) { + super(pTrain, pLocation, pEnd); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.endOfSiding_step_5 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern endOfSiding_step_5(in train : Train, in location : Segment, in end : Segment) {
    +   * //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    +   * //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    +   * //         ...OR...
    +   * //         results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    +   * //         results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    +   * 	Train(train);
    +   *     Train.location(train, location);
    +   *     Segment.connectedTo(location, end);
    +   * 	neg find multipleConnectedTo(end);
    +   * }
    +   * 
    + * + * @see Match + * @see EndOfSiding_step_5 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static EndOfSiding_step_5.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static EndOfSiding_step_5.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final int POSITION_END = 2; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(EndOfSiding_step_5.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawHasMatch(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return rawCountMatches(new Object[]{pTrain, pLocation, pEnd}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Segment pEnd, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation, pEnd}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param pEnd the fixed value of pattern parameter end, or null if not bound. + * @return the (partial) match object. + * + */ + public EndOfSiding_step_5.Match newMatch(final Train pTrain, final Segment pLocation, final Segment pEnd) { + return EndOfSiding_step_5.Match.newMatch(pTrain, pLocation, pEnd); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation, final Segment pEnd) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain, final Segment pEnd) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null, pEnd}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfend(final Object[] parameters) { + return rawStreamAllValues(POSITION_END, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend() { + return rawStreamAllValuesOfend(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for end. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final EndOfSiding_step_5.Match partialMatch) { + return rawStreamAllValuesOfend(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for end. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfend(final Train pTrain, final Segment pLocation) { + return rawStreamAllValuesOfend(new Object[]{pTrain, pLocation, null}).collect(Collectors.toSet()); + } + + @Override + protected EndOfSiding_step_5.Match tupleToMatch(final Tuple t) { + try { + return EndOfSiding_step_5.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION), (Segment) t.get(POSITION_END)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_5.Match arrayToMatch(final Object[] match) { + try { + return EndOfSiding_step_5.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected EndOfSiding_step_5.Match arrayToMatchMutable(final Object[] match) { + try { + return EndOfSiding_step_5.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION], (Segment) match[POSITION_END]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return EndOfSiding_step_5.instance(); + } + } + + private EndOfSiding_step_5() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static EndOfSiding_step_5 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected EndOfSiding_step_5.Matcher instantiate(final ViatraQueryEngine engine) { + return EndOfSiding_step_5.Matcher.on(engine); + } + + @Override + public EndOfSiding_step_5.Matcher instantiate() { + return EndOfSiding_step_5.Matcher.create(); + } + + @Override + public EndOfSiding_step_5.Match newEmptyMatch() { + return EndOfSiding_step_5.Match.newEmptyMatch(); + } + + @Override + public EndOfSiding_step_5.Match newMatch(final Object... parameters) { + return EndOfSiding_step_5.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1], (modes3.Segment) parameters[2]); + } + + /** + * Inner class allowing the singleton instance of {@link EndOfSiding_step_5} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link EndOfSiding_step_5#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final EndOfSiding_step_5 INSTANCE = new EndOfSiding_step_5(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final EndOfSiding_step_5.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final PParameter parameter_end = new PParameter("end", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location, parameter_end); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.endOfSiding_step_5"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location","end"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + PVariable var_end = body.getOrCreateVariableByName("end"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_end), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location), + new ExportedParameter(body, var_end, parameter_end) + )); + // // 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) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + // Segment.connectedTo(location, end) + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_location, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_1_, var_end); + // neg find multipleConnectedTo(end) + new NegativePatternCall(body, Tuples.flatTupleOf(var_end), MultipleConnectedTo.instance().getInternalQueryRepresentation()); + bodies.add(body); + } + return bodies; + } + } +} 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 @@ package modes3.queries; import modes3.queries.Adjacent; +import modes3.queries.CloseTrains_step_2; +import modes3.queries.CloseTrains_step_3; +import modes3.queries.CloseTrains_step_4; +import modes3.queries.CloseTrains_step_5; +import modes3.queries.CloseTrains_step_6; +import modes3.queries.CloseTrains_step_7; +import modes3.queries.ConnectedSegmentsDirected; import modes3.queries.ConnectedTo; import modes3.queries.ConnectedToNotSymmetric; import modes3.queries.ConnectedToReflexive; +import modes3.queries.EndOfSiding_step_2; +import modes3.queries.EndOfSiding_step_3; +import modes3.queries.EndOfSiding_step_4; +import modes3.queries.EndOfSiding_step_5; import modes3.queries.InputsOfTurnout; +import modes3.queries.MisalignedTurnout_step_2; +import modes3.queries.MisalignedTurnout_step_3; +import modes3.queries.MisalignedTurnout_step_4; +import modes3.queries.MisalignedTurnout_step_5; +import modes3.queries.MultipleConnectedTo; import modes3.queries.Output; import modes3.queries.OutputReflexive; import modes3.queries.Reachable; import modes3.queries.TooFewInputsOfTurnout; import modes3.queries.TooManyInputsOfSegment; import modes3.queries.TooManyInputsOfTurnout; +import modes3.queries.TrainLocations_step_2; +import modes3.queries.TrainLocations_step_3; import modes3.queries.TurnoutConnectedToBothOutputs; import modes3.queries.TurnoutOutput; import modes3.queries.TurnoutOutputsAreSame; @@ -44,6 +62,24 @@ import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedPatternGroup; *

  • tooFewInputsOfTurnout
  • *
  • reachable
  • *
  • unreachable
  • + *
  • closeTrains_step_2
  • + *
  • closeTrains_step_3
  • + *
  • closeTrains_step_4
  • + *
  • closeTrains_step_5
  • + *
  • closeTrains_step_6
  • + *
  • closeTrains_step_7
  • + *
  • trainLocations_step_2
  • + *
  • trainLocations_step_3
  • + *
  • misalignedTurnout_step_2
  • + *
  • misalignedTurnout_step_3
  • + *
  • misalignedTurnout_step_4
  • + *
  • misalignedTurnout_step_5
  • + *
  • connectedSegmentsDirected
  • + *
  • endOfSiding_step_2
  • + *
  • endOfSiding_step_3
  • + *
  • endOfSiding_step_4
  • + *
  • endOfSiding_step_5
  • + *
  • multipleConnectedTo
  • * * * @see IQueryGroup @@ -83,6 +119,24 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { querySpecifications.add(TooFewInputsOfTurnout.instance()); querySpecifications.add(Reachable.instance()); querySpecifications.add(Unreachable.instance()); + querySpecifications.add(CloseTrains_step_2.instance()); + querySpecifications.add(CloseTrains_step_3.instance()); + querySpecifications.add(CloseTrains_step_4.instance()); + querySpecifications.add(CloseTrains_step_5.instance()); + querySpecifications.add(CloseTrains_step_6.instance()); + querySpecifications.add(CloseTrains_step_7.instance()); + querySpecifications.add(TrainLocations_step_2.instance()); + querySpecifications.add(TrainLocations_step_3.instance()); + querySpecifications.add(MisalignedTurnout_step_2.instance()); + querySpecifications.add(MisalignedTurnout_step_3.instance()); + querySpecifications.add(MisalignedTurnout_step_4.instance()); + querySpecifications.add(MisalignedTurnout_step_5.instance()); + querySpecifications.add(ConnectedSegmentsDirected.instance()); + querySpecifications.add(EndOfSiding_step_2.instance()); + querySpecifications.add(EndOfSiding_step_3.instance()); + querySpecifications.add(EndOfSiding_step_4.instance()); + querySpecifications.add(EndOfSiding_step_5.instance()); + querySpecifications.add(MultipleConnectedTo.instance()); } public ConnectedTo getConnectedTo() { @@ -204,4 +258,148 @@ public final class Modes3Queries extends BaseGeneratedPatternGroup { public Unreachable.Matcher getUnreachable(final ViatraQueryEngine engine) { return Unreachable.Matcher.on(engine); } + + public CloseTrains_step_2 getCloseTrains_step_2() { + return CloseTrains_step_2.instance(); + } + + public CloseTrains_step_2.Matcher getCloseTrains_step_2(final ViatraQueryEngine engine) { + return CloseTrains_step_2.Matcher.on(engine); + } + + public CloseTrains_step_3 getCloseTrains_step_3() { + return CloseTrains_step_3.instance(); + } + + public CloseTrains_step_3.Matcher getCloseTrains_step_3(final ViatraQueryEngine engine) { + return CloseTrains_step_3.Matcher.on(engine); + } + + public CloseTrains_step_4 getCloseTrains_step_4() { + return CloseTrains_step_4.instance(); + } + + public CloseTrains_step_4.Matcher getCloseTrains_step_4(final ViatraQueryEngine engine) { + return CloseTrains_step_4.Matcher.on(engine); + } + + public CloseTrains_step_5 getCloseTrains_step_5() { + return CloseTrains_step_5.instance(); + } + + public CloseTrains_step_5.Matcher getCloseTrains_step_5(final ViatraQueryEngine engine) { + return CloseTrains_step_5.Matcher.on(engine); + } + + public CloseTrains_step_6 getCloseTrains_step_6() { + return CloseTrains_step_6.instance(); + } + + public CloseTrains_step_6.Matcher getCloseTrains_step_6(final ViatraQueryEngine engine) { + return CloseTrains_step_6.Matcher.on(engine); + } + + public CloseTrains_step_7 getCloseTrains_step_7() { + return CloseTrains_step_7.instance(); + } + + public CloseTrains_step_7.Matcher getCloseTrains_step_7(final ViatraQueryEngine engine) { + return CloseTrains_step_7.Matcher.on(engine); + } + + public TrainLocations_step_2 getTrainLocations_step_2() { + return TrainLocations_step_2.instance(); + } + + public TrainLocations_step_2.Matcher getTrainLocations_step_2(final ViatraQueryEngine engine) { + return TrainLocations_step_2.Matcher.on(engine); + } + + public TrainLocations_step_3 getTrainLocations_step_3() { + return TrainLocations_step_3.instance(); + } + + public TrainLocations_step_3.Matcher getTrainLocations_step_3(final ViatraQueryEngine engine) { + return TrainLocations_step_3.Matcher.on(engine); + } + + public MisalignedTurnout_step_2 getMisalignedTurnout_step_2() { + return MisalignedTurnout_step_2.instance(); + } + + public MisalignedTurnout_step_2.Matcher getMisalignedTurnout_step_2(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_2.Matcher.on(engine); + } + + public MisalignedTurnout_step_3 getMisalignedTurnout_step_3() { + return MisalignedTurnout_step_3.instance(); + } + + public MisalignedTurnout_step_3.Matcher getMisalignedTurnout_step_3(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_3.Matcher.on(engine); + } + + public MisalignedTurnout_step_4 getMisalignedTurnout_step_4() { + return MisalignedTurnout_step_4.instance(); + } + + public MisalignedTurnout_step_4.Matcher getMisalignedTurnout_step_4(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_4.Matcher.on(engine); + } + + public MisalignedTurnout_step_5 getMisalignedTurnout_step_5() { + return MisalignedTurnout_step_5.instance(); + } + + public MisalignedTurnout_step_5.Matcher getMisalignedTurnout_step_5(final ViatraQueryEngine engine) { + return MisalignedTurnout_step_5.Matcher.on(engine); + } + + public ConnectedSegmentsDirected getConnectedSegmentsDirected() { + return ConnectedSegmentsDirected.instance(); + } + + public ConnectedSegmentsDirected.Matcher getConnectedSegmentsDirected(final ViatraQueryEngine engine) { + return ConnectedSegmentsDirected.Matcher.on(engine); + } + + public EndOfSiding_step_2 getEndOfSiding_step_2() { + return EndOfSiding_step_2.instance(); + } + + public EndOfSiding_step_2.Matcher getEndOfSiding_step_2(final ViatraQueryEngine engine) { + return EndOfSiding_step_2.Matcher.on(engine); + } + + public EndOfSiding_step_3 getEndOfSiding_step_3() { + return EndOfSiding_step_3.instance(); + } + + public EndOfSiding_step_3.Matcher getEndOfSiding_step_3(final ViatraQueryEngine engine) { + return EndOfSiding_step_3.Matcher.on(engine); + } + + public EndOfSiding_step_4 getEndOfSiding_step_4() { + return EndOfSiding_step_4.instance(); + } + + public EndOfSiding_step_4.Matcher getEndOfSiding_step_4(final ViatraQueryEngine engine) { + return EndOfSiding_step_4.Matcher.on(engine); + } + + public EndOfSiding_step_5 getEndOfSiding_step_5() { + return EndOfSiding_step_5.instance(); + } + + public EndOfSiding_step_5.Matcher getEndOfSiding_step_5(final ViatraQueryEngine engine) { + return EndOfSiding_step_5.Matcher.on(engine); + } + + public MultipleConnectedTo getMultipleConnectedTo() { + return MultipleConnectedTo.instance(); + } + + public MultipleConnectedTo.Matcher getMultipleConnectedTo(final ViatraQueryEngine engine) { + return MultipleConnectedTo.Matcher.on(engine); + } } 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 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Inequality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern multipleConnectedTo(s : Segment) {
    + *         	Segment.connectedTo(s, n1);
    + *         	Segment.connectedTo(s, n2);
    + *         	n1 != n2;
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class MultipleConnectedTo extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.multipleConnectedTo pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Segment fS; + + private static List parameterNames = makeImmutableList("s"); + + private Match(final Segment pS) { + this.fS = pS; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "s": return this.fS; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fS; + default: return null; + } + } + + public Segment getS() { + return this.fS; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("s".equals(parameterName) ) { + this.fS = (Segment) newValue; + return true; + } + return false; + } + + public void setS(final Segment pS) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fS = pS; + } + + @Override + public String patternName() { + return "modes3.queries.multipleConnectedTo"; + } + + @Override + public List parameterNames() { + return MultipleConnectedTo.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fS}; + } + + @Override + public MultipleConnectedTo.Match toImmutable() { + return isMutable() ? newMatch(fS) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"s\"=" + prettyPrintValue(fS)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fS); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof MultipleConnectedTo.Match)) { + MultipleConnectedTo.Match other = (MultipleConnectedTo.Match) obj; + return Objects.equals(fS, other.fS); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public MultipleConnectedTo specification() { + return MultipleConnectedTo.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static MultipleConnectedTo.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static MultipleConnectedTo.Match newMutableMatch(final Segment pS) { + return new Mutable(pS); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the (partial) match object. + * + */ + public static MultipleConnectedTo.Match newMatch(final Segment pS) { + return new Immutable(pS); + } + + private static final class Mutable extends MultipleConnectedTo.Match { + Mutable(final Segment pS) { + super(pS); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends MultipleConnectedTo.Match { + Immutable(final Segment pS) { + super(pS); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.multipleConnectedTo pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern multipleConnectedTo(s : Segment) {
    +   * 	Segment.connectedTo(s, n1);
    +   * 	Segment.connectedTo(s, n2);
    +   * 	n1 != n2;
    +   * }
    +   * 
    + * + * @see Match + * @see MultipleConnectedTo + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static MultipleConnectedTo.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static MultipleConnectedTo.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_S = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(MultipleConnectedTo.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Segment pS) { + return rawStreamAllMatches(new Object[]{pS}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Segment pS) { + return rawStreamAllMatches(new Object[]{pS}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Segment pS) { + return rawGetOneArbitraryMatch(new Object[]{pS}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Segment pS) { + return rawHasMatch(new Object[]{pS}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Segment pS) { + return rawCountMatches(new Object[]{pS}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Segment pS, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pS}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pS the fixed value of pattern parameter s, or null if not bound. + * @return the (partial) match object. + * + */ + public MultipleConnectedTo.Match newMatch(final Segment pS) { + return MultipleConnectedTo.Match.newMatch(pS); + } + + /** + * Retrieve the set of values that occur in matches for s. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOfs(final Object[] parameters) { + return rawStreamAllValues(POSITION_S, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for s. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOfs() { + return rawStreamAllValuesOfs(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for s. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOfs() { + return rawStreamAllValuesOfs(emptyArray()); + } + + @Override + protected MultipleConnectedTo.Match tupleToMatch(final Tuple t) { + try { + return MultipleConnectedTo.Match.newMatch((Segment) t.get(POSITION_S)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected MultipleConnectedTo.Match arrayToMatch(final Object[] match) { + try { + return MultipleConnectedTo.Match.newMatch((Segment) match[POSITION_S]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected MultipleConnectedTo.Match arrayToMatchMutable(final Object[] match) { + try { + return MultipleConnectedTo.Match.newMutableMatch((Segment) match[POSITION_S]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return MultipleConnectedTo.instance(); + } + } + + private MultipleConnectedTo() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static MultipleConnectedTo instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected MultipleConnectedTo.Matcher instantiate(final ViatraQueryEngine engine) { + return MultipleConnectedTo.Matcher.on(engine); + } + + @Override + public MultipleConnectedTo.Matcher instantiate() { + return MultipleConnectedTo.Matcher.create(); + } + + @Override + public MultipleConnectedTo.Match newEmptyMatch() { + return MultipleConnectedTo.Match.newEmptyMatch(); + } + + @Override + public MultipleConnectedTo.Match newMatch(final Object... parameters) { + return MultipleConnectedTo.Match.newMatch((modes3.Segment) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link MultipleConnectedTo} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link MultipleConnectedTo#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final MultipleConnectedTo INSTANCE = new MultipleConnectedTo(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final MultipleConnectedTo.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_s = new PParameter("s", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_s); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.multipleConnectedTo"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("s"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_s = body.getOrCreateVariableByName("s"); + PVariable var_n1 = body.getOrCreateVariableByName("n1"); + PVariable var_n2 = body.getOrCreateVariableByName("n2"); + new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_s, parameter_s) + )); + // Segment.connectedTo(s, n1) + new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_s, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_n1); + // Segment.connectedTo(s, n2) + new TypeConstraint(body, Tuples.flatTupleOf(var_s), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + PVariable var__virtual_1_ = body.getOrCreateVariableByName(".virtual{1}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_s, var__virtual_1_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment", "connectedTo"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_1_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_1_, var_n2); + // n1 != n2 + new Inequality(body, var_n1, var_n2); + bodies.add(body); + } + return bodies; + } + } +} 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; * *

    Original source: *

    - *         //{@literal @}Constraint(message = "noInputOfSegment", severity = "error", key = { S })
    - *         //pattern noInputOfSegment(S : Segment) {
    - *         //	neg find turnout(S);
    - *         //	neg find output(_, S);
    - *         //}
    - *         
      *         {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
      *         pattern tooManyInputsOfSegment(S : SimpleSegment) {
      *         	find output(I1, S);
    @@ -251,12 +245,6 @@ public final class TooManyInputsOfSegment extends BaseGeneratedEMFQuerySpecifica
        * 
        * 

    Original source: *

    -   * //{@literal @}Constraint(message = "noInputOfSegment", severity = "error", key = { S })
    -   * //pattern noInputOfSegment(S : Segment) {
    -   * //	neg find turnout(S);
    -   * //	neg find output(_, S);
    -   * //}
    -   * 
        * {@literal @}Constraint(message = "tooManyInputsOfSegment", severity = "error", key = { S })
        * pattern tooManyInputsOfSegment(S : SimpleSegment) {
        * 	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 @@
    +/**
    + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql
    + */
    +package modes3.queries;
    +
    +import java.util.Arrays;
    +import java.util.Collection;
    +import java.util.LinkedHashSet;
    +import java.util.List;
    +import java.util.Objects;
    +import java.util.Optional;
    +import java.util.Set;
    +import java.util.function.Consumer;
    +import java.util.stream.Collectors;
    +import java.util.stream.Stream;
    +import modes3.Train;
    +import org.apache.log4j.Logger;
    +import org.eclipse.emf.ecore.EClass;
    +import org.eclipse.viatra.query.runtime.api.IPatternMatch;
    +import org.eclipse.viatra.query.runtime.api.IQuerySpecification;
    +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
    +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery;
    +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification;
    +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher;
    +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch;
    +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey;
    +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection;
    +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility;
    +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
    +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
    +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil;
    +
    +/**
    + * A pattern-specific query specification that can instantiate Matcher in a type-safe way.
    + * 
    + * 

    Original source: + *

    + *         //
    + *         // trainLocations
    + *         //
    + *         
    + *         pattern trainLocations_step_2(in train : Train) {
    + *         //   frame-{@literal >}train = model-{@literal >}trains[i0];
    + *         //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
    + *         //   if (frame-{@literal >}location != NULL) {
    + *         //     ...
    + *         //   }
    + *         
    + *         	Train(train);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class TrainLocations_step_2 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.trainLocations_step_2 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private static List parameterNames = makeImmutableList("train"); + + private Match(final Train pTrain) { + this.fTrain = pTrain; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + @Override + public String patternName() { + return "modes3.queries.trainLocations_step_2"; + } + + @Override + public List parameterNames() { + return TrainLocations_step_2.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain}; + } + + @Override + public TrainLocations_step_2.Match toImmutable() { + return isMutable() ? newMatch(fTrain) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof TrainLocations_step_2.Match)) { + TrainLocations_step_2.Match other = (TrainLocations_step_2.Match) obj; + return Objects.equals(fTrain, other.fTrain); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public TrainLocations_step_2 specification() { + return TrainLocations_step_2.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static TrainLocations_step_2.Match newEmptyMatch() { + return new Mutable(null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static TrainLocations_step_2.Match newMutableMatch(final Train pTrain) { + return new Mutable(pTrain); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public static TrainLocations_step_2.Match newMatch(final Train pTrain) { + return new Immutable(pTrain); + } + + private static final class Mutable extends TrainLocations_step_2.Match { + Mutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends TrainLocations_step_2.Match { + Immutable(final Train pTrain) { + super(pTrain); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.trainLocations_step_2 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * //
    +   * // trainLocations
    +   * //
    +   * 
    +   * pattern trainLocations_step_2(in train : Train) {
    +   * //   frame-{@literal >}train = model-{@literal >}trains[i0];
    +   * //   frame-{@literal >}location = frame-{@literal >}train-{@literal >}location;
    +   * //   if (frame-{@literal >}location != NULL) {
    +   * //     ...
    +   * //   }
    +   * 
    +   * 	Train(train);
    +   * }
    +   * 
    + * + * @see Match + * @see TrainLocations_step_2 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static TrainLocations_step_2.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static TrainLocations_step_2.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TrainLocations_step_2.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain) { + return rawStreamAllMatches(new Object[]{pTrain}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain) { + return rawGetOneArbitraryMatch(new Object[]{pTrain}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain) { + return rawHasMatch(new Object[]{pTrain}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain) { + return rawCountMatches(new Object[]{pTrain}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @return the (partial) match object. + * + */ + public TrainLocations_step_2.Match newMatch(final Train pTrain) { + return TrainLocations_step_2.Match.newMatch(pTrain); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + @Override + protected TrainLocations_step_2.Match tupleToMatch(final Tuple t) { + try { + return TrainLocations_step_2.Match.newMatch((Train) t.get(POSITION_TRAIN)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_2.Match arrayToMatch(final Object[] match) { + try { + return TrainLocations_step_2.Match.newMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_2.Match arrayToMatchMutable(final Object[] match) { + try { + return TrainLocations_step_2.Match.newMutableMatch((Train) match[POSITION_TRAIN]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return TrainLocations_step_2.instance(); + } + } + + private TrainLocations_step_2() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static TrainLocations_step_2 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected TrainLocations_step_2.Matcher instantiate(final ViatraQueryEngine engine) { + return TrainLocations_step_2.Matcher.on(engine); + } + + @Override + public TrainLocations_step_2.Matcher instantiate() { + return TrainLocations_step_2.Matcher.create(); + } + + @Override + public TrainLocations_step_2.Match newEmptyMatch() { + return TrainLocations_step_2.Match.newEmptyMatch(); + } + + @Override + public TrainLocations_step_2.Match newMatch(final Object... parameters) { + return TrainLocations_step_2.Match.newMatch((modes3.Train) parameters[0]); + } + + /** + * Inner class allowing the singleton instance of {@link TrainLocations_step_2} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link TrainLocations_step_2#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final TrainLocations_step_2 INSTANCE = new TrainLocations_step_2(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final TrainLocations_step_2.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.trainLocations_step_2"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train) + )); + // // frame->train = model->trains[i0];// frame->location = frame->train->location;// if (frame->location != NULL) {// ...// } Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + bodies.add(body); + } + return bodies; + } + } +} 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 @@ +/** + * Generated from platform:/resource/ca.mcgill.rtgmrt.example.modes3/src/modes3/queries/Modes3Queries.vql + */ +package modes3.queries; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import modes3.Segment; +import modes3.Train; +import org.apache.log4j.Logger; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.viatra.query.runtime.api.IQuerySpecification; +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFPQuery; +import org.eclipse.viatra.query.runtime.api.impl.BaseGeneratedEMFQuerySpecification; +import org.eclipse.viatra.query.runtime.api.impl.BaseMatcher; +import org.eclipse.viatra.query.runtime.api.impl.BasePatternMatch; +import org.eclipse.viatra.query.runtime.emf.types.EClassTransitiveInstancesKey; +import org.eclipse.viatra.query.runtime.emf.types.EStructuralFeatureInstancesKey; +import org.eclipse.viatra.query.runtime.matchers.backend.QueryEvaluationHint; +import org.eclipse.viatra.query.runtime.matchers.psystem.PBody; +import org.eclipse.viatra.query.runtime.matchers.psystem.PVariable; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.Equality; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicdeferred.ExportedParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.basicenumerables.TypeConstraint; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameter; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PParameterDirection; +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PVisibility; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple; +import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples; +import org.eclipse.viatra.query.runtime.util.ViatraQueryLoggingUtil; + +/** + * A pattern-specific query specification that can instantiate Matcher in a type-safe way. + * + *

    Original source: + *

    + *         pattern trainLocations_step_3(in train : Train, in location : Segment) {
    + *         //     results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    + *         //     results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    + *         	Train(train);
    + *             Train.location(train, location);
    + *         }
    + * 
    + * + * @see Matcher + * @see Match + * + */ +@SuppressWarnings("all") +public final class TrainLocations_step_3 extends BaseGeneratedEMFQuerySpecification { + /** + * Pattern-specific match representation of the modes3.queries.trainLocations_step_3 pattern, + * to be used in conjunction with {@link Matcher}. + * + *

    Class fields correspond to parameters of the pattern. Fields with value null are considered unassigned. + * Each instance is a (possibly partial) substitution of pattern parameters, + * usable to represent a match of the pattern in the result of a query, + * or to specify the bound (fixed) input parameters when issuing a query. + * + * @see Matcher + * + */ + public static abstract class Match extends BasePatternMatch { + private Train fTrain; + + private Segment fLocation; + + private static List parameterNames = makeImmutableList("train", "location"); + + private Match(final Train pTrain, final Segment pLocation) { + this.fTrain = pTrain; + this.fLocation = pLocation; + } + + @Override + public Object get(final String parameterName) { + switch(parameterName) { + case "train": return this.fTrain; + case "location": return this.fLocation; + default: return null; + } + } + + @Override + public Object get(final int index) { + switch(index) { + case 0: return this.fTrain; + case 1: return this.fLocation; + default: return null; + } + } + + public Train getTrain() { + return this.fTrain; + } + + public Segment getLocation() { + return this.fLocation; + } + + @Override + public boolean set(final String parameterName, final Object newValue) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + if ("train".equals(parameterName) ) { + this.fTrain = (Train) newValue; + return true; + } + if ("location".equals(parameterName) ) { + this.fLocation = (Segment) newValue; + return true; + } + return false; + } + + public void setTrain(final Train pTrain) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fTrain = pTrain; + } + + public void setLocation(final Segment pLocation) { + if (!isMutable()) throw new java.lang.UnsupportedOperationException(); + this.fLocation = pLocation; + } + + @Override + public String patternName() { + return "modes3.queries.trainLocations_step_3"; + } + + @Override + public List parameterNames() { + return TrainLocations_step_3.Match.parameterNames; + } + + @Override + public Object[] toArray() { + return new Object[]{fTrain, fLocation}; + } + + @Override + public TrainLocations_step_3.Match toImmutable() { + return isMutable() ? newMatch(fTrain, fLocation) : this; + } + + @Override + public String prettyPrint() { + StringBuilder result = new StringBuilder(); + result.append("\"train\"=" + prettyPrintValue(fTrain) + ", "); + result.append("\"location\"=" + prettyPrintValue(fLocation)); + return result.toString(); + } + + @Override + public int hashCode() { + return Objects.hash(fTrain, fLocation); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) { + return false; + } + if ((obj instanceof TrainLocations_step_3.Match)) { + TrainLocations_step_3.Match other = (TrainLocations_step_3.Match) obj; + return Objects.equals(fTrain, other.fTrain) && Objects.equals(fLocation, other.fLocation); + } else { + // this should be infrequent + if (!(obj instanceof IPatternMatch)) { + return false; + } + IPatternMatch otherSig = (IPatternMatch) obj; + return Objects.equals(specification(), otherSig.specification()) && Arrays.deepEquals(toArray(), otherSig.toArray()); + } + } + + @Override + public TrainLocations_step_3 specification() { + return TrainLocations_step_3.instance(); + } + + /** + * Returns an empty, mutable match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @return the empty match. + * + */ + public static TrainLocations_step_3.Match newEmptyMatch() { + return new Mutable(null, null); + } + + /** + * Returns a mutable (partial) match. + * Fields of the mutable match can be filled to create a partial match, usable as matcher input. + * + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the new, mutable (partial) match object. + * + */ + public static TrainLocations_step_3.Match newMutableMatch(final Train pTrain, final Segment pLocation) { + return new Mutable(pTrain, pLocation); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public static TrainLocations_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return new Immutable(pTrain, pLocation); + } + + private static final class Mutable extends TrainLocations_step_3.Match { + Mutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return true; + } + } + + private static final class Immutable extends TrainLocations_step_3.Match { + Immutable(final Train pTrain, final Segment pLocation) { + super(pTrain, pLocation); + } + + @Override + public boolean isMutable() { + return false; + } + } + } + + /** + * Generated pattern matcher API of the modes3.queries.trainLocations_step_3 pattern, + * providing pattern-specific query methods. + * + *

    Use the pattern matcher on a given model via {@link #on(ViatraQueryEngine)}, + * e.g. in conjunction with {@link ViatraQueryEngine#on(QueryScope)}. + * + *

    Matches of the pattern will be represented as {@link Match}. + * + *

    Original source: + *

    +   * pattern trainLocations_step_3(in train : Train, in location : Segment) {
    +   * //     results-{@literal >}matches[match_cntr].location = frame-{@literal >}location;
    +   * //     results-{@literal >}matches[match_cntr++].train = frame-{@literal >}train;
    +   * 	Train(train);
    +   *     Train.location(train, location);
    +   * }
    +   * 
    + * + * @see Match + * @see TrainLocations_step_3 + * + */ + public static class Matcher extends BaseMatcher { + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + public static TrainLocations_step_3.Matcher on(final ViatraQueryEngine engine) { + // check if matcher already exists + Matcher matcher = engine.getExistingMatcher(querySpecification()); + if (matcher == null) { + matcher = (Matcher)engine.getMatcher(querySpecification()); + } + return matcher; + } + + /** + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * @return an initialized matcher + * @noreference This method is for internal matcher initialization by the framework, do not call it manually. + * + */ + public static TrainLocations_step_3.Matcher create() { + return new Matcher(); + } + + private static final int POSITION_TRAIN = 0; + + private static final int POSITION_LOCATION = 1; + + private static final Logger LOGGER = ViatraQueryLoggingUtil.getLogger(TrainLocations_step_3.Matcher.class); + + /** + * Initializes the pattern matcher within an existing VIATRA Query engine. + * If the pattern matcher is already constructed in the engine, only a light-weight reference is returned. + * + * @param engine the existing VIATRA Query engine in which this matcher will be created. + * @throws ViatraQueryRuntimeException if an error occurs during pattern matcher creation + * + */ + private Matcher() { + super(querySpecification()); + } + + /** + * Returns the set of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return matches represented as a Match object. + * + */ + public Collection getAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}).collect(Collectors.toSet()); + } + + /** + * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a stream of matches represented as a Match object. + * + */ + public Stream streamAllMatches(final Train pTrain, final Segment pLocation) { + return rawStreamAllMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return a match represented as a Match object, or null if no match is found. + * + */ + public Optional getOneArbitraryMatch(final Train pTrain, final Segment pLocation) { + return rawGetOneArbitraryMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, + * under any possible substitution of the unspecified parameters (if any). + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return true if the input is a valid (partial) match of the pattern. + * + */ + public boolean hasMatch(final Train pTrain, final Segment pLocation) { + return rawHasMatch(new Object[]{pTrain, pLocation}); + } + + /** + * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the number of pattern matches found. + * + */ + public int countMatches(final Train pTrain, final Segment pLocation) { + return rawCountMatches(new Object[]{pTrain, pLocation}); + } + + /** + * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters. + * Neither determinism nor randomness of selection is guaranteed. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @param processor the action that will process the selected match. + * @return true if the pattern has at least one match with the given parameter values, false if the processor was not invoked + * + */ + public boolean forOneArbitraryMatch(final Train pTrain, final Segment pLocation, final Consumer processor) { + return rawForOneArbitraryMatch(new Object[]{pTrain, pLocation}, processor); + } + + /** + * Returns a new (partial) match. + * This can be used e.g. to call the matcher with a partial match. + *

    The returned match will be immutable. Use {@link #newEmptyMatch()} to obtain a mutable match object. + * @param pTrain the fixed value of pattern parameter train, or null if not bound. + * @param pLocation the fixed value of pattern parameter location, or null if not bound. + * @return the (partial) match object. + * + */ + public TrainLocations_step_3.Match newMatch(final Train pTrain, final Segment pLocation) { + return TrainLocations_step_3.Match.newMatch(pTrain, pLocation); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOftrain(final Object[] parameters) { + return rawStreamAllValues(POSITION_TRAIN, parameters).map(Train.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain() { + return rawStreamAllValuesOftrain(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for train. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOftrain(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for train. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOftrain(final Segment pLocation) { + return rawStreamAllValuesOftrain(new Object[]{null, pLocation}).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + protected Stream rawStreamAllValuesOflocation(final Object[] parameters) { + return rawStreamAllValues(POSITION_LOCATION, parameters).map(Segment.class::cast); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation() { + return rawStreamAllValuesOflocation(emptyArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()); + } + + /** + * Retrieve the set of values that occur in matches for location. + *

    + * NOTE: It is important not to modify the source model while the stream is being processed. + * If the match set of the pattern changes during processing, the contents of the stream is undefined. + * In such cases, either rely on {@link #getAllMatches()} or collect the results of the stream in end-user code. + * + * @return the Stream of all values or empty set if there are no matches + * + */ + public Stream streamAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final TrainLocations_step_3.Match partialMatch) { + return rawStreamAllValuesOflocation(partialMatch.toArray()).collect(Collectors.toSet()); + } + + /** + * Retrieve the set of values that occur in matches for location. + * @return the Set of all values or empty set if there are no matches + * + */ + public Set getAllValuesOflocation(final Train pTrain) { + return rawStreamAllValuesOflocation(new Object[]{pTrain, null}).collect(Collectors.toSet()); + } + + @Override + protected TrainLocations_step_3.Match tupleToMatch(final Tuple t) { + try { + return TrainLocations_step_3.Match.newMatch((Train) t.get(POSITION_TRAIN), (Segment) t.get(POSITION_LOCATION)); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in tuple not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_3.Match arrayToMatch(final Object[] match) { + try { + return TrainLocations_step_3.Match.newMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + @Override + protected TrainLocations_step_3.Match arrayToMatchMutable(final Object[] match) { + try { + return TrainLocations_step_3.Match.newMutableMatch((Train) match[POSITION_TRAIN], (Segment) match[POSITION_LOCATION]); + } catch(ClassCastException e) { + LOGGER.error("Element(s) in array not properly typed!",e); + return null; + } + } + + /** + * @return the singleton instance of the query specification of this pattern + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static IQuerySpecification querySpecification() { + return TrainLocations_step_3.instance(); + } + } + + private TrainLocations_step_3() { + super(GeneratedPQuery.INSTANCE); + } + + /** + * @return the singleton instance of the query specification + * @throws ViatraQueryRuntimeException if the pattern definition could not be loaded + * + */ + public static TrainLocations_step_3 instance() { + try{ + return LazyHolder.INSTANCE; + } catch (ExceptionInInitializerError err) { + throw processInitializerError(err); + } + } + + @Override + protected TrainLocations_step_3.Matcher instantiate(final ViatraQueryEngine engine) { + return TrainLocations_step_3.Matcher.on(engine); + } + + @Override + public TrainLocations_step_3.Matcher instantiate() { + return TrainLocations_step_3.Matcher.create(); + } + + @Override + public TrainLocations_step_3.Match newEmptyMatch() { + return TrainLocations_step_3.Match.newEmptyMatch(); + } + + @Override + public TrainLocations_step_3.Match newMatch(final Object... parameters) { + return TrainLocations_step_3.Match.newMatch((modes3.Train) parameters[0], (modes3.Segment) parameters[1]); + } + + /** + * Inner class allowing the singleton instance of {@link TrainLocations_step_3} to be created + * not at the class load time of the outer class, + * but rather at the first call to {@link TrainLocations_step_3#instance()}. + * + *

    This workaround is required e.g. to support recursion. + * + */ + private static class LazyHolder { + private static final TrainLocations_step_3 INSTANCE = new TrainLocations_step_3(); + + /** + * Statically initializes the query specification after the field {@link #INSTANCE} is assigned. + * This initialization order is required to support indirect recursion. + * + *

    The static initializer is defined using a helper field to work around limitations of the code generator. + * + */ + private static final Object STATIC_INITIALIZER = ensureInitialized(); + + public static Object ensureInitialized() { + INSTANCE.ensureInitializedInternal(); + return null; + } + } + + private static class GeneratedPQuery extends BaseGeneratedEMFPQuery { + private static final TrainLocations_step_3.GeneratedPQuery INSTANCE = new GeneratedPQuery(); + + private final PParameter parameter_train = new PParameter("train", "modes3.Train", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Train")), PParameterDirection.INOUT); + + private final PParameter parameter_location = new PParameter("location", "modes3.Segment", new EClassTransitiveInstancesKey((EClass)getClassifierLiteralSafe("http://www.ece.mcgill.ca/wcet/modes3", "Segment")), PParameterDirection.INOUT); + + private final List parameters = Arrays.asList(parameter_train, parameter_location); + + private GeneratedPQuery() { + super(PVisibility.PUBLIC); + } + + @Override + public String getFullyQualifiedName() { + return "modes3.queries.trainLocations_step_3"; + } + + @Override + public List getParameterNames() { + return Arrays.asList("train","location"); + } + + @Override + public List getParameters() { + return parameters; + } + + @Override + public Set doGetContainedBodies() { + setEvaluationHints(new QueryEvaluationHint(null, QueryEvaluationHint.BackendRequirement.UNSPECIFIED)); + Set bodies = new LinkedHashSet<>(); + { + PBody body = new PBody(this); + PVariable var_train = body.getOrCreateVariableByName("train"); + PVariable var_location = body.getOrCreateVariableByName("location"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + new TypeConstraint(body, Tuples.flatTupleOf(var_location), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + body.setSymbolicParameters(Arrays.asList( + new ExportedParameter(body, var_train, parameter_train), + new ExportedParameter(body, var_location, parameter_location) + )); + // // results->matches[match_cntr].location = frame->location;// results->matches[match_cntr++].train = frame->train; Train(train) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + // Train.location(train, location) + new TypeConstraint(body, Tuples.flatTupleOf(var_train), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train"))); + PVariable var__virtual_0_ = body.getOrCreateVariableByName(".virtual{0}"); + new TypeConstraint(body, Tuples.flatTupleOf(var_train, var__virtual_0_), new EStructuralFeatureInstancesKey(getFeatureLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Train", "location"))); + new TypeConstraint(body, Tuples.flatTupleOf(var__virtual_0_), new EClassTransitiveInstancesKey((EClass)getClassifierLiteral("http://www.ece.mcgill.ca/wcet/modes3", "Segment"))); + new Equality(body, var__virtual_0_, var_location); + bodies.add(body); + } + return bodies; + } + } +} 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 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.CloseTrainsObjectiveHint.xtendbin 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 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.EndOfSidingObjectiveHint.xtendbin 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 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.MisalignedTurnoutObjectiveHint.xtendbin 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 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3ModelGenerator.xtendbin 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 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3TypeScopeHint.xtendbin 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 Binary files a/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.Modes3UnitPropagationGenerator.xtendbin 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 Binary files /dev/null and b/Domains/ca.mcgill.rtgmrt.example.modes3/xtend-gen/modes3/run/.TrainLocationsObjectiveHint.xtendbin 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 @@ /.Modes3ModelGenerator.java._trace /.Modes3UnitPropagationGenerator.java._trace /.Modes3TypeScopeHint.java._trace +/.Modes3TypeScopeHint.xtendbin +/.Modes3UnitPropagationGenerator.xtendbin +/Modes3TypeScopeHint.java +/.Modes3ModelGenerator.xtendbin +/Modes3ModelGenerator.java +/Modes3UnitPropagationGenerator.java +/.CloseTrainsObjectiveHint.java._trace +/.TrainLocationsObjectiveHint.java._trace +/.MisalignedTurnoutObjectiveHint.java._trace +/.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 @@ +package modes3.run; + +import com.google.common.base.Objects; +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.CloseTrains_step_2; +import modes3.queries.CloseTrains_step_3; +import modes3.queries.CloseTrains_step_4; +import modes3.queries.CloseTrains_step_5; +import modes3.queries.CloseTrains_step_6; +import modes3.queries.CloseTrains_step_7; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class CloseTrainsObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type trainType; + + public CloseTrainsObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(CloseTrains_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(CloseTrains_step_3.instance().getFullyQualifiedName()); + final CostElementMatchers step4 = costElementMatchers.get(CloseTrains_step_4.instance().getFullyQualifiedName()); + final CostElementMatchers step5 = costElementMatchers.get(CloseTrains_step_5.instance().getFullyQualifiedName()); + final CostElementMatchers step6 = costElementMatchers.get(CloseTrains_step_6.instance().getFullyQualifiedName()); + final CostElementMatchers step7 = costElementMatchers.get(CloseTrains_step_7.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_1 = (CostElementMatch it_1) -> { + return step2.projectMayMatch(it_1.getMatch(), 2); + }; + Set>> _entrySet = IterableExtensions.groupBy(step3Matches, _function_1).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m_2 : _value) { + multiplicityBuilder.add(1, m_2.getMatch()); + } + multiplicityBuilder.add((-1), pair.getKey()); + multiplicityBuilder.build().assertEqualsTo(0); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1); + CloseTrainsObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1); + final ImmutableList step4Matches = step4.getMatches(); + for (final CostElementMatch m_2 : step4Matches) { + { + final Dimension dimension = it.getDimension(m_2.getMatch()); + objectiveBuilder.add(step4.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_2.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_2.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_2 = (CostElementMatch it_1) -> { + return step3.projectMayMatch(it_1.getMatch(), 2, 3); + }; + Set>> _entrySet_1 = IterableExtensions.groupBy(step4Matches, _function_2).entrySet(); + for (final Map.Entry> pair_1 : _entrySet_1) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_1.getValue(); + for (final CostElementMatch m_3 : _value) { + multiplicityBuilder.add(1, m_3.getMatch()); + } + multiplicityBuilder.add((-2), pair_1.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 2, this.trainType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step4Matches, 4, this.segmentType, 2); + final ImmutableList step5Matches = step5.getMatches(); + for (final CostElementMatch m_3 : step5Matches) { + { + final Dimension dimension = it.getDimension(m_3.getMatch()); + objectiveBuilder.add(step5.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_3.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_3.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_3 = (CostElementMatch it_1) -> { + return step4.projectMayMatch(it_1.getMatch(), 2, 3, 4); + }; + Set>> _entrySet_2 = IterableExtensions.groupBy(step5Matches, _function_3).entrySet(); + for (final Map.Entry> pair_2 : _entrySet_2) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_2.getValue(); + for (final CostElementMatch m_4 : _value) { + multiplicityBuilder.add(1, m_4.getMatch()); + } + multiplicityBuilder.add((-2), pair_2.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 2, this.trainType, 4); + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 4); + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 4, this.segmentType, 4); + CloseTrainsObjectiveHint.boundLimit(it, step5Matches, 5, this.segmentType, 4); + final ImmutableList step6Matches = step6.getMatches(); + for (final CostElementMatch m_4 : step6Matches) { + { + final Dimension dimension = it.getDimension(m_4.getMatch()); + objectiveBuilder.add(step6.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_4.isMulti(); + if (_isMulti) { + Object _get = m_4.getMatch().get(3); + Object _get_1 = m_4.getMatch().get(5); + boolean _equals = Objects.equal(_get, _get_1); + if (_equals) { + it.createBuilder().add(2, m_4.getMatch()).add((-1), step5.projectMayMatch(m_4.getMatch(), 2, 3, 4, 5)).build().assertEqualsTo(0); + } else { + it.createBuilder().add(1, m_4.getMatch()).add((-1), step5.projectMayMatch(m_4.getMatch(), 2, 3, 4, 5)).build().assertEqualsTo(0); + } + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_4.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 2, this.trainType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 3, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 4, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step6Matches, 5, this.segmentType, 2); + final ImmutableList step7Matches = step7.getMatches(); + for (final CostElementMatch m_5 : step7Matches) { + { + final Dimension dimension = it.getDimension(m_5.getMatch()); + objectiveBuilder.add(step7.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_5.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_5.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_4 = (CostElementMatch it_1) -> { + return step6.projectMayMatch(it_1.getMatch(), 2, 3, 4, 5); + }; + Set>> _entrySet_3 = IterableExtensions.groupBy(step7Matches, _function_4).entrySet(); + for (final Map.Entry> pair_3 : _entrySet_3) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_3.getValue(); + for (final CostElementMatch m_6 : _value) { + multiplicityBuilder.add(1, m_6.getMatch()); + } + multiplicityBuilder.add((-1), pair_3.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 2, this.trainType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 3, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 4, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 5, this.segmentType, 2); + CloseTrainsObjectiveHint.boundLimit(it, step7Matches, 6, this.trainType, 2); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} 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 @@ +package modes3.run; + +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.EndOfSiding_step_2; +import modes3.queries.EndOfSiding_step_3; +import modes3.queries.EndOfSiding_step_4; +import modes3.queries.EndOfSiding_step_5; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class EndOfSidingObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type trainType; + + public EndOfSidingObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(EndOfSiding_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(EndOfSiding_step_3.instance().getFullyQualifiedName()); + final CostElementMatchers step4 = costElementMatchers.get(EndOfSiding_step_4.instance().getFullyQualifiedName()); + final CostElementMatchers step5 = costElementMatchers.get(EndOfSiding_step_5.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_1 = (CostElementMatch it_1) -> { + return step2.projectMayMatch(it_1.getMatch(), 2); + }; + Set>> _entrySet = IterableExtensions.groupBy(step3Matches, _function_1).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m_2 : _value) { + multiplicityBuilder.add(1, m_2.getMatch()); + } + multiplicityBuilder.add((-1), pair.getKey()); + multiplicityBuilder.build().assertEqualsTo(0); + } + } + EndOfSidingObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1); + EndOfSidingObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1); + final ImmutableList step4Matches = step4.getMatches(); + for (final CostElementMatch m_2 : step4Matches) { + { + final Dimension dimension = it.getDimension(m_2.getMatch()); + objectiveBuilder.add(step4.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_2.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_2.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_2 = (CostElementMatch it_1) -> { + return step3.projectMayMatch(it_1.getMatch(), 2, 3); + }; + Set>> _entrySet_1 = IterableExtensions.groupBy(step4Matches, _function_2).entrySet(); + for (final Map.Entry> pair_1 : _entrySet_1) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_1.getValue(); + for (final CostElementMatch m_3 : _value) { + multiplicityBuilder.add(1, m_3.getMatch()); + } + multiplicityBuilder.add((-2), pair_1.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 2, this.trainType, 2); + EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2); + EndOfSidingObjectiveHint.boundLimit(it, step4Matches, 4, this.segmentType, 2); + final ImmutableList step5Matches = step5.getMatches(); + for (final CostElementMatch m_3 : step5Matches) { + { + final Dimension dimension = it.getDimension(m_3.getMatch()); + objectiveBuilder.add(step5.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_3.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_3.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + it.createBuilder().add(1, m_3.getMatch()).add((-1), step4.projectMayMatch(m_3.getMatch(), 2, 3, 4)).build().tightenUpperBound(Integer.valueOf(0)); + } + } + EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 2, this.trainType, 1); + EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 2); + EndOfSidingObjectiveHint.boundLimit(it, step5Matches, 4, this.segmentType, 1); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} 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 @@ +package modes3.run; + +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.MisalignedTurnout_step_2; +import modes3.queries.MisalignedTurnout_step_3; +import modes3.queries.MisalignedTurnout_step_4; +import modes3.queries.MisalignedTurnout_step_5; +import org.eclipse.viatra.query.runtime.api.IPatternMatch; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class MisalignedTurnoutObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type turnoutType; + + private final Type trainType; + + public MisalignedTurnoutObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.turnoutType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTurnout()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(MisalignedTurnout_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(MisalignedTurnout_step_3.instance().getFullyQualifiedName()); + final CostElementMatchers step4 = costElementMatchers.get(MisalignedTurnout_step_4.instance().getFullyQualifiedName()); + final CostElementMatchers step5 = costElementMatchers.get(MisalignedTurnout_step_5.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.turnoutType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_1 = (CostElementMatch it_1) -> { + return step2.projectMayMatch(it_1.getMatch(), 2); + }; + Set>> _entrySet = IterableExtensions.groupBy(step3Matches, _function_1).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m_2 : _value) { + multiplicityBuilder.add(1, m_2.getMatch()); + } + multiplicityBuilder.add((-1), pair.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + MisalignedTurnoutObjectiveHint.boundLimit(it, step3Matches, 2, this.turnoutType, 1); + MisalignedTurnoutObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 2); + final ImmutableList step4Matches = step4.getMatches(); + for (final CostElementMatch m_2 : step4Matches) { + { + final Dimension dimension = it.getDimension(m_2.getMatch()); + objectiveBuilder.add(step4.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_2.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_2.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + it.createBuilder().add(1, m_2.getMatch()).add((-1), step3.projectMayMatch(m_2.getMatch(), 2, 3)).build().tightenUpperBound(Integer.valueOf(0)); + } + } + MisalignedTurnoutObjectiveHint.boundLimit(it, step4Matches, 2, this.turnoutType, 1); + MisalignedTurnoutObjectiveHint.boundLimit(it, step4Matches, 3, this.segmentType, 2); + final ImmutableList step5Matches = step5.getMatches(); + for (final CostElementMatch m_3 : step5Matches) { + { + final Dimension dimension = it.getDimension(m_3.getMatch()); + objectiveBuilder.add(step5.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_3.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_3.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final Function1 _function_2 = (CostElementMatch it_1) -> { + return step4.projectMayMatch(it_1.getMatch(), 2, 3); + }; + Set>> _entrySet_1 = IterableExtensions.groupBy(step5Matches, _function_2).entrySet(); + for (final Map.Entry> pair_1 : _entrySet_1) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = it.createBuilder(); + List _value = pair_1.getValue(); + for (final CostElementMatch m_4 : _value) { + multiplicityBuilder.add(1, m_4.getMatch()); + } + multiplicityBuilder.add((-1), pair_1.getKey()); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } + } + MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 2, this.turnoutType, 1); + MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 3, this.segmentType, 2); + MisalignedTurnoutObjectiveHint.boundLimit(it, step5Matches, 4, this.trainType, 2); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} 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 import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.Ecore2logicannotationsPackage; import hu.bme.mit.inf.dslreasoner.ecore2logic.ecore2logicannotations.InverseRelationAssertion; import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; +import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicModelInterpretation; import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicProblemBuilder; import hu.bme.mit.inf.dslreasoner.logic.model.builder.SolutionScope; import hu.bme.mit.inf.dslreasoner.logic.model.builder.TracedOutput; @@ -32,6 +33,7 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem; import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; +import hu.bme.mit.inf.dslreasoner.logic2ecore.Logic2Ecore; import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2Logic; import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicConfiguration; import hu.bme.mit.inf.dslreasoner.viatra2logic.Viatra2LogicTrace; @@ -50,10 +52,15 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.par import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RelationLink; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretation2Gml; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DebugConfiguration; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.StateCoderStrategy; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasoner; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PartialModelAsLogicInterpretation; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold; import hu.bme.mit.inf.dslreasoner.visualisation.pi2graphviz.GraphvizVisualiser; import hu.bme.mit.inf.dslreasoner.workspace.FileSystemWorkspace; import java.util.Collections; @@ -64,10 +71,31 @@ import java.util.function.Predicate; import modes3.Modes3Factory; import modes3.Modes3ModelRoot; import modes3.Modes3Package; +import modes3.queries.CloseTrains_step_2; +import modes3.queries.CloseTrains_step_3; +import modes3.queries.CloseTrains_step_4; +import modes3.queries.CloseTrains_step_5; +import modes3.queries.CloseTrains_step_6; +import modes3.queries.CloseTrains_step_7; +import modes3.queries.EndOfSiding_step_2; +import modes3.queries.EndOfSiding_step_3; +import modes3.queries.EndOfSiding_step_4; +import modes3.queries.EndOfSiding_step_5; +import modes3.queries.MisalignedTurnout_step_2; +import modes3.queries.MisalignedTurnout_step_3; +import modes3.queries.MisalignedTurnout_step_4; +import modes3.queries.MisalignedTurnout_step_5; import modes3.queries.Modes3Queries; +import modes3.queries.TrainLocations_step_2; +import modes3.queries.TrainLocations_step_3; +import modes3.run.CloseTrainsObjectiveHint; +import modes3.run.EndOfSidingObjectiveHint; +import modes3.run.MisalignedTurnoutObjectiveHint; import modes3.run.Modes3TypeScopeHint; import modes3.run.Modes3UnitPropagationGenerator; +import modes3.run.TrainLocationsObjectiveHint; import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; @@ -102,6 +130,10 @@ public class Modes3ModelGenerator { private enum MonitoringQuery { closeTrains, + trainLocations, + + endOfSiding, + misalignedTurnout; } @@ -183,8 +215,9 @@ public class Modes3ModelGenerator { ObjectExtensions.>operator_doubleArrow( it_1.minNewElementsByType, _function_4); final Procedure1> _function_5 = (Map it_2) -> { - it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf(5)); - it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf(5)); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTrain()), Integer.valueOf((this.modelSize / 5))); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getTurnout()), Integer.valueOf((this.modelSize / 5))); + it_2.put(this.ecore2Logic.TypeofEClass(metamodelLogic.getTrace(), Modes3Package.eINSTANCE.getSimpleSegment()), Integer.valueOf(((3 * this.modelSize) / 5))); }; ObjectExtensions.>operator_doubleArrow( it_1.maxNewElementsByType, _function_5); @@ -196,7 +229,9 @@ public class Modes3ModelGenerator { }; ObjectExtensions.operator_doubleArrow( it.solutionScope, _function_4); - it.scopeWeight = 5; + CostObjectiveConfiguration _objective = this.getObjective(this.ecore2Logic, metamodelLogic.getTrace()); + it.costObjectives.add(_objective); + it.scopeWeight = 6; it.nameNewElements = false; it.typeInferenceMethod = TypeInferenceMethod.PreliminaryAnalysis; it.stateCoderStrategy = StateCoderStrategy.PairwiseNeighbourhood; @@ -224,80 +259,103 @@ public class Modes3ModelGenerator { URI _xifexpression = null; if ((solution instanceof ModelResult)) { InputOutput.println("Saving generated solutions"); - final EList representations = ((ModelResult)solution).getRepresentation(); - int _size = representations.size(); + final Logic2Ecore logic2Ecore = new Logic2Ecore(this.ecore2Logic); + final List interpretations = this.solver.getInterpretations(((ModelResult)solution)); + int _size = interpretations.size(); ExclusiveRange _doubleDotLessThan = new ExclusiveRange(0, _size, true); for (final Integer representationIndex : _doubleDotLessThan) { { - final Object representation = representations.get((representationIndex).intValue()); + final LogicModelInterpretation interpretation = interpretations.get((representationIndex).intValue()); final int representationNumber = ((representationIndex).intValue() + 1); - if ((representation instanceof PartialInterpretation)) { + if ((interpretation instanceof PartialModelAsLogicInterpretation)) { + final PartialInterpretation representation = ((PartialModelAsLogicInterpretation)interpretation).getPartialInterpretation(); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("solution"); _builder_1.append(representationNumber); _builder_1.append(".partialinterpretation"); - workspace.writeModel(((EObject)representation), _builder_1.toString()); + workspace.writeModel(representation, _builder_1.toString()); final PartialInterpretation2Gml partialInterpretation2GML = new PartialInterpretation2Gml(); - final String gml = partialInterpretation2GML.transform(((PartialInterpretation)representation)); + final String gml = partialInterpretation2GML.transform(representation); StringConcatenation _builder_2 = new StringConcatenation(); _builder_2.append("solution"); _builder_2.append(representationNumber); _builder_2.append(".gml"); workspace.writeText(_builder_2.toString(), gml); - int _size_1 = ((PartialInterpretation)representation).getNewElements().size(); - boolean _lessThan = (_size_1 < 160); - if (_lessThan) { - if ((representation instanceof PartialInterpretation)) { - final Function1 _function_3 = (Type it) -> { + final EObject model = logic2Ecore.transformInterpretation(interpretation, metamodelLogic.getTrace()); + final TreeIterator iterator = model.eAllContents(); + int id = 0; + while (iterator.hasNext()) { + { + final EObject obj = iterator.next(); + final Function1 _function_3 = (EAttribute it) -> { String _name_2 = it.getName(); - return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart")); + return Boolean.valueOf(Objects.equal(_name_2, "id")); }; - Type _findFirst = IterableExtensions.findFirst(((PartialInterpretation)representation).getProblem().getTypes(), _function_3); - final TypeDefinition rootType = ((TypeDefinition) _findFirst); - final Function1 _function_4 = (PartialComplexTypeInterpretation it) -> { - String _name_2 = it.getInterpretationOf().getName(); - return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class")); - }; - final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.findFirst(Iterables.filter(((PartialInterpretation)representation).getPartialtypeinterpratation(), - PartialComplexTypeInterpretation.class), _function_4); - rootIntepretation.getElements().removeAll(rootType.getElements()); - ((PartialInterpretation)representation).getProblem().getElements().removeAll(rootType.getElements()); - EList _partialrelationinterpretation = ((PartialInterpretation)representation).getPartialrelationinterpretation(); - for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) { - final Predicate _function_5 = (RelationLink link) -> { - boolean _xifexpression_1 = false; - if ((link instanceof BinaryElementRelationLink)) { - _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) || rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2())); - } else { - _xifexpression_1 = false; - } - return _xifexpression_1; - }; - relationInterpretation.getRelationlinks().removeIf(_function_5); + final EAttribute idFeature = IterableExtensions.findFirst(obj.eClass().getEAllAttributes(), _function_3); + if ((idFeature != null)) { + obj.eSet(idFeature, Integer.valueOf(id)); + id++; } - rootType.getElements().clear(); } + } + StringConcatenation _builder_3 = new StringConcatenation(); + _builder_3.append("solution"); + _builder_3.append(representationNumber); + _builder_3.append(".modes3"); + workspace.writeModel(model, _builder_3.toString()); + int _size_1 = representation.getNewElements().size(); + boolean _lessThan = (_size_1 < 160); + if (_lessThan) { + final Function1 _function_3 = (Type it) -> { + String _name_2 = it.getName(); + return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class DefinedPart")); + }; + Type _findFirst = IterableExtensions.findFirst(representation.getProblem().getTypes(), _function_3); + final TypeDefinition rootType = ((TypeDefinition) _findFirst); + final Function1 _function_4 = (PartialComplexTypeInterpretation it) -> { + String _name_2 = it.getInterpretationOf().getName(); + return Boolean.valueOf(Objects.equal(_name_2, "Modes3ModelRoot class")); + }; + final PartialComplexTypeInterpretation rootIntepretation = IterableExtensions.findFirst(Iterables.filter(representation.getPartialtypeinterpratation(), + PartialComplexTypeInterpretation.class), _function_4); + rootIntepretation.getElements().removeAll(rootType.getElements()); + representation.getProblem().getElements().removeAll(rootType.getElements()); + EList _partialrelationinterpretation = representation.getPartialrelationinterpretation(); + for (final PartialRelationInterpretation relationInterpretation : _partialrelationinterpretation) { + final Predicate _function_5 = (RelationLink link) -> { + boolean _xifexpression_1 = false; + if ((link instanceof BinaryElementRelationLink)) { + _xifexpression_1 = (rootType.getElements().contains(((BinaryElementRelationLink)link).getParam1()) || + rootType.getElements().contains(((BinaryElementRelationLink)link).getParam2())); + } else { + _xifexpression_1 = false; + } + return _xifexpression_1; + }; + relationInterpretation.getRelationlinks().removeIf(_function_5); + } + rootType.getElements().clear(); final GraphvizVisualiser visualiser = new GraphvizVisualiser(); - final PartialInterpretationVisualisation visualisation = visualiser.visualiseConcretization(((PartialInterpretation)representation)); - StringConcatenation _builder_3 = new StringConcatenation(); - _builder_3.append("solution"); - _builder_3.append(representationNumber); - _builder_3.append(".png"); - visualisation.writeToFile(workspace, _builder_3.toString()); + final PartialInterpretationVisualisation visualisation = visualiser.visualiseConcretization(representation); + StringConcatenation _builder_4 = new StringConcatenation(); + _builder_4.append("solution"); + _builder_4.append(representationNumber); + _builder_4.append(".png"); + visualisation.writeToFile(workspace, _builder_4.toString()); } } else { - StringConcatenation _builder_4 = new StringConcatenation(); - _builder_4.append("solution"); - _builder_4.append(representationNumber); - _builder_4.append(".txt"); - workspace.writeText(_builder_4.toString(), representation.toString()); + StringConcatenation _builder_5 = new StringConcatenation(); + _builder_5.append("solution"); + _builder_5.append(representationNumber); + _builder_5.append(".txt"); + workspace.writeText(_builder_5.toString(), interpretation.toString()); } } } } else { URI _xblockexpression_1 = null; { - InputOutput.println("Failed to solver problem"); + InputOutput.println("Failed to solve problem"); final LogicProblem partial = logic.getOutput(); _xblockexpression_1 = workspace.writeModel(partial, "solution.partialinterpretation"); } @@ -354,6 +412,153 @@ public class Modes3ModelGenerator { return _xblockexpression; } + public CostObjectiveConfiguration getObjective(final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + CostObjectiveConfiguration _costObjectiveConfiguration = new CostObjectiveConfiguration(); + final Procedure1 _function = (CostObjectiveConfiguration it) -> { + final Modes3ModelGenerator.MonitoringQuery monitoringQuery = this.monitoringQuery; + if (monitoringQuery != null) { + switch (monitoringQuery) { + case closeTrains: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration = new CostObjectiveElementConfiguration(); + final Procedure1 _function_1 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration, _function_1); + it.elements.add(_doubleArrow); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_1 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_2 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_3.instance().getFullyQualifiedName(); + it_1.weight = (21 + 14); + }; + CostObjectiveElementConfiguration _doubleArrow_1 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_1, _function_2); + it.elements.add(_doubleArrow_1); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_2 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_3 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_4.instance().getFullyQualifiedName(); + it_1.weight = (((14 + 44) + 14) + 9); + }; + CostObjectiveElementConfiguration _doubleArrow_2 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_2, _function_3); + it.elements.add(_doubleArrow_2); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_3 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_4 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_5.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 41) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_3 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_3, _function_4); + it.elements.add(_doubleArrow_3); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_4 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_5 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_6.instance().getFullyQualifiedName(); + it_1.weight = 27; + }; + CostObjectiveElementConfiguration _doubleArrow_4 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_4, _function_5); + it.elements.add(_doubleArrow_4); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_5 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_6 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = CloseTrains_step_7.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_5 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_5, _function_6); + it.elements.add(_doubleArrow_5); + CloseTrainsObjectiveHint _closeTrainsObjectiveHint = new CloseTrainsObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _closeTrainsObjectiveHint; + break; + case trainLocations: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_6 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_7 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = TrainLocations_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_6 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_6, _function_7); + it.elements.add(_doubleArrow_6); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_7 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_8 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = TrainLocations_step_3.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_7 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_7, _function_8); + it.elements.add(_doubleArrow_7); + TrainLocationsObjectiveHint _trainLocationsObjectiveHint = new TrainLocationsObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _trainLocationsObjectiveHint; + break; + case misalignedTurnout: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_8 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_9 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_8 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_8, _function_9); + it.elements.add(_doubleArrow_8); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_9 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_10 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_3.instance().getFullyQualifiedName(); + it_1.weight = 108; + }; + CostObjectiveElementConfiguration _doubleArrow_9 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_9, _function_10); + it.elements.add(_doubleArrow_9); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_10 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_11 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_4.instance().getFullyQualifiedName(); + it_1.weight = 27; + }; + CostObjectiveElementConfiguration _doubleArrow_10 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_10, _function_11); + it.elements.add(_doubleArrow_10); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_11 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_12 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = MisalignedTurnout_step_5.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_11 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_11, _function_12); + it.elements.add(_doubleArrow_11); + MisalignedTurnoutObjectiveHint _misalignedTurnoutObjectiveHint = new MisalignedTurnoutObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _misalignedTurnoutObjectiveHint; + break; + case endOfSiding: + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_12 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_13 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_2.instance().getFullyQualifiedName(); + it_1.weight = ((14 + 53) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_12 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_12, _function_13); + it.elements.add(_doubleArrow_12); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_13 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_14 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_3.instance().getFullyQualifiedName(); + it_1.weight = (21 + 14); + }; + CostObjectiveElementConfiguration _doubleArrow_13 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_13, _function_14); + it.elements.add(_doubleArrow_13); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_14 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_15 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_4.instance().getFullyQualifiedName(); + it_1.weight = (((((((14 + 35) + 21) + 15) + 14) + 21) + 15) + 11); + }; + CostObjectiveElementConfiguration _doubleArrow_14 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_14, _function_15); + it.elements.add(_doubleArrow_14); + CostObjectiveElementConfiguration _costObjectiveElementConfiguration_15 = new CostObjectiveElementConfiguration(); + final Procedure1 _function_16 = (CostObjectiveElementConfiguration it_1) -> { + it_1.patternQualifiedName = EndOfSiding_step_5.instance().getFullyQualifiedName(); + it_1.weight = 48; + }; + CostObjectiveElementConfiguration _doubleArrow_15 = ObjectExtensions.operator_doubleArrow(_costObjectiveElementConfiguration_15, _function_16); + it.elements.add(_doubleArrow_15); + EndOfSidingObjectiveHint _endOfSidingObjectiveHint = new EndOfSidingObjectiveHint(ecore2Logic, ecore2LogicTrace); + it.hint = _endOfSidingObjectiveHint; + break; + default: + throw new IllegalArgumentException(("Unknown monitoring query: " + this.monitoringQuery)); + } + } else { + throw new IllegalArgumentException(("Unknown monitoring query: " + this.monitoringQuery)); + } + it.kind = ObjectiveKind.HIGHER_IS_BETTER; + it.threshold = ObjectiveThreshold.NO_THRESHOLD; + it.findExtremum = true; + }; + return ObjectExtensions.operator_doubleArrow(_costObjectiveConfiguration, _function); + } + public static Object init() { Object _xblockexpression = null; { 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 @@ +package modes3.run; + +import com.google.common.collect.ImmutableList; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic; +import hu.bme.mit.inf.dslreasoner.ecore2logic.Ecore2Logic_Trace; +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Dimension; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilderFactory; +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatch; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostElementMatchers; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import modes3.Modes3Package; +import modes3.queries.TrainLocations_step_2; +import modes3.queries.TrainLocations_step_3; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.eclipse.xtext.xbase.lib.IterableExtensions; + +@SuppressWarnings("all") +public class TrainLocationsObjectiveHint extends CostObjectiveHint { + private final Type segmentType; + + private final Type trainType; + + public TrainLocationsObjectiveHint(@Extension final Ecore2Logic ecore2Logic, final Ecore2Logic_Trace ecore2LogicTrace) { + @Extension + final Modes3Package Modes3Package = modes3.Modes3Package.eINSTANCE; + this.segmentType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getSegment()); + this.trainType = ecore2Logic.TypeofEClass(ecore2LogicTrace, Modes3Package.getTrain()); + } + + @Override + public boolean isExact() { + return true; + } + + @Override + public PolyhedronExtensionOperator createPolyhedronExtensionOperator(final Map costElementMatchers) { + PolyhedronExtensionOperator _xblockexpression = null; + { + final CostElementMatchers step2 = costElementMatchers.get(TrainLocations_step_2.instance().getFullyQualifiedName()); + final CostElementMatchers step3 = costElementMatchers.get(TrainLocations_step_3.instance().getFullyQualifiedName()); + final PolyhedronExtensionOperator _function = (ExtendedLinearExpressionBuilderFactory it) -> { + final ExtendedLinearExpressionBuilder objectiveBuilder = it.createBuilder(); + ImmutableList _matches = step2.getMatches(); + for (final CostElementMatch m : _matches) { + { + final Dimension dimension = it.getDimension(m.getMatch()); + objectiveBuilder.add(step2.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m.isMulti(); + if (_isMulti) { + it.createBuilder().add(1, dimension).add((-1), this.trainType).build().assertEqualsTo(0); + } else { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + final ImmutableList step3Matches = step3.getMatches(); + for (final CostElementMatch m_1 : step3Matches) { + { + final Dimension dimension = it.getDimension(m_1.getMatch()); + objectiveBuilder.add(step3.getWeight(), dimension); + dimension.tightenLowerBound(Integer.valueOf(0)); + boolean _isMulti = m_1.isMulti(); + boolean _not = (!_isMulti); + if (_not) { + dimension.tightenUpperBound(Integer.valueOf(1)); + boolean _isMust = m_1.isMust(); + if (_isMust) { + dimension.tightenLowerBound(Integer.valueOf(1)); + } + } + } + } + TrainLocationsObjectiveHint.boundLimit(it, step3Matches, 2, this.trainType, 1); + TrainLocationsObjectiveHint.boundLimit(it, step3Matches, 3, this.segmentType, 1); + this.buildWithBounds(objectiveBuilder); + }; + _xblockexpression = _function; + } + return _xblockexpression; + } + + private static void boundLimit(@Extension final ExtendedLinearExpressionBuilderFactory factory, final Collection matches, final int index, final Type type, final int count) { + final Function1 _function = (CostElementMatch it) -> { + return it.getMatch().get(index); + }; + Set>> _entrySet = IterableExtensions.groupBy(matches, _function).entrySet(); + for (final Map.Entry> pair : _entrySet) { + { + final ExtendedLinearExpressionBuilder multiplicityBuilder = factory.createBuilder(); + List _value = pair.getValue(); + for (final CostElementMatch m : _value) { + multiplicityBuilder.add(1, m.getMatch()); + } + boolean _isMulti = CostElementMatchers.isMulti(pair.getKey()); + if (_isMulti) { + multiplicityBuilder.add((-count), type); + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(0)); + } else { + multiplicityBuilder.build().tightenUpperBound(Integer.valueOf(count)); + } + } + } + } +} 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, org.eclipse.viatra.query.runtime, org.eclipse.core.runtime, org.eclipse.emf.ecore;visibility:=reexport, - org.eclipse.emf.emfstore.common, com.google.guava, org.eclipse.xtext.xbase.lib, 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, hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval, hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.interval.aggregators, hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns, - hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries + hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.queries, + hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules Require-Bundle: hu.bme.mit.inf.dslreasoner.logic.model;bundle-version="1.0.0", hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage;bundle-version="1.0.0", 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/ModelGenerationMethodProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend deleted file mode 100644 index 3bcd9116..00000000 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra/src/hu/bme/mit/inf/dslreasoner/viatrasolver/logic2viatra/ModelGenerationMethodProvider.xtend +++ /dev/null @@ -1,226 +0,0 @@ -package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra - -import com.google.common.collect.ImmutableMap -import com.google.common.collect.ImmutableSet -import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel -import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem -import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation -import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace -import java.util.Collection -import java.util.List -import java.util.Map -import java.util.Set -import org.eclipse.viatra.query.runtime.api.GenericQueryGroup -import org.eclipse.viatra.query.runtime.api.IPatternMatch -import org.eclipse.viatra.query.runtime.api.IQuerySpecification -import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -import org.eclipse.viatra.query.runtime.emf.EMFScope -import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint -import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery -import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule -import org.eclipse.xtend.lib.annotations.Data - -class ModelGenerationStatistics { - public var long transformationExecutionTime = 0 - - synchronized def addExecutionTime(long amount) { - transformationExecutionTime += amount - } - - public var long scopePropagationTime = 0 - - synchronized def addScopePropagationTime(long amount) { - scopePropagationTime += amount - } - - public var long mustRelationPropagationTime = 0 - - synchronized def addMustRelationPropagationTime(long amount) { - mustRelationPropagationTime += amount - } - - public var long preliminaryTypeAnalisisTime = 0 - - public var int decisionsTried = 0 - - synchronized def incrementDecisionCount() { - decisionsTried++ - } - - public var int transformationInvocations - - synchronized def incrementTransformationCount() { - transformationInvocations++ - } - - public var int scopePropagatorInvocations - - synchronized def incrementScopePropagationCount() { - scopePropagatorInvocations++ - } - - public var int scopePropagatorSolverInvocations - - synchronized def incrementScopePropagationSolverCount() { - scopePropagatorSolverInvocations++ - } -} - -@Data class ModelGenerationMethod { - ModelGenerationStatistics statistics - - Collection> objectRefinementRules - Collection> relationRefinementRules - - List unfinishedMultiplicities - - Collection>> unfinishedWF - - Collection>> invalidWF - - Map>> mustUnitPropagationPreconditions - Map>> currentUnitPropagationPreconditions - - Map modalRelationQueries - - Collection>> allPatterns -} - -enum TypeInferenceMethod { - Generic, - PreliminaryAnalysis -} - -class ModelGenerationMethodProvider { - val PatternProvider patternProvider = new PatternProvider - val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider - val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider - val relationConstraintCalculator = new RelationConstraintCalculator - - def ModelGenerationMethod createModelGenerationMethod( - LogicProblem logicProblem, - PartialInterpretation emptySolution, - ReasonerWorkspace workspace, - boolean nameNewElements, - TypeInferenceMethod typeInferenceMethod, - boolean calculateObjectCreationCosts, - ScopePropagatorStrategy scopePropagatorStrategy, - Collection hints, - Collection unitPropagationPatternGenerators, - DocumentationLevel debugLevel - ) { - val statistics = new ModelGenerationStatistics - val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL) - - val Set existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery). - map[it.patternPQuery as PQuery].toSet - - val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem) - val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries, - workspace, typeInferenceMethod, scopePropagatorStrategy, relationConstraints, hints, - unitPropagationPatternGenerators, writeFiles) - - val scopePropagator = createScopePropagator(scopePropagatorStrategy, emptySolution, hints, queries, statistics) - scopePropagator.propagateAllScopeConstraints - val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, - queries, scopePropagator, statistics) - val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, - queries, unitRulePropagator, nameNewElements, statistics) - val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator, - statistics) - - val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries, - calculateObjectCreationCosts) - - val unfinishedWF = queries.getUnfinishedWFQueries.values - - val modalRelationQueriesBuilder = ImmutableMap.builder - for (entry : queries.modalRelationQueries.entrySet) { - val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head - if (annotation !== null) { - modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value) - } - } - val modalRelationQueries = modalRelationQueriesBuilder.build - - val invalidWF = queries.getInvalidWFQueries.values - - val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns - val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns - - val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll( - queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll(queries. - multiplicityConstraintQueries.values.flatMap[allQueries]).addAll(queries.unfinishedWFQueries.values).addAll( - queries.invalidWFQueries.values).addAll(queries.mustUnitPropagationPreconditionPatterns.values).addAll( - queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build - val queryEngine = ViatraQueryEngine.on(new EMFScope(emptySolution)) - GenericQueryGroup.of(queriesToPrepare).prepare(queryEngine) - - return new ModelGenerationMethod( - statistics, - objectRefinementRules.values, - relationRefinementRules.values, - unfinishedMultiplicities, - unfinishedWF, - invalidWF, - mustUnitPropagationPreconditions, - currentUnitPropagationPreconditions, - modalRelationQueries, - queries.allQueries - ) - } - - private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy, - PartialInterpretation emptySolution, Collection hints, GeneratedPatterns queries, - ModelGenerationStatistics statistics) { - if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) { - throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.") - } - switch (scopePropagatorStrategy) { - case ScopePropagatorStrategy.None, - case ScopePropagatorStrategy.Basic: - new ScopePropagator(emptySolution, statistics) - case ScopePropagatorStrategy.BasicTypeHierarchy: - new TypeHierarchyScopePropagator(emptySolution, statistics) - ScopePropagatorStrategy.Polyhedral: { - val types = queries.refineObjectQueries.keySet.map[newType].toSet - val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName] - val solver = switch (scopePropagatorStrategy.solver) { - case Z3Integer: - new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds) - case Z3Real: - new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds) - case Cbc: - new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true) - case Clp: - new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true) - default: - throw new IllegalArgumentException("Unknown polyhedron solver: " + - scopePropagatorStrategy.solver) - } - new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries, - queries.hasElementInContainmentQuery, allPatternsByName, hints, solver, - scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic) - } - default: - throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy) - } - } -} 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra + +class ModelGenerationStatistics { + public var long transformationExecutionTime = 0 + + synchronized def addExecutionTime(long amount) { + transformationExecutionTime += amount + } + + public var long scopePropagationTime = 0 + + synchronized def addScopePropagationTime(long amount) { + scopePropagationTime += amount + } + + public var long mustRelationPropagationTime = 0 + + synchronized def addMustRelationPropagationTime(long amount) { + mustRelationPropagationTime += amount + } + + public var long preliminaryTypeAnalisisTime = 0 + + public var int decisionsTried = 0 + + synchronized def incrementDecisionCount() { + decisionsTried++ + } + + public var int transformationInvocations + + synchronized def incrementTransformationCount() { + transformationInvocations++ + } + + public var int scopePropagatorInvocations + + synchronized def incrementScopePropagationCount() { + scopePropagatorInvocations++ + } + + public var int scopePropagatorSolverInvocations + + synchronized def incrementScopePropagationSolverCount() { + scopePropagatorSolverInvocations++ + } +} 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra + +import com.google.common.collect.ImmutableMap +import com.google.common.collect.ImmutableSet +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CachingSimplePolyhedronScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace +import java.util.Collection +import java.util.List +import java.util.Map +import java.util.Set +import org.eclipse.viatra.query.runtime.api.GenericQueryGroup +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.IQuerySpecification +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.viatra.query.runtime.emf.EMFScope +import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule +import org.eclipse.xtend.lib.annotations.Data + +enum TypeInferenceMethod { + Generic, + PreliminaryAnalysis +} \ 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import java.util.ArrayList +import java.util.HashMap +import java.util.HashSet +import java.util.List +import java.util.Map +import java.util.Set +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.xtend.lib.annotations.Accessors +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor + +interface BoundSaturationListener { + def void boundsSaturated(Integer lower, Integer upper) +} + +interface ExtendedLinearExpressionBuilderFactory { + def ExtendedLinearExpressionBuilder createBuilder() + + def Dimension getDimension(IPatternMatch patternMatch) +} + +interface ExtendedLinearExpressionBuilder extends LinearTypeExpressionBuilder { + override ExtendedLinearExpressionBuilder add(int scale, Type type) + + def ExtendedLinearExpressionBuilder add(int scale, IPatternMatch patternMatch) + + def ExtendedLinearExpressionBuilder add(int scale, Dimension dimension) + + def LinearBoundedExpression build(BoundSaturationListener listener) +} + +class ExtendedPolyhedronBuilder implements ExtendedLinearExpressionBuilderFactory { + val Map typeBounds + val Map, LinearBoundedExpression> expressionsCache + + val ImmutableList.Builder dimensions = ImmutableList.builder + val Set constraints = new HashSet + val Set expressionsToSaturate = new HashSet + val Map patternMatchCounts = new HashMap + @Accessors(PUBLIC_GETTER) val List> saturationListeners = new ArrayList + + new(Polyhedron polyhedron, Map typeBounds, + Map, LinearBoundedExpression> initialExpressionsCache) { + this.typeBounds = typeBounds + this.expressionsCache = new HashMap(initialExpressionsCache) + dimensions.addAll(polyhedron.dimensions) + constraints.addAll(polyhedron.constraints) + expressionsToSaturate.addAll(polyhedron.expressionsToSaturate) + } + + override createBuilder() { + new ExtendedLinearExpressionBuilderImpl(this) + } + + override getDimension(IPatternMatch patternMatch) { + patternMatchCounts.computeIfAbsent(patternMatch) [ key | + val dimension = new Dimension(key.toString, 0, null) + dimensions.add(dimension) + dimension + ] + } + + def buildPolyhedron() { + new Polyhedron( + dimensions.build, + ImmutableList.copyOf(constraints), + ImmutableList.copyOf(expressionsToSaturate) + ) + } + + @FinalFieldsConstructor + private static class ExtendedLinearExpressionBuilderImpl implements ExtendedLinearExpressionBuilder { + val ExtendedPolyhedronBuilder polyhedronBuilder + + val Map coefficients = new HashMap + + override add(int scale, Type type) { + val expression = polyhedronBuilder.typeBounds.get(type) + if (expression === null) { + throw new IllegalArgumentException("Unknown Type: " + type) + } + add(scale, expression) + } + + override add(int scale, IPatternMatch patternMatch) { + val dimension = polyhedronBuilder.getDimension(patternMatch) + add(scale, dimension) + } + + private def add(int scale, LinearBoundedExpression expression) { + switch (expression) { + Dimension: add(scale, expression) + LinearConstraint: add(scale, expression.coefficients) + default: throw new IllegalArgumentException("Unknown LinearBoundedExpression: " + expression) + } + } + + private def add(int scale, Map coefficients) { + for (pair : coefficients.entrySet) { + add(scale * pair.value, pair.key) + } + this + } + + override add(int scale, Dimension dimension) { + coefficients.merge(dimension, scale)[a, b|a + b] + this + } + + override build() { + val filteredCoefficients = ImmutableMap.copyOf(coefficients.filter [ _, coefficient | + coefficient != 0 + ]) + polyhedronBuilder.expressionsCache.computeIfAbsent(filteredCoefficients) [ map | + if (map.size == 1) { + val pair = map.entrySet.head + if (pair.value == 1) { + return pair.key + } + } + val constraint = new LinearConstraint(map) + polyhedronBuilder.constraints.add(constraint) + constraint + ] + } + + override build(BoundSaturationListener listener) { + val expression = build() + if (listener !== null) { + polyhedronBuilder.expressionsToSaturate.add(expression) + polyhedronBuilder.saturationListeners.add(expression -> listener) + } + expression + } + } +} 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics +import java.util.Collection +import java.util.Map +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation + +interface PolyhedronExtensionOperator { + def void extendPolyhedron(ExtendedLinearExpressionBuilderFactory factory) +} + +class ExtendedPolyhedronScopePropagatorStrategy extends PolyhedronScopePropagatorStrategy { + val PolyhedronSolver solver + val Collection extensionOperators + + var Map typeBounds + var Map, LinearBoundedExpression> initialExpressionsCache + + new(PolyhedronSolver solver, Collection extensionOperators, + ModelGenerationStatistics statistics) { + super(statistics) + this.solver = solver + this.extensionOperators = extensionOperators + } + + override setPolyhedron(Polyhedron polyhedron, Map typeBounds, + Map, LinearBoundedExpression> initialExpressionsCache) { + super.setPolyhedron(polyhedron, typeBounds, initialExpressionsCache) + this.typeBounds = typeBounds + this.initialExpressionsCache = initialExpressionsCache + } + + override isRelevantRelation(Relation relation) { + true + } + + override protected doSaturate() { + val builder = new ExtendedPolyhedronBuilder(polyhedron, typeBounds, initialExpressionsCache) + for (extensionOperator : extensionOperators) { + extensionOperator.extendPolyhedron(builder) + } + val extendedPolyhedron = builder.buildPolyhedron() + val saturationOperator = solver.createSaturationOperator(extendedPolyhedron) + val result = try { + saturationOperator.saturate() + } finally { + saturationOperator.close() + } + if (result == PolyhedronSaturationResult.EMPTY) { + // The partial model cannot be refined any more, we can't provide objective bounds. + for (pair : builder.saturationListeners) { + pair.value.boundsSaturated(null, null) + } + return false + } + for (pair : builder.saturationListeners) { + val expression = pair.key + pair.value.boundsSaturated(expression.lowerBound, expression.upperBound) + } + true + } +} 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 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality -import com.google.common.cache.Cache -import com.google.common.cache.CacheBuilder import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableSet @@ -23,7 +21,6 @@ import java.util.HashSet import java.util.List import java.util.Map import java.util.Set -import javax.naming.OperationNotSupportedException import org.eclipse.viatra.query.runtime.api.IPatternMatch import org.eclipse.viatra.query.runtime.api.IQuerySpecification import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine @@ -32,31 +29,29 @@ import org.eclipse.viatra.query.runtime.emf.EMFScope import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { - static val CACHE_SIZE = 10000 - val boolean updateHeuristic val Map scopeBounds val LinearBoundedExpression topLevelBounds val Polyhedron polyhedron - val PolyhedronSaturationOperator operator + val PolyhedronScopePropagatorStrategy strategy val Set relevantRelations - val Cache cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build List updaters = emptyList new(PartialInterpretation p, ModelGenerationStatistics statistics, Set possibleNewDynamicTypes, Map unfinishedMultiplicityQueries, IQuerySpecification> hasElementInContainmentQuery, Map>> allPatternsByName, - Collection hints, PolyhedronSolver solver, boolean propagateRelations, - boolean updateHeuristic) { + Collection hints, PolyhedronScopePropagatorStrategy strategy, + boolean propagateRelations, boolean updateHeuristic) { super(p, statistics) this.updateHeuristic = updateHeuristic + this.strategy = strategy val builder = new PolyhedronBuilder(p) builder.buildPolyhedron(possibleNewDynamicTypes) scopeBounds = builder.scopeBounds topLevelBounds = builder.topLevelBounds polyhedron = builder.polyhedron - operator = solver.createSaturationOperator(polyhedron) + strategy.setPolyhedron(polyhedron, builder.typeBounds, builder.expressionsCache) propagateAllScopeConstraints() if (propagateRelations) { val maximumNumberOfNewNodes = topLevelBounds.upperBound @@ -80,30 +75,10 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { resetBounds() populatePolyhedronFromScope() // println(polyhedron) - val signature = polyhedron.createSignature - val cachedSignature = cache.getIfPresent(signature) - switch (cachedSignature) { - case null: { - statistics.incrementScopePropagationSolverCount - val result = operator.saturate() - if (result == PolyhedronSaturationResult.EMPTY) { - cache.put(signature, PolyhedronSignature.EMPTY) -// println("INVALID") - setScopesInvalid() - } else { - val resultSignature = polyhedron.createSignature - cache.put(signature, resultSignature) - populateScopesFromPolyhedron() - } - } - case PolyhedronSignature.EMPTY: - setScopesInvalid() - PolyhedronSignature.Bounds: { - polyhedron.applySignature(signature) - populateScopesFromPolyhedron() - } - default: - throw new IllegalStateException("Unknown polyhedron signature: " + signature) + if (strategy.saturate) { + populateScopesFromPolyhedron() + } else { + setScopesInvalid() } // println(polyhedron) if (updateHeuristic) { @@ -112,9 +87,9 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } override isPropagationNeededAfterAdditionToRelation(Relation r) { - relevantRelations.contains(r) || super.isPropagationNeededAfterAdditionToRelation(r) + relevantRelations.contains(r) || strategy.isRelevantRelation(r) || super.isPropagationNeededAfterAdditionToRelation(r) } - + override isQueryEngineFlushRequiredBeforePropagation() { true } @@ -253,7 +228,10 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { } buildRelevantRelations(constraints.keySet) for (hint : hints) { - updatersBuilder.add(hint.createConstraintUpdater(this)) + val updater = hint.createConstraintUpdater(this) + if (updater !== null) { + updatersBuilder.add(updater) + } } updaters = updatersBuilder.build addCachedConstraintsToPolyhedron() @@ -410,7 +388,7 @@ class PolyhedronScopePropagator extends TypeHierarchyScopePropagator { for (scope : p.scopes) { switch (targetTypeInterpretation : scope.targetTypeInterpretation) { PartialPrimitiveInterpretation: - throw new OperationNotSupportedException("Primitive type scopes are not yet implemented") + throw new IllegalStateException("Primitive type scopes are not yet implemented") PartialComplexTypeInterpretation: { val complexType = targetTypeInterpretation.interpretationOf 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality + +import com.google.common.cache.Cache +import com.google.common.cache.CacheBuilder +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Type +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics +import java.util.Map +import org.eclipse.xtend.lib.annotations.Accessors +import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor + +@FinalFieldsConstructor +abstract class PolyhedronScopePropagatorStrategy { + val ModelGenerationStatistics statistics + + @Accessors(PUBLIC_GETTER) var Polyhedron polyhedron + + def void setPolyhedron(Polyhedron polyhedron, Map typeBounds, + Map, LinearBoundedExpression> initialExpressionsCache) { + if (this.polyhedron !== null) { + throw new IllegalStateException("polyhedron was already set") + } + this.polyhedron = polyhedron + initialize() + } + + def boolean saturate() { + if (polyhedron === null) { + throw new IllegalStateException("polyhedron was not set") + } + doSaturate() + } + + def boolean isRelevantRelation(Relation relation) { + false + } + + protected def incrementScopePropagationSolverCount() { + statistics.incrementScopePropagationSolverCount() + } + + protected def void initialize() { + } + + protected def boolean doSaturate() +} + +@FinalFieldsConstructor +class CachingSimplePolyhedronScopePropagatorStrategy extends PolyhedronScopePropagatorStrategy { + static val CACHE_SIZE = 10000 + + val PolyhedronSolver solver + + val Cache cache = CacheBuilder.newBuilder.maximumSize(CACHE_SIZE).build + var PolyhedronSaturationOperator operator + + new(PolyhedronSolver solver, ModelGenerationStatistics statistics) { + super(statistics) + this.solver = solver + } + + override protected initialize() { + operator = solver.createSaturationOperator(polyhedron) + } + + override protected doSaturate() { + val signature = polyhedron.createSignature + val cachedSignature = cache.getIfPresent(signature) + switch (cachedSignature) { + case null: { + incrementScopePropagationSolverCount() + val result = operator.saturate() + if (result == PolyhedronSaturationResult.EMPTY) { + cache.put(signature, PolyhedronSignature.EMPTY) + false + } else { + val resultSignature = polyhedron.createSignature + cache.put(signature, resultSignature) + true + } + } + case PolyhedronSignature.EMPTY: + false + PolyhedronSignature.Bounds: { + polyhedron.applySignature(signature) + true + } + default: + throw new IllegalStateException("Unknown polyhedron signature: " + signature) + } + } +} 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 { } @Accessors -abstract class LinearBoundedExpression { +class Bounds { var Integer lowerBound var Integer upperBound @@ -132,12 +132,19 @@ abstract class LinearBoundedExpression { } } + def void assertBetween(Integer tighterLowerBound, Integer tighterUpperBound) { + tightenLowerBound(tighterLowerBound) + tightenUpperBound(tighterUpperBound) + } + def void assertEqualsTo(int bound) { - tightenLowerBound(bound) - tightenUpperBound(bound) + assertBetween(bound, bound) } } +abstract class LinearBoundedExpression extends Bounds { +} + @Accessors class Dimension extends LinearBoundedExpression { 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 Bundle-SymbolicName: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner Bundle-Version: 1.0.0.qualifier Export-Package: hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner, + hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse, hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization Require-Bundle: hu.bme.mit.inf.dslreasoner.ecore2logic;bundle-version="1.0.0", 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 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner import org.eclipse.viatra.dse.objectives.IGlobalConstraint -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod abstract class ModelGenerationMethodBasedGlobalConstraint implements IGlobalConstraint { val protected ModelGenerationMethod method diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend new file mode 100644 index 00000000..25137eba --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/ModelGenerationMethodProvider.xtend @@ -0,0 +1,201 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner + +import com.google.common.collect.ImmutableMap +import com.google.common.collect.ImmutableSet +import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationStatistics +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CachingSimplePolyhedronScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.CbcPolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.RelationConstraintCalculator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.TypeHierarchyScopePropagator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Z3PolyhedronSolver +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.GeneratedPatterns +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.GoalConstraintProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.rules.RefinementRuleProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjectiveProvider +import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace +import java.util.Collection +import java.util.List +import java.util.Map +import java.util.Set +import org.eclipse.viatra.dse.objectives.IObjective +import org.eclipse.viatra.query.runtime.api.GenericQueryGroup +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.IQuerySpecification +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.viatra.query.runtime.emf.EMFScope +import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule +import org.eclipse.xtend.lib.annotations.Data +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedPolyhedronScopePropagatorStrategy + +@Data class ModelGenerationMethod { + ModelGenerationStatistics statistics + + Collection> objectRefinementRules + Collection> relationRefinementRules + + List unfinishedMultiplicities + + Collection>> unfinishedWF + + Collection>> invalidWF + + Map>> mustUnitPropagationPreconditions + Map>> currentUnitPropagationPreconditions + + Map modalRelationQueries + + Collection>> allPatterns + + Collection costObjectives + boolean optimizationProblem + ViatraReasonerSolutionSaver solutionSaver +} + +class ModelGenerationMethodProvider { + val PatternProvider patternProvider = new PatternProvider + val RefinementRuleProvider refinementRuleProvider = new RefinementRuleProvider + val GoalConstraintProvider goalConstraintProvider = new GoalConstraintProvider + val relationConstraintCalculator = new RelationConstraintCalculator + + def ModelGenerationMethod createModelGenerationMethod( + LogicProblem logicProblem, + PartialInterpretation emptySolution, + ReasonerWorkspace workspace, + ViatraReasonerConfiguration config + ) { + val statistics = new ModelGenerationStatistics + val debugLevel = config.documentationLevel + val writeFiles = (debugLevel === DocumentationLevel.NORMAL || debugLevel === DocumentationLevel.FULL) + + val Set existingQueries = logicProblem.relations.map[annotations].flatten.filter(TransfomedViatraQuery). + map[it.patternPQuery as PQuery].toSet + + val relationConstraints = relationConstraintCalculator.calculateRelationConstraints(logicProblem) + val queries = patternProvider.generateQueries(logicProblem, emptySolution, statistics, existingQueries, + workspace, config.typeInferenceMethod, config.scopePropagatorStrategy, relationConstraints, config.hints, + config.unitPropagationPatternGenerators, writeFiles) + + val unfinishedMultiplicities = goalConstraintProvider.getUnfinishedMultiplicityQueries(logicProblem, queries, + config.calculateObjectCreationCosts) + val unfinishedWF = queries.getUnfinishedWFQueries.values + val modalRelationQueriesBuilder = ImmutableMap.builder + for (entry : queries.modalRelationQueries.entrySet) { + val annotation = entry.key.annotations.filter(TransfomedViatraQuery).head + if (annotation !== null) { + modalRelationQueriesBuilder.put(annotation.patternFullyQualifiedName, entry.value) + } + } + val modalRelationQueries = modalRelationQueriesBuilder.build + val invalidWF = queries.getInvalidWFQueries.values + val mustUnitPropagationPreconditions = queries.getMustUnitPropagationPreconditionPatterns + val currentUnitPropagationPreconditions = queries.getCurrentUnitPropagationPreconditionPatterns + val queriesToPrepare = ImmutableSet.builder.addAll(queries.refineObjectQueries.values).addAll( + queries.refineTypeQueries.values).addAll(queries.refineRelationQueries.values).addAll( + queries.mustRelationPropagationQueries.values).addAll(queries.multiplicityConstraintQueries.values.flatMap [ + allQueries + ]).addAll(queries.unfinishedWFQueries.values).addAll(queries.invalidWFQueries.values).addAll( + queries.mustUnitPropagationPreconditionPatterns.values).addAll( + queries.currentUnitPropagationPreconditionPatterns.values).add(queries.hasElementInContainmentQuery).build + val queryEngine = ViatraQueryEngine.on(new EMFScope(emptySolution)) + GenericQueryGroup.of(queriesToPrepare).prepare(queryEngine) + + val objectiveProvider = new ThreeValuedCostObjectiveProvider(queryEngine, emptySolution, modalRelationQueries) + val transformedObjectives = objectiveProvider.getCostObjectives(config.costObjectives) + + val solutionSaver = new ViatraReasonerSolutionSaver(transformedObjectives.leveledExtremalObjectives, + config.solutionScope.numberOfRequiredSolutions, DiversityChecker.of(config.diversityRequirement)) + + val allHints = ImmutableSet.builder + allHints.addAll(config.hints) + for (hint : transformedObjectives.hints) { + hint.boundsProvider = solutionSaver + allHints.add(hint) + } + + val scopePropagator = createScopePropagator(config.scopePropagatorStrategy, emptySolution, allHints.build, + transformedObjectives.extensionOperators, queries, statistics) + scopePropagator.propagateAllScopeConstraints + val unitRulePropagator = refinementRuleProvider.createUnitPrulePropagator(logicProblem, emptySolution, queries, + scopePropagator, statistics) + val objectRefinementRules = refinementRuleProvider.createObjectRefinementRules(logicProblem, emptySolution, + queries, unitRulePropagator, config.nameNewElements, statistics) + val relationRefinementRules = refinementRuleProvider.createRelationRefinementRules(queries, unitRulePropagator, + statistics) + + return new ModelGenerationMethod( + statistics, + objectRefinementRules.values, + relationRefinementRules.values, + unfinishedMultiplicities, + unfinishedWF, + invalidWF, + mustUnitPropagationPreconditions, + currentUnitPropagationPreconditions, + modalRelationQueries, + queries.allQueries, + transformedObjectives.objectives, + transformedObjectives.optimizationProblem, + solutionSaver + ) + } + + private def createScopePropagator(ScopePropagatorStrategy scopePropagatorStrategy, + PartialInterpretation emptySolution, Collection hints, + Collection extensionOperators, GeneratedPatterns queries, + ModelGenerationStatistics statistics) { + if (!hints.empty && !(scopePropagatorStrategy instanceof ScopePropagatorStrategy.Polyhedral)) { + throw new IllegalArgumentException("Only the Polyhedral scope propagator strategy can use hints.") + } + switch (scopePropagatorStrategy) { + case ScopePropagatorStrategy.None, + case ScopePropagatorStrategy.Basic: + new ScopePropagator(emptySolution, statistics) + case ScopePropagatorStrategy.BasicTypeHierarchy: + new TypeHierarchyScopePropagator(emptySolution, statistics) + ScopePropagatorStrategy.Polyhedral: { + val types = queries.refineObjectQueries.keySet.map[newType].toSet + val allPatternsByName = queries.allQueries.toMap[fullyQualifiedName] + val solver = switch (scopePropagatorStrategy.solver) { + case Z3Integer: + new Z3PolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds) + case Z3Real: + new Z3PolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds) + case Cbc: + new CbcPolyhedronSolver(false, scopePropagatorStrategy.timeoutSeconds, true) + case Clp: + new CbcPolyhedronSolver(true, scopePropagatorStrategy.timeoutSeconds, true) + default: + throw new IllegalArgumentException("Unknown polyhedron solver: " + + scopePropagatorStrategy.solver) + } + val strategy = if (extensionOperators.empty) { + new CachingSimplePolyhedronScopePropagatorStrategy(solver, statistics) + } else { + new ExtendedPolyhedronScopePropagatorStrategy(solver, extensionOperators, statistics) + } + new PolyhedronScopePropagator(emptySolution, statistics, types, queries.multiplicityConstraintQueries, + queries.hasElementInContainmentQuery, allPatternsByName, hints, strategy, + scopePropagatorStrategy.requiresUpperBoundIndexing, scopePropagatorStrategy.updateHeuristic) + } + default: + throw new IllegalArgumentException("Unknown scope propagator strategy: " + scopePropagatorStrategy) + } + } +} 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 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner -import com.google.common.collect.ImmutableList -import com.google.common.collect.Lists import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasonerException @@ -11,7 +9,6 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicresultFactory import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethodProvider import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.PartialInterpretationInitialiser import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation @@ -22,7 +19,6 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.sta import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.PairwiseNeighbourhoodBasedStateCoderFactory import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BasicScopeGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.BestFirstStrategyForModelGeneration -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.DiversityChecker import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.InconsistentScopeGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.LoggerSolutionFoundHandler import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ModelGenerationCompositeObjective @@ -32,11 +28,8 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.PunishSizeObjective import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ScopeObjective import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.SurelyViolatedObjectiveGlobalConstraint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.UnfinishedMultiplicityObjective -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.ViatraReasonerSolutionSaver import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse.WF2ObjectiveConverter import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostElement -import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ThreeValuedCostObjective import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace import java.util.List import java.util.Map @@ -86,13 +79,7 @@ class ViatraReasoner extends LogicReasoner { problem, emptySolution, workspace, - viatraConfig.nameNewElements, - viatraConfig.typeInferenceMethod, - viatraConfig.calculateObjectCreationCosts, - viatraConfig.scopePropagatorStrategy, - viatraConfig.hints, - viatraConfig.unitPropagationPatternGenerators, - viatraConfig.documentationLevel + viatraConfig ) val compositeObjective = new ModelGenerationCompositeObjective( @@ -112,45 +99,21 @@ class ViatraReasoner extends LogicReasoner { dse.addObjective(punishObjective) } - val extremalObjectives = Lists.newArrayListWithExpectedSize(viatraConfig.costObjectives.size) - for (entry : viatraConfig.costObjectives.indexed) { - val objectiveName = '''costObjective«entry.key»''' - val objectiveConfig = entry.value - val elementsBuilder = ImmutableList.builder - for (elementConfig : objectiveConfig.elements) { - val relationName = elementConfig.patternQualifiedName - val modalQueries = method.modalRelationQueries.get(relationName) - if (modalQueries === null) { - throw new IllegalArgumentException("Unknown relation: " + relationName) - } - elementsBuilder.add(new ThreeValuedCostElement( - modalQueries.currentQuery, - modalQueries.mayQuery, - modalQueries.mustQuery, - elementConfig.weight - )) - } - val costElements = elementsBuilder.build - val costObjective = new ThreeValuedCostObjective(objectiveName, costElements, objectiveConfig.kind, - objectiveConfig.threshold, 3) + for (costObjective : method.costObjectives) { dse.addObjective(costObjective) - if (objectiveConfig.findExtremum) { - extremalObjectives += costObjective - } } - val numberOfRequiredSolutions = configuration.solutionScope.numberOfRequiredSolutions - val solutionStore = if (extremalObjectives.empty) { - new SolutionStore(numberOfRequiredSolutions) - } else { + val solutionStore = if (method.optimizationProblem) { new SolutionStore() + } else { + new SolutionStore(numberOfRequiredSolutions) } solutionStore.registerSolutionFoundHandler(new LoggerSolutionFoundHandler(viatraConfig)) - val diversityChecker = DiversityChecker.of(viatraConfig.diversityRequirement) val numericSolver = new NumericSolver(method, viatraConfig.runIntermediateNumericalConsistencyChecks, false) - val solutionSaver = new ViatraReasonerSolutionSaver(newArrayList(extremalObjectives), numberOfRequiredSolutions, - diversityChecker, numericSolver) + val solutionSaver = method.solutionSaver + solutionSaver.numericSolver = numericSolver val solutionCopier = solutionSaver.solutionCopier + val diversityChecker = solutionSaver.diversityChecker solutionStore.withSolutionSaver(solutionSaver) dse.solutionStore = solutionStore @@ -185,7 +148,8 @@ class ViatraReasoner extends LogicReasoner { dse.addTransformationRule(rule) } - val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, numericSolver) + val strategy = new BestFirstStrategyForModelGeneration(workspace, viatraConfig, method, solutionSaver, + numericSolver) viatraConfig.progressMonitor.workedForwardTransformation val transformationFinished = System.nanoTime val transformationTime = transformationFinished - transformationStartTime @@ -211,14 +175,15 @@ class ViatraReasoner extends LogicReasoner { it.value = (pair.value / 1000000) as int ] } - for(x: 0.. [ it.name = '''Solution«x+1»DetailedStatistics''' it.value = strategy.times.get(x) ] } it.entries += createIntStatisticEntry => [ - it.name = "ExplorationInitializationTime" it.value = ((strategy.explorationStarted-transformationFinished)/1000000) as int + it.name = "ExplorationInitializationTime" + it.value = ((strategy.explorationStarted - transformationFinished) / 1000000) as int ] it.entries += createIntStatisticEntry => [ it.name = "TransformationExecutionTime" @@ -253,22 +218,28 @@ class ViatraReasoner extends LogicReasoner { it.value = dse.numberOfStates as int ] it.entries += createIntStatisticEntry => [ - it.name = "ForwardTime" it.value = (strategy.forwardTime/1000000) as int + it.name = "ForwardTime" + it.value = (strategy.forwardTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "BacktrackingTime" it.value = (strategy.backtrackingTime/1000000) as int + it.name = "BacktrackingTime" + it.value = (strategy.backtrackingTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "GlobalConstraintEvaluationTime" it.value = (strategy.globalConstraintEvaluationTime/1000000) as int + it.name = "GlobalConstraintEvaluationTime" + it.value = (strategy.globalConstraintEvaluationTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "FitnessCalculationTime" it.value = (strategy.fitnessCalculationTime/1000000) as int + it.name = "FitnessCalculationTime" + it.value = (strategy.fitnessCalculationTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "SolutionCopyTime" it.value = (solutionSaver.totalCopierRuntime/1000000) as int + it.name = "SolutionCopyTime" + it.value = (solutionSaver.totalCopierRuntime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "ActivationSelectionTime" it.value = (strategy.activationSelector.runtime/1000000) as int + it.name = "ActivationSelectionTime" + it.value = (strategy.activationSelector.runtime / 1000000) as int ] it.entries += createIntStatisticEntry => [ it.name = "Decisions" @@ -287,27 +258,34 @@ class ViatraReasoner extends LogicReasoner { it.value = method.statistics.scopePropagatorSolverInvocations ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverSumTime" it.value = (strategy.numericSolver.runtime/1000000) as int + it.name = "NumericalSolverSumTime" + it.value = (strategy.numericSolver.runtime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverProblemFormingTime" it.value = (strategy.numericSolver.solverFormingProblem/1000000) as int + it.name = "NumericalSolverProblemFormingTime" + it.value = (strategy.numericSolver.solverFormingProblem / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverSolvingTime" it.value = (strategy.numericSolver.solverSolvingProblem/1000000) as int + it.name = "NumericalSolverSolvingTime" + it.value = (strategy.numericSolver.solverSolvingProblem / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverInterpretingSolution" it.value = (strategy.numericSolver.solverSolution/1000000) as int + it.name = "NumericalSolverInterpretingSolution" + it.value = (strategy.numericSolver.solverSolution / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverCachingTime" it.value = (strategy.numericSolver.cachingTime/1000000) as int + it.name = "NumericalSolverCachingTime" + it.value = (strategy.numericSolver.cachingTime / 1000000) as int ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverCallNumber" it.value = strategy.numericSolver.numberOfSolverCalls + it.name = "NumericalSolverCallNumber" + it.value = strategy.numericSolver.numberOfSolverCalls ] it.entries += createIntStatisticEntry => [ - it.name = "NumericalSolverCachedAnswerNumber" it.value = strategy.numericSolver.numberOfCachedSolverCalls + it.name = "NumericalSolverCachedAnswerNumber" + it.value = strategy.numericSolver.numberOfCachedSolverCalls ] - if(diversityChecker.active) { + if (diversityChecker.active) { it.entries += createIntStatisticEntry => [ it.name = "SolutionDiversityCheckTime" 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 import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicSolverConfiguration import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RelationDeclaration import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.TypeInferenceMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedralScopePropagatorConstraints @@ -12,6 +11,7 @@ import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Polyhedr import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ScopePropagatorStrategy import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.UnitPropagationPatternGenerator import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.CostObjectiveHint import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold import java.util.LinkedList @@ -114,9 +114,11 @@ class CostObjectiveConfiguration { public var ObjectiveKind kind public var ObjectiveThreshold threshold public var boolean findExtremum + public var CostObjectiveHint hint } class CostObjectiveElementConfiguration { public var String patternQualifiedName public var int weight } + 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; import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler; import org.eclipse.viatra.dse.solutionstore.SolutionStore; -import org.eclipse.viatra.query.runtime.api.IPatternMatch; -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher; import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; @@ -37,12 +35,11 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; -import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod; import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; @@ -301,7 +298,7 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { return activationIds; } - private void checkForSolution(final Fitness fittness) { + private void checkForSolution(final Fitness fitness) { solutionStore.newSolution(context); } 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 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import java.math.BigDecimal import java.util.HashMap import 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 import java.util.Map import java.util.TreeSet import org.eclipse.emf.ecore.EObject +import org.eclipse.xtend.lib.annotations.Accessors import org.eclipse.xtext.xbase.lib.Functions.Function1 import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ - val PartialInterpretation partialInterpretation + @Accessors val PartialInterpretation partialInterpretation val Map trace; val Map type2Interpretation val Map 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 { * using the supplied {@link NumericSolver}. */ class SolutionCopier { - val NumericSolver numericSolver val copiedSolutions = new LinkedHashMap + @Accessors NumericSolver numericSolver long startTime = System.nanoTime @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0 - new(NumericSolver numericSolver) { - this.numericSolver = numericSolver - } - def void copySolution(ThreadContext context, Object solutionId) { val existingCopy = copiedSolutions.get(solutionId) if (existingCopy === null) { @@ -47,7 +43,7 @@ class SolutionCopier { totalCopierRuntime += System.nanoTime - copyStart val copierRuntime = System.nanoTime - startTime val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime) - numericSolver.fillSolutionCopy(copiedSolution.trace) + numericSolver?.fillSolutionCopy(copiedSolution.trace) copiedSolutions.put(solutionId, copiedSolution) } else { 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 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.DirectionalThresholdObjective +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IObjectiveBoundsProvider +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold import java.util.HashMap import java.util.Map import org.eclipse.viatra.dse.api.DSEException @@ -18,24 +22,32 @@ import org.eclipse.xtend.lib.annotations.Accessors * Will also automatically fill any missing numerical values in the saved solutions * using the supplied {@link NumericSolver}. */ -class ViatraReasonerSolutionSaver implements ISolutionSaver { +class ViatraReasonerSolutionSaver implements ISolutionSaver, IObjectiveBoundsProvider { + static val TOLERANCE = 1e-10 + @Accessors val SolutionCopier solutionCopier - val NumericSolver numericSolver @Accessors val DiversityChecker diversityChecker + val IObjective[][] leveledExtremalObjectives val boolean hasExtremalObjectives val int numberOfRequiredSolutions val ObjectiveComparatorHelper comparatorHelper val Map trajectories = new HashMap - @Accessors(PUBLIC_SETTER) var Map solutionsCollection + @Accessors var NumericSolver numericSolver + @Accessors var Map solutionsCollection - new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker, NumericSolver numericSolver) { + new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker) { this.diversityChecker = diversityChecker comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) + this.leveledExtremalObjectives = leveledExtremalObjectives hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] this.numberOfRequiredSolutions = numberOfRequiredSolutions - this.solutionCopier = new SolutionCopier(numericSolver) + this.solutionCopier = new SolutionCopier + } + + def setNumericSolver(NumericSolver numericSolver) { this.numericSolver = numericSolver + solutionCopier.numericSolver = numericSolver } override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { @@ -51,6 +63,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { if (!shouldSaveSolution(fitness, context)) { return false } + println("Found: " + fitness) val dominatedTrajectories = newArrayList for (entry : trajectories.entrySet) { val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value) @@ -99,7 +112,7 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { } private def shouldSaveSolution(Fitness fitness, ThreadContext context) { - return fitness.satisifiesHardObjectives && numericSolver.currentSatisfiable + fitness.satisifiesHardObjectives && (numericSolver === null || numericSolver.currentSatisfiable) } private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, @@ -145,8 +158,93 @@ class ViatraReasonerSolutionSaver implements ISolutionSaver { } solutionsCollection.size < numberOfRequiredSolutions } - + def getTotalCopierRuntime() { solutionCopier.totalCopierRuntime } + + override computeRequiredBounds(IObjective objective, Bounds bounds) { + if (!hasExtremalObjectives) { + return + } + if (objective instanceof DirectionalThresholdObjective) { + switch (threshold : objective.threshold) { + case ObjectiveThreshold.NO_THRESHOLD: { + // No threshold to set. + } + ObjectiveThreshold.Exclusive: { + switch (kind : objective.kind) { + case HIGHER_IS_BETTER: + bounds.tightenLowerBound(Math.floor(threshold.threshold + 1) as int) + case LOWER_IS_BETTER: + bounds.tightenUpperBound(Math.ceil(threshold.threshold - 1) as int) + default: + throw new IllegalArgumentException("Unknown objective kind" + kind) + } + if (threshold.clampToThreshold) { + return + } + } + ObjectiveThreshold.Inclusive: { + switch (kind : objective.kind) { + case HIGHER_IS_BETTER: + bounds.tightenLowerBound(Math.ceil(threshold.threshold) as int) + case LOWER_IS_BETTER: + bounds.tightenUpperBound(Math.floor(threshold.threshold) as int) + default: + throw new IllegalArgumentException("Unknown objective kind" + kind) + } + if (threshold.clampToThreshold) { + return + } + } + default: + throw new IllegalArgumentException("Unknown threshold: " + threshold) + } + for (level : leveledExtremalObjectives) { + switch (level.size) { + case 0: { + // Nothing to do, wait for the next level. + } + case 1: { + val primaryObjective = level.get(0) + if (primaryObjective != objective) { + // There are no worst-case bounds for secondary objectives. + return + } + } + default: + // There are no worst-case bounds for Pareto front calculation. + return + } + } + val fitnessIterator = trajectories.values.iterator + if (!fitnessIterator.hasNext) { + return + } + val fitness = fitnessIterator.next.get(objective.name) + while (fitnessIterator.hasNext) { + val otherFitness = fitnessIterator.next.get(objective.name) + if (Math.abs(fitness - otherFitness) > TOLERANCE) { + throw new IllegalStateException("Inconsistent fitness: " + objective.name) + } + } + switch (kind : objective.kind) { + case HIGHER_IS_BETTER: + if (needsMoreSolutionsWithSameFitness) { + bounds.tightenLowerBound(Math.floor(fitness) as int) + } else { + bounds.tightenLowerBound(Math.floor(fitness + 1) as int) + } + case LOWER_IS_BETTER: + if (needsMoreSolutionsWithSameFitness) { + bounds.tightenUpperBound(Math.ceil(fitness) as int) + } else { + bounds.tightenUpperBound(Math.ceil(fitness - 1) as int) + } + default: + throw new IllegalArgumentException("Unknown objective kind" + kind) + } + } + } } 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import com.google.common.collect.ImmutableList +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicproblemPackage +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialinterpretationPackage +import java.util.List +import org.eclipse.emf.ecore.EObject +import org.eclipse.viatra.query.runtime.api.IPatternMatch +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher +import org.eclipse.xtend.lib.annotations.Data +import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation + +@FunctionalInterface +interface ParameterScopeBound { + def double getUpperBound() +} + +@Data +class CostElementMatch { + val IPatternMatch match + val boolean must + + def isMulti() { + CostElementMatchers.isMultiMatch(match) + } +} + +@Data +class CostElementMatchers { + val ViatraQueryMatcher currentMatcher + val ViatraQueryMatcher mayMatcher + val ViatraQueryMatcher mustMatcher + val List parameterScopeBounds + val int weight + + def getCurrentNumberOfMatches() { + currentMatcher.countMatches + } + + def getMinimumNumberOfMatches() { + mustMatcher.countMatches + } + + def getMaximumNumberOfMatches() { + var double sum = 0 + val iterator = mayMatcher.streamAllMatches.iterator + while (iterator.hasNext) { + val match = iterator.next + var double product = 1 + val numberOfParameters = parameterScopeBounds.size + for (var int i = 0; i < numberOfParameters; i++) { + if (isMulti(match.get(i + 2))) { + val scopeBound = parameterScopeBounds.get(i) + product *= scopeBound.upperBound + } + + } + sum += product + } + sum + } + + def getMatches() { + ImmutableList.copyOf(mayMatcher.streamAllMatches.iterator.map [ match | + new CostElementMatch(match, mustMatcher.isMatch(match)) + ]) + } + + def projectMayMatch(IPatternMatch match, int... indices) { + mayMatcher.projectMatch(match, indices) + } + + private static def projectMatch(ViatraQueryMatcher matcher, IPatternMatch match, int... indices) { + checkMatch(match) + val n = matcher.specification.parameters.length - 2 + if (indices.length != n) { + throw new IllegalArgumentException("Invalid number of projection indices") + } + val newMatch = matcher.newEmptyMatch + newMatch.set(0, match.get(0)) + newMatch.set(1, match.get(1)) + for (var int i = 0; i < n; i++) { + newMatch.set(i + 2, match.get(indices.get(i))) + } + if (!matcher.hasMatch(newMatch)) { + throw new IllegalArgumentException("Projected match does not exist") + } + return newMatch + } + + private static def isMatch(ViatraQueryMatcher matcher, IPatternMatch match) { + val n = matcher.specification.parameters.length + if (n != match.specification.parameters.length) { + throw new IllegalArgumentException("Invalid number of match arguments") + } + val newMatch = matcher.newEmptyMatch + for (var int i = 0; i < n; i++) { + newMatch.set(i, match.get(i)) + } + return matcher.hasMatch(newMatch) + } + + static def isMulti(Object o) { + if (o instanceof EObject) { + switch (feature : o.eContainmentFeature) { + case LogicproblemPackage.eINSTANCE.logicProblem_Elements, + case PartialinterpretationPackage.eINSTANCE.partialInterpretation_NewElements: + false + case PartialinterpretationPackage.eINSTANCE.partialInterpretation_OpenWorldElements: + true + default: + throw new IllegalStateException("Unknown containment feature for element: " + feature) + } + } else { + false + } + } + + static def isMultiMatch(IPatternMatch match) { + checkMatch(match) + val n = match.specification.parameters.length + for (var int i = 2; i < n; i++) { + if (isMulti(match.get(i))) { + return true + } + } + false + } + + private static def checkMatch(IPatternMatch match) { + val n = match.specification.parameters.length + if (n < 2 || !(match.get(0) instanceof LogicProblem) || !(match.get(1) instanceof PartialInterpretation)) { + throw new IllegalArgumentException("Match is not from the partial interpretation") + } + } +} 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.ExtendedLinearExpressionBuilder +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeExpressionBuilderFactory +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.PatternGenerator +import java.util.Map +import org.eclipse.viatra.query.runtime.matchers.psystem.queries.PQuery +import org.eclipse.xtend.lib.annotations.Accessors + +abstract class CostObjectiveHint implements LinearTypeConstraintHint, BoundSaturationListener { + @Accessors ThreeValuedCostObjective objective + @Accessors IObjectiveBoundsProvider boundsProvider + + Integer bestUpper = null + + override getAdditionalPatterns(PatternGenerator patternGenerator, Map fqnToPQuery) { + '''''' + } + + override createConstraintUpdater(LinearTypeExpressionBuilderFactory builderFactory) { + null + } + + def isExact() { + false + } + + def PolyhedronExtensionOperator createPolyhedronExtensionOperator( + Map costElementMatchers) { + null + } + + def setObjective(ThreeValuedCostObjective objective) { + if (this.objective !== null) { + throw new IllegalStateException("Objective was already set") + } + this.objective = objective + } + + def setBoundsProvider(IObjectiveBoundsProvider boundsProvider) { + if (this.boundsProvider !== null) { + throw new IllegalStateException("Objective bounds provider was already set") + } + this.boundsProvider = boundsProvider + } + + protected def buildWithBounds(ExtendedLinearExpressionBuilder builder) { + val bounds = builder.build(this) + if (objective !== null && boundsProvider !== null) { + boundsProvider.computeRequiredBounds(objective, bounds) + } + if (exact && bestUpper !== null) { + bounds.tightenLowerBound(bestUpper) + } + bounds + } + + override boundsSaturated(Integer lower, Integer upper) { + if (upper !== null && (bestUpper === null || bestUpper < upper)) { + bestUpper = upper + } + objective?.boundsSaturated(lower, upper) + } + +} 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds +import org.eclipse.viatra.dse.objectives.IObjective + +interface IObjectiveBoundsProvider { + def void computeRequiredBounds(IObjective objective, Bounds bounds) +} 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 @@ package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization -import com.google.common.collect.ImmutableList -import java.util.Collection +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.BoundSaturationListener +import java.util.Map import org.eclipse.viatra.dse.base.ThreadContext -import org.eclipse.viatra.query.runtime.api.IPatternMatch -import org.eclipse.viatra.query.runtime.api.IQuerySpecification -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -import org.eclipse.xtend.lib.annotations.Data +import org.eclipse.xtend.lib.annotations.Accessors -@Data -class ThreeValuedCostElement { - val IQuerySpecification> currentMatchQuery - val IQuerySpecification> mayMatchQuery - val IQuerySpecification> mustMatchQuery - val int weight -} - -class ThreeValuedCostObjective extends AbstractThreeValuedObjective { - val Collection costElements - Collection matchers +class ThreeValuedCostObjective extends AbstractThreeValuedObjective implements BoundSaturationListener { + @Accessors val Map matchers + double lowerBoundHint = Double.NEGATIVE_INFINITY + double upperBoundHint = Double.POSITIVE_INFINITY - new(String name, Collection costElements, ObjectiveKind kind, ObjectiveThreshold threshold, + new(String name, Map matchers, ObjectiveKind kind, ObjectiveThreshold threshold, int level) { super(name, kind, threshold, level) - this.costElements = costElements + this.matchers = matchers } override createNew() { - new ThreeValuedCostObjective(name, costElements, kind, threshold, level) + // new ThreeValuedCostObjective(name, matchers, kind, threshold, level) + throw new UnsupportedOperationException("ThreeValuedCostObjective can only be used from a single thread") } override init(ThreadContext context) { - val queryEngine = context.queryEngine - matchers = ImmutableList.copyOf(costElements.map [ element | - new CostElementMatchers( - queryEngine.getMatcher(element.currentMatchQuery), - queryEngine.getMatcher(element.mayMatchQuery), - queryEngine.getMatcher(element.mustMatchQuery), - element.weight - ) - ]) } override getRawFitness(ThreadContext context) { - var int cost = 0 - for (matcher : matchers) { - cost += matcher.weight * matcher.currentMatcher.countMatches + var double cost = 0 + for (matcher : matchers.values) { + cost += matcher.weight * matcher.currentNumberOfMatches } - cost as double + cost } override getLowestPossibleFitness(ThreadContext threadContext) { - var int cost = 0 - for (matcher : matchers) { + var double cost = 0 + for (matcher : matchers.values) { if (matcher.weight >= 0) { - cost += matcher.weight * matcher.mustMatcher.countMatches - } else if (matcher.mayMatcher.countMatches > 0) { - // TODO Count may matches. - return Double.NEGATIVE_INFINITY + cost += matcher.weight * matcher.minimumNumberOfMatches + } else { + cost += matcher.weight * matcher.maximumNumberOfMatches } } - cost as double + val boundWithHint = Math.max(lowerBoundHint, cost) + if (boundWithHint > upperBoundHint) { + throw new IllegalStateException("Inconsistent cost bounds") + } + boundWithHint } override getHighestPossibleFitness(ThreadContext threadContext) { - var int cost = 0 - for (matcher : matchers) { + var double cost = 0 + for (matcher : matchers.values) { if (matcher.weight <= 0) { - cost += matcher.weight * matcher.mustMatcher.countMatches - } else if (matcher.mayMatcher.countMatches > 0) { - return Double.POSITIVE_INFINITY + cost += matcher.weight * matcher.minimumNumberOfMatches + } else { + cost += matcher.weight * matcher.maximumNumberOfMatches } } - cost as double + val boundWithHint = Math.min(upperBoundHint, cost) + if (boundWithHint < lowerBoundHint) { + throw new IllegalStateException("Inconsistent cost bounds") + } + boundWithHint } - @Data - private static class CostElementMatchers { - val ViatraQueryMatcher currentMatcher - val ViatraQueryMatcher mayMatcher - val ViatraQueryMatcher mustMatcher - val int weight + override boundsSaturated(Integer lower, Integer upper) { + lowerBoundHint = if (lower === null) { + Double.NEGATIVE_INFINITY + } else { + lower + } + upperBoundHint = if (upper === null) { + Double.POSITIVE_INFINITY + } else { + upper + } + println('''Bounds saturated: «lower»..«upper»''') } } 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 @@ +package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Lists +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.BoolTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.ComplexTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.IntTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.RealTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.Relation +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.StringTypeReference +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeDeclaration +import hu.bme.mit.inf.dslreasoner.logic.model.logiclanguage.TypeReference +import hu.bme.mit.inf.dslreasoner.viatra2logic.viatra2logicannotations.TransfomedViatraQuery +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.PolyhedronExtensionOperator +import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.patterns.ModalPatternQueries +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialBooleanInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialComplexTypeInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialIntegerInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialRealInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialStringInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.Scope +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveConfiguration +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.CostObjectiveElementConfiguration +import java.util.Collection +import java.util.Map +import org.eclipse.viatra.dse.objectives.IObjective +import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine +import org.eclipse.xtend.lib.annotations.Data + +@Data +class ThreeValuedCostObjectiveProviderResult { + val Collection objectives + val Collection hints + val Collection extensionOperators + val IObjective[][] leveledExtremalObjectives + val boolean optimizationProblem +} + +class ThreeValuedCostObjectiveProvider { + static val COST_OBJECTIVE_LEVEL = 3 + + val ViatraQueryEngine queryEngine + val Map modalRelationQueries + val Map qualifiedNameToRelationMap + val ParameterScopeBound defaultBounds + val ParameterScopeBound booleanBounds + val ParameterScopeBound integerBounds + val ParameterScopeBound realBounds + val ParameterScopeBound stringBounds + val Map typeDeclarationToBoundsMap + + new(ViatraQueryEngine queryEngine, PartialInterpretation interpretation, + Map modalRelationQueries) { + this.queryEngine = queryEngine + this.modalRelationQueries = modalRelationQueries + qualifiedNameToRelationMap = ImmutableMap.copyOf( + interpretation.problem.annotations.filter(TransfomedViatraQuery). + toMap([patternFullyQualifiedName], [target])) + defaultBounds = new PartialInterpretationBasedParameterScopeBound(interpretation) + var ParameterScopeBound booleanBounds = null + var ParameterScopeBound integerBounds = null + var ParameterScopeBound realBounds = null + var ParameterScopeBound stringBounds = null + val typeDeclarationToBoundsMapBuilder = ImmutableMap.builder + for (scope : interpretation.scopes) { + val bounds = new ScopeBasedParameterScopeBound(scope) + switch (typeInterpretation : scope.targetTypeInterpretation) { + PartialBooleanInterpretation: + if (booleanBounds === null) { + booleanBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial boolean interpretation") + } + PartialIntegerInterpretation: + if (integerBounds === null) { + integerBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial integer interpretation") + } + PartialRealInterpretation: + if (realBounds === null) { + realBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial real interpretation") + } + PartialStringInterpretation: + if (stringBounds === null) { + stringBounds = bounds + } else { + throw new IllegalStateException("Duplicate partial string interpretation") + } + PartialComplexTypeInterpretation: + typeDeclarationToBoundsMapBuilder.put(typeInterpretation.interpretationOf, bounds) + } + } + this.booleanBounds = booleanBounds ?: defaultBounds + this.integerBounds = integerBounds ?: defaultBounds + this.realBounds = realBounds ?: defaultBounds + this.stringBounds = stringBounds ?: defaultBounds + typeDeclarationToBoundsMap = typeDeclarationToBoundsMapBuilder.build + } + + def getCostObjectives(Collection costObjectives) { + val objectives = ImmutableList.builder + val hints = ImmutableList.builder + val extensionOperators = ImmutableList.builder + val extremalObjectives = Lists.newArrayListWithExpectedSize(costObjectives.size) + for (entry : costObjectives.indexed) { + val objectiveName = '''costObjective«entry.key»''' + val objectiveConfig = entry.value + val costObjective = transformCostObjective(objectiveConfig, objectiveName) + objectives.add(costObjective) + if (objectiveConfig.findExtremum) { + extremalObjectives += costObjective + } + val hint = objectiveConfig.hint + if (hint !== null) { + hints.add(hint) + hint.objective = costObjective + val extensionOperator = hint.createPolyhedronExtensionOperator(costObjective.matchers) + if (extensionOperator !== null) { + extensionOperators.add(extensionOperator) + } + } + } + new ThreeValuedCostObjectiveProviderResult( + objectives.build, + hints.build, + extensionOperators.build, + newArrayList(extremalObjectives), + !extremalObjectives.empty + ) + } + + private def transformCostObjective(CostObjectiveConfiguration configuration, String name) { + val costElements = ImmutableMap.copyOf(configuration.elements.toMap([patternQualifiedName], [ + transformCostElement + ])) + new ThreeValuedCostObjective(name, costElements, configuration.kind, configuration.threshold, + COST_OBJECTIVE_LEVEL) + } + + private def transformCostElement(CostObjectiveElementConfiguration elementConfig) { + val relationName = elementConfig.patternQualifiedName + val modalQueries = modalRelationQueries.get(relationName) + if (modalQueries === null) { + throw new IllegalArgumentException("Unknown relation queries: " + relationName) + } + val relation = qualifiedNameToRelationMap.get(relationName) + if (relation === null) { + throw new IllegalArgumentException("Unknown transformed relation: " + relationName) + } + val parameterBounds = ImmutableList.copyOf(relation.parameters.map[parameterBound]) + new CostElementMatchers( + queryEngine.getMatcher(modalQueries.currentQuery), + queryEngine.getMatcher(modalQueries.mayQuery), + queryEngine.getMatcher(modalQueries.mustQuery), + parameterBounds, + elementConfig.weight + ) + } + + private def getParameterBound(TypeReference typeReference) { + switch (typeReference) { + BoolTypeReference: booleanBounds + IntTypeReference: integerBounds + RealTypeReference: realBounds + StringTypeReference: stringBounds + ComplexTypeReference: typeDeclarationToBoundsMap.getOrDefault(typeReference.referred, defaultBounds) + } + } + + private static abstract class AbstractParameterScopeBound implements ParameterScopeBound { + override getUpperBound() { + val rawValue = rawUpperBound + if (rawValue < 0) { + Double.POSITIVE_INFINITY + } else { + rawValue + } + } + + protected def int getRawUpperBound() + } + + @Data + private static class ScopeBasedParameterScopeBound extends AbstractParameterScopeBound { + val Scope scope + + override protected getRawUpperBound() { + scope.maxNewElements + } + } + + @Data + private static class PartialInterpretationBasedParameterScopeBound extends AbstractParameterScopeBound { + val PartialInterpretation interpretation + + override protected getRawUpperBound() { + interpretation.maxNewElements + } + } +} 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 @@ /.MemberHasParent.java._trace /.TwoMembersHaveNoParent.java._trace /.NegativeAge.java._trace +/MemberHasParent.java +/NegativeAge.java +/ParentTooYoung.java +/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 @@ /.MemberHasParent.java._trace /.TwoMembersHaveNoParent.java._trace /.NegativeAge.java._trace +/MemberHasParent.java +/NegativeAge.java +/ParentTooYoung.java +/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 Binary files a/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin and b/Tests/MODELS2020-CaseStudies/case.study.pledge.originalFiles/xtend-gen/converter/.UML2TGF.xtendbin 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 @@ package hu.bme.mit.inf.dslreasoner.run -import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import org.eclipse.viatra.dse.base.ThreadContext +import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher class FileSystemInconsistencyDetector extends ModelGenerationMethodBasedGlobalConstraint { 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 import hu.bme.mit.inf.dslreasoner.ecore2logic.EcoreMetamodelDescriptor import hu.bme.mit.inf.dslreasoner.partialsnapshot_mavo.yakindu.Patterns import hu.bme.mit.inf.dslreasoner.viatra2logic.ViatraQuerySetDescriptor -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.LinearTypeConstraintHint +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace import 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 @@ package hu.bme.mit.inf.dslreasoner.run -import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation +import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethodBasedGlobalConstraint import org.eclipse.viatra.dse.base.ThreadContext import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher -- cgit v1.2.3-54-g00ecf