Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
| Download
Project: test
Views: 91872# -*- coding: utf-8 -*-1"""2Created on Tue May 27 21:21:19 201434@author: rlabbe5"""6from filterpy.kalman import UnscentedKalmanFilter as UKF7from filterpy.kalman import MerweScaledSigmaPoints8import filterpy.stats as stats9from filterpy.stats import plot_covariance_ellipse10import matplotlib.pyplot as plt11from matplotlib.patches import Ellipse,Arrow12import math13import numpy as np1415def _sigma_points(mean, sigma, kappa):16sigma1 = mean + math.sqrt((1+kappa)*sigma)17sigma2 = mean - math.sqrt((1+kappa)*sigma)18return mean, sigma1, sigma2192021def arrow(x1,y1,x2,y2, width=0.2):22return Arrow(x1,y1, x2-x1, y2-y1, lw=1, width=width, ec='k', color='k')232425def show_two_sensor_bearing():26circle1=plt.Circle((-4,0),5,color='#004080',fill=False,linewidth=20, alpha=.7)27circle2=plt.Circle((4,0),5,color='#E24A33', fill=False, linewidth=5, alpha=.7)2829fig = plt.gcf()30ax = fig.gca()3132plt.axis('equal')33#plt.xlim((-10,10))34plt.ylim((-6,6))3536plt.plot ([-4,0], [0,3], c='#004080')37plt.plot ([4,0], [0,3], c='#E24A33')38plt.text(-4, -.5, "A", fontsize=16, horizontalalignment='center')39plt.text(4, -.5, "B", fontsize=16, horizontalalignment='center')4041ax.add_patch(circle1)42ax.add_patch(circle2)43plt.show()444546def show_three_gps():47circle1=plt.Circle((-4,0),5,color='#004080',fill=False,linewidth=20, alpha=.7)48circle2=plt.Circle((4,0),5,color='#E24A33', fill=False, linewidth=8, alpha=.7)49circle3=plt.Circle((0,-3),6,color='#534543',fill=False, linewidth=13, alpha=.7)5051fig = plt.gcf()52ax = fig.gca()5354ax.add_patch(circle1)55ax.add_patch(circle2)56ax.add_patch(circle3)5758plt.axis('equal')59plt.show()606162def show_four_gps():63circle1=plt.Circle((-4,2),5,color='#004080',fill=False,linewidth=20, alpha=.7)64circle2=plt.Circle((5.5,1),5,color='#E24A33', fill=False, linewidth=8, alpha=.7)65circle3=plt.Circle((0,-3),6,color='#534543',fill=False, linewidth=13, alpha=.7)66circle4=plt.Circle((0,8),5,color='#214513',fill=False, linewidth=13, alpha=.7)6768fig = plt.gcf()69ax = fig.gca()7071ax.add_patch(circle1)72ax.add_patch(circle2)73ax.add_patch(circle3)74ax.add_patch(circle4)7576plt.axis('equal')77plt.show()787980def show_sigma_transform(with_text=False):81fig = plt.figure()82ax=fig.gca()8384x = np.array([0, 5])85P = np.array([[4, -2.2], [-2.2, 3]])8687plot_covariance_ellipse(x, P, facecolor='b', alpha=0.6, variance=9)88sigmas = MerweScaledSigmaPoints(2, alpha=.5, beta=2., kappa=0.)8990S = sigmas.sigma_points(x=x, P=P)91plt.scatter(S[:,0], S[:,1], c='k', s=80)9293x = np.array([15, 5])94P = np.array([[3, 1.2],[1.2, 6]])95plot_covariance_ellipse(x, P, facecolor='g', variance=9, alpha=0.3)9697ax.add_artist(arrow(S[0,0], S[0,1], 11, 4.1, 0.6))98ax.add_artist(arrow(S[1,0], S[1,1], 13, 7.7, 0.6))99ax.add_artist(arrow(S[2,0], S[2,1], 16.3, 0.93, 0.6))100ax.add_artist(arrow(S[3,0], S[3,1], 16.7, 10.8, 0.6))101ax.add_artist(arrow(S[4,0], S[4,1], 17.7, 5.6, 0.6))102103ax.axes.get_xaxis().set_visible(False)104ax.axes.get_yaxis().set_visible(False)105106if with_text:107plt.text(2.5, 1.5, r"$\chi$", fontsize=32)108plt.text(13, -1, r"$\mathcal{Y}$", fontsize=32)109110#plt.axis('equal')111plt.show()112113114115def show_2d_transform():116117plt.cla()118ax=plt.gca()119120ax.add_artist(Ellipse(xy=(2,5), width=2, height=3,angle=70,linewidth=1,ec='k'))121ax.add_artist(Ellipse(xy=(7,5), width=2.2, alpha=0.3, height=3.8,angle=150,fc='g',linewidth=1,ec='k'))122123ax.add_artist(arrow(2, 5, 6, 4.8))124ax.add_artist(arrow(1.5, 5.5, 7, 3.8))125ax.add_artist(arrow(2.3, 4.1, 8, 6))126ax.add_artist(arrow(3.3, 5.1, 6.5, 4.3))127ax.add_artist(arrow(1.3, 4.8, 7.2, 6.3))128ax.add_artist(arrow(1.1, 5.2, 8.2, 5.3))129ax.add_artist(arrow(2, 4.4, 7.3, 4.5))130131ax.axes.get_xaxis().set_visible(False)132ax.axes.get_yaxis().set_visible(False)133134plt.axis('equal')135plt.xlim(0,10); plt.ylim(0,10)136plt.show()137138139def show_3_sigma_points():140xs = np.arange(-4, 4, 0.1)141var = 1.5142ys = [stats.gaussian(x, 0, var) for x in xs]143samples = [0, 1.2, -1.2]144for x in samples:145plt.scatter ([x], [stats.gaussian(x, 0, var)], s=80)146147plt.plot(xs, ys)148plt.show()149150def show_sigma_selections():151ax=plt.gca()152ax.axes.get_xaxis().set_visible(False)153ax.axes.get_yaxis().set_visible(False)154155x = np.array([2, 5])156P = np.array([[3, 1.1], [1.1, 4]])157158points = MerweScaledSigmaPoints(2, .05, 2., 1.)159sigmas = points.sigma_points(x, P)160plot_covariance_ellipse(x, P, facecolor='b', alpha=0.6, variance=[.5])161plt.scatter(sigmas[:,0], sigmas[:, 1], c='k', s=50)162163x = np.array([5, 5])164points = MerweScaledSigmaPoints(2, .15, 2., 1.)165sigmas = points.sigma_points(x, P)166plot_covariance_ellipse(x, P, facecolor='b', alpha=0.6, variance=[.5])167plt.scatter(sigmas[:,0], sigmas[:, 1], c='k', s=50)168169x = np.array([8, 5])170points = MerweScaledSigmaPoints(2, .4, 2., 1.)171sigmas = points.sigma_points(x, P)172plot_covariance_ellipse(x, P, facecolor='b', alpha=0.6, variance=[.5])173plt.scatter(sigmas[:,0], sigmas[:, 1], c='k', s=50)174175plt.axis('equal')176plt.xlim(0,10); plt.ylim(0,10)177plt.show()178179180def show_sigmas_for_2_kappas():181# generate the Gaussian data182183xs = np.arange(-4, 4, 0.1)184mean = 0185sigma = 1.5186ys = [stats.gaussian(x, mean, sigma*sigma) for x in xs]187188189190#generate our samples191kappa = 2192x0,x1,x2 = _sigma_points(mean, sigma, kappa)193194samples = [x0,x1,x2]195for x in samples:196p1 = plt.scatter([x], [stats.gaussian(x, mean, sigma*sigma)], s=80, color='k')197198kappa = -.5199x0,x1,x2 = _sigma_points(mean, sigma, kappa)200201samples = [x0,x1,x2]202for x in samples:203p2 = plt.scatter([x], [stats.gaussian(x, mean, sigma*sigma)], s=80, color='b')204205plt.legend([p1,p2], ['$kappa$=2', '$kappa$=-0.5'])206plt.plot(xs, ys)207plt.show()208209210def plot_sigma_points():211x = np.array([0, 0])212P = np.array([[4, 2], [2, 4]])213214sigmas = MerweScaledSigmaPoints(n=2, alpha=.3, beta=2., kappa=1.)215S0 = sigmas.sigma_points(x, P)216Wm0, Wc0 = sigmas.weights()217218sigmas = MerweScaledSigmaPoints(n=2, alpha=1., beta=2., kappa=1.)219S1 = sigmas.sigma_points(x, P)220Wm1, Wc1 = sigmas.weights()221222def plot_sigmas(s, w, **kwargs):223min_w = min(abs(w))224scale_factor = 100 / min_w225return plt.scatter(s[:, 0], s[:, 1], s=abs(w)*scale_factor, alpha=.5, **kwargs)226227plt.subplot(121)228plot_sigmas(S0, Wc0, c='b')229plot_covariance_ellipse(x, P, facecolor='g', alpha=0.2, variance=[1, 4])230plt.title('alpha=0.3')231plt.subplot(122)232plot_sigmas(S1, Wc1, c='b', label='Kappa=2')233plot_covariance_ellipse(x, P, facecolor='g', alpha=0.2, variance=[1, 4])234plt.title('alpha=1')235plt.show()236print(sum(Wc0))237238def plot_radar(xs, t, plot_x=True, plot_vel=True, plot_alt=True):239xs = np.asarray(xs)240if plot_x:241plt.figure()242plt.plot(t, xs[:, 0]/1000.)243plt.xlabel('time(sec)')244plt.ylabel('position(km)')245if plot_vel:246plt.figure()247plt.plot(t, xs[:, 1])248plt.xlabel('time(sec)')249plt.ylabel('velocity')250if plot_alt:251plt.figure()252plt.plot(t, xs[:,2])253plt.xlabel('time(sec)')254plt.ylabel('altitude')255plt.show()256257def print_sigmas(n=1, mean=5, cov=3, alpha=.1, beta=2., kappa=2):258points = MerweScaledSigmaPoints(n, alpha, beta, kappa)259print('sigmas: ', points.sigma_points(mean, cov).T[0])260Wm, Wc = points.weights()261print('mean weights:', Wm)262print('cov weights:', Wc)263print('lambda:', alpha**2 *(n+kappa) - n)264print('sum cov', sum(Wc))265266267def plot_rts_output(xs, Ms, t):268plt.figure()269plt.plot(t, xs[:, 0]/1000., label='KF', lw=2)270plt.plot(t, Ms[:, 0]/1000., c='k', label='RTS', lw=2)271plt.xlabel('time(sec)')272plt.ylabel('x')273plt.legend(loc=4)274275plt.figure()276277plt.plot(t, xs[:, 1], label='KF')278plt.plot(t, Ms[:, 1], c='k', label='RTS')279plt.xlabel('time(sec)')280plt.ylabel('x velocity')281plt.legend(loc=4)282283plt.figure()284plt.plot(t, xs[:, 2], label='KF')285plt.plot(t, Ms[:, 2], c='k', label='RTS')286plt.xlabel('time(sec)')287plt.ylabel('Altitude(m)')288plt.legend(loc=4)289290np.set_printoptions(precision=4)291print('Difference in position in meters:', xs[-6:-1, 0] - Ms[-6:-1, 0])292293294if __name__ == '__main__':295296#show_2d_transform()297#show_sigma_selections()298299show_sigma_transform(True)300#show_four_gps()301#show_sigma_transform()302#show_sigma_selections()303304305306