This repository has been archived by the owner on Jan 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.java
436 lines (396 loc) · 13.2 KB
/
Solver.java
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Iterator;
import java.util.HashMap;
import java.io.IOException;
class Solver{
private PropositionalFormula formula;
private Character[] propositions;
private int[] vector;
private List<String> clauseSet;
public Solver(PropositionalFormula formula){
this.formula = formula;
if (formula.isCNF()){
this.propositions = extractPropositions(formula);
this.vector = extractBitVector(propositions);
this.clauseSet = extractClauseSet(formula);
}
}
private Character[] extractPropositions(PropositionalFormula formula){
String CNF = formula.getCNF();
List<Character> props = new ArrayList<>();
for (int i = 0; i < CNF.length(); i++){
Character c = CNF.charAt(i);
if ((c == '{') || (c == '}') || (c == ' ') || (c == ',') || (c == '-')){
continue;
}
if (props.contains(c)){
continue;
}
props.add(c);
}
Character[] propositions = new Character[props.size()];
propositions = props.toArray(propositions);
return propositions;
}
private int[] extractBitVector(Character[] propositions){
//Initialize a new array able to hold as many bits as propositions.
//An integer can hold 31 bits.
int[] vector = new int[propositions.length / 32 + 1];
int index = 0;
int counter = 0;
for (Character c : propositions){
vector[index] = (vector[index] << 1) | 1;
counter++;
if (counter >=32 ){
index++;
counter = 0;
}
}
return vector;
}
private List<String> extractClauseSet(PropositionalFormula formula){
return formula.getClauseSet();
}
public int bruteForce(){
return bruteForce(this.clauseSet, this.propositions, this.vector[0]);
}
private int bruteForce(List<String> clauses, Character[] propositions, int bitvector){
// Map the literals to the interpreted value as decided by the bitvector.
HashMap<Character, Boolean> interpretation = new HashMap<>();
while(bitvector >= 0){
int check = 1;
interpretation.clear();
for (Character c : propositions){
interpretation.put(c, (bitvector & check) > 0);
check = check << 1;
}
// Iterate through all clauses. If a clause is unsatisfied in the interpretation,
// recurse with decremented bitvector.
boolean sat = true;
for (String s : clauses){
if (!isClauseSatisfiable(s, interpretation)){
sat = false;
break;
}
}
// All clauses satisfied by the interpretation.
if (sat) {
System.out.println("\nA satisfying interpretation: " + interpretation);
return bitvector;
}
bitvector--;
}
return -1;
}
public int bruteForceUnit(){
HashMap<Character, Boolean> unitClauses = new HashMap<>();
for (String s : this.clauseSet){
if (s.length() > 2)
continue;
if (s.charAt(0) == '-'){
unitClauses.put(s.charAt(1), false);
}
if (s.length() == 1){
unitClauses.put(s.charAt(0), true);
}
}
return bruteForceUnit(this.clauseSet, this.propositions, this.vector[0], unitClauses);
}
private int bruteForceUnit(List<String> clauses, Character[] propositions, int bitvector, HashMap<Character, Boolean> unitClauses){
// Map the literals to the interpreted value as decided by the bitvector.
HashMap<Character, Boolean> interpretation = new HashMap<>();
while(bitvector > 0){
int check = 1;
interpretation.clear();
for (Character c : propositions){
if (unitClauses.keySet().contains(c)){
interpretation.put(c, unitClauses.get(c));
if (!interpretation.get(c))
bitvector &= (bitvector ^ check);
} else {
interpretation.put(c, (bitvector & check) > 0);
}
check = check << 1;
}
// Iterate through all clauses. If a clause is unsatisfied in the interpretation,
// recurse with decremented bitvector.
boolean sat = true;
for (String s : clauses){
if (!isClauseSatisfiable(s, interpretation)){
sat = false;
break;
}
}
// All clauses satisfied by the interpretation.
if (sat) {
System.out.println("\nA satisfying interpretation: " + interpretation);
return bitvector;
}
bitvector--;
}
return -1;
}
private List<String> trues = new ArrayList<>();
public int dpll(){
int i = dpll(this.formula);
if (i > 0){
System.out.println("A satisfying interpretation: " + trues);
} else {
System.out.println("Formula is invalid.");
}
return i;
}
//https://en.wikipedia.org/wiki/DPLL_algorithm
private int dpll(PropositionalFormula formula){
if (containsEmptyClause(formula)){
return -1;
}
if (isConsistentSetOfLiterals(formula)){
for (String s : formula.getClauseSet()){
trues.add(s);
}
return 1;
}
List<String> unitClauses = extractUnitClauses(formula);
for (String literal : unitClauses){
try{
unitPropagate(literal, formula, (literal.length() == 2));
} catch(Exception e){
e.printStackTrace();
}
}
List<String> pureLiterals = extractPureLiterals(formula);
for (String literal : pureLiterals){
try{
unitPropagate(literal, formula, (literal.length() == 2));
} catch(Exception e){
e.printStackTrace();
}
}
// Choose branching literal
Iterator<String> iter = formula.getClauseSet().iterator();
String firstClause = iter.next();
String literal = (firstClause.charAt(0) == '-') ? firstClause.substring(1,2) : firstClause.substring(0,1);
PropositionalFormula branching = formula.clone();
try {
unitPropagate(literal, branching, false);
} catch(Exception e){
e.printStackTrace();
}
int ret = dpll(branching);
if (ret < 0){
branching = formula.clone();
try {
unitPropagate("-" + literal, branching, true);
} catch(Exception e){
e.printStackTrace();
}
if(!trues.contains("-"+literal))
trues.add("-" + literal);
ret = dpll(branching);
} else {
trues.add(literal);
}
return ret;
}
private boolean isConsistentSetOfLiterals(PropositionalFormula formula){
List<String> clauseSet = formula.getClauseSet();
List<Character> literals = new ArrayList<>();
List<Character> negatedLiterals = new ArrayList<>();
for (String clause : clauseSet){
// Empty clause
if (clause == null){
continue;
}
char[] clauseLiterals = clause.toCharArray();
for (int i = 0; i < clauseLiterals.length; i++){
char literal = clauseLiterals[i];
if (i > 0 && clauseLiterals[i-1] == '-'){
if (literals.contains(literal)){
return false;
}
negatedLiterals.add(literal);
continue;
}
if (negatedLiterals.contains(literal)){
return false;
}
literals.add(literal);
}
}
return true;
}
private boolean containsEmptyClause(PropositionalFormula formula){
return (formula.getClauseSet().contains(null));
}
private List<String> extractUnitClauses(PropositionalFormula formula){
List<String> list = new ArrayList<>();
List<String> clauses = formula.getClauseSet();
for (String clause : clauses){
char[] clauseLiterals = clause.toCharArray();
if (clauseLiterals.length == 1){
list.add(clause);
continue;
}
if (clauseLiterals.length == 2 && clauseLiterals[0] == '-'){
list.add(clause);
continue;
}
}
return list;
}
/**
* Sets the literal to be parameter negated in the formula, and
* propagates the change through the formula. This method is destructive;
* it makes changes to the formula.
*
* @param literal The literal to propagate on.
* @param formula The formula to propagate on.
* @param negated True if literal is negated, false if not.
* @throws IOException If @param literal is not of length 1 (i.e., not a literal) and negated is false.
* @see https://en.wikipedia.org/wiki/Unit_propagation
*/
private void unitPropagate(String literal, PropositionalFormula formula, boolean negated) throws IOException{
if (literal.length() != 1 && !negated){
throw new IOException("Length of supplied literal parameter is not 1.");
}
if (literal.length() != 2 && negated){
throw new IOException("Length of supplied negated literal parameter is not 2.");
}
List<String> clauses = formula.getClauseSet();
for (ListIterator<String> iter = clauses.listIterator(); iter.hasNext();){
String clause = iter.next();
// Empty clause
if (clause == null){
continue;
}
if (clause.length() <= 1){
// Either empty clause or unit clause
continue;
}
if (clause.length() == 2 && negated && (clause.charAt(0) == '-')){
// Negated unit clause
continue;
}
boolean neg = negated;
for (int i = 0; i < clause.length(); i++){
if (clause.charAt(i) == '-'){
if (negated){
if (clause.charAt(i+1) == literal.charAt(1)){
// Clause contains negated literal, clause can be removed.
iter.remove();
break;
}
}
neg = !negated;
continue;
}
if (clause.charAt(i) == literal.charAt(0)){
// Clause contains non-negated literal, clause can be removed
if (neg == negated){
iter.remove();
break;
}
// Clause contains negated literal, remove the literal and the negation from the clause
String s = (i==0) ? clause.substring(i+1) : clause.substring(0, i-1) + clause.substring(i+1);
iter.set((s.length() > 0) ? s : null);
}
if (negated && clause.charAt(i) == literal.charAt(1)){
// Clause contains non-negated literal, remove the literal.
String s = (i==1) ? clause.substring(i+1) : clause.substring(0, i) + clause.substring(i+1);
iter.set((s.length() > 0) ? s : null);
}
neg = negated;
}
}
}
/**
* This method extracts all pure literals of a formula.
* Pure literals are literals that occur with only one polarity.
* This method is non-destructive towards the formula.
*
* @param formula propositional formula to extract pure literals from
* @return List<String> list of all pure literals in the formula
* @see https://en.wikipedia.org/wiki/DPLL_algorithm
*/
private List<String> extractPureLiterals(PropositionalFormula formula){
List<String> clauses = formula.getClauseSet();
HashMap<Character, Boolean> literals = new HashMap<>();
List<Character> duplicates = new ArrayList<>();
for (Iterator<String> iter = clauses.listIterator(); iter.hasNext(); ){
String clause = iter.next();
// Empty clause
if (clause == null){
continue;
}
for (int i = 0; i < clause.length(); i++){
// Duplicate allready noted, skip
if (duplicates.contains(clause.charAt(i))){
continue;
}
Character literal;
if (clause.charAt(i) == '-'){
// Increment counter to get index to the literal
i++;
literal = clause.charAt(i);
if (duplicates.contains(literal)){
continue;
}
// Literal has been seen before
if (literals.keySet().contains(literal)){
// Literal has been seen negated before, nothing new; skip
if (literals.get(literal)){
continue;
}
// Literal has been non-negated before, but is negated now; add to duplicates.
duplicates.add(literal);
continue;
}
// New literal, add it
literals.put(literal, true);
continue;
}
literal = clause.charAt(i);
// Literal has been seen before
if (literals.keySet().contains(literal)){
// Literal has been seen negated before; add to duplicates
if (literals.get(literal)){
duplicates.add(literal);
}
continue;
}
literals.put(literal, false);
}
}
List<String> pureLiterals = new ArrayList<>();
// The pure literas are the characters that are inn literals but not in duplicates.
for (Character c : literals.keySet()){
if (duplicates.contains(c)){
continue;
}
pureLiterals.add((literals.get(c)) ? ("-" + c) : Character.toString(c));
}
return pureLiterals;
}
private boolean isClauseSatisfiable(String clause, HashMap<Character, Boolean> interpretation){
boolean negated = false;
//Iterate through each literal in the clause.
for (int i = 0; i < clause.length(); i++){
char c = clause.charAt(i);
if (c == '-'){
negated = true;
continue;
}
//True if literal is interpreted to true and not negated, or
//if literal is interpreted to false and negated. Classical XOR.
//If a literal is true, the clause is satisfied.
if (interpretation.get(c) ^ negated){
return true;
}
negated = false;
}
return false;
}
}