【问题标题】:GEKKO variable update in real timeGEKKO 变量实时更新
【发布时间】:2022-01-06 21:25:06
【问题描述】:

如果我想在每秒更新的在线模拟中使用 GEKKO,我需要如何设置 m.time 并更新初始条件?我试过了:

m.time = np.linspace(0,1,2)
while simulation_on:
    m.solve()
    x1.value = x1.value.value
    x2.value =  x2.value.value
    x3.value = x3.value.value

但它似乎没有更新值。我正在使用IMODE = 4 这只是一个动态模拟应用程序。目前无法控制。

【问题讨论】:

    标签: python simulation gekko


    【解决方案1】:

    Gekko 在m.options.TIME_SHIFT=1(默认)时自动管理初始条件。下面是一个带有模拟循环和单输入单输出的简单示例。

    import numpy as np
    from gekko import GEKKO
    import matplotlib.pyplot as plt
    
    m = GEKKO()    # create GEKKO model
    n = 10
    m.time = np.linspace(0,n,n+1) # time points
    
    # input step 0 to 0.5 at t=3
    us = np.zeros_like(m.time); us[3:] = 0.5
    u = m.Param(0)
    x = m.Var(0.0)
    m.Equation(2*x.dt()==-x+4*u) 
    m.options.IMODE = 4
    
    xs=[0]
    for i in range(n):
        u.value=us[i] # new input
        m.solve(disp=False)
        xs.append(x.value[1])
        
    # plot results
    plt.plot(m.time,us,'ro',label='u(t)')
    plt.plot(m.time,xs,'bx-',label='x(t)')
    plt.ylabel('values')
    plt.xlabel('time')
    plt.legend(loc='best')
    plt.show()
    

    如果需要逐个周期地改变初始条件,可以调整,例如:

        if i==5:
            xs[i]=5
            x.value = xs[i]
    

    import numpy as np
    from gekko import GEKKO
    import matplotlib.pyplot as plt
    
    m = GEKKO()    # create GEKKO model
    n = 10
    m.time = np.linspace(0,n,n+1) # time points
    
    # input step 0 to 0.5 at t=3
    us = np.zeros_like(m.time); us[3:] = 0.5
    u = m.Param(0)
    x = m.Var(0.0)
    m.Equation(2*x.dt()==-x+4*u) 
    m.options.IMODE = 4
    
    xs=[0]
    for i in range(n):
        u.value=us[i] # new input
        if i==5:
            xs[i]=5
            x.value = xs[i]
        m.solve(disp=False)
        xs.append(x.value[1])
        
    # plot results
    plt.plot(m.time,us,'ro',label='u(t)')
    plt.plot(m.time,xs,'bx-',label='x(t)')
    plt.ylabel('values')
    plt.xlabel('time')
    plt.legend(loc='best')
    plt.show()
    

    Gekko v1.0.1 中存在一个错误,可能会影响这些结果。我建议使用pip install gekko --upgrade 升级到最新版本。

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2021-01-07
      • 2021-12-21
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多