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).
Table of contents:
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.
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:
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.
In [ ]:
from docplex.cp.model import CpoModel
from sys import stdout
Set model parameter
In [ ]:
NB_QUEEN = 8
Create CPO model
In [ ]:
mdl = CpoModel(name="NQueen")
In [ ]:
# Create column index of each queen
x = mdl.integer_var_list(NB_QUEEN, 0, NB_QUEEN - 1, "X")
In [ ]:
# One queen per raw
mdl.add(mdl.all_diff(x))
# 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)))
In [ ]:
print("\nSolving model....")
msol = mdl.solve(TimeLimit=10)
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"
wq = plt.imread(wq_im_file)
bq = plt.imread(bq_im_file)
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")
Copyright © 2017, 2018 IBM. IPLA licensed Sample Materials.
In [ ]: