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
statanim/props/urn.py ADDED
@@ -0,0 +1,1531 @@
1
+ """
2
+ statanim/props/urn.py
3
+ ========================
4
+ Urn3D & Ball3D — Highly detailed, physically-inspired 3D urn and ball
5
+ props for Manim statistics animations.
6
+
7
+ Primary use cases
8
+ -----------------
9
+ Hypergeometric distribution — draw without replacement from a mixed urn
10
+ Conditional probability — Bayes / Urn problems
11
+ Combinatorics — ordered / unordered draws
12
+ Sampling demonstrations — with / without replacement
13
+
14
+ Design goals
15
+ ------------
16
+ Urn3D
17
+ * Classical amphora silhouette — lathe-profile built from a Bézier
18
+ spine: foot ring → base taper → wide belly → shoulder curve →
19
+ narrow neck → flared lip. NOT a plain cylinder.
20
+ * Dual-wall construction — outer surface (glazed ceramic) +
21
+ inner dark well visible from above, creating genuine depth.
22
+ * Decorative meander band — Greek key pattern drawn as a VGroup
23
+ of thin Polygons wrapped around the belly equator.
24
+ * Ear handles — two torus-arc handles, one per side,
25
+ correctly proportioned and attached at neck and shoulder.
26
+ * Multi-layer ceramic shading — base glaze, specular highlight stripe
27
+ down the lit side, ambient-occlusion darkening near curves.
28
+ * Optional lid — domed lid with a spherical knob;
29
+ can be animated open/closed.
30
+
31
+ Ball3D
32
+ * Correct sphere layering — dark shadow hemisphere (bottom),
33
+ mid-tone body, bright specular cap (top-left), thin rim highlight.
34
+ * Visible label — number or letter centred on the
35
+ ball's face, sized to the ball radius.
36
+ * Configurable color — any named palette or hex color.
37
+ * Packing positions — `get_packed_positions()` returns
38
+ realistic staggered ball-stack coordinates inside the urn interior.
39
+
40
+ Animations
41
+ ----------
42
+ DrawBall — ball rises out of urn (smooth ease-out), moves to hand pos
43
+ ReplaceBall — ball arcs back in and sinks
44
+ ShakeUrn — rapid lateral oscillation of the whole urn
45
+ PourUrn — urn tilts, balls roll/fall out in sequence
46
+ FillUrn — balls drop in one by one from above
47
+ SwapBalls — two balls exchange positions (for conditional demos)
48
+
49
+ Dependencies
50
+ ------------
51
+ manim (CE or GL), numpy
52
+
53
+ Usage
54
+ -----
55
+ from statanim.props.urn import Urn3D, Ball3D, DrawBall, FillUrn
56
+
57
+ class HypergeometricScene(ThreeDScene):
58
+ def construct(self):
59
+ urn = Urn3D(color_scheme="terracotta", n_slots=10)
60
+ balls = [
61
+ Ball3D(color="#E63946", label=str(i)) for i in range(6)
62
+ ] + [
63
+ Ball3D(color="#457B9D", label=str(i)) for i in range(4)
64
+ ]
65
+ self.play(FillUrn(urn, balls))
66
+ drawn = balls[0]
67
+ self.play(DrawBall(urn, drawn))
68
+ """
69
+
70
+ from __future__ import annotations
71
+
72
+ import numpy as np
73
+ from typing import Literal, Optional, List, Tuple
74
+
75
+ from manim import (
76
+ VGroup,
77
+ Sphere, Cylinder, Torus, Circle, Annulus,
78
+ Polygon, Rectangle, Square, Line, Arc,
79
+ Text, MathTex,
80
+ Animation, Succession, AnimationGroup,
81
+ ApplyMethod, FadeIn, FadeOut, MoveAlongPath,
82
+ Rotate,
83
+ CubicBezier,
84
+ interpolate_color, color_to_rgb,
85
+ WHITE, BLACK,
86
+ GREY, GREY_A, GREY_B, GREY_C, GREY_D, LIGHT_GREY,
87
+ RED, RED_A, RED_B, RED_C,
88
+ BLUE, BLUE_A, BLUE_B, BLUE_C,
89
+ GREEN_A, GREEN_E, YELLOW, GOLD, GOLD_A, GOLD_D,
90
+ ORANGE, PURPLE_A,
91
+ UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
92
+ PI, TAU,
93
+ rate_functions,
94
+ ManimColor,
95
+ ArcBetweenPoints,
96
+ ParametricFunction,
97
+ Surface,
98
+ )
99
+
100
+ # ──────────────────────────────────────────────────────────────────────────────
101
+ # Colour Palettes ── Urn body
102
+ # ──────────────────────────────────────────────────────────────────────────────
103
+
104
+ URN_PALETTES: dict[str, dict] = {
105
+ # Classic fired terracotta with black meander band
106
+ "terracotta": {
107
+ "glaze": "#C1440E", # main body
108
+ "glaze_dark": "#7A2A08", # shadow / AO areas
109
+ "glaze_light":"#E8784A", # lit highlight stripe
110
+ "band_bg": "#1A1008", # meander band background
111
+ "band_fg": "#C1440E", # meander key colour
112
+ "inner": "#2A1208", # inside well (very dark)
113
+ "lip": "#D4552A", # top lip ring
114
+ "foot": "#7A2A08", # foot ring
115
+ "handle": "#A33A0A", # ear handles
116
+ "lid_body": "#C1440E",
117
+ "lid_knob": "#7A2A08",
118
+ "specular": "#F0A070",
119
+ },
120
+ # Athenian black-figure style
121
+ "black_figure": {
122
+ "glaze": "#1C1008",
123
+ "glaze_dark": "#0A0804",
124
+ "glaze_light":"#3A2810",
125
+ "band_bg": "#C1440E",
126
+ "band_fg": "#1C1008",
127
+ "inner": "#050303",
128
+ "lip": "#3A2810",
129
+ "foot": "#0A0804",
130
+ "handle": "#1C1008",
131
+ "lid_body": "#1C1008",
132
+ "lid_knob": "#C1440E",
133
+ "specular": "#5A4020",
134
+ },
135
+ # Cobalt blue glazed ceramic
136
+ "cobalt": {
137
+ "glaze": "#1B3A8A",
138
+ "glaze_dark": "#0D1E52",
139
+ "glaze_light":"#4A70CC",
140
+ "band_bg": "#F0E8C0",
141
+ "band_fg": "#1B3A8A",
142
+ "inner": "#080E20",
143
+ "lip": "#2A4EB8",
144
+ "foot": "#0D1E52",
145
+ "handle": "#1B3A8A",
146
+ "lid_body": "#1B3A8A",
147
+ "lid_knob": "#F0E8C0",
148
+ "specular": "#8AAAE8",
149
+ },
150
+ # Ivory celadon with gold band
151
+ "celadon": {
152
+ "glaze": "#A8C5A0",
153
+ "glaze_dark": "#5A8050",
154
+ "glaze_light":"#D8EDD4",
155
+ "band_bg": "#B8960A",
156
+ "band_fg": "#F8E060",
157
+ "inner": "#1A2818",
158
+ "lip": "#C8E0C0",
159
+ "foot": "#5A8050",
160
+ "handle": "#8AAA82",
161
+ "lid_body": "#A8C5A0",
162
+ "lid_knob": "#B8960A",
163
+ "specular": "#EAFAE4",
164
+ },
165
+ # Dark obsidian / ritual urn
166
+ "obsidian": {
167
+ "glaze": "#1A1A20",
168
+ "glaze_dark": "#08080C",
169
+ "glaze_light":"#3A3A50",
170
+ "band_bg": "#D4AF37",
171
+ "band_fg": "#1A1A20",
172
+ "inner": "#04040A",
173
+ "lip": "#2A2A35",
174
+ "foot": "#08080C",
175
+ "handle": "#1A1A20",
176
+ "lid_body": "#1A1A20",
177
+ "lid_knob": "#D4AF37",
178
+ "specular": "#5A5A80",
179
+ },
180
+ # White marble with blue veining
181
+ "marble": {
182
+ "glaze": "#F4F0E8",
183
+ "glaze_dark": "#C8C0B0",
184
+ "glaze_light":"#FFFFFF",
185
+ "band_bg": "#2A4A8A",
186
+ "band_fg": "#F4F0E8",
187
+ "inner": "#2A2820",
188
+ "lip": "#E8E0D0",
189
+ "foot": "#C8C0B0",
190
+ "handle": "#D8D0C0",
191
+ "lid_body": "#F4F0E8",
192
+ "lid_knob": "#2A4A8A",
193
+ "specular": "#FFFFFF",
194
+ },
195
+ }
196
+
197
+ # Ball palette: named solid colours for common use
198
+ BALL_COLORS = {
199
+ "red": "#E63946",
200
+ "blue": "#457B9D",
201
+ "green": "#2A9D8F",
202
+ "yellow": "#E9C46A",
203
+ "white": "#F1FAEE",
204
+ "black": "#1D3557",
205
+ "orange": "#F4A261",
206
+ "purple": "#A8DADC",
207
+ "crimson": "#9B2226",
208
+ "gold": "#D4AF37",
209
+ }
210
+
211
+ # ──────────────────────────────────────────────────────────────────────────────
212
+ # Geometry helpers
213
+ # ──────────────────────────────────────────────────────────────────────────────
214
+
215
+ def _rotation_matrix_y(theta: float) -> np.ndarray:
216
+ c, s = np.cos(theta), np.sin(theta)
217
+ return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
218
+
219
+
220
+ def _lathe_profile_points(
221
+ belly_r: float,
222
+ neck_r: float,
223
+ total_h: float,
224
+ n_segments: int = 40,
225
+ ) -> np.ndarray:
226
+ """
227
+ Return (r, y) profile points for the urn silhouette via a piecewise
228
+ smooth Bézier curve:
229
+
230
+ Foot ring → base taper → belly → shoulder → neck → lip
231
+
232
+ Returns shape (n_segments, 2) array of (radius, y) values.
233
+ """
234
+ # Key profile waypoints as (r, y) normalised to belly_r=1, total_h=1
235
+ # fmt: off
236
+ ctrl = np.array([
237
+ [0.28, 0.00], # foot outer edge (bottom)
238
+ [0.32, 0.04], # foot ring bead
239
+ [0.30, 0.08], # base taper in
240
+ [0.55, 0.18], # lower belly begins to flare
241
+ [0.90, 0.35], # widest belly tangent
242
+ [1.00, 0.48], # maximum belly width
243
+ [0.95, 0.60], # upper belly
244
+ [0.72, 0.72], # shoulder starts curving in
245
+ [0.50, 0.80], # shoulder taper
246
+ [0.32, 0.86], # neck lower
247
+ [0.26, 0.91], # neck mid (slight narrowing)
248
+ [0.28, 0.95], # neck upper (slight flare)
249
+ [0.38, 0.99], # lip flare
250
+ [0.40, 1.00], # lip top
251
+ ], dtype=float)
252
+ # fmt: on
253
+ ctrl[:, 0] *= belly_r
254
+ ctrl[:, 1] = ctrl[:, 1] * total_h - total_h / 2 # centre at y=0
255
+
256
+ # Catmull-Rom spline through the control points
257
+ t_vals = np.linspace(0, 1, n_segments)
258
+ result = np.zeros((n_segments, 2))
259
+ n = len(ctrl)
260
+ for i, t in enumerate(t_vals):
261
+ # Map t to segment
262
+ seg_float = t * (n - 1)
263
+ seg = min(int(seg_float), n - 2)
264
+ local_t = seg_float - seg
265
+ # Catmull-Rom: use points seg-1, seg, seg+1, seg+2 (clamped)
266
+ p0 = ctrl[max(seg - 1, 0)]
267
+ p1 = ctrl[seg]
268
+ p2 = ctrl[min(seg + 1, n - 1)]
269
+ p3 = ctrl[min(seg + 2, n - 1)]
270
+ tt = local_t
271
+ tt2, tt3 = tt ** 2, tt ** 3
272
+ result[i] = 0.5 * (
273
+ 2 * p1
274
+ + (-p0 + p2) * tt
275
+ + (2*p0 - 5*p1 + 4*p2 - p3) * tt2
276
+ + (-p0 + 3*p1 - 3*p2 + p3) * tt3
277
+ )
278
+ return result
279
+
280
+
281
+ def _meander_key_unit(w: float, h: float) -> list[np.ndarray]:
282
+ """
283
+ One unit of a Greek meander / key pattern as a list of line
284
+ segments (start, end) pairs, normalised to box w×h.
285
+
286
+ The classic "T-spiral" unit:
287
+ ┌──┐
288
+ ─────┘ │
289
+ └──
290
+ Returns list of (start_xy, end_xy) tuples in 2-D.
291
+ """
292
+ s = min(w, h) / 4 # step size
293
+ segs = [
294
+ # Bottom horizontal run
295
+ (np.array([0, 0 ]), np.array([3*s, 0 ])),
296
+ # Up
297
+ (np.array([3*s, 0 ]), np.array([3*s, 3*s])),
298
+ # Left inner
299
+ (np.array([3*s, 3*s]), np.array([s, 3*s])),
300
+ # Down inner
301
+ (np.array([s, 3*s]), np.array([s, s ])),
302
+ # Right inner
303
+ (np.array([s, s ]), np.array([2*s, s ])),
304
+ # Up inner
305
+ (np.array([2*s, s ]), np.array([2*s, 2*s])),
306
+ # Continue top
307
+ (np.array([2*s, 2*s]), np.array([4*s, 2*s])),
308
+ ]
309
+ return segs
310
+
311
+
312
+ # ──────────────────────────────────────────────────────────────────────────────
313
+ # Ball3D
314
+ # ──────────────────────────────────────────────────────────────────────────────
315
+
316
+ class Ball3D(VGroup):
317
+ """
318
+ A detailed 3D ball for use inside Urn3D.
319
+
320
+ Layers (back → front):
321
+ 1. shadow_cap — dark hemisphere on the bottom (ambient shadow)
322
+ 2. body_sphere — full sphere in the ball's colour
323
+ 3. specular_cap — bright ellipse on the top-left (specular reflection)
324
+ 4. rim_ring — thin bright annulus around the specular cap edge
325
+ 5. label — centred text (number or letter), facing +Z
326
+
327
+ Parameters
328
+ ----------
329
+ color : str
330
+ Named key from ``BALL_COLORS`` or any hex colour string.
331
+ label : str | None
332
+ Text to display on the ball face. Default ``None`` (no label).
333
+ radius : float
334
+ Ball radius in Manim units. Default ``0.18``.
335
+ label_color : str | None
336
+ Override for label text colour; auto-contrasts if None.
337
+ resolution : int
338
+ Sphere surface resolution. Default ``16``.
339
+
340
+ Attributes
341
+ ----------
342
+ ball_color : str
343
+ ball_radius : float
344
+ label_text : str | None
345
+ """
346
+
347
+ def __init__(
348
+ self,
349
+ color: str = "red",
350
+ label: Optional[str] = None,
351
+ radius: float = 0.18,
352
+ label_color: Optional[str] = None,
353
+ resolution: int = 16,
354
+ **kwargs,
355
+ ):
356
+ super().__init__(**kwargs)
357
+
358
+ # Resolve colour
359
+ hex_col = BALL_COLORS.get(color, color)
360
+ self.ball_color = hex_col
361
+ self.ball_radius = radius
362
+ self.label_text = label
363
+
364
+ dark_col = interpolate_color(hex_col, BLACK, 0.60)
365
+ light_col = interpolate_color(hex_col, WHITE, 0.55)
366
+ rim_col = interpolate_color(hex_col, WHITE, 0.35)
367
+
368
+ # ── 1. Shadow hemisphere cap (bottom dark zone) ───────────────
369
+ # Approximate with a dark-filled sphere slightly smaller and offset
370
+ shadow = Sphere(
371
+ radius=radius * 0.98,
372
+ resolution=(resolution // 2, resolution // 2),
373
+ fill_color=dark_col,
374
+ fill_opacity=0.55,
375
+ stroke_width=0,
376
+ )
377
+ shadow.shift(DOWN * radius * 0.12)
378
+ self.add(shadow)
379
+
380
+ # ── 2. Main body sphere ───────────────────────────────────────
381
+ body = Sphere(
382
+ radius=radius,
383
+ resolution=(resolution, resolution),
384
+ fill_color=hex_col,
385
+ fill_opacity=1.0,
386
+ stroke_width=0,
387
+ )
388
+ self.add(body)
389
+
390
+ # ── 3. Specular highlight cap ─────────────────────────────────
391
+ spec = Circle(
392
+ radius=radius * 0.36,
393
+ fill_color=light_col,
394
+ fill_opacity=0.72,
395
+ stroke_width=0,
396
+ )
397
+ spec.scale([1.3, 0.85, 1]) # ellipse
398
+ spec.move_to(
399
+ np.array([-radius * 0.28, radius * 0.30, radius * 0.88])
400
+ )
401
+ self.add(spec)
402
+
403
+ # ── 4. Rim ring ───────────────────────────────────────────────
404
+ rim = Annulus(
405
+ inner_radius=radius * 0.32,
406
+ outer_radius=radius * 0.42,
407
+ fill_color=rim_col,
408
+ fill_opacity=0.38,
409
+ stroke_width=0,
410
+ )
411
+ rim.move_to(np.array([-radius * 0.26, radius * 0.28, radius * 0.86]))
412
+ self.add(rim)
413
+
414
+ # ── 5. Label ──────────────────────────────────────────────────
415
+ if label is not None:
416
+ # Auto-contrast: light label on dark ball, dark on light
417
+ if label_color is None:
418
+ rgb = np.array(color_to_rgb(hex_col))
419
+ lum = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]
420
+ label_color = WHITE if lum < 0.55 else "#1A1A1A"
421
+ lbl = Text(
422
+ str(label),
423
+ font_size=int(radius * 96),
424
+ color=label_color,
425
+ font="sans-serif",
426
+ )
427
+ lbl.move_to([0, 0, radius * 1.01]) # face front (+Z)
428
+ self.add(lbl)
429
+
430
+ # ──────────────────────────────────────────────────────────────────
431
+ # Utilities
432
+ # ──────────────────────────────────────────────────────────────────
433
+
434
+ def get_color_hex(self) -> str:
435
+ return self.ball_color
436
+
437
+ def make_copy_at(self, position: np.ndarray) -> "Ball3D":
438
+ c = self.copy()
439
+ c.move_to(position)
440
+ return c
441
+
442
+
443
+ def get_packed_positions(
444
+ n_balls: int,
445
+ urn_belly_r: float,
446
+ urn_inner_bottom_y: float,
447
+ ball_radius: float,
448
+ max_layers: int = 6,
449
+ ) -> list[np.ndarray]:
450
+ """
451
+ Compute staggered hexagonal-close-packed positions for n_balls
452
+ inside a cylindrical well of radius ``urn_belly_r * 0.72``.
453
+
454
+ Balls are placed in layers from the bottom up, each layer offset
455
+ by half a ball diameter in x and z to simulate packing.
456
+
457
+ Parameters
458
+ ----------
459
+ n_balls : total number of balls
460
+ urn_belly_r : urn maximum belly radius
461
+ urn_inner_bottom_y: y-coordinate of the urn interior floor
462
+ ball_radius : radius of each ball
463
+ max_layers : cap on vertical layers (prevents overflow)
464
+
465
+ Returns
466
+ -------
467
+ list of np.ndarray positions, length n_balls
468
+ """
469
+ well_r = urn_belly_r * 0.68 - ball_radius
470
+ diameter = 2 * ball_radius
471
+ row_dy = diameter * np.sqrt(2.0 / 3.0) # vertical layer spacing (HCP)
472
+ row_dx = diameter * np.sqrt(3.0) / 2 # hex offset in x
473
+
474
+ positions = []
475
+ placed = 0
476
+ layer = 0
477
+
478
+ while placed < n_balls and layer < max_layers:
479
+ y = urn_inner_bottom_y + ball_radius + layer * row_dy
480
+ # Offset alternate layers in x-z
481
+ x_off = (layer % 2) * ball_radius * 0.6
482
+ z_off = (layer % 2) * ball_radius * 0.5
483
+
484
+ # How many fit in this layer?
485
+ row = 0
486
+ r_step = diameter
487
+ while placed < n_balls:
488
+ r_ring = row * r_step
489
+ if r_ring == 0:
490
+ if well_r >= 0:
491
+ pos = np.array([x_off, y, z_off])
492
+ positions.append(pos)
493
+ placed += 1
494
+ row += 1
495
+ continue
496
+ # Number of balls in this ring (circumference / diameter)
497
+ n_ring = max(1, int(TAU * r_ring / diameter))
498
+ for k in range(n_ring):
499
+ if placed >= n_balls:
500
+ break
501
+ ang = k * TAU / n_ring
502
+ px = r_ring * np.cos(ang) + x_off
503
+ pz = r_ring * np.sin(ang) + z_off
504
+ # Check still inside well
505
+ if np.sqrt(px**2 + pz**2) + ball_radius <= well_r + ball_radius:
506
+ positions.append(np.array([px, y, pz]))
507
+ placed += 1
508
+ row += 1
509
+ if r_ring > well_r:
510
+ break
511
+ layer += 1
512
+
513
+ return positions[:n_balls]
514
+
515
+
516
+ # ──────────────────────────────────────────────────────────────────────────────
517
+ # Urn body sub-components
518
+ # ──────────────────────────────────────────────────────────────────────────────
519
+
520
+ class _UrnLatheBody(VGroup):
521
+ """
522
+ The main ceramic body of the urn, built by revolving a Catmull-Rom
523
+ profile curve around the Y-axis.
524
+
525
+ Approximated as a stack of thin Cylinders (frustum slices), which
526
+ Manim can render efficiently. Each slice has:
527
+ • outer cylinder — the glazed body colour
528
+ • specular stripe — bright thin strip on the lit side (+x direction)
529
+ • AO ring — darkened strip at top and bottom of each slice
530
+
531
+ Parameters
532
+ ----------
533
+ belly_r : float — maximum belly radius
534
+ neck_r : float — neck radius (≈ belly_r * 0.28)
535
+ height : float — total urn height
536
+ palette : dict
537
+ n_slices : int — lathe resolution (default 40)
538
+ """
539
+
540
+ def __init__(
541
+ self,
542
+ belly_r: float,
543
+ neck_r: float,
544
+ height: float,
545
+ palette: dict,
546
+ n_slices: int = 40,
547
+ **kwargs,
548
+ ):
549
+ super().__init__(**kwargs)
550
+ self.belly_r = belly_r
551
+ self.neck_r = neck_r
552
+ self.height = height
553
+
554
+ profile = _lathe_profile_points(belly_r, neck_r, height, n_slices + 1)
555
+
556
+ for i in range(len(profile) - 1):
557
+ r0, y0 = profile[i]
558
+ r1, y1 = profile[i + 1]
559
+ slice_h = abs(y1 - y0)
560
+ y_ctr = (y0 + y1) / 2
561
+
562
+ if slice_h < 1e-5 or min(r0, r1) < 1e-5:
563
+ continue
564
+
565
+ # ── Outer frustum slice ───────────────────────────────────
566
+ # Manim Cylinder doesn't support frustum natively, so we use
567
+ # the average radius and accept the slight approximation.
568
+ r_avg = (r0 + r1) / 2
569
+ frust = Cylinder(
570
+ radius=r_avg,
571
+ height=slice_h,
572
+ direction=UP,
573
+ resolution=(32, 1),
574
+ fill_color=palette["glaze"],
575
+ fill_opacity=1.0,
576
+ stroke_width=0,
577
+ )
578
+ frust.move_to([0, y_ctr, 0])
579
+ self.add(frust)
580
+
581
+ # ── Specular stripe (lit side, +X) ────────────────────────
582
+ # A thin vertical rectangle on the +X face of this slice
583
+ spec_w = r_avg * 0.18
584
+ spec_rect = Rectangle(
585
+ width=spec_w,
586
+ height=slice_h,
587
+ fill_color=palette["specular"],
588
+ fill_opacity=0.38,
589
+ stroke_width=0,
590
+ )
591
+ spec_rect.move_to([r_avg - spec_w * 0.3, y_ctr, 0.001])
592
+ self.add(spec_rect)
593
+
594
+ # ── Foot ring disc (bottom cap) ────────────────────────────────
595
+ foot_r = profile[0, 0]
596
+ foot = Circle(
597
+ radius=foot_r,
598
+ fill_color=palette["foot"],
599
+ fill_opacity=1.0,
600
+ stroke_width=0,
601
+ )
602
+ foot.rotate(PI / 2, axis=RIGHT)
603
+ foot.move_to([0, profile[0, 1], 0])
604
+ self.add(foot)
605
+
606
+ # ── Lip ring (top cap annulus) ─────────────────────────────────
607
+ lip_r = profile[-1, 0]
608
+ lip_y = profile[-1, 1]
609
+ # Outer ring
610
+ lip = Annulus(
611
+ inner_radius=lip_r * 0.55,
612
+ outer_radius=lip_r,
613
+ fill_color=palette["lip"],
614
+ fill_opacity=1.0,
615
+ stroke_width=0,
616
+ )
617
+ lip.rotate(PI / 2, axis=RIGHT)
618
+ lip.move_to([0, lip_y, 0])
619
+ self.add(lip)
620
+
621
+ # ── Inner dark well (depth illusion) ──────────────────────────
622
+ well = Circle(
623
+ radius=lip_r * 0.50,
624
+ fill_color=palette["inner"],
625
+ fill_opacity=1.0,
626
+ stroke_width=0,
627
+ )
628
+ well.rotate(PI / 2, axis=RIGHT)
629
+ well.move_to([0, lip_y - 0.02, 0])
630
+ self.add(well)
631
+
632
+ # Store key geometry for use by other components
633
+ self._profile = profile
634
+ self._lip_r = lip_r
635
+ self._lip_y = lip_y
636
+ self._foot_y = profile[0, 1]
637
+
638
+
639
+ class _MeanderBand(VGroup):
640
+ """
641
+ Greek key meander decorative band wrapped around the belly equator.
642
+
643
+ Strategy: build one meander tile in 2-D, duplicate it N times around
644
+ a circle of the belly radius, then rotate each tile to face outward.
645
+
646
+ Parameters
647
+ ----------
648
+ radius : float — band placement radius
649
+ band_y : float — vertical centre of the band
650
+ band_h : float — height of the band
651
+ palette : dict
652
+ n_repeats : int — how many key units around the circumference
653
+ """
654
+
655
+ def __init__(
656
+ self,
657
+ radius: float,
658
+ band_y: float,
659
+ band_h: float,
660
+ palette: dict,
661
+ n_repeats: int = 16,
662
+ **kwargs,
663
+ ):
664
+ super().__init__(**kwargs)
665
+
666
+ # Background band
667
+ band_bg = Cylinder(
668
+ radius=radius + 0.005,
669
+ height=band_h,
670
+ direction=UP,
671
+ resolution=(64, 1),
672
+ fill_color=palette["band_bg"],
673
+ fill_opacity=1.0,
674
+ stroke_width=0,
675
+ )
676
+ band_bg.move_to([0, band_y, 0])
677
+ self.add(band_bg)
678
+
679
+ # Meander key units
680
+ unit_w = TAU * radius / n_repeats # arc length per unit
681
+ unit_h = band_h * 0.82
682
+ segs = _meander_key_unit(unit_w, unit_h)
683
+ step_ang = TAU / n_repeats
684
+
685
+ for k in range(n_repeats):
686
+ ang = k * step_ang
687
+ # Build the key unit as thin lines, projected onto the cylinder surface
688
+ for (a2d, b2d) in segs:
689
+ # Map 2-D segment coords to 3-D cylinder surface
690
+ # u (horizontal along band) → angle offset
691
+ # v (vertical) → y offset
692
+ def _pt(xy2d: np.ndarray) -> np.ndarray:
693
+ u_frac = xy2d[0] / unit_w # 0..1 along this unit
694
+ v_offset = xy2d[1] - unit_h / 2
695
+ total_ang = ang + u_frac * step_ang
696
+ rx = (radius + 0.01) * np.cos(total_ang)
697
+ rz = (radius + 0.01) * np.sin(total_ang)
698
+ ry = band_y + v_offset
699
+ return np.array([rx, ry, rz])
700
+
701
+ seg_line = Line(
702
+ start=_pt(a2d),
703
+ end=_pt(b2d),
704
+ stroke_color=palette["band_fg"],
705
+ stroke_width=2.0,
706
+ )
707
+ self.add(seg_line)
708
+
709
+
710
+ class _UrnHandle(VGroup):
711
+ """
712
+ One ear handle: a planar arc of torus-like cross-section,
713
+ attaching at the neck and at the shoulder of the urn.
714
+
715
+ Built as a sequence of thin cylinders following an arc path,
716
+ giving the appearance of a pulled clay handle.
717
+
718
+ Parameters
719
+ ----------
720
+ attach_r : float — radius at attachment points
721
+ low_y : float — y of shoulder attachment
722
+ high_y : float — y of neck attachment
723
+ side : +1 or -1 (right or left)
724
+ palette : dict
725
+ n_segments : int — arc smoothness
726
+ """
727
+
728
+ def __init__(
729
+ self,
730
+ attach_r: float,
731
+ low_y: float,
732
+ high_y: float,
733
+ side: int,
734
+ palette: dict,
735
+ n_segments: int = 12,
736
+ **kwargs,
737
+ ):
738
+ super().__init__(**kwargs)
739
+
740
+ handle_col = palette["handle"]
741
+ handle_thick = attach_r * 0.12 # handle cross-section radius
742
+
743
+ # Handle arc: parametric path that bows outward from the urn
744
+ # Centre of arc is midway between attach points, bowing out by bow_r
745
+ mid_y = (low_y + high_y) / 2
746
+ arc_h = (high_y - low_y)
747
+ bow_out = attach_r * 0.55 # how far handle bows beyond rim
748
+
749
+ ts = np.linspace(0, 1, n_segments + 1)
750
+
751
+ def handle_path(t: float) -> np.ndarray:
752
+ """Quadratic Bézier: p0 → p_ctrl → p1"""
753
+ p0 = np.array([side * attach_r, low_y, 0.0])
754
+ p1 = np.array([side * attach_r, high_y, 0.0])
755
+ p_mid = np.array([side * (attach_r + bow_out), mid_y, 0.0])
756
+ pt = (1 - t)**2 * p0 + 2*(1-t)*t * p_mid + t**2 * p1
757
+ return pt
758
+
759
+ pts = [handle_path(t) for t in ts]
760
+
761
+ for i in range(len(pts) - 1):
762
+ seg_start = pts[i]
763
+ seg_end = pts[i + 1]
764
+ seg_vec = seg_end - seg_start
765
+ seg_len = np.linalg.norm(seg_vec)
766
+ if seg_len < 1e-6:
767
+ continue
768
+ seg_dir = seg_vec / seg_len
769
+ seg_ctr = (seg_start + seg_end) / 2
770
+
771
+ cyl = Cylinder(
772
+ radius=handle_thick,
773
+ height=seg_len * 1.05,
774
+ direction=seg_dir,
775
+ resolution=(6, 1),
776
+ fill_color=handle_col,
777
+ fill_opacity=1.0,
778
+ stroke_width=0,
779
+ )
780
+ cyl.move_to(seg_ctr)
781
+ self.add(cyl)
782
+
783
+ # Attachment discs
784
+ for y_att in [low_y, high_y]:
785
+ disc = Circle(
786
+ radius=handle_thick * 1.3,
787
+ fill_color=interpolate_color(handle_col, BLACK, 0.2),
788
+ fill_opacity=1.0,
789
+ stroke_width=0,
790
+ )
791
+ disc.move_to([side * attach_r, y_att, 0.005])
792
+ self.add(disc)
793
+
794
+
795
+ class _UrnLid(VGroup):
796
+ """
797
+ Domed lid with a spherical knob.
798
+
799
+ Layers:
800
+ • dome — shallow sphere cap (approximated as a squashed sphere)
801
+ • rim — flat annulus matching the urn lip
802
+ • knob — small sphere on top
803
+
804
+ Parameters
805
+ ----------
806
+ lip_r : float — inner radius of the lid (matches urn lip)
807
+ lip_y : float — y-position where lid sits
808
+ palette: dict
809
+ """
810
+
811
+ def __init__(
812
+ self,
813
+ lip_r: float,
814
+ lip_y: float,
815
+ palette: dict,
816
+ **kwargs,
817
+ ):
818
+ super().__init__(**kwargs)
819
+ lid_r = lip_r * 1.02
820
+ dome_h = lip_r * 0.55
821
+ knob_r = lip_r * 0.12
822
+
823
+ # Rim disc
824
+ rim = Circle(
825
+ radius=lid_r,
826
+ fill_color=palette["lid_body"],
827
+ fill_opacity=1.0,
828
+ stroke_width=0,
829
+ )
830
+ rim.rotate(PI / 2, axis=RIGHT)
831
+ rim.move_to([0, lip_y, 0])
832
+ self.add(rim)
833
+
834
+ # Dome (squashed sphere)
835
+ dome = Sphere(
836
+ radius=lid_r,
837
+ resolution=(16, 16),
838
+ fill_color=palette["lid_body"],
839
+ fill_opacity=1.0,
840
+ stroke_width=0,
841
+ )
842
+ dome.scale([1.0, dome_h / lid_r, 1.0])
843
+ dome.move_to([0, lip_y + dome_h * 0.3, 0])
844
+ self.add(dome)
845
+
846
+ # Specular on dome
847
+ dome_spec = Circle(
848
+ radius=lid_r * 0.22,
849
+ fill_color=palette["specular"],
850
+ fill_opacity=0.40,
851
+ stroke_width=0,
852
+ )
853
+ dome_spec.scale([1.4, 0.7, 1])
854
+ dome_spec.rotate(PI / 2, axis=RIGHT)
855
+ dome_spec.move_to([-lid_r * 0.22, lip_y + dome_h * 0.55, 0])
856
+ self.add(dome_spec)
857
+
858
+ # Knob
859
+ knob = Sphere(
860
+ radius=knob_r,
861
+ resolution=(10, 10),
862
+ fill_color=palette["lid_knob"],
863
+ fill_opacity=1.0,
864
+ stroke_width=0,
865
+ )
866
+ knob.move_to([0, lip_y + dome_h * 0.88 + knob_r, 0])
867
+ self.add(knob)
868
+
869
+ # Knob specular
870
+ ks = Circle(
871
+ radius=knob_r * 0.38,
872
+ fill_color=palette["specular"],
873
+ fill_opacity=0.55,
874
+ stroke_width=0,
875
+ )
876
+ ks.scale([1.3, 0.8, 1])
877
+ ks.move_to([-knob_r * 0.22, lip_y + dome_h * 0.88 + knob_r * 1.55, knob_r * 0.5])
878
+ self.add(ks)
879
+
880
+ self._lip_y = lip_y
881
+ self._lid_top_y = lip_y + dome_h + 2 * knob_r
882
+
883
+
884
+ # ──────────────────────────────────────────────────────────────────────────────
885
+ # Urn3D ── the main export
886
+ # ──────────────────────────────────────────────────────────────────────────────
887
+
888
+ class Urn3D(VGroup):
889
+ """
890
+ A classical Greek amphora-style urn for Manim statistics animations.
891
+
892
+ Parameters
893
+ ----------
894
+ belly_r : float
895
+ Maximum belly radius. Default ``1.0``.
896
+ height : float
897
+ Total urn height. Default ``2.8``.
898
+ color_scheme : str
899
+ Named palette. Default ``"terracotta"``.
900
+ custom_palette : dict | None
901
+ Override individual palette keys.
902
+ show_lid : bool
903
+ Start with lid on. Default ``False``.
904
+ show_handles : bool
905
+ Include ear handles. Default ``True``.
906
+ show_band : bool
907
+ Include meander decorative band. Default ``True``.
908
+ n_band_repeats : int
909
+ Number of meander units around the belly. Default ``16``.
910
+ lathe_slices : int
911
+ Lathe profile resolution. Default ``40``.
912
+ ball_radius : float
913
+ Radius of Ball3D objects stored inside. Default ``0.18``.
914
+
915
+ Attributes
916
+ ----------
917
+ body : _UrnLatheBody
918
+ lid : _UrnLid | None
919
+ handles : VGroup
920
+ band : _MeanderBand | None
921
+ balls : list[Ball3D] — balls currently inside
922
+ belly_r : float
923
+ lip_y : float — y of urn opening
924
+ inner_bottom_y : float — y of interior floor
925
+
926
+ Examples
927
+ --------
928
+ ::
929
+
930
+ urn = Urn3D(color_scheme="terracotta", show_lid=False)
931
+ red_balls = [Ball3D("red", label=str(i+1)) for i in range(4)]
932
+ blue_balls = [Ball3D("blue", label=str(i+5)) for i in range(3)]
933
+ scene.play(FillUrn(urn, red_balls + blue_balls))
934
+ scene.play(DrawBall(urn, red_balls[0]))
935
+ """
936
+
937
+ def __init__(
938
+ self,
939
+ belly_r: float = 1.0,
940
+ height: float = 2.8,
941
+ color_scheme: str = "terracotta",
942
+ custom_palette: Optional[dict] = None,
943
+ show_lid: bool = False,
944
+ show_handles: bool = True,
945
+ show_band: bool = True,
946
+ n_band_repeats: int = 16,
947
+ lathe_slices: int = 40,
948
+ ball_radius: float = 0.18,
949
+ **kwargs,
950
+ ):
951
+ super().__init__(**kwargs)
952
+
953
+ palette = dict(URN_PALETTES.get(color_scheme, URN_PALETTES["terracotta"]))
954
+ if custom_palette:
955
+ palette.update(custom_palette)
956
+
957
+ self._palette = palette
958
+ self._belly_r = belly_r
959
+ self._height = height
960
+ self._ball_r = ball_radius
961
+ self.balls: list[Ball3D] = []
962
+
963
+ neck_r = belly_r * 0.32
964
+
965
+ # ── Build body ────────────────────────────────────────────────
966
+ self.body = _UrnLatheBody(
967
+ belly_r=belly_r,
968
+ neck_r=neck_r,
969
+ height=height,
970
+ palette=palette,
971
+ n_slices=lathe_slices,
972
+ )
973
+ self.add(self.body)
974
+
975
+ # Extract key geometry from profile
976
+ profile = self.body._profile
977
+ self._lip_y = float(self.body._lip_y)
978
+ self._foot_y = float(self.body._foot_y)
979
+ self._lip_r = float(self.body._lip_r)
980
+ # Interior bottom is ~15% up from foot
981
+ self._inner_bottom_y = self._foot_y + height * 0.07
982
+
983
+ # ── Decorative band ───────────────────────────────────────────
984
+ self.band = None
985
+ if show_band:
986
+ # Find belly equator: widest profile point
987
+ belly_idx = int(np.argmax(profile[:, 0]))
988
+ belly_y = float(profile[belly_idx, 1])
989
+ belly_rr = float(profile[belly_idx, 0])
990
+ band_h = height * 0.10
991
+ self.band = _MeanderBand(
992
+ radius=belly_rr,
993
+ band_y=belly_y,
994
+ band_h=band_h,
995
+ palette=palette,
996
+ n_repeats=n_band_repeats,
997
+ )
998
+ self.add(self.band)
999
+
1000
+ # ── Handles ───────────────────────────────────────────────────
1001
+ self.handles = VGroup()
1002
+ if show_handles:
1003
+ # Attach at shoulder and neck
1004
+ shoulder_frac = 0.65 # shoulder ~65% up the profile
1005
+ neck_frac = 0.88
1006
+ n_pts = len(profile)
1007
+ shoulder_idx = int(shoulder_frac * n_pts)
1008
+ neck_idx = int(neck_frac * n_pts)
1009
+ shoulder_y = float(profile[min(shoulder_idx, n_pts-1), 1])
1010
+ neck_y = float(profile[min(neck_idx, n_pts-1), 1])
1011
+ handle_r = float(profile[min(shoulder_idx, n_pts-1), 0])
1012
+
1013
+ for side in [1, -1]:
1014
+ h = _UrnHandle(
1015
+ attach_r=handle_r,
1016
+ low_y=shoulder_y,
1017
+ high_y=neck_y,
1018
+ side=side,
1019
+ palette=palette,
1020
+ )
1021
+ self.handles.add(h)
1022
+ self.add(self.handles)
1023
+
1024
+ # ── Lid ───────────────────────────────────────────────────────
1025
+ self.lid = None
1026
+ if show_lid:
1027
+ self.lid = _UrnLid(
1028
+ lip_r=self._lip_r,
1029
+ lip_y=self._lip_y,
1030
+ palette=palette,
1031
+ )
1032
+ self.add(self.lid)
1033
+
1034
+ # ──────────────────────────────────────────────────────────────────
1035
+ # Properties
1036
+ # ──────────────────────────────────────────────────────────────────
1037
+
1038
+ @property
1039
+ def belly_r(self) -> float:
1040
+ return self._belly_r
1041
+
1042
+ @property
1043
+ def lip_y(self) -> float:
1044
+ return self._lip_y + self.get_center()[1]
1045
+
1046
+ @property
1047
+ def inner_bottom_y(self) -> float:
1048
+ return self._inner_bottom_y + self.get_center()[1]
1049
+
1050
+ @property
1051
+ def n_balls(self) -> int:
1052
+ return len(self.balls)
1053
+
1054
+ # ──────────────────────────────────────────────────────────────────
1055
+ # Ball management
1056
+ # ──────────────────────────────────────────────────────────────────
1057
+
1058
+ def add_ball(self, ball: Ball3D, position: Optional[np.ndarray] = None):
1059
+ """Place a ball inside the urn at the given position (or auto-packed)."""
1060
+ if position is None:
1061
+ positions = get_packed_positions(
1062
+ len(self.balls) + 1,
1063
+ self._belly_r,
1064
+ self._inner_bottom_y,
1065
+ self._ball_r,
1066
+ )
1067
+ position = positions[-1] + self.get_center()
1068
+ ball.move_to(position)
1069
+ self.balls.append(ball)
1070
+ self.add(ball)
1071
+
1072
+ def remove_ball(self, ball: Ball3D):
1073
+ """Remove a ball from the urn's tracking list."""
1074
+ if ball in self.balls:
1075
+ self.balls.remove(ball)
1076
+ self.remove(ball)
1077
+
1078
+ def get_ball_positions(self) -> list[np.ndarray]:
1079
+ """Return packed positions for all current balls."""
1080
+ return get_packed_positions(
1081
+ len(self.balls),
1082
+ self._belly_r,
1083
+ self._inner_bottom_y,
1084
+ self._ball_r,
1085
+ )
1086
+
1087
+ def get_draw_exit_point(self) -> np.ndarray:
1088
+ """Position just above the urn opening — where drawn balls emerge."""
1089
+ return np.array([
1090
+ self.get_center()[0],
1091
+ self.lip_y + self._ball_r * 1.5,
1092
+ self.get_center()[2],
1093
+ ])
1094
+
1095
+ def count_by_color(self) -> dict[str, int]:
1096
+ """Return {hex_color: count} for all balls currently in the urn."""
1097
+ counts: dict[str, int] = {}
1098
+ for b in self.balls:
1099
+ c = b.ball_color
1100
+ counts[c] = counts.get(c, 0) + 1
1101
+ return counts
1102
+
1103
+
1104
+ # ──────────────────────────────────────────────────────────────────────────────
1105
+ # Animations
1106
+ # ──────────────────────────────────────────────────────────────────────────────
1107
+
1108
+ class FillUrn(Succession):
1109
+ """
1110
+ Drop balls into the urn one by one from above.
1111
+
1112
+ Each ball starts above the urn opening, falls in (ease-in),
1113
+ and settles into its packed position.
1114
+
1115
+ Parameters
1116
+ ----------
1117
+ urn : Urn3D
1118
+ balls : list[Ball3D] — balls to add (in order)
1119
+ drop_height : float — how far above the lip each ball starts
1120
+ stagger : float — delay between consecutive drops (s)
1121
+ run_time : float — total animation time
1122
+ """
1123
+
1124
+ def __init__(
1125
+ self,
1126
+ urn: Urn3D,
1127
+ balls: list[Ball3D],
1128
+ drop_height: float = 1.2,
1129
+ stagger: float = 0.12,
1130
+ **kwargs,
1131
+ ):
1132
+ # Compute packed target positions
1133
+ packed = get_packed_positions(
1134
+ len(balls),
1135
+ urn._belly_r,
1136
+ urn._inner_bottom_y,
1137
+ urn._ball_r,
1138
+ )
1139
+ urn_ctr = urn.get_center()
1140
+
1141
+ anims = []
1142
+ for i, (ball, target) in enumerate(zip(balls, packed)):
1143
+ world_target = np.array(target) + urn_ctr
1144
+ # Start above urn
1145
+ start_pos = np.array([
1146
+ world_target[0],
1147
+ urn.lip_y + drop_height,
1148
+ world_target[2],
1149
+ ])
1150
+ ball.move_to(start_pos)
1151
+ urn.balls.append(ball)
1152
+
1153
+ drop = ApplyMethod(
1154
+ ball.move_to, world_target,
1155
+ run_time=0.35,
1156
+ rate_func=rate_functions.ease_in_cubic,
1157
+ )
1158
+ anims.append(drop)
1159
+
1160
+ kwargs.setdefault("run_time", sum(a.run_time for a in anims)
1161
+ + stagger * (len(anims) - 1))
1162
+ super().__init__(*anims, **kwargs)
1163
+
1164
+
1165
+ class DrawBall(Animation):
1166
+ """
1167
+ Draw one ball smoothly out of the urn.
1168
+
1169
+ The ball rises along a smooth ease-out arc from its current packed
1170
+ position, through the urn opening, to a position above the urn.
1171
+
1172
+ Parameters
1173
+ ----------
1174
+ urn : Urn3D
1175
+ ball : Ball3D — the ball to draw (must be in urn.balls)
1176
+ dest : np.ndarray — where the ball ends up; default is
1177
+ directly above the urn at a comfortable height
1178
+ run_time : float
1179
+ """
1180
+
1181
+ def __init__(
1182
+ self,
1183
+ urn: Urn3D,
1184
+ ball: Ball3D,
1185
+ dest: Optional[np.ndarray] = None,
1186
+ **kwargs,
1187
+ ):
1188
+ self.urn = urn
1189
+ self.ball = ball
1190
+ self.start = ball.get_center().copy()
1191
+ if dest is None:
1192
+ dest = urn.get_draw_exit_point() + UP * 0.8
1193
+ self.dest = dest
1194
+ kwargs.setdefault("run_time", 1.0)
1195
+ kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
1196
+ super().__init__(ball, **kwargs)
1197
+
1198
+ def begin(self):
1199
+ super().begin()
1200
+ # Remove from urn tracking when draw begins
1201
+ if self.ball in self.urn.balls:
1202
+ self.urn.balls.remove(self.ball)
1203
+
1204
+ def interpolate_mobject(self, alpha: float):
1205
+ # Arc path: slight bow to the right as ball rises
1206
+ bow = np.array([self.urn._belly_r * 0.3 * np.sin(alpha * PI), 0, 0])
1207
+ pos = self.start * (1 - alpha) + self.dest * alpha + bow
1208
+ self.ball.move_to(pos)
1209
+
1210
+
1211
+ class ReplaceBall(Animation):
1212
+ """
1213
+ Return a ball to the urn — arcs from current position back down.
1214
+
1215
+ Parameters
1216
+ ----------
1217
+ urn : Urn3D
1218
+ ball : Ball3D
1219
+ run_time : float
1220
+ """
1221
+
1222
+ def __init__(
1223
+ self,
1224
+ urn: Urn3D,
1225
+ ball: Ball3D,
1226
+ **kwargs,
1227
+ ):
1228
+ self.urn = urn
1229
+ self.ball = ball
1230
+ self.start = ball.get_center().copy()
1231
+
1232
+ # Find next available packed position
1233
+ packed = get_packed_positions(
1234
+ len(urn.balls) + 1,
1235
+ urn._belly_r,
1236
+ urn._inner_bottom_y,
1237
+ urn._ball_r,
1238
+ )
1239
+ self.dest = np.array(packed[-1]) + urn.get_center()
1240
+
1241
+ kwargs.setdefault("run_time", 0.85)
1242
+ kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
1243
+ super().__init__(ball, **kwargs)
1244
+
1245
+ def begin(self):
1246
+ super().begin()
1247
+ self.urn.balls.append(self.ball)
1248
+
1249
+ def interpolate_mobject(self, alpha: float):
1250
+ bow = np.array([0, np.sin(alpha * PI) * self.urn._belly_r * 0.25, 0])
1251
+ pos = self.start * (1 - alpha) + self.dest * alpha + bow
1252
+ self.ball.move_to(pos)
1253
+
1254
+
1255
+ class ShakeUrn(Animation):
1256
+ """
1257
+ Rapid lateral shake of the urn (mixing balls before drawing).
1258
+
1259
+ Parameters
1260
+ ----------
1261
+ urn : Urn3D
1262
+ n_shakes : int — oscillation count
1263
+ amplitude : float — max lateral displacement
1264
+ run_time : float
1265
+ """
1266
+
1267
+ def __init__(
1268
+ self,
1269
+ urn: Urn3D,
1270
+ n_shakes: int = 6,
1271
+ amplitude: float = 0.15,
1272
+ **kwargs,
1273
+ ):
1274
+ self.urn = urn
1275
+ self.n_shakes = n_shakes
1276
+ self.amplitude = amplitude
1277
+ self.start_pos = urn.get_center().copy()
1278
+ kwargs.setdefault("run_time", 0.9)
1279
+ kwargs.setdefault("rate_func", rate_functions.linear)
1280
+ super().__init__(urn, **kwargs)
1281
+
1282
+ def interpolate_mobject(self, alpha: float):
1283
+ decay = 1.0 - alpha
1284
+ osc = (np.sin(alpha * self.n_shakes * PI)
1285
+ * self.amplitude * decay)
1286
+ rot = osc * 0.08 # slight rotational tilt
1287
+ self.urn.become(self.starting_mobject.copy())
1288
+ self.urn.shift(np.array([osc, 0, 0]))
1289
+ self.urn.rotate(rot, axis=OUT, about_point=self.urn.get_center())
1290
+
1291
+
1292
+ class PourUrn(Succession):
1293
+ """
1294
+ Tilt the urn and pour all balls out in sequence.
1295
+
1296
+ Steps:
1297
+ 1. Urn tilts (Rotate ~100°)
1298
+ 2. Balls fly out one by one via parabolic arcs
1299
+ 3. Urn rights itself
1300
+
1301
+ Parameters
1302
+ ----------
1303
+ urn : Urn3D
1304
+ balls : list[Ball3D] | None — balls to pour; default = urn.balls
1305
+ pour_angle : float — tilt angle (default PI * 0.55)
1306
+ spread : float — x-spread of poured balls
1307
+ run_time : float
1308
+ """
1309
+
1310
+ def __init__(
1311
+ self,
1312
+ urn: Urn3D,
1313
+ balls: Optional[list[Ball3D]] = None,
1314
+ pour_angle: float = PI * 0.55,
1315
+ spread: float = 2.5,
1316
+ **kwargs,
1317
+ ):
1318
+ if balls is None:
1319
+ balls = list(urn.balls)
1320
+
1321
+ tilt = Rotate(urn, angle=pour_angle, axis=OUT,
1322
+ about_point=urn.get_center(),
1323
+ run_time=0.5)
1324
+
1325
+ pour_anims = []
1326
+ for i, ball in enumerate(balls):
1327
+ t_offset = i * 0.12
1328
+ dest = np.array([
1329
+ urn.get_center()[0] + spread * (i / max(len(balls)-1, 1) - 0.5),
1330
+ urn.get_center()[1] - urn._height * 0.6,
1331
+ 0,
1332
+ ])
1333
+ pour_anims.append(
1334
+ ApplyMethod(ball.move_to, dest, run_time=0.6,
1335
+ rate_func=rate_functions.ease_in_cubic)
1336
+ )
1337
+ urn.balls.remove(ball) if ball in urn.balls else None
1338
+
1339
+ right = Rotate(urn, angle=-pour_angle, axis=OUT,
1340
+ about_point=urn.get_center(),
1341
+ run_time=0.4)
1342
+
1343
+ super().__init__(tilt, AnimationGroup(*pour_anims), right, **kwargs)
1344
+
1345
+
1346
+ class SwapBalls(Animation):
1347
+ """
1348
+ Swap two balls between positions — useful for conditional probability
1349
+ illustrations (e.g., "given we drew red, which urn is more likely?").
1350
+
1351
+ Parameters
1352
+ ----------
1353
+ ball_a, ball_b : Ball3D — the two balls to swap
1354
+ arc_height : float — arc height during swap
1355
+ run_time : float
1356
+ """
1357
+
1358
+ def __init__(
1359
+ self,
1360
+ ball_a: Ball3D,
1361
+ ball_b: Ball3D,
1362
+ arc_height: float = 0.8,
1363
+ **kwargs,
1364
+ ):
1365
+ self.ball_a = ball_a
1366
+ self.ball_b = ball_b
1367
+ self.pos_a = ball_a.get_center().copy()
1368
+ self.pos_b = ball_b.get_center().copy()
1369
+ self.arc_height = arc_height
1370
+ kwargs.setdefault("run_time", 1.1)
1371
+ kwargs.setdefault("rate_func", rate_functions.ease_in_out_sine)
1372
+ # Animate both as a group
1373
+ group = VGroup(ball_a, ball_b)
1374
+ super().__init__(group, **kwargs)
1375
+
1376
+ def interpolate_mobject(self, alpha: float):
1377
+ # Ball A goes from pos_a → pos_b via upper arc
1378
+ h_a = self.arc_height * np.sin(alpha * PI)
1379
+ pa = self.pos_a * (1-alpha) + self.pos_b * alpha + UP * h_a
1380
+ # Ball B goes from pos_b → pos_a via lower arc
1381
+ h_b = self.arc_height * 0.65 * np.sin(alpha * PI)
1382
+ pb = self.pos_b * (1-alpha) + self.pos_a * alpha - UP * h_b
1383
+
1384
+ self.ball_a.move_to(pa)
1385
+ self.ball_b.move_to(pb)
1386
+
1387
+
1388
+ # ──────────────────────────────────────────────────────────────────────────────
1389
+ # Convenience factories
1390
+ # ──────────────────────────────────────────────────────────────────────────────
1391
+
1392
+ def make_labeled_urn(
1393
+ n_red: int,
1394
+ n_blue: int,
1395
+ urn_kwargs: Optional[dict] = None,
1396
+ ball_kwargs: Optional[dict] = None,
1397
+ ) -> tuple["Urn3D", list["Ball3D"], list["Ball3D"]]:
1398
+ """
1399
+ Create an urn pre-populated with red and blue balls — the classic
1400
+ hypergeometric / conditional probability setup.
1401
+
1402
+ Returns
1403
+ -------
1404
+ urn, red_balls, blue_balls
1405
+ """
1406
+ urn_kwargs = urn_kwargs or {}
1407
+ ball_kwargs = ball_kwargs or {}
1408
+ ball_r = urn_kwargs.get("ball_radius", 0.18)
1409
+
1410
+ urn = Urn3D(**urn_kwargs)
1411
+ red_balls = [Ball3D("red", label=str(i+1), radius=ball_r, **ball_kwargs)
1412
+ for i in range(n_red)]
1413
+ blue_balls = [Ball3D("blue", label=str(i+1), radius=ball_r, **ball_kwargs)
1414
+ for i in range(n_blue)]
1415
+
1416
+ all_balls = red_balls + blue_balls
1417
+ packed = get_packed_positions(
1418
+ len(all_balls), urn._belly_r, urn._inner_bottom_y, ball_r
1419
+ )
1420
+ urn_ctr = urn.get_center()
1421
+ for ball, pos in zip(all_balls, packed):
1422
+ ball.move_to(np.array(pos) + urn_ctr)
1423
+ urn.balls.append(ball)
1424
+
1425
+ return urn, red_balls, blue_balls
1426
+
1427
+
1428
+ def make_two_urn_setup(
1429
+ urn1_contents: list[tuple[str, int]], # [(color, count), ...]
1430
+ urn2_contents: list[tuple[str, int]],
1431
+ spacing: float = 4.5,
1432
+ scheme1: str = "terracotta",
1433
+ scheme2: str = "cobalt",
1434
+ ball_radius: float = 0.18,
1435
+ ) -> tuple["Urn3D", "Urn3D", list["Ball3D"], list["Ball3D"]]:
1436
+ """
1437
+ Create the classic two-urn Bayes problem setup.
1438
+
1439
+ Parameters
1440
+ ----------
1441
+ urn1_contents : e.g. [("red", 3), ("blue", 2)]
1442
+ urn2_contents : e.g. [("red", 1), ("blue", 4)]
1443
+ spacing : horizontal distance between urns
1444
+ scheme1/2 : colour schemes
1445
+ ball_radius : radius for all balls
1446
+
1447
+ Returns
1448
+ -------
1449
+ urn1, urn2, balls1, balls2
1450
+ """
1451
+ def _build_urn(contents, scheme):
1452
+ urn = Urn3D(color_scheme=scheme, ball_radius=ball_radius)
1453
+ balls = []
1454
+ for color, count in contents:
1455
+ for i in range(count):
1456
+ b = Ball3D(color, label=str(i+1), radius=ball_radius)
1457
+ balls.append(b)
1458
+ packed = get_packed_positions(
1459
+ len(balls), urn._belly_r, urn._inner_bottom_y, ball_radius
1460
+ )
1461
+ urn_ctr = urn.get_center()
1462
+ for ball, pos in zip(balls, packed):
1463
+ ball.move_to(np.array(pos) + urn_ctr)
1464
+ urn.balls.append(ball)
1465
+ return urn, balls
1466
+
1467
+ urn1, balls1 = _build_urn(urn1_contents, scheme1)
1468
+ urn2, balls2 = _build_urn(urn2_contents, scheme2)
1469
+
1470
+ urn1.shift(LEFT * spacing / 2)
1471
+ urn2.shift(RIGHT * spacing / 2)
1472
+
1473
+ return urn1, urn2, balls1, balls2
1474
+
1475
+
1476
+ # ──────────────────────────────────────────────────────────────────────────────
1477
+ # Demo Scene (run with: manim -pql urn.py UrnDemo)
1478
+ # ──────────────────────────────────────────────────────────────────────────────
1479
+
1480
+ try:
1481
+ from manim import ThreeDScene, DEGREES
1482
+
1483
+ class UrnDemo(ThreeDScene):
1484
+ """Showcase scene for Urn3D and Ball3D."""
1485
+
1486
+ def construct(self):
1487
+ self.set_camera_orientation(phi=62 * DEGREES, theta=-50 * DEGREES)
1488
+ self.begin_ambient_camera_rotation(rate=0.025)
1489
+
1490
+ # ── Two-urn Bayes setup ───────────────────────────────────
1491
+ urn1, urn2, balls1, balls2 = make_two_urn_setup(
1492
+ urn1_contents=[("red", 3), ("blue", 2)],
1493
+ urn2_contents=[("red", 1), ("blue", 4)],
1494
+ scheme1="terracotta",
1495
+ scheme2="cobalt",
1496
+ )
1497
+ all_balls = balls1 + balls2
1498
+ self.add(urn1, urn2, *all_balls)
1499
+ self.wait(1.0)
1500
+
1501
+ # ── Shake urn 1 before drawing ────────────────────────────
1502
+ self.play(ShakeUrn(urn1, n_shakes=8, run_time=1.0))
1503
+ self.wait(0.3)
1504
+
1505
+ # ── Draw a red ball from urn 1 ────────────────────────────
1506
+ drawn = balls1[0]
1507
+ dest = np.array([-2.8, 1.5, 0])
1508
+ self.play(DrawBall(urn1, drawn, dest=dest, run_time=1.2))
1509
+ self.wait(0.5)
1510
+
1511
+ # ── Replace it (sampling WITH replacement) ────────────────
1512
+ self.play(ReplaceBall(urn1, drawn, run_time=0.9))
1513
+ self.wait(0.5)
1514
+
1515
+ # ── Shake urn 2, draw a blue ball ─────────────────────────
1516
+ self.play(ShakeUrn(urn2, n_shakes=6, run_time=0.8))
1517
+ drawn2 = balls2[3] # a blue ball
1518
+ dest2 = np.array([2.8, 1.5, 0])
1519
+ self.play(DrawBall(urn2, drawn2, dest=dest2, run_time=1.1))
1520
+ self.wait(0.5)
1521
+
1522
+ # ── Swap the two drawn balls ──────────────────────────────
1523
+ self.play(SwapBalls(drawn, drawn2, arc_height=1.0, run_time=1.3))
1524
+ self.wait(1.0)
1525
+
1526
+ # ── Pour urn 2 ────────────────────────────────────────────
1527
+ self.play(PourUrn(urn2, run_time=2.0))
1528
+ self.wait(1.5)
1529
+
1530
+ except ImportError:
1531
+ pass # Manim not installed; skip demo scene definition