๐ Modeling with Qaekwy
In our first lesson, we learned the theory behind Constraint Satisfaction Problems (CSPs) using a map coloring example. Now, let’s translate that theory into practice and build a model using Qaekwy.
Recapping Our Problem
- Problem: Color a map with three countries (A, B, C).
- Adjacencies: A is next to B, and B is next to C.
- Colors (Domain): {Red, Green}.
- Constraint: Adjacent countries cannot have the same color.
To make this work with a computer, we’ll represent our colors as numbers: Red = 0, Green = 1.
Building the Qaekwy Model
Here is the step-by-step process to define this problem in Qaekwy.
1. The Model
Everything starts with a Modeller. This object holds all the pieces of your problem: variables, constraints, and objectives.
import qaekwy as qw
# Instantiate a new model
m = qw.Model()
2. Defining Variables
Next, we need to define our variables. We have three countries, and each can be colored with one of our two colors (0, 1). We can use an IntegerVariableArray for this, which is a convenient way to create a list of variables.
# Create an array of 3 integer variables, one for each country.
# Each variable can take a value from 0 to 1 (our colors).
countries = m.integer_array(
name="countries",
length=3,
domain=(0, 1)
)
We can think of this array as:
countries[0]= Color of Country Acountries[1]= Color of Country Bcountries[2]= Color of Country C
3. Adding Constraints
This is where we enforce the rules. The core rule is that adjacent countries must have different colors. We can use a simple relational constraint for this.
# Constraint 1: Color(A) != Color(B)
m.constraint(countries[0] != countries[1])
# Constraint 2: Color(B) != Color(C)
m.constraint(countries[1] != countries[2])
These two lines of code perfectly capture the rules of our map coloring problem.
The Complete Model
Here is the full Python script for our model:
import qaekwy as qw
# Instantiate a new model
m = qw.Model()
# 2. Define variables for our three countries
countries = m.integer_array(
name="countries",
length=3,
domain=(0, 1)
)
# 3. Add constraints for adjacent countries
# Country A (index 0) != Country B (index 1)
m.constraint(countries[0] != countries[1])
# Country B (index 1) != Country C (index 2)
m.constraint(countries[1] != countries[2])
We haven’t solved the problem yet, but we have successfully described it to Qaekwy. In the next and final lesson, we will learn how to ask the Qaekwy engine to solve this model and introduce the concept of optimization.