aboutsummaryrefslogtreecommitdiffstats
path: root/Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java
diff options
context:
space:
mode:
Diffstat (limited to 'Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java')
-rw-r--r--Solvers/VIATRA-Solver/org.eclipse.viatra.dse/src/org/eclipse/viatra/dse/base/ThreadContext.java542
1 files changed, 542 insertions, 0 deletions
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}