aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/store-dse/src/main/java/tools/refinery/store/dse/strategy/BestFirstStrategy.java
blob: 92d878ce982c0f15c89de6ae6548e0fdcab39b3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*******************************************************************************
 * Copyright (c) 2010-2016, Andras Szabolcs Nagy, Zoltan Ujhelyi and Daniel Varro
 * Copyright (c) 2023 The Refinery Authors <https://refinery.tools/>
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-v20.html.
 *
 * SPDX-License-Identifier: EPL-2.0
 *******************************************************************************/
package tools.refinery.store.dse.strategy;

import tools.refinery.store.map.Version;
import tools.refinery.store.dse.DesignSpaceExplorationAdapter;
import tools.refinery.store.dse.Strategy;
import tools.refinery.store.dse.internal.Activation;
import tools.refinery.store.dse.objectives.Fitness;
import tools.refinery.store.dse.objectives.ObjectiveComparatorHelper;

import java.util.*;

public class BestFirstStrategy implements Strategy {

	private DesignSpaceExplorationAdapter dseAdapter;

	private int maxDepth = Integer.MAX_VALUE;
	private int maxSolutions = Integer.MAX_VALUE;
	private boolean backTrackIfSolution = true;
	private boolean onlyBetterFirst = false;

	private PriorityQueue<TrajectoryWithFitness> trajectoriesToExplore;

	private record TrajectoryWithFitness(List<Version> trajectory, Fitness fitness) {
		@Override
		public String toString() {
				return trajectory.toString() + fitness.toString();
			}

		@Override
		public int hashCode() {
			return trajectory.get(trajectory.size() - 1).hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (obj instanceof TrajectoryWithFitness other) {
				return Objects.equals(trajectory.get(trajectory.size() - 1), other.trajectory.get(other.trajectory.size() - 1));
//				return trajectory.equals(((TrajectoryWithFitness) obj).trajectory);
			}
			return false;
		}
	}

	public BestFirstStrategy withDepthLimit(int maxDepth) {
		if (maxDepth >= 0) {
			this.maxDepth = maxDepth;
		}
		return this;
	}

	public BestFirstStrategy withSolutionLimit(int maxSolutions) {
		if (maxSolutions >= 0) {
			this.maxSolutions = maxSolutions;
		}
		return this;
	}

	public BestFirstStrategy continueIfHardObjectivesFulfilled() {
		backTrackIfSolution = false;
		return this;
	}

	public BestFirstStrategy goOnOnlyIfFitnessIsBetter() {
		onlyBetterFirst = true;
		return this;
	}

	@Override
	public void initialize(DesignSpaceExplorationAdapter designSpaceExplorationAdapter) {
		this.dseAdapter = designSpaceExplorationAdapter;
		final ObjectiveComparatorHelper objectiveComparatorHelper = dseAdapter.getObjectiveComparatorHelper();

		trajectoriesToExplore = new PriorityQueue<>(11,
				(o1, o2) -> objectiveComparatorHelper.compare(o2.fitness, o1.fitness));
	}

	@Override
	public void explore() {
		if (maxSolutions == 0) {
			return;
		}
		final ObjectiveComparatorHelper objectiveComparatorHelper = dseAdapter.getObjectiveComparatorHelper();

		boolean globalConstraintsAreSatisfied = dseAdapter.checkGlobalConstraints();
		if (!globalConstraintsAreSatisfied) {
			// Global constraint is not satisfied in the first state. Terminate.
			return;
		}

		final Fitness firstFitness = dseAdapter.getFitness();
		if (firstFitness.isSatisfiesHardObjectives()) {
			dseAdapter.newSolution();
			// First state is a solution. Terminate.
			if (backTrackIfSolution) {
				return;
			}
		}

		if (maxDepth == 0) {
			return;
		}


		var firstTrajectoryWithFitness = new TrajectoryWithFitness(dseAdapter.getTrajectory(), firstFitness);
		trajectoriesToExplore.add(firstTrajectoryWithFitness);
		TrajectoryWithFitness currentTrajectoryWithFitness = null;

		mainLoop: while (true) {

			if (currentTrajectoryWithFitness == null) {
				if (trajectoriesToExplore.isEmpty()) {
					// State space is fully traversed.
					return;
				} else {
					currentTrajectoryWithFitness = trajectoriesToExplore.element();
					// New trajectory is chosen: " + currentTrajectoryWithFitness
					dseAdapter.restoreTrajectory(currentTrajectoryWithFitness.trajectory);
				}
			}

			Collection<Activation> activations = dseAdapter.getUntraversedActivations();
			Iterator<Activation> iterator = activations.iterator();



			while (iterator.hasNext()) {
				final Activation nextActivation = iterator.next();
				if (!iterator.hasNext()) {
					// Last untraversed activation of the state.
					trajectoriesToExplore.remove(currentTrajectoryWithFitness);
				}

				// Executing new activation
				dseAdapter.fireActivation(nextActivation);
				if (dseAdapter.isCurrentStateAlreadyTraversed()) {
					// The new state is already visited.
					dseAdapter.backtrack();
				} else if (!dseAdapter.checkGlobalConstraints()) {
					// Global constraint is not satisfied.
					dseAdapter.backtrack();
				} else {
					final Fitness nextFitness = dseAdapter.getFitness();
					if (nextFitness.isSatisfiesHardObjectives()) {
						dseAdapter.newSolution();
						var solutions = dseAdapter.getSolutions().size();
						if (solutions >= maxSolutions) {
							return;
						}
						// Found a solution.
						if (backTrackIfSolution) {
							dseAdapter.backtrack();
							continue;
						}
					}
					if (dseAdapter.getDepth() >= maxDepth) {
						// Reached max depth.
						dseAdapter.backtrack();
						continue;
					}

					TrajectoryWithFitness nextTrajectoryWithFitness = new TrajectoryWithFitness(
							dseAdapter.getTrajectory(), nextFitness);
					trajectoriesToExplore.add(nextTrajectoryWithFitness);

					int compare = objectiveComparatorHelper.compare(currentTrajectoryWithFitness.fitness,
							nextTrajectoryWithFitness.fitness);
					if (compare < 0) {
						// Better fitness, moving on
						currentTrajectoryWithFitness = nextTrajectoryWithFitness;
						continue mainLoop;
					} else if (compare == 0) {
						if (onlyBetterFirst) {
							// Equally good fitness, backtrack
							dseAdapter.backtrack();
						} else {
							// Equally good fitness, moving on
							currentTrajectoryWithFitness = nextTrajectoryWithFitness;
							continue mainLoop;
						}
					} else {
						//"Worse fitness
						currentTrajectoryWithFitness = null;
						continue mainLoop;
					}
				}
			}

			// State is fully traversed.
			currentTrajectoryWithFitness = null;

		}
		// Interrupted.
	}
}