我正在尝试嵌套迭代,以稍微压缩我的代码。我有一个运行的大型MIP,但代码非常混乱。我想把它浓缩成矢量等
我的代码基本如下:
using JuMP
using Gurobi
model = Model(with_optimizer(Gurobi.Optimizer))
@variable(model, x[1:11, 1:17, 1:54], Bin)
I = [(1:6),(7:11),(1:6),(7:11)]
K = [(51:54), (1:4), (1:50),(5:54)]
RHS = [4,4,0,0]
@constraints(model, begin
[i in I[1]], sum(x[i,17,k] for k in K[1]) == RHS[1]
[i in I[2]], sum(x[i,17,k] for k in K[2]) == RHS[2]
[i in I[3]], sum(x[i,17,k] for k in K[3]) == RHS[4]
[i in I[4]], sum(x[i,17,k] for k in K[4]) == RHS[4]
end
)
本质上,我想把所有这些约束浓缩到一行,就像在程序中进一步做的那样,我有类似的约束,有54次迭代。
我试过:
@constraint(model,
for (a,b,c) in zip(I, K, RHS)
[i in a], sum(x[i,17,k] for k in b) == c
end
)
以及其他一些组合,如
@constraint(model, [(a,b,c) in zip(I, K, RHS), i in a], sum(x[i,17,k] for k in b) == c)
但它不会适合我——我会遇到Load错误或重复迭代器错误。
非常感谢您的帮助!!!:-(
这个版本对我有用:
@constraint(
model,
[(a, b, c) in zip(I, K, RHS), i in a],
sum(x[i, 17, k] for k in b) == c
)
另一个可读性稍高的版本是
for (a, b, c) in zip(I, K, RHS)
@constraint(model, [i in a], sum(x[i, 17, k] for k in b) == c)
end
我不知怎么让它工作起来了:
@constraint(model, [(a,b,c) in zip(I,K,RHS), i in a],
sum(x[i,17,k] for k in b) == c)