Switched to interactive plots!
Using %matplotlib notebook to render plots. I made the g-h filter chapter work. There is a very good chance I broke the other chapters. Need to push to really find out.
19204
01-g-h-filter.ipynb
@ -28,6 +28,11 @@ import os.path
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
try:
|
||||
import seaborn
|
||||
except:
|
||||
pass
|
||||
|
||||
# version 1.4.3 of matplotlib has a bug that makes
|
||||
# it issue a spurious warning on every plot that
|
||||
# clutters the notebook output
|
||||
@ -56,6 +61,15 @@ def test_filterpy_version():
|
||||
# chapter so the reader can see that they need to update FilterPy.
|
||||
test_filterpy_version()
|
||||
|
||||
pylab.rcParams['figure.max_open_warning'] = 50
|
||||
|
||||
|
||||
def end_interactive(fig):
|
||||
""" end interaction in a plot created with %matplotlib notebook """
|
||||
import time
|
||||
plt.gcf().canvas.draw()
|
||||
time.sleep(0.1)
|
||||
plt.close(fig)
|
||||
|
||||
def equal_axis():
|
||||
pylab.rcParams['figure.figsize'] = 10,10
|
||||
@ -78,6 +92,7 @@ def figsize(x=11, y=4):
|
||||
yield
|
||||
pylab.rcParams['figure.figsize'] = size
|
||||
|
||||
|
||||
@contextmanager
|
||||
def numpy_precision(precision):
|
||||
old = np.get_printoptions()['precision']
|
||||
@ -127,11 +142,15 @@ def load_style(directory = '.', name='code/custom.css'):
|
||||
|
||||
# matplotlib has deprecated the use of axes.color_cycle as of version
|
||||
|
||||
version = [int(version_no) for version_no in matplotlib.__version__.split('.')]
|
||||
if version[0] > 1 or (version[0] == 1 and version[1] >= 5):
|
||||
style["axes.prop_cycle"] = "cycler('color', ['#6d904f','#013afe', '#202020','#fc4f30','#e5ae38','#A60628','#30a2da','#008080','#7A68A6','#CF4457','#188487','#E24A33'])"
|
||||
style.pop("axes.color_cycle", None)
|
||||
plt.rcParams.update(style)
|
||||
try:
|
||||
import seaborn
|
||||
except:
|
||||
version = [int(version_no) for version_no in matplotlib.__version__.split('.')]
|
||||
if version[0] > 1 or (version[0] == 1 and version[1] >= 5):
|
||||
style["axes.prop_cycle"] = "cycler('color', ['#6d904f','#013afe', '#202020','#fc4f30','#e5ae38','#A60628','#30a2da','#008080','#7A68A6','#CF4457','#188487','#E24A33'])"
|
||||
style.pop("axes.color_cycle", None)
|
||||
plt.rcParams.update(style)
|
||||
|
||||
reset_axis ()
|
||||
np.set_printoptions(suppress=True,precision=3, linewidth=70,
|
||||
formatter={'float':lambda x:' {:.3}'.format(x)})
|
||||
|
@ -19,6 +19,37 @@ from __future__ import (absolute_import, division, print_function,
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from contextlib import contextmanager
|
||||
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, '..')
|
||||
from book_format import figsize
|
||||
|
||||
try:
|
||||
import seaborn
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
def end_interactive(fig):
|
||||
""" end interaction in a plot created with %matplotlib notebook """
|
||||
import time
|
||||
plt.gcf().canvas.draw()
|
||||
time.sleep(0.1)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def interactive_plot(close=True, fig=None):
|
||||
if fig is None:
|
||||
fig = plt.figure()
|
||||
yield
|
||||
if close:
|
||||
end_interactive(fig)
|
||||
|
||||
|
||||
def plot_errorbars(bars, xlims, ylims=(0, 2)):
|
||||
|
||||
@ -34,6 +65,240 @@ def plot_errorbars(bars, xlims, ylims=(0, 2)):
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_errorbar1():
|
||||
with figsize(y=2):
|
||||
plt.figure()
|
||||
plot_errorbars([(160, 8, 'A'), (170, 8, 'B')],
|
||||
xlims=(145, 185), ylims=(-1, 1))
|
||||
plt.show()
|
||||
plt.savefig('../figs/gh_errorbar1.png', pad_inches=0.)
|
||||
|
||||
|
||||
def plot_errorbar2():
|
||||
with figsize(y=2):
|
||||
plt.figure()
|
||||
plot_errorbars([(160, 3, 'A'), (170, 9, 'B')],
|
||||
xlims=(145, 185), ylims=(-1, 1))
|
||||
plt.savefig('../figs/gh_errorbar2.png', pad_inches=0.)
|
||||
|
||||
def plot_errorbar3():
|
||||
with figsize(y=2):
|
||||
plt.figure()
|
||||
plot_errorbars([(160, 1, 'A'), (170, 9, 'B')],
|
||||
xlims=(145, 185), ylims=(-1, 1))
|
||||
plt.savefig('../figs/gh_errorbar3.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_hypothesis1():
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
plt.errorbar([1, 2, 3], [170, 161, 169],
|
||||
xerr=0, yerr=10, fmt='bo', capthick=2, capsize=10)
|
||||
|
||||
plt.plot([1, 3], [180, 160], color='g', ls='--')
|
||||
plt.plot([1, 3], [170, 170], color='g', ls='--')
|
||||
plt.plot([1, 3], [160, 175], color='g', ls='--')
|
||||
plt.plot([1, 2, 3], [180, 152, 179], color='g', ls='--')
|
||||
plt.xlim(0,4); plt.ylim(150, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('lbs')
|
||||
plt.tight_layout()
|
||||
plt.savefig('../figs/gh_hypothesis1.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_hypothesis2():
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
plt.errorbar(range(1, 11), [169, 170, 169,171, 170, 171, 169, 170, 169, 170],
|
||||
xerr=0, yerr=6, fmt='bo', capthick=2, capsize=10)
|
||||
plt.plot([1, 10], [169, 170.5], color='g', ls='--')
|
||||
plt.xlim(0, 11); plt.ylim(150, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('lbs')
|
||||
plt.savefig('../figs/gh_hypothesis2.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_hypothesis3():
|
||||
weights = [158.0, 164.2, 160.3, 159.9, 162.1, 164.6,
|
||||
169.6, 167.4, 166.4, 171.0, 171.2, 172.6]
|
||||
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
|
||||
plt.errorbar(range(1, 13), weights,
|
||||
xerr=0, yerr=6, fmt='o', capthick=2, capsize=10)
|
||||
|
||||
plt.xlim(0, 13); plt.ylim(145, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
plt.savefig('../figs/gh_hypothesis3.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_hypothesis4():
|
||||
weights = [158.0, 164.2, 160.3, 159.9, 162.1, 164.6,
|
||||
169.6, 167.4, 166.4, 171.0, 171.2, 172.6]
|
||||
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
ave = np.sum(weights) / len(weights)
|
||||
plt.errorbar(range(1,13), weights, label='weights',
|
||||
yerr=6, fmt='o', capthick=2, capsize=10)
|
||||
plt.plot([1, 12], [ave,ave], c='r', label='hypothesis')
|
||||
plt.xlim(0, 13); plt.ylim(145, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
show_legend()
|
||||
plt.savefig('../figs/gh_hypothesis4.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_hypothesis5():
|
||||
weights = [158.0, 164.2, 160.3, 159.9, 162.1, 164.6,
|
||||
169.6, 167.4, 166.4, 171.0, 171.2, 172.6]
|
||||
|
||||
xs = range(1, len(weights)+1)
|
||||
line = np.poly1d(np.polyfit(xs, weights, 1))
|
||||
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
plt.errorbar(range(1, 13), weights, label='weights',
|
||||
yerr=5, fmt='o', capthick=2, capsize=10)
|
||||
plt.plot (xs, line(xs), c='r', label='hypothesis')
|
||||
plt.xlim(0, 13); plt.ylim(145, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
show_legend()
|
||||
plt.savefig('../figs/gh_hypothesis5.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_estimate_chart_1():
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
ax = plt.axes()
|
||||
ax.annotate('', xy=[1,159], xytext=[0,158],
|
||||
arrowprops=dict(arrowstyle='->', ec='r',shrinkA=6, lw=3,shrinkB=5))
|
||||
plt.scatter ([0], [158], c='b')
|
||||
plt.scatter ([1], [159], c='r')
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
ax.xaxis.grid(True, which="major", linestyle='dotted')
|
||||
ax.yaxis.grid(True, which="major", linestyle='dotted')
|
||||
plt.tight_layout()
|
||||
plt.savefig('../figs/gh_estimate1.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def plot_estimate_chart_2():
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
ax = plt.axes()
|
||||
ax.annotate('', xy=[1,159], xytext=[0,158],
|
||||
arrowprops=dict(arrowstyle='->',
|
||||
ec='r', lw=3, shrinkA=6, shrinkB=5))
|
||||
plt.scatter ([0], [158.0], c='k',s=128)
|
||||
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.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
ax.xaxis.grid(True, which="major", linestyle='dotted')
|
||||
ax.yaxis.grid(True, which="major", linestyle='dotted')
|
||||
plt.savefig('../figs/gh_estimate2.png', pad_inches=0.1)
|
||||
|
||||
def plot_estimate_chart_3():
|
||||
with figsize(y=2.5):
|
||||
plt.figure()
|
||||
ax = plt.axes()
|
||||
ax.annotate('', xy=[1,159], xytext=[0,158],
|
||||
arrowprops=dict(arrowstyle='->',
|
||||
ec='r', lw=3, shrinkA=6, shrinkB=5))
|
||||
|
||||
ax.annotate('', xy=[1,159], xytext=[1,164.2],
|
||||
arrowprops=dict(arrowstyle='-',
|
||||
ec='k', lw=3, shrinkA=8, shrinkB=8))
|
||||
|
||||
est_y = ((164.2-158)*.8 + 158)
|
||||
plt.scatter ([0,1], [158.0,est_y], c='k',s=128)
|
||||
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 (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.savefig('../figs/gh_estimate3.png', pad_inches=0.1)
|
||||
|
||||
|
||||
|
||||
def create_predict_update_chart(box_bg = '#CCCCCC',
|
||||
arrow1 = '#88CCFF',
|
||||
arrow2 = '#88FF88'):
|
||||
plt.close('all')
|
||||
plt.figure(figsize=(4, 2.), facecolor='w')
|
||||
#plt.figure(figsize=(14,12.5), facecolor='w')
|
||||
ax = plt.axes((0, 0, 1, 1),
|
||||
xticks=[], yticks=[], frameon=False)
|
||||
|
||||
pc = Circle((4,5), 0.7, fc=box_bg)
|
||||
uc = Circle((6,5), 0.7, fc=box_bg)
|
||||
ax.add_patch (pc)
|
||||
ax.add_patch (uc)
|
||||
|
||||
plt.text(4,5, "Predict\nStep",ha='center', va='center', fontsize=12)
|
||||
plt.text(6,5, "Update\nStep",ha='center', va='center', fontsize=12)
|
||||
|
||||
#btm arrow from update to predict
|
||||
ax.annotate('',
|
||||
xy=(4.1, 4.5), xycoords='data',
|
||||
xytext=(6, 4.5), textcoords='data',
|
||||
size=20,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none",
|
||||
patchB=pc,
|
||||
patchA=uc,
|
||||
connectionstyle="arc3,rad=-0.5"))
|
||||
#top arrow from predict to update
|
||||
ax.annotate('',
|
||||
xy=(6, 5.5), xycoords='data',
|
||||
xytext=(4.1, 5.5), textcoords='data',
|
||||
size=20,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none",
|
||||
patchB=uc,
|
||||
patchA=pc,
|
||||
connectionstyle="arc3,rad=-0.5"))
|
||||
|
||||
|
||||
ax.annotate('Measurement ($\mathbf{z_k}$)',
|
||||
xy=(6.3, 5.6), xycoords='data',
|
||||
xytext=(6,6), textcoords='data',
|
||||
size=14,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none"))
|
||||
|
||||
# arrow from predict to state estimate
|
||||
ax.annotate('',
|
||||
xy=(4.0, 3.8), xycoords='data',
|
||||
xytext=(4.0,4.3), textcoords='data',
|
||||
size=12,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none"))
|
||||
|
||||
ax.annotate('Initial\nConditions ($\mathbf{x_0}$)',
|
||||
xy=(4.05, 5.7), xycoords='data',
|
||||
xytext=(2.5, 6.5), textcoords='data',
|
||||
size=14,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none"))
|
||||
|
||||
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.savefig('../figs/gh_predict_update.png', pad_inches=0.1)
|
||||
|
||||
|
||||
def show_legend():
|
||||
@ -42,32 +307,32 @@ def show_legend():
|
||||
|
||||
def bar_plot(pos, x=None, ylim=(0,1), title=None, c='#30a2da',
|
||||
**kwargs):
|
||||
""" plot the values in `pos` as a bar plot.
|
||||
|
||||
""" plot the values in `pos` as a bar plot.
|
||||
|
||||
**Parameters**
|
||||
|
||||
|
||||
pos : list-like
|
||||
list of values to plot as bars
|
||||
|
||||
|
||||
x : list-like, optional
|
||||
If provided, specifies the x value for each value in pos. If not
|
||||
provided, the first pos element is plotted at x == 0, the second
|
||||
at 1, etc.
|
||||
|
||||
|
||||
ylim : (lower, upper), default = (0,1)
|
||||
specifies the lower and upper limits for the y-axis
|
||||
|
||||
|
||||
title : str, optional
|
||||
If specified, provides a title for the plot
|
||||
|
||||
|
||||
c : color, default='#30a2da'
|
||||
Color for the bars
|
||||
|
||||
|
||||
**kwargs : keywords, optional
|
||||
extra keyword arguments passed to ax.bar()
|
||||
|
||||
extra keyword arguments passed to ax.bar()
|
||||
|
||||
"""
|
||||
|
||||
|
||||
ax = plt.gca()
|
||||
if x is None:
|
||||
x = np.arange(len(pos))
|
||||
@ -83,11 +348,11 @@ def plot_belief_vs_prior(belief, prior, **kwargs):
|
||||
""" plots two discrete probability distributions side by side, with
|
||||
titles "belief" and "prior"
|
||||
"""
|
||||
|
||||
|
||||
plt.subplot(121)
|
||||
bar_plot(belief, title='belief', **kwargs)
|
||||
plt.subplot(122)
|
||||
bar_plot(prior, title='prior', **kwargs)
|
||||
bar_plot(prior, title='prior', **kwargs)
|
||||
|
||||
|
||||
def plot_prior_vs_posterior(prior, posterior, reverse=False, **kwargs):
|
||||
@ -96,15 +361,15 @@ def plot_prior_vs_posterior(prior, posterior, reverse=False, **kwargs):
|
||||
"""
|
||||
if reverse:
|
||||
plt.subplot(121)
|
||||
bar_plot(posterior, title='posterior', **kwargs)
|
||||
bar_plot(posterior, title='posterior', **kwargs)
|
||||
plt.subplot(122)
|
||||
bar_plot(prior, title='prior', **kwargs)
|
||||
else:
|
||||
plt.subplot(121)
|
||||
bar_plot(prior, title='prior', **kwargs)
|
||||
plt.subplot(122)
|
||||
bar_plot(posterior, title='posterior', **kwargs)
|
||||
|
||||
bar_plot(posterior, title='posterior', **kwargs)
|
||||
|
||||
|
||||
def set_labels(title=None, x=None, y=None):
|
||||
""" helps make code in book shorter. Optional set title, xlabel and ylabel
|
||||
@ -156,16 +421,16 @@ def plot_measurements(xs, ys=None, color='k', lw=2, label='Measurements',
|
||||
plt.autoscale(tight=True)
|
||||
if lines:
|
||||
if ys is not None:
|
||||
plt.plot(xs, ys, color=color, lw=lw, ls='--', label=label, **kwargs)
|
||||
return plt.plot(xs, ys, color=color, lw=lw, ls='--', label=label, **kwargs)
|
||||
else:
|
||||
plt.plot(xs, color=color, lw=lw, ls='--', label=label, **kwargs)
|
||||
return plt.plot(xs, color=color, lw=lw, ls='--', label=label, **kwargs)
|
||||
else:
|
||||
if ys is not None:
|
||||
plt.scatter(xs, ys, edgecolor=color, facecolor='none',
|
||||
lw=2, label=label, **kwargs)
|
||||
return plt.scatter(xs, ys, edgecolor=color, facecolor='none',
|
||||
lw=2, label=label, **kwargs),
|
||||
else:
|
||||
plt.scatter(range(len(xs)), xs, edgecolor=color, facecolor='none',
|
||||
lw=2, label=label, **kwargs)
|
||||
return plt.scatter(range(len(xs)), xs, edgecolor=color, facecolor='none',
|
||||
lw=2, label=label, **kwargs),
|
||||
|
||||
|
||||
def plot_residual_limits(Ps, stds=1.):
|
||||
@ -184,9 +449,9 @@ def plot_residual_limits(Ps, stds=1.):
|
||||
|
||||
def plot_track(xs, ys=None, label='Track', c='k', lw=2, **kwargs):
|
||||
if ys is not None:
|
||||
plt.plot(xs, ys, color=c, lw=lw, ls=':', label=label, **kwargs)
|
||||
return plt.plot(xs, ys, color=c, lw=lw, ls=':', label=label, **kwargs)
|
||||
else:
|
||||
plt.plot(xs, color=c, lw=lw, ls=':', label=label, **kwargs)
|
||||
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):
|
||||
@ -267,7 +532,22 @@ def hinton(W, maxweight=None):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = [0.2245871, 0.06288015, 0.06109133, 0.0581008, 0.09334062, 0.2245871,
|
||||
|
||||
plot_errorbar1()
|
||||
plot_errorbar2()
|
||||
plot_errorbar3()
|
||||
plot_hypothesis1()
|
||||
plot_hypothesis2()
|
||||
plot_hypothesis3()
|
||||
plot_hypothesis4()
|
||||
plot_hypothesis5()
|
||||
plot_estimate_chart_1()
|
||||
plot_estimate_chart_2()
|
||||
plot_estimate_chart_3()
|
||||
create_predict_update_chart()
|
||||
plt.close('all')
|
||||
|
||||
'''p = [0.2245871, 0.06288015, 0.06109133, 0.0581008, 0.09334062, 0.2245871,
|
||||
0.06288015, 0.06109133, 0.0581008, 0.09334062]*2
|
||||
bar_plot(p)
|
||||
plot_measurements(p)
|
||||
plot_measurements(p)'''
|
@ -24,7 +24,7 @@
|
||||
font-family: 'Source Code Pro', Consolas, monocco, monospace;
|
||||
}
|
||||
div.cell{
|
||||
width: 850px;
|
||||
//width: 950px;
|
||||
margin-left: 0% !important;
|
||||
margin-right: auto;
|
||||
}
|
||||
@ -38,7 +38,7 @@
|
||||
//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: '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;
|
||||
@ -62,10 +62,10 @@
|
||||
h1 {
|
||||
font-family: 'Open sans',verdana,arial,sans-serif;
|
||||
}
|
||||
|
||||
|
||||
div.input_area {
|
||||
background: #F6F6F9;
|
||||
border: 1px solid #586e75;
|
||||
border: 1px solid #586e75;
|
||||
}
|
||||
|
||||
.text_cell_render h1 {
|
||||
@ -78,7 +78,7 @@
|
||||
display: block;
|
||||
white-space: wrap;
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
h2 {
|
||||
font-family: 'Open sans',verdana,arial,sans-serif;
|
||||
text-align: left;
|
||||
@ -94,7 +94,7 @@
|
||||
display: block;
|
||||
white-space: wrap;
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
h3 {
|
||||
font-family: 'Open sans',verdana,arial,sans-serif;
|
||||
}
|
||||
@ -161,27 +161,27 @@
|
||||
margin: 2em;
|
||||
}
|
||||
ul li{
|
||||
padding-left: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
margin-top: 0.5em;
|
||||
padding-left: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
margin-top: 0.5em;
|
||||
}
|
||||
ul li li{
|
||||
padding-left: 0.2em;
|
||||
margin-bottom: 0.2em;
|
||||
margin-top: 0.2em;
|
||||
padding-left: 0.2em;
|
||||
margin-bottom: 0.2em;
|
||||
margin-top: 0.2em;
|
||||
}
|
||||
ol{
|
||||
margin: 2em;
|
||||
}
|
||||
ol li{
|
||||
padding-left: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
margin-top: 0.5em;
|
||||
padding-left: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
margin-top: 0.5em;
|
||||
}
|
||||
ul li{
|
||||
padding-left: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
margin-top: 0.2em;
|
||||
padding-left: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
margin-top: 0.2em;
|
||||
}
|
||||
a:link{
|
||||
color:#447adb;
|
||||
@ -200,10 +200,10 @@
|
||||
color:#447adb;
|
||||
}
|
||||
.rendered_html :link {
|
||||
text-decoration: underline;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.rendered_html :hover {
|
||||
text-decoration: none;
|
||||
text-decoration: none;
|
||||
}
|
||||
.rendered_html :visited {
|
||||
text-decoration: none;
|
||||
@ -216,7 +216,7 @@
|
||||
}
|
||||
.warning{
|
||||
color: rgb( 240, 20, 20 )
|
||||
}
|
||||
}
|
||||
hr {
|
||||
color: #f3f3f3;
|
||||
background-color: #f3f3f3;
|
||||
|
@ -16,243 +16,99 @@ for more information.
|
||||
from __future__ import (absolute_import, division, print_function,
|
||||
unicode_literals)
|
||||
|
||||
import book_format
|
||||
import sys
|
||||
sys.path.insert(0, '..')
|
||||
import book_plots
|
||||
import numpy as np
|
||||
from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow
|
||||
import pylab as plt
|
||||
|
||||
def plot_errorbar1():
|
||||
with book_format.figsize(y=1.5):
|
||||
book_plots.plot_errorbars([(160, 8, 'A'), (170, 8, 'B')],
|
||||
xlims=(145, 185), ylims=(-1, 2))
|
||||
|
||||
def plot_errorbar2():
|
||||
with book_format.figsize(y=1.5):
|
||||
book_plots.plot_errorbars([(160, 3, 'A'), (170, 9, 'B')],
|
||||
xlims=(145, 185), ylims=(-1, 2))
|
||||
|
||||
def plot_errorbar3():
|
||||
with book_format.figsize(y=1.5):
|
||||
book_plots.plot_errorbars([(160, 1, 'A'), (170, 9, 'B')],
|
||||
xlims=(145, 185), ylims=(-1, 2))
|
||||
import time
|
||||
|
||||
|
||||
|
||||
def plot_gh_results(weights, estimates, predictions):
|
||||
|
||||
|
||||
def plot_gh_results(weights, estimates, predictions, time_step=0):
|
||||
|
||||
n = len(weights)
|
||||
if time_step > 0:
|
||||
rng = range(1, n+1)
|
||||
else:
|
||||
rng = range(n, n+1)
|
||||
|
||||
xs = list(range(n+1))
|
||||
book_plots.plot_filter(xs, estimates, marker='o')
|
||||
book_plots.plot_measurements(xs[1:], weights, color='k', label='Scale', lines=False)
|
||||
book_plots.plot_track([0, n], [160, 160+n], c='k', label='Actual Weight')
|
||||
book_plots.plot_track(xs[1:], predictions, c='r', label='Predictions', marker='v')
|
||||
book_plots.show_legend()
|
||||
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])
|
||||
plt.gcf().canvas.draw()
|
||||
time.sleep(time_step)
|
||||
|
||||
scale, = book_plots.plot_measurements(xs[1:], weights[:i], color='k', lines=False)
|
||||
plt.xlim([-1, n+1])
|
||||
plt.ylim([156.0, 173])
|
||||
plt.gcf().canvas.draw()
|
||||
time.sleep(time_step)
|
||||
|
||||
book_plots.plot_filter(xs[:i+1], estimates[:i+1], marker='o')
|
||||
plt.xlim([-1, n+1])
|
||||
plt.ylim([156.0, 173])
|
||||
plt.gcf().canvas.draw()
|
||||
time.sleep(time_step)
|
||||
|
||||
plt.legend([act, scale, pred], ['Actual Weight', 'Measurement', 'Predictions'], loc=4)
|
||||
book_plots.set_labels(x='day', y='weight (lbs)')
|
||||
plt.xlim([0, n])
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
||||
def print_results(estimates, prediction, weight):
|
||||
print('previous: {:.2f}, prediction: {:.2f} estimate {:.2f}'.format(
|
||||
estimates[-2], prediction, weight))
|
||||
|
||||
def create_predict_update_chart(box_bg = '#CCCCCC',
|
||||
arrow1 = '#88CCFF',
|
||||
arrow2 = '#88FF88'):
|
||||
plt.figure(figsize=(3,3), facecolor='w')
|
||||
ax = plt.axes((0, 0, 1, 1),
|
||||
xticks=[], yticks=[], frameon=False)
|
||||
#ax.set_xlim(0, 10)
|
||||
#ax.set_ylim(0, 10)
|
||||
|
||||
|
||||
pc = Circle((4,5), 0.5, fc=box_bg)
|
||||
uc = Circle((6,5), 0.5, fc=box_bg)
|
||||
ax.add_patch (pc)
|
||||
ax.add_patch (uc)
|
||||
|
||||
|
||||
plt.text(4,5, "Predict\nStep",ha='center', va='center', fontsize=14)
|
||||
plt.text(6,5, "Update\nStep",ha='center', va='center', fontsize=14)
|
||||
|
||||
#btm
|
||||
ax.annotate('',
|
||||
xy=(4.1, 4.5), xycoords='data',
|
||||
xytext=(6, 4.5), textcoords='data',
|
||||
size=20,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none",
|
||||
patchB=pc,
|
||||
patchA=uc,
|
||||
connectionstyle="arc3,rad=-0.5"))
|
||||
#top
|
||||
ax.annotate('',
|
||||
xy=(6, 5.5), xycoords='data',
|
||||
xytext=(4.1, 5.5), textcoords='data',
|
||||
size=20,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none",
|
||||
patchB=uc,
|
||||
patchA=pc,
|
||||
connectionstyle="arc3,rad=-0.5"))
|
||||
|
||||
|
||||
ax.annotate('Measurement ($\mathbf{z_k}$)',
|
||||
xy=(6.3, 5.4), xycoords='data',
|
||||
xytext=(6,6), textcoords='data',
|
||||
size=18,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none"))
|
||||
|
||||
ax.annotate('',
|
||||
xy=(4.0, 3.5), xycoords='data',
|
||||
xytext=(4.0,4.5), textcoords='data',
|
||||
size=18,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none"))
|
||||
|
||||
ax.annotate('Initial\nConditions ($\mathbf{x_0}$)',
|
||||
xy=(4.0, 5.5), xycoords='data',
|
||||
xytext=(2.5,6.5), textcoords='data',
|
||||
size=18,
|
||||
arrowprops=dict(arrowstyle="simple",
|
||||
fc="0.6", ec="none"))
|
||||
|
||||
plt.text (4,3.4,'State Estimate ($\mathbf{\hat{x}_k}$)',
|
||||
ha='center', va='center', fontsize=18)
|
||||
plt.axis('equal')
|
||||
#plt.axis([0,8,0,8])
|
||||
#plt.show()
|
||||
|
||||
|
||||
def plot_estimate_chart_1():
|
||||
ax = plt.axes()
|
||||
ax.annotate('', xy=[1,159], xytext=[0,158],
|
||||
arrowprops=dict(arrowstyle='->', ec='r',shrinkA=6, lw=3,shrinkB=5))
|
||||
plt.scatter ([0], [158], c='b')
|
||||
plt.scatter ([1], [159], c='r')
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
ax.xaxis.grid(True, which="major", linestyle='dotted')
|
||||
ax.yaxis.grid(True, which="major", linestyle='dotted')
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_estimate_chart_2():
|
||||
ax = plt.axes()
|
||||
ax.annotate('', xy=[1,159], xytext=[0,158],
|
||||
arrowprops=dict(arrowstyle='->',
|
||||
ec='r', lw=3, shrinkA=6, shrinkB=5))
|
||||
plt.scatter ([0], [158.0], c='k',s=128)
|
||||
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.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
ax.xaxis.grid(True, which="major", linestyle='dotted')
|
||||
ax.yaxis.grid(True, which="major", linestyle='dotted')
|
||||
plt.show()
|
||||
|
||||
def plot_estimate_chart_3():
|
||||
ax = plt.axes()
|
||||
ax.annotate('', xy=[1,159], xytext=[0,158],
|
||||
arrowprops=dict(arrowstyle='->',
|
||||
ec='r', lw=3, shrinkA=6, shrinkB=5))
|
||||
|
||||
ax.annotate('', xy=[1,159], xytext=[1,164.2],
|
||||
arrowprops=dict(arrowstyle='-',
|
||||
ec='k', lw=3, shrinkA=8, shrinkB=8))
|
||||
|
||||
est_y = ((164.2-158)*.8 + 158)
|
||||
plt.scatter ([0,1], [158.0,est_y], c='k',s=128)
|
||||
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 (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.show()
|
||||
|
||||
def plot_hypothesis():
|
||||
plt.errorbar([1, 2, 3], [170, 161, 169],
|
||||
xerr=0, yerr=10, fmt='bo', capthick=2, capsize=10)
|
||||
|
||||
plt.plot([1, 3], [180, 160], color='g', ls='--')
|
||||
plt.plot([1, 3], [170, 170], color='g', ls='--')
|
||||
plt.plot([1, 3], [160, 175], color='g', ls='--')
|
||||
plt.plot([1, 2, 3], [180, 152, 179], color='g', ls='--')
|
||||
plt.xlim(0,4); plt.ylim(150, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('lbs')
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
def plot_hypothesis2():
|
||||
plt.errorbar(range(1, 11), [169, 170, 169,171, 170, 171, 169, 170, 169, 170],
|
||||
xerr=0, yerr=6, fmt='bo', capthick=2, capsize=10)
|
||||
plt.plot([1, 10], [169, 170.5], color='g', ls='--')
|
||||
plt.xlim(0, 11); plt.ylim(150, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('lbs')
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_hypothesis3():
|
||||
weights = [158.0, 164.2, 160.3, 159.9, 162.1, 164.6,
|
||||
169.6, 167.4, 166.4, 171.0, 171.2, 172.6]
|
||||
plt.errorbar(range(1, 13), weights,
|
||||
xerr=0, yerr=6, fmt='o', capthick=2, capsize=10)
|
||||
|
||||
plt.xlim(0, 13); plt.ylim(145, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_hypothesis4():
|
||||
weights = [158.0, 164.2, 160.3, 159.9, 162.1, 164.6,
|
||||
169.6, 167.4, 166.4, 171.0, 171.2, 172.6]
|
||||
|
||||
ave = np.sum(weights) / len(weights)
|
||||
plt.errorbar(range(1,13), weights, label='weights',
|
||||
yerr=6, fmt='o', capthick=2, capsize=10)
|
||||
plt.plot([1, 12], [ave,ave], c='r', label='hypothesis')
|
||||
plt.xlim(0, 13); plt.ylim(145, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
book_plots.show_legend()
|
||||
plt.show()
|
||||
|
||||
|
||||
def plot_hypothesis5():
|
||||
weights = [158.0, 164.2, 160.3, 159.9, 162.1, 164.6,
|
||||
169.6, 167.4, 166.4, 171.0, 171.2, 172.6]
|
||||
|
||||
xs = range(1, len(weights)+1)
|
||||
line = np.poly1d(np.polyfit(xs, weights, 1))
|
||||
plt.errorbar(range(1, 13), weights, label='weights',
|
||||
yerr=5, fmt='o', capthick=2, capsize=10)
|
||||
plt.plot (xs, line(xs), c='r', label='hypothesis')
|
||||
plt.xlim(0, 13); plt.ylim(145, 185)
|
||||
plt.xlabel('day')
|
||||
plt.ylabel('weight (lbs)')
|
||||
book_plots.show_legend()
|
||||
plt.show()
|
||||
|
||||
def plot_g_h_results(measurements, filtered_data,
|
||||
title='', z_label='Measurements', **kwargs):
|
||||
title='', z_label='Measurements',
|
||||
**kwargs):
|
||||
|
||||
book_plots.plot_filter(filtered_data, **kwargs)
|
||||
book_plots.plot_measurements(measurements, label=z_label)
|
||||
book_plots.show_legend()
|
||||
plt.title(title)
|
||||
plt.gca().set_xlim(left=0,right=len(measurements))
|
||||
|
||||
return
|
||||
|
||||
import time
|
||||
if not interactive:
|
||||
book_plots.plot_filter(filtered_data, **kwargs)
|
||||
book_plots.plot_measurements(measurements, label=z_label)
|
||||
book_plots.show_legend()
|
||||
plt.title(title)
|
||||
plt.gca().set_xlim(left=0,right=len(measurements))
|
||||
else:
|
||||
for i in range(2, len(measurements)):
|
||||
book_plots.plot_filter(filtered_data, **kwargs)
|
||||
book_plots.plot_measurements(measurements, label=z_label)
|
||||
book_plots.show_legend()
|
||||
plt.title(title)
|
||||
plt.gca().set_xlim(left=0,right=len(measurements))
|
||||
plt.gca().canvas.draw()
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
create_predict_update_chart()
|
||||
import seaborn
|
||||
plot_errorbar1()
|
||||
#create_predict_update_chart()
|
BIN
figs/gh_errorbar1.png
Normal file
After Width: | Height: | Size: 5.7 KiB |
BIN
figs/gh_errorbar2.png
Normal file
After Width: | Height: | Size: 5.7 KiB |
BIN
figs/gh_errorbar3.png
Normal file
After Width: | Height: | Size: 5.7 KiB |
BIN
figs/gh_estimate1.png
Normal file
After Width: | Height: | Size: 24 KiB |
BIN
figs/gh_estimate2.png
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
figs/gh_estimate3.png
Normal file
After Width: | Height: | Size: 36 KiB |
BIN
figs/gh_hypothesis1.png
Normal file
After Width: | Height: | Size: 26 KiB |
BIN
figs/gh_hypothesis2.png
Normal file
After Width: | Height: | Size: 14 KiB |
BIN
figs/gh_hypothesis3.png
Normal file
After Width: | Height: | Size: 16 KiB |
BIN
figs/gh_hypothesis4.png
Normal file
After Width: | Height: | Size: 19 KiB |
BIN
figs/gh_hypothesis5.png
Normal file
After Width: | Height: | Size: 21 KiB |
BIN
figs/gh_predict_update.png
Normal file
After Width: | Height: | Size: 17 KiB |