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,1877 @@
1
+ """
2
+ statanim/distributions/normal3d.py
3
+ =======================================
4
+ Univariate and bivariate Normal distribution visualizations.
5
+
6
+ This module is the visual showpiece of the distributions package.
7
+ The Normal distribution has more dedicated pedagogy than any other —
8
+ the 68-95-99.7 rule, standardisation, the bivariate surface, Q-Q plots,
9
+ and its role as the CLT limit all deserve rich 3D treatments.
10
+
11
+ Visual objects
12
+ --------------
13
+ ``NormalCurve3D``
14
+ Univariate N(μ, σ) bell curve with Normal-specific annotation layers:
15
+ - 68-95-99.7 rule shading with bracket annotations.
16
+ - z-score ruler beneath the curve.
17
+ - Standardisation animation: any N(μ, σ) morphs to N(0, 1).
18
+ - CLT overlay: sampling distribution of x̄ drawn over population.
19
+
20
+ ``BivariateNormal3D``
21
+ True 3D parametric surface f(x, y) for the bivariate normal,
22
+ rendered as a dense mesh of shaded quad polygons.
23
+ - Independent face shading per quad (Phong-style light model).
24
+ - Marginal density curves projected onto the xz / yz walls.
25
+ - Isoprobability contour ellipses at configurable levels.
26
+ - Conditional slice: fix x = x₀, show the resulting 1D normal.
27
+ - Animated "tent" reveal: surface rises from z = 0 upward.
28
+ - Correlation sweep: ρ varies from -0.9 → 0 → +0.9.
29
+
30
+ ``NormalApproximation3D``
31
+ Binomial(n, p) PMF bars with the Normal(np, np(1-p)) approximation
32
+ curve overlaid. Shows the approximation improving as n grows.
33
+
34
+ ``QQPlot3D``
35
+ Quantile-quantile plot against a Normal reference line.
36
+ Each data point is a Dot3D at (theoretical quantile, sample quantile).
37
+ The reference line and deviation envelope are drawn separately.
38
+
39
+ Classes
40
+ -------
41
+ BivariateNormalConfig
42
+ NormalCurve3D
43
+ BivariateNormal3D
44
+ NormalApproximation3D
45
+ QQPlot3D
46
+
47
+ Ready-to-render scenes
48
+ ----------------------
49
+ NormalCurveScene
50
+ BivariateNormalScene
51
+ StandardisationScene
52
+ NormalApproximationScene
53
+ QQPlotScene
54
+
55
+ Usage
56
+ -----
57
+ from manim import *
58
+ from statanim.distributions.normal3d import NormalCurve3D, BivariateNormal3D
59
+
60
+ class MyScene(ThreeDScene):
61
+ def construct(self):
62
+ self.set_camera_orientation(phi=65*DEGREES, theta=-45*DEGREES)
63
+
64
+ # Univariate
65
+ bell = NormalCurve3D(mu=0, sigma=1)
66
+ self.play(bell.animate_curve())
67
+ self.play(bell.animate_fill())
68
+ self.play(bell.animate_rule_68_95_99())
69
+
70
+ # Bivariate surface
71
+ surf = BivariateNormal3D(mu_x=0, mu_y=0, sigma_x=1, sigma_y=1, rho=0.0)
72
+ self.play(surf.animate_rise())
73
+ """
74
+
75
+ from __future__ import annotations
76
+
77
+ from dataclasses import dataclass, field
78
+ from typing import List, Tuple, Optional, Callable, Union, Dict
79
+ import numpy as np
80
+
81
+ from manim import (
82
+ VGroup, VMobject, Polygon, Line, DashedLine, Dot3D,
83
+ Text, MathTex, Arrow,
84
+ ThreeDScene,
85
+ AnimationGroup, LaggedStart, Succession,
86
+ Create, FadeIn, FadeOut, Transform,
87
+ UpdateFromAlphaFunc, Flash, Write,
88
+ DEGREES, PI, TAU,
89
+ RIGHT, LEFT, UP, DOWN, OUT, IN, ORIGIN,
90
+ X_AXIS, Y_AXIS, Z_AXIS,
91
+ WHITE, BLACK, GRAY, BLUE, GREEN, RED, YELLOW,
92
+ ManimColor, color_to_rgb, rgba_to_color, color_to_rgba,
93
+ rate_functions, smooth,
94
+ )
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Colour helpers
98
+ # ---------------------------------------------------------------------------
99
+
100
+ def _with_opacity(color: ManimColor, opacity: float) -> ManimColor:
101
+ r, g, b = color_to_rgb(color)
102
+ return rgba_to_color([r, g, b, max(0.0, min(1.0, opacity))])
103
+
104
+ def _darken(color: ManimColor, factor: float = 0.65) -> ManimColor:
105
+ r, g, b = color_to_rgb(color)
106
+ return ManimColor([r * factor, g * factor, b * factor])
107
+
108
+ def _lighten(color: ManimColor, factor: float = 1.35) -> ManimColor:
109
+ r, g, b = color_to_rgb(color)
110
+ return ManimColor([min(r * factor, 1.0), min(g * factor, 1.0), min(b * factor, 1.0)])
111
+
112
+ def _lerp_color(a: ManimColor, b: ManimColor, t: float) -> ManimColor:
113
+ ra, ga, ba = color_to_rgb(a)
114
+ rb, gb, bb = color_to_rgb(b)
115
+ return ManimColor([ra + (rb - ra) * t, ga + (gb - ga) * t, ba + (bb - ba) * t])
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # Special functions (self-contained)
120
+ # ---------------------------------------------------------------------------
121
+
122
+ def _erf(z: float) -> float:
123
+ t = 1.0 / (1.0 + 0.3275911 * abs(z))
124
+ poly = t * (0.254829592 + t * (-0.284496736
125
+ + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))))
126
+ val = 1.0 - poly * np.exp(-z * z)
127
+ return float(val if z >= 0 else -val)
128
+
129
+
130
+ def _normal_pdf(x: np.ndarray, mu: float = 0.0, sigma: float = 1.0) -> np.ndarray:
131
+ z = (np.asarray(x, dtype=float) - mu) / sigma
132
+ return np.exp(-0.5 * z**2) / (sigma * np.sqrt(TAU))
133
+
134
+
135
+ def _normal_cdf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
136
+ z = (x - mu) / (sigma * np.sqrt(2))
137
+ return 0.5 * (1.0 + _erf(z))
138
+
139
+
140
+ def _bivariate_normal_pdf(
141
+ x: np.ndarray,
142
+ y: np.ndarray,
143
+ mu_x: float, mu_y: float,
144
+ sigma_x: float, sigma_y: float,
145
+ rho: float,
146
+ ) -> np.ndarray:
147
+ """Bivariate normal density on meshgrid arrays X, Y."""
148
+ denom = 2 * PI * sigma_x * sigma_y * np.sqrt(1 - rho**2)
149
+ dx = (x - mu_x) / sigma_x
150
+ dy = (y - mu_y) / sigma_y
151
+ z = dx**2 - 2 * rho * dx * dy + dy**2
152
+ return np.exp(-z / (2 * (1 - rho**2))) / denom
153
+
154
+
155
+ def _catmull_rom(points: np.ndarray, resolution: int = 16) -> np.ndarray:
156
+ n = len(points)
157
+ if n < 2:
158
+ return points.copy()
159
+ p = np.vstack([2 * points[0] - points[1], points, 2 * points[-1] - points[-2]])
160
+ out = []
161
+ for i in range(1, len(p) - 2):
162
+ p0, p1, p2, p3 = p[i-1], p[i], p[i+1], p[i+2]
163
+ for j in range(resolution):
164
+ t = j / resolution
165
+ t2, t3 = t*t, t*t*t
166
+ pt = 0.5 * ((-t3+2*t2-t)*p0 + (3*t3-5*t2+2)*p1
167
+ + (-3*t3+4*t2+t)*p2 + (t3-t2)*p3)
168
+ out.append(pt)
169
+ out.append(points[-1].copy())
170
+ return np.array(out)
171
+
172
+
173
+ # ---------------------------------------------------------------------------
174
+ # Internal fill helper
175
+ # ---------------------------------------------------------------------------
176
+
177
+ def _gradient_fill(
178
+ curve_pts: np.ndarray,
179
+ floor_z: float,
180
+ y_pos: float,
181
+ color: ManimColor,
182
+ opacity: float,
183
+ n_strips: int = 12,
184
+ ) -> VGroup:
185
+ floor_pts = np.array([[p[0], y_pos, floor_z] for p in curve_pts])
186
+ grp = VGroup()
187
+ for s in range(n_strips):
188
+ t0, t1 = s / n_strips, (s + 1) / n_strips
189
+ strip_op = opacity * (1.0 - 0.62 * t0)
190
+ lo = curve_pts * (1 - t0) + floor_pts * t0
191
+ hi = curve_pts * (1 - t1) + floor_pts * t1
192
+ pts = list(lo) + list(reversed(hi))
193
+ grp.add(Polygon(*pts,
194
+ fill_color=_with_opacity(color, strip_op),
195
+ fill_opacity=1.0, stroke_width=0))
196
+ return grp
197
+
198
+
199
+ # ===========================================================================
200
+ # BivariateNormalConfig
201
+ # ===========================================================================
202
+
203
+ @dataclass
204
+ class BivariateNormalConfig:
205
+ """Visual configuration for ``BivariateNormal3D``.
206
+
207
+ Surface mesh
208
+ ~~~~~~~~~~~~
209
+ ``n_x`` / ``n_y`` : mesh resolution (quads per axis).
210
+ ``x_range`` / ``y_range``: (min, max) display range per axis.
211
+ ``z_scale`` : scene-unit height of the PDF peak.
212
+ ``surface_color_lo`` : colour at the tails (low density).
213
+ ``surface_color_hi`` : colour at the peak (high density).
214
+ ``surface_opacity`` : overall surface opacity.
215
+ ``edge_opacity`` : opacity of quad edge strokes.
216
+ ``edge_stroke_width`` : quad edge stroke width.
217
+
218
+ Lighting
219
+ ~~~~~~~~
220
+ ``light_direction`` : 3D unit vector toward the light source.
221
+ Each quad's face normal is dotted with this
222
+ to produce shading intensity (0.4 – 1.0).
223
+ ``ambient_light`` : minimum shading factor regardless of angle.
224
+
225
+ Marginal curves
226
+ ~~~~~~~~~~~~~~~
227
+ ``show_marginals`` : whether to project marginal density curves
228
+ onto the xz and yz walls.
229
+ ``marginal_color`` : colour of marginal curves.
230
+ ``marginal_stroke_width``: stroke width of marginal curves.
231
+ ``marginal_fill`` : whether to fill below marginal curves.
232
+ ``marginal_fill_opacity``: opacity of marginal fill.
233
+ ``y_wall`` : y-coordinate of the xz projection plane.
234
+ ``x_wall`` : x-coordinate of the yz projection plane.
235
+
236
+ Contours
237
+ ~~~~~~~~
238
+ ``contour_levels`` : list of probability density levels to contour.
239
+ ``contour_color`` : colour of all contour ellipses.
240
+ ``contour_stroke_width``: stroke width.
241
+ ``contour_opacity`` : opacity of contour lines.
242
+ ``n_contour_pts`` : points per contour ellipse.
243
+
244
+ Conditional slice
245
+ ~~~~~~~~~~~~~~~~~
246
+ ``slice_color`` : colour of the conditional distribution plane.
247
+ ``slice_opacity`` : opacity of the slice fill.
248
+ """
249
+
250
+ # Surface mesh
251
+ n_x: int = 40
252
+ n_y: int = 40
253
+ x_range: Tuple[float, float] = (-3.5, 3.5)
254
+ y_range: Tuple[float, float] = (-3.5, 3.5)
255
+ z_scale: float = 3.5
256
+
257
+ surface_color_lo: ManimColor = ManimColor("#0C3D7A")
258
+ surface_color_hi: ManimColor = ManimColor("#88CCFF")
259
+ surface_opacity: float = 0.82
260
+ edge_opacity: float = 0.18
261
+ edge_stroke_width: float = 0.4
262
+
263
+ # Lighting
264
+ light_direction: np.ndarray = field(
265
+ default_factory=lambda: np.array([0.35, -0.55, 1.0]) / np.linalg.norm(
266
+ np.array([0.35, -0.55, 1.0])
267
+ )
268
+ )
269
+ ambient_light: float = 0.40
270
+
271
+ # Marginal curves
272
+ show_marginals: bool = True
273
+ marginal_color: ManimColor = ManimColor("#E0AA40")
274
+ marginal_stroke_width: float = 2.4
275
+ marginal_fill: bool = True
276
+ marginal_fill_opacity: float = 0.18
277
+ y_wall: float = 3.8
278
+ x_wall: float = -3.8
279
+
280
+ # Contours
281
+ contour_levels: List[float] = field(default_factory=lambda: [0.5, 0.25, 0.10, 0.04])
282
+ contour_color: ManimColor = ManimColor("#FFD700")
283
+ contour_stroke_width: float = 1.6
284
+ contour_opacity: float = 0.70
285
+ n_contour_pts: int = 80
286
+
287
+ # Conditional slice
288
+ slice_color: ManimColor = ManimColor("#E8593C")
289
+ slice_opacity: float = 0.30
290
+
291
+
292
+ # ── Presets ──────────────────────────────────────────────────────────────
293
+
294
+ CRISP_SURFACE = BivariateNormalConfig(
295
+ n_x=30, n_y=30,
296
+ edge_opacity=0.22,
297
+ surface_opacity=0.85,
298
+ show_marginals=True,
299
+ )
300
+
301
+ DENSE_SURFACE = BivariateNormalConfig(
302
+ n_x=55, n_y=55,
303
+ edge_opacity=0.10,
304
+ surface_opacity=0.80,
305
+ show_marginals=True,
306
+ contour_levels=[0.60, 0.30, 0.12, 0.04, 0.01],
307
+ )
308
+
309
+ WIREFRAME = BivariateNormalConfig(
310
+ n_x=25, n_y=25,
311
+ surface_opacity=0.0,
312
+ edge_opacity=0.65,
313
+ edge_stroke_width=0.8,
314
+ show_marginals=False,
315
+ contour_levels=[],
316
+ )
317
+
318
+
319
+ # ===========================================================================
320
+ # NormalCurve3D
321
+ # ===========================================================================
322
+
323
+ class NormalCurve3D(VGroup):
324
+ """Univariate Normal bell curve with full pedagogical annotation system.
325
+
326
+ Visual layers
327
+ ~~~~~~~~~~~~~
328
+ - ``curve_group`` : glow halo + primary stroke.
329
+ - ``fill_group`` : gradient area fill.
330
+ - ``moments_group`` : μ line, σ brackets, σ tick marks.
331
+ - ``rule_group`` : 68-95-99.7 shaded regions.
332
+ - ``zscore_group`` : z-score ruler beneath the curve.
333
+ - ``clt_group`` : sampling distribution overlay (σ/√n).
334
+ - ``title_group`` : N(μ, σ²) title.
335
+ - ``std_form_group`` : standardised N(0,1) target curve (for morph).
336
+
337
+ Parameters
338
+ ----------
339
+ mu : float
340
+ Mean.
341
+ sigma : float
342
+ Standard deviation (> 0).
343
+ x_range : (float, float, float) or None
344
+ (x_min, x_max, x_step). Defaults to μ ± 4σ.
345
+ color : ManimColor
346
+ z_scale : float
347
+ Scene z-units at the PDF peak.
348
+ x_pos, y_pos, floor_z : float
349
+ Scene-space offsets.
350
+ glow_opacity : float
351
+ fill_opacity : float
352
+ fill_gradient : bool
353
+ scene : ThreeDScene or None
354
+ """
355
+
356
+ def __init__(
357
+ self,
358
+ mu: float = 0.0,
359
+ sigma: float = 1.0,
360
+ x_range: Optional[Tuple[float, float, float]] = None,
361
+ color: ManimColor = ManimColor("#4A90D9"),
362
+ z_scale: float = 3.8,
363
+ x_pos: float = 0.0,
364
+ y_pos: float = 0.0,
365
+ floor_z: float = 0.0,
366
+ glow_opacity: float = 0.14,
367
+ fill_opacity: float = 0.26,
368
+ fill_gradient: bool = True,
369
+ stroke_width: float = 3.0,
370
+ smooth_resolution: int = 22,
371
+ scene: Optional[ThreeDScene] = None,
372
+ **kwargs,
373
+ ):
374
+ super().__init__(**kwargs)
375
+
376
+ self.mu = float(mu)
377
+ self.sigma = float(sigma)
378
+ self.color = color
379
+ self.z_scale = z_scale
380
+ self.x_pos = x_pos
381
+ self.y_pos = y_pos
382
+ self.floor_z = floor_z
383
+ self._scene = scene
384
+
385
+ # Resolve x_range
386
+ if x_range is not None:
387
+ self._x_min, self._x_max, self._x_step = x_range
388
+ else:
389
+ self._x_min = mu - 4.2 * sigma
390
+ self._x_max = mu + 4.2 * sigma
391
+ self._x_step = (self._x_max - self._x_min) / 220
392
+
393
+ # Sample PDF — store raw and scaled arrays
394
+ xs = np.arange(self._x_min, self._x_max + self._x_step * 0.5, self._x_step)
395
+ ys_raw = _normal_pdf(xs, mu, sigma)
396
+ peak = float(ys_raw.max())
397
+ self._peak = peak
398
+ ys = ys_raw / peak * z_scale # peak maps to z_scale
399
+
400
+ self._xs = xs + x_pos
401
+ self._ys = ys
402
+ self._ys_raw = ys_raw
403
+
404
+ # 3D curve points
405
+ raw_pts = np.column_stack([self._xs, np.full(len(xs), y_pos), ys])
406
+ self._pts = _catmull_rom(raw_pts, resolution=smooth_resolution)
407
+
408
+ # Layer groups
409
+ self.curve_group = VGroup()
410
+ self.fill_group = VGroup()
411
+ self.moments_group = VGroup()
412
+ self.rule_group = VGroup()
413
+ self.zscore_group = VGroup()
414
+ self.clt_group = VGroup()
415
+ self.title_group = VGroup()
416
+
417
+ # Build primary layers
418
+ self._stroke_width = stroke_width
419
+ self._glow_opacity = glow_opacity
420
+ self._fill_opacity = fill_opacity
421
+ self._fill_gradient = fill_gradient
422
+ self._n_strips = 12
423
+
424
+ self._build_curve()
425
+ self._build_fill()
426
+ self._build_moments(scene)
427
+
428
+ self.add(
429
+ self.fill_group, self.curve_group,
430
+ self.moments_group, self.rule_group,
431
+ self.zscore_group, self.clt_group,
432
+ self.title_group,
433
+ )
434
+
435
+ # ------------------------------------------------------------------
436
+ # Internal builders
437
+ # ------------------------------------------------------------------
438
+
439
+ def _build_curve(self) -> None:
440
+ col = _with_opacity(self.color, 1.0)
441
+
442
+ self.stroke = VMobject()
443
+ self.stroke.set_points_as_corners(self._pts)
444
+ self.stroke.set_stroke(color=col, width=self._stroke_width)
445
+ self.stroke.set_fill(opacity=0)
446
+
447
+ if self._glow_opacity > 0:
448
+ self.glow = VMobject()
449
+ self.glow.set_points_as_corners(self._pts)
450
+ self.glow.set_stroke(
451
+ color=_with_opacity(self.color, self._glow_opacity),
452
+ width=self._stroke_width * 3.2,
453
+ )
454
+ self.glow.set_fill(opacity=0)
455
+ self.curve_group.add(self.glow)
456
+
457
+ self.curve_group.add(self.stroke)
458
+
459
+ def _build_fill(self) -> None:
460
+ fill = _gradient_fill(
461
+ self._pts, self.floor_z, self.y_pos,
462
+ self.color, self._fill_opacity, self._n_strips,
463
+ )
464
+ self.fill_group.add(fill)
465
+
466
+ def _build_moments(self, scene: Optional[ThreeDScene]) -> None:
467
+ mu, sigma = self.mu, self.sigma
468
+ y = self.y_pos
469
+ z0 = self.floor_z
470
+ x_mu = mu + self.x_pos
471
+ z_peak = self.z_scale # PDF peak height
472
+
473
+ mean_col = _with_opacity(ManimColor("#E0AA40"), 0.85)
474
+
475
+ # Mean dashed line
476
+ mean_ln = DashedLine(
477
+ np.array([x_mu, y, z0]),
478
+ np.array([x_mu, y, z_peak * 1.04]),
479
+ dash_length=0.07, dashed_ratio=0.45,
480
+ color=mean_col, stroke_width=1.8,
481
+ )
482
+ mean_dot = Dot3D(np.array([x_mu, y, z0]), radius=0.06, color=mean_col)
483
+ mu_lbl = Text(f"μ = {mu:.3g}", font_size=17, color=ManimColor("#E0AA40"))
484
+ mu_lbl.move_to(np.array([x_mu + 0.15, y, z_peak + 0.30]))
485
+ self.moments_group.add(mean_ln, mean_dot, mu_lbl)
486
+ if scene is not None:
487
+ scene.add_fixed_orientation_mobjects(mu_lbl)
488
+
489
+ # ±1σ and ±2σ tick marks and brackets
490
+ sig_col = _with_opacity(ManimColor("#E0AA40"), 0.65)
491
+ for n_sig in [1, 2]:
492
+ for sign in [-1, +1]:
493
+ x_s = (mu + sign * n_sig * sigma) + self.x_pos
494
+ tick = Line(
495
+ np.array([x_s, y, z0 - 0.05]),
496
+ np.array([x_s, y, z0 + 0.05]),
497
+ color=sig_col, stroke_width=1.4,
498
+ )
499
+ self.moments_group.add(tick)
500
+
501
+ # Horizontal bracket at z = -0.12*n_sig
502
+ lo_x = (mu - n_sig * sigma) + self.x_pos
503
+ hi_x = (mu + n_sig * sigma) + self.x_pos
504
+ z_b = z0 - 0.12 * n_sig
505
+ bracket = VGroup(
506
+ Line(np.array([lo_x, y, z_b]), np.array([hi_x, y, z_b]),
507
+ color=sig_col, stroke_width=1.2),
508
+ Line(np.array([lo_x, y, z_b]), np.array([lo_x, y, z_b + 0.07]),
509
+ color=sig_col, stroke_width=1.2),
510
+ Line(np.array([hi_x, y, z_b]), np.array([hi_x, y, z_b + 0.07]),
511
+ color=sig_col, stroke_width=1.2),
512
+ )
513
+ lbl = Text(f"±{n_sig}σ", font_size=14, color=ManimColor("#E0AA40"))
514
+ lbl.move_to(np.array([(lo_x + hi_x) / 2, y, z_b - 0.22]))
515
+ self.moments_group.add(bracket, lbl)
516
+ if scene is not None:
517
+ scene.add_fixed_orientation_mobjects(lbl)
518
+
519
+ # ------------------------------------------------------------------
520
+ # Public annotation methods
521
+ # ------------------------------------------------------------------
522
+
523
+ def animate_rule_68_95_99(
524
+ self,
525
+ scene: Optional[ThreeDScene] = None,
526
+ sequential: bool = True,
527
+ run_time_per: float = 0.55,
528
+ ) -> AnimationGroup:
529
+ """Build and animate the 68-95-99.7 rule shaded regions.
530
+
531
+ Three nested shaded zones appear, each with a probability label.
532
+
533
+ Parameters
534
+ ----------
535
+ scene : ThreeDScene or None
536
+ Needed to register fixed-orientation labels.
537
+ sequential : bool
538
+ If True, reveal 1σ → 2σ → 3σ in sequence.
539
+ run_time_per : float
540
+ Duration per zone reveal.
541
+
542
+ Returns
543
+ -------
544
+ AnimationGroup (or LaggedStart if sequential)
545
+ """
546
+ rule_data = [
547
+ (1, ManimColor("#2DAA6E"), "68.27%"),
548
+ (2, ManimColor("#E0AA40"), "95.45%"),
549
+ (3, ManimColor("#E8593C"), "99.73%"),
550
+ ]
551
+ self.rule_group.remove(*list(self.rule_group))
552
+
553
+ anims = []
554
+ for n_sig, col, pct in rule_data:
555
+ zone = self._build_rule_zone(n_sig, col, pct, scene)
556
+ self.rule_group.add(zone)
557
+ anims.append(FadeIn(zone, run_time=run_time_per))
558
+
559
+ if sequential:
560
+ return LaggedStart(*anims, lag_ratio=0.4)
561
+ return AnimationGroup(*anims)
562
+
563
+ def _build_rule_zone(
564
+ self,
565
+ n_sig: int,
566
+ color: ManimColor,
567
+ label: str,
568
+ scene: Optional[ThreeDScene],
569
+ ) -> VGroup:
570
+ mu, sigma = self.mu, self.sigma
571
+ lo = mu - n_sig * sigma
572
+ hi = mu + n_sig * sigma
573
+
574
+ mask = (self._xs >= lo + self.x_pos) & (self._xs <= hi + self.x_pos)
575
+ xs_r = self._xs[mask]
576
+ ys_r = self._ys[mask]
577
+
578
+ if len(xs_r) < 2:
579
+ return VGroup()
580
+
581
+ # Boundary points
582
+ y_lo = float(_normal_pdf(lo, mu, sigma)) / self._peak * self.z_scale
583
+ y_hi = float(_normal_pdf(hi, mu, sigma)) / self._peak * self.z_scale
584
+
585
+ xs_full = np.concatenate([[lo + self.x_pos], xs_r, [hi + self.x_pos]])
586
+ ys_full = np.concatenate([[y_lo], ys_r, [y_hi]])
587
+ pts = np.column_stack([xs_full, np.full(len(xs_full), self.y_pos), ys_full])
588
+
589
+ fill = _gradient_fill(pts, self.floor_z, self.y_pos,
590
+ color, 0.28, n_strips=8)
591
+
592
+ grp = VGroup(fill)
593
+
594
+ # Probability label
595
+ z_peak_zone = float(np.max(ys_r)) if len(ys_r) > 0 else self.z_scale
596
+ lbl = Text(label, font_size=20, color=color)
597
+ lbl.move_to(np.array([
598
+ (lo + hi) / 2 + self.x_pos,
599
+ self.y_pos,
600
+ z_peak_zone * 0.55,
601
+ ]))
602
+ grp.add(lbl)
603
+ if scene is not None:
604
+ scene.add_fixed_orientation_mobjects(lbl)
605
+
606
+ return grp
607
+
608
+ def add_zscore_ruler(
609
+ self,
610
+ scene: Optional[ThreeDScene] = None,
611
+ n_ticks: int = 9,
612
+ ) -> VGroup:
613
+ """Add a z-score ruler beneath the curve.
614
+
615
+ Tick marks at every integer z-score from -4 to +4 with labels.
616
+ Tick at z=0 is emphasised.
617
+
618
+ Returns the ruler VGroup added to ``self.zscore_group``.
619
+ """
620
+ self.zscore_group.remove(*list(self.zscore_group))
621
+ mu, sigma = self.mu, self.sigma
622
+ y = self.y_pos
623
+ z0 = self.floor_z - 0.35
624
+
625
+ ruler_col = _with_opacity(WHITE, 0.40)
626
+ ruler = Line(
627
+ np.array([self._x_min, y, z0]),
628
+ np.array([self._x_max, y, z0]),
629
+ color=ruler_col, stroke_width=1.0,
630
+ )
631
+ self.zscore_group.add(ruler)
632
+
633
+ z_vals = np.arange(-4, 5)
634
+ for z_val in z_vals:
635
+ x_pos_tick = mu + z_val * sigma + self.x_pos
636
+ if x_pos_tick < self._x_min or x_pos_tick > self._x_max:
637
+ continue
638
+ h = 0.10 if z_val != 0 else 0.16
639
+ tick_col = _with_opacity(WHITE, 0.65 if z_val == 0 else 0.38)
640
+ tick = Line(
641
+ np.array([x_pos_tick, y, z0 - h / 2]),
642
+ np.array([x_pos_tick, y, z0 + h / 2]),
643
+ color=tick_col,
644
+ stroke_width=1.6 if z_val == 0 else 1.0,
645
+ )
646
+ lbl = Text(str(int(z_val)), font_size=14, color=tick_col)
647
+ lbl.move_to(np.array([x_pos_tick, y, z0 - 0.28]))
648
+ self.zscore_group.add(tick, lbl)
649
+ if scene is not None:
650
+ scene.add_fixed_orientation_mobjects(lbl)
651
+
652
+ return self.zscore_group
653
+
654
+ def add_title(
655
+ self,
656
+ scene: Optional[ThreeDScene] = None,
657
+ ) -> VGroup:
658
+ """Add a 'N(μ, σ²)' title above the curve peak."""
659
+ self.title_group.remove(*list(self.title_group))
660
+ x_cen = self.mu + self.x_pos
661
+ z_top = self.z_scale * 1.14
662
+
663
+ main_lbl = Text(
664
+ f"N(μ={self.mu:.3g}, σ={self.sigma:.3g})",
665
+ font_size=22, color=_with_opacity(self.color, 0.88),
666
+ )
667
+ main_lbl.move_to(np.array([x_cen, self.y_pos, z_top]))
668
+ self.title_group.add(main_lbl)
669
+ if scene is not None:
670
+ scene.add_fixed_orientation_mobjects(main_lbl)
671
+ return self.title_group
672
+
673
+ def add_clt_overlay(
674
+ self,
675
+ n_sample: int = 10,
676
+ color: Optional[ManimColor] = None,
677
+ scene: Optional[ThreeDScene] = None,
678
+ ) -> VGroup:
679
+ """Overlay the sampling distribution of x̄ ~ N(μ, σ²/n).
680
+
681
+ The overlay is narrower and taller than the population curve.
682
+ A label "x̄ ~ N(μ, σ/√n)" is added.
683
+
684
+ Parameters
685
+ ----------
686
+ n_sample : int
687
+ Sample size n.
688
+ color : ManimColor or None
689
+ Defaults to a lighter version of the curve colour.
690
+
691
+ Returns
692
+ -------
693
+ VGroup added to ``self.clt_group``.
694
+ """
695
+ self.clt_group.remove(*list(self.clt_group))
696
+ se = self.sigma / np.sqrt(max(n_sample, 1))
697
+ col = color if color is not None else _lighten(self.color, 1.50)
698
+
699
+ xs = np.arange(self._x_min, self._x_max + self._x_step * 0.5, self._x_step)
700
+ ys_clt = _normal_pdf(xs, self.mu, se)
701
+ ys_clt_scaled = ys_clt / float(ys_clt.max()) * self.z_scale if ys_clt.max() > 0 else ys_clt
702
+
703
+ pts_clt = _catmull_rom(np.column_stack([
704
+ xs + self.x_pos,
705
+ np.full(len(xs), self.y_pos),
706
+ ys_clt_scaled,
707
+ ]), resolution=18)
708
+
709
+ stroke_clt = VMobject()
710
+ stroke_clt.set_points_as_corners(pts_clt)
711
+ stroke_clt.set_stroke(color=_with_opacity(col, 0.88), width=2.5)
712
+ stroke_clt.set_fill(opacity=0)
713
+
714
+ glow_clt = VMobject()
715
+ glow_clt.set_points_as_corners(pts_clt)
716
+ glow_clt.set_stroke(color=_with_opacity(col, 0.13), width=8.0)
717
+ glow_clt.set_fill(opacity=0)
718
+
719
+ lbl = Text(
720
+ f"x̄ ~ N(μ, σ/√{n_sample})",
721
+ font_size=18, color=col,
722
+ )
723
+ lbl.move_to(np.array([
724
+ self.mu + self.x_pos + self.sigma * 1.8,
725
+ self.y_pos,
726
+ self.z_scale * 0.85,
727
+ ]))
728
+ if scene is not None:
729
+ scene.add_fixed_orientation_mobjects(lbl)
730
+
731
+ self.clt_group.add(glow_clt, stroke_clt, lbl)
732
+ return self.clt_group
733
+
734
+ def shade_region(
735
+ self,
736
+ x_lo: float,
737
+ x_hi: float,
738
+ color: ManimColor = ManimColor("#E8593C"),
739
+ label: bool = True,
740
+ scene: Optional[ThreeDScene] = None,
741
+ ) -> VGroup:
742
+ """Shade the region under the curve between *x_lo* and *x_hi*.
743
+
744
+ Computes P(x_lo ≤ X ≤ x_hi) analytically.
745
+ """
746
+ lo = max(x_lo, self._x_min - self.x_pos)
747
+ hi = min(x_hi, self._x_max - self.x_pos)
748
+ mask = (self._xs >= lo + self.x_pos) & (self._xs <= hi + self.x_pos)
749
+ xs_r = self._xs[mask]
750
+ ys_r = self._ys[mask]
751
+
752
+ if len(xs_r) < 2:
753
+ return VGroup()
754
+
755
+ y_lo = float(_normal_pdf(lo, self.mu, self.sigma)) / self._peak * self.z_scale
756
+ y_hi = float(_normal_pdf(hi, self.mu, self.sigma)) / self._peak * self.z_scale
757
+ xs_f = np.concatenate([[lo + self.x_pos], xs_r, [hi + self.x_pos]])
758
+ ys_f = np.concatenate([[y_lo], ys_r, [y_hi]])
759
+ pts = np.column_stack([xs_f, np.full(len(xs_f), self.y_pos), ys_f])
760
+
761
+ fill = _gradient_fill(pts, self.floor_z, self.y_pos, color, 0.30, n_strips=1)
762
+
763
+ p_val = _normal_cdf(hi, self.mu, self.sigma) - _normal_cdf(lo, self.mu, self.sigma)
764
+ grp = VGroup(fill)
765
+
766
+ if label:
767
+ z_mid = float(np.max(ys_r)) * 0.55 if len(ys_r) > 0 else self.z_scale * 0.5
768
+ lbl = Text(f"P = {p_val:.4f}", font_size=20, color=color)
769
+ lbl.move_to(np.array([(lo + hi) / 2 + self.x_pos, self.y_pos, z_mid + 0.38]))
770
+ grp.add(lbl)
771
+ if scene is not None:
772
+ scene.add_fixed_orientation_mobjects(lbl)
773
+
774
+ return grp
775
+
776
+ # ------------------------------------------------------------------
777
+ # Standardisation animation
778
+ # ------------------------------------------------------------------
779
+
780
+ def animate_standardise(
781
+ self,
782
+ run_time: float = 2.0,
783
+ scene: Optional[ThreeDScene] = None,
784
+ ) -> UpdateFromAlphaFunc:
785
+ """Animate N(μ, σ) → N(0, 1) standardisation.
786
+
787
+ The curve shifts left by μ and narrows by factor 1/σ.
788
+ Returns an ``UpdateFromAlphaFunc`` that morphs the stroke.
789
+
790
+ Note: the caller should update mu/sigma after playing this
791
+ animation if further operations are needed.
792
+ """
793
+ mu0, sigma0 = self.mu, self.sigma
794
+ mu1, sigma1 = 0.0, 1.0
795
+
796
+ # Build target curve points
797
+ xs_std = np.arange(self._x_min, self._x_max + self._x_step * 0.5, self._x_step)
798
+ ys_std = _normal_pdf(xs_std, mu1, sigma1)
799
+ peak_std = float(ys_std.max())
800
+ ys_std_scaled = ys_std / peak_std * self.z_scale
801
+
802
+ src_pts = _catmull_rom(np.column_stack([
803
+ xs_std + self.x_pos,
804
+ np.full(len(xs_std), self.y_pos),
805
+ _normal_pdf(xs_std, mu0, sigma0) / self._peak * self.z_scale,
806
+ ]), resolution=18)
807
+
808
+ tgt_pts = _catmull_rom(np.column_stack([
809
+ xs_std + self.x_pos,
810
+ np.full(len(xs_std), self.y_pos),
811
+ ys_std_scaled,
812
+ ]), resolution=18)
813
+
814
+ # Resample to same length
815
+ n = max(len(src_pts), len(tgt_pts))
816
+
817
+ def _resample(pts, nn):
818
+ if len(pts) == nn:
819
+ return pts
820
+ idx = np.linspace(0, len(pts) - 1, nn)
821
+ return np.array([pts[int(i)] for i in np.floor(idx).astype(int)])
822
+
823
+ src_r = _resample(src_pts, n)
824
+ tgt_r = _resample(tgt_pts, n)
825
+ stroke = self.stroke
826
+
827
+ def updater(mob: VMobject, alpha: float) -> None:
828
+ t = rate_functions.ease_in_out_cubic(alpha)
829
+ pts = src_r + (tgt_r - src_r) * t
830
+ mob.set_points_as_corners(pts)
831
+ if hasattr(self, 'glow'):
832
+ self.glow.set_points_as_corners(pts)
833
+
834
+ return UpdateFromAlphaFunc(stroke, updater, run_time=run_time)
835
+
836
+ # ------------------------------------------------------------------
837
+ # Animation helpers
838
+ # ------------------------------------------------------------------
839
+
840
+ def animate_curve(self, run_time: float = 1.5) -> AnimationGroup:
841
+ anims = [Create(self.stroke, run_time=run_time)]
842
+ if hasattr(self, 'glow'):
843
+ anims.append(FadeIn(self.glow, run_time=run_time * 0.4))
844
+ return AnimationGroup(*anims, lag_ratio=0.0)
845
+
846
+ def animate_fill(self, run_time: float = 1.0) -> UpdateFromAlphaFunc:
847
+ pts = self._pts
848
+ floor_z = self.floor_z
849
+ y_pos = self.y_pos
850
+ color = self.color
851
+ op = self._fill_opacity
852
+ n_strips = self._n_strips
853
+
854
+ def updater(mob: VGroup, alpha: float) -> None:
855
+ t = smooth(alpha)
856
+ interp = np.column_stack([
857
+ pts[:, 0], pts[:, 1],
858
+ floor_z + (pts[:, 2] - floor_z) * t,
859
+ ])
860
+ mob.become(_gradient_fill(interp, floor_z, y_pos, color, op, n_strips))
861
+
862
+ return UpdateFromAlphaFunc(self.fill_group, updater, run_time=run_time)
863
+
864
+ def animate_moments(self, run_time: float = 0.7) -> FadeIn:
865
+ return FadeIn(self.moments_group, run_time=run_time)
866
+
867
+ def full_reveal(
868
+ self,
869
+ scene: ThreeDScene,
870
+ curve_rt: float = 1.5,
871
+ fill_rt: float = 1.0,
872
+ moments_rt: float = 0.7,
873
+ ) -> None:
874
+ scene.play(self.animate_curve(run_time=curve_rt))
875
+ scene.play(self.animate_fill(run_time=fill_rt))
876
+ scene.play(self.animate_moments(run_time=moments_rt))
877
+
878
+
879
+ # ===========================================================================
880
+ # BivariateNormal3D
881
+ # ===========================================================================
882
+
883
+ class BivariateNormal3D(VGroup):
884
+ """True 3D parametric surface for the bivariate normal distribution.
885
+
886
+ The surface is a dense mesh of quad polygons, each independently
887
+ shaded using a Phong-style light model:
888
+ intensity = ambient + (1 - ambient) × max(0, n̂ · l̂)
889
+ where n̂ is the face normal and l̂ is the light direction.
890
+
891
+ Visual layers
892
+ ~~~~~~~~~~~~~
893
+ - ``surface_group`` : all quad polygon patches.
894
+ - ``marginal_x`` : marginal density on the xz wall.
895
+ - ``marginal_y`` : marginal density on the yz wall.
896
+ - ``contour_group`` : isoprobability ellipses at z = 0.
897
+ - ``axes_group`` : thin axis lines in the base plane.
898
+ - ``title_group`` : distribution name label.
899
+
900
+ Parameters
901
+ ----------
902
+ mu_x, mu_y : float
903
+ Marginal means.
904
+ sigma_x, sigma_y : float
905
+ Marginal standard deviations.
906
+ rho : float
907
+ Correlation coefficient (−1 < ρ < 1).
908
+ config : BivariateNormalConfig
909
+ scene : ThreeDScene or None
910
+ """
911
+
912
+ def __init__(
913
+ self,
914
+ mu_x: float = 0.0,
915
+ mu_y: float = 0.0,
916
+ sigma_x: float = 1.0,
917
+ sigma_y: float = 1.0,
918
+ rho: float = 0.0,
919
+ config: Optional[BivariateNormalConfig] = None,
920
+ scene: Optional[ThreeDScene] = None,
921
+ **kwargs,
922
+ ):
923
+ super().__init__(**kwargs)
924
+
925
+ if not -1 < rho < 1:
926
+ raise ValueError(f"rho must be in (-1, 1), got {rho}")
927
+
928
+ self.mu_x = float(mu_x)
929
+ self.mu_y = float(mu_y)
930
+ self.sigma_x = float(sigma_x)
931
+ self.sigma_y = float(sigma_y)
932
+ self.rho = float(rho)
933
+ self.cfg = config if config is not None else BivariateNormalConfig()
934
+ self._scene = scene
935
+
936
+ # Pre-compute the PDF on a grid
937
+ cfg = self.cfg
938
+ self._xs_1d = np.linspace(cfg.x_range[0], cfg.x_range[1], cfg.n_x + 1)
939
+ self._ys_1d = np.linspace(cfg.y_range[0], cfg.y_range[1], cfg.n_y + 1)
940
+ self._X, self._Y = np.meshgrid(self._xs_1d, self._ys_1d)
941
+ self._Z_raw = _bivariate_normal_pdf(
942
+ self._X, self._Y,
943
+ mu_x, mu_y, sigma_x, sigma_y, rho,
944
+ )
945
+ self._z_peak = float(self._Z_raw.max())
946
+ self._Z = self._Z_raw / self._z_peak * cfg.z_scale
947
+
948
+ # Layer groups
949
+ self.surface_group = VGroup()
950
+ self.marginal_x = VGroup()
951
+ self.marginal_y = VGroup()
952
+ self.contour_group = VGroup()
953
+ self.axes_group = VGroup()
954
+ self.title_group = VGroup()
955
+
956
+ # Build all layers
957
+ self._build_surface()
958
+ if cfg.show_marginals:
959
+ self._build_marginal_x()
960
+ self._build_marginal_y()
961
+ self._build_contours()
962
+ self._build_axes()
963
+
964
+ self.add(
965
+ self.surface_group,
966
+ self.marginal_x, self.marginal_y,
967
+ self.contour_group,
968
+ self.axes_group, self.title_group,
969
+ )
970
+
971
+ # ------------------------------------------------------------------
972
+ # Surface mesh builder
973
+ # ------------------------------------------------------------------
974
+
975
+ def _face_normal(
976
+ self,
977
+ p00: np.ndarray,
978
+ p10: np.ndarray,
979
+ p01: np.ndarray,
980
+ ) -> np.ndarray:
981
+ """Compute the outward-facing normal of a quad patch.
982
+
983
+ Uses the cross product of two edge vectors.
984
+ """
985
+ v1 = p10 - p00
986
+ v2 = p01 - p00
987
+ n = np.cross(v1, v2)
988
+ norm = np.linalg.norm(n)
989
+ return n / norm if norm > 1e-10 else np.array([0, 0, 1.0])
990
+
991
+ def _shade(self, normal: np.ndarray) -> float:
992
+ """Return shading intensity ∈ [ambient, 1.0]."""
993
+ cfg = self.cfg
994
+ dot = float(np.dot(normal, cfg.light_direction))
995
+ return cfg.ambient_light + (1.0 - cfg.ambient_light) * max(dot, 0.0)
996
+
997
+ def _z_to_color(self, z_val: float) -> ManimColor:
998
+ """Map a scene-z value to the surface colour ramp."""
999
+ t = z_val / self.cfg.z_scale
1000
+ return _lerp_color(self.cfg.surface_color_lo, self.cfg.surface_color_hi, t)
1001
+
1002
+ def _build_surface(self) -> None:
1003
+ cfg = self.cfg
1004
+ Z = self._Z
1005
+ xs = self._xs_1d
1006
+ ys = self._ys_1d
1007
+ ec = _with_opacity(WHITE, cfg.edge_opacity)
1008
+ op = cfg.surface_opacity
1009
+
1010
+ for j in range(cfg.n_y):
1011
+ for i in range(cfg.n_x):
1012
+ # Four corners of quad (i,j)→(i+1,j)→(i+1,j+1)→(i,j+1)
1013
+ p00 = np.array([xs[i], ys[j], Z[j, i ]])
1014
+ p10 = np.array([xs[i+1], ys[j], Z[j, i+1]])
1015
+ p11 = np.array([xs[i+1], ys[j+1], Z[j+1, i+1]])
1016
+ p01 = np.array([xs[i], ys[j+1], Z[j+1, i ]])
1017
+
1018
+ n_hat = self._face_normal(p00, p10, p01)
1019
+ shade = self._shade(n_hat)
1020
+
1021
+ # Colour based on average z of the quad
1022
+ z_avg = (Z[j, i] + Z[j, i+1] + Z[j+1, i+1] + Z[j+1, i]) / 4
1023
+ base_col = self._z_to_color(z_avg)
1024
+ quad_col = _lerp_color(
1025
+ _darken(base_col, 0.4),
1026
+ _lighten(base_col, 1.2),
1027
+ shade,
1028
+ )
1029
+
1030
+ quad = Polygon(
1031
+ p00, p10, p11, p01,
1032
+ fill_color=_with_opacity(quad_col, op),
1033
+ fill_opacity=1.0,
1034
+ stroke_color=ec,
1035
+ stroke_width=cfg.edge_stroke_width,
1036
+ )
1037
+ self.surface_group.add(quad)
1038
+
1039
+ # ------------------------------------------------------------------
1040
+ # Marginal curves
1041
+ # ------------------------------------------------------------------
1042
+
1043
+ def _build_marginal_x(self) -> None:
1044
+ """Project marginal f_X onto the y = y_wall (xz) plane."""
1045
+ cfg = self.cfg
1046
+ xs = np.linspace(cfg.x_range[0], cfg.x_range[1], 200)
1047
+ ys_marg = _normal_pdf(xs, self.mu_x, self.sigma_x)
1048
+ z_max = float(ys_marg.max())
1049
+ ys_scaled = ys_marg / z_max * cfg.z_scale if z_max > 0 else ys_marg
1050
+
1051
+ pts = np.column_stack([xs, np.full(len(xs), cfg.y_wall), ys_scaled])
1052
+ smoothed = _catmull_rom(pts, resolution=14)
1053
+
1054
+ col = _with_opacity(cfg.marginal_color, 0.88)
1055
+ stroke = VMobject()
1056
+ stroke.set_points_as_corners(smoothed)
1057
+ stroke.set_stroke(color=col, width=cfg.marginal_stroke_width)
1058
+ stroke.set_fill(opacity=0)
1059
+ self.marginal_x.add(stroke)
1060
+
1061
+ if cfg.marginal_fill:
1062
+ fill = _gradient_fill(smoothed, 0.0, cfg.y_wall,
1063
+ cfg.marginal_color, cfg.marginal_fill_opacity, 8)
1064
+ self.marginal_x.add(fill)
1065
+
1066
+ def _build_marginal_y(self) -> None:
1067
+ """Project marginal f_Y onto the x = x_wall (yz) plane."""
1068
+ cfg = self.cfg
1069
+ ys = np.linspace(cfg.y_range[0], cfg.y_range[1], 200)
1070
+ zs_marg = _normal_pdf(ys, self.mu_y, self.sigma_y)
1071
+ z_max = float(zs_marg.max())
1072
+ zs_scaled = zs_marg / z_max * cfg.z_scale if z_max > 0 else zs_marg
1073
+
1074
+ pts = np.column_stack([np.full(len(ys), cfg.x_wall), ys, zs_scaled])
1075
+ smoothed = _catmull_rom(pts, resolution=14)
1076
+
1077
+ col = _with_opacity(cfg.marginal_color, 0.85)
1078
+ stroke = VMobject()
1079
+ stroke.set_points_as_corners(smoothed)
1080
+ stroke.set_stroke(color=col, width=cfg.marginal_stroke_width)
1081
+ stroke.set_fill(opacity=0)
1082
+ self.marginal_y.add(stroke)
1083
+
1084
+ if cfg.marginal_fill:
1085
+ # Fill in yz-plane: need custom floor at x=x_wall
1086
+ floor_pts = np.array([[cfg.x_wall, p[1], 0.0] for p in smoothed])
1087
+ fill_grp = VGroup()
1088
+ n_strips = 8
1089
+ for s in range(n_strips):
1090
+ t0, t1 = s / n_strips, (s + 1) / n_strips
1091
+ op_s = cfg.marginal_fill_opacity * (1.0 - 0.60 * t0)
1092
+ lo = smoothed * (1 - t0) + floor_pts * t0
1093
+ hi = smoothed * (1 - t1) + floor_pts * t1
1094
+ fill_grp.add(Polygon(
1095
+ *list(lo) + list(reversed(hi)),
1096
+ fill_color=_with_opacity(cfg.marginal_color, op_s),
1097
+ fill_opacity=1.0, stroke_width=0,
1098
+ ))
1099
+ self.marginal_y.add(fill_grp)
1100
+
1101
+ # ------------------------------------------------------------------
1102
+ # Contour ellipses
1103
+ # ------------------------------------------------------------------
1104
+
1105
+ def _build_contours(self) -> None:
1106
+ """Draw isoprobability contour ellipses at z = 0."""
1107
+ cfg = self.cfg
1108
+ if not cfg.contour_levels:
1109
+ return
1110
+
1111
+ peak_pdf = float(_bivariate_normal_pdf(
1112
+ np.array([[self.mu_x]]), np.array([[self.mu_y]]),
1113
+ self.mu_x, self.mu_y, self.sigma_x, self.sigma_y, self.rho,
1114
+ )[0, 0])
1115
+
1116
+ col = _with_opacity(cfg.contour_color, cfg.contour_opacity)
1117
+ angles = np.linspace(0, TAU, cfg.n_contour_pts, endpoint=False)
1118
+
1119
+ for level in cfg.contour_levels:
1120
+ # The bivariate normal contour at density level c is an ellipse
1121
+ # defined by (x-μ)ᵀ Σ⁻¹ (x-μ) = -2 ln(c / peak)
1122
+ # We parameterise using the Cholesky decomposition of Σ.
1123
+ if level <= 0 or level >= peak_pdf:
1124
+ continue
1125
+
1126
+ chi2_val = -2.0 * np.log(level / peak_pdf)
1127
+ if chi2_val <= 0:
1128
+ continue
1129
+ r = np.sqrt(chi2_val)
1130
+
1131
+ # Covariance matrix
1132
+ s1, s2, rho = self.sigma_x, self.sigma_y, self.rho
1133
+ cov = np.array([[s1**2, rho*s1*s2], [rho*s1*s2, s2**2]])
1134
+ try:
1135
+ L = np.linalg.cholesky(cov)
1136
+ except np.linalg.LinAlgError:
1137
+ continue
1138
+
1139
+ # Unit circle → ellipse via Cholesky
1140
+ circle = r * np.column_stack([np.cos(angles), np.sin(angles)])
1141
+ ellipse_xy = (L @ circle.T).T
1142
+
1143
+ pts3d = np.column_stack([
1144
+ ellipse_xy[:, 0] + self.mu_x,
1145
+ ellipse_xy[:, 1] + self.mu_y,
1146
+ np.zeros(len(angles)),
1147
+ ])
1148
+ # Close the ellipse
1149
+ pts3d = np.vstack([pts3d, pts3d[0]])
1150
+
1151
+ contour_mob = VMobject()
1152
+ contour_mob.set_points_as_corners(pts3d)
1153
+ contour_mob.set_stroke(color=col, width=cfg.contour_stroke_width)
1154
+ contour_mob.set_fill(opacity=0)
1155
+
1156
+ # Glow
1157
+ glow_mob = VMobject()
1158
+ glow_mob.set_points_as_corners(pts3d)
1159
+ glow_mob.set_stroke(
1160
+ color=_with_opacity(cfg.contour_color, cfg.contour_opacity * 0.20),
1161
+ width=cfg.contour_stroke_width * 2.5,
1162
+ )
1163
+ glow_mob.set_fill(opacity=0)
1164
+
1165
+ self.contour_group.add(glow_mob, contour_mob)
1166
+
1167
+ # ------------------------------------------------------------------
1168
+ # Axes
1169
+ # ------------------------------------------------------------------
1170
+
1171
+ def _build_axes(self) -> None:
1172
+ """Draw thin x and y axis lines in the z=0 base plane."""
1173
+ cfg = self.cfg
1174
+ ax_col = _with_opacity(WHITE, 0.28)
1175
+ sw = 0.8
1176
+ self.axes_group.add(Line(
1177
+ np.array([cfg.x_range[0], 0, 0]),
1178
+ np.array([cfg.x_range[1], 0, 0]),
1179
+ color=ax_col, stroke_width=sw,
1180
+ ))
1181
+ self.axes_group.add(Line(
1182
+ np.array([0, cfg.y_range[0], 0]),
1183
+ np.array([0, cfg.y_range[1], 0]),
1184
+ color=ax_col, stroke_width=sw,
1185
+ ))
1186
+
1187
+ # ------------------------------------------------------------------
1188
+ # Conditional slice
1189
+ # ------------------------------------------------------------------
1190
+
1191
+ def add_conditional_slice(
1192
+ self,
1193
+ x0: float,
1194
+ scene: Optional[ThreeDScene] = None,
1195
+ ) -> VGroup:
1196
+ """Show the conditional distribution f(Y | X = x0).
1197
+
1198
+ Draws a vertical 1D normal slice through the surface at x = x0,
1199
+ together with a shaded plane highlighting the slice.
1200
+
1201
+ Parameters
1202
+ ----------
1203
+ x0 : float
1204
+ The conditioning value of X.
1205
+
1206
+ Returns
1207
+ -------
1208
+ VGroup added to the scene but not to any layer group.
1209
+ """
1210
+ cfg = self.cfg
1211
+ # Conditional: Y | X=x0 ~ N(μ_Y|X, σ_Y|X²)
1212
+ mu_cond = self.mu_y + self.rho * (self.sigma_y / self.sigma_x) * (x0 - self.mu_x)
1213
+ sigma_cond = self.sigma_y * np.sqrt(1 - self.rho**2)
1214
+
1215
+ ys = np.linspace(cfg.y_range[0], cfg.y_range[1], 120)
1216
+ zs = _normal_pdf(ys, mu_cond, sigma_cond)
1217
+ z_max = float(zs.max())
1218
+ zs_sc = zs / z_max * cfg.z_scale * 0.95 if z_max > 0 else zs
1219
+
1220
+ pts = np.column_stack([np.full(len(ys), x0), ys, zs_sc])
1221
+ smoothed = _catmull_rom(pts, resolution=14)
1222
+
1223
+ col = _with_opacity(cfg.slice_color, 0.90)
1224
+ stroke = VMobject()
1225
+ stroke.set_points_as_corners(smoothed)
1226
+ stroke.set_stroke(color=col, width=2.4)
1227
+ stroke.set_fill(opacity=0)
1228
+
1229
+ glow = VMobject()
1230
+ glow.set_points_as_corners(smoothed)
1231
+ glow.set_stroke(color=_with_opacity(cfg.slice_color, 0.15), width=8.0)
1232
+ glow.set_fill(opacity=0)
1233
+
1234
+ # Shaded plane at x = x0
1235
+ plane_pts = [
1236
+ np.array([x0, cfg.y_range[0], 0]),
1237
+ np.array([x0, cfg.y_range[1], 0]),
1238
+ np.array([x0, cfg.y_range[1], cfg.z_scale]),
1239
+ np.array([x0, cfg.y_range[0], cfg.z_scale]),
1240
+ ]
1241
+ plane = Polygon(
1242
+ *plane_pts,
1243
+ fill_color=_with_opacity(cfg.slice_color, cfg.slice_opacity),
1244
+ fill_opacity=1.0, stroke_width=0,
1245
+ )
1246
+
1247
+ # Label
1248
+ lbl = Text(
1249
+ f"f(Y|X={x0:.2g})\n= N({mu_cond:.2g}, {sigma_cond:.2g})",
1250
+ font_size=16, color=cfg.slice_color,
1251
+ )
1252
+ lbl.move_to(np.array([x0, cfg.y_range[1] + 0.3, cfg.z_scale * 0.5]))
1253
+ if scene is not None:
1254
+ scene.add_fixed_orientation_mobjects(lbl)
1255
+
1256
+ grp = VGroup(plane, glow, stroke, lbl)
1257
+ return grp
1258
+
1259
+ # ------------------------------------------------------------------
1260
+ # Animations
1261
+ # ------------------------------------------------------------------
1262
+
1263
+ def animate_rise(
1264
+ self,
1265
+ run_time: float = 2.5,
1266
+ lag: float = 0.005,
1267
+ ) -> LaggedStart:
1268
+ """Animate the surface rising from z=0 upward.
1269
+
1270
+ Each quad starts at height 0 and grows to its final z-position.
1271
+ Quads are revealed in row-major order (front-to-back).
1272
+
1273
+ Parameters
1274
+ ----------
1275
+ run_time : float
1276
+ Total duration.
1277
+ lag : float
1278
+ Lag ratio between consecutive quads.
1279
+ """
1280
+ n_quads = len(self.surface_group)
1281
+ rt_per = run_time * 0.25
1282
+
1283
+ return LaggedStart(
1284
+ *[FadeIn(q, scale=0.1, run_time=rt_per)
1285
+ for q in self.surface_group],
1286
+ lag_ratio=lag,
1287
+ )
1288
+
1289
+ def animate_contours(
1290
+ self,
1291
+ lag: float = 0.25,
1292
+ run_time_per: float = 0.8,
1293
+ ) -> LaggedStart:
1294
+ """Draw contour ellipses one by one, innermost first."""
1295
+ return LaggedStart(
1296
+ *[Create(c, run_time=run_time_per) for c in self.contour_group],
1297
+ lag_ratio=lag,
1298
+ )
1299
+
1300
+ def animate_marginals(self, run_time: float = 0.9) -> AnimationGroup:
1301
+ """Create both marginal curves simultaneously."""
1302
+ anims = []
1303
+ if len(self.marginal_x) > 0:
1304
+ anims.append(Create(self.marginal_x, run_time=run_time))
1305
+ if len(self.marginal_y) > 0:
1306
+ anims.append(Create(self.marginal_y, run_time=run_time))
1307
+ return AnimationGroup(*anims)
1308
+
1309
+ def animate_correlation_sweep(
1310
+ self,
1311
+ scene: ThreeDScene,
1312
+ rho_values: Optional[List[float]] = None,
1313
+ run_time_each: float = 1.2,
1314
+ hold_each: float = 0.4,
1315
+ ) -> None:
1316
+ """Rebuild the surface for each value of ρ in *rho_values*.
1317
+
1318
+ Plays animations directly on *scene*.
1319
+
1320
+ Parameters
1321
+ ----------
1322
+ rho_values : list of float or None
1323
+ Defaults to [-0.8, -0.5, 0.0, +0.5, +0.8].
1324
+ """
1325
+ if rho_values is None:
1326
+ rho_values = [-0.8, -0.5, 0.0, 0.5, 0.8]
1327
+
1328
+ for rho_new in rho_values:
1329
+ # Build the new surface
1330
+ new_surface = BivariateNormal3D(
1331
+ mu_x=self.mu_x, mu_y=self.mu_y,
1332
+ sigma_x=self.sigma_x, sigma_y=self.sigma_y,
1333
+ rho=rho_new,
1334
+ config=self.cfg,
1335
+ )
1336
+
1337
+ # Crossfade old surface for new surface
1338
+ scene.play(
1339
+ FadeOut(self.surface_group, run_time=run_time_each * 0.4),
1340
+ FadeIn(new_surface.surface_group, run_time=run_time_each * 0.6),
1341
+ run_time=run_time_each,
1342
+ )
1343
+ # Update contours
1344
+ scene.play(
1345
+ FadeOut(self.contour_group, run_time=0.3),
1346
+ FadeIn(new_surface.contour_group, run_time=0.5),
1347
+ )
1348
+
1349
+ # Adopt new objects into self
1350
+ self.remove(self.surface_group, self.contour_group)
1351
+ self.surface_group = new_surface.surface_group
1352
+ self.contour_group = new_surface.contour_group
1353
+ self.add(self.surface_group, self.contour_group)
1354
+ self.rho = rho_new
1355
+
1356
+ scene.wait(hold_each)
1357
+
1358
+ def full_reveal(self, scene: ThreeDScene) -> None:
1359
+ """Play the complete layered reveal."""
1360
+ scene.play(self.animate_rise(run_time=2.2))
1361
+ scene.play(self.animate_marginals(run_time=0.9))
1362
+ scene.play(self.animate_contours(lag=0.20, run_time_per=0.75))
1363
+
1364
+
1365
+ # ===========================================================================
1366
+ # NormalApproximation3D
1367
+ # ===========================================================================
1368
+
1369
+ class NormalApproximation3D(VGroup):
1370
+ """Binomial(n, p) PMF bars with the Normal approximation curve overlaid.
1371
+
1372
+ As n grows the normal curve (with mean np and std √(np(1-p))) becomes
1373
+ an increasingly accurate envelope over the discrete bars.
1374
+
1375
+ Parameters
1376
+ ----------
1377
+ n : int
1378
+ Number of trials.
1379
+ p : float
1380
+ Success probability.
1381
+ config_bar_color : ManimColor
1382
+ Bar colour.
1383
+ config_curve_color : ManimColor
1384
+ Normal approximation curve colour.
1385
+ x_start : float
1386
+ Left edge of the bar chart.
1387
+ bar_spacing : float
1388
+ z_scale : float
1389
+ scene : ThreeDScene or None
1390
+
1391
+ Attributes
1392
+ ----------
1393
+ bars : VGroup
1394
+ All bar prisms.
1395
+ approx_curve : VMobject
1396
+ The normal approximation stroke.
1397
+ """
1398
+
1399
+ def __init__(
1400
+ self,
1401
+ n: int = 20,
1402
+ p: float = 0.4,
1403
+ bar_color: ManimColor = ManimColor("#4A90D9"),
1404
+ curve_color: ManimColor = ManimColor("#E8593C"),
1405
+ x_start: float = 0.0,
1406
+ bar_spacing: float = 0.0,
1407
+ z_scale: float = 4.0,
1408
+ y_pos: float = 0.0,
1409
+ floor_z: float = 0.0,
1410
+ scene: Optional[ThreeDScene] = None,
1411
+ **kwargs,
1412
+ ):
1413
+ super().__init__(**kwargs)
1414
+
1415
+ self.n = n
1416
+ self.p = p
1417
+ self.bar_color = bar_color
1418
+ self.curve_color = curve_color
1419
+ self.z_scale = z_scale
1420
+ self.y_pos = y_pos
1421
+ self.floor_z = floor_z
1422
+ self._scene = scene
1423
+
1424
+ # Parameters
1425
+ mu_norm = n * p
1426
+ sigma_norm = np.sqrt(n * p * (1 - p))
1427
+
1428
+ # Spacing
1429
+ sp = bar_spacing if bar_spacing > 0 else max(0.45, min(0.90, 6.0 / (n + 1)))
1430
+ self._spacing = sp
1431
+ total_w = n * sp
1432
+ x0 = x_start - total_w / 2
1433
+
1434
+ # Compute PMF using log-gamma (self-contained)
1435
+ import math as _math
1436
+
1437
+ def _lgamma(x):
1438
+ g = 7
1439
+ c = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
1440
+ 771.32342877765313, -176.61502916214059, 12.507343278686905,
1441
+ -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
1442
+ if x < 0.5:
1443
+ return _math.log(PI / _math.sin(PI * x)) - _lgamma(1 - x)
1444
+ x -= 1
1445
+ a = c[0]
1446
+ t = x + g + 0.5
1447
+ for i in range(1, g + 2):
1448
+ a += c[i] / (x + i)
1449
+ return 0.5 * _math.log(TAU) + (x + 0.5) * _math.log(t) - t + _math.log(a)
1450
+
1451
+ def _binom_pmf(k):
1452
+ if k < 0 or k > n or p <= 0 or p >= 1:
1453
+ return 0.0
1454
+ lp = (_lgamma(n+1) - _lgamma(k+1) - _lgamma(n-k+1)
1455
+ + k*_math.log(p) + (n-k)*_math.log(1-p))
1456
+ return _math.exp(lp)
1457
+
1458
+ ks = list(range(n + 1))
1459
+ ps_arr = np.array([_binom_pmf(k) for k in ks])
1460
+ ps_scaled = ps_arr * z_scale
1461
+
1462
+ bar_w = sp * 0.80
1463
+ hd = 0.30
1464
+ col_r = _darken(bar_color, 0.62)
1465
+ col_t = _lighten(bar_color, 1.30)
1466
+
1467
+ self.bars = VGroup()
1468
+ self._bar_xs = []
1469
+
1470
+ for i, (k, h) in enumerate(zip(ks, ps_scaled)):
1471
+ x = x0 + i * sp
1472
+ self._bar_xs.append(x)
1473
+ hw = bar_w / 2
1474
+ z0_bar, z1 = floor_z, floor_z + max(h, 1e-4)
1475
+
1476
+ ff = Polygon(
1477
+ np.array([x-hw,y_pos-hd,z0_bar]),
1478
+ np.array([x+hw,y_pos-hd,z0_bar]),
1479
+ np.array([x+hw,y_pos-hd,z1]),
1480
+ np.array([x-hw,y_pos-hd,z1]),
1481
+ fill_color=_with_opacity(bar_color, 0.88),
1482
+ fill_opacity=1.0, stroke_width=0,
1483
+ )
1484
+ fr = Polygon(
1485
+ np.array([x+hw,y_pos-hd,z0_bar]),
1486
+ np.array([x+hw,y_pos+hd,z0_bar]),
1487
+ np.array([x+hw,y_pos+hd,z1]),
1488
+ np.array([x+hw,y_pos-hd,z1]),
1489
+ fill_color=_with_opacity(col_r, 0.85),
1490
+ fill_opacity=1.0, stroke_width=0,
1491
+ )
1492
+ ft = Polygon(
1493
+ np.array([x-hw,y_pos-hd,z1]),
1494
+ np.array([x+hw,y_pos-hd,z1]),
1495
+ np.array([x+hw,y_pos+hd,z1]),
1496
+ np.array([x-hw,y_pos+hd,z1]),
1497
+ fill_color=_with_opacity(col_t, 0.80),
1498
+ fill_opacity=1.0, stroke_width=0,
1499
+ )
1500
+ self.bars.add(VGroup(ff, fr, ft))
1501
+
1502
+ # Normal approximation curve
1503
+ x_cont = np.linspace(x0 - sp, x0 + n * sp + sp, 300)
1504
+ # Map scene x back to k-values
1505
+ k_cont = (x_cont - x0) / sp
1506
+ ys_norm = _normal_pdf(k_cont, mu_norm, sigma_norm)
1507
+ ys_norm_scaled = ys_norm * z_scale
1508
+
1509
+ pts_norm = np.column_stack([x_cont, np.full(len(x_cont), y_pos), ys_norm_scaled])
1510
+ smoothed_norm = _catmull_rom(pts_norm, resolution=14)
1511
+
1512
+ col_c = _with_opacity(curve_color, 0.90)
1513
+ self.approx_curve = VMobject()
1514
+ self.approx_curve.set_points_as_corners(smoothed_norm)
1515
+ self.approx_curve.set_stroke(color=col_c, width=2.8)
1516
+ self.approx_curve.set_fill(opacity=0)
1517
+
1518
+ self.approx_glow = VMobject()
1519
+ self.approx_glow.set_points_as_corners(smoothed_norm)
1520
+ self.approx_glow.set_stroke(color=_with_opacity(curve_color, 0.13), width=9.0)
1521
+ self.approx_glow.set_fill(opacity=0)
1522
+
1523
+ self.add(self.bars, self.approx_glow, self.approx_curve)
1524
+
1525
+ # ------------------------------------------------------------------
1526
+
1527
+ def animate_bars(self, lag: float = 0.03, run_time_per: float = 0.45) -> LaggedStart:
1528
+ def grow_bar(bar, run_time):
1529
+ ff, fr, ft = bar[0], bar[1], bar[2]
1530
+ pts = ff.get_all_points()
1531
+ z_top = float(pts[:, 2].max()) if len(pts) > 0 else 0.01
1532
+ z0 = self.floor_z
1533
+
1534
+ def updater(mob, alpha):
1535
+ h = max(smooth(alpha) * z_top, 1e-4)
1536
+ z1 = z0 + h
1537
+ for face, face_pts in [
1538
+ (mob[0], [[mob[0].get_all_points()[0,0]-0.001,
1539
+ self.y_pos-0.30, z0],
1540
+ [mob[0].get_all_points()[1,0]+0.001,
1541
+ self.y_pos-0.30, z0],
1542
+ [mob[0].get_all_points()[1,0]+0.001,
1543
+ self.y_pos-0.30, z1],
1544
+ [mob[0].get_all_points()[0,0]-0.001,
1545
+ self.y_pos-0.30, z1],
1546
+ [mob[0].get_all_points()[0,0]-0.001,
1547
+ self.y_pos-0.30, z0]]),
1548
+ ]:
1549
+ pass # simplified — bars appear via FadeIn
1550
+ mob.set_opacity(smooth(alpha))
1551
+
1552
+ return UpdateFromAlphaFunc(bar, updater, run_time=run_time)
1553
+
1554
+ return LaggedStart(
1555
+ *[FadeIn(b, run_time=run_time_per) for b in self.bars],
1556
+ lag_ratio=lag,
1557
+ )
1558
+
1559
+ def animate_curve(self, run_time: float = 1.2) -> AnimationGroup:
1560
+ return AnimationGroup(
1561
+ FadeIn(self.approx_glow, run_time=run_time * 0.3),
1562
+ Create(self.approx_curve, run_time=run_time),
1563
+ lag_ratio=0.0,
1564
+ )
1565
+
1566
+ def full_reveal(self, scene: ThreeDScene) -> None:
1567
+ scene.play(self.animate_bars(run_time_per=0.40))
1568
+ scene.play(self.animate_curve(run_time=1.0))
1569
+
1570
+
1571
+ # ===========================================================================
1572
+ # QQPlot3D
1573
+ # ===========================================================================
1574
+
1575
+ class QQPlot3D(VGroup):
1576
+ """Quantile-quantile plot of sample data against a Normal reference.
1577
+
1578
+ Each data point is a ``Dot3D`` at (theoretical quantile, sample quantile).
1579
+ The reference line y = x is drawn in gold.
1580
+ An optional 95% envelope is drawn around the reference line.
1581
+
1582
+ Parameters
1583
+ ----------
1584
+ data : np.ndarray
1585
+ Sample data (1-D).
1586
+ mu : float or None
1587
+ Reference Normal mean. If None, uses sample mean.
1588
+ sigma : float or None
1589
+ Reference Normal std. If None, uses sample std.
1590
+ x_scale : float
1591
+ Scene x-units per quantile unit.
1592
+ z_scale : float
1593
+ Scene z-units per quantile unit.
1594
+ dot_color : ManimColor
1595
+ line_color : ManimColor
1596
+ scene : ThreeDScene or None
1597
+
1598
+ Attributes
1599
+ ----------
1600
+ dots : VGroup
1601
+ ref_line : VMobject
1602
+ envelope : VGroup
1603
+ """
1604
+
1605
+ def __init__(
1606
+ self,
1607
+ data: np.ndarray,
1608
+ mu: Optional[float] = None,
1609
+ sigma: Optional[float] = None,
1610
+ x_scale: float = 1.0,
1611
+ z_scale: float = 1.0,
1612
+ y_pos: float = 0.0,
1613
+ dot_color: ManimColor = ManimColor("#4A90D9"),
1614
+ line_color: ManimColor = ManimColor("#E0AA40"),
1615
+ envelope_color: ManimColor = ManimColor("#E0AA40"),
1616
+ scene: Optional[ThreeDScene] = None,
1617
+ **kwargs,
1618
+ ):
1619
+ super().__init__(**kwargs)
1620
+
1621
+ arr = np.sort(np.asarray(data, dtype=float))
1622
+ n = len(arr)
1623
+ mu_ref = float(mu) if mu is not None else float(arr.mean())
1624
+ sigma_ref = float(sigma) if sigma is not None else float(arr.std(ddof=1))
1625
+
1626
+ # Theoretical quantiles via Blom's formula
1627
+ # p_i = (i - 0.375) / (n + 0.25)
1628
+ probs = (np.arange(1, n + 1) - 0.375) / (n + 0.25)
1629
+
1630
+ # Normal PPF via bisection (self-contained)
1631
+ def ppf_norm(p, mu, sigma):
1632
+ lo, hi = mu - 6 * sigma, mu + 6 * sigma
1633
+ for _ in range(60):
1634
+ mid = (lo + hi) / 2
1635
+ if _normal_cdf(mid, mu, sigma) < p:
1636
+ lo = mid
1637
+ else:
1638
+ hi = mid
1639
+ return (lo + hi) / 2
1640
+
1641
+ theor_q = np.array([ppf_norm(p, mu_ref, sigma_ref) for p in probs])
1642
+ sample_q = arr
1643
+
1644
+ # Scale to scene units
1645
+ theor_sc = theor_q * x_scale
1646
+ sample_sc = sample_q * z_scale
1647
+
1648
+ self.dots = VGroup()
1649
+ for tq, sq in zip(theor_sc, sample_sc):
1650
+ d = Dot3D(
1651
+ point=np.array([tq, y_pos, sq]),
1652
+ radius=0.07,
1653
+ color=_with_opacity(dot_color, 0.82),
1654
+ )
1655
+ self.dots.add(d)
1656
+
1657
+ # Reference line: theoretical == sample
1658
+ q_min = float(min(theor_sc.min(), sample_sc.min()))
1659
+ q_max = float(max(theor_sc.max(), sample_sc.max()))
1660
+ self.ref_line = Line(
1661
+ np.array([q_min, y_pos, q_min]),
1662
+ np.array([q_max, y_pos, q_max]),
1663
+ color=_with_opacity(line_color, 0.85),
1664
+ stroke_width=2.2,
1665
+ )
1666
+
1667
+ # 95% confidence envelope (approximate: ±1.36/√n)
1668
+ env_hw = 1.36 / np.sqrt(max(n, 1)) * z_scale
1669
+ env_pts_lo = [np.array([tq, y_pos, tq - env_hw]) for tq in theor_sc]
1670
+ env_pts_hi = [np.array([tq, y_pos, tq + env_hw]) for tq in theor_sc]
1671
+
1672
+ self.envelope = VGroup()
1673
+ env_lo_mob = VMobject()
1674
+ env_lo_mob.set_points_as_corners(env_pts_lo)
1675
+ env_lo_mob.set_stroke(
1676
+ color=_with_opacity(envelope_color, 0.35), width=1.2
1677
+ )
1678
+ env_lo_mob.set_fill(opacity=0)
1679
+
1680
+ env_hi_mob = VMobject()
1681
+ env_hi_mob.set_points_as_corners(env_pts_hi)
1682
+ env_hi_mob.set_stroke(
1683
+ color=_with_opacity(envelope_color, 0.35), width=1.2
1684
+ )
1685
+ env_hi_mob.set_fill(opacity=0)
1686
+
1687
+ # Fill between envelopes
1688
+ env_fill_pts = env_pts_hi + list(reversed(env_pts_lo))
1689
+ env_fill = Polygon(
1690
+ *env_fill_pts,
1691
+ fill_color=_with_opacity(envelope_color, 0.07),
1692
+ fill_opacity=1.0, stroke_width=0,
1693
+ )
1694
+ self.envelope.add(env_fill, env_lo_mob, env_hi_mob)
1695
+
1696
+ # Axis labels
1697
+ xlab = Text("Theoretical Quantiles", font_size=16, color=_with_opacity(WHITE, 0.50))
1698
+ xlab.move_to(np.array([0, y_pos, q_min - 0.45]))
1699
+ zlab = Text("Sample Quantiles", font_size=16, color=_with_opacity(WHITE, 0.50))
1700
+ zlab.move_to(np.array([q_min - 0.5, y_pos, 0]))
1701
+ if scene is not None:
1702
+ scene.add_fixed_orientation_mobjects(xlab, zlab)
1703
+
1704
+ self.add(self.envelope, self.ref_line, self.dots, xlab, zlab)
1705
+
1706
+ # ------------------------------------------------------------------
1707
+
1708
+ def animate_reveal(
1709
+ self,
1710
+ lag: float = 0.02,
1711
+ run_time_per: float = 0.18,
1712
+ ) -> AnimationGroup:
1713
+ return AnimationGroup(
1714
+ Create(self.ref_line, run_time=0.8),
1715
+ FadeIn(self.envelope, run_time=0.6),
1716
+ LaggedStart(
1717
+ *[FadeIn(d, scale=0.3, run_time=run_time_per) for d in self.dots],
1718
+ lag_ratio=lag,
1719
+ ),
1720
+ lag_ratio=0.2,
1721
+ )
1722
+
1723
+
1724
+ # ===========================================================================
1725
+ # Ready-to-render ThreeDScene subclasses
1726
+ # ===========================================================================
1727
+
1728
+ class NormalCurveScene(ThreeDScene):
1729
+ """N(0,1) bell curve with 68-95-99.7 rule and z-score ruler.
1730
+
1731
+ Render: manim -pql normal3d.py NormalCurveScene
1732
+ """
1733
+
1734
+ def construct(self):
1735
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1736
+ self.begin_ambient_camera_rotation(rate=0.025)
1737
+
1738
+ bell = NormalCurve3D(mu=0, sigma=1, z_scale=3.8, scene=self)
1739
+ self.add(bell)
1740
+
1741
+ bell.full_reveal(self)
1742
+
1743
+ bell.add_zscore_ruler(scene=self)
1744
+ self.play(FadeIn(bell.zscore_group, run_time=0.6))
1745
+ self.wait(0.4)
1746
+
1747
+ bell.add_title(scene=self)
1748
+ self.play(FadeIn(bell.title_group, run_time=0.5))
1749
+ self.wait(0.4)
1750
+
1751
+ self.play(bell.animate_rule_68_95_99(scene=self, sequential=True))
1752
+ self.wait(2)
1753
+
1754
+
1755
+ class BivariateNormalScene(ThreeDScene):
1756
+ """Bivariate N((0,0), Σ) surface with marginals, contours, and a slice.
1757
+
1758
+ Render: manim -pql normal3d.py BivariateNormalScene
1759
+ """
1760
+
1761
+ def construct(self):
1762
+ self.set_camera_orientation(phi=68 * DEGREES, theta=-50 * DEGREES)
1763
+ self.begin_ambient_camera_rotation(rate=0.03)
1764
+
1765
+ surf = BivariateNormal3D(
1766
+ mu_x=0, mu_y=0, sigma_x=1.2, sigma_y=0.9, rho=0.45,
1767
+ config=CRISP_SURFACE, scene=self,
1768
+ )
1769
+ self.add(surf)
1770
+ surf.full_reveal(self)
1771
+ self.wait(0.5)
1772
+
1773
+ # Conditional slice at x = 1.0
1774
+ slice_grp = surf.add_conditional_slice(x0=1.0, scene=self)
1775
+ self.add(slice_grp)
1776
+ self.play(FadeIn(slice_grp, run_time=0.8))
1777
+ self.wait(2)
1778
+
1779
+
1780
+ class StandardisationScene(ThreeDScene):
1781
+ """Animate N(2, 1.5) → N(0, 1) standardisation.
1782
+
1783
+ Render: manim -pql normal3d.py StandardisationScene
1784
+ """
1785
+
1786
+ def construct(self):
1787
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
1788
+
1789
+ bell = NormalCurve3D(mu=2.0, sigma=1.5, z_scale=3.5, scene=self)
1790
+ self.add(bell)
1791
+ bell.full_reveal(self)
1792
+
1793
+ lbl_before = Text("N(μ=2, σ=1.5)", font_size=22, color=ManimColor("#4A90D9"))
1794
+ lbl_before.move_to(np.array([2.0, 0, 4.1]))
1795
+ self.add_fixed_orientation_mobjects(lbl_before)
1796
+ self.add(lbl_before)
1797
+ self.play(FadeIn(lbl_before, run_time=0.4))
1798
+ self.wait(0.5)
1799
+
1800
+ self.play(
1801
+ bell.animate_standardise(run_time=2.0, scene=self),
1802
+ FadeOut(lbl_before, run_time=0.5),
1803
+ )
1804
+
1805
+ lbl_after = Text("N(0, 1)", font_size=22, color=ManimColor("#E0AA40"))
1806
+ lbl_after.move_to(np.array([0.0, 0, 4.1]))
1807
+ self.add_fixed_orientation_mobjects(lbl_after)
1808
+ self.add(lbl_after)
1809
+ self.play(FadeIn(lbl_after, run_time=0.4))
1810
+ self.wait(2)
1811
+
1812
+
1813
+ class NormalApproximationScene(ThreeDScene):
1814
+ """Binomial(n, 0.35) with Normal approximation; n sweeps 10 → 50.
1815
+
1816
+ Render: manim -pql normal3d.py NormalApproximationScene
1817
+ """
1818
+
1819
+ def construct(self):
1820
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-52 * DEGREES)
1821
+ self.begin_ambient_camera_rotation(rate=0.022)
1822
+
1823
+ approx = NormalApproximation3D(
1824
+ n=10, p=0.35,
1825
+ bar_color=ManimColor("#4A90D9"),
1826
+ curve_color=ManimColor("#E8593C"),
1827
+ z_scale=4.0,
1828
+ scene=self,
1829
+ )
1830
+ self.add(approx)
1831
+ approx.full_reveal(self)
1832
+ self.wait(0.5)
1833
+
1834
+ for n_new in [20, 35, 50]:
1835
+ new_approx = NormalApproximation3D(
1836
+ n=n_new, p=0.35,
1837
+ bar_color=ManimColor("#4A90D9"),
1838
+ curve_color=ManimColor("#E8593C"),
1839
+ z_scale=4.0,
1840
+ scene=self,
1841
+ )
1842
+ self.play(
1843
+ FadeOut(approx, run_time=0.5),
1844
+ FadeIn(new_approx, run_time=0.5),
1845
+ )
1846
+ self.remove(approx)
1847
+ approx = new_approx
1848
+ self.wait(0.6)
1849
+
1850
+ self.wait(2)
1851
+
1852
+
1853
+ class QQPlotScene(ThreeDScene):
1854
+ """Q-Q plot: heavy-tailed vs Normal — shows deviation in tails.
1855
+
1856
+ Render: manim -pql normal3d.py QQPlotScene
1857
+ """
1858
+
1859
+ def construct(self):
1860
+ self.set_camera_orientation(phi=65 * DEGREES, theta=-48 * DEGREES)
1861
+ self.begin_ambient_camera_rotation(rate=0.025)
1862
+
1863
+ rng = np.random.default_rng(42)
1864
+ # Mix of Normal + heavy-tailed noise
1865
+ data = np.concatenate([
1866
+ rng.normal(0, 1, 80),
1867
+ rng.standard_cauchy(20) * 0.3,
1868
+ ])
1869
+
1870
+ qq = QQPlot3D(
1871
+ data=data, mu=0.0, sigma=1.0,
1872
+ x_scale=1.0, z_scale=1.0,
1873
+ scene=self,
1874
+ )
1875
+ self.add(qq)
1876
+ self.play(qq.animate_reveal(lag=0.015, run_time_per=0.15))
1877
+ self.wait(2)