Repository navigation
Expand file tree
/
Copy pathprobabilistic_programming.py
More file actions
242 lines (193 loc) · 11.6 KB
/
Copy pathprobabilistic_programming.py
File metadata and controls
242 lines (193 loc) · 11.6 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
Probabilistic Programming (Chapter 15, 4th edition)
The figures of the chapter are generative programs: each function below samples
one possible world of the model, using a numpy random Generator so that a run
can be repeated. Where the book leaves a part of the model unspecified (the
grammar of citations, the physics of seismic waves, the font of a rendered
letter), the functions use the simplest version that keeps the structure of
the figure, and say so.
"""
import string
from collections import Counter, defaultdict
import numpy as np
def om(a, b, rng):
"""The order-of-magnitude distribution OM(a, b) of section 15.2: a discrete
log-normal whose values are about 10^a, give or take b orders of magnitude."""
return int(round(10 ** rng.normal(a, b)))
# ______________________________________________________________________________
# [Figure 15.5] An OUPM for citation information extraction
def generate_citation_world(n_citations=10, rng=None):
"""Sample a world of the citation model: researchers (#Researcher ~ OM(3, 1)),
each a professor with probability 0.2 and with #Paper ~ OM(1.5, 0.5) papers
if a professor and OM(1, 0.5) otherwise, and citations that each pick a
paper uniformly. The text of a citation stands in for the HMM grammar of
the figure: the author's name and the title, with a typo now and then."""
rng = rng or np.random.default_rng()
researchers = [{'name': random_name(rng), 'professor': bool(rng.random() < 0.2)}
for _ in range(max(1, om(3, 1, rng)))]
papers = []
for r in researchers:
for _ in range(max(0, om(1.5, 0.5, rng) if r['professor'] else om(1, 0.5, rng))):
papers.append({'author': r, 'title': random_title(rng)})
citations = []
for _ in range(n_citations if papers else 0):
p = papers[rng.integers(len(papers))]
citations.append({'cited_paper': p, 'text': noisy_text(p['author']['name'] + '. ' + p['title'] + '.', rng)})
return researchers, papers, citations
def random_name(rng):
"""NamePrior(): a capitalized surname of 4 to 9 letters."""
return ''.join(rng.choice(list(string.ascii_lowercase), rng.integers(4, 10))).capitalize()
def random_title(rng):
"""PaperTitlePrior(): 2 to 6 words of 3 to 8 letters."""
return ' '.join(''.join(rng.choice(list(string.ascii_lowercase), rng.integers(3, 9)))
for _ in range(rng.integers(2, 7))).capitalize()
def noisy_text(text, rng, p_typo=0.02):
"""Replace each letter by a random one with probability p_typo."""
return ''.join(rng.choice(list(string.ascii_lowercase)) if c.isalpha() and rng.random() < p_typo else c
for c in text)
# ______________________________________________________________________________
# [Figure 15.6] A simplified version of the NET-VISA model
EARTH_RADIUS = 6371.0 # km
P_WAVE_SPEED = 8.0 # km/s, a single constant speed stands in for the travel-time model GeoTT
def great_circle_distance(loc1, loc2):
"""Distance in km between two (latitude, longitude) points, in degrees."""
(lat1, lon1), (lat2, lon2) = np.radians(loc1), np.radians(loc2)
c = np.sin(lat1) * np.sin(lat2) + np.cos(lat1) * np.cos(lat2) * np.cos(lon1 - lon2)
return EARTH_RADIUS * np.arccos(np.clip(c, -1.0, 1.0))
def uniform_earth(rng):
"""A point uniformly distributed on the surface of the earth."""
return float(np.degrees(np.arcsin(rng.uniform(-1, 1)))), float(rng.uniform(-180, 180))
def generate_seismic_world(stations, T=3600.0, event_rate=1 / 1800, noise_rate=1 / 600,
spatial_prior=None, rng=None):
"""Sample a world of NET-VISA over T seconds: seismic events (#SeismicEvents ~
Poisson(T * event_rate)), each an earthquake with probability 0.999, located
by spatial_prior() if so (uniform on earth by default) and anywhere otherwise,
with an Exponential(log 10) magnitude; each station detects an event with a
logistic probability in magnitude, depth and distance, and also records
#Detections ~ Poisson(T * noise_rate) noise detections. A detection has an
onset time (the event time plus travel time plus Laplace noise) and an
amplitude; the simplifications are one phase, a constant wave speed, and no
azimuth or slowness."""
rng = rng or np.random.default_rng()
spatial_prior = spatial_prior or uniform_earth
events = []
for _ in range(rng.poisson(T * event_rate)):
earthquake = bool(rng.random() < 0.999)
events.append({'time': float(rng.uniform(0, T)), 'earthquake': earthquake,
'location': spatial_prior(rng) if earthquake else uniform_earth(rng),
'depth': float(rng.uniform(0, 700)) if earthquake else 0.0,
'magnitude': float(rng.exponential(1 / np.log(10)))})
detections = []
for s, site in enumerate(stations):
for e in events:
dist = great_circle_distance(e['location'], site)
p_detect = 1 / (1 + np.exp(-(2.0 * e['magnitude'] - 0.001 * e['depth'] - 0.0005 * dist)))
if rng.random() < p_detect:
detections.append({'station': s, 'event': e,
'onset_time': e['time'] + dist / P_WAVE_SPEED + float(rng.laplace(0, 1)),
'amplitude': float(np.exp(e['magnitude'] - dist / 5000 + rng.normal(0, 0.5)))})
for _ in range(rng.poisson(T * noise_rate)):
detections.append({'station': s, 'event': None, 'onset_time': float(rng.uniform(0, T)),
'amplitude': float(np.exp(rng.normal(-1, 0.5)))})
return events, detections
# ______________________________________________________________________________
# [Figure 15.9] An OUPM for radar tracking of multiple targets
def generate_radar_world(T, aircraft_rate=0.3, exit_prob=0.1, false_alarm_rate=1.0,
F=None, sigma_x=None, H=None, sigma_z=None, region=((0, 100), (0, 100)),
detection_prob=lambda x: 0.9, rng=None):
"""Sample T time steps of the radar model: at each step #Aircraft ~
Poisson(aircraft_rate) aircraft enter at a uniform position with zero
velocity, every aircraft in flight exits with probability exit_prob, moves
by the linear-Gaussian model X_t ~ N(F X_{t-1}, sigma_x) (state x, y, vx, vy)
and produces a blip with probability detection_prob(X), observed as
Z ~ N(H X, sigma_z); #Blip ~ Poisson(false_alarm_rate) false alarms per step
appear uniformly in the region. Returns the aircraft tracks and the blips."""
rng = rng or np.random.default_rng()
F = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]) if F is None else F
sigma_x = np.diag([0.1, 0.1, 0.5, 0.5]) if sigma_x is None else sigma_x
H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) if H is None else H
sigma_z = np.eye(2) if sigma_z is None else sigma_z
(x0, x1), (y0, y1) = region
aircraft, in_flight, blips = [], [], []
for t in range(T):
for a in list(in_flight):
if rng.random() < exit_prob:
in_flight.remove(a)
else:
a['track'][t] = rng.multivariate_normal(F @ a['track'][t - 1], sigma_x)
for _ in range(rng.poisson(aircraft_rate)):
a = {'entry_time': t, 'track': {t: np.array([rng.uniform(x0, x1), rng.uniform(y0, y1), 0.0, 0.0])}}
aircraft.append(a)
in_flight.append(a)
for a in in_flight:
if rng.random() < detection_prob(a['track'][t]):
blips.append({'time': t, 'source': a, 'z': rng.multivariate_normal(H @ a['track'][t], sigma_z)})
for _ in range(rng.poisson(false_alarm_rate)):
blips.append({'time': t, 'source': None, 'z': np.array([rng.uniform(x0, x1), rng.uniform(y0, y1)])})
return aircraft, blips
# ______________________________________________________________________________
# [Figure 15.11] Generative program for optical character recognition
# A 3 x 5 pixel font for the lowercase letters, one string of 15 bits per letter, row by row
FONT = dict(zip(string.ascii_lowercase, [
'010101111101101', '110101110101110', '011100100100011', '110101101101110', '111100110100111',
'111100110100100', '011100101101011', '101101111101101', '111010010010111', '001001001101010',
'101101110101101', '100100100100111', '101111111101101', '110101101101101', '010101101101010',
'110101110100100', '010101101011001', '110101110101101', '011100010001110', '111010010010010',
'101101101101111', '101101101101010', '101101111111101', '101101010101101', '101101010010010',
'111001010100111']))
def generate_letters(lam, rng=None, alphabet=string.ascii_lowercase):
"""GENERATE-LETTERS: n ~ Poisson(lam) letters, each chosen uniformly."""
rng = rng or np.random.default_rng()
return [str(rng.choice(list(alphabet))) for _ in range(rng.poisson(lam))]
def render(letters, width, height, text_top=10, text_left=10):
"""RENDER: a clean image with width rows and height columns (the book's
names), 1.0 where a letter of the 3 x 5 font is drawn and 0.0 elsewhere;
letters that do not fit are cut."""
image = np.zeros((width, height))
for k, letter in enumerate(letters):
glyph = np.array([int(b) for b in FONT[letter]]).reshape(5, 3)
left = text_left + 4 * k
rows = slice(text_top, min(width, text_top + 5))
cols = slice(left, min(height, left + 3))
if left < height and text_top < width:
image[rows, cols] = glyph[:rows.stop - rows.start, :cols.stop - cols.start]
return image
def render_noisy_image(letters, width, height, rng=None):
"""RENDER-NOISY-IMAGE: the clean rendering plus Gaussian noise at every pixel,
with a variance drawn uniformly from 0.1 to 1."""
rng = rng or np.random.default_rng()
clean_image = render(letters, width, height, text_top=10, text_left=10)
noise_variance = rng.uniform(0.1, 1)
return rng.normal(clean_image, np.sqrt(noise_variance))
def generate_image(rng=None):
"""GENERATE-IMAGE: about 10 letters rendered as a noisy 32 x 128 image;
returns the letters too, so that inference can be checked against them."""
rng = rng or np.random.default_rng()
letters = generate_letters(10, rng)
return letters, render_noisy_image(letters, 32, 128, rng)
# ______________________________________________________________________________
# [Figure 15.15] Letters generated by a letter bigram model
def letter_bigram_model(words):
"""MARKOV-INITIAL and MARKOV-TRANSITION estimated from a list of words: the
distribution of first letters, and for each letter the distribution of the
letter that follows it."""
words = [w.lower() for w in words if w.isalpha() and w.isascii()]
initial = Counter(w[0] for w in words)
transition = defaultdict(Counter)
for w in words:
for a, b in zip(w, w[1:]):
transition[a][b] += 1
def normalize(counts):
total = sum(counts.values())
return {c: n / total for c, n in counts.items()}
return normalize(initial), {a: normalize(c) for a, c in transition.items()}
def generate_markov_letters(lam, initial, transition, rng=None):
"""GENERATE-MARKOV-LETTERS: n ~ Poisson(lam) letters, the first drawn from
initial and each next one from the transition distribution of the letter
before it (from initial again after a letter with no recorded successor)."""
rng = rng or np.random.default_rng()
letters, letter_probs = [], initial
for _ in range(rng.poisson(lam)):
letters.append(str(rng.choice(list(letter_probs), p=list(letter_probs.values()))))
letter_probs = transition.get(letters[-1], initial)
return letters