In the following code, I have implemented an Extended Kalman Filter for modeling the movement of a car with constant turn rate and velocity. The code is mainly based on this work (I did some bug fixing and some adaptation such that the code runs similar to the Kalman filter that I have earlier implemented).
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 234 235 |
import matplotlib.dates as mdates import numpy as np np.set_printoptions(threshold=3) np.set_printoptions(suppress=True) from numpy import genfromtxt import matplotlib.pyplot as plt from scipy.stats import norm from sympy import Symbol, symbols, Matrix, sin, cos from sympy import init_printing from sympy.utilities.codegen import codegen init_printing(use_latex=True) x0 = [] x1 = [] x2 = [] def prediction(X_hat_t_1,P_t_1,Q_t,drivingStraight): X_hat_t=X_hat_t_1 if drivingStraight: # Driving straight X_hat_t[0] = X_hat_t_1[0] + X_hat_t_1[3]*dt * np.cos(X_hat_t_1[2]) X_hat_t[1] = X_hat_t_1[1] + X_hat_t_1[3]*dt * np.sin(X_hat_t_1[2]) X_hat_t[2] = X_hat_t_1[2] X_hat_t[3] = X_hat_t_1[3] + X_hat_t_1[5]*dt X_hat_t[4] = 0.0000001 # avoid numerical issues in Jacobians X_hat_t[5] = X_hat_t_1[5] else: # otherwise X_hat_t[0] = X_hat_t_1[0] + (X_hat_t_1[3]/X_hat_t_1[4]) * (np.sin(X_hat_t_1[4]*dt+X_hat_t_1[2]) - np.sin(X_hat_t_1[2])) X_hat_t[1] = X_hat_t_1[1] + (X_hat_t_1[3]/X_hat_t_1[4]) * (-np.cos(X_hat_t_1[4]*dt+X_hat_t_1[2])+ np.cos(X_hat_t_1[2])) X_hat_t[2] = (X_hat_t_1[2] + X_hat_t_1[4]*dt + np.pi) % (2.0*np.pi) - np.pi X_hat_t[3] = X_hat_t_1[3] + X_hat_t_1[5]*dt X_hat_t[4] = X_hat_t_1[4] # Constant Turn Rate X_hat_t[5] = X_hat_t_1[5] # Constant Acceleration # Calculate the Jacobian of the Dynamic Matrix A # see "Calculate the Jacobian of the Dynamic Matrix with respect to the state vector" a13 = float((X_hat_t[3]/X_hat_t[4]) * (np.cos(X_hat_t[4]*dt+X_hat_t[2]) - np.cos(X_hat_t[2]))) a14 = float((1.0/X_hat_t[4]) * (np.sin(X_hat_t[4]*dt+X_hat_t[2]) - np.sin(X_hat_t[2]))) a15 = float((dt*X_hat_t[3]/X_hat_t[4])*np.cos(X_hat_t[4]*dt+X_hat_t[2]) - (X_hat_t[3]/X_hat_t[4]**2)*(np.sin(X_hat_t[4]*dt+X_hat_t[2]) - np.sin(X_hat_t[2]))) a23 = float((X_hat_t[3]/X_hat_t[4]) * (np.sin(X_hat_t[4]*dt+X_hat_t[2]) - np.sin(X_hat_t[2]))) a24 = float((1.0/X_hat_t[4]) * (-np.cos(X_hat_t[4]*dt+X_hat_t[2]) + np.cos(X_hat_t[2]))) a25 = float((dt*X_hat_t[3]/X_hat_t[4])*np.sin(X_hat_t[4]*dt+X_hat_t[2]) - (X_hat_t[3]/X_hat_t[4]**2)*(-np.cos(X_hat_t[4]*dt+X_hat_t[2]) + np.cos(X_hat_t[2]))) JA = np.matrix([[1.0, 0.0, a13, a14, a15, 0.0], [0.0, 1.0, a23, a24, a25, 0.0], [0.0, 0.0, 1.0, 0.0, dt, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, dt], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]]) # Project the error covariance ahead P_t_1 = JA*P_t_1*JA.T + Q_t return X_hat_t,P_t_1 def update(X_hat_t,P_t,Z_t,R_t,GPSAvailable): hx = np.matrix([[float(X_hat_t[0])], [float(X_hat_t[1])], [float(X_hat_t[3])], [float(X_hat_t[4])], [float(X_hat_t[5])]]) if GPSAvailable: # with 10Hz, every 5th step JH = np.matrix([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]]) else: # every other step JH = np.matrix([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]]) S = JH*P_t*JH.T + R_t K = (P_t*JH.T) * np.linalg.inv(S) #print("K:\n",K) # Update the estimate via Z = Z_t.reshape(JH.shape[0],1) #print("Z:\n",Z) y = Z - (hx) # Innovation or Residual X_t = X_hat_t + (K*y) # Update the error covariance I = np.eye(X_hat_t.shape[0]) P_t = (I - (K*JH))*P_t x0.append(float(X_t[0])) x1.append(float(X_t[1])) x2.append(float(X_t[2])) return X_t,P_t numstates=6 # States dt = 1.0/50.0 # Sample Rate of the Measurements is 50Hz dtGPS=1.0/10.0 # Sample Rate of GPS is 10Hz vs, psis, dpsis, dts, xs, ys, lats, lons, axs = symbols('v \psi \dot\psi T x y lat lon a') gs = Matrix([[xs+(vs/dpsis)*(sin(psis+dpsis*dts)-sin(psis))], [ys+(vs/dpsis)*(-cos(psis+dpsis*dts)+cos(psis))], [psis+dpsis*dts], [axs*dts + vs], [dpsis], [axs]]) state = Matrix([xs,ys,psis,vs,dpsis,axs]) #Initial State cov P_t = np.diag([1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0]) #Measurment cov varGPS = 5.0 # Standard Deviation of GPS Measurement varspeed = 3.0 # Variance of the speed measurement varyaw = 0.1 # Variance of the yawrate measurement varacc = 1.0 # Variance of the longitudinal Acceleration R_t = np.diag([varGPS**2, varGPS**2, varspeed**2, varyaw**2, varacc**2]) #Measurment Matrix hs = Matrix([[xs], [ys], [vs], [dpsis], [axs]]) #Process cov sGPS = 0.5*8.8*dt**2 # assume 8.8m/s2 as maximum acceleration, forcing the vehicle sCourse = 0.1*dt # assume 0.1rad/s as maximum turn rate for the vehicle sVelocity= 8.8*dt # assume 8.8m/s2 as maximum acceleration, forcing the vehicle sYaw = 1.0*dt # assume 1.0rad/s2 as the maximum turn rate acceleration for the vehicle sAccel = 0.5 Q_t = np.diag([sGPS**2, sGPS**2, sCourse**2, sVelocity**2, sYaw**2, sAccel**2]) path="data/" datafile = '2014-03-26-000-Data.csv' fullPath=path+datafile def bytespdate2num(fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter date, time, millis, ax, ay, az, rollrate, pitchrate, yawrate, roll, pitch, yaw, speed, course, latitude, longitude, altitude, pdop, hdop, vdop, epe, fix, satellites_view, satellites_used, temp = np.loadtxt(fullPath, delimiter=',', unpack=True, converters={1:bytespdate2num('%H%M%S%f'), 0: bytespdate2num('%y%m%d')}, skiprows=1) # A course of 0 means the Car is traveling north bound # and 90 means it is traveling east bound. # In the Calculation following, East is Zero and North is 90 # We need an offset. course =(-course+90.0) # ## Approx. Lat/Lon to Meters to check Location # In[17]: RadiusEarth = 6378388.0 # m arc= 2.0*np.pi*(RadiusEarth+altitude)/360.0 # m/ dx = arc * np.cos(latitude*np.pi/180.0) * np.hstack((0.0, np.diff(longitude))) # in m dy = arc * np.hstack((0.0, np.diff(latitude))) # in m mx = np.cumsum(dx) my = np.cumsum(dy) ds = np.sqrt(dx**2+dy**2) GPS=(ds!=0.0).astype('bool') # GPS Trigger for Kalman Filter # ## Initial State X_hat_t = np.matrix([[mx[0], my[0], course[0]/180.0*np.pi, speed[0]/3.6+0.001, yawrate[0]/180.0*np.pi, ax[0]]]).T measurements = np.vstack((mx, my, speed/3.6, yawrate/180.0*np.pi, ax)) # Lenth of the measurement m = measurements.shape[1] for i in range(measurements.shape[1]): #for i in range(3): if np.abs(yawrate[i])<0.0001: drivingStraight=True else: drivingStraight=False X_hat_t,P_hat_t = prediction(X_hat_t,P_t,Q_t,drivingStraight) #print("Prediction:") #print("X_hat_t:\n",X_hat_t,"\nP_t:\n",P_hat_t) Z_t=measurements[:,i] if GPS[i]: GPSAvailable=True else: GPSAvailable=False X_t,P_t=update(X_hat_t,P_hat_t,Z_t,R_t,GPSAvailable) #print("Update:") #print("X_t:\n",X_t,"\nP_t:\n",P_t) X_hat_t=X_t P_hat_t=P_t fig = plt.figure(figsize=(16,9)) # EKF State plt.quiver(x0,x1,np.cos(x2), np.sin(x2), color='#94C600', units='xy', width=0.05, scale=0.5) plt.plot(x0,x1, label='EKF Position', c='k', lw=5) # Measurements plt.scatter(mx[::5],my[::5], s=50, label='GPS Measurements', marker='+') # Start/Goal plt.scatter(x0[0],x1[0], s=60, label='Start', c='g') plt.scatter(x0[-1],x1[-1], s=60, label='Goal', c='r') plt.xlabel('X [m]') plt.ylabel('Y [m]') plt.title('Position') plt.legend(loc='best') plt.axis('equal') plt.show() |
References: [1] [2] [3] [4] [5]
Hi, first of all thank you for you amazing video series that is helping me so much understanding the Kalman filter !
In this video, what is the C function and Ck matrix at the end, in the Update State equations ?
Any way to get the /home/behnam/Kalman/2014-03-26-000-Data.csv file?
Hi, I have fixed the missing csv file, please check the git repository.
https://github.com/behnamasadi/Filters/
Hi, I like your explanation, in the video.
Actually I try to practice EKF by simulating a simple pendulum and using python code.
however I got a problem, How can I have further discussion about it. ?
If you don’t mind, would you send me your email, so I can share my short python code about my problem.
Thanks
Hi, thanks for your comment, I would love to help but honestly I can’t do much now, I strongly recommend you to watch this YouTube channel: https://www.youtube.com/channel/UCi1TC2fLRvgBQNe-T4dp8Eg
In your case SLAM course maybe, just follow “Cyrill Stachniss” instructions he is really a good researcher.
Hello!
Amazing work.
I just have one doubt, in the given dataset, latitude and logitude values are in range of 111 and 13 respectively. Then how come output is in range from 0-100? Please explain this? I just need co-ordinates of ekf plot in terms of lat and long,so i can see how much difference when compared to gps values. If you know piece of code to get these co-ordinates, please share.
Thankyou
Hi, thanks for your comment, I will share with you where I get the dataset once I’m back on my PC, thank for your patience.
Hello Vijay, please visit https://github.com/balzer82/Kalman/ for more information. It is listed also in ref section of the post, regards.
Hi. Firstly, thank you for your video and source code in python. It’s very useful for me. However, could you plz explain the motion equation when the car does not drive straight and especially the Jacobian matrix?
In addition, in your source code, Does JA*P_t_1*JA.T + Q_t means np.dot or just np.mul?
Traceback (most recent call last):
File “e:\Python_Test\test4efk.py”, line 157, in <module>
converters={1:bytespdate2num(‘%H%M%S%f’),
File “e:\Python_Test\test4efk.py”, line 149, in bytespdate2num
strconverter = mdates.strpdate2num(fmt)
AttributeError: module ‘matplotlib.dates’ has no attribute ‘strpdate2num’
how fix it?
replace with this
def bytespdate2num(fmt, encoding=‘utf-8’):
strconverter = lambda x: datetime.datetime.strptime(x.decode(encoding), fmt)
def bytesconverter(b):
dt = strconverter(b)
return mdates.date2num(dt)
return bytesconverter