bobby
bobby

Reputation: 113

How to index a dictionary by a Gurobi variable - Linear programming

In my optimization problem, I have a dictionary with data (given), and corresponding to each key there is a decision variable. I want to add a constraint where I need to use the decision variable as the index to the dictionary.

import gurobipy as gp
from gurobipy import GRB

model = gp.Model()

dic = {1: 0.5, 2: 1.45, 3: 3, 4: 0.3, 5: 2, 6: 2.8, 7: 1}

# domain of x is defined by the indices of the above dictionary
x = model.addVar(vtype = GRB.INTEGER, lb = 1, ub = 7)

# now, I want to put a constraint on the following lines
# model.addConstr(dic[x] >= 2.1)

I am new to Gurobi, any help will appreciated.

Upvotes: 1

Views: 145

Answers (1)

Bhartendu Awasthi
Bhartendu Awasthi

Reputation: 1029

You cannot use a decision variable to index a dictionary in Gurobi, like the way you are doing. To achieve the desired purpose, one way is to introduce binary variables. Please see the below code snippet :

import gurobipy as gp
from gurobipy import GRB

model = gp.Model()

dic = {1: 0.5, 2: 1.45, 3: 3, 4: 0.3, 5: 2, 6: 2.8, 7: 1}

len_dic = len(dic)
bool_varb = model.addVars(range(1, len_dic + 1), vtype=GRB.BINARY)
# assuming we want to select only one unique index, basis some constraints
model.addConstr(bool_varb.sum() == 1)

# x = model.addVar(vtype = GRB.INTEGER)
# model.addConstr(dic[x] >= 2.1)
# use below to express above
model.addConstr(bool_varb.prod(dic) >= 2.1)

# just added for illustration
# below expression in the constraint would resolve to 'x'
model.addConstr(gp.quicksum(i * j for i, j in zip(bool_varb.values(), dic.keys())) >= 4)

model.optimize()

As expected, x (using your terminology) resolves to 6
dic[x] (using your terminology) resolves to 2.8

Upvotes: 2

Related Questions