{ "cells": [ { "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", "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", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['R', 'G', 'B']" ] }, "execution_count": 3, "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", "execution_count": 4, "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", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "%pdoc parse_neighbors" ] }, { "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": [ "(,\n", " ,\n", " )" ] }, "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", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "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" } }, "nbformat": 4, "nbformat_minor": 0 }