'Pyomo: How to create new a model variable without declaring its name, and then store it in a dictionary?
I was wondering if there is a way to create a variable that attaches to the model without specifying its name. Or, how do I dynamically create variables with different names in pyomo?
Background: I currently have a concrete model for a master problem and another concrete model for a subproblem. My goal is to solve a two stage optimization problem using a column and constraint generation algorithm under this master and subproblem framework.
I am trying to constrict a while loop to add new variables and constraints to the master problem. Specifically, I am trying to create a new variable for each iteration of a while loop. Then I'd like to add to the master problem some new constraints/cuts that involve the new variable in each iteration.
To do this, I was trying to construct a dictionary using a for loop. In the dictionary, each key corresponds to a newly created variable. I wrote something like this:
for i in I:
xname= 'x' + str(i)
new_x[xname] = model.add_component(xname, pyo.Var())
where I is the set of iteration counts used to create new variables and assign them to a dictionary key.
However, this doesn't work because model.add_component(xname, pyo.Var()) cannot be assigned to a key since it is a procedure that adds the new variable directly to the model. However, I can't use the standard syntax model.x = pyo.Var() to create the new variables either because it means I have to do it manually, defeating the purpose of a while loop.
I was wondering if there is a way to create a variable that attaches to the model without specifying its name. Or, how do I dynamically create different variables in pyomo?
Thank you!
Solution 1:[1]
Some first options:
You could use
setattr(model, xnnam, pyo.Var)in your while loop instead;You could create a set using 'I' elements, then the variable indexed over I and solve the model for each 'i' only in your while loop.
Hope these make sense.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EJay |
