Pyomo约束中的For循环

时间:2020-04-27 22:12:49

标签: 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个不同的约束,每个约束都有自己的规则。 您对此有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

因为正如您所说,并根据for循环,您还希望每个时间步长一个约束,所以这要简单得多。

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

         <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
            <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsse11="http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" wsse11:TokenType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey">
               <wsse:Reference URI="#EK-C31BABEAC91B9AC09E158807958051227807" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" />
            </wsse:SecurityTokenReference>
         </ds:KeyInfo>

这意味着约束将应用于集合model.logic_constr = Constraint(model.Machines, model.times, rule = logic_constr) 的每个成员,即,集合模型的每个元素将有504个约束。机械。

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