statanim 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statanim/__init__.py +0 -0
- statanim/animations/__init__.py +0 -0
- statanim/animations/clt_demo.py +1852 -0
- statanim/animations/flip_roll.py +1851 -0
- statanim/animations/sampling.py +2291 -0
- statanim/animations/transitions.py +1857 -0
- statanim/axes/__init__.py +0 -0
- statanim/axes/axes3d.py +1989 -0
- statanim/axes/grid3d.py +1127 -0
- statanim/axes/number_plane3d.py +1526 -0
- statanim/charts/__init__.py +0 -0
- statanim/charts/bar_chart3d.py +1572 -0
- statanim/charts/box_plot3d.py +1977 -0
- statanim/charts/heat_map3d.py +1639 -0
- statanim/charts/histogram3d.py +1019 -0
- statanim/charts/line_plot3d.py +1891 -0
- statanim/charts/scatter_plot3d.py +1469 -0
- statanim/charts/violin_plot3d.py +1567 -0
- statanim/core/__init__.py +0 -0
- statanim/core/base.py +1585 -0
- statanim/core/colors.py +1373 -0
- statanim/core/math_utils.py +2081 -0
- statanim/core/tex_utils.py +2111 -0
- statanim/distributions/__init__.py +0 -0
- statanim/distributions/base_dist.py +1936 -0
- statanim/distributions/cdf_viz.py +1773 -0
- statanim/distributions/continuous_dists.py +1769 -0
- statanim/distributions/discrete_dists.py +1734 -0
- statanim/distributions/normal3d.py +1877 -0
- statanim/distributions/pdf_viz.py +2247 -0
- statanim/distributions/pmf_viz.py +1936 -0
- statanim/inference/__init__.py +0 -0
- statanim/inference/confidence_interval.py +1693 -0
- statanim/inference/error_types.py +1825 -0
- statanim/inference/hypothesis.py +1821 -0
- statanim/inference/sampling_dist.py +1933 -0
- statanim/probability/__init__.py +0 -0
- statanim/probability/bayes.py +1682 -0
- statanim/probability/prob_tree.py +1478 -0
- statanim/probability/sample_space.py +1642 -0
- statanim/probability/venn3d.py +1857 -0
- statanim/props/__init__.py +0 -0
- statanim/props/card.py +2259 -0
- statanim/props/coin.py +1011 -0
- statanim/props/die.py +1391 -0
- statanim/props/spinner.py +1591 -0
- statanim/props/urn.py +1531 -0
- statanim/regression/__init__.py +0 -0
- statanim/regression/correlation.py +2805 -0
- statanim/regression/regression_plane.py +2286 -0
- statanim/regression/residuals.py +2599 -0
- statanim/scenes/__init__.py +0 -0
- statanim/scenes/demo_bayes.py +2056 -0
- statanim/scenes/demo_clt.py +1756 -0
- statanim/scenes/demo_distributions.py +1905 -0
- statanim/scenes/demo_hypothesis.py +1791 -0
- statanim/ui/__init__.py +0 -0
- statanim/ui/labels.py +1844 -0
- statanim/ui/panels.py +1937 -0
- statanim/ui/table3d.py +1745 -0
- statanim/ui/ticker.py +2007 -0
- statanim-0.1.0.dist-info/METADATA +463 -0
- statanim-0.1.0.dist-info/RECORD +66 -0
- statanim-0.1.0.dist-info/WHEEL +5 -0
- statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
- statanim-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1936 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/distributions/pmf_viz.py
|
|
3
|
+
======================================
|
|
4
|
+
Production-quality probability mass function (PMF) visualizer.
|
|
5
|
+
|
|
6
|
+
Design philosophy
|
|
7
|
+
-----------------
|
|
8
|
+
Discrete distributions require a fundamentally different visual treatment
|
|
9
|
+
from continuous ones. A PMF is a collection of *point masses*, not an
|
|
10
|
+
area under a curve, so the primary geometry is **3D prism bars** — one
|
|
11
|
+
bar per support value k — rather than a smooth stroke.
|
|
12
|
+
|
|
13
|
+
``PMFVisualizer3D`` is built from independent layers, each a public
|
|
14
|
+
VGroup attribute that can be animated separately:
|
|
15
|
+
|
|
16
|
+
bars_group – one 3-faced prism per mass point, height ∝ P(X=k).
|
|
17
|
+
spine – thin baseline connecting all bar feet.
|
|
18
|
+
mean_marker – vertical marker + dot at the expected value.
|
|
19
|
+
mode_marker – marker at the mode (tallest bar).
|
|
20
|
+
regions – highlighted bars (different colour) for P(a≤X≤b).
|
|
21
|
+
cdf_overlay – step-function CDF drawn above the PMF bars.
|
|
22
|
+
title_group – distribution name + parameter label.
|
|
23
|
+
k_labels – integer tick labels below each bar.
|
|
24
|
+
prob_labels – P(X=k) floating above each bar (optional).
|
|
25
|
+
|
|
26
|
+
Key differences from ``PDFVisualizer3D``
|
|
27
|
+
-----------------------------------------
|
|
28
|
+
- No smoothing. Each bar is independent; parameter morphing reshapes
|
|
29
|
+
individual bars rather than warping a continuous curve.
|
|
30
|
+
- Mode ≠ mean in general (Geometric, Poisson at boundary, etc.).
|
|
31
|
+
Both are annotated separately.
|
|
32
|
+
- ``shade_region`` recolours whole bars rather than filling a polygon.
|
|
33
|
+
- CDF is a step function, not a smooth curve.
|
|
34
|
+
- Parameter morphing uses per-bar ``UpdateFromAlphaFunc`` so bar heights
|
|
35
|
+
interpolate independently with no visual coupling.
|
|
36
|
+
|
|
37
|
+
Distribution support
|
|
38
|
+
--------------------
|
|
39
|
+
All PMFs are implemented from closed-form combinatorial expressions using
|
|
40
|
+
the Lanczos log-gamma approximation. No scipy dependency.
|
|
41
|
+
|
|
42
|
+
BernoulliDist(p) support {0, 1}
|
|
43
|
+
BinomialDist(n, p) support {0, …, n}
|
|
44
|
+
GeometricDist(p) support {1, 2, …} (trials-until-success)
|
|
45
|
+
NegBinomialDist(r, p) support {r, r+1, …}
|
|
46
|
+
PoissonDist(lam) support {0, 1, 2, …}
|
|
47
|
+
HypergeometricDist(N, K, n) support {max(0,n+K-N), …, min(n,K)}
|
|
48
|
+
DiscreteUniformDist(a, b) support {a, …, b}
|
|
49
|
+
MultinomialDist(n, probs) marginal bars for each category
|
|
50
|
+
|
|
51
|
+
Classes
|
|
52
|
+
-------
|
|
53
|
+
PMFConfig
|
|
54
|
+
PMFVisualizer3D
|
|
55
|
+
MultiplePMFComparison3D
|
|
56
|
+
PMFDistribution (abstract base)
|
|
57
|
+
BernoulliDist
|
|
58
|
+
BinomialDist
|
|
59
|
+
GeometricDist
|
|
60
|
+
NegBinomialDist
|
|
61
|
+
PoissonDist
|
|
62
|
+
HypergeometricDist
|
|
63
|
+
DiscreteUniformDist
|
|
64
|
+
|
|
65
|
+
Ready-to-render scenes
|
|
66
|
+
----------------------
|
|
67
|
+
BinomialPMFScene
|
|
68
|
+
PoissonPMFScene
|
|
69
|
+
GeometricPMFScene
|
|
70
|
+
PMFComparisonScene
|
|
71
|
+
BinomialNSweepScene
|
|
72
|
+
|
|
73
|
+
Usage
|
|
74
|
+
-----
|
|
75
|
+
from manim import *
|
|
76
|
+
from statanim.distributions.pmf_viz import PMFVisualizer3D, BinomialDist
|
|
77
|
+
|
|
78
|
+
class MyScene(ThreeDScene):
|
|
79
|
+
def construct(self):
|
|
80
|
+
self.set_camera_orientation(phi=65*DEGREES, theta=-50*DEGREES)
|
|
81
|
+
viz = PMFVisualizer3D(BinomialDist(n=10, p=0.4))
|
|
82
|
+
self.play(viz.animate_bars())
|
|
83
|
+
self.play(viz.animate_mean_mode())
|
|
84
|
+
viz.shade_tail_right(k_crit=8)
|
|
85
|
+
self.play(FadeIn(viz.regions))
|
|
86
|
+
self.wait()
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
from __future__ import annotations
|
|
90
|
+
|
|
91
|
+
from dataclasses import dataclass, field
|
|
92
|
+
from typing import List, Tuple, Optional, Callable, Union, Dict, Sequence
|
|
93
|
+
from abc import ABC, abstractmethod
|
|
94
|
+
import math
|
|
95
|
+
import numpy as np
|
|
96
|
+
|
|
97
|
+
from manim import (
|
|
98
|
+
VGroup, VMobject, Polygon, Line, DashedLine, Dot3D,
|
|
99
|
+
Text, MathTex,
|
|
100
|
+
ThreeDScene,
|
|
101
|
+
AnimationGroup, LaggedStart, Succession,
|
|
102
|
+
Create, FadeIn, FadeOut, Transform,
|
|
103
|
+
UpdateFromAlphaFunc, Flash, GrowFromEdge,
|
|
104
|
+
DEGREES, PI, TAU,
|
|
105
|
+
RIGHT, LEFT, UP, DOWN, OUT, IN, ORIGIN,
|
|
106
|
+
X_AXIS, Y_AXIS, Z_AXIS,
|
|
107
|
+
WHITE, BLACK, GRAY, BLUE, GREEN, RED, YELLOW,
|
|
108
|
+
ManimColor, color_to_rgb, rgba_to_color, color_to_rgba,
|
|
109
|
+
rate_functions, smooth,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------------------
|
|
113
|
+
# Shared colour helpers
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def _with_opacity(color: ManimColor, opacity: float) -> ManimColor:
|
|
117
|
+
r, g, b = color_to_rgb(color)
|
|
118
|
+
return rgba_to_color([r, g, b, max(0.0, min(1.0, opacity))])
|
|
119
|
+
|
|
120
|
+
def _darken(color: ManimColor, factor: float = 0.65) -> ManimColor:
|
|
121
|
+
r, g, b = color_to_rgb(color)
|
|
122
|
+
return ManimColor([r * factor, g * factor, b * factor])
|
|
123
|
+
|
|
124
|
+
def _lighten(color: ManimColor, factor: float = 1.35) -> ManimColor:
|
|
125
|
+
r, g, b = color_to_rgb(color)
|
|
126
|
+
return ManimColor([min(r * factor, 1.0), min(g * factor, 1.0), min(b * factor, 1.0)])
|
|
127
|
+
|
|
128
|
+
def _lerp_color(a: ManimColor, b: ManimColor, t: float) -> ManimColor:
|
|
129
|
+
ra, ga, ba = color_to_rgb(a)
|
|
130
|
+
rb, gb, bb = color_to_rgb(b)
|
|
131
|
+
return ManimColor([ra + (rb - ra) * t, ga + (gb - ga) * t, ba + (bb - ba) * t])
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
# Special function — log-gamma (self-contained, matches pdf_viz.py)
|
|
136
|
+
# ---------------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
def _lgamma(x: float) -> float:
|
|
139
|
+
"""Natural log of the gamma function via Lanczos approximation."""
|
|
140
|
+
g = 7
|
|
141
|
+
c = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
|
|
142
|
+
771.32342877765313, -176.61502916214059, 12.507343278686905,
|
|
143
|
+
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
|
|
144
|
+
if x < 0.5:
|
|
145
|
+
return math.log(PI / math.sin(PI * x)) - _lgamma(1 - x)
|
|
146
|
+
x -= 1
|
|
147
|
+
a = c[0]
|
|
148
|
+
t = x + g + 0.5
|
|
149
|
+
for i in range(1, g + 2):
|
|
150
|
+
a += c[i] / (x + i)
|
|
151
|
+
return 0.5 * math.log(TAU) + (x + 0.5) * math.log(t) - t + math.log(a)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _log_comb(n: int, k: int) -> float:
|
|
155
|
+
"""log C(n, k) = lgamma(n+1) - lgamma(k+1) - lgamma(n-k+1)."""
|
|
156
|
+
if k < 0 or k > n:
|
|
157
|
+
return float("-inf")
|
|
158
|
+
return _lgamma(n + 1) - _lgamma(k + 1) - _lgamma(n - k + 1)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# ===========================================================================
|
|
162
|
+
# Abstract base
|
|
163
|
+
# ===========================================================================
|
|
164
|
+
|
|
165
|
+
class PMFDistribution(ABC):
|
|
166
|
+
"""Abstract base class for all discrete distributions.
|
|
167
|
+
|
|
168
|
+
Subclasses implement ``pmf(k)``, ``cdf(k)``, ``support``, ``mean``,
|
|
169
|
+
``variance``, ``name``, and ``param_string``.
|
|
170
|
+
|
|
171
|
+
The ``support`` property returns the finite or truncated integer range
|
|
172
|
+
that will be displayed. For infinite-support distributions (Geometric,
|
|
173
|
+
Poisson, NegBinomial) a practical truncation at ``P(X > k) < 1e-4`` is
|
|
174
|
+
used.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
@abstractmethod
|
|
178
|
+
def pmf(self, k: int) -> float:
|
|
179
|
+
"""P(X = k)."""
|
|
180
|
+
|
|
181
|
+
def cdf(self, k: int) -> float:
|
|
182
|
+
"""P(X ≤ k) — default: sum pmf from support[0] to k."""
|
|
183
|
+
lo = self.support[0]
|
|
184
|
+
return sum(self.pmf(j) for j in range(lo, k + 1))
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
@abstractmethod
|
|
188
|
+
def support(self) -> List[int]:
|
|
189
|
+
"""Ordered list of integer support values to display."""
|
|
190
|
+
|
|
191
|
+
@property
|
|
192
|
+
@abstractmethod
|
|
193
|
+
def name(self) -> str: ...
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
@abstractmethod
|
|
197
|
+
def param_string(self) -> str: ...
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
@abstractmethod
|
|
201
|
+
def mean(self) -> Optional[float]: ...
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
@abstractmethod
|
|
205
|
+
def variance(self) -> Optional[float]: ...
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def std(self) -> Optional[float]:
|
|
209
|
+
v = self.variance
|
|
210
|
+
return math.sqrt(v) if v is not None and v >= 0 else None
|
|
211
|
+
|
|
212
|
+
def mode(self) -> int:
|
|
213
|
+
"""Return the k in support that maximises pmf(k)."""
|
|
214
|
+
ks = self.support
|
|
215
|
+
return max(ks, key=lambda k: self.pmf(k))
|
|
216
|
+
|
|
217
|
+
def pmf_array(self) -> Tuple[np.ndarray, np.ndarray]:
|
|
218
|
+
"""Return (ks, ps) arrays over the full support."""
|
|
219
|
+
ks = np.array(self.support, dtype=int)
|
|
220
|
+
ps = np.array([self.pmf(int(k)) for k in ks], dtype=float)
|
|
221
|
+
return ks, ps
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ===========================================================================
|
|
225
|
+
# Discrete distributions
|
|
226
|
+
# ===========================================================================
|
|
227
|
+
|
|
228
|
+
class BernoulliDist(PMFDistribution):
|
|
229
|
+
"""Bernoulli(p). Single trial: success (1) or failure (0).
|
|
230
|
+
|
|
231
|
+
Parameters
|
|
232
|
+
----------
|
|
233
|
+
p : float
|
|
234
|
+
P(X = 1) ∈ (0, 1).
|
|
235
|
+
"""
|
|
236
|
+
|
|
237
|
+
def __init__(self, p: float = 0.5):
|
|
238
|
+
if not 0 < p < 1:
|
|
239
|
+
raise ValueError("p must be in (0, 1)")
|
|
240
|
+
self.p = float(p)
|
|
241
|
+
|
|
242
|
+
def pmf(self, k: int) -> float:
|
|
243
|
+
if k == 0:
|
|
244
|
+
return 1.0 - self.p
|
|
245
|
+
if k == 1:
|
|
246
|
+
return self.p
|
|
247
|
+
return 0.0
|
|
248
|
+
|
|
249
|
+
def cdf(self, k: int) -> float:
|
|
250
|
+
if k < 0:
|
|
251
|
+
return 0.0
|
|
252
|
+
if k < 1:
|
|
253
|
+
return 1.0 - self.p
|
|
254
|
+
return 1.0
|
|
255
|
+
|
|
256
|
+
@property
|
|
257
|
+
def support(self) -> List[int]:
|
|
258
|
+
return [0, 1]
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def name(self) -> str:
|
|
262
|
+
return "Bernoulli"
|
|
263
|
+
|
|
264
|
+
@property
|
|
265
|
+
def param_string(self) -> str:
|
|
266
|
+
return f"p = {self.p:.3g}"
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def mean(self) -> float:
|
|
270
|
+
return self.p
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def variance(self) -> float:
|
|
274
|
+
return self.p * (1 - self.p)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
class BinomialDist(PMFDistribution):
|
|
278
|
+
"""Binomial(n, p). Counts of successes in n independent trials.
|
|
279
|
+
|
|
280
|
+
Parameters
|
|
281
|
+
----------
|
|
282
|
+
n : int
|
|
283
|
+
Number of trials.
|
|
284
|
+
p : float
|
|
285
|
+
P(success) per trial.
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
def __init__(self, n: int = 10, p: float = 0.5):
|
|
289
|
+
if n < 1:
|
|
290
|
+
raise ValueError("n must be ≥ 1")
|
|
291
|
+
if not 0 <= p <= 1:
|
|
292
|
+
raise ValueError("p must be in [0, 1]")
|
|
293
|
+
self.n = int(n)
|
|
294
|
+
self.p = float(p)
|
|
295
|
+
|
|
296
|
+
def pmf(self, k: int) -> float:
|
|
297
|
+
if k < 0 or k > self.n:
|
|
298
|
+
return 0.0
|
|
299
|
+
if self.p == 0:
|
|
300
|
+
return 1.0 if k == 0 else 0.0
|
|
301
|
+
if self.p == 1:
|
|
302
|
+
return 1.0 if k == self.n else 0.0
|
|
303
|
+
log_p = (_log_comb(self.n, k)
|
|
304
|
+
+ k * math.log(self.p)
|
|
305
|
+
+ (self.n - k) * math.log(1 - self.p))
|
|
306
|
+
return math.exp(log_p)
|
|
307
|
+
|
|
308
|
+
def cdf(self, k: int) -> float:
|
|
309
|
+
return sum(self.pmf(j) for j in range(max(0, k + 1)))
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def support(self) -> List[int]:
|
|
313
|
+
return list(range(self.n + 1))
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def name(self) -> str:
|
|
317
|
+
return "Binomial"
|
|
318
|
+
|
|
319
|
+
@property
|
|
320
|
+
def param_string(self) -> str:
|
|
321
|
+
return f"n = {self.n}, p = {self.p:.3g}"
|
|
322
|
+
|
|
323
|
+
@property
|
|
324
|
+
def mean(self) -> float:
|
|
325
|
+
return self.n * self.p
|
|
326
|
+
|
|
327
|
+
@property
|
|
328
|
+
def variance(self) -> float:
|
|
329
|
+
return self.n * self.p * (1 - self.p)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
class GeometricDist(PMFDistribution):
|
|
333
|
+
"""Geometric(p). Trials until first success (inclusive).
|
|
334
|
+
|
|
335
|
+
P(X = k) = (1-p)^(k-1) · p, k = 1, 2, 3, …
|
|
336
|
+
|
|
337
|
+
Parameters
|
|
338
|
+
----------
|
|
339
|
+
p : float
|
|
340
|
+
P(success) per trial.
|
|
341
|
+
max_k : int
|
|
342
|
+
Truncation of the support (default: until P(X > max_k) < 1e-5).
|
|
343
|
+
"""
|
|
344
|
+
|
|
345
|
+
def __init__(self, p: float = 0.3, max_k: Optional[int] = None):
|
|
346
|
+
if not 0 < p <= 1:
|
|
347
|
+
raise ValueError("p must be in (0, 1]")
|
|
348
|
+
self.p = float(p)
|
|
349
|
+
if max_k is not None:
|
|
350
|
+
self._max_k = int(max_k)
|
|
351
|
+
else:
|
|
352
|
+
# Truncate at P(X > k) = (1-p)^k < 1e-5
|
|
353
|
+
if p >= 1.0:
|
|
354
|
+
self._max_k = 1
|
|
355
|
+
else:
|
|
356
|
+
self._max_k = int(math.ceil(math.log(1e-5) / math.log(1 - p)))
|
|
357
|
+
self._max_k = min(max(self._max_k, 5), 50)
|
|
358
|
+
|
|
359
|
+
def pmf(self, k: int) -> float:
|
|
360
|
+
if k < 1:
|
|
361
|
+
return 0.0
|
|
362
|
+
return self.p * (1 - self.p) ** (k - 1)
|
|
363
|
+
|
|
364
|
+
def cdf(self, k: int) -> float:
|
|
365
|
+
if k < 1:
|
|
366
|
+
return 0.0
|
|
367
|
+
return 1.0 - (1 - self.p) ** k
|
|
368
|
+
|
|
369
|
+
@property
|
|
370
|
+
def support(self) -> List[int]:
|
|
371
|
+
return list(range(1, self._max_k + 1))
|
|
372
|
+
|
|
373
|
+
@property
|
|
374
|
+
def name(self) -> str:
|
|
375
|
+
return "Geometric"
|
|
376
|
+
|
|
377
|
+
@property
|
|
378
|
+
def param_string(self) -> str:
|
|
379
|
+
return f"p = {self.p:.3g}"
|
|
380
|
+
|
|
381
|
+
@property
|
|
382
|
+
def mean(self) -> float:
|
|
383
|
+
return 1.0 / self.p
|
|
384
|
+
|
|
385
|
+
@property
|
|
386
|
+
def variance(self) -> float:
|
|
387
|
+
return (1 - self.p) / self.p**2
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
class NegBinomialDist(PMFDistribution):
|
|
391
|
+
"""Negative Binomial(r, p). Trials until r-th success.
|
|
392
|
+
|
|
393
|
+
P(X = k) = C(k-1, r-1) · p^r · (1-p)^(k-r), k = r, r+1, …
|
|
394
|
+
|
|
395
|
+
Parameters
|
|
396
|
+
----------
|
|
397
|
+
r : int
|
|
398
|
+
Number of required successes.
|
|
399
|
+
p : float
|
|
400
|
+
P(success) per trial.
|
|
401
|
+
max_k : int or None
|
|
402
|
+
Truncation of support.
|
|
403
|
+
"""
|
|
404
|
+
|
|
405
|
+
def __init__(self, r: int = 3, p: float = 0.4, max_k: Optional[int] = None):
|
|
406
|
+
if r < 1:
|
|
407
|
+
raise ValueError("r must be ≥ 1")
|
|
408
|
+
if not 0 < p <= 1:
|
|
409
|
+
raise ValueError("p must be in (0, 1]")
|
|
410
|
+
self.r = int(r)
|
|
411
|
+
self.p = float(p)
|
|
412
|
+
if max_k is not None:
|
|
413
|
+
self._max_k = int(max_k)
|
|
414
|
+
else:
|
|
415
|
+
mean_k = r / p
|
|
416
|
+
self._max_k = min(int(mean_k + 6 * math.sqrt(r * (1 - p)) / p) + r, 80)
|
|
417
|
+
|
|
418
|
+
def pmf(self, k: int) -> float:
|
|
419
|
+
if k < self.r:
|
|
420
|
+
return 0.0
|
|
421
|
+
log_p = (_log_comb(k - 1, self.r - 1)
|
|
422
|
+
+ self.r * math.log(self.p)
|
|
423
|
+
+ (k - self.r) * math.log(1 - self.p))
|
|
424
|
+
return math.exp(log_p)
|
|
425
|
+
|
|
426
|
+
@property
|
|
427
|
+
def support(self) -> List[int]:
|
|
428
|
+
return list(range(self.r, self._max_k + 1))
|
|
429
|
+
|
|
430
|
+
@property
|
|
431
|
+
def name(self) -> str:
|
|
432
|
+
return "Negative Binomial"
|
|
433
|
+
|
|
434
|
+
@property
|
|
435
|
+
def param_string(self) -> str:
|
|
436
|
+
return f"r = {self.r}, p = {self.p:.3g}"
|
|
437
|
+
|
|
438
|
+
@property
|
|
439
|
+
def mean(self) -> float:
|
|
440
|
+
return self.r / self.p
|
|
441
|
+
|
|
442
|
+
@property
|
|
443
|
+
def variance(self) -> float:
|
|
444
|
+
return self.r * (1 - self.p) / self.p**2
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
class PoissonDist(PMFDistribution):
|
|
448
|
+
"""Poisson(λ). Count of rare events in a fixed interval.
|
|
449
|
+
|
|
450
|
+
P(X = k) = e^(-λ) · λ^k / k!, k = 0, 1, 2, …
|
|
451
|
+
|
|
452
|
+
Parameters
|
|
453
|
+
----------
|
|
454
|
+
lam : float
|
|
455
|
+
Rate parameter λ > 0.
|
|
456
|
+
max_k : int or None
|
|
457
|
+
Truncation of support.
|
|
458
|
+
"""
|
|
459
|
+
|
|
460
|
+
def __init__(self, lam: float = 4.0, max_k: Optional[int] = None):
|
|
461
|
+
if lam <= 0:
|
|
462
|
+
raise ValueError("lam must be > 0")
|
|
463
|
+
self.lam = float(lam)
|
|
464
|
+
if max_k is not None:
|
|
465
|
+
self._max_k = int(max_k)
|
|
466
|
+
else:
|
|
467
|
+
# P(X > max_k) < 1e-5 via Chebyshev-ish heuristic
|
|
468
|
+
self._max_k = min(int(lam + 6 * math.sqrt(lam)) + 5, 100)
|
|
469
|
+
|
|
470
|
+
def pmf(self, k: int) -> float:
|
|
471
|
+
if k < 0:
|
|
472
|
+
return 0.0
|
|
473
|
+
log_p = k * math.log(self.lam) - self.lam - _lgamma(k + 1)
|
|
474
|
+
return math.exp(log_p)
|
|
475
|
+
|
|
476
|
+
def cdf(self, k: int) -> float:
|
|
477
|
+
return sum(self.pmf(j) for j in range(max(0, k + 1)))
|
|
478
|
+
|
|
479
|
+
@property
|
|
480
|
+
def support(self) -> List[int]:
|
|
481
|
+
return list(range(0, self._max_k + 1))
|
|
482
|
+
|
|
483
|
+
@property
|
|
484
|
+
def name(self) -> str:
|
|
485
|
+
return "Poisson"
|
|
486
|
+
|
|
487
|
+
@property
|
|
488
|
+
def param_string(self) -> str:
|
|
489
|
+
return f"λ = {self.lam:.3g}"
|
|
490
|
+
|
|
491
|
+
@property
|
|
492
|
+
def mean(self) -> float:
|
|
493
|
+
return self.lam
|
|
494
|
+
|
|
495
|
+
@property
|
|
496
|
+
def variance(self) -> float:
|
|
497
|
+
return self.lam
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
class HypergeometricDist(PMFDistribution):
|
|
501
|
+
"""Hypergeometric(N, K, n). Draws without replacement.
|
|
502
|
+
|
|
503
|
+
P(X = k) = C(K,k) · C(N-K, n-k) / C(N, n)
|
|
504
|
+
|
|
505
|
+
Parameters
|
|
506
|
+
----------
|
|
507
|
+
N : int
|
|
508
|
+
Population size.
|
|
509
|
+
K : int
|
|
510
|
+
Number of success states in population.
|
|
511
|
+
n : int
|
|
512
|
+
Number of draws.
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
def __init__(self, N: int = 20, K: int = 8, n: int = 5):
|
|
516
|
+
if not (0 < n <= N and 0 <= K <= N):
|
|
517
|
+
raise ValueError("Must have 0 < n ≤ N and 0 ≤ K ≤ N")
|
|
518
|
+
self.N = int(N)
|
|
519
|
+
self.K = int(K)
|
|
520
|
+
self.n = int(n)
|
|
521
|
+
self._lo = max(0, n + K - N)
|
|
522
|
+
self._hi = min(n, K)
|
|
523
|
+
|
|
524
|
+
def pmf(self, k: int) -> float:
|
|
525
|
+
if k < self._lo or k > self._hi:
|
|
526
|
+
return 0.0
|
|
527
|
+
log_p = (_log_comb(self.K, k)
|
|
528
|
+
+ _log_comb(self.N - self.K, self.n - k)
|
|
529
|
+
- _log_comb(self.N, self.n))
|
|
530
|
+
return math.exp(log_p)
|
|
531
|
+
|
|
532
|
+
@property
|
|
533
|
+
def support(self) -> List[int]:
|
|
534
|
+
return list(range(self._lo, self._hi + 1))
|
|
535
|
+
|
|
536
|
+
@property
|
|
537
|
+
def name(self) -> str:
|
|
538
|
+
return "Hypergeometric"
|
|
539
|
+
|
|
540
|
+
@property
|
|
541
|
+
def param_string(self) -> str:
|
|
542
|
+
return f"N={self.N}, K={self.K}, n={self.n}"
|
|
543
|
+
|
|
544
|
+
@property
|
|
545
|
+
def mean(self) -> float:
|
|
546
|
+
return self.n * self.K / self.N
|
|
547
|
+
|
|
548
|
+
@property
|
|
549
|
+
def variance(self) -> float:
|
|
550
|
+
N, K, n = self.N, self.K, self.n
|
|
551
|
+
return n * (K / N) * (1 - K / N) * (N - n) / (N - 1)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
class DiscreteUniformDist(PMFDistribution):
|
|
555
|
+
"""Discrete Uniform(a, b). Equal probability on {a, a+1, …, b}.
|
|
556
|
+
|
|
557
|
+
Parameters
|
|
558
|
+
----------
|
|
559
|
+
a, b : int
|
|
560
|
+
Support endpoints (inclusive).
|
|
561
|
+
"""
|
|
562
|
+
|
|
563
|
+
def __init__(self, a: int = 1, b: int = 6):
|
|
564
|
+
if b < a:
|
|
565
|
+
raise ValueError("b must be ≥ a")
|
|
566
|
+
self.a = int(a)
|
|
567
|
+
self.b = int(b)
|
|
568
|
+
self._p = 1.0 / (b - a + 1)
|
|
569
|
+
|
|
570
|
+
def pmf(self, k: int) -> float:
|
|
571
|
+
return self._p if self.a <= k <= self.b else 0.0
|
|
572
|
+
|
|
573
|
+
def cdf(self, k: int) -> float:
|
|
574
|
+
if k < self.a:
|
|
575
|
+
return 0.0
|
|
576
|
+
if k > self.b:
|
|
577
|
+
return 1.0
|
|
578
|
+
return (k - self.a + 1) * self._p
|
|
579
|
+
|
|
580
|
+
@property
|
|
581
|
+
def support(self) -> List[int]:
|
|
582
|
+
return list(range(self.a, self.b + 1))
|
|
583
|
+
|
|
584
|
+
@property
|
|
585
|
+
def name(self) -> str:
|
|
586
|
+
return "Discrete Uniform"
|
|
587
|
+
|
|
588
|
+
@property
|
|
589
|
+
def param_string(self) -> str:
|
|
590
|
+
return f"a = {self.a}, b = {self.b}"
|
|
591
|
+
|
|
592
|
+
@property
|
|
593
|
+
def mean(self) -> float:
|
|
594
|
+
return (self.a + self.b) / 2
|
|
595
|
+
|
|
596
|
+
@property
|
|
597
|
+
def variance(self) -> float:
|
|
598
|
+
return ((self.b - self.a + 1) ** 2 - 1) / 12
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
# ===========================================================================
|
|
602
|
+
# PMFConfig
|
|
603
|
+
# ===========================================================================
|
|
604
|
+
|
|
605
|
+
@dataclass
|
|
606
|
+
class PMFConfig:
|
|
607
|
+
"""Complete visual configuration for ``PMFVisualizer3D``.
|
|
608
|
+
|
|
609
|
+
Bar geometry
|
|
610
|
+
~~~~~~~~~~~~
|
|
611
|
+
``bar_width`` : width of each bar along x.
|
|
612
|
+
``bar_depth`` : depth of each bar along y.
|
|
613
|
+
``bar_spacing`` : centre-to-centre x distance between bars.
|
|
614
|
+
If 0, auto-computed from support size.
|
|
615
|
+
``z_scale`` : scene z-units for P(X=k) = 1 (the maximum
|
|
616
|
+
possible probability). Actual heights scale
|
|
617
|
+
proportionally so the modal bar reaches
|
|
618
|
+
z_scale × modal_prob.
|
|
619
|
+
|
|
620
|
+
Bar shading
|
|
621
|
+
~~~~~~~~~~~
|
|
622
|
+
``bar_color`` : base colour.
|
|
623
|
+
``side_shade_factor`` : darkness multiplier for the right face.
|
|
624
|
+
``top_shade_factor`` : brightness multiplier for the top face.
|
|
625
|
+
``bar_opacity`` : overall bar opacity.
|
|
626
|
+
``edge_color`` : edge stroke colour.
|
|
627
|
+
``edge_stroke_width`` : edge stroke width.
|
|
628
|
+
``edge_opacity`` : edge stroke opacity.
|
|
629
|
+
``gloss_opacity`` : gloss strip opacity on front face (0 = off).
|
|
630
|
+
``gloss_height_frac`` : height fraction occupied by gloss strip.
|
|
631
|
+
|
|
632
|
+
Region highlighting
|
|
633
|
+
~~~~~~~~~~~~~~~~~~~
|
|
634
|
+
``region_colors`` : colour cycle for highlighted regions.
|
|
635
|
+
``region_opacity`` : opacity of highlighted bars.
|
|
636
|
+
``dimmed_opacity`` : opacity of bars *outside* a highlighted region.
|
|
637
|
+
|
|
638
|
+
Mean / mode markers
|
|
639
|
+
~~~~~~~~~~~~~~~~~~~
|
|
640
|
+
``mean_color`` : colour of the mean marker and annotation.
|
|
641
|
+
``mode_color`` : colour of the mode marker and annotation.
|
|
642
|
+
``marker_stroke_width``: stroke width of marker lines.
|
|
643
|
+
|
|
644
|
+
CDF overlay
|
|
645
|
+
~~~~~~~~~~~
|
|
646
|
+
``cdf_color`` : colour of the CDF step line.
|
|
647
|
+
``cdf_stroke_width`` : stroke width of CDF line.
|
|
648
|
+
``cdf_opacity`` : CDF line opacity.
|
|
649
|
+
``cdf_glow_opacity`` : glow halo opacity behind CDF line.
|
|
650
|
+
|
|
651
|
+
Probability labels
|
|
652
|
+
~~~~~~~~~~~~~~~~~~
|
|
653
|
+
``show_prob_labels`` : show P(X=k) text above each bar.
|
|
654
|
+
``prob_label_font`` : font size.
|
|
655
|
+
``prob_label_decimals``: decimal places.
|
|
656
|
+
``prob_label_threshold``: only label bars where P(X=k) ≥ threshold.
|
|
657
|
+
|
|
658
|
+
Axis labels
|
|
659
|
+
~~~~~~~~~~~
|
|
660
|
+
``show_k_labels`` : show integer k below each bar.
|
|
661
|
+
``k_label_font`` : font size.
|
|
662
|
+
``k_label_step`` : label every k-th value (1 = all, 2 = even, …).
|
|
663
|
+
|
|
664
|
+
Title
|
|
665
|
+
~~~~~
|
|
666
|
+
``show_title`` : show distribution name.
|
|
667
|
+
``title_font`` : font size.
|
|
668
|
+
``show_param_label`` : show parameter string.
|
|
669
|
+
``param_label_font`` : font size.
|
|
670
|
+
|
|
671
|
+
Layout
|
|
672
|
+
~~~~~~
|
|
673
|
+
``x_start`` : x position of the first (leftmost) bar.
|
|
674
|
+
``y_pos`` : y (depth) position.
|
|
675
|
+
``floor_z`` : z-coordinate of bar bases.
|
|
676
|
+
"""
|
|
677
|
+
|
|
678
|
+
# Bar geometry
|
|
679
|
+
bar_width: float = 0.50
|
|
680
|
+
bar_depth: float = 0.35
|
|
681
|
+
bar_spacing: float = 0.0 # 0 = auto
|
|
682
|
+
z_scale: float = 4.0
|
|
683
|
+
|
|
684
|
+
# Bar shading
|
|
685
|
+
bar_color: ManimColor = ManimColor("#4A90D9")
|
|
686
|
+
side_shade_factor: float = 0.62
|
|
687
|
+
top_shade_factor: float = 1.32
|
|
688
|
+
bar_opacity: float = 0.90
|
|
689
|
+
edge_color: ManimColor = WHITE
|
|
690
|
+
edge_stroke_width: float = 0.6
|
|
691
|
+
edge_opacity: float = 0.25
|
|
692
|
+
gloss_opacity: float = 0.14
|
|
693
|
+
gloss_height_frac: float = 0.28
|
|
694
|
+
|
|
695
|
+
# Region highlighting
|
|
696
|
+
region_colors: List[ManimColor] = field(default_factory=lambda: [
|
|
697
|
+
ManimColor("#E8593C"),
|
|
698
|
+
ManimColor("#2DAA6E"),
|
|
699
|
+
ManimColor("#9B59B6"),
|
|
700
|
+
ManimColor("#1ABC9C"),
|
|
701
|
+
])
|
|
702
|
+
region_opacity: float = 0.92
|
|
703
|
+
dimmed_opacity: float = 0.18
|
|
704
|
+
|
|
705
|
+
# Mean / mode markers
|
|
706
|
+
mean_color: ManimColor = ManimColor("#E0AA40")
|
|
707
|
+
mode_color: ManimColor = ManimColor("#E8593C")
|
|
708
|
+
marker_stroke_width: float = 1.8
|
|
709
|
+
|
|
710
|
+
# CDF overlay
|
|
711
|
+
cdf_color: ManimColor = ManimColor("#9B59B6")
|
|
712
|
+
cdf_stroke_width: float = 2.2
|
|
713
|
+
cdf_opacity: float = 0.85
|
|
714
|
+
cdf_glow_opacity: float = 0.12
|
|
715
|
+
|
|
716
|
+
# Probability labels
|
|
717
|
+
show_prob_labels: bool = False
|
|
718
|
+
prob_label_font: int = 14
|
|
719
|
+
prob_label_decimals: int = 3
|
|
720
|
+
prob_label_threshold: float = 0.01
|
|
721
|
+
|
|
722
|
+
# Axis labels
|
|
723
|
+
show_k_labels: bool = True
|
|
724
|
+
k_label_font: int = 16
|
|
725
|
+
k_label_step: int = 1
|
|
726
|
+
|
|
727
|
+
# Title
|
|
728
|
+
show_title: bool = True
|
|
729
|
+
title_font: int = 22
|
|
730
|
+
show_param_label: bool = True
|
|
731
|
+
param_label_font: int = 18
|
|
732
|
+
|
|
733
|
+
# Layout
|
|
734
|
+
x_start: float = 0.0
|
|
735
|
+
y_pos: float = 0.0
|
|
736
|
+
floor_z: float = 0.0
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
# ── Presets ─────────────────────────────────────────────────────────────────
|
|
740
|
+
|
|
741
|
+
MINIMAL_PMF = PMFConfig(
|
|
742
|
+
gloss_opacity=0.0,
|
|
743
|
+
edge_opacity=0.15,
|
|
744
|
+
show_prob_labels=False,
|
|
745
|
+
show_k_labels=True,
|
|
746
|
+
show_title=False,
|
|
747
|
+
show_param_label=False,
|
|
748
|
+
)
|
|
749
|
+
|
|
750
|
+
TEACHING_PMF = PMFConfig(
|
|
751
|
+
gloss_opacity=0.16,
|
|
752
|
+
edge_opacity=0.30,
|
|
753
|
+
show_prob_labels=True,
|
|
754
|
+
prob_label_font=15,
|
|
755
|
+
show_k_labels=True,
|
|
756
|
+
show_title=True,
|
|
757
|
+
show_param_label=True,
|
|
758
|
+
)
|
|
759
|
+
|
|
760
|
+
COMPARISON_PMF = PMFConfig(
|
|
761
|
+
bar_opacity=0.80,
|
|
762
|
+
gloss_opacity=0.08,
|
|
763
|
+
edge_opacity=0.18,
|
|
764
|
+
show_prob_labels=False,
|
|
765
|
+
show_k_labels=True,
|
|
766
|
+
show_title=False,
|
|
767
|
+
show_param_label=False,
|
|
768
|
+
)
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
# ===========================================================================
|
|
772
|
+
# _PMFBar3D — internal
|
|
773
|
+
# ===========================================================================
|
|
774
|
+
|
|
775
|
+
class _PMFBar3D(VGroup):
|
|
776
|
+
"""A single PMF bar: 3-faced prism (front, right, top) with gloss.
|
|
777
|
+
|
|
778
|
+
Matches the geometry of ``Bar3D`` from ``bar_chart3d.py``.
|
|
779
|
+
Stored as three Polygon objects so faces can be independently
|
|
780
|
+
updated during parameter morphing.
|
|
781
|
+
|
|
782
|
+
Parameters
|
|
783
|
+
----------
|
|
784
|
+
x, y_pos, floor_z : float
|
|
785
|
+
Bar centre and floor coordinates.
|
|
786
|
+
width, depth : float
|
|
787
|
+
Bar dimensions.
|
|
788
|
+
height : float
|
|
789
|
+
Bar height (z direction).
|
|
790
|
+
color, side_color, top_color : ManimColor
|
|
791
|
+
bar_opacity : float
|
|
792
|
+
edge_color : ManimColor
|
|
793
|
+
edge_stroke_width, edge_opacity : float
|
|
794
|
+
gloss_opacity, gloss_height_frac : float
|
|
795
|
+
k : int
|
|
796
|
+
Associated k-value (stored for selection logic).
|
|
797
|
+
prob : float
|
|
798
|
+
Associated probability (stored for label logic).
|
|
799
|
+
"""
|
|
800
|
+
|
|
801
|
+
def __init__(
|
|
802
|
+
self,
|
|
803
|
+
x: float,
|
|
804
|
+
y_pos: float,
|
|
805
|
+
floor_z: float,
|
|
806
|
+
width: float,
|
|
807
|
+
depth: float,
|
|
808
|
+
height: float,
|
|
809
|
+
color: ManimColor,
|
|
810
|
+
side_color: ManimColor,
|
|
811
|
+
top_color: ManimColor,
|
|
812
|
+
bar_opacity: float,
|
|
813
|
+
edge_color: ManimColor,
|
|
814
|
+
edge_stroke_width: float,
|
|
815
|
+
edge_opacity: float,
|
|
816
|
+
gloss_opacity: float,
|
|
817
|
+
gloss_height_frac: float,
|
|
818
|
+
k: int = 0,
|
|
819
|
+
prob: float = 0.0,
|
|
820
|
+
**kwargs,
|
|
821
|
+
):
|
|
822
|
+
super().__init__(**kwargs)
|
|
823
|
+
self.k = k
|
|
824
|
+
self.prob = prob
|
|
825
|
+
self._x = x
|
|
826
|
+
self._y = y_pos
|
|
827
|
+
self._floor = floor_z
|
|
828
|
+
self._width = width
|
|
829
|
+
self._depth = depth
|
|
830
|
+
self._height = height
|
|
831
|
+
self._base_color = color
|
|
832
|
+
self._side_color = side_color
|
|
833
|
+
self._top_color = top_color
|
|
834
|
+
self._opacity = bar_opacity
|
|
835
|
+
|
|
836
|
+
hw, hd = width / 2, depth / 2
|
|
837
|
+
z0, z1 = floor_z, floor_z + height
|
|
838
|
+
|
|
839
|
+
# Front face
|
|
840
|
+
self.face_front = Polygon(
|
|
841
|
+
np.array([x-hw, y_pos-hd, z0]),
|
|
842
|
+
np.array([x+hw, y_pos-hd, z0]),
|
|
843
|
+
np.array([x+hw, y_pos-hd, z1]),
|
|
844
|
+
np.array([x-hw, y_pos-hd, z1]),
|
|
845
|
+
fill_color=_with_opacity(color, bar_opacity),
|
|
846
|
+
fill_opacity=1.0, stroke_width=0,
|
|
847
|
+
)
|
|
848
|
+
# Right face
|
|
849
|
+
self.face_right = Polygon(
|
|
850
|
+
np.array([x+hw, y_pos-hd, z0]),
|
|
851
|
+
np.array([x+hw, y_pos+hd, z0]),
|
|
852
|
+
np.array([x+hw, y_pos+hd, z1]),
|
|
853
|
+
np.array([x+hw, y_pos-hd, z1]),
|
|
854
|
+
fill_color=_with_opacity(side_color, bar_opacity * 0.95),
|
|
855
|
+
fill_opacity=1.0, stroke_width=0,
|
|
856
|
+
)
|
|
857
|
+
# Top face
|
|
858
|
+
self.face_top = Polygon(
|
|
859
|
+
np.array([x-hw, y_pos-hd, z1]),
|
|
860
|
+
np.array([x+hw, y_pos-hd, z1]),
|
|
861
|
+
np.array([x+hw, y_pos+hd, z1]),
|
|
862
|
+
np.array([x-hw, y_pos+hd, z1]),
|
|
863
|
+
fill_color=_with_opacity(top_color, bar_opacity * 0.88),
|
|
864
|
+
fill_opacity=1.0, stroke_width=0,
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
# Silhouette edges
|
|
868
|
+
ecol = _with_opacity(edge_color, edge_opacity)
|
|
869
|
+
self.edges = VGroup(*[
|
|
870
|
+
Line(a, b, color=ecol, stroke_width=edge_stroke_width)
|
|
871
|
+
for a, b in [
|
|
872
|
+
(np.array([x-hw,y_pos-hd,z0]), np.array([x+hw,y_pos-hd,z0])),
|
|
873
|
+
(np.array([x+hw,y_pos-hd,z0]), np.array([x+hw,y_pos-hd,z1])),
|
|
874
|
+
(np.array([x+hw,y_pos-hd,z1]), np.array([x-hw,y_pos-hd,z1])),
|
|
875
|
+
(np.array([x-hw,y_pos-hd,z1]), np.array([x-hw,y_pos-hd,z0])),
|
|
876
|
+
(np.array([x+hw,y_pos-hd,z0]), np.array([x+hw,y_pos+hd,z0])),
|
|
877
|
+
(np.array([x+hw,y_pos+hd,z0]), np.array([x+hw,y_pos+hd,z1])),
|
|
878
|
+
(np.array([x+hw,y_pos+hd,z1]), np.array([x+hw,y_pos-hd,z1])),
|
|
879
|
+
(np.array([x-hw,y_pos-hd,z1]), np.array([x+hw,y_pos-hd,z1])),
|
|
880
|
+
(np.array([x+hw,y_pos-hd,z1]), np.array([x+hw,y_pos+hd,z1])),
|
|
881
|
+
(np.array([x-hw,y_pos-hd,z1]), np.array([x-hw,y_pos+hd,z1])),
|
|
882
|
+
(np.array([x-hw,y_pos+hd,z1]), np.array([x+hw,y_pos+hd,z1])),
|
|
883
|
+
]
|
|
884
|
+
])
|
|
885
|
+
|
|
886
|
+
# Gloss strip on front face
|
|
887
|
+
self.gloss = VGroup()
|
|
888
|
+
if gloss_opacity > 0 and height > 0.02:
|
|
889
|
+
gh = height * gloss_height_frac
|
|
890
|
+
zb = z1 - gh
|
|
891
|
+
gloss_poly = Polygon(
|
|
892
|
+
np.array([x-hw, y_pos-hd, zb]),
|
|
893
|
+
np.array([x+hw, y_pos-hd, zb]),
|
|
894
|
+
np.array([x+hw, y_pos-hd, z1]),
|
|
895
|
+
np.array([x-hw, y_pos-hd, z1]),
|
|
896
|
+
fill_color=_with_opacity(WHITE, gloss_opacity),
|
|
897
|
+
fill_opacity=1.0, stroke_width=0,
|
|
898
|
+
)
|
|
899
|
+
self.gloss.add(gloss_poly)
|
|
900
|
+
|
|
901
|
+
self.add(self.face_front, self.face_right, self.face_top,
|
|
902
|
+
self.edges, self.gloss)
|
|
903
|
+
|
|
904
|
+
# ------------------------------------------------------------------
|
|
905
|
+
|
|
906
|
+
def set_height_instant(self, new_height: float) -> None:
|
|
907
|
+
"""Reshape bar to *new_height* immediately (no animation)."""
|
|
908
|
+
self._height = new_height
|
|
909
|
+
x, y = self._x, self._y
|
|
910
|
+
hw, hd = self._width / 2, self._depth / 2
|
|
911
|
+
z0, z1 = self._floor, self._floor + max(new_height, 1e-4)
|
|
912
|
+
|
|
913
|
+
for face, pts in [
|
|
914
|
+
(self.face_front, [
|
|
915
|
+
[x-hw,y-hd,z0],[x+hw,y-hd,z0],
|
|
916
|
+
[x+hw,y-hd,z1],[x-hw,y-hd,z1],[x-hw,y-hd,z0]]),
|
|
917
|
+
(self.face_right, [
|
|
918
|
+
[x+hw,y-hd,z0],[x+hw,y+hd,z0],
|
|
919
|
+
[x+hw,y+hd,z1],[x+hw,y-hd,z1],[x+hw,y-hd,z0]]),
|
|
920
|
+
(self.face_top, [
|
|
921
|
+
[x-hw,y-hd,z1],[x+hw,y-hd,z1],
|
|
922
|
+
[x+hw,y+hd,z1],[x-hw,y+hd,z1],[x-hw,y-hd,z1]]),
|
|
923
|
+
]:
|
|
924
|
+
face.set_points_as_corners([np.array(p) for p in pts])
|
|
925
|
+
|
|
926
|
+
def animate_grow(self, run_time: float = 0.55) -> UpdateFromAlphaFunc:
|
|
927
|
+
"""Grow bar from floor to full height."""
|
|
928
|
+
target = self._height
|
|
929
|
+
x, y = self._x, self._y
|
|
930
|
+
hw, hd = self._width / 2, self._depth / 2
|
|
931
|
+
z0 = self._floor
|
|
932
|
+
cfg_gloss_h = self._height # capture for closure
|
|
933
|
+
|
|
934
|
+
def updater(mob: _PMFBar3D, alpha: float) -> None:
|
|
935
|
+
h = max(smooth(alpha) * target, 1e-4)
|
|
936
|
+
z1 = z0 + h
|
|
937
|
+
mob.face_front.set_points_as_corners([
|
|
938
|
+
np.array([x-hw,y-hd,z0]), np.array([x+hw,y-hd,z0]),
|
|
939
|
+
np.array([x+hw,y-hd,z1]), np.array([x-hw,y-hd,z1]),
|
|
940
|
+
np.array([x-hw,y-hd,z0]),
|
|
941
|
+
])
|
|
942
|
+
mob.face_right.set_points_as_corners([
|
|
943
|
+
np.array([x+hw,y-hd,z0]), np.array([x+hw,y+hd,z0]),
|
|
944
|
+
np.array([x+hw,y+hd,z1]), np.array([x+hw,y-hd,z1]),
|
|
945
|
+
np.array([x+hw,y-hd,z0]),
|
|
946
|
+
])
|
|
947
|
+
mob.face_top.set_points_as_corners([
|
|
948
|
+
np.array([x-hw,y-hd,z1]), np.array([x+hw,y-hd,z1]),
|
|
949
|
+
np.array([x+hw,y+hd,z1]), np.array([x-hw,y+hd,z1]),
|
|
950
|
+
np.array([x-hw,y-hd,z1]),
|
|
951
|
+
])
|
|
952
|
+
|
|
953
|
+
return UpdateFromAlphaFunc(self, updater, run_time=run_time)
|
|
954
|
+
|
|
955
|
+
def highlight(
|
|
956
|
+
self,
|
|
957
|
+
color: ManimColor,
|
|
958
|
+
opacity: float = 0.92,
|
|
959
|
+
) -> "None":
|
|
960
|
+
"""Recolour all faces to a highlight colour."""
|
|
961
|
+
self.face_front.set_fill(_with_opacity(color, opacity))
|
|
962
|
+
self.face_right.set_fill(_with_opacity(_darken(color, 0.62), opacity * 0.95))
|
|
963
|
+
self.face_top.set_fill(_with_opacity(_lighten(color, 1.32), opacity * 0.88))
|
|
964
|
+
|
|
965
|
+
def restore_color(self) -> None:
|
|
966
|
+
"""Restore original colours."""
|
|
967
|
+
op = self._opacity
|
|
968
|
+
self.face_front.set_fill(_with_opacity(self._base_color, op))
|
|
969
|
+
self.face_right.set_fill(_with_opacity(self._side_color, op * 0.95))
|
|
970
|
+
self.face_top.set_fill(_with_opacity(self._top_color, op * 0.88))
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
# ===========================================================================
|
|
974
|
+
# PMFVisualizer3D
|
|
975
|
+
# ===========================================================================
|
|
976
|
+
|
|
977
|
+
class PMFVisualizer3D(VGroup):
|
|
978
|
+
"""Full-featured 3D PMF visualizer for a single discrete distribution.
|
|
979
|
+
|
|
980
|
+
Visual layers (all public VGroup attributes, independently animatable):
|
|
981
|
+
|
|
982
|
+
- ``bars_group`` : one ``_PMFBar3D`` per support value.
|
|
983
|
+
- ``spine`` : thin baseline connecting bar centres.
|
|
984
|
+
- ``mean_marker`` : dashed vertical + dot at E[X].
|
|
985
|
+
- ``mode_marker`` : dashed vertical + dot at mode(X).
|
|
986
|
+
- ``regions`` : re-coloured subsets of bars for P(a≤X≤b).
|
|
987
|
+
- ``cdf_overlay`` : step-function CDF line above bars.
|
|
988
|
+
- ``title_group`` : name + parameter labels.
|
|
989
|
+
- ``k_labels`` : integer labels below each bar.
|
|
990
|
+
- ``prob_labels`` : P(X=k) labels above each bar.
|
|
991
|
+
|
|
992
|
+
Parameters
|
|
993
|
+
----------
|
|
994
|
+
distribution : PMFDistribution
|
|
995
|
+
config : PMFConfig
|
|
996
|
+
scene : ThreeDScene or None
|
|
997
|
+
"""
|
|
998
|
+
|
|
999
|
+
def __init__(
|
|
1000
|
+
self,
|
|
1001
|
+
distribution: PMFDistribution,
|
|
1002
|
+
config: Optional[PMFConfig] = None,
|
|
1003
|
+
scene: Optional[ThreeDScene] = None,
|
|
1004
|
+
**kwargs,
|
|
1005
|
+
):
|
|
1006
|
+
super().__init__(**kwargs)
|
|
1007
|
+
|
|
1008
|
+
self.dist = distribution
|
|
1009
|
+
self.cfg = config if config is not None else PMFConfig()
|
|
1010
|
+
self._scene = scene
|
|
1011
|
+
|
|
1012
|
+
# Compute bar heights in scene units
|
|
1013
|
+
ks_arr, ps_arr = distribution.pmf_array()
|
|
1014
|
+
self._ks: np.ndarray = ks_arr
|
|
1015
|
+
self._ps: np.ndarray = ps_arr
|
|
1016
|
+
self._heights: np.ndarray = ps_arr * self.cfg.z_scale
|
|
1017
|
+
|
|
1018
|
+
# Resolve bar spacing
|
|
1019
|
+
cfg = self.cfg
|
|
1020
|
+
n_bars = len(ks_arr)
|
|
1021
|
+
if cfg.bar_spacing > 0:
|
|
1022
|
+
spacing = cfg.bar_spacing
|
|
1023
|
+
else:
|
|
1024
|
+
# Auto: fit comfortably; wider support → narrower spacing
|
|
1025
|
+
spacing = max(0.50, min(1.00, 6.0 / max(n_bars, 1)))
|
|
1026
|
+
self._spacing = spacing
|
|
1027
|
+
|
|
1028
|
+
# X positions for each bar (centred around x_start)
|
|
1029
|
+
total_width = (n_bars - 1) * spacing
|
|
1030
|
+
self._bar_xs: np.ndarray = (
|
|
1031
|
+
cfg.x_start
|
|
1032
|
+
- total_width / 2
|
|
1033
|
+
+ np.arange(n_bars) * spacing
|
|
1034
|
+
)
|
|
1035
|
+
|
|
1036
|
+
# Override bar width to fit spacing
|
|
1037
|
+
bar_w = min(cfg.bar_width, spacing * 0.82)
|
|
1038
|
+
|
|
1039
|
+
# Derived face colours
|
|
1040
|
+
col_base = cfg.bar_color
|
|
1041
|
+
col_right = _darken(col_base, cfg.side_shade_factor)
|
|
1042
|
+
col_top = _lighten(col_base, cfg.top_shade_factor)
|
|
1043
|
+
|
|
1044
|
+
# Public layer groups
|
|
1045
|
+
self.bars_group = VGroup()
|
|
1046
|
+
self.spine = VGroup()
|
|
1047
|
+
self.mean_marker = VGroup()
|
|
1048
|
+
self.mode_marker = VGroup()
|
|
1049
|
+
self.regions = VGroup()
|
|
1050
|
+
self.cdf_overlay = VGroup()
|
|
1051
|
+
self.title_group = VGroup()
|
|
1052
|
+
self.k_labels = VGroup()
|
|
1053
|
+
self.prob_labels = VGroup()
|
|
1054
|
+
|
|
1055
|
+
# Internal bar references for quick access
|
|
1056
|
+
self._bars: List[_PMFBar3D] = []
|
|
1057
|
+
self._k_to_idx: Dict[int, int] = {}
|
|
1058
|
+
|
|
1059
|
+
# Build layers
|
|
1060
|
+
self._build_bars(bar_w, col_base, col_right, col_top)
|
|
1061
|
+
self._build_spine(bar_w)
|
|
1062
|
+
self._build_mean_mode_markers(scene)
|
|
1063
|
+
if cfg.show_k_labels:
|
|
1064
|
+
self._build_k_labels(bar_w, scene)
|
|
1065
|
+
if cfg.show_prob_labels:
|
|
1066
|
+
self._build_prob_labels(scene)
|
|
1067
|
+
if cfg.show_title:
|
|
1068
|
+
self._build_title(scene)
|
|
1069
|
+
|
|
1070
|
+
self.add(
|
|
1071
|
+
self.spine, self.bars_group,
|
|
1072
|
+
self.mean_marker, self.mode_marker,
|
|
1073
|
+
self.regions, self.cdf_overlay,
|
|
1074
|
+
self.k_labels, self.prob_labels,
|
|
1075
|
+
self.title_group,
|
|
1076
|
+
)
|
|
1077
|
+
|
|
1078
|
+
# ------------------------------------------------------------------
|
|
1079
|
+
# Internal builders
|
|
1080
|
+
# ------------------------------------------------------------------
|
|
1081
|
+
|
|
1082
|
+
def _build_bars(
|
|
1083
|
+
self,
|
|
1084
|
+
bar_w: float,
|
|
1085
|
+
col_base: ManimColor,
|
|
1086
|
+
col_right: ManimColor,
|
|
1087
|
+
col_top: ManimColor,
|
|
1088
|
+
) -> None:
|
|
1089
|
+
cfg = self.cfg
|
|
1090
|
+
for i, (k, p, h, x) in enumerate(
|
|
1091
|
+
zip(self._ks, self._ps, self._heights, self._bar_xs)
|
|
1092
|
+
):
|
|
1093
|
+
bar = _PMFBar3D(
|
|
1094
|
+
x=float(x),
|
|
1095
|
+
y_pos=cfg.y_pos,
|
|
1096
|
+
floor_z=cfg.floor_z,
|
|
1097
|
+
width=bar_w,
|
|
1098
|
+
depth=cfg.bar_depth,
|
|
1099
|
+
height=max(float(h), 1e-4),
|
|
1100
|
+
color=col_base,
|
|
1101
|
+
side_color=col_right,
|
|
1102
|
+
top_color=col_top,
|
|
1103
|
+
bar_opacity=cfg.bar_opacity,
|
|
1104
|
+
edge_color=cfg.edge_color,
|
|
1105
|
+
edge_stroke_width=cfg.edge_stroke_width,
|
|
1106
|
+
edge_opacity=cfg.edge_opacity,
|
|
1107
|
+
gloss_opacity=cfg.gloss_opacity,
|
|
1108
|
+
gloss_height_frac=cfg.gloss_height_frac,
|
|
1109
|
+
k=int(k),
|
|
1110
|
+
prob=float(p),
|
|
1111
|
+
)
|
|
1112
|
+
self._bars.append(bar)
|
|
1113
|
+
self._k_to_idx[int(k)] = i
|
|
1114
|
+
self.bars_group.add(bar)
|
|
1115
|
+
|
|
1116
|
+
def _build_spine(self, bar_w: float) -> None:
|
|
1117
|
+
"""Thin baseline connecting leftmost to rightmost bar foot."""
|
|
1118
|
+
cfg = self.cfg
|
|
1119
|
+
if len(self._bar_xs) < 2:
|
|
1120
|
+
return
|
|
1121
|
+
x0 = float(self._bar_xs[0]) - bar_w / 2
|
|
1122
|
+
x1 = float(self._bar_xs[-1]) + bar_w / 2
|
|
1123
|
+
col = _with_opacity(cfg.bar_color, 0.35)
|
|
1124
|
+
self.spine.add(Line(
|
|
1125
|
+
np.array([x0, cfg.y_pos - cfg.bar_depth / 2, cfg.floor_z]),
|
|
1126
|
+
np.array([x1, cfg.y_pos - cfg.bar_depth / 2, cfg.floor_z]),
|
|
1127
|
+
color=col, stroke_width=1.0,
|
|
1128
|
+
))
|
|
1129
|
+
|
|
1130
|
+
def _build_mean_mode_markers(self, scene: Optional[ThreeDScene]) -> None:
|
|
1131
|
+
cfg = self.cfg
|
|
1132
|
+
mu = self.dist.mean
|
|
1133
|
+
mode_k = self.dist.mode()
|
|
1134
|
+
|
|
1135
|
+
if mu is not None:
|
|
1136
|
+
self._add_float_marker(
|
|
1137
|
+
value=mu,
|
|
1138
|
+
color=cfg.mean_color,
|
|
1139
|
+
label=f"μ = {mu:.3g}",
|
|
1140
|
+
z_extra=0.32,
|
|
1141
|
+
scene=scene,
|
|
1142
|
+
group=self.mean_marker,
|
|
1143
|
+
)
|
|
1144
|
+
|
|
1145
|
+
mode_idx = self._k_to_idx.get(mode_k)
|
|
1146
|
+
if mode_idx is not None:
|
|
1147
|
+
mode_x = float(self._bar_xs[mode_idx])
|
|
1148
|
+
mode_h = float(self._heights[mode_idx])
|
|
1149
|
+
self._add_vertical_marker(
|
|
1150
|
+
x=mode_x,
|
|
1151
|
+
z_top=mode_h + cfg.floor_z + 0.35,
|
|
1152
|
+
color=cfg.mode_color,
|
|
1153
|
+
label=f"mode = {mode_k}",
|
|
1154
|
+
scene=scene,
|
|
1155
|
+
group=self.mode_marker,
|
|
1156
|
+
)
|
|
1157
|
+
|
|
1158
|
+
def _add_float_marker(
|
|
1159
|
+
self,
|
|
1160
|
+
value: float,
|
|
1161
|
+
color: ManimColor,
|
|
1162
|
+
label: str,
|
|
1163
|
+
z_extra: float,
|
|
1164
|
+
scene: Optional[ThreeDScene],
|
|
1165
|
+
group: VGroup,
|
|
1166
|
+
) -> None:
|
|
1167
|
+
"""Add a floating marker at a non-integer x position."""
|
|
1168
|
+
cfg = self.cfg
|
|
1169
|
+
# Interpolate scene x from data value
|
|
1170
|
+
if len(self._ks) < 2:
|
|
1171
|
+
return
|
|
1172
|
+
k_min, k_max = float(self._ks[0]), float(self._ks[-1])
|
|
1173
|
+
t = (value - k_min) / (k_max - k_min) if k_max > k_min else 0.5
|
|
1174
|
+
x_scene = float(self._bar_xs[0]) + t * (float(self._bar_xs[-1]) - float(self._bar_xs[0]))
|
|
1175
|
+
z_pdf = float(self.dist.pmf(int(round(value)))) * cfg.z_scale
|
|
1176
|
+
col = _with_opacity(color, 0.82)
|
|
1177
|
+
|
|
1178
|
+
ln = DashedLine(
|
|
1179
|
+
np.array([x_scene, cfg.y_pos - cfg.bar_depth / 2, cfg.floor_z]),
|
|
1180
|
+
np.array([x_scene, cfg.y_pos - cfg.bar_depth / 2, z_pdf + z_extra]),
|
|
1181
|
+
dash_length=0.07, dashed_ratio=0.45,
|
|
1182
|
+
color=col, stroke_width=cfg.marker_stroke_width,
|
|
1183
|
+
)
|
|
1184
|
+
dot = DashedLine(
|
|
1185
|
+
np.array([x_scene, cfg.y_pos - cfg.bar_depth / 2, cfg.floor_z - 0.07]),
|
|
1186
|
+
np.array([x_scene, cfg.y_pos - cfg.bar_depth / 2, cfg.floor_z + 0.07]),
|
|
1187
|
+
dash_length=1000, dashed_ratio=1.0,
|
|
1188
|
+
color=col, stroke_width=cfg.marker_stroke_width * 2,
|
|
1189
|
+
)
|
|
1190
|
+
lbl = Text(label, font_size=17, color=color)
|
|
1191
|
+
lbl.move_to(np.array([x_scene, cfg.y_pos - cfg.bar_depth / 2, z_pdf + z_extra + 0.28]))
|
|
1192
|
+
group.add(ln, dot, lbl)
|
|
1193
|
+
if scene is not None:
|
|
1194
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1195
|
+
|
|
1196
|
+
def _add_vertical_marker(
|
|
1197
|
+
self,
|
|
1198
|
+
x: float,
|
|
1199
|
+
z_top: float,
|
|
1200
|
+
color: ManimColor,
|
|
1201
|
+
label: str,
|
|
1202
|
+
scene: Optional[ThreeDScene],
|
|
1203
|
+
group: VGroup,
|
|
1204
|
+
) -> None:
|
|
1205
|
+
cfg = self.cfg
|
|
1206
|
+
col = _with_opacity(color, 0.78)
|
|
1207
|
+
ln = Line(
|
|
1208
|
+
np.array([x, cfg.y_pos - cfg.bar_depth / 2, cfg.floor_z]),
|
|
1209
|
+
np.array([x, cfg.y_pos - cfg.bar_depth / 2, z_top]),
|
|
1210
|
+
color=col, stroke_width=cfg.marker_stroke_width,
|
|
1211
|
+
)
|
|
1212
|
+
lbl = Text(label, font_size=17, color=color)
|
|
1213
|
+
lbl.move_to(np.array([x, cfg.y_pos - cfg.bar_depth / 2, z_top + 0.25]))
|
|
1214
|
+
group.add(ln, lbl)
|
|
1215
|
+
if scene is not None:
|
|
1216
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1217
|
+
|
|
1218
|
+
def _build_k_labels(self, bar_w: float, scene: Optional[ThreeDScene]) -> None:
|
|
1219
|
+
cfg = self.cfg
|
|
1220
|
+
for i, (k, x) in enumerate(zip(self._ks, self._bar_xs)):
|
|
1221
|
+
if i % cfg.k_label_step != 0:
|
|
1222
|
+
continue
|
|
1223
|
+
lbl = Text(str(int(k)), font_size=cfg.k_label_font,
|
|
1224
|
+
color=_with_opacity(WHITE, 0.55))
|
|
1225
|
+
lbl.move_to(np.array([
|
|
1226
|
+
float(x),
|
|
1227
|
+
cfg.y_pos - cfg.bar_depth / 2,
|
|
1228
|
+
cfg.floor_z - 0.25,
|
|
1229
|
+
]))
|
|
1230
|
+
self.k_labels.add(lbl)
|
|
1231
|
+
if scene is not None:
|
|
1232
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1233
|
+
|
|
1234
|
+
def _build_prob_labels(self, scene: Optional[ThreeDScene]) -> None:
|
|
1235
|
+
cfg = self.cfg
|
|
1236
|
+
for i, (k, p, h, x) in enumerate(
|
|
1237
|
+
zip(self._ks, self._ps, self._heights, self._bar_xs)
|
|
1238
|
+
):
|
|
1239
|
+
if p < cfg.prob_label_threshold:
|
|
1240
|
+
continue
|
|
1241
|
+
fmt = f"{p:.{cfg.prob_label_decimals}f}"
|
|
1242
|
+
lbl = Text(fmt, font_size=cfg.prob_label_font,
|
|
1243
|
+
color=_with_opacity(WHITE, 0.72))
|
|
1244
|
+
lbl.move_to(np.array([
|
|
1245
|
+
float(x),
|
|
1246
|
+
cfg.y_pos - cfg.bar_depth / 2,
|
|
1247
|
+
cfg.floor_z + float(h) + 0.20,
|
|
1248
|
+
]))
|
|
1249
|
+
self.prob_labels.add(lbl)
|
|
1250
|
+
if scene is not None:
|
|
1251
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1252
|
+
|
|
1253
|
+
def _build_title(self, scene: Optional[ThreeDScene]) -> None:
|
|
1254
|
+
cfg = self.cfg
|
|
1255
|
+
x_cen = float(np.mean(self._bar_xs)) if len(self._bar_xs) > 0 else cfg.x_start
|
|
1256
|
+
z_top = cfg.z_scale * 1.12
|
|
1257
|
+
|
|
1258
|
+
title_lbl = Text(
|
|
1259
|
+
self.dist.name, font_size=cfg.title_font,
|
|
1260
|
+
color=_with_opacity(cfg.bar_color, 0.88),
|
|
1261
|
+
)
|
|
1262
|
+
title_lbl.move_to(np.array([x_cen, cfg.y_pos - cfg.bar_depth / 2, z_top]))
|
|
1263
|
+
self.title_group.add(title_lbl)
|
|
1264
|
+
|
|
1265
|
+
if cfg.show_param_label:
|
|
1266
|
+
param_lbl = Text(
|
|
1267
|
+
self.dist.param_string, font_size=cfg.param_label_font,
|
|
1268
|
+
color=_with_opacity(cfg.bar_color, 0.60),
|
|
1269
|
+
)
|
|
1270
|
+
param_lbl.move_to(np.array([x_cen, cfg.y_pos - cfg.bar_depth / 2, z_top - 0.38]))
|
|
1271
|
+
self.title_group.add(param_lbl)
|
|
1272
|
+
|
|
1273
|
+
for mob in self.title_group:
|
|
1274
|
+
if scene is not None:
|
|
1275
|
+
scene.add_fixed_orientation_mobjects(mob)
|
|
1276
|
+
|
|
1277
|
+
# ------------------------------------------------------------------
|
|
1278
|
+
# Public region API
|
|
1279
|
+
# ------------------------------------------------------------------
|
|
1280
|
+
|
|
1281
|
+
def shade_region(
|
|
1282
|
+
self,
|
|
1283
|
+
k_lo: int,
|
|
1284
|
+
k_hi: int,
|
|
1285
|
+
color: Optional[ManimColor] = None,
|
|
1286
|
+
dim_outside: bool = False,
|
|
1287
|
+
label: bool = True,
|
|
1288
|
+
scene: Optional[ThreeDScene] = None,
|
|
1289
|
+
) -> VGroup:
|
|
1290
|
+
"""Highlight bars for k ∈ [k_lo, k_hi] by recolouring them.
|
|
1291
|
+
|
|
1292
|
+
Parameters
|
|
1293
|
+
----------
|
|
1294
|
+
k_lo, k_hi : int
|
|
1295
|
+
Inclusive range of k values to highlight.
|
|
1296
|
+
color : ManimColor or None
|
|
1297
|
+
Uses next colour from ``cfg.region_colors`` if None.
|
|
1298
|
+
dim_outside : bool
|
|
1299
|
+
If True, dim all bars outside [k_lo, k_hi].
|
|
1300
|
+
label : bool
|
|
1301
|
+
If True, add a P(k_lo ≤ X ≤ k_hi) annotation above the region.
|
|
1302
|
+
scene : ThreeDScene or None
|
|
1303
|
+
|
|
1304
|
+
Returns
|
|
1305
|
+
-------
|
|
1306
|
+
VGroup — the recoloured bars + label, added to ``self.regions``.
|
|
1307
|
+
"""
|
|
1308
|
+
cfg = self.cfg
|
|
1309
|
+
col = (color if color is not None
|
|
1310
|
+
else cfg.region_colors[len(self.regions) % len(cfg.region_colors)])
|
|
1311
|
+
|
|
1312
|
+
region_grp = VGroup()
|
|
1313
|
+
|
|
1314
|
+
# Compute probability
|
|
1315
|
+
p_region = sum(
|
|
1316
|
+
self.dist.pmf(k) for k in self._ks
|
|
1317
|
+
if k_lo <= k <= k_hi
|
|
1318
|
+
)
|
|
1319
|
+
|
|
1320
|
+
for i, (k, bar) in enumerate(zip(self._ks, self._bars)):
|
|
1321
|
+
if k_lo <= k <= k_hi:
|
|
1322
|
+
# Clone face colours to highlight colour
|
|
1323
|
+
bar.face_front.set_fill(_with_opacity(col, cfg.region_opacity))
|
|
1324
|
+
bar.face_right.set_fill(_with_opacity(_darken(col, 0.62), cfg.region_opacity * 0.95))
|
|
1325
|
+
bar.face_top.set_fill(_with_opacity(_lighten(col, 1.32), cfg.region_opacity * 0.88))
|
|
1326
|
+
region_grp.add(bar)
|
|
1327
|
+
elif dim_outside:
|
|
1328
|
+
bar.set_opacity(cfg.dimmed_opacity)
|
|
1329
|
+
|
|
1330
|
+
if label and len(region_grp) > 0:
|
|
1331
|
+
# Position label above the tallest bar in range
|
|
1332
|
+
region_bars = [b for k, b in zip(self._ks, self._bars)
|
|
1333
|
+
if k_lo <= k <= k_hi]
|
|
1334
|
+
max_h = max(b._height for b in region_bars) if region_bars else 0.5
|
|
1335
|
+
x_mid = float(np.mean([b._x for b in region_bars]))
|
|
1336
|
+
lbl = Text(
|
|
1337
|
+
f"P = {p_region:.{cfg.prob_label_decimals}f}",
|
|
1338
|
+
font_size=19,
|
|
1339
|
+
color=col,
|
|
1340
|
+
)
|
|
1341
|
+
lbl.move_to(np.array([
|
|
1342
|
+
x_mid, cfg.y_pos - cfg.bar_depth / 2,
|
|
1343
|
+
cfg.floor_z + max_h + 0.40,
|
|
1344
|
+
]))
|
|
1345
|
+
region_grp.add(lbl)
|
|
1346
|
+
if scene is not None:
|
|
1347
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1348
|
+
|
|
1349
|
+
self.regions.add(region_grp)
|
|
1350
|
+
return region_grp
|
|
1351
|
+
|
|
1352
|
+
def shade_tail_left(
|
|
1353
|
+
self,
|
|
1354
|
+
k_crit: int,
|
|
1355
|
+
label: bool = True,
|
|
1356
|
+
color: Optional[ManimColor] = None,
|
|
1357
|
+
scene: Optional[ThreeDScene] = None,
|
|
1358
|
+
) -> VGroup:
|
|
1359
|
+
"""Highlight P(X ≤ k_crit) — left tail."""
|
|
1360
|
+
return self.shade_region(int(self._ks[0]), k_crit,
|
|
1361
|
+
color=color, label=label, scene=scene)
|
|
1362
|
+
|
|
1363
|
+
def shade_tail_right(
|
|
1364
|
+
self,
|
|
1365
|
+
k_crit: int,
|
|
1366
|
+
label: bool = True,
|
|
1367
|
+
color: Optional[ManimColor] = None,
|
|
1368
|
+
scene: Optional[ThreeDScene] = None,
|
|
1369
|
+
) -> VGroup:
|
|
1370
|
+
"""Highlight P(X ≥ k_crit) — right tail."""
|
|
1371
|
+
return self.shade_region(k_crit, int(self._ks[-1]),
|
|
1372
|
+
color=color, label=label, scene=scene)
|
|
1373
|
+
|
|
1374
|
+
def shade_two_tails(
|
|
1375
|
+
self,
|
|
1376
|
+
alpha: float = 0.05,
|
|
1377
|
+
label: bool = True,
|
|
1378
|
+
color: Optional[ManimColor] = None,
|
|
1379
|
+
scene: Optional[ThreeDScene] = None,
|
|
1380
|
+
) -> VGroup:
|
|
1381
|
+
"""Shade the rejection region for a two-sided test at level *alpha*."""
|
|
1382
|
+
ks = self._ks
|
|
1383
|
+
ps = self._ps
|
|
1384
|
+
# Find critical values from the tails
|
|
1385
|
+
cum_lo = 0.0
|
|
1386
|
+
k_lo = int(ks[0])
|
|
1387
|
+
for k, p in zip(ks, ps):
|
|
1388
|
+
cum_lo += p
|
|
1389
|
+
if cum_lo >= alpha / 2:
|
|
1390
|
+
k_lo = int(k)
|
|
1391
|
+
break
|
|
1392
|
+
cum_hi = 0.0
|
|
1393
|
+
k_hi = int(ks[-1])
|
|
1394
|
+
for k, p in zip(reversed(ks), reversed(ps)):
|
|
1395
|
+
cum_hi += p
|
|
1396
|
+
if cum_hi >= alpha / 2:
|
|
1397
|
+
k_hi = int(k)
|
|
1398
|
+
break
|
|
1399
|
+
g_left = self.shade_tail_left(k_lo, label=label, color=color, scene=scene)
|
|
1400
|
+
g_right = self.shade_tail_right(k_hi, label=label, color=color, scene=scene)
|
|
1401
|
+
return VGroup(g_left, g_right)
|
|
1402
|
+
|
|
1403
|
+
def restore_colors(self) -> None:
|
|
1404
|
+
"""Remove all region highlights and restore original bar colours."""
|
|
1405
|
+
for bar in self._bars:
|
|
1406
|
+
bar.restore_color()
|
|
1407
|
+
bar.set_opacity(1.0)
|
|
1408
|
+
|
|
1409
|
+
# ------------------------------------------------------------------
|
|
1410
|
+
# CDF overlay
|
|
1411
|
+
# ------------------------------------------------------------------
|
|
1412
|
+
|
|
1413
|
+
def build_cdf_overlay(
|
|
1414
|
+
self,
|
|
1415
|
+
scene: Optional[ThreeDScene] = None,
|
|
1416
|
+
) -> VGroup:
|
|
1417
|
+
"""Build a step-function CDF line above the PMF bars.
|
|
1418
|
+
|
|
1419
|
+
The CDF steps up at each k. Returns the VGroup so the caller
|
|
1420
|
+
can animate it with ``Create`` or ``FadeIn``.
|
|
1421
|
+
"""
|
|
1422
|
+
cfg = self.cfg
|
|
1423
|
+
col = _with_opacity(cfg.cdf_color, cfg.cdf_opacity)
|
|
1424
|
+
y = cfg.y_pos - cfg.bar_depth / 2
|
|
1425
|
+
floor = cfg.floor_z
|
|
1426
|
+
|
|
1427
|
+
pts: List[np.ndarray] = []
|
|
1428
|
+
cum = 0.0
|
|
1429
|
+
for k, p, x in zip(self._ks, self._ps, self._bar_xs):
|
|
1430
|
+
z_before = cum * cfg.z_scale
|
|
1431
|
+
cum += p
|
|
1432
|
+
z_after = cum * cfg.z_scale
|
|
1433
|
+
# Horizontal segment at z_before, then vertical jump to z_after
|
|
1434
|
+
pts.append(np.array([float(x) - self._spacing / 2, y, z_before]))
|
|
1435
|
+
pts.append(np.array([float(x) + self._spacing / 2, y, z_before]))
|
|
1436
|
+
pts.append(np.array([float(x) + self._spacing / 2, y, z_after]))
|
|
1437
|
+
|
|
1438
|
+
# Final horizontal to the right
|
|
1439
|
+
if pts:
|
|
1440
|
+
pts.append(np.array([pts[-1][0] + self._spacing * 0.5, y, pts[-1][2]]))
|
|
1441
|
+
|
|
1442
|
+
stroke = VMobject()
|
|
1443
|
+
stroke.set_points_as_corners(pts)
|
|
1444
|
+
stroke.set_stroke(color=col, width=cfg.cdf_stroke_width)
|
|
1445
|
+
stroke.set_fill(opacity=0)
|
|
1446
|
+
|
|
1447
|
+
self.cdf_overlay.add(stroke)
|
|
1448
|
+
|
|
1449
|
+
if cfg.cdf_glow_opacity > 0:
|
|
1450
|
+
glow = VMobject()
|
|
1451
|
+
glow.set_points_as_corners(pts)
|
|
1452
|
+
glow.set_stroke(
|
|
1453
|
+
color=_with_opacity(cfg.cdf_color, cfg.cdf_glow_opacity),
|
|
1454
|
+
width=cfg.cdf_stroke_width * 2.8,
|
|
1455
|
+
)
|
|
1456
|
+
glow.set_fill(opacity=0)
|
|
1457
|
+
self.cdf_overlay.add(glow)
|
|
1458
|
+
|
|
1459
|
+
# CDF label
|
|
1460
|
+
lbl = Text("CDF", font_size=16, color=cfg.cdf_color)
|
|
1461
|
+
if pts:
|
|
1462
|
+
lbl.move_to(pts[-1] + np.array([0.3, 0, 0]))
|
|
1463
|
+
self.cdf_overlay.add(lbl)
|
|
1464
|
+
if scene is not None:
|
|
1465
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1466
|
+
|
|
1467
|
+
return self.cdf_overlay
|
|
1468
|
+
|
|
1469
|
+
# ------------------------------------------------------------------
|
|
1470
|
+
# Parameter morphing
|
|
1471
|
+
# ------------------------------------------------------------------
|
|
1472
|
+
|
|
1473
|
+
def morph_to_distribution(
|
|
1474
|
+
self,
|
|
1475
|
+
new_dist: PMFDistribution,
|
|
1476
|
+
run_time: float = 1.2,
|
|
1477
|
+
update_title: bool = True,
|
|
1478
|
+
scene: Optional[ThreeDScene] = None,
|
|
1479
|
+
) -> AnimationGroup:
|
|
1480
|
+
"""Morph bars to a new distribution over the same support.
|
|
1481
|
+
|
|
1482
|
+
Each bar interpolates independently from its current height to
|
|
1483
|
+
the new PMF value at that k. If the new distribution has a
|
|
1484
|
+
different support, bars outside the new support shrink to zero;
|
|
1485
|
+
new k values not previously visible are not added.
|
|
1486
|
+
|
|
1487
|
+
Parameters
|
|
1488
|
+
----------
|
|
1489
|
+
new_dist : PMFDistribution
|
|
1490
|
+
run_time : float
|
|
1491
|
+
update_title : bool
|
|
1492
|
+
Fade-in new title/param labels.
|
|
1493
|
+
|
|
1494
|
+
Returns
|
|
1495
|
+
-------
|
|
1496
|
+
AnimationGroup
|
|
1497
|
+
"""
|
|
1498
|
+
cfg = self.cfg
|
|
1499
|
+
anims: List = []
|
|
1500
|
+
new_params: Dict[int, float] = {}
|
|
1501
|
+
|
|
1502
|
+
new_ks, new_ps = new_dist.pmf_array()
|
|
1503
|
+
for k, p in zip(new_ks, new_ps):
|
|
1504
|
+
new_params[int(k)] = float(p)
|
|
1505
|
+
|
|
1506
|
+
for i, (k, bar) in enumerate(zip(self._ks, self._bars)):
|
|
1507
|
+
k_int = int(k)
|
|
1508
|
+
old_h = bar._height
|
|
1509
|
+
new_p = new_params.get(k_int, 0.0)
|
|
1510
|
+
new_h = new_p * cfg.z_scale
|
|
1511
|
+
x, y = bar._x, bar._y
|
|
1512
|
+
hw, hd = bar._width / 2, bar._depth / 2
|
|
1513
|
+
z0 = bar._floor
|
|
1514
|
+
|
|
1515
|
+
def make_bar_updater(b, oh, nh, bx, by, bhw, bhd, bz0):
|
|
1516
|
+
def updater(mob, alpha: float) -> None:
|
|
1517
|
+
t = rate_functions.ease_in_out_cubic(alpha)
|
|
1518
|
+
h = max(oh + (nh - oh) * t, 1e-4)
|
|
1519
|
+
z1 = bz0 + h
|
|
1520
|
+
mob.face_front.set_points_as_corners([
|
|
1521
|
+
np.array([bx-bhw,by-bhd,bz0]),
|
|
1522
|
+
np.array([bx+bhw,by-bhd,bz0]),
|
|
1523
|
+
np.array([bx+bhw,by-bhd,z1]),
|
|
1524
|
+
np.array([bx-bhw,by-bhd,z1]),
|
|
1525
|
+
np.array([bx-bhw,by-bhd,bz0]),
|
|
1526
|
+
])
|
|
1527
|
+
mob.face_right.set_points_as_corners([
|
|
1528
|
+
np.array([bx+bhw,by-bhd,bz0]),
|
|
1529
|
+
np.array([bx+bhw,by+bhd,bz0]),
|
|
1530
|
+
np.array([bx+bhw,by+bhd,z1]),
|
|
1531
|
+
np.array([bx+bhw,by-bhd,z1]),
|
|
1532
|
+
np.array([bx+bhw,by-bhd,bz0]),
|
|
1533
|
+
])
|
|
1534
|
+
mob.face_top.set_points_as_corners([
|
|
1535
|
+
np.array([bx-bhw,by-bhd,z1]),
|
|
1536
|
+
np.array([bx+bhw,by-bhd,z1]),
|
|
1537
|
+
np.array([bx+bhw,by+bhd,z1]),
|
|
1538
|
+
np.array([bx-bhw,by+bhd,z1]),
|
|
1539
|
+
np.array([bx-bhw,by-bhd,z1]),
|
|
1540
|
+
])
|
|
1541
|
+
return updater
|
|
1542
|
+
|
|
1543
|
+
anims.append(UpdateFromAlphaFunc(
|
|
1544
|
+
bar,
|
|
1545
|
+
make_bar_updater(bar, old_h, new_h, x, y, hw, hd, z0),
|
|
1546
|
+
run_time=run_time,
|
|
1547
|
+
))
|
|
1548
|
+
bar._height = new_h
|
|
1549
|
+
bar.prob = new_params.get(k_int, 0.0)
|
|
1550
|
+
|
|
1551
|
+
# Update prob labels (fade out old, rebuild)
|
|
1552
|
+
if len(self.prob_labels) > 0 and update_title:
|
|
1553
|
+
anims.append(FadeOut(self.prob_labels, run_time=run_time * 0.4))
|
|
1554
|
+
|
|
1555
|
+
# Update title labels
|
|
1556
|
+
if update_title and cfg.show_title:
|
|
1557
|
+
old_title = VGroup(*[m for m in self.title_group])
|
|
1558
|
+
self.dist = new_dist
|
|
1559
|
+
self.title_group.remove(*list(self.title_group))
|
|
1560
|
+
self._build_title(scene)
|
|
1561
|
+
anims.append(
|
|
1562
|
+
AnimationGroup(
|
|
1563
|
+
FadeOut(old_title, run_time=run_time * 0.3),
|
|
1564
|
+
FadeIn(self.title_group, run_time=run_time * 0.5),
|
|
1565
|
+
)
|
|
1566
|
+
)
|
|
1567
|
+
else:
|
|
1568
|
+
self.dist = new_dist
|
|
1569
|
+
|
|
1570
|
+
# Update stored arrays
|
|
1571
|
+
self._ps = np.array([new_params.get(int(k), 0.0) for k in self._ks])
|
|
1572
|
+
self._heights = self._ps * cfg.z_scale
|
|
1573
|
+
|
|
1574
|
+
return AnimationGroup(*anims)
|
|
1575
|
+
|
|
1576
|
+
# ------------------------------------------------------------------
|
|
1577
|
+
# Animation helpers
|
|
1578
|
+
# ------------------------------------------------------------------
|
|
1579
|
+
|
|
1580
|
+
def animate_bars(
|
|
1581
|
+
self,
|
|
1582
|
+
lag: float = 0.04,
|
|
1583
|
+
run_time_per: float = 0.55,
|
|
1584
|
+
left_to_right: bool = True,
|
|
1585
|
+
) -> LaggedStart:
|
|
1586
|
+
"""Grow all bars from the floor with a stagger.
|
|
1587
|
+
|
|
1588
|
+
Parameters
|
|
1589
|
+
----------
|
|
1590
|
+
left_to_right : bool
|
|
1591
|
+
If True, bars grow left-to-right. False = right-to-left.
|
|
1592
|
+
"""
|
|
1593
|
+
bars = self._bars if left_to_right else list(reversed(self._bars))
|
|
1594
|
+
return LaggedStart(
|
|
1595
|
+
*[b.animate_grow(run_time=run_time_per) for b in bars],
|
|
1596
|
+
lag_ratio=lag,
|
|
1597
|
+
)
|
|
1598
|
+
|
|
1599
|
+
def animate_mean_mode(self, run_time: float = 0.7) -> AnimationGroup:
|
|
1600
|
+
"""Fade in mean and mode markers together."""
|
|
1601
|
+
anims = []
|
|
1602
|
+
if len(self.mean_marker) > 0:
|
|
1603
|
+
anims.append(Create(self.mean_marker, run_time=run_time))
|
|
1604
|
+
if len(self.mode_marker) > 0:
|
|
1605
|
+
anims.append(Create(self.mode_marker, run_time=run_time))
|
|
1606
|
+
return AnimationGroup(*anims)
|
|
1607
|
+
|
|
1608
|
+
def animate_cdf(self, run_time: float = 1.2) -> Create:
|
|
1609
|
+
"""Draw the CDF step function left-to-right."""
|
|
1610
|
+
if len(self.cdf_overlay) == 0:
|
|
1611
|
+
self.build_cdf_overlay()
|
|
1612
|
+
return Create(self.cdf_overlay, run_time=run_time)
|
|
1613
|
+
|
|
1614
|
+
def animate_title(self, run_time: float = 0.5) -> FadeIn:
|
|
1615
|
+
return FadeIn(self.title_group, run_time=run_time)
|
|
1616
|
+
|
|
1617
|
+
def animate_regions(
|
|
1618
|
+
self,
|
|
1619
|
+
lag: float = 0.10,
|
|
1620
|
+
run_time_per: float = 0.45,
|
|
1621
|
+
) -> LaggedStart:
|
|
1622
|
+
"""Fade in probability regions one by one."""
|
|
1623
|
+
return LaggedStart(
|
|
1624
|
+
*[FadeIn(r, run_time=run_time_per) for r in self.regions],
|
|
1625
|
+
lag_ratio=lag,
|
|
1626
|
+
)
|
|
1627
|
+
|
|
1628
|
+
def full_reveal(
|
|
1629
|
+
self,
|
|
1630
|
+
scene: ThreeDScene,
|
|
1631
|
+
bar_rt: float = 1.0,
|
|
1632
|
+
mean_mode_rt: float = 0.6,
|
|
1633
|
+
title_rt: float = 0.5,
|
|
1634
|
+
) -> None:
|
|
1635
|
+
"""Play the complete layer-by-layer reveal directly on *scene*."""
|
|
1636
|
+
scene.play(self.animate_bars(run_time_per=bar_rt / max(len(self._bars), 1) * 0.8))
|
|
1637
|
+
if cfg := self.cfg:
|
|
1638
|
+
if len(self.k_labels) > 0:
|
|
1639
|
+
scene.play(FadeIn(self.k_labels, run_time=0.35))
|
|
1640
|
+
scene.play(self.animate_mean_mode(run_time=mean_mode_rt))
|
|
1641
|
+
if len(self.title_group) > 0:
|
|
1642
|
+
scene.play(self.animate_title(run_time=title_rt))
|
|
1643
|
+
|
|
1644
|
+
|
|
1645
|
+
# ===========================================================================
|
|
1646
|
+
# MultiplePMFComparison3D
|
|
1647
|
+
# ===========================================================================
|
|
1648
|
+
|
|
1649
|
+
class MultiplePMFComparison3D(VGroup):
|
|
1650
|
+
"""Display two PMF distributions on the same k-axis.
|
|
1651
|
+
|
|
1652
|
+
Two display modes:
|
|
1653
|
+
- ``"grouped"`` – bars for each distribution placed side by side
|
|
1654
|
+
for each k value.
|
|
1655
|
+
- ``"superimposed"`` – bars share x position; second distribution
|
|
1656
|
+
rendered semi-transparent behind the first.
|
|
1657
|
+
|
|
1658
|
+
Parameters
|
|
1659
|
+
----------
|
|
1660
|
+
dist_a, dist_b : PMFDistribution
|
|
1661
|
+
The two distributions to compare. Must share at least part of
|
|
1662
|
+
their support for a meaningful comparison.
|
|
1663
|
+
mode : str
|
|
1664
|
+
``"grouped"`` or ``"superimposed"``.
|
|
1665
|
+
colors : (ManimColor, ManimColor) or None
|
|
1666
|
+
config_a, config_b : PMFConfig or None
|
|
1667
|
+
x_start : float
|
|
1668
|
+
scene : ThreeDScene or None
|
|
1669
|
+
|
|
1670
|
+
Attributes
|
|
1671
|
+
----------
|
|
1672
|
+
viz_a, viz_b : PMFVisualizer3D
|
|
1673
|
+
"""
|
|
1674
|
+
|
|
1675
|
+
def __init__(
|
|
1676
|
+
self,
|
|
1677
|
+
dist_a: PMFDistribution,
|
|
1678
|
+
dist_b: PMFDistribution,
|
|
1679
|
+
mode: str = "grouped",
|
|
1680
|
+
colors: Optional[Tuple[ManimColor, ManimColor]] = None,
|
|
1681
|
+
config_a: Optional[PMFConfig] = None,
|
|
1682
|
+
config_b: Optional[PMFConfig] = None,
|
|
1683
|
+
x_start: float = 0.0,
|
|
1684
|
+
scene: Optional[ThreeDScene] = None,
|
|
1685
|
+
**kwargs,
|
|
1686
|
+
):
|
|
1687
|
+
super().__init__(**kwargs)
|
|
1688
|
+
|
|
1689
|
+
self.mode = mode
|
|
1690
|
+
col_a = (colors[0] if colors else ManimColor("#4A90D9"))
|
|
1691
|
+
col_b = (colors[1] if colors else ManimColor("#E8593C"))
|
|
1692
|
+
|
|
1693
|
+
# Union of supports
|
|
1694
|
+
support_a = set(dist_a.support)
|
|
1695
|
+
support_b = set(dist_b.support)
|
|
1696
|
+
all_ks = sorted(support_a | support_b)
|
|
1697
|
+
n = len(all_ks)
|
|
1698
|
+
|
|
1699
|
+
spacing = max(0.55, min(1.05, 7.0 / max(n, 1)))
|
|
1700
|
+
|
|
1701
|
+
if mode == "grouped":
|
|
1702
|
+
bar_w = spacing * 0.40
|
|
1703
|
+
# dist_a at x - bar_w*0.6, dist_b at x + bar_w*0.6
|
|
1704
|
+
offset = bar_w * 0.62
|
|
1705
|
+
|
|
1706
|
+
cfg_a = PMFConfig(**COMPARISON_PMF.__dict__)
|
|
1707
|
+
cfg_a.bar_color = col_a
|
|
1708
|
+
cfg_a.bar_width = bar_w
|
|
1709
|
+
cfg_a.bar_spacing = spacing
|
|
1710
|
+
cfg_a.x_start = x_start - offset
|
|
1711
|
+
cfg_a.show_k_labels = True
|
|
1712
|
+
|
|
1713
|
+
cfg_b = PMFConfig(**COMPARISON_PMF.__dict__)
|
|
1714
|
+
cfg_b.bar_color = col_b
|
|
1715
|
+
cfg_b.bar_width = bar_w
|
|
1716
|
+
cfg_b.bar_spacing = spacing
|
|
1717
|
+
cfg_b.x_start = x_start + offset
|
|
1718
|
+
cfg_b.show_k_labels = False
|
|
1719
|
+
cfg_b.show_title = False
|
|
1720
|
+
|
|
1721
|
+
else: # superimposed
|
|
1722
|
+
bar_w = spacing * 0.72
|
|
1723
|
+
|
|
1724
|
+
cfg_a = PMFConfig(**COMPARISON_PMF.__dict__)
|
|
1725
|
+
cfg_a.bar_color = col_a
|
|
1726
|
+
cfg_a.bar_width = bar_w
|
|
1727
|
+
cfg_a.bar_spacing = spacing
|
|
1728
|
+
cfg_a.x_start = x_start
|
|
1729
|
+
cfg_a.bar_opacity = 0.90
|
|
1730
|
+
|
|
1731
|
+
cfg_b = PMFConfig(**COMPARISON_PMF.__dict__)
|
|
1732
|
+
cfg_b.bar_color = col_b
|
|
1733
|
+
cfg_b.bar_width = bar_w * 0.82
|
|
1734
|
+
cfg_b.bar_spacing = spacing
|
|
1735
|
+
cfg_b.x_start = x_start
|
|
1736
|
+
cfg_b.bar_opacity = 0.50
|
|
1737
|
+
cfg_b.show_k_labels = False
|
|
1738
|
+
cfg_b.show_title = False
|
|
1739
|
+
|
|
1740
|
+
if config_a is not None:
|
|
1741
|
+
cfg_a = config_a
|
|
1742
|
+
if config_b is not None:
|
|
1743
|
+
cfg_b = config_b
|
|
1744
|
+
|
|
1745
|
+
self.viz_a = PMFVisualizer3D(dist_a, config=cfg_a, scene=scene)
|
|
1746
|
+
self.viz_b = PMFVisualizer3D(dist_b, config=cfg_b, scene=scene)
|
|
1747
|
+
self.add(self.viz_a, self.viz_b)
|
|
1748
|
+
|
|
1749
|
+
# Legend
|
|
1750
|
+
self._build_legend(dist_a, dist_b, col_a, col_b, scene)
|
|
1751
|
+
|
|
1752
|
+
def _build_legend(
|
|
1753
|
+
self,
|
|
1754
|
+
dist_a: PMFDistribution,
|
|
1755
|
+
dist_b: PMFDistribution,
|
|
1756
|
+
col_a: ManimColor,
|
|
1757
|
+
col_b: ManimColor,
|
|
1758
|
+
scene: Optional[ThreeDScene],
|
|
1759
|
+
) -> None:
|
|
1760
|
+
self.legend = VGroup()
|
|
1761
|
+
entries = [(dist_a, col_a), (dist_b, col_b)]
|
|
1762
|
+
for i, (dist, col) in enumerate(entries):
|
|
1763
|
+
swatch = Line(ORIGIN, RIGHT * 0.38,
|
|
1764
|
+
color=_with_opacity(col, 0.90), stroke_width=3.0)
|
|
1765
|
+
lbl = Text(
|
|
1766
|
+
f"{dist.name} ({dist.param_string})",
|
|
1767
|
+
font_size=16, color=col,
|
|
1768
|
+
)
|
|
1769
|
+
row = VGroup(swatch, lbl)
|
|
1770
|
+
row.arrange(RIGHT, buff=0.12)
|
|
1771
|
+
row.move_to(np.array([5.2, 0, 3.8 - i * 0.38]))
|
|
1772
|
+
self.legend.add(row)
|
|
1773
|
+
if scene is not None:
|
|
1774
|
+
scene.add_fixed_orientation_mobjects(row)
|
|
1775
|
+
self.add(self.legend)
|
|
1776
|
+
|
|
1777
|
+
def animate_reveal(
|
|
1778
|
+
self,
|
|
1779
|
+
stagger: float = 0.4,
|
|
1780
|
+
run_time_per: float = 1.0,
|
|
1781
|
+
) -> AnimationGroup:
|
|
1782
|
+
"""Reveal both distributions with a stagger."""
|
|
1783
|
+
return AnimationGroup(
|
|
1784
|
+
self.viz_a.animate_bars(run_time_per=run_time_per / max(len(self.viz_a._bars), 1) * 0.8),
|
|
1785
|
+
LaggedStart(
|
|
1786
|
+
FadeIn(VGroup(), run_time=stagger),
|
|
1787
|
+
self.viz_b.animate_bars(run_time_per=run_time_per / max(len(self.viz_b._bars), 1) * 0.8),
|
|
1788
|
+
),
|
|
1789
|
+
lag_ratio=0.0,
|
|
1790
|
+
)
|
|
1791
|
+
|
|
1792
|
+
|
|
1793
|
+
# ===========================================================================
|
|
1794
|
+
# Ready-to-render ThreeDScene subclasses
|
|
1795
|
+
# ===========================================================================
|
|
1796
|
+
|
|
1797
|
+
class BinomialPMFScene(ThreeDScene):
|
|
1798
|
+
"""Binomial(10, 0.4) PMF with mean, mode, and right-tail shading.
|
|
1799
|
+
|
|
1800
|
+
Render: manim -pql pmf_viz.py BinomialPMFScene
|
|
1801
|
+
"""
|
|
1802
|
+
|
|
1803
|
+
def construct(self):
|
|
1804
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
1805
|
+
self.begin_ambient_camera_rotation(rate=0.025)
|
|
1806
|
+
|
|
1807
|
+
dist = BinomialDist(n=10, p=0.4)
|
|
1808
|
+
viz = PMFVisualizer3D(dist, config=TEACHING_PMF, scene=self)
|
|
1809
|
+
self.add(viz)
|
|
1810
|
+
|
|
1811
|
+
viz.full_reveal(self)
|
|
1812
|
+
self.wait(0.5)
|
|
1813
|
+
|
|
1814
|
+
# Shade P(X ≥ 7) — right tail rejection region
|
|
1815
|
+
region = viz.shade_tail_right(7, label=True, scene=self)
|
|
1816
|
+
self.play(FadeIn(viz.regions, run_time=0.55))
|
|
1817
|
+
self.wait(0.5)
|
|
1818
|
+
|
|
1819
|
+
# Add CDF overlay
|
|
1820
|
+
viz.build_cdf_overlay(scene=self)
|
|
1821
|
+
self.play(viz.animate_cdf(run_time=1.2))
|
|
1822
|
+
self.wait(2)
|
|
1823
|
+
|
|
1824
|
+
|
|
1825
|
+
class PoissonPMFScene(ThreeDScene):
|
|
1826
|
+
"""Poisson PMF for λ = 1, 2, 4, 8 — showing mean = variance = λ.
|
|
1827
|
+
|
|
1828
|
+
Render: manim -pql pmf_viz.py PoissonPMFScene
|
|
1829
|
+
"""
|
|
1830
|
+
|
|
1831
|
+
def construct(self):
|
|
1832
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
1833
|
+
self.begin_ambient_camera_rotation(rate=0.025)
|
|
1834
|
+
|
|
1835
|
+
dist = PoissonDist(lam=1.0)
|
|
1836
|
+
cfg = PMFConfig(**TEACHING_PMF.__dict__)
|
|
1837
|
+
cfg.bar_color = ManimColor("#E8593C")
|
|
1838
|
+
cfg.mean_color = ManimColor("#4A90D9")
|
|
1839
|
+
cfg.mode_color = ManimColor("#2DAA6E")
|
|
1840
|
+
|
|
1841
|
+
viz = PMFVisualizer3D(dist, config=cfg, scene=self)
|
|
1842
|
+
self.add(viz)
|
|
1843
|
+
viz.full_reveal(self)
|
|
1844
|
+
self.wait(0.5)
|
|
1845
|
+
|
|
1846
|
+
for lam in [2.0, 4.0, 8.0]:
|
|
1847
|
+
new_dist = PoissonDist(lam=lam)
|
|
1848
|
+
self.play(
|
|
1849
|
+
viz.morph_to_distribution(new_dist, run_time=1.0, scene=self),
|
|
1850
|
+
)
|
|
1851
|
+
self.wait(0.6)
|
|
1852
|
+
|
|
1853
|
+
self.wait(2)
|
|
1854
|
+
|
|
1855
|
+
|
|
1856
|
+
class GeometricPMFScene(ThreeDScene):
|
|
1857
|
+
"""Geometric(p) PMF for p = 0.5, 0.3, 0.1 — showing memorylessness.
|
|
1858
|
+
|
|
1859
|
+
Render: manim -pql pmf_viz.py GeometricPMFScene
|
|
1860
|
+
"""
|
|
1861
|
+
|
|
1862
|
+
def construct(self):
|
|
1863
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
1864
|
+
|
|
1865
|
+
dist = GeometricDist(p=0.5)
|
|
1866
|
+
cfg = PMFConfig(**TEACHING_PMF.__dict__)
|
|
1867
|
+
cfg.bar_color = ManimColor("#2DAA6E")
|
|
1868
|
+
|
|
1869
|
+
viz = PMFVisualizer3D(dist, config=cfg, scene=self)
|
|
1870
|
+
self.add(viz)
|
|
1871
|
+
viz.full_reveal(self)
|
|
1872
|
+
self.wait(0.5)
|
|
1873
|
+
|
|
1874
|
+
for p in [0.3, 0.1]:
|
|
1875
|
+
new_dist = GeometricDist(p=p)
|
|
1876
|
+
self.play(
|
|
1877
|
+
viz.morph_to_distribution(new_dist, run_time=1.2, scene=self),
|
|
1878
|
+
)
|
|
1879
|
+
self.wait(0.8)
|
|
1880
|
+
|
|
1881
|
+
self.wait(2)
|
|
1882
|
+
|
|
1883
|
+
|
|
1884
|
+
class PMFComparisonScene(ThreeDScene):
|
|
1885
|
+
"""Binomial(20, 0.3) vs Poisson(6) — same mean, different variance.
|
|
1886
|
+
|
|
1887
|
+
Render: manim -pql pmf_viz.py PMFComparisonScene
|
|
1888
|
+
"""
|
|
1889
|
+
|
|
1890
|
+
def construct(self):
|
|
1891
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
1892
|
+
self.begin_ambient_camera_rotation(rate=0.020)
|
|
1893
|
+
|
|
1894
|
+
binom = BinomialDist(n=20, p=0.3) # mean = 6
|
|
1895
|
+
poisson = PoissonDist(lam=6.0)
|
|
1896
|
+
|
|
1897
|
+
comp = MultiplePMFComparison3D(
|
|
1898
|
+
dist_a=binom,
|
|
1899
|
+
dist_b=poisson,
|
|
1900
|
+
mode="grouped",
|
|
1901
|
+
scene=self,
|
|
1902
|
+
)
|
|
1903
|
+
self.add(comp)
|
|
1904
|
+
self.play(comp.animate_reveal(stagger=0.35, run_time_per=0.9))
|
|
1905
|
+
self.play(FadeIn(comp.legend, run_time=0.5))
|
|
1906
|
+
self.wait(2)
|
|
1907
|
+
|
|
1908
|
+
|
|
1909
|
+
class BinomialNSweepScene(ThreeDScene):
|
|
1910
|
+
"""Binomial(n, 0.3) PMF for n = 5 → 50, showing CLT convergence.
|
|
1911
|
+
|
|
1912
|
+
Render: manim -pql pmf_viz.py BinomialNSweepScene
|
|
1913
|
+
"""
|
|
1914
|
+
|
|
1915
|
+
def construct(self):
|
|
1916
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-52 * DEGREES)
|
|
1917
|
+
self.begin_ambient_camera_rotation(rate=0.025)
|
|
1918
|
+
|
|
1919
|
+
dist = BinomialDist(n=5, p=0.3)
|
|
1920
|
+
cfg = PMFConfig(**TEACHING_PMF.__dict__)
|
|
1921
|
+
cfg.bar_color = ManimColor("#9B59B6")
|
|
1922
|
+
cfg.show_prob_labels = False
|
|
1923
|
+
|
|
1924
|
+
viz = PMFVisualizer3D(dist, config=cfg, scene=self)
|
|
1925
|
+
self.add(viz)
|
|
1926
|
+
viz.full_reveal(self, bar_rt=0.8)
|
|
1927
|
+
self.wait(0.4)
|
|
1928
|
+
|
|
1929
|
+
for n in [10, 20, 30, 50]:
|
|
1930
|
+
new_dist = BinomialDist(n=n, p=0.3)
|
|
1931
|
+
self.play(
|
|
1932
|
+
viz.morph_to_distribution(new_dist, run_time=0.90, scene=self),
|
|
1933
|
+
)
|
|
1934
|
+
self.wait(0.5)
|
|
1935
|
+
|
|
1936
|
+
self.wait(2)
|