使用GEKKO求解带x(0)+x(2)=0约束的最优控制问题求助
Gekko最优控制问题修复方案
错误原因
你现有代码中对x1的边界约束写法错误:你定义的infin参数在t=0和t=2时刻取值均为1,约束m.Equation(infin*x1==0)相当于强制要求x1(0)=0且x1(2)=0,和你需要的x1(0)+x1(2)=0约束完全不符,这是求解结果错误的核心原因。
修正方法
你不需要额外定义infin参数,直接调用x1的初始位和结合final参数的终值位构建约束即可,修正后的约束为:
m.Equation(x1[0] + final * x1 == 0)
如果需要更直观的写法,也可以直接用索引取终值:
m.Equation(x1[0] + x1[-1] == 0)
完整修正后代码
import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO m = GEKKO(remote=False) # initialize gekko nt = 101 m.time = np.linspace(0,2,nt) # Variables x1 = m.Var(fixed_initial=False) x2 = m.Var(fixed_initial=False) x3 = m.Var(value=0) u = m.MV(fixed_initial=False,lb=-2,ub=2) u.STATUS = 1 p = np.zeros(nt) # mark final time point p[-1] = 1.0 final = m.Param(value=p) # Equations m.Equation(x1.dt()==x2) m.Equation(x2.dt()==u) m.Equation(x3.dt()==x1) # 修正后的约束 m.Equation(x1[0] + final*x1 == 0) m.Equation(final*x2 == 0) m.Obj(x3*final) # Objective function m.options.IMODE = 6 # optimal control mode m.solve(disp=False) # solve plt.figure(1) # plot results plt.plot(m.time,x1.value,'k-',label=r'$x_1$') plt.plot(m.time,x2.value,'b-',label=r'$x_2$') plt.plot(m.time,x3.value,'g-',label=r'$x_3$') plt.plot(m.time,u.value,'r--',label=r'$u$') plt.legend(loc='best') plt.xlabel('Time') plt.ylabel('Value') plt.show() plt.figure(2) # plot results plt.plot(m.time,x1.value,'k-',label=r'$x_1$') plt.plot(m.time,(m.time-2)**2-2,'g--',label=r'$\hat x_1$') plt.legend(loc='best') plt.xlabel('Time') plt.ylabel('Value') plt.show()
运行效果
修正后求解得到的x1曲线会与你给出的解析解x₁(t) = (t-2)² - 2完全重合,约束满足要求。
内容的提问来源于stack exchange,提问作者MRon
相关产品推荐
相关产品推荐

