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,1851 @@
1
+ """
2
+ statanim/animations/flip_roll.py
3
+ =====================================
4
+ Coin flip and die roll animations for probability demonstrations.
5
+
6
+ Design philosophy
7
+ -----------------
8
+ Physical props (coins, dice) are the most concrete way to introduce
9
+ probability. These animations are built at two levels:
10
+
11
+ Geometry level – ``Coin3D`` and ``Die3D`` are cylindrical /
12
+ polyhedral VGroup objects with correctly labelled
13
+ faces, independent shading, and gloss highlights.
14
+ They stand in for the future ``props/coin.py`` and
15
+ ``props/die.py`` — that module will simply export
16
+ the same class names.
17
+
18
+ Animation level – ``CoinFlipAnimation``, ``DieRollAnimation``, and
19
+ the sequence / accumulator classes consume those
20
+ props and add motion: arc trajectories, spin rates,
21
+ bounce physics, and result annotation.
22
+
23
+ Physical realism comes from four sub-animations composed together:
24
+ 1. Lift – prop rises from rest position to arc apex.
25
+ 2. Spin – prop rotates at a rate proportional to arc speed.
26
+ 3. Descent – prop follows the other half of the arc.
27
+ 4. Settle – one or two damped bounces then comes to rest, face up.
28
+
29
+ Teaching animations
30
+ -------------------
31
+ ``BinomialAccumulator``
32
+ Flip n coins, collect heads counts into a growing bar chart,
33
+ watch Binomial(n, p) emerge.
34
+
35
+ ``LLNAccumulator``
36
+ Flip a single coin repeatedly, plot the running relative frequency
37
+ of heads, watch it converge to p. Demonstrates the Law of Large
38
+ Numbers.
39
+
40
+ ``DiceSumAccumulator``
41
+ Roll two (or more) dice, record the sum, accumulate into a bar
42
+ chart. The triangular / normal-ish distribution of sums emerges.
43
+
44
+ Classes
45
+ -------
46
+ Coin3D
47
+ Die3D
48
+ CoinFlipAnimation
49
+ DieRollAnimation
50
+ BinomialAccumulator
51
+ LLNAccumulator
52
+ DiceSumAccumulator
53
+
54
+ Helpers / internals
55
+ -------------------
56
+ FlipConfig
57
+ RollConfig
58
+ _ArcPath
59
+ _BounceUpdater
60
+ _ResultLabel3D
61
+
62
+ Ready-to-render scenes
63
+ ----------------------
64
+ CoinFlipScene
65
+ DieRollScene
66
+ BinomialScene
67
+ LLNScene
68
+ DiceSumScene
69
+
70
+ Usage
71
+ -----
72
+ # Render one coin flip:
73
+ # manim -pql flip_roll.py CoinFlipScene
74
+
75
+ # Embed in your own scene:
76
+ from statanim.animations.flip_roll import CoinFlipAnimation, Coin3D
77
+
78
+ class MyScene(ThreeDScene):
79
+ def construct(self):
80
+ coin = Coin3D(radius=0.5, thickness=0.12)
81
+ self.add(coin)
82
+ flip = CoinFlipAnimation(coin, outcome="heads", arc_height=2.0)
83
+ self.play(flip.animate(self))
84
+ """
85
+
86
+ from __future__ import annotations
87
+
88
+ from dataclasses import dataclass, field
89
+ from typing import List, Sequence, Tuple, Optional, Callable, Union, Dict
90
+ import numpy as np
91
+
92
+ from manim import (
93
+ VGroup, VMobject, Polygon, Line, DashedLine, Dot3D,
94
+ Ellipse, Text, MathTex, Arc, Circle,
95
+ Cylinder, ThreeDScene,
96
+ AnimationGroup, LaggedStart, Succession,
97
+ Create, FadeIn, FadeOut, Transform, MoveAlongPath,
98
+ Rotate, UpdateFromAlphaFunc, Flash, Indicate,
99
+ DEGREES, PI, TAU,
100
+ RIGHT, LEFT, UP, DOWN, OUT, IN, ORIGIN,
101
+ X_AXIS, Y_AXIS, Z_AXIS,
102
+ WHITE, BLACK, GRAY, BLUE, GREEN, RED, YELLOW,
103
+ ManimColor, color_to_rgb, rgba_to_color, color_to_rgba,
104
+ rate_functions, smooth,
105
+ )
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Colour helpers
109
+ # ---------------------------------------------------------------------------
110
+
111
+ def _with_opacity(color: ManimColor, opacity: float) -> ManimColor:
112
+ r, g, b = color_to_rgb(color)
113
+ return rgba_to_color([r, g, b, max(0.0, min(1.0, opacity))])
114
+
115
+ def _darken(color: ManimColor, factor: float = 0.65) -> ManimColor:
116
+ r, g, b = color_to_rgb(color)
117
+ return ManimColor([r * factor, g * factor, b * factor])
118
+
119
+ def _lighten(color: ManimColor, factor: float = 1.35) -> ManimColor:
120
+ r, g, b = color_to_rgb(color)
121
+ return ManimColor([min(r * factor, 1.0), min(g * factor, 1.0), min(b * factor, 1.0)])
122
+
123
+ def _lerp_color(a: ManimColor, b: ManimColor, t: float) -> ManimColor:
124
+ ra, ga, ba = color_to_rgb(a)
125
+ rb, gb, bb = color_to_rgb(b)
126
+ return ManimColor([ra+(rb-ra)*t, ga+(gb-ga)*t, ba+(bb-ba)*t])
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Coin3D
131
+ # ---------------------------------------------------------------------------
132
+
133
+ class Coin3D(VGroup):
134
+ """A 3D coin prop: a flat cylinder with distinct faces.
135
+
136
+ Geometry
137
+ --------
138
+ The coin is built from three layers of polygons:
139
+
140
+ - ``face_heads`` – top circular face (n_segments-gon) in gold/silver.
141
+ - ``face_tails`` – bottom circular face, slightly darker.
142
+ - ``rim`` – a band of thin quadrilaterals around the edge,
143
+ producing visible depth and shading.
144
+ - ``heads_label`` – "H" text on the heads face.
145
+ - ``tails_label`` – "T" text on the tails face.
146
+ - ``gloss`` – a small semi-transparent arc across the top face.
147
+
148
+ Parameters
149
+ ----------
150
+ radius : float
151
+ Coin radius in scene units.
152
+ thickness : float
153
+ Coin thickness (distance between faces).
154
+ heads_color : ManimColor
155
+ Main face colour (heads side).
156
+ tails_color : ManimColor
157
+ Tails face colour.
158
+ rim_color : ManimColor
159
+ Edge band colour.
160
+ n_segments : int
161
+ Polygon resolution for circular faces (higher = smoother).
162
+ show_label : bool
163
+ Whether to add "H"/"T" text labels to faces.
164
+ position : np.ndarray
165
+ Initial 3D position of the coin centre.
166
+ """
167
+
168
+ def __init__(
169
+ self,
170
+ radius: float = 0.45,
171
+ thickness: float = 0.10,
172
+ heads_color: ManimColor = ManimColor("#D4A820"), # gold
173
+ tails_color: ManimColor = ManimColor("#B8922A"), # darker gold
174
+ rim_color: ManimColor = ManimColor("#8A6A18"), # deep gold
175
+ n_segments: int = 48,
176
+ show_label: bool = True,
177
+ position: np.ndarray = ORIGIN,
178
+ **kwargs,
179
+ ):
180
+ super().__init__(**kwargs)
181
+
182
+ self.coin_radius = radius
183
+ self.thickness = thickness
184
+ self.heads_color = heads_color
185
+ self.tails_color = tails_color
186
+ self.rim_color = rim_color
187
+ self._n_seg = n_segments
188
+ self._pos = np.array(position, dtype=float)
189
+
190
+ # Unit circle angles
191
+ angles = np.linspace(0, TAU, n_segments, endpoint=False)
192
+ cos_a = np.cos(angles)
193
+ sin_a = np.sin(angles)
194
+
195
+ half_t = thickness / 2
196
+
197
+ # Heads face (z = +half_t)
198
+ heads_pts = [
199
+ self._pos + np.array([radius * cos_a[i], radius * sin_a[i], half_t])
200
+ for i in range(n_segments)
201
+ ]
202
+ self.face_heads = Polygon(
203
+ *heads_pts,
204
+ fill_color=_with_opacity(heads_color, 0.96),
205
+ fill_opacity=1.0,
206
+ stroke_color=_darken(heads_color, 0.70),
207
+ stroke_width=0.6,
208
+ )
209
+
210
+ # Tails face (z = -half_t)
211
+ tails_pts = [
212
+ self._pos + np.array([radius * cos_a[i], radius * sin_a[i], -half_t])
213
+ for i in range(n_segments)
214
+ ]
215
+ # Reverse winding so normal faces -z
216
+ self.face_tails = Polygon(
217
+ *reversed(tails_pts),
218
+ fill_color=_with_opacity(tails_color, 0.92),
219
+ fill_opacity=1.0,
220
+ stroke_color=_darken(tails_color, 0.65),
221
+ stroke_width=0.5,
222
+ )
223
+
224
+ # Rim: n_segments quads around the edge
225
+ rim_quads = VGroup()
226
+ rim_col_outer = _with_opacity(rim_color, 0.90)
227
+ rim_col_inner = _with_opacity(_darken(rim_color, 0.78), 0.88)
228
+ for i in range(n_segments):
229
+ j = (i + 1) % n_segments
230
+ # Two triangles per quad (Manim Polygon works fine for quads)
231
+ quad = Polygon(
232
+ self._pos + np.array([radius * cos_a[i], radius * sin_a[i], half_t]),
233
+ self._pos + np.array([radius * cos_a[j], radius * sin_a[j], half_t]),
234
+ self._pos + np.array([radius * cos_a[j], radius * sin_a[j], -half_t]),
235
+ self._pos + np.array([radius * cos_a[i], radius * sin_a[i], -half_t]),
236
+ fill_color=_lerp_color(rim_col_outer, rim_col_inner,
237
+ 0.5 + 0.5 * cos_a[i]), # shading varies around rim
238
+ fill_opacity=1.0,
239
+ stroke_width=0,
240
+ )
241
+ rim_quads.add(quad)
242
+ self.rim = rim_quads
243
+
244
+ # Gloss arc on heads face
245
+ n_gloss = n_segments // 3
246
+ gloss_pts = [
247
+ self._pos + np.array([
248
+ radius * 0.82 * np.cos(a),
249
+ radius * 0.82 * np.sin(a),
250
+ half_t + 0.001,
251
+ ])
252
+ for a in np.linspace(PI * 0.15, PI * 0.65, n_gloss)
253
+ ]
254
+ # Close the gloss arc into a thin crescent
255
+ gloss_inner_pts = [
256
+ self._pos + np.array([
257
+ radius * 0.55 * np.cos(a),
258
+ radius * 0.55 * np.sin(a),
259
+ half_t + 0.001,
260
+ ])
261
+ for a in np.linspace(PI * 0.65, PI * 0.15, n_gloss)
262
+ ]
263
+ self.gloss = Polygon(
264
+ *(gloss_pts + gloss_inner_pts),
265
+ fill_color=_with_opacity(WHITE, 0.18),
266
+ fill_opacity=1.0,
267
+ stroke_width=0,
268
+ )
269
+
270
+ # Labels
271
+ self.heads_label = VGroup()
272
+ self.tails_label = VGroup()
273
+ if show_label:
274
+ h_lbl = Text("H", font_size=int(radius * 80), color=_darken(heads_color, 0.55))
275
+ h_lbl.move_to(self._pos + np.array([0, 0, half_t + 0.005]))
276
+ t_lbl = Text("T", font_size=int(radius * 80), color=_darken(tails_color, 0.50))
277
+ t_lbl.move_to(self._pos + np.array([0, 0, -half_t - 0.005]))
278
+ self.heads_label.add(h_lbl)
279
+ self.tails_label.add(t_lbl)
280
+
281
+ self.add(
282
+ self.face_tails, self.rim, self.face_heads,
283
+ self.gloss, self.heads_label, self.tails_label,
284
+ )
285
+
286
+ # ------------------------------------------------------------------
287
+
288
+ def get_position(self) -> np.ndarray:
289
+ return self.get_center()
290
+
291
+ def show_heads(self) -> "Coin3D":
292
+ """Orient the coin so heads (H) faces upward (+z)."""
293
+ # Ensure face_heads is at top — default orientation is already heads-up
294
+ return self
295
+
296
+ def show_tails(self) -> "Coin3D":
297
+ """Orient the coin so tails (T) faces upward (+z)."""
298
+ self.rotate(PI, axis=RIGHT)
299
+ return self
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # Die3D
304
+ # ---------------------------------------------------------------------------
305
+
306
+ class Die3D(VGroup):
307
+ """A 3D six-sided die (D6) with pip dots on each face.
308
+
309
+ Geometry
310
+ --------
311
+ Six square faces as Polygon objects, each with independent shading
312
+ (front-facing face is brightest, side/top are progressively darker).
313
+ Pip dots are ``Dot3D`` spheres inset slightly above each face.
314
+
315
+ Standard die orientation (Western convention):
316
+ 1 opposite 6, 2 opposite 5, 3 opposite 4.
317
+ When face *k* is on top (+z), the die reads correctly.
318
+
319
+ Parameters
320
+ ----------
321
+ size : float
322
+ Half-edge length of the die (full edge = 2 × size).
323
+ face_color : ManimColor
324
+ Base colour for all faces (shaded per face).
325
+ pip_color : ManimColor
326
+ Dot colour.
327
+ edge_color : ManimColor
328
+ Edge stroke colour.
329
+ corner_radius_frac : float
330
+ Fraction of size used to round corners (visual only —
331
+ approximated by slightly inset face polygons).
332
+ position : np.ndarray
333
+ Initial centre of the die.
334
+ """
335
+
336
+ # Face normals for a unit cube (which face points in which direction)
337
+ _FACE_NORMALS: List[Tuple[np.ndarray, int]] = [
338
+ (np.array([ 0, 0, 1]), 1), # +z → face 1
339
+ (np.array([ 0, 0, -1]), 6), # -z → face 6
340
+ (np.array([ 1, 0, 0]), 2), # +x → face 2
341
+ (np.array([-1, 0, 0]), 5), # -x → face 5
342
+ (np.array([ 0, 1, 0]), 3), # +y → face 3
343
+ (np.array([ 0, -1, 0]), 4), # -y → face 4
344
+ ]
345
+
346
+ # Pip positions for faces 1–6 in a local (u,v) ∈ [-1,1]² coordinate
347
+ _PIP_LAYOUTS: Dict[int, List[Tuple[float, float]]] = {
348
+ 1: [(0.0, 0.0)],
349
+ 2: [(-0.45, -0.45), (0.45, 0.45)],
350
+ 3: [(-0.45, -0.45), (0.0, 0.0), (0.45, 0.45)],
351
+ 4: [(-0.45, -0.45), (0.45, -0.45), (-0.45, 0.45), (0.45, 0.45)],
352
+ 5: [(-0.45, -0.45), (0.45, -0.45), (0.0, 0.0),
353
+ (-0.45, 0.45), (0.45, 0.45)],
354
+ 6: [(-0.45, -0.60), (0.45, -0.60),
355
+ (-0.45, 0.00), (0.45, 0.00),
356
+ (-0.45, 0.60), (0.45, 0.60)],
357
+ }
358
+
359
+ def __init__(
360
+ self,
361
+ size: float = 0.40,
362
+ face_color: ManimColor = ManimColor("#F0EAD6"), # ivory
363
+ pip_color: ManimColor = ManimColor("#1A1A2E"), # near-black
364
+ edge_color: ManimColor = ManimColor("#A09070"),
365
+ corner_radius_frac: float = 0.12,
366
+ position: np.ndarray = ORIGIN,
367
+ **kwargs,
368
+ ):
369
+ super().__init__(**kwargs)
370
+
371
+ self.die_size = size
372
+ self.face_color = face_color
373
+ self.pip_color = pip_color
374
+ self._pos = np.array(position, dtype=float)
375
+
376
+ s = size
377
+ cr = corner_radius_frac * s # corner inset for visual rounding
378
+ ec = _with_opacity(edge_color, 0.55)
379
+
380
+ self.faces = VGroup()
381
+ self.pips = VGroup()
382
+
383
+ # Build six faces
384
+ for normal, face_num in self._FACE_NORMALS:
385
+ shade = self._face_shade(normal)
386
+ col = _with_opacity(_lerp_color(_darken(face_color, 0.80),
387
+ face_color, shade), 0.97)
388
+
389
+ # Build square face perpendicular to normal
390
+ face_pts = self._face_corners(normal, s, cr)
391
+ face_poly = Polygon(
392
+ *face_pts,
393
+ fill_color=col,
394
+ fill_opacity=1.0,
395
+ stroke_color=ec,
396
+ stroke_width=0.8,
397
+ )
398
+ self.faces.add(face_poly)
399
+
400
+ # Build pips on this face
401
+ for (pu, pv) in self._PIP_LAYOUTS[face_num]:
402
+ pip_pos = self._pip_position(normal, s, pu, pv)
403
+ pip = Dot3D(
404
+ point=pip_pos,
405
+ radius=s * 0.085,
406
+ color=_with_opacity(pip_color, 0.95),
407
+ )
408
+ self.pips.add(pip)
409
+
410
+ self.add(self.faces, self.pips)
411
+ if not np.allclose(position, ORIGIN):
412
+ self.move_to(position)
413
+
414
+ # ------------------------------------------------------------------
415
+
416
+ @staticmethod
417
+ def _face_shade(normal: np.ndarray) -> float:
418
+ """Shading factor 0–1 based on face orientation.
419
+ Top (+z) = brightest, sides middling, bottom = darkest.
420
+ """
421
+ key_light = np.array([0.3, -0.5, 1.0])
422
+ key_light = key_light / np.linalg.norm(key_light)
423
+ dot = float(np.dot(normal, key_light))
424
+ return 0.55 + 0.45 * max(dot, 0.0)
425
+
426
+ def _face_corners(
427
+ self,
428
+ normal: np.ndarray,
429
+ s: float,
430
+ cr: float,
431
+ ) -> List[np.ndarray]:
432
+ """Compute the four corners of a face with its normal."""
433
+ pos = self._pos + normal * s
434
+
435
+ # Build two tangent vectors perpendicular to normal
436
+ if abs(normal[2]) < 0.9:
437
+ up = np.array([0, 0, 1], dtype=float)
438
+ else:
439
+ up = np.array([0, 1, 0], dtype=float)
440
+
441
+ right_vec = np.cross(normal, up)
442
+ right_vec /= np.linalg.norm(right_vec)
443
+ up_vec = np.cross(right_vec, normal)
444
+ up_vec /= np.linalg.norm(up_vec)
445
+
446
+ inset = s - cr
447
+ corners = [
448
+ pos + inset * (-right_vec - up_vec),
449
+ pos + inset * ( right_vec - up_vec),
450
+ pos + inset * ( right_vec + up_vec),
451
+ pos + inset * (-right_vec + up_vec),
452
+ ]
453
+ return corners
454
+
455
+ def _pip_position(
456
+ self,
457
+ normal: np.ndarray,
458
+ s: float,
459
+ pu: float,
460
+ pv: float,
461
+ ) -> np.ndarray:
462
+ """Compute a pip's 3D position on the face."""
463
+ pos = self._pos + normal * s
464
+ inset_offset = 0.008 # pip floats slightly above face
465
+
466
+ if abs(normal[2]) < 0.9:
467
+ up = np.array([0, 0, 1], dtype=float)
468
+ else:
469
+ up = np.array([0, 1, 0], dtype=float)
470
+
471
+ right_vec = np.cross(normal, up)
472
+ right_vec /= np.linalg.norm(right_vec)
473
+ up_vec = np.cross(right_vec, normal)
474
+ up_vec /= np.linalg.norm(up_vec)
475
+
476
+ return pos + pu * s * right_vec + pv * s * up_vec + normal * inset_offset
477
+
478
+ def get_top_face(self) -> int:
479
+ """Return which face number (1–6) is currently on top (+z)."""
480
+ best_face = 1
481
+ best_dot = -2.0
482
+ for normal, face_num in self._FACE_NORMALS:
483
+ # Rotate normal by die's current transform (approximate: use center shift)
484
+ d = float(np.dot(normal, np.array([0, 0, 1])))
485
+ if d > best_dot:
486
+ best_dot = d
487
+ best_face = face_num
488
+ return best_face
489
+
490
+
491
+ # ---------------------------------------------------------------------------
492
+ # FlipConfig
493
+ # ---------------------------------------------------------------------------
494
+
495
+ @dataclass
496
+ class FlipConfig:
497
+ """Visual and physics parameters for a coin flip animation.
498
+
499
+ Flip styles
500
+ ~~~~~~~~~~~
501
+ ``"tumble"``
502
+ Coin tumbles end-over-end (rotates around a diameter axis).
503
+ Most realistic. The number of full rotations is ``n_spins``.
504
+ ``"rotate_y"``
505
+ Coin spins around its central axis (like a top). Shows edge
506
+ prominently. Good for emphasising the coin's cylindrical shape.
507
+ ``"arc"``
508
+ Parabolic arc with tumble. The coin moves laterally while
509
+ flipping — useful when showing multiple coins side by side.
510
+
511
+ Settle styles
512
+ ~~~~~~~~~~~~~
513
+ ``"instant"``
514
+ No bouncing — coin appears in final position immediately.
515
+ ``"bounce"``
516
+ One soft bounce with damping before coming to rest.
517
+ ``"wobble"``
518
+ The coin lands edge-on, rocks left-right twice, then falls flat.
519
+
520
+ Attributes
521
+ ----------
522
+ flip_style : str
523
+ ``"tumble"`` | ``"rotate_y"`` | ``"arc"``.
524
+ settle_style : str
525
+ ``"instant"`` | ``"bounce"`` | ``"wobble"``.
526
+ arc_height : float
527
+ Maximum height of the flip arc in scene units.
528
+ arc_lateral : float
529
+ Lateral (x) displacement during an ``"arc"`` flip.
530
+ n_spins : float
531
+ Number of full rotations during the flip.
532
+ spin_axis : np.ndarray
533
+ Axis of rotation (normalised). Default RIGHT for tumble.
534
+ run_time : float
535
+ Total animation duration in seconds.
536
+ bounce_height : float
537
+ Maximum height of the settle bounce (fraction of arc_height).
538
+ bounce_damping : float
539
+ Damping factor per bounce (0 < damping < 1).
540
+ show_result_label : bool
541
+ Whether to show "H" / "T" label after settling.
542
+ result_label_font_size : int
543
+ result_label_color : ManimColor
544
+ result_label_offset : float
545
+ Z offset for the result label above the coin.
546
+ trail_opacity : float
547
+ Opacity of motion trail dots (0 = no trail).
548
+ trail_n_dots : int
549
+ Number of trail dots to draw.
550
+ """
551
+
552
+ flip_style: str = "tumble"
553
+ settle_style: str = "bounce"
554
+ arc_height: float = 2.2
555
+ arc_lateral: float = 0.0
556
+ n_spins: float = 3.5
557
+ spin_axis: np.ndarray = field(default_factory=lambda: RIGHT.copy())
558
+ run_time: float = 1.4
559
+ bounce_height: float = 0.22
560
+ bounce_damping: float = 0.42
561
+ show_result_label: bool = True
562
+ result_label_font_size: int = 22
563
+ result_label_color: ManimColor = WHITE
564
+ result_label_offset: float = 0.55
565
+ trail_opacity: float = 0.0
566
+ trail_n_dots: int = 8
567
+
568
+
569
+ # ---------------------------------------------------------------------------
570
+ # RollConfig
571
+ # ---------------------------------------------------------------------------
572
+
573
+ @dataclass
574
+ class RollConfig:
575
+ """Visual and physics parameters for a die roll animation.
576
+
577
+ Roll styles
578
+ ~~~~~~~~~~~
579
+ ``"toss"``
580
+ Die arcs through the air while tumbling on two axes.
581
+ Lands, bounces once, settles face-up.
582
+ ``"roll"``
583
+ Die rolls across a flat surface (rotates along one axis while
584
+ translating). Stays on the floor throughout.
585
+ ``"drop"``
586
+ Die falls from above, hits the floor, bounces 1–2 times.
587
+
588
+ Attributes
589
+ ----------
590
+ roll_style : str
591
+ ``"toss"`` | ``"roll"`` | ``"drop"``.
592
+ arc_height : float
593
+ Peak height (for ``"toss"`` and ``"drop"``).
594
+ arc_lateral : float
595
+ Lateral travel distance (for ``"toss"`` and ``"roll"``).
596
+ n_tumbles : float
597
+ Number of full tumble rotations during flight.
598
+ tumble_axis : np.ndarray
599
+ Primary tumble axis.
600
+ secondary_spin : float
601
+ Additional spin around the vertical axis (adds randomness).
602
+ run_time : float
603
+ Total animation duration.
604
+ n_bounces : int
605
+ Number of bounces after landing (0–3).
606
+ bounce_decay : float
607
+ Height multiplier per bounce (0 < decay < 1).
608
+ show_result_label : bool
609
+ result_label_font_size : int
610
+ result_label_color : ManimColor
611
+ """
612
+
613
+ roll_style: str = "toss"
614
+ arc_height: float = 1.8
615
+ arc_lateral: float = 0.0
616
+ n_tumbles: float = 2.5
617
+ tumble_axis: np.ndarray = field(default_factory=lambda: RIGHT.copy())
618
+ secondary_spin: float = 0.5
619
+ run_time: float = 1.6
620
+ n_bounces: int = 1
621
+ bounce_decay: float = 0.38
622
+ show_result_label: bool = True
623
+ result_label_font_size: int = 22
624
+ result_label_color: ManimColor = WHITE
625
+
626
+
627
+ # ---------------------------------------------------------------------------
628
+ # _ArcPath (internal)
629
+ # ---------------------------------------------------------------------------
630
+
631
+ def _arc_trajectory(
632
+ start: np.ndarray,
633
+ end: np.ndarray,
634
+ apex_height: float,
635
+ t: float,
636
+ ) -> np.ndarray:
637
+ """Evaluate a parabolic arc from *start* to *end* at parameter *t* ∈ [0,1].
638
+
639
+ The arc peaks at ``apex_height`` above the midpoint's z.
640
+
641
+ Parameters
642
+ ----------
643
+ start, end : np.ndarray
644
+ Start and end positions.
645
+ apex_height : float
646
+ Maximum height above the start/end z level.
647
+ t : float
648
+ Arc parameter 0 → 1.
649
+
650
+ Returns
651
+ -------
652
+ np.ndarray
653
+ 3D position at parameter *t*.
654
+ """
655
+ # Quadratic Bézier with control point at arc apex
656
+ mid = (start + end) / 2 + np.array([0, 0, apex_height])
657
+ return (1 - t)**2 * start + 2 * (1 - t) * t * mid + t**2 * end
658
+
659
+
660
+ def _bounce_trajectory(
661
+ land: np.ndarray,
662
+ t: float,
663
+ bounce_height: float,
664
+ bounce_damping: float,
665
+ n_bounces: int = 1,
666
+ ) -> np.ndarray:
667
+ """Position during a damped bounce sequence starting at *land*.
668
+
669
+ The settle occupies t ∈ [0, 1]. Each bounce takes equal time.
670
+
671
+ Parameters
672
+ ----------
673
+ land : np.ndarray
674
+ Landing position (z = floor level).
675
+ t : float
676
+ Settle parameter 0 → 1.
677
+ bounce_height : float
678
+ Height of the first bounce.
679
+ bounce_damping : float
680
+ Height multiplier per subsequent bounce.
681
+ n_bounces : int
682
+ Number of bounces.
683
+ """
684
+ if n_bounces == 0 or bounce_height < 0.01:
685
+ return land.copy()
686
+
687
+ # Divide [0, 1] into n_bounces equal segments
688
+ seg = 1.0 / n_bounces
689
+ seg_idx = min(int(t / seg), n_bounces - 1)
690
+ t_local = (t - seg_idx * seg) / seg # ∈ [0, 1] within this bounce
691
+
692
+ h = bounce_height * (bounce_damping ** seg_idx)
693
+ z_offset = 4 * h * t_local * (1 - t_local) # parabolic mini-arc
694
+
695
+ pos = land.copy()
696
+ pos[2] += z_offset
697
+ return pos
698
+
699
+
700
+ # ---------------------------------------------------------------------------
701
+ # _ResultLabel3D (internal)
702
+ # ---------------------------------------------------------------------------
703
+
704
+ class _ResultLabel3D(VGroup):
705
+ """Floating label shown after a coin flip or die roll settles.
706
+
707
+ For coins: "H" / "T".
708
+ For dice: the face value as a digit.
709
+
710
+ Parameters
711
+ ----------
712
+ text : str
713
+ position : np.ndarray
714
+ color : ManimColor
715
+ font_size : int
716
+ scene : ThreeDScene or None
717
+ """
718
+
719
+ def __init__(
720
+ self,
721
+ text: str,
722
+ position: np.ndarray,
723
+ color: ManimColor = WHITE,
724
+ font_size: int = 22,
725
+ scene: Optional[ThreeDScene] = None,
726
+ **kwargs,
727
+ ):
728
+ super().__init__(**kwargs)
729
+ lbl = Text(text, font_size=font_size, color=color)
730
+ lbl.move_to(np.array(position, dtype=float))
731
+ self.add(lbl)
732
+ if scene is not None:
733
+ scene.add_fixed_orientation_mobjects(lbl)
734
+
735
+
736
+ # ---------------------------------------------------------------------------
737
+ # CoinFlipAnimation
738
+ # ---------------------------------------------------------------------------
739
+
740
+ class CoinFlipAnimation:
741
+ """Physics-based coin flip animation.
742
+
743
+ Usage::
744
+
745
+ coin = Coin3D(position=np.array([0, 0, 0]))
746
+ flip = CoinFlipAnimation(coin, outcome="heads")
747
+ # inside a ThreeDScene.construct:
748
+ self.play(*flip.build(self))
749
+
750
+ Parameters
751
+ ----------
752
+ coin : Coin3D
753
+ The coin to animate. It is modified in place.
754
+ outcome : str
755
+ ``"heads"`` or ``"tails"``.
756
+ config : FlipConfig
757
+ rest_position : np.ndarray or None
758
+ Where the coin settles. Defaults to its current position.
759
+ scene : ThreeDScene or None
760
+ Provide to register result labels for fixed orientation.
761
+ """
762
+
763
+ def __init__(
764
+ self,
765
+ coin: Coin3D,
766
+ outcome: str = "heads",
767
+ config: Optional[FlipConfig] = None,
768
+ rest_position: Optional[np.ndarray] = None,
769
+ scene: Optional[ThreeDScene] = None,
770
+ ):
771
+ self.coin = coin
772
+ self.outcome = outcome.lower()
773
+ self.cfg = config if config is not None else FlipConfig()
774
+ self._rest = (
775
+ rest_position.copy() if rest_position is not None
776
+ else coin.get_center().copy()
777
+ )
778
+ self._scene = scene
779
+
780
+ # ------------------------------------------------------------------
781
+
782
+ def build(
783
+ self,
784
+ scene: ThreeDScene,
785
+ ) -> List:
786
+ """Return a list of Manim animations to ``scene.play(*result)``.
787
+
788
+ Builds the full flip as a ``Succession`` of three phases:
789
+ flight arc + spin, then settle bounce.
790
+ """
791
+ scene_ref = scene if self._scene is None else self._scene
792
+ coin = self.coin
793
+ cfg = self.cfg
794
+ start = coin.get_center().copy()
795
+ end = self._rest.copy()
796
+
797
+ if cfg.arc_lateral != 0.0:
798
+ end = end + np.array([cfg.arc_lateral, 0, 0])
799
+
800
+ # Phase 1+2: arc flight + spin combined via UpdateFromAlphaFunc
801
+ flip_run = cfg.run_time * 0.70
802
+ settle_run = cfg.run_time * 0.30
803
+
804
+ # Total spin angle
805
+ total_spin_angle = cfg.n_spins * TAU
806
+ # Add half turn if tails (so the right face ends up on top)
807
+ if self.outcome == "tails":
808
+ total_spin_angle += PI
809
+
810
+ # Spin axis
811
+ spin_ax = np.array(cfg.spin_axis, dtype=float)
812
+ spin_ax /= np.linalg.norm(spin_ax)
813
+
814
+ # For "rotate_y" style, spin around Z axis instead
815
+ if cfg.flip_style == "rotate_y":
816
+ spin_ax = np.array([0, 0, 1], dtype=float)
817
+
818
+ def flight_updater(mob: VGroup, alpha: float) -> None:
819
+ t = rate_functions.ease_in_out_sine(alpha)
820
+ pos = _arc_trajectory(start, end, cfg.arc_height, t)
821
+ mob.move_to(pos)
822
+ # Cumulative rotation
823
+ angle = total_spin_angle * t
824
+ mob.rotate(
825
+ angle - getattr(mob, "_last_flip_angle", 0.0),
826
+ axis=spin_ax,
827
+ about_point=mob.get_center(),
828
+ )
829
+ mob._last_flip_angle = angle
830
+
831
+ # Initialise tracking attribute
832
+ coin._last_flip_angle = 0.0
833
+
834
+ flight_anim = UpdateFromAlphaFunc(
835
+ coin, flight_updater, run_time=flip_run
836
+ )
837
+
838
+ # Phase 3: settle bounce
839
+ if cfg.settle_style == "instant" or cfg.bounce_height < 0.01:
840
+ settle_anim = UpdateFromAlphaFunc(
841
+ coin,
842
+ lambda mob, a: mob.move_to(end),
843
+ run_time=0.01,
844
+ )
845
+ else:
846
+ n_b = 1 if cfg.settle_style == "bounce" else 2
847
+
848
+ def settle_updater(mob: VGroup, alpha: float) -> None:
849
+ t = smooth(alpha)
850
+ pos = _bounce_trajectory(
851
+ end, t, cfg.bounce_height, cfg.bounce_damping, n_b
852
+ )
853
+ mob.move_to(pos)
854
+
855
+ settle_anim = UpdateFromAlphaFunc(
856
+ coin, settle_updater, run_time=settle_run
857
+ )
858
+
859
+ anims: List = [Succession(flight_anim, settle_anim)]
860
+
861
+ # Trail dots
862
+ if cfg.trail_opacity > 0 and cfg.trail_n_dots > 0:
863
+ trail = self._build_trail(start, end, cfg)
864
+ anims.append(FadeIn(trail, run_time=flip_run * 0.3))
865
+ anims.append(FadeOut(trail, run_time=flip_run * 0.3))
866
+
867
+ # Result label
868
+ if cfg.show_result_label:
869
+ label_text = "H" if self.outcome == "heads" else "T"
870
+ label_pos = end + np.array([0, 0, cfg.result_label_offset])
871
+ lbl = _ResultLabel3D(
872
+ label_text, label_pos,
873
+ color=cfg.result_label_color,
874
+ font_size=cfg.result_label_font_size,
875
+ scene=scene_ref,
876
+ )
877
+ scene_ref.add(lbl)
878
+ anims.append(FadeIn(lbl, scale=0.5, run_time=0.3))
879
+
880
+ return anims
881
+
882
+ def _build_trail(
883
+ self,
884
+ start: np.ndarray,
885
+ end: np.ndarray,
886
+ cfg: FlipConfig,
887
+ ) -> VGroup:
888
+ """Build ghost-dot trail along the arc."""
889
+ trail = VGroup()
890
+ for i in range(1, cfg.trail_n_dots + 1):
891
+ t = i / (cfg.trail_n_dots + 1)
892
+ pos = _arc_trajectory(start, end, cfg.arc_height, t)
893
+ fade = cfg.trail_opacity * (1.0 - t)
894
+ d = Dot3D(point=pos, radius=0.04,
895
+ color=_with_opacity(WHITE, fade))
896
+ trail.add(d)
897
+ return trail
898
+
899
+
900
+ # ---------------------------------------------------------------------------
901
+ # DieRollAnimation
902
+ # ---------------------------------------------------------------------------
903
+
904
+ class DieRollAnimation:
905
+ """Physics-based die roll animation.
906
+
907
+ Usage::
908
+
909
+ die = Die3D(position=np.array([0, 0, 0.4]))
910
+ roll = DieRollAnimation(die, outcome=4, config=RollConfig(roll_style="toss"))
911
+ self.play(*roll.build(self))
912
+
913
+ Parameters
914
+ ----------
915
+ die : Die3D
916
+ The die to animate.
917
+ outcome : int
918
+ The face value (1–6) that lands face-up.
919
+ config : RollConfig
920
+ rest_position : np.ndarray or None
921
+ scene : ThreeDScene or None
922
+ """
923
+
924
+ # Rotation needed to bring each face to +z (face-up) from rest
925
+ # Rest orientation: face 1 on +z. Rotations are (axis, angle).
926
+ _FACE_TO_TOP: Dict[int, Tuple[np.ndarray, float]] = {
927
+ 1: (RIGHT, 0.0), # already face-up
928
+ 6: (RIGHT, PI), # flip 180° around x
929
+ 2: (UP, PI / 2), # rotate 90° around z
930
+ 5: (UP, -PI / 2), # rotate -90° around z
931
+ 3: (RIGHT, -PI / 2), # rotate -90° around x
932
+ 4: (RIGHT, PI / 2), # rotate +90° around x
933
+ }
934
+
935
+ def __init__(
936
+ self,
937
+ die: Die3D,
938
+ outcome: int = 1,
939
+ config: Optional[RollConfig] = None,
940
+ rest_position: Optional[np.ndarray] = None,
941
+ scene: Optional[ThreeDScene] = None,
942
+ ):
943
+ if outcome not in range(1, 7):
944
+ raise ValueError(f"outcome must be 1–6, got {outcome}")
945
+ self.die = die
946
+ self.outcome = outcome
947
+ self.cfg = config if config is not None else RollConfig()
948
+ self._rest = (
949
+ rest_position.copy() if rest_position is not None
950
+ else die.get_center().copy()
951
+ )
952
+ self._scene = scene
953
+
954
+ # ------------------------------------------------------------------
955
+
956
+ def build(self, scene: ThreeDScene) -> List:
957
+ """Return a list of Manim animations."""
958
+ scene_ref = scene if self._scene is None else self._scene
959
+ die = self.die
960
+ cfg = self.cfg
961
+ start = die.get_center().copy()
962
+ end = self._rest.copy()
963
+
964
+ # Compute total rotation to show correct face on top
965
+ settle_ax, settle_angle = self._FACE_TO_TOP[self.outcome]
966
+
967
+ # Total tumble + settle
968
+ tumble_angle = cfg.n_tumbles * TAU + settle_angle
969
+ tumble_ax = np.array(cfg.tumble_axis, dtype=float)
970
+ tumble_ax /= np.linalg.norm(tumble_ax)
971
+
972
+ # Secondary spin (around Z, adds visual randomness)
973
+ secondary_total = cfg.secondary_spin * TAU
974
+
975
+ roll_run = cfg.run_time * 0.65
976
+ settle_run = cfg.run_time * 0.35
977
+
978
+ if cfg.roll_style == "roll":
979
+ # Roll along surface: lateral motion + rotation around X
980
+ def roll_updater(mob: VGroup, alpha: float) -> None:
981
+ t = rate_functions.ease_out_cubic(alpha)
982
+ # Stay at floor z = rest z, only move laterally
983
+ pos = start + (end - start) * t
984
+ mob.move_to(pos)
985
+ dangle = tumble_angle * alpha - getattr(mob, "_last_roll", 0.0)
986
+ mob.rotate(dangle, axis=tumble_ax, about_point=mob.get_center())
987
+ mob._last_roll = tumble_angle * alpha
988
+
989
+ die._last_roll = 0.0
990
+ flight_anim = UpdateFromAlphaFunc(die, roll_updater, run_time=roll_run)
991
+
992
+ elif cfg.roll_style == "drop":
993
+ # Drop from directly above
994
+ drop_start = end + np.array([0, 0, cfg.arc_height])
995
+ die.move_to(drop_start)
996
+
997
+ def drop_updater(mob: VGroup, alpha: float) -> None:
998
+ t = rate_functions.ease_in_cubic(alpha)
999
+ pos = drop_start + (end - drop_start) * t
1000
+ mob.move_to(pos)
1001
+ dangle = tumble_angle * alpha - getattr(mob, "_last_drop", 0.0)
1002
+ mob.rotate(dangle, axis=tumble_ax, about_point=mob.get_center())
1003
+ mob._last_drop = tumble_angle * alpha
1004
+
1005
+ die._last_drop = 0.0
1006
+ flight_anim = UpdateFromAlphaFunc(die, drop_updater, run_time=roll_run)
1007
+
1008
+ else:
1009
+ # Default: toss (arc trajectory + tumble)
1010
+ def toss_updater(mob: VGroup, alpha: float) -> None:
1011
+ t = smooth(alpha)
1012
+ pos = _arc_trajectory(start, end, cfg.arc_height, t)
1013
+ mob.move_to(pos)
1014
+ dangle = tumble_angle * t - getattr(mob, "_last_toss", 0.0)
1015
+ mob.rotate(dangle, axis=tumble_ax, about_point=mob.get_center())
1016
+ if cfg.secondary_spin > 0:
1017
+ d2 = secondary_total * t - getattr(mob, "_last_spin2", 0.0)
1018
+ mob.rotate(d2, axis=Z_AXIS, about_point=mob.get_center())
1019
+ mob._last_spin2 = secondary_total * t
1020
+ mob._last_toss = tumble_angle * t
1021
+
1022
+ die._last_toss = 0.0
1023
+ die._last_spin2 = 0.0
1024
+ flight_anim = UpdateFromAlphaFunc(die, toss_updater, run_time=roll_run)
1025
+
1026
+ # Settle with bounces
1027
+ if cfg.n_bounces == 0:
1028
+ settle_anim = UpdateFromAlphaFunc(
1029
+ die, lambda mob, a: mob.move_to(end), run_time=0.01
1030
+ )
1031
+ else:
1032
+ def settle_updater(mob: VGroup, alpha: float) -> None:
1033
+ pos = _bounce_trajectory(
1034
+ end, smooth(alpha),
1035
+ end[2] * cfg.bounce_decay,
1036
+ cfg.bounce_decay,
1037
+ cfg.n_bounces,
1038
+ )
1039
+ mob.move_to(pos)
1040
+
1041
+ settle_anim = UpdateFromAlphaFunc(die, settle_updater, run_time=settle_run)
1042
+
1043
+ anims: List = [Succession(flight_anim, settle_anim)]
1044
+
1045
+ # Result label
1046
+ if cfg.show_result_label:
1047
+ label_pos = end + np.array([0, 0, die.die_size * 2.0])
1048
+ lbl = _ResultLabel3D(
1049
+ str(self.outcome), label_pos,
1050
+ color=cfg.result_label_color,
1051
+ font_size=cfg.result_label_font_size,
1052
+ scene=scene_ref,
1053
+ )
1054
+ scene_ref.add(lbl)
1055
+ anims.append(FadeIn(lbl, scale=0.5, run_time=0.3))
1056
+
1057
+ return anims
1058
+
1059
+
1060
+ # ---------------------------------------------------------------------------
1061
+ # BinomialAccumulator
1062
+ # ---------------------------------------------------------------------------
1063
+
1064
+ class BinomialAccumulator(VGroup):
1065
+ """Flip n coins, accumulate heads counts into a Binomial histogram.
1066
+
1067
+ Each trial flips ``n_coins`` coins (using ``CoinFlipAnimation`` for the
1068
+ first ``n_visible_trials`` trials) and records the number of heads.
1069
+ The result is added to a live bar chart.
1070
+
1071
+ After enough trials, the Binomial(n_coins, p) PMF is overlaid as
1072
+ a step plot for comparison.
1073
+
1074
+ Parameters
1075
+ ----------
1076
+ n_coins : int
1077
+ Number of coins per trial (n parameter of Binomial).
1078
+ p : float
1079
+ Probability of heads (bias).
1080
+ n_trials : int
1081
+ Total number of trials to simulate.
1082
+ rng_seed : int
1083
+ chart_x : float
1084
+ X position of the bar chart in the scene.
1085
+ chart_z_scale : float
1086
+ Height scaling for bars.
1087
+ bar_color_lo : ManimColor
1088
+ Bars near the expected value.
1089
+ bar_color_hi : ManimColor
1090
+ Bars in the tails.
1091
+ pmf_color : ManimColor
1092
+ Colour of the theoretical PMF overlay.
1093
+ scene : ThreeDScene or None
1094
+ """
1095
+
1096
+ def __init__(
1097
+ self,
1098
+ n_coins: int = 10,
1099
+ p: float = 0.5,
1100
+ n_trials: int = 500,
1101
+ rng_seed: int = 42,
1102
+ chart_x: float = 0.0,
1103
+ chart_z_scale: float = 0.70,
1104
+ bar_color_lo: ManimColor = ManimColor("#2DAA6E"),
1105
+ bar_color_hi: ManimColor = ManimColor("#E0AA40"),
1106
+ pmf_color: ManimColor = ManimColor("#E8593C"),
1107
+ scene: Optional[ThreeDScene] = None,
1108
+ **kwargs,
1109
+ ):
1110
+ super().__init__(**kwargs)
1111
+
1112
+ self.n_coins = n_coins
1113
+ self.p = p
1114
+ self.n_trials = n_trials
1115
+ self.chart_x = chart_x
1116
+ self.z_scale = chart_z_scale
1117
+ self.bar_color_lo = bar_color_lo
1118
+ self.bar_color_hi = bar_color_hi
1119
+ self.pmf_color = pmf_color
1120
+ self._scene = scene
1121
+
1122
+ rng = np.random.default_rng(rng_seed)
1123
+ # Pre-simulate
1124
+ self._results: List[int] = [
1125
+ int(rng.binomial(n_coins, p)) for _ in range(n_trials)
1126
+ ]
1127
+
1128
+ # Counts array indexed 0..n_coins
1129
+ self._counts: np.ndarray = np.zeros(n_coins + 1, dtype=int)
1130
+ self._max_count: int = 1
1131
+ self._bar_mobs: Dict[int, VGroup] = {}
1132
+
1133
+ # Bar geometry params
1134
+ self._bar_w = min(0.55, 4.0 / (n_coins + 1))
1135
+ self._bar_depth = 0.35
1136
+ self._spacing = min(0.70, 5.0 / (n_coins + 1))
1137
+ x_total = n_coins * self._spacing
1138
+ self._x0 = chart_x - x_total / 2
1139
+
1140
+ self.bars = VGroup()
1141
+ self.pmf_overlay = VGroup()
1142
+ self.add(self.bars, self.pmf_overlay)
1143
+
1144
+ # Labels
1145
+ self._build_axis_labels(scene)
1146
+
1147
+ # ------------------------------------------------------------------
1148
+
1149
+ def _bar_x(self, k: int) -> float:
1150
+ return self._x0 + k * self._spacing
1151
+
1152
+ def _bar_color(self, k: int) -> ManimColor:
1153
+ mu = self.n_coins * self.p
1154
+ dist = abs(k - mu) / max(self.n_coins * self.p * (1 - self.p), 0.5)
1155
+ t = min(dist / 3.0, 1.0)
1156
+ return _lerp_color(self.bar_color_lo, self.bar_color_hi, t)
1157
+
1158
+ def _build_bar(self, k: int, height: float) -> VGroup:
1159
+ x = self._bar_x(k)
1160
+ hw = self._bar_w / 2
1161
+ hd = self._bar_depth / 2
1162
+ y, z0, z1 = 0.0, 0.0, max(height, 0.01)
1163
+ col = self._bar_color(k)
1164
+ col_r = _darken(col, 0.60)
1165
+ col_t = _lighten(col, 1.28)
1166
+
1167
+ ff = Polygon(
1168
+ np.array([x-hw, y-hd, z0]), np.array([x+hw, y-hd, z0]),
1169
+ np.array([x+hw, y-hd, z1]), np.array([x-hw, y-hd, z1]),
1170
+ fill_color=_with_opacity(col, 0.90), fill_opacity=1.0, stroke_width=0,
1171
+ )
1172
+ fr = Polygon(
1173
+ np.array([x+hw, y-hd, z0]), np.array([x+hw, y+hd, z0]),
1174
+ np.array([x+hw, y+hd, z1]), np.array([x+hw, y-hd, z1]),
1175
+ fill_color=_with_opacity(col_r, 0.88), fill_opacity=1.0, stroke_width=0,
1176
+ )
1177
+ ft = Polygon(
1178
+ np.array([x-hw, y-hd, z1]), np.array([x+hw, y-hd, z1]),
1179
+ np.array([x+hw, y+hd, z1]), np.array([x-hw, y+hd, z1]),
1180
+ fill_color=_with_opacity(col_t, 0.80), fill_opacity=1.0, stroke_width=0,
1181
+ )
1182
+ return VGroup(ff, fr, ft)
1183
+
1184
+ def _update_bar(self, k: int) -> None:
1185
+ count = self._counts[k]
1186
+ height = (count / self._max_count) * self.z_scale * 4.0
1187
+ x = self._bar_x(k)
1188
+ hw = self._bar_w / 2
1189
+ hd = self._bar_depth / 2
1190
+ y, z0, z1 = 0.0, 0.0, max(height, 0.01)
1191
+ bar = self._bar_mobs[k]
1192
+ ff, fr, ft = bar[0], bar[1], bar[2]
1193
+
1194
+ for face, pts in [
1195
+ (ff, [[x-hw,y-hd,z0],[x+hw,y-hd,z0],[x+hw,y-hd,z1],[x-hw,y-hd,z1],[x-hw,y-hd,z0]]),
1196
+ (fr, [[x+hw,y-hd,z0],[x+hw,y+hd,z0],[x+hw,y+hd,z1],[x+hw,y-hd,z1],[x+hw,y-hd,z0]]),
1197
+ (ft, [[x-hw,y-hd,z1],[x+hw,y-hd,z1],[x+hw,y+hd,z1],[x-hw,y+hd,z1],[x-hw,y-hd,z1]]),
1198
+ ]:
1199
+ face.set_points_as_corners([np.array(p) for p in pts])
1200
+
1201
+ def _build_axis_labels(self, scene: Optional[ThreeDScene]) -> None:
1202
+ self.axis_labels = VGroup()
1203
+ for k in range(self.n_coins + 1):
1204
+ x = self._bar_x(k)
1205
+ lbl = Text(str(k), font_size=14, color=_with_opacity(WHITE, 0.50))
1206
+ lbl.move_to(np.array([x, -self._bar_depth / 2, -0.25]))
1207
+ self.axis_labels.add(lbl)
1208
+ if scene is not None:
1209
+ scene.add_fixed_orientation_mobjects(lbl)
1210
+ self.add(self.axis_labels)
1211
+
1212
+ # ------------------------------------------------------------------
1213
+
1214
+ def add_trial(
1215
+ self,
1216
+ trial_index: int,
1217
+ animate: bool = True,
1218
+ run_time: float = 0.10,
1219
+ ) -> Optional[AnimationGroup]:
1220
+ """Record the result for *trial_index* and update the histogram."""
1221
+ k = self._results[trial_index]
1222
+ self._counts[k] += 1
1223
+ self._max_count = max(self._max_count, int(self._counts.max()))
1224
+
1225
+ # Rescale all bars
1226
+ for i in self._bar_mobs:
1227
+ self._update_bar(i)
1228
+
1229
+ if k not in self._bar_mobs:
1230
+ h = (self._counts[k] / self._max_count) * self.z_scale * 4.0
1231
+ bar = self._build_bar(k, max(h, 0.01))
1232
+ self._bar_mobs[k] = bar
1233
+ self.bars.add(bar)
1234
+ if animate:
1235
+ return FadeIn(bar, run_time=run_time)
1236
+ return None
1237
+
1238
+ def build_pmf_overlay(self) -> VGroup:
1239
+ """Build the theoretical Binomial(n, p) PMF as a step-line overlay.
1240
+
1241
+ Returns the VGroup so the caller can animate it with ``Create``.
1242
+ """
1243
+ from math import comb as _comb
1244
+ self.pmf_overlay = VGroup()
1245
+ self.add(self.pmf_overlay)
1246
+
1247
+ max_bar_h = self.z_scale * 4.0
1248
+
1249
+ prev_prob = 0.0
1250
+ pts: List[np.ndarray] = []
1251
+ for k in range(self.n_coins + 1):
1252
+ prob = _comb(self.n_coins, k) * (self.p ** k) * ((1 - self.p) ** (self.n_coins - k))
1253
+ x = self._bar_x(k)
1254
+ hd = self._bar_depth / 2
1255
+ z = prob * max_bar_h / max(
1256
+ _comb(self.n_coins, int(self.n_coins * self.p)) *
1257
+ (self.p ** int(self.n_coins * self.p)) *
1258
+ ((1 - self.p) ** (self.n_coins - int(self.n_coins * self.p))),
1259
+ 1e-9,
1260
+ )
1261
+ pts.append(np.array([x, -hd, z]))
1262
+
1263
+ curve = VMobject()
1264
+ curve.set_points_as_corners(pts)
1265
+ curve.set_stroke(color=_with_opacity(self.pmf_color, 0.88), width=2.5)
1266
+ curve.set_fill(opacity=0)
1267
+
1268
+ if True: # glow
1269
+ glow = VMobject()
1270
+ glow.set_points_as_corners(pts)
1271
+ glow.set_stroke(color=_with_opacity(self.pmf_color, 0.14), width=8.0)
1272
+ glow.set_fill(opacity=0)
1273
+ self.pmf_overlay.add(glow)
1274
+
1275
+ self.pmf_overlay.add(curve)
1276
+
1277
+ # Dot at each k
1278
+ for k, pt in enumerate(pts):
1279
+ d = Dot3D(point=pt, radius=0.06,
1280
+ color=_with_opacity(self.pmf_color, 0.85))
1281
+ self.pmf_overlay.add(d)
1282
+
1283
+ return self.pmf_overlay
1284
+
1285
+ def run_accumulation(
1286
+ self,
1287
+ scene: ThreeDScene,
1288
+ n_visible: int = 50,
1289
+ run_time_per: float = 0.09,
1290
+ show_pmf_after: bool = True,
1291
+ ) -> None:
1292
+ """Animate the full accumulation directly on *scene*.
1293
+
1294
+ Parameters
1295
+ ----------
1296
+ n_visible : int
1297
+ Number of trials animated individually.
1298
+ run_time_per : float
1299
+ Duration per animated trial.
1300
+ show_pmf_after : bool
1301
+ If True, draw the Binomial PMF overlay after accumulation.
1302
+ """
1303
+ scene.play(FadeIn(self.axis_labels, run_time=0.4))
1304
+
1305
+ for i in range(min(n_visible, self.n_trials)):
1306
+ anim = self.add_trial(i, animate=True, run_time=run_time_per)
1307
+ if anim is not None:
1308
+ scene.play(anim)
1309
+ else:
1310
+ scene.wait(run_time_per * 0.3)
1311
+
1312
+ # Silent batch
1313
+ for i in range(n_visible, self.n_trials):
1314
+ self.add_trial(i, animate=False)
1315
+ scene.wait(0.3)
1316
+
1317
+ if show_pmf_after:
1318
+ pmf = self.build_pmf_overlay()
1319
+ scene.play(Create(pmf, run_time=1.2))
1320
+ scene.wait(1.0)
1321
+
1322
+
1323
+ # ---------------------------------------------------------------------------
1324
+ # LLNAccumulator
1325
+ # ---------------------------------------------------------------------------
1326
+
1327
+ class LLNAccumulator(VGroup):
1328
+ """Flip a biased coin repeatedly and track the running relative frequency.
1329
+
1330
+ Plots the running proportion of heads as a ``LineSeries3D``-style
1331
+ VMobject that extends right with each new flip. Shows convergence
1332
+ to the true probability p (Law of Large Numbers).
1333
+
1334
+ Parameters
1335
+ ----------
1336
+ p : float
1337
+ True probability of heads.
1338
+ n_flips : int
1339
+ Total number of flips to simulate.
1340
+ rng_seed : int
1341
+ chart_x_start : float
1342
+ Left edge of the line plot.
1343
+ chart_width : float
1344
+ Total width of the plot in scene units.
1345
+ chart_z_scale : float
1346
+ Total height of the plot (z-axis scale).
1347
+ line_color : ManimColor
1348
+ Running frequency line colour.
1349
+ true_p_color : ManimColor
1350
+ Horizontal reference line at z = p.
1351
+ scene : ThreeDScene or None
1352
+ """
1353
+
1354
+ def __init__(
1355
+ self,
1356
+ p: float = 0.5,
1357
+ n_flips: int = 300,
1358
+ rng_seed: int = 42,
1359
+ chart_x_start: float = -3.0,
1360
+ chart_width: float = 6.0,
1361
+ chart_z_scale: float = 3.5,
1362
+ line_color: ManimColor = ManimColor("#4A90D9"),
1363
+ true_p_color: ManimColor = ManimColor("#E8593C"),
1364
+ scene: Optional[ThreeDScene] = None,
1365
+ **kwargs,
1366
+ ):
1367
+ super().__init__(**kwargs)
1368
+
1369
+ self.p = p
1370
+ self.n_flips = n_flips
1371
+ self._scene = scene
1372
+ self.x_start = chart_x_start
1373
+ self.width = chart_width
1374
+ self.z_scale = chart_z_scale
1375
+ self.line_color = line_color
1376
+ self.true_p_color = true_p_color
1377
+
1378
+ rng = np.random.default_rng(rng_seed)
1379
+ self._flips: np.ndarray = rng.binomial(1, p, n_flips).astype(float)
1380
+
1381
+ # Running mean after each flip
1382
+ self._running: np.ndarray = np.cumsum(self._flips) / np.arange(1, n_flips + 1)
1383
+
1384
+ # x positions for each flip
1385
+ self._xs: np.ndarray = np.linspace(chart_x_start,
1386
+ chart_x_start + chart_width, n_flips)
1387
+
1388
+ # Visual objects
1389
+ self.freq_line = VMobject()
1390
+ self.freq_line.set_stroke(color=_with_opacity(line_color, 0.90), width=2.2)
1391
+ self.freq_line.set_fill(opacity=0)
1392
+ self._pts_built: int = 0
1393
+
1394
+ # Glow
1395
+ self.freq_glow = VMobject()
1396
+ self.freq_glow.set_stroke(color=_with_opacity(line_color, 0.12), width=7.0)
1397
+ self.freq_glow.set_fill(opacity=0)
1398
+
1399
+ # True p reference line
1400
+ true_z = p * chart_z_scale
1401
+ self.true_p_line = DashedLine(
1402
+ np.array([chart_x_start, 0, true_z]),
1403
+ np.array([chart_x_start + chart_width, 0, true_z]),
1404
+ dash_length=0.08, dashed_ratio=0.4,
1405
+ color=_with_opacity(true_p_color, 0.75),
1406
+ stroke_width=1.8,
1407
+ )
1408
+
1409
+ # p label
1410
+ p_lbl = Text(f"p = {p}", font_size=18, color=true_p_color)
1411
+ p_lbl.move_to(np.array([chart_x_start + chart_width + 0.35, 0, true_z]))
1412
+ self._p_label = VGroup(p_lbl)
1413
+ if scene is not None:
1414
+ scene.add_fixed_orientation_mobjects(p_lbl)
1415
+
1416
+ # n label (updates live)
1417
+ self._n_label_pos = np.array([chart_x_start + chart_width * 0.5, 0, -0.35])
1418
+
1419
+ self.add(self.true_p_line, self._p_label, self.freq_glow, self.freq_line)
1420
+
1421
+ # ------------------------------------------------------------------
1422
+
1423
+ def _flip_to_point(self, i: int) -> np.ndarray:
1424
+ return np.array([self._xs[i], 0.0, self._running[i] * self.z_scale])
1425
+
1426
+ def extend_to(self, n: int) -> None:
1427
+ """Extend the frequency line to *n* flips (immediate, no animation)."""
1428
+ n = min(n, self.n_flips)
1429
+ if n <= self._pts_built:
1430
+ return
1431
+ pts = [self._flip_to_point(i) for i in range(self._pts_built, n)]
1432
+ all_pts = (
1433
+ [self._flip_to_point(i) for i in range(self._pts_built)] + pts
1434
+ if self._pts_built > 0 else pts
1435
+ )
1436
+ if len(all_pts) > 1:
1437
+ self.freq_line.set_points_as_corners(all_pts)
1438
+ self.freq_glow.set_points_as_corners(all_pts)
1439
+ self._pts_built = n
1440
+
1441
+ def animate_draw(
1442
+ self,
1443
+ scene: ThreeDScene,
1444
+ batch_size: int = 5,
1445
+ run_time_per_batch: float = 0.06,
1446
+ final_hold: float = 1.5,
1447
+ ) -> None:
1448
+ """Animate the line extending flip-by-flip directly on *scene*.
1449
+
1450
+ Parameters
1451
+ ----------
1452
+ batch_size : int
1453
+ Number of flips added per animation frame.
1454
+ run_time_per_batch : float
1455
+ Duration per batch animation.
1456
+ """
1457
+ scene.play(Create(self.true_p_line, run_time=0.6))
1458
+ scene.play(FadeIn(self._p_label, run_time=0.3))
1459
+
1460
+ all_pts: List[np.ndarray] = []
1461
+
1462
+ def make_extend_updater(target_n: int):
1463
+ start_pts = list(all_pts)
1464
+
1465
+ def updater(mob: VMobject, alpha: float) -> None:
1466
+ new_pts = [self._flip_to_point(i)
1467
+ for i in range(len(start_pts),
1468
+ len(start_pts) + batch_size)]
1469
+ combined = start_pts + new_pts[:max(1, int(alpha * batch_size))]
1470
+ if len(combined) > 1:
1471
+ mob.set_points_as_corners(combined)
1472
+ return updater
1473
+
1474
+ for start in range(0, self.n_flips, batch_size):
1475
+ end = min(start + batch_size, self.n_flips)
1476
+ new_pts = [self._flip_to_point(i) for i in range(start, end)]
1477
+ all_pts.extend(new_pts)
1478
+
1479
+ if len(all_pts) > 1:
1480
+ self.freq_line.set_points_as_corners(all_pts)
1481
+ self.freq_glow.set_points_as_corners(all_pts)
1482
+ scene.wait(run_time_per_batch)
1483
+
1484
+ scene.wait(final_hold)
1485
+
1486
+ def get_final_frequency(self) -> float:
1487
+ return float(self._running[-1])
1488
+
1489
+
1490
+ # ---------------------------------------------------------------------------
1491
+ # DiceSumAccumulator
1492
+ # ---------------------------------------------------------------------------
1493
+
1494
+ class DiceSumAccumulator(VGroup):
1495
+ """Roll multiple dice, accumulate sum distribution as a bar chart.
1496
+
1497
+ With 2 dice the sums 2–12 form a triangular distribution.
1498
+ With more dice the CLT kicks in and the distribution normalises.
1499
+
1500
+ Parameters
1501
+ ----------
1502
+ n_dice : int
1503
+ Number of dice per roll (2 = classic, 3+ shows CLT).
1504
+ n_faces : int
1505
+ Faces per die (default 6 for standard D6).
1506
+ n_trials : int
1507
+ Number of rolls to simulate.
1508
+ rng_seed : int
1509
+ chart_x : float
1510
+ X centre of the bar chart.
1511
+ z_scale : float
1512
+ bar_color : ManimColor
1513
+ Base colour for all bars.
1514
+ normal_color : ManimColor
1515
+ Colour of the CLT normal overlay (shown when n_dice ≥ 3).
1516
+ scene : ThreeDScene or None
1517
+ """
1518
+
1519
+ def __init__(
1520
+ self,
1521
+ n_dice: int = 2,
1522
+ n_faces: int = 6,
1523
+ n_trials: int = 500,
1524
+ rng_seed: int = 42,
1525
+ chart_x: float = 0.0,
1526
+ z_scale: float = 0.75,
1527
+ bar_color: ManimColor = ManimColor("#E8593C"),
1528
+ normal_color: ManimColor = ManimColor("#4A90D9"),
1529
+ scene: Optional[ThreeDScene] = None,
1530
+ **kwargs,
1531
+ ):
1532
+ super().__init__(**kwargs)
1533
+
1534
+ self.n_dice = n_dice
1535
+ self.n_faces = n_faces
1536
+ self.n_trials = n_trials
1537
+ self.z_scale = z_scale
1538
+ self.bar_color = bar_color
1539
+ self.normal_color = normal_color
1540
+ self._scene = scene
1541
+ self.chart_x = chart_x
1542
+
1543
+ rng = np.random.default_rng(rng_seed)
1544
+ rolls = rng.integers(1, n_faces + 1, size=(n_trials, n_dice))
1545
+ self._sums: np.ndarray = rolls.sum(axis=1)
1546
+
1547
+ # Possible sums: n_dice … n_dice * n_faces
1548
+ self._min_sum = n_dice
1549
+ self._max_sum = n_dice * n_faces
1550
+ n_buckets = self._max_sum - self._min_sum + 1
1551
+ self._counts: np.ndarray = np.zeros(n_buckets, dtype=int)
1552
+ self._max_count: int = 1
1553
+ self._bar_mobs: Dict[int, VGroup] = {}
1554
+
1555
+ self._bar_w = min(0.50, 5.0 / n_buckets)
1556
+ self._bar_depth = 0.35
1557
+ self._spacing = min(0.65, 6.0 / n_buckets)
1558
+ x_total = (n_buckets - 1) * self._spacing
1559
+ self._x0 = chart_x - x_total / 2
1560
+
1561
+ self.bars = VGroup()
1562
+ self.normal_overlay = VGroup()
1563
+ self.add(self.bars, self.normal_overlay)
1564
+ self._build_axis_labels(scene)
1565
+
1566
+ # ------------------------------------------------------------------
1567
+
1568
+ def _sum_x(self, s: int) -> float:
1569
+ return self._x0 + (s - self._min_sum) * self._spacing
1570
+
1571
+ def _build_bar(self, s: int, height: float) -> VGroup:
1572
+ x = self._sum_x(s)
1573
+ hw = self._bar_w / 2
1574
+ hd = self._bar_depth / 2
1575
+ y, z0, z1 = 0.0, 0.0, max(height, 0.01)
1576
+ col = self.bar_color
1577
+ col_r = _darken(col, 0.60)
1578
+ col_t = _lighten(col, 1.28)
1579
+
1580
+ ff = Polygon(
1581
+ np.array([x-hw,y-hd,z0]), np.array([x+hw,y-hd,z0]),
1582
+ np.array([x+hw,y-hd,z1]), np.array([x-hw,y-hd,z1]),
1583
+ fill_color=_with_opacity(col, 0.90), fill_opacity=1.0, stroke_width=0,
1584
+ )
1585
+ fr = Polygon(
1586
+ np.array([x+hw,y-hd,z0]), np.array([x+hw,y+hd,z0]),
1587
+ np.array([x+hw,y+hd,z1]), np.array([x+hw,y-hd,z1]),
1588
+ fill_color=_with_opacity(col_r, 0.88), fill_opacity=1.0, stroke_width=0,
1589
+ )
1590
+ ft = Polygon(
1591
+ np.array([x-hw,y-hd,z1]), np.array([x+hw,y-hd,z1]),
1592
+ np.array([x+hw,y+hd,z1]), np.array([x-hw,y+hd,z1]),
1593
+ fill_color=_with_opacity(col_t, 0.80), fill_opacity=1.0, stroke_width=0,
1594
+ )
1595
+ return VGroup(ff, fr, ft)
1596
+
1597
+ def _update_bar(self, s: int) -> None:
1598
+ count = self._counts[s - self._min_sum]
1599
+ height = (count / self._max_count) * self.z_scale * 4.0
1600
+ x = self._sum_x(s)
1601
+ hw = self._bar_w / 2
1602
+ hd = self._bar_depth / 2
1603
+ y, z0, z1 = 0.0, 0.0, max(height, 0.01)
1604
+ bar = self._bar_mobs[s]
1605
+ for face, pts in [
1606
+ (bar[0], [[x-hw,y-hd,z0],[x+hw,y-hd,z0],[x+hw,y-hd,z1],[x-hw,y-hd,z1],[x-hw,y-hd,z0]]),
1607
+ (bar[1], [[x+hw,y-hd,z0],[x+hw,y+hd,z0],[x+hw,y+hd,z1],[x+hw,y-hd,z1],[x+hw,y-hd,z0]]),
1608
+ (bar[2], [[x-hw,y-hd,z1],[x+hw,y-hd,z1],[x+hw,y+hd,z1],[x-hw,y+hd,z1],[x-hw,y-hd,z1]]),
1609
+ ]:
1610
+ face.set_points_as_corners([np.array(p) for p in pts])
1611
+
1612
+ def _build_axis_labels(self, scene: Optional[ThreeDScene]) -> None:
1613
+ self.axis_labels = VGroup()
1614
+ step = max(1, (self._max_sum - self._min_sum) // 10)
1615
+ for s in range(self._min_sum, self._max_sum + 1, step):
1616
+ lbl = Text(str(s), font_size=14, color=_with_opacity(WHITE, 0.50))
1617
+ lbl.move_to(np.array([self._sum_x(s), -self._bar_depth / 2, -0.25]))
1618
+ self.axis_labels.add(lbl)
1619
+ if scene is not None:
1620
+ scene.add_fixed_orientation_mobjects(lbl)
1621
+ self.add(self.axis_labels)
1622
+
1623
+ def add_trial(self, trial_index: int, animate: bool = True,
1624
+ run_time: float = 0.09) -> Optional[AnimationGroup]:
1625
+ s = int(self._sums[trial_index])
1626
+ idx = s - self._min_sum
1627
+ self._counts[idx] += 1
1628
+ self._max_count = max(self._max_count, int(self._counts.max()))
1629
+
1630
+ for existing_s in self._bar_mobs:
1631
+ self._update_bar(existing_s)
1632
+
1633
+ if s not in self._bar_mobs:
1634
+ h = (self._counts[idx] / self._max_count) * self.z_scale * 4.0
1635
+ bar = self._build_bar(s, max(h, 0.01))
1636
+ self._bar_mobs[s] = bar
1637
+ self.bars.add(bar)
1638
+ if animate:
1639
+ return FadeIn(bar, run_time=run_time)
1640
+ return None
1641
+
1642
+ def build_normal_overlay(self) -> VGroup:
1643
+ """Build a normal approximation overlay (useful for n_dice ≥ 3)."""
1644
+ import numpy as np as _np
1645
+ mu_sum = self.n_dice * (self.n_faces + 1) / 2
1646
+ var_one = (self.n_faces ** 2 - 1) / 12
1647
+ sigma_sum = np.sqrt(self.n_dice * var_one)
1648
+
1649
+ xs_data = np.linspace(self._min_sum, self._max_sum, 300)
1650
+ ys = np.exp(-0.5 * ((xs_data - mu_sum) / sigma_sum) ** 2)
1651
+ ys = ys / ys.max() * self.z_scale * 4.0
1652
+
1653
+ pts = [
1654
+ np.array([self._sum_x(int(round(xd))), -self._bar_depth / 2, max(float(zv), 0.0)])
1655
+ for xd, zv in zip(xs_data, ys)
1656
+ ]
1657
+ curve = VMobject()
1658
+ curve.set_points_as_corners(pts)
1659
+ col = self.normal_color
1660
+ curve.set_stroke(color=_with_opacity(col, 0.90), width=2.5)
1661
+ curve.set_fill(opacity=0)
1662
+
1663
+ glow = VMobject()
1664
+ glow.set_points_as_corners(pts)
1665
+ glow.set_stroke(color=_with_opacity(col, 0.13), width=8.0)
1666
+ glow.set_fill(opacity=0)
1667
+
1668
+ self.normal_overlay.add(glow, curve)
1669
+ return self.normal_overlay
1670
+
1671
+ def run_accumulation(
1672
+ self,
1673
+ scene: ThreeDScene,
1674
+ n_visible: int = 60,
1675
+ run_time_per: float = 0.09,
1676
+ show_normal_after: bool = True,
1677
+ ) -> None:
1678
+ scene.play(FadeIn(self.axis_labels, run_time=0.4))
1679
+ for i in range(min(n_visible, self.n_trials)):
1680
+ anim = self.add_trial(i, animate=True, run_time=run_time_per)
1681
+ if anim is not None:
1682
+ scene.play(anim)
1683
+ else:
1684
+ scene.wait(run_time_per * 0.3)
1685
+ for i in range(n_visible, self.n_trials):
1686
+ self.add_trial(i, animate=False)
1687
+ scene.wait(0.4)
1688
+ if show_normal_after and self.n_dice >= 3:
1689
+ ov = self.build_normal_overlay()
1690
+ scene.play(Create(ov, run_time=1.1))
1691
+ scene.wait(1.0)
1692
+
1693
+
1694
+ # ---------------------------------------------------------------------------
1695
+ # Ready-to-render ThreeDScene subclasses
1696
+ # ---------------------------------------------------------------------------
1697
+
1698
+ class CoinFlipScene(ThreeDScene):
1699
+ """Demonstrate a single biased coin flip with trail and result label.
1700
+
1701
+ Render: manim -pql flip_roll.py CoinFlipScene
1702
+ """
1703
+
1704
+ def construct(self):
1705
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-45 * DEGREES)
1706
+ self.begin_ambient_camera_rotation(rate=0.05)
1707
+
1708
+ coin = Coin3D(radius=0.48, thickness=0.11)
1709
+ self.add(coin)
1710
+ self.wait(0.3)
1711
+
1712
+ for outcome, x_pos in [("heads", -1.2), ("tails", 1.2)]:
1713
+ cfg = FlipConfig(
1714
+ flip_style="tumble",
1715
+ settle_style="bounce",
1716
+ arc_height=2.4,
1717
+ n_spins=3.5,
1718
+ run_time=1.5,
1719
+ bounce_height=0.25,
1720
+ trail_opacity=0.30,
1721
+ trail_n_dots=10,
1722
+ )
1723
+ c = Coin3D(radius=0.48, thickness=0.11,
1724
+ position=np.array([x_pos, 0, 0]))
1725
+ self.add(c)
1726
+ flip = CoinFlipAnimation(c, outcome=outcome, config=cfg, scene=self)
1727
+ self.play(*flip.build(self))
1728
+ self.wait(0.4)
1729
+
1730
+ self.wait(1.5)
1731
+
1732
+
1733
+ class DieRollScene(ThreeDScene):
1734
+ """Roll a die with each of the three roll styles back to back.
1735
+
1736
+ Render: manim -pql flip_roll.py DieRollScene
1737
+ """
1738
+
1739
+ def construct(self):
1740
+ self.set_camera_orientation(phi=68 * DEGREES, theta=-50 * DEGREES)
1741
+ self.begin_ambient_camera_rotation(rate=0.04)
1742
+
1743
+ for outcome, x, style in [(3, -2.5, "toss"), (5, 0.0, "roll"), (1, 2.5, "drop")]:
1744
+ die = Die3D(size=0.38, position=np.array([x, 0.0, 0.38]))
1745
+ self.add(die)
1746
+
1747
+ cfg = RollConfig(
1748
+ roll_style=style,
1749
+ arc_height=2.0,
1750
+ n_tumbles=2.5,
1751
+ run_time=1.8,
1752
+ n_bounces=1,
1753
+ bounce_decay=0.35,
1754
+ )
1755
+ roll = DieRollAnimation(
1756
+ die, outcome=outcome, config=cfg,
1757
+ rest_position=np.array([x, 0.0, die.die_size]),
1758
+ scene=self,
1759
+ )
1760
+ self.play(*roll.build(self))
1761
+ self.wait(0.5)
1762
+
1763
+ self.wait(1.5)
1764
+
1765
+
1766
+ class BinomialScene(ThreeDScene):
1767
+ """Accumulate coin flips into a Binomial(10, 0.5) histogram.
1768
+
1769
+ Render: manim -pql flip_roll.py BinomialScene
1770
+ """
1771
+
1772
+ def construct(self):
1773
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1774
+
1775
+ accum = BinomialAccumulator(
1776
+ n_coins=10, p=0.5, n_trials=600,
1777
+ chart_x=0.0, chart_z_scale=0.80,
1778
+ scene=self,
1779
+ )
1780
+ self.add(accum)
1781
+ accum.run_accumulation(self, n_visible=60,
1782
+ run_time_per=0.09, show_pmf_after=True)
1783
+ self.wait(2)
1784
+
1785
+
1786
+ class LLNScene(ThreeDScene):
1787
+ """Running frequency converges to p. Law of Large Numbers.
1788
+
1789
+ Uses a biased coin (p=0.3) so convergence is visually obvious.
1790
+
1791
+ Render: manim -pql flip_roll.py LLNScene
1792
+ """
1793
+
1794
+ def construct(self):
1795
+ self.set_camera_orientation(phi=62 * DEGREES, theta=-48 * DEGREES)
1796
+
1797
+ accum = LLNAccumulator(
1798
+ p=0.30, n_flips=400, chart_x_start=-3.5,
1799
+ chart_width=7.0, chart_z_scale=3.5,
1800
+ scene=self,
1801
+ )
1802
+ self.add(accum)
1803
+ accum.animate_draw(self, batch_size=4, run_time_per_batch=0.05)
1804
+ self.wait(2)
1805
+
1806
+
1807
+ class DiceSumScene(ThreeDScene):
1808
+ """Two-dice sum distribution → triangular shape.
1809
+
1810
+ Render: manim -pql flip_roll.py DiceSumScene
1811
+ """
1812
+
1813
+ def construct(self):
1814
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1815
+
1816
+ # Two dice
1817
+ accum2 = DiceSumAccumulator(
1818
+ n_dice=2, n_faces=6, n_trials=500,
1819
+ chart_x=-2.5, z_scale=0.75,
1820
+ bar_color=ManimColor("#4A90D9"),
1821
+ scene=self,
1822
+ )
1823
+ self.add(accum2)
1824
+ accum2.run_accumulation(self, n_visible=55, run_time_per=0.09,
1825
+ show_normal_after=False)
1826
+
1827
+ title2 = Text("2 dice: triangular", font_size=20,
1828
+ color=ManimColor("#4A90D9"))
1829
+ title2.move_to(np.array([-2.5, 0, -0.55]))
1830
+ self.add_fixed_orientation_mobjects(title2)
1831
+ self.add(title2)
1832
+ self.wait(1.0)
1833
+
1834
+ # Three dice — shows CLT beginning
1835
+ accum3 = DiceSumAccumulator(
1836
+ n_dice=3, n_faces=6, n_trials=500,
1837
+ chart_x=2.5, z_scale=0.75,
1838
+ bar_color=ManimColor("#2DAA6E"),
1839
+ normal_color=ManimColor("#E8593C"),
1840
+ scene=self,
1841
+ )
1842
+ self.add(accum3)
1843
+ accum3.run_accumulation(self, n_visible=55, run_time_per=0.09,
1844
+ show_normal_after=True)
1845
+
1846
+ title3 = Text("3 dice: approaching normal", font_size=20,
1847
+ color=ManimColor("#2DAA6E"))
1848
+ title3.move_to(np.array([2.5, 0, -0.55]))
1849
+ self.add_fixed_orientation_mobjects(title3)
1850
+ self.add(title3)
1851
+ self.wait(2)