forked from typetools/checker-framework-inference
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathMaxSatSolver.java
More file actions
400 lines (347 loc) · 15.4 KB
/
Copy pathMaxSatSolver.java
File metadata and controls
400 lines (347 loc) · 15.4 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package checkers.inference.solver.backend.maxsat;
import org.checkerframework.javacutil.BugInCF;
import org.plumelib.util.IPair;
import org.sat4j.core.VecInt;
import org.sat4j.maxsat.SolverFactory;
import org.sat4j.maxsat.WeightedMaxSatDecorator;
import org.sat4j.pb.IPBSolver;
import org.sat4j.specs.ContradictionException;
import org.sat4j.specs.IConstr;
import org.sat4j.tools.xplain.DeletionStrategy;
import org.sat4j.tools.xplain.Xplain;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import checkers.inference.InferenceMain;
import checkers.inference.SlotManager;
import checkers.inference.model.Constraint;
import checkers.inference.model.PreferenceConstraint;
import checkers.inference.model.Slot;
import checkers.inference.solver.backend.Solver;
import checkers.inference.solver.frontend.Lattice;
import checkers.inference.solver.util.FileUtils;
import checkers.inference.solver.util.SolverArg;
import checkers.inference.solver.util.SolverEnvironment;
import checkers.inference.solver.util.Statistics;
/**
* MaxSatSolver calls MaxSatFormatTranslator that converts constraint into a list of VecInt, then
* invoke Sat4j lib to solve the clauses, and decode the result.
*/
public class MaxSatSolver extends Solver<MaxSatFormatTranslator> {
protected enum MaxSatSolverArg implements SolverArg {
/** Whether should print the CNF formulas. */
outputCNF;
}
protected final SlotManager slotManager;
protected final List<VecInt> hardClauses = new LinkedList<>();
private List<VecInt> wellFormednessClauses = new LinkedList<>();
protected final List<IPair<VecInt, Integer>> softClauses = new LinkedList<>();
private MaxSATUnsatisfiableConstraintExplainer unsatisfiableConstraintExplainer;
protected final File CNFData = new File(new File("").getAbsolutePath() + "/cnfData");
protected StringBuilder CNFInput = new StringBuilder();
private long serializationStart;
private long serializationEnd;
protected long solvingStart;
protected long solvingEnd;
public MaxSatSolver(
SolverEnvironment solverEnvironment,
Collection<Slot> slots,
Collection<Constraint> constraints,
MaxSatFormatTranslator formatTranslator,
Lattice lattice) {
super(solverEnvironment, slots, constraints, formatTranslator, lattice);
this.slotManager = InferenceMain.getInstance().getSlotManager();
if (shouldOutputCNF()) {
CNFData.mkdir();
}
}
@Override
public Map<Integer, AnnotationMirror> solve() {
Map<Integer, AnnotationMirror> solutions = null;
final WeightedMaxSatDecorator solver =
new WeightedMaxSatDecorator(org.sat4j.pb.SolverFactory.newBoth());
this.serializationStart = System.currentTimeMillis();
// Serialization step:
encodeAllConstraints();
encodeWellFormednessRestriction();
this.serializationEnd = System.currentTimeMillis();
if (shouldOutputCNF()) {
buildCNFInput();
writeCNFInput();
}
// printClauses();
configureSatSolver(solver);
try {
addClausesToSolver(solver);
cleanUpClauses();
this.solvingStart = System.currentTimeMillis();
boolean isSatisfiable = solver.isSatisfiable();
this.solvingEnd = System.currentTimeMillis();
long solvingTime = solvingEnd - solvingStart;
long serializationTime = serializationEnd - serializationStart;
Statistics.addOrIncrementEntry("sat_serialization_time(ms)", serializationTime);
Statistics.addOrIncrementEntry("sat_solving_time(ms)", solvingTime);
if (isSatisfiable) {
solutions = decode(solver.model());
} else {
System.out.println("Not solvable!");
// Lazily initialize unsatisfiableConstraintExplainer when there is no solution
unsatisfiableConstraintExplainer = new MaxSATUnsatisfiableConstraintExplainer();
}
} catch (ContradictionException e) {
InferenceMain.getInstance().logger.warning("Contradiction exception: ");
// This case indicates that constraints are not solvable, too. This is normal so
// continue
// execution and let solver strategy to explain why there is no solution
unsatisfiableConstraintExplainer = new MaxSATUnsatisfiableConstraintExplainer();
} catch (Exception e) {
throw new BugInCF("Unexpected error occurred!", e);
}
return solutions;
}
/** Convert constraints to list of VecInt. */
@Override
public void encodeAllConstraints() {
for (Constraint constraint : constraints) {
collectVarSlots(constraint);
VecInt[] encoding = constraint.serialize(formatTranslator);
if (encoding == null) {
InferenceMain.getInstance()
.logger
.warning(
getClass()
+ " doesn't support encoding constraint: "
+ constraint
+ "of class: "
+ constraint.getClass());
continue;
}
for (VecInt res : encoding) {
if (res != null && res.size() != 0) {
if (constraint instanceof PreferenceConstraint) {
softClauses.add(
IPair.of(res, ((PreferenceConstraint) constraint).getWeight()));
} else {
hardClauses.add(res);
}
}
}
}
}
protected void encodeWellFormednessRestriction() {
for (Integer varSlotId : varSlotIds) {
formatTranslator.generateWellFormednessClauses(wellFormednessClauses, varSlotId);
}
}
/**
* sat solver configuration Configure
*
* @param solver
*/
private void configureSatSolver(WeightedMaxSatDecorator solver) {
final int totalVars = (slotManager.getNumberOfSlots() * lattice.numTypes);
final int totalClauses =
hardClauses.size() + wellFormednessClauses.size() + softClauses.size();
solver.newVar(totalVars);
solver.setExpectedNumberOfClauses(totalClauses);
Statistics.addOrIncrementEntry("cnf_clause_size", totalClauses);
countVariables();
solver.setTimeoutMs(1000000);
}
private void addClausesToSolver(WeightedMaxSatDecorator solver) throws ContradictionException {
for (VecInt hardClause : hardClauses) {
solver.addHardClause(hardClause);
}
for (VecInt wellFormednessClause : wellFormednessClauses) {
solver.addHardClause(wellFormednessClause);
}
for (IPair<VecInt, Integer> softclause : softClauses) {
solver.addSoftClause(softclause.second, softclause.first);
}
}
private void cleanUpClauses() {
hardClauses.clear();
wellFormednessClauses.clear();
softClauses.clear();
}
protected Map<Integer, AnnotationMirror> decode(int[] solution) {
Map<Integer, AnnotationMirror> result = new HashMap<>();
for (Integer var : solution) {
if (var > 0) {
var = var - 1;
int slotId = MathUtils.getSlotId(var, lattice);
AnnotationMirror type =
formatTranslator.decodeSolution(
var, solverEnvironment.processingEnvironment);
result.put(slotId, type);
}
}
return result;
}
protected void countVariables() {
Set<Integer> vars = new HashSet<Integer>();
for (VecInt vi : hardClauses) {
for (int i : vi.toArray()) {
vars.add(i);
}
}
Statistics.addOrIncrementEntry("cnf_variable_size", vars.size());
}
protected boolean shouldOutputCNF() {
return solverEnvironment.getBoolArg(MaxSatSolverArg.outputCNF);
}
/** Write CNF clauses into a string. */
protected void buildCNFInput() {
final int totalClauses = hardClauses.size() + wellFormednessClauses.size();
final int totalVars = slotManager.getNumberOfSlots() * lattice.numTypes;
CNFInput.append("c This is the CNF input\n");
CNFInput.append("p cnf ");
CNFInput.append(totalVars);
CNFInput.append(" ");
CNFInput.append(totalClauses);
CNFInput.append("\n");
for (VecInt hardClause : hardClauses) {
buildCNFInputHelper(hardClause);
}
for (VecInt wellFormedNessClause : wellFormednessClauses) {
buildCNFInputHelper(wellFormedNessClause);
}
}
private void buildCNFInputHelper(VecInt clause) {
int[] literals = clause.toArray();
for (int i = 0; i < literals.length; i++) {
CNFInput.append(literals[i]);
CNFInput.append(" ");
}
CNFInput.append("0\n");
}
protected void writeCNFInput() {
writeCNFInput("cnfdata.txt");
}
protected void writeCNFInput(String file) {
FileUtils.writeFile(new File(CNFData.getAbsolutePath() + "/" + file), CNFInput.toString());
}
/** print all soft and hard clauses for testing. */
protected void printClauses() {
System.out.println("Hard clauses: ");
for (VecInt hardClause : hardClauses) {
System.out.println(hardClause);
}
System.out.println();
System.out.println("WellFormedness clauses: ");
for (VecInt wellFormednessClause : wellFormednessClauses) {
System.out.println(wellFormednessClause);
}
System.out.println();
System.out.println("Soft clauses: ");
for (IPair<VecInt, Integer> softclause : softClauses) {
System.out.println(softclause.first + " w: " + softclause.second);
}
}
@Override
public Collection<Constraint> explainUnsatisfiable() {
return unsatisfiableConstraintExplainer.minimumUnsatisfiableConstraints();
}
class MaxSATUnsatisfiableConstraintExplainer {
/** A mapping from VecInt to Constraint. */
private final Map<VecInt, Constraint> vecIntConstraintMap;
/** A mapping from IConstr to VecInt. IConstr is the result of adding VecInt to solver. */
private final Map<IConstr, VecInt> iConstrVecIntMap;
private MaxSATUnsatisfiableConstraintExplainer() {
// Using IdentityHashMap because different VecInts can share the same hash code,
// one VecInt might be overriden by a different VecInt.But VecInt has one-to-one
// relation to Constraint. Therefore, IdentityHashMap is used.
vecIntConstraintMap = new IdentityHashMap<>();
iConstrVecIntMap = new IdentityHashMap<>();
cleanUpClauses();
// Fill up hardClauses and wellFormednessClauses again(cleared before) to feed into
// explanation solver
fillHardClauses();
encodeWellFormednessRestriction();
}
// Compared to encodeAllConstrains(), this method doesn't format translate soft clauses,
// and additionally stores the mapping from VecInt to Constraint, so that Constraint can
// be reversly looked up by VecInt
private void fillHardClauses() {
// Fill up vecIntConstraintMap to reversely lookup Constraint from VecInt
for (Constraint constraint : constraints) {
VecInt[] encoding = constraint.serialize(formatTranslator);
if (encoding == null) {
// Happens for unsupported Constraints. Already warned in encodeAllConstraints()
continue;
}
for (VecInt e : encoding) {
if (e != null
&& e.size() != 0
&& !(constraint instanceof PreferenceConstraint)) {
hardClauses.add(e);
vecIntConstraintMap.put(e, constraint);
}
}
}
}
public Collection<Constraint> minimumUnsatisfiableConstraints() {
// It's ok to use HashSet for Constraint, because its hashCose() implementation
// differentiates different
// Constraints well.
Set<Constraint> mus = new HashSet<>();
// Explainer solver that is used
Xplain<IPBSolver> explanationSolver = new Xplain<>(SolverFactory.newDefault());
configureExplanationSolver(
hardClauses, wellFormednessClauses, slotManager, lattice, explanationSolver);
try {
addClausesToExplanationSolver(explanationSolver);
assert !explanationSolver.isSatisfiable();
Collection<IConstr> explanation = explanationSolver.explain();
for (IConstr i : explanation) {
VecInt vecInt = iConstrVecIntMap.get(i);
if (vecIntConstraintMap.get(vecInt) != null) {
// This case is reached if vecInt is from Constraint
mus.add(vecIntConstraintMap.get(vecInt));
} else {
// This case indicates vecInt is well-formedness restriction
// TODO Instead of printing it, can we have a dedicated type, e.g.
// WellFormednessConstraint <: Constraint
// TODO so that we can also add it to the result set?
System.out.println("Explanation hits well-formedness restriction: " + i);
}
}
} catch (Exception e) {
throw new BugInCF("Explanation solver encountered not-expected exception: ", e);
}
return mus;
}
private void configureExplanationSolver(
final List<VecInt> hardClauses,
final List<VecInt> wellformedness,
final SlotManager slotManager,
final Lattice lattice,
final Xplain<IPBSolver> explainer) {
int numberOfNewVars = slotManager.getNumberOfSlots() * lattice.numTypes;
System.out.println("Number of variables: " + numberOfNewVars);
int numberOfClauses = hardClauses.size() + wellformedness.size();
System.out.println("Number of clauses: " + numberOfClauses);
explainer.setMinimizationStrategy(new DeletionStrategy());
explainer.newVar(numberOfNewVars);
explainer.setExpectedNumberOfClauses(numberOfClauses);
}
private void addClausesToExplanationSolver(Xplain<IPBSolver> explanationSolver)
throws ContradictionException {
for (VecInt clause : hardClauses) {
IConstr iConstr = explanationSolver.addClause(clause);
iConstrVecIntMap.put(iConstr, clause);
}
for (VecInt clause : wellFormednessClauses) {
IConstr iConstr = explanationSolver.addClause(clause);
iConstrVecIntMap.put(iConstr, clause);
}
}
}
}