-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdp.py
executable file
·428 lines (360 loc) · 15 KB
/
dp.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
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
#!/usr/bin/env python
import argparse
import copy
import itertools
import logging
from signal import signal, SIGPIPE, SIG_DFL
import sys
from decomposer import Decomposer
from formula import Formula, Literal
from graph import Graph
from td import TD
log = logging.getLogger(__name__)
# https://docs.python.org/3/library/itertools.html#itertools-recipes
# def powerset(iterable):
# "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
# s = list(iterable)
# return itertools.chain.from_iterable(
# itertools.combinations(s, r) for r in range(len(s)+1))
# Deletes the i'th bit (starting from the right with 0)
def delete_bit(bits, i):
right_part = bits & (1 << i) - 1
bits >>= i + 1
bits <<= i
return bits | right_part
def select_falsifying_ep(ept):
assert any(ep.cost > 0 for ep in ept)
return next(ep for ep in ept if ep.cost > 0)
class Assignment(object):
# variables: list of variables.
# bits store the truth values of the given variables, first variable is
# leftmost bit.
def __init__(self, variables, bits):
self.variables = variables
self.bits = bits
# Map variable to index in variable list / bit array
self.index_of = {
v: i for v, i in
zip(self.variables, range(len(self.variables) - 1, -1, -1))}
def __repr__(self):
return str(self.to_literals())
def __hash__(self):
# We only check the bits since we assume that we only hash assignments
# from the same table, thus the variables are the same
return self.bits
# Two assignments are only equal if their variables are in the same order
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.variables == other.variables
and self.bits == other.bits)
return NotImplemented
def __getitem__(self, key):
assert key in self.variables
return self.bit(self.index_of[key])
# Returns the bit with the given index (counted from the right)
def bit(self, index):
return bool(self.bits & (1 << index))
def consistent(self, other):
common_vars = [v for v in self.variables if v in other.variables]
return all(self[v] == other[v] for v in common_vars)
# Restrict the assignment to the given variables. If a given variable is
# not in the assignment, it is ignored.
def restrict(self, variables):
# The following assertion only holds for our DP algorithm on weakly
# normalized TDs.
#assert all(v in self.variables for v in variables)
indices = [self.index_of[v] for v in variables if v in self.variables]
bits = 0
for index in indices:
bits = (bits << 1) | self.bit(index)
return Assignment(variables, bits)
# Return new assignment that extends this one by the given
# variable-disjoint assignment
def extend_disjoint(self, new_vars, new_bits):
assert frozenset(self.variables).isdisjoint(frozenset(new_vars))
extended_bits = (self.bits << len(new_vars)) | new_bits
return Assignment(self.variables + new_vars, extended_bits)
# Returns a new assignment that combines the given ones, which must be
# consistent with each other
def combine(*assignments):
assert all(x.consistent(y)
for x, y in itertools.combinations(assignments, 2))
if not assignments:
return Assignment([], 0)
# We first just append all assignments and then eliminate duplicate
# variables
combined_vars = []
combined_bits = 0
for a in assignments:
combined_vars.extend(a.variables)
combined_bits = (combined_bits << len(a.variables)) | a.bits
# Eliminate duplicates
seen_vars = set()
final_vars = []
i = len(combined_vars)
for v in combined_vars:
i -= 1
if v in seen_vars:
combined_bits = delete_bit(combined_bits, i)
else:
seen_vars.add(v)
final_vars.append(v)
return Assignment(final_vars, combined_bits)
def to_literals(self):
l = []
mask = 1 << len(self.variables)
for var in self.variables:
mask >>= 1
sign = bool(self.bits & mask)
l.append(Literal(sign=sign, var=var))
return l
class Row(object):
def __init__(self, assignment, falsified, cost, epts):
self.assignment = assignment
self.falsified = falsified
self.cost = cost
self.epts = epts
def __str__(self):
return "; ".join([str(self.assignment),
'{'+ ','.join(str(c) for c in self.falsified) + '}',
str(self.cost)])
def __repr__(self):
return "; ".join([repr(self.assignment),
repr(self.falsified),
repr(self.cost),
repr(self.epts)])
def __iter__(self):
return RowIterator(self)
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return NotImplemented
# Returns a new row that extends this row by the given ept. The new row has
# no EPTs.
def extend(self, ept):
assert all(r.cost <= self.cost for r in ept)
assignment = Assignment.combine(self.assignment,
*[r.assignment for r in ept])
falsified = self.falsified.union(*(r.falsified for r in ept))
return Row(assignment, falsified, self.cost, [])
# def find_falsified(self):
# """Find a "small" set of clauses such that every extension of this row
# falsifies at least one of these clauses.
#
# Formally, let C be a collection that contains, for each extension of
# this row, the clauses falsified by this extension. We are looking for a
# small hitting set for C.
#
# TODO: Explain more, write a one-liner docstring..."""
# assert self.cost > 0
# if self.falsified:
# return self.falsified
# # TODO
class RowIterator(object):
def __init__(self, row):
self.row = row
self.ept_it = iter(row.epts)
self.current_ept = None
self.child_iterators = None
self.current_combination = None
def __iter__(self):
return self
def next_ept(self):
self.current_ept = next(self.ept_it)
self.child_iterators = [RowIterator(r) for r in self.current_ept]
self.current_combination = [next(it) for it in self.child_iterators]
def increment(self, i=0):
if i == len(self.child_iterators):
# The last one was the rightmost extension iterator.
# Use next extension pointer tuple.
self.next_ept()
return
try:
self.current_combination[i] = next(self.child_iterators[i])
except StopIteration:
self.child_iterators[i] = RowIterator(self.current_ept[i])
self.current_combination[i] = next(self.child_iterators[i])
self.increment(i + 1)
def __next__(self):
if not self.current_ept:
self.next_ept()
else:
self.increment()
# self.current_combination now contains a row from each child table.
# We combine these and add the local information.
return self.row.extend(tuple(self.current_combination))
class Table(object):
def __init__(self, tree, formula):
self.td = tree
self.children = []
self.local_vars = list(tree.node)
self.new_vars = list(tree.introduced())
self.shared_vars = list(tree.shared())
self.hard_weight = formula.hard_weight
for subtree in tree.children:
self.children.append(Table(subtree, formula))
self.local_clauses = formula.induced_clauses(tree.node)
# Store clauses that contain an introduced variable.
self.new_clauses = []
# For each child, store clauses that are "present" in both this TD node
# and the child.
self.shared_clauses = [[]] * len(self.children)
for c in self.local_clauses:
if any(v in self.new_vars for v in c.variables()):
self.new_clauses.append(c)
else:
for i, child in enumerate(self.children):
if c in child.local_clauses:
self.shared_clauses[i].append(c)
self.rows = {} # maps assignments to rows
def __iter__(self):
return iter(self.rows.values())
def __str__(self):
return self.to_str()
def to_str(self, indent_level=0):
return '\n'.join(
' ' * indent_level
+ str(r) for r in self.rows.values())
def write_recursively(self, f=sys.stdout, indent_level=0):
"""Write descendants of this table to the given file."""
if indent_level > 0:
f.write('\n')
f.write(self.to_str(indent_level) + '\n')
indent_level += 1
for child in self.children:
child.write_recursively(f, indent_level)
def joinable(self, rows):
assert len(rows) == len(self.children)
if len(rows) < 2:
return True
return all(r.assignment.consistent(rows[0].assignment)
for r in rows[1:])
def unsat(self):
return all(r.cost > 0 for r in self.rows.values())
def sat(self):
return not self.unsat()
def locally_unsat(self):
return all(r.falsified for r in self.rows.values())
def deep_unsat_descendants(self):
if self.unsat() and all(c.sat() for c in self.children):
yield self
else:
if self.locally_unsat():
yield self
for c in self.children:
for d in c.deep_unsat_descendants():
yield d
def compute(self):
for child in self.children:
child.compute()
log.debug(f"Now computing table of bag {set(self.td.node)}")
# Go through all extension pointer tuples (EPTs)
for ept in itertools.product(
*(table.rows.values() for table in self.children)):
log.debug(f"EPT = {[str(ep) for ep in ept]}")
if not self.joinable(ept):
log.debug(" EPT not joinable")
continue
restricted_assignments = [
r.assignment.restrict(self.shared_vars[i])
for i, r in enumerate(ept)]
log.debug(f" Restricted assignments: {restricted_assignments}")
inherited_assignment = Assignment.combine(*restricted_assignments)
log.debug(f" Inherited assignment: {inherited_assignment}")
shared_cost = [
[c.weight for c in r.falsified
if c in self.shared_clauses[i]]
for i, r in enumerate(ept)]
forgotten_cost = (
sum(r.cost - sum(shared_cost[i])
for i, r in enumerate(ept)))
log.debug(f" forgotten_cost: {forgotten_cost}")
for bits in range(1 << len(self.new_vars)):
assignment = inherited_assignment.extend_disjoint(
list(self.new_vars), bits)
falsified = frozenset(c for c in self.local_clauses
if c.falsified(assignment))
cost = forgotten_cost + sum(c.weight for c in falsified)
log.debug(
f" Row candidate: "
f"{Row(assignment, falsified, cost, [ept])}")
if assignment in self.rows:
# XXX unnecessary extra lookup
row = self.rows[assignment]
if cost < row.cost:
log.debug(" Replacing existing row")
row.falsified = falsified
row.cost = cost
row.epts = [ept]
elif cost == row.cost:
log.debug(" Adding EPT to existing row")
assert row.falsified == falsified
row.epts.append(ept)
else:
log.debug(" Inserting new row")
new_row = Row(assignment, falsified, cost, [ept])
self.rows[assignment] = new_row
def unsat_cores(self):
for table in self.deep_unsat_descendants():
yield table.unsat_core()
def unsat_core(self):
# Note that a core for MaxSAT is a set of only soft clauses. It is not
# necessarily inconsistent in itself, but in combination with the hard
# clauses.
assert self.unsat()
# Unify the falsified clauses of each row.
# If a row has no falsified clauses, recursively extend it until we
# reach falsified clauses.
# return frozenset.union(*(r.find_falsified()
# for r in self.rows.values()))
# TODO explain the following
core = set()
stack = [r for r in self.rows.values() if r.cost < self.hard_weight]
# The latter condition excludes rows that have falsified hard clauses.
while stack:
row = stack.pop()
if row.falsified:
core |= row.falsified
else:
# For each EPT of the row, push an arbitrary EP with positive
# cost to the stack
for ept in row.epts:
stack.append(select_falsifying_ep(ept))
return core
if __name__ == "__main__":
signal(SIGPIPE, SIG_DFL)
parser = argparse.ArgumentParser(
description="Dynamic programming on a TD of a MaxSAT instance")
parser.add_argument("file")
parser.add_argument("--log", default="info")
args = parser.parse_args()
log_level_number = getattr(logging, args.log.upper(), None)
if not isinstance(log_level_number, int):
raise ValueError(f"Invalid log level: {loglevel}")
logging.basicConfig(level=log_level_number)
with open(args.file) as f:
print("Parsing...")
formula = Formula(f)
log.debug(formula)
print("Constructing primal graph...")
g = formula.primal_graph()
log.debug(g)
print("Decomposing...")
tds = Decomposer(g, Graph.min_degree_vertex,
normalize=TD.weakly_normalize).decompose()
assert len(tds) == 1
td = tds[0]
log.debug(td)
root_table = Table(td, formula)
print("Solving...")
root_table.compute()
print("Resulting tables:")
root_table.write_recursively()
# for row in root_table.rows.values():
# print(f"Extensions of root row {row}:")
# for extension in row:
# print(extension)
if root_table.unsat():
print("Some cores:")
for core in root_table.unsat_cores():
print(core)