Skip to content

Commit ad4148b

Browse files
authored
Merge pull request AtsushiSakai#205 from rsasaki0109/add_localization_with_ensemble_kalman_filter
add localization with ensemble kalman filter
2 parents 0fabea1 + 2fb7c72 commit ad4148b

File tree

1 file changed

+232
-0
lines changed

1 file changed

+232
-0
lines changed
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
"""
2+
3+
Ensemble Kalman Filter(EnKF) localization sample
4+
5+
author: Ryohei Sasaki(rsasaki0109)
6+
7+
Ref:
8+
- [Ensemble Kalman filtering](https://rmets.onlinelibrary.wiley.com/doi/10.1256/qj.05.135)
9+
10+
"""
11+
12+
import numpy as np
13+
import math
14+
import matplotlib.pyplot as plt
15+
16+
# Simulation parameter
17+
Qsim = np.diag([0.2, np.deg2rad(1.0)])**2
18+
Rsim = np.diag([1.0, np.deg2rad(30.0)])**2
19+
20+
DT = 0.1 # time tick [s]
21+
SIM_TIME = 50.0 # simulation time [s]
22+
MAX_RANGE = 20.0 # maximum observation range
23+
24+
# Ensemble Kalman filter parameter
25+
NP = 20 # Number of Particle
26+
27+
show_animation = True
28+
29+
30+
def calc_input():
31+
v = 1.0 # [m/s]
32+
yawrate = 0.1 # [rad/s]
33+
u = np.array([[v, yawrate]]).T
34+
return u
35+
36+
37+
38+
def observation(xTrue, xd, u, RFID):
39+
40+
xTrue = motion_model(xTrue, u)
41+
42+
z = np.zeros((0, 4))
43+
44+
for i in range(len(RFID[:, 0])):
45+
46+
dx = RFID[i, 0] - xTrue[0, 0]
47+
dy = RFID[i, 1] - xTrue[1, 0]
48+
d = math.sqrt(dx**2 + dy**2)
49+
angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0])
50+
if d <= MAX_RANGE:
51+
dn = d + np.random.randn() * Qsim[0, 0] # add noise
52+
anglen = angle + np.random.randn() * Qsim[1, 1] # add noise
53+
zi = np.array([dn, anglen,RFID[i, 0], RFID[i, 1]])
54+
z = np.vstack((z, zi))
55+
56+
# add noise to input
57+
ud = np.array([[
58+
u[0, 0] + np.random.randn() * Rsim[0, 0],
59+
u[1, 0] + np.random.randn() * Rsim[1, 1]]]).T
60+
61+
xd = motion_model(xd, ud)
62+
return xTrue, z, xd, ud
63+
64+
65+
def motion_model(x, u):
66+
F = np.array([[1.0, 0, 0, 0],
67+
[0, 1.0, 0, 0],
68+
[0, 0, 1.0, 0],
69+
[0, 0, 0, 0]])
70+
71+
B = np.array([[DT * math.cos(x[2, 0]), 0],
72+
[DT * math.sin(x[2, 0]), 0],
73+
[0.0, DT],
74+
[1.0, 0.0]])
75+
x = F.dot(x) + B.dot(u)
76+
77+
return x
78+
79+
80+
def calc_LM_Pos(x, landmarks):
81+
landmarks_pos=np.zeros((2*landmarks.shape[0],1))
82+
for (i,lm) in enumerate(landmarks):
83+
landmarks_pos[2*i] = x[0, 0] + lm[0] * math.cos(x[2, 0] + lm[1]) + np.random.randn() * Qsim[0, 0]/np.sqrt(2)
84+
landmarks_pos[2*i+1] = x[1, 0] + lm[0] * math.sin(x[2, 0] + lm[1]) + np.random.randn() * Qsim[0, 0]/np.sqrt(2)
85+
return landmarks_pos
86+
87+
def calc_covariance(xEst, px):
88+
cov = np.zeros((3, 3))
89+
90+
for i in range(px.shape[1]):
91+
dx = (px[:, i] - xEst)[0:3]
92+
cov += dx.dot(dx.T)
93+
94+
return cov
95+
96+
97+
def enkf_localization(px, xEst, PEst, z, u):
98+
"""
99+
Localization with Ensemble Kalman filter
100+
"""
101+
pz = np.zeros((z.shape[0]*2, NP)) # Particle store of z
102+
for ip in range(NP):
103+
x = np.array([px[:, ip]]).T
104+
105+
# Predict with random input sampling
106+
ud1 = u[0, 0] + np.random.randn() * Rsim[0, 0]
107+
ud2 = u[1, 0] + np.random.randn() * Rsim[1, 1]
108+
ud = np.array([[ud1, ud2]]).T
109+
x = motion_model(x, ud)
110+
px[:, ip] = x[:, 0]
111+
z_pos=calc_LM_Pos(x, z)
112+
pz[:, ip] = z_pos[:, 0]
113+
114+
x_ave=np.mean(px, axis=1)
115+
x_dif=px - np.tile(x_ave,(NP,1)).T
116+
117+
z_ave=np.mean(pz, axis=1)
118+
z_dif=pz - np.tile(z_ave,(NP,1)).T
119+
120+
U = 1/(NP-1)* x_dif @ z_dif.T
121+
V = 1/(NP-1)* z_dif @ z_dif.T
122+
123+
K = U @ np.linalg.inv(V) # Kalman Gain
124+
125+
z_lm_pos = z[:,[2,3]].reshape(-1,)
126+
127+
px_hat=px + K @ (np.tile(z_lm_pos,(NP,1)).T- pz)
128+
129+
xEst=np.average(px_hat, axis=1).reshape(4,1)
130+
PEst=calc_covariance(xEst, px_hat)
131+
132+
return xEst, PEst, px_hat
133+
134+
135+
def plot_covariance_ellipse(xEst, PEst): # pragma: no cover
136+
Pxy = PEst[0:2, 0:2]
137+
eigval, eigvec = np.linalg.eig(Pxy)
138+
139+
if eigval[0] >= eigval[1]:
140+
bigind = 0
141+
smallind = 1
142+
else:
143+
bigind = 1
144+
smallind = 0
145+
146+
t = np.arange(0, 2 * math.pi + 0.1, 0.1)
147+
148+
# eigval[bigind] or eiqval[smallind] were occassionally negative numbers extremely
149+
# close to 0 (~10^-20), catch these cases and set the respective variable to 0
150+
try:
151+
a = math.sqrt(eigval[bigind])
152+
except ValueError:
153+
a = 0
154+
155+
try:
156+
b = math.sqrt(eigval[smallind])
157+
except ValueError:
158+
b = 0
159+
160+
x = [a * math.cos(it) for it in t]
161+
y = [b * math.sin(it) for it in t]
162+
angle = math.atan2(eigvec[bigind, 1], eigvec[bigind, 0])
163+
R = np.array([[math.cos(angle), math.sin(angle)],
164+
[-math.sin(angle), math.cos(angle)]])
165+
fx = R.dot(np.array([[x, y]]))
166+
px = np.array(fx[0, :] + xEst[0, 0]).flatten()
167+
py = np.array(fx[1, :] + xEst[1, 0]).flatten()
168+
plt.plot(px, py, "--r")
169+
170+
171+
def pi_2_pi(angle):
172+
return (angle + math.pi) % (2 * math.pi) - math.pi
173+
174+
def main():
175+
print(__file__ + " start!!")
176+
177+
time = 0.0
178+
179+
# RFID positions [x, y]
180+
RFID = np.array([[10.0, 0.0],
181+
[10.0, 10.0],
182+
[0.0, 15.0],
183+
[-5.0, 20.0]])
184+
185+
# State Vector [x y yaw v]'
186+
xEst = np.zeros((4, 1))
187+
xTrue = np.zeros((4, 1))
188+
PEst = np.eye(4)
189+
190+
px = np.zeros((4, NP)) # Particle store of x
191+
192+
xDR = np.zeros((4, 1)) # Dead reckoning
193+
194+
# history
195+
hxEst = xEst
196+
hxTrue = xTrue
197+
hxDR = xTrue
198+
199+
while SIM_TIME >= time:
200+
time += DT
201+
u = calc_input()
202+
203+
xTrue, z, xDR, ud = observation(xTrue, xDR, u, RFID)
204+
205+
xEst, PEst, px = enkf_localization(px, xEst, PEst, z, ud)
206+
207+
# store data history
208+
hxEst = np.hstack((hxEst, xEst))
209+
hxDR = np.hstack((hxDR, xDR))
210+
hxTrue = np.hstack((hxTrue, xTrue))
211+
212+
if show_animation:
213+
plt.cla()
214+
215+
for i in range(len(z[:, 0])):
216+
plt.plot([xTrue[0, 0], z[i, 2]], [xTrue[1, 0], z[i, 3]], "-k")
217+
plt.plot(RFID[:, 0], RFID[:, 1], "*k")
218+
plt.plot(px[0, :], px[1, :], ".r")
219+
plt.plot(np.array(hxTrue[0, :]).flatten(),
220+
np.array(hxTrue[1, :]).flatten(), "-b")
221+
plt.plot(np.array(hxDR[0, :]).flatten(),
222+
np.array(hxDR[1, :]).flatten(), "-k")
223+
plt.plot(np.array(hxEst[0, :]).flatten(),
224+
np.array(hxEst[1, :]).flatten(), "-r")
225+
#plot_covariance_ellipse(xEst, PEst)
226+
plt.axis("equal")
227+
plt.grid(True)
228+
plt.pause(0.001)
229+
230+
231+
if __name__ == '__main__':
232+
main()

0 commit comments

Comments
 (0)