简体   繁体   中英

Change objective in GEKKO optimisation suite python

I am using GEKKO as a MINP-solver. To establish more or less lower and upper bounds, I would like to minimise the sum of variables once, and then maximise it. GEKKO adds up the objectives on the second optimisation, however. How can I delete the old objective and add a new one? And how can I reset the variables to their default values after the first optimisation?

Thank you for any help

solver = GEKKO()
solver.Minimize(sum(x))
solver.solve(disp=False)
print(x)
solver.Maximize(sum(x))
solver.solve(disp=False)
print(x)

Thanks for proposing the solution to your own question. You can create an answer to your own question and mark it as the accepted answer. The comments section is also a good place to put the solution but then StackOverflow thinks the questions is still unanswered.

Approach 1

Here are two ways to switch from minimize to maximimize . If it is just Minimize(sum(x)) to Maximize(sum(x)) then just included an extra Maximize(sum(x)) to cancel out the prior Minimize(sum(x)) . Here is a simple script that shows this first approach:

from gekko import GEKKO
m = GEKKO(remote=False)
x = m.Array(m.Var,3,lb=0,ub=1)
m.Minimize(m.sum(x))
m.solve(disp=False)
print('-'*20)
print('x: ', x)
print('obj: ', m.options.OBJFCNVAL)

m.Maximize(2*m.sum(x))
m.solve(disp=False)
print('-'*20)
print('x: ', x)
print('obj: ', m.options.OBJFCNVAL)

Approach 2

A second approach (as you already found) is to clear the _objectives list with m._objectives.clear() . Here is a sample script with that second approach:

from gekko import GEKKO
m = GEKKO(remote=False)
x = m.Array(m.Var,3,lb=0,ub=1)
m.Minimize(m.sum(x))
m.solve(disp=False)
print('-'*20)
print('x: ', x)
print('obj: ', m.options.OBJFCNVAL)

m._objectives.clear()
m.Maximize(m.sum(x))
m.solve(disp=False)
print('-'*20)
print('x: ', x)
print('obj: ', m.options.OBJFCNVAL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM