Path: blob/master/experiments/dme.py
1700 views
# -*- coding: utf-8 -*-1"""2Spyder Editor34This is a temporary script file.5"""67from KalmanFilter import *8from math import cos, sin, sqrt, atan291011def H_of (pos, pos_A, pos_B):12""" Given the position of our object at 'pos' in 2D, and two transmitters13A and B at positions 'pos_A' and 'pos_B', return the partial derivative14of H15"""1617theta_a = atan2(pos_a[1]-pos[1], pos_a[0] - pos[0])18theta_b = atan2(pos_b[1]-pos[1], pos_b[0] - pos[0])1920if False:21return np.mat([[0, -cos(theta_a), 0, -sin(theta_a)],22[0, -cos(theta_b), 0, -sin(theta_b)]])23else:24return np.mat([[-cos(theta_a), 0, -sin(theta_a), 0],25[-cos(theta_b), 0, -sin(theta_b), 0]])2627class DMESensor(object):28def __init__(self, pos_a, pos_b, noise_factor=1.0):29self.A = pos_a30self.B = pos_b31self.noise_factor = noise_factor3233def range_of (self, pos):34""" returns tuple containing noisy range data to A and B35given a position 'pos'36"""3738ra = sqrt((self.A[0] - pos[0])**2 + (self.A[1] - pos[1])**2)39rb = sqrt((self.B[0] - pos[0])**2 + (self.B[1] - pos[1])**2)4041return (ra + random.randn()*self.noise_factor,42rb + random.randn()*self.noise_factor)434445pos_a = (100,-20)46pos_b = (-100, -20)4748f1 = KalmanFilter(dim_x=4, dim_z=2)4950f1.F = np.mat ([[0, 1, 0, 0],51[0, 0, 0, 0],52[0, 0, 0, 1],53[0, 0, 0, 0]])5455f1.B = 0.5657f1.R *= 1.58f1.Q *= .15960f1.x = np.mat([1,0,1,0]).T61f1.P = np.eye(4) * 5.6263# initialize storage and other variables for the run64count = 3065xs, ys = [],[]66pxs, pys = [],[]6768# create the simulated sensor69d = DMESensor (pos_a, pos_b, noise_factor=1.)7071# pos will contain our nominal position since the filter does not72# maintain position.73pos = [0,0]7475for i in range(count):76# move (1,1) each step, so just use i77pos = [i,i]7879# compute the difference in range between the nominal track and measured80# ranges81ra,rb = d.range_of(pos)82rx,ry = d.range_of((i+f1.x[0,0], i+f1.x[2,0]))8384print ra, rb85print rx,ry86z = np.mat([[ra-rx],[rb-ry]])87print z.T8889# compute linearized H for this time step90f1.H = H_of (pos, pos_a, pos_b)9192# store stuff so we can plot it later93xs.append (f1.x[0,0]+i)94ys.append (f1.x[2,0]+i)95pxs.append (pos[0])96pys.append(pos[1])9798# perform the Kalman filter steps99f1.predict ()100f1.update(z)101102103p1, = plt.plot (xs, ys, 'r--')104p2, = plt.plot (pxs, pys)105plt.legend([p1,p2], ['filter', 'ideal'], 2)106plt.show()107108109110