Kalman Filter (python)

对卡尔曼滤波算法的一些理解和思考,以python形式呈现

 

// 取位置初值为0,速度初值为10m/s
// T为采样周期,q为过程噪声方差,r为量测噪声方差
// N为蒙特卡洛模拟次数
// 初始状态协方差矩阵 \[P=\left[\begin{array}{cc}R & R / T \\ R / T & 2 R / T^{2}\end{array}\right]\]

源代码:

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
229
230
231
232
233
import numpy as np
import matplotlib.pyplot as plt

T = 1
q = 1
r = 5
R = r
Q = q
N = 50 # Monte Carlo simulation times

M_measPos = []
M_estPos = []
M_estVel = []
M_measTime = []
M_estDifPos = []
M_estDifVel = []
x_rme = []
x_rmse = []
x_rrmse = []
v_rme = []
v_rmse = []
v_rrmse = []

for i in range(N):
def getMeasurement(updateNumber):
if updateNumber == 1:
getMeasurement.currentPosition = 0 # initial position
getMeasurement.currentVelocity = 10 # m/s initial velocity

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

x = getMeasurement.currentPosition + getMeasurement.currentVelocity*T + v
getMeasurement.currentPosition = x - v
getMeasurement.currentVelocity = 10 + w
return [x, getMeasurement.currentPosition, getMeasurement.currentVelocity]

def filter(x, updateNumber):
# Initialize State
if updateNumber == 1:
filter.X = np.array([[0],
[10]])
filter.P = np.array([[R, R/T],
[R/T, 2*R/(T**2)]])
filter.F = np.array([[1, T],
[0, 1]])
filter.H = np.array([[1, 0]])
filter.HT = np.array([[1],
[0]])
filter.Gamma = np.array([[T**2/2],
[T]])
filter.R = R
filter.Q = Q

# Predict State Forward
X_prime = filter.F.dot(filter.X)
# Predict Covariance Forward
P_prime = filter.F.dot(filter.P).dot(filter.F.T) + filter.Gamma.dot(filter.Q).dot(filter.Gamma.T)
# Compute Kalman Gain
S = filter.H.dot(P_prime).dot(filter.HT) + filter.R
K = P_prime.dot(filter.HT)*(1/S)
# Estimate State
residual = x - filter.H.dot(X_prime)
filter.X = X_prime + K*residual
# Estimate Covariance
filter.P = P_prime - K.dot(filter.H).dot(P_prime)
return [filter.X[0], filter.X[1], filter.P]

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

measTime = []
measPos = []
measDifPos = []
estDifPos = []
estDifVel = []
estPos = []
estVel = []
x_rme = []
x_rmse = []
x_rrmse = []
v_rme = []
v_rmse = []
v_rrmse = []

for k in range(1,numOfMeasurements):
x = getMeasurement(k)
# Call Filter and return new State
f = filter(x[0], k)
# Save off that state so that it could be plotted
measTime.append(k)
measPos.append(x[0])
measDifPos.append(x[0]-x[1])
estDifPos.append(f[0]-x[1])
x_rme.append(np.abs((f[0]-x[1])/x[1]))
x_rmse.append((f[0]-x[1])**2)
x_rrmse.append(((f[0]-x[1])/x[1])**2)
estDifVel.append(f[1]-x[2])
v_rme.append(np.abs((f[1]-x[2])/x[2]))
v_rmse.append((f[1]-x[2])**2)
v_rrmse.append(((f[1]-x[2])/x[2])**2)
estPos.append(f[0])
estVel.append(f[1])
posVar = f[2]

return [measTime, measPos, estPos, estVel, estDifPos, estDifVel,
x_rme, v_rme, x_rmse, v_rmse, x_rrmse, v_rrmse]

t = testFilter()

M_measTime.append(t[0])
M_measPos.append(t[1])
M_estPos.append(t[2])
M_estVel.append(t[3])
M_estDifPos.append(np.abs(t[4]))
M_estDifVel.append(np.abs(t[5]))
x_rme.append(t[6])
v_rme.append(t[7])
x_rmse.append(t[8])
v_rmse.append(t[9])
x_rrmse.append(t[10])
v_rrmse.append(t[11])

x_ME = np.mean(M_estDifPos, axis=0) # mean error of position
print(np.mean(x_ME))
x_RME = np.mean(x_rme, axis=0) # relative mean error of position
print(np.mean(x_RME))
x_RMSE = np.sqrt(np.mean(x_rmse, axis=0)) # root mean square error of position
print(np.mean(x_RMSE))
x_RRMSE = np.sqrt(np.mean(x_rrmse, axis=0)) # relative root mean square error of position
print(np.mean(x_RRMSE))

v_ME = np.mean(M_estDifVel, axis=0) # mean error of velocity
print(np.mean(v_ME))
v_RME = np.mean(v_rme, axis=0) # relative mean error of velocity
print(np.mean(v_RME))
v_RMSE = np.sqrt(np.mean(v_rmse, axis=0)) # root mean square error of velocity
print(np.mean(v_RMSE))
v_RRMSE = np.sqrt(np.mean(v_rrmse, axis=0)) # relative root mean square error of velocity
print(np.mean(v_RRMSE))

# ##################### plot ######################
# ###### one simulation results #####
# plot1 = plt.figure(1)
# plt.plot(t[0], t[2])
# plt.ylabel('Position')
# plt.xlabel('Time')
# plt.title('Position Estimate On one Measurement Update \n', fontweight="bold")
# plt.legend(['Estimate Position'])
# plt.grid(True)

# plot2 = plt.figure(2)
# plt.plot(t[0], t[3])
# plt.ylabel('Velocity (meters/seconds)')
# plt.xlabel('Update Number')
# plt.title('Velocity Estimate On one Measurement Update \n', fontweight="bold")
# plt.legend(['Estimate Velocity'])
# plt.grid(True)

# ###### error analysis with Monte Carlo simulation #####
# plot3 = plt.figure(3)
# plt.plot(t[0], x_ME)
# plt.title('Position Mean Errors \n', fontweight="bold")
# plt.ylabel('ME (meters)')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

# plot4 = plt.figure(4)
# plt.plot(t[0], x_RME)
# plt.title('Position Relative Mean Errors \n', fontweight="bold")
# plt.ylabel('RME')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

# plot5 = plt.figure(5)
# plt.plot(t[0], x_RMSE)
# plt.title('Position Root Mean Square Errors \n', fontweight="bold")
# plt.ylabel('RMSE')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

# plot6 = plt.figure(6)
# plt.plot(t[0], x_RRMSE)
# plt.title('Position Relative Root Mean Square Errors \n', fontweight="bold")
# plt.ylabel('RRMSE')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()


# plot7 = plt.figure(7)
# plt.plot(t[0], v_ME)
# plt.title('Velocity Mean Errors \n', fontweight="bold")
# plt.ylabel('ME (meters/s)')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

# plot8 = plt.figure(8)
# plt.plot(t[0], v_RME)
# plt.title('Velocity Relative Mean Errors \n', fontweight="bold")
# plt.ylabel('RME')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

# plot9 = plt.figure(9)
# plt.plot(t[0], v_RMSE)
# plt.title('Velocity Root Mean Square Errors \n', fontweight="bold")
# plt.ylabel('RMSE')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

# plot10 = plt.figure(10)
# plt.plot(t[0], v_RRMSE)
# plt.title('Velocity Relative Root Mean Square Errors \n', fontweight="bold")
# plt.ylabel('RRMSE')
# plt.xlabel('Update Number')
# plt.grid(True)
# plt.xlim([0, 100])
# plt.show()

#代码部分修改自网络#