0% found this document useful (0 votes)
1 views

Lab 06 Constraint Satisfaction Problem

The document provides an overview of Constraint Satisfaction Problems (CSPs) in artificial intelligence, detailing their components, types, and constraints. It includes code examples for solving simple CSPs and the N-Queens problem using OR-Tools, along with explanations of the functions used for defining variables and constraints. The objective is to teach representation of real-world problems and efficient solving techniques through backtracking and constraint propagation.

Uploaded by

alishba.subhani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Lab 06 Constraint Satisfaction Problem

The document provides an overview of Constraint Satisfaction Problems (CSPs) in artificial intelligence, detailing their components, types, and constraints. It includes code examples for solving simple CSPs and the N-Queens problem using OR-Tools, along with explanations of the functions used for defining variables and constraints. The objective is to teach representation of real-world problems and efficient solving techniques through backtracking and constraint propagation.

Uploaded by

alishba.subhani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Artificial Lab 06

Intelligence​ Constraint
AI-2002 Satisfaction Problem

National University of Computer & Emerging Sciences –


NUCES – Karachi
Course Code: AI-2002 Artificial Intelligence Lab

1. Objective​ 3

2. Introduction to CSP​ 3

2.1 Components of CSP​ 3

2.2 CSP Representation​ 3

2.3 Types of CSP​ 4

2.4 Types of Constraints​ 4

2.5 Local Consistency in CSP​ 5

3. Code Example 1: Solving a simple CSP using OR-Tools​ 6

4. Code Example 2: Solving N-Queens​ 7

5. OR-Tools Help​ 9

6. Tasks​ 12

2
1. Objective
1.​ Learn how to represent real-world problems as variables, domains, and
constraints.
2.​ Gain knowledge of backtracking search, constraint propagation to solve CSPs
efficiently.

2. Introduction to CSP
A Constraint Satisfaction Problem is a mathematical problem where the solution must
meet a number of constraints. In a CSP, the objective is to assign values to variables such
that all the constraints are satisfied. CSPs are used extensively in artificial intelligence
for decision-making problems where resources must be managed or arranged within
strict guidelines. A solution to a CSP is an assignment of values to the variables such
that all constraints are satisfied.

2.1 Components Of CSP


CSPs are composed of three key elements:

1.​ Variables: The things that need to be determined are variables. Variables in a
CSP are the objects that must have values assigned to them in order to satisfy
a particular set of constraints.
2.​ Domains: The range of potential values that a variable can have is
represented by domains. Depending on the issue, a domain may be finite or
limitless. For instance, in Sudoku, the set of numbers from 1 to 9 can serve as
the domain of a variable representing a problem cell.
3.​ Constraints: The guidelines that control how variables relate to one another
are known as constraints. For instance, in a sudoku problem, the restrictions
might be that each row, column, and 3×3 box can only have one instance of
each number from 1 to 9.

2.2 CSP Representation

2.2.1 Map Coloring Problem


In this example, we will model a map coloring problem where the goal is to color a map
of countries such that no two adjacent countries share the same color. This is a classic
example of a Constraint Satisfaction Problem (CSP).

Variables: A, B, C, D (the countries).​


Domains: {Red, Green, Blue} (for each country).​
Constraints:​
A≠B, A≠C, B≠C, B≠D, C≠D

3
2.2.2 N-Queens Problem
Variables: q1, q2, q3, q4 (representing the columns where each queen is placed).​
Domains: {0, 1, 2, 3} (the columns for each queen).​
Constraints:
●​ q1 ≠ q2, q1 ≠ q3, q1 ≠ q4, q2 ≠ q3, q2 ≠ q4, q3 ≠ q4 (No two queens can share the
same column)
●​ Primary Diagonal: |q1 - q2| ≠ 1, |q1 - q3| ≠ 2, |q2 - q3| ≠ 1 (and so on for all pairs
of queens)
●​ Secondary Diagonal: q1 + q1 ≠ q2 + q2, q1 + q1 ≠ q3 + q3 (and so on for all pairs
of queens)

2.3 Types Of CSP


1.​ Binary CSPs: In these problems, each constraint involves only two variables. For
example, in a scheduling problem, the constraint could specify that task A must
be completed before task B.
2.​ Non-Binary CSPs: These problems have constraints that involve more than two
variables. For instance, in a seating arrangement problem, a constraint could
state that three people cannot sit next to each other.
3.​ Hard and Soft Constraints: Hard constraints must be strictly satisfied, while
soft constraints can be violated, but at a certain cost. This distinction is often
used in real-world applications where not all constraints are equally important.

