【问题标题】:KeyError in Gurobi Python for multidimensional variablesGurobi Python中用于多维变量的KeyError
【发布时间】:2018-12-24 22:22:02
【问题描述】:

我在 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')

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

【问题讨论】:

    标签: python optimization gurobi


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-25
      • 2020-05-23
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多