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 Thu May 1 16:56:49 201434@author: rlabbe5"""6import filterpy.stats as stats7from filterpy.stats import plot_covariance_ellipse8import numpy as np9from matplotlib.patches import Ellipse10import matplotlib.pyplot as plt11from matplotlib import cm12from mpl_toolkits.mplot3d import Axes3D13from numpy.random import multivariate_normal1415def show_residual_chart():16est_y = ((164.2-158)*.8 + 158)1718ax = plt.axes(xticks=[], yticks=[], frameon=False)19ax.annotate('', xy=[1,159], xytext=[0,158],20arrowprops=dict(arrowstyle='->',21ec='r', lw=3, shrinkA=6, shrinkB=5))2223ax.annotate('', xy=[1,159], xytext=[1,164.2],24arrowprops=dict(arrowstyle='-',25ec='k', lw=1, shrinkA=8, shrinkB=8))2627ax.annotate('', xy=(1., est_y), xytext=(0.9, est_y),28arrowprops=dict(arrowstyle='->', ec='#004080',29lw=2,30shrinkA=3, shrinkB=4))313233plt.scatter ([0,1], [158.0,est_y], c='k',s=128)34plt.scatter ([1], [164.2], c='b',s=128)35plt.scatter ([1], [159], c='r', s=128)36plt.text (1.0, 158.8, "prediction ($x_t)$", ha='center',va='top',fontsize=18,color='red')37plt.text (1.0, 164.4, "measurement ($z$)",ha='center',va='bottom',fontsize=18,color='blue')38plt.text (0, 157.8, "prior estimate ($\hat{x}_{t-1}$)", ha='center', va='top',fontsize=18)39plt.text (1.02, est_y-1.5, "residual", ha='left', va='center',fontsize=18)40plt.text (0.9, est_y, "new estimate ($\hat{x}_{t}$)", ha='right', va='center',fontsize=18)41plt.xlabel('time')42ax.yaxis.set_label_position("right")43plt.ylabel('state')44plt.xlim(-0.5, 1.5)45plt.show()464748def plot_gaussian_multiply():49xs = np.arange(-5, 10, 0.1)5051mean1, var1 = 0, 552mean2, var2 = 5, 153mean, var = stats.mul(mean1, var1, mean2, var2)5455ys = [stats.gaussian(x, mean1, var1) for x in xs]56plt.plot(xs, ys, label='M1')5758ys = [stats.gaussian(x, mean2, var2) for x in xs]59plt.plot(xs, ys, label='M2')6061ys = [stats.gaussian(x, mean, var) for x in xs]62plt.plot(xs, ys, label='M1 x M2')63plt.legend()64plt.show()656667def show_position_chart():68""" Displays 3 measurements at t=1,2,3, with x=1,2,3"""6970plt.scatter ([1,2,3], [1,2,3], s=128, color='#004080')71plt.xlim([0,4]);72plt.ylim([0,4])7374plt.annotate('t=1', xy=(1,1), xytext=(0,-10),75textcoords='offset points', ha='center', va='top')7677plt.annotate('t=2', xy=(2,2), xytext=(0,-10),78textcoords='offset points', ha='center', va='top')7980plt.annotate('t=3', xy=(3,3), xytext=(0,-10),81textcoords='offset points', ha='center', va='top')8283plt.xlabel("X")84plt.ylabel("Y")8586plt.xticks(np.arange(1,4,1))87plt.yticks(np.arange(1,4,1))88plt.show()899091def show_position_prediction_chart():92""" displays 3 measurements, with the next position predicted"""9394plt.scatter ([1,2,3], [1,2,3], s=128, color='#004080')9596plt.annotate('t=1', xy=(1,1), xytext=(0,-10),97textcoords='offset points', ha='center', va='top')9899plt.annotate('t=2', xy=(2,2), xytext=(0,-10),100textcoords='offset points', ha='center', va='top')101102plt.annotate('t=3', xy=(3,3), xytext=(0,-10),103textcoords='offset points', ha='center', va='top')104105plt.xlim([0,5])106plt.ylim([0,5])107108plt.xlabel("Position")109plt.ylabel("Time")110111plt.xticks(np.arange(1,5,1))112plt.yticks(np.arange(1,5,1))113114plt.scatter ([4], [4], c='g',s=128, color='#8EBA42')115ax = plt.axes()116ax.annotate('', xy=(4,4), xytext=(3,3),117arrowprops=dict(arrowstyle='->',118ec='g',119shrinkA=6, shrinkB=5,120lw=3))121plt.show()122123124def show_x_error_chart(count):125""" displays x=123 with covariances showing error"""126127plt.cla()128plt.gca().autoscale(tight=True)129130cov = np.array([[0.03,0], [0,8]])131e = stats.covariance_ellipse (cov)132133cov2 = np.array([[0.03,0], [0,4]])134e2 = stats.covariance_ellipse (cov2)135136cov3 = np.array([[12,11.95], [11.95,12]])137e3 = stats.covariance_ellipse (cov3)138139140sigma=[1, 4, 9]141142if count >= 1:143stats.plot_covariance_ellipse ((0,0), ellipse=e, variance=sigma)144145if count == 2 or count == 3:146147stats.plot_covariance_ellipse ((5,5), ellipse=e, variance=sigma)148149if count == 3:150151stats.plot_covariance_ellipse ((5,5), ellipse=e3, variance=sigma,152edgecolor='r')153154if count == 4:155M1 = np.array([[5, 5]]).T156m4, cov4 = stats.multivariate_multiply(M1, cov2, M1, cov3)157e4 = stats.covariance_ellipse (cov4)158159stats.plot_covariance_ellipse ((5,5), ellipse=e, variance=sigma,160alpha=0.25)161162stats.plot_covariance_ellipse ((5,5), ellipse=e3, variance=sigma,163edgecolor='r', alpha=0.25)164stats.plot_covariance_ellipse (m4[:,0], ellipse=e4, variance=sigma)165166#plt.ylim([0,11])167#plt.xticks(np.arange(1,4,1))168169plt.xlabel("Position")170plt.ylabel("Velocity")171172plt.show()173174175def show_x_with_unobserved():176""" shows x=1,2,3 with velocity superimposed on top """177178# plot velocity179sigma=[0.5,1.,1.5,2]180cov = np.array([[1,1],[1,1.1]])181stats.plot_covariance_ellipse ((2,2), cov=cov, variance=sigma, axis_equal=False)182183# plot positions184cov = np.array([[0.003,0], [0,12]])185sigma=[0.5,1.,1.5,2]186e = stats.covariance_ellipse (cov)187188stats.plot_covariance_ellipse ((1,1), ellipse=e, variance=sigma, axis_equal=False)189stats.plot_covariance_ellipse ((2,1), ellipse=e, variance=sigma, axis_equal=False)190stats.plot_covariance_ellipse ((3,1), ellipse=e, variance=sigma, axis_equal=False)191192# plot intersection cirle193isct = Ellipse(xy=(2,2), width=.2, height=1.2, edgecolor='r', fc='None', lw=4)194plt.gca().add_artist(isct)195196plt.ylim([0,11])197plt.xlim([0,4])198plt.xticks(np.arange(1,4,1))199200plt.xlabel("Position")201plt.ylabel("Time")202203plt.show()204205206207def plot_3d_covariance(mean, cov):208""" plots a 2x2 covariance matrix positioned at mean. mean will be plotted209in x and y, and the probability in the z axis.210211Parameters212----------213mean : 2x1 tuple-like object214mean for x and y coordinates. For example (2.3, 7.5)215216cov : 2x2 nd.array217the covariance matrix218219"""220221# compute width and height of covariance ellipse so we can choose222# appropriate ranges for x and y223o,w,h = stats.covariance_ellipse(cov,3)224# rotate width and height to x,y axis225wx = abs(w*np.cos(o) + h*np.sin(o))*1.2226wy = abs(h*np.cos(o) - w*np.sin(o))*1.2227228229# ensure axis are of the same size so everything is plotted with the same230# scale231if wx > wy:232w = wx233else:234w = wy235236minx = mean[0] - w237maxx = mean[0] + w238miny = mean[1] - w239maxy = mean[1] + w240241xs = np.arange(minx, maxx, (maxx-minx)/40.)242ys = np.arange(miny, maxy, (maxy-miny)/40.)243xv, yv = np.meshgrid (xs, ys)244245zs = np.array([100.* stats.multivariate_gaussian(np.array([x,y]),mean,cov) \246for x,y in zip(np.ravel(xv), np.ravel(yv))])247zv = zs.reshape(xv.shape)248249ax = plt.figure().add_subplot(111, projection='3d')250ax.plot_surface(xv, yv, zv, rstride=1, cstride=1, cmap=cm.autumn)251252ax.set_xlabel('X')253ax.set_ylabel('Y')254255ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.autumn)256ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.BuGn)257258259def plot_3d_sampled_covariance(mean, cov):260""" plots a 2x2 covariance matrix positioned at mean. mean will be plotted261in x and y, and the probability in the z axis.262263Parameters264----------265mean : 2x1 tuple-like object266mean for x and y coordinates. For example (2.3, 7.5)267268cov : 2x2 nd.array269the covariance matrix270271"""272273# compute width and height of covariance ellipse so we can choose274# appropriate ranges for x and y275o,w,h = stats.covariance_ellipse(cov,3)276# rotate width and height to x,y axis277wx = abs(w*np.cos(o) + h*np.sin(o))*1.2278wy = abs(h*np.cos(o) - w*np.sin(o))*1.2279280281# ensure axis are of the same size so everything is plotted with the same282# scale283if wx > wy:284w = wx285else:286w = wy287288minx = mean[0] - w289maxx = mean[0] + w290miny = mean[1] - w291maxy = mean[1] + w292293count = 1000294x,y = multivariate_normal(mean=mean, cov=cov, size=count).T295296xs = np.arange(minx, maxx, (maxx-minx)/40.)297ys = np.arange(miny, maxy, (maxy-miny)/40.)298xv, yv = np.meshgrid (xs, ys)299300zs = np.array([100.* stats.multivariate_gaussian(np.array([xx,yy]),mean,cov) \301for xx,yy in zip(np.ravel(xv), np.ravel(yv))])302zv = zs.reshape(xv.shape)303304ax = plt.figure().add_subplot(111, projection='3d')305ax.scatter(x,y, [0]*count, marker='.')306307ax.set_xlabel('X')308ax.set_ylabel('Y')309310ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.autumn)311ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.BuGn)312313314def plot_3_covariances():315316P = [[2, 0], [0, 2]]317plt.subplot(131)318plot_covariance_ellipse((2, 7), cov=P, facecolor='g', alpha=0.2,319title='|2 0|\n|0 2|', axis_equal=False)320plt.ylim((4, 10))321plt.gca().set_aspect('equal', adjustable='box')322323plt.subplot(132)324P = [[2, 0], [0, 9]]325plt.ylim((4, 10))326plt.gca().set_aspect('equal', adjustable='box')327plot_covariance_ellipse((2, 7), P, facecolor='g', alpha=0.2,328axis_equal=False, title='|2 0|\n|0 9|')329330plt.subplot(133)331P = [[2, 1.2], [1.2, 2]]332plt.ylim((4, 10))333plt.gca().set_aspect('equal', adjustable='box')334plot_covariance_ellipse((2, 7), P, facecolor='g', alpha=0.2,335axis_equal=False,336title='|2 1.2|\n|1.2 2|')337338plt.tight_layout()339plt.show()340341342def plot_correlation_covariance():343P = [[4, 3.9], [3.9, 4]]344plot_covariance_ellipse((5, 10), P, edgecolor='k',345variance=[1, 2**2, 3**2])346plt.xlabel('X')347plt.ylabel('Y')348plt.gca().autoscale(tight=True)349plt.axvline(7.5, ls='--', lw=1)350plt.axhline(12.5, ls='--', lw=1)351plt.scatter(7.5, 12.5, s=2000, alpha=0.5)352plt.title('|4.0 3.9|\n|3.9 4.0|')353plt.show()354355356import book_plots as bp357def plot_track(ps, zs, cov, std_scale=1,358plot_P=True, y_lim=None,359title='Kalman Filter'):360361count = len(zs)362actual = np.linspace(0, count - 1, count)363cov = np.asarray(cov)364std = std_scale*np.sqrt(cov[:,0,0])365std_top = np.minimum(actual+std, [count + 10])366std_btm = np.maximum(actual-std, [-50])367368std_top = actual+std369std_btm = actual-std370371bp.plot_track(actual,c='k')372bp.plot_measurements(range(1, count + 1), zs)373bp.plot_filter(range(1, count + 1), ps)374375plt.plot(std_top, linestyle=':', color='k', lw=1, alpha=0.4)376plt.plot(std_btm, linestyle=':', color='k', lw=1, alpha=0.4)377plt.fill_between(range(len(std_top)), std_top, std_btm,378facecolor='yellow', alpha=0.2, interpolate=True)379plt.legend(loc=4)380if y_lim is not None:381plt.ylim(y_lim)382else:383plt.ylim((-50, count + 10))384385plt.xlim((0,count))386plt.title(title)387plt.show()388389if plot_P:390ax = plt.subplot(121)391ax.set_title("$\sigma^2_x$")392plot_covariance(cov, (0, 0))393ax = plt.subplot(122)394ax.set_title("$\sigma^2_y$")395plot_covariance(cov, (1, 1))396plt.show()397398def plot_covariance(P, index=(0, 0)):399ps = []400for p in P:401ps.append(p[index[0], index[1]])402plt.plot(ps)403404405406if __name__ == "__main__":407pass408#show_position_chart()409#plot_3d_covariance((2,7), np.array([[8.,0],[0,4.]]))410#plot_3d_sampled_covariance([2,7], [[8.,0],[0,4.]])411#show_residual_chart()412413#show_position_chart()414#show_x_error_chart(4)415416417418