-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDPLL.cs
273 lines (226 loc) · 8.63 KB
/
DPLL.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace SAT_Solver {
public class DPLL : SATSolver {
/// <summary>Branch order is the predefined order in which literals are branched on. [index] is the order, [value] is the literal index.</summary>
private List<Literal> BranchOrder;
/// <summary>List of literals which were propagated at [index] decision level</summary>
protected List<HashSet<Literal>> propagates;
private List<bool> Defaults;
private readonly string heuristic;
private bool backtrack;
private int leftBranches;
public DPLL(string dimacs, bool debug, string heuristic = null, int timeout = 0) {
this.debug = debug;
this.heuristic = heuristic;
this.timeout = timeout;
ParseDimacs(dimacs);
SetBranchInfo();
Initialize();
}
private void SetBranchInfo() {
BranchOrder = ClauseReferences.Select((clause, variable) => new { variable, clause }).OrderByDescending(x => x.clause.Count).Select(x => new Literal(x.variable, false)).ToList();
if (heuristic == "reverse") {
BranchOrder.Reverse();
}
Defaults = new List<bool>();
for (int i = 0; i < LiteralCount; i++) {
int T = 0;
int F = 0;
foreach (var clause in ClauseReferences[i]) {
foreach (var literal in clause) {
if (literal.index == i) {
if (literal.value)
T++;
else
F++;
}
}
}
if (T >= F)
Defaults.Add(true);
else
Defaults.Add(false);
}
if (debug) {
for (int i = 0; i < BranchOrder.Count; i++) {
var lit = BranchOrder[i];
Console.WriteLine($"{i}: {lit.index + 1}\t\t{lit.index + 1}'s clauses: {ClauseReferences[lit.index].Count}");
}
}
}
private void Initialize() {
level = 0;
branch = new Stack<Literal>();
propagates = new List<HashSet<Literal>>();
for (int i = 0; i < LiteralCount; i++)
propagates.Add(new HashSet<Literal>());
}
public override SolverResult Run() {
if (Running)
throw new InvalidOperationException("Solver is already running");
Running = true;
totalwatch = Stopwatch.StartNew();
InitialUnitPropagation(out bool conflict);
if (conflict) {
Running = false;
return SolverResult.Fail(iterations);
}
if (AllAssigned) {
Running = false;
return SolverResult.Success(iterations, literals);
}
while (true) {
iterations++;
Literal variable = Branch();
UnitPropagation(variable, out conflict);
if (debug) {
Console.WriteLine($"branching, level: {level} tree: {string.Join(" ", branch.Select(x => x.ToString()).Reverse())}");
Console.WriteLine("propagations: " + string.Join(" ", propagates.SelectMany(x => x)));
Console.WriteLine("literals: " + string.Join(" ", literals.Select((x, i) => i + ":" + (x == null ? "__" : x.ToString()))));
Console.WriteLine();
}
if (!conflict && AllAssigned) {
Running = false;
return SolverResult.Success(iterations, literals);
}
if (conflict && leftBranches == 0) {
Running = false;
return SolverResult.Fail(iterations);
}
if (conflict)
backtrack = true;
if (timeout != 0 && totalwatch.ElapsedMilliseconds > timeout) {
totalwatch.Stop();
return SolverResult.Timeout(iterations, (int) totalwatch.ElapsedMilliseconds);
}
}
}
private Literal Branch() {
if (backtrack)
return Backtrack();
return BranchLeft();
}
private Literal Backtrack() {
while (true) {
if (debug)
Console.WriteLine("Backtrack");
backtrack = false;
foreach (var literal in propagates[level]) {
literals[literal.index] = null;
assignCount--;
}
propagates[level] = new HashSet<Literal>();
Literal old = branch.Peek();
literals[old.index] = null;
assignCount--;
if (old.value == Defaults[old.index]) {
return BranchRight();
}
level--;
branch.Pop();
}
}
private Literal BranchLeft() {
if (debug)
Console.WriteLine("Branch left");
var literal = SelectLiteral();
branch.Push(literal);
level++;
leftBranches++;
literals[literal.index] = literal;
assignCount++;
return literal;
}
private Literal BranchRight() {
if (debug)
Console.WriteLine("Branch right");
leftBranches--;
var old = branch.Pop();
var literal = new Literal(old.index, !Defaults[old.index]);
branch.Push(literal);
literals[literal.index] = literal;
assignCount++;
return literal;
}
protected void InitialUnitPropagation(out bool conflict) {
foreach (var clause in Clauses) {
if (clause.Count == 1) {
UnitPropagation(clause[0], out conflict);
if (conflict)
return;
}
}
//Console.WriteLine("initial propagations: " + string.Join(" ", propagates.SelectMany(x => x)));
conflict = false;
}
protected void UnitPropagation(Literal variable, out bool conflict) {
conflict = false;
foreach (var clause in ClauseReferences[variable.index]) {
TryPropagate(clause, out conflict);
if (conflict) {
return;
}
}
return;
}
protected bool TryPropagate(Clause clause, out bool conflict) {
int assignedValues = 0;
int falseValues = 0;
Literal literal = default;
conflict = false;
foreach (var lit in clause) {
if (literals[lit.index].HasValue) {
if (literals[lit.index].Value.value != lit.value)
falseValues++;
assignedValues++;
} else {
literal = lit;
}
}
if (assignedValues != falseValues) {
return false;
}
if (assignedValues == clause.Count - 1) {
propagates[level].Add(literal);
literals[literal.index] = literal;
assignCount++;
UnitPropagation(literal, out conflict);
return true;
}
if (falseValues == clause.Count) {
conflict = true;
return false;
}
return false;
}
private Literal SelectLiteral() {
if (heuristic == "random")
return RandomPick();
return UseBranchOrder();
}
#region heuristics
private Literal UseBranchOrder() {
for (int i = 0; i < LiteralCount; i++) {
var index = BranchOrder[i].index;
if (!literals[index].HasValue) {
return new Literal(index, Defaults[index]);
}
}
throw new Exception("Branchable literal not found");
}
private Literal RandomPick() {
var rnd = new Random();
while (true) {
var val = rnd.Next(LiteralCount);
if (!literals[val].HasValue) {
return new Literal(val, Defaults[val]);
}
}
}
#endregion
}
}