BYU-PRISM / GEKKO

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

Maximum operator #114

Closed tdincer closed 3 years ago

tdincer commented 3 years ago

Great library! Thank you for your amazing work and making GEKKO public.

I have a question! My cost function involves a maximum operator, which returns the maximum of decision variables in addition to another term. Is there an easy way in GEKKO to write this maximum operator?

My problem can be described as follows:

X = x1, x2, x3, ... , xN - (decision variables) B = b1, b2, b3, ... , bN - (a constant vector)

Cost(X) = Some stuff + max(X + B)

APMonitor commented 3 years ago

Sure, use the m.max3() or m.max2() functions. There is more information in the documentation: https://gekko.readthedocs.io/en/latest/model_methods.html?highlight=max3#logical-functions

tdincer commented 3 years ago

I am aware of the max2 and max3 functions. These functions compare only two inputs. In my case, X+B is an N dimensional array. Is the only solution to compare each element of X+B with another one by one?

APMonitor commented 3 years ago

Try list comprehensions and loops:

X = [x1, x2, x3, xN] #(decision variables)
B = [b1, b2, b3, bN] #(a constant vector)
n = len(B)
Y = [X[i]+B[i] for i in range(n)]
mx = 0
for i in range(n):
   mx = m.max3(mx,Y[i])
Cost = Some stuff + mx
tdincer commented 3 years ago

Thank you so much! This is very useful. I think a model building function that would do this operation would be a nice addition to the GEKKO library.

APMonitor commented 3 years ago

I agree. The np.vectorize() function may help.