Reformat, and changes to work with IPython 6.0

After a new Anaconda install I was getting a lot of minor errors
in the notebooks. I've fixed all of those. Along the ways I altered
the format of the PDF output to exclude the In[] Out[] tags so the
code is indented less. I also altered the font size of the notebooks
to better match fonts in other pages on chrome.

FilterPy was updated to 1.1.0, and this check in requires that release
at the minimum.
This commit is contained in:
Roger Labbe
2017-11-18 17:14:31 -08:00
parent 5ab83047d9
commit 850c7fc0dd
35 changed files with 2949 additions and 3524 deletions

View File

@@ -1,27 +1,11 @@
{
"lines.linewidth": 2.0,
"lines.linewidth": 1.5,
"patch.linewidth": 0.5,
"legend.fancybox": true,
"axes.color_cycle": [
"#6d904f",
"#013afe",
"#202020",
"#fc4f30",
"#e5ae38",
"#A60628",
"#30a2da",
"#008080",
"#7A68A6",
"#CF4457",
"#188487",
"#E24A33"
],
"axes.facecolor": "#ffffff",
"axes.labelsize": "large",
"axes.axisbelow": true,
"axes.grid": true,
"patch.edgecolor": "#f0f0f0",
"axes.titlesize": "x-large",
"examples.directory": "",
"figure.facecolor": "#ffffff",
"grid.linestyle": "-",
@@ -33,8 +17,7 @@
"ytick.major.size": 0,
"ytick.minor.size": 0,
"axes.linewidth": 3.0,
"font.size":14.0,
"lines.linewidth": 3,
"font.size":12.0,
"lines.solid_capstyle": "butt",
"savefig.edgecolor": "#f0f0f0",
"savefig.facecolor": "#f0f0f0",

View File

@@ -22,7 +22,9 @@ import matplotlib.pyplot as plt
import numpy as np
def plot_track_and_residuals(t, xs, z_xs, res):
def plot_track_and_residuals(dt, xs, z_xs, res):
assert np.isscalar(dt)
t = np.arange(0, len(xs)*dt, dt)
plt.subplot(121)
if z_xs is not None:
bp.plot_measurements(t, z_xs, label='z')
@@ -45,8 +47,7 @@ def plot_markov_chain():
fig = plt.figure(figsize=(4,4), facecolor='w')
ax = plt.axes((0, 0, 1, 1),
xticks=[], yticks=[], frameon=False)
#ax.set_xlim(0, 10)
#ax.set_ylim(0, 10)
box_bg = '#DDDDDD'
kf1c = Circle((4,5), 0.5, fc=box_bg)
@@ -99,7 +100,6 @@ def plot_markov_chain():
plt.axis('equal')
plt.show()
bp.end_interactive(fig)
def turning_target(N=600, turn_start=400):

View File

@@ -33,25 +33,25 @@ except:
pass
def equal_axis():
pylab.rcParams['figure.figsize'] = 10,10
def equal_axis(sz=10):
pylab.rcParams['figure.figsize'] = sz, sz
plt.axis('equal')
def reset_axis():
pylab.rcParams['figure.figsize'] = 9, 3
pylab.rcParams['figure.figsize'] = 8, 3
def reset_figsize():
pylab.rcParams['figure.figsize'] = 9, 4
pylab.rcParams['figure.figsize'] = 8, 3
def set_figsize(x=9, y=4):
def set_figsize(x=8, y=3):
pylab.rcParams['figure.figsize'] = x, y
@contextmanager
def figsize(x=9, y=4):
def figsize(x=8, y=3):
"""Temporarily set the figure size using 'with figsize(a,b):'"""
size = pylab.rcParams['figure.figsize']
@@ -100,18 +100,19 @@ def interactive_plot(close=True, fig=None):
end_interactive(fig)
def plot_errorbars(bars, xlims, ylims=(0, 2)):
def plot_errorbars(bars, xlims, ylims=(-1, 1)):
i = 0.0
for bar in bars:
plt.errorbar([bar[0]], [i], xerr=[bar[1]], fmt='o', label=bar[2] , capthick=2, capsize=10)
i += 0.2
with figsize(y=2):
i = 0.0
for bar in bars:
plt.errorbar([bar[0]], [i], xerr=[bar[1]], fmt='o', label=bar[2] , capthick=2, capsize=10)
i += 0.2
plt.ylim(*ylims)
plt.xlim(xlims[0], xlims[1])
show_legend()
plt.gca().axes.yaxis.set_ticks([])
plt.show()
plt.ylim(*ylims)
plt.xlim(xlims[0], xlims[1])
show_legend()
plt.gca().axes.yaxis.set_ticks([])
plt.show()
def plot_errorbar1():
@@ -237,12 +238,13 @@ def plot_estimate_chart_2():
plt.scatter ([1], [164.2], c='b',s=128)
plt.scatter ([1], [159], c='r', s=128)
plt.text (1.0, 158.8, "prediction ($x_t)$", ha='center',va='top',fontsize=18,color='red')
plt.text (1.0, 164.4, "measurement ($z$)",ha='center',va='bottom',fontsize=18,color='blue')
plt.text (0, 157.8, "estimate ($\hat{x}_{t-1}$)", ha='center', va='top',fontsize=18)
plt.text (1.0, 164.4, "measurement ($z_t$)",ha='center',va='bottom',fontsize=18,color='blue')
plt.text (0.0, 159.8, "estimate ($\hat{x}_{t-1}$)", ha='left', va='top',fontsize=18)
plt.xlabel('day')
plt.ylabel('weight (lbs)')
ax.xaxis.grid(True, which="major", linestyle='dotted')
ax.yaxis.grid(True, which="major", linestyle='dotted')
plt.ylim(157, 164.5)
def plot_estimate_chart_3():
@@ -263,16 +265,16 @@ def plot_estimate_chart_3():
plt.scatter ([1], [159], c='r', s=128)
plt.text (1.0, 158.8, "prediction ($x_t)$", ha='center',va='top',fontsize=18,color='red')
plt.text (1.0, 164.4, "measurement ($z$)",ha='center',va='bottom',fontsize=18,color='blue')
plt.text (0, 157.8, "estimate ($\hat{x}_{t-1}$)", ha='center', va='top',fontsize=18)
plt.text (0, 159.8, "estimate ($\hat{x}_{t-1}$)", ha='left', va='top',fontsize=18)
plt.text (0.95, est_y, "new estimate ($\hat{x}_{t}$)", ha='right', va='center',fontsize=18)
plt.xlabel('day')
plt.ylabel('weight (lbs)')
ax.xaxis.grid(True, which="major", linestyle='dotted')
ax.yaxis.grid(True, which="major", linestyle='dotted')
plt.ylim(157, 164.5)
def create_predict_update_chart(box_bg = '#CCCCCC',
def predict_update_chart(box_bg = '#CCCCCC',
arrow1 = '#88CCFF',
arrow2 = '#88FF88'):
plt.figure(figsize=(4,4), facecolor='w')
@@ -334,7 +336,7 @@ def create_predict_update_chart(box_bg = '#CCCCCC',
plt.text (4, 3.7,'State Estimate ($\mathbf{\hat{x}_k}$)',
ha='center', va='center', fontsize=14)
plt.axis('equal')
plt.xlim(2,10)
plt.show()
def show_residual_chart(show_eq=True, show_H=False):
@@ -417,7 +419,7 @@ def bar_plot(pos, x=None, ylim=(0,1), title=None, c='#30a2da',
ax.bar(x, pos, color=c, **kwargs)
if ylim:
plt.ylim(ylim)
plt.xticks(np.asarray(x)+0.4, x)
plt.xticks(np.asarray(x), x)
if title is not None:
plt.title(title)
@@ -490,11 +492,14 @@ def plot_kf_output(xs, filter_xs, zs, title=None, aspect_equal=True):
plt.show()
def plot_measurements(xs, ys=None, color='k', lw=2, label='Measurements',
def plot_measurements(xs, ys=None, dt=None, color='k', lw=1, label='Measurements',
lines=False, **kwargs):
""" Helper function to give a consistant way to display
measurements in the book.
"""
if ys is None and dt is not None:
ys = xs
xs = np.arange(0, len(ys)*dt, dt)
plt.autoscale(tight=True)
if lines:
@@ -525,17 +530,23 @@ def plot_residual_limits(Ps, stds=1.):
facecolor='#ffff00', alpha=0.3)
def plot_track(xs, ys=None, label='Track', c='k', lw=2, **kwargs):
def plot_track(xs, ys=None, dt=None, label='Track', c='k', lw=2, **kwargs):
if ys is None and dt is not None:
ys = xs
xs = np.arange(0, len(ys)*dt, dt)
if ys is not None:
return plt.plot(xs, ys, color=c, lw=lw, ls=':', label=label, **kwargs)
else:
return plt.plot(xs, color=c, lw=lw, ls=':', label=label, **kwargs)
def plot_filter(xs, ys=None, c='#013afe', label='Filter', var=None, **kwargs):
def plot_filter(xs, ys=None, dt=None, c='C0', label='Filter', var=None, **kwargs):
""" plot result of KF with color `c`, optionally displaying the variance
of `xs`. Returns the list of lines generated by plt.plot()"""
if ys is None and dt is not None:
ys = xs
xs = np.arange(0, len(ys) * dt, dt)
if ys is None:
ys = xs
xs = range(len(ys))
@@ -622,7 +633,7 @@ if __name__ == "__main__":
plot_estimate_chart_1()
plot_estimate_chart_2()
plot_estimate_chart_3()
create_predict_update_chart()
predict_update_chart()
show_residual_chart()
show_residual_chart(True, True)
plt.close('all')

View File

@@ -2,24 +2,6 @@
@import url('http://fonts.googleapis.com/css?family=Source+Code+Pro');
@import url('http://fonts.googleapis.com/css?family=Lora');
//@import url('http://fonts.googleapis.com/css?family=Open+Sans');
//@import url('http://fonts.googleapis.com/css?family=Vollkorn');
//@import url('http://fonts.googleapis.com/css?family=Karla');
//@import url('http://fonts.googleapis.com/css?family=Poppins');
//@import url('http://fonts.googleapis.com/css?family=Arimo');
//@import url('http://fonts.googleapis.com/css?family=Roboto');
//@import url('http://fonts.googleapis.com/css?family=Lato');
//@import url('http://fonts.googleapis.com/css?family=Domine');
//@import url('http://fonts.googleapis.com/css?family=Chivo');
//@import url('http://fonts.googleapis.com/css?family=Cardo');
//@import url('http://fonts.googleapis.com/css?family=Arvo');
//@import url('http://fonts.googleapis.com/css?family=Crimson+Text');
//@import url('http://fonts.googleapis.com/css?family=Ubuntu');
//@import url('http://fonts.googleapis.com/css?family=Fontin');
//@import url('http://fonts.googleapis.com/css?family=Raleway');
//@import url('http://fonts.googleapis.com/css?family=Merriweather');
.CodeMirror pre {
font-family: 'Source Code Pro', Consolas, monocco, monospace;
}
@@ -30,24 +12,8 @@
}
div.text_cell_render{
font-family: 'Lora';
//font-family: 'Open Sans';
//font-family: 'Karla',verdana,arial,sans-serif;
//font-family: 'Roboto',verdana,arial,sans-serif;
//font-family: 'Lato',verdana,arial,sans-serif;
//font-family: 'Domine',verdana,arial,sans-serif;
//font-family: 'Chivo',verdana,arial,sans-serif;
//font-family: 'Cardo',verdana,arial,sans-serif;
//font-family: 'Arvo',verdana,arial,sans-serif;
//font-family: 'Poppins',verdana,arial,sans-serif;
//font-family: 'Ubuntu',verdana,arial,sans-serif;
//font-family: 'Fontin',verdana,arial,sans-serif;
//font-family: 'Raleway',verdana,arial,sans-serif;
//font-family: 'Merriweather',verdana,arial,sans-serif;
//font-family: 'Crimson Text', verdana,arial,sans-serif;
//font-family: verdana,arial,sans-serif;
//font-family: arial,sans-serif;
line-height: 125%;
font-size: 130%;
font-size: 100%;
text-align: justify;
text-justify:inter-word;
}
@@ -55,8 +21,7 @@
background: transparent;
color: #000000;
font-weight: 400;
font-size: 12pt;
//font-style: bold;
font-size: 11pt;
font-family: 'Source Code Pro', Consolas, monocco, monospace;
}
h1 {
@@ -137,13 +102,13 @@
}
div.output_subarea.output_text.output_pyout {
overflow-x: auto;
overflow-y: scroll;
max-height: 50000px;
overflow-y: visible;
max-height: 5000000px;
}
div.output_subarea.output_stream.output_stdout.output_text {
overflow-x: auto;
overflow-y: scroll;
max-height: 50000px;
overflow-y: visible;
max-height: 5000000px;
}
div.output_wrapper{
margin-top:0.2em;

View File

@@ -201,8 +201,7 @@ def show_radar_chart():
plt.ylim([0.5,2.5])
plt.scatter ([1,2],[1,2])
#plt.scatter ([2],[1],marker='o')
ax = plt.axes()
ax = plt.gca()
ax.annotate('', xy=(2,2), xytext=(1,1),
arrowprops=dict(arrowstyle='->', ec='r',shrinkA=3, shrinkB=4))
@@ -239,7 +238,7 @@ def show_linearization():
plt.plot(xs, ys, label='$f(x)=x^22x$')
plt.plot([1, 2], [y(1), y(2)], color='k', ls='--', label='linearization')
plt.axes().axvline(1.5, lw=1, c='k')
plt.gca().axvline(1.5, lw=1, c='k')
plt.xlim(0, 2)
plt.ylim([-1.5, 0.0])
plt.title('Linearization of $f(x)$ at $x=1.5$')

View File

@@ -34,6 +34,7 @@ def plot_height_std(x, lw=10):
facecolor='yellow', alpha=0.4)
plt.xlabel('student')
plt.ylabel('height (m)')
plt.show()
def plot_correlated_data(X, Y, xlabel=None,
@@ -54,11 +55,11 @@ def plot_correlated_data(X, Y, xlabel=None,
plt.gca().set_aspect('equal')
plt.show()
def plot_gaussian (mu, variance,
mu_line=False,
xlim=None,
xlabel=None,
ylabel=None):
def plot_gaussian(mu, variance,
mu_line=False,
xlim=None,
xlabel=None,
ylabel=None):
xs = np.arange(mu-variance*2,mu+variance*2,0.1)
ys = [stats.gaussian (x, mu, variance)*100 for x in xs]
@@ -73,6 +74,7 @@ def plot_gaussian (mu, variance,
plt.ylabel(ylabel)
plt.show()
def display_stddev_plot():
xs = np.arange(10,30,0.1)
var = 8;
@@ -94,7 +96,7 @@ def display_stddev_plot():
plt.plot ([20,20],[0,y],'b')
x = 20+stddev
ax = plt.axes()
ax = plt.gca()
ax.annotate('68%', xy=(20.3, 0.045))
ax.annotate('', xy=(20-stddev,0.04), xytext=(x,0.04),
arrowprops=dict(arrowstyle="<->",

View File

@@ -26,22 +26,18 @@ import time
def plot_gh_results(weights, estimates, predictions, time_step=0):
plt.figure(figsize=(9,4))
n = len(weights)
if time_step > 0:
rng = range(1, n+1)
else:
rng = range(n, n+1)
plt.xlim([-1, n+1])
plt.ylim([156.0, 173])
act, = book_plots.plot_track([0, n], [160, 160+n], c='k')
plt.gcf().canvas.draw()
for i in rng:
xs = list(range(i+1))
#plt.cla()
pred, = book_plots.plot_track(xs[1:], predictions[:i], c='r', marker='v')
plt.xlim([-1, n+1])
plt.ylim([156.0, 173])
@@ -62,6 +58,8 @@ def plot_gh_results(weights, estimates, predictions, time_step=0):
plt.legend([act, scale, est, pred], ['Actual Weight', 'Measurement', 'Estimates', 'Predictions'], loc=4)
book_plots.set_labels(x='day', y='weight (lbs)')
plt.xlim([-1, n+1])
plt.ylim([156.0, 173])

View File

@@ -149,7 +149,7 @@ def show_position_prediction_chart():
plt.yticks(np.arange(1,5,1))
plt.scatter ([4], [4], s=128, color='#8EBA42')
ax = plt.axes()
ax = plt.gca()
ax.annotate('', xy=(4,4), xytext=(3,3),
arrowprops=dict(arrowstyle='->',
ec='g',

View File

@@ -16,8 +16,7 @@ for more information.
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from filterpy.kalman import MerweScaledSigmaPoints, unscented_transform
from filterpy.stats import multivariate_gaussian
import math
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
@@ -25,8 +24,11 @@ import numpy as np
from numpy.random import normal, multivariate_normal
import scipy.stats
def plot_nonlinear_func(data, f, gaussian, num_bins=300):
from filterpy.kalman import MerweScaledSigmaPoints, unscented_transform
from filterpy.stats import multivariate_gaussian
def plot_nonlinear_func(data, f, gaussian, num_bins=300):
# linearize at mean to simulate EKF
#x = gaussian[0]
@@ -44,11 +46,10 @@ def plot_nonlinear_func(data, f, gaussian, num_bins=300):
in_lims = [x0-in_std*3, x0+in_std*3]
out_lims = [y-std*3, y+std*3]
#plot output
h = np.histogram(ys, num_bins, density=False)
plt.subplot(2,2,4)
plt.plot(h[0], h[1][1:], lw=4, alpha=0.8)
plt.plot(h[0], h[1][1:], lw=2, alpha=0.8)
plt.ylim(out_lims[1], out_lims[0])
plt.gca().xaxis.set_ticklabels([])
plt.title('Output')
@@ -82,15 +83,13 @@ def plot_nonlinear_func(data, f, gaussian, num_bins=300):
h = np.histogram(data, num_bins, density=True)
plt.subplot(2,2,1)
plt.plot(h[1][1:], h[0], lw=4)
plt.plot(h[1][1:], h[0], lw=2)
plt.xlim(in_lims)
plt.gca().yaxis.set_ticklabels([])
plt.title('Input')
plt.show()
import math
def plot_ekf_vs_mc():
def fx(x):
@@ -205,7 +204,6 @@ def test_plot():
plt.plot(h[1][1:], h[0], lw=4)
def plot_bivariate_colormap(xs, ys):
xs = np.asarray(xs)
ys = np.asarray(ys)
@@ -230,17 +228,17 @@ def plot_monte_carlo_mean(xs, ys, f, mean_fx, label, plot_colormap=True):
computed_mean_x = np.average(fxs)
computed_mean_y = np.average(fys)
plt.subplot(121)
plt.gca().grid(b=False)
ax = plt.subplot(121)
ax.grid(b=False)
plot_bivariate_colormap(xs, ys)
plt.scatter(xs, ys, marker='.', alpha=0.02, color='k')
plt.xlim(-20, 20)
plt.ylim(-20, 20)
ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
plt.subplot(122)
plt.gca().grid(b=False)
ax = plt.subplot(122)
ax.grid(b=False)
plt.scatter(fxs, fys, marker='.', alpha=0.02, color='k')
plt.scatter(mean_fx[0], mean_fx[1],
@@ -249,16 +247,15 @@ def plot_monte_carlo_mean(xs, ys, f, mean_fx, label, plot_colormap=True):
marker='*',s=120, c='b', label='Computed Mean')
plot_bivariate_colormap(fxs, fys)
plt.ylim([-10, 200])
plt.xlim([-100, 100])
ax.set_xlim([-100, 100])
ax.set_ylim([-10, 200])
plt.legend(loc='best', scatterpoints=1)
print ('Difference in mean x={:.3f}, y={:.3f}'.format(
computed_mean_x-mean_fx[0], computed_mean_y-mean_fx[1]))
def plot_cov_ellipse_colormap(cov=[[1,1],[1,1]]):
side = np.linspace(-3,3,24)
side = np.linspace(-3, 3, 200)
X,Y = np.meshgrid(side,side)
pos = np.empty(X.shape + (2,))
@@ -271,7 +268,6 @@ def plot_cov_ellipse_colormap(cov=[[1,1],[1,1]]):
plt.show()
def plot_gaussians(xs, ps, x_range, y_range, N):
""" given a list of 2d states (x,y) and 2x2 covariance matrices, produce
a surface plot showing all of the gaussians"""

View File

@@ -111,12 +111,14 @@ def plot_random_pd():
y2 = (0.1 * np.sin(norm(x, 0.2, 0.05)) + 0.25 * norm(x, 0.6, 0.05) +
.5*norm(x, .5, .08) +
np.sqrt(norm(x, 0.8, 0.06)) +0.1 * (1 - sigmoid(x, 0.45, 0.15)))
with plt.xkcd():
#plt.setp(plt.gca().get_xticklabels(), visible=False)
#plt.setp(plt.gca().get_yticklabels(), visible=False)
plt.axes(xticks=[], yticks=[], frameon=False)
plt.plot(x, y2)
plt.ylim([0, max(y2)+.1])
# hack because of bug `with plt.xkcd()` doesn't return context correctly
saved_state = mpl.rcParams.copy()
plt.xkcd()
plt.axes(xticks=[], yticks=[], frameon=False)
plt.plot(x, y2)
plt.ylim([0, max(y2)+.1])
mpl.rcParams.update(saved_state)
def plot_monte_carlo_ukf():

View File

@@ -367,7 +367,7 @@ def plot_scatter_moving_target():
a = actual_angle + randn() * math.radians(1)
xs.append(d*math.cos(a))
ys.append(d*math.sin(a))
plt.scatter(xs, ys)
plt.scatter(xs, ys, c='C0')
plt.axis('equal')
plt.plot([5.5, pos[0]], [6, pos[1]], c='g', linestyle='--')
@@ -419,7 +419,7 @@ def _plot_iscts(pos, sa, sb, N=4):
plt.scatter(xs, ys, c='r', marker='.', alpha=0.5)
plt.scatter(xs_a, ys_a, c='k', edgecolor='k')
plt.scatter(xs_b, ys_b, marker='v', edgecolor=None)
plt.scatter(xs_b, ys_b, marker='v', edgecolor=None, c='C0')
plt.gca().set_aspect('equal')
@@ -430,7 +430,7 @@ def plot_iscts_two_sensors():
sb = [8., 2.]
plt.scatter(*sa, s=200, c='k', marker='v')
plt.scatter(*sb, s=200, marker='s')
plt.scatter(*sb, s=200, marker='s', c='C0')
_plot_iscts(pos, sa, sb, N=4)
plt.subplot(122)
plot_iscts_two_sensors_changed_sensors()