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: 91872from filterpy.monte_carlo import stratified_resample1import matplotlib as mpl2import matplotlib.pyplot as plt34import numpy as np5from numpy.random import randn, random, uniform, multivariate_normal, seed6#from nonlinear_plots import plot_monte_carlo_mean7import pylab as plt8import scipy.stats9from RobotLocalizationParticleFilter import *10111213class ParticleFilter(object):1415def __init__(self, N, x_dim, y_dim):16self.particles = np.empty((N, 3)) # x, y, heading17self.N = N18self.x_dim = x_dim19self.y_dim = y_dim2021# distribute particles randomly with uniform weight22self.weights = np.empty(N)23self.weights.fill(1./N)24self.particles[:, 0] = uniform(0, x_dim, size=N)25self.particles[:, 1] = uniform(0, y_dim, size=N)26self.particles[:, 2] = uniform(0, 2*np.pi, size=N)272829def predict(self, u, std):30""" move according to control input u with noise std"""3132self.particles[:, 2] += u[0] + randn(self.N) * std[0]33self.particles[:, 2] %= 2 * np.pi3435d = u[1] + randn(self.N)36self.particles[:, 0] += np.cos(self.particles[:, 2]) * d37self.particles[:, 1] += np.sin(self.particles[:, 2]) * d3839self.particles[:, 0:2] += u + randn(self.N, 2) * std404142def weight(self, z, var):43dist = np.sqrt((self.particles[:, 0] - z[0])**2 +44(self.particles[:, 1] - z[1])**2)4546# simplification assumes variance is invariant to world projection47n = scipy.stats.norm(0, np.sqrt(var))48prob = n.pdf(dist)4950# particles far from a measurement will give us 0.0 for a probability51# due to floating point limits. Once we hit zero we can never recover,52# so add some small nonzero value to all points.53prob += 1.e-1254self.weights += prob55self.weights /= sum(self.weights) # normalize565758def neff(self):59return 1. / np.sum(np.square(self.weights))606162def resample(self):63p = np.zeros((self.N, 3))64w = np.zeros(self.N)6566cumsum = np.cumsum(self.weights)67for i in range(self.N):68index = np.searchsorted(cumsum, random())69p[i] = self.particles[index]70w[i] = self.weights[index]7172self.particles = p73self.weights = w / np.sum(w)747576def estimate(self):77""" returns mean and variance """78pos = self.particles[:, 0:2]79mu = np.average(pos, weights=self.weights, axis=0)80var = np.average((pos - mu)**2, weights=self.weights, axis=0)8182return mu, var838485def plot_random_pd():86def norm(x, x0, sigma):87return np.exp(-0.5 * (x - x0) ** 2 / sigma ** 2)888990def sigmoid(x, x0, alpha):91return 1. / (1. + np.exp(- (x - x0) / alpha))9293x = np.linspace(0, 1, 100)94y2 = (0.1 * np.sin(norm(x, 0.2, 0.05)) + 0.25 * norm(x, 0.6, 0.05) +95.5*norm(x, .5, .08) +96np.sqrt(norm(x, 0.8, 0.06)) +0.1 * (1 - sigmoid(x, 0.45, 0.15)))97with plt.xkcd():98#plt.setp(plt.gca().get_xticklabels(), visible=False)99#plt.setp(plt.gca().get_yticklabels(), visible=False)100plt.axes(xticks=[], yticks=[], frameon=False)101plt.plot(x, y2)102103104def plot_monte_carlo_ukf():105106def f(x,y):107return x+y, .1*x**2 + y*y108109mean = (0, 0)110p = np.array([[32, 15], [15., 40.]])111112# Compute linearized mean113mean_fx = f(*mean)114115#generate random points116xs, ys = multivariate_normal(mean=mean, cov=p, size=3000).T117fxs, fys = f(xs, ys)118119plt.subplot(121)120plt.gca().grid(b=False)121122plt.scatter(xs, ys, marker='.', alpha=.2, color='k')123plt.xlim(-25, 25)124plt.ylim(-25, 25)125126plt.subplot(122)127plt.gca().grid(b=False)128129plt.scatter(fxs, fys, marker='.', alpha=0.2, color='k')130131plt.ylim([-10, 200])132plt.xlim([-100, 100])133plt.show()134135136def plot_pf(pf, xlim=100, ylim=100, weights=True):137138if weights:139a = plt.subplot(221)140a.cla()141142plt.xlim(0, ylim)143#plt.ylim(0, 1)144a.set_yticklabels('')145plt.scatter(pf.particles[:, 0], pf.weights, marker='.', s=1, color='k')146a.set_ylim(bottom=0)147148a = plt.subplot(224)149a.cla()150a.set_xticklabels('')151plt.scatter(pf.weights, pf.particles[:, 1], marker='.', s=1, color='k')152plt.ylim(0, xlim)153a.set_xlim(left=0)154#plt.xlim(0, 1)155156a = plt.subplot(223)157a.cla()158159else:160plt.cla()161plt.scatter(pf.particles[:, 0], pf.particles[:, 1], marker='.', s=1, color='k')162plt.xlim(0, xlim)163plt.ylim(0, ylim)164165166def Gaussian(mu, sigma, x):167168# calculates the probability of x for 1-dim Gaussian with mean mu and var. sigma169g = (np.exp(-((mu - x) ** 2) / (sigma ** 2) / 2.0) /170np.sqrt(2.0 * np.pi * (sigma ** 2)))171for i in range(len(g)):172g[i] = max(g[i], 1.e-29)173174return g175176177def test_gaussian(N):178for i in range(N):179mean, std, x = randn(3)180std = abs(std)181182d = Gaussian(mean, std, x) - scipy.stats.norm(mean, std).pdf(x)183assert abs(d) < 1.e-8, "{}, {}, {}, {}, {}, {}".format(d, mean, std, x, Gaussian(mean, std, x), scipy.stats.norm(mean, std).pdf(x))184185186def show_two_pf_plots():187""" Displays results of PF after 1 and 10 iterations for the book.188Note the book says this solves the full robot localization problem.189It doesn't bother simulating landmarks as this is just an illustration.190"""191192seed(1234)193N = 3000194pf = ParticleFilter(N, 20, 20)195z = np.array([20, 20])196197#plot(pf, weights=False)198199for x in range(10):200201z[0] = x+1 + randn()*0.3202z[1] = x+1 + randn()*0.3203204pf.predict((1,1), (0.2, 0.2))205pf.weight(z=z, var=.8)206pf.resample()207208if x == 0:209plt.subplot(121)210elif x == 9:211plt.subplot(122)212213if x == 0 or x == 9:214mu, var = pf.estimate()215plot_pf(pf, 20, 20, weights=False)216if x == 0:217plt.scatter(mu[0], mu[1], color='g', s=100)218plt.scatter(x+1, x+1, marker='x', color='r', s=180, lw=3)219else:220plt.scatter(mu[0], mu[1], color='g', s=100, label="PF")221plt.scatter([x+1], [x+1], marker='x', color='r', s=180, label="True", lw=3)222plt.legend(scatterpoints=1)223plt.tight_layout()224225226def test_pf():227228#seed(1234)229N = 10000230R = .2231landmarks = [[-1, 2], [20,4], [10,30], [18,25]]232#landmarks = [[-1, 2], [2,4]]233234pf = RobotLocalizationParticleFilter(N, 20, 20, landmarks, R)235236plot_pf(pf, 20, 20, weights=False)237238dt = .01239plt.pause(dt)240241for x in range(18):242243zs = []244pos=(x+3, x+3)245246for landmark in landmarks:247d = np.sqrt((landmark[0]-pos[0])**2 + (landmark[1]-pos[1])**2)248zs.append(d + randn()*R)249250pf.predict((0.01, 1.414), (.2, .05))251pf.update(z=zs)252pf.resample()253#print(x, np.array(list(zip(pf.particles, pf.weights))))254255mu, var = pf.estimate()256plot_pf(pf, 20, 20, weights=False)257plt.plot(pos[0], pos[1], marker='*', color='r', ms=10)258plt.scatter(mu[0], mu[1], color='g', s=100)259plt.tight_layout()260plt.pause(dt)261262263def test_pf2():264N = 1000265sensor_std_err = .2266landmarks = [[-1, 2], [20,4], [-20,6], [18,25]]267268pf = RobotLocalizationParticleFilter(N, 20, 20, landmarks, sensor_std_err)269270xs = []271for x in range(18):272zs = []273pos=(x+1, x+1)274275for landmark in landmarks:276d = np.sqrt((landmark[0]-pos[0])**2 + (landmark[1]-pos[1])**2)277zs.append(d + randn()*sensor_std_err)278279# move diagonally forward to (x+1, x+1)280pf.predict((0.00, 1.414), (.2, .05))281pf.update(z=zs)282pf.resample()283284mu, var = pf.estimate()285xs.append(mu)286287xs = np.array(xs)288plt.plot(xs[:, 0], xs[:, 1])289plt.show()290291292def plot_cumsum(a):293294N = len(a)295296cmap = mpl.colors.ListedColormap([[0., .4, 1.],297[0., .8, 1.],298[1., .8, 0.],299[1., .4, 0.]]*(int(N/4) + 1))300cumsum = np.cumsum(np.asarray(a) / np.sum(a))301cumsum = np.insert(cumsum, 0, 0)302303fig = plt.figure(figsize=(6,3))304ax = fig.add_axes([0.05, 0.475, 0.9, 0.15])305norm = mpl.colors.BoundaryNorm(cumsum, cmap.N)306bar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,307norm=norm,308drawedges=False,309spacing='proportional',310orientation='horizontal')311if N > 10:312bar.set_ticks([])313plt.show()314315316def plot_stratified_resample(a):317N = len(a)318319cmap = mpl.colors.ListedColormap([[0., .4, 1.],320[0., .8, 1.],321[1., .8, 0.],322[1., .4, 0.]]*(int(N/4) + 1))323cumsum = np.cumsum(np.asarray(a) / np.sum(a))324cumsum = np.insert(cumsum, 0, 0)325326fig = plt.figure(figsize=(6,3))327ax = fig.add_axes([0.05, 0.475, 0.9, 0.15])328norm = mpl.colors.BoundaryNorm(cumsum, cmap.N)329bar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,330norm=norm,331drawedges=False,332spacing='proportional',333orientation='horizontal')334xs = np.linspace(0., 1.-1./N, N)335ax.vlines(xs, 0, 1, lw=2)336337# make N subdivisions, and chose a random position within each one338b = (random(N) + range(N)) / N339plt.scatter(b, [.5]*len(b), s=60, facecolor='k', edgecolor='k')340bar.set_ticks([])341plt.title('stratified resampling')342plt.show()343344345def plot_systematic_resample(a):346N = len(a)347348cmap = mpl.colors.ListedColormap([[0., .4, 1.],349[0., .8, 1.],350[1., .8, 0.],351[1., .4, 0.]]*(int(N/4) + 1))352cumsum = np.cumsum(np.asarray(a) / np.sum(a))353cumsum = np.insert(cumsum, 0, 0)354355fig = plt.figure(figsize=(6,3))356ax = fig.add_axes([0.05, 0.475, 0.9, 0.15])357norm = mpl.colors.BoundaryNorm(cumsum, cmap.N)358bar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,359norm=norm,360drawedges=False,361spacing='proportional',362orientation='horizontal')363xs = np.linspace(0., 1.-1./N, N)364ax.vlines(xs, 0, 1, lw=2)365366# make N subdivisions, and chose a random position within each one367b = (random() + np.array(range(N))) / N368plt.scatter(b, [.5]*len(b), s=60, facecolor='k', edgecolor='k')369bar.set_ticks([])370plt.title('systematic resampling')371plt.show()372373374def plot_multinomial_resample(a):375N = len(a)376377cmap = mpl.colors.ListedColormap([[0., .4, 1.],378[0., .8, 1.],379[1., .8, 0.],380[1., .4, 0.]]*(int(N/4) + 1))381cumsum = np.cumsum(np.asarray(a) / np.sum(a))382cumsum = np.insert(cumsum, 0, 0)383384fig = plt.figure(figsize=(6,3))385ax = fig.add_axes([0.05, 0.475, 0.9, 0.15])386norm = mpl.colors.BoundaryNorm(cumsum, cmap.N)387bar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,388norm=norm,389drawedges=False,390spacing='proportional',391orientation='horizontal')392393# make N subdivisions, and chose a random position within each one394b = random(N)395plt.scatter(b, [.5]*len(b), s=60, facecolor='k', edgecolor='k')396bar.set_ticks([])397plt.title('multinomial resampling')398plt.show()399400401def plot_residual_resample(a):402N = len(a)403404a_norm = np.asarray(a) / np.sum(a)405cumsum = np.cumsum(a_norm)406cumsum = np.insert(cumsum, 0, 0)407408cmap = mpl.colors.ListedColormap([[0., .4, 1.],409[0., .8, 1.],410[1., .8, 0.],411[1., .4, 0.]]*(int(N/4) + 1))412413fig = plt.figure(figsize=(6,3))414ax = fig.add_axes([0.05, 0.475, 0.9, 0.15])415norm = mpl.colors.BoundaryNorm(cumsum, cmap.N)416bar = mpl.colorbar.ColorbarBase(ax, cmap=cmap,417norm=norm,418drawedges=False,419spacing='proportional',420orientation='horizontal')421422indexes = residual_resample(a_norm)423bins = np.bincount(indexes)424for i in range(1, N):425n = bins[i-1] # number particles in this sample426if n > 0:427b = np.linspace(cumsum[i-1], cumsum[i], n+2)[1:-1]428plt.scatter(b, [.5]*len(b), s=60, facecolor='k', edgecolor='k')429bar.set_ticks([])430plt.title('residual resampling')431plt.show()432433434if __name__ == '__main__':435plot_residual_resample([.1, .2, .3, .4, .2, .3, .1])436437#example()438#show_two_pf_plots()439440a = [.1, .2, .1, .6]441#plot_cumsum(a)442#test_pf()443444445