Gurobi, How to change a continuous variable to a binary variable

user2512443 picture user2512443 · May 22, 2015 · Viewed 7.6k times · Source

I am using gurobi-python interface. Is there anyway to convert a continuous variable to a binary variable. I just do not want to convert

m.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS)

to

m.addVar(lb=0, ub=1, vtype=GRB.BINARY). 

I have to do it in another way, not using

m.addVar() 

I appreciate your possible feedback.

Thank you.

Answer

David Nehme picture David Nehme · May 23, 2015

In the gurobi python API, you can simply set the vtype attribute on the variable. It is easy if you save a reference to the variable In your case, if you create a varaible

x = m.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS)

You can set it's attribe

x.vtype = GRB.BINARY

You can see it work in this longer example.

import gurobipy  as grb
GRB = grb.GRB
m = grb.Model()

x = m.addVar(0.0, 1.0, vtype=GRB.CONTINUOUS)
y = m.addVar(0.0, 1.0, vtype=GRB.CONTINUOUS)
m.update()
# add constraints so that y >= |x - 0.75|
m.addConstr(y >= x-0.75)
m.addConstr(y >= 0.75 - x)
m.setObjective(y)
m.update()
m.optimize()
print x.X
# 0.75
x.vtype=GRB.BINARY
m.optimize()
print x.X
# 1.0

In the first solve, x was continuous, so the optimal value for x was 0.75. In the second solve, x was binary, so the optimal value for x was 1.0.