【问题标题】:How to include time as a variable in Python Gekko?如何在 Python Gekko 中包含时间作为变量?
【发布时间】:2020-08-12 23:31:27
【问题描述】:

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

我在 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】:

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

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

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

    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

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2022-01-19
      • 2022-01-06
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2021-01-07
      • 1970-01-01
      相关资源
      最近更新 更多