1. Mixed Integer Programming
Easy
Description
Formulate and solve the following simple MIP model:
🚀 Test your code
Try to solve the problem below in the code editor before reading the solution.
Solutions
Approach 1: Using MIP Model
import gurobipy as gp
from gurobipy import GRB
def solveMipModel():
# Create a new model
m = gp.Model("mip1")
# Create variables
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")
# Set objective
m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
# Add constraint: x + 2 y + 3 z <= 4
m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
# Add constraint: x + y >= 1
m.addConstr(x + y >= 1, "c1")
# Optimize model
m.optimize()
print(f"Objective value: {m.ObjVal:g}")
for v in m.getVars():
print(f"{v.VarName} {v.X:g}")
if __name__ == "__main__":
solve_mip_model()
from pulp import *
def solveMipModel():
# Create the model
model = LpProblem(name="maximize_xyz", sense=LpMaximize)
# Define the decision variables
x = LpVariable(name="x", cat=LpBinary)
y = LpVariable(name="y", cat=LpBinary)
z = LpVariable(name="z", cat=LpBinary)
# Add the objective function
model += lpSum([x, y, 2*z]), "objective_function"
# Add the constraints
model += (x + 2*y + 3*z <= 4), "constraint_1"
model += (x + y >= 1), "constraint_2"
# Solve the model
model.solve()
# Print the results
print(f"Status: {model.status}")
print(f"Objective value: {model.objective.value()}")
for var in model.variables():
print(f"{var.name}: {var.value()}")
if __name__ == "__main__":
solve_mip_model()
Approach 2: Using Matrix API
import gurobipy as gp
from gurobipy import GRB
import numpy as np
import scipy.sparse as sp
try:
# Create a new model
m = gp.Model("matrix1")
# Create variables
x = m.addMVar(shape=3, vtype=GRB.BINARY, name="x")
# Set objective
obj = np.array([1.0, 1.0, 2.0])
m.setObjective(obj @ x, GRB.MAXIMIZE)
# Build (sparse) constraint matrix
val = np.array([1.0, 2.0, 3.0, -1.0, -1.0])
row = np.array([0, 0, 0, 1, 1])
col = np.array([0, 1, 2, 0, 1])
A = sp.csr_matrix((val, (row, col)), shape=(2, 3))
# Build rhs vector
rhs = np.array([4.0, -1.0])
# Add constraints
m.addConstr(A @ x <= rhs, name="c")
# Optimize model
m.optimize()
print(x.X)
print(f"Obj: {m.ObjVal:g}")
except gp.GurobiError as e:
print(f"Error code {e.errno}: {e}")
except AttributeError:
print("Encountered an attribute error")