有没有办法在 Pyomo 中获取包含变量名的列表?

Is there a way to get a list with variable names in Pyomo?

我想将我所有的整数边界变量附加到我定义的 integer_constraints_list 中。有没有办法获得某种列表或数组,其中包含我所有的变量名,以迭代我使用 for 循环编写的代码? 像 variables_list = [inst.x[i], inst.y[i], inst.z[i]].

我知道 pyomo 内核有类似的东西,但我使用 environ 来定义模型

model.I = RangeSet(1,20)
model.x = Var(model.I, domain=NonNegativeIntegers)
model.y = Var(model.I, domain=NonPositiveIntegers)
model.z = Var(model.I, domain=NonPositiveIntegers)

inst = model.create_instance(data)
integer_constraints_list = []

for i in inst.I:
     if "nonnegativeintegers" in str(inst.x[i].domain).lower():
          integer_constraints_list.append(inst.x[i])
          inst.x[i].domain = NonNegativeReals

类似于

variables_list = [inst.x[i], inst.y[i], inst.z[i]]
for v in variables_list:
     for i in inst.I:
          if "nonnegativeintegers" in str(v.domain).lower():
               integer_constraints_list.append(v[i])
               v.domain = NonNegativeReals

你可以这样做:

variables_list = ['inst.x', 'inst.y', 'inst.z']
for v in variables_list:
     for i in inst.I:
          if "nonnegativeintegers" in str(vars()[v][i].domain).lower():
               integer_constraints_list.append(v[i])
               vars()[v][i].domain = NonNegativeReals

好吧,解决方案并不像我想象的那么复杂

variables_list = [inst.x, inst.y, inst.z]
for v in variables_list:
    for i in inst.I:
        if "nonnegativeintegers" in str(v[i].domain).lower():
           integer_constraints_list.append(v[i])
           v[i].domain = NonNegativeReals

我建议进行域相等性比较,而不是对字符串表示进行比较:

integer_vars = [v for v in inst.component_data_objects(Var) if v.domain == NonNegativeIntegers]
integer_constraints_list.extend(integer_vars)
for v in integer_vars:
    v.domain = NonNegativeReals