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.
Files changed (66) hide show
  1. statanim/__init__.py +0 -0
  2. statanim/animations/__init__.py +0 -0
  3. statanim/animations/clt_demo.py +1852 -0
  4. statanim/animations/flip_roll.py +1851 -0
  5. statanim/animations/sampling.py +2291 -0
  6. statanim/animations/transitions.py +1857 -0
  7. statanim/axes/__init__.py +0 -0
  8. statanim/axes/axes3d.py +1989 -0
  9. statanim/axes/grid3d.py +1127 -0
  10. statanim/axes/number_plane3d.py +1526 -0
  11. statanim/charts/__init__.py +0 -0
  12. statanim/charts/bar_chart3d.py +1572 -0
  13. statanim/charts/box_plot3d.py +1977 -0
  14. statanim/charts/heat_map3d.py +1639 -0
  15. statanim/charts/histogram3d.py +1019 -0
  16. statanim/charts/line_plot3d.py +1891 -0
  17. statanim/charts/scatter_plot3d.py +1469 -0
  18. statanim/charts/violin_plot3d.py +1567 -0
  19. statanim/core/__init__.py +0 -0
  20. statanim/core/base.py +1585 -0
  21. statanim/core/colors.py +1373 -0
  22. statanim/core/math_utils.py +2081 -0
  23. statanim/core/tex_utils.py +2111 -0
  24. statanim/distributions/__init__.py +0 -0
  25. statanim/distributions/base_dist.py +1936 -0
  26. statanim/distributions/cdf_viz.py +1773 -0
  27. statanim/distributions/continuous_dists.py +1769 -0
  28. statanim/distributions/discrete_dists.py +1734 -0
  29. statanim/distributions/normal3d.py +1877 -0
  30. statanim/distributions/pdf_viz.py +2247 -0
  31. statanim/distributions/pmf_viz.py +1936 -0
  32. statanim/inference/__init__.py +0 -0
  33. statanim/inference/confidence_interval.py +1693 -0
  34. statanim/inference/error_types.py +1825 -0
  35. statanim/inference/hypothesis.py +1821 -0
  36. statanim/inference/sampling_dist.py +1933 -0
  37. statanim/probability/__init__.py +0 -0
  38. statanim/probability/bayes.py +1682 -0
  39. statanim/probability/prob_tree.py +1478 -0
  40. statanim/probability/sample_space.py +1642 -0
  41. statanim/probability/venn3d.py +1857 -0
  42. statanim/props/__init__.py +0 -0
  43. statanim/props/card.py +2259 -0
  44. statanim/props/coin.py +1011 -0
  45. statanim/props/die.py +1391 -0
  46. statanim/props/spinner.py +1591 -0
  47. statanim/props/urn.py +1531 -0
  48. statanim/regression/__init__.py +0 -0
  49. statanim/regression/correlation.py +2805 -0
  50. statanim/regression/regression_plane.py +2286 -0
  51. statanim/regression/residuals.py +2599 -0
  52. statanim/scenes/__init__.py +0 -0
  53. statanim/scenes/demo_bayes.py +2056 -0
  54. statanim/scenes/demo_clt.py +1756 -0
  55. statanim/scenes/demo_distributions.py +1905 -0
  56. statanim/scenes/demo_hypothesis.py +1791 -0
  57. statanim/ui/__init__.py +0 -0
  58. statanim/ui/labels.py +1844 -0
  59. statanim/ui/panels.py +1937 -0
  60. statanim/ui/table3d.py +1745 -0
  61. statanim/ui/ticker.py +2007 -0
  62. statanim-0.1.0.dist-info/METADATA +463 -0
  63. statanim-0.1.0.dist-info/RECORD +66 -0
  64. statanim-0.1.0.dist-info/WHEEL +5 -0
  65. statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
  66. statanim-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1756 @@
