问题描述
解决了pyomo模型后,我遍历了变量以对数据做一些处理。现在,我尝试根据pyomo集的变量索引制作代码。我正在寻找一种执行以下操作的方法:
model = ConcreteModel()
model.I = Set()
model.p = Var(model.I)
#objective,etc.
...
# solve model
...
for v in instance.component_objects(pyo.Var,active=True):
# Now the next line is what I try to achieve:
used_sets = v.get_sets()
if model.I in used_sets:
# Do stuff
有没有简单的方法可以做到这一点?感谢您的帮助!
解决方法
下面的一些变体可能会起作用。您可以向Var
索取索引集的名称。请注意,二维索引内部构造为虚拟集。不知道是否有一种方法可以将其解压缩到本机组件。 (请参见下面的m.display()
结果。)
我会说你的构造看起来很奇怪。如果您要创建一个具体的模型,您已经知道了变量...因此对其进行测试以查看它们的索引似乎有些循环。也许有一个更简单的选择。
# accessing indexing sets...
from pyomo.environ import *
m = ConcreteModel()
m.I = Set(initialize=[1,2,3])
m.J = Set(initialize=list('abc'))
m.X = Var(m.I)
m.Y = Var(m.J)
m.Z = Var(m.J,m.I)
for v in m.component_objects(Var):
my_index_name = v.index_set().getname()
if my_index_name == 'I':
print(f'variable {v.getname()} is indexed by I')
m.display()
输出:
variable X is indexed by I
Model unknown
Variables:
X : Size=3,Index=I
Key : Lower : Value : Upper : Fixed : Stale : Domain
1 : None : None : None : False : True : Reals
2 : None : None : None : False : True : Reals
3 : None : None : None : False : True : Reals
Y : Size=3,Index=J
Key : Lower : Value : Upper : Fixed : Stale : Domain
a : None : None : None : False : True : Reals
b : None : None : None : False : True : Reals
c : None : None : None : False : True : Reals
Z : Size=9,Index=Z_index
Key : Lower : Value : Upper : Fixed : Stale : Domain
('a',1) : None : None : None : False : True : Reals
('a',2) : None : None : None : False : True : Reals
('a',3) : None : None : None : False : True : Reals
('b',1) : None : None : None : False : True : Reals
('b',2) : None : None : None : False : True : Reals
('b',3) : None : None : None : False : True : Reals
('c',1) : None : None : None : False : True : Reals
('c',2) : None : None : None : False : True : Reals
('c',3) : None : None : None : False : True : Reals
Objectives:
None
Constraints:
None
,
我今天需要做类似的事情。我得到了一些工作,但是这取决于一个“私有”属性,这当然不理想。
from pyomo.environ import *
m = ConcreteModel()
m.I = Set(initialize=[1,m.I)
for v in m.component_objects(Var):
if v.index_set()._implicit_subsets is None:
index_set = v.index_set()
index_set_name = index_set.name
print('{} is indexed in {}'.format(v.name,index_set_name))
print('{} indexed in I? {}'.format(v.name,index_set is m.I))
else:
index_sets = v.index_set()._implicit_subsets
index_sets_names = [index_set.name for index_set in index_sets]
print('{} is multi-indexed in {}'.format(v.name,','.join(index_sets_names)))
print('{} indexed in I? {}'.format(v.name,m.I in index_sets))
输出:
X is indexed in I X indexed in I? True Y is indexed in J Y indexed in I? False Z is multi-indexed in J,I Z indexed in I? True