-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
394 lines (323 loc) · 11.1 KB
/
utils.py
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
#!/usr/bin/python
import random
import copy
from collections import defaultdict
class DP(object):
'''Class for Davis-Putnam solver.
'''
def __init__(self, file):
self.file = file
self.split = 0
self.count = 0
def split_choice(self, clauses):
'''Select a heuristic to split.
Arguments:
clauses {list} -- list of clauses
Returns:
int -- variable to split
'''
if self.split == 1:
return self.random_split(clauses)
elif self.split == 2:
return self.JW_det_split(clauses)
elif self.split == 3:
return self.JW_prob_split(clauses)
elif self.split == 4:
return self.DLIS_det_split(clauses)
elif self.split == 5:
return self.DLIS_prob_split(clauses)
def solver(self, clauses):
'''Main method of solver.
Arguments:
clauses {list} -- list of clauses
Returns:
dict -- dictionary of variables with assigned values
'''
# print('|START count:', self.count)
# print('start:', clauses)
clauses = self.pure_literals(clauses)
# print('after pure:', clauses)
clauses = self.unit_clauses(clauses)
# print('after unit:', clauses)
if [] in clauses:
# print('false')
return False
if len(clauses) == 0:
# print('success!')
return self.vars
split_var = self.split_choice(clauses)
self.count += 1
# print(split_var)
tmp = copy.deepcopy(clauses)
assignment = self.solver(self.remove_clauses(split_var, clauses))
if assignment is False:
# print('backtracking...')
self.count += 1
clauses = copy.deepcopy(tmp)
assignment = self.solver(self.remove_clauses(-split_var, clauses))
if assignment is False:
return False
return self.vars
def random_split(self, clauses):
'''Random splitting heuristic.
Arguments:
clauses {list} -- list of clauses
Returns:
int -- variable to split
'''
clause = random.choice(clauses)
split = random.choice(clause)
return split
def remove_clauses(self, variable, clauses):
'''Update the list of clauses with the given variable assigned.
Arguments:
variable {int} -- variable with assgined value
clauses {list} -- list of clauses
Returns:
list -- updated list of clauses
'''
new_clauses = []
if variable >= 0:
self.vars[variable] = True
else:
self.vars[abs(variable)] = False
for clause in clauses:
if variable in clause:
continue
else:
if -variable in clause:
clause.remove(-variable)
new_clauses.append(clause)
return new_clauses
def remove_clauses_testing_only(self, variable, clauses):
'''Update the list of clauses with the given variable assigned.
Arguments:
variable {int} -- variable with assgined value
clauses {list} -- list of clauses
Returns:
list -- updated list of clauses
'''
print('variable:', variable)
print('number of clauses:', len(clauses))
new_clauses = []
if variable >= 0:
self.vars[variable] = True
else:
self.vars[abs(variable)] = False
for clause in clauses:
if variable in clause:
continue
else:
if -variable in clause:
clause.remove(-variable)
new_clauses.append(clause)
return new_clauses
def read(self):
'''Method for reading the clauses from the input file.
Returns:
list -- list of clauses
'''
# Initialize clauses list.
clauses = []
# Initialize variables.
vars_tmp = set()
# Start reading from the file.
with open(self.file, 'r') as input_file:
for line in input_file:
parsed = line.split()
# Check whether it is valid line or supplementary line.
if not parsed or parsed[0] == 'p' or parsed[0] == 'c':
continue
else:
eff_parsed = parsed[:-1]
clause = set()
for lit in eff_parsed:
lit = int(lit)
clause.add(lit)
# Collect variable.
abs_lit = abs(lit)
vars_tmp.add(abs_lit)
clauses.append(list(clause))
# Initialize all collected variables, e.g. {'115': [False] ...} - where [truth_val]
self.vars = dict.fromkeys(vars_tmp, False)
return clauses
def tautology(self, clauses):
'''Check and remove tautology from the list of clauses.
Returns:
list -- list of clauses
'''
new_clauses = []
check = 1
for clause in clauses:
for lit in clause:
if -lit in clause:
check = 0
break
if check == 1:
new_clauses.append(clause)
else:
check = 1
return new_clauses
def pure_literals(self, clauses):
'''Collect and remove the pure literals from the list of clauses.
Returns:
list -- list of clauses
'''
p_lits = set()
non_p_lits = set()
for clause in clauses:
for lit in clause:
neg_lit = -lit
abs_lit = abs(lit)
if neg_lit not in p_lits:
if abs_lit not in non_p_lits:
p_lits.add(lit)
else:
p_lits.remove(neg_lit)
non_p_lits.add(abs_lit)
for lit in p_lits:
clauses = self.remove_clauses(lit, clauses)
return clauses
def unit_clauses(self, clauses):
'''Collect and remove unit clauses from the list of clauses.
Returns:
list -- list of clauses
'''
unit_var = set()
for clause in clauses:
if len(clause) == 1:
unit_var.add(clause[0])
while len(unit_var) > 0:
for unit in unit_var:
clauses = self.remove_clauses(unit, clauses)
unit_var = set()
clauses = self.unit_clauses(clauses)
return clauses
def JW_det_split(self, clauses):
'''Use deterministic Jeroslow-Wang heuristic to split variable.
Arguments:
clauses {list} -- list of clauses
Returns:
int -- selected variable to split
'''
J = defaultdict(int)
for clause in clauses:
clause_len = len(clause)
for lit in clause:
J[lit] += 2 ** (-clause_len)
max_pair = [-1, 0]
for k in J.keys():
sum_J = J[k] + J[-k]
if sum_J > max_pair[1] and max_pair[0] != -k:
max_pair = [k, sum_J]
split = abs(max_pair[0])
if J[split] >= J[-split]:
return split
else:
return -split
def JW_prob_split(self, clauses):
'''Use probabilistic Jeroslow-Wang heuristic to split variable.
Arguments:
clauses {list} -- list of clauses
Returns:
int -- selected variable to split
'''
J = defaultdict(int)
for clause in clauses:
clause_len = len(clause)
for lit in clause:
J[lit] += 2 ** (-clause_len)
choices = []
vals = []
for k, v in J.items():
lit = abs(k)
if lit not in choices:
choices.append(lit)
vals.append(J[k] + J[-k])
split = random.choices(choices, weights=vals, k=1)
split = split[0]
split = random.choices([split, -split], weights=[J[split], J[-split]], k=1)
split = split[0]
return split
def DLIS_det_split(self, clauses):
'''Use deterministic DLIS heuristic to split variable.
Arguments:
clauses {list} -- list of clauses
Returns:
int -- selected variable to split
'''
C_p = defaultdict(int)
C_n = defaultdict(int)
for clause in clauses:
for lit in clause:
if lit > 0:
C_p[lit] += 1
else:
C_n[lit] += 1
max_pair_p = [0, -1]
for k, v in C_p.items():
if v > max_pair_p[1]:
max_pair_p = [k, v]
max_pair_n = [0, -1]
for k, v in C_n.items():
if v > max_pair_n[1]:
max_pair_n = [k, v]
if max_pair_p[1] > max_pair_n[1]:
return max_pair_p[0]
else:
return max_pair_n[0]
def DLIS_prob_split(self, clauses):
'''Use probabilistic DLIS heuristic to split variable.
Arguments:
clauses {list} -- list of clauses
Returns:
int -- selected variable to split
'''
C_p = defaultdict(int)
C_n = defaultdict(int)
for clause in clauses:
for lit in clause:
if lit > 0:
C_p[lit] += 1
else:
C_n[lit] += 1
choices_p = []
weights_p = []
for k, v in C_p.items():
choices_p.append(k)
weights_p.append(v)
choices_n = []
weights_n = []
for k, v in C_n.items():
choices_n.append(k)
weights_n.append(v)
choice_p = random.choices(choices_p, weights=weights_p, k=1)
choice_p = choice_p[0]
val_p = C_p[choice_p]
choice_n = random.choices(choices_n, weights=weights_n, k=1)
choice_n = choice_n[0]
val_n = C_n[choice_n]
split = random.choices([choice_p, choice_n], weights=[val_p, val_n], k=1)
split = split[0]
return split
def output_results(self, vars=None):
'''Method for outputting the results into input_filename.out.
Keyword Arguments:
vars {dict} -- dictionary to store the variables with their assignments (default: {None})
'''
input_file_name = self.file.split('/')
input_file_name = input_file_name[-1]
output_file = input_file_name[:-4] + '.out'
if vars is None:
with open(output_file, 'w') as output:
output.write('')
else:
assignments = []
for k, v in vars.items():
if v:
assignments.append(str(k) + ' 0\n')
else:
assignments.append(str(-k) + ' 0\n')
with open(output_file, 'w') as output:
output.write('p cnf {} {}\n'.format(len(vars), len(vars)))
output.writelines(assignments)