The gekko built-in max2 and max3 functions are suited to the task of finding a maximum or minimum from a list if two variables are compared with each loop through the list. These functions only allow the comparison of two values because there are additional equations and variables added to the problem for each comparison. The mx is the maximum of the list and mn is the minimum of the list. Each time through the list, the mx and mn values are compared to the next value in the list with the additional equations and variables. Consider a simple problem with a list [0,1,2,3,4,5,6] and intermediate calculation that takes the square of this list. The max3 and min3 functions are used in the loop to compare the next value in the t list.
from gekko import GEKKO
m=GEKKO(remote=False)
n=[0,1,2,3,4,5,6]
t=[m.Intermediate(i**2) for i in n]
mx = t[0] # max
mn = t[0] # min
for i in range(1,len(n)):
mx = m.max3(mx,t[i])
mn = m.min3(mn,t[i])
# initialize with IPOPT
#m.options.SOLVER = 3
#m.solve(disp=False)
# solve with APOPT
m.options.SOLVER = 1
m.solve(disp=False)
print(mx.value[0])
print(mn.value[0])
The solution to this simple problem is 36 for the maximum and 0 for the minimum. The intermediate list t can be replaced by any type of list that includes intermediates, constant, parameters, or variables. For this type of problem, it is sometimes helpful to initialize with the solver IPOPT (nonlinear programming solver) and finish with the APOPT solver (mixed integer nonlinear programming) to obtain an integer solution. Uncomment the presolve with m.options.SOLVER=3 and m.solve(disp=False) to use this initialization.