aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/store-dse/src/main/java/tools/refinery/store/dse/strategy/BestFirstExplorer.java
blob: 4a75a3a63f420f32d5b402ad09ddd1bad6bc5197 (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
/*
 * SPDX-FileCopyrightText: 2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package tools.refinery.store.dse.strategy;

import tools.refinery.store.model.Model;

import java.util.Random;

public class BestFirstExplorer extends BestFirstWorker {
	final int id;
	Random random;

	public BestFirstExplorer(BestFirstStoreManager storeManager, Model model, int id) {
		super(storeManager, model);
		this.id = id;
		this.random = new Random(id);
	}

	private boolean interrupted = false;

	public void interrupt() {
		this.interrupted = true;
	}

	private boolean shouldRun() {
		return !interrupted && !hasEnoughSolution();
	}

	public void explore() {
		var lastBest = submit().newVersion();
		while (shouldRun()) {
			if (lastBest == null) {
				if (random.nextInt(10) == 0) {
					lastBest = restoreToRandom(random);
				} else {
					lastBest = restoreToBest();
				}
				if (lastBest == null) {
					return;
				}
			}
			boolean tryActivation = true;
			while (tryActivation && shouldRun()) {
				var randomVisitResult = this.visitRandomUnvisited(random);
				tryActivation = randomVisitResult.shouldRetry();
				var newSubmit = randomVisitResult.submitResult();
				if (newSubmit != null) {
					if (!newSubmit.include()) {
						restoreToLast();
					} else {
						var newVisit = newSubmit.newVersion();
						int compareResult = compare(lastBest, newVisit);
						if (compareResult >= 0)  {
							lastBest = newVisit;
						} else {
							lastBest = null;
						}
						break;
					}
				} else {
					lastBest = null;
					break;
				}
			}
		}
	}
}