How to create new a model variable without declaring its name, and then store it in a dictionary

438 views
Skip to first unread message

Amanda Wang

unread,
Mar 28, 2021, 12:29:35 AM3/28/21
to Pyomo Forum
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:

new_x= {}
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!

Michael Bynum

unread,
Mar 29, 2021, 9:59:13 AM3/29/21
to Pyomo Forum
There are several ways to do this. My preference would be 

import pyomo.environ as pe

m = pe.ConcreteModel()
... build model ...
m.x = pe.VarList()
for i in I:
    new_v = m.x.add()

You could also do something similar to what you have above and use getattr to access the new variable systematically. Finally you could create a variable indexed over the Any set (with "dense=False").

Michael
Reply all
Reply to author
Forward
0 new messages