8

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.

David Nehme
  • 21,379
  • 8
  • 78
  • 117
Abhinav Yashkar
  • 81
  • 1
  • 1
  • 2

3 Answers3

10

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
David Nehme
  • 21,379
  • 8
  • 78
  • 117
  • 1
    There are two steps: retrieving the Var object as described above, and retrieving the solution value via the X attribute. – Greg Glockner May 10 '13 at 15:58
1

print (z[a].x)

Use the attribute X to get the value of a specific indexed variable. In my example, z is the variable and a is the index, while .x is the attribute.

Sabreen
  • 81
  • 1
  • 9
0

You can also do the following in case you don't have a name or reference handy (like when solving a saved model):

import gurobipy as gu
mdl = gu.read(<model_path>)
mdl.optimize()
mdl.getVars()

The last line will return a list of references to each variable.

Sean Kelley
  • 131
  • 5