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,1852 @@
1
+ """
2
+ statanim/animations/clt_demo.py
3
+ ====================================
4
+ Central Limit Theorem demonstration animations.
5
+
6
+ Pedagogical structure
7
+ ---------------------
8
+ The CLT demo is organised as a sequence of self-contained *phases*,
9
+ each teaching one aspect of the theorem. A full run proceeds:
10
+
11
+ Phase 0 – Population
12
+ Display the source distribution as a 3D histogram with PDF
13
+ overlay. Clearly label that it is NOT normal (Uniform,
14
+ Exponential, Bimodal, etc.).
15
+
16
+ Phase 1 – Single sample draw
17
+ Animated particles fall from population bars into a sample
18
+ collection zone. Sample size n shown live. x̄ computed and
19
+ annotated as the particles merge to a single point.
20
+
21
+ Phase 2 – Accumulate sample means
22
+ Repeat Phase 1 silently k times, each trial adding one bar to a
23
+ growing histogram of x̄ values. Bars colour-coded by distance
24
+ from the theoretical mean.
25
+
26
+ Phase 3 – Normal convergence
27
+ Once ≥ 30 trials are accumulated, a normal curve (μ, σ/√n)
28
+ emerges over the x̄ histogram. The fit improves visually.
29
+
30
+ Phase 4 – n-sweep
31
+ Repeat the full accumulation for n = 1, 2, 5, 10, 30, 100,
32
+ showing the x̄ histogram narrowing as 1/√n. σ/√n annotation
33
+ updates live.
34
+
35
+ Phase 4 produces the most visually striking proof of the theorem.
36
+
37
+ Classes
38
+ -------
39
+ CLTConfig
40
+ PopulationDistribution3D
41
+ SampleMeanHistogram3D
42
+ NormalConvergenceOverlay3D
43
+ CLTDemo
44
+
45
+ Internals
46
+ ---------
47
+ _SampleParticle3D
48
+ _VarianceAnnotation3D
49
+ _SampleDrawAnimation
50
+
51
+ Ready-to-render ThreeDScene subclasses
52
+ --------------------------------------
53
+ CLTUniformScene
54
+ CLTExponentialScene
55
+ CLTBimodalScene
56
+ CLTSweepScene
57
+ CLTComparisonScene
58
+
59
+ Usage
60
+ -----
61
+ # Render from the command line:
62
+ # manim -pql clt_demo.py CLTUniformScene
63
+
64
+ # Or embed phases into your own scene:
65
+ from statanim.animations.clt_demo import CLTDemo, CLTConfig
66
+
67
+ class MyScene(ThreeDScene):
68
+ def construct(self):
69
+ demo = CLTDemo(CLTConfig(
70
+ source="exponential", n=10, n_trials=200,
71
+ ))
72
+ demo.phase_population(self)
73
+ demo.phase_accumulate(self, n_visible=60)
74
+ demo.phase_normal_overlay(self)
75
+ """
76
+
77
+ from __future__ import annotations
78
+
79
+ from dataclasses import dataclass, field
80
+ from typing import (
81
+ List, Sequence, Tuple, Optional, Callable, Union, Dict
82
+ )
83
+ import numpy as np
84
+
85
+ from manim import (
86
+ # Mobjects
87
+ VGroup, VMobject, Polygon, Rectangle, Line, DashedLine,
88
+ Dot, Dot3D, Text, MathTex, Ellipse, Arrow,
89
+ # Scene
90
+ ThreeDScene,
91
+ # Animations
92
+ AnimationGroup, LaggedStart, Succession,
93
+ Create, FadeIn, FadeOut, Transform, MoveAlongPath,
94
+ UpdateFromAlphaFunc, Flash, Write, Indicate,
95
+ # Constants
96
+ DEGREES, PI, TAU,
97
+ RIGHT, LEFT, UP, DOWN, OUT, IN, ORIGIN,
98
+ X_AXIS, Y_AXIS, Z_AXIS,
99
+ WHITE, BLACK, GRAY, BLUE, GREEN, RED, YELLOW,
100
+ # Colour
101
+ ManimColor, color_to_rgb, rgba_to_color, color_to_rgba,
102
+ # Utilities
103
+ rate_functions, smooth,
104
+ # Camera
105
+ config as manim_config,
106
+ )
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Shared colour helpers
110
+ # ---------------------------------------------------------------------------
111
+
112
+ def _with_opacity(color: ManimColor, opacity: float) -> ManimColor:
113
+ r, g, b = color_to_rgb(color)
114
+ return rgba_to_color([r, g, b, max(0.0, min(1.0, opacity))])
115
+
116
+ def _darken(color: ManimColor, factor: float = 0.65) -> ManimColor:
117
+ r, g, b = color_to_rgb(color)
118
+ return ManimColor([r * factor, g * factor, b * factor])
119
+
120
+ def _lighten(color: ManimColor, factor: float = 1.35) -> ManimColor:
121
+ r, g, b = color_to_rgb(color)
122
+ return ManimColor([min(r * factor, 1.0), min(g * factor, 1.0), min(b * factor, 1.0)])
123
+
124
+ def _lerp_color(a: ManimColor, b: ManimColor, t: float) -> ManimColor:
125
+ ra, ga, ba = color_to_rgb(a)
126
+ rb, gb, bb = color_to_rgb(b)
127
+ return ManimColor([ra + (rb - ra) * t, ga + (gb - ga) * t, ba + (bb - ba) * t])
128
+
129
+ def _normal_pdf(x: np.ndarray, mu: float, sigma: float) -> np.ndarray:
130
+ return np.exp(-0.5 * ((x - mu) / sigma) ** 2) / (sigma * np.sqrt(TAU))
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # CLTConfig
135
+ # ---------------------------------------------------------------------------
136
+
137
+ @dataclass
138
+ class CLTConfig:
139
+ """Complete configuration for a CLT demonstration.
140
+
141
+ Source distribution
142
+ ~~~~~~~~~~~~~~~~~~~
143
+ ``source`` selects the population distribution:
144
+ - ``"uniform"`` – U(lo, hi).
145
+ - ``"exponential"`` – Exp(rate).
146
+ - ``"bimodal"`` – mixture of two normals.
147
+ - ``"bernoulli"`` – Bernoulli(p). Extreme discrete skew.
148
+ - ``"pareto"`` – Pareto(shape). Heavy tail.
149
+
150
+ Sampling
151
+ ~~~~~~~~
152
+ ``n`` : sample size per trial (the key CLT parameter).
153
+ ``n_trials``: total number of x̄ trials to simulate.
154
+ ``rng_seed``: reproducibility.
155
+
156
+ Layout
157
+ ~~~~~~
158
+ ``pop_x`` : x-position of the population histogram.
159
+ ``xbar_x`` : x-position of the x̄ histogram.
160
+ ``hist_width``: scene-unit width of both histograms.
161
+ ``hist_depth``: scene-unit depth (y) of bars.
162
+ ``z_scale`` : value → scene-unit height multiplier.
163
+ ``n_bins`` : number of histogram bins.
164
+
165
+ Visual
166
+ ~~~~~~
167
+ ``pop_color`` : population histogram bar colour.
168
+ ``xbar_color_lo`` : x̄ histogram colour for bars near the mean.
169
+ ``xbar_color_hi`` : x̄ histogram colour for bars far from the mean.
170
+ ``normal_color`` : convergence curve colour.
171
+ ``particle_color``: colour of animated sample particles.
172
+ ``glow_normal`` : whether to add a glow halo to the normal curve.
173
+
174
+ Attributes
175
+ ----------
176
+ source : str
177
+ n : int
178
+ n_trials : int
179
+ rng_seed : int
180
+ pop_params : dict
181
+ Distribution-specific parameters fed to the sampler.
182
+ pop_x : float
183
+ xbar_x : float
184
+ hist_width : float
185
+ hist_depth : float
186
+ z_scale : float
187
+ n_bins : int
188
+ pop_color : ManimColor
189
+ xbar_color_lo : ManimColor
190
+ xbar_color_hi : ManimColor
191
+ normal_color : ManimColor
192
+ particle_color : ManimColor
193
+ glow_normal : bool
194
+ show_formula_panel : bool
195
+ show_variance_annotation : bool
196
+ show_source_label : bool
197
+ """
198
+
199
+ source: str = "uniform"
200
+ n: int = 10
201
+ n_trials: int = 300
202
+ rng_seed: int = 42
203
+ pop_params: Dict = field(default_factory=dict)
204
+
205
+ pop_x: float = -2.5
206
+ xbar_x: float = 2.5
207
+ hist_width: float = 4.0
208
+ hist_depth: float = 0.45
209
+ z_scale: float = 0.9
210
+ n_bins: int = 25
211
+
212
+ pop_color: ManimColor = ManimColor("#4A90D9")
213
+ xbar_color_lo: ManimColor = ManimColor("#2DAA6E")
214
+ xbar_color_hi: ManimColor = ManimColor("#E0AA40")
215
+ normal_color: ManimColor = ManimColor("#E8593C")
216
+ particle_color: ManimColor = ManimColor("#FFD700")
217
+ glow_normal: bool = True
218
+
219
+ show_formula_panel: bool = True
220
+ show_variance_annotation: bool = True
221
+ show_source_label: bool = True
222
+
223
+
224
+ # ---------------------------------------------------------------------------
225
+ # Sampler helpers
226
+ # ---------------------------------------------------------------------------
227
+
228
+ def _make_sampler(
229
+ source: str,
230
+ params: Dict,
231
+ rng: np.random.Generator,
232
+ ) -> Callable[[int], np.ndarray]:
233
+ """Return a callable ``sampler(n)`` for the given distribution.
234
+
235
+ Parameters
236
+ ----------
237
+ source : str
238
+ Distribution name.
239
+ params : dict
240
+ Distribution-specific keyword parameters.
241
+ rng : np.random.Generator
242
+
243
+ Returns
244
+ -------
245
+ Callable[[int], np.ndarray]
246
+ Function that draws n samples and returns a 1-D array.
247
+ """
248
+ if source == "uniform":
249
+ lo = params.get("lo", 0.0)
250
+ hi = params.get("hi", 1.0)
251
+ return lambda n: rng.uniform(lo, hi, n)
252
+
253
+ elif source == "exponential":
254
+ rate = params.get("rate", 1.0)
255
+ return lambda n: rng.exponential(1.0 / rate, n)
256
+
257
+ elif source == "bimodal":
258
+ mu1 = params.get("mu1", -2.0)
259
+ mu2 = params.get("mu2", 2.0)
260
+ std1 = params.get("std1", 0.6)
261
+ std2 = params.get("std2", 0.6)
262
+ w = params.get("weight", 0.5)
263
+ def _bimodal(n):
264
+ mask = rng.random(n) < w
265
+ a = rng.normal(mu1, std1, n)
266
+ b = rng.normal(mu2, std2, n)
267
+ return np.where(mask, a, b)
268
+ return _bimodal
269
+
270
+ elif source == "bernoulli":
271
+ p = params.get("p", 0.2)
272
+ return lambda n: rng.binomial(1, p, n).astype(float)
273
+
274
+ elif source == "pareto":
275
+ shape = params.get("shape", 1.5)
276
+ # scipy-style: X = (np.random.pareto(shape) + 1)
277
+ return lambda n: (rng.pareto(shape, n) + 1.0)
278
+
279
+ else:
280
+ raise ValueError(f"Unknown source distribution: {source!r}")
281
+
282
+
283
+ def _population_range(source: str, params: Dict) -> Tuple[float, float]:
284
+ """Return a sensible (x_min, x_max) for the population histogram."""
285
+ if source == "uniform":
286
+ return params.get("lo", 0.0), params.get("hi", 1.0)
287
+ elif source == "exponential":
288
+ rate = params.get("rate", 1.0)
289
+ return 0.0, 5.0 / rate
290
+ elif source == "bimodal":
291
+ mu1 = params.get("mu1", -2.0)
292
+ mu2 = params.get("mu2", 2.0)
293
+ std = max(params.get("std1", 0.6), params.get("std2", 0.6))
294
+ return mu1 - 3 * std, mu2 + 3 * std
295
+ elif source == "bernoulli":
296
+ return -0.3, 1.3
297
+ elif source == "pareto":
298
+ return 1.0, 6.0
299
+ else:
300
+ return 0.0, 4.0
301
+
302
+
303
+ def _theoretical_mean_std(
304
+ source: str,
305
+ params: Dict,
306
+ n: int,
307
+ ) -> Tuple[float, float]:
308
+ """Return (population_mean, population_std) for the source."""
309
+ if source == "uniform":
310
+ lo, hi = params.get("lo", 0.0), params.get("hi", 1.0)
311
+ mu = (lo + hi) / 2
312
+ sigma = (hi - lo) / np.sqrt(12)
313
+ elif source == "exponential":
314
+ rate = params.get("rate", 1.0)
315
+ mu = 1.0 / rate
316
+ sigma = 1.0 / rate
317
+ elif source == "bimodal":
318
+ mu1 = params.get("mu1", -2.0)
319
+ mu2 = params.get("mu2", 2.0)
320
+ w = params.get("weight", 0.5)
321
+ mu = w * mu1 + (1 - w) * mu2
322
+ # var = E[X²] − μ²
323
+ std1 = params.get("std1", 0.6)
324
+ std2 = params.get("std2", 0.6)
325
+ ex2 = w * (mu1**2 + std1**2) + (1 - w) * (mu2**2 + std2**2)
326
+ sigma = np.sqrt(ex2 - mu**2)
327
+ elif source == "bernoulli":
328
+ p = params.get("p", 0.2)
329
+ mu = p
330
+ sigma = np.sqrt(p * (1 - p))
331
+ elif source == "pareto":
332
+ shape = params.get("shape", 1.5)
333
+ if shape > 1:
334
+ mu = shape / (shape - 1)
335
+ else:
336
+ mu = float("inf")
337
+ if shape > 2:
338
+ sigma = np.sqrt(shape / ((shape - 1)**2 * (shape - 2)))
339
+ else:
340
+ sigma = float("inf")
341
+ else:
342
+ mu, sigma = 0.5, 1.0
343
+
344
+ return float(mu), float(sigma)
345
+
346
+
347
+ # ---------------------------------------------------------------------------
348
+ # _SampleParticle3D (internal)
349
+ # ---------------------------------------------------------------------------
350
+
351
+ class _SampleParticle3D(VGroup):
352
+ """A single glowing dot representing one drawn observation.
353
+
354
+ Used in ``_SampleDrawAnimation``. Starts at a position inside
355
+ the population bar for its value, moves to the sample collection
356
+ zone, then merges with other particles to form x̄.
357
+
358
+ Parameters
359
+ ----------
360
+ start_pos : np.ndarray
361
+ Where the particle originates (centre of the source bar).
362
+ end_pos : np.ndarray
363
+ Where the particle lands in the sample zone.
364
+ color : ManimColor
365
+ radius : float
366
+ """
367
+
368
+ def __init__(
369
+ self,
370
+ start_pos: np.ndarray,
371
+ end_pos: np.ndarray,
372
+ color: ManimColor = ManimColor("#FFD700"),
373
+ radius: float = 0.06,
374
+ **kwargs,
375
+ ):
376
+ super().__init__(**kwargs)
377
+ self.start_pos = np.array(start_pos, dtype=float)
378
+ self.end_pos = np.array(end_pos, dtype=float)
379
+ self.dot = Dot3D(point=start_pos, radius=radius, color=color)
380
+ self.glow = Dot3D(
381
+ point=start_pos,
382
+ radius=radius * 2.5,
383
+ color=_with_opacity(color, 0.15),
384
+ )
385
+ self.add(self.glow, self.dot)
386
+
387
+ def animate_fall(self, run_time: float = 0.45) -> UpdateFromAlphaFunc:
388
+ """Animate the particle moving from start to end position."""
389
+ start = self.start_pos.copy()
390
+ end = self.end_pos.copy()
391
+ # Arc: rise slightly then fall toward end
392
+ mid = (start + end) / 2 + np.array([0, 0, 0.6])
393
+
394
+ def updater(mob: _SampleParticle3D, alpha: float) -> None:
395
+ t = smooth(alpha)
396
+ # Quadratic Bezier
397
+ p = (1 - t)**2 * start + 2 * (1 - t) * t * mid + t**2 * end
398
+ mob.dot.move_to(p)
399
+ mob.glow.move_to(p)
400
+
401
+ return UpdateFromAlphaFunc(self, updater, run_time=run_time)
402
+
403
+
404
+ # ---------------------------------------------------------------------------
405
+ # _VarianceAnnotation3D (internal)
406
+ # ---------------------------------------------------------------------------
407
+
408
+ class _VarianceAnnotation3D(VGroup):
409
+ """Floating annotation showing σ/√n and the current n value.
410
+
411
+ Used in Phase 4 (n-sweep). The annotation updates live as n changes.
412
+
413
+ Parameters
414
+ ----------
415
+ mu : float
416
+ Theoretical mean.
417
+ sigma : float
418
+ Population standard deviation.
419
+ n : int
420
+ Current sample size.
421
+ position : np.ndarray
422
+ 3D scene position.
423
+ scene : ThreeDScene or None
424
+ """
425
+
426
+ def __init__(
427
+ self,
428
+ mu: float,
429
+ sigma: float,
430
+ n: int,
431
+ position: np.ndarray = ORIGIN,
432
+ color: ManimColor = WHITE,
433
+ font_size: int = 22,
434
+ scene: Optional[ThreeDScene] = None,
435
+ **kwargs,
436
+ ):
437
+ super().__init__(**kwargs)
438
+ self._mu = mu
439
+ self._sigma = sigma
440
+ self._n = n
441
+ self._pos = np.array(position, dtype=float)
442
+ self._color = color
443
+ self._font_size = font_size
444
+ self._scene = scene
445
+ self._labels: List[Text] = []
446
+ self._build()
447
+
448
+ def _se(self) -> float:
449
+ return self._sigma / np.sqrt(max(self._n, 1))
450
+
451
+ def _build(self) -> None:
452
+ """Construct the text labels."""
453
+ se = self._se()
454
+ lines = [
455
+ f"n = {self._n}",
456
+ f"σ/√n = {se:.3f}",
457
+ f"μ = {self._mu:.3f}",
458
+ ]
459
+ for i, txt in enumerate(lines):
460
+ lbl = Text(txt, font_size=self._font_size, color=self._color)
461
+ lbl.move_to(self._pos + np.array([0, 0, -i * 0.32]))
462
+ self._labels.append(lbl)
463
+ self.add(lbl)
464
+ if self._scene is not None:
465
+ for lbl in self._labels:
466
+ self._scene.add_fixed_orientation_mobjects(lbl)
467
+
468
+ def update_n(
469
+ self,
470
+ new_n: int,
471
+ scene: ThreeDScene,
472
+ run_time: float = 0.35,
473
+ ) -> AnimationGroup:
474
+ """Animate the annotation updating to a new n value.
475
+
476
+ Returns an ``AnimationGroup`` that fades out the old labels
477
+ and fades in new ones.
478
+ """
479
+ self._n = new_n
480
+ old_labels = list(self._labels)
481
+
482
+ # Remove old
483
+ self._labels.clear()
484
+ for lbl in old_labels:
485
+ self.remove(lbl)
486
+
487
+ # Build new
488
+ se = self._se()
489
+ new_lines = [
490
+ f"n = {self._n}",
491
+ f"σ/√n = {se:.3f}",
492
+ f"μ = {self._mu:.3f}",
493
+ ]
494
+ new_label_mobs = []
495
+ for i, txt in enumerate(new_lines):
496
+ lbl = Text(txt, font_size=self._font_size, color=self._color)
497
+ lbl.move_to(self._pos + np.array([0, 0, -i * 0.32]))
498
+ new_label_mobs.append(lbl)
499
+ self._labels.append(lbl)
500
+ self.add(lbl)
501
+ if self._scene is not None:
502
+ for lbl in new_label_mobs:
503
+ self._scene.add_fixed_orientation_mobjects(lbl)
504
+
505
+ return AnimationGroup(
506
+ *[FadeOut(lbl, run_time=run_time * 0.5) for lbl in old_labels],
507
+ *[FadeIn(lbl, run_time=run_time) for lbl in new_label_mobs],
508
+ )
509
+
510
+
511
+ # ---------------------------------------------------------------------------
512
+ # PopulationDistribution3D
513
+ # ---------------------------------------------------------------------------
514
+
515
+ class PopulationDistribution3D(VGroup):
516
+ """3D histogram of the population distribution.
517
+
518
+ Displays the source distribution as a bar histogram (not a PDF curve)
519
+ so the student clearly sees its non-normal shape. An optional PDF
520
+ overlay shows the theoretical density.
521
+
522
+ Visual layers
523
+ ~~~~~~~~~~~~~
524
+ - ``bars`` : VGroup of 3-faced prism bars (front/right/top shaded).
525
+ - ``pdf_line``: VMobject PDF curve drawn over the bars (optional).
526
+ - ``title`` : floating label naming the distribution.
527
+ - ``x_axis`` : tick marks along the base.
528
+
529
+ Parameters
530
+ ----------
531
+ cfg : CLTConfig
532
+ The full demo config. Uses ``cfg.source``, ``cfg.pop_params``,
533
+ ``cfg.pop_x``, ``cfg.hist_width``, ``cfg.hist_depth``,
534
+ ``cfg.z_scale``, ``cfg.n_bins``, ``cfg.pop_color``.
535
+ n_population : int
536
+ Number of samples to draw for the histogram (large → smooth).
537
+ show_pdf : bool
538
+ If True, draw a theoretical PDF curve over the bars.
539
+ scene : ThreeDScene or None
540
+ """
541
+
542
+ # Source → human-readable name
543
+ SOURCE_NAMES: Dict[str, str] = {
544
+ "uniform": "Uniform distribution",
545
+ "exponential": "Exponential distribution",
546
+ "bimodal": "Bimodal mixture",
547
+ "bernoulli": "Bernoulli distribution",
548
+ "pareto": "Pareto distribution",
549
+ }
550
+
551
+ def __init__(
552
+ self,
553
+ cfg: CLTConfig,
554
+ n_population: int = 5000,
555
+ show_pdf: bool = True,
556
+ scene: Optional[ThreeDScene] = None,
557
+ **kwargs,
558
+ ):
559
+ super().__init__(**kwargs)
560
+
561
+ self.cfg = cfg
562
+ self._scene = scene
563
+
564
+ rng = np.random.default_rng(cfg.rng_seed + 9999)
565
+ sampler = _make_sampler(cfg.source, cfg.pop_params, rng)
566
+ pop_data = sampler(n_population)
567
+
568
+ x_min, x_max = _population_range(cfg.source, cfg.pop_params)
569
+ # Clamp data to visible range
570
+ pop_data = np.clip(pop_data, x_min, x_max)
571
+
572
+ # Histogram
573
+ counts, bin_edges = np.histogram(pop_data, bins=cfg.n_bins,
574
+ range=(x_min, x_max))
575
+ counts = counts / counts.max() # normalise to [0,1]
576
+
577
+ bar_w = (x_max - x_min) / cfg.n_bins
578
+ scene_bar_w = cfg.hist_width / cfg.n_bins
579
+
580
+ self.bars = VGroup()
581
+ self._bin_centers_scene: List[float] = []
582
+ self._bar_heights: List[float] = []
583
+
584
+ col_base = cfg.pop_color
585
+ col_right = _darken(col_base, 0.60)
586
+ col_top = _lighten(col_base, 1.30)
587
+
588
+ for i, count in enumerate(counts):
589
+ h = max(count * cfg.z_scale * 4.0, 0.01)
590
+ bin_center_data = bin_edges[i] + bar_w / 2
591
+ # Map data x to scene x
592
+ t = (bin_center_data - x_min) / (x_max - x_min)
593
+ scene_x = cfg.pop_x + (t - 0.5) * cfg.hist_width
594
+
595
+ self._bin_centers_scene.append(scene_x)
596
+ self._bar_heights.append(h)
597
+
598
+ # Build 3-faced prism bar
599
+ hw = scene_bar_w / 2 * 0.88 # small gap between bars
600
+ hd = cfg.hist_depth / 2
601
+ x, y = scene_x, 0.0
602
+ z0, z1 = 0.0, h
603
+
604
+ face_front = Polygon(
605
+ np.array([x - hw, y - hd, z0]),
606
+ np.array([x + hw, y - hd, z0]),
607
+ np.array([x + hw, y - hd, z1]),
608
+ np.array([x - hw, y - hd, z1]),
609
+ fill_color=_with_opacity(col_base, 0.88),
610
+ fill_opacity=1.0, stroke_width=0,
611
+ )
612
+ face_right = Polygon(
613
+ np.array([x + hw, y - hd, z0]),
614
+ np.array([x + hw, y + hd, z0]),
615
+ np.array([x + hw, y + hd, z1]),
616
+ np.array([x + hw, y - hd, z1]),
617
+ fill_color=_with_opacity(col_right, 0.85),
618
+ fill_opacity=1.0, stroke_width=0,
619
+ )
620
+ face_top = Polygon(
621
+ np.array([x - hw, y - hd, z1]),
622
+ np.array([x + hw, y - hd, z1]),
623
+ np.array([x + hw, y + hd, z1]),
624
+ np.array([x - hw, y + hd, z1]),
625
+ fill_color=_with_opacity(col_top, 0.80),
626
+ fill_opacity=1.0, stroke_width=0,
627
+ )
628
+ bar = VGroup(face_front, face_right, face_top)
629
+ self.bars.add(bar)
630
+
631
+ self.add(self.bars)
632
+
633
+ # PDF overlay curve
634
+ self.pdf_line = VGroup()
635
+ if show_pdf:
636
+ self.pdf_line = self._build_pdf_curve(x_min, x_max, pop_data)
637
+ self.add(self.pdf_line)
638
+
639
+ # Distribution title
640
+ if cfg.show_source_label:
641
+ self._build_title(scene)
642
+
643
+ # X-axis tick marks
644
+ self._build_x_axis(x_min, x_max, scene)
645
+
646
+ # ------------------------------------------------------------------
647
+
648
+ def _build_pdf_curve(
649
+ self,
650
+ x_min: float,
651
+ x_max: float,
652
+ pop_data: np.ndarray,
653
+ ) -> VMobject:
654
+ """Build a smoothed density curve matching the histogram scale."""
655
+ xs_data = np.linspace(x_min, x_max, 200)
656
+ # Kernel density estimate using histogram heights as proxy
657
+ # (avoids scipy dependency)
658
+ bandwidth = (x_max - x_min) / 20.0
659
+
660
+ # Gaussian KDE manually
661
+ kde_vals = np.zeros(len(xs_data))
662
+ step = (x_max - x_min) / self.cfg.n_bins
663
+ for i, (h, bc) in enumerate(zip(self._bar_heights, self._bin_centers_scene)):
664
+ # Convert scene x back to data x for this bar
665
+ t = (bc - self.cfg.pop_x) / self.cfg.hist_width + 0.5
666
+ bc_data = x_min + t * (x_max - x_min)
667
+ kde_vals += h * np.exp(-0.5 * ((xs_data - bc_data) / bandwidth) ** 2)
668
+
669
+ kde_vals = kde_vals / kde_vals.max() * max(self._bar_heights) * 1.05
670
+
671
+ pts_3d = []
672
+ for xd, kv in zip(xs_data, kde_vals):
673
+ t = (xd - x_min) / (x_max - x_min)
674
+ sx = self.cfg.pop_x + (t - 0.5) * self.cfg.hist_width
675
+ pts_3d.append(np.array([sx, -self.cfg.hist_depth / 2, max(kv, 0.0)]))
676
+
677
+ curve = VMobject()
678
+ curve.set_points_as_corners(pts_3d)
679
+ curve.set_stroke(
680
+ color=_with_opacity(_lighten(self.cfg.pop_color, 1.50), 0.85),
681
+ width=2.2,
682
+ )
683
+ curve.set_fill(opacity=0)
684
+ return curve
685
+
686
+ def _build_title(self, scene: Optional[ThreeDScene]) -> None:
687
+ name = self.SOURCE_NAMES.get(self.cfg.source, self.cfg.source)
688
+ lbl = Text(name, font_size=20, color=_with_opacity(self.cfg.pop_color, 0.80))
689
+ lbl.move_to(np.array([self.cfg.pop_x, 0, -0.45]))
690
+ self.title = VGroup(lbl)
691
+ if scene is not None:
692
+ scene.add_fixed_orientation_mobjects(lbl)
693
+ self.add(self.title)
694
+
695
+ def _build_x_axis(
696
+ self,
697
+ x_min: float,
698
+ x_max: float,
699
+ scene: Optional[ThreeDScene],
700
+ ) -> None:
701
+ """Draw a few tick marks below the histogram baseline."""
702
+ n_ticks = 5
703
+ self.x_axis = VGroup()
704
+ for i in range(n_ticks + 1):
705
+ t = i / n_ticks
706
+ val = x_min + t * (x_max - x_min)
707
+ sx = self.cfg.pop_x + (t - 0.5) * self.cfg.hist_width
708
+ y = -self.cfg.hist_depth / 2
709
+
710
+ tick = Line(
711
+ np.array([sx, y, -0.04]),
712
+ np.array([sx, y, 0.04]),
713
+ color=_with_opacity(WHITE, 0.40),
714
+ stroke_width=1.0,
715
+ )
716
+ lbl = Text(f"{val:.1f}", font_size=14,
717
+ color=_with_opacity(WHITE, 0.45))
718
+ lbl.move_to(np.array([sx, y, -0.22]))
719
+ self.x_axis.add(tick)
720
+ self.x_axis.add(lbl)
721
+ if scene is not None:
722
+ scene.add_fixed_orientation_mobjects(lbl)
723
+ self.add(self.x_axis)
724
+
725
+ # ------------------------------------------------------------------
726
+ # Animations
727
+ # ------------------------------------------------------------------
728
+
729
+ def animate_build(
730
+ self,
731
+ lag: float = 0.018,
732
+ run_time_per_bar: float = 0.35,
733
+ ) -> LaggedStart:
734
+ """Grow bars left-to-right from the baseline."""
735
+ anims = []
736
+ for bar in self.bars:
737
+ # Each bar is a VGroup(front, right, top)
738
+ anims.append(FadeIn(bar, shift=UP * 0.0, run_time=run_time_per_bar))
739
+ return LaggedStart(*anims, lag_ratio=lag)
740
+
741
+ def get_bar_top_position(self, bin_index: int) -> np.ndarray:
742
+ """Return the 3D top-centre of bar at *bin_index* (for particle origin)."""
743
+ sx = self._bin_centers_scene[bin_index]
744
+ h = self._bar_heights[bin_index]
745
+ return np.array([sx, -self.cfg.hist_depth / 2, h])
746
+
747
+
748
+ # ---------------------------------------------------------------------------
749
+ # SampleMeanHistogram3D
750
+ # ---------------------------------------------------------------------------
751
+
752
+ class SampleMeanHistogram3D(VGroup):
753
+ """A live-growing histogram of accumulated sample means (x̄ values).
754
+
755
+ Bars are built incrementally: each call to ``add_sample_mean``
756
+ recomputes the bin and updates the affected bar in place.
757
+
758
+ Bars are colour-coded by distance from the theoretical mean:
759
+ bars close to the mean use ``cfg.xbar_color_lo``,
760
+ bars far from the mean use ``cfg.xbar_color_hi``.
761
+
762
+ Visual layers
763
+ ~~~~~~~~~~~~~
764
+ - ``bars`` : Dict[int, VGroup] — one prism per active bin.
765
+ - ``normal_curve``: VMobject — appears after ``show_normal_overlay``.
766
+ - ``title`` : "Distribution of x̄" label.
767
+
768
+ Parameters
769
+ ----------
770
+ cfg : CLTConfig
771
+ mu : float
772
+ Theoretical population mean.
773
+ sigma : float
774
+ Theoretical population standard deviation.
775
+ scene : ThreeDScene or None
776
+ """
777
+
778
+ def __init__(
779
+ self,
780
+ cfg: CLTConfig,
781
+ mu: float,
782
+ sigma: float,
783
+ scene: Optional[ThreeDScene] = None,
784
+ **kwargs,
785
+ ):
786
+ super().__init__(**kwargs)
787
+
788
+ self.cfg = cfg
789
+ self.mu = mu
790
+ self.sigma = sigma
791
+ self._scene = scene
792
+ self._se = sigma / np.sqrt(max(cfg.n, 1))
793
+
794
+ # Determine histogram range: μ ± 4 σ/√n (covers the x̄ distribution)
795
+ half_range = max(self._se * 4.5, sigma * 0.5)
796
+ self._x_min = mu - half_range
797
+ self._x_max = mu + half_range
798
+ self._bin_width = (self._x_max - self._x_min) / cfg.n_bins
799
+ self._scene_bar_w = cfg.hist_width / cfg.n_bins
800
+
801
+ # Internal state
802
+ self._counts: np.ndarray = np.zeros(cfg.n_bins, dtype=int)
803
+ self._max_count: int = 1
804
+ self._bar_mobs: Dict[int, VGroup] = {} # bin_index → prism VGroup
805
+ self._xbar_values: List[float] = []
806
+
807
+ self.bars = VGroup()
808
+ self.normal_curve = VGroup()
809
+ self.title = VGroup()
810
+
811
+ self.add(self.bars, self.normal_curve)
812
+ self._build_title(scene)
813
+ self._build_mean_line()
814
+
815
+ # ------------------------------------------------------------------
816
+
817
+ def _data_to_scene_x(self, val: float) -> float:
818
+ t = (val - self._x_min) / (self._x_max - self._x_min)
819
+ return self.cfg.xbar_x + (t - 0.5) * self.cfg.hist_width
820
+
821
+ def _bin_index(self, val: float) -> Optional[int]:
822
+ idx = int((val - self._x_min) / self._bin_width)
823
+ if 0 <= idx < self.cfg.n_bins:
824
+ return idx
825
+ return None
826
+
827
+ def _bar_color(self, bin_index: int) -> ManimColor:
828
+ """Colour based on distance from mean bin."""
829
+ mu_bin = (self.mu - self._x_min) / self._bin_width
830
+ dist = abs(bin_index - mu_bin) / (self.cfg.n_bins / 2)
831
+ dist = min(dist, 1.0)
832
+ return _lerp_color(self.cfg.xbar_color_lo, self.cfg.xbar_color_hi, dist)
833
+
834
+ def _build_bar_mob(self, bin_index: int, height: float) -> VGroup:
835
+ """Create a prism bar for *bin_index* at *height* scene units."""
836
+ sx = self.cfg.xbar_x + (
837
+ (bin_index + 0.5) / self.cfg.n_bins - 0.5
838
+ ) * self.cfg.hist_width
839
+ hw = self._scene_bar_w / 2 * 0.88
840
+ hd = self.cfg.hist_depth / 2
841
+ x, y = sx, 0.0
842
+ z0, z1 = 0.0, height
843
+
844
+ col_base = self._bar_color(bin_index)
845
+ col_right = _darken(col_base, 0.60)
846
+ col_top = _lighten(col_base, 1.28)
847
+
848
+ face_front = Polygon(
849
+ np.array([x - hw, y - hd, z0]),
850
+ np.array([x + hw, y - hd, z0]),
851
+ np.array([x + hw, y - hd, z1]),
852
+ np.array([x - hw, y - hd, z1]),
853
+ fill_color=_with_opacity(col_base, 0.90),
854
+ fill_opacity=1.0, stroke_width=0,
855
+ )
856
+ face_right = Polygon(
857
+ np.array([x + hw, y - hd, z0]),
858
+ np.array([x + hw, y + hd, z0]),
859
+ np.array([x + hw, y + hd, z1]),
860
+ np.array([x + hw, y - hd, z1]),
861
+ fill_color=_with_opacity(col_right, 0.88),
862
+ fill_opacity=1.0, stroke_width=0,
863
+ )
864
+ face_top = Polygon(
865
+ np.array([x - hw, y - hd, z1]),
866
+ np.array([x + hw, y - hd, z1]),
867
+ np.array([x + hw, y + hd, z1]),
868
+ np.array([x - hw, y + hd, z1]),
869
+ fill_color=_with_opacity(col_top, 0.80),
870
+ fill_opacity=1.0, stroke_width=0,
871
+ )
872
+ return VGroup(face_front, face_right, face_top)
873
+
874
+ def _update_bar(self, bin_index: int) -> None:
875
+ """Recompute bar height for *bin_index* and update its geometry."""
876
+ count = self._counts[bin_index]
877
+ height = (count / self._max_count) * self.cfg.z_scale * 4.0
878
+
879
+ sx = self.cfg.xbar_x + (
880
+ (bin_index + 0.5) / self.cfg.n_bins - 0.5
881
+ ) * self.cfg.hist_width
882
+ hw = self._scene_bar_w / 2 * 0.88
883
+ hd = self.cfg.hist_depth / 2
884
+ x, y = sx, 0.0
885
+ z0, z1 = 0.0, max(height, 0.01)
886
+
887
+ col_base = self._bar_color(bin_index)
888
+ col_right = _darken(col_base, 0.60)
889
+ col_top = _lighten(col_base, 1.28)
890
+
891
+ bar = self._bar_mobs[bin_index]
892
+ face_front, face_right, face_top = bar[0], bar[1], bar[2]
893
+
894
+ face_front.set_points_as_corners([
895
+ np.array([x - hw, y - hd, z0]),
896
+ np.array([x + hw, y - hd, z0]),
897
+ np.array([x + hw, y - hd, z1]),
898
+ np.array([x - hw, y - hd, z1]),
899
+ np.array([x - hw, y - hd, z0]),
900
+ ])
901
+ face_right.set_points_as_corners([
902
+ np.array([x + hw, y - hd, z0]),
903
+ np.array([x + hw, y + hd, z0]),
904
+ np.array([x + hw, y + hd, z1]),
905
+ np.array([x + hw, y - hd, z1]),
906
+ np.array([x + hw, y - hd, z0]),
907
+ ])
908
+ face_top.set_points_as_corners([
909
+ np.array([x - hw, y - hd, z1]),
910
+ np.array([x + hw, y - hd, z1]),
911
+ np.array([x + hw, y + hd, z1]),
912
+ np.array([x - hw, y + hd, z1]),
913
+ np.array([x - hw, y - hd, z1]),
914
+ ])
915
+
916
+ def _build_title(self, scene: Optional[ThreeDScene]) -> None:
917
+ lbl = Text("Distribution of x̄", font_size=20,
918
+ color=_with_opacity(self.cfg.xbar_color_lo, 0.80))
919
+ lbl.move_to(np.array([self.cfg.xbar_x, 0, -0.45]))
920
+ self.title = VGroup(lbl)
921
+ if scene is not None:
922
+ scene.add_fixed_orientation_mobjects(lbl)
923
+ self.add(self.title)
924
+
925
+ def _build_mean_line(self) -> None:
926
+ """Draw a faint vertical reference line at μ."""
927
+ sx = self._data_to_scene_x(self.mu)
928
+ hd = self.cfg.hist_depth / 2
929
+ self.mean_line = DashedLine(
930
+ np.array([sx, -hd, 0.0]),
931
+ np.array([sx, -hd, self.cfg.z_scale * 5.0]),
932
+ dash_length=0.07, dashed_ratio=0.4,
933
+ color=_with_opacity(WHITE, 0.28),
934
+ stroke_width=1.2,
935
+ )
936
+ self.add(self.mean_line)
937
+
938
+ # ------------------------------------------------------------------
939
+ # Data API
940
+ # ------------------------------------------------------------------
941
+
942
+ def add_sample_mean(
943
+ self,
944
+ xbar: float,
945
+ scene: Optional[ThreeDScene] = None,
946
+ animate: bool = False,
947
+ run_time: float = 0.12,
948
+ ) -> Optional[AnimationGroup]:
949
+ """Record one x̄ value, updating the histogram.
950
+
951
+ Parameters
952
+ ----------
953
+ xbar : float
954
+ The sample mean to add.
955
+ animate : bool
956
+ If True, return an animation that grows/updates the bar.
957
+ If False, update immediately (no animation).
958
+ run_time : float
959
+ Duration if animated.
960
+
961
+ Returns
962
+ -------
963
+ AnimationGroup or None
964
+ """
965
+ self._xbar_values.append(xbar)
966
+ idx = self._bin_index(xbar)
967
+ if idx is None:
968
+ return None
969
+
970
+ self._counts[idx] += 1
971
+ self._max_count = max(self._max_count, self._counts[idx])
972
+
973
+ # Rescale all bars if max changed
974
+ for i in self._bar_mobs:
975
+ self._update_bar(i)
976
+
977
+ if idx not in self._bar_mobs:
978
+ # New bar — create it
979
+ height = (self._counts[idx] / self._max_count) * self.cfg.z_scale * 4.0
980
+ bar = self._build_bar_mob(idx, max(height, 0.01))
981
+ self._bar_mobs[idx] = bar
982
+ self.bars.add(bar)
983
+
984
+ if animate:
985
+ return FadeIn(bar, run_time=run_time)
986
+ else:
987
+ self._update_bar(idx)
988
+
989
+ return None
990
+
991
+ def reset(self) -> None:
992
+ """Clear all accumulated data and bars."""
993
+ self._counts[:] = 0
994
+ self._max_count = 1
995
+ self._xbar_values.clear()
996
+ for bar in list(self._bar_mobs.values()):
997
+ self.bars.remove(bar)
998
+ self._bar_mobs.clear()
999
+ if len(self.normal_curve) > 0:
1000
+ self.remove(self.normal_curve)
1001
+ self.normal_curve = VGroup()
1002
+ self.add(self.normal_curve)
1003
+
1004
+ def build_normal_overlay(self) -> VMobject:
1005
+ """Build and return a normal PDF curve scaled to match current bars.
1006
+
1007
+ Call after enough trials are accumulated (≥ 30 recommended).
1008
+ """
1009
+ xbar_se = self.sigma / np.sqrt(max(self.cfg.n, 1))
1010
+ xs = np.linspace(self._x_min, self._x_max, 300)
1011
+ ys = _normal_pdf(xs, self.mu, xbar_se)
1012
+
1013
+ # Scale normal to match histogram max height
1014
+ max_bar_h = (self.cfg.z_scale * 4.0) if self._max_count < 1 else (
1015
+ self.cfg.z_scale * 4.0
1016
+ )
1017
+ ys_scaled = ys / ys.max() * max_bar_h if ys.max() > 0 else ys
1018
+
1019
+ pts = []
1020
+ for xd, zv in zip(xs, ys_scaled):
1021
+ sx = self._data_to_scene_x(xd)
1022
+ pts.append(np.array([sx, -self.cfg.hist_depth / 2, max(zv, 0.0)]))
1023
+
1024
+ curve = VMobject()
1025
+ curve.set_points_as_corners(pts)
1026
+ col = self.cfg.normal_color
1027
+ curve.set_stroke(color=_with_opacity(col, 0.92), width=2.8)
1028
+ curve.set_fill(opacity=0)
1029
+
1030
+ if self.cfg.glow_normal:
1031
+ glow = VMobject()
1032
+ glow.set_points_as_corners(pts)
1033
+ glow.set_stroke(color=_with_opacity(col, 0.15), width=9.0)
1034
+ glow.set_fill(opacity=0)
1035
+ self.normal_curve.add(glow)
1036
+
1037
+ self.normal_curve.add(curve)
1038
+ return curve
1039
+
1040
+ @property
1041
+ def n_samples(self) -> int:
1042
+ return len(self._xbar_values)
1043
+
1044
+ @property
1045
+ def empirical_mean(self) -> float:
1046
+ if not self._xbar_values:
1047
+ return self.mu
1048
+ return float(np.mean(self._xbar_values))
1049
+
1050
+ @property
1051
+ def empirical_std(self) -> float:
1052
+ if len(self._xbar_values) < 2:
1053
+ return self._se
1054
+ return float(np.std(self._xbar_values))
1055
+
1056
+
1057
+ # ---------------------------------------------------------------------------
1058
+ # NormalConvergenceOverlay3D
1059
+ # ---------------------------------------------------------------------------
1060
+
1061
+ class NormalConvergenceOverlay3D(VGroup):
1062
+ """Animated emergence of a normal curve over the x̄ histogram.
1063
+
1064
+ As n increases, the curve narrows visibly. This class handles
1065
+ a sequence of curves at different n values, morphing between them
1066
+ to show convergence.
1067
+
1068
+ Parameters
1069
+ ----------
1070
+ cfg : CLTConfig
1071
+ mu : float
1072
+ sigma : float
1073
+ hist : SampleMeanHistogram3D
1074
+ The histogram to overlay (provides coordinate mapping).
1075
+ n_values : list[int]
1076
+ Sequence of n values to show (e.g. [1, 2, 5, 10, 30]).
1077
+ """
1078
+
1079
+ def __init__(
1080
+ self,
1081
+ cfg: CLTConfig,
1082
+ mu: float,
1083
+ sigma: float,
1084
+ hist: SampleMeanHistogram3D,
1085
+ n_values: Optional[List[int]] = None,
1086
+ **kwargs,
1087
+ ):
1088
+ super().__init__(**kwargs)
1089
+ self.cfg = cfg
1090
+ self.mu = mu
1091
+ self.sigma = sigma
1092
+ self._hist = hist
1093
+ self._n_values = n_values or [1, 2, 5, 10, 30, 100]
1094
+ self._current_curve: Optional[VMobject] = None
1095
+
1096
+ def _make_curve_points(self, n: int) -> np.ndarray:
1097
+ se = self.sigma / np.sqrt(max(n, 1))
1098
+ half_range = se * 5.0
1099
+ x_min = self.mu - half_range
1100
+ x_max = self.mu + half_range
1101
+ xs = np.linspace(x_min, x_max, 300)
1102
+ ys = _normal_pdf(xs, self.mu, se)
1103
+ ys_scaled = ys / ys.max() * self.cfg.z_scale * 3.8 if ys.max() > 0 else ys
1104
+
1105
+ pts = []
1106
+ for xd, zv in zip(xs, ys_scaled):
1107
+ sx = self._hist._data_to_scene_x(xd)
1108
+ pts.append(np.array([sx, -self.cfg.hist_depth / 2, max(float(zv), 0.0)]))
1109
+ return np.array(pts)
1110
+
1111
+ def build_for_n(self, n: int) -> VMobject:
1112
+ """Build the normal curve for a given *n*."""
1113
+ pts = self._make_curve_points(n)
1114
+ col = self.cfg.normal_color
1115
+ curve = VMobject()
1116
+ curve.set_points_as_corners(pts)
1117
+ curve.set_stroke(color=_with_opacity(col, 0.90), width=2.8)
1118
+ curve.set_fill(opacity=0)
1119
+ return curve
1120
+
1121
+ def animate_narrow(
1122
+ self,
1123
+ scene: ThreeDScene,
1124
+ n_sequence: Optional[List[int]] = None,
1125
+ run_time_each: float = 1.0,
1126
+ hold_time: float = 0.5,
1127
+ ) -> None:
1128
+ """Play the sequence of narrowing curves directly on *scene*.
1129
+
1130
+ For each n in *n_sequence*, morphs the current curve to the
1131
+ new one. Call ``scene.play`` and ``scene.wait`` internally.
1132
+
1133
+ Parameters
1134
+ ----------
1135
+ n_sequence : list[int] or None
1136
+ Sequence of n values. Defaults to ``self._n_values``.
1137
+ """
1138
+ seq = n_sequence or self._n_values
1139
+ first_n = seq[0]
1140
+ first_curve = self.build_for_n(first_n)
1141
+ self.add(first_curve)
1142
+ scene.play(Create(first_curve, run_time=run_time_each * 0.6))
1143
+ self._current_curve = first_curve
1144
+
1145
+ for n in seq[1:]:
1146
+ new_curve = self.build_for_n(n)
1147
+ scene.play(
1148
+ Transform(self._current_curve, new_curve, run_time=run_time_each),
1149
+ )
1150
+ scene.wait(hold_time)
1151
+
1152
+
1153
+ # ---------------------------------------------------------------------------
1154
+ # CLTDemo — orchestrator
1155
+ # ---------------------------------------------------------------------------
1156
+
1157
+ class CLTDemo:
1158
+ """Orchestrator for a full Central Limit Theorem demonstration.
1159
+
1160
+ ``CLTDemo`` owns the configuration and all visual objects. Call
1161
+ ``phase_*`` methods in order to build the animation incrementally,
1162
+ or call ``run(scene)`` to execute all phases automatically.
1163
+
1164
+ Parameters
1165
+ ----------
1166
+ cfg : CLTConfig
1167
+ Full configuration for the demo.
1168
+
1169
+ Attributes
1170
+ ----------
1171
+ cfg : CLTConfig
1172
+ population : PopulationDistribution3D
1173
+ xbar_hist : SampleMeanHistogram3D
1174
+ variance_annotation : _VarianceAnnotation3D
1175
+ formula_panel : VGroup
1176
+ mu : float
1177
+ Theoretical population mean.
1178
+ sigma : float
1179
+ Theoretical population standard deviation.
1180
+ """
1181
+
1182
+ def __init__(self, cfg: CLTConfig) -> None:
1183
+ self.cfg = cfg
1184
+ rng = np.random.default_rng(cfg.rng_seed)
1185
+ self._sampler = _make_sampler(cfg.source, cfg.pop_params, rng)
1186
+ self.mu, self.sigma = _theoretical_mean_std(cfg.source, cfg.pop_params, cfg.n)
1187
+ self._rng = rng
1188
+
1189
+ # Visual objects — not yet added to any scene
1190
+ self.population: Optional[PopulationDistribution3D] = None
1191
+ self.xbar_hist: Optional[SampleMeanHistogram3D] = None
1192
+ self.variance_annotation: Optional[_VarianceAnnotation3D] = None
1193
+ self.formula_panel: VGroup = VGroup()
1194
+ self._all_xbars: List[float] = [] # pre-simulated
1195
+
1196
+ # Pre-simulate all trials for deterministic animation
1197
+ self._pre_simulate()
1198
+
1199
+ # ------------------------------------------------------------------
1200
+ # Pre-simulation
1201
+ # ------------------------------------------------------------------
1202
+
1203
+ def _pre_simulate(self) -> None:
1204
+ """Draw all n_trials × n samples upfront for reproducibility."""
1205
+ self._all_xbars = []
1206
+ for _ in range(self.cfg.n_trials):
1207
+ sample = self._sampler(self.cfg.n)
1208
+ self._all_xbars.append(float(sample.mean()))
1209
+
1210
+ # ------------------------------------------------------------------
1211
+ # Phase 0: Population
1212
+ # ------------------------------------------------------------------
1213
+
1214
+ def phase_population(
1215
+ self,
1216
+ scene: ThreeDScene,
1217
+ run_time_build: float = 1.5,
1218
+ show_pdf: bool = True,
1219
+ ) -> None:
1220
+ """Show the source distribution histogram and label it non-normal.
1221
+
1222
+ Parameters
1223
+ ----------
1224
+ scene : ThreeDScene
1225
+ run_time_build : float
1226
+ Duration of the histogram build animation.
1227
+ show_pdf : bool
1228
+ Whether to overlay the theoretical PDF curve.
1229
+ """
1230
+ self.population = PopulationDistribution3D(
1231
+ cfg=self.cfg,
1232
+ n_population=8000,
1233
+ show_pdf=show_pdf,
1234
+ scene=scene,
1235
+ )
1236
+ scene.add(self.population)
1237
+ scene.play(self.population.animate_build(run_time_per_bar=0.28))
1238
+ if show_pdf and len(self.population.pdf_line) > 0:
1239
+ scene.play(Create(self.population.pdf_line, run_time=0.8))
1240
+ scene.wait(0.5)
1241
+
1242
+ # ------------------------------------------------------------------
1243
+ # Phase 1: Single sample draw (particle animation)
1244
+ # ------------------------------------------------------------------
1245
+
1246
+ def phase_single_draw(
1247
+ self,
1248
+ scene: ThreeDScene,
1249
+ n_particles: Optional[int] = None,
1250
+ run_time_per_particle: float = 0.40,
1251
+ show_xbar_label: bool = True,
1252
+ ) -> None:
1253
+ """Animate one sample of size n being drawn from the population.
1254
+
1255
+ Particles fall from population bars to a collection zone,
1256
+ then merge into the sample mean x̄.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ n_particles : int or None
1261
+ Number of particles to show (default = cfg.n, capped at 15
1262
+ for visual clarity).
1263
+ """
1264
+ if self.population is None:
1265
+ raise RuntimeError("Call phase_population first.")
1266
+
1267
+ n_show = min(n_particles or self.cfg.n, 15)
1268
+ sample = self._sampler(self.cfg.n)
1269
+ xbar = float(sample.mean())
1270
+
1271
+ x_min, x_max = _population_range(self.cfg.source, self.cfg.pop_params)
1272
+
1273
+ # Collection zone: a line below the population histogram
1274
+ collect_y = -self.cfg.hist_depth / 2
1275
+ collect_z = -0.55
1276
+ particle_mobs: List[_SampleParticle3D] = []
1277
+
1278
+ # Show n_show particles falling one by one
1279
+ for i, val in enumerate(sample[:n_show]):
1280
+ # Find which bin this value lands in
1281
+ t = np.clip((val - x_min) / (x_max - x_min), 0, 1)
1282
+ bin_idx = int(t * self.cfg.n_bins)
1283
+ bin_idx = min(bin_idx, self.cfg.n_bins - 1)
1284
+
1285
+ start = self.population.get_bar_top_position(bin_idx)
1286
+
1287
+ # Spread particles along x in collection zone
1288
+ spread_x = self.cfg.pop_x + (t - 0.5) * self.cfg.hist_width * 0.85
1289
+ end = np.array([spread_x, collect_y, collect_z])
1290
+
1291
+ p = _SampleParticle3D(
1292
+ start_pos=start,
1293
+ end_pos=end,
1294
+ color=self.cfg.particle_color,
1295
+ )
1296
+ scene.add(p)
1297
+ particle_mobs.append(p)
1298
+ scene.play(p.animate_fall(run_time=run_time_per_particle), run_time=run_time_per_particle)
1299
+
1300
+ scene.wait(0.3)
1301
+
1302
+ # Merge all particles into xbar point
1303
+ xbar_pos = np.array([self.cfg.pop_x, collect_y, collect_z])
1304
+ merge_anims = []
1305
+ for p in particle_mobs:
1306
+ path = VMobject()
1307
+ path.set_points_as_corners([p.end_pos, xbar_pos])
1308
+ merge_anims.append(MoveAlongPath(p, path, run_time=0.35))
1309
+ scene.play(AnimationGroup(*merge_anims))
1310
+
1311
+ # Flash at xbar and show label
1312
+ merged_dot = Dot3D(point=xbar_pos, radius=0.10, color=self.cfg.particle_color)
1313
+ scene.add(merged_dot)
1314
+ scene.play(Flash(merged_dot, color=self.cfg.particle_color, flash_radius=0.35))
1315
+
1316
+ if show_xbar_label:
1317
+ lbl = Text(f"x̄ = {xbar:.3f}", font_size=22, color=self.cfg.particle_color)
1318
+ lbl.move_to(xbar_pos + np.array([-0.1, 0, 0.28]))
1319
+ scene.add_fixed_orientation_mobjects(lbl)
1320
+ scene.add(lbl)
1321
+ scene.play(FadeIn(lbl, run_time=0.35))
1322
+ scene.wait(1.0)
1323
+ scene.play(FadeOut(lbl, run_time=0.3))
1324
+
1325
+ # Clean up
1326
+ scene.play(*[FadeOut(p, run_time=0.25) for p in particle_mobs],
1327
+ FadeOut(merged_dot, run_time=0.25))
1328
+
1329
+ # ------------------------------------------------------------------
1330
+ # Phase 2: Accumulate x̄ values
1331
+ # ------------------------------------------------------------------
1332
+
1333
+ def phase_accumulate(
1334
+ self,
1335
+ scene: ThreeDScene,
1336
+ n_visible: int = 80,
1337
+ run_time_per_bar: float = 0.10,
1338
+ batch_silent: bool = True,
1339
+ ) -> None:
1340
+ """Add x̄ trials to the histogram one by one (first n_visible animated).
1341
+
1342
+ Parameters
1343
+ ----------
1344
+ n_visible : int
1345
+ Number of trials to add with visible bar updates.
1346
+ Remaining trials (up to n_trials) are added silently.
1347
+ run_time_per_bar : float
1348
+ Animation time for each visible bar addition.
1349
+ batch_silent : bool
1350
+ If True, add remaining trials all at once after the visible batch.
1351
+ """
1352
+ if self.xbar_hist is None:
1353
+ self.xbar_hist = SampleMeanHistogram3D(
1354
+ cfg=self.cfg, mu=self.mu, sigma=self.sigma, scene=scene
1355
+ )
1356
+ scene.add(self.xbar_hist)
1357
+ scene.play(FadeIn(self.xbar_hist.title, run_time=0.4))
1358
+ scene.play(Create(self.xbar_hist.mean_line, run_time=0.5))
1359
+
1360
+ # Animated batch
1361
+ for i, xbar in enumerate(self._all_xbars[:n_visible]):
1362
+ anim = self.xbar_hist.add_sample_mean(xbar, scene=scene, animate=True,
1363
+ run_time=run_time_per_bar)
1364
+ if anim is not None:
1365
+ scene.play(anim)
1366
+ else:
1367
+ scene.wait(run_time_per_bar * 0.3)
1368
+
1369
+ # Silent batch — add remaining immediately
1370
+ if batch_silent and len(self._all_xbars) > n_visible:
1371
+ for xbar in self._all_xbars[n_visible:]:
1372
+ self.xbar_hist.add_sample_mean(xbar, animate=False)
1373
+ scene.wait(0.4)
1374
+
1375
+ # ------------------------------------------------------------------
1376
+ # Phase 3: Normal convergence overlay
1377
+ # ------------------------------------------------------------------
1378
+
1379
+ def phase_normal_overlay(
1380
+ self,
1381
+ scene: ThreeDScene,
1382
+ run_time: float = 1.2,
1383
+ hold: float = 1.5,
1384
+ ) -> None:
1385
+ """Draw the theoretical normal curve over the x̄ histogram.
1386
+
1387
+ Requires ``phase_accumulate`` to have been called first.
1388
+ """
1389
+ if self.xbar_hist is None:
1390
+ raise RuntimeError("Call phase_accumulate first.")
1391
+
1392
+ curve = self.xbar_hist.build_normal_overlay()
1393
+ if not self.xbar_hist.normal_curve in scene.mobjects:
1394
+ scene.add(self.xbar_hist.normal_curve)
1395
+
1396
+ scene.play(Create(curve, run_time=run_time))
1397
+ scene.wait(hold)
1398
+
1399
+ # Show σ/√n annotation beside the curve
1400
+ if self.cfg.show_variance_annotation:
1401
+ se = self.sigma / np.sqrt(max(self.cfg.n, 1))
1402
+ se_lbl = Text(
1403
+ f"σ/√n = {se:.3f}",
1404
+ font_size=20,
1405
+ color=self.cfg.normal_color,
1406
+ )
1407
+ se_lbl.move_to(np.array([
1408
+ self.cfg.xbar_x + self.cfg.hist_width * 0.55,
1409
+ -self.cfg.hist_depth / 2,
1410
+ self.cfg.z_scale * 3.5,
1411
+ ]))
1412
+ scene.add_fixed_orientation_mobjects(se_lbl)
1413
+ scene.add(se_lbl)
1414
+ scene.play(FadeIn(se_lbl, run_time=0.5))
1415
+ scene.wait(hold)
1416
+
1417
+ # ------------------------------------------------------------------
1418
+ # Phase 4: n-sweep
1419
+ # ------------------------------------------------------------------
1420
+
1421
+ def phase_n_sweep(
1422
+ self,
1423
+ scene: ThreeDScene,
1424
+ n_values: Optional[List[int]] = None,
1425
+ n_trials_per: int = 200,
1426
+ n_visible_per: int = 30,
1427
+ run_time_transition: float = 0.9,
1428
+ ) -> None:
1429
+ """Repeat accumulation for multiple values of n, showing convergence.
1430
+
1431
+ For each n in *n_values*:
1432
+ 1. Reset the x̄ histogram.
1433
+ 2. Update the variance annotation.
1434
+ 3. Accumulate ``n_trials_per`` sample means.
1435
+ 4. Draw the normal overlay.
1436
+ 5. Pause to show the fit.
1437
+
1438
+ Parameters
1439
+ ----------
1440
+ n_values : list[int] or None
1441
+ Sample sizes to demonstrate (default: [1, 2, 5, 10, 30, 100]).
1442
+ n_trials_per : int
1443
+ Number of x̄ trials per n value.
1444
+ n_visible_per : int
1445
+ Visibly animated trials per n value.
1446
+ run_time_transition : float
1447
+ Transition time between n values.
1448
+ """
1449
+ sweep_ns = n_values or [1, 2, 5, 10, 30, 100]
1450
+
1451
+ # Initialise histogram and annotation if not present
1452
+ if self.xbar_hist is None:
1453
+ self.xbar_hist = SampleMeanHistogram3D(
1454
+ cfg=self.cfg, mu=self.mu, sigma=self.sigma, scene=scene
1455
+ )
1456
+ scene.add(self.xbar_hist)
1457
+
1458
+ if self.variance_annotation is None and self.cfg.show_variance_annotation:
1459
+ self.variance_annotation = _VarianceAnnotation3D(
1460
+ mu=self.mu,
1461
+ sigma=self.sigma,
1462
+ n=sweep_ns[0],
1463
+ position=np.array([
1464
+ self.cfg.xbar_x + self.cfg.hist_width * 0.65,
1465
+ -self.cfg.hist_depth / 2,
1466
+ self.cfg.z_scale * 3.0,
1467
+ ]),
1468
+ color=WHITE,
1469
+ font_size=20,
1470
+ scene=scene,
1471
+ )
1472
+ scene.add(self.variance_annotation)
1473
+
1474
+ for n in sweep_ns:
1475
+ # 1 — Reset histogram and update config
1476
+ self.xbar_hist.reset()
1477
+
1478
+ old_n = self.cfg.n
1479
+ self.cfg.n = n
1480
+
1481
+ # Recompute SE for this n
1482
+ self.xbar_hist._se = self.sigma / np.sqrt(max(n, 1))
1483
+ half_range = max(self.xbar_hist._se * 4.5, self.sigma * 0.5)
1484
+ self.xbar_hist._x_min = self.mu - half_range
1485
+ self.xbar_hist._x_max = self.mu + half_range
1486
+ self.xbar_hist._bin_width = (
1487
+ self.xbar_hist._x_max - self.xbar_hist._x_min
1488
+ ) / self.cfg.n_bins
1489
+
1490
+ # 2 — Update annotation
1491
+ if self.variance_annotation is not None:
1492
+ scene.play(
1493
+ self.variance_annotation.update_n(n, scene, run_time=run_time_transition)
1494
+ )
1495
+
1496
+ # 3 — Re-simulate and accumulate
1497
+ rng_n = np.random.default_rng(self.cfg.rng_seed + n * 17)
1498
+ sampler_n = _make_sampler(self.cfg.source, self.cfg.pop_params, rng_n)
1499
+ xbars_n = [float(sampler_n(n).mean()) for _ in range(n_trials_per)]
1500
+
1501
+ for i, xbar in enumerate(xbars_n[:n_visible_per]):
1502
+ anim = self.xbar_hist.add_sample_mean(xbar, animate=True,
1503
+ run_time=0.08)
1504
+ if anim is not None:
1505
+ scene.play(anim)
1506
+ for xbar in xbars_n[n_visible_per:]:
1507
+ self.xbar_hist.add_sample_mean(xbar, animate=False)
1508
+
1509
+ scene.wait(0.3)
1510
+
1511
+ # 4 — Normal overlay
1512
+ self.xbar_hist.normal_curve = VGroup()
1513
+ self.xbar_hist.add(self.xbar_hist.normal_curve)
1514
+ curve = self.xbar_hist.build_normal_overlay()
1515
+ scene.play(Create(curve, run_time=0.8))
1516
+
1517
+ # 5 — Hold
1518
+ scene.wait(1.2)
1519
+
1520
+ # Clean up normal overlay before next iteration
1521
+ scene.play(FadeOut(self.xbar_hist.normal_curve, run_time=0.4))
1522
+ self.xbar_hist.normal_curve = VGroup()
1523
+ self.xbar_hist.add(self.xbar_hist.normal_curve)
1524
+
1525
+ self.cfg.n = old_n # restore
1526
+
1527
+ # ------------------------------------------------------------------
1528
+ # Formula panel
1529
+ # ------------------------------------------------------------------
1530
+
1531
+ def build_formula_panel(
1532
+ self,
1533
+ scene: ThreeDScene,
1534
+ position: Optional[np.ndarray] = None,
1535
+ ) -> VGroup:
1536
+ """Build a floating formula panel showing the CLT statement.
1537
+
1538
+ Displays:
1539
+ x̄ → N(μ, σ²/n) as n → ∞
1540
+
1541
+ Returns the ``VGroup`` for animation control.
1542
+ """
1543
+ if position is None:
1544
+ position = np.array([0.0, -self.cfg.hist_depth / 2, 5.2])
1545
+
1546
+ lines = [
1547
+ ("CLT:", 22, WHITE),
1548
+ ("x̄ → N(μ, σ²/n)", 20, ManimColor("#4A90D9")),
1549
+ (f"μ = {self.mu:.3f}", 18, ManimColor("#E0AA40")),
1550
+ (f"σ = {self.sigma:.3f}", 18, ManimColor("#E0AA40")),
1551
+ (f"n = {self.cfg.n}", 18, ManimColor("#2DAA6E")),
1552
+ (f"σ/√n = {self.sigma/np.sqrt(max(self.cfg.n,1)):.3f}", 18,
1553
+ ManimColor("#E8593C")),
1554
+ ]
1555
+
1556
+ grp = VGroup()
1557
+ for i, (txt, fs, col) in enumerate(lines):
1558
+ lbl = Text(txt, font_size=fs, color=col)
1559
+ lbl.move_to(position + np.array([0, 0, -i * 0.35]))
1560
+ grp.add(lbl)
1561
+ scene.add_fixed_orientation_mobjects(lbl)
1562
+
1563
+ self.formula_panel = grp
1564
+ scene.add(grp)
1565
+ return grp
1566
+
1567
+ # ------------------------------------------------------------------
1568
+ # Full run
1569
+ # ------------------------------------------------------------------
1570
+
1571
+ def run(
1572
+ self,
1573
+ scene: ThreeDScene,
1574
+ phases: Optional[List[str]] = None,
1575
+ ) -> None:
1576
+ """Execute all (or selected) phases in order.
1577
+
1578
+ Parameters
1579
+ ----------
1580
+ phases : list[str] or None
1581
+ Subset of ``["population", "single_draw", "accumulate",
1582
+ "normal", "formula"]``.
1583
+ If None, all phases run in order.
1584
+ """
1585
+ all_phases = ["population", "single_draw", "accumulate", "normal", "formula"]
1586
+ run_phases = phases if phases is not None else all_phases
1587
+
1588
+ if "population" in run_phases:
1589
+ self.phase_population(scene)
1590
+ if "single_draw" in run_phases:
1591
+ self.phase_single_draw(scene)
1592
+ if "accumulate" in run_phases:
1593
+ self.phase_accumulate(scene, n_visible=60)
1594
+ if "normal" in run_phases:
1595
+ self.phase_normal_overlay(scene)
1596
+ if "formula" in run_phases and self.cfg.show_formula_panel:
1597
+ self.build_formula_panel(scene)
1598
+ scene.play(FadeIn(self.formula_panel, run_time=0.8))
1599
+ scene.wait(2.0)
1600
+
1601
+
1602
+ # ---------------------------------------------------------------------------
1603
+ # Ready-to-render ThreeDScene subclasses
1604
+ # ---------------------------------------------------------------------------
1605
+
1606
+ class CLTUniformScene(ThreeDScene):
1607
+ """Full CLT demo with a Uniform(0, 1) population.
1608
+
1609
+ Render: manim -pql clt_demo.py CLTUniformScene
1610
+ """
1611
+
1612
+ def construct(self):
1613
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1614
+ self.begin_ambient_camera_rotation(rate=0.04)
1615
+
1616
+ cfg = CLTConfig(
1617
+ source="uniform",
1618
+ pop_params={"lo": 0.0, "hi": 1.0},
1619
+ n=10,
1620
+ n_trials=300,
1621
+ pop_x=-2.8,
1622
+ xbar_x=2.8,
1623
+ hist_width=4.2,
1624
+ z_scale=0.85,
1625
+ n_bins=20,
1626
+ )
1627
+ demo = CLTDemo(cfg)
1628
+ demo.phase_population(self)
1629
+ demo.phase_single_draw(self)
1630
+ demo.phase_accumulate(self, n_visible=60)
1631
+ demo.phase_normal_overlay(self)
1632
+ demo.build_formula_panel(self)
1633
+ self.play(FadeIn(demo.formula_panel, run_time=0.7))
1634
+ self.wait(2)
1635
+
1636
+
1637
+ class CLTExponentialScene(ThreeDScene):
1638
+ """Full CLT demo with an Exponential(rate=1) population.
1639
+
1640
+ The source is strongly right-skewed — making the normal emergence
1641
+ particularly striking.
1642
+
1643
+ Render: manim -pql clt_demo.py CLTExponentialScene
1644
+ """
1645
+
1646
+ def construct(self):
1647
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1648
+ self.begin_ambient_camera_rotation(rate=0.035)
1649
+
1650
+ cfg = CLTConfig(
1651
+ source="exponential",
1652
+ pop_params={"rate": 1.0},
1653
+ n=15,
1654
+ n_trials=400,
1655
+ pop_color=ManimColor("#E8593C"),
1656
+ xbar_color_lo=ManimColor("#1ABC9C"),
1657
+ xbar_color_hi=ManimColor("#E0AA40"),
1658
+ normal_color=ManimColor("#4A90D9"),
1659
+ pop_x=-2.8,
1660
+ xbar_x=2.8,
1661
+ hist_width=4.2,
1662
+ z_scale=0.85,
1663
+ n_bins=22,
1664
+ )
1665
+ demo = CLTDemo(cfg)
1666
+ demo.phase_population(self)
1667
+ demo.phase_single_draw(self, run_time_per_particle=0.35)
1668
+ demo.phase_accumulate(self, n_visible=70)
1669
+ demo.phase_normal_overlay(self)
1670
+ demo.build_formula_panel(self)
1671
+ self.play(FadeIn(demo.formula_panel, run_time=0.7))
1672
+ self.wait(2)
1673
+
1674
+
1675
+ class CLTBimodalScene(ThreeDScene):
1676
+ """Full CLT demo with a bimodal mixture population.
1677
+
1678
+ Two well-separated peaks converge to a single normal — the most
1679
+ pedagogically dramatic case.
1680
+
1681
+ Render: manim -pql clt_demo.py CLTBimodalScene
1682
+ """
1683
+
1684
+ def construct(self):
1685
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1686
+ self.begin_ambient_camera_rotation(rate=0.04)
1687
+
1688
+ cfg = CLTConfig(
1689
+ source="bimodal",
1690
+ pop_params={"mu1": -2.0, "mu2": 2.0, "std1": 0.55, "std2": 0.55},
1691
+ n=12,
1692
+ n_trials=350,
1693
+ pop_color=ManimColor("#9B59B6"),
1694
+ xbar_color_lo=ManimColor("#2DAA6E"),
1695
+ xbar_color_hi=ManimColor("#E0AA40"),
1696
+ normal_color=ManimColor("#E8593C"),
1697
+ pop_x=-3.0,
1698
+ xbar_x=3.0,
1699
+ hist_width=4.5,
1700
+ z_scale=0.80,
1701
+ n_bins=24,
1702
+ )
1703
+ demo = CLTDemo(cfg)
1704
+ demo.phase_population(self)
1705
+ demo.phase_single_draw(self, run_time_per_particle=0.38)
1706
+ demo.phase_accumulate(self, n_visible=65)
1707
+ demo.phase_normal_overlay(self)
1708
+ demo.build_formula_panel(self)
1709
+ self.play(FadeIn(demo.formula_panel, run_time=0.7))
1710
+ self.wait(2)
1711
+
1712
+
1713
+ class CLTSweepScene(ThreeDScene):
1714
+ """n-sweep demo: x̄ histogram narrows as n grows from 1 → 100.
1715
+
1716
+ Shows σ/√n → 0 visually. Most compelling proof of the theorem.
1717
+
1718
+ Render: manim -pql clt_demo.py CLTSweepScene
1719
+ """
1720
+
1721
+ def construct(self):
1722
+ self.set_camera_orientation(phi=68 * DEGREES, theta=-48 * DEGREES)
1723
+ self.begin_ambient_camera_rotation(rate=0.03)
1724
+
1725
+ cfg = CLTConfig(
1726
+ source="exponential",
1727
+ pop_params={"rate": 1.0},
1728
+ n=1,
1729
+ n_trials=200,
1730
+ pop_color=ManimColor("#E8593C"),
1731
+ xbar_color_lo=ManimColor("#1ABC9C"),
1732
+ xbar_color_hi=ManimColor("#E0AA40"),
1733
+ normal_color=ManimColor("#4A90D9"),
1734
+ pop_x=-3.0,
1735
+ xbar_x=3.0,
1736
+ hist_width=4.5,
1737
+ z_scale=0.80,
1738
+ n_bins=28,
1739
+ show_variance_annotation=True,
1740
+ )
1741
+ demo = CLTDemo(cfg)
1742
+
1743
+ # Show population once
1744
+ demo.phase_population(self, run_time_build=1.2)
1745
+ self.wait(0.5)
1746
+
1747
+ # Then sweep n
1748
+ demo.phase_n_sweep(
1749
+ self,
1750
+ n_values=[1, 2, 5, 10, 30, 100],
1751
+ n_trials_per=250,
1752
+ n_visible_per=35,
1753
+ run_time_transition=0.8,
1754
+ )
1755
+ self.wait(2)
1756
+
1757
+
1758
+ class CLTComparisonScene(ThreeDScene):
1759
+ """Side-by-side comparison of three source distributions.
1760
+
1761
+ Builds three ``CLTDemo`` objects with staggered x-positions,
1762
+ all accumulating simultaneously to show the CLT is distribution-agnostic.
1763
+
1764
+ Render: manim -pql clt_demo.py CLTComparisonScene
1765
+ """
1766
+
1767
+ def construct(self):
1768
+ self.set_camera_orientation(phi=60 * DEGREES, theta=-45 * DEGREES)
1769
+
1770
+ sources = [
1771
+ ("uniform", {"lo": 0.0, "hi": 1.0},
1772
+ ManimColor("#4A90D9"), -5.2),
1773
+ ("exponential", {"rate": 1.0},
1774
+ ManimColor("#E8593C"), 0.0),
1775
+ ("bimodal", {"mu1": -1.5, "mu2": 1.5, "std1": 0.45, "std2": 0.45},
1776
+ ManimColor("#9B59B6"), 5.2),
1777
+ ]
1778
+
1779
+ demos: List[CLTDemo] = []
1780
+ hists: List[SampleMeanHistogram3D] = []
1781
+
1782
+ for source, params, col, x_center in sources:
1783
+ cfg = CLTConfig(
1784
+ source=source,
1785
+ pop_params=params,
1786
+ n=15,
1787
+ n_trials=250,
1788
+ pop_color=col,
1789
+ xbar_color_lo=_lighten(col, 1.30),
1790
+ xbar_color_hi=_darken(col, 0.65),
1791
+ normal_color=_lighten(col, 1.60),
1792
+ pop_x=x_center - 1.4,
1793
+ xbar_x=x_center + 1.4,
1794
+ hist_width=2.2,
1795
+ hist_depth=0.35,
1796
+ z_scale=0.75,
1797
+ n_bins=16,
1798
+ show_source_label=True,
1799
+ show_formula_panel=False,
1800
+ )
1801
+ demo = CLTDemo(cfg)
1802
+ demos.append(demo)
1803
+
1804
+ # Build all three populations simultaneously
1805
+ for demo in demos:
1806
+ demo.population = PopulationDistribution3D(
1807
+ cfg=demo.cfg, n_population=6000, show_pdf=True, scene=self
1808
+ )
1809
+ self.add(demo.population)
1810
+
1811
+ self.play(AnimationGroup(*[
1812
+ demo.population.animate_build(run_time_per_bar=0.22)
1813
+ for demo in demos
1814
+ ]))
1815
+ self.wait(0.5)
1816
+
1817
+ # Build all three x̄ histograms simultaneously
1818
+ for demo in demos:
1819
+ demo.xbar_hist = SampleMeanHistogram3D(
1820
+ cfg=demo.cfg, mu=demo.mu, sigma=demo.sigma, scene=self
1821
+ )
1822
+ self.add(demo.xbar_hist)
1823
+
1824
+ # Add trials in batches — all three in parallel
1825
+ n_visible = 40
1826
+ for i in range(n_visible):
1827
+ batch_anims = []
1828
+ for demo in demos:
1829
+ xbar = demo._all_xbars[i]
1830
+ anim = demo.xbar_hist.add_sample_mean(xbar, animate=True, run_time=0.09)
1831
+ if anim is not None:
1832
+ batch_anims.append(anim)
1833
+ if batch_anims:
1834
+ self.play(AnimationGroup(*batch_anims))
1835
+
1836
+ # Add remaining silently
1837
+ for demo in demos:
1838
+ for xbar in demo._all_xbars[n_visible:]:
1839
+ demo.xbar_hist.add_sample_mean(xbar, animate=False)
1840
+ self.wait(0.3)
1841
+
1842
+ # Normal overlays for all three
1843
+ curves = []
1844
+ for demo in demos:
1845
+ curve = demo.xbar_hist.build_normal_overlay()
1846
+ self.add(demo.xbar_hist.normal_curve)
1847
+ curves.append(curve)
1848
+
1849
+ self.play(AnimationGroup(*[
1850
+ Create(c, run_time=1.0) for c in curves
1851
+ ]))
1852
+ self.wait(3)