def show_x_error_chart(count): """ displays x=123 with covariances showing error""" plt.cla() plt.gca().autoscale(tight=True) cov = np.array([[0.03, 0], [0, 8]]) e = stats.covariance_ellipse(cov) cov2 = np.array([[0.03, 0], [0, 4]]) e2 = stats.covariance_ellipse(cov2) cov3 = np.array([[12, 11.95], [11.95, 12]]) e3 = stats.covariance_ellipse(cov3) sigma = [1, 4, 9] if count >= 1: stats.plot_covariance_ellipse((0, 0), ellipse=e, variance=sigma) if count == 2 or count == 3: stats.plot_covariance_ellipse((5, 5), ellipse=e, variance=sigma) if count == 3: stats.plot_covariance_ellipse((5, 5), ellipse=e3, variance=sigma, edgecolor='r') if count == 4: M1 = np.array([[5, 5]]).T m4, cov4 = stats.multivariate_multiply(M1, cov2, M1, cov3) e4 = stats.covariance_ellipse(cov4) stats.plot_covariance_ellipse((5, 5), ellipse=e, variance=sigma, alpha=0.25) stats.plot_covariance_ellipse((5, 5), ellipse=e3, variance=sigma, edgecolor='r', alpha=0.25) stats.plot_covariance_ellipse(m4[:, 0], ellipse=e4, variance=sigma) plt.ylim((-9, 16)) #plt.ylim([0,11]) #plt.xticks(np.arange(1,4,1)) plt.xlabel("Position") plt.ylabel("Velocity") plt.show()
def show_x_error_chart(count): """ displays x=123 with covariances showing error""" plt.cla() plt.gca().autoscale(tight=True) cov = np.array([[0.03,0], [0,8]]) e = stats.covariance_ellipse (cov) cov2 = np.array([[0.03,0], [0,4]]) e2 = stats.covariance_ellipse (cov2) cov3 = np.array([[12,11.95], [11.95,12]]) e3 = stats.covariance_ellipse (cov3) sigma=[1, 4, 9] if count >= 1: stats.plot_covariance_ellipse ((0,0), ellipse=e, variance=sigma) if count == 2 or count == 3: stats.plot_covariance_ellipse ((5,5), ellipse=e, variance=sigma) if count == 3: stats.plot_covariance_ellipse ((5,5), ellipse=e3, variance=sigma, edgecolor='r') if count == 4: M1 = np.array([[5, 5]]).T m4, cov4 = stats.multivariate_multiply(M1, cov2, M1, cov3) e4 = stats.covariance_ellipse (cov4) stats.plot_covariance_ellipse ((5,5), ellipse=e, variance=sigma, alpha=0.25) stats.plot_covariance_ellipse ((5,5), ellipse=e3, variance=sigma, edgecolor='r', alpha=0.25) stats.plot_covariance_ellipse (m4[:,0], ellipse=e4, variance=sigma) plt.ylim((-9, 16)) #plt.ylim([0,11]) #plt.xticks(np.arange(1,4,1)) plt.xlabel("Position") plt.ylabel("Velocity") plt.show()
def do_plot_test(): import matplotlib.pyplot as plt from numpy.random import multivariate_normal as mnormal from filterpy.stats import covariance_ellipse, plot_covariance p = np.array([[32, 15], [15., 40.]]) x, y = mnormal(mean=(0, 0), cov=p, size=5000).T sd = 2 a, w, h = covariance_ellipse(p, sd) print(np.degrees(a), w, h) count = 0 color = [] for i in range(len(x)): if _is_inside_ellipse(x[i], y[i], 0, 0, a, w, h): color.append('b') count += 1 else: color.append('r') plt.scatter(x, y, alpha=0.2, c=color) plt.axis('equal') plot_covariance(mean=(0., 0.), cov=p, std=[1, 2, 3], alpha=0.3, facecolor='none') print(count / len(x))
def do_plot_test(): import matplotlib.pyplot as plt from numpy.random import multivariate_normal as mnormal from filterpy.stats import covariance_ellipse, plot_covariance p = np.array([[32, 15], [15., 40.]]) x, y = mnormal(mean=(0, 0), cov=p, size=5000).T sd = 2 a, w, h = covariance_ellipse(p, sd) print(np.degrees(a), w, h) count = 0 color = [] for i in range(len(x)): if _is_inside_ellipse(x[i], y[i], 0, 0, a, w, h): color.append('b') count += 1 else: color.append('r') plt.scatter(x, y, alpha=0.2, c=color) plt.axis('equal') plot_covariance(mean=(0., 0.), cov=p, std=[1,2,3], alpha=0.3, facecolor='none') print(count / len(x))
def show_x_with_unobserved(): """ shows x=1,2,3 with velocity superimposed on top """ # plot velocity sigma=[0.5,1.,1.5,2] cov = np.array([[1,1],[1,1.1]]) stats.plot_covariance_ellipse ((2,2), cov=cov, variance=sigma, axis_equal=False) # plot positions cov = np.array([[0.003,0], [0,12]]) sigma=[0.5,1.,1.5,2] e = stats.covariance_ellipse (cov) stats.plot_covariance_ellipse ((1,1), ellipse=e, variance=sigma, axis_equal=False) stats.plot_covariance_ellipse ((2,1), ellipse=e, variance=sigma, axis_equal=False) stats.plot_covariance_ellipse ((3,1), ellipse=e, variance=sigma, axis_equal=False) # plot intersection cirle isct = Ellipse(xy=(2,2), width=.2, height=1.2, edgecolor='r', fc='None', lw=4) plt.gca().add_artist(isct) plt.ylim([0,11]) plt.xlim([0,4]) plt.xticks(np.arange(1,4,1)) plt.xlabel("Position") plt.ylabel("Time") plt.show()
def plot_covariance( mean, cov=None, variance=1.0, std=None, interval=None, ellipse=None, title=None, axis_equal=False, show_semiaxis=False, show_center=True, facecolor=None, edgecolor=None, fc='none', ec='#004080', alpha=1.0, xlim=None, ylim=None, ls='solid',ax=None): "filterpy.stats covariance ellipse plot function with added parameter for custom axis" from matplotlib.patches import Ellipse import matplotlib.pyplot as plt if cov is not None and ellipse is not None: raise ValueError('You cannot specify both cov and ellipse') if cov is None and ellipse is None: raise ValueError('Specify one of cov or ellipse') if facecolor is None: facecolor = fc if edgecolor is None: edgecolor = ec if cov is not None: ellipse = covariance_ellipse(cov) if axis_equal: plt.axis('equal') if title is not None: plt.title(title) angle = np.degrees(ellipse[0]) width = ellipse[1] * 2. height = ellipse[2] * 2. std = _std_tuple_of(variance, std, interval) for sd in std: e = Ellipse(xy=mean, width=sd*width, height=sd*height, angle=angle, facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, lw=2, ls=ls) ax.add_patch(e) x, y = mean if show_center: ax.scatter(x, y, marker='+', color=edgecolor) if show_semiaxis: a = ellipse[0] h, w = height/4, width/4 ax.plot([x, x+ h*cos(a+np.pi/2)], [y, y + h*sin(a+np.pi/2)]) ax.plot([x, x+ w*cos(a)], [y, y + w*sin(a)])
def plot_3d_sampled_covariance(mean, cov): """ plots a 2x2 covariance matrix positioned at mean. mean will be plotted in x and y, and the probability in the z axis. Parameters ---------- mean : 2x1 tuple-like object mean for x and y coordinates. For example (2.3, 7.5) cov : 2x2 nd.array the covariance matrix """ # compute width and height of covariance ellipse so we can choose # appropriate ranges for x and y o,w,h = stats.covariance_ellipse(cov,3) # rotate width and height to x,y axis wx = abs(w*np.cos(o) + h*np.sin(o))*1.2 wy = abs(h*np.cos(o) - w*np.sin(o))*1.2 # ensure axis are of the same size so everything is plotted with the same # scale if wx > wy: w = wx else: w = wy minx = mean[0] - w maxx = mean[0] + w miny = mean[1] - w maxy = mean[1] + w count = 1000 x,y = multivariate_normal(mean=mean, cov=cov, size=count).T xs = np.arange(minx, maxx, (maxx-minx)/40.) ys = np.arange(miny, maxy, (maxy-miny)/40.) xv, yv = np.meshgrid (xs, ys) zs = np.array([100.* stats.multivariate_gaussian(np.array([xx,yy]),mean,cov) \ for xx,yy in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) ax = plt.figure().add_subplot(111, projection='3d') ax.scatter(x,y, [0]*count, marker='.') ax.set_xlabel('X') ax.set_ylabel('Y') ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.autumn) ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.BuGn)
def plot_3d_sampled_covariance(mean, cov): """ plots a 2x2 covariance matrix positioned at mean. mean will be plotted in x and y, and the probability in the z axis. Parameters ---------- mean : 2x1 tuple-like object mean for x and y coordinates. For example (2.3, 7.5) cov : 2x2 nd.array the covariance matrix """ # compute width and height of covariance ellipse so we can choose # appropriate ranges for x and y o, w, h = stats.covariance_ellipse(cov, 3) # rotate width and height to x,y axis wx = abs(w * np.cos(o) + h * np.sin(o)) * 1.2 wy = abs(h * np.cos(o) - w * np.sin(o)) * 1.2 # ensure axis are of the same size so everything is plotted with the same # scale if wx > wy: w = wx else: w = wy minx = mean[0] - w maxx = mean[0] + w miny = mean[1] - w maxy = mean[1] + w count = 1000 x, y = multivariate_normal(mean=mean, cov=cov, size=count).T xs = np.arange(minx, maxx, (maxx - minx) / 40.) ys = np.arange(miny, maxy, (maxy - miny) / 40.) xv, yv = np.meshgrid(xs, ys) zs = np.array([100.* stats.multivariate_gaussian(np.array([xx,yy]),mean,cov) \ for xx,yy in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) ax = plt.gcf().add_subplot(111, projection='3d') ax.scatter(x, y, [0] * count, marker='.') ax.set_xlabel('X') ax.set_ylabel('Y') x = mean[0] zs = np.array([ 100. * stats.multivariate_gaussian(np.array([x, y]), mean, cov) for _, y in zip(np.ravel(xv), np.ravel(yv)) ]) zv = zs.reshape(xv.shape) ax.contour(xv, yv, zv, zdir='x', offset=minx - 1, cmap=cm.binary) y = mean[1] zs = np.array([ 100. * stats.multivariate_gaussian(np.array([x, y]), mean, cov) for x, _ in zip(np.ravel(xv), np.ravel(yv)) ]) zv = zs.reshape(xv.shape) ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.binary)
def plot_3d_covariance(mean, cov): """ plots a 2x2 covariance matrix positioned at mean. mean will be plotted in x and y, and the probability in the z axis. Parameters ---------- mean : 2x1 tuple-like object mean for x and y coordinates. For example (2.3, 7.5) cov : 2x2 nd.array the covariance matrix """ # compute width and height of covariance ellipse so we can choose # appropriate ranges for x and y o,w,h = stats.covariance_ellipse(cov,3) # rotate width and height to x,y axis wx = abs(w*np.cos(o) + h*np.sin(o))*1.2 wy = abs(h*np.cos(o) - w*np.sin(o))*1.2 # ensure axis are of the same size so everything is plotted with the same # scale if wx > wy: w = wx else: w = wy minx = mean[0] - w maxx = mean[0] + w miny = mean[1] - w maxy = mean[1] + w xs = np.arange(minx, maxx, (maxx-minx)/40.) ys = np.arange(miny, maxy, (maxy-miny)/40.) xv, yv = np.meshgrid(xs, ys) zs = np.array([100.* stats.multivariate_gaussian(np.array([x,y]),mean,cov) \ for x, y in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) maxz = np.max(zs) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #ax = plt.gca(projection='3d') ax.plot_surface(xv, yv, zv, rstride=1, cstride=1, cmap=cm.autumn) ax.set_xlabel('X') ax.set_ylabel('Y') # For unknown reasons this started failing in Jupyter notebook when # using `%matplotlib inline` magic. Still works fine in IPython or when # `%matplotlib notebook` magic is used. x = mean[0] zs = np.array([100.* stats.multivariate_gaussian(np.array([x, y]),mean,cov) for _, y in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) try: pass #ax.contour(xv, yv, zv, zdir='x', offset=minx-1, cmap=cm.binary) except: pass y = mean[1] zs = np.array([100.* stats.multivariate_gaussian(np.array([x, y]),mean,cov) for x, _ in zip(np.ravel(xv), np.ravel(yv))]) zv = zs.reshape(xv.shape) try: pass #ax.contour(xv, yv, zv, zdir='y', offset=maxy, cmap=cm.binary) except: pass
def show_x_error_chart(count): """ displays x=123 with covariances showing error""" plt.cla() plt.gca().autoscale(tight=True) cov = np.array([[0.1, 0], [0, 8]]) pos_ellipse = stats.covariance_ellipse(cov) cov2 = np.array([[0.1, 0], [0, 4]]) cov3 = np.array([[12, 11.95], [11.95, 12]]) vel_ellipse = stats.covariance_ellipse(cov3) sigma = [1, 4, 9] if count < 4: stats.plot_covariance_ellipse((0, 0), ellipse=pos_ellipse, variance=sigma) if count == 2: stats.plot_covariance_ellipse((0, 0), ellipse=vel_ellipse, variance=sigma, edgecolor='r') if count == 3: stats.plot_covariance_ellipse((5, 5), ellipse=pos_ellipse, variance=sigma) stats.plot_covariance_ellipse((0, 0), ellipse=vel_ellipse, variance=sigma, edgecolor='r') if count == 4: M0 = np.array([[0, 0]]).T M1 = np.array([[5, 5]]).T _, cov4 = stats.multivariate_multiply(M0, cov2, M1, cov3) e4 = stats.covariance_ellipse(cov4) stats.plot_covariance_ellipse((0, 0), ellipse=pos_ellipse, variance=sigma, alpha=0.25) stats.plot_covariance_ellipse((5, 5), ellipse=pos_ellipse, variance=sigma, alpha=0.25) stats.plot_covariance_ellipse((0, 0), ellipse=vel_ellipse, variance=sigma, edgecolor='r', alpha=0.25) stats.plot_covariance_ellipse((5, 5), ellipse=e4, variance=sigma) plt.ylim((-9, 16)) plt.xlabel("Position") plt.ylabel("Velocity") plt.axis('equal') plt.show()