-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
313 lines (260 loc) · 10.9 KB
/
solver.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
import random
import math
import itertools as it
import copy
import networkx as nx
from bidict import bidict
from pysat.formula import CNF
from pysat.solvers import Minisat22
class Solution:
def __init__(self, rows, cols, mines):
self.rows = rows
self.cols = cols
self.mines = mines
self.unsolved = mines
self.grid = nx.grid_2d_graph(rows, cols)
self.grid.add_edges_from([
((x, y), (x+1, y+1))
for x in range(rows-1)
for y in range(cols-1)
] + [
((x+1, y), (x, y+1))
for x in range(rows-1)
for y in range(cols-1)
], weight=1.4)
for n in self.grid.nodes:
self.grid.nodes[n]["value"] = 0
self.grid.nodes[n]["solved"] = False
self.grid.nodes[n]["flagged"] = False
def __str__(self):
string = ''
for i in range(self.rows):
for j in range(self.cols):
if self.grid.nodes[i, j]['solved']:
if self.grid.nodes[i, j]['value'] == -1:
if self.grid.nodes[i, j]['flagged']:
string = string + ' . '
else:
string = string + ' * '
else:
if self.grid.nodes[i, j]['value'] == 0:
string = string + ' '
else:
string = string + ' ' + str(self.grid.nodes[i, j]['value']) + ' '
else:
string = string + ' _ '
string = string + '\n'
return string
def sat_inspect_cell(solution, source, depth=1):
if not solution.grid.nodes[source]["solved"]:
return []
dfs_tree = nx.dfs_tree(solution.grid, source, depth_limit=depth)
border_nodes = set([n for n in dfs_tree.nodes if solution.grid.nodes[n]["solved"]
and any(not solution.grid.nodes[m]["solved"] for m in solution.grid.neighbors(n))])
if len(border_nodes) == 0:
return []
unknown_nodes = set()
for n in border_nodes:
for m in solution.grid.neighbors(n):
if not solution.grid.nodes[m]["solved"]:
unknown_nodes.add(m)
variable_by_node = bidict({})
variable = 1
for n in unknown_nodes:
variable_by_node[n] = variable
variable += 1
cnf = CNF()
for n in border_nodes:
if solution.grid.nodes[n]["value"] == -1:
continue
adj = list(solution.grid.neighbors(n))
adj_unknown = [m for m in adj if not solution.grid.nodes[m]["solved"]]
adj_mine = [m for m in adj if solution.grid.nodes[m]["solved"] and solution.grid.nodes[m]["value"] == -1]
variables = [variable_by_node[m] for m in adj_unknown]
mines_total = solution.grid.nodes[n]["value"]
mines_needed = mines_total - len(adj_mine)
left_combis = set(it.combinations(variables, len(adj_unknown) + 1 - mines_needed))
right_combis = set(it.combinations(variables, 1 + mines_needed))
for lc in left_combis:
cnf.append(lc)
for rc in right_combis:
cnf.append([-1 * rc[i] for i in range(len(rc))])
solutions = []
for i in range(100000):
with Minisat22(bootstrap_with=cnf.clauses) as solver:
has_solution = solver.solve()
model = solver.get_model()
if has_solution:
cnf.append([-1 * model[i] for i in range(len(model))])
solutions.append(model)
else:
break
discovered_variables = []
for j in range(len(solutions[0])):
certain = True
first = solutions[0][j]
for i in range(len(solutions)):
if not solutions[i][j] == first:
certain = False
break
if certain:
discovered_variables.append(first)
solved_nodes = []
for v in discovered_variables:
node = variable_by_node.inv[abs(v)]
solved_nodes.append(node)
if v > 0:
solution.grid.nodes[node]["flagged"] = True
return solved_nodes
def sat_inspect(solution, depth=1):
solved_nodes = []
for n in solution.grid.nodes:
solved_nodes += sat_inspect_cell(solution, n, depth=depth)
return solved_nodes
def solve_remainder(solution, cutoff=16):
global_mines_solved = sum(
1 for n in solution.grid.nodes if solution.grid.nodes[n]["solved"] and solution.grid.nodes[n]["value"] == -1
)
global_mines_needed = solution.mines - global_mines_solved
border_nodes = set([
n for n in solution.grid.nodes if solution.grid.nodes[n]["solved"]
and any(not solution.grid.nodes[m]["solved"] for m in solution.grid.neighbors(n))
])
unknown_nodes = set([
n for n in solution.grid.nodes if not solution.grid.nodes[n]["solved"]
])
if len(unknown_nodes) <= cutoff:
variable_by_node = bidict({})
variable = 1
for n in unknown_nodes:
variable_by_node[n] = variable
variable += 1
cnf = CNF()
global_left_combis = set(
it.combinations(
list(variable_by_node.values()),
len(unknown_nodes) + 1 - global_mines_needed
)
)
global_right_combis = set(
it.combinations(
list(variable_by_node.values()),
1 + global_mines_needed
)
)
for glc in global_left_combis:
cnf.append(glc)
for grc in global_right_combis:
cnf.append([-1 * grc[i] for i in range(len(grc))])
for n in border_nodes:
if solution.grid.nodes[n]["value"] == -1:
continue
adj = list(solution.grid.neighbors(n))
adj_unknown = [m for m in adj if not solution.grid.nodes[m]["solved"]]
adj_mine = [m for m in adj if solution.grid.nodes[m]["solved"] and solution.grid.nodes[m]["value"] == -1]
variables = [variable_by_node[m] for m in adj_unknown]
mines_total = solution.grid.nodes[n]["value"]
mines_needed = mines_total - len(adj_mine)
left_combis = set(
it.combinations(
variables,
len(adj_unknown) + 1 - mines_needed
)
)
right_combis = set(
it.combinations(
variables,
1 + mines_needed
)
)
for lc in left_combis:
cnf.append(lc)
for rc in right_combis:
cnf.append([-1 * rc[i] for i in range(len(rc))])
solutions = []
for i in range(100000):
with Minisat22(bootstrap_with=cnf.clauses) as solver:
has_solution = solver.solve()
model = solver.get_model()
if has_solution:
cnf.append([-1 * model[i] for i in range(len(model))])
solutions.append(model)
else:
break
discovered_variables = []
for j in range(len(solutions[0])):
certain = True
first = solutions[0][j]
for i in range(len(solutions)):
if not solutions[i][j] == first:
certain = False
break
if certain:
discovered_variables.append(first)
solved_nodes = []
for v in discovered_variables:
node = variable_by_node.inv[abs(v)]
solved_nodes.append(node)
if v > 0:
solutions.grid.nodes[node]["flagged"] = True
return solved_nodes
else:
return []
def guess_node(board, solution):
unknown_nodes = set([n for n in solution.grid.nodes if not solution.grid.nodes[n]["solved"]])
if len(unknown_nodes) == 0:
return []
mines_solved = sum(1 for n in solution.grid.nodes if solution.grid.nodes[n]["solved"] and solution.grid.nodes[n]["value"] == -1)
mines_needed = solution.mines - mines_solved
landlocked_nodes = set([n for n in unknown_nodes if all(not solution.grid.nodes[m]["solved"] for m in solution.grid.neighbors(n))])
non_landlocked_nodes = set([n for n in unknown_nodes if any(solution.grid.nodes[m]["solved"] and solution.grid.nodes[m]["value"] != -1 for m in solution.grid.neighbors(n))])
possible_guesses = dict()
safety_weight = 1
progress_weight = 0.2
for n in landlocked_nodes:
a = math.comb(len(unknown_nodes) - 1 - len(list(solution.grid.neighbors(n))), mines_needed)
b = math.comb(len(unknown_nodes) - 1 , mines_needed)
progress = a / b
mines_accounted = 0
for m in solution.grid.nodes:
mines_accounted += solution.grid.nodes[m]["value"] - len([k for k in solution.grid.neighbors(m) if solution.grid.nodes[k]["flagged"]])
safety = 1 - ((mines_needed - mines_accounted) / (len(unknown_nodes) - 1))
if safety == 1:
return n
else:
possible_guesses[n] = safety * safety_weight + progress * progress_weight
for n in non_landlocked_nodes:
surroundings = [m for m in solution.grid.neighbors(n) if solution.grid.nodes[m]["solved"] and solution.grid.nodes[m]["value"] != -1]
unknown_neighbors = [m for m in solution.grid.neighbors(n) if not solution.grid.nodes[m]["solved"]]
safeties = []
for m in surroundings:
val = solution.grid.nodes[m]["value"]
val -= len([k for k in solution.grid.neighbors(m) if solution.grid.nodes[k]["flagged"]])
local_space = len([k for k in solution.grid.neighbors(m) if not solution.grid.nodes[k]["solved"]])
safeties.append(1 - (val/local_space))
safety = sum(safeties)/len(safeties)
possible_guesses[n] = safety
progress = 0
mine_value_range = range(len([m for m in solution.grid.neighbors(n) if solution.grid.nodes[m]["value"] == -1]), len([m for m in solution.grid.neighbors(n) if not solution.grid.nodes[m]["solved"]]))
for i in mine_value_range:
try:
fake_solution = copy.deepcopy(solution)
fake_solution.grid = solution.grid.copy()
fake_solution.grid.nodes[n]["value"] = i
fake_solution.grid.nodes[n]["solved"] = True
if len(sat_inspect(fake_solution)) >= 1:
progress += 1
except:
continue
progress /= max(len(mine_value_range), 1)
possible_guesses[n] = safety * safety_weight + progress * progress_weight
if possible_guesses:
guess = sorted(possible_guesses, key=lambda x: possible_guesses[x], reverse=True)[0]
return guess
else:
return random.choice(list(unknown_nodes))
def is_complete(solution):
for n in solution.grid.nodes:
if not solution.grid.nodes[n]["solved"]:
return False
return True