GEKKO变量实时更新

GEKKO variable update in real time

如果我想在每秒更新的在线模拟中使用 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 这只是一个动态模拟应用程序。暂时无法控制。

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 升级到最新版本。