Gurobi Python中的KeyError用于多维变量

时间:2018-12-24 22:22:02

标签: python optimization gurobi

我在Gurobi-Python中建立了一个非常简单的优化模型,如下所示:

from gurobipy import *

commodities = ['Pencils', 'Pens']
arcs ={
  ('Detroit', 'Boston'):   100,
  ('Detroit', 'New York'):  80,
  ('Detroit', 'Seattle'):  120,
  ('Denver',  'Boston'):   120,
  ('Denver',  'New York'): 120,
  ('Denver',  'Seattle'):  120 }


# Create optimization model
m = Model('netflow')

# Create variables
flow = m.addVars(arcs,commodities)

# THE ONLY CONSTRAINT WHICH IS THE SOURCE OF ERROR!
m.addConstrs( flow[e,c] == 1 for e in arcs for c in  commodities)

# Compute optimal solution
m.optimize()

但是对于约束我得到了KeyError。

  

KeyError:(((“底特律”,“波士顿”),“铅笔”)

我看不到此约束有什么问题。任何评论都将不胜感激!

1 个答案:

答案 0 :(得分:1)

如果您看一下变量:

{('Detroit', 'Boston', 'Pencils'): <gurobi.Var C0>,
 ('Detroit', 'Boston', 'Pens'): <gurobi.Var C1>,
 ('Detroit', 'New York', 'Pencils'): <gurobi.Var C2>,
 ('Detroit', 'New York', 'Pens'): <gurobi.Var C3>,
 ('Detroit', 'Seattle', 'Pencils'): <gurobi.Var C4>,
 ('Detroit', 'Seattle', 'Pens'): <gurobi.Var C5>,
 ('Denver', 'Boston', 'Pencils'): <gurobi.Var C6>,
 ('Denver', 'Boston', 'Pens'): <gurobi.Var C7>,
 ('Denver', 'New York', 'Pencils'): <gurobi.Var C8>,
 ('Denver', 'New York', 'Pens'): <gurobi.Var C9>,
 ('Denver', 'Seattle', 'Pencils'): <gurobi.Var C10>,
 ('Denver', 'Seattle', 'Pens'): <gurobi.Var C11>}

您会看到需要解压缩arcs的每个元组:

m.addConstrs( flow[e1, e2, c] == 1 for e1, e2 in arcs for c in commodities)