CPLEX and Docplex
Introduction
In this example, we will explore how to submit a program to Multivac using CPLEX and the docplex module to compute an objective function.
Warning
If you get an error indicating the number of variables is limited, it means you did not create the venv using Multivac’s special script, mvac_crear_venv.
This script patches the CPLEX binary from the Python 3.10 educational license to work with Python 3.11, which is the version available in the cluster.
Example Code
Suppose we want to minimize the following objective function:
We will create a file named test_docplex.py to compute the objective function value for a specific value of x:
#!/usr/bin/python3
from docplex.mp.model import Model
if __name__ == '__main__':
# Create a model
model = Model(name='Objective_Function_Minimization')
# Define decision variable
x = model.continuous_var(name='x')
# Add the constraint: x must be equal to 5
model.add_constraint(x == 5, ctname='restriccio_x')
# Define objective function to minimize
f_objectiu = x**2 + 3*x + 2
model.minimize(f_objectiu)
# Solve model
solucio = model.solve()
# Print results
print("Optimal x value:", solucio[x])
print("Optimal objective function value:", solucio.get_objective_value())
This code defines the objective function, assigns a specific value to x (in this case, 5), and computes the objective function result for that value.
Execution
We will create a Python virtual environment named venv. This step is only required the first time the venv is created; afterwards it can be reused.
$ mvac_crear_venv
We will create a configuration file, for example test_docplex.slurm, containing the execution settings for this docplex script.
VERSION=1.3
JOB_NAME=test_docplex
NAME_OUTPUT=out
PARTITION=all
N_TASKS=1
CPUS_PER_TASK=1
MAIL_TYPE=END,FAIL
MAIL_USER=nom.usuari@upc.edu
MEMORY=1G
BEGIN=now
TIME_LIMIT=00:05:00
LOG_OUTPUT=log
FORCED_NODES=
EXCLUDED_NODES=
ROUTE=~/
COMMANDS=(
"hostname" # To know which machine executed the job
"source $ROUTE/venv/bin/activate"
"python3 $ROUTE/test_docplex.py"
"deactivate"
)
We will submit this script from iocex using the following command:
multivac test_docplex.slurm
Once execution is complete, the output of our program will be visible in the same directory where the job was launched.