Gurobi 中的 KeyError Python 用于多维变量

KeyError in Gurobi Python for multidimensional variables

我在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: (('Detroit', 'Boston'), 'Pencils')

我看不出这个约束有什么问题。非常感谢任何评论!

如果你看看你的变量:

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