-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStochastic_Sampling.py
More file actions
1648 lines (1465 loc) · 69.7 KB
/
Copy pathStochastic_Sampling.py
File metadata and controls
1648 lines (1465 loc) · 69.7 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Reusable plotting and simulation helpers for the stochastic sampling notebook.
This module turns the original notebook cells into callable functions so the
notebook can keep short, readable cells that delegate the implementation here.
"""
import time
from dataclasses import dataclass
import matplotlib
import numpy as np
from IPython.display import display
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
from matplotlib.pyplot import *
from numpy import *
from scipy.stats import norm
try:
import pymc as pm
except ImportError: # pragma: no cover - optional dependency in this project
pm = None
def render_figure(fig, *, close_figure=True):
"""Display a matplotlib figure using the notebook-friendly pattern."""
display(fig)
if close_figure:
close(fig)
return fig
def animated_frame(fig, pause=1.5):
"""Display an animation frame in-place and optionally sleep."""
display_handle = getattr(fig, "_stochastic_sampling_display_handle", None)
if display_handle is None:
display_handle = display(fig, display_id=True)
setattr(fig, "_stochastic_sampling_display_handle", display_handle)
else:
display_handle.update(fig)
if pause:
time.sleep(pause)
def get_demo_grid(points=100, xmin=-5, xmax=5):
"""Return a standard x-grid used by the early 1D examples."""
return linspace(xmin, xmax, points, endpoint=False)
def f(x):
"""Mixture of Gaussians used for integral examples."""
return exp(-(x - 1) ** 2) + exp(-(x + 2) ** 2) / 2.0
def g(x):
"""Narrow Gaussian used to motivate importance sampling."""
return exp(-100 * (x - 1) ** 2)
def _plot_bar_samples(ax, sample_points, func, width, facecolor="#aa3333"):
for sample in sample_points:
ax.add_patch(
Rectangle(
(sample - width / 2.0, 0.0),
width,
func(sample),
facecolor=facecolor,
)
)
def plot_integral_function(points=100, xmin=-5, xmax=5):
"""Plot the target function whose integral we want to estimate."""
x = get_demo_grid(points=points, xmin=xmin, xmax=xmax)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
ax.text(-4.5, 0.9, r"$\int_{-\infty}^\infty f(x) \, \mathrm{d}x$", fontsize=12)
render_figure(fig)
return fig
def plot_regular_sampling(samples=40, xmin=-5, xmax=5, points=100):
"""Show regular-bin integration for the function f."""
x = get_demo_grid(points=points, xmin=xmin, xmax=xmax)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
ax.text(-4.5, 0.9, r"$\sum_{-5}^5 \,\Delta x f(x_i)$", fontsize=12)
width = (xmax - xmin) / samples
sample_points = linspace(xmin, xmax, samples, endpoint=False)
_plot_bar_samples(ax, sample_points, f, width)
render_figure(fig)
approximation = sum(f(sample_points)) * (xmax - xmin) / samples
print("Value of Integral = ", 1.5 * sqrt(pi))
print("Approximation = ", approximation)
return fig, approximation
def plot_uniform_sampling(samples=200, xmin=-5, xmax=5, points=100, seed=None):
"""Show Monte Carlo integration with uniformly distributed samples."""
if seed is not None:
random.seed(seed)
x = get_demo_grid(points=points, xmin=xmin, xmax=xmax)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
ax.text(-4.5, 0.8, r"$\frac{\mathrm{range}}{N} \sum_i \,f(x_i)$", fontsize=12)
width = 0.1
sample_points = random.uniform(xmin, xmax, samples)
_plot_bar_samples(ax, sample_points, f, width)
render_figure(fig)
approximation = sum(f(sample_points)) * (xmax - xmin) / samples
print("N = number of samples = ", samples)
print("Value of Integral = ", 1.5 * sqrt(pi))
print("Approximation = ", approximation)
return fig, approximation
def plot_narrow_function_uniform_sampling(samples=200, xmin=-5, xmax=5, points=100, seed=None):
"""Show the failure mode of uniform sampling on a narrow target."""
if seed is not None:
random.seed(seed)
x = get_demo_grid(points=points, xmin=xmin, xmax=xmax)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, g(x))
ax.text(-4.5, 0.8, r"$\frac{\mathrm{range}}{N}\sum_i \,f(x_i)$", fontsize=12)
ax.set_xlim((xmin, xmax))
width = 0.05
sample_points = random.uniform(xmin, xmax, samples)
_plot_bar_samples(ax, sample_points, g, width)
render_figure(fig)
approximation = sum(g(sample_points)) * (xmax - xmin) / samples
print("samples =", samples)
print("Value of Integral = ", sqrt(pi / 100))
print("Approximation = ", approximation)
return fig, approximation
def plot_importance_sampling(samples=200, mean=1.0, scale=0.2, points=100, seed=None):
"""Show importance sampling with a Gaussian proposal."""
if seed is not None:
random.seed(seed)
x = get_demo_grid(points=points)
proposal = norm(loc=mean, scale=scale)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, g(x))
ax.plot(x, proposal.pdf(x) / 2.0, "r")
ax.text(-4.5, 0.8, r"$\frac{\mathrm{range}}{N}\sum_i w_if(x_i)$", fontsize=12)
width = 0.05
sample_points = proposal.rvs(size=samples)
_plot_bar_samples(ax, sample_points, g, width)
render_figure(fig)
approximation = 1.0 / samples * sum(g(sample_points) / proposal.pdf(sample_points))
print("samples = ", samples)
print("Value of Integral = ", sqrt(pi / 100))
print("Approximation = ", approximation)
return fig, approximation
def plot_ideal_importance_sampling(samples=1, points=100, seed=None):
"""Show the near-ideal proposal for the narrow Gaussian example."""
if seed is not None:
random.seed(seed)
x = get_demo_grid(points=points)
proposal = norm(loc=1, scale=sqrt(0.005))
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, g(x))
ax.plot(x, proposal.pdf(x) / 6, "r")
ax.text(-4.5, 0.8, r"$\frac{\mathrm{range}}{N}\sum_i w_if(x_i)$", fontsize=12)
width = 1.0 / samples
sample_points = proposal.rvs(size=samples)
_plot_bar_samples(ax, sample_points, g, width)
render_figure(fig)
approximation = 1.0 / samples * sum(g(sample_points) / proposal.pdf(sample_points))
print("samples = ", samples)
print("Value of Integral = ", sqrt(pi / 100))
print("Approximation = ", approximation)
return fig, approximation
def animate_rejection_sampling(samples=50, xmin=-5, xmax=5, seed=None, pause=0.1):
"""Animate rejection sampling on the function f."""
if seed is not None:
random.seed(seed)
x = get_demo_grid()
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
sample_points = random.uniform(xmin, xmax, samples)
sample_heights = random.uniform(0, 1.2, samples)
for index in range(samples):
facecolor = "red" if sample_heights[index] > f(sample_points[index]) else "green"
ax.add_patch(
matplotlib.patches.Ellipse(
(sample_points[index], sample_heights[index]),
0.2,
0.03,
facecolor=facecolor,
edgecolor="none",
)
)
animated_frame(fig, pause=pause)
print("samples = ", samples)
close(fig)
return fig
def build_metropolis_patch_collection(sample_points, heights, colors):
"""Build a patch collection for the multi-particle Metropolis demo."""
dots = []
for index in range(sample_points.size):
dots.append(
matplotlib.patches.Ellipse(
(sample_points[index], heights[index] * f(sample_points[index])),
0.2,
0.03,
facecolor=colors[index],
edgecolor="none",
)
)
return PatchCollection(dots, match_original=True)
def metropolis_step(sample_points, target_function=f, proposal_scale=1.0):
"""Single Metropolis update for all sample points."""
delta = random.normal(0, proposal_scale, sample_points.size)
proposed = sample_points + delta
updated = sample_points.copy()
for index in range(sample_points.size):
if target_function(proposed[index]) < target_function(sample_points[index]):
if random.rand() < target_function(proposed[index]) / target_function(sample_points[index]):
updated[index] = proposed[index]
else:
updated[index] = proposed[index]
return updated
def animate_metropolis_sampling(samples=100, n_frames=10, moves_per_frame=2, seed=None, pause=0.5):
"""Animate the many-particle Metropolis sampler converging on f."""
if seed is not None:
random.seed(seed)
x = get_demo_grid()
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
sample_points = random.uniform(-5, 5, samples)
heights = random.uniform(0, 1, samples)
color_values = random.randint(0, 255, (samples, 3))
colors = ["#%02X%02X%02X" % tuple(rgb) for rgb in color_values]
for _ in range(n_frames):
patch_collection = build_metropolis_patch_collection(sample_points, heights, colors)
ax.add_collection(patch_collection)
animated_frame(fig, pause=pause)
for _ in range(moves_per_frame):
sample_points = metropolis_step(sample_points)
patch_collection.remove()
print("samples = ", samples)
close(fig)
return fig
def animate_single_chain_metropolis(samples=1, sigma=1.0, n_steps=10, seed=None, pause=3.0):
"""Animate the single-chain Metropolis proposal/accept cycle."""
if seed is not None:
random.seed(seed)
x = get_demo_grid()
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
current = -1.0
proposal = norm(loc=current, scale=sigma)
current_patch = matplotlib.patches.Ellipse(
(current, f(current)), 0.2, 0.03, facecolor="green", edgecolor="none"
)
ax.add_patch(current_patch)
proposal_line = ax.plot(x, proposal.pdf(x), "g")
animated_frame(fig, pause=2.0)
for _ in range(n_steps):
delta = random.normal(0, sigma, samples)
candidate = current + delta
candidate_patch = matplotlib.patches.Rectangle(
(candidate - 0.1, f(candidate) - 0.02),
0.2,
0.04,
facecolor="red",
edgecolor="none",
)
ax.add_patch(current_patch)
ax.add_patch(candidate_patch)
animated_frame(fig, pause=pause)
if f(candidate) < f(current):
if random.rand() < f(candidate) / f(current):
current = candidate
else:
current = candidate
proposal_line.pop(0).remove()
candidate_patch.remove()
proposal = norm(loc=current, scale=sigma)
current_patch = matplotlib.patches.Ellipse(
(current, f(current)), 0.2, 0.03, facecolor="green", edgecolor="none"
)
ax.add_patch(current_patch)
proposal_line = ax.plot(x, proposal.pdf(x), "g")
animated_frame(fig, pause=pause)
close(fig)
return fig
def plot_metropolis_hastings_bias(points=100):
"""Illustrate the asymmetric proposal in the Metropolis-Hastings section."""
x = get_demo_grid(points=points)
fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, f(x))
current = 0.0
proposal = norm(loc=current - 1, scale=1)
current_patch = matplotlib.patches.Ellipse(
(current, f(current)), 0.2, 0.03, facecolor="green", edgecolor="none"
)
ax.add_patch(current_patch)
ax.plot(x, proposal.pdf(x), "g")
fill_x = x[: int(x.size / 2 + 1)].copy()
fill_y = proposal.pdf(fill_x)
fill_x[-1] = fill_x[-2]
fill_y[-1] = 0
fill(fill_x, fill_y, facecolor="g", alpha=0.5)
ax.annotate(
"84%",
xy=(-1.5, 0.2),
xytext=(-4, 0.8),
arrowprops=dict(facecolor="g", shrink=0.05),
fontsize=16,
)
return render_figure(fig)
def load_text_message_data(path="txtdata.csv"):
"""Load the text-message count dataset used in the Poisson examples."""
count_data = np.loadtxt(path)
return count_data, len(count_data)
def plot_count_data(path="txtdata.csv", figsize=(12.5, 3.5)):
"""Plot the text-message count time series."""
count_data, n_count_data = load_text_message_data(path)
fig = figure()
fig.set_size_inches(*figsize)
bar(np.arange(n_count_data), count_data, color="#348ABD")
xlabel("Time (days)")
ylabel("count of text-msgs received")
xlim(0, n_count_data)
return render_figure(fig), count_data
def require_pymc():
"""Raise a clear error when PyMC examples are called without PyMC."""
if pm is None:
raise ImportError("PyMC is required for the Bayesian count-data examples.")
def run_single_change_mcmc(count_data, draws=10000, tune=5000, dist='exponential'):
"""Fit the one-change-point Poisson model and return posterior samples."""
require_pymc()
n_count_data = len(count_data)
with pm.Model() as model:
alpha = 1.0 / count_data.mean()
if dist == 'uniform':
lambda_1 = pm.Uniform("lambda_1", lower=0, upper=count_data.max())
lambda_2 = pm.Uniform("lambda_2", lower=0, upper=count_data.max())
else:
lambda_1 = pm.Exponential("lambda_1", alpha)
lambda_2 = pm.Exponential("lambda_2", alpha)
tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data - 1)
idx = np.arange(n_count_data)
lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)
pm.Poisson("obs", lambda_, observed=count_data)
step = pm.Metropolis()
trace = pm.sample(draws, tune=tune, step=step, return_inferencedata=False)
return {
"trace": trace,
"lambda_1_samples": trace["lambda_1"],
"lambda_2_samples": trace["lambda_2"],
"tau_samples": trace["tau"],
"n_count_data": n_count_data,
}
def hdi_of_mcmc(sample_vec, cred_mass=0.95):
"""Compute a highest density interval from MCMC samples."""
assert len(sample_vec), "need points to find HDI"
sorted_pts = sort(sample_vec)
ci_idx_inc = int(floor(cred_mass * len(sorted_pts)))
n_cis = len(sorted_pts) - ci_idx_inc
ci_width = sorted_pts[ci_idx_inc:] - sorted_pts[:n_cis]
min_idx = argmin(ci_width)
hdi_min = sorted_pts[min_idx]
hdi_max = sorted_pts[min_idx + ci_idx_inc]
return hdi_min, hdi_max
def plot_hdi(ax, hdi):
"""Draw a highest density interval marker on an axis."""
hdi_min, hdi_max = hdi
hdi_line, = ax.plot([hdi_min, hdi_max], [0, 0], lw=5.0, color="k")
hdi_line.set_clip_on(False)
ax.text(hdi_min, -0.04, "%.3g" % hdi_min, horizontalalignment="center", verticalalignment="top", color="r")
ax.text(hdi_max, -0.04, "%.3g" % hdi_max, horizontalalignment="center", verticalalignment="top", color="r")
ax.text((hdi_min + hdi_max) / 2, 0.08, "95% HDI", horizontalalignment="center", verticalalignment="bottom")
def plot_single_change_posteriors(lambda_1_samples, lambda_2_samples, tau_samples, n_count_data):
"""Plot posterior marginals for the one-change-point Poisson model."""
fig = figure()
fig.set_size_inches(10, 6)
ax = subplot(311)
ax.set_autoscaley_on(False)
hist(lambda_1_samples, histtype="stepfilled", bins=30, alpha=0.85,
label=r"posterior of $\lambda_1$", color="#A60628", density=True)
plot_hdi(ax, hdi_of_mcmc(lambda_1_samples))
legend(loc="upper right")
title(r"""Posterior distributions of the variables
$\lambda_1, \; \lambda_2, \; \tau$""")
xlim([15, 30])
xlabel(r"$\lambda_1$ value")
ylabel("probability density")
ax = subplot(312)
ax.set_autoscaley_on(False)
hist(lambda_2_samples, histtype="stepfilled", bins=30, alpha=0.85,
label=r"posterior of $\lambda_2$", color="#7A68A6", density=True)
plot_hdi(ax, hdi_of_mcmc(lambda_2_samples))
legend(loc="upper right")
xlim([15, 30])
xlabel(r"$\lambda_2$ value")
ylabel("probability density")
subplot(313)
weights = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)
hist(tau_samples, bins=n_count_data, alpha=1, label=r"posterior of $\tau$",
color="#467821", weights=weights, rwidth=2.0, width=0.4)
xticks(np.arange(n_count_data))
legend(loc="upper right")
ylim([0, 0.75])
xlim([35, n_count_data - 20])
xlabel(r"$\tau$ (in days)")
ylabel("probability")
render_figure(fig)
return fig
def run_three_segment_mcmc(count_data, draws=10000, tune=5000, seed=42):
"""Fit the three-rate Poisson change-point model and return posterior samples."""
require_pymc()
random.seed(seed)
n_count_data = len(count_data)
with pm.Model() as model:
alpha = 1.0 / count_data.mean()
lambda_1 = pm.Exponential("lambda_1", alpha)
lambda_2 = pm.Exponential("lambda_2", alpha)
lambda_3 = pm.Exponential("lambda_3", alpha)
tau_1 = pm.DiscreteUniform("tau_1", lower=0, upper=30)
tau_2 = pm.DiscreteUniform("tau_2", lower=40, upper=n_count_data - 1)
idx = np.arange(n_count_data)
lambda__ = pm.math.switch(tau_1 > idx, lambda_1, lambda_2)
lambda_ = pm.math.switch(tau_2 > idx, lambda__, lambda_3)
pm.Poisson("obs", lambda_, observed=count_data)
step = pm.Metropolis()
trace = pm.sample(draws, tune=tune, step=step, return_inferencedata=False)
return {
"trace": trace,
"lambda_1_samples": trace["lambda_1"],
"lambda_2_samples": trace["lambda_2"],
"lambda_3_samples": trace["lambda_3"],
"tau_1_samples": trace["tau_1"],
"tau_2_samples": trace["tau_2"],
"n_count_data": n_count_data,
}
def plot_three_segment_posteriors(lambda_1_samples, lambda_2_samples, lambda_3_samples,
tau_1_samples, tau_2_samples, n_count_data):
"""Plot posterior marginals for the three-segment Poisson model."""
fig = figure()
fig.set_size_inches(10, 10)
ax = subplot(511)
ax.set_autoscaley_on(False)
hist(lambda_1_samples, histtype="stepfilled", bins=30, alpha=0.85,
label=r"posterior of $\lambda_1$", color="#A60628", density=True)
plot_hdi(ax, hdi_of_mcmc(lambda_1_samples))
legend(loc="upper right")
title(r"""Posterior distributions of the variables
$\lambda_1, \; \lambda_2, \; \lambda_3, \; \tau_1, \; \tau_2$""")
xlim([5, 30])
xlabel(r"$\lambda_1$ value")
ylabel("probability density")
ax = subplot(512)
ax.set_autoscaley_on(False)
hist(lambda_2_samples, histtype="stepfilled", bins=30, alpha=0.85,
label=r"posterior of $\lambda_2$", color="#7A68A6", density=True)
plot_hdi(ax, hdi_of_mcmc(lambda_2_samples))
legend(loc="upper right")
xlim([5, 30])
xlabel(r"$\lambda_2$ value")
ylabel("probability density")
ax = subplot(513)
ax.set_autoscaley_on(False)
hist(lambda_3_samples, histtype="stepfilled", bins=30, alpha=0.85,
label=r"posterior of $\lambda_3$", color="#3A68A6", density=True)
plot_hdi(ax, hdi_of_mcmc(lambda_3_samples))
legend(loc="upper right")
xlim([5, 30])
xlabel(r"$\lambda_3$ value")
ylabel("probability density")
subplot(514)
weights = 1.0 / tau_1_samples.shape[0] * ones_like(tau_1_samples)
hist(tau_1_samples, bins=n_count_data, alpha=1, label=r"posterior of $\tau_1$",
color="#467821", weights=weights, rwidth=2.0, width=0.4)
xticks(arange(n_count_data))
legend(loc="upper right")
ylim([0, 1])
xlim([20, 40])
xlabel(r"$\tau_1$ (in days)")
ylabel("probability")
subplot(515)
weights = 1.0 / tau_2_samples.shape[0] * ones_like(tau_2_samples)
hist(tau_2_samples, bins=n_count_data, alpha=1, label=r"posterior of $\tau_2$",
color="#663821", weights=weights, rwidth=2.0, width=0.4)
xticks(arange(n_count_data))
legend(loc="upper right")
ylim([0, 1])
xlim([35, 55])
xlabel(r"$\tau_2$ (in days)")
ylabel("probability")
render_figure(fig)
return fig
def kalman_smoother_up_to(t_end, obs, proc_noise, obs_noise_sd):
"""Kalman filter + RTS smoother on obs[0..t_end]."""
horizon = t_end + 1
m = zeros(horizon)
P = zeros(horizon)
m_pred = zeros(horizon)
P_pred = zeros(horizon)
P_pred[0] = 1.0
K = P_pred[0] / (P_pred[0] + obs_noise_sd ** 2)
m[0] = K * obs[0]
P[0] = (1 - K) * P_pred[0]
for step in range(1, horizon):
m_pred[step] = m[step - 1]
P_pred[step] = P[step - 1] + proc_noise ** 2
K = P_pred[step] / (P_pred[step] + obs_noise_sd ** 2)
m[step] = m_pred[step] + K * (obs[step] - m_pred[step])
P[step] = (1 - K) * P_pred[step]
ms = m.copy()
Ps = P.copy()
for step in range(horizon - 2, -1, -1):
G = P[step] / P_pred[step + 1]
ms[step] = m[step] + G * (ms[step + 1] - m_pred[step + 1])
Ps[step] = P[step] + G ** 2 * (Ps[step + 1] - P_pred[step + 1])
return ms, sqrt(Ps)
def systematic_resample(weights, rng_module=random):
"""Systematic resampling indices for a vector of normalised weights."""
cumulative = cumsum(weights)
n_particles = weights.size
u0 = rng_module.uniform(0, 1.0 / n_particles)
u = u0 + arange(n_particles) / n_particles
return searchsorted(cumulative, u)
def generate_linear_gaussian_data(n_timesteps, process_noise, obs_noise, d=1, seed=42):
"""Generate synthetic state-space data for the particle-filter demos."""
random.seed(seed)
if d == 1:
true_x = zeros(n_timesteps)
observations = zeros(n_timesteps)
observations[0] = true_x[0] + random.normal(0, obs_noise)
for step in range(1, n_timesteps):
true_x[step] = true_x[step - 1] + random.normal(0, process_noise)
observations[step] = true_x[step] + random.normal(0, obs_noise)
return true_x, observations
true_x = zeros((n_timesteps, d))
observations = zeros((n_timesteps, d))
observations[0] = true_x[0] + random.normal(0, obs_noise, d)
for step in range(1, n_timesteps):
true_x[step] = true_x[step - 1] + random.normal(0, process_noise, d)
observations[step] = true_x[step] + random.normal(0, obs_noise, d)
return true_x, observations
def make_particle_colors(n_particles, seed=42):
"""Create repeatable pseudo-random colors for particles."""
random.seed(seed)
return array([
"#%02X%02X%02X" % (random.randint(80, 220), random.randint(80, 220), random.randint(80, 220))
for _ in range(n_particles)
])
@dataclass
class ParticleFilterHistory:
rmse_history: list
resample_times: list
def _set_panel_limits(ax, n_timesteps, y_min=-6, y_max=6):
ax.set_xlim(-0.5, n_timesteps - 0.5)
ax.set_ylim(y_min, y_max)
def _plot_weight_histogram(ax, weights, n_particles, ess, did_resample=False, title_suffix=""):
sorted_weights = sort(weights)[::-1]
bar_colors = ["limegreen" if did_resample else "steelblue"] * n_particles
ax.bar(range(n_particles), sorted_weights, color=bar_colors, alpha=0.75)
ax.axhline(1.0 / n_particles, color="orange", linestyle="--", linewidth=1.5, label="Uniform (1/N)")
ax.set_xlabel("Particle (sorted by weight)")
ax.set_ylabel("Weight")
resample_text = "RESAMPLED ✓" if did_resample else "no resample"
ax.set_title(f"Weight distribution — {resample_text}\nESS = {ess:.1f} / {n_particles}{title_suffix}")
ax.set_ylim(0, 1.0)
ax.text(
0.35,
0.75,
f"Particles with >1% weight: {int(sum(weights > 0.01))}\nMax weight: {weights.max():.3f}",
transform=ax.transAxes,
bbox=dict(
boxstyle="round,pad=0.3",
facecolor="lightgreen" if did_resample else "lightblue",
alpha=0.85,
),
)
ax.legend(fontsize=8)
ax.grid(True, alpha=0.3)
def _plot_rmse_panel(ax, rmse_history, n_timesteps, title, label=None, resample_times=None):
ax.plot(range(len(rmse_history)), rmse_history, "r-o", markersize=5, linewidth=2, label=label)
if resample_times:
for resample_time in resample_times:
ax.axvline(resample_time, color="limegreen", linewidth=2, linestyle="--", alpha=0.8)
ax.set_xlim(-0.5, n_timesteps - 0.5)
ax.set_ylim(0, max(rmse_history) * 1.5 + 0.05)
ax.set_xlabel("Time step t")
ax.set_ylabel(label or "RMSE")
ax.set_title(title)
if label is not None:
ax.legend(fontsize=8)
ax.grid(True, alpha=0.3)
def animate_sis_joint_demo(n_particles=50, n_timesteps=25, process_noise=0.5, obs_noise=1.0,
seed=42, pause=0.5, figsize=(14, 10)):
"""Animate SIS on the full 1D trajectory posterior without resampling."""
fig, axes = subplots(2, 2, figsize=figsize)
ax1, ax2, ax3, ax4 = axes.flat
true_x, observations = generate_linear_gaussian_data(n_timesteps, process_noise, obs_noise, seed=seed)
random.seed(seed)
trajectories = zeros((n_particles, n_timesteps))
trajectories[:, 0] = random.normal(0, 1.0, n_particles)
log_weights = -0.5 * ((observations[0] - trajectories[:, 0]) / obs_noise) ** 2
log_weights -= log_weights.max()
weights = exp(log_weights)
weights /= weights.sum()
particle_colors = make_particle_colors(n_particles, seed=seed)
rmse_history = []
for step in range(n_timesteps):
if step > 0:
trajectories[:, step] = trajectories[:, step - 1] + random.normal(0, process_noise, n_particles)
log_lik_t = -0.5 * ((observations[step] - trajectories[:, step]) / obs_noise) ** 2
log_weights += log_lik_t
log_weights -= log_weights.max()
weights = exp(log_weights)
weights /= weights.sum()
ks_mean, ks_std = kalman_smoother_up_to(step, observations, process_noise, obs_noise)
t_range = arange(step + 1)
part_mean = array([sum(weights * trajectories[:, past_step]) for past_step in range(step + 1)])
part_std = array([
sqrt(sum(weights * (trajectories[:, past_step] - part_mean[past_step]) ** 2))
for past_step in range(step + 1)
])
rmse_history.append(sqrt(mean((part_mean - ks_mean) ** 2)))
ax1.clear(); ax2.clear(); ax3.clear(); ax4.clear()
max_w = weights.max()
ax1.plot(true_x[: step + 1], "b-", linewidth=3, label="True state", zorder=5)
ax1.plot(observations[: step + 1], "ro", markersize=6, label="Observations", zorder=5)
for particle in range(n_particles):
alpha = float(0.1 + 0.85 * (weights[particle] / max_w))
linewidth = float(0.3 + 3.0 * (weights[particle] / max_w))
ax1.plot(range(step + 1), trajectories[particle, : step + 1],
color=particle_colors[particle], alpha=alpha, linewidth=linewidth)
ax1.scatter(
step,
trajectories[particle, step],
s=15 + (weights[particle] / max_w) * 180,
c=particle_colors[particle],
zorder=4,
edgecolors="black",
linewidth=0.4,
alpha=0.85,
)
ess = 1.0 / sum(weights ** 2)
_set_panel_limits(ax1, n_timesteps)
ax1.set_xlabel("Time")
ax1.set_ylabel("State")
ax1.set_title(
f"SIS — Joint $p(x_{{0:{step}}} \\mid y_{{0:{step}}})$ (t = {step})\n"
f"ESS = {ess:.1f} / {n_particles} — no resampling"
)
ax1.legend(fontsize=8)
ax1.grid(True, alpha=0.3)
ax2.plot(t_range, true_x[: step + 1], "b-", linewidth=3, zorder=5, label="True state")
ax2.fill_between(t_range, ks_mean - ks_std, ks_mean + ks_std,
color="forestgreen", alpha=0.20, label="KS ±1σ (true posterior)")
ax2.plot(t_range, ks_mean, color="forestgreen", linewidth=2.5, label="KS mean (true posterior)")
ax2.fill_between(t_range, part_mean - part_std, part_mean + part_std,
color="darkorange", alpha=0.20, label="Particle ±1σ")
ax2.plot(t_range, part_mean, color="darkorange", linewidth=2, linestyle="--", label="Particle mean")
_set_panel_limits(ax2, n_timesteps)
ax2.set_xlabel("Time")
ax2.set_ylabel("State")
ax2.set_title(f"Joint estimate quality (t = {step})\nParticle mean vs True posterior")
ax2.legend(fontsize=8)
ax2.grid(True, alpha=0.3)
_plot_weight_histogram(ax3, weights, n_particles, ess, did_resample=False)
_plot_rmse_panel(ax4, rmse_history, n_timesteps,
"Estimation error over time\nRMSE grows as weight degeneracy increases")
tight_layout()
animated_frame(fig, pause=pause)
close(fig)
return ParticleFilterHistory(rmse_history=rmse_history, resample_times=[])
def animate_sis_optimal_joint_demo(n_particles=50, n_timesteps=25, process_noise=0.5, obs_noise=1.0,
seed=42, pause=0.5, figsize=(14, 10)):
"""Animate SIS with the optimal proposal on the full 1D trajectory posterior."""
fig, axes = subplots(2, 2, figsize=figsize)
ax1, ax2, ax3, ax4 = axes.flat
true_x, observations = generate_linear_gaussian_data(n_timesteps, process_noise, obs_noise, seed=seed)
random.seed(seed)
trajectories = zeros((n_particles, n_timesteps))
trajectories[:, 0] = random.normal(0, 1.0, n_particles)
sigma_opt2 = 1.0 / (1.0 / process_noise ** 2 + 1.0 / obs_noise ** 2)
sigma_opt = sqrt(sigma_opt2)
sigma_pred2 = process_noise ** 2 + obs_noise ** 2
log_weights = -0.5 * ((observations[0] - trajectories[:, 0]) / obs_noise) ** 2
log_weights -= log_weights.max()
weights = exp(log_weights)
weights /= weights.sum()
particle_colors = make_particle_colors(n_particles, seed=seed)
rmse_history = []
for step in range(n_timesteps):
if step > 0:
x_prev = trajectories[:, step - 1]
mu_opt = sigma_opt2 * (x_prev / process_noise ** 2 + observations[step] / obs_noise ** 2)
trajectories[:, step] = random.normal(mu_opt, sigma_opt)
log_pred = -0.5 * ((observations[step] - x_prev) ** 2 / sigma_pred2)
log_weights += log_pred
log_weights -= log_weights.max()
weights = exp(log_weights)
weights /= weights.sum()
ks_mean, ks_std = kalman_smoother_up_to(step, observations, process_noise, obs_noise)
t_range = arange(step + 1)
part_mean = array([sum(weights * trajectories[:, past_step]) for past_step in range(step + 1)])
part_std = array([
sqrt(sum(weights * (trajectories[:, past_step] - part_mean[past_step]) ** 2))
for past_step in range(step + 1)
])
rmse_history.append(sqrt(mean((part_mean - ks_mean) ** 2)))
ax1.clear(); ax2.clear(); ax3.clear(); ax4.clear()
max_w = weights.max()
ax1.plot(true_x[: step + 1], "b-", linewidth=3, label="True state", zorder=5)
ax1.plot(observations[: step + 1], "ro", markersize=6, label="Observations", zorder=5)
for particle in range(n_particles):
alpha = float(0.1 + 0.85 * (weights[particle] / max_w))
linewidth = float(0.3 + 3.0 * (weights[particle] / max_w))
ax1.plot(range(step + 1), trajectories[particle, : step + 1],
color=particle_colors[particle], alpha=alpha, linewidth=linewidth)
ax1.scatter(
step,
trajectories[particle, step],
s=15 + (weights[particle] / max_w) * 180,
c=particle_colors[particle],
zorder=4,
edgecolors="black",
linewidth=0.4,
alpha=0.85,
)
ess = 1.0 / sum(weights ** 2)
_set_panel_limits(ax1, n_timesteps)
ax1.set_xlabel("Time")
ax1.set_ylabel("State")
ax1.set_title(f"SIS — Optimal proposal (t = {step})\nESS = {ess:.1f} / {n_particles} — no resampling")
ax1.legend(fontsize=8)
ax1.grid(True, alpha=0.3)
ax2.plot(t_range, true_x[: step + 1], "b-", linewidth=3, zorder=5, label="True state")
ax2.fill_between(t_range, ks_mean - ks_std, ks_mean + ks_std,
color="forestgreen", alpha=0.20, label="KS ±1σ (true posterior)")
ax2.plot(t_range, ks_mean, color="forestgreen", linewidth=2.5, label="KS mean (true posterior)")
ax2.fill_between(t_range, part_mean - part_std, part_mean + part_std,
color="darkorange", alpha=0.20, label="Particle ±1σ")
ax2.plot(t_range, part_mean, color="darkorange", linewidth=2, linestyle="--", label="Particle mean")
_set_panel_limits(ax2, n_timesteps)
ax2.set_xlabel("Time")
ax2.set_ylabel("State")
ax2.set_title(f"Joint estimate quality (t = {step})\nParticle mean vs True posterior")
ax2.legend(fontsize=8)
ax2.grid(True, alpha=0.3)
_plot_weight_histogram(ax3, weights, n_particles, ess, did_resample=False)
_plot_rmse_panel(ax4, rmse_history, n_timesteps, "Estimation error over time\nRMSE with optimal proposal")
tight_layout()
animated_frame(fig, pause=pause)
close(fig)
return ParticleFilterHistory(rmse_history=rmse_history, resample_times=[])
def _configure_pf_figure(figsize):
fig, axes = subplots(2, 2, figsize=figsize)
return fig, axes[0, 0], axes[0, 1], axes[1, 0], axes[1, 1]
def animate_optimal_resampling_demo(n_particles=50, n_timesteps=25, process_noise=0.5, obs_noise=1.0,
seed=42, pause=0.5, figsize=(14, 10)):
"""Animate the 1D optimal-proposal filter with systematic resampling."""
fig, ax1, ax2, ax3, ax4 = _configure_pf_figure(figsize)
true_x, observations = generate_linear_gaussian_data(n_timesteps, process_noise, obs_noise, seed=seed)
random.seed(seed)
lineage = zeros((n_particles, n_timesteps))
particles = random.normal(0, 1.0, n_particles)
lineage[:, 0] = particles.copy()
sigma_opt2 = 1.0 / (1.0 / process_noise ** 2 + 1.0 / obs_noise ** 2)
sigma_opt = sqrt(sigma_opt2)
sigma_pred2 = process_noise ** 2 + obs_noise ** 2
log_w = -0.5 * ((observations[0] - particles) / obs_noise) ** 2
log_w -= log_w.max()
weights = exp(log_w)
weights /= weights.sum()
colors = make_particle_colors(n_particles, seed=seed)
resample_times = []
rmse_history = []
resample_thresh = n_particles / 2
for step in range(n_timesteps):
did_resample = False
if step > 0:
x_prev = particles.copy()
ess = 1.0 / sum(weights ** 2)
if ess < resample_thresh:
idx = systematic_resample(weights)
lineage[:, :step] = lineage[idx, :step]
x_prev = x_prev[idx]
colors = colors[idx]
weights = ones(n_particles) / n_particles
did_resample = True
resample_times.append(step)
mu_opt = sigma_opt2 * (x_prev / process_noise ** 2 + observations[step] / obs_noise ** 2)
particles = random.normal(mu_opt, sigma_opt)
lineage[:, step] = particles
log_incr = -0.5 * ((observations[step] - x_prev) ** 2 / sigma_pred2)
log_incr -= log_incr.max()
weights = weights * exp(log_incr)
weights /= weights.sum()
ks_mean, ks_std = kalman_smoother_up_to(step, observations, process_noise, obs_noise)
t_range = arange(step + 1)
part_mean = array([sum(weights * lineage[:, past_step]) for past_step in range(step + 1)])
part_std = array([
sqrt(sum(weights * (lineage[:, past_step] - part_mean[past_step]) ** 2))
for past_step in range(step + 1)
])
rmse_history.append(sqrt(mean((part_mean - ks_mean) ** 2)))
ax1.clear(); ax2.clear(); ax3.clear(); ax4.clear()
max_w = weights.max()
ax1.plot(true_x[: step + 1], "b-", linewidth=3, label="True state", zorder=5)
ax1.plot(observations[: step + 1], "ro", markersize=6, label="Observations", zorder=5)
for particle in range(n_particles):
alpha = float(0.08 + 0.87 * (weights[particle] / max_w))
linewidth = float(0.3 + 2.7 * (weights[particle] / max_w))
ax1.plot(range(step + 1), lineage[particle, : step + 1],
color=colors[particle], alpha=alpha, linewidth=linewidth)
ax1.scatter(step, particles[particle], s=15 + (weights[particle] / max_w) * 170,
c=colors[particle], zorder=4, edgecolors="black", linewidth=0.4, alpha=0.9)
for resample_time in resample_times:
ax1.axvline(resample_time, color="limegreen", linewidth=2, linestyle="--", alpha=0.8)
if resample_times:
ax1.axvline(resample_times[0], color="limegreen", linewidth=2, linestyle="--", alpha=0.8,
label="Resampling event")
ess = 1.0 / sum(weights ** 2)
_set_panel_limits(ax1, n_timesteps)
ax1.set_xlabel("Time")
ax1.set_ylabel("State")
ax1.set_title(
f"SIS — Optimal proposal + resampling (t = {step})\n"
f"ESS = {ess:.1f} / {n_particles} — threshold = N/2 = {int(resample_thresh)}"
)
ax1.legend(fontsize=8)
ax1.grid(True, alpha=0.3)
ax2.plot(t_range, true_x[: step + 1], "b-", linewidth=3, zorder=5, label="True state")
ax2.fill_between(t_range, ks_mean - ks_std, ks_mean + ks_std,
color="forestgreen", alpha=0.20, label="KS ±1σ (true posterior)")
ax2.plot(t_range, ks_mean, color="forestgreen", linewidth=2.5, label="KS mean (true posterior)")
ax2.fill_between(t_range, part_mean - part_std, part_mean + part_std,
color="darkorange", alpha=0.20, label="Particle ±1σ")
ax2.plot(t_range, part_mean, color="darkorange", linewidth=2, linestyle="--", label="Particle mean")
for resample_time in resample_times:
ax2.axvline(resample_time, color="limegreen", linewidth=2, linestyle="--", alpha=0.8)
_set_panel_limits(ax2, n_timesteps)
ax2.set_xlabel("Time")
ax2.set_ylabel("State")
ax2.set_title(f"Joint estimate quality (t = {step})\nParticle mean vs True posterior")
ax2.legend(fontsize=8)
ax2.grid(True, alpha=0.3)
_plot_weight_histogram(ax3, weights, n_particles, ess, did_resample=did_resample)
_plot_rmse_panel(ax4, rmse_history, n_timesteps,
"Estimation error over time\nRMSE with optimal proposal + resampling",
resample_times=resample_times)
tight_layout()
animated_frame(fig, pause=pause)
print(f"\nResampling occurred at timesteps: {resample_times}")
print(f"Final ESS: {1.0 / sum(weights ** 2):.1f} / {n_particles}")
close(fig)
return ParticleFilterHistory(rmse_history=rmse_history, resample_times=resample_times)
def animate_prior_resampling_demo(n_particles=50, n_timesteps=25, process_noise=0.5, obs_noise=1.0,
seed=42, pause=0.5, figsize=(14, 10)):
"""Animate the 1D prior-proposal filter with systematic resampling."""
fig, ax1, ax2, ax3, ax4 = _configure_pf_figure(figsize)
true_x, observations = generate_linear_gaussian_data(n_timesteps, process_noise, obs_noise, seed=seed)
random.seed(seed)
lineage = zeros((n_particles, n_timesteps))
particles = random.normal(0, 1.0, n_particles)
lineage[:, 0] = particles.copy()
log_w = -0.5 * ((observations[0] - particles) / obs_noise) ** 2
log_w -= log_w.max()
weights = exp(log_w)
weights /= weights.sum()
colors = make_particle_colors(n_particles, seed=seed)
resample_times = []
rmse_history = []
resample_thresh = n_particles / 2
for step in range(n_timesteps):
did_resample = False
if step > 0:
x_prev = particles.copy()
ess = 1.0 / sum(weights ** 2)
if ess < resample_thresh: