multi-puzzle-solver 0.9.15__py3-none-any.whl → 0.9.18__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.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multi-puzzle-solver
3
- Version: 0.9.15
3
+ Version: 0.9.18
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
@@ -39,22 +39,35 @@ pip install multi-puzzle-solver
39
39
  Use:
40
40
 
41
41
  ```python
42
- from puzzle_solver import nonograms_solver
43
- solver = nonograms_solver.Board(top=[[2], [3], [1], [1, 1]], side=[[3], [1], [2, 1], [1]])
44
- solutions = solver.solve_and_print()
42
+ from puzzle_solver import nonograms_solver as solver
43
+ top_numbers = [[8, 2], [5, 4], [2, 1, 4], [2, 4], [2, 1, 4], [2, 5], [2, 8], [3, 2], [1, 6], [1, 9], [1, 6, 1], [1, 5, 3], [3, 2, 1], [4, 2], [1, 5]]
44
+ side_numbers = [[7, 3], [7, 1, 1], [2, 3], [2, 3], [3, 2], [1, 1, 1, 1, 2], [1, 6, 1], [1, 9], [9], [2, 4], [8], [11], [7, 1, 1], [4, 3], [3, 2]]
45
+ binst = solver.Board(top=top_numbers, side=side_numbers)
46
+ solutions = binst.solve_and_print()
45
47
  ```
46
48
 
47
49
  Output:
48
50
 
49
51
  ```python
50
52
  Solution found
51
- [[' ' 'B' 'B' 'B']
52
- [' ' 'B' ' ' ' ']
53
- ['B' 'B' ' ' 'B']
54
- ['B' ' ' ' ' ' ']]
53
+ [['B' 'B' 'B' 'B' 'B' 'B' 'B' ' ' 'B' 'B' 'B' ' ' ' ' ' ' ' ']
54
+ ['B' 'B' 'B' 'B' 'B' 'B' 'B' ' ' ' ' ' ' ' ' ' ' 'B' ' ' 'B']
55
+ ['B' 'B' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'B' 'B' 'B' ' ']
56
+ ['B' 'B' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'B' 'B' 'B']
57
+ ['B' 'B' 'B' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'B' 'B']
58
+ ['B' ' ' ' ' ' ' 'B' ' ' 'B' ' ' ' ' 'B' ' ' ' ' ' ' 'B' 'B']
59
+ ['B' ' ' ' ' ' ' ' ' ' ' 'B' 'B' 'B' 'B' 'B' 'B' ' ' ' ' 'B']
60
+ ['B' ' ' ' ' ' ' ' ' ' ' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B']
61
+ [' ' ' ' ' ' ' ' ' ' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' ' ']
62
+ [' ' ' ' ' ' ' ' ' ' 'B' 'B' ' ' 'B' 'B' 'B' 'B' ' ' ' ' ' ']
63
+ [' ' ' ' ' ' ' ' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' ' ' ' ' ' ']
64
+ ['B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' 'B' ' ' ' ' ' ' ' ']
65
+ ['B' 'B' 'B' 'B' 'B' 'B' 'B' ' ' ' ' 'B' ' ' 'B' ' ' ' ' ' ']
66
+ [' ' 'B' 'B' 'B' 'B' ' ' ' ' ' ' ' ' 'B' 'B' 'B' ' ' ' ' ' ']
67
+ [' ' 'B' 'B' 'B' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'B' 'B' ' ' ' ']]
55
68
  Solutions found: 1
56
69
  status: OPTIMAL
57
- Time taken: 0.00 seconds
70
+ Time taken: 0.04 seconds
58
71
  ```
59
72
  (Note: Printing can be turned off by setting `verbose=False`)
60
73
 
@@ -269,6 +282,23 @@ These are all the puzzles that are implemented in this repo. <br> Click on any o
269
282
  <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/black_box_solved.png" alt="Black Box" width="140">
270
283
  </a>
271
284
  </td>
285
+ <td align="center">
286
+ <a href="#galaxies-puzzle-type-35"><b>Galaxies</b><br><br>
287
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/galaxies_solved.png" alt="Galaxies" width="140">
288
+ </a>
289
+ </td>
290
+ </tr>
291
+ <tr>
292
+ <td align="center">
293
+ <a href="#slant-puzzle-type-36"><b>Slant</b><br><br>
294
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/slant_solved.png" alt="Slant" width="140">
295
+ </a>
296
+ </td>
297
+ <td align="center">
298
+ <a href="#unequal-puzzle-type-37"><b>Unequal</b><br><br>
299
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/unequal_solved.png" alt="Unequal" width="140">
300
+ </a>
301
+ </td>
272
302
  </tr>
273
303
  </table>
274
304
 
