Discrete Bayes Animations

In [1]:
from __future__ import division, print_function
import matplotlib.pyplot as plt
import sys
sys.path.insert(0,'..') # allow us to format the book
sys.path.insert(0,'../code') 
import book_format
book_format.load_style(directory='..')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-730769ca9272> in <module>
      5 sys.path.insert(0,'../code')
      6 import book_format
----> 7 book_format.load_style(directory='..')

AttributeError: module 'book_format' has no attribute 'load_style'

This notebook creates the animations for the Discrete Bayesian filters chapter. It is not really intended to be a readable part of the book, but of course you are free to look at the source code, and even modify it. However, if you are interested in running your own animations, I'll point you to the examples subdirectory of the book, which contains a number of python scripts that you can run and modify from an IDE or the command line. This module saves the animations to GIF files, which is quite slow and not very interactive.

In [2]:
from matplotlib import animation
import matplotlib.pyplot as plt
import numpy as np
from book_plots import bar_plot
%matplotlib inline

# the predict algorithm of the discrete bayesian filter
def predict(pos, move, p_correct, p_under, p_over):
    n = len(pos)
    result = np.array(pos, dtype=float)
    for i in range(n):
                result[i] =  \
            pos[(i-move) % n]   * p_correct + \
            pos[(i-move-1) % n] * p_over + \
            pos[(i-move+1) % n] * p_under          
    return result


def normalize(p):
    s = sum(p)
    for i in range (len(p)):
        p[i] = p[i] / s
        
# the update algorithm of the discrete bayesian filter
def update(pos, measure, p_hit, p_miss):
    q = np.array(pos, dtype=float)
    for i in range(len(hallway)):
        if hallway[i] == measure:
            q[i] = pos[i] * p_hit
        else:
            q[i] = pos[i] * p_miss
    normalize(q)
    return q
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-2-1d7fb353c3e8> in <module>
      2 import matplotlib.pyplot as plt
      3 import numpy as np
----> 4 from book_plots import bar_plot
      5 get_ipython().run_line_magic('matplotlib', 'inline')
      6 

ModuleNotFoundError: No module named 'book_plots'
In [3]:
import matplotlib
# make sure our matplotlibrc has been edited to use imagemagick
print(matplotlib.matplotlib_fname())
matplotlib.rcParams['animation.writer']
C:\Anaconda3\lib\site-packages\matplotlib\mpl-data\matplotlibrc
Out[3]:
'ffmpeg'
In [4]:
from gif_animate import animate

pos = [1.0,0,0,0,0,0,0,0,0,0]
def bar_animate(nframe):
    global pos
    plt.cla()
    bar_plot(pos)
    plt.title('Step {}'.format(nframe + 1))
    pos = predict(pos, 1, .8, .1, .1)

for i in range(10):
    bar_animate(i)

fig = plt.figure(figsize=(6.5, 2.5))
animate('02_no_info.gif', bar_animate, fig=fig, frames=75, interval=75);
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-4-c8909b74d11e> in <module>
----> 1 from gif_animate import animate
      2 
      3 pos = [1.0,0,0,0,0,0,0,0,0,0]
      4 def bar_animate(nframe):
      5     global pos

ModuleNotFoundError: No module named 'gif_animate'

In [5]:
pos = np.array([.1]*10)
hallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0])

def bar_animate(nframe):
    global pos
    #if nframe == 0:
    #   return

    bar_plot(pos, ylim=(0,1.0))
    plt.title('Step {}'.format(nframe + 1))
    if nframe % 2 == 0:
        pos = predict(pos, 1, .9, .05, .05)
    else:
        x = int((nframe/2) % len(hallway))
        z = hallway[x]
        pos = update(pos, z, .9, .2)
        

fig = plt.figure(figsize=(6.5, 2.5))
animate('02_simulate.gif', bar_animate, fig=fig, frames=40, interval=85);
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-0c3b6443d1db> in <module>
     18 
     19 fig = plt.figure(figsize=(6.5, 2.5))
---> 20 animate('02_simulate.gif', bar_animate, fig=fig, frames=40, interval=85);

NameError: name 'animate' is not defined
<Figure size 650x250 with 0 Axes>