我试图在 Pyomo 中实现一个相当复杂的约束并遇到错误。问题表述如下:
当前的工作(最后的代码块)导致以下错误:
ERROR: Rule failed when generating expression for Constraint c4 with index A0:
KeyError: "Index '(0, 0)' is not valid for indexed component 'x'"
ERROR: Constructing component 'c4' from data=None failed: KeyError: "Index
'(0, 0)' is not valid for indexed component 'x'"
我不确定为什么在这种情况下会导致错误。想法?
def constructAndIterate(m):
# Create the SuperMatrix including Decision Variables as Upper Right
newTopRight = np.ndarray((len(C), len(A)))
# Use the decision variables as matrix values
for c, i in enumerate(C):
for subA, j in enumerate(A):
newTopRight[i,j] = m.x[c,subA]
wNewTop = np.hstack((topLeft, newTopRight))
nW = np.vstack((wNewTop, wBot))
return iterateMatrix(nW)
model = pyo.ConcreteModel()
# Decision Variables
A = [ "A" + str(x) for x in range(10)]
C = [ "C" + str(x) for x in range(6)]
model.x = pyo.Var(C, A, domain = pyo.Reals)
@model.Objective(sense=pyo.minimize)
def cost(m):
return sum([m.x[c,a]**2.0 for a in A for c in C])
# Sum Columns of decisions vars
@model.Constraint(A)
def c1(m, a):
return sum([m.x[c,a] for c in C]) == 0
# Decision Var + W0 >= 0
@model.Constraint(C, A)
def c2(m, c, a):
# Extracts index from a and c -> "A0" becomes 0a
return m.x[c,a] + W0[int(c[1:])][int(a[1:])] >= 0
# Decision Var + W1 == 1
@model.Constraint(C,A)
def c3(m, c, a):
return m.x[c,a] + W0[int(c[1:])][int(a[1:])] == 1
# Limiting Priorites for C >= 0
@model.Constraint(A)
def c4(m, a):
_, _, _, _aVals = constructAndIterate(m)
# Create appropriate constraints
return _aVals[a] <= origPref
您正在翻转
enumerate()
的输出。
您所在的地方:
for c, i in enumerate(C):
你应该有
for i, c in enumerate(C):
你没有发布
enumerateMatrix
是什么/做什么,所以 YMMV。