If I initialize a boolean variable as 0 I get an incorrect solution (0). If I initialize it as 1 I get the correct solution (1).
# Squaring doesn't work
#######################################################
m = GEKKO(remote=False)
b = m.Var(lb=0,ub=1,integer=True, value=0)
m.Maximize(b**2)
m.options.SOLVER = 1
m.solve(debug=0, disp=True)
Returns:
Successful solution
Objective: 0.
with b: [0]
This is a follow up to a previous question ( Gekko returning incorrect successful solution ) that concerns a model involving matrix multiplication of two gekko arrays with gekko integer variables. I believe I've traced that issue to this problem.
Try this:
from gekko import GEKKO
m = GEKKO()
b = m.Var(value=0, integer=True)
m.Equation(b>=0)
m.Equation(b<=1)
m.Maximize(b**2)
m.options.SOLVER = 1
m.solve(disp=False)
print(b.value)
Output:
[1.0]
See a demo in this colab .
In the gekko examples I saw that Obj()
(which minimizes) is used along with Equation()
, so I thought, well maybe the lower and upper bounds of the variable could be expressed as equations instead. Apparently, it works that way.
The APOPT
solver is a local minimizer that assumes there is only one local minimum. It is also not checking the second derivative to differentiate between a local minimum and local maximum at x=0
. Hernán Alarcón gave a potential solution where inequality constraints are also solved. This causes the solver to not just accept the initial guess as a solution but to start a search and realize that there is a better solution. There are at least two other methods to find the correct solution.
Initialize with x>=1e-3
Instead of initializing at x=0
, try initializing x
at any value that does not meet the KKT conditions .
from gekko import GEKKO
m = GEKKO(remote=False)
b = m.Var(lb=0,ub=1,integer=True, value=1e-3)
m.Maximize(b**2)
m.options.SOLVER=1
m.solve(disp=False)
print(-m.options.OBJFCNVAL)
Switch Solvers
This is an integer optimization problem but a Nonlinear Programming (NLP) solver such as IPOPT
can also solve the problem with value=0
.
from gekko import GEKKO
m = GEKKO(remote=False)
b = m.Var(lb=0,ub=1,integer=True, value=0)
m.Maximize(b**2)
m.options.SOLVER=3
m.solve(disp=False)
print(-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.