@@ -318,6 +348,9 @@ These are all the puzzles that are implemented in this repo. <br> Click on any o
318
348
  - [Star Battle Shapeless (Puzzle Type #32)](#star-battle-shapeless-puzzle-type-32)
319
349
  - [Lits (Puzzle Type #33)](#lits-puzzle-type-33)
320
350
  - [Black Box (Puzzle Type #34)](#black-box-puzzle-type-34)
351
+ - [Galaxies (Puzzle Type #35)](#galaxies-puzzle-type-35)
352
+ - [Slant (Puzzle Type #36)](#slant-puzzle-type-36)
353
+ - [Unequal (Puzzle Type #37)](#unequal-puzzle-type-37)
321
354
  - [Why SAT / CP-SAT?](#why-sat--cp-sat)
322
355
  - [Testing](#testing)
323
356
  - [Contributing](#contributing)
@@ -1772,8 +1805,8 @@ Thus the solver was developed with the additional much harder goal of collecting
1772
1805
  It does so using the following high level steps:
1773
1806
 
1774
1807
  1. Model the board as a directed graph where the cells are nodes and legal moves as directed edges with unit cost. Each gem has to a group of edges where traversing any one of them collects that gem.
1775
- 2. Model step (1) as a [Generalized Traveling Salesman Problem (GTSP)](https://en.wikipedia.org/wiki/Set_TSP_problem), where each gems edge group forms a cluster.
1776
- 3. Apply the [Noon–Bean transformation](https://deepblue.lib.umich.edu/bitstream/handle/2027.42/6834/ban3102.0001.001.pdf?sequence=5) **(Noon & Bean, 1991)** to convert the GTSP from step (2) into an equivalent Asymmetric TSP (ATSP) that can be solved with OR-Tools routing solver. (Noon-Bean transformation is mentioned but not described in the [TSP wikipedia page](https://en.wikipedia.org/wiki/Travelling_salesman_problem).)
1808
+ 2. Model step (1) as a [Generalized Traveling Salesman Problem (GTSP)](https://en.wikipedia.org/wiki/Set_TSP_problem), where each gem's edge group forms a cluster.
1809
+ 3. Apply the [Noon–Bean transformation](https://deepblue.lib.umich.edu/bitstream/handle/2027.42/6834/ban3102.0001.001.pdf?sequence=5) **(Noon & Bean, 1991)** to convert the GTSP from step (2) into an equivalent Asymmetric TSP (ATSP) that can be solved with OR-Tools' routing solver. (Noon-Bean transformation is mentioned but not described in the [TSP wikipedia page](https://en.wikipedia.org/wiki/Travelling_salesman_problem).)
1777
1810
  4. Use a [Vehicle Routing Problem (VRP)](https://en.wikipedia.org/wiki/Vehicle_routing_problem) solver using the [OR-Tools VRP solver](https://developers.google.com/optimization/routing/routing_tasks) to solve the ATSP.
1778
1811
 
1779
1812
  This achieves a final sequence of moves that is empirically always faster than the website's solution.
@@ -2892,6 +2925,251 @@ Time taken: 30.33 seconds
2892
2925
 
2893
2926
  ---
2894
2927
 
2928
+ ## Galaxies (Puzzle Type #35)
2929
+
2930
+ * [**Play online**](https://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/galaxies.html)
2931
+
2932
+ * [**Instructions**](https://www.chiark.greenend.org.uk/~sgtatham/puzzles/doc/galaxies.html#galaxies)
2933
+
2934
+ * [**Solver Code**][35]
2935
+
2936
+ <details>
2937
+ <summary><strong>Rules</strong></summary>
2938
+
2939
+ You have a rectangular grid containing a number of dots. Your aim is to partition the rectangle into connected regions of squares, in such a way that every region is 180° rotationally symmetric, and contains exactly one dot which is located at its centre of symmetry.
2940
+
2941
+ To enter your solution, you draw lines along the grid edges to mark the boundaries of the regions. The puzzle is complete when the marked lines on the grid are precisely those that separate two squares belonging to different regions.
2942
+
2943
+ </details>
2944
+
2945
+ **Unsolved puzzle**
2946
+
2947
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/galaxies_unsolved.png" alt="Galaxies unsolved" width="500">
2948
+
2949
+ Code to utilize this package and solve the puzzle:
2950
+
2951
+ Note: The number are arbitrary and simply number each galaxy as an integer.
2952
+
2953
+ ```python
2954
+ from puzzle_solver import galaxies_solver as solver
2955
+ galaxies = np.array([
2956
+ [' ', ' ', '00', ' ', ' ', '01', '01', '02', '02', '03', '03', ' ', '04', '04', ' '],
2957
+ ['05', '05', ' ', ' ', '06', '01', '01', '02', '02', ' ', ' ', ' ', '07', ' ', ' '],
2958
+ ['08', ' ', ' ', ' ', '06', ' ', '09', '09', ' ', ' ', '10', ' ', ' ', ' ', ' '],
2959
+ [' ', ' ', ' ', ' ', ' ', ' ', '11', '11', '12', ' ', ' ', ' ', ' ', '13', '13'],
2960
+ ['14', ' ', ' ', ' ', '15', ' ', '11', '11', ' ', ' ', ' ', ' ', '16', ' ', ' '],
2961
+ [' ', '17', ' ', ' ', '15', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '16', ' ', '18'],
2962
+ [' ', '17', '19', ' ', ' ', ' ', ' ', ' ', ' ', '20', ' ', ' ', ' ', '21', '18'],
2963
+ [' ', '22', ' ', ' ', '23', ' ', ' ', ' ', ' ', '20', ' ', '24', '24', '21', '25'],
2964
+ ['26', '27', '27', '28', '28', '29', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '30', '30'],
2965
+ [' ', '27', '27', '28', '28', '31', '31', ' ', ' ', ' ', ' ', '32', ' ', '30', '30'],
2966
+ [' ', ' ', ' ', '33', '33', '31', '31', '34', ' ', ' ', '35', ' ', ' ', ' ', ' '],
2967
+ ['36', ' ', ' ', '33', '33', ' ', ' ', '34', ' ', ' ', ' ', ' ', ' ', '37', ' '],
2968
+ [' ', ' ', '38', '38', ' ', '39', ' ', '40', '40', '41', '41', '42', ' ', '37', ' '],
2969
+ ['43', '44', '38', '38', '45', '45', '46', '40', '40', '41', '41', '42', ' ', ' ', ' '],
2970
+ ['43', ' ', ' ', ' ', ' ', ' ', ' ', '47', ' ', ' ', ' ', ' ', '48', '48', ' ']
2971
+ ])
2972
+ binst = solver.Board(galaxies=galaxies)
2973
+ solutions = binst.solve_and_print()
2974
+ ```
2975
+ **Script Output**
2976
+
2977
+ As the instructions say, the solution to this puzzle is not garunteed to be unique.
2978
+
2979
+ ```python
2980
+ Solution found
2981
+ [
2982
+ ['00', '00', '00', '00', '00', '01', '01', '02', '02', '03', '03', '04', '04', '04', '04'],
2983
+ ['05', '05', '15', '06', '06', '01', '01', '02', '02', '10', '10', '07', '07', '07', '13'],
2984
+ ['08', '15', '15', '15', '06', '06', '09', '09', '10', '10', '10', '10', '10', '13', '13'],
2985
+ ['14', '15', '15', '15', '15', '15', '11', '11', '12', '20', '10', '10', '16', '13', '13'],
2986
+ ['14', '15', '15', '15', '15', '15', '11', '11', '20', '20', '20', '20', '16', '13', '13'],
2987
+ ['14', '17', '17', '15', '15', '15', '15', '15', '20', '20', '20', '20', '16', '13', '18'],
2988
+ ['17', '17', '19', '15', '15', '15', '15', '15', '20', '20', '20', '24', '16', '21', '18'],
2989
+ ['26', '22', '27', '27', '23', '15', '15', '15', '20', '20', '20', '24', '24', '21', '25'],
2990
+ ['26', '27', '27', '28', '28', '29', '15', '20', '20', '20', '20', '32', '24', '30', '30'],
2991
+ ['26', '27', '27', '28', '28', '31', '31', '20', '20', '20', '20', '32', '37', '30', '30'],
2992
+ ['27', '27', '33', '33', '33', '31', '31', '34', '34', '20', '35', '32', '37', '37', '37'],
2993
+ ['36', '38', '38', '33', '33', '33', '34', '34', '41', '41', '41', '41', '37', '37', '37'],
2994
+ ['44', '44', '38', '38', '45', '39', '46', '40', '40', '41', '41', '42', '37', '37', '37'],
2995
+ ['43', '44', '38', '38', '45', '45', '46', '40', '40', '41', '41', '42', '37', '37', '37'],
2996
+ ['43', '44', '44', '38', '38', '45', '46', '47', '41', '41', '41', '41', '48', '48', '37'],
2997
+ ]
2998
+ Solutions found: 1
2999
+ status: OPTIMAL
3000
+ Time taken: 0.07 seconds
3001
+ ```
3002
+
3003
+ **Solved puzzle**
3004
+
3005
+ Applying the solution to the puzzle visually:
3006
+
3007
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/galaxies_solved.png" alt="Galaxies solved" width="500">
3008
+
3009
+ ---
3010
+
3011
+ ## Slant (Puzzle Type #36)
3012
+
3013
+ * [**Play online**](https://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/slant.html)
3014
+
3015
+ * [**Instructions**](https://www.chiark.greenend.org.uk/~sgtatham/puzzles/doc/slant.html#slant)
3016
+
3017
+ * [**Solver Code**][36]
3018
+
3019
+ <details>
3020
+ <summary><strong>Rules</strong></summary>
3021
+
3022
+ You have a grid of squares. Your aim is to draw a diagonal line through each square, and choose which way each line slants so that the following conditions are met:
3023
+
3024
+ - The diagonal lines never form a loop.
3025
+ - Any point with a circled number has precisely that many lines meeting at it. (Thus, a 4 is the centre of a cross shape, whereas a zero is the centre of a diamond shape – or rather, a partial diamond shape, because a zero can never appear in the middle of the grid because that would immediately cause a loop.)
3026
+
3027
+ </details>
3028
+
3029
+ **Unsolved puzzle**
3030
+
3031
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/slant_unsolved.png" alt="Slant unsolved" width="500">
3032
+
3033
+ Code to utilize this package and solve the puzzle:
3034
+
3035
+ Note: For an NxM board you need an (N+1)x(M+1) array because the puzzle is to solve for the cells while the input is the values at the corners (there's always one more corner than cells in each dimension).
3036
+
3037
+ ```python
3038
+ from puzzle_solver import slant_solver as solver
3039
+ board = np.array([
3040
+ [' ', ' ', '1', ' ', '1', ' ', '1', ' ', '1', ' ', ' ', ' ', ' '],
3041
+ [' ', '1', '2', ' ', ' ', '2', ' ', '2', ' ', '2', ' ', '1', '1'],
3042
+ [' ', '2', '2', ' ', '2', '3', '2', ' ', '3', ' ', ' ', '1', ' '],
3043
+ ['1', '1', ' ', '3', '1', '2', ' ', '1', ' ', ' ', '3', ' ', ' '],
3044
+ [' ', ' ', '1', '1', ' ', ' ', ' ', '1', '1', '3', ' ', '3', ' '],
3045
+ ['1', '2', ' ', '2', '2', ' ', '2', ' ', ' ', '1', '2', ' ', ' '],
3046
+ [' ', '2', '2', '2', ' ', ' ', '2', '3', '2', ' ', ' ', ' ', ' '],
3047
+ [' ', '1', '2', ' ', ' ', '2', ' ', '2', ' ', ' ', ' ', '1', ' '],
3048
+ [' ', ' ', ' ', '3', '2', '2', ' ', '3', '1', ' ', ' ', ' ', '1'],
3049
+ [' ', '2', '1', '1', '2', ' ', '1', ' ', '1', ' ', '1', '1', ' '],
3050
+ [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1', ' ', ' '],
3051
+ ])
3052
+ binst = solver.Board(numbers=board)
3053
+ solutions = binst.solve_and_print()
3054
+ ```
3055
+ **Script Output**
3056
+
3057
+ ```python
3058
+ Solution found
3059
+ [
3060
+ [ / \ \ / / / / \ \ \ / \ ]
3061
+ [ \ \ \ \ \ \ / \ / / \ \ ]
3062
+ [ \ \ \ / / \ / \ \ \ \ / ]
3063
+ [ \ / \ \ / \ / / \ / \ / ]
3064
+ [ / \ \ / \ \ \ / / / \ \ ]
3065
+ [ / \ \ / \ \ \ / \ / \ \ ]
3066
+ [ / \ \ / \ / / / \ / / \ ]
3067
+ [ \ \ \ \ \ / / / \ / \ \ ]
3068
+ [ / / / \ \ / / \ \ / \ \ ]
3069
+ [ \ \ / / / \ / \ / \ \ / ]
3070
+ ]
3071
+ Solutions found: 1
3072
+ status: OPTIMAL
3073
+ Time taken: 0.06 seconds
3074
+ ```
3075
+
3076
+ **Solved puzzle**
3077
+
3078
+ Applying the solution to the puzzle visually:
3079
+
3080
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/slant_solved.png" alt="Slant solved" width="500">
3081
+
3082
+ ---
3083
+
3084
+ ## Unequal (Puzzle Type #37)
3085
+
3086
+ * [**Play online**](https://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/unequal.html)
3087
+
3088
+ * [**Instructions**](https://www.chiark.greenend.org.uk/~sgtatham/puzzles/doc/unequal.html#unequal)
3089
+
3090
+ * [**Solver Code**][37]
3091
+
3092
+ <details>
3093
+ <summary><strong>Rules</strong></summary>
3094
+
3095
+ You have a square grid; each square may contain a digit from 1 to the size of the grid, and some squares have clue signs between them. Your aim is to fully populate the grid with numbers such that:
3096
+
3097
+ - Each row contains only one occurrence of each digit
3098
+ - Each column contains only one occurrence of each digit
3099
+ - All the clue signs are satisfied.
3100
+
3101
+ There are two modes for this game, 'Unequal' and 'Adjacent'.
3102
+
3103
+ In 'Unequal' mode, the clue signs are greater-than symbols indicating one square's value is greater than its neighbour's. In this mode not all clues may be visible, particularly at higher difficulty levels.
3104
+
3105
+ In 'Adjacent' mode, the clue signs are bars indicating one square's value is numerically adjacent (i.e. one higher or one lower) than its neighbour. In this mode all clues are always visible: absence of a bar thus means that a square's value is definitely not numerically adjacent to that neighbour's.
3106
+
3107
+ In 'Trivial' difficulty level (available via the 'Custom' game type selector), there are no greater-than signs in 'Unequal' mode; the puzzle is to solve the Latin square only.
3108
+
3109
+ </details>
3110
+
3111
+ **Unsolved puzzle**
3112
+
3113
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/unequal_unsolved.png" alt="Unequal unsolved" width="500">
3114
+
3115
+ Code to utilize this package and solve the puzzle:
3116
+
3117
+ Note: For an NxM board you need an (2N-1)x(2M-1) array because the puzzle involves input in between the cells. Each numbered cell has neighbors horizontally to represent ">", "<", and "|" (where "|" represents adjacency) and vertically to represent "∧", "∨" and "-" (where "-" represents adjacency). The "X" in the input are unused corners that shouldnt contain anything (just a corner). The numbers should never appear orthogonal to an "X", only diagonally to it. vice-versa for the comparison operators.
3118
+
3119
+ ```python
3120
+ board = np.array([
3121
+ [' ', ' ', ' ', ' ', '9', ' ', '1', ' ', '7', '>', ' ', '>', ' ', ' ', ' ', ' ', ' ', '>', ' '],
3122
+ [' ', 'X', 'V', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', '∧', 'X', ' ', 'X', ' ', 'X', ' '],
3123
+ [' ', ' ', ' ', ' ', ' ', ' ', '6', ' ', ' ', ' ', '9', ' ', ' ', ' ', '5', ' ', '3', ' ', ' '],
3124
+ [' ', 'X', ' ', 'X', '∧', 'X', ' ', 'X', '∧', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' '],
3125
+ [' ', ' ', ' ', '>', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '6', ' ', '9', ' ', ' ', ' ', ' '],
3126
+ [' ', 'X', ' ', 'X', 'V', 'X', 'V', 'X', 'V', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', 'V'],
3127
+ [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '<', ' ', '<', ' ', '>', ' ', ' ', ' ', ' ', ' '],
3128
+ [' ', 'X', ' ', 'X', '∧', 'X', 'V', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' '],
3129
+ [' ', ' ', '3', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '<', ' ', ' ', ' '],
3130
+ [' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', '∧', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' '],
3131
+ [' ', '<', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '5', ' ', ' ', '>', ' ', '<', ' ', ' ', '4'],
3132
+ ['V', 'X', '∧', 'X', 'V', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', 'V', 'X', ' ', 'X', ' '],
3133
+ [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '>', ' ', ' ', ' ', ' ', ' '],
3134
+ [' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', '∧', 'X', ' ', 'X', ' ', 'X', 'V'],
3135
+ [' ', ' ', ' ', '<', ' ', ' ', ' ', '<', ' ', ' ', ' ', '<', ' ', '<', ' ', ' ', ' ', '<', ' '],
3136
+ [' ', 'X', ' ', 'X', ' ', 'X', 'V', 'X', ' ', 'X', 'V', 'X', '∧', 'X', ' ', 'X', ' ', 'X', ' '],
3137
+ [' ', ' ', ' ', ' ', ' ', '>', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '>', ' ', ' ', '9', ' ', ' '],
3138
+ ['V', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', 'V'],
3139
+ [' ', '>', ' ', ' ', ' ', '>', ' ', ' ', ' ', ' ', '4', '<', ' ', '<', ' ', '<', '7', ' ', '2'],
3140
+ ])
3141
+ binst = solver.Board(board=board)
3142
+ solutions = binst.solve_and_print()
3143
+ ```
3144
+ **Script Output**
3145
+
3146
+ ```python
3147
+ Solution found
3148
+ [
3149
+ [ 6 5 9 1 7 2 0 8 4 3 ]
3150
+ [ 7 1 0 6 4 9 2 5 3 8 ]
3151
+ [ 3 4 2 8 5 0 6 9 1 7 ]
3152
+ [ 5 9 1 7 3 6 8 4 2 0 ]
3153
+ [ 8 3 5 4 0 7 1 2 6 9 ]
3154
+ [ 2 6 7 0 1 5 9 3 8 4 ]
3155
+ [ 0 7 4 9 2 8 3 1 5 6 ]
3156
+ [ 9 2 6 5 8 3 4 7 0 1 ]
3157
+ [ 4 8 3 2 6 1 7 0 9 5 ]
3158
+ [ 1 0 8 3 9 4 5 6 7 2 ]
3159
+ ]
3160
+ Solutions found: 1
3161
+ status: OPTIMAL
3162
+ Time taken: 0.05 seconds
3163
+ ```
3164
+
3165
+ **Solved puzzle**
3166
+
3167
+ Applying the solution to the puzzle visually:
3168
+
3169
+ <img src="https://raw.githubusercontent.com/Ar-Kareem/puzzle_solver/master/images/unequal_solved.png" alt="Unequal solved" width="500">
3170
+
3171
+ ---
3172
+
2895
3173
  ---
2896
3174
 
2897
3175
  ## Why SAT / CP-SAT?
@@ -2977,3 +3255,6 @@ Issues and PRs welcome!
2977
3255
  [32]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/star_battle_shapeless "puzzle_solver/src/puzzle_solver/puzzles/star_battle_shapeless at master · Ar-Kareem/puzzle_solver · GitHub"
2978
3256
  [33]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/lits "puzzle_solver/src/puzzle_solver/puzzles/lits at master · Ar-Kareem/puzzle_solver · GitHub"
2979
3257
  [34]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/black_box "puzzle_solver/src/puzzle_solver/puzzles/black_box at master · Ar-Kareem/puzzle_solver · GitHub"
3258
+ [35]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/galaxies "puzzle_solver/src/puzzle_solver/puzzles/galaxies at master · Ar-Kareem/puzzle_solver · GitHub"
3259
+ [36]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/slant "puzzle_solver/src/puzzle_solver/puzzles/slant at master · Ar-Kareem/puzzle_solver · GitHub"
3260
+ [37]: https://github.com/Ar-Kareem/puzzle_solver/tree/master/src/puzzle_solver/puzzles/unequal "puzzle_solver/src/puzzle_solver/puzzles/unequal at master · Ar-Kareem/puzzle_solver · GitHub"
@@ -1,6 +1,6 @@
1
- puzzle_solver/__init__.py,sha256=hsdC4t9rGAyQMPNuCjepmf4hZhoUgGbAW83ROdkDAoc,2574
1
+ puzzle_solver/__init__.py,sha256=nqXtO2JuY0r7gNM1HwP_5apXmLX7OeriApzXNaJZjDA,2704
2
2
  puzzle_solver/core/utils.py,sha256=_LA81kHrsgvqPvq7RISBeaurXmYMKAU9N6qmV8n0G7s,8063
3
- puzzle_solver/core/utils_ortools.py,sha256=SZQyLE6eld7B_Zq5AjyVjeGimsxoRk3D7M40wWWExIE,10463
3
+ puzzle_solver/core/utils_ortools.py,sha256=2xEL9cMEKmNhRD9lhr2nGdZ3Lbmc9cnHY8xv6iLhUr0,10542
4
4
  puzzle_solver/puzzles/aquarium/aquarium.py,sha256=BUfkAS2d9eG3TdMoe1cOGGeNYgKUebRvn-z9nsC9gvE,5708
5
5
  puzzle_solver/puzzles/battleships/battleships.py,sha256=RuYCrs4j0vUjlU139NRYYP-uNPAgO0V7hAzbsHrRwD8,7446
6
6
  puzzle_solver/puzzles/black_box/black_box.py,sha256=ZnHDVt6PFS_r1kMNSsbz9hav1hxIrNDUvPyERGPjLjM,15635
@@ -11,8 +11,8 @@ puzzle_solver/puzzles/chess_range/chess_solo.py,sha256=U3v766UsZHx_dC3gxqU90VbjA
11
11
  puzzle_solver/puzzles/chess_sequence/chess_sequence.py,sha256=6ap3Wouf2PxHV4P56B9ol1QT98Ym6VHaxorQZWl6LnY,13692
12
12
  puzzle_solver/puzzles/dominosa/dominosa.py,sha256=Nmb7pn8U27QJwGy9F3wo8ylqo2_U51OAo3GN2soaNpc,7195
13
13
  puzzle_solver/puzzles/filling/filling.py,sha256=vrOIil285_r3IQ0F4c9mUBWMRVlPH4vowog_z1tCGdI,5567
14
- puzzle_solver/puzzles/galaxies/galaxies.py,sha256=AJwH-HMpSvOAu2DTV-VbP52jUK0hmlkP31g4xB0F3K4,5607
15
- puzzle_solver/puzzles/galaxies/parse_map/parse_map.py,sha256=DzVEihO6gokBDo-joSKCSyfdSsRdpZy3Ft50--nJyak,9354
14
+ puzzle_solver/puzzles/galaxies/galaxies.py,sha256=p10lpmW0FjtneFCMEjG1FSiEpQuvD8zZG9FG8zYGoes,5582
15
+ puzzle_solver/puzzles/galaxies/parse_map/parse_map.py,sha256=v5TCrdREeOB69s9_QFgPHKA7flG69Im1HVzIdxH0qQc,9355
16
16
  puzzle_solver/puzzles/guess/guess.py,sha256=sH-NlYhxM3DNbhk4eGde09kgM0KaDvSbLrpHQiwcFGo,10791
17
17
  puzzle_solver/puzzles/inertia/inertia.py,sha256=gJBahkh69CrSWNscalKEoP1j4X-Q3XpbIBMiG9PUpU0,5657
18
18
  puzzle_solver/puzzles/inertia/tsp.py,sha256=gobiISHtARA4Elq0jr90p6Yhq11ULjGoqsS-rLFhYcc,15389
@@ -31,19 +31,22 @@ puzzle_solver/puzzles/pearl/pearl.py,sha256=OhzpMYpxqvR3GCd5NH4ETT0NO4X753kRi6p5
31
31
  puzzle_solver/puzzles/range/range.py,sha256=rruvD5ZSaOgvQuX6uGV_Dkr82nSiWZ5kDz03_j7Tt24,4425
32
32
  puzzle_solver/puzzles/signpost/signpost.py,sha256=-0_S6ycwzwlUf9-ZhP127Rgo5gMBOHiTM6t08dLLDac,3869
33
33
  puzzle_solver/puzzles/singles/singles.py,sha256=3wACiUa1Vmh2ce6szQ2hPjyBuH7aHiQ888p4R2jFkW4,3342
34
+ puzzle_solver/puzzles/slant/slant.py,sha256=xF-N4PuXYfx638NP1f1mi6YncIZB4mLtXtdS79XyPbg,6122
35
+ puzzle_solver/puzzles/slant/parse_map/parse_map.py,sha256=dxnALSDXe9wU0uSD0QEXnzoh1q801mj1ePTNLtG0n60,4796
34
36
  puzzle_solver/puzzles/star_battle/star_battle.py,sha256=IX6w4H3sifN01kPPtrAVRCK0Nl_xlXXSHvJKw8K1EuE,3718
35
37
  puzzle_solver/puzzles/star_battle/star_battle_shapeless.py,sha256=lj05V0Y3A3NjMo1boMkPIwBhMtm6SWydjgAMeCf5EIo,225
36
38
  puzzle_solver/puzzles/stitches/stitches.py,sha256=iK8t02q43gH3FPbuIDn4dK0sbaOgZOnw8yHNRNvNuIU,6534
37
- puzzle_solver/puzzles/stitches/parse_map/parse_map.py,sha256=VWHT-iYDaFsd37h9DE07EkeZ_dJMEfatXSByqC2vh04,8916
39
+ puzzle_solver/puzzles/stitches/parse_map/parse_map.py,sha256=dbd7DoqjR4qkMQAeD_lPpuLB_KCFCIHfDauTbjB3W80,8880
38
40
  puzzle_solver/puzzles/sudoku/sudoku.py,sha256=M_pry7XyKKzlfCF5rFi02lyOrj5GWZzXnDAxmD3NXvI,3588
39
41
  puzzle_solver/puzzles/tents/tents.py,sha256=iyVK2WXfIT5j_9qqlQg0WmwvixwXlZSsHGK3XA-KpII,6283
40
42
  puzzle_solver/puzzles/thermometers/thermometers.py,sha256=nsvJZkm7G8FALT27bpaB0lv5E_AWawqmvapQI8QcYXw,4015
41
43
  puzzle_solver/puzzles/towers/towers.py,sha256=QvL0Pp-Z2ewCeq9ZkNrh8MShKOh-Y52sFBSudve68wk,6496
42
44
  puzzle_solver/puzzles/tracks/tracks.py,sha256=98xds9SKNqtOLFTRUX_KSMC7XYmZo567LOFeqotVQaM,7237
43
45
  puzzle_solver/puzzles/undead/undead.py,sha256=IrCUfzQFBem658P5KKqldG7vd2TugTHehcwseCarerM,6604
46
+ puzzle_solver/puzzles/unequal/unequal.py,sha256=ExY2XDCrqROCDpRLfHo8uVr1zuli1QvbCdNCiDhlCac,6978
44
47
  puzzle_solver/puzzles/unruly/unruly.py,sha256=sDF0oKT50G-NshyW2DYrvAgD9q9Ku9ANUyNhGSAu7cQ,3827
45
48
  puzzle_solver/utils/visualizer.py,sha256=tsX1yEKwmwXBYuBJpx_oZGe2UUt1g5yV73G3UbtmvtE,6817
46
- multi_puzzle_solver-0.9.15.dist-info/METADATA,sha256=LIonrn93fVCBRPPgFoBKnSezECoANY9lY5JXIKss_g8,148507
47
- multi_puzzle_solver-0.9.15.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
48
- multi_puzzle_solver-0.9.15.dist-info/top_level.txt,sha256=exwVUQa-anK9vYrpKzBPvH8bX43iElWI4VeNiAyBGJY,14
49
- multi_puzzle_solver-0.9.15.dist-info/RECORD,,
49
+ multi_puzzle_solver-0.9.18.dist-info/METADATA,sha256=q9i19rwenN_tEUfhsP8ayNEVfeKcRTm4xK4AmWyzw9M,163560
50
+ multi_puzzle_solver-0.9.18.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
51
+ multi_puzzle_solver-0.9.18.dist-info/top_level.txt,sha256=exwVUQa-anK9vYrpKzBPvH8bX43iElWI4VeNiAyBGJY,14
52
+ multi_puzzle_solver-0.9.18.dist-info/RECORD,,
puzzle_solver/__init__.py CHANGED
@@ -23,6 +23,7 @@ from puzzle_solver.puzzles.pearl import pearl as pearl_solver
23
23
  from puzzle_solver.puzzles.range import range as range_solver
24
24
  from puzzle_solver.puzzles.signpost import signpost as signpost_solver
25
25
  from puzzle_solver.puzzles.singles import singles as singles_solver
26
+ from puzzle_solver.puzzles.slant import slant as slant_solver
26
27
  from puzzle_solver.puzzles.star_battle import star_battle as star_battle_solver
27
28
  from puzzle_solver.puzzles.star_battle import star_battle_shapeless as star_battle_shapeless_solver
28
29
  from puzzle_solver.puzzles.stitches import stitches as stitches_solver
@@ -32,8 +33,9 @@ from puzzle_solver.puzzles.thermometers import thermometers as thermometers_solv
32
33
  from puzzle_solver.puzzles.towers import towers as towers_solver
33
34
  from puzzle_solver.puzzles.tracks import tracks as tracks_solver
34
35
  from puzzle_solver.puzzles.undead import undead as undead_solver
36
+ from puzzle_solver.puzzles.unequal import unequal as unequal_solver
35
37
  from puzzle_solver.puzzles.unruly import unruly as unruly_solver
36
38
 
37
39
  from puzzle_solver.puzzles.inertia.parse_map.parse_map import main as inertia_image_parser
38
40
 
39
- __version__ = '0.9.15'
41
+ __version__ = '0.9.18'
@@ -175,10 +175,15 @@ def force_no_loops(model: cp_model.CpModel, vars_to_force: dict[Any, cp_model.In
175
175
  tree_edge: dict[tuple[Pos, Pos], cp_model.IntVar] = {} # tree_edge[p, q] means p is parent of q
176
176
  prefix_name = "no_loops_"
177
177
 
178
- def parent_of(p: Pos) -> list[Pos]:
179
- return [q for q in keys_in_order if (q, p) in tree_edge]
180
- def children_of(p: Pos) -> list[Pos]:
181
- return [q for q in keys_in_order if (p, q) in tree_edge]
178
+ parent_of = {p: [] for p in vs.keys()}
179
+ children_of = {p: [] for p in vs.keys()}
180
+ for p in vs.keys():
181
+ for q in vs.keys():
182
+ if p == q:
183
+ continue
184
+ if is_neighbor(p, q):
185
+ parent_of[q].append(p)
186
+ children_of[p].append(q)
182
187
 
183
188
  keys_in_order = list(vs.keys()) # must enforce some ordering
184
189
  node_to_idx: dict[Pos, int] = {p: i+1 for i, p in enumerate(keys_in_order)}
@@ -197,16 +202,13 @@ def force_no_loops(model: cp_model.CpModel, vars_to_force: dict[Any, cp_model.In
197
202
  model.Add(block_root[p] == node_to_idx[p]).OnlyEnforceIf([is_root[p]])
198
203
 
199
204
  for p in keys_in_order:
200
- for q in keys_in_order:
201
- if p == q:
202
- continue
203
- if is_neighbor(p, q):
204
- tree_edge[(p, q)] = model.NewBoolVar(f"{prefix_name}tree_edge[{p} is parent of {q}]")
205
- model.Add(tree_edge[(p, q)] == 0).OnlyEnforceIf([vs[p].Not()])
206
- model.Add(tree_edge[(p, q)] == 0).OnlyEnforceIf([vs[q].Not()])
207
- # a tree_edge[p, q] means p is parent of q thus h[q] = h[p] + 1
208
- model.Add(node_height[q] == node_height[p] + 1).OnlyEnforceIf([tree_edge[(p, q)]])
209
- model.Add(block_root[q] == block_root[p]).OnlyEnforceIf([tree_edge[(p, q)]])
205
+ for q in children_of[p]:
206
+ tree_edge[(p, q)] = model.NewBoolVar(f"{prefix_name}tree_edge[{p} is parent of {q}]")
207
+ model.Add(tree_edge[(p, q)] == 0).OnlyEnforceIf([vs[p].Not()])
208
+ model.Add(tree_edge[(p, q)] == 0).OnlyEnforceIf([vs[q].Not()])
209
+ # a tree_edge[p, q] means p is parent of q thus h[q] = h[p] + 1
210
+ model.Add(node_height[q] == node_height[p] + 1).OnlyEnforceIf([tree_edge[(p, q)]])
211
+ model.Add(block_root[q] == block_root[p]).OnlyEnforceIf([tree_edge[(p, q)]])
210
212
 
211
213
  for (p, q) in tree_edge:
212
214
  if (q, p) in tree_edge:
@@ -214,14 +216,14 @@ def force_no_loops(model: cp_model.CpModel, vars_to_force: dict[Any, cp_model.In
214
216
  model.Add(tree_edge[(p, q)] == 1).OnlyEnforceIf([tree_edge[(q, p)].Not(), vs[p], vs[q]])
215
217
 
216
218
  for p in keys_in_order:
217
- for p_child in children_of(p):
219
+ for p_child in children_of[p]:
218
220
  # i am root thus I point to all my children
219
221
  model.Add(tree_edge[(p, p_child)] == 1).OnlyEnforceIf([is_root[p], vs[p_child]])
220
- for p_parent in parent_of(p):
222
+ for p_parent in parent_of[p]:
221
223
  # i am root thus I have no parent
222
224
  model.Add(tree_edge[(p_parent, p)] == 0).OnlyEnforceIf([is_root[p]])
223
225
  # every active node has exactly 1 parent except root has none
224
- model.AddExactlyOne([tree_edge[(p_parent, p)] for p_parent in parent_of(p)] + [vs[p].Not(), is_root[p]])
226
+ model.AddExactlyOne([tree_edge[(p_parent, p)] for p_parent in parent_of[p]] + [vs[p].Not(), is_root[p]])
225
227
 
226
228
  # now each subgraph has directions where each non-root points to a single parent (and its value is parent+1).
227
229
  # to break cycles, every non-root active node must be > all neighbors that arent children
@@ -233,5 +235,7 @@ def force_no_loops(model: cp_model.CpModel, vars_to_force: dict[Any, cp_model.In
233
235
  all_new_vars[f"{prefix_name}tree_edge[{k[0]} is parent of {k[1]}]"] = v
234
236
  for k, v in node_height.items():
235
237
  all_new_vars[f"{prefix_name}node_height[{k}]"] = v
238
+ for k, v in block_root.items():
239
+ all_new_vars[f"{prefix_name}block_root[{k}]"] = v
236
240
 
237
241
  return all_new_vars
@@ -4,8 +4,8 @@ from typing import Iterable, Union
4
4
  import numpy as np
5
5
  from ortools.sat.python import cp_model
6
6
 
7
- from puzzle_solver.core.utils import Pos, get_all_pos, get_char, set_char, Direction, get_next_pos, in_bounds, get_opposite_direction, get_pos
8
- from puzzle_solver.core.utils_ortools import generic_solve_all, SingleSolution, or_constraint, force_connected_component
7
+ from puzzle_solver.core.utils import Pos, get_all_pos, set_char, Direction, get_next_pos, in_bounds, get_opposite_direction, get_pos
8
+ from puzzle_solver.core.utils_ortools import generic_solve_all, SingleSolution, force_connected_component
9
9
 
10
10
 
11
11
  def parse_numpy(galaxies: np.ndarray) -> list[tuple[Pos, ...]]:
@@ -1,5 +1,5 @@
1
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.
2
+ This file is a simple helper that parses the images from https://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/galaxies.html and converts them to a json file.
3
3
  Look at the ./input_output/ directory for examples of input images and output json files.
4
4
  The output json is used in the test_solve.py file to test the solver.
5
5
  """
@@ -0,0 +1,133 @@
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
+
7
+ import json, itertools
8
+ from pathlib import Path
9
+ import numpy as np
10
+ cv = None
11
+
12
+
13
+ def extract_lines(bw):
14
+ horizontal = np.copy(bw)
15
+ vertical = np.copy(bw)
16
+
17
+ cols = horizontal.shape[1]
18
+ horizontal_size = max(5, cols // 20)
19
+ h_kernel = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1))
20
+ horizontal = cv.erode(horizontal, h_kernel)
21
+ horizontal = cv.dilate(horizontal, h_kernel)
22
+ h_means = np.mean(horizontal, axis=1)
23
+ h_idx = np.where(h_means > np.percentile(h_means, 70))[0]
24
+
25
+ rows = vertical.shape[0]
26
+ verticalsize = max(5, rows // 20)
27
+ v_kernel = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize))
28
+ vertical = cv.erode(vertical, v_kernel)
29
+ vertical = cv.dilate(vertical, v_kernel)
30
+ v_means = np.mean(vertical, axis=0)
31
+ v_idx = np.where(v_means > np.percentile(v_means, 70))[0]
32
+ return h_idx, v_idx
33
+
34
+ def mean_consecutives(arr):
35
+ if len(arr) == 0:
36
+ return arr
37
+ sums, counts = [arr[0]], [1]
38
+ for k in arr[1:]:
39
+ if k == sums[-1] + counts[-1]:
40
+ sums[-1] += k; counts[-1] += 1
41
+ else:
42
+ sums.append(k); counts.append(1)
43
+ return np.array(sums)//np.array(counts)
44
+
45
+ def main(img_path):
46
+ global cv
47
+ import cv2 as cv_module
48
+ cv = cv_module
49
+ image_path = Path(img_path)
50
+ output_path = image_path.parent / (image_path.stem + '.json')
51
+ src = cv.imread(img_path, cv.IMREAD_COLOR)
52
+ gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
53
+ inv = cv.bitwise_not(gray)
54
+ bw = cv.adaptiveThreshold(inv, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 15, -2)
55
+ h_idx, v_idx = extract_lines(bw)
56
+ h_idx = mean_consecutives(h_idx)
57
+ v_idx = mean_consecutives(v_idx)
58
+
59
+ # Estimate grid cell and circle radii
60
+ cell = int(np.median(np.diff(h_idx))) if len(h_idx) > 3 else 40
61
+ r_min = max(6, int(cell*0.18))
62
+ r_max = int(cell*0.52)
63
+
64
+ # Global Hough detection with parameter sweep
65
+ blur = cv.medianBlur(gray, 5)
66
+ detected = [] # x, y, r
67
+
68
+ for dp, p2 in itertools.product([1.2, 1.0], [20, 18, 16, 14, 12]):
69
+ circles = cv.HoughCircles(
70
+ blur, cv.HOUGH_GRADIENT, dp=dp, minDist=max(12, int(cell*0.75)),
71
+ param1=120, param2=p2, minRadius=r_min, maxRadius=r_max
72
+ )
73
+ if circles is not None:
74
+ for (x, y, r) in np.round(circles[0, :]).astype(int):
75
+ detected.append((x, y, r))
76
+
77
+ # Non-maximum suppression to remove duplicates
78
+ def nms(circles, dist_thr=10):
79
+ kept = []
80
+ for x,y,r in sorted(circles, key=lambda c: -c[2]):
81
+ if all((x-kx)**2+(y-ky)**2 > dist_thr**2 for kx,ky,kr in kept):
82
+ kept.append((x,y,r))
83
+ return kept
84
+
85
+ detected = nms(detected, dist_thr=max(10,int(cell*0.4)))
86
+
87
+ # Map circle centers to nearest intersection
88
+ H, W = len(h_idx), len(v_idx)
89
+ presence = np.zeros((H, W), dtype=int)
90
+
91
+ # Build KD-like search by grid proximity
92
+ tol = int(cell*0.5) # max distance from an intersection to accept a circle
93
+ for (cx, cy, r) in detected:
94
+ # find nearest indices
95
+ j = int(np.argmin(np.abs(h_idx - cy)))
96
+ i = int(np.argmin(np.abs(v_idx - cx)))
97
+ if abs(h_idx[j]-cy) <= tol and abs(v_idx[i]-cx) <= tol:
98
+ presence[j, i] = 1
99
+
100
+ with open(output_path, 'w') as f:
101
+ f.write('[\n')
102
+ for i, row in enumerate(presence):
103
+ f.write(' ' + str(row.tolist()).replace("'", '"'))
104
+ if i != len(presence) - 1:
105
+ f.write(',')
106
+ f.write('\n')
107
+ f.write(']')
108
+ print('output json: ', output_path)
109
+ print('output json: ', output_path)
110
+ print('output json: ', output_path)
111
+
112
+ overlay = src.copy()
113
+ for (cx, cy, r) in detected:
114
+ cv.circle(overlay, (cx, cy), r, (255,0,0), 2)
115
+ for j, y in enumerate(h_idx):
116
+ for i, x in enumerate(v_idx):
117
+ color = (0,0,255) if presence[j,i]==1 else (0,255,0)
118
+ cv.circle(overlay, (int(x), int(y)), 4, color, 2)
119
+ show_wait_destroy("overlay", overlay)
120
+
121
+
122
+
123
+ def show_wait_destroy(winname, img):
124
+ cv.imshow(winname, img)
125
+ cv.moveWindow(winname, 500, 0)
126
+ cv.waitKey(0)
127
+ cv.destroyWindow(winname)
128
+
129
+
130
+ if __name__ == '__main__':
131
+ # to run this script and visualize the output, in the root run:
132
+ # python .\src\puzzle_solver\puzzles\slant\parse_map\parse_map.py | python .\src\puzzle_solver\utils\visualizer.py --read_stdin
133
+ main(Path(__file__).parent / 'input_output' / '23131379850022376.png')
@@ -0,0 +1,117 @@
1
+ from typing import Literal, Optional, Union
2
+ from dataclasses import dataclass
3
+
4
+ import numpy as np
5
+ from ortools.sat.python import cp_model
6
+
7
+ from puzzle_solver.core.utils import Pos, get_all_pos, set_char, in_bounds, get_pos
8
+ from puzzle_solver.core.utils_ortools import force_no_loops, generic_solve_all, SingleSolution
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Node:
13
+ """The grid is represented as a graph of cells connected to corners."""
14
+ node_type: Union[Literal["Cell"], Literal["Corner"]]
15
+ pos: Pos
16
+ slant: Union[Literal["//"], Literal["\\"], None]
17
+
18
+ def get_neighbors(self, board_nodes: dict[tuple[str, Pos, Optional[str]], "Node"]) -> list["Node"]:
19
+ if self.node_type == "Cell" and self.slant == "//":
20
+ n1 = board_nodes[("Corner", get_pos(self.pos.x+1, self.pos.y), None)]
21
+ n2 = board_nodes[("Corner", get_pos(self.pos.x, self.pos.y+1), None)]
22
+ return [n1, n2]
23
+ elif self.node_type == "Cell" and self.slant == "\\":
24
+ n1 = board_nodes[("Corner", get_pos(self.pos.x, self.pos.y), None)]
25
+ n2 = board_nodes[("Corner", get_pos(self.pos.x+1, self.pos.y+1), None)]
26
+ return [n1, n2]
27
+ elif self.node_type == "Corner":
28
+ # 4 cells, 2 cells per slant
29
+ n1 = ("Cell", get_pos(self.pos.x-1, self.pos.y-1), "\\")
30
+ n2 = ("Cell", get_pos(self.pos.x, self.pos.y-1), "//")
31
+ n3 = ("Cell", get_pos(self.pos.x-1, self.pos.y), "//")
32
+ n4 = ("Cell", get_pos(self.pos.x, self.pos.y), "\\")
33
+ return {board_nodes[n] for n in [n1, n2, n3, n4] if n in board_nodes}
34
+
35
+
36
+ class Board:
37
+ def __init__(self, numbers: Union[list[tuple[Pos, int]], np.array], V: int = None, H: int = None):
38
+ if isinstance(numbers, np.ndarray):
39
+ V, H = numbers.shape
40
+ V = V - 1
41
+ H = H - 1
42
+ numbers = [(get_pos(x=pos[1], y=pos[0]), int(d)) for pos, d in np.ndenumerate(numbers) if str(d).isdecimal()]
43
+ numbers = [(p, n) for p, n in numbers if n >= 0]
44
+ else:
45
+ assert V is not None and H is not None, 'V and H must be provided if numbers is not a numpy array'
46
+ assert V >= 1 and H >= 1, 'V and H must be at least 1'
47
+ assert all(isinstance(number, int) and number >= 0 for (pos, number) in numbers), 'numbers must be a list of integers'
48
+ self.V = V
49
+ self.H = H
50
+ self.numbers = numbers
51
+ self.pos_to_number: dict[Pos, int] = {pos: number for pos, number in numbers}
52
+
53
+ self.model = cp_model.CpModel()
54
+ self.model_vars: dict[tuple[Pos, str], cp_model.IntVar] = {}
55
+ self.nodes: dict[Node, cp_model.IntVar] = {}
56
+ self.neighbor_dict: dict[Node, set[Node]] = {}
57
+
58
+ self.create_vars()
59
+ self.add_all_constraints()
60
+
61
+
62
+ def create_vars(self):
63
+ for pos in get_all_pos(self.V, self.H):
64
+ self.model_vars[(pos, '//')] = self.model.NewBoolVar(f'{pos}://')
65
+ self.model_vars[(pos, '\\')] = self.model.NewBoolVar(f'{pos}:\\')
66
+ self.model.AddExactlyOne([self.model_vars[(pos, '//')], self.model_vars[(pos, '\\')]])
67
+ for (pos, slant), v in self.model_vars.items():
68
+ self.nodes[Node(node_type="Cell", pos=pos, slant=slant)] = v
69
+ for pos in get_all_pos(self.V + 1, self.H + 1):
70
+ self.nodes[Node(node_type="Corner", pos=pos, slant=None)] = self.model.NewConstant(1)
71
+
72
+
73
+ def add_all_constraints(self):
74
+ for pos, number in self.pos_to_number.items():
75
+ # pos is a position on the intersection of 4 cells
76
+ # when pos is (xi, yi) then it gets a +1 contribution for each:
77
+ # - cell (xi-1, yi-1) is a "\\"
78
+ # - cell (xi, yi) is a "\\"
79
+ # - cell (xi, yi-1) is a "//"
80
+ # - cell (xi-1, yi) is a "//"
81
+ xi, yi = pos.x, pos.y
82
+ tl_pos = get_pos(xi-1, yi-1)
83
+ br_pos = get_pos(xi, yi)
84
+ tr_pos = get_pos(xi, yi-1)
85
+ bl_pos = get_pos(xi-1, yi)
86
+ tl_var = self.model_vars[(tl_pos, '\\')] if in_bounds(tl_pos, self.V, self.H) else 0
87
+ br_var = self.model_vars[(br_pos, '\\')] if in_bounds(br_pos, self.V, self.H) else 0
88
+ tr_var = self.model_vars[(tr_pos, '//')] if in_bounds(tr_pos, self.V, self.H) else 0
89
+ bl_var = self.model_vars[(bl_pos, '//')] if in_bounds(bl_pos, self.V, self.H) else 0
90
+ self.model.Add(sum([tl_var, tr_var, bl_var, br_var]) == number)
91
+ board_nodes = {(node.node_type, node.pos, node.slant): node for node in self.nodes.keys()}
92
+ self.neighbor_dict = {node: node.get_neighbors(board_nodes) for node in self.nodes.keys()}
93
+ no_loops_vars = force_no_loops(self.model, self.nodes, is_neighbor=lambda n1, n2: n1 in self.neighbor_dict[n2])
94
+ self.no_loops_vars = no_loops_vars
95
+
96
+
97
+ def solve_and_print(self, verbose: bool = True):
98
+ def board_to_solution(board: Board, solver: cp_model.CpSolverSolutionCallback) -> SingleSolution:
99
+ assignment: dict[Pos, int] = {}
100
+ # graph = {node: solver.Value(var) for node, var in board.nodes.items()}
101
+ for (pos, s), var in board.model_vars.items():
102
+ if solver.Value(var) == 1:
103
+ assignment[pos] = s
104
+ for p in get_all_pos(self.V, self.H):
105
+ assert p in assignment, f'position {p} is not assigned a number'
106
+ return SingleSolution(assignment=assignment)
107
+ def callback(single_res: SingleSolution):
108
+ print("Solution found")
109
+ res = np.full((self.V, self.H), ' ', dtype=object)
110
+ for pos in get_all_pos(self.V, self.H):
111
+ set_char(res, pos, '/' if single_res.assignment[pos] == '//' else '\\')
112
+ print('[')
113
+ for row in range(self.V):
114
+ line = ' [ ' + ' '.join(res[row].tolist()) + ' ]'
115
+ print(line)
116
+ print(']')
117
+ return generic_solve_all(self, board_to_solution, callback=callback if verbose else None, verbose=verbose)
@@ -1,5 +1,5 @@
1
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.
2
+ This file is a simple helper that parses the images from https://www.puzzle-stitches.com/ and converts them to a json file.
3
3
  Look at the ./input_output/ directory for examples of input images and output json files.
4
4
  The output json is used in the test_solve.py file to test the solver.
5
5
  """
@@ -0,0 +1,128 @@
1
+ import numpy as np
2
+ from ortools.sat.python import cp_model
3
+
4
+ from puzzle_solver.core.utils import Pos, get_all_pos, get_row_pos, get_col_pos, set_char, get_pos, get_char, Direction, in_bounds, get_next_pos
5
+ from puzzle_solver.core.utils_ortools import generic_solve_all, SingleSolution
6
+
7
+
8
+ def parse_board(board: np.array) -> tuple[np.array, list[tuple[Pos, Pos, str]]]:
9
+ """Returns the internal board and a list for every pair of positions (p1, p2, comparison_type) where p1 < p2 if comparison_type is '<' otherwise abs(p1 - p2)==1 if comparison_type is '|'"""
10
+ V = int(np.ceil(board.shape[0] / 2))
11
+ H = int(np.ceil(board.shape[1] / 2))
12
+ internal_board = np.full((V, H), ' ', dtype=object)
13
+ pairs = []
14
+ for row_i in range(board.shape[0]):
15
+ for col_i in range(board.shape[1]):
16
+ cell = board[row_i, col_i]
17
+ if row_i % 2 == 0 and col_i % 2 == 0: # number or empty cell
18
+ if cell == ' ':
19
+ continue
20
+ # map A to 10, B to 11, etc.
21
+ if str(cell).isalpha() and len(str(cell)) == 1:
22
+ cell = ord(cell.upper()) - ord('A') + 10
23
+ assert str(cell).isdecimal(), f'expected number at {row_i, col_i}, got {cell}'
24
+ internal_board[row_i // 2, col_i // 2] = int(cell)
25
+ elif row_i % 2 == 0 and col_i % 2 == 1: # horizontal comparison
26
+ assert cell in ['<', '>', '|', ' '], f'expected <, >, |, or empty cell at {row_i, col_i}, got {cell}'
27
+ if cell == ' ':
28
+ continue
29
+ p1 = get_pos(x=col_i // 2, y=row_i // 2)
30
+ p2 = get_pos(x=p1.x + 1, y=p1.y)
31
+ if cell == '<':
32
+ pairs.append((p1, p2, '<'))
33
+ elif cell == '>':
34
+ pairs.append((p2, p1, '<'))
35
+ elif cell == '|':
36
+ pairs.append((p1, p2, '|'))
37
+ else:
38
+ raise ValueError(f'unexpected cell {cell} at {row_i, col_i}')
39
+ elif row_i % 2 == 1 and col_i % 2 == 0: # vertical comparison
40
+ assert cell in ['∧', '∨', 'U', 'D', 'V', 'n', '-', '|', ' '], f'expected ∧, ∨, U, D, V, n, -, |, or empty cell at {row_i, col_i}, got {cell}'
41
+ if cell == ' ':
42
+ continue
43
+ p1 = get_pos(x=col_i // 2, y=row_i // 2)
44
+ p2 = get_pos(x=p1.x, y=p1.y + 1)
45
+ if cell in ['∨', 'U', 'V']:
46
+ pairs.append((p2, p1, '<'))
47
+ elif cell in ['∧', 'D', 'n']:
48
+ pairs.append((p1, p2, '<'))
49
+ elif cell in ['-', '|']:
50
+ pairs.append((p1, p2, '|'))
51
+ else:
52
+ raise ValueError(f'unexpected cell {cell} at {row_i, col_i}')
53
+ else:
54
+ assert cell in [' ', '.', 'X'], f'expected empty cell or dot or X at unused corner {row_i, col_i}, got {cell}'
55
+ return internal_board, pairs
56
+
57
+ class Board:
58
+ def __init__(self, board: np.array, adjacent_mode: bool = False, include_zero_before_letter: bool = True):
59
+ assert board.ndim == 2, f'board must be 2d, got {board.ndim}'
60
+ assert board.shape[0] > 0 and board.shape[1] > 0, 'board must be non-empty'
61
+ self.board, self.pairs = parse_board(board)
62
+ self.adjacent_mode = adjacent_mode
63
+ self.V, self.H = self.board.shape
64
+ self.lb = 1
65
+ self.N = max(self.V, self.H)
66
+ if include_zero_before_letter and self.N > 9: # zero is introduced when board gets to 10, then we add 1 letter after that
67
+ self.lb = 0
68
+ self.N -= 1
69
+
70
+ self.model = cp_model.CpModel()
71
+ self.model_vars: dict[Pos, cp_model.IntVar] = {}
72
+ self.create_vars()
73
+ self.add_all_constraints()
74
+
75
+ def create_vars(self):
76
+ for pos in get_all_pos(self.V, self.H):
77
+ self.model_vars[pos] = self.model.NewIntVar(self.lb, self.N, f'{pos}')
78
+
79
+ def add_all_constraints(self):
80
+ for row_i in range(self.V):
81
+ self.model.AddAllDifferent([self.model_vars[pos] for pos in get_row_pos(row_i, self.H)])
82
+ for col_i in range(self.H):
83
+ self.model.AddAllDifferent([self.model_vars[pos] for pos in get_col_pos(col_i, self.V)])
84
+ for pos in get_all_pos(self.V, self.H):
85
+ c = get_char(self.board, pos)
86
+ if str(c).isdecimal():
87
+ self.model.Add(self.model_vars[pos] == int(c))
88
+
89
+ for p1, p2, comparison_type in self.pairs:
90
+ assert comparison_type in ['<', '|'], f'SHOULD NEVER HAPPEN: invalid comparison type {comparison_type}, expected < or |'
91
+ if comparison_type == '<':
92
+ self.model.Add(self.model_vars[p1] < self.model_vars[p2])
93
+ elif comparison_type == '|':
94
+ aux = self.model.NewIntVar(0, 2*self.N, f'aux_{p1}_{p2}')
95
+ self.model.AddAbsEquality(aux, self.model_vars[p1] - self.model_vars[p2])
96
+ self.model.Add(aux == 1)
97
+ if self.adjacent_mode:
98
+ # in adjacent mode, there is strict NON adjacency if a | does not exist
99
+ all_pairs = {(p1, p2) for p1, p2, _ in self.pairs}
100
+ for pos in get_all_pos(self.V, self.H):
101
+ for direction in [Direction.RIGHT, Direction.DOWN]:
102
+ neighbor = get_next_pos(pos, direction)
103
+ if not in_bounds(neighbor, self.V, self.H):
104
+ continue
105
+ if (pos, neighbor) in all_pairs:
106
+ continue
107
+ assert (neighbor, pos) not in all_pairs, f'SHOULD NEVER HAPPEN: both {pos}->{neighbor} and {neighbor}->{pos} are in the same pair'
108
+ aux = self.model.NewIntVar(0, 2*self.N, f'aux_{pos}_{neighbor}')
109
+ self.model.AddAbsEquality(aux, self.model_vars[pos] - self.model_vars[neighbor])
110
+ self.model.Add(aux != 1)
111
+
112
+ def solve_and_print(self, verbose: bool = True):
113
+ def board_to_solution(board: Board, solver: cp_model.CpSolverSolutionCallback) -> SingleSolution:
114
+ assignment: dict[Pos, int] = {}
115
+ for pos, var in board.model_vars.items():
116
+ assignment[pos] = solver.Value(var)
117
+ return SingleSolution(assignment=assignment)
118
+ def callback(single_res: SingleSolution):
119
+ print("Solution found")
120
+ res = np.full((self.V, self.H), ' ', dtype=object)
121
+ for pos in get_all_pos(self.V, self.H):
122
+ set_char(res, pos, str(single_res.assignment[pos]))
123
+ print('[')
124
+ for row in range(self.V):
125
+ line = ' [ ' + ' '.join(res[row].tolist()) + ' ]'
126
+ print(line)
127
+ print(']')
128
+ return generic_solve_all(self, board_to_solution, callback=callback if verbose else None, verbose=verbose)