Newer
Older
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Constraint Satisfaction Problems (CSPs)\n",
"\n",
"This IPy notebook acts as supporting material for topics covered in **Chapter 6 Constraint Satisfaction Problems** of the book* Artificial Intelligence: A Modern Approach*. We make use of the implementations in **csp.py** module. Even though this notebook includes a brief summary of the main topics familiarity with the material present in the book is expected. We will look at some visualizations and solve some of the CSP problems described in the book. Let us import everything from the csp module to get started."
]
},
{
"cell_type": "code",
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from csp import *"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Review\n",
"\n",
"CSPs are a special kind of search problems. Here we don't treat the space as a black box but the state has a particular form and we use that to our advantage to tweak our algorithms to be more suited to the problems. A CSP State is defined by a set of variables which can take values from corresponding domains. These variables can take only certain values in their domains to satisfy the constraints. A set of assignments which satisfies all constraints passes the goal test. Let us start by exploring the CSP class which we will use to model our CSPs. You can keep the popup open and read the main page to get a better idea of the code.\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%psource CSP"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The __ _ _init_ _ __ method parameters specify the CSP. Variable can be passed as a list of strings or integers. Domains are passed as dict where key specify the variables and value specify the domains. The variables are passed as an empty list. Variables are extracted from the keys of the domain dictionary. Neighbor is a dict of variables that essentially describes the constraint graph. Here each variable key has a list its value which are the variables that are constraint along with it. The constraint parameter should be a function **f(A, a, B, b**) that **returns true** if neighbors A, B **satisfy the constraint** when they have values **A=a, B=b**. We have additional parameters like nassings which is incremented each time an assignment is made when calling the assign method. You can read more about the methods and parameters in the class doc string. We will talk more about them as we encounter their use. Let us jump to an example."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Graph Coloring\n",
"\n",
"We use the graph coloring problem as our running example for demonstrating the different algorithms in the **csp module**. The idea of map coloring problem is that the adjacent nodes (those connected by edges) should not have the same color throughout the graph. The graph can be colored using a fixed number of colors. Here each node is a variable and the values are the colors that can be assigned to them. Given that the domain will be the same for all our nodes we use a custom dict defined by the **UniversalDict** class. The **UniversalDict** Class takes in a parameter which it returns as value for all the keys of the dict. It is very similar to **defaultdict** in Python except that it does not support item assignment."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['R', 'G', 'B']"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s = UniversalDict(['R','G','B'])\n",
"s[5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For our CSP we also need to define a constraint function **f(A, a, B, b)**. In this what we need is that the neighbors must not have the same color. This is defined in the function **different_values_constraint** of the module."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%psource different_values_constraint"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The CSP class takes neighbors in the form of a Dict. The module specifies a simple helper function named **parse_neighbors** which allows to take input in the form of strings and return a Dict of the form compatible with the **CSP Class**."
]
},
{
"cell_type": "code",
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **MapColoringCSP** function creates and returns a CSP with the above constraint function and states. The variables our the keys of the neighbors dict and the constraint is the one specified by the **different_values_constratint** function. **australia**, **usa** and **france** are three CSPs that have been created using **MapColoringCSP**. **australia** corresponds to ** Figure 6.1 ** in the book."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%psource MapColoringCSP"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(<csp.CSP at 0x7f9da0d9aa58>,\n",
" <csp.CSP at 0x7f9da0da0ac8>,\n",
" <csp.CSP at 0x7f9da0d2a080>)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"australia, usa, france"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Helper Functions\n",
"\n",
"We will now implement few helper functions that will help us visualize the Coloring Problem. We will make some modifications to the existing Classes and Functions for additional book keeping. To begin with we modify the **assign** and **unassign** methods in the **CSP** to add a copy of the assignment to the **assingment_history**. We call this new class **InstruCSP**. This would allow us to see how the assignment evolves over time."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import copy\n",
"class InstruCSP(CSP):\n",
" \n",
" def __init__(self, variables, domains, neighbors, constraints):\n",
" super().__init__(variables, domains, neighbors, constraints)\n",
" self.assingment_history = []\n",
" \n",
" def assign(self, var, val, assignment):\n",
" super().assign(var,val, assignment)\n",
" self.assingment_history.append(copy.deepcopy(assignment))\n",
" \n",
" def unassign(self, var, assignment):\n",
" super().unassign(var,assignment)\n",
" self.assingment_history.append(copy.deepcopy(assignment)) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we modify the **MapColoringCSP** function to use the **InstruCSP**. "
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def ModMapColoringCSP(colors, neighbors):\n",
" if isinstance(neighbors, str):\n",
" neighbors = parse_neighbors(neighbors)\n",
" return InstruCSP(list(neighbors.keys()), UniversalDict(colors), neighbors,\n",
" different_values_constraint)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will now use the france graph for plotting purposes. The **parse_neighbors** function is used for parsing them."
]
},
{
"cell_type": "code",
"metadata": {
"collapsed": true
},
"outputs": [],
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"source": [
"neighbors = parse_neighbors(\"\"\"AL: LO FC; AQ: MP LI PC; AU: LI CE BO RA LR MP; BO: CE IF CA FC RA\n",
" AU; BR: NB PL; CA: IF PI LO FC BO; CE: PL NB NH IF BO AU LI PC; FC: BO\n",
" CA LO AL RA; IF: NH PI CA BO CE; LI: PC CE AU MP AQ; LO: CA AL FC; LR:\n",
" MP AU RA PA; MP: AQ LI AU LR; NB: NH CE PL BR; NH: PI IF CE NB; NO:\n",
" PI; PA: LR RA; PC: PL CE LI AQ; PI: NH NO CA IF; PL: BR NB CE PC; RA:\n",
" AU BO FC PA LR\"\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are ready to create an InstruCSP instance for our problem."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"coloring_problem1 = ModMapColoringCSP('RGBY', neighbors)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Backtracking Search\n",
"\n",
"For solving a CSP the main issue with Naive search algorithms is that they can continue expanding obviously wrong paths. In backtracking search, we check constraints as we go. Backtracking is just the above idea combined with the fact that we are dealing with one variable at a time. Backtracking Search is implemented in the repository as the function **backtracking_search**. This is the same as **Figure 6.5** in the book. The function takes as input a CSP and few other optional parameters which can be used to further speed it up. The function returns the correct assignment if it satisfies the goal. We will discuss these later. Let us solve our **coloring_problem1** with **backtracking_search**.\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"result = backtracking_search(coloring_problem1)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'AL': 'R',\n",
" 'AQ': 'B',\n",
" 'AU': 'G',\n",
" 'BO': 'B',\n",
" 'BR': 'Y',\n",
" 'CA': 'R',\n",
" 'CE': 'R',\n",
" 'FC': 'Y',\n",
" 'IF': 'G',\n",
" 'LI': 'Y',\n",
" 'LO': 'G',\n",
" 'LR': 'Y',\n",
" 'MP': 'R',\n",
" 'NB': 'G',\n",
" 'NH': 'B',\n",
" 'NO': 'R',\n",
" 'PA': 'G',\n",
" 'PC': 'G',\n",
" 'PI': 'Y',\n",
" 'PL': 'B',\n",
" 'RA': 'R'}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"result # A dictonary of assingments."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us also check the number of assingments made."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"37"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"coloring_problem1.nassigns"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let us check the total number of assingments and unassingments which is the lentgh ofour assingment history."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"53"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(coloring_problem1.assingment_history)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
},
"widgets": {
"state": {},
"version": "1.1.1"