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 package org.sat4j.tools.xplain;
29
30 import java.util.Map;
31 import java.util.Set;
32
33 import org.sat4j.core.VecInt;
34 import org.sat4j.specs.IConstr;
35 import org.sat4j.specs.ISolver;
36 import org.sat4j.specs.IVecInt;
37 import org.sat4j.specs.TimeoutException;
38
39
40
41
42
43
44 public class ReplayXplainStrategy implements XplainStrategy {
45
46 private boolean computationCanceled;
47
48
49
50
51 public void cancelExplanationComputation() {
52 computationCanceled = true;
53 }
54
55
56
57
58 public IVecInt explain(ISolver solver, Map<Integer, IConstr> constrs,
59 IVecInt assumps) throws TimeoutException {
60 computationCanceled = false;
61 IVecInt encodingAssumptions = new VecInt(constrs.size()
62 + assumps.size());
63 assumps.copyTo(encodingAssumptions);
64 IVecInt firstExplanation = solver.unsatExplanation();
65 Set<Integer> constraintsVariables = constrs.keySet();
66 int p;
67 for (int i = 0; i < firstExplanation.size(); i++) {
68 if (constraintsVariables.contains(p = -firstExplanation.get(i))) {
69 encodingAssumptions.push(p);
70 }
71 }
72 boolean shouldContinue;
73 int startingPoint = assumps.size();
74 do {
75 shouldContinue = false;
76 int i = startingPoint;
77 encodingAssumptions.set(i, -encodingAssumptions.get(i));
78 assert encodingAssumptions.get(i) < 0;
79 while (!computationCanceled
80 && solver.isSatisfiable(encodingAssumptions)) {
81 i++;
82 assert encodingAssumptions.get(i) > 0;
83 encodingAssumptions.set(i, -encodingAssumptions.get(i));
84 }
85 if (!computationCanceled && i > startingPoint) {
86 assert !solver.isSatisfiable(encodingAssumptions);
87 if (i < encodingAssumptions.size()) {
88
89
90 int tmp = encodingAssumptions.get(i);
91 for (int j = i; j > startingPoint; j--) {
92 encodingAssumptions.set(j, -encodingAssumptions
93 .get(j - 1));
94 }
95 encodingAssumptions.set(startingPoint, tmp);
96 }
97 shouldContinue = true;
98 }
99 startingPoint++;
100 } while (!computationCanceled && shouldContinue
101 && solver.isSatisfiable(encodingAssumptions));
102 if (computationCanceled) {
103 throw new TimeoutException();
104 }
105 IVecInt constrsKeys = new VecInt(startingPoint);
106 for (int i = assumps.size(); i < startingPoint; i++) {
107 constrsKeys.push(-encodingAssumptions.get(i));
108 }
109 return constrsKeys;
110 }
111 }