【发布时间】:2019-11-06 09:30:19
【问题描述】:
我有一个目标函数,其中有一个if 条件。我无法在 Gurobi Python 中实现它。
背景
有s 供应商和p 工厂。 x[s][p] 是一个变量,表示从supplier-x 流向plant-p 的项目数。 c[s][p] 表示从供应商向中心供应一件商品的成本。
此外,每个供应商都有固定成本t[s]。如果供应商向任何中心供货,就会产生这个固定成本(这个固定成本不取决于物品的数量)。
我想使用像这样的目标函数来最小化成本 -
第一部分很容易建模,如sum(x[s, p] * spc[s, p] for s in range(num_suppliers) for p in range(num_center))。
对于第二个术语,我该如何建模? (第二部分基本上意味着只有当供应商实际上是任何工厂的供应商时才添加供应商的固定成本)。
编辑
这是我现在拥有的代码。注意:这不会产生最小值 -
from gurobipy import *
supplier_capacity = [
5, 10
]
plant_demand = [
2, 4
]
num_suppliers = len(supplier_capacity)
num_plants = len(plant_demand)
t = [
100, 1
]
c = {
(0, 0): 1,
(0, 1): 4,
(1, 0): 4,
(1, 1): 2
}
x = {} # flow between each supplier to plant
m = Model()
xl = [(s, p) for s in range(num_suppliers) for p in range(num_plants)]
x = m.addVars(xl, vtype=GRB.INTEGER, lb=0, name='flow')
for s in range(num_suppliers):
m.addConstr(x.sum(s, '*') <= supplier_capacity[s])
for p in range(num_plants):
m.addConstr(x.sum('*', p) >= plant_demand[p])
m.setObjective(
(
sum(x[s, p] * c[s, p] for s in range(num_suppliers) for p in range(num_plants)) +
sum(t[s] for s in range(num_suppliers) if x.sum(s, '*') >= 0)
), GRB.MINIMIZE
)
m.update()
m.optimize()
if m.status == GRB.Status.OPTIMAL:
print('==== RESULTS ====')
print('Min Cost: {}'.format(m.ObjVal))
for v in m.getVars():
print('{} = {}'.format(v.VarName, v.X))
else:
print('Infeasible model')
【问题讨论】:
-
我们可以将
s视为二维数组中的行数,将p视为列数吗? -
@Buckeye14Guy 是的,这就是它的概念。但我已将
x和c建模为以元组为键的字典。
标签: python mathematical-optimization linear-programming gurobi