Extended Kalman Filter (python)

拓展卡尔曼滤波(python)

 

// 初值\(x_{0}=[120,4,25,0]^{T}\), 量测初值\(\hat{x}_{0}=[125,4.1,26,0.1]^{T}\) // T为采样周期,q为过程噪声方差,r为量测噪声方差
// N为蒙特卡洛模拟次数
// 初始状态协方差矩阵\(P_{0}=0.2 I_{4 \times 4}\)
// 定常速度模型 constant velocity \[ \begin{array}{l} x_{k+1} \triangleq\left[\begin{array}{l} x_{k+1} \\ \dot{x}_{k+1} \\ y_{k+1} \\ \dot{y}_{k+1} \end{array}\right]=F_{k} x_{k}+\Gamma_{k} v_{k} \\ \\ z_{k+1} \triangleq\left[\begin{array}{l} z_{k+1}^{x} \\ z_{k+1}^{y} \end{array}\right]=\left[\begin{array}{l} \sin \left(x_{k+1}\right) \\ \cos \left(y_{k+1}\right) \end{array}\right]+w_{k+1} \end{array} \]

// 其中 \[ \begin{array}{l} F_{k}=\left[\begin{array}{cccc} 1 & T & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & T \\ 0 & 0 & 0 & 1 \end{array}\right] \\ \\ \Gamma_{k}=\left[\begin{array}{cc} T^{2} / 2 & 0 \\ T & 0 \\ 0 & T^{2} / 2 \\ 0 & T \end{array}\right] \\ \\ E\left[v_{k}\right]=\left[\begin{array}{l} 0 \\ 0 \end{array}\right], Q_{k} \triangleq E\left[v_{k} v_{k}^{T}\right]=\left[\begin{array}{ll} q & 0 \\ 0 & q \end{array}\right] \\ \\ E\left[w_{k+1}\right]=\left[\begin{array}{l} 0 \\ 0 \end{array}\right], R_{k+1} \triangleq E\left[w_{k+1} w_{k+1}^{T}\right]=\left[\begin{array}{ll} 1 & 0 \\ 0 & 1 \end{array}\right] \end{array} \]

 

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import numpy as np
import matplotlib.pyplot as plt

T = 0.1
q = 0.2
r = 1
R = np.array([[1, 0],
[0, 1]])
Q = np.array([[q, 0],
[0, q]])
N = 100 # Monte Carlo simulation times

M_measTime = []
M_measPos_x = []
M_measPos_y = []
M_estPos_x = []
M_estPos_y = []
M_reaPos_x = []
M_reaPos_y = []
M_reaVel_x = []
M_reaVel_y = []
M_estVel_x = []
M_estVel_y = []
RMS_p = []
RMS_v = []

def h(x,y):
H = np.array([[np.sin(x)],
[np.cos(y)]])
return H

def hd(x,y):
HD = np.array([[np.cos(x), 0, 0, 0],
[0, 0, -1 * np.sin(y), 0]])
return HD

for i in range(N):
def getMeasurement(updateNumber):
if updateNumber == 1:
getMeasurement.currentPosition_x = 120
getMeasurement.currentVelocity_x = 4
getMeasurement.currentPosition_y = 25
getMeasurement.currentVelocity_y = 0

w = np.random.normal(loc=0,scale=np.sqrt(r),size=1)
v = np.random.normal(loc=0,scale=np.sqrt(q),size=1)

xx = getMeasurement.currentPosition_x + getMeasurement.currentVelocity_x*T + v
yy = getMeasurement.currentPosition_y + getMeasurement.currentVelocity_y*T + v
getMeasurement.currentPosition_x = xx - v
getMeasurement.currentPosition_y = yy - v
getMeasurement.currentVelocity_x = 4 + w
getMeasurement.currentVelocity_y = 0 + w
return [xx, yy, getMeasurement.currentPosition_x, getMeasurement.currentVelocity_x, getMeasurement.currentPosition_y, getMeasurement.currentVelocity_y]

def filter(xx, yy, updateNumber):
# Initialize State
if updateNumber == 1:
filter.X = np.mat([[125],
[4.1],
[26],
[0.1]])
filter.P = np.mat([[0.2, 0, 0, 0],
[0, 0.2, 0, 0],
[0, 0, 0.2, 0],
[0, 0, 0, 0.2]])
filter.F = np.mat([[1, T, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, T],
[0, 0, 0, 1]])

filter.Gamma = np.mat([[T**2/2, 0],
[T, 0],
[0, T**2/2],
[0, T]])
filter.R = R
filter.Q = Q

# print(xx)
# J = np.array([[-0.1289, 0, 0, 0], [0, 0, -0.004, 0]])
# Predict State Forward
# print('fx',filter.X)
# print('p',filter.P)
X_prime = filter.F.dot(filter.X)
# print('xp',X_prime)
# Predict Covariance Forward
P_prime = filter.F.dot(filter.P).dot(filter.F.T) + filter.Gamma.dot(filter.Q).dot(filter.Gamma.T)
# print('pp',P_prime)
# Jacobian
J = [[np.cos(X_prime[0,0]) , 0 ,0,0],
[0, 0, -1 * np.sin(X_prime[2,0]), 0]]
# print('J',J)
# Compute Kalman Gain
S = np.matmul(np.matmul(J ,P_prime), np.transpose(J).tolist()) + filter.R
#S = J.dot(P_prime).dot(J.T) + filter.R
S = S.astype(np.float)
# print('s',S)
K = np.matmul(np.matmul(P_prime,np.transpose(J).tolist()),np.linalg.inv(S))
# K = P_prime.dot(J.T).dot(np.linalg.inv(S))
# print('K',K)
# Estimate State

