# The eight queens puzzle

This tutorial includes everything you need to set up decision optimization engines, build constraint programming models.

When you finish this tutorial, you'll have a foundational knowledge of Prescriptive Analytics.

This notebook is part of Prescriptive Analytics for Python

It requires either an installation of CPLEX Optimizers or it can be run on IBM Watson Studio Cloud (Sign up for a free IBM Cloud account and you can start using Watson Studio Cloud right away).

• The eight queens puzzle is the problem of placing eight chess queens on an 8x8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.

• The eight queens puzzle is an example of the more general n-queens problem of placing n queens on an nxn chessboard, where solutions exist for all natural numbers n with the exception of n=2 and n=3.

## How decision optimization can help

• Prescriptive analytics technology recommends actions based on desired outcomes, taking into account specific scenarios, resources, and knowledge of past and current events. This insight can help your organization make better decisions and have greater control of business outcomes.

• Prescriptive analytics is the next step on the path to insight-based actions. It creates value through synergy with predictive analytics, which analyzes data to predict future outcomes.

• Prescriptive analytics takes that insight to the next level by suggesting the optimal way to handle that future situation. Organizations that can act fast in dynamic conditions and make superior decisions in uncertain environments gain a strong competitive advantage.

• For example:

• Automate complex decisions and trade-offs to better manage limited resources.
• Take advantage of a future opportunity or mitigate a future risk.
• Proactively update recommendations based on changing events.
• Meet operational goals, increase customer loyalty, prevent threats and fraud, and optimize business processes.

## Use decision optimization

Run the following code to install Decision Optimization CPLEX Modeling library. The DOcplex library contains the two modeling packages, Mathematical Programming and Constraint Programming, referred to earlier.

``````

In [ ]:

import sys
try:
import docplex.cp
except:
if hasattr(sys, 'real_prefix'):
#we are in a virtual env.
!pip install docplex
else:
!pip install --user docplex

``````

Note that the more global package docplex contains another subpackage docplex.mp that is dedicated to Mathematical Programming, another branch of optimization.

### Step 2: Model the data

``````

In [ ]:

from docplex.cp.model import CpoModel
from sys import stdout

``````

Set model parameter

``````

In [ ]:

NB_QUEEN = 8

``````

### Step 3: Set up the prescriptive model

Create CPO model

``````

In [ ]:

mdl = CpoModel(name="NQueen")

``````

#### Define the decision variables

``````

In [ ]:

# Create column index of each queen
x = mdl.integer_var_list(NB_QUEEN, 0, NB_QUEEN - 1, "X")

``````

``````

In [ ]:

# One queen per raw

# One queen per diagonal xi - xj != i - j
mdl.add(mdl.all_diff(x[i] + i for i in range(NB_QUEEN)))

# One queen per diagonal xi - xj != j - i
mdl.add(mdl.all_diff(x[i] - i for i in range(NB_QUEEN)))

``````

#### Solve the model

``````

In [ ]:

print("\nSolving model....")
msol = mdl.solve(TimeLimit=10)

``````

### Step 4: Investigate the solution and then run an example analysis

Import required external libraries (numpy and matplotlib)

``````

In [ ]:

try:
import numpy as np
import matplotlib.pyplot as plt
VISU_ENABLED = True
except ImportError:
VISU_ENABLED = False

``````
``````

In [ ]:

def display(sol):
%matplotlib inline

chess_board = np.zeros((NB_QUEEN, NB_QUEEN, 3))
black = 0.5
white = 1
for l in range(NB_QUEEN):
for c in range(NB_QUEEN):
if (l%2 == c%2):
col = white
else:
col = black
chess_board[l,c,::]=col

fig, ax = plt.subplots(figsize=(NB_QUEEN / 2, NB_QUEEN / 2))
ax.imshow(chess_board, interpolation='none')
# wq_im_file = "./n_queen_utils/WQueen.png"
# bq_im_file = "./n_queen_utils/BQueen.png"
wq_im_file = "https://github.com/IBMDecisionOptimization/docplex-examples/blob/master/examples/cp/jupyter/n_queen_utils/WQueen.png?raw=true"
bq_im_file = "https://github.com/IBMDecisionOptimization/docplex-examples/blob/master/examples/cp/jupyter/n_queen_utils/BQueen.png?raw=true"
for y, x in enumerate(sol):
if (x%2 == y%2):
queen = bq
else:
queen = wq
ax.imshow(queen, extent=[x-0.4, x + 0.4, y - 0.4, y + 0.4])
ax.set(xticks=[], yticks=[])
ax.axis('image')
plt.show()

``````
``````

In [ ]:

if msol:
stdout.write("Solution:")
sol = [msol[v] for v in x]
for v in range(NB_QUEEN):
stdout.write(" " + str(sol[v]))
stdout.write("\n")
stdout.write("Solve time: " + str(msol.get_solve_time()) + "\n")
if VISU_ENABLED:
display(sol)
else:
stdout.write("No solution found\n")

``````

## Summary

You learned how to set up and use the IBM Decision Optimization CPLEX Modeling for Python to formulate and solve a Constraint Programming model.

#### References

``````

In [ ]:

``````