对于Pyomo约束中的循环



我很难在Python Pyomo中使用for循环来创建多个约束。我的代码概念是以下

T = 504
model.times = RangeSet(0, T-1)
model.Machines = Set(initialize = Machines_parameters.keys())

然后,我将model.times划分为3个相同长度的集合,现在我想为集合的这一部分编写特定的约束。以下是代码的等效但简化版本:

for k in range(3): #number of parts in which I've divided the set [(0,167),(168,335),(336,503)]
for j in range(cluster_index[k][0], cluster_index[k][1]):   #respectively first and last number of the subset
def logic_constr(model,i):
if j >= const1[k] and j < const2[k]:
return model.z[i, j + 1] - model.z[i, j] == model.dsu[i, j + 1] - model.dsd[i, j + 1]
else j==const2[k]:
return model.z[i,const2[k]] - model.z[i,j] == model.dsu[i,const1[k]] - model.dsd[i,const1[k]]
model.logic_constr = Constraint(model.Machines, rule = logic_constr)

我想做的是迭代地创建504个不同的约束,每个约束都有自己的规则。你对如何做有什么建议吗?

按照您现在制定约束的方式,您最终只会在末尾有一个约束,因为在每个循环之后,约束都会被覆盖。

正如您所说,根据for循环,每个时间步长也需要一个约束,因此这要简单得多。

首先,您需要将约束定义为:

model.logic_constr = Constraint(model.Machines, model.times, rule = logic_constr)

这意味着约束将被应用于集合model.times的每个成员,即,对于集合模型的每个元素将有504个约束。机器。

然后,所有的if和for循环都可以进入logic_constr函数的定义中。

最新更新