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