如何通过 Gurobi 变量索引字典 - 线性规划

问题描述 投票:0回答:1

在我的优化问题中,我有一个包含数据(给定)的字典,并且对应于每个键有一个决策变量。我想添加一个约束,我需要使用决策变量作为字典的索引。

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)

我是 Gurobi 的新手,任何帮助将不胜感激。

linear-programming gurobi
1个回答
0
投票

您不能像您所做的那样使用决策变量在 Gurobi 中对字典进行索引。为了达到预期的目的,一种方法是引入二元变量。请参阅下面的代码片段:

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()

正如预期的那样,

x
(使用您的术语)解析为
6

dic[x]
(使用您的术语)解决为
2.8

© www.soinside.com 2019 - 2024. All rights reserved.