BYU-PRISM / GEKKO

GEKKO Python for Machine Learning and Dynamic Optimization
https://machinelearning.byu.edu
Other
580 stars 103 forks source link

Access named variables and params #52

Closed ericman314 closed 5 years ago

ericman314 commented 5 years ago

Say I have the following, where I want to reuse a model in multiple places. Other than using the gekko model's built-in _variables attribute, is there a "right" way to access the variable x?

def getModel():
  m = GEKKO()
  m.Var(value=5, name='x')
  return m

m = getModel()
# How to access variable x?

Putting x in the global scope is not what I intend.

abe-mart commented 5 years ago

One way that I have done this before is pack the variables back into the model object.

def getModel(): m = GEKKO() m.x = m.Var(value=5, name='x') return m

m = getModel() print(m.x)

On Wed, Jan 9, 2019 at 2:16 PM Eric Mansfield notifications@github.com wrote:

Say I have the following, where I want to reuse a model in multiple places. Other than using the gekko model's built-in _variables attribute, is there a "right" way to access the variable x?

def getModel(): m = GEKKO() m.Var(value=5, name='x') return m

m = getModel()# How to access variable x?

Putting x in the global scope is not what I intend.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/BYU-PRISM/GEKKO/issues/52, or mute the thread https://github.com/notifications/unsubscribe-auth/ASiToep6mj9BG_Xcjsge085G8vmYyW0Tks5vBlxEgaJpZM4Z4PAb .

ericman314 commented 5 years ago

Nice and clean. Thank you.

Still, I suppose having a method that returns a dictionary of variables, parameters, etc. wouldn't hurt, would it? It's possible you could have a collision with a built-in attribute of the model.

APMonitor commented 5 years ago

I like your idea to create a dictionary of variables such as:

def getModel():
    m = GEKKO()
    vars = {}
    vars['x'] = m.Var()
    vars['y'] = m.Param()
    return vars
print(vars)

There is checking in the GEKKO code to avoid collisions with built-in variable names. This isn't a problem, especially if you don't give your variables or parameters a non-default name. Feel free to open the issue again if you'd like more development work on this.