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,1933 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/inference/sampling_dist.py
|
|
3
|
+
========================================
|
|
4
|
+
SamplingDistribution3D — A highly detailed, animated Central Limit
|
|
5
|
+
Theorem and sampling distribution visualisation for Manim.
|
|
6
|
+
|
|
7
|
+
Primary use cases
|
|
8
|
+
-----------------
|
|
9
|
+
Central Limit Theorem demonstration — any population → normal sampling dist
|
|
10
|
+
Standard error intuition — SE = σ/√n shrinks with n
|
|
11
|
+
Sampling variability — watch individual means scatter
|
|
12
|
+
Point estimation — sample mean as an estimator of μ
|
|
13
|
+
Bootstrap intuition — repeated resampling
|
|
14
|
+
|
|
15
|
+
Design goals
|
|
16
|
+
------------
|
|
17
|
+
Population panel (left)
|
|
18
|
+
* Full rendered source distribution curve — supports Normal, Uniform,
|
|
19
|
+
Exponential, Chi-squared, Bimodal, and Bernoulli shapes.
|
|
20
|
+
* Three-layer curve: base fill polygon + AO tail darkening + ridge spine.
|
|
21
|
+
* Population parameter badges: μ, σ, shape description.
|
|
22
|
+
* "Sample zone" bracket: a highlighted sub-region with tick marks
|
|
23
|
+
showing one concrete sample being drawn.
|
|
24
|
+
|
|
25
|
+
Sample strip (centre)
|
|
26
|
+
* Dot strip: individual sample observations rendered as small coloured
|
|
27
|
+
circles on a number line, dropping in one by one.
|
|
28
|
+
* After all n dots land, a bracket collapses from both ends to the mean,
|
|
29
|
+
which is highlighted in a bright colour.
|
|
30
|
+
* Mean dot shoots upward from the strip to the histogram.
|
|
31
|
+
|
|
32
|
+
Sampling distribution histogram (right)
|
|
33
|
+
* Histogram bars with 3-D depth: bright top face cap, darker right
|
|
34
|
+
side face, and a subtle AO shadow polygon at the base.
|
|
35
|
+
* Bars grow upward from 0 (animated height).
|
|
36
|
+
* Relative frequency or count labelling above each bar.
|
|
37
|
+
* Bin highlight: when a new mean lands the bar flashes.
|
|
38
|
+
|
|
39
|
+
Theoretical overlay
|
|
40
|
+
* N(μ, σ²/n) normal curve drawn over the histogram.
|
|
41
|
+
* Dashed until enough samples accumulate (< 10), solid after.
|
|
42
|
+
* Curve animates toward the histogram as bars fill in.
|
|
43
|
+
|
|
44
|
+
Standard error annotation
|
|
45
|
+
* DoubleArrow bracket spanning ±1 SE around the theoretical mean.
|
|
46
|
+
* "SE = σ/√n = {value:.3f}" badge above the arrow.
|
|
47
|
+
* Arrow shrinks when n increases (NarrowSE animation).
|
|
48
|
+
|
|
49
|
+
Live stats panel
|
|
50
|
+
* Floating badge showing:
|
|
51
|
+
Samples drawn: k
|
|
52
|
+
Current x̄: value
|
|
53
|
+
True μ: value
|
|
54
|
+
SE = σ/√n: value
|
|
55
|
+
n per sample: n
|
|
56
|
+
|
|
57
|
+
CLT label
|
|
58
|
+
* Central arrow from population panel to sampling dist panel.
|
|
59
|
+
* Label: "n = {n}, repeat {k} times" — updates live.
|
|
60
|
+
|
|
61
|
+
Animations
|
|
62
|
+
----------
|
|
63
|
+
BuildPopulation — population curve grows from baseline
|
|
64
|
+
DrawSample — n dots drop onto the sample strip one by one
|
|
65
|
+
ExtractMean — bracket collapses → mean highlighted → mean dot rises
|
|
66
|
+
AddToHistogram — mean dot lands in correct bin, bar grows by 1 unit
|
|
67
|
+
RunCLT — orchestrates DrawSample→ExtractMean→AddToHistogram
|
|
68
|
+
for k iterations, updating stats panel
|
|
69
|
+
NarrowSE — increase n: sample strip widens/narrows, SE arrow
|
|
70
|
+
shrinks, theoretical curve narrows
|
|
71
|
+
ConvergenceRace — animate bars rapidly filling toward normal (speedup)
|
|
72
|
+
FlashBin — pulse the bar that just received a new count
|
|
73
|
+
|
|
74
|
+
Population constructors
|
|
75
|
+
-----------------------
|
|
76
|
+
SamplingDistribution3D.normal(mu, sigma, n, **kw)
|
|
77
|
+
SamplingDistribution3D.uniform(a, b, n, **kw)
|
|
78
|
+
SamplingDistribution3D.exponential(lam, n, **kw)
|
|
79
|
+
SamplingDistribution3D.chi_squared(df, n, **kw)
|
|
80
|
+
SamplingDistribution3D.bimodal(mu1, mu2, sigma, mix, n, **kw)
|
|
81
|
+
SamplingDistribution3D.bernoulli(p, n, **kw)
|
|
82
|
+
|
|
83
|
+
Dependencies
|
|
84
|
+
------------
|
|
85
|
+
manim (CE or GL), numpy, scipy (optional)
|
|
86
|
+
|
|
87
|
+
Usage
|
|
88
|
+
-----
|
|
89
|
+
from statanim.inference.sampling_dist import (
|
|
90
|
+
SamplingDistribution3D, RunCLT, NarrowSE
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
class CLTScene(Scene):
|
|
94
|
+
def construct(self):
|
|
95
|
+
sd = SamplingDistribution3D.exponential(lam=1.0, n=5)
|
|
96
|
+
self.play(BuildPopulation(sd))
|
|
97
|
+
for _ in range(30):
|
|
98
|
+
self.play(RunCLT(sd, run_time=0.6))
|
|
99
|
+
self.play(NarrowSE(sd, new_n=30, run_time=2.5))
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
from __future__ import annotations
|
|
103
|
+
|
|
104
|
+
import numpy as np
|
|
105
|
+
from typing import Optional, Callable, Literal, Sequence
|
|
106
|
+
|
|
107
|
+
from manim import (
|
|
108
|
+
VGroup,
|
|
109
|
+
Rectangle, RoundedRectangle, Square,
|
|
110
|
+
Circle, Annulus, Dot, Polygon, Line, DashedLine,
|
|
111
|
+
Arrow, DoubleArrow,
|
|
112
|
+
Text, MathTex,
|
|
113
|
+
Animation, Succession, AnimationGroup,
|
|
114
|
+
ApplyMethod, FadeIn, FadeOut,
|
|
115
|
+
Create, Write,
|
|
116
|
+
Indicate, Flash,
|
|
117
|
+
ValueTracker,
|
|
118
|
+
interpolate_color, color_to_rgb,
|
|
119
|
+
always_redraw,
|
|
120
|
+
WHITE, BLACK,
|
|
121
|
+
GREY, GREY_A, GREY_B, GREY_C, GREY_D,
|
|
122
|
+
RED, RED_A, RED_B, RED_C, RED_D,
|
|
123
|
+
GREEN, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
|
|
124
|
+
BLUE, BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E,
|
|
125
|
+
YELLOW, YELLOW_A, YELLOW_E,
|
|
126
|
+
ORANGE, TEAL, TEAL_A, TEAL_B, TEAL_C,
|
|
127
|
+
GOLD, GOLD_A, GOLD_B, GOLD_C, GOLD_D,
|
|
128
|
+
PURPLE_A, PURPLE_B, MAROON, PINK,
|
|
129
|
+
UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
|
|
130
|
+
PI, TAU,
|
|
131
|
+
rate_functions,
|
|
132
|
+
ManimColor,
|
|
133
|
+
VMobject,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
137
|
+
# scipy — graceful fallback
|
|
138
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
139
|
+
try:
|
|
140
|
+
from scipy import stats as _stats
|
|
141
|
+
def _norm_pdf(x, mu, sigma):
|
|
142
|
+
return _stats.norm.pdf(x, loc=mu, scale=sigma)
|
|
143
|
+
def _norm_ppf(p, mu, sigma):
|
|
144
|
+
return float(_stats.norm.ppf(p, loc=mu, scale=sigma))
|
|
145
|
+
def _sample_pop(pop_type, params, n, rng):
|
|
146
|
+
if pop_type == "normal":
|
|
147
|
+
return rng.normal(params["mu"], params["sigma"], n)
|
|
148
|
+
elif pop_type == "uniform":
|
|
149
|
+
return rng.uniform(params["a"], params["b"], n)
|
|
150
|
+
elif pop_type == "exponential":
|
|
151
|
+
return rng.exponential(1.0 / params["lam"], n)
|
|
152
|
+
elif pop_type == "chi2":
|
|
153
|
+
return rng.chisquare(params["df"], n)
|
|
154
|
+
elif pop_type == "bimodal":
|
|
155
|
+
mask = rng.random(n) < params["mix"]
|
|
156
|
+
s = np.where(
|
|
157
|
+
mask,
|
|
158
|
+
rng.normal(params["mu1"], params["sigma"], n),
|
|
159
|
+
rng.normal(params["mu2"], params["sigma"], n),
|
|
160
|
+
)
|
|
161
|
+
return s
|
|
162
|
+
elif pop_type == "bernoulli":
|
|
163
|
+
return rng.binomial(1, params["p"], n).astype(float)
|
|
164
|
+
return rng.normal(0, 1, n)
|
|
165
|
+
except ImportError:
|
|
166
|
+
def _norm_pdf(x, mu, sigma):
|
|
167
|
+
return (np.exp(-0.5*((x-mu)/sigma)**2)
|
|
168
|
+
/ (sigma * np.sqrt(2*PI)))
|
|
169
|
+
def _norm_ppf(p, mu, sigma):
|
|
170
|
+
z = 0.0
|
|
171
|
+
for _ in range(60):
|
|
172
|
+
z -= (_norm_pdf(np.array([z]),0,1)[0]
|
|
173
|
+
- _norm_pdf(np.array([z]),0,1)[0]) / (
|
|
174
|
+
_norm_pdf(np.array([z]),0,1)[0]+1e-14)
|
|
175
|
+
return mu + z*sigma
|
|
176
|
+
def _sample_pop(pop_type, params, n, rng):
|
|
177
|
+
return rng.normal(params.get("mu",0), params.get("sigma",1), n)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
181
|
+
# Palette
|
|
182
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
183
|
+
|
|
184
|
+
PAL = {
|
|
185
|
+
# Population curve
|
|
186
|
+
"pop_fill": "#1A3A5C",
|
|
187
|
+
"pop_fill_lite": "#2E6AAA",
|
|
188
|
+
"pop_ridge": "#70B4EE",
|
|
189
|
+
"pop_ao": "#081828",
|
|
190
|
+
"pop_label": "#90C8F8",
|
|
191
|
+
|
|
192
|
+
# Sample strip dots
|
|
193
|
+
"dot_default": "#E8B840",
|
|
194
|
+
"dot_mean": "#FF6040",
|
|
195
|
+
"dot_highlight": "#FFE080",
|
|
196
|
+
"strip_line": "#405060",
|
|
197
|
+
"bracket": "#C8D8E8",
|
|
198
|
+
"mean_beam": "#FF8060",
|
|
199
|
+
|
|
200
|
+
# Histogram
|
|
201
|
+
"bar_top": "#3A7AC8",
|
|
202
|
+
"bar_top_lite": "#60A0F0",
|
|
203
|
+
"bar_side": "#1A3A68",
|
|
204
|
+
"bar_ao": "#080C18",
|
|
205
|
+
"bar_flash": "#FFD060",
|
|
206
|
+
"bar_border": "#2A5090",
|
|
207
|
+
|
|
208
|
+
# Theoretical curve
|
|
209
|
+
"theory_solid": "#F0C040",
|
|
210
|
+
"theory_dashed": "#907020",
|
|
211
|
+
"theory_fill": "#3A2800",
|
|
212
|
+
|
|
213
|
+
# SE arrow
|
|
214
|
+
"se_arrow": "#D4AF37",
|
|
215
|
+
"se_label": "#F8E090",
|
|
216
|
+
"se_badge_bg": "#1A1208",
|
|
217
|
+
|
|
218
|
+
# Stats panel
|
|
219
|
+
"panel_bg": "#0C1018",
|
|
220
|
+
"panel_border": "#2A3848",
|
|
221
|
+
"panel_key": "#7090A8",
|
|
222
|
+
"panel_val": "#C8E0F8",
|
|
223
|
+
"panel_title": "#D8F0FF",
|
|
224
|
+
|
|
225
|
+
# CLT arrow
|
|
226
|
+
"clt_arrow": "#A0B8D0",
|
|
227
|
+
"clt_label": "#C8E0F8",
|
|
228
|
+
|
|
229
|
+
# Axis
|
|
230
|
+
"axis": "#506070",
|
|
231
|
+
"axis_label": "#90A8B8",
|
|
232
|
+
"tick": "#405060",
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
237
|
+
# Population PDF functions
|
|
238
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
239
|
+
|
|
240
|
+
def _pop_pdf(pop_type: str, params: dict, x: np.ndarray) -> np.ndarray:
|
|
241
|
+
"""Evaluate the population PDF on array x."""
|
|
242
|
+
if pop_type == "normal":
|
|
243
|
+
return _norm_pdf(x, params["mu"], params["sigma"])
|
|
244
|
+
elif pop_type == "uniform":
|
|
245
|
+
a, b = params["a"], params["b"]
|
|
246
|
+
return np.where((x >= a) & (x <= b), 1.0 / (b - a), 0.0)
|
|
247
|
+
elif pop_type == "exponential":
|
|
248
|
+
lam = params["lam"]
|
|
249
|
+
return np.where(x >= 0, lam * np.exp(-lam * x), 0.0)
|
|
250
|
+
elif pop_type == "chi2":
|
|
251
|
+
df = params["df"]
|
|
252
|
+
try:
|
|
253
|
+
from scipy.stats import chi2
|
|
254
|
+
return chi2.pdf(x, df)
|
|
255
|
+
except ImportError:
|
|
256
|
+
# Rough chi2 pdf via gamma approximation
|
|
257
|
+
k = df / 2
|
|
258
|
+
with np.errstate(all="ignore"):
|
|
259
|
+
import math
|
|
260
|
+
y = np.where(
|
|
261
|
+
x > 0,
|
|
262
|
+
(x**(k-1) * np.exp(-x/2)) / (2**k * math.gamma(k)),
|
|
263
|
+
0.0,
|
|
264
|
+
)
|
|
265
|
+
return y
|
|
266
|
+
elif pop_type == "bimodal":
|
|
267
|
+
m1 = _norm_pdf(x, params["mu1"], params["sigma"])
|
|
268
|
+
m2 = _norm_pdf(x, params["mu2"], params["sigma"])
|
|
269
|
+
mix = params.get("mix", 0.5)
|
|
270
|
+
return mix * m1 + (1 - mix) * m2
|
|
271
|
+
elif pop_type == "bernoulli":
|
|
272
|
+
p = params["p"]
|
|
273
|
+
# Discrete: approximate with two spikes
|
|
274
|
+
y = np.zeros_like(x, dtype=float)
|
|
275
|
+
for val, prob in [(0.0, 1-p), (1.0, p)]:
|
|
276
|
+
mask = np.abs(x - val) < 0.08
|
|
277
|
+
y[mask] = prob / 0.16 # normalise spike height
|
|
278
|
+
return y
|
|
279
|
+
return _norm_pdf(x, 0, 1)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _pop_stats(pop_type: str, params: dict) -> tuple[float, float]:
|
|
283
|
+
"""Return (mu, sigma) for the population."""
|
|
284
|
+
if pop_type == "normal":
|
|
285
|
+
return params["mu"], params["sigma"]
|
|
286
|
+
elif pop_type == "uniform":
|
|
287
|
+
a, b = params["a"], params["b"]
|
|
288
|
+
return (a+b)/2, (b-a)/np.sqrt(12)
|
|
289
|
+
elif pop_type == "exponential":
|
|
290
|
+
lam = params["lam"]
|
|
291
|
+
return 1.0/lam, 1.0/lam
|
|
292
|
+
elif pop_type == "chi2":
|
|
293
|
+
df = params["df"]
|
|
294
|
+
return float(df), float(np.sqrt(2*df))
|
|
295
|
+
elif pop_type == "bimodal":
|
|
296
|
+
mix = params.get("mix", 0.5)
|
|
297
|
+
mu = mix*params["mu1"] + (1-mix)*params["mu2"]
|
|
298
|
+
s2 = (mix*(params["sigma"]**2 + params["mu1"]**2)
|
|
299
|
+
+ (1-mix)*(params["sigma"]**2 + params["mu2"]**2)
|
|
300
|
+
- mu**2)
|
|
301
|
+
return mu, float(np.sqrt(max(s2, 1e-6)))
|
|
302
|
+
elif pop_type == "bernoulli":
|
|
303
|
+
p = params["p"]
|
|
304
|
+
return p, float(np.sqrt(p*(1-p)))
|
|
305
|
+
return 0.0, 1.0
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _pop_x_range(pop_type: str, params: dict) -> tuple[float, float]:
|
|
309
|
+
"""Suggest a good x-range for plotting this population."""
|
|
310
|
+
mu, sigma = _pop_stats(pop_type, params)
|
|
311
|
+
if pop_type == "uniform":
|
|
312
|
+
a, b = params["a"], params["b"]
|
|
313
|
+
pad = (b-a)*0.15
|
|
314
|
+
return a-pad, b+pad
|
|
315
|
+
elif pop_type == "exponential":
|
|
316
|
+
return 0.0, 5.0/params["lam"]
|
|
317
|
+
elif pop_type == "chi2":
|
|
318
|
+
df = params["df"]
|
|
319
|
+
return 0.0, df + 5*np.sqrt(2*df)
|
|
320
|
+
elif pop_type == "bernoulli":
|
|
321
|
+
return -0.5, 1.5
|
|
322
|
+
elif pop_type == "bimodal":
|
|
323
|
+
lo = min(params["mu1"], params["mu2"]) - 3.5*params["sigma"]
|
|
324
|
+
hi = max(params["mu1"], params["mu2"]) + 3.5*params["sigma"]
|
|
325
|
+
return lo, hi
|
|
326
|
+
return mu - 4*sigma, mu + 4*sigma
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
330
|
+
# Geometry helpers (shared)
|
|
331
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
332
|
+
|
|
333
|
+
def _curve_verts(x_px, y_px, baseline=0.0):
|
|
334
|
+
return (
|
|
335
|
+
[[float(x_px[0]), baseline, 0]]
|
|
336
|
+
+ [[float(x), float(y), 0] for x, y in zip(x_px, y_px)]
|
|
337
|
+
+ [[float(x_px[-1]), baseline, 0]]
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _map_x(raw_x, x_lo, x_hi, plot_w):
|
|
342
|
+
"""Map raw x values to Manim world x coordinates."""
|
|
343
|
+
return (np.asarray(raw_x) - x_lo) / (x_hi - x_lo) * plot_w - plot_w/2
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
347
|
+
# Sub-components
|
|
348
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
349
|
+
|
|
350
|
+
class _PopulationPanel(VGroup):
|
|
351
|
+
"""
|
|
352
|
+
Left panel: population distribution curve with parameter badges.
|
|
353
|
+
|
|
354
|
+
Layers:
|
|
355
|
+
1. Panel background rounded rect
|
|
356
|
+
2. Base fill polygon (curve area)
|
|
357
|
+
3. AO tail darkening (left and right tails)
|
|
358
|
+
4. Ridge spine (VMobject along curve top)
|
|
359
|
+
5. Peak cap circle
|
|
360
|
+
6. Parameter badges: μ, σ, distribution name
|
|
361
|
+
7. "Population" title label
|
|
362
|
+
|
|
363
|
+
Parameters
|
|
364
|
+
----------
|
|
365
|
+
pop_type : str — distribution family
|
|
366
|
+
params : dict — distribution parameters
|
|
367
|
+
panel_w : float — panel width (Manim units)
|
|
368
|
+
panel_h : float — panel height (curve max height)
|
|
369
|
+
baseline_y : float
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
def __init__(
|
|
373
|
+
self,
|
|
374
|
+
pop_type: str,
|
|
375
|
+
params: dict,
|
|
376
|
+
panel_w: float = 4.5,
|
|
377
|
+
panel_h: float = 3.0,
|
|
378
|
+
baseline_y: float = 0.0,
|
|
379
|
+
**kwargs,
|
|
380
|
+
):
|
|
381
|
+
super().__init__(**kwargs)
|
|
382
|
+
self._pop_type = pop_type
|
|
383
|
+
self._params = params
|
|
384
|
+
self._panel_w = panel_w
|
|
385
|
+
self._panel_h = panel_h
|
|
386
|
+
self._baseline = baseline_y
|
|
387
|
+
|
|
388
|
+
x_lo, x_hi = _pop_x_range(pop_type, params)
|
|
389
|
+
raw_x = np.linspace(x_lo, x_hi, 500)
|
|
390
|
+
x_px = _map_x(raw_x, x_lo, x_hi, panel_w)
|
|
391
|
+
|
|
392
|
+
y_raw = _pop_pdf(pop_type, params, raw_x)
|
|
393
|
+
y_raw = np.where(np.isfinite(y_raw), y_raw, 0.0)
|
|
394
|
+
peak = float(y_raw.max()) if y_raw.max() > 1e-12 else 1.0
|
|
395
|
+
scale_y = panel_h / peak
|
|
396
|
+
y_px = y_raw * scale_y
|
|
397
|
+
|
|
398
|
+
# Store for sample-zone overlay
|
|
399
|
+
self._raw_x = raw_x
|
|
400
|
+
self._x_px = x_px
|
|
401
|
+
self._y_px = y_px
|
|
402
|
+
self._x_lo = x_lo
|
|
403
|
+
self._x_hi = x_hi
|
|
404
|
+
self._scale_y = scale_y
|
|
405
|
+
|
|
406
|
+
# ── Panel background ──────────────────────────────────────────
|
|
407
|
+
bg = RoundedRectangle(
|
|
408
|
+
width=panel_w + 0.25,
|
|
409
|
+
height=panel_h + 1.10,
|
|
410
|
+
corner_radius=0.12,
|
|
411
|
+
fill_color=PAL["pop_ao"],
|
|
412
|
+
fill_opacity=0.55,
|
|
413
|
+
stroke_color=PAL["strip_line"],
|
|
414
|
+
stroke_width=0.8,
|
|
415
|
+
)
|
|
416
|
+
bg.move_to([0, baseline_y + panel_h/2 - 0.10, -0.002])
|
|
417
|
+
self.add(bg)
|
|
418
|
+
|
|
419
|
+
# ── Base fill polygon ─────────────────────────────────────────
|
|
420
|
+
verts = _curve_verts(x_px, y_px, baseline_y)
|
|
421
|
+
if len(verts) >= 3:
|
|
422
|
+
base = Polygon(
|
|
423
|
+
*verts,
|
|
424
|
+
fill_color=PAL["pop_fill"],
|
|
425
|
+
fill_opacity=0.85,
|
|
426
|
+
stroke_width=0,
|
|
427
|
+
)
|
|
428
|
+
base.shift([0, 0, 0.001])
|
|
429
|
+
self.add(base)
|
|
430
|
+
|
|
431
|
+
# ── AO darkening at tails ─────────────────────────────────────
|
|
432
|
+
ao_w = (x_px[-1] - x_px[0]) * 0.10
|
|
433
|
+
for x_edge, x_inner in [
|
|
434
|
+
(x_px[0], x_px[0] + ao_w),
|
|
435
|
+
(x_px[-1], x_px[-1] - ao_w),
|
|
436
|
+
]:
|
|
437
|
+
xl, xr = min(x_edge, x_inner), max(x_edge, x_inner)
|
|
438
|
+
mask = (x_px >= xl) & (x_px <= xr)
|
|
439
|
+
xs, ys = x_px[mask], y_px[mask]
|
|
440
|
+
if len(xs) >= 2:
|
|
441
|
+
av = ([[xl, baseline_y, 0]]
|
|
442
|
+
+ [[float(x),float(y),0] for x,y in zip(xs,ys)]
|
|
443
|
+
+ [[xr, baseline_y, 0]])
|
|
444
|
+
ao = Polygon(*av,
|
|
445
|
+
fill_color=PAL["pop_ao"],
|
|
446
|
+
fill_opacity=0.48, stroke_width=0)
|
|
447
|
+
ao.shift([0, 0, 0.002])
|
|
448
|
+
self.add(ao)
|
|
449
|
+
|
|
450
|
+
# ── Ridge spine ───────────────────────────────────────────────
|
|
451
|
+
step = max(1, len(x_px)//80)
|
|
452
|
+
pts3d = [np.array([float(x_px[i]), float(y_px[i]), 0.004])
|
|
453
|
+
for i in range(0, len(x_px), step) if y_px[i] > 1e-4]
|
|
454
|
+
if len(pts3d) >= 2:
|
|
455
|
+
spine = VMobject(stroke_color=PAL["pop_ridge"],
|
|
456
|
+
stroke_width=1.8, stroke_opacity=0.80)
|
|
457
|
+
spine.set_points_smoothly(pts3d)
|
|
458
|
+
self.add(spine)
|
|
459
|
+
|
|
460
|
+
# ── Peak cap ──────────────────────────────────────────────────
|
|
461
|
+
peak_i = int(np.argmax(y_px))
|
|
462
|
+
peak_pos = [float(x_px[peak_i]),
|
|
463
|
+
float(y_px[peak_i]) + 0.03, 0.005]
|
|
464
|
+
cap = Circle(radius=0.05,
|
|
465
|
+
fill_color=PAL["pop_ridge"],
|
|
466
|
+
fill_opacity=0.90, stroke_width=0)
|
|
467
|
+
cap.move_to(peak_pos)
|
|
468
|
+
self.add(cap)
|
|
469
|
+
|
|
470
|
+
# ── Axis line ─────────────────────────────────────────────────
|
|
471
|
+
ax = Line(
|
|
472
|
+
start=[-panel_w/2 - 0.15, baseline_y, 0.001],
|
|
473
|
+
end =[ panel_w/2 + 0.15, baseline_y, 0.001],
|
|
474
|
+
stroke_color=PAL["axis"], stroke_width=1.5,
|
|
475
|
+
)
|
|
476
|
+
self.add(ax)
|
|
477
|
+
|
|
478
|
+
# ── Axis ticks ────────────────────────────────────────────────
|
|
479
|
+
mu_pop, _ = _pop_stats(pop_type, params)
|
|
480
|
+
for rv in [x_lo, mu_pop, x_hi]:
|
|
481
|
+
xp = float(_map_x(rv, x_lo, x_hi, panel_w))
|
|
482
|
+
tk = Line([xp, baseline_y-0.07, 0.001],
|
|
483
|
+
[xp, baseline_y+0.07, 0.001],
|
|
484
|
+
stroke_color=PAL["tick"], stroke_width=1.2)
|
|
485
|
+
lbl = Text(f"{rv:.1f}", font_size=12,
|
|
486
|
+
color=PAL["axis_label"])
|
|
487
|
+
lbl.move_to([xp, baseline_y - 0.27, 0.001])
|
|
488
|
+
self.add(tk, lbl)
|
|
489
|
+
|
|
490
|
+
# ── Parameter badges ──────────────────────────────────────────
|
|
491
|
+
mu_v, sigma_v = _pop_stats(pop_type, params)
|
|
492
|
+
badge_y = baseline_y + panel_h + 0.25
|
|
493
|
+
for i, (sym, val) in enumerate(
|
|
494
|
+
[("\\mu", mu_v), ("\\sigma", sigma_v)]
|
|
495
|
+
):
|
|
496
|
+
try:
|
|
497
|
+
bm = MathTex(f"{sym} = {val:.3f}",
|
|
498
|
+
font_size=20, color=PAL["pop_label"])
|
|
499
|
+
except Exception:
|
|
500
|
+
bm = Text(f"{sym}={val:.3f}", font_size=17,
|
|
501
|
+
color=PAL["pop_label"])
|
|
502
|
+
bm.move_to([-panel_w/4 + i*panel_w/2,
|
|
503
|
+
badge_y, 0.003])
|
|
504
|
+
self.add(bm)
|
|
505
|
+
|
|
506
|
+
# ── Title ─────────────────────────────────────────────────────
|
|
507
|
+
title_map = {
|
|
508
|
+
"normal": "Normal Population",
|
|
509
|
+
"uniform": "Uniform Population",
|
|
510
|
+
"exponential": "Exponential Population",
|
|
511
|
+
"chi2": "Chi-Squared Population",
|
|
512
|
+
"bimodal": "Bimodal Population",
|
|
513
|
+
"bernoulli": "Bernoulli Population",
|
|
514
|
+
}
|
|
515
|
+
title = Text(title_map.get(pop_type, "Population"),
|
|
516
|
+
font_size=18, color=PAL["panel_title"])
|
|
517
|
+
title.move_to([0, baseline_y + panel_h + 0.62, 0.003])
|
|
518
|
+
self.add(title)
|
|
519
|
+
|
|
520
|
+
# Save geometry for use by animations
|
|
521
|
+
self._mu_pop = mu_v
|
|
522
|
+
self._sigma_pop = sigma_v
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
class _SampleStrip(VGroup):
|
|
526
|
+
"""
|
|
527
|
+
The sample observation strip: a number line with dots.
|
|
528
|
+
|
|
529
|
+
Components:
|
|
530
|
+
1. Horizontal number line with tick marks
|
|
531
|
+
2. n Dot objects (added one by one during DrawSample)
|
|
532
|
+
3. Bracket that collapses to the mean (added during ExtractMean)
|
|
533
|
+
4. Mean dot (highlighted, larger)
|
|
534
|
+
|
|
535
|
+
Parameters
|
|
536
|
+
----------
|
|
537
|
+
x_lo, x_hi : raw axis range
|
|
538
|
+
strip_w : Manim units width
|
|
539
|
+
y : vertical position
|
|
540
|
+
n_samples : sample size (number of dots)
|
|
541
|
+
"""
|
|
542
|
+
|
|
543
|
+
def __init__(
|
|
544
|
+
self,
|
|
545
|
+
x_lo: float,
|
|
546
|
+
x_hi: float,
|
|
547
|
+
strip_w: float,
|
|
548
|
+
y: float,
|
|
549
|
+
n_samples: int,
|
|
550
|
+
**kwargs,
|
|
551
|
+
):
|
|
552
|
+
super().__init__(**kwargs)
|
|
553
|
+
self._x_lo = x_lo
|
|
554
|
+
self._x_hi = x_hi
|
|
555
|
+
self._strip_w = strip_w
|
|
556
|
+
self._y = y
|
|
557
|
+
self._n = n_samples
|
|
558
|
+
self._dots: list = []
|
|
559
|
+
self._mean_dot = None
|
|
560
|
+
|
|
561
|
+
# ── Number line ───────────────────────────────────────────────
|
|
562
|
+
nline = Line(
|
|
563
|
+
start=[-strip_w/2, y, 0],
|
|
564
|
+
end =[ strip_w/2, y, 0],
|
|
565
|
+
stroke_color=PAL["strip_line"],
|
|
566
|
+
stroke_width=1.5,
|
|
567
|
+
)
|
|
568
|
+
self.add(nline)
|
|
569
|
+
|
|
570
|
+
# Tick marks
|
|
571
|
+
n_ticks = 6
|
|
572
|
+
for i in range(n_ticks + 1):
|
|
573
|
+
frac = i / n_ticks
|
|
574
|
+
rv = x_lo + frac * (x_hi - x_lo)
|
|
575
|
+
xp = frac * strip_w - strip_w/2
|
|
576
|
+
tk = Line([xp, y-0.06, 0.001],
|
|
577
|
+
[xp, y+0.06, 0.001],
|
|
578
|
+
stroke_color=PAL["tick"], stroke_width=1.0)
|
|
579
|
+
lbl = Text(f"{rv:.1f}", font_size=11,
|
|
580
|
+
color=PAL["axis_label"])
|
|
581
|
+
lbl.move_to([xp, y - 0.22, 0.001])
|
|
582
|
+
self.add(tk, lbl)
|
|
583
|
+
|
|
584
|
+
def raw_to_px(self, v: float) -> float:
|
|
585
|
+
frac = (v - self._x_lo) / (self._x_hi - self._x_lo)
|
|
586
|
+
return frac * self._strip_w - self._strip_w/2
|
|
587
|
+
|
|
588
|
+
def add_dot(
|
|
589
|
+
self,
|
|
590
|
+
raw_val: float,
|
|
591
|
+
color: str = None,
|
|
592
|
+
dot_r: float = 0.07,
|
|
593
|
+
) -> Dot:
|
|
594
|
+
"""Create and register a dot at raw_val."""
|
|
595
|
+
color = color or PAL["dot_default"]
|
|
596
|
+
xp = self.raw_to_px(raw_val)
|
|
597
|
+
# Jitter y slightly to avoid perfect overlap
|
|
598
|
+
y_jitt = self._y + np.random.uniform(0.04, 0.22)
|
|
599
|
+
dot = Dot(radius=dot_r,
|
|
600
|
+
point=[xp, y_jitt, 0.005],
|
|
601
|
+
color=color,
|
|
602
|
+
fill_opacity=0.88)
|
|
603
|
+
self._dots.append(dot)
|
|
604
|
+
self.add(dot)
|
|
605
|
+
return dot
|
|
606
|
+
|
|
607
|
+
def make_mean_dot(self, mean_raw: float) -> Dot:
|
|
608
|
+
"""Create the highlighted mean dot."""
|
|
609
|
+
xp = self.raw_to_px(mean_raw)
|
|
610
|
+
dot = Dot(radius=0.11,
|
|
611
|
+
point=[xp, self._y + 0.12, 0.010],
|
|
612
|
+
color=PAL["dot_mean"],
|
|
613
|
+
fill_opacity=1.0)
|
|
614
|
+
self._mean_dot = dot
|
|
615
|
+
self.add(dot)
|
|
616
|
+
return dot
|
|
617
|
+
|
|
618
|
+
def clear_dots(self):
|
|
619
|
+
"""Remove all sample dots (but keep the number line)."""
|
|
620
|
+
for d in self._dots:
|
|
621
|
+
if d in self.submobjects:
|
|
622
|
+
self.remove(d)
|
|
623
|
+
self._dots.clear()
|
|
624
|
+
if self._mean_dot and self._mean_dot in self.submobjects:
|
|
625
|
+
self.remove(self._mean_dot)
|
|
626
|
+
self._mean_dot = None
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
class _HistogramPanel(VGroup):
|
|
630
|
+
"""
|
|
631
|
+
Right panel: sampling distribution histogram with 3-D bar effect.
|
|
632
|
+
|
|
633
|
+
Each bar has three faces:
|
|
634
|
+
top_cap — bright thin rectangle (the "top face")
|
|
635
|
+
side_face — slightly darker rectangle on the right side
|
|
636
|
+
front_face — the main bar (body colour)
|
|
637
|
+
Plus a base AO shadow below each bar.
|
|
638
|
+
|
|
639
|
+
Parameters
|
|
640
|
+
----------
|
|
641
|
+
x_lo, x_hi : raw x range for the histogram
|
|
642
|
+
n_bins : number of histogram bins
|
|
643
|
+
panel_w : Manim units width
|
|
644
|
+
max_bar_h : maximum bar height (Manim units) at full count
|
|
645
|
+
baseline_y : y of the histogram baseline
|
|
646
|
+
max_count : expected maximum count (for bar scaling)
|
|
647
|
+
"""
|
|
648
|
+
|
|
649
|
+
def __init__(
|
|
650
|
+
self,
|
|
651
|
+
x_lo: float,
|
|
652
|
+
x_hi: float,
|
|
653
|
+
n_bins: int,
|
|
654
|
+
panel_w: float,
|
|
655
|
+
max_bar_h: float,
|
|
656
|
+
baseline_y: float,
|
|
657
|
+
max_count: int = 50,
|
|
658
|
+
**kwargs,
|
|
659
|
+
):
|
|
660
|
+
super().__init__(**kwargs)
|
|
661
|
+
self._x_lo = x_lo
|
|
662
|
+
self._x_hi = x_hi
|
|
663
|
+
self._n_bins = n_bins
|
|
664
|
+
self._panel_w = panel_w
|
|
665
|
+
self._max_bar_h = max_bar_h
|
|
666
|
+
self._baseline = baseline_y
|
|
667
|
+
self._max_count = max_count
|
|
668
|
+
|
|
669
|
+
# Bin edges and centres
|
|
670
|
+
self._edges = np.linspace(x_lo, x_hi, n_bins + 1)
|
|
671
|
+
self._centres = (self._edges[:-1] + self._edges[1:]) / 2
|
|
672
|
+
self._bin_w = panel_w / n_bins # bar width in px
|
|
673
|
+
self._counts = np.zeros(n_bins, dtype=int)
|
|
674
|
+
|
|
675
|
+
# 3-D depth parameters
|
|
676
|
+
self._depth_x = self._bin_w * 0.08 # right-face overhang
|
|
677
|
+
self._cap_h = 0.045 # top face height
|
|
678
|
+
|
|
679
|
+
# Pre-create bar groups (initially zero height)
|
|
680
|
+
self._bars: list[VGroup] = []
|
|
681
|
+
for i in range(n_bins):
|
|
682
|
+
bar_grp = self._make_bar(i, 0)
|
|
683
|
+
self._bars.append(bar_grp)
|
|
684
|
+
self.add(bar_grp)
|
|
685
|
+
|
|
686
|
+
# Axis
|
|
687
|
+
ax = Line(
|
|
688
|
+
start=[-panel_w/2 - 0.15, baseline_y, 0.001],
|
|
689
|
+
end =[ panel_w/2 + 0.15, baseline_y, 0.001],
|
|
690
|
+
stroke_color=PAL["axis"], stroke_width=1.5,
|
|
691
|
+
)
|
|
692
|
+
self.add(ax)
|
|
693
|
+
|
|
694
|
+
# Axis ticks + labels
|
|
695
|
+
for i in range(n_bins + 1):
|
|
696
|
+
xp = float(i * self._bin_w - panel_w/2)
|
|
697
|
+
rv = self._edges[i]
|
|
698
|
+
tk = Line([xp, baseline_y-0.06, 0.001],
|
|
699
|
+
[xp, baseline_y+0.06, 0.001],
|
|
700
|
+
stroke_color=PAL["tick"], stroke_width=0.9)
|
|
701
|
+
lbl = Text(f"{rv:.2f}", font_size=10,
|
|
702
|
+
color=PAL["axis_label"])
|
|
703
|
+
lbl.rotate(PI/4)
|
|
704
|
+
lbl.move_to([xp, baseline_y - 0.28, 0.001])
|
|
705
|
+
self.add(tk, lbl)
|
|
706
|
+
|
|
707
|
+
# Count labels above bars (initially empty)
|
|
708
|
+
self._count_labels: list = [None] * n_bins
|
|
709
|
+
|
|
710
|
+
# Theoretical curve placeholder (added later)
|
|
711
|
+
self._theory_curve = None
|
|
712
|
+
|
|
713
|
+
def _bar_left_px(self, i: int) -> float:
|
|
714
|
+
return i * self._bin_w - self._panel_w/2
|
|
715
|
+
|
|
716
|
+
def _bar_height(self, count: int) -> float:
|
|
717
|
+
"""Convert count to bar height in Manim units."""
|
|
718
|
+
return (count / max(self._max_count, 1)) * self._max_bar_h
|
|
719
|
+
|
|
720
|
+
def _make_bar(self, i: int, count: int) -> VGroup:
|
|
721
|
+
"""Build a 3-D bar at bin i with given count."""
|
|
722
|
+
grp = VGroup()
|
|
723
|
+
xl = self._bar_left_px(i)
|
|
724
|
+
h = self._bar_height(count)
|
|
725
|
+
bw = self._bin_w
|
|
726
|
+
by = self._baseline
|
|
727
|
+
dx = self._depth_x
|
|
728
|
+
cap_h = self._cap_h
|
|
729
|
+
|
|
730
|
+
if h < 1e-4:
|
|
731
|
+
return grp
|
|
732
|
+
|
|
733
|
+
# ── Front face (main bar body) ────────────────────────────────
|
|
734
|
+
front = Rectangle(
|
|
735
|
+
width=bw - 0.015,
|
|
736
|
+
height=h,
|
|
737
|
+
fill_color=PAL["bar_top"],
|
|
738
|
+
fill_opacity=0.88,
|
|
739
|
+
stroke_color=PAL["bar_border"],
|
|
740
|
+
stroke_width=0.5,
|
|
741
|
+
)
|
|
742
|
+
front.move_to([xl + bw/2, by + h/2, 0.002])
|
|
743
|
+
grp.add(front)
|
|
744
|
+
|
|
745
|
+
# ── Right side face ───────────────────────────────────────────
|
|
746
|
+
side_pts = [
|
|
747
|
+
[xl + bw - 0.008, by, 0.002],
|
|
748
|
+
[xl + bw - 0.008 + dx, by + dx*0.5, 0.002],
|
|
749
|
+
[xl + bw - 0.008 + dx, by + h + dx*0.5, 0.002],
|
|
750
|
+
[xl + bw - 0.008, by + h, 0.002],
|
|
751
|
+
]
|
|
752
|
+
side = Polygon(*side_pts,
|
|
753
|
+
fill_color=PAL["bar_side"],
|
|
754
|
+
fill_opacity=0.82, stroke_width=0)
|
|
755
|
+
side.shift([0, 0, 0.001])
|
|
756
|
+
grp.add(side)
|
|
757
|
+
|
|
758
|
+
# ── Top cap ───────────────────────────────────────────────────
|
|
759
|
+
top_pts = [
|
|
760
|
+
[xl + 0.008, by + h, 0.004],
|
|
761
|
+
[xl + bw - 0.008, by + h, 0.004],
|
|
762
|
+
[xl + bw - 0.008 + dx, by + h + dx*0.5, 0.004],
|
|
763
|
+
[xl + 0.008 + dx, by + h + dx*0.5, 0.004],
|
|
764
|
+
]
|
|
765
|
+
top = Polygon(*top_pts,
|
|
766
|
+
fill_color=PAL["bar_top_lite"],
|
|
767
|
+
fill_opacity=0.90, stroke_width=0)
|
|
768
|
+
grp.add(top)
|
|
769
|
+
|
|
770
|
+
# ── AO shadow at base ─────────────────────────────────────────
|
|
771
|
+
ao_h = 0.055
|
|
772
|
+
ao = Rectangle(
|
|
773
|
+
width=bw - 0.015,
|
|
774
|
+
height=ao_h,
|
|
775
|
+
fill_color=PAL["bar_ao"],
|
|
776
|
+
fill_opacity=0.55,
|
|
777
|
+
stroke_width=0,
|
|
778
|
+
)
|
|
779
|
+
ao.move_to([xl + bw/2, by + ao_h/2, 0.003])
|
|
780
|
+
grp.add(ao)
|
|
781
|
+
|
|
782
|
+
return grp
|
|
783
|
+
|
|
784
|
+
def update_bar(self, i: int):
|
|
785
|
+
"""Rebuild bar i to reflect current count."""
|
|
786
|
+
# Remove old bar
|
|
787
|
+
old = self._bars[i]
|
|
788
|
+
if old in self.submobjects:
|
|
789
|
+
self.remove(old)
|
|
790
|
+
# Build new
|
|
791
|
+
new = self._make_bar(i, int(self._counts[i]))
|
|
792
|
+
self._bars[i] = new
|
|
793
|
+
self.add(new)
|
|
794
|
+
|
|
795
|
+
# Count label
|
|
796
|
+
if self._count_labels[i] is not None:
|
|
797
|
+
if self._count_labels[i] in self.submobjects:
|
|
798
|
+
self.remove(self._count_labels[i])
|
|
799
|
+
xl = self._bar_left_px(i)
|
|
800
|
+
h = self._bar_height(int(self._counts[i]))
|
|
801
|
+
lbl = Text(str(int(self._counts[i])),
|
|
802
|
+
font_size=11, color=PAL["panel_val"])
|
|
803
|
+
lbl.move_to([xl + self._bin_w/2,
|
|
804
|
+
self._baseline + h + 0.18, 0.008])
|
|
805
|
+
self._count_labels[i] = lbl
|
|
806
|
+
self.add(lbl)
|
|
807
|
+
|
|
808
|
+
def add_count(self, raw_mean: float) -> int:
|
|
809
|
+
"""
|
|
810
|
+
Increment the bin containing raw_mean.
|
|
811
|
+
Returns the bin index.
|
|
812
|
+
"""
|
|
813
|
+
i = int(np.searchsorted(self._edges[1:], raw_mean))
|
|
814
|
+
i = np.clip(i, 0, self._n_bins - 1)
|
|
815
|
+
self._counts[i] += 1
|
|
816
|
+
self.update_bar(i)
|
|
817
|
+
return int(i)
|
|
818
|
+
|
|
819
|
+
def bin_top_position(self, i: int) -> np.ndarray:
|
|
820
|
+
"""World position of the top-centre of bar i."""
|
|
821
|
+
xl = self._bar_left_px(i)
|
|
822
|
+
h = self._bar_height(int(self._counts[i]))
|
|
823
|
+
return np.array([xl + self._bin_w/2,
|
|
824
|
+
self._baseline + h + 0.10, 0.0])
|
|
825
|
+
|
|
826
|
+
def set_theory_curve(
|
|
827
|
+
self,
|
|
828
|
+
mu: float,
|
|
829
|
+
sigma_n: float,
|
|
830
|
+
n_curves: int = 0,
|
|
831
|
+
) -> Optional[VGroup]:
|
|
832
|
+
"""
|
|
833
|
+
Draw or update the theoretical N(mu, sigma_n²) curve overlay.
|
|
834
|
+
``n_curves`` determines dashed (< 10) vs solid style.
|
|
835
|
+
"""
|
|
836
|
+
if self._theory_curve is not None:
|
|
837
|
+
if self._theory_curve in self.submobjects:
|
|
838
|
+
self.remove(self._theory_curve)
|
|
839
|
+
|
|
840
|
+
raw_x = np.linspace(self._x_lo, self._x_hi, 400)
|
|
841
|
+
y_pdf = _norm_pdf(raw_x, mu, sigma_n)
|
|
842
|
+
y_pdf = np.where(np.isfinite(y_pdf), y_pdf, 0.0)
|
|
843
|
+
|
|
844
|
+
# Scale: area of pdf = 1; histogram total area = sum(counts) * bin_width
|
|
845
|
+
bin_w_raw = (self._x_hi - self._x_lo) / self._n_bins
|
|
846
|
+
total = int(self._counts.sum())
|
|
847
|
+
if total < 2:
|
|
848
|
+
return None
|
|
849
|
+
|
|
850
|
+
scale_y = (total * bin_w_raw
|
|
851
|
+
* self._max_bar_h / self._max_count
|
|
852
|
+
/ (self._x_hi - self._x_lo) * self._n_bins)
|
|
853
|
+
|
|
854
|
+
x_px = _map_x(raw_x, self._x_lo, self._x_hi, self._panel_w)
|
|
855
|
+
y_px = y_pdf * scale_y
|
|
856
|
+
|
|
857
|
+
curve_grp = VGroup()
|
|
858
|
+
is_solid = n_curves >= 10
|
|
859
|
+
|
|
860
|
+
# Fill area (subtle)
|
|
861
|
+
verts = _curve_verts(x_px, y_px, self._baseline)
|
|
862
|
+
if len(verts) >= 3:
|
|
863
|
+
fill = Polygon(*verts,
|
|
864
|
+
fill_color=PAL["theory_fill"],
|
|
865
|
+
fill_opacity=0.30,
|
|
866
|
+
stroke_width=0)
|
|
867
|
+
fill.shift([0, 0, 0.006])
|
|
868
|
+
curve_grp.add(fill)
|
|
869
|
+
|
|
870
|
+
# Curve line
|
|
871
|
+
step = max(1, len(x_px)//100)
|
|
872
|
+
pts3d = [np.array([float(x_px[j]), float(y_px[j]), 0.008])
|
|
873
|
+
for j in range(0, len(x_px), step) if y_px[j] > 0.005]
|
|
874
|
+
if len(pts3d) >= 2:
|
|
875
|
+
col = PAL["theory_solid"] if is_solid else PAL["theory_dashed"]
|
|
876
|
+
sp = VMobject(stroke_color=col,
|
|
877
|
+
stroke_width=2.2 if is_solid else 1.5,
|
|
878
|
+
stroke_opacity=0.90 if is_solid else 0.60)
|
|
879
|
+
sp.set_points_smoothly(pts3d)
|
|
880
|
+
curve_grp.add(sp)
|
|
881
|
+
|
|
882
|
+
self._theory_curve = curve_grp
|
|
883
|
+
self.add(curve_grp)
|
|
884
|
+
return curve_grp
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
class _SEArrow(VGroup):
|
|
888
|
+
"""
|
|
889
|
+
Double-headed bracket arrow spanning ±1 SE around the sampling mean.
|
|
890
|
+
|
|
891
|
+
Components:
|
|
892
|
+
1. DoubleArrow
|
|
893
|
+
2. SE badge: "SE = σ/√n = {value:.3f}"
|
|
894
|
+
3. Bracket ticks at each end
|
|
895
|
+
|
|
896
|
+
Parameters
|
|
897
|
+
----------
|
|
898
|
+
mu_px : Manim x of the sampling distribution mean
|
|
899
|
+
se_px : Manim units width of 1 SE
|
|
900
|
+
y : vertical position
|
|
901
|
+
se_val : raw SE value (for label)
|
|
902
|
+
n : sample size (for label)
|
|
903
|
+
"""
|
|
904
|
+
|
|
905
|
+
def __init__(
|
|
906
|
+
self,
|
|
907
|
+
mu_px: float,
|
|
908
|
+
se_px: float,
|
|
909
|
+
y: float,
|
|
910
|
+
se_val: float,
|
|
911
|
+
n: int,
|
|
912
|
+
**kwargs,
|
|
913
|
+
):
|
|
914
|
+
super().__init__(**kwargs)
|
|
915
|
+
z0 = 0.012
|
|
916
|
+
|
|
917
|
+
arr = DoubleArrow(
|
|
918
|
+
start=[mu_px - se_px, y, z0],
|
|
919
|
+
end =[mu_px + se_px, y, z0],
|
|
920
|
+
stroke_color=PAL["se_arrow"],
|
|
921
|
+
stroke_width=2.0,
|
|
922
|
+
tip_length=0.14,
|
|
923
|
+
buff=0,
|
|
924
|
+
)
|
|
925
|
+
self.add(arr)
|
|
926
|
+
|
|
927
|
+
# Bracket ticks at ends
|
|
928
|
+
for xp in [mu_px - se_px, mu_px + se_px]:
|
|
929
|
+
tk = Line([xp, y - 0.10, z0+0.001],
|
|
930
|
+
[xp, y + 0.10, z0+0.001],
|
|
931
|
+
stroke_color=PAL["se_arrow"], stroke_width=1.5)
|
|
932
|
+
self.add(tk)
|
|
933
|
+
|
|
934
|
+
# Badge
|
|
935
|
+
try:
|
|
936
|
+
lbl = MathTex(
|
|
937
|
+
rf"\mathrm{{SE}} = \sigma/\sqrt{{n}} = {se_val:.3f}",
|
|
938
|
+
font_size=18, color=PAL["se_label"]
|
|
939
|
+
)
|
|
940
|
+
except Exception:
|
|
941
|
+
lbl = Text(f"SE = σ/√n = {se_val:.3f}",
|
|
942
|
+
font_size=15, color=PAL["se_label"])
|
|
943
|
+
bg = RoundedRectangle(
|
|
944
|
+
width=lbl.width + 0.22,
|
|
945
|
+
height=lbl.height + 0.14,
|
|
946
|
+
corner_radius=0.06,
|
|
947
|
+
fill_color=PAL["se_badge_bg"],
|
|
948
|
+
fill_opacity=0.90,
|
|
949
|
+
stroke_color=PAL["se_arrow"],
|
|
950
|
+
stroke_width=0.7,
|
|
951
|
+
)
|
|
952
|
+
bg.move_to([mu_px, y + 0.35, z0 + 0.001])
|
|
953
|
+
lbl.move_to([mu_px, y + 0.35, z0 + 0.002])
|
|
954
|
+
self.add(bg, lbl)
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
class _StatsPanel(VGroup):
|
|
958
|
+
"""
|
|
959
|
+
Floating live-stats panel showing current simulation state.
|
|
960
|
+
|
|
961
|
+
Rows:
|
|
962
|
+
Samples drawn: k
|
|
963
|
+
Sample size n: n
|
|
964
|
+
Current x̄: value
|
|
965
|
+
True μ: value
|
|
966
|
+
SE = σ/√n: value
|
|
967
|
+
Empirical SE: std(means) so far
|
|
968
|
+
|
|
969
|
+
Parameters
|
|
970
|
+
----------
|
|
971
|
+
panel_w, panel_h : dimensions
|
|
972
|
+
"""
|
|
973
|
+
|
|
974
|
+
def __init__(
|
|
975
|
+
self,
|
|
976
|
+
k: int = 0,
|
|
977
|
+
n: int = 1,
|
|
978
|
+
x_bar: float = 0.0,
|
|
979
|
+
true_mu: float = 0.0,
|
|
980
|
+
se_true: float = 1.0,
|
|
981
|
+
se_emp: float = 0.0,
|
|
982
|
+
panel_w: float = 2.40,
|
|
983
|
+
panel_h: float = 2.20,
|
|
984
|
+
**kwargs,
|
|
985
|
+
):
|
|
986
|
+
super().__init__(**kwargs)
|
|
987
|
+
z0 = 0.001
|
|
988
|
+
|
|
989
|
+
bg = RoundedRectangle(
|
|
990
|
+
width=panel_w, height=panel_h,
|
|
991
|
+
corner_radius=0.10,
|
|
992
|
+
fill_color=PAL["panel_bg"],
|
|
993
|
+
fill_opacity=0.92,
|
|
994
|
+
stroke_color=PAL["panel_border"],
|
|
995
|
+
stroke_width=0.8,
|
|
996
|
+
)
|
|
997
|
+
bg.move_to([0, 0, z0])
|
|
998
|
+
self.add(bg)
|
|
999
|
+
|
|
1000
|
+
# Left border strip
|
|
1001
|
+
strip = RoundedRectangle(
|
|
1002
|
+
width=0.08, height=panel_h-0.04,
|
|
1003
|
+
corner_radius=0.04,
|
|
1004
|
+
fill_color=PAL["bar_top"],
|
|
1005
|
+
fill_opacity=0.85, stroke_width=0,
|
|
1006
|
+
)
|
|
1007
|
+
strip.move_to([-panel_w/2+0.06, 0, z0+0.001])
|
|
1008
|
+
self.add(strip)
|
|
1009
|
+
|
|
1010
|
+
title = Text("CLT Simulation", font_size=15,
|
|
1011
|
+
color=PAL["panel_title"])
|
|
1012
|
+
title.move_to([0, panel_h/2 - 0.22, z0+0.002])
|
|
1013
|
+
self.add(title)
|
|
1014
|
+
|
|
1015
|
+
self.add(Line(
|
|
1016
|
+
[-panel_w/2+0.14, panel_h/2-0.42, z0+0.002],
|
|
1017
|
+
[ panel_w/2-0.08, panel_h/2-0.42, z0+0.002],
|
|
1018
|
+
stroke_color=PAL["panel_border"], stroke_width=0.6,
|
|
1019
|
+
))
|
|
1020
|
+
|
|
1021
|
+
rows = [
|
|
1022
|
+
("Samples drawn", str(k)),
|
|
1023
|
+
("n per sample", str(n)),
|
|
1024
|
+
("Current x̄", f"{x_bar:.3f}"),
|
|
1025
|
+
("True μ", f"{true_mu:.3f}"),
|
|
1026
|
+
("SE = σ/√n", f"{se_true:.4f}"),
|
|
1027
|
+
("Empirical SE", f"{se_emp:.4f}" if k>1 else "—"),
|
|
1028
|
+
]
|
|
1029
|
+
row_h = (panel_h - 0.80) / len(rows)
|
|
1030
|
+
y0 = panel_h/2 - 0.60
|
|
1031
|
+
for i, (key, val) in enumerate(rows):
|
|
1032
|
+
yr = y0 - i * row_h
|
|
1033
|
+
km = Text(key, font_size=12, color=PAL["panel_key"])
|
|
1034
|
+
vm = Text(val, font_size=12, color=PAL["panel_val"],
|
|
1035
|
+
font="monospace")
|
|
1036
|
+
km.move_to([-panel_w/2+0.22+km.width/2, yr, z0+0.003])
|
|
1037
|
+
vm.move_to([ panel_w/2-0.10-vm.width/2, yr, z0+0.003])
|
|
1038
|
+
self.add(km, vm)
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1042
|
+
# SamplingDistribution3D ── the main export
|
|
1043
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1044
|
+
|
|
1045
|
+
class SamplingDistribution3D(VGroup):
|
|
1046
|
+
"""
|
|
1047
|
+
Full Central Limit Theorem / sampling distribution visualisation.
|
|
1048
|
+
|
|
1049
|
+
Layout (left → right):
|
|
1050
|
+
[Population panel] → [CLT arrow] → [Sample strip] → [Histogram panel]
|
|
1051
|
+
|
|
1052
|
+
Parameters
|
|
1053
|
+
----------
|
|
1054
|
+
pop_type : str — "normal" | "uniform" | "exponential" |
|
|
1055
|
+
"chi2" | "bimodal" | "bernoulli"
|
|
1056
|
+
params : dict — distribution parameters
|
|
1057
|
+
n : int — sample size per draw
|
|
1058
|
+
n_bins : int — histogram bins (default 20)
|
|
1059
|
+
pop_panel_w: float — population panel width
|
|
1060
|
+
hist_panel_w: float — histogram panel width
|
|
1061
|
+
panel_h : float — curve / bar maximum height
|
|
1062
|
+
baseline_y : float
|
|
1063
|
+
max_samples: int — expected total samples (for bar scaling)
|
|
1064
|
+
seed : int — RNG seed for reproducibility
|
|
1065
|
+
show_strip : bool — show the sample dot strip
|
|
1066
|
+
show_se : bool — show the SE arrow on histogram
|
|
1067
|
+
show_panel : bool — show the stats panel
|
|
1068
|
+
|
|
1069
|
+
Attributes
|
|
1070
|
+
----------
|
|
1071
|
+
pop_panel : _PopulationPanel
|
|
1072
|
+
sample_strip : _SampleStrip | None
|
|
1073
|
+
hist_panel : _HistogramPanel
|
|
1074
|
+
se_arrow : _SEArrow | None
|
|
1075
|
+
stats_panel : _StatsPanel | None
|
|
1076
|
+
clt_arrow : Arrow
|
|
1077
|
+
n_tracker : ValueTracker
|
|
1078
|
+
k_drawn : int — samples drawn so far
|
|
1079
|
+
means : list — running list of drawn sample means
|
|
1080
|
+
current_sample: np.ndarray | None
|
|
1081
|
+
|
|
1082
|
+
Class methods
|
|
1083
|
+
-------------
|
|
1084
|
+
SamplingDistribution3D.normal(mu, sigma, n, **kw)
|
|
1085
|
+
SamplingDistribution3D.uniform(a, b, n, **kw)
|
|
1086
|
+
SamplingDistribution3D.exponential(lam, n, **kw)
|
|
1087
|
+
SamplingDistribution3D.chi_squared(df, n, **kw)
|
|
1088
|
+
SamplingDistribution3D.bimodal(mu1, mu2, sigma, mix, n, **kw)
|
|
1089
|
+
SamplingDistribution3D.bernoulli(p, n, **kw)
|
|
1090
|
+
"""
|
|
1091
|
+
|
|
1092
|
+
def __init__(
|
|
1093
|
+
self,
|
|
1094
|
+
pop_type: str = "normal",
|
|
1095
|
+
params: dict = None,
|
|
1096
|
+
n: int = 5,
|
|
1097
|
+
n_bins: int = 20,
|
|
1098
|
+
pop_panel_w: float = 4.0,
|
|
1099
|
+
hist_panel_w: float = 5.0,
|
|
1100
|
+
panel_h: float = 3.0,
|
|
1101
|
+
baseline_y: float = 0.0,
|
|
1102
|
+
max_samples: int = 100,
|
|
1103
|
+
seed: int = 42,
|
|
1104
|
+
show_strip: bool = True,
|
|
1105
|
+
show_se: bool = True,
|
|
1106
|
+
show_panel: bool = True,
|
|
1107
|
+
**kwargs,
|
|
1108
|
+
):
|
|
1109
|
+
super().__init__(**kwargs)
|
|
1110
|
+
|
|
1111
|
+
params = params or {"mu": 0.0, "sigma": 1.0}
|
|
1112
|
+
self._pop_type = pop_type
|
|
1113
|
+
self._params = params
|
|
1114
|
+
self._n = n
|
|
1115
|
+
self._n_bins = n_bins
|
|
1116
|
+
self._baseline = baseline_y
|
|
1117
|
+
self._panel_h = panel_h
|
|
1118
|
+
self._max_samples = max_samples
|
|
1119
|
+
self._rng = np.random.default_rng(seed)
|
|
1120
|
+
self.k_drawn = 0
|
|
1121
|
+
self.means: list[float] = []
|
|
1122
|
+
self.current_sample: Optional[np.ndarray] = None
|
|
1123
|
+
self.n_tracker = ValueTracker(float(n))
|
|
1124
|
+
|
|
1125
|
+
# Population statistics
|
|
1126
|
+
self._mu_pop, self._sigma_pop = _pop_stats(pop_type, params)
|
|
1127
|
+
self._se = self._sigma_pop / np.sqrt(n)
|
|
1128
|
+
x_lo_pop, x_hi_pop = _pop_x_range(pop_type, params)
|
|
1129
|
+
|
|
1130
|
+
# Sampling distribution x-range: ±4 SE around mu
|
|
1131
|
+
x_lo_hist = self._mu_pop - 4.5 * self._se
|
|
1132
|
+
x_hi_hist = self._mu_pop + 4.5 * self._se
|
|
1133
|
+
|
|
1134
|
+
# ── Layout positions ──────────────────────────────────────────
|
|
1135
|
+
gap = 0.45
|
|
1136
|
+
strip_w = hist_panel_w * 0.70
|
|
1137
|
+
strip_y = baseline_y - 1.30
|
|
1138
|
+
pop_cx = -(pop_panel_w/2 + gap + strip_w/2 + gap + hist_panel_w/2) / 2
|
|
1139
|
+
hist_cx = (hist_panel_w/2 + gap + strip_w/2 + gap + pop_panel_w/2) / 2
|
|
1140
|
+
|
|
1141
|
+
# Total width centres
|
|
1142
|
+
total_w = pop_panel_w + strip_w + hist_panel_w + 2*gap
|
|
1143
|
+
pop_cx = -total_w/2 + pop_panel_w/2
|
|
1144
|
+
hist_cx = total_w/2 - hist_panel_w/2
|
|
1145
|
+
strip_cx = 0.0
|
|
1146
|
+
|
|
1147
|
+
# ── Population panel ──────────────────────────────────────────
|
|
1148
|
+
self.pop_panel = _PopulationPanel(
|
|
1149
|
+
pop_type=pop_type,
|
|
1150
|
+
params=params,
|
|
1151
|
+
panel_w=pop_panel_w,
|
|
1152
|
+
panel_h=panel_h,
|
|
1153
|
+
baseline_y=baseline_y,
|
|
1154
|
+
)
|
|
1155
|
+
self.pop_panel.shift([pop_cx, 0, 0])
|
|
1156
|
+
self.add(self.pop_panel)
|
|
1157
|
+
|
|
1158
|
+
# ── CLT arrow ─────────────────────────────────────────────────
|
|
1159
|
+
clt_x_start = pop_cx + pop_panel_w/2 + 0.10
|
|
1160
|
+
clt_x_end = hist_cx - hist_panel_w/2 - 0.10
|
|
1161
|
+
clt_y = baseline_y + panel_h * 0.55
|
|
1162
|
+
self.clt_arrow = Arrow(
|
|
1163
|
+
start=[clt_x_start, clt_y, 0],
|
|
1164
|
+
end =[clt_x_end, clt_y, 0],
|
|
1165
|
+
stroke_color=PAL["clt_arrow"],
|
|
1166
|
+
stroke_width=2.0,
|
|
1167
|
+
tip_length=0.20,
|
|
1168
|
+
buff=0,
|
|
1169
|
+
)
|
|
1170
|
+
try:
|
|
1171
|
+
clt_lbl = MathTex(
|
|
1172
|
+
rf"n = {n},\;\text{{repeat}}",
|
|
1173
|
+
font_size=18, color=PAL["clt_label"]
|
|
1174
|
+
)
|
|
1175
|
+
except Exception:
|
|
1176
|
+
clt_lbl = Text(f"n={n}, repeat",
|
|
1177
|
+
font_size=15, color=PAL["clt_label"])
|
|
1178
|
+
clt_lbl.next_to(self.clt_arrow, UP, buff=0.10)
|
|
1179
|
+
self._clt_label = clt_lbl
|
|
1180
|
+
self.add(self.clt_arrow, clt_lbl)
|
|
1181
|
+
|
|
1182
|
+
# ── Sample strip ──────────────────────────────────────────────
|
|
1183
|
+
self.sample_strip = None
|
|
1184
|
+
if show_strip:
|
|
1185
|
+
self.sample_strip = _SampleStrip(
|
|
1186
|
+
x_lo=x_lo_pop,
|
|
1187
|
+
x_hi=x_hi_pop,
|
|
1188
|
+
strip_w=strip_w,
|
|
1189
|
+
y=strip_y,
|
|
1190
|
+
n_samples=n,
|
|
1191
|
+
)
|
|
1192
|
+
self.sample_strip.shift([strip_cx, 0, 0])
|
|
1193
|
+
self.add(self.sample_strip)
|
|
1194
|
+
|
|
1195
|
+
# ── Histogram panel ───────────────────────────────────────────
|
|
1196
|
+
self.hist_panel = _HistogramPanel(
|
|
1197
|
+
x_lo=x_lo_hist,
|
|
1198
|
+
x_hi=x_hi_hist,
|
|
1199
|
+
n_bins=n_bins,
|
|
1200
|
+
panel_w=hist_panel_w,
|
|
1201
|
+
max_bar_h=panel_h * 0.88,
|
|
1202
|
+
baseline_y=baseline_y,
|
|
1203
|
+
max_count=max(max_samples // n_bins * 3, 5),
|
|
1204
|
+
)
|
|
1205
|
+
self.hist_panel.shift([hist_cx, 0, 0])
|
|
1206
|
+
self._hist_cx = hist_cx
|
|
1207
|
+
self._hist_x_lo = x_lo_hist
|
|
1208
|
+
self._hist_x_hi = x_hi_hist
|
|
1209
|
+
self.add(self.hist_panel)
|
|
1210
|
+
|
|
1211
|
+
# ── Histogram title ───────────────────────────────────────────
|
|
1212
|
+
try:
|
|
1213
|
+
htitle = MathTex(
|
|
1214
|
+
r"\text{Sampling Distribution of }\bar{X}",
|
|
1215
|
+
font_size=20, color=PAL["panel_title"],
|
|
1216
|
+
)
|
|
1217
|
+
except Exception:
|
|
1218
|
+
htitle = Text("Sampling Distribution of X̄",
|
|
1219
|
+
font_size=17, color=PAL["panel_title"])
|
|
1220
|
+
htitle.move_to([hist_cx,
|
|
1221
|
+
baseline_y + panel_h + 0.62, 0.003])
|
|
1222
|
+
self.add(htitle)
|
|
1223
|
+
|
|
1224
|
+
# ── SE arrow ─────────────────────────────────────────────────
|
|
1225
|
+
self.se_arrow = None
|
|
1226
|
+
if show_se:
|
|
1227
|
+
mu_hist_px = self._hist_px(self._mu_pop)
|
|
1228
|
+
se_px_w = self._se * (hist_panel_w / (x_hi_hist - x_lo_hist))
|
|
1229
|
+
self.se_arrow = _SEArrow(
|
|
1230
|
+
mu_px=hist_cx + mu_hist_px,
|
|
1231
|
+
se_px=se_px_w,
|
|
1232
|
+
y=baseline_y - 0.58,
|
|
1233
|
+
se_val=self._se,
|
|
1234
|
+
n=n,
|
|
1235
|
+
)
|
|
1236
|
+
self.add(self.se_arrow)
|
|
1237
|
+
|
|
1238
|
+
# ── Stats panel ───────────────────────────────────────────────
|
|
1239
|
+
self.stats_panel = None
|
|
1240
|
+
if show_panel:
|
|
1241
|
+
self.stats_panel = _StatsPanel(
|
|
1242
|
+
k=0, n=n,
|
|
1243
|
+
x_bar=self._mu_pop,
|
|
1244
|
+
true_mu=self._mu_pop,
|
|
1245
|
+
se_true=self._se,
|
|
1246
|
+
)
|
|
1247
|
+
self.stats_panel.move_to([strip_cx, baseline_y - 2.30, 0])
|
|
1248
|
+
self.add(self.stats_panel)
|
|
1249
|
+
|
|
1250
|
+
# Internals
|
|
1251
|
+
self._strip_cx = strip_cx
|
|
1252
|
+
self._pop_cx = pop_cx
|
|
1253
|
+
self._x_lo_pop = x_lo_pop
|
|
1254
|
+
self._x_hi_pop = x_hi_pop
|
|
1255
|
+
self._hist_panel_w = hist_panel_w
|
|
1256
|
+
|
|
1257
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1258
|
+
# Coordinate helpers
|
|
1259
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1260
|
+
|
|
1261
|
+
def _hist_px(self, raw_val: float) -> float:
|
|
1262
|
+
"""Manim x relative to hist panel centre."""
|
|
1263
|
+
return _map_x(raw_val,
|
|
1264
|
+
self._hist_x_lo, self._hist_x_hi,
|
|
1265
|
+
self._hist_panel_w)
|
|
1266
|
+
|
|
1267
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1268
|
+
# Sample generation
|
|
1269
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1270
|
+
|
|
1271
|
+
def draw_new_sample(self) -> np.ndarray:
|
|
1272
|
+
"""Draw n observations from the population. Stores in self.current_sample."""
|
|
1273
|
+
sample = _sample_pop(self._pop_type, self._params,
|
|
1274
|
+
self._n, self._rng)
|
|
1275
|
+
self.current_sample = sample
|
|
1276
|
+
return sample
|
|
1277
|
+
|
|
1278
|
+
def commit_mean(self) -> float:
|
|
1279
|
+
"""Add current sample mean to means list. Returns the mean."""
|
|
1280
|
+
if self.current_sample is None:
|
|
1281
|
+
self.draw_new_sample()
|
|
1282
|
+
mean = float(np.mean(self.current_sample))
|
|
1283
|
+
self.means.append(mean)
|
|
1284
|
+
self.k_drawn += 1
|
|
1285
|
+
return mean
|
|
1286
|
+
|
|
1287
|
+
def update_stats_panel(self):
|
|
1288
|
+
"""Rebuild the stats panel with current counts."""
|
|
1289
|
+
if self.stats_panel is None:
|
|
1290
|
+
return
|
|
1291
|
+
if self.stats_panel in self.submobjects:
|
|
1292
|
+
self.remove(self.stats_panel)
|
|
1293
|
+
pos = self.stats_panel.get_center()
|
|
1294
|
+
emp_se = float(np.std(self.means)) if len(self.means) > 1 else 0.0
|
|
1295
|
+
x_bar = float(self.means[-1]) if self.means else self._mu_pop
|
|
1296
|
+
self.stats_panel = _StatsPanel(
|
|
1297
|
+
k=self.k_drawn, n=self._n,
|
|
1298
|
+
x_bar=x_bar,
|
|
1299
|
+
true_mu=self._mu_pop,
|
|
1300
|
+
se_true=self._se,
|
|
1301
|
+
se_emp=emp_se,
|
|
1302
|
+
)
|
|
1303
|
+
self.stats_panel.move_to(pos)
|
|
1304
|
+
self.add(self.stats_panel)
|
|
1305
|
+
|
|
1306
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1307
|
+
# Class-method constructors
|
|
1308
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1309
|
+
|
|
1310
|
+
@classmethod
|
|
1311
|
+
def normal(cls, mu: float = 0.0, sigma: float = 1.0,
|
|
1312
|
+
n: int = 5, **kw) -> "SamplingDistribution3D":
|
|
1313
|
+
return cls("normal", {"mu": mu, "sigma": sigma}, n=n, **kw)
|
|
1314
|
+
|
|
1315
|
+
@classmethod
|
|
1316
|
+
def uniform(cls, a: float = 0.0, b: float = 1.0,
|
|
1317
|
+
n: int = 5, **kw) -> "SamplingDistribution3D":
|
|
1318
|
+
return cls("uniform", {"a": a, "b": b}, n=n, **kw)
|
|
1319
|
+
|
|
1320
|
+
@classmethod
|
|
1321
|
+
def exponential(cls, lam: float = 1.0,
|
|
1322
|
+
n: int = 5, **kw) -> "SamplingDistribution3D":
|
|
1323
|
+
return cls("exponential", {"lam": lam}, n=n, **kw)
|
|
1324
|
+
|
|
1325
|
+
@classmethod
|
|
1326
|
+
def chi_squared(cls, df: int = 4,
|
|
1327
|
+
n: int = 5, **kw) -> "SamplingDistribution3D":
|
|
1328
|
+
return cls("chi2", {"df": df}, n=n, **kw)
|
|
1329
|
+
|
|
1330
|
+
@classmethod
|
|
1331
|
+
def bimodal(
|
|
1332
|
+
cls,
|
|
1333
|
+
mu1: float = -2.0, mu2: float = 2.0,
|
|
1334
|
+
sigma: float = 0.8, mix: float = 0.5,
|
|
1335
|
+
n: int = 5, **kw,
|
|
1336
|
+
) -> "SamplingDistribution3D":
|
|
1337
|
+
return cls("bimodal",
|
|
1338
|
+
{"mu1": mu1, "mu2": mu2,
|
|
1339
|
+
"sigma": sigma, "mix": mix},
|
|
1340
|
+
n=n, **kw)
|
|
1341
|
+
|
|
1342
|
+
@classmethod
|
|
1343
|
+
def bernoulli(cls, p: float = 0.3,
|
|
1344
|
+
n: int = 20, **kw) -> "SamplingDistribution3D":
|
|
1345
|
+
return cls("bernoulli", {"p": p}, n=n, **kw)
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1349
|
+
# Animations
|
|
1350
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1351
|
+
|
|
1352
|
+
class BuildPopulation(Animation):
|
|
1353
|
+
"""
|
|
1354
|
+
Population curve grows upward from the baseline.
|
|
1355
|
+
|
|
1356
|
+
α ∈ [0.00, 0.65] — curve scales up from 0
|
|
1357
|
+
α ∈ [0.55, 1.00] — parameter badges and title fade in
|
|
1358
|
+
"""
|
|
1359
|
+
|
|
1360
|
+
def __init__(self, sd: SamplingDistribution3D, **kwargs):
|
|
1361
|
+
self.sd = sd
|
|
1362
|
+
kwargs.setdefault("run_time", 2.0)
|
|
1363
|
+
kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
|
|
1364
|
+
super().__init__(sd.pop_panel, **kwargs)
|
|
1365
|
+
|
|
1366
|
+
def interpolate_mobject(self, alpha: float):
|
|
1367
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1368
|
+
scale = max(min(alpha / 0.65, 1.0), 1e-5)
|
|
1369
|
+
badge_a = np.clip((alpha - 0.55) / 0.45, 0, 1)
|
|
1370
|
+
self.mobject.scale(
|
|
1371
|
+
[1, scale, 1],
|
|
1372
|
+
about_point=[
|
|
1373
|
+
self.mobject.get_center()[0],
|
|
1374
|
+
self.sd._baseline, 0,
|
|
1375
|
+
],
|
|
1376
|
+
)
|
|
1377
|
+
# Fade in badges (last few submobjects)
|
|
1378
|
+
for sub in list(self.mobject.submobjects)[-5:]:
|
|
1379
|
+
sub.set_opacity(badge_a)
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
class DrawSample(Succession):
|
|
1383
|
+
"""
|
|
1384
|
+
Drop n observation dots onto the sample strip one by one.
|
|
1385
|
+
Each dot falls from the population curve level to the strip.
|
|
1386
|
+
|
|
1387
|
+
Parameters
|
|
1388
|
+
----------
|
|
1389
|
+
sd : SamplingDistribution3D
|
|
1390
|
+
sample : np.ndarray | None — if None, calls sd.draw_new_sample()
|
|
1391
|
+
dot_rt : float — time per dot drop
|
|
1392
|
+
stagger : float — delay between dots
|
|
1393
|
+
"""
|
|
1394
|
+
|
|
1395
|
+
def __init__(
|
|
1396
|
+
self,
|
|
1397
|
+
sd: SamplingDistribution3D,
|
|
1398
|
+
sample: Optional[np.ndarray] = None,
|
|
1399
|
+
dot_rt: float = 0.18,
|
|
1400
|
+
stagger: float = 0.04,
|
|
1401
|
+
**kwargs,
|
|
1402
|
+
):
|
|
1403
|
+
if sample is None:
|
|
1404
|
+
sample = sd.draw_new_sample()
|
|
1405
|
+
else:
|
|
1406
|
+
sd.current_sample = sample
|
|
1407
|
+
|
|
1408
|
+
if sd.sample_strip is None:
|
|
1409
|
+
super().__init__(FadeIn(VGroup(), run_time=0.01), **kwargs)
|
|
1410
|
+
return
|
|
1411
|
+
|
|
1412
|
+
# Clear previous dots
|
|
1413
|
+
sd.sample_strip.clear_dots()
|
|
1414
|
+
|
|
1415
|
+
anims = []
|
|
1416
|
+
for val in sample:
|
|
1417
|
+
# Clamp to strip range
|
|
1418
|
+
val = float(np.clip(val, sd._x_lo_pop, sd._x_hi_pop))
|
|
1419
|
+
dot = sd.sample_strip.add_dot(val)
|
|
1420
|
+
dot.set_opacity(0)
|
|
1421
|
+
anims.append(FadeIn(dot, shift=DOWN * 0.18, run_time=dot_rt))
|
|
1422
|
+
|
|
1423
|
+
kwargs.setdefault("run_time",
|
|
1424
|
+
len(anims) * (dot_rt + stagger))
|
|
1425
|
+
super().__init__(*anims, **kwargs)
|
|
1426
|
+
|
|
1427
|
+
|
|
1428
|
+
class ExtractMean(Animation):
|
|
1429
|
+
"""
|
|
1430
|
+
Bracket collapses from both ends to the mean.
|
|
1431
|
+
Mean dot brightens. Mean dot then rises toward the histogram.
|
|
1432
|
+
|
|
1433
|
+
Parameters
|
|
1434
|
+
----------
|
|
1435
|
+
sd : SamplingDistribution3D
|
|
1436
|
+
run_time : float
|
|
1437
|
+
"""
|
|
1438
|
+
|
|
1439
|
+
def __init__(self, sd: SamplingDistribution3D, **kwargs):
|
|
1440
|
+
self.sd = sd
|
|
1441
|
+
kwargs.setdefault("run_time", 0.90)
|
|
1442
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
|
|
1443
|
+
|
|
1444
|
+
# Ensure sample and mean dot exist
|
|
1445
|
+
if sd.current_sample is None:
|
|
1446
|
+
sd.draw_new_sample()
|
|
1447
|
+
mean_raw = float(np.mean(sd.current_sample))
|
|
1448
|
+
self._mean_raw = mean_raw
|
|
1449
|
+
|
|
1450
|
+
if sd.sample_strip is not None:
|
|
1451
|
+
self._mean_dot = sd.sample_strip.make_mean_dot(mean_raw)
|
|
1452
|
+
self._mean_dot.set_opacity(0)
|
|
1453
|
+
else:
|
|
1454
|
+
self._mean_dot = None
|
|
1455
|
+
|
|
1456
|
+
mob = sd.sample_strip if sd.sample_strip is not None else VGroup()
|
|
1457
|
+
super().__init__(mob, **kwargs)
|
|
1458
|
+
|
|
1459
|
+
def interpolate_mobject(self, alpha: float):
|
|
1460
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1461
|
+
# Fade in mean dot
|
|
1462
|
+
if self._mean_dot is not None:
|
|
1463
|
+
md_alpha = min(1.0, alpha * 2.5)
|
|
1464
|
+
# Re-find mean dot in submobjects (it was added during __init__)
|
|
1465
|
+
for sub in self.mobject.submobjects:
|
|
1466
|
+
if isinstance(sub, Dot) and sub.get_color() == PAL["dot_mean"]:
|
|
1467
|
+
sub.set_opacity(md_alpha)
|
|
1468
|
+
# Scale up slightly
|
|
1469
|
+
sub.scale(1.0 + 0.25 * np.sin(alpha * PI))
|
|
1470
|
+
break
|
|
1471
|
+
|
|
1472
|
+
# Shrink sample dots toward mean (collapse animation)
|
|
1473
|
+
collapse = min(1.0, alpha / 0.80)
|
|
1474
|
+
for sub in self.mobject.submobjects:
|
|
1475
|
+
if isinstance(sub, Dot) and sub.get_color() != PAL["dot_mean"]:
|
|
1476
|
+
if collapse > 0:
|
|
1477
|
+
sub.set_opacity(1.0 - collapse * 0.65)
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
class AddToHistogram(Animation):
|
|
1481
|
+
"""
|
|
1482
|
+
Mean dot flies from the strip to its histogram bin.
|
|
1483
|
+
The bar grows by 1 unit. The bin flashes.
|
|
1484
|
+
|
|
1485
|
+
Parameters
|
|
1486
|
+
----------
|
|
1487
|
+
sd : SamplingDistribution3D
|
|
1488
|
+
mean_val : float | None — if None uses sd.means[-1] or commits new
|
|
1489
|
+
run_time : float
|
|
1490
|
+
"""
|
|
1491
|
+
|
|
1492
|
+
def __init__(
|
|
1493
|
+
self,
|
|
1494
|
+
sd: SamplingDistribution3D,
|
|
1495
|
+
mean_val: Optional[float] = None,
|
|
1496
|
+
**kwargs,
|
|
1497
|
+
):
|
|
1498
|
+
self.sd = sd
|
|
1499
|
+
|
|
1500
|
+
if mean_val is None:
|
|
1501
|
+
mean_val = sd.commit_mean()
|
|
1502
|
+
self._mean_val = mean_val
|
|
1503
|
+
|
|
1504
|
+
# Determine target bin and bar top position
|
|
1505
|
+
bin_i = sd.hist_panel.add_count(mean_val)
|
|
1506
|
+
self._bin_i = bin_i
|
|
1507
|
+
self._target = sd.hist_panel.bin_top_position(bin_i)
|
|
1508
|
+
self._target = self._target + np.array([sd._hist_cx, 0, 0])
|
|
1509
|
+
|
|
1510
|
+
# Start position: above sample strip
|
|
1511
|
+
if sd.sample_strip is not None:
|
|
1512
|
+
sxp = sd.sample_strip.raw_to_px(
|
|
1513
|
+
float(np.clip(mean_val, sd._x_lo_pop, sd._x_hi_pop))
|
|
1514
|
+
)
|
|
1515
|
+
self._start = np.array([
|
|
1516
|
+
sxp + sd._strip_cx,
|
|
1517
|
+
sd._baseline - 1.0,
|
|
1518
|
+
0.015,
|
|
1519
|
+
])
|
|
1520
|
+
else:
|
|
1521
|
+
self._start = sd.hist_panel.bin_top_position(bin_i)
|
|
1522
|
+
|
|
1523
|
+
# Travelling dot
|
|
1524
|
+
self._trav_dot = Dot(
|
|
1525
|
+
radius=0.10,
|
|
1526
|
+
point=self._start,
|
|
1527
|
+
color=PAL["dot_mean"],
|
|
1528
|
+
fill_opacity=1.0,
|
|
1529
|
+
)
|
|
1530
|
+
sd.add(self._trav_dot)
|
|
1531
|
+
|
|
1532
|
+
kwargs.setdefault("run_time", 0.65)
|
|
1533
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
|
|
1534
|
+
super().__init__(self._trav_dot, **kwargs)
|
|
1535
|
+
|
|
1536
|
+
def interpolate_mobject(self, alpha: float):
|
|
1537
|
+
# Parabolic arc from start to target
|
|
1538
|
+
h_arc = abs(self._target[1] - self._start[1]) * 0.40
|
|
1539
|
+
pos = (self._start * (1 - alpha)
|
|
1540
|
+
+ self._target * alpha
|
|
1541
|
+
+ UP * h_arc * 4 * alpha * (1 - alpha))
|
|
1542
|
+
self.mobject.move_to(pos)
|
|
1543
|
+
# Fade out near destination
|
|
1544
|
+
self.mobject.set_opacity(1.0 - alpha * 0.6)
|
|
1545
|
+
|
|
1546
|
+
def clean_up_from_scene(self, scene) -> None:
|
|
1547
|
+
super().clean_up_from_scene(scene)
|
|
1548
|
+
if self._trav_dot in self.sd.submobjects:
|
|
1549
|
+
self.sd.remove(self._trav_dot)
|
|
1550
|
+
# Update theory curve and stats panel
|
|
1551
|
+
if self.sd.k_drawn >= 2:
|
|
1552
|
+
self.sd.hist_panel.set_theory_curve(
|
|
1553
|
+
self.sd._mu_pop,
|
|
1554
|
+
self.sd._se,
|
|
1555
|
+
self.sd.k_drawn,
|
|
1556
|
+
)
|
|
1557
|
+
self.sd.update_stats_panel()
|
|
1558
|
+
|
|
1559
|
+
|
|
1560
|
+
class RunCLT(Succession):
|
|
1561
|
+
"""
|
|
1562
|
+
One full CLT iteration:
|
|
1563
|
+
DrawSample → ExtractMean → AddToHistogram
|
|
1564
|
+
|
|
1565
|
+
Parameters
|
|
1566
|
+
----------
|
|
1567
|
+
sd : SamplingDistribution3D
|
|
1568
|
+
run_time : float — total time for the full iteration
|
|
1569
|
+
fast : bool — if True, skip dot animation (instant add)
|
|
1570
|
+
"""
|
|
1571
|
+
|
|
1572
|
+
def __init__(
|
|
1573
|
+
self,
|
|
1574
|
+
sd: SamplingDistribution3D,
|
|
1575
|
+
run_time: float = 1.5,
|
|
1576
|
+
fast: bool = False,
|
|
1577
|
+
**kwargs,
|
|
1578
|
+
):
|
|
1579
|
+
sample = sd.draw_new_sample()
|
|
1580
|
+
mean_val = float(np.mean(sample))
|
|
1581
|
+
|
|
1582
|
+
if fast:
|
|
1583
|
+
# Commit directly without animation
|
|
1584
|
+
sd.current_sample = sample
|
|
1585
|
+
sd.commit_mean()
|
|
1586
|
+
sd.hist_panel.set_theory_curve(
|
|
1587
|
+
sd._mu_pop, sd._se, sd.k_drawn)
|
|
1588
|
+
sd.update_stats_panel()
|
|
1589
|
+
anims = [FadeIn(VGroup(), run_time=0.01)]
|
|
1590
|
+
else:
|
|
1591
|
+
ds_rt = run_time * 0.38
|
|
1592
|
+
em_rt = run_time * 0.28
|
|
1593
|
+
ah_rt = run_time * 0.34
|
|
1594
|
+
anims = [
|
|
1595
|
+
DrawSample(sd, sample=sample,
|
|
1596
|
+
dot_rt=ds_rt / max(sd._n, 1),
|
|
1597
|
+
run_time=ds_rt),
|
|
1598
|
+
ExtractMean(sd, run_time=em_rt),
|
|
1599
|
+
AddToHistogram(sd, mean_val=mean_val,
|
|
1600
|
+
run_time=ah_rt),
|
|
1601
|
+
]
|
|
1602
|
+
|
|
1603
|
+
kwargs.setdefault("run_time", run_time)
|
|
1604
|
+
super().__init__(*anims, **kwargs)
|
|
1605
|
+
|
|
1606
|
+
|
|
1607
|
+
class FlashBin(AnimationGroup):
|
|
1608
|
+
"""
|
|
1609
|
+
Flash the histogram bar at bin index i.
|
|
1610
|
+
|
|
1611
|
+
Parameters
|
|
1612
|
+
----------
|
|
1613
|
+
sd : SamplingDistribution3D
|
|
1614
|
+
bin_i : int
|
|
1615
|
+
run_time : float
|
|
1616
|
+
"""
|
|
1617
|
+
|
|
1618
|
+
def __init__(
|
|
1619
|
+
self,
|
|
1620
|
+
sd: SamplingDistribution3D,
|
|
1621
|
+
bin_i: int,
|
|
1622
|
+
**kwargs,
|
|
1623
|
+
):
|
|
1624
|
+
bar = sd.hist_panel._bars[bin_i]
|
|
1625
|
+
col = PAL["bar_flash"]
|
|
1626
|
+
kwargs.setdefault("run_time", 0.40)
|
|
1627
|
+
super().__init__(
|
|
1628
|
+
Indicate(bar, color=col, scale_factor=1.06,
|
|
1629
|
+
run_time=kwargs["run_time"]),
|
|
1630
|
+
**kwargs,
|
|
1631
|
+
)
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
class NarrowSE(Animation):
|
|
1635
|
+
"""
|
|
1636
|
+
Increase n → SE shrinks → histogram bars narrow → SE arrow shrinks.
|
|
1637
|
+
|
|
1638
|
+
Morphs the entire visualisation into a rebuilt one.
|
|
1639
|
+
|
|
1640
|
+
Parameters
|
|
1641
|
+
----------
|
|
1642
|
+
sd : SamplingDistribution3D
|
|
1643
|
+
new_n : int
|
|
1644
|
+
run_time: float
|
|
1645
|
+
"""
|
|
1646
|
+
|
|
1647
|
+
def __init__(
|
|
1648
|
+
self,
|
|
1649
|
+
sd: SamplingDistribution3D,
|
|
1650
|
+
new_n: int,
|
|
1651
|
+
**kwargs,
|
|
1652
|
+
):
|
|
1653
|
+
self.sd = sd
|
|
1654
|
+
self.new_n = new_n
|
|
1655
|
+
# Build a fresh SD with the new n (no samples yet)
|
|
1656
|
+
self.target = type(sd)(
|
|
1657
|
+
pop_type=sd._pop_type,
|
|
1658
|
+
params=sd._params,
|
|
1659
|
+
n=new_n,
|
|
1660
|
+
n_bins=sd._n_bins,
|
|
1661
|
+
pop_panel_w=sd.pop_panel._panel_w,
|
|
1662
|
+
hist_panel_w=sd._hist_panel_w,
|
|
1663
|
+
panel_h=sd._panel_h,
|
|
1664
|
+
baseline_y=sd._baseline,
|
|
1665
|
+
max_samples=sd._max_samples,
|
|
1666
|
+
show_strip=sd.sample_strip is not None,
|
|
1667
|
+
show_se=sd.se_arrow is not None,
|
|
1668
|
+
show_panel=sd.stats_panel is not None,
|
|
1669
|
+
)
|
|
1670
|
+
self.target.move_to(sd.get_center())
|
|
1671
|
+
kwargs.setdefault("run_time", 2.5)
|
|
1672
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
|
|
1673
|
+
super().__init__(sd, **kwargs)
|
|
1674
|
+
|
|
1675
|
+
def interpolate_mobject(self, alpha: float):
|
|
1676
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1677
|
+
self.mobject.set_opacity(1 - alpha)
|
|
1678
|
+
self.target.set_opacity(alpha)
|
|
1679
|
+
if alpha >= 1.0:
|
|
1680
|
+
self.mobject.become(self.target)
|
|
1681
|
+
self.sd._n = self.new_n
|
|
1682
|
+
self.sd._se = self.sd._sigma_pop / np.sqrt(self.new_n)
|
|
1683
|
+
self.sd.n_tracker.set_value(float(self.new_n))
|
|
1684
|
+
|
|
1685
|
+
|
|
1686
|
+
class ConvergenceRace(Succession):
|
|
1687
|
+
"""
|
|
1688
|
+
Rapidly animate k_total CLT iterations in fast mode,
|
|
1689
|
+
then fade in the final theoretical curve prominently.
|
|
1690
|
+
|
|
1691
|
+
Parameters
|
|
1692
|
+
----------
|
|
1693
|
+
sd : SamplingDistribution3D
|
|
1694
|
+
k_total : int — total samples to draw
|
|
1695
|
+
burst_rt : float — time per fast iteration
|
|
1696
|
+
"""
|
|
1697
|
+
|
|
1698
|
+
def __init__(
|
|
1699
|
+
self,
|
|
1700
|
+
sd: SamplingDistribution3D,
|
|
1701
|
+
k_total: int = 100,
|
|
1702
|
+
burst_rt: float = 0.04,
|
|
1703
|
+
**kwargs,
|
|
1704
|
+
):
|
|
1705
|
+
# Burst phase: draw all samples in fast mode
|
|
1706
|
+
burst_anims = []
|
|
1707
|
+
for _ in range(k_total):
|
|
1708
|
+
burst_anims.append(
|
|
1709
|
+
RunCLT(sd, run_time=burst_rt, fast=True)
|
|
1710
|
+
)
|
|
1711
|
+
|
|
1712
|
+
# Final theory curve reveal
|
|
1713
|
+
def _reveal_theory(sd=sd):
|
|
1714
|
+
sd.hist_panel.set_theory_curve(
|
|
1715
|
+
sd._mu_pop, sd._se, sd.k_drawn)
|
|
1716
|
+
return FadeIn(
|
|
1717
|
+
sd.hist_panel._theory_curve or VGroup(),
|
|
1718
|
+
run_time=1.0,
|
|
1719
|
+
)
|
|
1720
|
+
|
|
1721
|
+
anims = burst_anims + [_reveal_theory()]
|
|
1722
|
+
kwargs.setdefault("run_time",
|
|
1723
|
+
k_total * burst_rt + 1.0)
|
|
1724
|
+
super().__init__(*anims, **kwargs)
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1728
|
+
# Convenience factories
|
|
1729
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1730
|
+
|
|
1731
|
+
def make_clt_comparison(
|
|
1732
|
+
pop_specs: list[tuple[str, dict]],
|
|
1733
|
+
n: int = 10,
|
|
1734
|
+
n_bins: int = 16,
|
|
1735
|
+
k_samples: int = 60,
|
|
1736
|
+
panel_scale: float = 0.52,
|
|
1737
|
+
seed: int = 42,
|
|
1738
|
+
) -> VGroup:
|
|
1739
|
+
"""
|
|
1740
|
+
Create a row of SamplingDistribution3D objects, one per population,
|
|
1741
|
+
with k_samples already drawn — for a side-by-side CLT comparison.
|
|
1742
|
+
|
|
1743
|
+
Parameters
|
|
1744
|
+
----------
|
|
1745
|
+
pop_specs : list of (pop_type, params) tuples
|
|
1746
|
+
n : sample size
|
|
1747
|
+
n_bins : histogram bins per panel
|
|
1748
|
+
k_samples : samples to pre-draw (fast mode)
|
|
1749
|
+
panel_scale : scale factor per panel
|
|
1750
|
+
seed : RNG seed
|
|
1751
|
+
|
|
1752
|
+
Returns
|
|
1753
|
+
-------
|
|
1754
|
+
VGroup of SamplingDistribution3D objects.
|
|
1755
|
+
"""
|
|
1756
|
+
grp = VGroup()
|
|
1757
|
+
pw = 3.0 # pop panel width per item
|
|
1758
|
+
hw = 3.5 # hist panel width per item
|
|
1759
|
+
gap = 0.3
|
|
1760
|
+
step = (pw + hw + gap * 3) * panel_scale
|
|
1761
|
+
|
|
1762
|
+
for i, (pt, pm) in enumerate(pop_specs):
|
|
1763
|
+
sd = SamplingDistribution3D(
|
|
1764
|
+
pop_type=pt, params=pm, n=n,
|
|
1765
|
+
n_bins=n_bins,
|
|
1766
|
+
pop_panel_w=pw, hist_panel_w=hw,
|
|
1767
|
+
max_samples=k_samples + 10,
|
|
1768
|
+
show_strip=False,
|
|
1769
|
+
show_se=True,
|
|
1770
|
+
show_panel=False,
|
|
1771
|
+
seed=seed + i,
|
|
1772
|
+
)
|
|
1773
|
+
# Fast-draw k_samples
|
|
1774
|
+
for _ in range(k_samples):
|
|
1775
|
+
sd.draw_new_sample()
|
|
1776
|
+
sd.commit_mean()
|
|
1777
|
+
sd.hist_panel.add_count(sd.means[-1])
|
|
1778
|
+
sd.hist_panel.set_theory_curve(
|
|
1779
|
+
sd._mu_pop, sd._se, sd.k_drawn)
|
|
1780
|
+
|
|
1781
|
+
sd.scale(panel_scale)
|
|
1782
|
+
sd.move_to([i * step, 0, 0])
|
|
1783
|
+
grp.add(sd)
|
|
1784
|
+
|
|
1785
|
+
grp.center()
|
|
1786
|
+
return grp
|
|
1787
|
+
|
|
1788
|
+
|
|
1789
|
+
def make_n_effect_row(
|
|
1790
|
+
pop_type: str = "exponential",
|
|
1791
|
+
params: dict = None,
|
|
1792
|
+
n_values: list[int] = None,
|
|
1793
|
+
k_samples: int = 80,
|
|
1794
|
+
panel_scale: float = 0.55,
|
|
1795
|
+
seed: int = 0,
|
|
1796
|
+
) -> VGroup:
|
|
1797
|
+
"""
|
|
1798
|
+
Create a row of SamplingDistribution3D objects varying n,
|
|
1799
|
+
showing how increasing n narrows the sampling distribution.
|
|
1800
|
+
|
|
1801
|
+
Parameters
|
|
1802
|
+
----------
|
|
1803
|
+
pop_type, params : source population
|
|
1804
|
+
n_values : list of sample sizes (default [1, 5, 25, 100])
|
|
1805
|
+
k_samples : samples to pre-draw per panel
|
|
1806
|
+
panel_scale, seed
|
|
1807
|
+
|
|
1808
|
+
Returns
|
|
1809
|
+
-------
|
|
1810
|
+
VGroup of SamplingDistribution3D objects with n labels.
|
|
1811
|
+
"""
|
|
1812
|
+
if params is None:
|
|
1813
|
+
params = {"lam": 1.0}
|
|
1814
|
+
if n_values is None:
|
|
1815
|
+
n_values = [1, 5, 25, 100]
|
|
1816
|
+
|
|
1817
|
+
grp = VGroup()
|
|
1818
|
+
pw, hw = 2.8, 3.2
|
|
1819
|
+
step = (pw + hw + 0.5) * panel_scale
|
|
1820
|
+
|
|
1821
|
+
for i, n in enumerate(n_values):
|
|
1822
|
+
sd = SamplingDistribution3D(
|
|
1823
|
+
pop_type=pop_type, params=params, n=n,
|
|
1824
|
+
n_bins=16,
|
|
1825
|
+
pop_panel_w=pw, hist_panel_w=hw,
|
|
1826
|
+
max_samples=k_samples + 10,
|
|
1827
|
+
show_strip=False, show_se=True, show_panel=False,
|
|
1828
|
+
seed=seed + i * 13,
|
|
1829
|
+
)
|
|
1830
|
+
for _ in range(k_samples):
|
|
1831
|
+
sd.draw_new_sample()
|
|
1832
|
+
sd.commit_mean()
|
|
1833
|
+
sd.hist_panel.add_count(sd.means[-1])
|
|
1834
|
+
sd.hist_panel.set_theory_curve(sd._mu_pop, sd._se, k_samples)
|
|
1835
|
+
|
|
1836
|
+
sd.scale(panel_scale)
|
|
1837
|
+
sd.move_to([i * step, 0, 0])
|
|
1838
|
+
|
|
1839
|
+
# n label below
|
|
1840
|
+
nlbl = Text(f"n = {n}", font_size=18,
|
|
1841
|
+
color=PAL["clt_label"])
|
|
1842
|
+
nlbl.next_to(sd, DOWN, buff=0.12)
|
|
1843
|
+
grp.add(sd, nlbl)
|
|
1844
|
+
|
|
1845
|
+
grp.center()
|
|
1846
|
+
return grp
|
|
1847
|
+
|
|
1848
|
+
|
|
1849
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1850
|
+
# Demo Scene (run with: manim -pql sampling_dist.py SamplingDistDemo)
|
|
1851
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1852
|
+
|
|
1853
|
+
try:
|
|
1854
|
+
from manim import Scene
|
|
1855
|
+
|
|
1856
|
+
class SamplingDistDemo(Scene):
|
|
1857
|
+
"""Full CLT demonstration showcase."""
|
|
1858
|
+
|
|
1859
|
+
def construct(self):
|
|
1860
|
+
|
|
1861
|
+
# ── Exponential population, n=5 ──────────────────────────
|
|
1862
|
+
sd = SamplingDistribution3D.exponential(
|
|
1863
|
+
lam=1.0, n=5,
|
|
1864
|
+
n_bins=18,
|
|
1865
|
+
pop_panel_w=3.8,
|
|
1866
|
+
hist_panel_w=4.8,
|
|
1867
|
+
panel_h=2.8,
|
|
1868
|
+
baseline_y=0.5,
|
|
1869
|
+
max_samples=80,
|
|
1870
|
+
show_strip=True,
|
|
1871
|
+
show_se=True,
|
|
1872
|
+
show_panel=True,
|
|
1873
|
+
)
|
|
1874
|
+
sd.center()
|
|
1875
|
+
self.add(sd)
|
|
1876
|
+
|
|
1877
|
+
# Build the population curve
|
|
1878
|
+
self.play(BuildPopulation(sd, run_time=1.8))
|
|
1879
|
+
self.play(FadeIn(sd.clt_arrow, run_time=0.5))
|
|
1880
|
+
self.wait(0.3)
|
|
1881
|
+
|
|
1882
|
+
# Run 8 full iterations with animation
|
|
1883
|
+
for _ in range(8):
|
|
1884
|
+
self.play(RunCLT(sd, run_time=1.2))
|
|
1885
|
+
self.wait(0.5)
|
|
1886
|
+
|
|
1887
|
+
# Flash the most-filled bin
|
|
1888
|
+
top_bin = int(np.argmax(sd.hist_panel._counts))
|
|
1889
|
+
self.play(FlashBin(sd, top_bin, run_time=0.5))
|
|
1890
|
+
self.wait(0.4)
|
|
1891
|
+
|
|
1892
|
+
# Convergence race: 40 more fast samples
|
|
1893
|
+
self.play(ConvergenceRace(sd, k_total=40,
|
|
1894
|
+
burst_rt=0.03))
|
|
1895
|
+
self.wait(0.6)
|
|
1896
|
+
|
|
1897
|
+
# Increase n → SE narrows
|
|
1898
|
+
self.play(NarrowSE(sd, new_n=25, run_time=2.5))
|
|
1899
|
+
self.wait(0.8)
|
|
1900
|
+
|
|
1901
|
+
self.play(FadeOut(sd))
|
|
1902
|
+
|
|
1903
|
+
# ── n-effect comparison row ───────────────────────────────
|
|
1904
|
+
row = make_n_effect_row(
|
|
1905
|
+
pop_type="exponential",
|
|
1906
|
+
params={"lam": 1.0},
|
|
1907
|
+
n_values=[1, 5, 30, 100],
|
|
1908
|
+
k_samples=100,
|
|
1909
|
+
panel_scale=0.48,
|
|
1910
|
+
)
|
|
1911
|
+
row.center()
|
|
1912
|
+
self.play(FadeIn(row, shift=UP*0.3), run_time=1.0)
|
|
1913
|
+
self.wait(2.5)
|
|
1914
|
+
|
|
1915
|
+
self.play(FadeOut(row))
|
|
1916
|
+
|
|
1917
|
+
# ── CLT comparison across population shapes ───────────────
|
|
1918
|
+
comparison = make_clt_comparison(
|
|
1919
|
+
pop_specs=[
|
|
1920
|
+
("uniform", {"a": 0.0, "b": 1.0}),
|
|
1921
|
+
("exponential", {"lam": 1.0}),
|
|
1922
|
+
("bimodal", {"mu1": -2.0, "mu2": 2.0,
|
|
1923
|
+
"sigma": 0.7, "mix": 0.5}),
|
|
1924
|
+
],
|
|
1925
|
+
n=20, k_samples=80,
|
|
1926
|
+
panel_scale=0.48,
|
|
1927
|
+
)
|
|
1928
|
+
comparison.center()
|
|
1929
|
+
self.play(FadeIn(comparison, shift=UP*0.2), run_time=1.0)
|
|
1930
|
+
self.wait(3.0)
|
|
1931
|
+
|
|
1932
|
+
except ImportError:
|
|
1933
|
+
pass
|