简体   繁体   中英

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 .

微分方程

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?

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.

微分方程解

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM