Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96160
License: OTHER
1
"""This file contains code used in "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2012 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
import thinkbayes
9
10
import matplotlib.pyplot as pyplot
11
import thinkplot
12
13
import math
14
import sys
15
16
17
FORMATS = ['pdf', 'eps', 'png']
18
19
20
def StrafingSpeed(alpha, beta, x):
21
"""Computes strafing speed, given location of shooter and impact.
22
23
alpha: x location of shooter
24
beta: y location of shooter
25
x: location of impact
26
27
Returns: derivative of x with respect to theta
28
"""
29
theta = math.atan2(x - alpha, beta)
30
speed = beta / math.cos(theta)**2
31
return speed
32
33
34
def MakeLocationPmf(alpha, beta, locations):
35
"""Computes the Pmf of the locations, given alpha and beta.
36
37
Given that the shooter is at coordinates (alpha, beta),
38
the probability of hitting any spot is inversely proportionate
39
to the strafe speed.
40
41
alpha: x position
42
beta: y position
43
locations: x locations where the pmf is evaluated
44
45
Returns: Pmf object
46
"""
47
pmf = thinkbayes.Pmf()
48
for x in locations:
49
prob = 1.0 / StrafingSpeed(alpha, beta, x)
50
pmf.Set(x, prob)
51
pmf.Normalize()
52
return pmf
53
54
55
class Paintball(thinkbayes.Suite, thinkbayes.Joint):
56
"""Represents hypotheses about the location of an opponent."""
57
58
def __init__(self, alphas, betas, locations):
59
"""Makes a joint suite of parameters alpha and beta.
60
61
Enumerates all pairs of alpha and beta.
62
Stores locations for use in Likelihood.
63
64
alphas: possible values for alpha
65
betas: possible values for beta
66
locations: possible locations along the wall
67
"""
68
self.locations = locations
69
pairs = [(alpha, beta)
70
for alpha in alphas
71
for beta in betas]
72
thinkbayes.Suite.__init__(self, pairs)
73
74
def Likelihood(self, data, hypo):
75
"""Computes the likelihood of the data under the hypothesis.
76
77
hypo: pair of alpha, beta
78
data: location of a hit
79
80
Returns: float likelihood
81
"""
82
alpha, beta = hypo
83
x = data
84
pmf = MakeLocationPmf(alpha, beta, self.locations)
85
like = pmf.Prob(x)
86
return like
87
88
89
def MakePmfPlot(alpha = 10):
90
"""Plots Pmf of location for a range of betas."""
91
locations = range(0, 31)
92
93
betas = [10, 20, 40]
94
thinkplot.PrePlot(num=len(betas))
95
96
for beta in betas:
97
pmf = MakeLocationPmf(alpha, beta, locations)
98
pmf.name = 'beta = %d' % beta
99
thinkplot.Pmf(pmf)
100
101
thinkplot.Save('paintball1',
102
xlabel='Distance',
103
ylabel='Prob',
104
formats=FORMATS)
105
106
107
def MakePosteriorPlot(suite):
108
"""Plots the posterior marginal distributions for alpha and beta.
109
110
suite: posterior joint distribution of location
111
"""
112
marginal_alpha = suite.Marginal(0)
113
marginal_alpha.name = 'alpha'
114
marginal_beta = suite.Marginal(1)
115
marginal_beta.name = 'beta'
116
117
print 'alpha CI', marginal_alpha.CredibleInterval(50)
118
print 'beta CI', marginal_beta.CredibleInterval(50)
119
120
thinkplot.PrePlot(num=2)
121
122
#thinkplot.Pmf(marginal_alpha)
123
#thinkplot.Pmf(marginal_beta)
124
125
thinkplot.Cdf(thinkbayes.MakeCdfFromPmf(marginal_alpha))
126
thinkplot.Cdf(thinkbayes.MakeCdfFromPmf(marginal_beta))
127
128
thinkplot.Save('paintball2',
129
xlabel='Distance',
130
ylabel='Prob',
131
loc=4,
132
formats=FORMATS)
133
134
135
def MakeConditionalPlot(suite):
136
"""Plots marginal CDFs for alpha conditioned on beta.
137
138
suite: posterior joint distribution of location
139
"""
140
betas = [10, 20, 40]
141
thinkplot.PrePlot(num=len(betas))
142
143
for beta in betas:
144
cond = suite.Conditional(0, 1, beta)
145
cond.name = 'beta = %d' % beta
146
thinkplot.Pmf(cond)
147
148
thinkplot.Save('paintball3',
149
xlabel='Distance',
150
ylabel='Prob',
151
formats=FORMATS)
152
153
154
def MakeContourPlot(suite):
155
"""Plots the posterior joint distribution as a contour plot.
156
157
suite: posterior joint distribution of location
158
"""
159
thinkplot.Contour(suite.GetDict(), contour=False, pcolor=True)
160
161
thinkplot.Save('paintball4',
162
xlabel='alpha',
163
ylabel='beta',
164
axis=[0, 30, 0, 20],
165
formats=FORMATS)
166
167
168
def MakeCrediblePlot(suite):
169
"""Makes a plot showing several two-dimensional credible intervals.
170
171
suite: Suite
172
"""
173
d = dict((pair, 0) for pair in suite.Values())
174
175
percentages = [75, 50, 25]
176
for p in percentages:
177
interval = suite.MaxLikeInterval(p)
178
for pair in interval:
179
d[pair] += 1
180
181
thinkplot.Contour(d, contour=False, pcolor=True)
182
pyplot.text(17, 4, '25', color='white')
183
pyplot.text(17, 15, '50', color='white')
184
pyplot.text(17, 30, '75')
185
186
thinkplot.Save('paintball5',
187
xlabel='alpha',
188
ylabel='beta',
189
formats=FORMATS)
190
191
192
def main(script):
193
194
alphas = range(0, 31)
195
betas = range(1, 51)
196
locations = range(0, 31)
197
198
suite = Paintball(alphas, betas, locations)
199
suite.UpdateSet([15, 16, 18, 21])
200
201
MakeCrediblePlot(suite)
202
203
MakeContourPlot(suite)
204
205
MakePosteriorPlot(suite)
206
207
MakeConditionalPlot(suite)
208
209
MakePmfPlot()
210
211
212
if __name__ == '__main__':
213
main(*sys.argv)
214
215