BYU-PRISM / GEKKO

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

Secondary variables fail to update after solution #106

Open reinderien opened 3 years ago

reinderien commented 3 years ago

Given this trivial program:

from gekko import GEKKO

APOPT = 1
m = GEKKO(remote=False)
m.options.solver = APOPT
m.solver_options = ['minlp_as_nlp 0']

x = m.Var(lb=1, ub=10, integer=True)
y = x + 1
m.Maximize(x)
m.solve()

One would expect y.value == 11, but it is instead 0. There's at least two layers of bug, here: the first is that 0 is a poor indicator that there is no value, and None would be less surprising; the second is that there's an explicitly accessible .value member on secondary variables and - after solution - .value on primary variables is correct, and is (inconsistently) unset on secondary variables.

APMonitor commented 3 years ago

Setting y=x+1 does not solve y. There is the Intermediate variable method that fills that purpose.

from gekko import GEKKO

APOPT = 1
m = GEKKO(remote=False)
m.options.solver = APOPT
m.solver_options = ['minlp_as_nlp 0']

x = m.Var(lb=1, ub=10, integer=True)
y = m.Intermediate(x + 1)
m.Maximize(x)
m.solve()

print(y.value)

I'll add this as a feature request. There may be a way to include the assignment in Python as an Intermediate.

reinderien commented 3 years ago

I actually had no idea that Intermediate is a thing, so this is already a huge help. Thanks!

reinderien commented 3 years ago

Otherwise, I think you may have trouble with

There may be a way to include the assignment in Python as an Intermediate

I just don't think that's possible. Does Intermediate rely on evaluation in Gekko, or in the subprocess-ed APMonitor binary? If the former, you could just have arbitrary expressions lazy-evaluated, with an invalidation flag upon solving (or more generally when any dependent GK_Operator changes). If the latter, you'd have to spin up a whole new evaluation mechanism within the Python code.

APMonitor commented 3 years ago

Here is additional information on Intermediate variables in APMonitor. Gekko writes an APMonitor model file in the run folder m.path. Thanks for the ideas. The x+1 results in a Gekko expression, not a new Gekko variable y so I'll need to think about how to return the invalidation flag or some other mechanism to show that it is bad.