1{
2 "cells": [
3  {
4   "cell_type": "markdown",
5   "id": "google",
6   "metadata": {},
7   "source": [
8    "##### Copyright 2021 Google LLC."
9   ]
10  },
11  {
12   "cell_type": "markdown",
13   "id": "apache",
14   "metadata": {},
15   "source": [
16    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
17    "you may not use this file except in compliance with the License.\n",
18    "You may obtain a copy of the License at\n",
19    "\n",
20    "    http://www.apache.org/licenses/LICENSE-2.0\n",
21    "\n",
22    "Unless required by applicable law or agreed to in writing, software\n",
23    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
24    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
25    "See the License for the specific language governing permissions and\n",
26    "limitations under the License.\n"
27   ]
28  },
29  {
30   "cell_type": "markdown",
31   "id": "basename",
32   "metadata": {},
33   "source": [
34    "# regular"
35   ]
36  },
37  {
38   "cell_type": "markdown",
39   "id": "link",
40   "metadata": {},
41   "source": [
42    "<table align=\"left\">\n",
43    "<td>\n",
44    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/contrib/regular.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
45    "</td>\n",
46    "<td>\n",
47    "<a href=\"https://github.com/google/or-tools/blob/master/examples/contrib/regular.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png\"/>View source on GitHub</a>\n",
48    "</td>\n",
49    "</table>"
50   ]
51  },
52  {
53   "cell_type": "markdown",
54   "id": "doc",
55   "metadata": {},
56   "source": [
57    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
58   ]
59  },
60  {
61   "cell_type": "code",
62   "execution_count": null,
63   "id": "install",
64   "metadata": {},
65   "outputs": [],
66   "source": [
67    "!pip install ortools"
68   ]
69  },
70  {
71   "cell_type": "code",
72   "execution_count": null,
73   "id": "code",
74   "metadata": {},
75   "outputs": [],
76   "source": [
77    "# Copyright 2010 Hakan Kjellerstrand hakank@gmail.com\n",
78    "#\n",
79    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
80    "# you may not use this file except in compliance with the License.\n",
81    "# You may obtain a copy of the License at\n",
82    "#\n",
83    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
84    "#\n",
85    "# Unless required by applicable law or agreed to in writing, software\n",
86    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
87    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
88    "# See the License for the specific language governing permissions and\n",
89    "# limitations under the License.\n",
90    "\"\"\"\n",
91    "\n",
92    "  Global constraint regular in Google CP Solver.\n",
93    "\n",
94    "  This is a translation of MiniZinc's regular constraint (defined in\n",
95    "  lib/zinc/globals.mzn). All comments are from the MiniZinc code.\n",
96    "  '''\n",
97    "  The sequence of values in array 'x' (which must all be in the range 1..S)\n",
98    "  is accepted by the DFA of 'Q' states with input 1..S and transition\n",
99    "  function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'\n",
100    "  (which must be in 1..Q) and accepting states 'F' (which all must be in\n",
101    "  1..Q).  We reserve state 0 to be an always failing state.\n",
102    "  '''\n",
103    "\n",
104    "  It is, however, translated from the Comet model:\n",
105    "  * Comet: http://www.hakank.org/comet/regular.co\n",
106    "\n",
107    "  Here we test with the following regular expression:\n",
108    "    0*1{3}0+1{2}0+1{1}0*\n",
109    "  using an array of size 10.\n",
110    "\n",
111    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
112    "  Also see my other Google CP Solver models:\n",
113    "  http://www.hakank.org/google_or_tools/\n",
114    "\n",
115    "\"\"\"\n",
116    "from ortools.constraint_solver import pywrapcp\n",
117    "\n",
118    "\n",
119    "#\n",
120    "# Global constraint regular\n",
121    "#\n",
122    "# This is a translation of MiniZinc's regular constraint (defined in\n",
123    "# lib/zinc/globals.mzn), via the Comet code refered above.\n",
124    "# All comments are from the MiniZinc code.\n",
125    "# '''\n",
126    "# The sequence of values in array 'x' (which must all be in the range 1..S)\n",
127    "# is accepted by the DFA of 'Q' states with input 1..S and transition\n",
128    "# function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'\n",
129    "# (which must be in 1..Q) and accepting states 'F' (which all must be in\n",
130    "# 1..Q).  We reserve state 0 to be an always failing state.\n",
131    "# '''\n",
132    "#\n",
133    "# x : IntVar array\n",
134    "# Q : number of states\n",
135    "# S : input_max\n",
136    "# d : transition matrix\n",
137    "# q0: initial state\n",
138    "# F : accepting states\n",
139    "def regular(x, Q, S, d, q0, F):\n",
140    "\n",
141    "  solver = x[0].solver()\n",
142    "\n",
143    "  assert Q > 0, 'regular: \"Q\" must be greater than zero'\n",
144    "  assert S > 0, 'regular: \"S\" must be greater than zero'\n",
145    "\n",
146    "  # d2 is the same as d, except we add one extra transition for\n",
147    "  # each possible input;  each extra transition is from state zero\n",
148    "  # to state zero.  This allows us to continue even if we hit a\n",
149    "  # non-accepted input.\n",
150    "\n",
151    "  # int d2[0..Q, 1..S];\n",
152    "  d2 = []\n",
153    "  for i in range(Q + 1):\n",
154    "    row = []\n",
155    "    for j in range(S):\n",
156    "      if i == 0:\n",
157    "        row.append(0)\n",
158    "      else:\n",
159    "        row.append(d[i - 1][j])\n",
160    "    d2.append(row)\n",
161    "\n",
162    "  d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]\n",
163    "\n",
164    "  # If x has index set m..n, then a[m-1] holds the initial state\n",
165    "  # (q0), and a[i+1] holds the state we're in after processing\n",
166    "  # x[i].  If a[n] is in F, then we succeed (ie. accept the\n",
167    "  # string).\n",
168    "  x_range = list(range(0, len(x)))\n",
169    "  m = 0\n",
170    "  n = len(x)\n",
171    "\n",
172    "  a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]\n",
173    "\n",
174    "  # Check that the final state is in F\n",
175    "  solver.Add(solver.MemberCt(a[-1], F))\n",
176    "  # First state is q0\n",
177    "  solver.Add(a[m] == q0)\n",
178    "  for i in x_range:\n",
179    "    solver.Add(x[i] >= 1)\n",
180    "    solver.Add(x[i] <= S)\n",
181    "\n",
182    "    # Determine a[i+1]: a[i+1] == d2[a[i], x[i]]\n",
183    "    solver.Add(\n",
184    "        a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))\n",
185    "\n",
186    "\n",
187    "#\n",
188    "# Make a transition (automaton) matrix from a\n",
189    "# single pattern, e.g. [3,2,1]\n",
190    "#\n",
191    "def make_transition_matrix(pattern):\n",
192    "\n",
193    "  p_len = len(pattern)\n",
194    "  print('p_len:', p_len)\n",
195    "  num_states = p_len + sum(pattern)\n",
196    "  print('num_states:', num_states)\n",
197    "  t_matrix = []\n",
198    "  for i in range(num_states):\n",
199    "    row = []\n",
200    "    for j in range(2):\n",
201    "      row.append(0)\n",
202    "    t_matrix.append(row)\n",
203    "\n",
204    "  # convert pattern to a 0/1 pattern for easy handling of\n",
205    "  # the states\n",
206    "  tmp = [0 for i in range(num_states)]\n",
207    "  c = 0\n",
208    "  tmp[c] = 0\n",
209    "  for i in range(p_len):\n",
210    "    for j in range(pattern[i]):\n",
211    "      c += 1\n",
212    "      tmp[c] = 1\n",
213    "    if c < num_states - 1:\n",
214    "      c += 1\n",
215    "      tmp[c] = 0\n",
216    "  print('tmp:', tmp)\n",
217    "\n",
218    "  t_matrix[num_states - 1][0] = num_states\n",
219    "  t_matrix[num_states - 1][1] = 0\n",
220    "\n",
221    "  for i in range(num_states):\n",
222    "    if tmp[i] == 0:\n",
223    "      t_matrix[i][0] = i + 1\n",
224    "      t_matrix[i][1] = i + 2\n",
225    "    else:\n",
226    "      if i < num_states - 1:\n",
227    "        if tmp[i + 1] == 1:\n",
228    "          t_matrix[i][0] = 0\n",
229    "          t_matrix[i][1] = i + 2\n",
230    "        else:\n",
231    "          t_matrix[i][0] = i + 2\n",
232    "          t_matrix[i][1] = 0\n",
233    "\n",
234    "  print('The states:')\n",
235    "  for i in range(num_states):\n",
236    "    for j in range(2):\n",
237    "      print(t_matrix[i][j], end=' ')\n",
238    "    print()\n",
239    "  print()\n",
240    "\n",
241    "  return t_matrix\n",
242    "\n",
243    "\n",
244    "\n",
245    "# Create the solver.\n",
246    "solver = pywrapcp.Solver('Regular test')\n",
247    "\n",
248    "#\n",
249    "# data\n",
250    "#\n",
251    "\n",
252    "this_len = 10\n",
253    "pp = [3, 2, 1]\n",
254    "\n",
255    "transition_fn = make_transition_matrix(pp)\n",
256    "n_states = len(transition_fn)\n",
257    "input_max = 2\n",
258    "\n",
259    "# Note: we use '1' and '2' (rather than 0 and 1)\n",
260    "# since 0 represents the failing state.\n",
261    "initial_state = 1\n",
262    "\n",
263    "accepting_states = [n_states]\n",
264    "\n",
265    "# declare variables\n",
266    "reg_input = [\n",
267    "    solver.IntVar(1, input_max, 'reg_input[%i]' % i) for i in range(this_len)\n",
268    "]\n",
269    "\n",
270    "#\n",
271    "# constraints\n",
272    "#\n",
273    "regular(reg_input, n_states, input_max, transition_fn, initial_state,\n",
274    "        accepting_states)\n",
275    "\n",
276    "#\n",
277    "# solution and search\n",
278    "#\n",
279    "db = solver.Phase(reg_input, solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,\n",
280    "                  solver.ASSIGN_MIN_VALUE)\n",
281    "\n",
282    "solver.NewSearch(db)\n",
283    "\n",
284    "num_solutions = 0\n",
285    "while solver.NextSolution():\n",
286    "  print('reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)])\n",
287    "  num_solutions += 1\n",
288    "\n",
289    "solver.EndSearch()\n",
290    "print()\n",
291    "print('num_solutions:', num_solutions)\n",
292    "print('failures:', solver.Failures())\n",
293    "print('branches:', solver.Branches())\n",
294    "print('WallTime:', solver.WallTime(), 'ms')\n",
295    "\n"
296   ]
297  }
298 ],
299 "metadata": {},
300 "nbformat": 4,
301 "nbformat_minor": 5
302}
303