Gurobi python get value of the defined variable

Abhinav Yashkar picture Abhinav Yashkar · May 8, 2013 · Viewed 9.4k times · Source

How do i get the value of the variable that i have define previously(using addVar) in gurobi python? I need to compare the value of the gurobi variable and then perform calculations to reach to my objective variable. The same has to be done before optimization.

Answer

David Nehme picture David Nehme · May 9, 2013

You have two options. The most straightforward is to save a reference to the Var object returned by Model.addVar. Another way is to give a name your variables with the name parameter in addVar, then retrieve the variable with Model.getVarByName.

from gurobipy import *
a_var = m.addVar(name="variable.0")
# ...
a_var_reference = m.getVarByName("variable.0")
# a_var and a_var_reference refer to the same object
m.optimize()
#obtain the value of a_var in the optimal solution
if m.Status == GRB.OPTIMAL:
   print a_var.X