multi-puzzle-solver 0.9.3__py3-none-any.whl → 0.9.4__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.
- {multi_puzzle_solver-0.9.3.dist-info → multi_puzzle_solver-0.9.4.dist-info}/METADATA +91 -5
- {multi_puzzle_solver-0.9.3.dist-info → multi_puzzle_solver-0.9.4.dist-info}/RECORD +8 -6
- puzzle_solver/__init__.py +2 -1
- puzzle_solver/puzzles/stitches/parse_map/parse_map.py +209 -0
- puzzle_solver/puzzles/stitches/stitches.py +111 -0
- puzzle_solver/utils/visualizer.py +50 -24
- {multi_puzzle_solver-0.9.3.dist-info → multi_puzzle_solver-0.9.4.dist-info}/WHEEL +0 -0
- {multi_puzzle_solver-0.9.3.dist-info → multi_puzzle_solver-0.9.4.dist-info}/top_level.txt +0 -0
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: multi-puzzle-solver
|
3
|
-
Version: 0.9.
|
3
|
+
Version: 0.9.4
|
4
4
|
Summary: Efficient solvers for numerous popular and esoteric logic puzzles using CP-SAT
|
5
5
|
Author: Ar-Kareem
|
6
6
|
Project-URL: Homepage, https://github.com/Ar-Kareem/puzzle_solver
|
@@ -232,6 +232,11 @@ These are all the puzzles that are implemented in this repo. <br> Click on any o
|
|
232
232
|
<img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/aquarium_solved.png" alt="Aquarium" width="140">
|
233
233
|
</a>
|
234
234
|
</td>
|
235
|
+
<td align="center">
|
236
|
+
<a href="#stitches-puzzle-type-28"><b>Stitches</b><br><br>
|
237
|
+
<img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/stitches_solved.png" alt="Stitches" width="140">
|
238
|
+
</a>
|
239
|
+
</td>
|
235
240
|
</tr>
|
236
241
|
</table>
|
237
242
|
|
@@ -274,6 +279,7 @@ These are all the puzzles that are implemented in this repo. <br> Click on any o
|
|
274
279
|
- [Chess Melee (Puzzle Type #25)](#chess-melee-puzzle-type-25)
|
275
280
|
- [Thermometers (Puzzle Type #26)](#thermometers-puzzle-type-26)
|
276
281
|
- [Aquarium (Puzzle Type #27)](#aquarium-puzzle-type-27)
|
282
|
+
- [Stitches (Puzzle Type #28)](#stitches-puzzle-type-28)
|
277
283
|
- [Why SAT / CP-SAT?](#why-sat--cp-sat)
|
278
284
|
- [Testing](#testing)
|
279
285
|
- [Contributing](#contributing)
|
@@ -2134,8 +2140,6 @@ The numbers outside the grid show the number of filled cells horizontally and ve
|
|
2134
2140
|
|
2135
2141
|
Code to utilize this package and solve the puzzle:
|
2136
2142
|
|
2137
|
-
(Note that this puzzle does not typically have a unique solution. Thus, we specify here that we only want the first valid solution that the solver finds.)
|
2138
|
-
|
2139
2143
|
```python
|
2140
2144
|
from puzzle_solver import thermometers_solver as solver
|
2141
2145
|
board = np.array([
|
@@ -2184,6 +2188,12 @@ status: OPTIMAL
|
|
2184
2188
|
Time taken: 0.01 seconds
|
2185
2189
|
```
|
2186
2190
|
|
2191
|
+
**Solved puzzle**
|
2192
|
+
|
2193
|
+
<img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/thermometers_solved.png" alt="Thermometers solved" width="500">
|
2194
|
+
|
2195
|
+
---
|
2196
|
+
|
2187
2197
|
## Aquarium (Puzzle Type #27)
|
2188
2198
|
|
2189
2199
|
* [**Play online**](https://www.puzzle-aquarium.com/)
|
@@ -2209,8 +2219,6 @@ The numbers outside the grid show the number of filled cells horizontally and ve
|
|
2209
2219
|
|
2210
2220
|
Code to utilize this package and solve the puzzle:
|
2211
2221
|
|
2212
|
-
(Note that this puzzle does not typically have a unique solution. Thus, we specify here that we only want the first valid solution that the solver finds.)
|
2213
|
-
|
2214
2222
|
```python
|
2215
2223
|
from puzzle_solver import aquarium_solver as solver
|
2216
2224
|
board = np.array([
|
@@ -2265,6 +2273,83 @@ Time taken: 0.02 seconds
|
|
2265
2273
|
|
2266
2274
|
---
|
2267
2275
|
|
2276
|
+
## Stitches (Puzzle Type #28)
|
2277
|
+
|
2278
|
+
* [**Play online**](https://www.puzzle-stitches.com/)
|
2279
|
+
|
2280
|
+
* [**Solver Code**][28]
|
2281
|
+
|
2282
|
+
<details>
|
2283
|
+
<summary><strong>Rules</strong></summary>
|
2284
|
+
|
2285
|
+
- Connect each block with ALL its neighbor blocks with exactly 1 "stitch" each.
|
2286
|
+
- A "stitch" connects 2 orthogonally adjacent cells from different blocks.
|
2287
|
+
- 2 stitches cannot share a hole.
|
2288
|
+
- The clues outside the grid indicate the number of holes on that row/column
|
2289
|
+
- For 2÷ puzzles, you have to use 2 stitches to connect neighbor blocks, for 3÷ puzzles - 3 stitches etc.
|
2290
|
+
|
2291
|
+
</details>
|
2292
|
+
|
2293
|
+
**Unsolved puzzle**
|
2294
|
+
|
2295
|
+
<img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/stitches_unsolved.png" alt="Stitches unsolved" width="500">
|
2296
|
+
|
2297
|
+
Code to utilize this package and solve the puzzle:
|
2298
|
+
|
2299
|
+
```python
|
2300
|
+
from puzzle_solver import stitches_solver as solver
|
2301
|
+
board = np.array([
|
2302
|
+
["00", "00", "00", "00", "00", "01", "01", "01", "01", "01", "01", "01", "01", "02", "02"],
|
2303
|
+
["00", "03", "03", "04", "00", "00", "01", "05", "05", "05", "05", "05", "01", "01", "02"],
|
2304
|
+
["00", "03", "04", "04", "04", "00", "05", "05", "05", "05", "05", "05", "05", "05", "02"],
|
2305
|
+
["00", "03", "04", "04", "04", "04", "05", "05", "06", "05", "02", "02", "02", "02", "02"],
|
2306
|
+
["07", "03", "03", "03", "03", "04", "06", "06", "06", "06", "06", "06", "06", "02", "02"],
|
2307
|
+
["07", "07", "07", "03", "03", "04", "04", "06", "08", "08", "08", "06", "02", "02", "02"],
|
2308
|
+
["07", "07", "03", "03", "03", "04", "04", "08", "08", "08", "08", "06", "06", "06", "02"],
|
2309
|
+
["07", "07", "07", "07", "07", "08", "08", "08", "09", "09", "08", "06", "08", "06", "02"],
|
2310
|
+
["10", "10", "07", "07", "09", "09", "09", "09", "09", "09", "08", "08", "08", "11", "02"],
|
2311
|
+
["10", "10", "07", "09", "09", "09", "09", "09", "09", "09", "09", "08", "08", "11", "02"],
|
2312
|
+
["10", "09", "09", "09", "12", "12", "12", "13", "09", "09", "11", "11", "11", "11", "11"],
|
2313
|
+
["10", "10", "10", "09", "12", "12", "12", "13", "09", "11", "11", "11", "13", "13", "11"],
|
2314
|
+
["14", "15", "10", "12", "12", "16", "17", "13", "13", "11", "13", "13", "13", "13", "11"],
|
2315
|
+
["14", "15", "10", "12", "16", "16", "17", "17", "13", "13", "13", "13", "13", "13", "11"],
|
2316
|
+
["14", "15", "15", "12", "16", "16", "17", "17", "17", "17", "17", "13", "13", "13", "13"]
|
2317
|
+
])
|
2318
|
+
top = np.array([6, 6, 9, 5, 3, 8, 9, 3, 1, 4, 4, 1, 4, 8, 5])
|
2319
|
+
side = np.array([0, 10, 6, 4, 4, 1, 5, 8, 2, 6, 5, 11, 4, 3, 7])
|
2320
|
+
binst = solver.Board(board=board, top=top, side=side)
|
2321
|
+
solutions = binst.solve_and_print()
|
2322
|
+
```
|
2323
|
+
**Script Output**
|
2324
|
+
|
2325
|
+
```python
|
2326
|
+
Solution found
|
2327
|
+
[[' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ']
|
2328
|
+
['R' 'L' 'D' 'R' 'L' 'R' 'L' ' ' ' ' ' ' ' ' ' ' 'D' 'R' 'L']
|
2329
|
+
[' ' ' ' 'U' ' ' ' ' 'R' 'L' ' ' ' ' ' ' ' ' ' ' 'U' 'R' 'L']
|
2330
|
+
['D' ' ' ' ' ' ' ' ' 'R' 'L' ' ' ' ' 'D' ' ' ' ' ' ' ' ' ' ']
|
2331
|
+
['U' ' ' ' ' ' ' ' ' 'R' 'L' ' ' ' ' 'U' ' ' ' ' ' ' ' ' ' ']
|
2332
|
+
[' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'D' ' ']
|
2333
|
+
[' ' ' ' 'D' ' ' ' ' ' ' 'R' 'L' ' ' 'D' ' ' ' ' ' ' 'U' ' ']
|
2334
|
+
[' ' 'D' 'U' ' ' 'R' 'L' ' ' ' ' ' ' 'U' ' ' 'R' 'L' 'D' ' ']
|
2335
|
+
[' ' 'U' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'U' ' ']
|
2336
|
+
[' ' ' ' 'R' 'L' ' ' ' ' ' ' ' ' ' ' ' ' 'D' ' ' 'R' 'L' 'D']
|
2337
|
+
[' ' ' ' 'D' ' ' ' ' ' ' 'R' 'L' ' ' ' ' 'U' ' ' ' ' ' ' 'U']
|
2338
|
+
['D' 'D' 'U' 'R' 'L' 'D' 'D' 'R' 'L' ' ' ' ' ' ' ' ' 'R' 'L']
|
2339
|
+
['U' 'U' ' ' ' ' ' ' 'U' 'U' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ']
|
2340
|
+
[' ' ' ' 'R' 'L' ' ' ' ' ' ' ' ' ' ' ' ' 'D' ' ' ' ' ' ' ' ']
|
2341
|
+
['R' 'L' 'R' 'L' ' ' 'R' 'L' ' ' ' ' ' ' 'U' ' ' ' ' ' ' ' ']]
|
2342
|
+
Solutions found: 1
|
2343
|
+
status: OPTIMAL
|
2344
|
+
Time taken: 0.01 seconds
|
2345
|
+
```
|
2346
|
+
|
2347
|
+
**Solved puzzle**
|
2348
|
+
|
2349
|
+
<img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/stitches_solved.png" alt="Stitches solved" width="500">
|
2350
|
+
|
2351
|
+
---
|
2352
|
+
|
2268
2353
|
---
|
2269
2354
|
|
2270
2355
|
## Why SAT / CP-SAT?
|
@@ -2343,3 +2428,4 @@ Issues and PRs welcome!
|
|
2343
2428
|
[25]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/chess_range#chess-melee-puzzle-type-25 "puzzle_solver/src/puzzle_solver/puzzles/chess_range at master · Ar-Kareem/puzzle_solver · GitHub"
|
2344
2429
|
[26]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/thermometers "puzzle_solver/src/puzzle_solver/puzzles/thermometers at master · Ar-Kareem/puzzle_solver · GitHub"
|
2345
2430
|
[27]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/aquarium "puzzle_solver/src/puzzle_solver/puzzles/aquarium at master · Ar-Kareem/puzzle_solver · GitHub"
|
2431
|
+
[28]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/stitches "puzzle_solver/src/puzzle_solver/puzzles/stitches at master · Ar-Kareem/puzzle_solver · GitHub"
|
@@ -1,4 +1,4 @@
|
|
1
|
-
puzzle_solver/__init__.py,sha256=
|
1
|
+
puzzle_solver/__init__.py,sha256=J4CxLjjSv2Lbfk5spsG42NR1JcQNrspGpt7Yz3EIx9o,2038
|
2
2
|
puzzle_solver/core/utils.py,sha256=3LlBDuie_G0uSlzibpQS2ULmEYSZmpJXh1kawj7rjkg,3396
|
3
3
|
puzzle_solver/core/utils_ortools.py,sha256=qLTIzmITqmgGZvg8XpYAZ4c-lhD5sEDQfS8ECdQ_dkM,3005
|
4
4
|
puzzle_solver/puzzles/aquarium/aquarium.py,sha256=BUfkAS2d9eG3TdMoe1cOGGeNYgKUebRvn-z9nsC9gvE,5708
|
@@ -24,6 +24,8 @@ puzzle_solver/puzzles/pearl/pearl.py,sha256=AP0whWwwZ-1zKingW14OwseYylNAr6NkXSrv
|
|
24
24
|
puzzle_solver/puzzles/range/range.py,sha256=g6ZuHuulYLpNFsqbnPoIB5KoGPllYppU10-Zzqfj5f8,6993
|
25
25
|
puzzle_solver/puzzles/signpost/signpost.py,sha256=D19ua8rVwO6sgXq4nVLkZfEyz8hqc6qMOk3j-g44soU,3931
|
26
26
|
puzzle_solver/puzzles/singles/singles.py,sha256=kwMENfqQ-OP3YIz5baY6LRcvYCsNfhImEXN00lwazKM,5658
|
27
|
+
puzzle_solver/puzzles/stitches/stitches.py,sha256=YvT9WXvUMPLcFGOYXWIPyifCi6caZqRqBTuCgNmcTPQ,6662
|
28
|
+
puzzle_solver/puzzles/stitches/parse_map/parse_map.py,sha256=_BcYXtDCieKaPOpjG8BFHaFIkbYvMyuwzLL-TmjFZ2k,8786
|
27
29
|
puzzle_solver/puzzles/sudoku/sudoku.py,sha256=M_pry7XyKKzlfCF5rFi02lyOrj5GWZzXnDAxmD3NXvI,3588
|
28
30
|
puzzle_solver/puzzles/tents/tents.py,sha256=iyVK2WXfIT5j_9qqlQg0WmwvixwXlZSsHGK3XA-KpII,6283
|
29
31
|
puzzle_solver/puzzles/thermometers/thermometers.py,sha256=nsvJZkm7G8FALT27bpaB0lv5E_AWawqmvapQI8QcYXw,4015
|
@@ -31,8 +33,8 @@ puzzle_solver/puzzles/towers/towers.py,sha256=QvL0Pp-Z2ewCeq9ZkNrh8MShKOh-Y52sFB
|
|
31
33
|
puzzle_solver/puzzles/tracks/tracks.py,sha256=VnAtxBkuUTHJYNXr1JGg0yYzJj3kRMBi8Nz7NHKS94A,9089
|
32
34
|
puzzle_solver/puzzles/undead/undead.py,sha256=ygNugW5SOlYLy6d740gZ2IW9UJQ3SAr9vuMm0ZFr2nY,6630
|
33
35
|
puzzle_solver/puzzles/unruly/unruly.py,sha256=sDF0oKT50G-NshyW2DYrvAgD9q9Ku9ANUyNhGSAu7cQ,3827
|
34
|
-
puzzle_solver/utils/visualizer.py,sha256=
|
35
|
-
multi_puzzle_solver-0.9.
|
36
|
-
multi_puzzle_solver-0.9.
|
37
|
-
multi_puzzle_solver-0.9.
|
38
|
-
multi_puzzle_solver-0.9.
|
36
|
+
puzzle_solver/utils/visualizer.py,sha256=0DP3qs4RC0FDxHNBwPFjk6Y1RDvmLdI1jVFpYweCC00,5878
|
37
|
+
multi_puzzle_solver-0.9.4.dist-info/METADATA,sha256=4eFPtWAt3CIxMTbbJVZDxU5NCQie7QlXqfAlkNWR3lc,117546
|
38
|
+
multi_puzzle_solver-0.9.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
39
|
+
multi_puzzle_solver-0.9.4.dist-info/top_level.txt,sha256=exwVUQa-anK9vYrpKzBPvH8bX43iElWI4VeNiAyBGJY,14
|
40
|
+
multi_puzzle_solver-0.9.4.dist-info/RECORD,,
|
puzzle_solver/__init__.py
CHANGED
@@ -18,6 +18,7 @@ from puzzle_solver.puzzles.pearl import pearl as pearl_solver
|
|
18
18
|
from puzzle_solver.puzzles.range import range as range_solver
|
19
19
|
from puzzle_solver.puzzles.signpost import signpost as signpost_solver
|
20
20
|
from puzzle_solver.puzzles.singles import singles as singles_solver
|
21
|
+
from puzzle_solver.puzzles.stitches import stitches as stitches_solver
|
21
22
|
from puzzle_solver.puzzles.sudoku import sudoku as sudoku_solver
|
22
23
|
from puzzle_solver.puzzles.tents import tents as tents_solver
|
23
24
|
from puzzle_solver.puzzles.thermometers import thermometers as thermometers_solver
|
@@ -28,4 +29,4 @@ from puzzle_solver.puzzles.unruly import unruly as unruly_solver
|
|
28
29
|
|
29
30
|
from puzzle_solver.puzzles.inertia.parse_map.parse_map import main as inertia_image_parser
|
30
31
|
|
31
|
-
__version__ = '0.9.
|
32
|
+
__version__ = '0.9.4'
|
@@ -0,0 +1,209 @@
|
|
1
|
+
"""
|
2
|
+
This file is a simple helper that parses the images from https://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/inertia.html and converts them to a json file.
|
3
|
+
Look at the ./input_output/ directory for examples of input images and output json files.
|
4
|
+
The output json is used in the test_solve.py file to test the solver.
|
5
|
+
"""
|
6
|
+
from pathlib import Path
|
7
|
+
import numpy as np
|
8
|
+
import numpy as np
|
9
|
+
import matplotlib.pyplot as plt
|
10
|
+
cv = None
|
11
|
+
Image = None
|
12
|
+
|
13
|
+
|
14
|
+
def extract_lines(bw):
|
15
|
+
# Create the images that will use to extract the horizontal and vertical lines
|
16
|
+
horizontal = np.copy(bw)
|
17
|
+
vertical = np.copy(bw)
|
18
|
+
|
19
|
+
cols = horizontal.shape[1]
|
20
|
+
horizontal_size = cols // 5
|
21
|
+
# Create structure element for extracting horizontal lines through morphology operations
|
22
|
+
horizontalStructure = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1))
|
23
|
+
horizontal = cv.erode(horizontal, horizontalStructure)
|
24
|
+
horizontal = cv.dilate(horizontal, horizontalStructure)
|
25
|
+
horizontal_means = np.mean(horizontal, axis=1)
|
26
|
+
horizontal_cutoff = np.percentile(horizontal_means, 50)
|
27
|
+
# location where the horizontal lines are
|
28
|
+
horizontal_idx = np.where(horizontal_means > horizontal_cutoff)[0]
|
29
|
+
# print(f"horizontal_idx: {horizontal_idx}")
|
30
|
+
height = len(horizontal_idx)
|
31
|
+
# show_wait_destroy("horizontal", horizontal) # this has the horizontal lines
|
32
|
+
|
33
|
+
rows = vertical.shape[0]
|
34
|
+
verticalsize = rows // 5
|
35
|
+
# Create structure element for extracting vertical lines through morphology operations
|
36
|
+
verticalStructure = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize))
|
37
|
+
vertical = cv.erode(vertical, verticalStructure)
|
38
|
+
vertical = cv.dilate(vertical, verticalStructure)
|
39
|
+
vertical_means = np.mean(vertical, axis=0)
|
40
|
+
vertical_cutoff = np.percentile(vertical_means, 50)
|
41
|
+
vertical_idx = np.where(vertical_means > vertical_cutoff)[0]
|
42
|
+
# print(f"vertical_idx: {vertical_idx}")
|
43
|
+
width = len(vertical_idx)
|
44
|
+
# print(f"height: {height}, width: {width}")
|
45
|
+
# print(f"vertical_means: {vertical_means}")
|
46
|
+
# show_wait_destroy("vertical", vertical) # this has the vertical lines
|
47
|
+
|
48
|
+
vertical = cv.bitwise_not(vertical)
|
49
|
+
# show_wait_destroy("vertical_bit", vertical)
|
50
|
+
|
51
|
+
return horizontal_idx, vertical_idx
|
52
|
+
|
53
|
+
def show_wait_destroy(winname, img):
|
54
|
+
cv.imshow(winname, img)
|
55
|
+
cv.moveWindow(winname, 500, 0)
|
56
|
+
cv.waitKey(0)
|
57
|
+
cv.destroyWindow(winname)
|
58
|
+
|
59
|
+
|
60
|
+
def mean_consecutives(arr: np.ndarray) -> np.ndarray:
|
61
|
+
"""if a sequence of values is consecutive, then average the values"""
|
62
|
+
sums = []
|
63
|
+
counts = []
|
64
|
+
for i in range(len(arr)):
|
65
|
+
if i == 0:
|
66
|
+
sums.append(arr[i])
|
67
|
+
counts.append(1)
|
68
|
+
elif arr[i] == arr[i-1] + 1:
|
69
|
+
sums[-1] += arr[i]
|
70
|
+
counts[-1] += 1
|
71
|
+
else:
|
72
|
+
sums.append(arr[i])
|
73
|
+
counts.append(1)
|
74
|
+
return np.array(sums) // np.array(counts)
|
75
|
+
|
76
|
+
def dfs(x, y, out, output, current_num):
|
77
|
+
if x < 0 or x >= out.shape[1] or y < 0 or y >= out.shape[0]:
|
78
|
+
return
|
79
|
+
if out[y, x] != ' ':
|
80
|
+
return
|
81
|
+
out[y, x] = current_num
|
82
|
+
if output['top'][y, x] == 0:
|
83
|
+
dfs(x, y-1, out, output, current_num)
|
84
|
+
if output['left'][y, x] == 0:
|
85
|
+
dfs(x-1, y, out, output, current_num)
|
86
|
+
if output['right'][y, x] == 0:
|
87
|
+
dfs(x+1, y, out, output, current_num)
|
88
|
+
if output['bottom'][y, x] == 0:
|
89
|
+
dfs(x, y+1, out, output, current_num)
|
90
|
+
|
91
|
+
def main(image):
|
92
|
+
global Image
|
93
|
+
global cv
|
94
|
+
from PIL import Image as Image_module
|
95
|
+
import cv2 as cv_module
|
96
|
+
Image = Image_module
|
97
|
+
cv = cv_module
|
98
|
+
|
99
|
+
|
100
|
+
image_path = Path(image)
|
101
|
+
output_path = image_path.parent / (image_path.stem + '.json')
|
102
|
+
src = cv.imread(image, cv.IMREAD_COLOR)
|
103
|
+
assert src is not None, f'Error opening image: {image}'
|
104
|
+
if len(src.shape) != 2:
|
105
|
+
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
|
106
|
+
else:
|
107
|
+
gray = src
|
108
|
+
# now the image is in grayscale
|
109
|
+
|
110
|
+
# Apply adaptiveThreshold at the bitwise_not of gray, notice the ~ symbol
|
111
|
+
gray = cv.bitwise_not(gray)
|
112
|
+
bw = cv.adaptiveThreshold(gray.copy(), 255, cv.ADAPTIVE_THRESH_MEAN_C, \
|
113
|
+
cv.THRESH_BINARY, 15, -2)
|
114
|
+
# show_wait_destroy("binary", bw)
|
115
|
+
|
116
|
+
# show_wait_destroy("src", src)
|
117
|
+
horizontal_idx, vertical_idx = extract_lines(bw)
|
118
|
+
horizontal_idx = mean_consecutives(horizontal_idx)
|
119
|
+
vertical_idx = mean_consecutives(vertical_idx)
|
120
|
+
height = len(horizontal_idx)
|
121
|
+
width = len(vertical_idx)
|
122
|
+
print(f"height: {height}, width: {width}")
|
123
|
+
print(f"horizontal_idx: {horizontal_idx}")
|
124
|
+
print(f"vertical_idx: {vertical_idx}")
|
125
|
+
arr = np.zeros((height - 1, width - 1), dtype=object)
|
126
|
+
output = {'top': arr.copy(), 'left': arr.copy(), 'right': arr.copy(), 'bottom': arr.copy()}
|
127
|
+
target = 200_000
|
128
|
+
hists = {'top': {}, 'left': {}, 'right': {}, 'bottom': {}}
|
129
|
+
for j in range(height - 1):
|
130
|
+
for i in range(width - 1):
|
131
|
+
hidx1, hidx2 = horizontal_idx[j], horizontal_idx[j+1]
|
132
|
+
vidx1, vidx2 = vertical_idx[i], vertical_idx[i+1]
|
133
|
+
hidx1 = max(0, hidx1 - 2)
|
134
|
+
hidx2 = min(src.shape[0], hidx2 + 4)
|
135
|
+
vidx1 = max(0, vidx1 - 2)
|
136
|
+
vidx2 = min(src.shape[1], vidx2 + 4)
|
137
|
+
cell = src[hidx1:hidx2, vidx1:vidx2]
|
138
|
+
mid_x = cell.shape[1] // 2
|
139
|
+
mid_y = cell.shape[0] // 2
|
140
|
+
# show_wait_destroy(f"cell_{i}_{j}", cell)
|
141
|
+
cell = cv.bitwise_not(cell) # invert colors
|
142
|
+
top = cell[0:10, mid_y-5:mid_y+5]
|
143
|
+
hists['top'][j, i] = np.sum(top)
|
144
|
+
left = cell[mid_x-5:mid_x+5, 0:10]
|
145
|
+
hists['left'][j, i] = np.sum(left)
|
146
|
+
right = cell[mid_x-5:mid_x+5, -10:]
|
147
|
+
hists['right'][j, i] = np.sum(right)
|
148
|
+
bottom = cell[-10:, mid_y-5:mid_y+5]
|
149
|
+
hists['bottom'][j, i] = np.sum(bottom)
|
150
|
+
|
151
|
+
fig, axs = plt.subplots(2, 2)
|
152
|
+
axs[0, 0].hist(list(hists['top'].values()), bins=100)
|
153
|
+
axs[0, 0].set_title('Top')
|
154
|
+
axs[0, 1].hist(list(hists['left'].values()), bins=100)
|
155
|
+
axs[0, 1].set_title('Left')
|
156
|
+
axs[1, 0].hist(list(hists['right'].values()), bins=100)
|
157
|
+
axs[1, 0].set_title('Right')
|
158
|
+
axs[1, 1].hist(list(hists['bottom'].values()), bins=100)
|
159
|
+
axs[1, 1].set_title('Bottom')
|
160
|
+
target_top = np.mean(list(hists['top'].values()))
|
161
|
+
target_left = np.mean(list(hists['left'].values()))
|
162
|
+
target_right = np.mean(list(hists['right'].values()))
|
163
|
+
target_bottom = np.mean(list(hists['bottom'].values()))
|
164
|
+
axs[0, 0].axvline(target_top, color='red')
|
165
|
+
axs[0, 1].axvline(target_left, color='red')
|
166
|
+
axs[1, 0].axvline(target_right, color='red')
|
167
|
+
axs[1, 1].axvline(target_bottom, color='red')
|
168
|
+
# plt.show()
|
169
|
+
# 1/0
|
170
|
+
print(f"target_top: {target_top}, target_left: {target_left}, target_right: {target_right}, target_bottom: {target_bottom}")
|
171
|
+
for j in range(height - 1):
|
172
|
+
for i in range(width - 1):
|
173
|
+
if hists['top'][j, i] > target_top:
|
174
|
+
output['top'][j, i] = 1
|
175
|
+
if hists['left'][j, i] > target_left:
|
176
|
+
output['left'][j, i] = 1
|
177
|
+
if hists['right'][j, i] > target_right:
|
178
|
+
output['right'][j, i] = 1
|
179
|
+
if hists['bottom'][j, i] > target_bottom:
|
180
|
+
output['bottom'][j, i] = 1
|
181
|
+
print(f"cell_{j}_{i}", end=': ')
|
182
|
+
print('T' if output['top'][j, i] else '', end='')
|
183
|
+
print('L' if output['left'][j, i] else '', end='')
|
184
|
+
print('R' if output['right'][j, i] else '', end='')
|
185
|
+
print('B' if output['bottom'][j, i] else '', end='')
|
186
|
+
print(' Sums: ', hists['top'][j, i], hists['left'][j, i], hists['right'][j, i], hists['bottom'][j, i])
|
187
|
+
|
188
|
+
current_count = 0
|
189
|
+
out = np.full_like(output['top'], ' ', dtype='U2')
|
190
|
+
for j in range(out.shape[0]):
|
191
|
+
for i in range(out.shape[1]):
|
192
|
+
if out[j, i] == ' ':
|
193
|
+
dfs(i, j, out, output, str(current_count).zfill(2))
|
194
|
+
current_count += 1
|
195
|
+
|
196
|
+
with open(output_path, 'w') as f:
|
197
|
+
f.write('[\n')
|
198
|
+
for i, row in enumerate(out):
|
199
|
+
f.write(' ' + str(row.tolist()).replace("'", '"'))
|
200
|
+
if i != len(out) - 1:
|
201
|
+
f.write(',')
|
202
|
+
f.write('\n')
|
203
|
+
f.write(']')
|
204
|
+
print('output json: ', output_path)
|
205
|
+
|
206
|
+
if __name__ == '__main__':
|
207
|
+
# to run this script and visualize the output, in the root run:
|
208
|
+
# python .\src\puzzle_solver\puzzles\stitches\parse_map\parse_map.py | python .\src\puzzle_solver\utils\visualizer.py --read_stdin
|
209
|
+
main(Path(__file__).parent / 'input_output' / 'MTM6OSw4MjEsNDAx.png')
|
@@ -0,0 +1,111 @@
|
|
1
|
+
from collections import defaultdict
|
2
|
+
from typing import Union
|
3
|
+
|
4
|
+
import numpy as np
|
5
|
+
from ortools.sat.python import cp_model
|
6
|
+
from ortools.sat.python.cp_model import LinearExpr as lxp
|
7
|
+
|
8
|
+
from puzzle_solver.core.utils import Pos, get_all_pos, get_char, get_neighbors4, set_char, get_neighbors8, get_next_pos, Direction, get_row_pos, get_col_pos, in_bounds, get_opposite_direction
|
9
|
+
from puzzle_solver.core.utils_ortools import generic_solve_all, SingleSolution, and_constraint
|
10
|
+
|
11
|
+
|
12
|
+
class Board:
|
13
|
+
def __init__(self, board: np.array, top: np.array, side: np.array, connection_count=1):
|
14
|
+
assert board.ndim == 2, f'board must be 2d, got {board.ndim}'
|
15
|
+
self.V = board.shape[0]
|
16
|
+
self.H = board.shape[1]
|
17
|
+
assert top.ndim == 1 and top.shape[0] == self.H, 'top must be a 1d array of length board width'
|
18
|
+
assert side.ndim == 1 and side.shape[0] == self.V, 'side must be a 1d array of length board height'
|
19
|
+
assert all((str(c.item()).isdecimal() for c in np.nditer(board))), 'board must contain only digits'
|
20
|
+
assert isinstance(connection_count, int) and connection_count >= 1, f'connection count must be int and >= 1, got {connection_count}'
|
21
|
+
self.board = board
|
22
|
+
self.top = top
|
23
|
+
self.side = side
|
24
|
+
self.connection_count = connection_count
|
25
|
+
self.top_empties = [self.H - i for i in self.top]
|
26
|
+
self.side_empties = [self.V - i for i in self.side]
|
27
|
+
self.block_numbers = set([int(c.item()) for c in np.nditer(board)])
|
28
|
+
self.blocks = {i: [pos for pos in get_all_pos(self.V, self.H) if int(get_char(self.board, pos)) == i] for i in self.block_numbers}
|
29
|
+
# keys are (block_i, block_j) where block_i < block_j to avoid double counting
|
30
|
+
# values are sets of (pos_a, direction_a, pos_b, direction_b) where the two blocks meet
|
31
|
+
self.block_neighbors: dict[tuple[int, int], set[tuple[Pos, Direction, Pos, Direction]]] = {}
|
32
|
+
self.valid_stitches: set[tuple[Pos, Pos]] = set() # records all pairs of positions that can have a stitch
|
33
|
+
for pos in get_all_pos(self.V, self.H):
|
34
|
+
block_i = int(get_char(self.board, pos))
|
35
|
+
for direction in Direction:
|
36
|
+
neighbor = get_next_pos(pos, direction)
|
37
|
+
if not in_bounds(neighbor, self.V, self.H):
|
38
|
+
continue
|
39
|
+
block_j = int(get_char(self.board, neighbor))
|
40
|
+
if block_i < block_j: # avoid double counting
|
41
|
+
opposite_direction = get_opposite_direction(direction)
|
42
|
+
self.block_neighbors.setdefault((block_i, block_j), set()).add((pos, direction, neighbor, opposite_direction))
|
43
|
+
self.valid_stitches.add((pos, neighbor))
|
44
|
+
self.valid_stitches.add((neighbor, pos))
|
45
|
+
# for pair in self.block_neighbors.keys():
|
46
|
+
# print(pair, self.block_neighbors[pair])
|
47
|
+
# print('top empties', self.top_empties)
|
48
|
+
# print('side empties', self.side_empties)
|
49
|
+
|
50
|
+
self.model = cp_model.CpModel()
|
51
|
+
self.model_vars: dict[tuple[Pos, Union[Direction, None]], cp_model.IntVar] = {}
|
52
|
+
self.create_vars()
|
53
|
+
self.add_all_constraints()
|
54
|
+
|
55
|
+
def create_vars(self):
|
56
|
+
for pos in get_all_pos(self.V, self.H):
|
57
|
+
for direction in Direction:
|
58
|
+
self.model_vars[(pos, direction)] = self.model.NewBoolVar(f'{pos}:{direction}')
|
59
|
+
self.model_vars[(pos, None)] = self.model.NewBoolVar(f'{pos}:empty')
|
60
|
+
|
61
|
+
def add_all_constraints(self):
|
62
|
+
# every position has exactly 1 state
|
63
|
+
for pos in get_all_pos(self.V, self.H):
|
64
|
+
state = [self.model_vars[(pos, direction)] for direction in Direction]
|
65
|
+
state.append(self.model_vars[(pos, None)])
|
66
|
+
self.model.AddExactlyOne(state)
|
67
|
+
# print('ONLY 1 DIRECTION. only one', state)
|
68
|
+
# If a position points at X (and this is a valid pair) then X has to point at me
|
69
|
+
for pos in get_all_pos(self.V, self.H):
|
70
|
+
for direction in Direction:
|
71
|
+
neighbor = get_next_pos(pos, direction)
|
72
|
+
if not in_bounds(neighbor, self.V, self.H) or (pos, neighbor) not in self.valid_stitches:
|
73
|
+
# this is not a valid stitch
|
74
|
+
self.model.Add(self.model_vars[(pos, direction)] == 0)
|
75
|
+
# print(f'Pos {pos} cant be {direction}')
|
76
|
+
continue
|
77
|
+
opposite_direction = get_opposite_direction(direction)
|
78
|
+
self.model.Add(self.model_vars[(pos, direction)] == self.model_vars[(neighbor, opposite_direction)])
|
79
|
+
# print(f'{pos}:{direction} must == {neighbor}:{opposite_direction}')
|
80
|
+
|
81
|
+
# all blocks connected exactly N times (N usually 1 but can be 2 or 3)
|
82
|
+
for (block_i, block_j), connections in self.block_neighbors.items():
|
83
|
+
is_connected_list = []
|
84
|
+
for pos_a, direction_a, pos_b, direction_b in connections:
|
85
|
+
v = self.model.NewBoolVar(f'{pos_a}:{direction_a}->{pos_b}:{direction_b}')
|
86
|
+
and_constraint(self.model, v, [self.model_vars[pos_a, direction_a], self.model_vars[pos_b, direction_b]])
|
87
|
+
is_connected_list.append(v)
|
88
|
+
self.model.Add(sum(is_connected_list) == self.connection_count)
|
89
|
+
|
90
|
+
# sums of top and side must match
|
91
|
+
for col in range(self.H):
|
92
|
+
self.model.Add(sum([self.model_vars[pos, None] for pos in get_col_pos(col, self.V)]) == self.top_empties[col])
|
93
|
+
for row in range(self.V):
|
94
|
+
self.model.Add(sum([self.model_vars[pos, None] for pos in get_row_pos(row, self.H)]) == self.side_empties[row])
|
95
|
+
|
96
|
+
def solve_and_print(self, verbose: bool = True):
|
97
|
+
def board_to_solution(board: Board, solver: cp_model.CpSolverSolutionCallback) -> SingleSolution:
|
98
|
+
assignment: dict[Pos, str] = {}
|
99
|
+
for (pos, direction), var in board.model_vars.items():
|
100
|
+
if solver.value(var) == 1:
|
101
|
+
assignment[pos] = direction.name[0] if direction is not None else ' '
|
102
|
+
return SingleSolution(assignment=assignment)
|
103
|
+
def callback(single_res: SingleSolution):
|
104
|
+
print("Solution found")
|
105
|
+
res = np.full((self.V, self.H), ' ', dtype=object)
|
106
|
+
for pos in get_all_pos(self.V, self.H):
|
107
|
+
c = get_char(self.board, pos)
|
108
|
+
c = single_res.assignment[pos]
|
109
|
+
set_char(res, pos, c)
|
110
|
+
print(res)
|
111
|
+
return generic_solve_all(self, board_to_solution, callback=callback if verbose else None, verbose=verbose, max_solutions=9)
|
@@ -1,5 +1,8 @@
|
|
1
1
|
from __future__ import annotations
|
2
|
+
import argparse
|
2
3
|
from typing import Any, Mapping, Tuple
|
4
|
+
import json
|
5
|
+
import sys
|
3
6
|
|
4
7
|
import numpy as np
|
5
8
|
from PIL import Image, ImageDraw, ImageFont
|
@@ -9,13 +12,12 @@ RGB = Tuple[int, int, int]
|
|
9
12
|
def render_board_image(
|
10
13
|
board: np.ndarray,
|
11
14
|
colors: Mapping[Any, RGB],
|
12
|
-
output_filename: str,
|
13
15
|
cell_size: int = 64,
|
14
16
|
grid: bool = True,
|
15
17
|
bg_default: RGB = (240, 240, 240),
|
16
18
|
text_color: RGB = (0, 0, 0),
|
17
19
|
padding: int = 20,
|
18
|
-
) -> None:
|
20
|
+
) -> None:
|
19
21
|
"""
|
20
22
|
Render a 2D numpy array as a colored grid image with centered text labels.
|
21
23
|
|
@@ -23,7 +25,6 @@ def render_board_image(
|
|
23
25
|
board: 2D numpy array (dtype can be object/str/int/etc.). Each cell's value
|
24
26
|
is looked up in `colors` for its fill color.
|
25
27
|
colors: Dict-like mapping from cell values to RGB tuples (0-255).
|
26
|
-
output_filename: Where to save the image (e.g., 'board.png').
|
27
28
|
cell_size: Square side length (pixels) for each cell.
|
28
29
|
grid: Whether to draw grid lines around cells.
|
29
30
|
bg_default: Fill color when a cell's value is not in `colors`.
|
@@ -76,33 +77,58 @@ def render_board_image(
|
|
76
77
|
ty = y0 + (cell_size - th) / 2
|
77
78
|
draw.text((tx, ty), text, fill=text_color, font=font)
|
78
79
|
|
79
|
-
img.
|
80
|
+
img.show()
|
80
81
|
|
81
82
|
|
83
|
+
|
84
|
+
|
85
|
+
|
86
|
+
def get_input():
|
87
|
+
parser = argparse.ArgumentParser()
|
88
|
+
parser.add_argument('--read_stdin', action='store_true')
|
89
|
+
args = parser.parse_args()
|
90
|
+
if args.read_stdin:
|
91
|
+
# read from stdin until the line starts with "output json: "
|
92
|
+
print('reading board from stdin until the line starts with "output json: "')
|
93
|
+
json_path = None
|
94
|
+
while True:
|
95
|
+
line = sys.stdin.readline()
|
96
|
+
if line.startswith('output json: '):
|
97
|
+
json_path = line.split('output json: ')[1].strip()
|
98
|
+
break
|
99
|
+
with open(json_path, 'r') as f:
|
100
|
+
board = np.array(json.load(f))
|
101
|
+
print(f'read board from {json_path}')
|
102
|
+
else:
|
103
|
+
# with open('src/puzzle_solver/puzzles/stitches/parse_map/input_output/MTM6OSw4MjEsNDAx.json', 'r') as f:
|
104
|
+
# board = np.array(json.load(f))
|
105
|
+
board = np.array([
|
106
|
+
['01', '123', '01', '01', '02', '02', '02', '03', '03', '03', '03', '04', '05', '05', '05'],
|
107
|
+
['01', '02', '02', '02', '02', '06', '07', '07', '03', '08', '03', '04', '04', '05', '09'],
|
108
|
+
['01', '01', '02', '11', '06', '06', '06', '12', '12', '08', '13', '13', '13', '09', '09'],
|
109
|
+
['01', '11', '11', '11', '14', '06', '06', '12', '12', '15', '15', '13', '09', '09', '09'],
|
110
|
+
['01', '01', '11', '11', '14', '12', '12', '12', '16', '16', '15', '13', '13', '17', '09'],
|
111
|
+
['01', '11', '11', '14', '14', '12', '42', '42', '42', '15', '15', '13', '13', '17', '18'],
|
112
|
+
['01', '11', '11', '14', '14', '12', '12', '43', '15', '15', '20', '13', '13', '17', '18'],
|
113
|
+
['01', '01', '11', '19', '19', '19', '43', '43', '44', '20', '20', '20', '13', '17', '18'],
|
114
|
+
['01', '22', '23', '23', '23', '19', '43', '21', '21', '24', '24', '24', '25', '17', '17'],
|
115
|
+
['22', '22', '22', '23', '19', '19', '26', '24', '24', '24', '28', '28', '25', '17', '33'],
|
116
|
+
['22', '22', '23', '23', '27', '27', '26', '26', '24', '24', '29', '29', '25', '25', '33'],
|
117
|
+
['22', '22', '35', '27', '27', '26', '26', '26', '26', '30', '30', '30', '25', '34', '34'],
|
118
|
+
['37', '22', '35', '35', '35', '35', '35', '26', '26', '30', '31', '31', '32', '32', '40'],
|
119
|
+
['37', '37', '37', '36', '36', '35', '26', '26', '26', '40', '40', '40', '40', '40', '40'],
|
120
|
+
['37', '37', '37', '37', '35', '35', '38', '38', '39', '39', '40', '40', '40', '41', '41'],
|
121
|
+
])
|
122
|
+
return board
|
123
|
+
|
82
124
|
if __name__ == '__main__':
|
83
|
-
board =
|
84
|
-
['01', '01', '01', '01', '02', '02', '02', '03', '03', '03', '03', '04', '05', '05', '05'],
|
85
|
-
['01', '02', '02', '02', '02', '06', '07', '07', '03', '08', '03', '04', '04', '05', '09'],
|
86
|
-
['01', '01', '02', '11', '06', '06', '06', '12', '12', '08', '13', '13', '13', '09', '09'],
|
87
|
-
['01', '11', '11', '11', '14', '06', '06', '12', '12', '15', '15', '13', '09', '09', '09'],
|
88
|
-
['01', '01', '11', '11', '14', '12', '12', '12', '16', '16', '15', '13', '13', '17', '09'],
|
89
|
-
['01', '11', '11', '14', '14', '12', '42', '42', '42', '15', '15', '13', '13', '17', '18'],
|
90
|
-
['01', '11', '11', '14', '14', '12', '12', '43', '15', '15', '20', '13', '13', '17', '18'],
|
91
|
-
['01', '01', '11', '19', '19', '19', '43', '43', '44', '20', '20', '20', '13', '17', '18'],
|
92
|
-
['01', '22', '23', '23', '23', '19', '43', '21', '21', '24', '24', '24', '25', '17', '17'],
|
93
|
-
['22', '22', '22', '23', '19', '19', '26', '24', '24', '24', '28', '28', '25', '17', '33'],
|
94
|
-
['22', '22', '23', '23', '27', '27', '26', '26', '24', '24', '29', '29', '25', '25', '33'],
|
95
|
-
['22', '22', '35', '27', '27', '26', '26', '26', '26', '30', '30', '30', '25', '34', '34'],
|
96
|
-
['37', '22', '35', '35', '35', '35', '35', '26', '26', '30', '31', '31', '32', '32', '40'],
|
97
|
-
['37', '37', '37', '36', '36', '35', '26', '26', '26', '40', '40', '40', '40', '40', '40'],
|
98
|
-
['37', '37', '37', '37', '35', '35', '38', '38', '39', '39', '40', '40', '40', '41', '41'],
|
99
|
-
])
|
125
|
+
board = get_input()
|
100
126
|
# rcolors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255), (255, 255, 255), (128, 128, 128)]
|
101
|
-
vs =[0, 255]
|
127
|
+
vs =[0, 128, 255]
|
102
128
|
rcolors = [(v1, v2, v3) for v1 in vs for v2 in vs for v3 in vs if (v1, v2, v3) != (0, 0, 0)]
|
103
129
|
nums = set([c.item() for c in np.nditer(board)])
|
104
|
-
colors = {
|
130
|
+
colors = {c: rcolors[i % len(rcolors)] for i, c in enumerate(nums)}
|
105
131
|
print(nums)
|
106
132
|
print('max i:', max(nums))
|
107
133
|
print('skipped:', set(range(int(max(nums)) + 1)) - set(int(i) for i in nums))
|
108
|
-
render_board_image(board, colors
|
134
|
+
render_board_image(board, colors)
|
File without changes
|
File without changes
|