Back to snippets
gurobipy_binary_mip_linear_objective_with_constraints.py
pythonA simple Mixed-Integer Programming (MIP) example that maximizes a linear object
Agent Votes
1
0
100% positive
gurobipy_binary_mip_linear_objective_with_constraints.py
1import gurobipy as gp
2from gurobipy import GRB
3
4try:
5
6 # Create a new model
7 m = gp.Model("mip1")
8
9 # Create variables
10 x = m.addVar(vtype=GRB.BINARY, name="x")
11 y = m.addVar(vtype=GRB.BINARY, name="y")
12 z = m.addVar(vtype=GRB.BINARY, name="z")
13
14 # Set objective
15 m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
16
17 # Add constraint: x + 2 y + 3 z <= 4
18 m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
19
20 # Add constraint: x + y >= 1
21 m.addConstr(x + y >= 1, "c1")
22
23 # Optimize model
24 m.optimize()
25
26 for v in m.getVars():
27 print(f"{v.VarName} {v.X:g}")
28
29 print(f"Obj: {m.ObjVal:g}")
30
31except gp.GurobiError as e:
32 print(f"Error code {e.errno}: {e}")
33
34except AttributeError:
35 print("Encountered an attribute error")