aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base
diff options
context:
space:
mode:
Diffstat (limited to 'Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base')
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ActivationCodesConflictSet.java213
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DesignSpaceManager.java563
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictResolver.java35
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictSet.java83
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseEvmRuleBase.java21
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseIdPoolHelper.java68
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ExplorerThread.java88
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java374
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/IDseStrategyContext.java117
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/SingletonSetConflictResolver.java53
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java542
11 files changed, 2157 insertions, 0 deletions
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ActivationCodesConflictSet.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ActivationCodesConflictSet.java
new file mode 100644
index 00000000..d3990c23
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ActivationCodesConflictSet.java
@@ -0,0 +1,213 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2017, Andras Szabolcs Nagy and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.Collection;
12import java.util.HashMap;
13import java.util.HashSet;
14import java.util.Map;
15import java.util.Objects;
16import java.util.Set;
17
18import org.eclipse.viatra.dse.statecode.IStateCoder;
19import org.eclipse.viatra.query.runtime.api.IPatternMatch;
20import org.eclipse.viatra.transformation.evm.api.Activation;
21import org.eclipse.viatra.transformation.evm.api.resolver.ChangeableConflictSet;
22import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
23import org.eclipse.viatra.transformation.evm.api.resolver.ConflictSet;
24
25public class ActivationCodesConflictSet implements ChangeableConflictSet {
26
27 private static class ActivationCodesMultiBiMap {
28 public Map<Activation<?>, Object> activationsToCodes = new HashMap<>();
29 public Map<Object, Set<Activation<?>>> codesToActivations = new HashMap<>();
30
31 public void addActivation(Activation<?> activation, Object activationCode) {
32 activationsToCodes.put(activation, activationCode);
33 codesToActivations.computeIfAbsent(activationCode, k -> new HashSet<>()).add(activation);
34 }
35
36 public void removeActivaion(Activation<?> activation) {
37 Object activationCode = activationsToCodes.remove(activation);
38 Set<Activation<?>> activations = codesToActivations.get(activationCode);
39 if (activations != null) {
40 activations.remove(activation);
41 }
42 }
43
44 public void clear() {
45 activationsToCodes.clear();
46 codesToActivations.clear();
47 }
48 }
49
50 protected ActivationCodesMultiBiMap activationCodes;
51 protected IStateCoder stateCoder;
52
53 protected Set<Activation<?>> newActivations = new HashSet<>();
54 protected Set<Activation<?>> removedActivations = new HashSet<>();
55// private Logger logger = Logger.getLogger(getClass());
56
57 private boolean isIncremental = false;
58 private ConflictSet nextActivationsConflictSet;
59
60 public void setIncremental(boolean isIncremental) {
61 this.isIncremental = isIncremental;
62 }
63
64 public ActivationCodesConflictSet(ConflictSet nextActivationsConflictSet, IStateCoder stateCoder) {
65 Objects.requireNonNull(nextActivationsConflictSet);
66 this.nextActivationsConflictSet = nextActivationsConflictSet;
67 this.stateCoder = stateCoder;
68 activationCodes = new ActivationCodesMultiBiMap();
69 }
70
71 private Object createActivationCode(Activation<?> activation) {
72 return stateCoder.createActivationCode((IPatternMatch) activation.getAtom());
73 }
74
75 @Override
76 public boolean removeActivation(Activation<?> activation) {
77 if (isIncremental) {
78//*
79 removedActivations.add(activation);
80 newActivations.remove(activation);
81/*/
82 if(!removedActivations.add(activation)) {
83 logger.debug("Abnormal: already marked to remove: " + activation);
84 } else {
85 logger.debug("marked to remove: " + activation);
86 }
87 if(newActivations.remove(activation)) {
88 logger.debug("Abnormal: removed from new activations: " + activation);
89 }
90//*/
91 }
92 return false;
93 }
94
95 @Override
96 public boolean addActivation(Activation<?> activation) {
97 if (isIncremental) {
98//*
99 newActivations.add(activation);
100 removedActivations.remove(activation);
101 /*/
102 if (activation.isEnabled()) {
103 if (!newActivations.add(activation)) {
104 logger.debug("Abnormal: already added as new: " + activation);
105 } else {
106 logger.debug("activation added: " + activation);
107 }
108 }
109 if(removedActivations.remove(activation)) {
110 logger.debug("Abnormal: was already marked to remove: " + activation);
111 }
112//*/
113 }
114 return false;
115 }
116
117 public Object getActivationId(Activation<?> activation) {
118 return activationCodes.activationsToCodes.get(activation);
119 }
120
121 public Activation<?> getActivation(Object activationId) {
122 Set<Activation<?>> activationsSet = activationCodes.codesToActivations.get(activationId);
123 if (activationsSet == null || activationsSet.isEmpty()) {
124 return null;
125 } else {
126 return activationsSet.iterator().next();
127 }
128 }
129
130 public void updateActivationCodes() {
131// logger.debug("Updating activation codes.");
132
133 if (isIncremental) {
134 for (Activation<?> activation : removedActivations) {
135 activationCodes.removeActivaion(activation);
136// logger.debug("removed activation: " + activationId);
137 }
138
139 for (Activation<?> activation : newActivations) {
140 if (activation.getState().isInactive()) {
141 continue;
142 }
143 Object activationCode = createActivationCode(activation);
144 activationCodes.addActivation(activation, activationCode);
145// logger.debug("new activation: " + activationId);
146// Activation<?> similarActivation = activationIds.inverse().get(activationId);
147// if (similarActivation != null) {
148// logger.debug("Activation " + toStringAct(activation) + " is already present with id: " + activationId);
149// if (similarActivation.isEnabled()) {
150// logger.warn("Duplicate activation code: " + activationId);
151// } else {
152// logger.debug("Force put: " + activationId);
153// }
154// continue;
155// }
156// activationIds.put(activation, activationId);
157 }
158 removedActivations.clear();
159 newActivations.clear();
160 } else {
161 activationCodes.clear();
162 for (Activation<?> activation : nextActivationsConflictSet.getNextActivations()) {
163 Object activationCode = createActivationCode(activation);
164 activationCodes.addActivation(activation, activationCode);
165 }
166 }
167
168
169 }
170
171 protected void reinitWithActivations(ConflictSet nextActivationsConflictSet) {
172 this.nextActivationsConflictSet = nextActivationsConflictSet;
173 activationCodes.clear();
174 for (Activation<?> activation : nextActivationsConflictSet.getNextActivations()) {
175 Object activationCode = createActivationCode(activation);
176 activationCodes.addActivation(activation, activationCode);
177 }
178 }
179
180 @Override
181 public Activation<?> getNextActivation() {
182 throw new UnsupportedOperationException();
183 }
184
185 @Override
186 public Set<Activation<?>> getNextActivations() {
187 throw new UnsupportedOperationException();
188 }
189
190 @Override
191 public Set<Activation<?>> getConflictingActivations() {
192 throw new UnsupportedOperationException();
193 }
194
195 @Override
196 public ConflictResolver getConflictResolver() {
197 throw new UnsupportedOperationException();
198 }
199
200 @Override
201 public String toString() {
202 StringBuilder sb = new StringBuilder();
203 for (Object activationCode : activationCodes.activationsToCodes.values()) {
204 sb.append(activationCode);
205 sb.append(" | ");
206 }
207 return sb.toString();
208 }
209
210 public Collection<Object> getCurrentActivationCodes() {
211 return activationCodes.activationsToCodes.values();
212 }
213}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DesignSpaceManager.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DesignSpaceManager.java
new file mode 100644
index 00000000..4c6b4097
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DesignSpaceManager.java
@@ -0,0 +1,563 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2014, Miklos Foldenyi, Andras Szabolcs Nagy, Abel Hegedus, Akos Horvath, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.lang.reflect.InvocationTargetException;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.Iterator;
16import java.util.List;
17import java.util.Map;
18import java.util.Random;
19
20import org.apache.log4j.Logger;
21import org.eclipse.emf.common.notify.Notifier;
22import org.eclipse.emf.edit.command.ChangeCommand;
23import org.eclipse.emf.edit.domain.EditingDomain;
24import org.eclipse.viatra.dse.api.DSEException;
25import org.eclipse.viatra.dse.api.SolutionTrajectory;
26import org.eclipse.viatra.dse.designspace.api.IBacktrackListener;
27import org.eclipse.viatra.dse.designspace.api.IDesignSpace;
28import org.eclipse.viatra.dse.designspace.api.TrajectoryInfo;
29import org.eclipse.viatra.dse.objectives.ActivationFitnessProcessor;
30import org.eclipse.viatra.dse.statecode.IStateCoder;
31import org.eclipse.viatra.dse.visualizer.IExploreEventHandler;
32import org.eclipse.viatra.query.runtime.api.AdvancedViatraQueryEngine;
33import org.eclipse.viatra.query.runtime.api.IPatternMatch;
34import org.eclipse.viatra.transformation.evm.api.Activation;
35import org.eclipse.viatra.transformation.evm.api.Context;
36import org.eclipse.viatra.transformation.evm.api.resolver.ChangeableConflictSet;
37import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule;
38
39public class DesignSpaceManager implements IBacktrackListener {
40
41 private final IStateCoder stateCoder;
42 private final EditingDomain domain;
43 private Notifier model;
44
45 private IDesignSpace designSpace;
46
47 private final TrajectoryInfo trajectory;
48
49 // the occurence vector callback
50 private List<IExploreEventHandler> handlers;
51
52 // Dummy context for evm
53 private final Context evmContext = Context.create();
54
55 private Logger logger = Logger.getLogger(this.getClass());
56
57 private boolean isNewState = false;
58 private Map<BatchTransformationRule<?, ?>, ActivationFitnessProcessor> activationFitnessProcessors;
59 private Map<BatchTransformationRule<?, ?>, String> activationFitnessProcessorNames;
60 private ThreadContext context;
61
62 private ActivationCodesConflictSet activationCodes;
63 private ChangeableConflictSet conflictSet;
64
65 private AdvancedViatraQueryEngine engine;
66
67 private Random random = new Random();
68
69 private long forwardTime = 0;
70 private long backtrackingTime = 0;
71
72 public DesignSpaceManager(ThreadContext context) {
73
74 this.context = context;
75 model = context.getModel();
76 designSpace = context.getGlobalContext().getDesignSpace();
77 domain = context.getEditingDomain();
78
79 conflictSet = context.getConflictResolver().getLastCreatedConflictSet();
80
81 stateCoder = context.getStateCoder();
82 Object initialStateId = stateCoder.createStateCode();
83 designSpace.addState(null, null, initialStateId);
84
85 activationCodes = context.getActivationCodesConflictSet();
86
87 engine = (AdvancedViatraQueryEngine) context.getQueryEngine();
88
89 this.trajectory = new TrajectoryInfo(initialStateId);
90
91 logger.debug("DesignSpaceManager initialized with initial model: " + initialStateId);
92 }
93
94 public void fireActivation(final Object transition) {
95 if (fireActivationSilent(transition)) {
96 return;
97 }
98
99 StringBuilder sb = new StringBuilder();
100 sb.append(
101 "A retrieved Transition SHOULD have a matching Activation. Possible causes: the state serializer is faulty; the algorithm choosed a wrong Transition.");
102 sb.append("\nSought transition: ");
103 sb.append(transition);
104 Object currentStateId = getCurrentState();
105 sb.append("\nCurrent known state: ");
106 sb.append(currentStateId);
107 Object actualStateId = stateCoder.createStateCode();
108 sb.append("\nActual state: ");
109 sb.append((actualStateId.equals(currentStateId) ? "same as current" : actualStateId));
110 sb.append("\n");
111 sb.append(trajectory);
112 sb.append("\nAvailable transitions:");
113 for (Activation<?> act : conflictSet.getNextActivations()) {
114 IPatternMatch match = (IPatternMatch) act.getAtom();
115 Object code = generateMatchCode(match);
116 sb.append("\n\t");
117 sb.append(code);
118 }
119
120 throw new DSEException(sb.toString());
121 }
122
123 public boolean tryFireActivation(final Object transition) {
124 return fireActivationSilent(transition);
125 }
126
127 private boolean fireActivationSilent(final Object transition) {
128 final Activation<?> activation = getActivationById(transition);
129
130 if (activation == null) {
131 return false;
132 }
133
134 BatchTransformationRule<?, ?> rule = getRuleByActivation(activation);
135
136 Map<String, Double> measureCosts = new HashMap<String, Double>();
137 if (activationFitnessProcessors != null && activationFitnessProcessors.containsKey(rule)) {
138 IPatternMatch match = (IPatternMatch) activation.getAtom();
139 ActivationFitnessProcessor processor = activationFitnessProcessors.get(rule);
140 double fitness = processor.process(match);
141 measureCosts.put(activationFitnessProcessorNames.get(rule), fitness);
142 }
143
144 ChangeCommand rc = new ChangeCommand(model) {
145 @Override
146 protected void doExecute() {
147 activation.fire(evmContext);
148 }
149 };
150
151 Object previousState = trajectory.getCurrentStateId();
152
153 long start = System.nanoTime();
154 domain.getCommandStack().execute(rc);
155 forwardTime += System.nanoTime() - start;
156
157 Object newStateId = stateCoder.createStateCode();
158 updateActivationCodes();
159
160 if (designSpace != null) {
161 isNewState = !designSpace.isTraversed(newStateId);
162 designSpace.addState(previousState, transition, newStateId);
163 }
164
165 trajectory.addStep(transition, rule, newStateId, measureCosts);
166
167 if (handlers != null) {
168 for (IExploreEventHandler iExploreEventHandler : handlers) {
169 iExploreEventHandler.transitionFired(transition);
170 }
171 }
172
173 logger.debug("Executed activation: " + transition);/*
174 * + " from state: " + previousState + " to " + newStateId);
175 */
176
177 return true;
178 }
179
180 public boolean executeRandomActivationId() {
181 Collection<Object> transitions = getTransitionsFromCurrentState();
182 int size = transitions.size();
183 if (size == 0) {
184 return false;
185 }
186
187 int index = random.nextInt(size);
188 Iterator<Object> iterator = transitions.iterator();
189 for (int i = 0; i < index; ++i) {
190 iterator.next();
191 }
192 Object transition = iterator.next();
193
194 fireActivation(transition);
195 return true;
196 }
197
198 public int executeTrajectory(Object[] trajectoryToExecute) {
199 return executeTrajectory(trajectoryToExecute, 0, trajectoryToExecute.length, false, true);
200 }
201
202 public int executeTrajectory(Object[] trajectoryToExecute, int fromIncludedIndex, int toExcludedIndex) {
203 return executeTrajectory(trajectoryToExecute, fromIncludedIndex, toExcludedIndex, false, true);
204 }
205
206 public int executeTrajectoryByTrying(Object[] trajectoryToExecute) {
207 return executeTrajectory(trajectoryToExecute, 0, trajectoryToExecute.length, true, true);
208 }
209
210 public int executeTrajectoryByTrying(Object[] trajectoryToExecute, int fromIncludedIndex, int toExcludedIndex) {
211 return executeTrajectory(trajectoryToExecute, fromIncludedIndex, toExcludedIndex, true, true);
212 }
213
214 public int executeTrajectoryWithoutStateCoding(Object[] trajectoryToExecute) {
215 return executeTrajectory(trajectoryToExecute, 0, trajectoryToExecute.length, false, false);
216 }
217
218 public int executeTrajectoryWithoutStateCoding(Object[] trajectoryToExecute, int fromIncludedIndex,
219 int toExcludedIndex) {
220 return executeTrajectory(trajectoryToExecute, fromIncludedIndex, toExcludedIndex, false, false);
221 }
222
223 public int executeTrajectoryByTryingWithoutStateCoding(Object[] trajectoryToExecute) {
224 return executeTrajectory(trajectoryToExecute, 0, trajectoryToExecute.length, true, false);
225 }
226
227 public int executeTrajectoryByTryingWithoutStateCoding(Object[] trajectoryToExecute, int fromIncludedIndex,
228 int toExcludedIndex) {
229 return executeTrajectory(trajectoryToExecute, fromIncludedIndex, toExcludedIndex, true, false);
230 }
231
232 private int executeTrajectory(Object[] trajectoryToExecute, int fromIncludedIndex, int toExcludedIndex,
233 boolean tryAllActivations, boolean createStateCode) {
234 logger.debug("Executing trajectory.");
235 int unsuccesfulIndex = -1;
236 if (tryAllActivations) {
237 unsuccesfulIndex = 0;
238 }
239 for (int i = fromIncludedIndex; i < toExcludedIndex; i++) {
240 Object activationId = trajectoryToExecute[i];
241 final Activation<?> activation = getActivationById(activationId);
242
243 if (activation == null) {
244 logger.debug("Couldn't execute activation: " + activationId);
245 if (tryAllActivations) {
246 unsuccesfulIndex++;
247 continue;
248 } else {
249 unsuccesfulIndex = i;
250 logger.debug("Trajectory execution stopped at index " + i + "/" + trajectoryToExecute.length);
251 break;
252 }
253 }
254
255 BatchTransformationRule<?, ?> rule = getRuleByActivation(activation);
256
257 Map<String, Double> measureCosts = new HashMap<String, Double>();
258 if (activationFitnessProcessors != null && activationFitnessProcessors.containsKey(rule)) {
259 IPatternMatch match = (IPatternMatch) activation.getAtom();
260 ActivationFitnessProcessor processor = activationFitnessProcessors.get(rule);
261 double fitness = processor.process(match);
262 measureCosts.put(activationFitnessProcessorNames.get(rule), fitness);
263 }
264
265 ChangeCommand rc = new ChangeCommand(model) {
266 @Override
267 protected void doExecute() {
268 activation.fire(evmContext);
269 }
270 };
271
272 long start = System.nanoTime();
273 domain.getCommandStack().execute(rc);
274 forwardTime += System.nanoTime() - start;
275
276 Object newStateId = null;
277 if (createStateCode) {
278 newStateId = stateCoder.createStateCode();
279 }
280 updateActivationCodes();
281
282 trajectory.addStep(activationId, rule, newStateId, measureCosts);
283
284 logger.debug("Activation executed: " + activationId);
285 }
286 if (!createStateCode) {
287 trajectory.modifyLastStateCode(stateCoder.createStateCode());
288 }
289 logger.debug("Trajectory execution finished.");
290 return unsuccesfulIndex;
291
292 }
293
294 public Object getTransitionByActivation(Activation<?> activation) {
295 return activationCodes.getActivationId(activation);
296 }
297
298 public Activation<?> getActivationById(Object activationId) {
299 return activationCodes.getActivation(activationId);
300 }
301
302 public BatchTransformationRule<?, ?> getRuleByActivation(Activation<?> activation) {
303 return context.getGlobalContext().getSpecificationRuleMap().get(activation.getInstance().getSpecification());
304 }
305
306 public BatchTransformationRule<?, ?> getRuleByActivationId(Object activationId) {
307 return getRuleByActivation(getActivationById(activationId));
308 }
309
310 /**
311 * Returns true if the given state is not owned by this crawler.
312 *
313 **/
314 public boolean isNewModelStateAlreadyTraversed() {
315 return !isNewState;
316 }
317
318 public List<Object> getTrajectoryFromRoot() {
319 return trajectory.getTrajectory();
320 }
321
322 public Collection<Object> getTransitionsFromCurrentState() {
323 return activationCodes.getCurrentActivationCodes();
324 }
325
326 public Collection<Object> getUntraversedTransitionsFromCurrentState() {
327 if (designSpace == null) {
328 throw new DSEException("Unsupported without a design space");
329 }
330 Object currentState = trajectory.getCurrentStateId();
331 Collection<Object> traversedIds = designSpace.getActivationIds(currentState);
332
333 List<Object> untraversedTransitions = new ArrayList<>();
334 for (Object activationId : activationCodes.getCurrentActivationCodes()) {
335 if (!traversedIds.contains(activationId)) {
336 untraversedTransitions.add(activationId);
337 }
338 }
339
340 return untraversedTransitions;
341 }
342
343 public boolean undoLastTransformation() {
344
345 if (!trajectory.canStepBack()) {
346 return false;
347 }
348
349 long start = System.nanoTime();
350 try {
351 engine.delayUpdatePropagation(() -> {
352 domain.getCommandStack().undo();
353 return null;
354 });
355 } catch (InvocationTargetException e) {
356 throw new RuntimeException(e);
357 }
358 updateActivationCodes();
359
360 Object lastActivationId = trajectory.getLastActivationId();
361
362 trajectory.backtrack();
363
364 if (handlers != null) {
365 for (IExploreEventHandler iExploreEventHandler : handlers) {
366 iExploreEventHandler.undo(lastActivationId);
367 }
368 }
369
370 logger.debug("Backtrack.");
371 backtrackingTime += System.nanoTime() - start;
372
373 return true;
374 }
375
376 public void backtrackXTimes(int steps) {
377 long start = System.nanoTime();
378 try {
379 engine.delayUpdatePropagation(() -> {
380 for (int i = steps; i > 0; i--) {
381 domain.getCommandStack().undo();
382 trajectory.backtrack();
383 }
384 return null;
385 });
386 } catch (InvocationTargetException e) {
387 throw new RuntimeException(e);
388 }
389 backtrackingTime += System.nanoTime() - start;
390 updateActivationCodes();
391 logger.debug("Backtracked " + steps + " times.");
392 }
393
394 public int backtrackUntilLastCommonActivation(Object[] newTrajectory) {
395 long start = System.nanoTime();
396 Iterator<Object> currentTrajectoryIterator = trajectory.getTrajectory().iterator();
397 if (!currentTrajectoryIterator.hasNext()) {
398 return 0;
399 }
400 int indexOfLastCommonActivation = 0;
401 for (Object activationCode : newTrajectory) {
402 if (currentTrajectoryIterator.hasNext()) {
403 Object activationCodeFromCurrent = currentTrajectoryIterator.next();
404 if (activationCodeFromCurrent.equals(activationCode)) {
405 indexOfLastCommonActivation++;
406 } else {
407 break;
408 }
409 } else {
410 // current trajectory is smaller
411 break;
412 }
413 }
414 int numberOfBacktracks = trajectory.getDepth() - indexOfLastCommonActivation;
415 if (numberOfBacktracks > 0) {
416 try {
417 engine.delayUpdatePropagation(() -> {
418 for (int i = numberOfBacktracks; i > 0; i--) {
419 domain.getCommandStack().undo();
420 trajectory.backtrack();
421 }
422 return null;
423 });
424 } catch (InvocationTargetException e) {
425 throw new RuntimeException(e);
426 }
427 }
428 backtrackingTime += System.nanoTime() - start;
429 updateActivationCodes();
430 logger.debug("Backtracked " + numberOfBacktracks + " times.");
431 return indexOfLastCommonActivation;
432 }
433
434 public void executeTrajectoryWithMinimalBacktrack(Object[] trajectory) {
435 executeTrajectoryWithMinimalBacktrack(trajectory, trajectory.length);
436 }
437
438 public void executeTrajectoryWithMinimalBacktrack(Object[] trajectory, int toExcludedIndex) {
439 int fromIndex = backtrackUntilLastCommonActivation(trajectory);
440 executeTrajectory(trajectory, fromIndex, toExcludedIndex, false, true);
441 }
442
443 public void executeTrajectoryWithMinimalBacktrackWithoutStateCoding(Object[] trajectory) {
444 executeTrajectoryWithMinimalBacktrackWithoutStateCoding(trajectory, trajectory.length);
445 }
446
447 public void executeTrajectoryWithMinimalBacktrackWithoutStateCoding(Object[] trajectory, int toExcludedIndex) {
448 int fromIndex = backtrackUntilLastCommonActivation(trajectory);
449 executeTrajectory(trajectory, fromIndex, toExcludedIndex, false, false);
450 Object stateCode = stateCoder.createStateCode();
451 this.trajectory.modifyLastStateCode(stateCode);
452 }
453
454 public void undoUntilRoot() {
455 long start = System.nanoTime();
456 try {
457 engine.delayUpdatePropagation(() -> {
458 while (trajectory.canStepBack()) {
459 domain.getCommandStack().undo();
460 trajectory.backtrack();
461 }
462 return null;
463 });
464 } catch (InvocationTargetException e) {
465 throw new RuntimeException(e);
466 }
467 backtrackingTime += System.nanoTime() - start;
468 updateActivationCodes();
469 logger.debug("Backtracked to root.");
470 }
471
472 private Object generateMatchCode(IPatternMatch match) {
473 return stateCoder.createActivationCode(match);
474 }
475
476 public Object getCurrentState() {
477 return trajectory.getCurrentStateId();
478 }
479
480 public SolutionTrajectory createSolutionTrajectroy() {
481 return trajectory.createSolutionTrajectory(context.getGlobalContext().getStateCoderFactory(), this);
482 }
483
484 public TrajectoryInfo getTrajectoryInfo() {
485 return trajectory;
486 }
487
488 public void setDesignSpace(IDesignSpace designSpace) {
489 this.designSpace = designSpace;
490 }
491
492 public IDesignSpace getDesignSpace() {
493 return designSpace;
494 }
495
496 public void registerExploreEventHandler(IExploreEventHandler handler) {
497 if (handler == null) {
498 return;
499 }
500 if (handlers == null) {
501 handlers = new ArrayList<IExploreEventHandler>();
502 }
503 handlers.add(handler);
504 }
505
506 public void deregisterExploreEventHandler(IExploreEventHandler handler) {
507 if (handler == null) {
508 return;
509 }
510 if (handlers != null) {
511 handlers.remove(handler);
512 }
513 }
514
515 public void registerActivationCostProcessor(String name, BatchTransformationRule<?, ?> rule,
516 ActivationFitnessProcessor activationFitnessProcessor) {
517 if (activationFitnessProcessors == null || activationFitnessProcessorNames == null) {
518 activationFitnessProcessors = new HashMap<BatchTransformationRule<?, ?>, ActivationFitnessProcessor>();
519 activationFitnessProcessorNames = new HashMap<BatchTransformationRule<?, ?>, String>();
520 }
521 activationFitnessProcessors.put(rule, activationFitnessProcessor);
522 activationFitnessProcessorNames.put(rule, name);
523 }
524
525 public boolean isCurentStateInTrajectory() {
526 Object currentStateId = trajectory.getCurrentStateId();
527 List<Object> stateTrajectory = trajectory.getStateTrajectory();
528 int size = stateTrajectory.size();
529 for (int i = 0; i < size - 1; i++) {
530 Object stateId = stateTrajectory.get(i);
531 if (currentStateId.equals(stateId)) {
532 return true;
533 }
534 }
535 return false;
536 }
537
538 public IStateCoder getStateCoder() {
539 return stateCoder;
540 }
541
542 private void updateActivationCodes() {
543 activationCodes.updateActivationCodes();
544 }
545
546 public long getForwardTime() {
547 return forwardTime;
548 }
549
550 public long getBacktrackingTime() {
551 return backtrackingTime;
552 }
553
554 @Override
555 public void forwardWorked(long nanos) {
556 forwardTime += nanos;
557 }
558
559 @Override
560 public void backtrackWorked(long nanos) {
561 backtrackingTime += nanos;
562 }
563}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictResolver.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictResolver.java
new file mode 100644
index 00000000..35504b56
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictResolver.java
@@ -0,0 +1,35 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2017, Andras Szabolcs Nagy and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import org.eclipse.viatra.dse.statecode.IStateCoder;
12import org.eclipse.viatra.transformation.evm.api.resolver.ChangeableConflictSet;
13import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
14
15public class DseConflictResolver implements ConflictResolver {
16
17 private ConflictResolver activationOrderingconflictResolver;
18 private IStateCoder stateCoder;
19 private DseConflictSet lastCreatedConflictSet;
20
21 public DseConflictResolver(ConflictResolver activationOrderingConflictResolver, IStateCoder stateCoder) {
22 this.activationOrderingconflictResolver = activationOrderingConflictResolver;
23 this.stateCoder = stateCoder;
24 }
25
26 @Override
27 public ChangeableConflictSet createConflictSet() {
28 lastCreatedConflictSet = new DseConflictSet(this, activationOrderingconflictResolver, stateCoder);
29 return lastCreatedConflictSet;
30 }
31
32 public DseConflictSet getLastCreatedConflictSet() {
33 return lastCreatedConflictSet;
34 }
35}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictSet.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictSet.java
new file mode 100644
index 00000000..cba595f4
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseConflictSet.java
@@ -0,0 +1,83 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2017, Andras Szabolcs Nagy and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.Set;
12
13import org.eclipse.viatra.dse.statecode.IStateCoder;
14import org.eclipse.viatra.transformation.evm.api.Activation;
15import org.eclipse.viatra.transformation.evm.api.resolver.ChangeableConflictSet;
16import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
17
18public class DseConflictSet implements ChangeableConflictSet {
19
20 private ActivationCodesConflictSet activationCodesConflictSet;
21 private ChangeableConflictSet activationOrderingConflictSet;
22 private ChangeableConflictSet prevActivationOrderingConflictSet;
23 private ConflictResolver resolver;
24
25 public DseConflictSet(ConflictResolver resolver, ConflictResolver activationOrderingConflictResolver,
26 IStateCoder stateCoder) {
27 this.resolver = resolver;
28 activationOrderingConflictSet = activationOrderingConflictResolver.createConflictSet();
29 activationCodesConflictSet = new ActivationCodesConflictSet(activationOrderingConflictSet, stateCoder);
30 }
31
32 @Override
33 public Activation<?> getNextActivation() {
34 return activationOrderingConflictSet.getNextActivation();
35 }
36
37 @Override
38 public Set<Activation<?>> getNextActivations() {
39 return activationOrderingConflictSet.getNextActivations();
40 }
41
42 @Override
43 public Set<Activation<?>> getConflictingActivations() {
44 return activationOrderingConflictSet.getConflictingActivations();
45 }
46
47 @Override
48 public ConflictResolver getConflictResolver() {
49 return resolver;
50 }
51
52 @Override
53 public boolean addActivation(Activation<?> activation) {
54 activationCodesConflictSet.addActivation(activation);
55 return activationOrderingConflictSet.addActivation(activation);
56 }
57
58 @Override
59 public boolean removeActivation(Activation<?> activation) {
60 activationCodesConflictSet.removeActivation(activation);
61 return activationOrderingConflictSet.removeActivation(activation);
62 }
63
64 public ActivationCodesConflictSet getActivationCodesConflictSet() {
65 return activationCodesConflictSet;
66 }
67
68 public void changeActivationOrderingConflictSet(ChangeableConflictSet newActivationOrderingConflictSet) {
69 for (Activation<?> activation : activationOrderingConflictSet.getConflictingActivations()) {
70 newActivationOrderingConflictSet.addActivation(activation);
71 }
72 activationCodesConflictSet.reinitWithActivations(newActivationOrderingConflictSet);
73 ChangeableConflictSet tmp = activationOrderingConflictSet;
74 activationOrderingConflictSet = newActivationOrderingConflictSet;
75 prevActivationOrderingConflictSet = tmp;
76 }
77
78 public void changeActivationOrderingConflictSetBack() {
79 ChangeableConflictSet newActivationOrderingConflictSet =
80 prevActivationOrderingConflictSet.getConflictResolver().createConflictSet();
81 changeActivationOrderingConflictSet(newActivationOrderingConflictSet);
82 }
83}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseEvmRuleBase.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseEvmRuleBase.java
new file mode 100644
index 00000000..838c1d1b
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseEvmRuleBase.java
@@ -0,0 +1,21 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2016, Andras Szabolcs Nagy and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import org.eclipse.viatra.transformation.evm.api.Agenda;
12import org.eclipse.viatra.transformation.evm.api.RuleBase;
13import org.eclipse.viatra.transformation.evm.api.event.EventRealm;
14
15public class DseEvmRuleBase extends RuleBase {
16
17 public DseEvmRuleBase(EventRealm eventRealm, Agenda agenda) {
18 super(eventRealm, agenda);
19 }
20
21}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseIdPoolHelper.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseIdPoolHelper.java
new file mode 100644
index 00000000..f6fee7be
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/DseIdPoolHelper.java
@@ -0,0 +1,68 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2016, Andras Szabolcs Nagy and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.Collection;
12import java.util.HashMap;
13import java.util.concurrent.ConcurrentHashMap;
14
15import org.eclipse.viatra.dse.api.DSEException;
16import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule;
17
18public enum DseIdPoolHelper {
19
20 INSTANCE;
21
22 public static interface IGetRuleExecutions {
23 int getRuleExecutions(BatchTransformationRule<?, ?> rule);
24 }
25
26 public static class IdProvider {
27
28 private final BatchTransformationRule<?, ?> rule;
29 private IGetRuleExecutions getRuleExecutions;
30
31 public IdProvider(IGetRuleExecutions getRuleExecutions, BatchTransformationRule<?, ?> rule) {
32 this.getRuleExecutions = getRuleExecutions;
33 this.rule = rule;
34 }
35
36 public int getId() {
37 return getRuleExecutions.getRuleExecutions(rule);
38 }
39
40 }
41
42 private ConcurrentHashMap<Thread, HashMap<BatchTransformationRule<?, ?>, IdProvider>> idProviders = new ConcurrentHashMap<>();
43
44 public int getId(BatchTransformationRule<?, ?> rule) {
45 Thread currentThread = Thread.currentThread();
46 HashMap<BatchTransformationRule<?, ?>, IdProvider> ruleMap = idProviders.get(currentThread);
47 if (ruleMap == null) {
48 throw new DSEException("There is no registered id provider");
49 }
50 IdProvider idProvider = ruleMap.get(rule);
51 return idProvider.getId();
52 }
53
54 public void registerRules(IGetRuleExecutions getRuleExecutions, Collection<BatchTransformationRule<?, ?>> rules) {
55 Thread currentThread = Thread.currentThread();
56 HashMap<BatchTransformationRule<?, ?>, IdProvider> ruleMap = new HashMap<>();
57 for (BatchTransformationRule<?, ?> rule : rules) {
58 IdProvider idProvider = new IdProvider(getRuleExecutions, rule);
59 ruleMap.put(rule, idProvider);
60 }
61 idProviders.put(currentThread, ruleMap);
62 }
63
64 public void disposeByThread() {
65 Thread currentThread = Thread.currentThread();
66 idProviders.remove(currentThread);
67 }
68}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ExplorerThread.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ExplorerThread.java
new file mode 100644
index 00000000..f2231e5c
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ExplorerThread.java
@@ -0,0 +1,88 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2014, Miklos Foldenyi, Andras Szabolcs Nagy, Abel Hegedus, Akos Horvath, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import org.apache.log4j.Logger;
12import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
13import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
14import org.eclipse.viatra.transformation.evm.api.RuleEngine;
15
16/**
17 * This class implements the {@link Runnable} interface, to able to run an exploration strategy in a separate thread. It
18 * is also responsible to initialize the exploration, start the exploration (call the {@link IStrategy#explore()}
19 * method), catch any exception during exploration and to shutdown the thread correctly.
20 *
21 * @author Földenyi Miklos & Nagy Andras Szabolcs
22 *
23 */
24public class ExplorerThread implements Runnable {
25
26 private final ThreadContext threadContext;
27
28 private IStrategy strategy;
29
30 public ExplorerThread(final ThreadContext context) {
31 this.threadContext = context;
32 strategy = threadContext.getStrategy();
33 }
34
35 /**
36 * Signals the {@link IStrategy} instance that execution should be stopped. By contract, the strategy is to
37 * stop execution at the next stage of execution where stopping and exiting is appropriate.
38 */
39 public void stopRunning() {
40 strategy.interruptStrategy();
41 }
42
43 /**
44 * Starts the design space exploration. Returns only when the {@link IStrategy#explore()} method returns.
45 */
46 public void run() {
47 GlobalContext globalContext = threadContext.getGlobalContext();
48 try {
49
50 threadContext.init();
51
52 strategy.initStrategy(threadContext);
53
54 strategy.explore();
55
56 threadContext.backtrackUntilRoot();
57
58 } catch (Throwable e) {
59 Logger.getLogger(IStrategy.class).error("Thread stopped unexpectedly!", e);
60 globalContext.registerException(e);
61 } finally {
62 globalContext.strategyFinished(this);
63 dispose();
64 }
65 }
66
67 /**
68 * Disposes of this strategy. Recursively calls dispose on the underlying {@link RuleEngine} and
69 * {@link ViatraQueryEngine}. Calling this is only required if the design space exploration was launched in thread, as
70 * the underlying engines get collected on the stop of the running {@link Thread}.
71 */
72 public void dispose() {
73 threadContext.getRuleEngine().dispose();
74 DseIdPoolHelper.INSTANCE.disposeByThread();
75 }
76
77 /**
78 * Returns the associated {@link ThreadContext} that houses all the thread specific data about the exploration
79 * process, and is also the gateway to the {@link GlobalContext} which stores data relevant to the design space
80 * exploration process as a whole.
81 *
82 * @return the relevant {@link ThreadContext}.
83 */
84 public ThreadContext getThreadContext() {
85 return threadContext;
86 }
87
88}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java
new file mode 100644
index 00000000..7325ead3
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/GlobalContext.java
@@ -0,0 +1,374 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2014, Miklos Foldenyi, Andras Szabolcs Nagy, Abel Hegedus, Akos Horvath, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.HashMap;
14import java.util.HashSet;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import java.util.concurrent.ConcurrentLinkedQueue;
19import java.util.concurrent.atomic.AtomicBoolean;
20
21import org.apache.log4j.Logger;
22import org.eclipse.emf.common.notify.Notifier;
23import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
24import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategyFactory;
25import org.eclipse.viatra.dse.designspace.api.IDesignSpace;
26import org.eclipse.viatra.dse.multithreading.DSEThreadPool;
27import org.eclipse.viatra.dse.objectives.IGlobalConstraint;
28import org.eclipse.viatra.dse.objectives.IObjective;
29import org.eclipse.viatra.dse.objectives.LeveledObjectivesHelper;
30import org.eclipse.viatra.dse.solutionstore.SolutionStore;
31import org.eclipse.viatra.dse.statecode.IStateCoderFactory;
32import org.eclipse.viatra.dse.util.EMFHelper;
33import org.eclipse.viatra.dse.visualizer.IDesignSpaceVisualizer;
34import org.eclipse.viatra.transformation.evm.api.RuleSpecification;
35import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
36import org.eclipse.viatra.transformation.evm.specific.ConflictResolvers;
37import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule;
38
39import com.google.common.base.Preconditions;
40import com.google.common.collect.ImmutableList;
41
42/**
43 * Creates new contexts for strategies. It is needed because of the multithreading.
44 *
45 * @author Andras Szabolcs Nagy
46 *
47 */
48public class GlobalContext {
49
50 // **** fields and methods for multi threading *****//
51 // *************************************************//
52
53 public enum ExplorationProcessState {
54 NOT_STARTED,
55 RUNNING,
56 STOPPING,
57 COMPLETED
58 }
59
60 private ConcurrentLinkedQueue<Throwable> exceptions = new ConcurrentLinkedQueue<Throwable>();
61
62 private volatile ExplorationProcessState state = ExplorationProcessState.NOT_STARTED;
63 private final Set<ExplorerThread> runningThreads = new HashSet<ExplorerThread>();
64 private DSEThreadPool threadPool = new DSEThreadPool();
65 private int numberOfStartedThreads = 0;
66 private IDesignSpace designSpace;
67
68 private AtomicBoolean firstThreadContextInited = new AtomicBoolean(false);
69 private AtomicBoolean firstThreadContextIniting = new AtomicBoolean(false);
70
71 private Map<RuleSpecification<?>, BatchTransformationRule<?,?>> specificationRuleMap;
72
73 private Object terminationSnycObject = new Object();
74
75 private Logger logger = Logger.getLogger(IStrategy.class);
76
77 private boolean isAlreadyInited;
78
79 public void waitForTermination() {
80 synchronized (terminationSnycObject) {
81 while (!isDone()) {
82 try {
83 terminationSnycObject.wait();
84 } catch (InterruptedException e) {
85 }
86 }
87 }
88 }
89
90 /**
91 * Starts a new thread to explore the design space.
92 *
93 * @param originalThreadContext The context of the thread which starts the new thread.
94 * @param model The model to start from.
95 * @param cloneModel It should be true in most cases.
96 * @param strategy The strategy, the thread will use.
97 * @return The {@link ExplorerThread}
98 */
99 private synchronized ExplorerThread tryStartNewThread(ThreadContext originalThreadContext, Notifier model,
100 IStrategy strategy) {
101
102 if(!isAlreadyInited) {
103 isAlreadyInited = true;
104 init();
105 }
106
107 if (state != ExplorationProcessState.COMPLETED && state != ExplorationProcessState.STOPPING
108 && threadPool.canStartNewThread()) {
109
110 ThreadContext newThreadContext = new ThreadContext(this, strategy, model);
111
112 // TODO : clone undo list? slave strategy can't go further back...
113 ExplorerThread explorerThread = new ExplorerThread(newThreadContext);
114 newThreadContext.setExplorerThread(explorerThread);
115
116 boolean isSuccessful = threadPool.tryStartNewStrategy(explorerThread);
117
118 if (isSuccessful) {
119 runningThreads.add(explorerThread);
120
121 state = ExplorationProcessState.RUNNING;
122 ++numberOfStartedThreads;
123
124 logger.info("New thread started, active threads: " + runningThreads.size());
125
126 return explorerThread;
127 }
128 }
129 return null;
130 }
131
132 public synchronized ExplorerThread tryStartNewThread(ThreadContext originalThreadContext, IStrategy strategy) {
133 return tryStartNewThread(originalThreadContext, EMFHelper.clone(originalThreadContext.getModel()), strategy);
134 }
135
136 public synchronized ExplorerThread tryStartNewThreadWithoutModelClone(ThreadContext originalThreadContext,
137 IStrategy strategy) {
138 return tryStartNewThread(originalThreadContext, originalThreadContext.getModel(), strategy);
139 }
140
141 public synchronized ExplorerThread startFirstThread(IStrategy strategy, Notifier model) {
142 Preconditions.checkState(!isAlreadyInited, "First thread is already started.");
143 return tryStartNewThread(null, EMFHelper.clone(model), strategy);
144 }
145
146 public synchronized ExplorerThread startFirstThreadWithoutModelClone(IStrategy strategy, Notifier model) {
147 Preconditions.checkState(!isAlreadyInited, "First thread is already started.");
148 return tryStartNewThread(null, model, strategy);
149 }
150
151 public synchronized void startAllThreads(ThreadContext originalThreadContext, IStrategyFactory strategyFactory) {
152 while (canStartNewThread()) {
153 tryStartNewThread(originalThreadContext, strategyFactory.createStrategy());
154 }
155 }
156
157 /**
158 * Starts a new thread to explore the design space.
159 *
160 * @param strategyBase
161 * The {@link Strategy}.
162 * @param tedToClone
163 * The model to clone. Hint: context.getTed()
164 */
165
166 public synchronized void strategyFinished(ExplorerThread strategy) {
167 runningThreads.remove(strategy);
168
169 logger.info("Thread finished, active threads: " + runningThreads.size());
170
171 // is the first part necessary?
172 if (runningThreads.isEmpty()) {
173 state = ExplorationProcessState.COMPLETED;
174 threadPool.shutdown();
175
176 // if the main thread (which started the exploration)
177 // is waiting for the solution, than wake it up
178 synchronized (terminationSnycObject) {
179 terminationSnycObject.notify();
180 logger.info("Exploration terminated.");
181 }
182
183 }
184 }
185
186 public synchronized boolean isDone() {
187 return state == ExplorationProcessState.COMPLETED && runningThreads.isEmpty();
188 }
189
190 public synchronized boolean isNotStarted() {
191 return state == ExplorationProcessState.NOT_STARTED;
192 }
193
194 public boolean canStartNewThread() {
195 return (state == ExplorationProcessState.NOT_STARTED || state == ExplorationProcessState.RUNNING)
196 && threadPool.canStartNewThread();
197 }
198
199 public synchronized void stopAllThreads() {
200 if (state == ExplorationProcessState.RUNNING) {
201 state = ExplorationProcessState.STOPPING;
202 logger.info("Stopping all threads.");
203 for (ExplorerThread strategy : runningThreads) {
204 strategy.stopRunning();
205 }
206 }
207 }
208
209 public void registerException(Throwable e) {
210 exceptions.add(e);
211 }
212
213 // ******* fields and methods for exploration *******//
214 // **************************************************//
215
216 private List<IObjective> objectives = new ArrayList<IObjective>();
217 private IObjective[][] leveledObjectives;
218 private List<IGlobalConstraint> globalConstraints = new ArrayList<IGlobalConstraint>();
219 private Set<BatchTransformationRule<?, ?>> transformations = new HashSet<BatchTransformationRule<?, ?>>();
220 private IStateCoderFactory stateCoderFactory;
221 private SolutionStore solutionStore = new SolutionStore(1);
222 private Object sharedObject;
223 private List<IDesignSpaceVisualizer> visualizers;
224
225 private ConflictResolver conflictResolver = ConflictResolvers.createArbitraryResolver();
226
227 private void init() {
228 leveledObjectives = new LeveledObjectivesHelper(objectives).initLeveledObjectives();
229
230 specificationRuleMap = new HashMap<>();
231 for (BatchTransformationRule<?,?> rule : transformations) {
232 specificationRuleMap.put(rule.getRuleSpecification(), rule);
233 }
234 }
235
236 public List<IDesignSpaceVisualizer> getVisualizers() {
237 return ImmutableList.copyOf(visualizers);
238 }
239
240 public void registerDesignSpaceVisualizer(IDesignSpaceVisualizer visualizer) {
241 if (visualizer == null) {
242 return;
243 }
244 if (visualizers == null) {
245 visualizers = new ArrayList<IDesignSpaceVisualizer>();
246 }
247 visualizers.add(visualizer);
248 }
249
250 public void deregisterDesignSpaceVisualizer(IDesignSpaceVisualizer visualizer) {
251 if (visualizer == null) {
252 return;
253 }
254 if (visualizers != null) {
255 visualizers.remove(visualizer);
256 }
257 }
258
259 public boolean isDesignSpaceVisualizerRegistered(IDesignSpaceVisualizer visualizer) {
260 if (visualizers != null) {
261 return visualizers.contains(visualizer);
262 }
263 return false;
264 }
265
266 public void initVisualizersForThread(ThreadContext threadContext) {
267 if (visualizers != null && !visualizers.isEmpty()) {
268 for (IDesignSpaceVisualizer visualizer : visualizers) {
269 visualizer.init(threadContext);
270 threadContext.getDesignSpaceManager().registerExploreEventHandler(visualizer);
271 }
272 }
273 }
274
275 public boolean isExceptionHappendInOtherThread() {
276 return !exceptions.isEmpty();
277 }
278
279 public Collection<Throwable> getExceptions() {
280 return exceptions;
281 }
282
283 public IStateCoderFactory getStateCoderFactory() {
284 return stateCoderFactory;
285 }
286
287 public void setStateCoderFactory(IStateCoderFactory stateCoderFactory) {
288 this.stateCoderFactory = stateCoderFactory;
289 }
290
291 public Set<BatchTransformationRule<?, ?>> getTransformations() {
292 return transformations;
293 }
294
295 public void setTransformations(Set<BatchTransformationRule<?, ?>> transformations) {
296 this.transformations = transformations;
297 }
298
299 public DSEThreadPool getThreadPool() {
300 return threadPool;
301 }
302
303 public IDesignSpace getDesignSpace() {
304 return designSpace;
305 }
306
307 public void setDesignSpace(IDesignSpace designSpace) {
308 this.designSpace = designSpace;
309 }
310
311 public int getNumberOfStartedThreads() {
312 return numberOfStartedThreads;
313 }
314
315 public Object getSharedObject() {
316 return sharedObject;
317 }
318
319 public void setSharedObject(Object sharedObject) {
320 this.sharedObject = sharedObject;
321 }
322
323 public ExplorationProcessState getState() {
324 return state;
325 }
326
327 public List<IObjective> getObjectives() {
328 return objectives;
329 }
330
331 public void setObjectives(List<IObjective> objectives) {
332 this.objectives = objectives;
333 }
334
335 public List<IGlobalConstraint> getGlobalConstraints() {
336 return globalConstraints;
337 }
338
339 public void setGlobalConstraints(List<IGlobalConstraint> globalConstraints) {
340 this.globalConstraints = globalConstraints;
341 }
342
343 AtomicBoolean getFirstThreadContextInited() {
344 return firstThreadContextInited;
345 }
346
347 AtomicBoolean getFirstThreadContextIniting() {
348 return firstThreadContextIniting;
349 }
350
351 public IObjective[][] getLeveledObjectives() {
352 return leveledObjectives;
353 }
354
355 public void setSolutionStore(SolutionStore solutionStore) {
356 this.solutionStore = solutionStore;
357 }
358
359 public SolutionStore getSolutionStore() {
360 return solutionStore;
361 }
362
363 public Map<RuleSpecification<?>, BatchTransformationRule<?, ?>> getSpecificationRuleMap() {
364 return specificationRuleMap;
365 }
366
367 public void setConflictResolver(ConflictResolver conflictResolver) {
368 this.conflictResolver = conflictResolver;
369 }
370
371 public ConflictResolver getConflictResolver() {
372 return conflictResolver;
373 }
374}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/IDseStrategyContext.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/IDseStrategyContext.java
new file mode 100644
index 00000000..d630964f
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/IDseStrategyContext.java
@@ -0,0 +1,117 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2016, Andras Szabolcs Nagy, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.Collection;
12import java.util.List;
13import java.util.Set;
14
15import org.eclipse.emf.common.notify.Notifier;
16import org.eclipse.emf.edit.domain.EditingDomain;
17import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
18import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategyFactory;
19import org.eclipse.viatra.dse.designspace.api.IDesignSpace;
20import org.eclipse.viatra.dse.designspace.api.TrajectoryInfo;
21import org.eclipse.viatra.dse.objectives.Fitness;
22import org.eclipse.viatra.dse.objectives.IGlobalConstraint;
23import org.eclipse.viatra.dse.objectives.IObjective;
24import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
25import org.eclipse.viatra.dse.solutionstore.SolutionStore;
26import org.eclipse.viatra.dse.statecode.IStateCoder;
27import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
28import org.eclipse.viatra.transformation.evm.api.Activation;
29import org.eclipse.viatra.transformation.evm.api.RuleEngine;
30import org.eclipse.viatra.transformation.evm.api.RuleSpecification;
31import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule;
32
33/**
34 * This interface is only to overview the required methods for exploration strategies. It is not used explicitly.
35 *
36 * @author Andras Szabolcs Nagy
37 *
38 */
39public interface IDseStrategyContext {
40
41 void init();
42
43 Notifier getModel();
44 EditingDomain getEditingDomain();
45 ViatraQueryEngine getQueryEngine();
46 RuleEngine getRuleEngine();
47 IStrategy getStrategy();
48 ExplorerThread getExplorerThread();
49 List<IObjective> getObjectives();
50 IObjective[][] getLeveledObjectives();
51 List<IGlobalConstraint> getGlobalConstraints();
52
53 SolutionStore getSolutionStore();
54 void newSolution();
55// TODO void newSolution(TrajectoryFitness trajectoryFitness);
56
57
58 ObjectiveComparatorHelper getObjectiveComparatorHelper();
59
60 GlobalContext getGlobalContext();
61 Set<BatchTransformationRule<?, ?>> getRules();
62 BatchTransformationRule<?, ?> getRuleByRuleSpecification(RuleSpecification<?> ruleSpecification);
63 ExplorerThread tryStartNewThread(IStrategy strategy); /*IDseStrategyContext originalContext*/
64 ExplorerThread tryStartNewThreadWithoutModelClone(IStrategy strategy);
65 void startAllThreads(IStrategyFactory strategyFactory);
66 Object getSharedObject();
67 void setSharedObject(Object sharedObject);
68
69
70 DesignSpaceManager getDesignSpaceManager();
71 IStateCoder getStateCoder();
72 IDesignSpace getDesignSpace();
73 TrajectoryInfo getTrajectoryInfo();
74 List<Object> getTrajectory();
75 List<Object> getTrajectoryCopied();
76 int getDepth();
77 Object getCurrentStateId();
78
79 Object getTransitionByActivation(Activation<?> activation);
80 Activation<?> getActivationById(Object activationId);
81 BatchTransformationRule<?, ?> getRuleByActivation(Activation<?> activation);
82 BatchTransformationRule<?, ?> getRuleByActivationId(Object activationId);
83
84 Collection<Object> getCurrentActivationIds();
85 Collection<Object> getUntraversedActivationIds();
86// TODO Object getArbitraryActivationId();
87// TODO Object getArbitraryUntraversedActivationId();
88
89 void executeAcitvationId(Object activationId);
90 boolean tryExecuteAcitvationId(Object activationId);
91 boolean executeRandomActivationId();
92 void executeTrajectory(Object[] activationIds);
93 void executeTrajectory(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex);
94 int executeTrajectoryByTrying(Object[] activationIds);
95 int executeTrajectoryByTrying(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex);
96 int executeTrajectoryWithoutStateCoding(Object[] activationIds);
97 int executeTrajectoryWithoutStateCoding(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex);
98 int executeTrajectoryByTryingWithoutStateCoding(Object[] activationIds);
99 int executeTrajectoryByTryingWithoutStateCoding(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex);
100 void executeTrajectoryWithMinimalBacktrack(Object[] trajectory);
101 void executeTrajectoryWithMinimalBacktrack(Object[] trajectory, int toExcludedIndex);
102 void executeTrajectoryWithMinimalBacktrackWithoutStateCoding(Object[] trajectory);
103 void executeTrajectoryWithMinimalBacktrackWithoutStateCoding(Object[] trajectory, int toExcludedIndex);
104
105 boolean backtrack();
106 // TODO int backtrack(int times);
107 void backtrackUntilLastCommonActivation(Object[] trajectory);
108 void backtrackUntilRoot();
109
110 Fitness calculateFitness();
111 Fitness getLastFitness();
112 boolean checkGlobalConstraints();
113 boolean isCurrentStateAlreadyTraversed();
114 // this needs states stored:
115 boolean isCurrentStateInTrajectory();
116
117}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/SingletonSetConflictResolver.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/SingletonSetConflictResolver.java
new file mode 100644
index 00000000..8c0a715a
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/SingletonSetConflictResolver.java
@@ -0,0 +1,53 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2016, Andras Szabolcs Nagy, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import org.eclipse.viatra.transformation.evm.api.RuleEngine;
12import org.eclipse.viatra.transformation.evm.api.resolver.ChangeableConflictSet;
13import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
14
15/**
16 *
17 * @author Andras Szabolcs Nagy
18 *
19 */
20public class SingletonSetConflictResolver implements ConflictResolver {
21
22 protected ChangeableConflictSet conflictSet;
23 protected ConflictResolver conflictResolver;
24 protected ConflictResolver prevConflictResolver;
25 protected RuleEngine ruleEngine;
26
27 public SingletonSetConflictResolver(ConflictResolver conflictResolver) {
28 this.conflictResolver = conflictResolver;
29 conflictSet = conflictResolver.createConflictSet();
30 }
31
32 @Override
33 public ChangeableConflictSet createConflictSet() {
34 return conflictSet;
35 }
36
37 public void changeConflictResolver(ConflictResolver conflictResolver) {
38 ConflictResolver tmp = this.conflictResolver;
39 this.conflictResolver = conflictResolver;
40 prevConflictResolver = tmp;
41 conflictSet = conflictResolver.createConflictSet();
42 ruleEngine.setConflictResolver(this);
43 }
44
45 public void changeConflictResolverBack() {
46 changeConflictResolver(prevConflictResolver);
47 }
48
49 public void setRuleEngine(RuleEngine ruleEngine) {
50 this.ruleEngine = ruleEngine;
51 ruleEngine.setConflictResolver(this);
52 }
53}
diff --git a/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java
new file mode 100644
index 00000000..b62442ce
--- /dev/null
+++ b/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java
@@ -0,0 +1,542 @@
1/*******************************************************************************
2 * Copyright (c) 2010-2014, Miklos Foldenyi, Andras Szabolcs Nagy, Abel Hegedus, Akos Horvath, Zoltan Ujhelyi and Daniel Varro
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v. 2.0 which is available at
5 * http://www.eclipse.org/legal/epl-v20.html.
6 *
7 * SPDX-License-Identifier: EPL-2.0
8 *******************************************************************************/
9package org.eclipse.viatra.dse.base;
10
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.List;
14import java.util.Set;
15import java.util.concurrent.atomic.AtomicBoolean;
16
17import org.apache.log4j.Logger;
18import org.eclipse.emf.common.notify.Notifier;
19import org.eclipse.emf.edit.domain.EditingDomain;
20import org.eclipse.viatra.dse.api.DSEException;
21import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy;
22import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategyFactory;
23import org.eclipse.viatra.dse.designspace.api.IDesignSpace;
24import org.eclipse.viatra.dse.designspace.api.TrajectoryInfo;
25import org.eclipse.viatra.dse.objectives.Fitness;
26import org.eclipse.viatra.dse.objectives.IGlobalConstraint;
27import org.eclipse.viatra.dse.objectives.IObjective;
28import org.eclipse.viatra.dse.objectives.ObjectiveComparatorHelper;
29import org.eclipse.viatra.dse.solutionstore.SolutionStore;
30import org.eclipse.viatra.dse.statecode.IStateCoder;
31import org.eclipse.viatra.dse.util.EMFHelper;
32import org.eclipse.viatra.query.runtime.api.IPatternMatch;
33import org.eclipse.viatra.query.runtime.api.ViatraQueryEngine;
34import org.eclipse.viatra.query.runtime.emf.EMFScope;
35import org.eclipse.viatra.query.runtime.exception.ViatraQueryException;
36import org.eclipse.viatra.query.runtime.matchers.util.Preconditions;
37import org.eclipse.viatra.transformation.evm.api.Activation;
38import org.eclipse.viatra.transformation.evm.api.RuleEngine;
39import org.eclipse.viatra.transformation.evm.api.RuleSpecification;
40import org.eclipse.viatra.transformation.evm.api.event.EventFilter;
41import org.eclipse.viatra.transformation.evm.api.resolver.ChangeableConflictSet;
42import org.eclipse.viatra.transformation.evm.api.resolver.ConflictResolver;
43import org.eclipse.viatra.transformation.evm.api.resolver.ConflictSet;
44import org.eclipse.viatra.transformation.evm.specific.RuleEngines;
45import org.eclipse.viatra.transformation.runtime.emf.rules.batch.BatchTransformationRule;
46
47/**
48 * This class holds all the information that is related to a single processing thread of the DesignSpaceExploration
49 * process. For any attributes related to the Design Space Exploration process as a whole, see {@link GlobalContext}.
50 *
51 * @author Miklos Foldenyi
52 *
53 */
54public class ThreadContext implements IDseStrategyContext{
55
56 private final GlobalContext globalContext;
57 private final IStrategy strategy;
58 private ExplorerThread explorerThread;
59 private RuleEngine ruleEngine;
60 private ViatraQueryEngine queryEngine;
61 private EditingDomain domain;
62 private Notifier model;
63 private DesignSpaceManager designSpaceManager;
64 private List<IObjective> objectives;
65 private List<IGlobalConstraint> globalConstraints;
66 private Fitness lastFitness;
67 private ObjectiveComparatorHelper objectiveComparatorHelper;
68 private IStateCoder stateCoder;
69 private DseConflictResolver dseConflictResolver;
70 private DseConflictSet dseConflictSet;
71 private ActivationCodesConflictSet activationCodesConflictSet;
72
73 /**
74 * This value is true after the {@link ThreadContext} has been initialized in it's own thread.
75 */
76 private AtomicBoolean inited = new AtomicBoolean(false);
77
78 private boolean isFirstThread = false;
79 private IObjective[][] leveledObjectives;
80
81 private static class GetRuleExecutionsImpl implements DseIdPoolHelper.IGetRuleExecutions {
82
83 private List<BatchTransformationRule<?, ?>> executedRules;
84
85 public GetRuleExecutionsImpl(List<BatchTransformationRule<?, ?>> executedRulesView) {
86 this.executedRules = executedRulesView;
87 }
88
89 @Override
90 public int getRuleExecutions(BatchTransformationRule<?, ?> rule) {
91 int nextId = 0;
92 for (BatchTransformationRule<?, ?> r : executedRules) {
93 if (r.equals(rule)) {
94 nextId ++;
95 }
96 }
97 return nextId;
98 }
99
100 }
101
102 public DseConflictResolver getConflictResolver() {
103 return dseConflictResolver;
104 }
105
106 public ConflictSet getConflictSet() {
107 return dseConflictSet;
108 }
109
110 /**
111 * Creates a {@link ThreadContext} and sets it up to be initialized on the given {@link TransactionalEditingDomain}
112 *
113 * @param globalContext
114 * @param strategyBase
115 * @param domain
116 * @param trajectoryInfoToClone
117 * @param parentGuidance
118 */
119 public ThreadContext(final GlobalContext globalContext, IStrategy strategy, Notifier model) {
120 Preconditions.checkArgument(model != null, "Cannot initialize ThreadContext on a null model.");
121 this.globalContext = globalContext;
122 this.strategy = strategy;
123 this.model = model;
124 }
125
126 /**
127 * Initializes the {@link ThreadContext} by initializing the underlying {@link ViatraQueryEngine} and
128 * {@link RuleEngine}. {@link Guidance} initialization is also happening within this method.
129 *
130 * @throws DSEException
131 */
132 public void init() {
133
134 AtomicBoolean isFirst = globalContext.getFirstThreadContextIniting();
135 AtomicBoolean isFirstReady = globalContext.getFirstThreadContextInited();
136 if (!isFirstReady.get()) {
137 if (!isFirst.compareAndSet(false, true)) {
138 try {
139 do {
140 Thread.sleep(5);
141 } while (!isFirstReady.get());
142 } catch (InterruptedException e) {
143 }
144 } else {
145 isFirstThread = true;
146 }
147 }
148 // prohibit re-initialization
149 Preconditions.checkArgument(!inited.getAndSet(true), "This Thread context has been initialized already!");
150
151 try {
152 // initialize query engine
153 final EMFScope scope = new EMFScope(model);
154 queryEngine = ViatraQueryEngine.on(scope);
155
156
157 stateCoder = getGlobalContext().getStateCoderFactory().createStateCoder();
158 stateCoder.init(model);
159 stateCoder.createStateCode();
160
161 ConflictResolver activationOrderingCconflictResolver = globalContext.getConflictResolver();
162 dseConflictResolver = new DseConflictResolver(activationOrderingCconflictResolver, stateCoder);
163
164 ruleEngine = RuleEngines.createViatraQueryRuleEngine(queryEngine);
165 ruleEngine.setConflictResolver(dseConflictResolver);
166 for (BatchTransformationRule<?, ?> tr : globalContext.getTransformations()) {
167 ruleEngine.addRule(tr.getRuleSpecification(), (EventFilter<IPatternMatch>) tr.getFilter());
168 }
169 dseConflictSet = dseConflictResolver.getLastCreatedConflictSet();
170 activationCodesConflictSet = dseConflictSet.getActivationCodesConflictSet();
171 activationCodesConflictSet.updateActivationCodes();
172
173
174 } catch (ViatraQueryException e) {
175 throw new DSEException("Failed to create unmanaged ViatraQueryEngine on the model.", e);
176 }
177
178 if (isFirstThread) {
179
180 objectives = globalContext.getObjectives();
181 leveledObjectives = globalContext.getLeveledObjectives();
182 globalConstraints = globalContext.getGlobalConstraints();
183
184 } else {
185 objectives = new ArrayList<IObjective>();
186
187 IObjective[][] leveledObjectivesToCopy = globalContext.getLeveledObjectives();
188 leveledObjectives = new IObjective[leveledObjectivesToCopy.length][];
189 for (int i = 0; i < leveledObjectivesToCopy.length; i++) {
190 leveledObjectives[i] = new IObjective[leveledObjectivesToCopy[i].length];
191 for (int j = 0; j < leveledObjectivesToCopy[i].length; j++) {
192 leveledObjectives[i][j] = leveledObjectivesToCopy[i][j].createNew();
193 objectives.add(leveledObjectives[i][j]);
194 }
195 }
196
197 globalConstraints = new ArrayList<IGlobalConstraint>();
198 for (IGlobalConstraint globalConstraint : globalContext.getGlobalConstraints()) {
199 globalConstraints.add(globalConstraint.createNew());
200 }
201
202 }
203 // create the thread specific DesignSpaceManager
204 this.domain = EMFHelper.createEditingDomain(model);
205 designSpaceManager = new DesignSpaceManager(this);
206
207 boolean isThereHardObjective = false;
208 for (IObjective objective : objectives) {
209 objective.init(this);
210 if (objective.isHardObjective()) {
211 isThereHardObjective = true;
212 }
213 }
214 if (!isThereHardObjective) {
215 Logger.getLogger(IStrategy.class).warn(
216 "No hard objective is specified: all reachable state is a solution. Use a dummy hard objective to be explicit.");
217 }
218
219 for (IGlobalConstraint globalConstraint : globalConstraints) {
220 globalConstraint.init(this);
221 }
222
223 DseIdPoolHelper.INSTANCE.registerRules(new GetRuleExecutionsImpl(getDesignSpaceManager().getTrajectoryInfo().getRules()), getRules());
224
225 globalContext.initVisualizersForThread(this);
226
227 if (isFirstThread) {
228 isFirstReady.set(true);
229 }
230
231 }
232
233 public Fitness calculateFitness() {
234 Fitness result = new Fitness();
235
236 boolean satisifiesHardObjectives = true;
237
238 for (IObjective objective : objectives) {
239 Double fitness = objective.getFitness(this);
240 result.put(objective.getName(), fitness);
241 if (objective.isHardObjective() && !objective.satisifiesHardObjective(fitness)) {
242 satisifiesHardObjectives = false;
243 }
244 }
245
246 result.setSatisifiesHardObjectives(satisifiesHardObjectives);
247
248 lastFitness = result;
249
250 return result;
251 }
252
253 public boolean checkGlobalConstraints() {
254 for (IGlobalConstraint globalConstraint : globalContext.getGlobalConstraints()) {
255 if (!globalConstraint.checkGlobalConstraint(this)) {
256 return false;
257 }
258 }
259 return true;
260 }
261
262 public RuleEngine getRuleEngine() {
263 return ruleEngine;
264 }
265
266 public GlobalContext getGlobalContext() {
267 return globalContext;
268 }
269
270 public DesignSpaceManager getDesignSpaceManager() {
271 return designSpaceManager;
272 }
273
274 public EditingDomain getEditingDomain() {
275 return domain;
276 }
277
278 public Notifier getModel() {
279 return model;
280 }
281
282 public ViatraQueryEngine getQueryEngine() {
283 return queryEngine;
284 }
285
286 public IStrategy getStrategy() {
287 return strategy;
288 }
289
290 public ExplorerThread getExplorerThread() {
291 return explorerThread;
292 }
293
294 public void setExplorerThread(ExplorerThread explorerThread) {
295 this.explorerThread = explorerThread;
296 }
297
298 public Fitness getLastFitness() {
299 return lastFitness;
300 }
301
302 public ObjectiveComparatorHelper getObjectiveComparatorHelper() {
303 if (objectiveComparatorHelper == null) {
304 objectiveComparatorHelper = new ObjectiveComparatorHelper(leveledObjectives);
305 }
306 return objectiveComparatorHelper;
307 }
308
309 public IObjective[][] getLeveledObjectives() {
310 return leveledObjectives;
311 }
312
313 public List<IObjective> getObjectives() {
314 return objectives;
315 }
316
317 public List<IGlobalConstraint> getGlobalConstraints() {
318 return globalConstraints;
319 }
320
321 @Override
322 public SolutionStore getSolutionStore() {
323 return globalContext.getSolutionStore();
324 }
325
326 @Override
327 public void newSolution() {
328 globalContext.getSolutionStore().newSolution(this);
329 }
330
331 @Override
332 public Object getSharedObject() {
333 return globalContext.getSharedObject();
334 }
335
336 @Override
337 public void setSharedObject(Object sharedObject) {
338 globalContext.setSharedObject(sharedObject);
339 }
340
341 @Override
342 public Set<BatchTransformationRule<?, ?>> getRules() {
343 return globalContext.getTransformations();
344 }
345
346 @Override
347 public BatchTransformationRule<?, ?> getRuleByRuleSpecification(RuleSpecification<?> ruleSpecification) {
348 return globalContext.getSpecificationRuleMap().get(ruleSpecification);
349 }
350
351 @Override
352 public ExplorerThread tryStartNewThread(IStrategy strategy) {
353 return globalContext.tryStartNewThread(this, strategy);
354 }
355
356 @Override
357 public ExplorerThread tryStartNewThreadWithoutModelClone(IStrategy strategy) {
358 return globalContext.tryStartNewThreadWithoutModelClone(this, strategy);
359 }
360
361 @Override
362 public void startAllThreads(IStrategyFactory strategyFactory) {
363 globalContext.startAllThreads(this, strategyFactory);
364 }
365
366 @Override
367 public IStateCoder getStateCoder() {
368 return stateCoder;
369 }
370
371 @Override
372 public IDesignSpace getDesignSpace() {
373 return globalContext.getDesignSpace();
374 }
375
376 @Override
377 public TrajectoryInfo getTrajectoryInfo() {
378 return designSpaceManager.getTrajectoryInfo();
379 }
380
381 @Override
382 public List<Object> getTrajectory() {
383 return designSpaceManager.getTrajectoryInfo().getTrajectory();
384 }
385
386 @Override
387 public List<Object> getTrajectoryCopied() {
388 return new ArrayList<Object>(getTrajectory());
389 }
390
391 @Override
392 public int getDepth() {
393 return designSpaceManager.getTrajectoryInfo().getDepth();
394 }
395
396 @Override
397 public Object getCurrentStateId() {
398 return designSpaceManager.getTrajectoryInfo().getCurrentStateId();
399 }
400
401 @Override
402 public Object getTransitionByActivation(Activation<?> activation) {
403 return designSpaceManager.getTransitionByActivation(activation);
404 }
405
406 @Override
407 public Activation<?> getActivationById(Object activationId) {
408 return designSpaceManager.getActivationById(activationId);
409 }
410
411 @Override
412 public BatchTransformationRule<?, ?> getRuleByActivation(Activation<?> activation) {
413 return designSpaceManager.getRuleByActivation(activation);
414 }
415
416 @Override
417 public BatchTransformationRule<?, ?> getRuleByActivationId(Object activationId) {
418 return designSpaceManager.getRuleByActivationId(activationId);
419 }
420
421 @Override
422 public Collection<Object> getCurrentActivationIds() {
423 return designSpaceManager.getTransitionsFromCurrentState();
424 }
425
426 @Override
427 public Collection<Object> getUntraversedActivationIds() {
428 return designSpaceManager.getUntraversedTransitionsFromCurrentState();
429 }
430
431 @Override
432 public void executeAcitvationId(Object activationId) {
433 designSpaceManager.fireActivation(activationId);
434 }
435
436 @Override
437 public boolean tryExecuteAcitvationId(Object activationId) {
438 return designSpaceManager.tryFireActivation(activationId);
439 }
440
441 @Override
442 public boolean executeRandomActivationId() {
443 return designSpaceManager.executeRandomActivationId();
444 }
445
446 @Override
447 public void executeTrajectory(Object[] activationIds) {
448 designSpaceManager.executeTrajectory(activationIds);
449 }
450
451 @Override
452 public void executeTrajectory(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex) {
453 designSpaceManager.executeTrajectory(activationIds, fromIncludedIndex, toExcludedIndex);
454 }
455
456 @Override
457 public int executeTrajectoryByTrying(Object[] activationIds) {
458 return designSpaceManager.executeTrajectoryByTrying(activationIds);
459 }
460
461 @Override
462 public int executeTrajectoryByTrying(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex) {
463 return designSpaceManager.executeTrajectoryByTrying(activationIds, fromIncludedIndex, toExcludedIndex);
464 }
465
466 @Override
467 public int executeTrajectoryWithoutStateCoding(Object[] activationIds) {
468 return designSpaceManager.executeTrajectoryWithoutStateCoding(activationIds);
469 }
470
471 @Override
472 public int executeTrajectoryWithoutStateCoding(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex) {
473 return designSpaceManager.executeTrajectoryWithoutStateCoding(activationIds, fromIncludedIndex, toExcludedIndex);
474 }
475
476 @Override
477 public int executeTrajectoryByTryingWithoutStateCoding(Object[] activationIds) {
478 return designSpaceManager.executeTrajectoryByTryingWithoutStateCoding(activationIds);
479 }
480
481 @Override
482 public int executeTrajectoryByTryingWithoutStateCoding(Object[] activationIds, int fromIncludedIndex, int toExcludedIndex) {
483 return designSpaceManager.executeTrajectoryByTryingWithoutStateCoding(activationIds, fromIncludedIndex, toExcludedIndex);
484 }
485
486 @Override
487 public void executeTrajectoryWithMinimalBacktrack(Object[] trajectory) {
488 designSpaceManager.executeTrajectoryWithMinimalBacktrack(trajectory);
489 }
490
491 @Override
492 public void executeTrajectoryWithMinimalBacktrack(Object[] trajectory, int toExcludedIndex) {
493 designSpaceManager.executeTrajectoryWithMinimalBacktrack(trajectory, toExcludedIndex);
494 }
495
496 @Override
497 public void executeTrajectoryWithMinimalBacktrackWithoutStateCoding(Object[] trajectory) {
498 designSpaceManager.executeTrajectoryWithMinimalBacktrackWithoutStateCoding(trajectory);
499 }
500
501 @Override
502 public void executeTrajectoryWithMinimalBacktrackWithoutStateCoding(Object[] trajectory, int toExcludedIndex) {
503 designSpaceManager.executeTrajectoryWithMinimalBacktrackWithoutStateCoding(trajectory, toExcludedIndex);
504 }
505
506 @Override
507 public boolean backtrack() {
508 return designSpaceManager.undoLastTransformation();
509 }
510
511 @Override
512 public void backtrackUntilLastCommonActivation(Object[] trajectory) {
513 designSpaceManager.backtrackUntilLastCommonActivation(trajectory);
514 }
515
516 @Override
517 public void backtrackUntilRoot() {
518 designSpaceManager.undoUntilRoot();
519 }
520
521 @Override
522 public boolean isCurrentStateAlreadyTraversed() {
523 return designSpaceManager.isNewModelStateAlreadyTraversed();
524 }
525
526 @Override
527 public boolean isCurrentStateInTrajectory() {
528 return designSpaceManager.isCurentStateInTrajectory();
529 }
530
531 public ActivationCodesConflictSet getActivationCodesConflictSet() {
532 return activationCodesConflictSet;
533 }
534
535 public void changeActivationOrdering(ChangeableConflictSet activationOrderingConflictSet) {
536 this.dseConflictSet.changeActivationOrderingConflictSet(activationOrderingConflictSet);
537 }
538
539 public void changeActivationOrderingBack() {
540 this.dseConflictSet.changeActivationOrderingConflictSetBack();
541 }
542}