trimat
trimat

Reputation: 101

Set negative value to zero in equation in Gekko?

How do I set all the negative value of a variable to zero in an equation. I've tried using m.max2(0,W) so when W is negative I get zero but when it's positive I get the value but since W is defined as W.dt()==s*p the value seems to be trailing I cant' set the lower bound to zero because I need the negative value elsewhere.

Upvotes: 2

Views: 203

Answers (1)

John Hedengren
John Hedengren

Reputation: 14346

The max2 function is a Mathematical Program with Complementarity Constraints (MPCC) and sometimes has a hard time converging when at W=0 because it is a saddle point for optimization. Another option is the max3 function but this requires a mixed integer solver that can require more time to compute a solution. A third option is to use a function such as w * (0.5*tanh(b*w)+0.5) to get a continuously differentiable approximation to the max function. You can set the b to be a higher value but then it makes the problem harder to solve.

tanh function

Another option is to successively solve the problem with higher values of b, like a barrier function in the interior point method.

Here is an example script that has all three functions:

import numpy as np
from gekko import GEKKO
m = GEKKO()
w = m.Param(np.linspace(-10,10,101))
x = m.Intermediate(w * 0.5*(m.tanh(10*w)+1))
y = m.max2(w,0)
z = m.max3(w,0)

m.options.IMODE=2
m.solve()

import matplotlib.pyplot as plt
plt.plot(w,x,'ko',label='x=0.5 w (tanh(10w)+1)')
plt.plot(w,y,'b-',label='y=min2(w,0)')
plt.plot(w,z,'r--',label='z=min3(w,0)')
plt.legend()
plt.show()

max functions

Upvotes: 2

Related Questions