multi-puzzle-solver 0.9.10__py3-none-any.whl → 0.9.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of multi-puzzle-solver might be problematic. Click here for more details.

@@ -0,0 +1,255 @@
1
+ import json
2
+ import time
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Union
5
+
6
+ from ortools.sat.python import cp_model
7
+ import numpy as np
8
+
9
+ from puzzle_solver.core.utils import Pos, get_all_pos, get_char, set_char, get_pos, in_bounds, Direction, get_next_pos
10
+ from puzzle_solver.core.utils_ortools import generic_solve_all, SingleSolution, force_connected_component
11
+
12
+
13
+ # a shape on the 2d board is just a set of positions
14
+ Shape = frozenset[Pos]
15
+
16
+
17
+ def polyominoes(N):
18
+ """Generate all polyominoes of size N. Every rotation and reflection is considered different and included in the result.
19
+ Translation is not considered different and is removed from the result (otherwise the result would be infinite).
20
+
21
+ Below is the number of unique polyominoes of size N (not including rotations and reflections) and the lenth of the returned result (which includes all rotations and reflections)
22
+ N name #shapes #results
23
+ 1 monomino 1 1
24
+ 2 domino 1 2
25
+ 3 tromino 2 6
26
+ 4 tetromino 5 19
27
+ 5 pentomino 12 63
28
+ 6 hexomino 35 216
29
+ 7 heptomino 108 760
30
+ 8 octomino 369 2,725
31
+ 9 nonomino 1,285 9,910
32
+ 10 decomino 4,655 36,446
33
+ 11 undecomino 17,073 135,268
34
+ 12 dodecomino 63,600 505,861
35
+ Source: https://en.wikipedia.org/wiki/Polyomino
36
+
37
+ Args:
38
+ N (int): The size of the polyominoes to generate.
39
+
40
+ Returns:
41
+ set[(frozenset[Pos], int)]: A set of all polyominoes of size N (rotated and reflected up to D4 symmetry) along with a unique ID for each polyomino.
42
+ """
43
+ assert N >= 1, 'N cannot be less than 1'
44
+ # need a frozenset because regular sets are not hashable
45
+ shapes: set[Shape] = {frozenset({Pos(0, 0)})}
46
+ for i in range(1, N):
47
+ next_shapes: set[Shape] = set()
48
+ for s in shapes:
49
+ # frontier: all 4-neighbors of existing cells not already in the shape
50
+ frontier = {get_next_pos(pos, direction)
51
+ for pos in s
52
+ for direction in Direction
53
+ if get_next_pos(pos, direction) not in s}
54
+ for cell in frontier:
55
+ t = s | {cell}
56
+ # normalize by translation only: shift so min x,y is (0,0). This removes translational symmetries.
57
+ minx = min(pos.x for pos in t)
58
+ miny = min(pos.y for pos in t)
59
+ t0 = frozenset(Pos(x=pos.x - minx, y=pos.y - miny) for pos in t)
60
+ next_shapes.add(t0)
61
+ shapes = next_shapes
62
+ # shapes is now complete, now classify up to D4 symmetry (rotations/reflections), translations ignored
63
+ mats = (
64
+ ( 1, 0, 0, 1), # regular
65
+ (-1, 0, 0, 1), # reflect about x
66
+ ( 1, 0, 0,-1), # reflect about y
67
+ (-1, 0, 0,-1), # reflect about x and y
68
+ # trnaspose then all 4 above
69
+ ( 0, 1, 1, 0), ( 0, 1, -1, 0), ( 0,-1, 1, 0), ( 0,-1, -1, 0),
70
+ )
71
+ # compute canonical representative for each shape (lexicographically smallest normalized transform)
72
+ shape_to_canon: dict[Shape, tuple[Pos, ...]] = {}
73
+ for s in shapes:
74
+ reps: list[tuple[Pos, ...]] = []
75
+ for a, b, c, d in mats:
76
+ pts = {Pos(x=a*p.x + b*p.y, y=c*p.x + d*p.y) for p in s}
77
+ minx = min(p.x for p in pts)
78
+ miny = min(p.y for p in pts)
79
+ rep = tuple(sorted(Pos(x=p.x - minx, y=p.y - miny) for p in pts))
80
+ reps.append(rep)
81
+ canon = min(reps)
82
+ shape_to_canon[s] = canon
83
+
84
+ canon_set = set(shape_to_canon.values())
85
+ canon_to_id = {canon: i for i, canon in enumerate(sorted(canon_set))}
86
+ result = {(s, canon_to_id[shape_to_canon[s]]) for s in shapes}
87
+ return result
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class SingleSolution:
92
+ assignment: dict[Pos, Union[str, int]]
93
+ all_other_variables: dict
94
+
95
+ def get_hashable_solution(self) -> str:
96
+ result = []
97
+ for pos, v in self.assignment.items():
98
+ result.append((pos.x, pos.y, v))
99
+ return json.dumps(result, sort_keys=True)
100
+
101
+
102
+
103
+ @dataclass
104
+ class ShapeOnBoard:
105
+ is_active: cp_model.IntVar
106
+ shape: Shape
107
+ shape_id: int
108
+ body: set[Pos]
109
+ disallow_same_shape: set[Pos]
110
+
111
+
112
+ class Board:
113
+ def __init__(self, board: np.array, polyomino_degrees: int = 4):
114
+ assert board.ndim == 2, f'board must be 2d, got {board.ndim}'
115
+ self.V = board.shape[0]
116
+ self.H = board.shape[1]
117
+ assert all((str(c.item()).isdecimal() for c in np.nditer(board))), 'board must contain only digits'
118
+ self.board = board
119
+ self.polyomino_degrees = polyomino_degrees
120
+ self.polyominoes = polyominoes(self.polyomino_degrees)
121
+
122
+ self.block_numbers = set([int(c.item()) for c in np.nditer(board)])
123
+ self.blocks = {i: set() for i in self.block_numbers}
124
+ for cell in get_all_pos(self.V, self.H):
125
+ self.blocks[int(get_char(self.board, cell))].add(cell)
126
+
127
+ self.model = cp_model.CpModel()
128
+ self.model_vars: dict[Pos, cp_model.IntVar] = {}
129
+ self.connected_components: dict[Pos, cp_model.IntVar] = {}
130
+ self.shapes_on_board: list[ShapeOnBoard] = [] # will contain every possible shape on the board based on polyomino degrees
131
+
132
+ self.create_vars()
133
+ self.init_shapes_on_board()
134
+ self.add_all_constraints()
135
+
136
+ def create_vars(self):
137
+ for pos in get_all_pos(self.V, self.H):
138
+ self.model_vars[pos] = self.model.NewBoolVar(f'{pos}')
139
+ # print('base vars:', len(self.model_vars))
140
+
141
+ def init_shapes_on_board(self):
142
+ for idx, (shape, shape_id) in enumerate(self.polyominoes):
143
+ for translate in get_all_pos(self.V, self.H): # body of shape is translated to be at pos
144
+ body = {get_pos(x=p.x + translate.x, y=p.y + translate.y) for p in shape}
145
+ if any(not in_bounds(p, self.V, self.H) for p in body):
146
+ continue
147
+ # shape must be fully contained in one block
148
+ if len(set(get_char(self.board, p) for p in body)) > 1:
149
+ continue
150
+ # 2 tetrominoes of matching types cannot touch each other horizontally or vertically. Rotations and reflections count as matching.
151
+ disallow_same_shape = set(get_next_pos(p, direction) for p in body for direction in Direction)
152
+ disallow_same_shape -= body
153
+ self.shapes_on_board.append(ShapeOnBoard(
154
+ is_active=self.model.NewBoolVar(f'{idx}:{translate}:is_active'),
155
+ shape=shape,
156
+ shape_id=shape_id,
157
+ body=body,
158
+ disallow_same_shape=disallow_same_shape,
159
+ ))
160
+ # print('shapes on board:', len(self.shapes_on_board))
161
+
162
+ def add_all_constraints(self):
163
+ # RULES:
164
+ # 1- You have to place one tetromino in each region in such a way that:
165
+ # 2- 2 tetrominoes of matching types cannot touch each other horizontally or vertically. Rotations and reflections count as matching.
166
+ # 3- The shaded cells should form a single connected area.
167
+ # 4- 2x2 shaded areas are not allowed
168
+
169
+ # each cell must be part of a shape, every shape must be fully on the board. Core constraint, otherwise shapes on the board make no sense.
170
+ self.only_allow_shapes_on_board()
171
+
172
+ self.force_one_shape_per_block() # Rule #1
173
+ self.disallow_same_shape_touching() # Rule #2
174
+ self.fc = force_connected_component(self.model, self.model_vars) # Rule #3
175
+ # print('force connected vars:', len(fc))
176
+ shape_2_by_2 = frozenset({Pos(0, 0), Pos(0, 1), Pos(1, 0), Pos(1, 1)})
177
+ self.disallow_shape(shape_2_by_2) # Rule #4
178
+
179
+
180
+ def only_allow_shapes_on_board(self):
181
+ for shape_on_board in self.shapes_on_board:
182
+ # if shape is active then all its body cells must be active
183
+ self.model.Add(sum(self.model_vars[p] for p in shape_on_board.body) == len(shape_on_board.body)).OnlyEnforceIf(shape_on_board.is_active)
184
+ # each cell must be part of a shape
185
+ for p in get_all_pos(self.V, self.H):
186
+ shapes_on_p = [s for s in self.shapes_on_board if p in s.body]
187
+ self.model.Add(sum(s.is_active for s in shapes_on_p) == 1).OnlyEnforceIf(self.model_vars[p])
188
+
189
+ def force_one_shape_per_block(self):
190
+ # You have to place exactly one tetromino in each region
191
+ for block_i in self.block_numbers:
192
+ shapes_on_block = [s for s in self.shapes_on_board if s.body & self.blocks[block_i]]
193
+ assert all(s.body.issubset(self.blocks[block_i]) for s in shapes_on_block), 'expected all shapes on block to be fully contained in the block'
194
+ # print(f'shapes on block {block_i} has {len(shapes_on_block)} shapes')
195
+ self.model.Add(sum(s.is_active for s in shapes_on_block) == 1)
196
+
197
+ def disallow_same_shape_touching(self):
198
+ # if shape is active then it must not touch any other shape of the same type
199
+ for shape_on_board in self.shapes_on_board:
200
+ similar_shapes = [s for s in self.shapes_on_board if s.shape_id == shape_on_board.shape_id]
201
+ for s in similar_shapes:
202
+ if shape_on_board.disallow_same_shape & s.body: # this shape disallows having s be on the board
203
+ self.model.Add(s.is_active == 0).OnlyEnforceIf(shape_on_board.is_active)
204
+
205
+ def disallow_shape(self, shape_to_disallow: Shape):
206
+ # for every position in the board, force sum of body < len(body)
207
+ for translate in get_all_pos(self.V, self.H):
208
+ cur_body = {get_pos(x=p.x + translate.x, y=p.y + translate.y) for p in shape_to_disallow}
209
+ if any(not in_bounds(p, self.V, self.H) for p in cur_body):
210
+ continue
211
+ self.model.Add(sum(self.model_vars[p] for p in cur_body) < len(cur_body))
212
+
213
+
214
+
215
+
216
+ def solve_and_print(self, verbose: bool = True, max_solutions: Optional[int] = None, verbose_callback: Optional[bool] = None):
217
+ if verbose_callback is None:
218
+ verbose_callback = verbose
219
+ def board_to_solution(board: Board, solver: cp_model.CpSolverSolutionCallback) -> SingleSolution:
220
+ assignment: dict[Pos, int] = {}
221
+ for pos, var in board.model_vars.items():
222
+ assignment[pos] = solver.Value(var)
223
+ all_other_variables = {
224
+ 'fc': {k: solver.Value(v) for k, v in board.fc.items()}
225
+ }
226
+ return SingleSolution(assignment=assignment, all_other_variables=all_other_variables)
227
+ def callback(single_res: SingleSolution):
228
+ print("Solution found")
229
+ res = np.full((self.V, self.H), ' ', dtype=str)
230
+ for pos, val in single_res.assignment.items():
231
+ c = 'X' if val == 1 else ' '
232
+ set_char(res, pos, c)
233
+ print('[\n' + '\n'.join([' ' + str(res[row].tolist()) + ',' for row in range(self.V)]) + '\n]')
234
+ pass
235
+ return generic_solve_all(self, board_to_solution, callback=callback if verbose_callback else None, verbose=verbose, max_solutions=max_solutions)
236
+
237
+ def solve_then_constrain(self, verbose: bool = True):
238
+ tic = time.time()
239
+ all_solutions = []
240
+ while True:
241
+ solutions = self.solve_and_print(verbose=False, verbose_callback=verbose, max_solutions=1)
242
+ if len(solutions) == 0:
243
+ break
244
+ all_solutions.extend(solutions)
245
+ assignment = solutions[0].assignment
246
+ # constrain the board to not return the same solution again
247
+ lits = [self.model_vars[p].Not() if assignment[p] == 1 else self.model_vars[p] for p in assignment.keys()]
248
+ self.model.AddBoolOr(lits)
249
+ self.model.ClearHints()
250
+ for k, v in solutions[0].all_other_variables['fc'].items():
251
+ self.model.AddHint(self.fc[k], v)
252
+ print(f'Solutions found: {len(all_solutions)}')
253
+ toc = time.time()
254
+ print(f'Time taken: {toc - tic:.2f} seconds')
255
+ return all_solutions