1
+ """
2
+ statanim/scenes/demo_clt.py
3
+ ================================
4
+ CLTDemo — A complete, cinematic Central Limit Theorem demonstration scene.
5
+
6
+ Story arc (8 acts)
7
+ ------------------
8
+ Act 0 Title card + hook
9
+ "No matter the shape of the population…"
10
+ Three wildly different population curves pulse onto screen.
11
+ "…the sample mean always converges to normal."
12
+
13
+ Act 1 Population zoo
14
+ Three panels: Uniform, Exponential, Bimodal.
15
+ Each curve animates in with its μ, σ badges.
16
+ Population dots scatter on a number line below each curve.
17
+
18
+ Act 2 What is a sample mean?
19
+ Focus on the Exponential panel.
20
+ n=5 dots are drawn one by one from the distribution.
21
+ A bracket collapses to the mean. Mean dot labelled x̄.
22
+ Formula: x̄ = (x₁ + x₂ + … + xₙ) / n
23
+
24
+ Act 3 Build one histogram — slow
25
+ 10 full DrawSample→ExtractMean→AddToHistogram cycles.
26
+ Each bar flash highlighted.
27
+ Live k-counter badge updates.
28
+
29
+ Act 4 Convergence speed-up
30
+ "Let's draw 100 samples..."
31
+ Fast burst: bars blur upward.
32
+ At k=50: theoretical curve appears dashed.
33
+ At k=100: curve becomes solid, histogram clearly matches.
34
+ Overlay reveal animation.
35
+
36
+ Act 5 The n effect
37
+ Side-by-side: n=1, n=5, n=30, n=100.
38
+ Each panel pre-loaded with 80 samples.
39
+ All four histograms shown simultaneously.
40
+ SE arrow shrinks from left to right.
41
+ "SE = σ/√n" formula with live substitution.
42
+
43
+ Act 6 Population independence
44
+ Three simultaneous panels (Uniform, Exponential, Bimodal).
45
+ All run 80 fast samples in parallel.
46
+ All three histograms converge to normal.
47
+ "The shape of the population doesn't matter."
48
+
49
+ Act 7 Normal Q-Q plot
50
+ After the Exponential histogram converges,
51
+ a Q-Q plot appears beside it.
52
+ Theoretical normal line vs empirical quantiles.
53
+ Points hug the line — visual proof of normality.
54
+
55
+ Act 8 CLT formal statement + closing
56
+ Full formal statement animates in term by term.
57
+ "√n (X̄ − μ) / σ → N(0,1) as n → ∞"
58
+ Each symbol colour-coded.
59
+ Closing title card.
60
+
61
+ Scene uses
62
+ ----------
63
+ statanim.inference.sampling_dist — SamplingDistribution3D,
64
+ BuildPopulation, RunCLT, NarrowSE, ConvergenceRace,
65
+ make_n_effect_row, make_clt_comparison
66
+
67
+ Dependencies
68
+ ------------
69
+ manim (CE or GL), numpy, scipy (optional)
70
+ """
71
+
72
+ from __future__ import annotations
73
+
74
+ import numpy as np
75
+ from typing import Optional, List
76
+
77
+ from manim import (
78
+ Scene,
79
+ VGroup, Group,
80
+ Rectangle, RoundedRectangle, Square,
81
+ Circle, Annulus, Dot, Polygon, Line, DashedLine, Arc,
82
+ Arrow, DoubleArrow,
83
+ Text, MathTex,
84
+ Animation, Succession, AnimationGroup,
85
+ ApplyMethod, FadeIn, FadeOut, GrowFromCenter,
86
+ Create, Write, Uncreate,
87
+ Indicate, Flash,
88
+ Rotate,
89
+ Transform, ReplacementTransform,
90
+ ValueTracker,
91
+ interpolate_color, color_to_rgb,
92
+ always_redraw,
93
+ BLACK, WHITE,
94
+ GREY, GREY_A, GREY_B, GREY_C, GREY_D,
95
+ RED, RED_A, RED_B, RED_C, RED_D,
96
+ GREEN, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
97
+ BLUE, BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E,
98
+ YELLOW, YELLOW_A, YELLOW_E,
99
+ ORANGE, TEAL, TEAL_A, TEAL_B, TEAL_C,
100
+ GOLD, GOLD_A, GOLD_B, GOLD_C, GOLD_D,
101
+ PURPLE_A, PURPLE_B, MAROON, PINK,
102
+ UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
103
+ PI, TAU,
104
+ rate_functions,
105
+ ManimColor,
106
+ VMobject,
107
+ )
108
+
109
+ # ─────────────────────────────────────────────────────────────────────────────
110
+ # Import sampling_dist components (graceful fallback)
111
+ # ─────────────────────────────────────────────────────────────────────────────
112
+ try:
113
+ import sys, os
114
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
115
+ from inference.sampling_dist import (
116
+ SamplingDistribution3D,
117
+ BuildPopulation,
118
+ RunCLT,
119
+ NarrowSE,
120
+ ConvergenceRace,
121
+ FlashBin,
122
+ make_n_effect_row,
123
+ make_clt_comparison,
124
+ _PopulationPanel,
125
+ _HistogramPanel,
126
+ _SampleStrip,
127
+ _pop_pdf,
128
+ _pop_stats,
129
+ _pop_x_range,
130
+ _map_x,
131
+ _curve_verts,
132
+ _sample_pop,
133
+ PAL as SPAL,
134
+ )
135
+ _SD_AVAILABLE = True
136
+ except ImportError:
137
+ _SD_AVAILABLE = False
138
+ SPAL = {}
139
+
140
+
141
+ # ─────────────────────────────────────────────────────────────────────────────
142
+ # Scene palette
143
+ # ─────────────────────────────────────────────────────────────────────────────
144
+
145
+ P = {
146
+ # Population colours (one per distribution)
147
+ "uniform_fill": "#1A3A5C",
148
+ "uniform_ridge": "#70B4EE",
149
+ "exp_fill": "#2A1A5C",
150
+ "exp_ridge": "#B070EE",
151
+ "bimodal_fill": "#1A3A20",
152
+ "bimodal_ridge": "#70EE90",
153
+
154
+ # Sample dots
155
+ "dot": "#F0C040",
156
+ "dot_mean": "#FF6040",
157
+ "mean_beam": "#FF9060",
158
+
159
+ # Histogram
160
+ "bar": "#3A7AC8",
161
+ "bar_lite": "#60A0F0",
162
+ "bar_side": "#1A3A68",
163
+ "bar_flash": "#FFD060",
164
+
165
+ # Theory curve
166
+ "theory": "#F0C040",
167
+ "theory_dash": "#806010",
168
+
169
+ # SE arrow
170
+ "se": "#D4AF37",
171
+ "se_label": "#F8E090",
172
+
173
+ # Formula terms
174
+ "f_xbar": "#70C8FF",
175
+ "f_mu": "#FFD060",
176
+ "f_sigma": "#FF9060",
177
+ "f_n": "#90FF90",
178
+ "f_norm": "#E080FF",
179
+ "f_eq": "#C8D8E8",
180
+
181
+ # QQ plot
182
+ "qq_dot": "#60C0FF",
183
+ "qq_line": "#FFD060",
184
+ "qq_axis": "#506070",
185
+
186
+ # Title / UI
187
+ "title": "#D8F0FF",
188
+ "subtitle": "#8090A8",
189
+ "badge_bg": "#0C1018",
190
+ "badge_border": "#2A3848",
191
+ "section": "#607080",
192
+ "bg": "#080C12",
193
+ "bg_panel": "#0C1018",
194
+ "panel_border": "#2A3848",
195
+ }
196
+
197
+
198
+ # ─────────────────────────────────────────────────────────────────────────────
199
+ # Shared scene helpers
200
+ # ─────────────────────────────────────────────────────────────────────────────
201
+
202
+ def _title_card(main: str, sub: str = "",
203
+ main_fs: int = 44, sub_fs: int = 22) -> VGroup:
204
+ g = VGroup()
205
+ bg = Rectangle(width=16, height=9,
206
+ fill_color=P["bg"],
207
+ fill_opacity=1.0, stroke_width=0)
208
+ g.add(bg)
209
+ ml = Text(main, font_size=main_fs, color=P["title"])
210
+ ml.move_to([0, 0.35 if sub else 0, 0])
211
+ g.add(ml)
212
+ if sub:
213
+ sl = Text(sub, font_size=sub_fs, color=P["subtitle"])
214
+ sl.move_to([0, -0.50, 0])
215
+ g.add(sl)
216
+ return g
217
+
218
+
219
+ def _section_label(text: str) -> Text:
220
+ return Text(text, font_size=16, color=P["section"])
221
+
222
+
223
+ def _badge(text: str, color: str = None) -> VGroup:
224
+ """Small floating info badge."""
225
+ g = VGroup()
226
+ col = color or P["subtitle"]
227
+ lbl = Text(text, font_size=15, color=col)
228
+ bg = RoundedRectangle(
229
+ width=lbl.width + 0.22,
230
+ height=lbl.height + 0.14,
231
+ corner_radius=0.06,
232
+ fill_color=P["badge_bg"],
233
+ fill_opacity=0.90,
234
+ stroke_color=col,
235
+ stroke_width=0.7,
236
+ )
237
+ bg.move_to(ORIGIN)
238
+ lbl.move_to([0, 0, 0.001])
239
+ g.add(bg, lbl)
240
+ return g
241
+
242
+
243
+ def _norm_pdf_scene(x: np.ndarray, mu: float, sigma: float) -> np.ndarray:
244
+ return np.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * np.sqrt(2 * PI))
245
+
246
+
247
+ # ─────────────────────────────────────────────────────────────────────────────
248
+ # Mini population curve (self-contained, no sampling_dist dependency)
249
+ # ─────────────────────────────────────────────────────────────────────────────
250
+
251
+ class _MiniPopCurve(VGroup):
252
+ """
253
+ Compact population curve panel with:
254
+ - Base fill polygon (3 layers)
255
+ - Ridge spine
256
+ - μ and σ badges
257
+ - Title label
258
+ - Optional dot strip below
259
+
260
+ Completely self-contained — does not require sampling_dist.
261
+ """
262
+
263
+ def __init__(
264
+ self,
265
+ pop_type: str,
266
+ params: dict,
267
+ title: str,
268
+ fill_color: str,
269
+ ridge_color: str,
270
+ width: float = 3.5,
271
+ height: float = 2.2,
272
+ baseline_y: float = 0.0,
273
+ show_dots: bool = True,
274
+ n_dots: int = 60,
275
+ seed: int = 0,
276
+ **kwargs,
277
+ ):
278
+ super().__init__(**kwargs)
279
+ self._pop_type = pop_type
280
+ self._params = params
281
+ self._width = width
282
+ self._height = height
283
+ self._baseline = baseline_y
284
+
285
+ x_lo, x_hi = self._x_range(pop_type, params)
286
+ raw_x = np.linspace(x_lo, x_hi, 400)
287
+ y_raw = self._pdf(pop_type, params, raw_x)
288
+ y_raw = np.where(np.isfinite(y_raw), y_raw, 0.0)
289
+ peak = float(y_raw.max()) if y_raw.max() > 1e-9 else 1.0
290
+ y_scaled = y_raw / peak * height
291
+ x_px = (raw_x - x_lo) / (x_hi - x_lo) * width - width / 2
292
+
293
+ ao_col = interpolate_color(fill_color, BLACK, 0.55)
294
+
295
+ # ── 1. AO under-layer ─────────────────────────────────────────
296
+ verts_ao = self._verts(x_px, y_scaled * 0.95, baseline_y)
297
+ if len(verts_ao) >= 3:
298
+ self.add(Polygon(*verts_ao,
299
+ fill_color=ao_col,
300
+ fill_opacity=0.55, stroke_width=0).shift([0.04,-0.04,0]))
301
+
302
+ # ── 2. Base fill ──────────────────────────────────────────────
303
+ verts = self._verts(x_px, y_scaled, baseline_y)
304
+ if len(verts) >= 3:
305
+ self.add(Polygon(*verts,
306
+ fill_color=fill_color,
307
+ fill_opacity=0.82, stroke_width=0))
308
+
309
+ # ── 3. Inner lite band ────────────────────────────────────────
310
+ lite_col = interpolate_color(fill_color, WHITE, 0.22)
311
+ verts_l = self._verts(x_px, y_scaled * 0.45, baseline_y)
312
+ if len(verts_l) >= 3:
313
+ self.add(Polygon(*verts_l,
314
+ fill_color=lite_col,
315
+ fill_opacity=0.28, stroke_width=0,
316
+ ).shift([0, 0, 0.001]))
317
+
318
+ # ── 4. Ridge spine ────────────────────────────────────────────
319
+ step = max(1, len(x_px) // 80)
320
+ pts3d = [np.array([float(x_px[i]), float(y_scaled[i]), 0.004])
321
+ for i in range(0, len(x_px), step) if y_scaled[i] > 0.01]
322
+ if len(pts3d) >= 2:
323
+ spine = VMobject(stroke_color=ridge_color,
324
+ stroke_width=1.8, stroke_opacity=0.85)
325
+ spine.set_points_smoothly(pts3d)
326
+ self.add(spine)
327
+
328
+ # ── 5. Axis ───────────────────────────────────────────────────
329
+ self.add(Line(
330
+ [-width/2, baseline_y, 0.001],
331
+ [ width/2, baseline_y, 0.001],
332
+ stroke_color=P["qq_axis"], stroke_width=1.3,
333
+ ))
334
+
335
+ # ── 6. Population dots below axis ─────────────────────────────
336
+ if show_dots:
337
+ rng = np.random.default_rng(seed)
338
+ sample = _sample_pop(pop_type, params, n_dots, rng) if _SD_AVAILABLE else (
339
+ rng.uniform(x_lo, x_hi, n_dots)
340
+ )
341
+ for val in sample:
342
+ val = float(np.clip(val, x_lo, x_hi))
343
+ xdot = (val - x_lo) / (x_hi - x_lo) * width - width / 2
344
+ ydot = baseline_y - np.random.uniform(0.06, 0.20)
345
+ d = Dot(radius=0.035,
346
+ point=[xdot, ydot, 0.002],
347
+ color=P["dot"],
348
+ fill_opacity=0.60)
349
+ self.add(d)
350
+
351
+ # ── 7. Title + stat badges ────────────────────────────────────
352
+ self.add(Text(title, font_size=17, color=ridge_color)
353
+ .move_to([0, baseline_y + height + 0.35, 0.003]))
354
+
355
+ mu, sigma = self._stats(pop_type, params)
356
+ stat_str = f"μ={mu:.2f} σ={sigma:.2f}"
357
+ self.add(Text(stat_str, font_size=13, color=P["subtitle"])
358
+ .move_to([0, baseline_y + height + 0.08, 0.003]))
359
+
360
+ self._mu = mu
361
+ self._sigma = sigma
362
+ self._x_lo = x_lo
363
+ self._x_hi = x_hi
364
+
365
+ # ──── static helpers ─────────────────────────────────────────────
366
+
367
+ @staticmethod
368
+ def _verts(x_px, y_scaled, baseline):
369
+ return (
370
+ [[float(x_px[0]), baseline, 0]]
371
+ + [[float(x), float(y), 0]
372
+ for x, y in zip(x_px, y_scaled)]
373
+ + [[float(x_px[-1]), baseline, 0]]
374
+ )
375
+
376
+ @staticmethod
377
+ def _pdf(pop_type, params, x):
378
+ if _SD_AVAILABLE:
379
+ return _pop_pdf(pop_type, params, x)
380
+ # fallback: normal
381
+ mu = params.get("mu", 0.0)
382
+ sig = params.get("sigma", 1.0)
383
+ return _norm_pdf_scene(x, mu, sig)
384
+
385
+ @staticmethod
386
+ def _stats(pop_type, params):
387
+ if _SD_AVAILABLE:
388
+ return _pop_stats(pop_type, params)
389
+ return params.get("mu", 0.0), params.get("sigma", 1.0)
390
+
391
+ @staticmethod
392
+ def _x_range(pop_type, params):
393
+ if _SD_AVAILABLE:
394
+ return _pop_x_range(pop_type, params)
395
+ mu = params.get("mu", 0.0)
396
+ sig = params.get("sigma", 1.0)
397
+ return mu - 4*sig, mu + 4*sig
398
+
399
+
400
+ # ─────────────────────────────────────────────────────────────────────────────
401
+ # Mini histogram (self-contained 3-D style bars)
402
+ # ─────────────────────────────────────────────────────────────────────────────
403
+
404
+ class _MiniHistogram(VGroup):
405
+ """
406
+ Compact 3-D histogram from a list of sample means.
407
+
408
+ Bars have: front face, right side face, top cap, base AO shadow.
409
+ Includes the theoretical N(μ, σ²/n) overlay curve.
410
+ """
411
+
412
+ def __init__(
413
+ self,
414
+ means: np.ndarray,
415
+ mu: float,
416
+ sigma_n: float,
417
+ n_bins: int = 18,
418
+ width: float = 3.5,
419
+ height: float = 2.2,
420
+ baseline_y: float = 0.0,
421
+ show_theory: bool = True,
422
+ **kwargs,
423
+ ):
424
+ super().__init__(**kwargs)
425
+
426
+ means = np.asarray(means)
427
+ if len(means) == 0:
428
+ return
429
+
430
+ # Bin setup: ±3.5 SE around mu
431
+ x_lo = mu - 3.8 * sigma_n
432
+ x_hi = mu + 3.8 * sigma_n
433
+ edges = np.linspace(x_lo, x_hi, n_bins + 1)
434
+ centres = (edges[:-1] + edges[1:]) / 2
435
+ counts, _ = np.histogram(means, bins=edges)
436
+ max_count = max(counts.max(), 1)
437
+ bin_w_px = width / n_bins
438
+ dx = bin_w_px * 0.07 # 3-D right-face depth
439
+ cap_h = 0.040
440
+
441
+ # ── Axis ──────────────────────────────────────────────────────
442
+ self.add(Line(
443
+ [-width/2, baseline_y, 0.001],
444
+ [ width/2, baseline_y, 0.001],
445
+ stroke_color=P["qq_axis"], stroke_width=1.2,
446
+ ))
447
+
448
+ # Tick marks
449
+ for i in range(n_bins + 1):
450
+ xp = i * bin_w_px - width/2
451
+ self.add(Line(
452
+ [xp, baseline_y - 0.05, 0.001],
453
+ [xp, baseline_y + 0.05, 0.001],
454
+ stroke_color=P["qq_axis"], stroke_width=0.7,
455
+ ))
456
+
457
+ # ── Bars ──────────────────────────────────────────────────────
458
+ for i, count in enumerate(counts):
459
+ if count == 0:
460
+ continue
461
+ h = (count / max_count) * height
462
+ xl = i * bin_w_px - width / 2
463
+ xr = xl + bin_w_px
464
+ by = baseline_y
465
+
466
+ # Front face
467
+ self.add(Rectangle(
468
+ width=bin_w_px - 0.012,
469
+ height=h,
470
+ fill_color=P["bar"],
471
+ fill_opacity=0.88,
472
+ stroke_color=P["bar_side"],
473
+ stroke_width=0.4,
474
+ ).move_to([xl + bin_w_px/2, by + h/2, 0.002]))
475
+
476
+ # Right side
477
+ side = Polygon(
478
+ [xr - 0.006, by, 0.002],
479
+ [xr - 0.006 + dx, by + dx*0.5, 0.002],
480
+ [xr - 0.006 + dx, by + h + dx*0.5, 0.002],
481
+ [xr - 0.006, by + h, 0.002],
482
+ fill_color=P["bar_side"],
483
+ fill_opacity=0.80, stroke_width=0,
484
+ )
485
+ side.shift([0, 0, 0.001])
486
+ self.add(side)
487
+
488
+ # Top cap
489
+ top = Polygon(
490
+ [xl + 0.006, by + h, 0.004],
491
+ [xr - 0.006, by + h, 0.004],
492
+ [xr - 0.006 + dx, by + h + dx*0.5, 0.004],
493
+ [xl + 0.006 + dx, by + h + dx*0.5, 0.004],
494
+ fill_color=P["bar_lite"],
495
+ fill_opacity=0.88, stroke_width=0,
496
+ )
497
+ self.add(top)
498
+
499
+ # AO base shadow
500
+ self.add(Rectangle(
501
+ width=bin_w_px - 0.012,
502
+ height=0.040,
503
+ fill_color="#040608",
504
+ fill_opacity=0.55, stroke_width=0,
505
+ ).move_to([xl + bin_w_px/2, by + 0.020, 0.003]))
506
+
507
+ # ── Theoretical overlay ───────────────────────────────────────
508
+ if show_theory and len(means) >= 5:
509
+ raw_x = np.linspace(x_lo, x_hi, 300)
510
+ y_pdf = _norm_pdf_scene(raw_x, mu, sigma_n)
511
+ y_pdf = np.where(np.isfinite(y_pdf), y_pdf, 0.0)
512
+ bin_w_raw = (x_hi - x_lo) / n_bins
513
+ scale = (len(means) * bin_w_raw
514
+ * height / max_count)
515
+ x_px = (raw_x - x_lo) / (x_hi - x_lo) * width - width/2
516
+ y_px = y_pdf * scale
517
+
518
+ # Fill
519
+ verts = (
520
+ [[float(x_px[0]), baseline_y, 0]]
521
+ + [[float(x), float(y), 0]
522
+ for x, y in zip(x_px, y_px)]
523
+ + [[float(x_px[-1]), baseline_y, 0]]
524
+ )
525
+ if len(verts) >= 3:
526
+ self.add(Polygon(*verts,
527
+ fill_color="#2A1A00",
528
+ fill_opacity=0.35,
529
+ stroke_width=0).shift([0,0,0.006]))
530
+
531
+ # Curve
532
+ step = max(1, len(x_px)//80)
533
+ pts3d = [np.array([float(x_px[i]), float(y_px[i]), 0.008])
534
+ for i in range(0, len(x_px), step)
535
+ if y_px[i] > 0.005]
536
+ if len(pts3d) >= 2:
537
+ sp = VMobject(stroke_color=P["theory"],
538
+ stroke_width=2.0, stroke_opacity=0.90)
539
+ sp.set_points_smoothly(pts3d)
540
+ self.add(sp)
541
+
542
+ self._counts = counts
543
+ self._n_bins = n_bins
544
+ self._x_lo = x_lo
545
+ self._x_hi = x_hi
546
+ self._width = width
547
+ self._height = height
548
+ self._baseline = baseline_y
549
+
550
+
551
+ # ─────────────────────────────────────────────────────────────────────────────
552
+ # QQ plot (normal quantile–quantile)
553
+ # ─────────────────────────────────────────────────────────────────────────────
554
+
555
+ class _QQPlot(VGroup):
556
+ """
557
+ Normal Q-Q plot comparing empirical quantiles of sample means
558
+ to theoretical N(0,1) quantiles.
559
+
560
+ Components:
561
+ 1. Axes (x = theoretical, y = empirical)
562
+ 2. Reference line (45° through mean/std)
563
+ 3. Data dots
564
+ 4. Confidence band (dashed lines either side)
565
+ 5. Title and axis labels
566
+ """
567
+
568
+ def __init__(
569
+ self,
570
+ means: np.ndarray,
571
+ mu: float,
572
+ sigma_n: float,
573
+ width: float = 3.5,
574
+ height: float = 3.0,
575
+ baseline_y: float = 0.0,
576
+ **kwargs,
577
+ ):
578
+ super().__init__(**kwargs)
579
+
580
+ if len(means) < 4:
581
+ return
582
+
583
+ z0 = 0.001
584
+ n = len(means)
585
+ sorted_means = np.sort(means)
586
+
587
+ # Theoretical quantiles (Filliben's approximation)
588
+ probs = (np.arange(1, n+1) - 0.375) / (n + 0.25)
589
+ try:
590
+ from scipy.stats import norm as _scnorm
591
+ z_theory = _scnorm.ppf(probs)
592
+ except ImportError:
593
+ # Rational approximation for normal ppf
594
+ def _ppf_approx(p):
595
+ if p <= 0: return -4.0
596
+ if p >= 1: return 4.0
597
+ t = np.sqrt(-2 * np.log(min(p, 1-p)))
598
+ c = [2.515517, 0.802853, 0.010328]
599
+ d = [1.432788, 0.189269, 0.001308]
600
+ z = t - (c[0]+c[1]*t+c[2]*t**2)/(1+d[0]*t+d[1]*t**2+d[2]*t**3)
601
+ return z if p > 0.5 else -z
602
+ z_theory = np.array([_ppf_approx(p) for p in probs])
603
+
604
+ # Standardise empirical quantiles
605
+ emp_std = float(np.std(sorted_means)) or 1.0
606
+ emp_mean = float(np.mean(sorted_means))
607
+ z_emp = (sorted_means - emp_mean) / emp_std
608
+
609
+ # Axis range
610
+ z_min = min(float(z_theory.min()), float(z_emp.min()), -3.0)
611
+ z_max = max(float(z_theory.max()), float(z_emp.max()), 3.0)
612
+ rng = z_max - z_min
613
+
614
+ def to_px_x(z): return (z - z_min) / rng * width - width/2
615
+ def to_px_y(z): return (z - z_min) / rng * height + baseline_y
616
+
617
+ # ── Axes ──────────────────────────────────────────────────────
618
+ x_ax = Line(
619
+ [-width/2, baseline_y, z0+0.001],
620
+ [ width/2, baseline_y, z0+0.001],
621
+ stroke_color=P["qq_axis"], stroke_width=1.4,
622
+ )
623
+ y_ax = Line(
624
+ [-width/2, baseline_y, z0+0.001],
625
+ [-width/2, baseline_y + height, z0+0.001],
626
+ stroke_color=P["qq_axis"], stroke_width=1.4,
627
+ )
628
+ self.add(x_ax, y_ax)
629
+
630
+ # Axis ticks
631
+ for tv in [-2, -1, 0, 1, 2]:
632
+ xp = to_px_x(float(tv))
633
+ yp = to_px_y(float(tv))
634
+ if z_min <= tv <= z_max:
635
+ self.add(Line([xp, baseline_y-0.06, z0+0.001],
636
+ [xp, baseline_y+0.06, z0+0.001],
637
+ stroke_color=P["qq_axis"], stroke_width=0.9))
638
+ self.add(Text(str(tv), font_size=10,
639
+ color=P["subtitle"])
640
+ .move_to([xp, baseline_y - 0.22, z0+0.001]))
641
+ self.add(Line([-width/2-0.06, yp, z0+0.001],
642
+ [-width/2+0.06, yp, z0+0.001],
643
+ stroke_color=P["qq_axis"], stroke_width=0.9))
644
+
645
+ # ── 45° reference line ────────────────────────────────────────
646
+ ref_lo = [to_px_x(z_min), to_px_y(z_min), z0+0.002]
647
+ ref_hi = [to_px_x(z_max), to_px_y(z_max), z0+0.002]
648
+ ref_line = Line(ref_lo, ref_hi,
649
+ stroke_color=P["qq_line"],
650
+ stroke_width=1.8, stroke_opacity=0.85)
651
+ self.add(ref_line)
652
+
653
+ # ── Confidence band (±1.36/√n envelope) ──────────────────────
654
+ env_half = 1.36 / np.sqrt(n)
655
+ for sign in [-1, 1]:
656
+ band_pts = [
657
+ np.array([to_px_x(zt),
658
+ to_px_y(zt + sign*env_half), z0+0.002])
659
+ for zt in np.linspace(z_min, z_max, 80)
660
+ ]
661
+ band = VMobject(stroke_color=P["theory_dash"] if sign == 1
662
+ else P["theory_dash"],
663
+ stroke_width=1.0,
664
+ stroke_opacity=0.50)
665
+ band.set_points_smoothly(band_pts)
666
+ self.add(band)
667
+
668
+ # ── Data dots ─────────────────────────────────────────────────
669
+ for zt, ze in zip(z_theory, z_emp):
670
+ xp = to_px_x(float(zt))
671
+ yp = to_px_y(float(ze))
672
+ if (-width/2 <= xp <= width/2
673
+ and baseline_y <= yp <= baseline_y + height):
674
+ d = Dot(radius=0.045,
675
+ point=[xp, yp, z0+0.004],
676
+ color=P["qq_dot"],
677
+ fill_opacity=0.80)
678
+ self.add(d)
679
+
680
+ # ── Labels ────────────────────────────────────────────────────
681
+ self.add(Text("Normal Q-Q Plot", font_size=15,
682
+ color=P["title"])
683
+ .move_to([0, baseline_y + height + 0.30, z0+0.003]))
684
+ self.add(Text("Theoretical quantiles", font_size=11,
685
+ color=P["subtitle"])
686
+ .move_to([0, baseline_y - 0.42, z0+0.002]))
687
+ self.add(Text("Sample quantiles", font_size=11,
688
+ color=P["subtitle"])
689
+ .rotate(PI/2)
690
+ .move_to([-width/2 - 0.42,
691
+ baseline_y + height/2, z0+0.002]))
692
+
693
+
694
+ # ─────────────────────────────────────────────────────────────────────────────
695
+ # Live sample-mean counter badge
696
+ # ─────────────────────────────────────────────────────────────────────────────
697
+
698
+ class _LiveCounter(VGroup):
699
+ """
700
+ Live k-counter + SE badge.
701
+
702
+ Shows:
703
+ k = {n} samples drawn
704
+ SE = σ/√n = {val}
705
+ """
706
+
707
+ def __init__(
708
+ self,
709
+ k: int,
710
+ se_val: float,
711
+ n: int,
712
+ **kwargs,
713
+ ):
714
+ super().__init__(**kwargs)
715
+ z0 = 0.001
716
+
717
+ bg = RoundedRectangle(
718
+ width=3.20, height=0.88,
719
+ corner_radius=0.09,
720
+ fill_color=P["badge_bg"],
721
+ fill_opacity=0.92,
722
+ stroke_color=P["badge_border"],
723
+ stroke_width=0.8,
724
+ )
725
+ bg.move_to(ORIGIN)
726
+ self.add(bg)
727
+
728
+ rows = [
729
+ (f"k = {k} samples drawn", P["subtitle"]),
730
+ (f"SE = σ/√{n} = {se_val:.4f}", P["se_label"]),
731
+ ]
732
+ for i, (txt, col) in enumerate(rows):
733
+ lbl = Text(txt, font_size=14, color=col,
734
+ font="monospace")
735
+ lbl.move_to([0, 0.20 - i * 0.38, z0+0.002])
736
+ self.add(lbl)
737
+
738
+
739
+ # ─────────────────────────────────────────────────────────────────────────────
740
+ # CLT formal statement
741
+ # ─────────────────────────────────────────────────────────────────────────────
742
+
743
+ class _CLTStatement(VGroup):
744
+ """
745
+ Colour-coded formal CLT statement.
746
+
747
+ √n (X̄ − μ) / σ → N(0,1) as n → ∞
748
+
749
+ Arranged in three lines:
750
+ Line 1: symbolic statement
751
+ Line 2: "Equivalently: X̄ ~ N(μ, σ²/n)"
752
+ Line 3: conditions
753
+ """
754
+
755
+ def __init__(self, **kwargs):
756
+ super().__init__(**kwargs)
757
+ z0 = 0.001
758
+
759
+ bg = RoundedRectangle(
760
+ width=9.50, height=3.80,
761
+ corner_radius=0.14,
762
+ fill_color=P["bg_panel"],
763
+ fill_opacity=0.96,
764
+ stroke_color=P["badge_border"],
765
+ stroke_width=1.0,
766
+ )
767
+ bg.move_to(ORIGIN)
768
+ self.add(bg)
769
+
770
+ # Strip
771
+ strip = RoundedRectangle(
772
+ width=0.09, height=3.72,
773
+ corner_radius=0.045,
774
+ fill_color=P["f_norm"],
775
+ fill_opacity=0.85, stroke_width=0,
776
+ )
777
+ strip.move_to([-4.70, 0, z0+0.001])
778
+ self.add(strip)
779
+
780
+ title = Text("Central Limit Theorem",
781
+ font_size=24, color=P["title"])
782
+ title.move_to([0, 1.55, z0+0.002])
783
+ self.add(title)
784
+
785
+ self.add(Line(
786
+ [-4.60, 1.20, z0+0.002],
787
+ [ 4.60, 1.20, z0+0.002],
788
+ stroke_color=P["badge_border"], stroke_width=0.7,
789
+ ))
790
+
791
+ # ── Line 1: main formula ──────────────────────────────────────
792
+ pieces1 = [
793
+ ("\\frac{\\sqrt{n}\\,(\\bar{X}", P["f_xbar"]),
794
+ ("\\;-\\;", P["f_eq"]),
795
+ ("\\mu", P["f_mu"]),
796
+ (")}{", P["f_eq"]),
797
+ ("\\sigma", P["f_sigma"]),
798
+ ("}", P["f_eq"]),
799
+ ("\\;\\xrightarrow{d}\\;", P["f_eq"]),
800
+ ("\\mathcal{N}(0,\\,1)", P["f_norm"]),
801
+ ("\\quad\\text{as }", P["f_eq"]),
802
+ ("n\\to\\infty", P["f_n"]),
803
+ ]
804
+ self.sym_pieces = VGroup()
805
+ x_cur = -4.40
806
+ for tex_str, col in pieces1:
807
+ try:
808
+ m = MathTex(tex_str, font_size=28, color=col)
809
+ except Exception:
810
+ m = Text(tex_str.replace("\\",""), font_size=22, color=col)
811
+ m.move_to([x_cur + m.width/2, 0.52, z0+0.003])
812
+ self.sym_pieces.add(m)
813
+ x_cur += m.width + 0.06
814
+ self.add(self.sym_pieces)
815
+
816
+ # ── Line 2: equivalently ──────────────────────────────────────
817
+ try:
818
+ eq2 = MathTex(
819
+ r"\text{Equivalently:}\quad"
820
+ r"\bar{X} \;\sim\; \mathcal{N}\!\left(\mu,\;"
821
+ r"\frac{\sigma^2}{n}\right)",
822
+ font_size=24, color=P["f_eq"],
823
+ )
824
+ except Exception:
825
+ eq2 = Text("Equivalently: X̄ ~ N(μ, σ²/n)",
826
+ font_size=20, color=P["f_eq"])
827
+ eq2.move_to([0, -0.18, z0+0.003])
828
+ self.add(eq2)
829
+
830
+ # ── Line 3: conditions ────────────────────────────────────────
831
+ cond = Text(
832
+ "Conditions: finite μ and σ², i.i.d. samples,"
833
+ " n sufficiently large",
834
+ font_size=15, color=P["subtitle"],
835
+ )
836
+ cond.move_to([0, -0.90, z0+0.003])
837
+ self.add(cond)
838
+
839
+ # ── Line 4: interpretation ────────────────────────────────────
840
+ interp = Text(
841
+ "The sampling distribution of the mean is normal"
842
+ " regardless of the population shape.",
843
+ font_size=15, color=P["subtitle"],
844
+ )
845
+ interp.move_to([0, -1.40, z0+0.003])
846
+ self.add(interp)
847
+
848
+
849
+ # ─────────────────────────────────────────────────────────────────────────────
850
+ # SE effect panel (n=1 → n=100, SE arrow shrinks)
851
+ # ─────────────────────────────────────────────────────────────────────────────
852
+
853
+ class _SEPanel(VGroup):
854
+ """
855
+ One column of the n-effect comparison showing a histogram
856
+ with SE arrow and n label.
857
+
858
+ Parameters
859
+ ----------
860
+ means : np.ndarray
861
+ mu, sigma_n : distribution parameters for overlay
862
+ n : sample size (label)
863
+ width, height, baseline_y : geometry
864
+ """
865
+
866
+ def __init__(
867
+ self,
868
+ means: np.ndarray,
869
+ mu: float,
870
+ sigma_n: float,
871
+ n: int,
872
+ width: float = 2.80,
873
+ height: float = 2.20,
874
+ baseline_y: float = 0.0,
875
+ **kwargs,
876
+ ):
877
+ super().__init__(**kwargs)
878
+ z0 = 0.001
879
+
880
+ # Histogram
881
+ hist = _MiniHistogram(
882
+ means=means,
883
+ mu=mu, sigma_n=sigma_n,
884
+ n_bins=16,
885
+ width=width, height=height,
886
+ baseline_y=baseline_y,
887
+ )
888
+ self.add(hist)
889
+
890
+ # SE arrow
891
+ px_per_unit = width / (7.6 * sigma_n) # ±3.8 SE range → full width
892
+ se_px_half = sigma_n * px_per_unit
893
+ arr = DoubleArrow(
894
+ start=[-se_px_half, baseline_y - 0.50, z0+0.002],
895
+ end =[ se_px_half, baseline_y - 0.50, z0+0.002],
896
+ stroke_color=P["se"], stroke_width=1.8,
897
+ tip_length=0.13, buff=0,
898
+ )
899
+ self.add(arr)
900
+
901
+ se_lbl = Text(f"SE={sigma_n:.3f}", font_size=12,
902
+ color=P["se_label"])
903
+ se_lbl.move_to([0, baseline_y - 0.82, z0+0.002])
904
+ self.add(se_lbl)
905
+
906
+ # n label
907
+ n_lbl = Text(f"n = {n}", font_size=18, color=P["title"])
908
+ n_lbl.move_to([0, baseline_y + height + 0.30, z0+0.003])
909
+ self.add(n_lbl)
910
+
911
+
912
+ # ─────────────────────────────────────────────────────────────────────────────
913
+ # The full demo scene
914
+ # ─────────────────────────────────────────────────────────────────────────────
915
+
916
+ class CLTDemo(Scene):
917
+ """
918
+ Central Limit Theorem cinematic demonstration.
919
+
920
+ Run with:
921
+ manim -pql demo_clt.py CLTDemo
922
+ For high quality:
923
+ manim -pqh demo_clt.py CLTDemo
924
+ """
925
+
926
+ # ── Population parameters ─────────────────────────────────────────
927
+ POP_TYPE = "exponential"
928
+ POP_PARAMS = {"lam": 1.0}
929
+ N_MAIN = 5
930
+ SIGMA_POP = 1.0 # σ for exponential(lam=1)
931
+ MU_POP = 1.0 # μ for exponential(lam=1)
932
+
933
+ def construct(self):
934
+ self._act0_title()
935
+ self._act1_population_zoo()
936
+ self._act2_what_is_sample_mean()
937
+ self._act3_build_histogram_slow()
938
+ self._act4_convergence_speedup()
939
+ self._act5_n_effect()
940
+ self._act6_population_independence()
941
+ self._act7_qq_plot()
942
+ self._act8_clt_statement()
943
+
944
+ # ─────────────────────────────────────────────────────────────────
945
+ # Act 0 — Title / hook
946
+ # ─────────────────────────────────────────────────────────────────
947
+
948
+ def _act0_title(self):
949
+ bg = Rectangle(width=16, height=9,
950
+ fill_color=P["bg"],
951
+ fill_opacity=1.0, stroke_width=0)
952
+ self.add(bg)
953
+
954
+ # Three population curves pulse in
955
+ pop_specs = [
956
+ ("uniform", {"a": 0.0, "b": 1.0},
957
+ "Uniform", P["uniform_fill"], P["uniform_ridge"]),
958
+ ("exponential", {"lam": 1.0},
959
+ "Exponential", P["exp_fill"], P["exp_ridge"]),
960
+ ("bimodal", {"mu1": -1.8, "mu2": 1.8,
961
+ "sigma": 0.6, "mix": 0.5},
962
+ "Bimodal", P["bimodal_fill"], P["bimodal_ridge"]),
963
+ ]
964
+ curves = VGroup()
965
+ for i, (pt, pm, title, fc, rc) in enumerate(pop_specs):
966
+ c = _MiniPopCurve(pt, pm, title, fc, rc,
967
+ width=2.6, height=1.6,
968
+ baseline_y=0.0,
969
+ show_dots=False)
970
+ c.scale(0.90)
971
+ c.move_to([(i-1) * 3.6, 0.60, 0])
972
+ curves.add(c)
973
+
974
+ self.play(
975
+ *[FadeIn(c, shift=UP*0.20,
976
+ rate_func=rate_functions.ease_out_back,
977
+ run_time=1.0)
978
+ for c in curves],
979
+ )
980
+ self.wait(0.3)
981
+
982
+ # Hook text
983
+ hook = Text("No matter the shape of the population…",
984
+ font_size=27, color=P["subtitle"])
985
+ hook.move_to([0, -1.30, 0])
986
+ self.play(Write(hook, run_time=1.2))
987
+ self.wait(0.4)
988
+
989
+ punchline = Text(
990
+ "…the sampling distribution of the mean converges to normal.",
991
+ font_size=25, color=P["title"],
992
+ )
993
+ punchline.move_to([0, -1.95, 0])
994
+ self.play(FadeIn(punchline, shift=UP*0.12, run_time=0.9))
995
+ self.wait(0.7)
996
+
997
+ # Main title
998
+ main_title = Text("Central Limit Theorem",
999
+ font_size=46, color=P["title"])
1000
+ main_title.move_to([0, -3.00, 0])
1001
+ self.play(FadeIn(main_title,
1002
+ rate_func=rate_functions.ease_out_back,
1003
+ run_time=0.8))
1004
+ self.wait(0.9)
1005
+
1006
+ self.play(
1007
+ FadeOut(curves),
1008
+ FadeOut(hook),
1009
+ FadeOut(punchline),
1010
+ FadeOut(main_title),
1011
+ FadeOut(bg),
1012
+ run_time=0.70,
1013
+ )
1014
+
1015
+ # ─────────────────────────────────────────────────────────────────
1016
+ # Act 1 — Population zoo
1017
+ # ─────────────────────────────────────────────────────────────────
1018
+
1019
+ def _act1_population_zoo(self):
1020
+ act_lbl = _section_label("Act 1 — Population Zoo")
1021
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1022
+ self.play(FadeIn(act_lbl, run_time=0.4))
1023
+
1024
+ zoo_specs = [
1025
+ ("uniform", {"a": 0.0, "b": 1.0},
1026
+ "Uniform[0,1]", P["uniform_fill"], P["uniform_ridge"]),
1027
+ ("exponential", {"lam": 1.0},
1028
+ "Exp(λ=1)", P["exp_fill"], P["exp_ridge"]),
1029
+ ("bimodal", {"mu1": -1.8, "mu2": 1.8,
1030
+ "sigma": 0.6, "mix": 0.5},
1031
+ "Bimodal", P["bimodal_fill"], P["bimodal_ridge"]),
1032
+ ]
1033
+
1034
+ self._zoo_curves = VGroup()
1035
+ for i, (pt, pm, title, fc, rc) in enumerate(zoo_specs):
1036
+ c = _MiniPopCurve(
1037
+ pt, pm, title, fc, rc,
1038
+ width=3.4, height=2.2,
1039
+ baseline_y=0.10,
1040
+ show_dots=True, n_dots=50, seed=i*7,
1041
+ )
1042
+ c.move_to([(i-1) * 4.60, 0.50, 0])
1043
+ self._zoo_curves.add(c)
1044
+
1045
+ for c in self._zoo_curves:
1046
+ self.play(FadeIn(c, shift=UP*0.18,
1047
+ run_time=0.75))
1048
+
1049
+ # Stat badges
1050
+ badges = VGroup()
1051
+ for i, (pt, pm, *_) in enumerate(zoo_specs):
1052
+ if _SD_AVAILABLE:
1053
+ mu, sigma = _pop_stats(pt, pm)
1054
+ else:
1055
+ mu, sigma = 0.5, 0.29
1056
+ b = _badge(f"μ={mu:.2f} σ={sigma:.2f}",
1057
+ zoo_specs[i][4])
1058
+ b.move_to([(i-1)*4.60, -1.65, 0])
1059
+ badges.add(b)
1060
+ self.play(FadeIn(badges, run_time=0.7))
1061
+ self.wait(0.8)
1062
+
1063
+ # "All different shapes — all will produce normal sample means"
1064
+ msg = Text(
1065
+ "All very different shapes. "
1066
+ "The CLT says their sample means will all be normal.",
1067
+ font_size=20, color=P["subtitle"],
1068
+ )
1069
+ msg.move_to([0, -2.60, 0])
1070
+ self.play(Write(msg, run_time=1.3))
1071
+ self.wait(0.8)
1072
+
1073
+ self.play(
1074
+ FadeOut(badges), FadeOut(msg),
1075
+ FadeOut(act_lbl),
1076
+ run_time=0.5,
1077
+ )
1078
+ # Keep zoo_curves visible but shrink for next act
1079
+
1080
+ # ─────────────────────────────────────────────────────────────────
1081
+ # Act 2 — What is a sample mean?
1082
+ # ─────────────────────────────────────────────────────────────────
1083
+
1084
+ def _act2_what_is_sample_mean(self):
1085
+ act_lbl = _section_label("Act 2 — What is a Sample Mean?")
1086
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1087
+ self.play(FadeIn(act_lbl, run_time=0.4))
1088
+
1089
+ # Focus on exponential curve (index 1)
1090
+ exp_curve = self._zoo_curves[1]
1091
+ others = VGroup(self._zoo_curves[0], self._zoo_curves[2])
1092
+
1093
+ self.play(
1094
+ others.animate.set_opacity(0.22),
1095
+ exp_curve.animate.scale(1.15).move_to([-3.20, 0.55, 0]),
1096
+ run_time=0.80,
1097
+ )
1098
+
1099
+ # Number line below the curve
1100
+ n_strip = 5
1101
+ rng = np.random.default_rng(99)
1102
+ lam = 1.0
1103
+ sample = rng.exponential(1.0/lam, n_strip)
1104
+ sample = np.clip(sample, 0.05, 5.0)
1105
+
1106
+ x_lo, x_hi = 0.0, 5.0
1107
+ strip_w = 3.2
1108
+ strip_y = -1.75
1109
+ strip_cx = -3.20
1110
+
1111
+ # Number line
1112
+ nline = Line(
1113
+ [strip_cx - strip_w/2, strip_y, 0],
1114
+ [strip_cx + strip_w/2, strip_y, 0],
1115
+ stroke_color=P["qq_axis"], stroke_width=1.4,
1116
+ )
1117
+ self.add(nline)
1118
+ for rv in [0, 1, 2, 3, 4, 5]:
1119
+ xp = (rv / 5.0) * strip_w - strip_w/2 + strip_cx
1120
+ self.add(Line([xp, strip_y-0.07, 0.001],
1121
+ [xp, strip_y+0.07, 0.001],
1122
+ stroke_color=P["qq_axis"],
1123
+ stroke_width=1.0))
1124
+ self.add(Text(str(rv), font_size=11,
1125
+ color=P["subtitle"])
1126
+ .move_to([xp, strip_y-0.26, 0.001]))
1127
+
1128
+ # Drop dots one by one
1129
+ dot_mobs = []
1130
+ for j, val in enumerate(sample):
1131
+ xp = (val / (x_hi - x_lo)) * strip_w - strip_w/2 + strip_cx
1132
+ ystart = strip_y + 1.10
1133
+ d = Dot(radius=0.09,
1134
+ point=[xp, ystart, 0.005],
1135
+ color=P["dot"],
1136
+ fill_opacity=0.90)
1137
+ # Subscript label
1138
+ try:
1139
+ lbl = MathTex(f"x_{{{j+1}}}",
1140
+ font_size=16, color=P["dot"])
1141
+ except Exception:
1142
+ lbl = Text(f"x{j+1}", font_size=13, color=P["dot"])
1143
+ lbl.move_to([xp, ystart + 0.25, 0.006])
1144
+
1145
+ self.play(
1146
+ FadeIn(d, shift=DOWN*1.00,
1147
+ rate_func=rate_functions.ease_in_cubic,
1148
+ run_time=0.30),
1149
+ FadeIn(lbl, run_time=0.25),
1150
+ )
1151
+ dot_mobs.append((d, lbl, xp))
1152
+ self.wait(0.08)
1153
+
1154
+ # Bracket collapses to mean
1155
+ mean_val = float(np.mean(sample))
1156
+ mean_px = (mean_val / (x_hi - x_lo)) * strip_w - strip_w/2 + strip_cx
1157
+
1158
+ self.wait(0.3)
1159
+ bracket_l = Line(
1160
+ [dot_mobs[0][2], strip_y + 0.25, 0.006],
1161
+ [dot_mobs[-1][2], strip_y + 0.25, 0.006],
1162
+ stroke_color=P["f_xbar"], stroke_width=1.8,
1163
+ )
1164
+ self.play(Create(bracket_l, run_time=0.55))
1165
+
1166
+ # Bracket ticks
1167
+ for xp2 in [dot_mobs[0][2], dot_mobs[-1][2]]:
1168
+ self.add(Line(
1169
+ [xp2, strip_y + 0.17, 0.006],
1170
+ [xp2, strip_y + 0.33, 0.006],
1171
+ stroke_color=P["f_xbar"], stroke_width=1.6,
1172
+ ))
1173
+
1174
+ # Mean dot appears
1175
+ mean_dot = Dot(radius=0.13,
1176
+ point=[mean_px, strip_y + 0.25, 0.008],
1177
+ color=P["dot_mean"],
1178
+ fill_opacity=1.0)
1179
+ self.play(
1180
+ GrowFromCenter(mean_dot,
1181
+ rate_func=rate_functions.ease_out_back,
1182
+ run_time=0.55)
1183
+ )
1184
+
1185
+ # x̄ label
1186
+ try:
1187
+ xbar_lbl = MathTex(r"\bar{x} = " + f"{mean_val:.2f}",
1188
+ font_size=22, color=P["dot_mean"])
1189
+ except Exception:
1190
+ xbar_lbl = Text(f"x̄ = {mean_val:.2f}",
1191
+ font_size=18, color=P["dot_mean"])
1192
+ xbar_lbl.move_to([mean_px, strip_y + 0.62, 0.008])
1193
+ self.play(FadeIn(xbar_lbl, shift=UP*0.08, run_time=0.5))
1194
+
1195
+ # Formula
1196
+ try:
1197
+ formula = MathTex(
1198
+ r"\bar{x} = \frac{x_1 + x_2 + \cdots + x_n}{n}",
1199
+ font_size=26, color=P["f_eq"],
1200
+ )
1201
+ except Exception:
1202
+ formula = Text("x̄ = (x₁ + … + xₙ) / n",
1203
+ font_size=22, color=P["f_eq"])
1204
+ formula.move_to([1.80, -0.10, 0])
1205
+ self.play(Write(formula, run_time=1.1))
1206
+ self.wait(0.9)
1207
+
1208
+ # Mean dot beams upward (preview of histogram)
1209
+ beam = Line(
1210
+ [mean_px, strip_y + 0.35, 0.008],
1211
+ [mean_px, strip_y + 2.20, 0.008],
1212
+ stroke_color=P["mean_beam"],
1213
+ stroke_width=1.4, stroke_opacity=0.60,
1214
+ )
1215
+ self.play(Create(beam, run_time=0.45))
1216
+ self.wait(0.30)
1217
+
1218
+ # Clean up act 2
1219
+ act2_group = VGroup(
1220
+ nline, bracket_l, mean_dot, xbar_lbl,
1221
+ formula, beam,
1222
+ *[d for d,l,_ in dot_mobs],
1223
+ *[l for _,l,_ in dot_mobs],
1224
+ )
1225
+ self.play(
1226
+ FadeOut(act2_group),
1227
+ others.animate.set_opacity(1.0),
1228
+ exp_curve.animate.scale(1/1.15).move_to([0, 0.50, 0]),
1229
+ FadeOut(act_lbl),
1230
+ run_time=0.65,
1231
+ )
1232
+
1233
+ # ─────────────────────────────────────────────────────────────────
1234
+ # Act 3 — Build histogram slow (using SamplingDistribution3D)
1235
+ # ─────────────────────────────────────────────────────────────────
1236
+
1237
+ def _act3_build_histogram_slow(self):
1238
+ act_lbl = _section_label("Act 3 — Building the Histogram")
1239
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1240
+ self.play(FadeIn(act_lbl, run_time=0.4))
1241
+
1242
+ # Fade out zoo, build full SD panel
1243
+ self.play(
1244
+ FadeOut(self._zoo_curves),
1245
+ run_time=0.50,
1246
+ )
1247
+
1248
+ if not _SD_AVAILABLE:
1249
+ # Fallback: show message
1250
+ msg = Text("(Install statanim to see live CLT simulation)",
1251
+ font_size=20, color=P["subtitle"])
1252
+ msg.move_to(ORIGIN)
1253
+ self.play(FadeIn(msg, run_time=0.5))
1254
+ self.wait(1.5)
1255
+ self.play(FadeOut(msg, act_lbl, run_time=0.4))
1256
+ return
1257
+
1258
+ # Build full SamplingDistribution3D
1259
+ self._sd = SamplingDistribution3D.exponential(
1260
+ lam=1.0, n=self.N_MAIN,
1261
+ n_bins=18,
1262
+ pop_panel_w=3.8,
1263
+ hist_panel_w=4.8,
1264
+ panel_h=2.6,
1265
+ baseline_y=0.3,
1266
+ max_samples=120,
1267
+ show_strip=True,
1268
+ show_se=True,
1269
+ show_panel=True,
1270
+ seed=42,
1271
+ )
1272
+ self._sd.center()
1273
+ self._sd.shift(DOWN * 0.20)
1274
+ self.add(self._sd)
1275
+
1276
+ # Build population
1277
+ self.play(BuildPopulation(self._sd, run_time=1.8))
1278
+ self.play(FadeIn(self._sd.clt_arrow, run_time=0.5))
1279
+ self.wait(0.3)
1280
+
1281
+ # Counter badge
1282
+ sigma_n = self.SIGMA_POP / np.sqrt(self.N_MAIN)
1283
+ counter = _LiveCounter(k=0, se_val=sigma_n, n=self.N_MAIN)
1284
+ counter.move_to([0, -2.80, 0])
1285
+ self.play(FadeIn(counter, run_time=0.4))
1286
+
1287
+ # 10 slow iterations
1288
+ for k in range(1, 11):
1289
+ self.play(RunCLT(self._sd, run_time=1.10))
1290
+
1291
+ # Update counter every 2 steps
1292
+ if k % 2 == 0:
1293
+ new_counter = _LiveCounter(
1294
+ k=k, se_val=sigma_n, n=self.N_MAIN
1295
+ )
1296
+ new_counter.move_to(counter.get_center())
1297
+ self.play(
1298
+ ReplacementTransform(counter, new_counter,
1299
+ run_time=0.25)
1300
+ )
1301
+ counter = new_counter
1302
+
1303
+ self.wait(0.5)
1304
+ self.play(FadeOut(act_lbl), FadeOut(counter), run_time=0.4)
1305
+
1306
+ # ─────────────────────────────────────────────────────────────────
1307
+ # Act 4 — Convergence speed-up
1308
+ # ─────────────────────────────────────────────────────────────────
1309
+
1310
+ def _act4_convergence_speedup(self):
1311
+ act_lbl = _section_label("Act 4 — Convergence")
1312
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1313
+ self.play(FadeIn(act_lbl, run_time=0.4))
1314
+
1315
+ if not _SD_AVAILABLE or not hasattr(self, "_sd"):
1316
+ self.play(FadeOut(act_lbl), run_time=0.3)
1317
+ return
1318
+
1319
+ # "Let's speed up…" banner
1320
+ speed_banner = Text(
1321
+ "Let's draw 90 more samples…",
1322
+ font_size=25, color=P["subtitle"],
1323
+ )
1324
+ speed_banner.move_to([0, -2.70, 0])
1325
+ self.play(FadeIn(speed_banner, run_time=0.5))
1326
+ self.wait(0.4)
1327
+
1328
+ # Fast burst: 50 samples
1329
+ for _ in range(50):
1330
+ self.play(RunCLT(self._sd, run_time=0.06, fast=True))
1331
+
1332
+ # Theory curve appears dashed after 50
1333
+ self._sd.hist_panel.set_theory_curve(
1334
+ self._sd._mu_pop, self._sd._se, self._sd.k_drawn
1335
+ )
1336
+ if self._sd.hist_panel._theory_curve is not None:
1337
+ self.play(
1338
+ FadeIn(self._sd.hist_panel._theory_curve,
1339
+ run_time=0.6)
1340
+ )
1341
+
1342
+ at50_badge = _badge(f"k = 50 (theory: dashed)",
1343
+ P["theory_dash"])
1344
+ at50_badge.move_to([0, -2.70, 0])
1345
+ self.play(
1346
+ ReplacementTransform(speed_banner, at50_badge,
1347
+ run_time=0.5)
1348
+ )
1349
+ self.wait(0.4)
1350
+
1351
+ # 40 more → curve goes solid
1352
+ for _ in range(40):
1353
+ self.play(RunCLT(self._sd, run_time=0.04, fast=True))
1354
+
1355
+ self._sd.hist_panel.set_theory_curve(
1356
+ self._sd._mu_pop, self._sd._se, self._sd.k_drawn
1357
+ )
1358
+
1359
+ at100_badge = _badge(
1360
+ f"k = {self._sd.k_drawn} (theory: solid)",
1361
+ P["theory"]
1362
+ )
1363
+ at100_badge.move_to([0, -2.70, 0])
1364
+ self.play(
1365
+ ReplacementTransform(at50_badge, at100_badge,
1366
+ run_time=0.5)
1367
+ )
1368
+ self.wait(0.5)
1369
+
1370
+ # Converged message
1371
+ conv_msg = Text(
1372
+ "The histogram is converging to the theoretical normal curve.",
1373
+ font_size=20, color=P["title"],
1374
+ )
1375
+ conv_msg.move_to([0, -3.40, 0])
1376
+ self.play(Write(conv_msg, run_time=1.0))
1377
+ self.wait(0.8)
1378
+
1379
+ self.play(
1380
+ FadeOut(act_lbl),
1381
+ FadeOut(at100_badge),
1382
+ FadeOut(conv_msg),
1383
+ FadeOut(self._sd),
1384
+ run_time=0.65,
1385
+ )
1386
+
1387
+ # ─────────────────────────────────────────────────────────────────
1388
+ # Act 5 — The n effect
1389
+ # ─────────────────────────────────────────────────────────────────
1390
+
1391
+ def _act5_n_effect(self):
1392
+ act_lbl = _section_label("Act 5 — The Effect of n")
1393
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1394
+ self.play(FadeIn(act_lbl, run_time=0.4))
1395
+
1396
+ n_values = [1, 5, 30, 100]
1397
+ rng = np.random.default_rng(7)
1398
+ k_pre = 120
1399
+
1400
+ panels = VGroup()
1401
+ spacing = 3.40
1402
+ for i, n in enumerate(n_values):
1403
+ sigma_n = self.SIGMA_POP / np.sqrt(n)
1404
+ means = np.array([
1405
+ float(np.mean(rng.exponential(
1406
+ 1.0/self.POP_PARAMS["lam"], n
1407
+ )))
1408
+ for _ in range(k_pre)
1409
+ ])
1410
+ pan = _SEPanel(
1411
+ means=means,
1412
+ mu=self.MU_POP, sigma_n=sigma_n,
1413
+ n=n,
1414
+ width=2.80, height=2.20,
1415
+ baseline_y=0.0,
1416
+ )
1417
+ pan.move_to([(i - 1.5) * spacing, 0.40, 0])
1418
+ panels.add(pan)
1419
+
1420
+ self.play(
1421
+ *[FadeIn(p, shift=UP*0.15,
1422
+ run_time=0.60 + i*0.10)
1423
+ for i, p in enumerate(panels)],
1424
+ )
1425
+ self.wait(0.5)
1426
+
1427
+ # SE = σ/√n formula reveal
1428
+ try:
1429
+ se_form = MathTex(
1430
+ r"\mathrm{SE} = \frac{\sigma}{\sqrt{n}}"
1431
+ r"\quad\Rightarrow\quad"
1432
+ r"\text{larger }n\Rightarrow\text{narrower distribution}",
1433
+ font_size=24, color=P["se_label"],
1434
+ )
1435
+ except Exception:
1436
+ se_form = Text(
1437
+ "SE = σ/√n → larger n → narrower distribution",
1438
+ font_size=20, color=P["se_label"],
1439
+ )
1440
+ se_form.move_to([0, -2.20, 0])
1441
+ self.play(Write(se_form, run_time=1.2))
1442
+ self.wait(0.8)
1443
+
1444
+ # Live SE values
1445
+ for i, n in enumerate(n_values):
1446
+ sigma_n = self.SIGMA_POP / np.sqrt(n)
1447
+ self.play(
1448
+ Indicate(panels[i], color=P["se"],
1449
+ scale_factor=1.05, run_time=0.45),
1450
+ )
1451
+ self.wait(0.08)
1452
+ self.wait(0.5)
1453
+
1454
+ self.play(
1455
+ FadeOut(panels),
1456
+ FadeOut(se_form),
1457
+ FadeOut(act_lbl),
1458
+ run_time=0.55,
1459
+ )
1460
+
1461
+ # ─────────────────────────────────────────────────────────────────
1462
+ # Act 6 — Population independence
1463
+ # ─────────────────────────────────────────────────────────────────
1464
+
1465
+ def _act6_population_independence(self):
1466
+ act_lbl = _section_label("Act 6 — Population Independence")
1467
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1468
+ self.play(FadeIn(act_lbl, run_time=0.4))
1469
+
1470
+ pop_specs = [
1471
+ ("uniform", {"a": 0.0, "b": 1.0},
1472
+ P["uniform_fill"], P["uniform_ridge"]),
1473
+ ("exponential", {"lam": 1.0},
1474
+ P["exp_fill"], P["exp_ridge"]),
1475
+ ("bimodal", {"mu1": -1.8, "mu2": 1.8,
1476
+ "sigma": 0.6, "mix": 0.5},
1477
+ P["bimodal_fill"], P["bimodal_ridge"]),
1478
+ ]
1479
+
1480
+ rng = np.random.default_rng(31)
1481
+ n_samp = 10
1482
+ k_fast = 100
1483
+ spacing = 4.50
1484
+ panels = VGroup()
1485
+
1486
+ for i, (pt, pm, fc, rc) in enumerate(pop_specs):
1487
+ if _SD_AVAILABLE:
1488
+ mu, sigma = _pop_stats(pt, pm)
1489
+ else:
1490
+ mu, sigma = 0.5, 0.3
1491
+ sigma_n = sigma / np.sqrt(n_samp)
1492
+
1493
+ # Generate means
1494
+ means = []
1495
+ for _ in range(k_fast):
1496
+ if _SD_AVAILABLE:
1497
+ s = _sample_pop(pt, pm, n_samp, rng)
1498
+ else:
1499
+ s = rng.normal(mu, sigma, n_samp)
1500
+ means.append(float(np.mean(s)))
1501
+ means = np.array(means)
1502
+
1503
+ # Mini population curve
1504
+ pop_c = _MiniPopCurve(
1505
+ pt, pm, "", fc, rc,
1506
+ width=3.0, height=1.30,
1507
+ baseline_y=0.0,
1508
+ show_dots=False,
1509
+ )
1510
+
1511
+ # Mini histogram
1512
+ hist = _MiniHistogram(
1513
+ means=means,
1514
+ mu=mu, sigma_n=sigma_n,
1515
+ n_bins=16,
1516
+ width=3.0, height=1.80,
1517
+ baseline_y=0.0,
1518
+ show_theory=True,
1519
+ )
1520
+
1521
+ # Arrow between them
1522
+ arr = Arrow(
1523
+ start=[0, -0.20, 0],
1524
+ end =[0, -0.80, 0],
1525
+ stroke_color=P["subtitle"],
1526
+ stroke_width=1.4, tip_length=0.16, buff=0,
1527
+ )
1528
+ try:
1529
+ arr_lbl = MathTex(rf"n={n_samp}", font_size=14,
1530
+ color=P["subtitle"])
1531
+ except Exception:
1532
+ arr_lbl = Text(f"n={n_samp}", font_size=12,
1533
+ color=P["subtitle"])
1534
+ arr_lbl.next_to(arr, RIGHT, buff=0.08)
1535
+
1536
+ col_grp = VGroup()
1537
+ pop_c.move_to([0, 1.60, 0])
1538
+ arr.move_to([0, 0.38, 0])
1539
+ arr_lbl.move_to([0.60, 0.38, 0])
1540
+ hist.move_to([0, -1.00, 0])
1541
+ col_grp.add(pop_c, arr, arr_lbl, hist)
1542
+ col_grp.move_to([(i-1) * spacing, 0.20, 0])
1543
+ panels.add(col_grp)
1544
+
1545
+ self.play(
1546
+ *[FadeIn(p, shift=UP*0.15, run_time=0.70)
1547
+ for p in panels],
1548
+ )
1549
+ self.wait(0.6)
1550
+
1551
+ msg = Text(
1552
+ "All three converge to a normal shape. "
1553
+ "The population doesn't matter.",
1554
+ font_size=22, color=P["title"],
1555
+ )
1556
+ msg.move_to([0, -3.0, 0])
1557
+ self.play(Write(msg, run_time=1.2))
1558
+ self.wait(0.8)
1559
+
1560
+ # Flash all histograms simultaneously
1561
+ self.play(
1562
+ *[Indicate(p.submobjects[-1],
1563
+ color=P["theory"],
1564
+ scale_factor=1.04,
1565
+ run_time=0.6)
1566
+ for p in panels],
1567
+ )
1568
+ self.wait(0.5)
1569
+
1570
+ self.play(
1571
+ FadeOut(panels),
1572
+ FadeOut(msg),
1573
+ FadeOut(act_lbl),
1574
+ run_time=0.60,
1575
+ )
1576
+
1577
+ # ─────────────────────────────────────────────────────────────────
1578
+ # Act 7 — Normal Q-Q plot
1579
+ # ─────────────────────────────────────────────────────────────────
1580
+
1581
+ def _act7_qq_plot(self):
1582
+ act_lbl = _section_label("Act 7 — Normal Q-Q Plot")
1583
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1584
+ self.play(FadeIn(act_lbl, run_time=0.4))
1585
+
1586
+ # Generate a large sample of means from exponential
1587
+ rng = np.random.default_rng(88)
1588
+ n_samp = 30
1589
+ k_total = 200
1590
+ lam = 1.0
1591
+ means = np.array([
1592
+ float(np.mean(rng.exponential(1.0/lam, n_samp)))
1593
+ for _ in range(k_total)
1594
+ ])
1595
+ sigma_n = (1.0/lam) / np.sqrt(n_samp)
1596
+ mu = 1.0 / lam
1597
+
1598
+ # Histogram on left
1599
+ hist = _MiniHistogram(
1600
+ means=means,
1601
+ mu=mu, sigma_n=sigma_n,
1602
+ n_bins=20,
1603
+ width=4.0, height=3.0,
1604
+ baseline_y=-0.30,
1605
+ show_theory=True,
1606
+ )
1607
+ hist.move_to([-3.30, 0.35, 0])
1608
+
1609
+ # Label
1610
+ hist_title = Text(
1611
+ f"n={n_samp}, k={k_total} samples\nExp(λ=1) population",
1612
+ font_size=16, color=P["subtitle"],
1613
+ )
1614
+ hist_title.move_to([-3.30, 2.30, 0])
1615
+
1616
+ self.play(FadeIn(hist, shift=LEFT*0.15, run_time=0.9))
1617
+ self.play(FadeIn(hist_title, run_time=0.5))
1618
+ self.wait(0.4)
1619
+
1620
+ # Arrow
1621
+ arr = Arrow(
1622
+ start=[-1.0, 0.35, 0],
1623
+ end =[ 0.6, 0.35, 0],
1624
+ stroke_color=P["subtitle"],
1625
+ stroke_width=1.6, tip_length=0.18, buff=0,
1626
+ )
1627
+ self.play(Create(arr, run_time=0.5))
1628
+
1629
+ # QQ plot on right
1630
+ qq = _QQPlot(
1631
+ means=means,
1632
+ mu=mu, sigma_n=sigma_n,
1633
+ width=3.8, height=3.0,
1634
+ baseline_y=-0.30,
1635
+ )
1636
+ qq.move_to([3.10, 0.35, 0])
1637
+ qq.set_opacity(0)
1638
+ self.play(FadeIn(qq, shift=RIGHT*0.15, run_time=1.0))
1639
+ self.wait(0.5)
1640
+
1641
+ # Highlight that points hug the line
1642
+ qq_msg = Text(
1643
+ "Points hug the 45° line → distribution is approximately normal.",
1644
+ font_size=19, color=P["title"],
1645
+ )
1646
+ qq_msg.move_to([0, -2.70, 0])
1647
+ self.play(Write(qq_msg, run_time=1.1))
1648
+ self.wait(0.9)
1649
+
1650
+ self.play(
1651
+ FadeOut(hist), FadeOut(hist_title),
1652
+ FadeOut(arr), FadeOut(qq),
1653
+ FadeOut(qq_msg), FadeOut(act_lbl),
1654
+ run_time=0.60,
1655
+ )
1656
+
1657
+ # ─────────────────────────────────────────────────────────────────
1658
+ # Act 8 — Formal CLT statement + closing
1659
+ # ─────────────────────────────────────────────────────────────────
1660
+
1661
+ def _act8_clt_statement(self):
1662
+ act_lbl = _section_label("Act 8 — The Formal Statement")
1663
+ act_lbl.to_corner(LEFT + UP, buff=0.22)
1664
+ self.play(FadeIn(act_lbl, run_time=0.4))
1665
+
1666
+ stmt = _CLTStatement()
1667
+ stmt.scale(0.94)
1668
+ stmt.move_to([0, 0.10, 0])
1669
+ stmt.set_opacity(0)
1670
+
1671
+ self.play(FadeIn(stmt, shift=UP*0.15, run_time=1.2))
1672
+ self.wait(0.5)
1673
+
1674
+ # Highlight formula terms one by one
1675
+ highlight_sequence = [
1676
+ (0, P["f_xbar"], "sample mean"),
1677
+ (2, P["f_mu"], "population mean"),
1678
+ (4, P["f_sigma"], "population std dev"),
1679
+ (7, P["f_norm"], "standard normal"),
1680
+ (9, P["f_n"], "n → ∞"),
1681
+ ]
1682
+ for idx, col, _ in highlight_sequence:
1683
+ if idx < len(stmt.sym_pieces):
1684
+ self.play(
1685
+ Indicate(stmt.sym_pieces[idx],
1686
+ color=col,
1687
+ scale_factor=1.18,
1688
+ run_time=0.55),
1689
+ )
1690
+ self.wait(0.10)
1691
+ self.wait(0.7)
1692
+
1693
+ # Legend for colour codes
1694
+ legend_items = [
1695
+ (P["f_xbar"], "X̄ = sample mean"),
1696
+ (P["f_mu"], "μ = population mean"),
1697
+ (P["f_sigma"], "σ = population std dev"),
1698
+ (P["f_n"], "n = sample size"),
1699
+ (P["f_norm"], "N(0,1) = standard normal"),
1700
+ ]
1701
+ legend = VGroup()
1702
+ for j, (col, txt) in enumerate(legend_items):
1703
+ dot = Dot(radius=0.06,
1704
+ point=[-4.30, -2.20 + j*0.32, 0.001],
1705
+ color=col, fill_opacity=1.0)
1706
+ lbl = Text(txt, font_size=13, color=col)
1707
+ lbl.move_to([-3.60 + lbl.width/2, -2.20 + j*0.32, 0.001])
1708
+ legend.add(dot, lbl)
1709
+ self.play(FadeIn(legend, run_time=0.7))
1710
+ self.wait(1.0)
1711
+
1712
+ # Closing statement
1713
+ closing = Text(
1714
+ "This is why the normal distribution appears everywhere in statistics.",
1715
+ font_size=22, color=P["title"],
1716
+ )
1717
+ closing.move_to([0, -3.30, 0])
1718
+ self.play(Write(closing, run_time=1.2))
1719
+ self.wait(1.0)
1720
+
1721
+ self.play(
1722
+ FadeOut(stmt),
1723
+ FadeOut(legend),
1724
+ FadeOut(closing),
1725
+ FadeOut(act_lbl),
1726
+ run_time=0.70,
1727
+ )
1728
+
1729
+ # End card
1730
+ end_bg = Rectangle(width=16, height=9,
1731
+ fill_color=P["bg"],
1732
+ fill_opacity=1.0, stroke_width=0)
1733
+ end_title = Text("Central Limit Theorem",
1734
+ font_size=46, color=P["title"])
1735
+ try:
1736
+ end_sub = MathTex(
1737
+ r"\bar{X} \;\overset{d}{\longrightarrow}\; "
1738
+ r"\mathcal{N}\!\left(\mu,\,\frac{\sigma^2}{n}\right)",
1739
+ font_size=34, color=P["f_norm"],
1740
+ )
1741
+ except Exception:
1742
+ end_sub = Text("X̄ → N(μ, σ²/n)", font_size=28,
1743
+ color=P["f_norm"])
1744
+ end_title.move_to([0, 0.55, 0])
1745
+ end_sub.move_to([0, -0.45, 0])
1746
+
1747
+ self.play(
1748
+ FadeIn(end_bg, run_time=0.5),
1749
+ FadeIn(end_title, run_time=0.7),
1750
+ )
1751
+ self.play(FadeIn(end_sub,
1752
+ rate_func=rate_functions.ease_out_back,
1753
+ run_time=0.8))
1754
+ self.wait(2.0)
1755
+ self.play(FadeOut(VGroup(end_bg, end_title, end_sub)),
1756
+ run_time=0.9)