在pyomo中创建一个带有稀疏索引的变量 [英] Create a variable with sparse index in pyomo
问题描述
我需要帮助来创建一个带有稀疏索引的变量.我有这样的事情:
I need help to create a variable with sparse indices. I have something like this:
model.K = Set()
model.P = Set()
model.KP = Param(model.K, model.P, default=0)
我将为 model.KP
加载一个 CSV 文件,其值为 KP==1
用于 K & 的组合.
I will load a CSV file for model.KP
with value KP==1
for the combinations of K & P.
model.X = Var(model.K, model.P)
我只想为模型中 K 和 P 的组合创建这个变量.KP 因为当我用 K 和 P 的所有组合创建变量时,它使用我给出的集合产生了 3700 万个索引,这个正在造成内存问题.
I want to create this variable only for the combinations of K and P in the model.KP because when I create the variable with all the combinations of K and P, it is producing 37 million indices with the sets I give and this is creating memory issues.
推荐答案
制作包含元组 (k,p)
的 Set
并将其用作定义两者的集合你的变量和你的参数.
Make a Set
containing tuples (k,p)
and use it as the set that defines both your variable and your parameter.
定义你的集合元素:
kp = []
for k in model.K:
for p in model.P:
foo_tuple = (k, p)
kp.append(foo_tuple)
注意:由于您将使用 CSV 文件加载数据,因此此时也可以使用所有 K 和 P 组合来填充 kp
.
Note: Since you will use a CSV file to load your data, populationg kp
with all K and P combinations can also be done at this time.
然后使用kp
中的元素创建一个Set
:
Then create a Set
using elements in kp
:
model.S = Set(initialize=kp)
如果您不需要,我建议不要在 model.KP
参数中使用默认值.这样做会通知您一个元素的缺失值,它应该有一个值.但是,假设您仍然希望在没有为元组 (p,k)提供值时,参数
model.PK
的所有值都为 0
code> 并继续使用默认值,您应该像这样定义参数:
I recommend not using default values in your model.KP
parameter if you don't need it. Doing so will notify you of a missing value for an element where it should have one. But let's say that you still want to have all values of parameter model.PK
to be 0
when no value was provided for tuple (p,k)
and continue using default values, you should define your parameter like so:
model.KP = Param(model.S, default=0)
然后,定义您的变量将是:
Then, defining your variable will be:
model.X = Var(model.S)
这篇关于在pyomo中创建一个带有稀疏索引的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!