2.4 Types of Constraints in CSP

A constraint specifies the relationship between one or more variables. Here are the
different types of constraints:

1.​ Unary Constraints: Constraints that involve a single variable.


○​ Example: A variable x must be greater than 5 (x > 5).
2.​ Binary Constraints: Constraints that involve exactly two variables.
○​ Example: A constraint between x and y could be x ≠ y.
3.​ Global Constraints: Constraints that involve more than two variables and are
often pre-defined in CSP solvers.
○​ Example: AllDifferent constraint: No two variables can take the same
value, applied to a set of variables.
4.​ N-ary Constraints: These involve more than two variables but are not
necessarily global. They may specify complex relationships between multiple
variables.
5.​ Sum and Difference Constraints: Constraints that enforce relationships
involving arithmetic sums or differences.
○​ Example: x + y = 10, where both x and y are variables.

4
2.5 Local Consistency in CSP

In CSP, local consistency refers to the process of reducing the search space by enforcing
consistency at various levels of constraints. There are several types of local consistency:

1. Node Consistency (NC):

●​ A variable is node-consistent if all the values in its domain satisfy the unary
constraints (if any).
●​ Example: For the constraint x > 5, a variable with domain {1, 2, 3, 6, 7} would not
be node-consistent because the values 1, 2, 3 violate the constraint.​

2. Arc Consistency (AC):

●​ A binary constraint is arc-consistent if for every variable X and every value in the
domain of X, there exists a value in the domain of Y (for the constraint X ∼ Y) such
that the constraint is satisfied.
●​ Example: If x + y = 10 and the domains of x and y are {5, 6, 7} and {3, 4, 5, 6}, then
arc-consistency would check if for every x value, there is a corresponding valid y
value.​

3. Path Consistency (PC):

●​ A CSP is path-consistent if for all triples of variables (X, Y, Z), whenever X and Y
are consistent with a binary constraint, and Y and Z are consistent with another
binary constraint, then X and Z must be consistent as well.​

4. k-consistency:

●​ A CSP is k-consistent if for every set of k-1 variables, the remaining variable can
be assigned a value such that all constraints are satisfied.​

Local consistency is crucial for reducing the search space and speeding up the solution
process.

5
3. Code Example 1: Solving a Simple CSP using
OR-Tools

Let's solve a simple CSP where:

●​ We have two variables x and y.


●​ Both variables have a domain of {1, 2, 3}.
●​ We want to satisfy the constraint x ≠ y.

#Import the google ortools library to solve the csp problem


from ortools.sat.python import cp_model

# 1. Create the model


model = cp_model.CpModel()

# 2. Define variables
x = model.NewIntVar(1, 3, 'x') # x can be 1, 2, or 3
y = model.NewIntVar(1, 3, 'y') # y can be 1, 2, or 3

# 3. Define constraints
model.Add(x != y) # x should not be equal to y

# 4. Create the solver and solve


solver = cp_model.CpSolver()
status = solver.Solve(model)
# 5. Output the solution
if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
print(f'Solution found: x = {solver.Value(x)}, y = {solver.Value(y)}')
else:
print('No solution found')

6
Explanation:

●​ cp_model.CpModel(): Creates a model for the CSP.


●​ model.NewIntVar(1, 3, 'x'): Defines an integer variable x with domain {1, 2, 3}.
●​ model.Add(x != y): Adds a constraint ensuring x is not equal to y.
●​ cp_model.CpSolver(): Creates a solver to solve the model.
●​ solver.Solve(model): Solves the model.
●​ solver.Value(x): Retrieves the value assigned to x.

4. Code Example 2: Solving N-Queens using OR-Tools


The N-Queens problem is a well-known CSP where we place N queens on an N×N
chessboard such that no two queens threaten each other. The constraints are:

1.​ No two queens are in the same row.


2.​ No two queens are in the same column.
3.​ No two queens are on the same diagonal.

from ortools.sat.python import cp_model

def solve_n_queens(n):
model = cp_model.CpModel()

# 1. Create the variables for each queen. Each queen is represented by a


column position.
queens = [model.NewIntVar(0, n - 1, f'queen_{i}') for i in range(n)]

# 2. Add the "AllDifferent" constraint to ensure no two queens share the


same column.
model.AddAllDifferent(queens)

# 3. Add diagonal constraints


