📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This file contains code used in "Think Bayes",1by Allen B. Downey, available from greenteapress.com23Copyright 2012 Allen B. Downey4License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html5"""67import thinkbayes89import matplotlib.pyplot as pyplot10import thinkplot1112import math13import sys141516FORMATS = ['pdf', 'eps', 'png']171819def StrafingSpeed(alpha, beta, x):20"""Computes strafing speed, given location of shooter and impact.2122alpha: x location of shooter23beta: y location of shooter24x: location of impact2526Returns: derivative of x with respect to theta27"""28theta = math.atan2(x - alpha, beta)29speed = beta / math.cos(theta)**230return speed313233def MakeLocationPmf(alpha, beta, locations):34"""Computes the Pmf of the locations, given alpha and beta.3536Given that the shooter is at coordinates (alpha, beta),37the probability of hitting any spot is inversely proportionate38to the strafe speed.3940alpha: x position41beta: y position42locations: x locations where the pmf is evaluated4344Returns: Pmf object45"""46pmf = thinkbayes.Pmf()47for x in locations:48prob = 1.0 / StrafingSpeed(alpha, beta, x)49pmf.Set(x, prob)50pmf.Normalize()51return pmf525354class Paintball(thinkbayes.Suite, thinkbayes.Joint):55"""Represents hypotheses about the location of an opponent."""5657def __init__(self, alphas, betas, locations):58"""Makes a joint suite of parameters alpha and beta.5960Enumerates all pairs of alpha and beta.61Stores locations for use in Likelihood.6263alphas: possible values for alpha64betas: possible values for beta65locations: possible locations along the wall66"""67self.locations = locations68pairs = [(alpha, beta)69for alpha in alphas70for beta in betas]71thinkbayes.Suite.__init__(self, pairs)7273def Likelihood(self, data, hypo):74"""Computes the likelihood of the data under the hypothesis.7576hypo: pair of alpha, beta77data: location of a hit7879Returns: float likelihood80"""81alpha, beta = hypo82x = data83pmf = MakeLocationPmf(alpha, beta, self.locations)84like = pmf.Prob(x)85return like868788def MakePmfPlot(alpha = 10):89"""Plots Pmf of location for a range of betas."""90locations = range(0, 31)9192betas = [10, 20, 40]93thinkplot.PrePlot(num=len(betas))9495for beta in betas:96pmf = MakeLocationPmf(alpha, beta, locations)97pmf.name = 'beta = %d' % beta98thinkplot.Pmf(pmf)99100thinkplot.Save('paintball1',101xlabel='Distance',102ylabel='Prob',103formats=FORMATS)104105106def MakePosteriorPlot(suite):107"""Plots the posterior marginal distributions for alpha and beta.108109suite: posterior joint distribution of location110"""111marginal_alpha = suite.Marginal(0)112marginal_alpha.name = 'alpha'113marginal_beta = suite.Marginal(1)114marginal_beta.name = 'beta'115116print 'alpha CI', marginal_alpha.CredibleInterval(50)117print 'beta CI', marginal_beta.CredibleInterval(50)118119thinkplot.PrePlot(num=2)120121#thinkplot.Pmf(marginal_alpha)122#thinkplot.Pmf(marginal_beta)123124thinkplot.Cdf(thinkbayes.MakeCdfFromPmf(marginal_alpha))125thinkplot.Cdf(thinkbayes.MakeCdfFromPmf(marginal_beta))126127thinkplot.Save('paintball2',128xlabel='Distance',129ylabel='Prob',130loc=4,131formats=FORMATS)132133134def MakeConditionalPlot(suite):135"""Plots marginal CDFs for alpha conditioned on beta.136137suite: posterior joint distribution of location138"""139betas = [10, 20, 40]140thinkplot.PrePlot(num=len(betas))141142for beta in betas:143cond = suite.Conditional(0, 1, beta)144cond.name = 'beta = %d' % beta145thinkplot.Pmf(cond)146147thinkplot.Save('paintball3',148xlabel='Distance',149ylabel='Prob',150formats=FORMATS)151152153def MakeContourPlot(suite):154"""Plots the posterior joint distribution as a contour plot.155156suite: posterior joint distribution of location157"""158thinkplot.Contour(suite.GetDict(), contour=False, pcolor=True)159160thinkplot.Save('paintball4',161xlabel='alpha',162ylabel='beta',163axis=[0, 30, 0, 20],164formats=FORMATS)165166167def MakeCrediblePlot(suite):168"""Makes a plot showing several two-dimensional credible intervals.169170suite: Suite171"""172d = dict((pair, 0) for pair in suite.Values())173174percentages = [75, 50, 25]175for p in percentages:176interval = suite.MaxLikeInterval(p)177for pair in interval:178d[pair] += 1179180thinkplot.Contour(d, contour=False, pcolor=True)181pyplot.text(17, 4, '25', color='white')182pyplot.text(17, 15, '50', color='white')183pyplot.text(17, 30, '75')184185thinkplot.Save('paintball5',186xlabel='alpha',187ylabel='beta',188formats=FORMATS)189190191def main(script):192193alphas = range(0, 31)194betas = range(1, 51)195locations = range(0, 31)196197suite = Paintball(alphas, betas, locations)198suite.UpdateSet([15, 16, 18, 21])199200MakeCrediblePlot(suite)201202MakeContourPlot(suite)203204MakePosteriorPlot(suite)205206MakeConditionalPlot(suite)207208MakePmfPlot()209210211if __name__ == '__main__':212main(*sys.argv)213214215