Defining Gurobi variables based on other variables
AnsweredI am using Python 3.9.12 and Gurobi version 10.0.1 to solve a MILP and trying to define an absolute value of the difference between a gurobi variable and a given number. However, when defining the auxiliary variables ("deviation") as constraints, my model becomes infeasible.
These are the relevant code snippets:
# Define decision variables
x = {}
y = {}
deviation = {}
# Adding variables to the Model
for j in range(m):
# Loop over days
for i in range(n):
# Adding variable to model as integer, with name and an upper bound
x[i, j] = model.addVar(vtype=GRB.INTEGER, name=f"x[{i, j}]")
# Adding a binary variable that indicates whether there is a collection on the current day or not
y[i, j] = model.addVar(vtype=GRB.BINARY, name=f"y[{i, j}]")
# Adding the variables that is to be the difference between "x" and the mean
deviation[i,j] = model.addVar(vtype=GRB.CONTINUOUS, name=f"deviation[{i,j}]")
Adding the constraints that should further define the variables:
for j in range(m):
model.addConstrs((deviation[i,j] == x[i,j]  mean) for i in range(n))
So I tried to use the constraints to use the "deviation" variable at a later point in my objective function. I expected the "deviation" variable to simply take on the values of difference between "x" and the mean, but in fact Gurobi seems to not be able to solve my model anymore as soon as the constraints are added. So far, I have not used the variable "deviation" at a later point in my model (eg., in the objective function).
Let me know if there is more information needed.

Hi Helen,
All variables in Gurobi have an implicit lower bound of 0  it is customary to model with nonnegative variables. I imagine that the infeasibility comes from your continuous deviation variables being nonnegative as well. You need to define them as follows:
deviation[i,j] = model.addVar(
vtype=GRB.CONTINUOUS,
lb=GRB.INFINITY,
name=f"deviation[{i,j}]"
)I hope that fixes your issue.
Cheers,
Matthias0 
Hi Matthias,
thank you so much for your prompt reply  I didn't know that, but it works now!
Best,
Helen
0
Please sign in to leave a comment.
Comments
2 comments