diff options
Diffstat (limited to 'Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse')
20 files changed, 1098 insertions, 350 deletions
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 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import com.google.common.collect.ImmutableList | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialTypeInterpratation | ||
6 | import java.util.Comparator | ||
7 | import java.util.List | ||
8 | import org.eclipse.viatra.dse.base.ThreadContext | ||
9 | import org.eclipse.viatra.dse.objectives.Comparators | ||
10 | import org.eclipse.viatra.dse.objectives.IGlobalConstraint | ||
11 | import org.eclipse.viatra.dse.objectives.IObjective | ||
12 | import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor | ||
13 | |||
14 | class BasicScopeGlobalConstraint implements IGlobalConstraint, IObjective { | ||
15 | val PartialInterpretation p | ||
16 | val List<ScopeAssertion> assertions | ||
17 | |||
18 | new(PartialInterpretation p) { | ||
19 | this.p = p | ||
20 | assertions = ImmutableList.copyOf(p.scopes.map [ | ||
21 | val currentSize = targetTypeInterpretation.elements.size | ||
22 | val minElements = minNewElements + currentSize | ||
23 | val maxElements = if (maxNewElements < 0) { | ||
24 | -1 | ||
25 | } else { | ||
26 | maxNewElements + currentSize | ||
27 | } | ||
28 | new ScopeAssertion(minElements, maxElements, targetTypeInterpretation) | ||
29 | ]) | ||
30 | } | ||
31 | |||
32 | override init(ThreadContext context) { | ||
33 | if (context.model != p) { | ||
34 | throw new IllegalArgumentException( | ||
35 | "Partial model must be passed to the constructor of BasicScopeGlobalConstraint") | ||
36 | } | ||
37 | } | ||
38 | |||
39 | override checkGlobalConstraint(ThreadContext context) { | ||
40 | assertions.forall[upperBoundSatisfied] | ||
41 | } | ||
42 | |||
43 | override getFitness(ThreadContext context) { | ||
44 | var double fitness = p.minNewElements | ||
45 | for (assertion : assertions) { | ||
46 | if (!assertion.lowerBoundSatisfied) { | ||
47 | fitness += 1 | ||
48 | } | ||
49 | } | ||
50 | fitness | ||
51 | } | ||
52 | |||
53 | override satisifiesHardObjective(Double fitness) { | ||
54 | fitness <= 0.01 | ||
55 | } | ||
56 | |||
57 | override BasicScopeGlobalConstraint createNew() { | ||
58 | this | ||
59 | } | ||
60 | |||
61 | override getName() { | ||
62 | class.name | ||
63 | } | ||
64 | |||
65 | override getComparator() { | ||
66 | Comparators.LOWER_IS_BETTER | ||
67 | } | ||
68 | |||
69 | override getLevel() { | ||
70 | 2 | ||
71 | } | ||
72 | |||
73 | override isHardObjective() { | ||
74 | true | ||
75 | } | ||
76 | |||
77 | override setComparator(Comparator<Double> comparator) { | ||
78 | throw new UnsupportedOperationException | ||
79 | } | ||
80 | |||
81 | override setLevel(int level) { | ||
82 | throw new UnsupportedOperationException | ||
83 | } | ||
84 | |||
85 | @FinalFieldsConstructor | ||
86 | private static class ScopeAssertion { | ||
87 | val int lowerBound | ||
88 | val int upperBound | ||
89 | val PartialTypeInterpratation typeDefinitions | ||
90 | |||
91 | private def getCount() { | ||
92 | typeDefinitions.elements.size | ||
93 | } | ||
94 | |||
95 | private def isLowerBoundSatisfied() { | ||
96 | count >= lowerBound | ||
97 | } | ||
98 | |||
99 | private def isUpperBoundSatisfied() { | ||
100 | upperBound < 0 || count <= upperBound | ||
101 | } | ||
102 | } | ||
103 | } | ||
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 e0f838a6..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 | |||
@@ -9,33 +9,25 @@ | |||
9 | *******************************************************************************/ | 9 | *******************************************************************************/ |
10 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse; | 10 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse; |
11 | 11 | ||
12 | import java.io.BufferedReader; | ||
13 | import java.io.IOException; | ||
14 | import java.io.InputStreamReader; | ||
15 | import java.util.ArrayList; | ||
16 | import java.util.Arrays; | 12 | import java.util.Arrays; |
17 | import java.util.Collection; | ||
18 | import java.util.Collections; | 13 | import java.util.Collections; |
19 | import java.util.Comparator; | 14 | import java.util.Comparator; |
20 | import java.util.Iterator; | 15 | import java.util.Iterator; |
21 | import java.util.LinkedList; | 16 | import java.util.LinkedList; |
22 | import java.util.List; | 17 | import java.util.List; |
23 | import java.util.Map; | ||
24 | import java.util.PriorityQueue; | 18 | import java.util.PriorityQueue; |
25 | import java.util.Random; | 19 | import java.util.Random; |
26 | 20 | ||
27 | import org.apache.log4j.Logger; | 21 | import org.apache.log4j.Logger; |
28 | import org.eclipse.emf.ecore.EObject; | 22 | import org.eclipse.emf.ecore.EObject; |
29 | import org.eclipse.emf.ecore.util.EcoreUtil; | 23 | import org.eclipse.emf.ecore.util.EcoreUtil; |
24 | import org.eclipse.viatra.dse.api.SolutionTrajectory; | ||
30 | import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; | 25 | import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; |
31 | import org.eclipse.viatra.dse.base.ThreadContext; | 26 | import org.eclipse.viatra.dse.base.ThreadContext; |
32 | import org.eclipse.viatra.dse.objectives.Fitness; | 27 | import org.eclipse.viatra.dse.objectives.Fitness; |
33 | import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; | 28 | import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper; |
29 | import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler; | ||
34 | import org.eclipse.viatra.dse.solutionstore.SolutionStore; | 30 | import org.eclipse.viatra.dse.solutionstore.SolutionStore; |
35 | import org.eclipse.viatra.query.runtime.api.IPatternMatch; | ||
36 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification; | ||
37 | import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine; | ||
38 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher; | ||
39 | 31 | ||
40 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; | 32 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.DocumentationLevel; |
41 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; | 33 | import hu.bme.mit.inf.dslreasoner.logic.model.builder.LogicReasoner; |
@@ -43,13 +35,11 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem; | |||
43 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; | 35 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; |
44 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; | 36 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; |
45 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; | 37 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; |
46 | import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericProblemSolver; | ||
47 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; | ||
48 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; | 38 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; |
49 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; | 39 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; |
50 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder; | ||
51 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; | 40 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; |
52 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; | 41 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; |
42 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod; | ||
53 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; | 43 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; |
54 | import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; | 44 | import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; |
55 | 45 | ||
@@ -82,58 +72,72 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
82 | // Running | 72 | // Running |
83 | private PriorityQueue<TrajectoryWithFitness> trajectoiresToExplore; | 73 | private PriorityQueue<TrajectoryWithFitness> trajectoiresToExplore; |
84 | private SolutionStore solutionStore; | 74 | private SolutionStore solutionStore; |
85 | private SolutionStoreWithCopy solutionStoreWithCopy; | ||
86 | private SolutionStoreWithDiversityDescriptor solutionStoreWithDiversityDescriptor; | ||
87 | private volatile boolean isInterrupted = false; | 75 | private volatile boolean isInterrupted = false; |
88 | private ModelResult modelResultByInternalSolver = null; | 76 | private ModelResult modelResultByInternalSolver = null; |
89 | private Random random = new Random(); | 77 | private Random random = new Random(); |
90 | //private Collection<ViatraQueryMatcher<? extends IPatternMatch>> matchers; | 78 | // private Collection<ViatraQueryMatcher<? extends IPatternMatch>> matchers; |
91 | public ActivationSelector activationSelector = new EvenActivationSelector(random); | 79 | public ActivationSelector activationSelector = new EvenActivationSelector(random); |
92 | public NumericSolver numericSolver = null; | 80 | public ViatraReasonerSolutionSaver solutionSaver; |
81 | public NumericSolver numericSolver; | ||
93 | // Statistics | 82 | // Statistics |
94 | private int numberOfStatecoderFail = 0; | 83 | private int numberOfStatecoderFail = 0; |
95 | private int numberOfPrintedModel = 0; | 84 | private int numberOfPrintedModel = 0; |
96 | private int numberOfSolverCalls = 0; | 85 | private int numberOfSolverCalls = 0; |
86 | public long globalConstraintEvaluationTime = 0; | ||
87 | public long fitnessCalculationTime = 0; | ||
97 | 88 | ||
98 | public long explorationStarted = 0; | 89 | public long explorationStarted = 0; |
99 | 90 | ||
100 | public BestFirstStrategyForModelGeneration( | 91 | public BestFirstStrategyForModelGeneration( |
101 | ReasonerWorkspace workspace, | 92 | ReasonerWorkspace workspace, |
102 | ViatraReasonerConfiguration configuration, | 93 | ViatraReasonerConfiguration configuration, |
103 | ModelGenerationMethod method) | 94 | ModelGenerationMethod method, |
104 | { | 95 | ViatraReasonerSolutionSaver solutionSaver, |
96 | NumericSolver numericSolver) { | ||
105 | this.workspace = workspace; | 97 | this.workspace = workspace; |
106 | this.configuration = configuration; | 98 | this.configuration = configuration; |
107 | this.method = method; | 99 | this.method = method; |
100 | this.solutionSaver = solutionSaver; | ||
101 | this.numericSolver = numericSolver; | ||
102 | // logger.setLevel(Level.DEBUG); | ||
108 | } | 103 | } |
109 | 104 | ||
110 | public SolutionStoreWithCopy getSolutionStoreWithCopy() { | ||
111 | return solutionStoreWithCopy; | ||
112 | } | ||
113 | public SolutionStoreWithDiversityDescriptor getSolutionStoreWithDiversityDescriptor() { | ||
114 | return solutionStoreWithDiversityDescriptor; | ||
115 | } | ||
116 | public int getNumberOfStatecoderFail() { | 105 | public int getNumberOfStatecoderFail() { |
117 | return numberOfStatecoderFail; | 106 | return numberOfStatecoderFail; |
118 | } | 107 | } |
119 | //LinkedList<ViatraQueryMatcher<? extends IPatternMatch>> matchers; | 108 | public long getForwardTime() { |
109 | return context.getDesignSpaceManager().getForwardTime(); | ||
110 | } | ||
111 | public long getBacktrackingTime() { | ||
112 | return context.getDesignSpaceManager().getBacktrackingTime(); | ||
113 | } | ||
114 | |||
120 | @Override | 115 | @Override |
121 | public void initStrategy(ThreadContext context) { | 116 | public void initStrategy(ThreadContext context) { |
122 | this.context = context; | 117 | this.context = context; |
123 | this.solutionStore = context.getGlobalContext().getSolutionStore(); | 118 | this.solutionStore = context.getGlobalContext().getSolutionStore(); |
119 | solutionStore.registerSolutionFoundHandler(new ISolutionFoundHandler() { | ||
120 | |||
121 | @Override | ||
122 | public void solutionTriedToSave(ThreadContext context, SolutionTrajectory trajectory) { | ||
123 | // Ignore. | ||
124 | } | ||
125 | |||
126 | @Override | ||
127 | public void solutionFound(ThreadContext context, SolutionTrajectory trajectory) { | ||
128 | configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolutions); | ||
129 | saveTimes(); | ||
130 | logger.debug("Found a solution."); | ||
131 | } | ||
132 | }); | ||
133 | numericSolver.init(context); | ||
124 | 134 | ||
125 | // ViatraQueryEngine engine = context.getQueryEngine(); | 135 | // ViatraQueryEngine engine = context.getQueryEngine(); |
126 | // // TODO: visualisation | ||
127 | // matchers = new LinkedList<ViatraQueryMatcher<? extends IPatternMatch>>(); | 136 | // matchers = new LinkedList<ViatraQueryMatcher<? extends IPatternMatch>>(); |
128 | // for(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> p : this.method.getAllPatterns()) { | 137 | // for(IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>> p : this.method.getAllPatterns()) { |
129 | // //System.out.println(p.getSimpleName()); | 138 | // ViatraQueryMatcher<? extends IPatternMatch> matcher = p.getMatcher(engine); |
130 | // ViatraQueryMatcher<? extends IPatternMatch> matcher = p.getMatcher(engine); | ||
131 | // matchers.add(matcher); | ||
132 | // } | 139 | // } |
133 | 140 | // | |
134 | this.solutionStoreWithCopy = new SolutionStoreWithCopy(); | ||
135 | this.solutionStoreWithDiversityDescriptor = new SolutionStoreWithDiversityDescriptor(configuration.diversityRequirement); | ||
136 | |||
137 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); | 141 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); |
138 | this.comparator = new Comparator<TrajectoryWithFitness>() { | 142 | this.comparator = new Comparator<TrajectoryWithFitness>() { |
139 | @Override | 143 | @Override |
@@ -141,23 +145,14 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
141 | return objectiveComparatorHelper.compare(o2.fitness, o1.fitness); | 145 | return objectiveComparatorHelper.compare(o2.fitness, o1.fitness); |
142 | } | 146 | } |
143 | }; | 147 | }; |
144 | |||
145 | this.numericSolver = new NumericSolver(context, method, this.configuration.runIntermediateNumericalConsistencyChecks, false); | ||
146 | 148 | ||
147 | trajectoiresToExplore = new PriorityQueue<TrajectoryWithFitness>(11, comparator); | 149 | trajectoiresToExplore = new PriorityQueue<TrajectoryWithFitness>(11, comparator); |
148 | } | 150 | } |
149 | 151 | ||
150 | @Override | 152 | @Override |
151 | public void explore() { | 153 | public void explore() { |
152 | // System.out.println("press enter"); | ||
153 | // try { | ||
154 | // new BufferedReader(new InputStreamReader(System.in)).readLine(); | ||
155 | // } catch (IOException e) { | ||
156 | // // TODO Auto-generated catch block | ||
157 | // e.printStackTrace(); | ||
158 | // } | ||
159 | this.explorationStarted=System.nanoTime(); | 154 | this.explorationStarted=System.nanoTime(); |
160 | if (!context.checkGlobalConstraints()) { | 155 | if (!checkGlobalConstraints()) { |
161 | logger.info("Global contraint is not satisifed in the first state. Terminate."); | 156 | logger.info("Global contraint is not satisifed in the first state. Terminate."); |
162 | return; | 157 | return; |
163 | } else if(!numericSolver.maySatisfiable()) { | 158 | } else if(!numericSolver.maySatisfiable()) { |
@@ -169,14 +164,13 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
169 | return; | 164 | return; |
170 | } | 165 | } |
171 | 166 | ||
172 | final Fitness firstFittness = context.calculateFitness(); | 167 | final Fitness firstFitness = calculateFitness(); |
173 | checkForSolution(firstFittness); | 168 | checkForSolution(firstFitness); |
174 | 169 | ||
175 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); | 170 | final ObjectiveComparatorHelper objectiveComparatorHelper = context.getObjectiveComparatorHelper(); |
176 | final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]); | 171 | final Object[] firstTrajectory = context.getTrajectory().toArray(new Object[0]); |
177 | TrajectoryWithFitness currentTrajectoryWithFittness = new TrajectoryWithFitness(firstTrajectory, firstFittness); | 172 | TrajectoryWithFitness currentTrajectoryWithFitness = new TrajectoryWithFitness(firstTrajectory, firstFitness); |
178 | trajectoiresToExplore.add(currentTrajectoryWithFittness); | 173 | trajectoiresToExplore.add(currentTrajectoryWithFitness); |
179 | |||
180 | //if(configuration) | 174 | //if(configuration) |
181 | visualiseCurrentState(); | 175 | visualiseCurrentState(); |
182 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { | 176 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { |
@@ -190,22 +184,22 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
190 | 184 | ||
191 | mainLoop: while (!isInterrupted && !configuration.progressMonitor.isCancelled()) { | 185 | mainLoop: while (!isInterrupted && !configuration.progressMonitor.isCancelled()) { |
192 | 186 | ||
193 | if (currentTrajectoryWithFittness == null) { | 187 | if (currentTrajectoryWithFitness == null) { |
194 | if (trajectoiresToExplore.isEmpty()) { | 188 | if (trajectoiresToExplore.isEmpty()) { |
195 | logger.debug("State space is fully traversed."); | 189 | logger.debug("State space is fully traversed."); |
196 | return; | 190 | return; |
197 | } else { | 191 | } else { |
198 | currentTrajectoryWithFittness = selectState(); | 192 | currentTrajectoryWithFitness = selectState(); |
199 | if (logger.isDebugEnabled()) { | 193 | if (logger.isDebugEnabled()) { |
200 | logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray())); | 194 | logger.debug("Current trajectory: " + Arrays.toString(context.getTrajectory().toArray())); |
201 | logger.debug("New trajectory is chosen: " + currentTrajectoryWithFittness); | 195 | logger.debug("New trajectory is chosen: " + currentTrajectoryWithFitness); |
202 | } | 196 | } |
203 | context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFittness.trajectory); | 197 | context.getDesignSpaceManager().executeTrajectoryWithMinimalBacktrackWithoutStateCoding(currentTrajectoryWithFitness.trajectory); |
204 | } | 198 | } |
205 | } | 199 | } |
206 | 200 | ||
207 | // visualiseCurrentState(); | 201 | // visualiseCurrentState(); |
208 | // boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness); | 202 | // boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithfitness); |
209 | // if(consistencyCheckResult == true) { | 203 | // if(consistencyCheckResult == true) { |
210 | // continue mainLoop; | 204 | // continue mainLoop; |
211 | // } | 205 | // } |
@@ -215,29 +209,25 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
215 | 209 | ||
216 | while (!isInterrupted && !configuration.progressMonitor.isCancelled() && iterator.hasNext()) { | 210 | while (!isInterrupted && !configuration.progressMonitor.isCancelled() && iterator.hasNext()) { |
217 | final Object nextActivation = iterator.next(); | 211 | final Object nextActivation = iterator.next(); |
218 | // if (!iterator.hasNext()) { | ||
219 | // logger.debug("Last untraversed activation of the state."); | ||
220 | // trajectoiresToExplore.remove(currentTrajectoryWithFittness); | ||
221 | // } | ||
222 | logger.debug("Executing new activation: " + nextActivation); | 212 | logger.debug("Executing new activation: " + nextActivation); |
223 | context.executeAcitvationId(nextActivation); | 213 | context.executeAcitvationId(nextActivation); |
214 | method.getStatistics().incrementDecisionCount(); | ||
224 | 215 | ||
225 | visualiseCurrentState(); | 216 | visualiseCurrentState(); |
226 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { | 217 | // for(ViatraQueryMatcher<? extends IPatternMatch> matcher : matchers) { |
227 | // int c = matcher.countMatches(); | 218 | // int c = matcher.countMatches(); |
228 | // if(c>=100) { | 219 | // if(c>=1) { |
229 | // System.out.println(c+ " " +matcher.getPatternName()); | 220 | // System.out.println(c+ " " +matcher.getPatternName()); |
230 | // } | 221 | // } |
231 | // | ||
232 | // } | 222 | // } |
233 | 223 | ||
234 | boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness); | 224 | boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFitness); |
235 | if(consistencyCheckResult == true) { continue mainLoop; } | 225 | if(consistencyCheckResult == true) { continue mainLoop; } |
236 | 226 | ||
237 | if (context.isCurrentStateAlreadyTraversed()) { | 227 | if (context.isCurrentStateAlreadyTraversed()) { |
238 | logger.info("The new state is already visited."); | 228 | logger.info("The new state is already visited."); |
239 | context.backtrack(); | 229 | context.backtrack(); |
240 | } else if (!context.checkGlobalConstraints()) { | 230 | } else if (!checkGlobalConstraints()) { |
241 | logger.debug("Global contraint is not satisifed."); | 231 | logger.debug("Global contraint is not satisifed."); |
242 | context.backtrack(); | 232 | context.backtrack(); |
243 | } else if (!numericSolver.maySatisfiable()) { | 233 | } else if (!numericSolver.maySatisfiable()) { |
@@ -252,76 +242,84 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
252 | continue; | 242 | continue; |
253 | } | 243 | } |
254 | 244 | ||
255 | TrajectoryWithFitness nextTrajectoryWithFittness = new TrajectoryWithFitness( | 245 | TrajectoryWithFitness nextTrajectoryWithfitness = new TrajectoryWithFitness( |
256 | context.getTrajectory().toArray(), nextFitness); | 246 | context.getTrajectory().toArray(), nextFitness); |
257 | trajectoiresToExplore.add(nextTrajectoryWithFittness); | 247 | trajectoiresToExplore.add(nextTrajectoryWithfitness); |
258 | 248 | ||
259 | int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFittness.fitness, | 249 | int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFitness.fitness, |
260 | nextTrajectoryWithFittness.fitness); | 250 | nextTrajectoryWithfitness.fitness); |
261 | if (compare < 0) { | 251 | if (compare < 0) { |
262 | logger.debug("Better fitness, moving on: " + nextFitness); | 252 | logger.debug("Better fitness, moving on: " + nextFitness); |
263 | currentTrajectoryWithFittness = nextTrajectoryWithFittness; | 253 | currentTrajectoryWithFitness = nextTrajectoryWithfitness; |
264 | continue mainLoop; | 254 | continue mainLoop; |
265 | } else if (compare == 0) { | 255 | } else if (compare == 0) { |
266 | logger.debug("Equally good fitness, moving on: " + nextFitness); | 256 | logger.debug("Equally good fitness, moving on: " + nextFitness); |
267 | currentTrajectoryWithFittness = nextTrajectoryWithFittness; | 257 | currentTrajectoryWithFitness = nextTrajectoryWithfitness; |
268 | continue mainLoop; | 258 | continue mainLoop; |
269 | } else { | 259 | } else { |
270 | logger.debug("Worse fitness."); | 260 | logger.debug("Worse fitness."); |
271 | currentTrajectoryWithFittness = null; | 261 | currentTrajectoryWithFitness = null; |
272 | continue mainLoop; | 262 | continue mainLoop; |
273 | } | 263 | } |
274 | } | 264 | } |
275 | } | 265 | } |
276 | 266 | ||
277 | logger.debug("State is fully traversed."); | 267 | logger.debug("State is fully traversed."); |
278 | trajectoiresToExplore.remove(currentTrajectoryWithFittness); | 268 | trajectoiresToExplore.remove(currentTrajectoryWithFitness); |
279 | currentTrajectoryWithFittness = null; | 269 | currentTrajectoryWithFitness = null; |
280 | 270 | ||
281 | } | 271 | } |
282 | logger.info("Interrupted."); | 272 | logger.info("Interrupted."); |
283 | } | 273 | } |
284 | 274 | ||
275 | private boolean checkGlobalConstraints() { | ||
276 | long start = System.nanoTime(); | ||
277 | boolean result = context.checkGlobalConstraints(); | ||
278 | globalConstraintEvaluationTime += System.nanoTime() - start; | ||
279 | return result; | ||
280 | } | ||
281 | |||
282 | private Fitness calculateFitness() { | ||
283 | long start = System.nanoTime(); | ||
284 | Fitness fitness = context.calculateFitness(); | ||
285 | fitnessCalculationTime += System.nanoTime() - start; | ||
286 | return fitness; | ||
287 | } | ||
288 | |||
285 | private List<Object> selectActivation() { | 289 | private List<Object> selectActivation() { |
286 | List<Object> activationIds; | 290 | List<Object> activationIds; |
287 | try { | 291 | try { |
288 | activationIds = this.activationSelector.randomizeActivationIDs(context.getUntraversedActivationIds()); | 292 | activationIds = this.activationSelector.randomizeActivationIDs(context.getUntraversedActivationIds()); |
289 | } catch (NullPointerException e) { | 293 | } catch (NullPointerException e) { |
294 | // logger.warn("Unexpected state code: " + context.getDesignSpaceManager().getCurrentState()); | ||
290 | numberOfStatecoderFail++; | 295 | numberOfStatecoderFail++; |
291 | activationIds = Collections.emptyList(); | 296 | activationIds = Collections.emptyList(); |
292 | } | 297 | } |
293 | return activationIds; | 298 | return activationIds; |
294 | } | 299 | } |
295 | 300 | ||
296 | private void checkForSolution(final Fitness fittness) { | 301 | private void checkForSolution(final Fitness fitness) { |
297 | if (fittness.isSatisifiesHardObjectives()) { | 302 | solutionStore.newSolution(context); |
298 | if (solutionStoreWithDiversityDescriptor.isDifferent(context)) { | ||
299 | if(numericSolver.currentSatisfiable()) { | ||
300 | Map<EObject, EObject> trace = solutionStoreWithCopy.newSolution(context); | ||
301 | numericSolver.fillSolutionCopy(trace); | ||
302 | solutionStoreWithDiversityDescriptor.newSolution(context); | ||
303 | solutionStore.newSolution(context); | ||
304 | configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolution); | ||
305 | saveTimes(); | ||
306 | logger.debug("Found a solution."); | ||
307 | } | ||
308 | } | ||
309 | } | ||
310 | } | 303 | } |
304 | |||
311 | public List<String> times = new LinkedList<String>(); | 305 | public List<String> times = new LinkedList<String>(); |
312 | private void saveTimes() { | 306 | private void saveTimes() { |
313 | long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder)this.context.getStateCoder()).getStatecoderRuntime()/1000000; | 307 | long forwardTime = context.getDesignSpaceManager().getForwardTime()/1000000; |
314 | long solutionCopy = solutionStoreWithCopy.getSumRuntime()/1000000; | 308 | long backtrackingTime = context.getDesignSpaceManager().getBacktrackingTime()/1000000; |
315 | long activationSelection = this.activationSelector.getRuntime()/1000000; | 309 | long activationSelection = this.activationSelector.getRuntime()/1000000; |
310 | long solutionCopierTime = this.solutionSaver.getTotalCopierRuntime()/1000000; | ||
316 | long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000; | 311 | long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000; |
317 | long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000; | 312 | long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000; |
318 | long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; | 313 | long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; |
319 | long numericalSolverInterpreting = this.numericSolver.getSolverSolution()/1000000; | 314 | long numericalSolverInterpreting = this.numericSolver.getSolverSolution()/1000000; |
320 | this.times.add( | 315 | this.times.add( |
321 | "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ | 316 | "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ |
322 | "|StateCoderTime:"+statecoderTime+ | 317 | "|ForwardTime:"+forwardTime+ |
323 | "|SolutionCopyTime:"+solutionCopy+ | 318 | "|Backtrackingtime:"+backtrackingTime+ |
319 | "|GlobalConstraintEvaluationTime:"+(globalConstraintEvaluationTime/1000000)+ | ||
320 | "|FitnessCalculationTime:"+(fitnessCalculationTime/1000000)+ | ||
324 | "|ActivationSelectionTime:"+activationSelection+ | 321 | "|ActivationSelectionTime:"+activationSelection+ |
322 | "|SolutionCopyTime:"+solutionCopierTime+ | ||
325 | "|NumericalSolverSumTime:"+numericalSolverSumTime+ | 323 | "|NumericalSolverSumTime:"+numericalSolverSumTime+ |
326 | "|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+ | 324 | "|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+ |
327 | "|NumericalSolverSolvingTime:"+numericalSolverSolving+ | 325 | "|NumericalSolverSolvingTime:"+numericalSolverSolving+ |
@@ -355,16 +353,19 @@ public class BestFirstStrategyForModelGeneration implements IStrategy { | |||
355 | } else { | 353 | } else { |
356 | return trajectoiresToExplore.element(); | 354 | return trajectoiresToExplore.element(); |
357 | } | 355 | } |
358 | } | 356 | } |
359 | 357 | ||
360 | public void visualiseCurrentState() { | 358 | public void visualiseCurrentState() { |
361 | PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugCongiguration.partialInterpretatioVisualiser; | 359 | PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugConfiguration.partialInterpretatioVisualiser; |
362 | if(partialInterpretatioVisualiser != null && this.configuration.documentationLevel == DocumentationLevel.FULL && workspace != null) { | 360 | if(partialInterpretatioVisualiser != null && this.configuration.documentationLevel == DocumentationLevel.FULL && workspace != null) { |
363 | PartialInterpretation p = (PartialInterpretation) (context.getModel()); | 361 | PartialInterpretation p = (PartialInterpretation) (context.getModel()); |
364 | int id = ++numberOfPrintedModel; | 362 | int id = ++numberOfPrintedModel; |
365 | if (id % configuration.debugCongiguration.partalInterpretationVisualisationFrequency == 0) { | 363 | if (id % configuration.debugConfiguration.partalInterpretationVisualisationFrequency == 0) { |
366 | PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p); | 364 | PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p); |
367 | visualisation.writeToFile(workspace, String.format("state%09d.png", id)); | 365 | logger.debug("Visualizing state: " + id + " (" + context.getDesignSpaceManager().getCurrentState() + ")"); |
366 | String name = String.format("state%09d", id); | ||
367 | visualisation.writeToFile(workspace, name + ".png"); | ||
368 | workspace.writeModel((EObject) context.getModel(), name + ".xmi"); | ||
368 | } | 369 | } |
369 | } | 370 | } |
370 | } | 371 | } |
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 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import com.google.common.collect.HashMultiset | ||
4 | import com.google.common.collect.ImmutableSet | ||
5 | import com.google.common.collect.Multiset | ||
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.AbstractNodeDescriptor | ||
7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.NeighbourhoodWithTraces | ||
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.PartialInterpretation2ImmutableTypeLattice | ||
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor | ||
11 | import java.util.Collection | ||
12 | import java.util.HashSet | ||
13 | import java.util.Map | ||
14 | import java.util.Set | ||
15 | import org.eclipse.viatra.dse.base.ThreadContext | ||
16 | import org.eclipse.xtend.lib.annotations.Accessors | ||
17 | |||
18 | interface DiversityChecker { | ||
19 | public static val NO_DIVERSITY_CHECKER = new DiversityChecker { | ||
20 | override isActive() { | ||
21 | false | ||
22 | } | ||
23 | |||
24 | override getTotalRuntime() { | ||
25 | 0 | ||
26 | } | ||
27 | |||
28 | override getSuccessRate() { | ||
29 | 1.0 | ||
30 | } | ||
31 | |||
32 | override newSolution(ThreadContext threadContext, Object solutionId, Collection<Object> dominatedSolutionIds) { | ||
33 | true | ||
34 | } | ||
35 | } | ||
36 | |||
37 | def boolean isActive() | ||
38 | |||
39 | def long getTotalRuntime() | ||
40 | |||
41 | def double getSuccessRate() | ||
42 | |||
43 | def boolean newSolution(ThreadContext threadContext, Object solutionId, Collection<Object> dominatedSolutionIds) | ||
44 | |||
45 | static def of(DiversityDescriptor descriptor) { | ||
46 | if (descriptor.ensureDiversity) { | ||
47 | new NodewiseDiversityChecker(descriptor) | ||
48 | } else { | ||
49 | NO_DIVERSITY_CHECKER | ||
50 | } | ||
51 | } | ||
52 | } | ||
53 | |||
54 | abstract class AbstractDiversityChecker implements DiversityChecker { | ||
55 | val DiversityDescriptor descriptor | ||
56 | val PartialInterpretation2ImmutableTypeLattice solutionCoder = new PartialInterpretation2ImmutableTypeLattice | ||
57 | |||
58 | @Accessors(PUBLIC_GETTER) var long totalRuntime = 0 | ||
59 | var int allCheckCount = 0 | ||
60 | var int successfulCheckCount = 0 | ||
61 | |||
62 | protected new(DiversityDescriptor descriptor) { | ||
63 | if (!descriptor.ensureDiversity) { | ||
64 | throw new IllegalArgumentException( | ||
65 | "Diversity description should enforce diversity or NO_DIVERSITY_CHECKER should be used instead.") | ||
66 | } | ||
67 | this.descriptor = descriptor | ||
68 | } | ||
69 | |||
70 | override isActive() { | ||
71 | true | ||
72 | } | ||
73 | |||
74 | override getTotalRuntime() { | ||
75 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | ||
76 | } | ||
77 | |||
78 | override getSuccessRate() { | ||
79 | (allCheckCount as double) / (successfulCheckCount as double) | ||
80 | } | ||
81 | |||
82 | override newSolution(ThreadContext threadContext, Object solutionId, Collection<Object> dominatedSolutionIds) { | ||
83 | val start = System.nanoTime | ||
84 | val model = threadContext.model as PartialInterpretation | ||
85 | val representation = solutionCoder.createRepresentation(model, descriptor.range, descriptor.parallels, | ||
86 | descriptor.maxNumber, descriptor.relevantTypes, descriptor.relevantRelations) | ||
87 | val isDifferent = internalNewSolution(representation, solutionId, dominatedSolutionIds) | ||
88 | totalRuntime += System.nanoTime - start | ||
89 | allCheckCount++ | ||
90 | if (isDifferent) { | ||
91 | successfulCheckCount++ | ||
92 | } | ||
93 | isDifferent | ||
94 | } | ||
95 | |||
96 | protected abstract def boolean internalNewSolution( | ||
97 | NeighbourhoodWithTraces<Map<? extends AbstractNodeDescriptor, Integer>, AbstractNodeDescriptor> representation, | ||
98 | Object solutionId, Collection<Object> dominatedSolutionIds) | ||
99 | } | ||
100 | |||
101 | class NodewiseDiversityChecker extends AbstractDiversityChecker { | ||
102 | var Multiset<Integer> nodeCodes = HashMultiset.create | ||
103 | val Map<Object, Set<Integer>> tracedNodeCodes = newHashMap | ||
104 | |||
105 | new(DiversityDescriptor descriptor) { | ||
106 | super(descriptor) | ||
107 | } | ||
108 | |||
109 | override protected internalNewSolution( | ||
110 | NeighbourhoodWithTraces<Map<? extends AbstractNodeDescriptor, Integer>, AbstractNodeDescriptor> representation, | ||
111 | Object solutionId, Collection<Object> dominatedSolutionIds) { | ||
112 | val nodeCodesInSolution = ImmutableSet.copyOf(representation.modelRepresentation.keySet.map[hashCode]) | ||
113 | val remainingNodeCodes = if (dominatedSolutionIds.empty) { | ||
114 | nodeCodes | ||
115 | } else { | ||
116 | getRemainingNodeCodes(dominatedSolutionIds) | ||
117 | } | ||
118 | val hasNewCode = nodeCodesInSolution.exists[!remainingNodeCodes.contains(it)] | ||
119 | if (hasNewCode) { | ||
120 | nodeCodes = remainingNodeCodes | ||
121 | nodeCodes.addAll(nodeCodesInSolution) | ||
122 | for (dominatedSolutionId : dominatedSolutionIds) { | ||
123 | tracedNodeCodes.remove(dominatedSolutionId) | ||
124 | } | ||
125 | tracedNodeCodes.put(solutionId, nodeCodesInSolution) | ||
126 | } | ||
127 | hasNewCode | ||
128 | } | ||
129 | |||
130 | private def getRemainingNodeCodes(Collection<Object> dominatedSolutionIds) { | ||
131 | // TODO Optimize multiset operations. | ||
132 | val copyOfNodeCodes = HashMultiset.create(nodeCodes) | ||
133 | for (dominatedSolutionId : dominatedSolutionIds) { | ||
134 | val dominatedModelCode = tracedNodeCodes.get(dominatedSolutionId) | ||
135 | if (dominatedModelCode === null) { | ||
136 | throw new IllegalArgumentException("Unknown dominated solution: " + dominatedSolutionId) | ||
137 | } | ||
138 | copyOfNodeCodes.removeAll(dominatedModelCode) | ||
139 | } | ||
140 | copyOfNodeCodes | ||
141 | } | ||
142 | } | ||
143 | |||
144 | class GraphwiseDiversityChecker extends AbstractDiversityChecker { | ||
145 | var Set<Integer> modelCodes = newHashSet | ||
146 | val Map<Object, Integer> tracedModelCodes = newHashMap | ||
147 | |||
148 | new(DiversityDescriptor descriptor) { | ||
149 | super(descriptor) | ||
150 | } | ||
151 | |||
152 | override protected internalNewSolution( | ||
153 | NeighbourhoodWithTraces<Map<? extends AbstractNodeDescriptor, Integer>, AbstractNodeDescriptor> representation, | ||
154 | Object solutionId, Collection<Object> dominatedSolutionIds) { | ||
155 | val modelCodeOfSolution = representation.modelRepresentation.hashCode | ||
156 | val remainingModelCodes = if (dominatedSolutionIds.empty) { | ||
157 | modelCodes | ||
158 | } else { | ||
159 | getRemainingModelCodes(dominatedSolutionIds) | ||
160 | } | ||
161 | val isNewCode = !remainingModelCodes.contains(modelCodeOfSolution) | ||
162 | if (isNewCode) { | ||
163 | modelCodes = remainingModelCodes | ||
164 | modelCodes += modelCodeOfSolution | ||
165 | for (dominatedSolutionId : dominatedSolutionIds) { | ||
166 | tracedModelCodes.remove(dominatedSolutionId) | ||
167 | } | ||
168 | tracedModelCodes.put(solutionId, modelCodeOfSolution) | ||
169 | } | ||
170 | isNewCode | ||
171 | } | ||
172 | |||
173 | private def getRemainingModelCodes(Collection<Object> dominatedSolutionIds) { | ||
174 | val copyOfModelCodes = new HashSet(modelCodes) | ||
175 | for (dominatedSolutionId : dominatedSolutionIds) { | ||
176 | val dominatedModelCode = tracedModelCodes.get(dominatedSolutionId) | ||
177 | if (dominatedModelCode === null) { | ||
178 | throw new IllegalArgumentException("Unknown dominated solution: " + dominatedSolutionId) | ||
179 | } | ||
180 | copyOfModelCodes -= dominatedModelCode | ||
181 | } | ||
182 | copyOfModelCodes | ||
183 | } | ||
184 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend new file mode 100644 index 00000000..3c2e3319 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/DseUtils.xtend | |||
@@ -0,0 +1,66 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IThreeValuedObjective | ||
4 | import org.eclipse.viatra.dse.base.ThreadContext | ||
5 | import org.eclipse.viatra.dse.objectives.Comparators | ||
6 | import org.eclipse.viatra.dse.objectives.Fitness | ||
7 | import org.eclipse.viatra.dse.objectives.IObjective | ||
8 | |||
9 | final class DseUtils { | ||
10 | private new() { | ||
11 | throw new IllegalStateException("This is a static utility class and should not be instantiated directly.") | ||
12 | } | ||
13 | |||
14 | static def calculateFitness(ThreadContext it, (IObjective)=>Double getFitness) { | ||
15 | val result = new Fitness | ||
16 | var boolean satisifiesHardObjectives = true | ||
17 | for (objective : objectives) { | ||
18 | val fitness = getFitness.apply(objective) | ||
19 | result.put(objective.name, fitness) | ||
20 | if (objective.isHardObjective() && !objective.satisifiesHardObjective(fitness)) { | ||
21 | satisifiesHardObjectives = false | ||
22 | } | ||
23 | } | ||
24 | result.satisifiesHardObjectives = satisifiesHardObjectives | ||
25 | result | ||
26 | } | ||
27 | |||
28 | static def caclulateBestPossibleFitness(ThreadContext threadContext) { | ||
29 | threadContext.calculateFitness [ objective | | ||
30 | if (objective instanceof IThreeValuedObjective) { | ||
31 | objective.getBestPossibleFitness(threadContext) | ||
32 | } else { | ||
33 | switch (objective.comparator) { | ||
34 | case Comparators.LOWER_IS_BETTER: | ||
35 | Double.NEGATIVE_INFINITY | ||
36 | case Comparators.HIGHER_IS_BETTER: | ||
37 | Double.POSITIVE_INFINITY | ||
38 | case Comparators.DIFFERENCE_TO_ZERO_IS_BETTER: | ||
39 | 0.0 | ||
40 | default: | ||
41 | throw new IllegalArgumentException("Unknown comparator for non-three-valued objective: " + | ||
42 | objective.name) | ||
43 | } | ||
44 | } | ||
45 | ] | ||
46 | } | ||
47 | |||
48 | static def caclulateWorstPossibleFitness(ThreadContext threadContext) { | ||
49 | threadContext.calculateFitness [ objective | | ||
50 | if (objective instanceof IThreeValuedObjective) { | ||
51 | objective.getWorstPossibleFitness(threadContext) | ||
52 | } else { | ||
53 | switch (objective.comparator) { | ||
54 | case Comparators.LOWER_IS_BETTER, | ||
55 | case Comparators.DIFFERENCE_TO_ZERO_IS_BETTER: | ||
56 | Double.POSITIVE_INFINITY | ||
57 | case Comparators.HIGHER_IS_BETTER: | ||
58 | Double.NEGATIVE_INFINITY | ||
59 | default: | ||
60 | throw new IllegalArgumentException("Unknown comparator for non-three-valued objective: " + | ||
61 | objective.name) | ||
62 | } | ||
63 | } | ||
64 | ] | ||
65 | } | ||
66 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/HillClimbingOnRealisticMetricStrategyForModelGeneration.java b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/HillClimbingOnRealisticMetricStrategyForModelGeneration.java index f1bf96b6..d9f84b36 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/HillClimbingOnRealisticMetricStrategyForModelGeneration.java +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/HillClimbingOnRealisticMetricStrategyForModelGeneration.java | |||
@@ -16,6 +16,7 @@ import java.util.Random; | |||
16 | import java.util.Set; | 16 | import java.util.Set; |
17 | 17 | ||
18 | import org.apache.log4j.Logger; | 18 | import org.apache.log4j.Logger; |
19 | import org.eclipse.emf.ecore.EObject; | ||
19 | import org.eclipse.emf.ecore.util.EcoreUtil; | 20 | import org.eclipse.emf.ecore.util.EcoreUtil; |
20 | import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; | 21 | import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; |
21 | import org.eclipse.viatra.dse.base.ThreadContext; | 22 | import org.eclipse.viatra.dse.base.ThreadContext; |
@@ -35,12 +36,12 @@ import hu.bme.mit.inf.dslreasoner.logic.model.logicproblem.LogicProblem; | |||
35 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; | 36 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.InconsistencyResult; |
36 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; | 37 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.LogicResult; |
37 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; | 38 | import hu.bme.mit.inf.dslreasoner.logic.model.logicresult.ModelResult; |
38 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod; | ||
39 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; | 39 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretation2logic.PartialInterpretation2Logic; |
40 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; | 40 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation; |
41 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder; | 41 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.statecoder.NeighbourhoodBasedPartialInterpretationStateCoder; |
42 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; | 42 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualisation; |
43 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; | 43 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.visualisation.PartialInterpretationVisualiser; |
44 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod; | ||
44 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.RealisticGuidance; | 45 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.RealisticGuidance; |
45 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; | 46 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration; |
46 | import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; | 47 | import hu.bme.mit.inf.dslreasoner.workspace.ReasonerWorkspace; |
@@ -84,6 +85,8 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
84 | private double currentNodeTypeDistance = 1; | 85 | private double currentNodeTypeDistance = 1; |
85 | private int numNodesToGenerate = 0; | 86 | private int numNodesToGenerate = 0; |
86 | public long explorationStarted = 0; | 87 | public long explorationStarted = 0; |
88 | public long globalConstraintEvaluationTime = 0; | ||
89 | public long fitnessCalculationTime = 0; | ||
87 | 90 | ||
88 | public HillClimbingOnRealisticMetricStrategyForModelGeneration( | 91 | public HillClimbingOnRealisticMetricStrategyForModelGeneration( |
89 | ReasonerWorkspace workspace, | 92 | ReasonerWorkspace workspace, |
@@ -104,6 +107,13 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
104 | public int getNumberOfStatecoderFail() { | 107 | public int getNumberOfStatecoderFail() { |
105 | return numberOfStatecoderFail; | 108 | return numberOfStatecoderFail; |
106 | } | 109 | } |
110 | |||
111 | public long getForwardTime() { | ||
112 | return context.getDesignSpaceManager().getForwardTime(); | ||
113 | } | ||
114 | public long getBacktrackingTime() { | ||
115 | return context.getDesignSpaceManager().getBacktrackingTime(); | ||
116 | } | ||
107 | 117 | ||
108 | @Override | 118 | @Override |
109 | public void initStrategy(ThreadContext context) { | 119 | public void initStrategy(ThreadContext context) { |
@@ -147,13 +157,13 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
147 | //set whether allows must violations during the realistic generation | 157 | //set whether allows must violations during the realistic generation |
148 | allowMustViolation = configuration.allowMustViolations; | 158 | allowMustViolation = configuration.allowMustViolations; |
149 | targetSize = configuration.typeScopes.maxNewElements + 2; | 159 | targetSize = configuration.typeScopes.maxNewElements + 2; |
150 | this.numericSolver = new NumericSolver(context, method, this.configuration.runIntermediateNumericalConsistencyChecks, false); | 160 | //this.numericSolver = new NumericSolver(method, this.configuration.runIntermediateNumericalConsistencyChecks, false); |
151 | } | 161 | } |
152 | 162 | ||
153 | @Override | 163 | @Override |
154 | public void explore() { | 164 | public void explore() { |
155 | this.explorationStarted=System.nanoTime(); | 165 | this.explorationStarted=System.nanoTime(); |
156 | if (!context.checkGlobalConstraints()) { | 166 | if (!checkGlobalConstraints()) { |
157 | logger.info("Global contraint is not satisifed in the first state. Terminate."); | 167 | logger.info("Global contraint is not satisifed in the first state. Terminate."); |
158 | return; | 168 | return; |
159 | } | 169 | } |
@@ -236,6 +246,14 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
236 | boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness); | 246 | boolean consistencyCheckResult = checkConsistency(currentTrajectoryWithFittness); |
237 | if(consistencyCheckResult == true) { continue mainLoop; } | 247 | if(consistencyCheckResult == true) { continue mainLoop; } |
238 | 248 | ||
249 | // if (context.isCurrentStateAlreadyTraversed()) { | ||
250 | // logger.info("The new state is already visited."); | ||
251 | // context.backtrack(); | ||
252 | // } else if (!checkGlobalConstraints()) { | ||
253 | // logger.debug("Global contraint is not satisifed."); | ||
254 | // context.backtrack(); | ||
255 | // } | ||
256 | |||
239 | int currentSize = model.getNewElements().size(); | 257 | int currentSize = model.getNewElements().size(); |
240 | int targetDiff = targetSize - currentSize; | 258 | int targetDiff = targetSize - currentSize; |
241 | boolean shouldFinish = currentSize >= targetSize; | 259 | boolean shouldFinish = currentSize >= targetSize; |
@@ -278,6 +296,20 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
278 | logger.info("Interrupted."); | 296 | logger.info("Interrupted."); |
279 | } | 297 | } |
280 | 298 | ||
299 | private boolean checkGlobalConstraints() { | ||
300 | long start = System.nanoTime(); | ||
301 | boolean result = context.checkGlobalConstraints(); | ||
302 | globalConstraintEvaluationTime += System.nanoTime() - start; | ||
303 | return result; | ||
304 | } | ||
305 | |||
306 | private Fitness calculateFitness() { | ||
307 | long start = System.nanoTime(); | ||
308 | Fitness fitness = context.calculateFitness(); | ||
309 | fitnessCalculationTime += System.nanoTime() - start; | ||
310 | return fitness; | ||
311 | } | ||
312 | |||
281 | /** | 313 | /** |
282 | * | 314 | * |
283 | * @param activationIds | 315 | * @param activationIds |
@@ -475,7 +507,7 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
475 | solutionStoreWithCopy.newSolution(context); | 507 | solutionStoreWithCopy.newSolution(context); |
476 | solutionStoreWithDiversityDescriptor.newSolution(context); | 508 | solutionStoreWithDiversityDescriptor.newSolution(context); |
477 | solutionStore.newSolution(context); | 509 | solutionStore.newSolution(context); |
478 | configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolution); | 510 | configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolutions); |
479 | 511 | ||
480 | logger.debug("Found a solution."); | 512 | logger.debug("Found a solution."); |
481 | } | 513 | } |
@@ -484,23 +516,27 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
484 | 516 | ||
485 | public List<String> times = new LinkedList<String>(); | 517 | public List<String> times = new LinkedList<String>(); |
486 | private void saveTimes() { | 518 | private void saveTimes() { |
519 | long forwardTime = context.getDesignSpaceManager().getForwardTime()/1000000; | ||
520 | long backtrackingTime = context.getDesignSpaceManager().getBacktrackingTime()/1000000; | ||
487 | long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder)this.context.getStateCoder()).getStatecoderRuntime()/1000000; | 521 | long statecoderTime = ((NeighbourhoodBasedPartialInterpretationStateCoder)this.context.getStateCoder()).getStatecoderRuntime()/1000000; |
488 | long solutionCopy = solutionStoreWithCopy.getSumRuntime()/1000000; | 522 | long solutionCopy = solutionStoreWithCopy.getSumRuntime()/1000000; |
489 | long activationSelection = this.activationSelector.getRuntime()/1000000; | 523 | long activationSelection = this.activationSelector.getRuntime()/1000000; |
490 | long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000; | 524 | // long numericalSolverSumTime = this.numericSolver.getRuntime()/1000000; |
491 | long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000; | 525 | // long numericalSolverProblemForming = this.numericSolver.getSolverSolvingProblem()/1000000; |
492 | long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; | 526 | // long numericalSolverSolving = this.numericSolver.getSolverSolvingProblem()/1000000; |
493 | long numericalSolverInterpreting = this.numericSolver.getSolverSolution()/1000000; | 527 | // long numericalSolverInterpreting = this.numericSolver.getSolverSolution()/1000000; |
494 | long metricCalculationTime = this.method.getStatistics().metricCalculationTime / 1000000; | 528 | long metricCalculationTime = this.method.getStatistics().metricCalculationTime / 1000000; |
495 | this.times.add( | 529 | this.times.add( |
496 | "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ | 530 | "(TransformationExecutionTime"+method.getStatistics().transformationExecutionTime/1000000+ |
531 | "|ForwardTime:"+forwardTime+ | ||
532 | "|Backtrackingtime:"+backtrackingTime+ | ||
497 | "|StateCoderTime:"+statecoderTime+ | 533 | "|StateCoderTime:"+statecoderTime+ |
498 | "|SolutionCopyTime:"+solutionCopy+ | 534 | "|SolutionCopyTime:"+solutionCopy+ |
499 | "|ActivationSelectionTime:"+activationSelection+ | 535 | "|ActivationSelectionTime:"+activationSelection+ |
500 | "|NumericalSolverSumTime:"+numericalSolverSumTime+ | 536 | //"|NumericalSolverSumTime:"+numericalSolverSumTime+ |
501 | "|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+ | 537 | //"|NumericalSolverProblemFormingTime:"+numericalSolverProblemForming+ |
502 | "|NumericalSolverSolvingTime:"+numericalSolverSolving+ | 538 | //"|NumericalSolverSolvingTime:"+numericalSolverSolving+ |
503 | "|NumericalSolverInterpretingSolution:"+numericalSolverInterpreting+ | 539 | //"|NumericalSolverInterpretingSolution:"+numericalSolverInterpreting+ |
504 | "|MetricCalculationTime:"+metricCalculationTime + ")" | 540 | "|MetricCalculationTime:"+metricCalculationTime + ")" |
505 | ); | 541 | ); |
506 | 542 | ||
@@ -544,13 +580,16 @@ public class HillClimbingOnRealisticMetricStrategyForModelGeneration implements | |||
544 | // } | 580 | // } |
545 | 581 | ||
546 | public void visualiseCurrentState() { | 582 | public void visualiseCurrentState() { |
547 | PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugCongiguration.partialInterpretatioVisualiser; | 583 | PartialInterpretationVisualiser partialInterpretatioVisualiser = configuration.debugConfiguration.partialInterpretatioVisualiser; |
548 | if(partialInterpretatioVisualiser != null && this.configuration.documentationLevel == DocumentationLevel.FULL && workspace != null) { | 584 | if(partialInterpretatioVisualiser != null && this.configuration.documentationLevel == DocumentationLevel.FULL && workspace != null) { |
549 | PartialInterpretation p = (PartialInterpretation) (context.getModel()); | 585 | PartialInterpretation p = (PartialInterpretation) (context.getModel()); |
550 | int id = ++numberOfPrintedModel; | 586 | int id = ++numberOfPrintedModel; |
551 | if (id % configuration.debugCongiguration.partalInterpretationVisualisationFrequency == 0) { | 587 | if (id % configuration.debugConfiguration.partalInterpretationVisualisationFrequency == 0) { |
552 | PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p); | 588 | PartialInterpretationVisualisation visualisation = partialInterpretatioVisualiser.visualiseConcretization(p); |
553 | visualisation.writeToFile(workspace, String.format("state%09d.png", id)); | 589 | logger.debug("Visualizing state: " + id + " (" + context.getDesignSpaceManager().getCurrentState() + ")"); |
590 | String name = String.format("state%09d", id); | ||
591 | visualisation.writeToFile(workspace, name + ".png"); | ||
592 | workspace.writeModel((EObject) context.getModel(), name + ".xmi"); | ||
554 | } | 593 | } |
555 | } | 594 | } |
556 | } | 595 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend new file mode 100644 index 00000000..2e039ca2 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/InconsistentScopeGlobalConstraint.xtend | |||
@@ -0,0 +1,25 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import org.eclipse.viatra.dse.objectives.IGlobalConstraint | ||
4 | import org.eclipse.viatra.dse.base.ThreadContext | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
6 | |||
7 | class InconsistentScopeGlobalConstraint implements IGlobalConstraint { | ||
8 | |||
9 | override init(ThreadContext context) { | ||
10 | // Nothing to initialize. | ||
11 | } | ||
12 | |||
13 | override createNew() { | ||
14 | this | ||
15 | } | ||
16 | |||
17 | override getName() { | ||
18 | class.name | ||
19 | } | ||
20 | |||
21 | override checkGlobalConstraint(ThreadContext context) { | ||
22 | val partialModel = context.model as PartialInterpretation | ||
23 | partialModel.minNewElements <= partialModel.maxNewElements || partialModel.maxNewElements < 0 | ||
24 | } | ||
25 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend new file mode 100644 index 00000000..39ef5f9a --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/LoggerSolutionFoundHandler.xtend | |||
@@ -0,0 +1,24 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration | ||
4 | import org.apache.log4j.Logger | ||
5 | import org.eclipse.viatra.dse.api.SolutionTrajectory | ||
6 | import org.eclipse.viatra.dse.base.ThreadContext | ||
7 | import org.eclipse.viatra.dse.solutionstore.ISolutionFoundHandler | ||
8 | import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor | ||
9 | |||
10 | @FinalFieldsConstructor | ||
11 | class LoggerSolutionFoundHandler implements ISolutionFoundHandler { | ||
12 | val ViatraReasonerConfiguration configuration | ||
13 | |||
14 | val logger = Logger.getLogger(SolutionCopier) | ||
15 | |||
16 | override solutionFound(ThreadContext context, SolutionTrajectory trajectory) { | ||
17 | configuration.progressMonitor.workedModelFound(configuration.solutionScope.numberOfRequiredSolutions) | ||
18 | logger.debug("Found a solution.") | ||
19 | } | ||
20 | |||
21 | override solutionTriedToSave(ThreadContext context, SolutionTrajectory trajectory) { | ||
22 | // We are not interested in invalid solutions, ignore. | ||
23 | } | ||
24 | } | ||
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 a10530c7..27208cf4 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 | |||
@@ -1,67 +1,49 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import com.google.common.collect.ImmutableList | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration | ||
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IThreeValuedObjective | ||
3 | import java.util.Comparator | 7 | import java.util.Comparator |
4 | import java.util.List | 8 | import java.util.List |
5 | import org.eclipse.viatra.dse.base.ThreadContext | 9 | import org.eclipse.viatra.dse.base.ThreadContext |
6 | import org.eclipse.viatra.dse.objectives.Comparators | 10 | import org.eclipse.viatra.dse.objectives.Comparators |
7 | import org.eclipse.viatra.dse.objectives.IObjective | 11 | import org.eclipse.viatra.dse.objectives.IObjective |
8 | import org.eclipse.viatra.dse.objectives.impl.BaseObjective | 12 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement |
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ViatraReasonerConfiguration | ||
11 | 13 | ||
12 | //class ViatraReasonerNumbers { | 14 | class ModelGenerationCompositeObjective implements IThreeValuedObjective { |
13 | // public static val scopePriority = 2 | 15 | val IObjective scopeObjective |
14 | // public static val unfinishedMultiplicityPriority = 2 | ||
15 | // public static val unifinshedWFPriority = 2 | ||
16 | // //public static val complexityPriority = 4 | ||
17 | // | ||
18 | // public static val scopeWeigth = 1.0 | ||
19 | // public static val unfinishedMultiplicityWeigth = 1.5 | ||
20 | // public static val unfinishedWFWeigth = 1.5 | ||
21 | // //public static val complexityWeigth = 0.1 | ||
22 | // | ||
23 | // public static val useCompositeObjective = true | ||
24 | // public static val compositePriority = 2 | ||
25 | //} | ||
26 | |||
27 | class ModelGenerationCompositeObjective implements IObjective{ | ||
28 | val ScopeObjective scopeObjective | ||
29 | val List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives | 16 | val List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives |
30 | val UnfinishedWFObjective unfinishedWFObjective | 17 | val UnfinishedWFObjective unfinishedWFObjective |
31 | var PartialInterpretation model=null; | 18 | var PartialInterpretation model = null |
32 | val boolean punishSize | ||
33 | val int scopeWeight | 19 | val int scopeWeight |
34 | val int conaintmentWeight | 20 | val int conaintmentWeight |
35 | val int nonContainmentWeight | 21 | val int nonContainmentWeight |
36 | val int unfinishedWFWeight | 22 | val int unfinishedWFWeight |
37 | 23 | ||
38 | new( | 24 | new( |
39 | ScopeObjective scopeObjective, | 25 | IObjective scopeObjective, |
40 | List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, | 26 | List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, |
41 | UnfinishedWFObjective unfinishedWFObjective, | 27 | UnfinishedWFObjective unfinishedWFObjective, |
42 | ViatraReasonerConfiguration configuration) | 28 | ViatraReasonerConfiguration configuration) |
43 | { | 29 | { |
44 | this.scopeObjective = scopeObjective | 30 | this( |
45 | this.unfinishedMultiplicityObjectives = unfinishedMultiplicityObjectives | 31 | scopeObjective, unfinishedMultiplicityObjectives, unfinishedWFObjective, |
46 | this.unfinishedWFObjective = unfinishedWFObjective | 32 | configuration.scopeWeight, configuration.conaintmentWeight, configuration.nonContainmentWeight, |
47 | 33 | configuration.unfinishedWFWeight | |
48 | this.punishSize = configuration.punishSize | 34 | ) |
49 | this.scopeWeight = configuration.scopeWeight | ||
50 | this.conaintmentWeight = configuration.conaintmentWeight | ||
51 | this.nonContainmentWeight = configuration.nonContainmentWeight | ||
52 | this.unfinishedWFWeight = configuration.unfinishedWFWeight | ||
53 | } | 35 | } |
36 | |||
54 | new( | 37 | new( |
55 | ScopeObjective scopeObjective, | 38 | IObjective scopeObjective, |
56 | List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, | 39 | List<UnfinishedMultiplicityObjective> unfinishedMultiplicityObjectives, |
57 | UnfinishedWFObjective unfinishedWFObjective, | 40 | UnfinishedWFObjective unfinishedWFObjective, |
58 | boolean punishSize, int scopeWeight, int conaintmentWeight, int nonContainmentWeight, int unfinishedWFWeight) | 41 | int scopeWeight, int conaintmentWeight, int nonContainmentWeight, int unfinishedWFWeight) |
59 | { | 42 | { |
60 | this.scopeObjective = scopeObjective | 43 | this.scopeObjective = scopeObjective |
61 | this.unfinishedMultiplicityObjectives = unfinishedMultiplicityObjectives | 44 | this.unfinishedMultiplicityObjectives = unfinishedMultiplicityObjectives |
62 | this.unfinishedWFObjective = unfinishedWFObjective | 45 | this.unfinishedWFObjective = unfinishedWFObjective |
63 | 46 | ||
64 | this.punishSize = punishSize | ||
65 | this.scopeWeight = scopeWeight | 47 | this.scopeWeight = scopeWeight |
66 | this.conaintmentWeight = conaintmentWeight | 48 | this.conaintmentWeight = conaintmentWeight |
67 | this.nonContainmentWeight = nonContainmentWeight | 49 | this.nonContainmentWeight = nonContainmentWeight |
@@ -74,33 +56,34 @@ class ModelGenerationCompositeObjective implements IObjective{ | |||
74 | this.unfinishedMultiplicityObjectives.forEach[it.init(context)] | 56 | this.unfinishedMultiplicityObjectives.forEach[it.init(context)] |
75 | this.unfinishedWFObjective.init(context) | 57 | this.unfinishedWFObjective.init(context) |
76 | } | 58 | } |
77 | 59 | ||
78 | override createNew() { | 60 | override createNew() { |
79 | return new ModelGenerationCompositeObjective( | 61 | return new ModelGenerationCompositeObjective( |
80 | this.scopeObjective, this.unfinishedMultiplicityObjectives, this.unfinishedWFObjective, | 62 | scopeObjective.createNew, |
81 | this.punishSize, this.scopeWeight, this.conaintmentWeight, this.nonContainmentWeight, this.unfinishedWFWeight) | 63 | ImmutableList.copyOf(unfinishedMultiplicityObjectives.map[createNew as UnfinishedMultiplicityObjective]), |
64 | unfinishedWFObjective.createNew as UnfinishedWFObjective, | ||
65 | scopeWeight, conaintmentWeight, nonContainmentWeight, unfinishedWFWeight | ||
66 | ) | ||
82 | } | 67 | } |
83 | 68 | ||
84 | override getComparator() { Comparators.LOWER_IS_BETTER } | 69 | override getComparator() { Comparators.LOWER_IS_BETTER } |
70 | |||
85 | override getFitness(ThreadContext context) { | 71 | override getFitness(ThreadContext context) { |
86 | 72 | ||
87 | val scopeFitnes = scopeObjective.getFitness(context) | 73 | val scopeFitnes = scopeObjective.getFitness(context) |
88 | //val unfinishedMultiplicitiesFitneses = unfinishedMultiplicityObjectives.map[x|x.getFitness(context)] | ||
89 | val unfinishedWFsFitness = unfinishedWFObjective.getFitness(context) | 74 | val unfinishedWFsFitness = unfinishedWFObjective.getFitness(context) |
90 | 75 | ||
91 | var containmentMultiplicity = 0.0 | 76 | var containmentMultiplicity = 0.0 |
92 | var nonContainmentMultiplicity = 0.0 | 77 | var nonContainmentMultiplicity = 0.0 |
93 | for(multiplicityObjective : unfinishedMultiplicityObjectives) { | 78 | for(multiplicityObjective : unfinishedMultiplicityObjectives) { |
79 | val multiplicity = multiplicityObjective.getFitness(context) | ||
80 | // println(multiplicityObjective.name + "=" + multiplicity) | ||
94 | if(multiplicityObjective.containment) { | 81 | if(multiplicityObjective.containment) { |
95 | containmentMultiplicity+=multiplicityObjective.getFitness(context) | 82 | containmentMultiplicity+=multiplicity |
96 | } else { | 83 | } else { |
97 | nonContainmentMultiplicity+=multiplicityObjective.getFitness(context) | 84 | nonContainmentMultiplicity+=multiplicity |
98 | } | 85 | } |
99 | } | 86 | |
100 | val size = if(punishSize) { | ||
101 | 0.9/model.newElements.size | ||
102 | } else { | ||
103 | 0 | ||
104 | } | 87 | } |
105 | 88 | ||
106 | var sum = 0.0 | 89 | var sum = 0.0 |
@@ -108,25 +91,33 @@ class ModelGenerationCompositeObjective implements IObjective{ | |||
108 | sum += containmentMultiplicity*conaintmentWeight | 91 | sum += containmentMultiplicity*conaintmentWeight |
109 | sum += nonContainmentMultiplicity*nonContainmentWeight | 92 | sum += nonContainmentMultiplicity*nonContainmentWeight |
110 | sum += unfinishedWFsFitness*unfinishedWFWeight | 93 | sum += unfinishedWFsFitness*unfinishedWFWeight |
111 | sum+=size | ||
112 | 94 | ||
113 | //println('''Sum=«sum»|Scope=«scopeFitnes»|ContainmentMultiplicity=«containmentMultiplicity»|NonContainmentMultiplicity=«nonContainmentMultiplicity»|WFs=«unfinishedWFsFitness»''') | 95 | // println('''scope=«scopeFitnes», containment=«containmentMultiplicity», nonContainment=«nonContainmentMultiplicity», wf=«unfinishedWFsFitness», sum=«sum»''') |
114 | 96 | ||
115 | return sum | 97 | return sum |
116 | } | 98 | } |
117 | 99 | ||
118 | override getLevel() { 2 } | 100 | override getWorstPossibleFitness(ThreadContext threadContext) { |
119 | override getName() { "CompositeUnfinishednessObjective"} | 101 | Double.POSITIVE_INFINITY |
102 | } | ||
120 | 103 | ||
104 | override getBestPossibleFitness(ThreadContext threadContext) { | ||
105 | 0.0 | ||
106 | } | ||
107 | |||
108 | override getLevel() { 2 } | ||
109 | |||
110 | override getName() { "CompositeUnfinishednessObjective" } | ||
111 | |||
121 | override isHardObjective() { true } | 112 | override isHardObjective() { true } |
122 | override satisifiesHardObjective(Double fitness) { fitness < 0.95 } | 113 | |
123 | 114 | override satisifiesHardObjective(Double fitness) { fitness < 0.01 } | |
124 | 115 | ||
125 | override setComparator(Comparator<Double> comparator) { | 116 | override setComparator(Comparator<Double> comparator) { |
126 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 117 | throw new UnsupportedOperationException("Model generation objective comparator cannot be set.") |
127 | } | 118 | } |
119 | |||
128 | override setLevel(int level) { | 120 | override setLevel(int level) { |
129 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 121 | throw new UnsupportedOperationException("Model generation objective level cannot be set.") |
130 | } | 122 | } |
131 | 123 | } | |
132 | } \ 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/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 0b0feb1a..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 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator | 3 | import hu.bme.mit.inf.dslreasoner.viatra2logic.NumericTranslator |
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.ModelGenerationMethod | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement | 4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.BooleanElement |
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement | 5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.IntegerElement |
7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | 6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation |
8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement | 7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement |
9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement | 8 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.RealElement |
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement | 9 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.StringElement |
10 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.ModelGenerationMethod | ||
11 | import java.math.BigDecimal | 11 | import java.math.BigDecimal |
12 | import java.util.HashMap | 12 | import java.util.HashMap |
13 | import java.util.LinkedHashMap | 13 | import java.util.LinkedHashMap |
@@ -21,7 +21,8 @@ import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | |||
21 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint | 21 | import org.eclipse.viatra.query.runtime.matchers.psystem.PConstraint |
22 | 22 | ||
23 | class NumericSolver { | 23 | class NumericSolver { |
24 | val ThreadContext threadContext; | 24 | val ModelGenerationMethod method |
25 | var ThreadContext threadContext | ||
25 | val constraint2MustUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> | 26 | val constraint2MustUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> |
26 | val constraint2CurrentUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> | 27 | val constraint2CurrentUnitPropagationPrecondition = new HashMap<PConstraint,ViatraQueryMatcher<? extends IPatternMatch>> |
27 | NumericTranslator t = new NumericTranslator | 28 | NumericTranslator t = new NumericTranslator |
@@ -35,8 +36,16 @@ class NumericSolver { | |||
35 | var int numberOfSolverCalls = 0 | 36 | var int numberOfSolverCalls = 0 |
36 | var int numberOfCachedSolverCalls = 0 | 37 | var int numberOfCachedSolverCalls = 0 |
37 | 38 | ||
38 | new(ThreadContext threadContext, ModelGenerationMethod method, boolean intermediateConsistencyCheck, boolean caching) { | 39 | new(ModelGenerationMethod method, boolean intermediateConsistencyCheck, boolean caching) { |
39 | this.threadContext = threadContext | 40 | this.method = method |
41 | this.intermediateConsistencyCheck = intermediateConsistencyCheck | ||
42 | this.caching = caching | ||
43 | } | ||
44 | |||
45 | def init(ThreadContext context) { | ||
46 | // This makes the NumericSolver single-threaded, | ||
47 | // but that's not a problem, because we only use the solver on a single thread anyways. | ||
48 | this.threadContext = context | ||
40 | val engine = threadContext.queryEngine | 49 | val engine = threadContext.queryEngine |
41 | for(entry : method.mustUnitPropagationPreconditions.entrySet) { | 50 | for(entry : method.mustUnitPropagationPreconditions.entrySet) { |
42 | val constraint = entry.key | 51 | val constraint = entry.key |
@@ -50,8 +59,6 @@ class NumericSolver { | |||
50 | val matcher = querySpec.getMatcher(engine); | 59 | val matcher = querySpec.getMatcher(engine); |
51 | constraint2CurrentUnitPropagationPrecondition.put(constraint,matcher) | 60 | constraint2CurrentUnitPropagationPrecondition.put(constraint,matcher) |
52 | } | 61 | } |
53 | this.intermediateConsistencyCheck = intermediateConsistencyCheck | ||
54 | this.caching = caching | ||
55 | } | 62 | } |
56 | 63 | ||
57 | def getRuntime(){runtime} | 64 | def getRuntime(){runtime} |
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 efc2ef36..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 | |||
22 | import java.util.Map | 22 | import java.util.Map |
23 | import java.util.TreeSet | 23 | import java.util.TreeSet |
24 | import org.eclipse.emf.ecore.EObject | 24 | import org.eclipse.emf.ecore.EObject |
25 | import org.eclipse.xtend.lib.annotations.Accessors | ||
25 | import org.eclipse.xtext.xbase.lib.Functions.Function1 | 26 | import org.eclipse.xtext.xbase.lib.Functions.Function1 |
26 | 27 | ||
27 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* | 28 | import static extension hu.bme.mit.inf.dslreasoner.util.CollectionsUtil.* |
28 | 29 | ||
29 | class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ | 30 | class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ |
30 | val PartialInterpretation partialInterpretation | 31 | @Accessors val PartialInterpretation partialInterpretation |
31 | val Map<EObject, EObject> trace; | 32 | val Map<EObject, EObject> trace; |
32 | val Map<TypeDeclaration,PartialComplexTypeInterpretation> type2Interpretation | 33 | val Map<TypeDeclaration,PartialComplexTypeInterpretation> type2Interpretation |
33 | val Map<RelationDeclaration,PartialRelationInterpretation> relation2Interpretation | 34 | val Map<RelationDeclaration,PartialRelationInterpretation> relation2Interpretation |
@@ -219,4 +220,4 @@ class PartialModelAsLogicInterpretation implements LogicModelInterpretation{ | |||
219 | } | 220 | } |
220 | builder | 221 | builder |
221 | } | 222 | } |
222 | } \ No newline at end of file | 223 | } |
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PunishSizeObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PunishSizeObjective.xtend new file mode 100644 index 00000000..bad8e4d1 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/PunishSizeObjective.xtend | |||
@@ -0,0 +1,52 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PrimitiveElement | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.AbstractThreeValuedObjective | ||
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveKind | ||
7 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold | ||
8 | import org.eclipse.viatra.dse.base.ThreadContext | ||
9 | |||
10 | class PunishSizeObjective extends AbstractThreeValuedObjective { | ||
11 | static val NAME = typeof(PunishSizeObjective).name | ||
12 | |||
13 | new(ObjectiveKind kind, int level) { | ||
14 | super(NAME, kind, ObjectiveThreshold.NO_THRESHOLD, level) | ||
15 | } | ||
16 | |||
17 | override createNew() { | ||
18 | new PunishSizeObjective(kind, level) | ||
19 | } | ||
20 | |||
21 | override init(ThreadContext context) { | ||
22 | // Nothing to initialize. | ||
23 | } | ||
24 | |||
25 | override getRawFitness(ThreadContext threadContext) { | ||
26 | val model = threadContext.model | ||
27 | if (model instanceof PartialInterpretation) { | ||
28 | val size = model.newObjectCount | ||
29 | // println('''size=«size»''') | ||
30 | size as double | ||
31 | } else { | ||
32 | throw new IllegalArgumentException("notifier must be a PartialInterpretation") | ||
33 | } | ||
34 | } | ||
35 | |||
36 | override getLowestPossibleFitness(ThreadContext threadContext) { | ||
37 | getRawFitness(threadContext) | ||
38 | } | ||
39 | |||
40 | override getHighestPossibleFitness(ThreadContext threadContext) { | ||
41 | val model = threadContext.model | ||
42 | if (model instanceof PartialInterpretation) { | ||
43 | (model.newObjectCount + model.maxNewElements) as double | ||
44 | } else { | ||
45 | throw new IllegalArgumentException("notifier must be a PartialInterpretation") | ||
46 | } | ||
47 | } | ||
48 | |||
49 | private def getNewObjectCount(PartialInterpretation interpretation) { | ||
50 | interpretation.newElements.reject[it instanceof PrimitiveElement].size | ||
51 | } | ||
52 | } \ 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/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..b61bd20b 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{ | |||
23 | 23 | ||
24 | override getFitness(ThreadContext context) { | 24 | override getFitness(ThreadContext context) { |
25 | val interpretation = context.model as PartialInterpretation | 25 | val interpretation = context.model as PartialInterpretation |
26 | var res = interpretation.minNewElements.doubleValue | 26 | var res = interpretation.minNewElementsHeuristic.doubleValue |
27 | for(scope : interpretation.scopes) { | 27 | for(scope : interpretation.scopes) { |
28 | res += scope.minNewElements*2 | 28 | res += scope.minNewElementsHeuristic * 2 |
29 | } | 29 | } |
30 | return res | 30 | return res |
31 | } | 31 | } |
@@ -41,4 +41,4 @@ class ScopeObjective implements IObjective{ | |||
41 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 41 | throw new UnsupportedOperationException("TODO: auto-generated method stub") |
42 | } | 42 | } |
43 | override getLevel() { 2 } | 43 | override getLevel() { 2 } |
44 | } \ No newline at end of file | 44 | } |
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 new file mode 100644 index 00000000..888eda18 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionCopier.xtend | |||
@@ -0,0 +1,82 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import com.google.common.collect.ImmutableList | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
5 | import java.util.LinkedHashMap | ||
6 | import java.util.List | ||
7 | import java.util.Map | ||
8 | import org.eclipse.emf.ecore.EObject | ||
9 | import org.eclipse.emf.ecore.util.EcoreUtil | ||
10 | import org.eclipse.viatra.dse.base.ThreadContext | ||
11 | import org.eclipse.xtend.lib.annotations.Accessors | ||
12 | import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor | ||
13 | |||
14 | @FinalFieldsConstructor | ||
15 | class CopiedSolution { | ||
16 | @Accessors val PartialInterpretation partialInterpretations | ||
17 | @Accessors val Map<EObject, EObject> trace | ||
18 | @Accessors val long copierRuntime | ||
19 | @Accessors var boolean current = true | ||
20 | } | ||
21 | |||
22 | /** | ||
23 | * Based on {@link SolutionStore.BestSolutionSaver}. | ||
24 | * | ||
25 | * Will also automatically fill any missing numerical values in the saved solutions | ||
26 | * using the supplied {@link NumericSolver}. | ||
27 | */ | ||
28 | class SolutionCopier { | ||
29 | val copiedSolutions = new LinkedHashMap<Object, CopiedSolution> | ||
30 | |||
31 | @Accessors NumericSolver numericSolver | ||
32 | long startTime = System.nanoTime | ||
33 | @Accessors(PUBLIC_GETTER) long totalCopierRuntime = 0 | ||
34 | |||
35 | def void copySolution(ThreadContext context, Object solutionId) { | ||
36 | val existingCopy = copiedSolutions.get(solutionId) | ||
37 | if (existingCopy === null) { | ||
38 | val copyStart = System.nanoTime | ||
39 | val solution = context.model as PartialInterpretation | ||
40 | val copier = new EcoreUtil.Copier | ||
41 | val copiedPartialInterpretation = copier.copy(solution) as PartialInterpretation | ||
42 | copier.copyReferences | ||
43 | totalCopierRuntime += System.nanoTime - copyStart | ||
44 | val copierRuntime = System.nanoTime - startTime | ||
45 | val copiedSolution = new CopiedSolution(copiedPartialInterpretation, copier, copierRuntime) | ||
46 | //numericSolver?.fillSolutionCopy(copiedSolution.trace) | ||
47 | copiedSolutions.put(solutionId, copiedSolution) | ||
48 | } else { | ||
49 | existingCopy.current = true | ||
50 | } | ||
51 | } | ||
52 | |||
53 | def void markAsObsolete(Object solutionId) { | ||
54 | val copiedSolution = copiedSolutions.get(solutionId) | ||
55 | if (copiedSolution === null) { | ||
56 | throw new IllegalStateException("No solution to mark as obsolete for state code: " + solutionId) | ||
57 | } | ||
58 | copiedSolution.current = false | ||
59 | } | ||
60 | |||
61 | def List<PartialInterpretation> getPartialInterpretations(boolean currentOnly) { | ||
62 | getListOfCopiedSolutions(currentOnly).map[partialInterpretations] | ||
63 | } | ||
64 | |||
65 | def List<Map<EObject, EObject>> getTraces(boolean currentOnly) { | ||
66 | getListOfCopiedSolutions(currentOnly).map[trace] | ||
67 | } | ||
68 | |||
69 | def List<Long> getAllCopierRuntimes(boolean currentOnly) { | ||
70 | getListOfCopiedSolutions(currentOnly).map[copierRuntime] | ||
71 | } | ||
72 | |||
73 | def List<CopiedSolution> getListOfCopiedSolutions(boolean currentOnly) { | ||
74 | val values = copiedSolutions.values | ||
75 | val filteredSolutions = if (currentOnly) { | ||
76 | values.filter[current] | ||
77 | } else { | ||
78 | values | ||
79 | } | ||
80 | ImmutableList.copyOf(filteredSolutions) | ||
81 | } | ||
82 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend index 21867a4e..4bd2c349 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SolutionStoreWithCopy.xtend | |||
@@ -1,14 +1,12 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import java.util.List | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | 3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation |
5 | import java.util.LinkedList | 4 | import java.util.LinkedList |
6 | import org.eclipse.emf.ecore.EObject | 5 | import java.util.List |
7 | import java.util.Map | 6 | import java.util.Map |
7 | import org.eclipse.emf.ecore.EObject | ||
8 | import org.eclipse.emf.ecore.util.EcoreUtil | 8 | import org.eclipse.emf.ecore.util.EcoreUtil |
9 | import org.eclipse.viatra.dse.base.ThreadContext | 9 | import org.eclipse.viatra.dse.base.ThreadContext |
10 | import java.util.TreeMap | ||
11 | import java.util.SortedMap | ||
12 | 10 | ||
13 | class SolutionStoreWithCopy { | 11 | class SolutionStoreWithCopy { |
14 | 12 | ||
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 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.neighbourhood.PartialInterpretation2ImmutableTypeLattice | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.partialinterpretationlanguage.partialinterpretation.PartialInterpretation | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.DiversityDescriptor | ||
6 | import java.util.LinkedList | ||
7 | import java.util.List | ||
8 | import org.eclipse.viatra.dse.base.ThreadContext | ||
9 | import java.util.HashSet | ||
10 | import java.util.Set | ||
11 | |||
12 | enum DiversityGranularity { | ||
13 | Nodewise, Graphwise | ||
14 | } | ||
15 | |||
16 | class SolutionStoreWithDiversityDescriptor { | ||
17 | val DiversityDescriptor descriptor | ||
18 | DiversityGranularity granularity | ||
19 | val PartialInterpretation2ImmutableTypeLattice solutionCoder = new PartialInterpretation2ImmutableTypeLattice | ||
20 | val Set<Integer> solutionCodeList = new HashSet | ||
21 | |||
22 | var long runtime | ||
23 | var int allCheck | ||
24 | var int successfulCheck | ||
25 | |||
26 | new(DiversityDescriptor descriptor) { | ||
27 | if(descriptor.ensureDiversity) { | ||
28 | this.descriptor = descriptor | ||
29 | this.granularity = DiversityGranularity::Nodewise | ||
30 | } else { | ||
31 | this.descriptor = null | ||
32 | this.granularity = DiversityGranularity::Nodewise | ||
33 | } | ||
34 | } | ||
35 | |||
36 | def public isActive() { | ||
37 | descriptor!==null | ||
38 | } | ||
39 | |||
40 | def getSumRuntime() { | ||
41 | return runtime | ||
42 | } | ||
43 | def getSuccessRate() { | ||
44 | return successfulCheck as double / allCheck | ||
45 | } | ||
46 | |||
47 | def isDifferent(ThreadContext context) { | ||
48 | if(active) { | ||
49 | val start = System.nanoTime | ||
50 | val model = context.model as PartialInterpretation | ||
51 | var boolean isDifferent | ||
52 | if(this.granularity == DiversityGranularity::Graphwise) { | ||
53 | val code = solutionCoder.createRepresentation(model, | ||
54 | descriptor.range, | ||
55 | descriptor.parallels, | ||
56 | descriptor.maxNumber, | ||
57 | descriptor.relevantTypes, | ||
58 | descriptor.relevantRelations).modelRepresentation.hashCode | ||
59 | |||
60 | isDifferent = !solutionCodeList.contains(code) | ||
61 | } else if(this.granularity == DiversityGranularity::Nodewise){ | ||
62 | val codes = solutionCoder.createRepresentation(model, | ||
63 | descriptor.range, | ||
64 | descriptor.parallels, | ||
65 | descriptor.maxNumber, | ||
66 | descriptor.relevantTypes, | ||
67 | descriptor.relevantRelations).modelRepresentation.keySet.map[hashCode].toList | ||
68 | val differentCodes = codes.filter[!solutionCodeList.contains(it)] | ||
69 | //println(differentCodes.size) | ||
70 | |||
71 | isDifferent = differentCodes.size>=1 | ||
72 | } else { | ||
73 | throw new UnsupportedOperationException('''Unsupported diversity type: «this.granularity»''') | ||
74 | } | ||
75 | |||
76 | runtime += System.nanoTime - start | ||
77 | allCheck++ | ||
78 | if(isDifferent) { successfulCheck++ } | ||
79 | return isDifferent | ||
80 | } else { | ||
81 | allCheck++ | ||
82 | successfulCheck++ | ||
83 | return true | ||
84 | } | ||
85 | } | ||
86 | |||
87 | def canBeDifferent(ThreadContext context) { | ||
88 | return true | ||
89 | } | ||
90 | |||
91 | def newSolution(ThreadContext context) { | ||
92 | if(active) { | ||
93 | val start = System.nanoTime | ||
94 | val model = context.model as PartialInterpretation | ||
95 | if(this.granularity == DiversityGranularity::Graphwise) { | ||
96 | val code = solutionCoder.createRepresentation(model, | ||
97 | descriptor.range, | ||
98 | descriptor.parallels, | ||
99 | descriptor.maxNumber, | ||
100 | descriptor.relevantTypes, | ||
101 | descriptor.relevantRelations).modelRepresentation.hashCode | ||
102 | |||
103 | solutionCodeList += code.hashCode | ||
104 | } else if(this.granularity == DiversityGranularity::Nodewise){ | ||
105 | val codes = solutionCoder.createRepresentation(model, | ||
106 | descriptor.range, | ||
107 | descriptor.parallels, | ||
108 | descriptor.maxNumber, | ||
109 | descriptor.relevantTypes, | ||
110 | descriptor.relevantRelations).modelRepresentation.keySet.map[hashCode].toList | ||
111 | |||
112 | solutionCodeList += codes.map[it.hashCode] | ||
113 | } else { | ||
114 | throw new UnsupportedOperationException('''Unsupported diversity type: «this.granularity»''') | ||
115 | } | ||
116 | |||
117 | runtime += System.nanoTime - start | ||
118 | } | ||
119 | } | ||
120 | } \ 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/SurelyViolatedObjectiveGlobalConstraint.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend new file mode 100644 index 00000000..8ed3e912 --- /dev/null +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/SurelyViolatedObjectiveGlobalConstraint.xtend | |||
@@ -0,0 +1,27 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import org.eclipse.viatra.dse.base.ThreadContext | ||
4 | import org.eclipse.viatra.dse.objectives.IGlobalConstraint | ||
5 | import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor | ||
6 | |||
7 | @FinalFieldsConstructor | ||
8 | class SurelyViolatedObjectiveGlobalConstraint implements IGlobalConstraint { | ||
9 | val ViatraReasonerSolutionSaver solutionSaver | ||
10 | |||
11 | override init(ThreadContext context) { | ||
12 | // Nothing to initialize. | ||
13 | } | ||
14 | |||
15 | override createNew() { | ||
16 | this | ||
17 | } | ||
18 | |||
19 | override getName() { | ||
20 | class.name | ||
21 | } | ||
22 | |||
23 | override checkGlobalConstraint(ThreadContext context) { | ||
24 | val bestFitness = DseUtils.caclulateBestPossibleFitness(context) | ||
25 | bestFitness.satisifiesHardObjectives && solutionSaver.fitnessMayBeSaved(bestFitness) | ||
26 | } | ||
27 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend index 2b0807d6..e1582d3b 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/UnfinishedMultiplicityObjective.xtend | |||
@@ -1,15 +1,15 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.MultiplicityGoalConstraintCalculator | 3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.MultiplicityGoalConstraintCalculator |
4 | import java.util.Comparator | 4 | import java.util.Comparator |
5 | import org.eclipse.viatra.dse.base.ThreadContext | 5 | import org.eclipse.viatra.dse.base.ThreadContext |
6 | import org.eclipse.viatra.dse.objectives.IObjective | ||
7 | import org.eclipse.viatra.dse.objectives.Comparators | 6 | import org.eclipse.viatra.dse.objectives.Comparators |
7 | import org.eclipse.viatra.dse.objectives.IObjective | ||
8 | 8 | ||
9 | class UnfinishedMultiplicityObjective implements IObjective { | 9 | class UnfinishedMultiplicityObjective implements IObjective { |
10 | val MultiplicityGoalConstraintCalculator unfinishedMultiplicity; | 10 | val MultiplicityGoalConstraintCalculator unfinishedMultiplicity |
11 | 11 | ||
12 | public new(MultiplicityGoalConstraintCalculator unfinishedMultiplicity) { | 12 | new(MultiplicityGoalConstraintCalculator unfinishedMultiplicity) { |
13 | this.unfinishedMultiplicity = unfinishedMultiplicity | 13 | this.unfinishedMultiplicity = unfinishedMultiplicity |
14 | } | 14 | } |
15 | 15 | ||
@@ -29,12 +29,13 @@ class UnfinishedMultiplicityObjective implements IObjective { | |||
29 | override satisifiesHardObjective(Double fitness) { return fitness <=0.01 } | 29 | override satisifiesHardObjective(Double fitness) { return fitness <=0.01 } |
30 | 30 | ||
31 | override setComparator(Comparator<Double> comparator) { | 31 | override setComparator(Comparator<Double> comparator) { |
32 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 32 | throw new UnsupportedOperationException |
33 | } | 33 | } |
34 | override setLevel(int level) { | 34 | override setLevel(int level) { |
35 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 35 | throw new UnsupportedOperationException |
36 | } | 36 | } |
37 | |||
37 | def isContainment() { | 38 | def isContainment() { |
38 | return this.unfinishedMultiplicity.containment | 39 | return this.unfinishedMultiplicity.containment |
39 | } | 40 | } |
40 | } \ No newline at end of file | 41 | } |
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 e0111cf6..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 | |||
@@ -1,56 +1,64 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import org.eclipse.viatra.dse.objectives.IObjective | 3 | import java.util.ArrayList |
4 | import org.eclipse.viatra.query.runtime.api.IPatternMatch | ||
5 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | ||
6 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification | ||
7 | import java.util.Collection | 4 | import java.util.Collection |
8 | import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine | 5 | import java.util.Comparator |
9 | import org.eclipse.viatra.query.runtime.emf.EMFScope | ||
10 | import org.eclipse.viatra.dse.base.ThreadContext | ||
11 | import java.util.List | 6 | import java.util.List |
7 | import org.eclipse.viatra.dse.base.ThreadContext | ||
12 | import org.eclipse.viatra.dse.objectives.Comparators | 8 | import org.eclipse.viatra.dse.objectives.Comparators |
13 | import java.util.ArrayList | 9 | import org.eclipse.viatra.dse.objectives.IObjective |
14 | import java.util.Comparator | 10 | import org.eclipse.viatra.query.runtime.api.IPatternMatch |
11 | import org.eclipse.viatra.query.runtime.api.IQuerySpecification | ||
12 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | ||
15 | 13 | ||
16 | class UnfinishedWFObjective implements IObjective { | 14 | class UnfinishedWFObjective implements IObjective { |
17 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs | 15 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs |
18 | val List<ViatraQueryMatcher<?>> matchers | 16 | val List<ViatraQueryMatcher<?>> matchers |
19 | 17 | ||
20 | public new(Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs) { | 18 | new( |
19 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWFs) { | ||
21 | this.unfinishedWFs = unfinishedWFs | 20 | this.unfinishedWFs = unfinishedWFs |
22 | matchers = new ArrayList(unfinishedWFs.size) | 21 | matchers = new ArrayList(unfinishedWFs.size) |
23 | } | 22 | } |
23 | |||
24 | override getName() '''unfinishedWFs''' | 24 | override getName() '''unfinishedWFs''' |
25 | |||
25 | override createNew() { | 26 | override createNew() { |
26 | return new UnfinishedWFObjective(unfinishedWFs) | 27 | return new UnfinishedWFObjective(unfinishedWFs) |
27 | } | 28 | } |
29 | |||
28 | override init(ThreadContext context) { | 30 | override init(ThreadContext context) { |
29 | val engine = context.queryEngine//ViatraQueryEngine.on(new EMFScope(context.model)) | 31 | val engine = context.queryEngine // ViatraQueryEngine.on(new EMFScope(context.model)) |
30 | for(unfinishedWF : unfinishedWFs) { | 32 | for (unfinishedWF : unfinishedWFs) { |
31 | matchers += unfinishedWF.getMatcher(engine) | 33 | matchers += unfinishedWF.getMatcher(engine) |
32 | } | 34 | } |
33 | } | 35 | } |
34 | 36 | ||
35 | override getComparator() { Comparators.LOWER_IS_BETTER } | 37 | override getComparator() { Comparators.LOWER_IS_BETTER } |
38 | |||
36 | override getFitness(ThreadContext context) { | 39 | override getFitness(ThreadContext context) { |
37 | var sumOfMatches = 0 | 40 | var sumOfMatches = 0 |
38 | for(matcher : matchers) { | 41 | for (matcher : matchers) { |
39 | val number = matcher.countMatches | 42 | val number = matcher.countMatches |
40 | //println('''«matcher.patternName» = «number»''') | 43 | // if (number > 0) { |
41 | sumOfMatches+=number | 44 | // println('''«matcher.patternName» = «number»''') |
45 | // } | ||
46 | sumOfMatches += number | ||
42 | } | 47 | } |
43 | return sumOfMatches.doubleValue | 48 | return sumOfMatches.doubleValue |
44 | } | 49 | } |
45 | 50 | ||
46 | override getLevel() { 2 } | 51 | override getLevel() { 2 } |
52 | |||
47 | override isHardObjective() { true } | 53 | override isHardObjective() { true } |
48 | override satisifiesHardObjective(Double fitness) { return fitness <=0.01 } | 54 | |
49 | 55 | override satisifiesHardObjective(Double fitness) { return fitness <= 0.01 } | |
56 | |||
50 | override setComparator(Comparator<Double> comparator) { | 57 | override setComparator(Comparator<Double> comparator) { |
51 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 58 | throw new UnsupportedOperationException() |
52 | } | 59 | } |
60 | |||
53 | override setLevel(int level) { | 61 | override setLevel(int level) { |
54 | throw new UnsupportedOperationException("TODO: auto-generated method stub") | 62 | throw new UnsupportedOperationException() |
55 | } | 63 | } |
56 | } \ No newline at end of file | 64 | } |
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..e00f76ff --- /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,250 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | ||
2 | |||
3 | import hu.bme.mit.inf.dslreasoner.viatrasolver.logic2viatra.cardinality.Bounds | ||
4 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.DirectionalThresholdObjective | ||
5 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.IObjectiveBoundsProvider | ||
6 | import hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.optimization.ObjectiveThreshold | ||
7 | import java.util.HashMap | ||
8 | import java.util.Map | ||
9 | import org.eclipse.viatra.dse.api.DSEException | ||
10 | import org.eclipse.viatra.dse.api.Solution | ||
11 | import org.eclipse.viatra.dse.api.SolutionTrajectory | ||
12 | import org.eclipse.viatra.dse.base.ThreadContext | ||
13 | import org.eclipse.viatra.dse.objectives.Fitness | ||
14 | import org.eclipse.viatra.dse.objectives.IObjective | ||
15 | import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper | ||
16 | import org.eclipse.viatra.dse.solutionstore.SolutionStore.ISolutionSaver | ||
17 | import org.eclipse.xtend.lib.annotations.Accessors | ||
18 | |||
19 | /** | ||
20 | * Based on {@link SolutionStore.BestSolutionSaver}. | ||
21 | * | ||
22 | * Will also automatically fill any missing numerical values in the saved solutions | ||
23 | * using the supplied {@link NumericSolver}. | ||
24 | */ | ||
25 | class ViatraReasonerSolutionSaver implements ISolutionSaver, IObjectiveBoundsProvider { | ||
26 | static val TOLERANCE = 1e-10 | ||
27 | |||
28 | @Accessors val SolutionCopier solutionCopier | ||
29 | @Accessors val DiversityChecker diversityChecker | ||
30 | val IObjective[][] leveledExtremalObjectives | ||
31 | val boolean hasExtremalObjectives | ||
32 | val int numberOfRequiredSolutions | ||
33 | val ObjectiveComparatorHelper comparatorHelper | ||
34 | val Map<SolutionTrajectory, Fitness> trajectories = new HashMap | ||
35 | |||
36 | @Accessors var NumericSolver numericSolver | ||
37 | @Accessors var Map<Object, Solution> solutionsCollection | ||
38 | |||
39 | new(IObjective[][] leveledExtremalObjectives, int numberOfRequiredSolutions, DiversityChecker diversityChecker) { | ||
40 | this.diversityChecker = diversityChecker | ||
41 | comparatorHelper = new ObjectiveComparatorHelper(leveledExtremalObjectives) | ||
42 | this.leveledExtremalObjectives = leveledExtremalObjectives | ||
43 | hasExtremalObjectives = leveledExtremalObjectives.exists[!empty] | ||
44 | this.numberOfRequiredSolutions = numberOfRequiredSolutions | ||
45 | this.solutionCopier = new SolutionCopier | ||
46 | } | ||
47 | |||
48 | def setNumericSolver(NumericSolver numericSolver) { | ||
49 | this.numericSolver = numericSolver | ||
50 | solutionCopier.numericSolver = numericSolver | ||
51 | } | ||
52 | |||
53 | override saveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { | ||
54 | if (hasExtremalObjectives) { | ||
55 | saveBestSolutionOnly(context, id, solutionTrajectory) | ||
56 | } else { | ||
57 | saveAnyDiverseSolution(context, id, solutionTrajectory) | ||
58 | } | ||
59 | } | ||
60 | |||
61 | private def saveBestSolutionOnly(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { | ||
62 | val fitness = context.lastFitness | ||
63 | if (!shouldSaveSolution(fitness, context)) { | ||
64 | return false | ||
65 | } | ||
66 | println("Found: " + fitness) | ||
67 | val dominatedTrajectories = newArrayList | ||
68 | for (entry : trajectories.entrySet) { | ||
69 | val isLastFitnessBetter = comparatorHelper.compare(fitness, entry.value) | ||
70 | if (isLastFitnessBetter < 0) { | ||
71 | // Found a trajectory that dominates the current one, no need to save | ||
72 | return false | ||
73 | } | ||
74 | if (isLastFitnessBetter > 0) { | ||
75 | dominatedTrajectories += entry.key | ||
76 | } | ||
77 | } | ||
78 | if (dominatedTrajectories.size == 0 && !needsMoreSolutionsWithSameFitness) { | ||
79 | return false | ||
80 | } | ||
81 | if (!diversityChecker.newSolution(context, id, dominatedTrajectories.map[solution.stateCode])) { | ||
82 | return false | ||
83 | } | ||
84 | // We must save the new trajectory before removing dominated trajectories | ||
85 | // to avoid removing the current solution when it is reachable only via dominated trajectories. | ||
86 | val solutionSaved = basicSaveSolution(context, id, solutionTrajectory, fitness) | ||
87 | for (dominatedTrajectory : dominatedTrajectories) { | ||
88 | trajectories -= dominatedTrajectory | ||
89 | val dominatedSolution = dominatedTrajectory.solution | ||
90 | if (!dominatedSolution.trajectories.remove(dominatedTrajectory)) { | ||
91 | throw new DSEException( | ||
92 | "Dominated solution is not reachable from dominated trajectory. This should never happen!") | ||
93 | } | ||
94 | if (dominatedSolution.trajectories.empty) { | ||
95 | val dominatedSolutionId = dominatedSolution.stateCode | ||
96 | solutionCopier.markAsObsolete(dominatedSolutionId) | ||
97 | solutionsCollection -= dominatedSolutionId | ||
98 | } | ||
99 | } | ||
100 | solutionSaved | ||
101 | } | ||
102 | |||
103 | private def saveAnyDiverseSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory) { | ||
104 | val fitness = context.lastFitness | ||
105 | if (!shouldSaveSolution(fitness, context)) { | ||
106 | return false | ||
107 | } | ||
108 | if (!diversityChecker.newSolution(context, id, emptyList)) { | ||
109 | return false | ||
110 | } | ||
111 | basicSaveSolution(context, id, solutionTrajectory, fitness) | ||
112 | } | ||
113 | |||
114 | private def shouldSaveSolution(Fitness fitness, ThreadContext context) { | ||
115 | fitness.satisifiesHardObjectives && (numericSolver === null || numericSolver.currentSatisfiable) | ||
116 | } | ||
117 | |||
118 | private def basicSaveSolution(ThreadContext context, Object id, SolutionTrajectory solutionTrajectory, | ||
119 | Fitness fitness) { | ||
120 | var boolean solutionSaved = false | ||
121 | var dseSolution = solutionsCollection.get(id) | ||
122 | if (dseSolution === null) { | ||
123 | solutionCopier.copySolution(context, id) | ||
124 | dseSolution = new Solution(id, solutionTrajectory) | ||
125 | solutionsCollection.put(id, dseSolution) | ||
126 | solutionSaved = true | ||
127 | } else { | ||
128 | solutionSaved = dseSolution.trajectories.add(solutionTrajectory) | ||
129 | } | ||
130 | if (solutionSaved) { | ||
131 | solutionTrajectory.solution = dseSolution | ||
132 | trajectories.put(solutionTrajectory, fitness) | ||
133 | } | ||
134 | solutionSaved | ||
135 | } | ||
136 | |||
137 | def fitnessMayBeSaved(Fitness fitness) { | ||
138 | if (!hasExtremalObjectives) { | ||
139 | return true | ||
140 | } | ||
141 | var boolean mayDominate | ||
142 | for (existingFitness : trajectories.values) { | ||
143 | val isNewFitnessBetter = comparatorHelper.compare(fitness, existingFitness) | ||
144 | if (isNewFitnessBetter < 0) { | ||
145 | return false | ||
146 | } | ||
147 | if (isNewFitnessBetter > 0) { | ||
148 | mayDominate = true | ||
149 | } | ||
150 | } | ||
151 | mayDominate || needsMoreSolutionsWithSameFitness | ||
152 | } | ||
153 | |||
154 | private def boolean needsMoreSolutionsWithSameFitness() { | ||
155 | if (solutionsCollection === null) { | ||
156 | // The solutions collection will only be initialized upon saving the first solution. | ||
157 | return true | ||
158 | } | ||
159 | solutionsCollection.size < numberOfRequiredSolutions | ||
160 | } | ||
161 | |||
162 | def getTotalCopierRuntime() { | ||
163 | solutionCopier.totalCopierRuntime | ||
164 | } | ||
165 | |||
166 | override computeRequiredBounds(IObjective objective, Bounds bounds) { | ||
167 | if (!hasExtremalObjectives) { | ||
168 | return | ||
169 | } | ||
170 | if (objective instanceof DirectionalThresholdObjective) { | ||
171 | switch (threshold : objective.threshold) { | ||
172 | case ObjectiveThreshold.NO_THRESHOLD: { | ||
173 | // No threshold to set. | ||
174 | } | ||
175 | ObjectiveThreshold.Exclusive: { | ||
176 | switch (kind : objective.kind) { | ||
177 | case HIGHER_IS_BETTER: | ||
178 | bounds.tightenLowerBound(Math.floor(threshold.threshold + 1) as int) | ||
179 | case LOWER_IS_BETTER: | ||
180 | bounds.tightenUpperBound(Math.ceil(threshold.threshold - 1) as int) | ||
181 | default: | ||
182 | throw new IllegalArgumentException("Unknown objective kind" + kind) | ||
183 | } | ||
184 | if (threshold.clampToThreshold) { | ||
185 | return | ||
186 | } | ||
187 | } | ||
188 | ObjectiveThreshold.Inclusive: { | ||
189 | switch (kind : objective.kind) { | ||
190 | case HIGHER_IS_BETTER: | ||
191 | bounds.tightenLowerBound(Math.ceil(threshold.threshold) as int) | ||
192 | case LOWER_IS_BETTER: | ||
193 | bounds.tightenUpperBound(Math.floor(threshold.threshold) as int) | ||
194 | default: | ||
195 | throw new IllegalArgumentException("Unknown objective kind" + kind) | ||
196 | } | ||
197 | if (threshold.clampToThreshold) { | ||
198 | return | ||
199 | } | ||
200 | } | ||
201 | default: | ||
202 | throw new IllegalArgumentException("Unknown threshold: " + threshold) | ||
203 | } | ||
204 | for (level : leveledExtremalObjectives) { | ||
205 | switch (level.size) { | ||
206 | case 0: { | ||
207 | // Nothing to do, wait for the next level. | ||
208 | } | ||
209 | case 1: { | ||
210 | val primaryObjective = level.get(0) | ||
211 | if (primaryObjective != objective) { | ||
212 | // There are no worst-case bounds for secondary objectives. | ||
213 | return | ||
214 | } | ||
215 | } | ||
216 | default: | ||
217 | // There are no worst-case bounds for Pareto front calculation. | ||
218 | return | ||
219 | } | ||
220 | } | ||
221 | val fitnessIterator = trajectories.values.iterator | ||
222 | if (!fitnessIterator.hasNext) { | ||
223 | return | ||
224 | } | ||
225 | val fitness = fitnessIterator.next.get(objective.name) | ||
226 | while (fitnessIterator.hasNext) { | ||
227 | val otherFitness = fitnessIterator.next.get(objective.name) | ||
228 | if (Math.abs(fitness - otherFitness) > TOLERANCE) { | ||
229 | throw new IllegalStateException("Inconsistent fitness: " + objective.name) | ||
230 | } | ||
231 | } | ||
232 | switch (kind : objective.kind) { | ||
233 | case HIGHER_IS_BETTER: | ||
234 | if (needsMoreSolutionsWithSameFitness) { | ||
235 | bounds.tightenLowerBound(Math.floor(fitness) as int) | ||
236 | } else { | ||
237 | bounds.tightenLowerBound(Math.floor(fitness + 1) as int) | ||
238 | } | ||
239 | case LOWER_IS_BETTER: | ||
240 | if (needsMoreSolutionsWithSameFitness) { | ||
241 | bounds.tightenUpperBound(Math.ceil(fitness) as int) | ||
242 | } else { | ||
243 | bounds.tightenUpperBound(Math.ceil(fitness - 1) as int) | ||
244 | } | ||
245 | default: | ||
246 | throw new IllegalArgumentException("Unknown objective kind" + kind) | ||
247 | } | ||
248 | } | ||
249 | } | ||
250 | } | ||
diff --git a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend index 5a528a9e..6d772f32 100644 --- a/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend +++ b/Solvers/VIATRA-Solver/hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner/src/hu/bme/mit/inf/dslreasoner/viatrasolver/reasoner/dse/WF2ObjectiveConverter.xtend | |||
@@ -1,5 +1,6 @@ | |||
1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse | 1 | package hu.bme.mit.inf.dslreasoner.viatrasolver.reasoner.dse |
2 | 2 | ||
3 | import com.google.common.collect.ImmutableList | ||
3 | import java.util.ArrayList | 4 | import java.util.ArrayList |
4 | import java.util.Collection | 5 | import java.util.Collection |
5 | import org.eclipse.viatra.dse.objectives.Comparators | 6 | import org.eclipse.viatra.dse.objectives.Comparators |
@@ -12,25 +13,33 @@ import org.eclipse.viatra.query.runtime.api.IQuerySpecification | |||
12 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher | 13 | import org.eclipse.viatra.query.runtime.api.ViatraQueryMatcher |
13 | 14 | ||
14 | class WF2ObjectiveConverter { | 15 | class WF2ObjectiveConverter { |
15 | 16 | static val INVALIDATED_WFS_NAME = "invalidatedWFs" | |
17 | |||
16 | def createCompletenessObjective( | 18 | def createCompletenessObjective( |
17 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF) | 19 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> unfinishedWF) { |
18 | { | 20 | new UnfinishedWFObjective(unfinishedWF) |
19 | val res = new ConstraintsObjective('''unfinishedWFs''', | 21 | } |
20 | unfinishedWF.map[ | 22 | |
21 | new QueryConstraint(it.fullyQualifiedName,it,2.0) | 23 | def createInvalidationObjective( |
22 | ].toList | 24 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidatedByWF) { |
25 | createConstraintObjective(INVALIDATED_WFS_NAME, invalidatedByWF) | ||
26 | } | ||
27 | |||
28 | def IGlobalConstraint createInvalidationGlobalConstraint( | ||
29 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidatedByWF) { | ||
30 | new ModelQueriesGlobalConstraint(INVALIDATED_WFS_NAME, new ArrayList(invalidatedByWF)) | ||
31 | } | ||
32 | |||
33 | private def createConstraintObjective(String name, | ||
34 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> queries) { | ||
35 | val res = new ConstraintsObjective( | ||
36 | name, | ||
37 | ImmutableList.copyOf(queries.map [ | ||
38 | new QueryConstraint(it.fullyQualifiedName, it, 1.0) | ||
39 | ]) | ||
23 | ) | 40 | ) |
24 | res.withComparator(Comparators.LOWER_IS_BETTER) | 41 | res.withComparator(Comparators.LOWER_IS_BETTER) |
25 | res.level = 2 | 42 | res.level = 2 |
26 | return res | 43 | res |
27 | } | ||
28 | |||
29 | def IGlobalConstraint createInvalidationObjective( | ||
30 | Collection<? extends IQuerySpecification<? extends ViatraQueryMatcher<? extends IPatternMatch>>> invalidatedByWF) | ||
31 | { | ||
32 | return new ModelQueriesGlobalConstraint('''invalidatedWFs''', | ||
33 | new ArrayList(invalidatedByWF) | ||
34 | ) | ||
35 | } | 44 | } |
36 | } \ No newline at end of file | 45 | } |