real = np.array([[np.sin(xx)],
[np.cos(yy)]])
real = np.array(real).flatten()
real = np.array([[real[0]],[real[1]]])
# print('real',real)
D = np.array([[np.sin(X_prime[0])],
[np.cos(X_prime[2])]])

D = np.array(D).flatten()
D = np.array([[D[0]],[D[1]]])

residual = real - D

# print('D',D)
# print('res',residual)
filter.X = X_prime + K.dot(residual)
# Estimate Covariance
filter.P = P_prime - K.dot(J).dot(P_prime)
return [filter.X[0], filter.X[1], filter.X[2], filter.X[3]]

def testFilter():
t = np.linspace(0, 1, num=100)
numOfMeasurements = len(t)

measTime = []
measPos_x = []
measPos_y = []
estPos_x = []
estPos_y = []
reaPos_x = []
reaPos_y = []
reaVel_x = []
reaVel_y = []
estVel_x = []
estVel_y = []
rms_p = []
rms_v = []

for k in range(1,numOfMeasurements):
r = getMeasurement(k)
# Call Filter and return new State
f = filter(r[2], r[3], k)

f = np.array(f).flatten()
f = np.array([f[0],f[1],f[2],f[3]])

# print('f',f)
# Save off that state so that it could be plotted
measTime.append(k)
measPos_x.append(r[0])
measPos_y.append(r[1])
estPos_x.append(f[0])
estPos_y.append(f[2])
reaPos_x.append(r[2])
reaPos_y.append(r[4])
reaVel_x.append(r[3])
reaVel_y.append(r[5])
estVel_x.append(f[1])
estVel_y.append(f[3])
rms_p.append((r[2]-f[0])**2 + (r[4]-f[2])**2)
rms_v.append((r[3]-f[1])**2 + (r[5]-f[3])**2)

return [measTime, measPos_x, measPos_y, estPos_x, estPos_y, reaPos_x, reaPos_y,reaVel_x,reaVel_y,estVel_x,estVel_y,rms_p,rms_v]

t = testFilter()

M_measTime.append(t[0])
M_measPos_x.append(t[1])
M_measPos_y.append(t[2])
M_estPos_x.append(t[3])
M_estPos_y.append(t[4])
M_reaPos_x.append(t[5])
M_reaPos_y.append(t[6])
M_reaVel_x.append(t[7])
M_reaVel_y.append(t[8])
M_estVel_x.append(t[9])
M_estVel_y.append(t[10])
RMS_p.append(t[11])
RMS_v.append(t[12])

##################### plot ######################
###### one simulation results #####
plot1 = plt.figure(1)
plt.plot(t[0], t[1], color='green',label='measurementPos_x')
plt.plot(t[0], t[5], color='red',label='truePos_x')
plt.ylabel('position of x')
plt.xlabel('Time')
plt.legend()
plt.title('Position Measurement On one Measurement Update \n', fontweight="bold")
plt.grid(True)
plt.show()

plot2 = plt.figure(2)
plt.plot(t[0], t[2], color='green',label='measurementPos_y')
plt.plot(t[0], t[6], color='red',label='truePos_y')
plt.ylabel(' position of y')
plt.xlabel('Time')
plt.title('Position Measurement On one Measurement Update \n', fontweight="bold")
plt.grid(True)
plt.legend()
plt.show()

plot3 = plt.figure(3)
plt.plot(t[0], t[3], color='green',label='estimatePos_x')
plt.plot(t[0], t[5], color='red',label='truePos_x')
plt.ylabel('position of x')
plt.xlabel('Time')
plt.title('Position estimate On one Measurement Update \n', fontweight="bold")
plt.grid(True)
plt.legend()
plt.show()

plot4 = plt.figure(4)
plt.plot(t[0], t[4], color='green',label='estimatePos_y')
plt.plot(t[0], t[6], color='red',label='truePos_y')
plt.ylabel('position of y')
plt.xlabel('Time')
plt.title('Position estimate On one Measurement Update \n', fontweight="bold")
plt.grid(True)
plt.legend()
plt.show()

RMS_P = np.mean(RMS_p, axis=0)
print('RMS_P_q0.2',np.mean(RMS_P))
RMS_V = np.mean(RMS_v, axis=0)
print('RMS_V_q0.2',np.mean(RMS_V))
  • 注意 np.array 与 np.mat
  • 注意 .dot 和 * 和 np.matmul区别
  • S = S.astype(np.float)是对S求逆时报错解决方法
  • real = np.array(real).flatten() 是为了去除real中多余的array
  • 一些结果:(T=0.01 Q=0.2) ,有点发散。。。