Gurobi

Introduction

In this example, we will explore how to submit a Gurobi program to Multivac to compute an objective function using Python.

We will create a file named test_gurobi.py to compute the result.

Example Code

from gurobipy import Model, GRB

# Create a new model
model = Model("Exemple")

# Add decision variables
x = model.addVar(name="x")
y = model.addVar(name="y")

# Define the objective function
model.setObjective(3 * x + 4 * y, GRB.MAXIMIZE)

# Add constraints
model.addConstr(2 * x + y <= 20, "Constraint 1")
model.addConstr(4 * x + 3 * y <= 45, "Constraint 2")
model.addConstr(x >= 0, "Constraint 3")
model.addConstr(y >= 0, "Constraint 4")

# Optimize the model
model.optimize()

# Show results
if model.status == GRB.OPTIMAL:
   print(f"Optimal solution found: x = {x.X}, y = {y.X}")
   print(f"Objective function value: {model.ObjVal}")
else:
   print("No optimal solution was found.")

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. You need to install the gurobipy package: pip install gurobipy

$ python3 -m venv venv
$ source venv/bin/activate
$ pip install gurobipy
$ deactivate

We will create a configuration file, for example test_gurobi.slurm, containing the execution settings for this Gurobi script. Choose one of the two alternatives shown below.

VERSION=1.3
JOB_NAME=test_gurobi
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=~/
# ALTERNATIVE 1
COMMANDS=(
   "hostname" # To know which machine executed the job
   "source $ROUTE/venv/bin/activate"
   "python3 $ROUTE/test_gurobi.py"
   "deactivate"

)
# ALTERNATIVE 2
COMMANDS=(
   "/opt/gurobi/gurobi1102/linux64/bin/gurobi.sh \"$ROUTE/test_gurobi.py\""
)

We will submit this script from iocex using the following command:

multivac test_gurobi.slurm

Once execution is complete, the output of our program will be visible in the same directory where the job was launched.