for i in range(n):
for j in range(i + 1, n):
# Ensure queens i and j are not on the same diagonal (primary and
secondary).
model.Add(queens[i] - queens[j] != i - j) # Primary diagonal
constraint
model.Add(queens[i] - queens[j] != j - i) # Secondary diagonal
constraint

7
# 4. Create the solver and solve the model
solver = cp_model.CpSolver()
status = solver.Solve(model)

# 5. Output the solution


if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
solution = [solver.Value(q) for q in queens]
print(f'Solution for {n}-Queens: {solution}')
for row in range(n):
line = ['Q' if col == solution[row] else '.' for col in range(n)]
print(' '.join(line))
else:
print('No solution found')

# Solve for N = 8
solve_n_queens(8)

Solution for 8-Queens: [7, 1, 3, 0, 6, 4, 2, 5]


. . . . . . . Q
. Q . . . . . .
. . . Q . . . .
Q . . . . . . .
. . . . . . Q .
. . . . Q . . .
. . Q . . . . .

. . . . . Q . .

Explanation:

●​ Variables: queens[i] represents the column position of queen i on the


chessboard. The domain for each queen is {0, 1, 2, ..., n-1}, where n is the size of
the board.
●​ Constraints:
○​ model.AddAllDifferent(queens) ensures that no two queens are placed in
the same column.
○​ The diagonal constraints ensure that no two queens are placed on the
same diagonal.
●​ Solver: The solver tries to find a solution to the problem. If a solution exists, it is
printed in a human-readable format; otherwise, it outputs "No solution found."

8
5. OR-Tools Help
OR-Tools provides several functions to help define variables, domains, and constraints
when solving a Constraint Satisfaction Problem (CSP). Below is a list of key functions
and their purpose that will give you insight into how to define variables, set domains,
and specify constraints.

5.1 Functions for Defining Variables

Variables in OR-Tools are defined using the CpModel class, which allows you to specify
the domain for each variable.

●​ model.NewIntVar():
○​ Defines an integer variable within a specific domain.
○​ Syntax: model.NewIntVar(lb, ub, name)
○​ Parameters:
■​ lb: The lower bound of the domain.
■​ ub: The upper bound of the domain.
■​ name: The name of the variable.
○​ Example: x = model.NewIntVar(0, 9, 'x') creates a variable x with a domain
{0, 1, 2, ..., 9}.​

●​ model.NewIntVarArray():
○​ Defines an array of integer variables.
○​ Syntax: model.NewIntVarArray(n, lb, ub, name_prefix)
○​ Parameters:
■​ n: The number of variables to create.
■​ lb: The lower bound of the domain.
■​ ub: The upper bound of the domain.
■​ name_prefix: A common name prefix for all variables.
○​ Example: x = model.NewIntVarArray(5, 0, 9, 'x') creates 5 variables with
domains {0, 1, 2, ..., 9}.​

●​ model.NewBoolVar():
○​ Defines a boolean variable (can take values 0 or 1).
○​ Syntax: model.NewBoolVar(name)
○​ Example: x = model.NewBoolVar('x') creates a boolean variable x.​

●​ model.NewBoolVarArray():
○​ Defines an array of boolean variables.
○​ Syntax: model.NewBoolVarArray(n, name_prefix)
○​ Example: x = model.NewBoolVarArray(3, 'x') creates 3 boolean variables
with names x0, x1, and x2.

9

●​ model.NewIntervalVar():
○​ Defines an interval variable, often used in scheduling problems.
○​ Syntax: model.NewIntervalVar(start, size, end, name)
○​ Parameters:
■​ start: The start variable of the interval.
■​ size: The size (duration) of the interval.
■​ end: The end variable of the interval.
○​ Example: interval = model.NewIntervalVar(start, duration, end, 'interval')

5.2 Functions for Defining Constraints

Constraints are used to limit the values that the variables can take. The following
functions are commonly used to define various types of constraints.

●​ model.Add():
○​ Adds a general constraint to the model.
○​ Syntax: model.Add(expression)
○​ Example: model.Add(x != y) adds a constraint that x must not equal y.​

●​ model.AddAllDifferent():
○​ Adds the AllDifferent constraint, which ensures that all variables in the
list take distinct values.
○​ Syntax: model.AddAllDifferent([var1, var2, ..., varn])
○​ Example: model.AddAllDifferent([x, y, z]) ensures that x, y, and z all have
distinct values.​

●​ model.AddEquality():
○​ Adds an equality constraint between two expressions.
○​ Syntax: model.AddEquality(expression1, expression2)
○​ Example: model.AddEquality(x + y, 10) adds a constraint that x + y = 10.​

