如何将时间作为变量包含在Python Gekko中?

问题描述 投票:1回答:1

我需要在模型中包括时间以解决一组复杂的微分方程。这是一个简单的问题,演示了常数k=0.1和初始条件y(0)=10的问题。

differential equation

我在Python Gekko中进行了尝试,但无法弄清楚如何将时间作为变量包含在内。在Scipy ODEINT中,该函数具有时间和状态变量。在Gekko中,我将m.time定义为希望查看解决方案的点,但是在方程式中使用m.time会出错。

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...

如何将时间作为变量包含在Gekko方程中?

python differential-equations odeint gekko
1个回答
0
投票

您可以通过添加新变量t和方程d(t)/dt=1在Gekko模型中包括时间。

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

这里是微分方程问题的解决方案。

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()

例如,请参见problem #3 for Python Gekko或相同的problem #3 with ODEINT

© www.soinside.com 2019 - 2024. All rights reserved.