/
distribution.py
205 lines (150 loc) · 5.52 KB
/
distribution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from __future__ import print_function, division
import matplotlib.pyplot as plt
import numpy as np
from numpy.fft import fft, ifft
class Pmf:
def __init__(self, d=None):
"""Initializes the distribution.
d: map from values to probabilities
"""
self.d = {} if d is None else d
def items(self):
"""Returns a sequence of (value, prob) pairs."""
return self.d.items()
def __repr__(self):
"""Returns a string representation of the object."""
cls = self.__class__.__name__
return '%s(%s)' % (cls, repr(self.d))
def __getitem__(self, value):
"""Looks up the probability of a value."""
return self.d.get(value, 0)
def __setitem__(self, value, prob):
"""Sets the probability associated with a value."""
self.d[value] = prob
def __add__(self, other):
"""Computes the Pmf of the sum of values drawn from self and other.
other: another Pmf or a scalar
returns: new Pmf
"""
if other == 0:
return self
pmf = Pmf()
for v1, p1 in self.items():
for v2, p2 in other.items():
pmf[v1 + v2] += p1 * p2
return pmf
__radd__ = __add__
def total(self):
"""Returns the total of the probabilities."""
return sum(self.d.values())
def normalize(self):
"""Normalizes this PMF so the sum of all probs is 1.
Args:
fraction: what the total should be after normalization
Returns: the total probability before normalizing
"""
total = self.total()
for x in self.d:
self.d[x] /= total
return total
def mean(self):
"""Computes the mean of a PMF."""
return sum(p * x for x, p in self.items())
def var(self, mu=None):
"""Computes the variance of a PMF.
mu: the point around which the variance is computed;
if omitted, computes the mean
"""
if mu is None:
mu = self.mean()
return sum(p * (x - mu) ** 2 for x, p in self.items())
def expect(self, func):
"""Computes the expectation of a given function, E[f(x)]
func: function
"""
return sum(p * func(x) for x, p in self.items())
def display(self):
"""Displays the values and probabilities."""
for value, prob in self.items():
print(value, prob)
def plot_pmf(self, **options):
"""Plots the values and probabilities."""
xs, ps = zip(*sorted(self.items()))
plt.plot(xs, ps, **options)
class Cdf:
def __init__(self, xs, ps):
self.xs = xs
self.ps = ps
def __repr__(self):
return 'Cdf(%s, %s)' % (repr(self.xs), repr(self.ps))
def __getitem__(self, x):
return self.cumprobs([x])[0]
def cumprobs(self, values):
"""Gets probabilities for a sequence of values.
values: any sequence that can be converted to NumPy array
returns: NumPy array of cumulative probabilities
"""
values = np.asarray(values)
index = np.searchsorted(self.xs, values, side='right')
ps = self.ps[index-1]
ps[values < self.xs[0]] = 0.0
return ps
def values(self, ps):
"""Returns InverseCDF(p), the value that corresponds to probability p.
ps: sequence of numbers in the range [0, 1]
returns: NumPy array of values
"""
ps = np.asarray(ps)
if np.any(ps < 0) or np.any(ps > 1):
raise ValueError('Probability p must be in range [0, 1]')
index = np.searchsorted(self.ps, ps, side='left')
return self.xs[index]
def sample(self, shape):
"""Generates a random sample from the distribution.
shape: dimensions of the resulting NumPy array
"""
ps = np.random.random(shape)
return self.values(ps)
def maximum(self, k):
"""Computes the CDF of the maximum of k samples from the distribution."""
return Cdf(self.xs, self.ps**k)
def display(self):
"""Displays the values and cumulative probabilities."""
for x, p in zip(self.xs, self.ps):
print(x, p)
def plot_cdf(self, **options):
"""Plots the cumulative probabilities."""
plt.plot(self.xs, self.ps, **options)
class CharFunc:
def __init__(self, hs):
"""Initializes the CF.
hs: NumPy array of complex
"""
self.hs = hs
def __mul__(self, other):
"""Computes the elementwise product of two CFs."""
return CharFunc(self.hs * other.hs)
def make_pmf(self, thresh=1e-11):
"""Converts a CF to a PMF.
Values with probabilities below `thresh` are dropped.
"""
ps = ifft(self.hs)
d = dict((i, p) for i, p in enumerate(ps.real) if p > thresh)
return Pmf(d)
def plot_cf(self, **options):
"""Plots the real and imaginary parts of the CF."""
n = len(self.hs)
xs = np.arange(-n//2, n//2)
hs = np.roll(self.hs, len(self.hs) // 2)
plt.plot(xs, hs.real, label='real', **options)
plt.plot(xs, hs.imag, label='imag', **options)
plt.legend()
def compute_cumprobs(d):
"""Computes cumulative probabilities.
d: map from values to probabilities
"""
xs, freqs = zip(*sorted(d.items()))
xs = np.asarray(xs)
ps = np.cumsum(freqs, dtype=np.float)
ps /= ps[-1]
return xs, ps