●​ model.AddLessThan():
○​ Adds a constraint to ensure that one expression is less than another.
○​ Syntax: model.AddLessThan(expression1, expression2)
○​ Example: model.AddLessThan(x, y) ensures that x < y.​

●​ model.AddGreaterThan():
○​ Adds a constraint to ensure that one expression is greater than another.
○​ Syntax: model.AddGreaterThan(expression1, expression2)
○​ Example: model.AddGreaterThan(x, y) ensures that x > y.​

10
●​ model.AddAbsEquality():
○​ Adds a constraint that enforces absolute equality (e.g., for diagonal
constraints in the N-Queens problem).
○​ Syntax: model.AddAbsEquality(expression1, expression2)
○​ Example: model.AddAbsEquality(x - y, 3) enforces |x - y| = 3.​

●​ model.AddBoolAnd():
○​ Adds an AND constraint between boolean variables
○​ Syntax: model.AddBoolAnd([var1, var2, ..., varn])
○​ Example: model.AddBoolAnd([x, y]) ensures that both x and y are true.​

●​ model.AddBoolOr():
○​ Adds an OR constraint between boolean variables
○​ Syntax: model.AddBoolOr([var1, var2, ..., varn])
○​ Example: model.AddBoolOr([x, y]) ensures that at least one of x or y is
true.​

●​ model.AddBoolNot():
○​ Adds a constraint that ensures a boolean variable is not true.
○​ Syntax: model.AddBoolNot(var)
○​ Example: model.AddBoolNot(x) ensures that x is false.​

●​ model.Minimize() and model.Maximize():


○​ Used to define an optimization problem where the goal is to either
minimize or maximize an expression.
○​ Example: model.Minimize(x + y) minimizes the sum of x and y.​

●​ model.AddExactlyOne():
○​ Adds a constraint that ensures exactly one variable in a list is set to True.
○​ Syntax: model.AddExactlyOne([var1, var2, ..., varn])
○​ Example: model.AddExactlyOne([x, y, z]) ensures that exactly one of x, y,
or z is True.

11
TASK: 01
Problem: Solve a standard 9x9 Sudoku puzzle, where you need to fill the grid with
numbers from 1 to 9. Each number can appear only once in each row, column, and 3x3
subgrid.

Variables: Each cell of the grid is a variable, with a domain of {1, 2, 3, ..., 9}.

Constraints:

○​ Each number must appear only once in each row.


○​ Each number must appear only once in each column.
○​ Each number must appear only once in each of the nine 3x3 subgrids.

Use OR-Tools to model the problem and apply the constraints for solving it.

Task: 02
Problem: Given a map with several countries (represented as nodes), color the
countries such that no two adjacent countries share the same color. For example, use
three colors: Red, Green, and Blue.​
Variables: Each country is a variable, with a domain of {Red, Green, Blue}.

Constraints: No two adjacent countries can have the same color.​


Goal: Find a valid color assignment for all countries, satisfying the adjacency
constraints.

Use OR-Tools to model the problem and define adjacency constraints using the
AddAllDifferent method to ensure different colors for adjacent countries.

Task: 03
Problem: Assign employees to work shifts such that every shift is covered, and the
employees work within their available hours. This problem can include constraints like
working hours limits, preference for shifts, and employee availability.

Variables: Each employee is assigned to a set of shifts, where the shifts are the
variables, and the values represent the employee's name or ID.

Employees = ['E1', 'E2', 'E3']​​ ​ ​ ​ shifts = ['S1', 'S2', 'S3']

Constraints:

○​ Every shift must be assigned to exactly one employee


○​ Each employee can work at most 2 shifts

12
Goal: Create a schedule that satisfies all constraints.

Use OR-Tools to define employee variables, apply constraints on employee shift


assignments, and use a solver to find a valid schedule.

Task: 04
A school needs to assign 3 teachers (T1, T2, T3) to 3 classes (C1, C2, C3). Each class
requires one teacher, and each teacher can be assigned to only one class. The
assignment must satisfy the following constraints:

1.​ T1 is only qualified to teach C1 and C3.


2.​ T2 cannot teach C2.
3.​ T3 prefers C2, and must be assigned to it if possible.
4.​ No class can have more than one teacher, and no teacher can be assigned to more
than one class.

Tasks:

a) Formulate this as a CSP. Specify:

●​ Variables
●​ Domains
●​ Constraints

b) Find a solution using OR-Tools that satisfies all constraints, or state if no solution
exists.

13

You might also like