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

import tools.refinery.store.dse.propagation.BoundPropagator;
import tools.refinery.store.dse.propagation.PropagationAdapter;
import tools.refinery.store.dse.propagation.PropagationResult;
import tools.refinery.store.dse.propagation.PropagationStoreAdapter;
import tools.refinery.store.model.Model;

class PropagationAdapterImpl implements PropagationAdapter {
	private final Model model;
	private final PropagationStoreAdapterImpl storeAdapter;
	private final BoundPropagator[] boundPropagators;

	public PropagationAdapterImpl(Model model, PropagationStoreAdapterImpl storeAdapter) {
		this.model = model;
		this.storeAdapter = storeAdapter;
		var propagators = storeAdapter.getPropagators();
		boundPropagators = new BoundPropagator[propagators.size()];
		for (int i = 0; i < boundPropagators.length; i++) {
			boundPropagators[i] = propagators.get(i).bindToModel(model);
		}
	}

	@Override
	public PropagationResult propagate() {
		PropagationResult result = PropagationResult.UNCHANGED;
		PropagationResult lastResult;
		do {
			lastResult = propagateOne();
			result = result.andThen(lastResult);
		} while (lastResult.isChanged());
		return result;
	}

	private PropagationResult propagateOne() {
		PropagationResult result = PropagationResult.UNCHANGED;
		for (int i = 0; i < boundPropagators.length; i++) {
			var lastResult = propagateUntilFixedPoint(i);
			result = result.andThen(lastResult);
			if (result.isRejected()) {
				break;
			}
		}
		return result;
	}

	private PropagationResult propagateUntilFixedPoint(int propagatorIndex) {
		var propagator = boundPropagators[propagatorIndex];
		PropagationResult result = PropagationResult.UNCHANGED;
		PropagationResult lastResult;
		do {
			lastResult = propagator.propagateOne();
			result = result.andThen(lastResult);
		} while (lastResult.isChanged());
		return result;
	}

	@Override
	public Model getModel() {
		return model;
	}

	@Override
	public PropagationStoreAdapter getStoreAdapter() {
		return storeAdapter;
	}
}