1

I want to create a pyomo model with 1000 basic pyomo variables. I know it is a bad idea to do this like the following script. And it is also not working. I hope you understand the idea and be able to help me.

import pyomo.core as pyomo

def create_model_a():
    m = pyomo.ConcreteModel()

    for i in range(1000):
        m.var_i = pyomo.Var(within=pyomo.NonNegativeReals)

    return m

so basically instead of writing m.var_0 = ... to m.var_999 = ..., I used a for loop and of course in this way it is not working but the idea is creating 1000 variables without hard-coding m.var_0, m.var_1, m.var_2, and so on till m.var_999. How can I do it?

I want to create this not to model anything but I wanna use memory profile on this function to understand how much memory is needed for a pyomo model with 1000 variables.

Ps: I tried following and it is not working (cannot see any declarations when I cast m.pprint()):

def create_model_a():
    m = pyomo.ConcreteModel()
    m.var = {}
    for i in range(1000):
        m.var[i] = pyomo.Var(within=pyomo.NonNegativeReals)

    return m

PS2: checked also How to increment variable names/Is this a bad idea and How do I create a variable number of variables? ... sadly no help

oakca
  • 1,408
  • 1
  • 18
  • 40
  • Can't you use a dict? (I just noticed it's in your answer actually, not sure why it's not working). Something like this should probably work though: `setattr(m, 'var_'+str(i), pyomo.Var(within=pyomo.NonNegativeReals))` – Peter Mar 27 '19 at 15:59

1 Answers1

1

If you really want to understand the memory implications of having many Pyomo variables you should compare the case where you have many singleton variables with the case where you have one large indexed variable. Examples of both are below:

# Make a large indexed variable
m = ConcreteModel()
m.s = RangeSet(1000)
m.v = Var(m.s, within=NonNegativeReals)

# Make many singleton variables
m = ConcreteModel()
for i in range(1000):
    name = 'var_' + str(i)
    m.add_component(name, Var(within=NonNegativeReals))
Bethany Nicholson
  • 2,723
  • 1
  • 11
  • 18
  • this was definitly what I was looking for ty. Btw how do you measure memory of the first `m` and the second `m` with a package or something else? + I was also comparing it :) just had a problem where I did not want to hard code these 1000 variables. but ty!! – oakca Mar 27 '19 at 16:06
  • Check out these other questions on determining the size of Python objects: https://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python, https://stackoverflow.com/questions/33978/find-out-how-much-memory-is-being-used-by-an-object-in-python – Bethany Nicholson Mar 27 '19 at 16:59