<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 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 Cloud Pak for Data as a Service (Sign up for a free IBM Cloud account
and you can start using IBM Cloud Pak for Data as a Service right away).
CPLEX is available on <i>IBM Cloud Pack for Data</i> and <i>IBM Cloud Pak for Data as a Service</i>
Step1:  Note that the more global package <i>docplex</i> contains another subpackage <i>docplex.mp</i> that is dedicated to Mathematical Programming, another branch of optimization.
Step 2
Step2:  Set model parameter
Step3:  Step 3
Step4:  Define the decision variables
Step5:  Express the business constraints
Step6:  Solve the model
Step7:  Step 4
<ASSISTANT_TASK:>
Python Code:
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
Explanation: 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 Cloud Pak for Data as a Service (Sign up for a free IBM Cloud account
and you can start using IBM Cloud Pak for Data as a Service right away).
CPLEX is available on <i>IBM Cloud Pack for Data</i> and <i>IBM Cloud Pak for Data as a Service</i>:
   - <i>IBM Cloud Pak for Data as a Service</i>: Depends on the runtime used:
        - <i>Python 3.x</i> runtime: Community edition
        - <i>Python 3.x + DO</i> runtime: full edition
   - <i>Cloud Pack for Data</i>: Community edition is installed by default. Please install DO addon in Watson Studio Premium for the full edition
Table of contents:
Describe the business problem
How decision optimization (prescriptive analytics) can help
Use decision optimization
Step 1: Download the library
Step 2: Model the Data
Step 3: Set up the prescriptive model
Define the decision variables
Express the business constraints
Solve with Decision Optimization solve service
Step 4: Investigate the solution and run an example analysis
Summary
Describe the business problem
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.
References
https://en.wikipedia.org/wiki/Eight_queens_puzzle
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.
<br/>
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
Step 1: Download the library
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.
End of explanation
from docplex.cp.model import CpoModel
from sys import stdout
Explanation: Note that the more global package <i>docplex</i> contains another subpackage <i>docplex.mp</i> that is dedicated to Mathematical Programming, another branch of optimization.
Step 2: Model the data
End of explanation
NB_QUEEN = 8
Explanation: Set model parameter
End of explanation
mdl = CpoModel(name="NQueen")
Explanation: Step 3: Set up the prescriptive model
Create CPO model
End of explanation
# Create column index of each queen
x = mdl.integer_var_list(NB_QUEEN, 0, NB_QUEEN - 1, "X")
Explanation: Define the decision variables
End of explanation
# 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)))
Explanation: Express the business constraints
End of explanation
print("\nSolving model....")
msol = mdl.solve(TimeLimit=10)
Explanation: Solve the model
End of explanation
try:
    import numpy as np
    import matplotlib.pyplot as plt
    VISU_ENABLED = True
except ImportError:
    VISU_ENABLED = False
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()
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")
Explanation: Step 4: Investigate the solution and then run an example analysis
Import required external libraries (numpy and matplotlib)
End of explanation
<END_TASK>