Search code examples
pythonvariablesmathematical-optimizationgurobi

Get and compare Variable Values in Gurobi/Python


I would like to compare the value of an optimal gurobi variable to a number in order to decide the next steps for the model.

from gurobipy import *
m=Model("flow_model")   
arcs = [(0,1),(1,2),(3,4),(0,3), (1,4)]
f= m.addVars((a for a in arcs), vtype=GRB.CONTINUOUS, name = "flow")
d = [0,2,4,0,8]     
G = [10,0,0,4,0]

for i,j in arcs:
    m.addConstr(f.sum(i,'*') + d[i] == f.sum('*',i) + G[i], "node%d" %i) 

m.setObjective((quicksum(f[i,j] for i,j in arcs)), GRB.MAXIMIZE)

m.optimize()

for i,j in f:
    if f[(i,j)] > 1 :
        print('built a line')

I get an error saying "Unorderable types: Var() > int()". I also tried the following variation:

var_ref = m.getVarByName("flow")
for i,j in var_ref:
    if var_ref[(i,j)] > 1 :
        print('built a line')

But this error states its a "NoneType Object", so nothing is being stored in var_ref


Solution

  • f[(i,j)] is not a number-type recognized by python, it's a Gurobi Var object.

    You need to ask gurobi for its value:

    if f[(i,j)].X > 1:  # attribute! No function!
        ...
    

    This is explained in the docs:

    Variable value in the current solution.
    

    Overview of supported variable attributes