-
Notifications
You must be signed in to change notification settings - Fork 14
/
GPS_Kalman.py
280 lines (220 loc) · 8.63 KB
/
GPS_Kalman.py
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
'''
Reads in serial data from wireless transmitter data stream. Parces the GPS, Velocity, Heading, and loop time.
The GPS position and velocity is sent through a Kalman filter (code adapted from the Kalman lecture CS373 by Prof. Thurn, Udacity.com) to update the cars position. Calculates the azimuth heading and distance to a GPS waypoint
'''
import binascii
import struct
import serial
from math import *
import csv
import datetime
import time
import numpy as np
import matplotlib.pyplot as plt
class matrix:
# implements basic operations of a matrix class
def __init__(self, value):
self.value = value
self.dimx = len(value)
self.dimy = len(value[0])
if value == [[]]:
self.dimx = 0
def zero(self, dimx, dimy):
# check if valid dimensions
if dimx < 1 or dimy < 1:
raise ValueError, "Invalid size of matrix"
else:
self.dimx = dimx
self.dimy = dimy
self.value = [[0 for row in range(dimy)] for col in range(dimx)]
def identity(self, dim):
# check if valid dimension
if dim < 1:
raise ValueError, "Invalid size of matrix"
else:
self.dimx = dim
self.dimy = dim
self.value = [[0 for row in range(dim)] for col in range(dim)]
for i in range(dim):
self.value[i][i] = 1
def show(self):
for i in range(self.dimx):
print self.value[i]
print ' '
def __add__(self, other):
# check if correct dimensions
if self.dimx != other.dimx or self.dimy != other.dimy:
raise ValueError, "Matrices must be of equal dimensions to add"
else:
# add if correct dimensions
res = matrix([[]])
res.zero(self.dimx, self.dimy)
for i in range(self.dimx):
for j in range(self.dimy):
res.value[i][j] = self.value[i][j] + other.value[i][j]
return res
def __sub__(self, other):
# check if correct dimensions
if self.dimx != other.dimx or self.dimy != other.dimy:
raise ValueError, "Matrices must be of equal dimensions to subtract"
else:
# subtract if correct dimensions
res = matrix([[]])
res.zero(self.dimx, self.dimy)
for i in range(self.dimx):
for j in range(self.dimy):
res.value[i][j] = self.value[i][j] - other.value[i][j]
return res
def __mul__(self, other):
# check if correct dimensions
if self.dimy != other.dimx:
raise ValueError, "Matrices must be m*n and n*p to multiply"
else:
# subtract if correct dimensions
res = matrix([[]])
res.zero(self.dimx, other.dimy)
for i in range(self.dimx):
for j in range(other.dimy):
for k in range(self.dimy):
res.value[i][j] += self.value[i][k] * other.value[k][j]
return res
def transpose(self):
# compute transpose
res = matrix([[]])
res.zero(self.dimy, self.dimx)
for i in range(self.dimx):
for j in range(self.dimy):
res.value[j][i] = self.value[i][j]
return res
# Thanks to Ernesto P. Adorio for use of Cholesky and CholeskyInverse functions
def Cholesky(self, ztol=1.0e-5):
# Computes the upper triangular Cholesky factorization of
# a positive definite matrix.
res = matrix([[]])
res.zero(self.dimx, self.dimx)
for i in range(self.dimx):
S = sum([(res.value[k][i])**2 for k in range(i)])
d = self.value[i][i] - S
if abs(d) < ztol:
res.value[i][i] = 0.0
else:
if d < 0.0:
raise ValueError, "Matrix not positive-definite"
res.value[i][i] = sqrt(d)
for j in range(i+1, self.dimx):
S = sum([res.value[k][i] * res.value[k][j] for k in range(self.dimx)])
if abs(S) < ztol:
S = 0.0
res.value[i][j] = (self.value[i][j] - S)/res.value[i][i]
return res
def CholeskyInverse(self):
# Computes inverse of matrix given its Cholesky upper Triangular
# decomposition of matrix.
res = matrix([[]])
res.zero(self.dimx, self.dimx)
# Backward step for inverse.
for j in reversed(range(self.dimx)):
tjj = self.value[j][j]
S = sum([self.value[j][k]*res.value[j][k] for k in range(j+1, self.dimx)])
res.value[j][j] = 1.0/tjj**2 - S/tjj
for i in reversed(range(j)):
res.value[j][i] = res.value[i][j] = -sum([self.value[i][k]*res.value[k][j] for k in range(i+1, self.dimx)])/self.value[i][i]
return res
def inverse(self):
aux = self.Cholesky()
res = aux.CholeskyInverse()
return res
def __repr__(self):
return repr(self.value)
########################################
def filter(x, P):
for n in range(len(measurements)):
# prediction
x = (F * x) + u
P = F * P * F.transpose()
# measurement update
Z = matrix([measurements[n]])
y = Z.transpose() - (H * x)
S = H * P * H.transpose() + R
K = P * H.transpose() * S.inverse()
x = x + (K * y)
P = (I - (K * H)) * P
#print 'x= '
#x.show()
#print 'P= '
#P.show()
return x.value[0][0], x.value[1][0]
########################################
def bearing(lat1, lon1, lat2, lon2):
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = atan2(sin(dlon)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(dlon))
angle = ((a*(180./pi))+360.)%360
return angle
def distance(lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lat1, lon1, lat2, lon2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + (cos(lat1) * cos(lat2) * sin(dlon/2)**2)
c = 2*atan2(float(sqrt(a)),float(sqrt(1-a)))
km = 6371 * c
return km
def packIntegerAsULong(value):
"""Packs a python 4 byte unsigned integer to an arduino unsigned long"""
return struct.pack('I', value) #should check bounds
u = matrix([[0.], [0.], [0.], [0.]]) # external motion
P = matrix([[1000, 0., 0., 0.],
[0., 1000, 0., 0.],
[0., 0., 1000000, 0.],
[0., 0., 0., 1000000]])
H = matrix([[1., 0., 0., 0.],
[0., 1., 0., 0.]])
R = matrix([[0.2, 0.],
[0., 0.1]])
I = matrix([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
initial_x = 0
initial_y = 0
waypoints = [40.5887,-74.892211]
port = "/dev/ttyUSB1"
ser = serial.Serial(port, 57600, timeout = 3)
while True:
content = ser.readline()
t = [int(i) for i in content.split(',')]
print ' *****************'
print t
lat = t[0]
lat = (lat/1000000)+(((lat/10000)%100)/60.)+((((lat/10000.)%1)*100)/3600)
lon = t[1]
lon = -((lon/1000000)+(((lon/10000)%100)/60.)+((((lon/10000.)%1)*100)/3600))
dt = t[2]
heading = t[4]
steering = t[5]
velx = (t[3]/2)*0.514444444 #assuming x and y have same velocity, m/s
vely = velx
F = matrix([[1., 0., dt, 0.],[0., 1., 0., dt],[0., 0., 1., 0.],[0., 0., 0., 1.]])
measurements = [[lat,lon]]
print 'Measured position [lat,lon] ', measurements
print 'Velocity (x,y) ','(',velx,',',vely,')'
x = matrix([[initial_x], [initial_y], [velx], [vely]])
# (initial_x, initial_y) = filter(x, P)
print 'Updated position [lat,lon] ', initial_x, ',', initial_y
angle = bearing(lat,lon,waypoints[0],waypoints[1])
print 'Current bearing ', heading
print 'Bearing to next waypoint ' ,angle
dist = distance(lat,lon,waypoints[0],waypoints[1])
print 'Distance to waypoint ', dist
print 'Steering from Arduino ', steering
print ' *****************'
ser.write(packIntegerAsULong(angle))