407 lines
13 KiB
Plaintext
407 lines
13 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "google",
|
|
"metadata": {},
|
|
"source": [
|
|
"##### Copyright 2025 Google LLC."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "apache",
|
|
"metadata": {},
|
|
"source": [
|
|
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
|
|
"you may not use this file except in compliance with the License.\n",
|
|
"You may obtain a copy of the License at\n",
|
|
"\n",
|
|
" http://www.apache.org/licenses/LICENSE-2.0\n",
|
|
"\n",
|
|
"Unless required by applicable law or agreed to in writing, software\n",
|
|
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
|
|
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
|
|
"See the License for the specific language governing permissions and\n",
|
|
"limitations under the License.\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "basename",
|
|
"metadata": {},
|
|
"source": [
|
|
"# nonogram_regular"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "link",
|
|
"metadata": {},
|
|
"source": [
|
|
"<table align=\"left\">\n",
|
|
"<td>\n",
|
|
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/nonogram_regular.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
|
|
"</td>\n",
|
|
"<td>\n",
|
|
"<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/nonogram_regular.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
|
|
"</td>\n",
|
|
"</table>"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "doc",
|
|
"metadata": {},
|
|
"source": [
|
|
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "install",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"%pip install ortools"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "description",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"\n",
|
|
" Nonogram (Painting by numbers) in Google CP Solver.\n",
|
|
"\n",
|
|
" http://en.wikipedia.org/wiki/Nonogram\n",
|
|
" '''\n",
|
|
" Nonograms or Paint by Numbers are picture logic puzzles in which cells in a\n",
|
|
" grid have to be colored or left blank according to numbers given at the\n",
|
|
" side of the grid to reveal a hidden picture. In this puzzle type, the\n",
|
|
" numbers measure how many unbroken lines of filled-in squares there are\n",
|
|
" in any given row or column. For example, a clue of '4 8 3' would mean\n",
|
|
" there are sets of four, eight, and three filled squares, in that order,\n",
|
|
" with at least one blank square between successive groups.\n",
|
|
"\n",
|
|
" '''\n",
|
|
"\n",
|
|
" See problem 12 at http://www.csplib.org/.\n",
|
|
"\n",
|
|
" http://www.puzzlemuseum.com/nonogram.htm\n",
|
|
"\n",
|
|
" Haskell solution:\n",
|
|
" http://twan.home.fmf.nl/blog/haskell/Nonograms.details\n",
|
|
"\n",
|
|
" Brunetti, Sara & Daurat, Alain (2003)\n",
|
|
" 'An algorithm reconstructing convex lattice sets'\n",
|
|
" http://geodisi.u-strasbg.fr/~daurat/papiers/tomoqconv.pdf\n",
|
|
"\n",
|
|
"\n",
|
|
" The Comet model (http://www.hakank.org/comet/nonogram_regular.co)\n",
|
|
" was a major influence when writing this Google CP solver model.\n",
|
|
"\n",
|
|
" I have also blogged about the development of a Nonogram solver in Comet\n",
|
|
" using the regular constraint.\n",
|
|
" * 'Comet: Nonogram improved: solving problem P200 from 1:30 minutes\n",
|
|
" to about 1 second'\n",
|
|
" http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html\n",
|
|
"\n",
|
|
" * 'Comet: regular constraint, a much faster Nonogram with the regular\n",
|
|
" constraint,\n",
|
|
" some OPL models, and more'\n",
|
|
" http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html\n",
|
|
"\n",
|
|
" Compare with the other models:\n",
|
|
" * Gecode/R: http://www.hakank.org/gecode_r/nonogram.rb (using 'regexps')\n",
|
|
" * MiniZinc: http://www.hakank.org/minizinc/nonogram_regular.mzn\n",
|
|
" * MiniZinc: http://www.hakank.org/minizinc/nonogram_create_automaton.mzn\n",
|
|
" * MiniZinc: http://www.hakank.org/minizinc/nonogram_create_automaton2.mzn\n",
|
|
" Note: nonogram_create_automaton2.mzn is the preferred model\n",
|
|
"\n",
|
|
" This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
|
|
" Also see my other Google CP Solver models:\n",
|
|
" http://www.hakank.org/google_or_tools/\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "code",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import sys\n",
|
|
"\n",
|
|
"from ortools.constraint_solver import pywrapcp\n",
|
|
"\n",
|
|
"\n",
|
|
"#\n",
|
|
"# Global constraint regular\n",
|
|
"#\n",
|
|
"# This is a translation of MiniZinc's regular constraint (defined in\n",
|
|
"# lib/zinc/globals.mzn), via the Comet code refered above.\n",
|
|
"# All comments are from the MiniZinc code.\n",
|
|
"# '''\n",
|
|
"# The sequence of values in array 'x' (which must all be in the range 1..S)\n",
|
|
"# is accepted by the DFA of 'Q' states with input 1..S and transition\n",
|
|
"# function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'\n",
|
|
"# (which must be in 1..Q) and accepting states 'F' (which all must be in\n",
|
|
"# 1..Q). We reserve state 0 to be an always failing state.\n",
|
|
"# '''\n",
|
|
"#\n",
|
|
"# x : IntVar array\n",
|
|
"# Q : number of states\n",
|
|
"# S : input_max\n",
|
|
"# d : transition matrix\n",
|
|
"# q0: initial state\n",
|
|
"# F : accepting states\n",
|
|
"def regular(x, Q, S, d, q0, F):\n",
|
|
"\n",
|
|
" solver = x[0].solver()\n",
|
|
"\n",
|
|
" assert Q > 0, 'regular: \"Q\" must be greater than zero'\n",
|
|
" assert S > 0, 'regular: \"S\" must be greater than zero'\n",
|
|
"\n",
|
|
" # d2 is the same as d, except we add one extra transition for\n",
|
|
" # each possible input; each extra transition is from state zero\n",
|
|
" # to state zero. This allows us to continue even if we hit a\n",
|
|
" # non-accepted input.\n",
|
|
"\n",
|
|
" # int d2[0..Q, 1..S]\n",
|
|
" d2 = []\n",
|
|
" for i in range(Q + 1):\n",
|
|
" row = []\n",
|
|
" for j in range(S):\n",
|
|
" if i == 0:\n",
|
|
" row.append(0)\n",
|
|
" else:\n",
|
|
" row.append(d[i - 1][j])\n",
|
|
" d2.append(row)\n",
|
|
"\n",
|
|
" d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]\n",
|
|
"\n",
|
|
" # If x has index set m..n, then a[m-1] holds the initial state\n",
|
|
" # (q0), and a[i+1] holds the state we're in after processing\n",
|
|
" # x[i]. If a[n] is in F, then we succeed (ie. accept the\n",
|
|
" # string).\n",
|
|
" x_range = list(range(0, len(x)))\n",
|
|
" m = 0\n",
|
|
" n = len(x)\n",
|
|
"\n",
|
|
" a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]\n",
|
|
"\n",
|
|
" # Check that the final state is in F\n",
|
|
" solver.Add(solver.MemberCt(a[-1], F))\n",
|
|
" # First state is q0\n",
|
|
" solver.Add(a[m] == q0)\n",
|
|
" for i in x_range:\n",
|
|
" solver.Add(x[i] >= 1)\n",
|
|
" solver.Add(x[i] <= S)\n",
|
|
" # Determine a[i+1]: a[i+1] == d2[a[i], x[i]]\n",
|
|
" solver.Add(\n",
|
|
" a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))\n",
|
|
"\n",
|
|
"\n",
|
|
"#\n",
|
|
"# Make a transition (automaton) matrix from a\n",
|
|
"# single pattern, e.g. [3,2,1]\n",
|
|
"#\n",
|
|
"def make_transition_matrix(pattern):\n",
|
|
"\n",
|
|
" p_len = len(pattern)\n",
|
|
" num_states = p_len + sum(pattern)\n",
|
|
"\n",
|
|
" # this is for handling 0-clues. It generates\n",
|
|
" # just the state 1,2\n",
|
|
" if num_states == 0:\n",
|
|
" num_states = 1\n",
|
|
"\n",
|
|
" t_matrix = []\n",
|
|
" for i in range(num_states):\n",
|
|
" row = []\n",
|
|
" for j in range(2):\n",
|
|
" row.append(0)\n",
|
|
" t_matrix.append(row)\n",
|
|
"\n",
|
|
" # convert pattern to a 0/1 pattern for easy handling of\n",
|
|
" # the states\n",
|
|
" tmp = [0 for i in range(num_states)]\n",
|
|
" c = 0\n",
|
|
" tmp[c] = 0\n",
|
|
" for i in range(p_len):\n",
|
|
" for j in range(pattern[i]):\n",
|
|
" c += 1\n",
|
|
" tmp[c] = 1\n",
|
|
" if c < num_states - 1:\n",
|
|
" c += 1\n",
|
|
" tmp[c] = 0\n",
|
|
"\n",
|
|
" t_matrix[num_states - 1][0] = num_states\n",
|
|
" t_matrix[num_states - 1][1] = 0\n",
|
|
"\n",
|
|
" for i in range(num_states):\n",
|
|
" if tmp[i] == 0:\n",
|
|
" t_matrix[i][0] = i + 1\n",
|
|
" t_matrix[i][1] = i + 2\n",
|
|
" else:\n",
|
|
" if i < num_states - 1:\n",
|
|
" if tmp[i + 1] == 1:\n",
|
|
" t_matrix[i][0] = 0\n",
|
|
" t_matrix[i][1] = i + 2\n",
|
|
" else:\n",
|
|
" t_matrix[i][0] = i + 2\n",
|
|
" t_matrix[i][1] = 0\n",
|
|
"\n",
|
|
" # print 'The states:'\n",
|
|
" # for i in range(num_states):\n",
|
|
" # for j in range(2):\n",
|
|
" # print t_matrix[i][j],\n",
|
|
" # print\n",
|
|
" # print\n",
|
|
"\n",
|
|
" return t_matrix\n",
|
|
"\n",
|
|
"\n",
|
|
"#\n",
|
|
"# check each rule by creating an automaton\n",
|
|
"# and regular\n",
|
|
"#\n",
|
|
"\n",
|
|
"\n",
|
|
"def check_rule(rules, y):\n",
|
|
" solver = y[0].solver()\n",
|
|
"\n",
|
|
" r_len = sum([1 for i in range(len(rules)) if rules[i] > 0])\n",
|
|
" rules_tmp = []\n",
|
|
" for i in range(len(rules)):\n",
|
|
" if rules[i] > 0:\n",
|
|
" rules_tmp.append(rules[i])\n",
|
|
"\n",
|
|
" transition_fn = make_transition_matrix(rules_tmp)\n",
|
|
" n_states = len(transition_fn)\n",
|
|
" input_max = 2\n",
|
|
"\n",
|
|
" # Note: we cannot use 0 since it's the failing state\n",
|
|
" initial_state = 1\n",
|
|
" accepting_states = [n_states] # This is the last state\n",
|
|
"\n",
|
|
" regular(y, n_states, input_max, transition_fn, initial_state,\n",
|
|
" accepting_states)\n",
|
|
"\n",
|
|
"\n",
|
|
"def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):\n",
|
|
"\n",
|
|
" # Create the solver.\n",
|
|
" solver = pywrapcp.Solver('Regular test')\n",
|
|
"\n",
|
|
" #\n",
|
|
" # data\n",
|
|
" #\n",
|
|
"\n",
|
|
" #\n",
|
|
" # variables\n",
|
|
" #\n",
|
|
" board = {}\n",
|
|
" for i in range(rows):\n",
|
|
" for j in range(cols):\n",
|
|
" board[i, j] = solver.IntVar(1, 2, 'board[%i,%i]' % (i, j))\n",
|
|
" board_flat = [board[i, j] for i in range(rows) for j in range(cols)]\n",
|
|
"\n",
|
|
" # Flattened board for labeling.\n",
|
|
" # This labeling was inspired by a suggestion from\n",
|
|
" # Pascal Van Hentenryck about my Comet nonogram model.\n",
|
|
" board_label = []\n",
|
|
" if rows * row_rule_len < cols * col_rule_len:\n",
|
|
" for i in range(rows):\n",
|
|
" for j in range(cols):\n",
|
|
" board_label.append(board[i, j])\n",
|
|
" else:\n",
|
|
" for j in range(cols):\n",
|
|
" for i in range(rows):\n",
|
|
" board_label.append(board[i, j])\n",
|
|
"\n",
|
|
" #\n",
|
|
" # constraints\n",
|
|
" #\n",
|
|
" for i in range(rows):\n",
|
|
" check_rule([row_rules[i][j] for j in range(row_rule_len)],\n",
|
|
" [board[i, j] for j in range(cols)])\n",
|
|
"\n",
|
|
" for j in range(cols):\n",
|
|
" check_rule([col_rules[j][k] for k in range(col_rule_len)],\n",
|
|
" [board[i, j] for i in range(rows)])\n",
|
|
"\n",
|
|
" #\n",
|
|
" # solution and search\n",
|
|
" #\n",
|
|
" db = solver.Phase(board_label, solver.CHOOSE_FIRST_UNBOUND,\n",
|
|
" solver.ASSIGN_MIN_VALUE)\n",
|
|
"\n",
|
|
" solver.NewSearch(db)\n",
|
|
"\n",
|
|
" num_solutions = 0\n",
|
|
" while solver.NextSolution():\n",
|
|
" print()\n",
|
|
" num_solutions += 1\n",
|
|
" for i in range(rows):\n",
|
|
" row = [board[i, j].Value() - 1 for j in range(cols)]\n",
|
|
" row_pres = []\n",
|
|
" for j in row:\n",
|
|
" if j == 1:\n",
|
|
" row_pres.append('#')\n",
|
|
" else:\n",
|
|
" row_pres.append(' ')\n",
|
|
" print(' ', ''.join(row_pres))\n",
|
|
"\n",
|
|
" print()\n",
|
|
" print(' ', '-' * cols)\n",
|
|
"\n",
|
|
" if num_solutions >= 2:\n",
|
|
" print('2 solutions is enough...')\n",
|
|
" break\n",
|
|
"\n",
|
|
" solver.EndSearch()\n",
|
|
" print()\n",
|
|
" print('num_solutions:', num_solutions)\n",
|
|
" print('failures:', solver.Failures())\n",
|
|
" print('branches:', solver.Branches())\n",
|
|
" print('WallTime:', solver.WallTime(), 'ms')\n",
|
|
"\n",
|
|
"\n",
|
|
"#\n",
|
|
"# Default problem\n",
|
|
"#\n",
|
|
"# From http://twan.home.fmf.nl/blog/haskell/Nonograms.details\n",
|
|
"# The lambda picture\n",
|
|
"#\n",
|
|
"rows = 12\n",
|
|
"row_rule_len = 3\n",
|
|
"row_rules = [[0, 0, 2], [0, 1, 2], [0, 1, 1], [0, 0, 2], [0, 0, 1], [0, 0, 3],\n",
|
|
" [0, 0, 3], [0, 2, 2], [0, 2, 1], [2, 2, 1], [0, 2, 3], [0, 2, 2]]\n",
|
|
"\n",
|
|
"cols = 10\n",
|
|
"col_rule_len = 2\n",
|
|
"col_rules = [[2, 1], [1, 3], [2, 4], [3, 4], [0, 4], [0, 3], [0, 3], [0, 3],\n",
|
|
" [0, 2], [0, 2]]\n",
|
|
"\n",
|
|
"if len(sys.argv) > 1:\n",
|
|
" file = sys.argv[1]\n",
|
|
" exec(compile(open(file).read(), file, 'exec'))\n",
|
|
"main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules)\n",
|
|
"\n"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"language_info": {
|
|
"name": "python"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|