问题描述
我最近尝试通过状态空间模型控制我的 TCLab Arduino。我参考State Space Models,将一阶线性系统(无时延)转化为状态空间形式,控制效果不错。现在想用一阶加死区时间模型来控制实验室,但不知道如何将FOPDT模型转化为状态空间形式。如何在状态空间模型中添加时间延迟?
代码如下:
import tclab
import numpy as np
import time
import matplotlib.pyplot as plt
from gekko import GEKKO
import json
# Connect to Arduino
# a = tclab.TCLab()
a = tclab.TCLabModel()
# Run time in minutes
run_time = 60.0
# Number of cycles
loops = int(60.0*run_time)
tm = np.zeros(loops)
# Temperature (K)
T1 = np.ones(loops) * a.T1 # temperature (degC)
Tsp1 = np.ones(loops) * 40.0 # set point (degC)
# heater values
Q1s = np.ones(loops) * 0.0
Q1_ss = 0
#########################################################
# Initialize Model
#########################################################
tau = 160.0
kp = 0.6
Am = np.zeros((1,1))
Bm = np.zeros((1,1))
Cm = np.zeros((1,1))
Am[0,0] = - 1/tau
Bm[0,0] = kp/tau
Cm[0,0] = 1
# state space simulation
m = GEKKO(remote=False)
x,y,u = m.state_space(Am,Bm,Cm,D=None)
mv = u[0]
cv = y[0]
mv.VALUE = Q1_ss
mv.STATUS = 1 # use to control temperature
mv.FSTATUS = 0 # no Feedback measurement
mv.LOWER = 0.0
mv.UPPER = 100.0
mv.DMAX = 10.0
mv.COST = 0.0
mv.dcosT = 0.1
cv.VALUE = a.T1
cv.STATUS = 1 # minimize error with setpoint range
cv.FSTATUS = 1 # receive measurement
cv.TR_INIT = 2 # reference trajectory
cv.TAU = 60 # time constant for response
m.time = np.linspace(0,160,81)
m.options.IMODE = 6 # MPC
m.options.CV_TYPE = 1 # Objective type
m.options.NODES = 2 # collocation nodes
m.options.MAX_TIME = 10
##################################################################
# Create plot
plt.figure()
plt.ion()
plt.show()
filter_tc1 = []
def movefilter(predata,new,n):
if len(predata) < n:
predata.append(new)
else:
predata.pop(0)
predata.append(new)
return np.average(predata)
# Main Loop
start_time = time.time()
prev_time = start_time
last_Q1 = Q1_ss
try:
for i in range(1,loops):
# Sleep time
sleep_max = 2.0
print(time.time() - prev_time)
sleep = sleep_max - (time.time() - prev_time)
if sleep>=0.01:
time.sleep(sleep)
else:
time.sleep(0.01)
# Record time and change in time
t = time.time()
dt = t - prev_time
prev_time = t
tm[i] = t - start_time
# Read temperatures in Kelvin
curr_T1 = a.T1
last_T1 = curr_T1
avg_T1 = movefilter(filter_tc1,last_T1,3)
T1[i] = curr_T1
###############################
### MPC CONTROLLER ###
###############################
cv.MEAS = avg_T1
# input setpoint with deadband +/- DT
DT = 0.5
cv.SPHI = Tsp1[i] + DT
cv.SPLO = Tsp1[i] - DT
# solve MPC
m.solve(disp=False)
# test for successful solution
if (m.options.APPSTATUS==1):
# retrieve the first Q value
Q1s[i] = mv.NEWVAL
print('Q1.NEWVAL',mv.NEWVAL)
with open(m.path+'//results.json') as f:
results = json.load(f)
else:
# not successful,set heater to zero
Q1s[i] = last_Q1
print('last_Q1',mv.NEWVAL)
print(m.path)
# Write output (0-100)
a.Q1(Q1s[i])
# Plot
plt.clf()
ax=plt.subplot(2,1,1)
ax.grid()
plt.plot(tm[0:i],T1[0:i],'ro',MarkerSize=3,label=r'$T_1$')
plt.plot(tm[0:i],Tsp1[0:i],'b-',label=r'$T_1 Setpoint$')
cv_name = cv.NAME + '.bcv'
print(cv_name)
plt.plot(tm[i]+m.time,results[cv_name],'k-.',\
label=r'$T_1$ predicted',linewidth=3)
# plt.plot(tm[i]+m.time,results['tc1.tr_hi'],'k--',\
# label=r'$T_1$ trajectory')
# plt.plot(tm[i]+m.time,results['tc1.tr_lo'],'k--')
plt.ylabel('Temperature (degC)')
plt.legend(loc='best')
ax=plt.subplot(2,2)
ax.grid()
plt.plot(tm[0:i],Q1s[0:i],'r-',linewidth=3,label=r'$Q_1$')
plt.plot(tm[i]+m.time,mv.value,\
label=r'$Q_1$ plan',linewidth=3)
# plt.plot(tm[0:i],Q2s[0:i],'b:',label=r'$Q_2$')
plt.ylabel('Heaters')
plt.xlabel('Time (sec)')
plt.legend(loc='best')
plt.draw()
plt.pause(0.05)
# Turn off heaters
a.Q1(0)
a.Q2(0)
print('Shutting down')
a.close()
# Allow user to end loop with Ctrl-C
except KeyboardInterrupt:
# disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Shutting down')
a.close()
# Make sure serial connection still closes when there's an error
except:
# disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Error: Shutting down')
a.close()
解决方法
使用 Gekko 中的 delay
函数添加时间延迟。这是一个 example。要将其添加到状态空间模型,您可以延迟输入 mv
或输出 cv
。这是带有输出延迟的状态空间模型。
# state space simulation
m = GEKKO(remote=False)
x,y,u = m.state_space(Am,Bm,Cm,D=None)
mv = u[0]
cv_in = y[0]
cv = m.CV()
m.delay(cv_in,cv,4) # delay of 4 steps (8 sec)
import tclab
import numpy as np
import time
import matplotlib.pyplot as plt
from gekko import GEKKO
import json
# Connect to Arduino
# a = tclab.TCLab()
a = tclab.TCLabModel()
# Run time in minutes
run_time = 60.0
# Number of cycles
loops = int(60.0*run_time)
tm = np.zeros(loops)
# Temperature (K)
T1 = np.ones(loops) * a.T1 # temperature (degC)
Tsp1 = np.ones(loops) * 40.0 # set point (degC)
# heater values
Q1s = np.ones(loops) * 0.0
Q1_ss = 0
#########################################################
# Initialize Model
#########################################################
tau = 160.0
kp = 0.6
Am = np.zeros((1,1))
Bm = np.zeros((1,1))
Cm = np.zeros((1,1))
Am[0,0] = - 1/tau
Bm[0,0] = kp/tau
Cm[0,0] = 1
# state space simulation
m = GEKKO(remote=False)
x,4) # delay of 4 steps (8 sec)
mv.VALUE = Q1_ss
mv.STATUS = 1 # use to control temperature
mv.FSTATUS = 0 # no feedback measurement
mv.LOWER = 0.0
mv.UPPER = 100.0
mv.DMAX = 10.0
mv.COST = 0.0
mv.DCOST = 0.1
cv.VALUE = a.T1
cv.STATUS = 1 # minimize error with setpoint range
cv.FSTATUS = 1 # receive measurement
cv.TR_INIT = 2 # reference trajectory
cv.TAU = 60 # time constant for response
m.time = np.linspace(0,160,81)
m.options.IMODE = 6 # MPC
m.options.CV_TYPE = 1 # Objective type
m.options.NODES = 2 # Collocation nodes
m.options.MAX_TIME = 10
##################################################################
# Create plot
plt.figure()
plt.ion()
plt.show()
filter_tc1 = []
def movefilter(predata,new,n):
if len(predata) < n:
predata.append(new)
else:
predata.pop(0)
predata.append(new)
return np.average(predata)
# Main Loop
start_time = time.time()
prev_time = start_time
last_Q1 = Q1_ss
try:
for i in range(1,loops):
# Sleep time
sleep_max = 2.0
print(time.time() - prev_time)
sleep = sleep_max - (time.time() - prev_time)
if sleep>=0.01:
time.sleep(sleep)
else:
time.sleep(0.01)
# Record time and change in time
t = time.time()
dt = t - prev_time
prev_time = t
tm[i] = t - start_time
# Read temperatures in Kelvin
curr_T1 = a.T1
last_T1 = curr_T1
avg_T1 = movefilter(filter_tc1,last_T1,3)
T1[i] = curr_T1
###############################
### MPC CONTROLLER ###
###############################
cv.MEAS = avg_T1
# input setpoint with deadband +/- DT
DT = 0.5
cv.SPHI = Tsp1[i] + DT
cv.SPLO = Tsp1[i] - DT
# solve MPC
m.solve(disp=False)
# test for successful solution
if (m.options.APPSTATUS==1):
# retrieve the first Q value
Q1s[i] = mv.NEWVAL
print('Q1.NEWVAL',mv.NEWVAL)
with open(m.path+'//results.json') as f:
results = json.load(f)
else:
# not successful,set heater to zero
Q1s[i] = last_Q1
print('last_Q1',mv.NEWVAL)
print(m.path)
# Write output (0-100)
a.Q1(Q1s[i])
# Plot
plt.clf()
ax=plt.subplot(2,1,1)
ax.grid()
plt.plot(tm[0:i],T1[0:i],'ro',MarkerSize=3,label=r'$T_1$')
plt.plot(tm[0:i],Tsp1[0:i],'b-',label=r'$T_1 Setpoint$')
cv_name = cv.NAME + '.bcv'
print(cv_name)
plt.plot(tm[i]+m.time,results[cv_name],'k-.',\
label=r'$T_1$ predicted',lw=3)
# plt.plot(tm[i]+m.time,results['tc1.tr_hi'],'k--',\
# label=r'$T_1$ trajectory')
# plt.plot(tm[i]+m.time,results['tc1.tr_lo'],'k--')
plt.ylabel('Temperature (degC)')
plt.legend(loc='best')
ax=plt.subplot(2,2)
ax.grid()
plt.plot(tm[0:i],Q1s[0:i],'r-',lw=3,label=r'$Q_1$')
plt.plot(tm[i]+m.time,mv.value,\
label=r'$Q_1$ plan',lw=3)
# plt.plot(tm[0:i],Q2s[0:i],'b:',label=r'$Q_2$')
plt.ylabel('Heaters')
plt.xlabel('Time (sec)')
plt.legend(loc='best')
plt.draw()
plt.pause(0.05)
# Turn off heaters
a.Q1(0)
a.Q2(0)
print('Shutting down')
a.close()
# Allow user to end loop with Ctrl-C
except KeyboardInterrupt:
# Disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Shutting down')
a.close()
# Make sure serial connection still closes when there's an error
except:
# Disconnect from Arduino
a.Q1(0)
a.Q2(0)
print('Error: Shutting down')
a.close()