How to write conditions and Tolerance in GEKKO?

Viewed 94

Need help for the following conditions to be implemented in GEKKO python.

  1. For Matlab, i have the following conditions

    if t<15

    x1 = 1e-7;

    else x1 = 0;

    end

For python I have written the code as

m.time = np.linspace(0,60)
t = m.Var(0)
m.Equation(t.dt()==1)
x1 = m.if2(t-15,1e-7,0)

But that didn't work. Basically x1 is my input and I want that x1 to be available for 15min only, after that it is 0. Please let me know the solution to this.

2.effect=min((0.2x17+0.8x19)/APequil, 1) in Matlab

In python I have used the following effect=m.min2(((0.2x17+0.8x19)/APequil),1)

Please check if its okay? As removing min2 is not affecting my solution.

  1. In matlab, have used options=odeset('InitialStep',0.0001,'RelTol',1e-09),

how to use the same in GEKKO python? As I have successful solution in matlab, but the same output is not achieved in Python, i think it is due to this tolerance value or what?

1 Answers

Use a list of values to give different values based on the time or position.

x1 = m.Param([0 if i<15 else 1e-7 for i in range(101)])

Use a slack variable s to clip the value of effect at an upper bound of 1. This is more efficient than using the if2() or if3() function.

effect = m.Var(ub=1)
s = m.Var(lb=0)
m.Minimize(s)
m.Equation(effect==x1*3e7-s)

The tolerance can be set with m.options.RTOL (equation residual tolerance) and m.options.OTOL (objective tolerance). Here is an example:

example problem

import numpy as np
from gekko import GEKKO

m = GEKKO(remote=False)
t  = np.linspace(0,100,101); m.time = t
x1 = m.Param([0 if i<15 else 1e-7 for i in range(101)])
effect = m.Var(ub=1)
s = m.Var(lb=0)
m.Minimize(s)
m.Equation(effect==x1*3e7-s)

m.options.IMODE=6
m.options.RTOL = 1e-6
m.options.OTOL = 1e-6
m.solve()

import matplotlib.pyplot as plt
plt.subplot(2,1,1)
plt.plot(t,x1,'k--',label='x1')
plt.legend()
plt.subplot(2,1,2)
plt.plot(t,effect,'r--',label='Effect')
plt.plot(t,s,'b.-',label='Slack')
plt.legend(); plt.xlabel('Time')
plt.show()

There are additional examples and documentation that can also help.

Related