pythoninstance-variablespyomoenviron

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


I wanna append all of my integer-bounded variables into the integer_constraints_list that i've defined. Is there a way to get some sort of list or array with all of my variable names to iterate over the code i made using a for loop? something like variables_list = [inst.x[i], inst.y[i], inst.z[i]].

I know there is something of the sort for pyomo kernel, but i used environ to define the model

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

to something like

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

Solution

  • I would suggest doing a domain equality comparison rather than a comparison on the string representation:

    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