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.
Gurobi python get value of the defined variable
Asked Answered
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
There are two steps: retrieving the Var object as described above, and retrieving the solution value via the X attribute. –
Smacker
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.
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.
© 2022 - 2024 — McMap. All rights reserved.