Gurobi Using the Obj Parameter from addVar

I am new to gurobi and I do not understand why the following two code snippets do not return the same minimized objective function. I am attempting to set the objective function coefficient from the addVar function instead of the setObjective function.

Code Snippet 1:

import gurobipy as gb
from gurobipy import GRB

# create model
m = gb.Model()

# add variables
b = m.addVar(vtype=GRB.CONTINUOUS, lb=0, ub=1500000, name="variable_1")
c = m.addVar(vtype=GRB.CONTINUOUS, lb=0, ub=1200000, name="variable_2")
p = m.addVar(vtype=GRB.CONTINUOUS, lb=0, ub=2000000, name="variable_3")


# add objective function
m.setObjective(.5 * b + .6 * c + .7 * p, GRB.MINIMIZE)


# add constraints
m.addConstr(b + c + p == 4000000, "constraint_one")
m.addConstr(-3 * b - 18 * c + 7 * p >= 0, "constraint_two")
m.addConstr(-b + 4 * c + 2 * p >= 0, "constraint_three")

m.optimize()

Code Snippet 2:

import gurobipy as gb
from gurobipy import GRB

# create model
m = gb.Model()

# add variables
b = m.addVar(vtype=GRB.CONTINUOUS, lb=0, obj=0.5, ub=1500000, name="variable_1")
c = m.addVar(vtype=GRB.CONTINUOUS, lb=0, obj=0.6, ub=1200000, name="variable_2")
p = m.addVar(vtype=GRB.CONTINUOUS, lb=0, obj=0.7, ub=2000000, name="variable_3")


# add objective function
m.setObjective(b + c + p, GRB.MINIMIZE)


# add constraints
m.addConstr(b + c + p == 4000000, "constraint_one")
m.addConstr(-3 * b - 18 * c + 7 * p >= 0, "constraint_two")
m.addConstr(-b + 4 * c + 2 * p >= 0, "constraint_three")

m.optimize()

1 Answer

Use Model.setObjective() for code like snippet 1, when you want to specify the objective using a linear expression (LinExpr object). For snippet 2, you already specified the objective coefficients when you called Model.addVar(); instead, call m.ModelSense = GRB.MINIMIZE to tell Gurobi that you want to minimize the objective function.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest