Gurobi python get value of the defined variable
Asked Answered
S

3

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.

Secede answered 8/5, 2013 at 9:15 Comment(0)
S
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
Serriform answered 8/5, 2013 at 22:0 Comment(1)
There are two steps: retrieving the Var object as described above, and retrieving the solution value via the X attribute.Smacker
B
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.

Bituminize answered 12/4, 2020 at 18:24 Comment(0)
A
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.

Anthozoan answered 22/11, 2021 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.