TexasEngineer
TexasEngineer

Reputation: 734

How to include time as a variable in Python Gekko?

I need to include time in my model for the solution of a complex set of differential equations. Here is a simple problem that demonstrates the issue with constant k=0.1 and initial condition y(0)=10.

differential equation

I tried it in Python Gekko but can't figure out how to include time as a variable. In Scipy ODEINT, the function has time and the state variables. In Gekko, I define m.time as the points where I would like to see the solution but using m.time in the equation has an error.

import numpy as np
from gekko import GEKKO
import matplotlib.pyplot as plt

m = GEKKO()    # create GEKKO model
m.time = np.linspace(0,20) # time points
k = 0.1        # constant
y = m.Var(10)  # create GEKKO variable
m.Equation(y.dt()==-k*m.time*y) # create GEKKO equation

# solve ODE
m.options.IMODE = 4
m.solve()

# plot results
plt.plot(m.time,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()
 @error: Equation Definition
 Equation without an equality (=) or inequality (>,<)
 ((-0.12244897959183675)*(v1))((-0.163265306122449)*(v1))
 STOPPING...
Traceback (most recent call last):
  File "ode_time.py", line 13, in <module>
    m.solve()
  File "C:\Python37\lib\site-packages\gekko\gekko.py", line 2103, in solve
    raise Exception(response)
Exception:  @error: Equation Definition
 Equation without an equality (=) or inequality (>,<)
 ((-0.12244897959183675)*(v1))((-0.163265306122449)*(v1))
 STOPPING...

How can I include time as a variable in Gekko equations?

Upvotes: 2

Views: 754

Answers (1)

John Hedengren
John Hedengren

Reputation: 14346

You can include time in a Gekko model by adding a new variable t and equation d(t)/dt=1.

t = m.Var(0); m.Equation(t.dt()==1)

Here is a solution to the differential equation problem.

Differential Equation Solution

import numpy as np
from gekko import GEKKO
import matplotlib.pyplot as plt

m = GEKKO()    # create GEKKO model
m.time = np.linspace(0,20) # time points
k = 0.1        # constant
y = m.Var(10)  # create GEKKO variable
t = m.Var(0); m.Equation(t.dt()==1)
m.Equation(y.dt()==-k*t*y) # create GEKKO equation

# solve ODE
m.options.IMODE = 4
m.solve()

# plot results
plt.plot(m.time,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()

For another example, see problem #3 for Python Gekko or the same problem #3 with ODEINT.

Upvotes: 1

Related Questions