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,1693 @@
1
+ """
2
+ statanim/inference/confidence_interval.py
3
+ ============================================
4
+ ConfidenceInterval3D — Highly detailed, statistically rich confidence
5
+ interval visualisation for Manim statistics animations.
6
+
7
+ Primary use cases
8
+ -----------------
9
+ Frequentist CI interpretation — repeated sampling coverage demos
10
+ Z-interval / t-interval — known vs unknown σ
11
+ CLT demonstration — how CI width shrinks with n
12
+ Capture probability — does the CI contain the true parameter?
13
+ Comparison of confidence levels — 90 / 95 / 99% side-by-side
14
+
15
+ Design goals
16
+ ------------
17
+ Single CI object
18
+ * Rounded gradient bar — thick central bar with a bright centre
19
+ fading to darker ends (probability mass
20
+ feels denser near the point estimate).
21
+ * End-cap brackets — real ruler-bracket style: vertical serif
22
+ with a tiny inward tick, not plain lines.
23
+ * Uncertainty fog — semi-transparent tapered "halo" region
24
+ extending slightly beyond each end cap,
25
+ visualising that the boundary is not a
26
+ hard cliff.
27
+ * Center estimate marker — multi-layer: outer ring → filled disc →
28
+ specular dot. Two styles: round (x̄) and
29
+ diamond (μ̂).
30
+ * True-parameter line — optional dashed vertical line for μ₀,
31
+ coloured green/red based on capture.
32
+ * Capture flash region — when the CI captures the true value a
33
+ subtle filled region between bar and axis
34
+ pulses green; red otherwise.
35
+ * Floating badge — "95% CI" text badge with leader line and
36
+ a small rounded rect background.
37
+ * Number line — clean axis with tick marks, labels, and
38
+ an arrow tip; the CI sits on this line.
39
+
40
+ CIStack
41
+ * Vertical stack of N intervals — each row is one CI from a repeated
42
+ sample. Green = captures μ, red = misses.
43
+ * Coverage counter — live "k / N captured (p%)" text badge
44
+ that updates as CIs are added.
45
+ * True-parameter column — vertical dashed line running the full
46
+ height of the stack.
47
+
48
+ Animations
49
+ ----------
50
+ BuildCI — bar grows symmetrically from point estimate outward,
51
+ end caps materialise, badge fades in.
52
+ RevealCapture — true-param line drops from above, interval flashes
53
+ green (captured) or red (missed), badge updates.
54
+ SweepCI — CI slides horizontally along the number line,
55
+ showing how a different sample shifts the interval.
56
+ NarrowCI — CI shrinks from current width to a new (narrower)
57
+ width; models increasing n or lowering α.
58
+ StackCIs — animate N CIs dropping onto the stack one by one,
59
+ counter incrementing, coverage proportion converging.
60
+
61
+ Dependencies
62
+ ------------
63
+ manim (CE or GL), numpy, scipy (optional — for t-distribution quantiles)
64
+
65
+ Usage
66
+ -----
67
+ from statanim.inference.confidence_interval import (
68
+ ConfidenceInterval3D, CIStack, BuildCI, RevealCapture, StackCIs
69
+ )
70
+
71
+ class CoverageDemo(ThreeDScene):
72
+ def construct(self):
73
+ ax = NumberLine(x_range=[60, 100, 5])
74
+ ci = ConfidenceInterval3D(
75
+ center=80.0, half_width=6.0,
76
+ true_param=82.0,
77
+ confidence=0.95,
78
+ axis=ax,
79
+ )
80
+ self.play(BuildCI(ci))
81
+ self.play(RevealCapture(ci))
82
+ """
83
+
84
+ from __future__ import annotations
85
+
86
+ import numpy as np
87
+ from typing import Optional, Sequence, Literal, List, Tuple
88
+
89
+ from manim import (
90
+ VGroup,
91
+ Rectangle, RoundedRectangle, Circle, Annulus, Dot,
92
+ Line, DashedLine, Arrow, DoubleArrow,
93
+ Polygon, Arc,
94
+ Text, MathTex, Tex,
95
+ NumberLine,
96
+ Animation, Succession, AnimationGroup,
97
+ ApplyMethod, FadeIn, FadeOut, GrowFromCenter,
98
+ Flash, Indicate,
99
+ Rotate,
100
+ Create, Write, Uncreate,
101
+ always_redraw,
102
+ interpolate_color,
103
+ color_to_rgb,
104
+ WHITE, BLACK,
105
+ GREY, GREY_A, GREY_B, GREY_C, GREY_D, LIGHT_GREY,
106
+ RED, RED_A, RED_B, RED_C, RED_D, RED_E,
107
+ GREEN, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
108
+ BLUE, BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E,
109
+ YELLOW, YELLOW_A, YELLOW_B, YELLOW_E,
110
+ ORANGE, TEAL, TEAL_A, TEAL_B, TEAL_C,
111
+ GOLD, GOLD_A, GOLD_B, GOLD_C, GOLD_D,
112
+ MAROON, PURPLE_A,
113
+ UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
114
+ PI, TAU,
115
+ rate_functions,
116
+ ManimColor,
117
+ ValueTracker,
118
+ )
119
+
120
+ # ──────────────────────────────────────────────────────────────────────────────
121
+ # Colour themes
122
+ # ──────────────────────────────────────────────────────────────────────────────
123
+
124
+ CI_THEMES: dict[str, dict] = {
125
+ # Classic blue interval — neutral / unknown capture status
126
+ "blue": {
127
+ "bar_center": "#4A90D9",
128
+ "bar_edge": "#1B4F8A",
129
+ "fog": "#90C8F8",
130
+ "cap": "#1B4F8A",
131
+ "cap_tick": "#4A90D9",
132
+ "marker_outer": "#1B4F8A",
133
+ "marker_inner": "#4A90D9",
134
+ "marker_spec": "#A8D4F8",
135
+ "badge_bg": "#1B4F8A",
136
+ "badge_fg": WHITE,
137
+ "axis": GREY_B,
138
+ "axis_label": GREY_A,
139
+ },
140
+ # Green — CI captures the true parameter
141
+ "captured": {
142
+ "bar_center": "#2A9D6A",
143
+ "bar_edge": "#155E3E",
144
+ "fog": "#80DBA8",
145
+ "cap": "#155E3E",
146
+ "cap_tick": "#2A9D6A",
147
+ "marker_outer": "#155E3E",
148
+ "marker_inner": "#2A9D6A",
149
+ "marker_spec": "#A8ECC8",
150
+ "badge_bg": "#155E3E",
151
+ "badge_fg": WHITE,
152
+ "axis": GREY_B,
153
+ "axis_label": GREY_A,
154
+ },
155
+ # Red — CI misses the true parameter
156
+ "missed": {
157
+ "bar_center": "#D94A4A",
158
+ "bar_edge": "#8A1B1B",
159
+ "fog": "#F8A0A0",
160
+ "cap": "#8A1B1B",
161
+ "cap_tick": "#D94A4A",
162
+ "marker_outer": "#8A1B1B",
163
+ "marker_inner": "#D94A4A",
164
+ "marker_spec": "#F8C8C8",
165
+ "badge_bg": "#8A1B1B",
166
+ "badge_fg": WHITE,
167
+ "axis": GREY_B,
168
+ "axis_label": GREY_A,
169
+ },
170
+ # Gold — for population parameter / prior highlight
171
+ "gold": {
172
+ "bar_center": "#D4AF37",
173
+ "bar_edge": "#8B6914",
174
+ "fog": "#F8E090",
175
+ "cap": "#8B6914",
176
+ "cap_tick": "#D4AF37",
177
+ "marker_outer": "#8B6914",
178
+ "marker_inner": "#D4AF37",
179
+ "marker_spec": "#FFF0A0",
180
+ "badge_bg": "#8B6914",
181
+ "badge_fg": WHITE,
182
+ "axis": GREY_B,
183
+ "axis_label": GREY_A,
184
+ },
185
+ # Dark mode
186
+ "dark": {
187
+ "bar_center": "#6A6AFF",
188
+ "bar_edge": "#2A2A80",
189
+ "fog": "#9090FF",
190
+ "cap": "#2A2A80",
191
+ "cap_tick": "#6A6AFF",
192
+ "marker_outer": "#2A2A80",
193
+ "marker_inner": "#6A6AFF",
194
+ "marker_spec": "#C0C0FF",
195
+ "badge_bg": "#1A1A50",
196
+ "badge_fg": WHITE,
197
+ "axis": GREY_C,
198
+ "axis_label": GREY_B,
199
+ },
200
+ }
201
+
202
+ TRUE_PARAM_COLORS = {
203
+ "unknown": "#D4AF37", # gold — not yet revealed
204
+ "captured": "#2A9D6A", # green — CI contains it
205
+ "missed": "#D94A4A", # red — CI misses it
206
+ }
207
+
208
+ # ──────────────────────────────────────────────────────────────────────────────
209
+ # Statistical helpers
210
+ # ──────────────────────────────────────────────────────────────────────────────
211
+
212
+ def _z_half_width(
213
+ std_err: float,
214
+ confidence: float = 0.95,
215
+ ) -> float:
216
+ """Half-width of a Z-interval: z* · SE."""
217
+ try:
218
+ from scipy.stats import norm
219
+ z_star = norm.ppf((1 + confidence) / 2)
220
+ except ImportError:
221
+ # Fallback table for common levels
222
+ _table = {0.80: 1.282, 0.90: 1.645, 0.95: 1.960,
223
+ 0.99: 2.576, 0.999: 3.291}
224
+ z_star = _table.get(round(confidence, 3), 1.960)
225
+ return z_star * std_err
226
+
227
+
228
+ def _t_half_width(
229
+ std_err: float,
230
+ df: int,
231
+ confidence: float = 0.95,
232
+ ) -> float:
233
+ """Half-width of a t-interval: t*(df) · SE."""
234
+ try:
235
+ from scipy.stats import t as t_dist
236
+ t_star = t_dist.ppf((1 + confidence) / 2, df=df)
237
+ except ImportError:
238
+ t_star = _z_half_width(1.0, confidence) * (1 + 1.0 / df)
239
+ return t_star * std_err
240
+
241
+
242
+ def _captures(lower: float, upper: float, true_param: float) -> bool:
243
+ return lower <= true_param <= upper
244
+
245
+
246
+ # ──────────────────────────────────────────────────────────────────────────────
247
+ # Sub-components
248
+ # ──────────────────────────────────────────────────────────────────────────────
249
+
250
+ class _CIBar(VGroup):
251
+ """
252
+ The main horizontal interval bar.
253
+
254
+ Layers (back → front):
255
+ 1. fog_left / fog_right — tapered semi-transparent halo extending
256
+ beyond each end cap
257
+ 2. bar_base — solid rounded rectangle, edge colour
258
+ 3. bar_center_highlight — brighter inner rectangle fading at ends
259
+ (gradient approximation)
260
+ 4. center_line — thin bright centre stripe (lit surface)
261
+
262
+ Parameters
263
+ ----------
264
+ half_width : float — CI half-width in axis units
265
+ bar_height : float — visual bar thickness
266
+ unit_scale : float — pixels (Manim units) per axis unit
267
+ theme : dict
268
+ y : float — vertical position
269
+ """
270
+
271
+ def __init__(
272
+ self,
273
+ half_width: float,
274
+ bar_height: float,
275
+ unit_scale: float,
276
+ theme: dict,
277
+ y: float = 0.0,
278
+ **kwargs,
279
+ ):
280
+ super().__init__(**kwargs)
281
+ self._hw = half_width
282
+ self._bh = bar_height
283
+ self._us = unit_scale
284
+ self._theme = theme
285
+ self._y = y
286
+
287
+ w_px = 2 * half_width * unit_scale # bar width in Manim units
288
+ fog_w = w_px * 0.12 # fog extends 12% beyond each end
289
+
290
+ # ── 1. Fog halos ──────────────────────────────────────────────
291
+ for sign in [-1, 1]:
292
+ fog = self._make_fog(
293
+ cx=sign * (w_px / 2 + fog_w * 0.45),
294
+ fog_w=fog_w,
295
+ bar_h=bar_height,
296
+ color=theme["fog"],
297
+ )
298
+ fog.move_to([sign * (w_px / 2 + fog_w * 0.45), y, -0.001])
299
+ self.add(fog)
300
+
301
+ # ── 2. Bar base ───────────────────────────────────────────────
302
+ bar = RoundedRectangle(
303
+ width=w_px,
304
+ height=bar_height,
305
+ corner_radius=bar_height * 0.40,
306
+ fill_color=theme["bar_edge"],
307
+ fill_opacity=1.0,
308
+ stroke_width=0,
309
+ )
310
+ bar.move_to([0, y, 0])
311
+ self.add(bar)
312
+
313
+ # ── 3. Center highlight (gradient approx: 4 overlapping rects) ──
314
+ n_layers = 5
315
+ for i in range(n_layers):
316
+ frac = i / (n_layers - 1) # 0 = edge, 1 = centre
317
+ w_layer = w_px * (0.30 + 0.70 * frac)
318
+ alpha_val = 0.08 + 0.32 * frac
319
+ hl = RoundedRectangle(
320
+ width=w_layer,
321
+ height=bar_height * (0.55 + 0.35 * frac),
322
+ corner_radius=bar_height * 0.30,
323
+ fill_color=theme["bar_center"],
324
+ fill_opacity=alpha_val,
325
+ stroke_width=0,
326
+ )
327
+ hl.move_to([0, y, 0.001 + i * 0.0005])
328
+ self.add(hl)
329
+
330
+ # ── 4. Thin bright centre spine ───────────────────────────────
331
+ spine = Line(
332
+ start=[-w_px * 0.42, y, 0.003],
333
+ end =[ w_px * 0.42, y, 0.003],
334
+ stroke_color=interpolate_color(
335
+ theme["bar_center"], WHITE, 0.50
336
+ ),
337
+ stroke_width=1.0,
338
+ stroke_opacity=0.55,
339
+ )
340
+ self.add(spine)
341
+
342
+ @staticmethod
343
+ def _make_fog(
344
+ cx: float,
345
+ fog_w: float,
346
+ bar_h: float,
347
+ color: str,
348
+ ) -> VGroup:
349
+ """Tapered ellipse halo for the fog effect at each end."""
350
+ g = VGroup()
351
+ for i in range(4):
352
+ alpha_val = 0.18 - i * 0.04
353
+ scale_x = 1.0 - i * 0.18
354
+ scale_y = 1.0 - i * 0.10
355
+ ell = Circle(
356
+ radius=fog_w * 0.60,
357
+ fill_color=color,
358
+ fill_opacity=max(0, alpha_val),
359
+ stroke_width=0,
360
+ )
361
+ ell.scale([scale_x, scale_y * bar_h / (fog_w * 0.60), 1])
362
+ g.add(ell)
363
+ return g
364
+
365
+
366
+ class _EndCap(VGroup):
367
+ """
368
+ Bracket-style end cap at one end of the CI bar.
369
+
370
+ Structure (from outside in):
371
+ • outer_serif — full-height vertical line (the bracket arm)
372
+ • inner_tick — short inward tick at the centre height
373
+ • base_disc — small filled circle where the bracket meets the bar
374
+
375
+ Parameters
376
+ ----------
377
+ side : +1 (right end) or -1 (left end)
378
+ bar_h : float — bar visual height
379
+ theme : dict
380
+ y : float — vertical centre
381
+ """
382
+
383
+ def __init__(
384
+ self,
385
+ side: int,
386
+ bar_h: float,
387
+ theme: dict,
388
+ y: float = 0.0,
389
+ **kwargs,
390
+ ):
391
+ super().__init__(**kwargs)
392
+ z0 = 0.004
393
+ arm_h = bar_h * 2.20 # total bracket height
394
+ tick_l = bar_h * 0.55 # inward tick length
395
+ sw = 2.8 # stroke width
396
+
397
+ # ── Vertical arm ──────────────────────────────────────────────
398
+ arm = Line(
399
+ start=[0, y - arm_h / 2, z0],
400
+ end =[0, y + arm_h / 2, z0],
401
+ stroke_color=theme["cap"],
402
+ stroke_width=sw,
403
+ )
404
+ self.add(arm)
405
+
406
+ # ── Inward tick ───────────────────────────────────────────────
407
+ tick = Line(
408
+ start=[0, y, z0 + 0.001],
409
+ end =[-side * tick_l, y, z0 + 0.001],
410
+ stroke_color=theme["cap_tick"],
411
+ stroke_width=sw * 0.75,
412
+ )
413
+ self.add(tick)
414
+
415
+ # ── Top and bottom serifs (horizontal feet) ───────────────────
416
+ serif_w = bar_h * 0.30
417
+ for y_end in [y - arm_h / 2, y + arm_h / 2]:
418
+ serif = Line(
419
+ start=[-serif_w * 0.4, y_end, z0],
420
+ end =[ serif_w * 0.4, y_end, z0],
421
+ stroke_color=theme["cap"],
422
+ stroke_width=sw * 0.6,
423
+ )
424
+ self.add(serif)
425
+
426
+ # ── Base disc ─────────────────────────────────────────────────
427
+ disc = Circle(
428
+ radius=bar_h * 0.28,
429
+ fill_color=theme["cap"],
430
+ fill_opacity=1.0,
431
+ stroke_width=0,
432
+ )
433
+ disc.move_to([0, y, z0 + 0.001])
434
+ self.add(disc)
435
+
436
+
437
+ class _PointEstimateMarker(VGroup):
438
+ """
439
+ Multi-layer point estimate marker.
440
+
441
+ Styles
442
+ ------
443
+ "circle" — classic ● (sample mean x̄)
444
+ "diamond" — ◆ rotated square (MLE estimate)
445
+ "cross" — ✕ (population parameter μ)
446
+
447
+ Layers:
448
+ outer_ring — thin annulus
449
+ body — filled shape
450
+ inner_disc — slightly brighter inner fill
451
+ specular — bright offset dot
452
+ label — optional symbol (x̄, μ, etc.)
453
+ """
454
+
455
+ def __init__(
456
+ self,
457
+ style: Literal["circle", "diamond", "cross"] = "circle",
458
+ radius: float = 0.12,
459
+ theme: dict = None,
460
+ label: Optional[str] = None,
461
+ y: float = 0.0,
462
+ **kwargs,
463
+ ):
464
+ super().__init__(**kwargs)
465
+ if theme is None:
466
+ theme = CI_THEMES["blue"]
467
+ z0 = 0.008
468
+
469
+ mo = theme["marker_outer"]
470
+ mi = theme["marker_inner"]
471
+ ms = theme["marker_spec"]
472
+
473
+ if style == "circle":
474
+ # Outer ring
475
+ ring = Annulus(
476
+ inner_radius=radius * 0.55,
477
+ outer_radius=radius,
478
+ fill_color=mo,
479
+ fill_opacity=1.0,
480
+ stroke_width=0,
481
+ )
482
+ ring.move_to([0, y, z0])
483
+ self.add(ring)
484
+ # Inner disc
485
+ inner = Circle(
486
+ radius=radius * 0.52,
487
+ fill_color=mi,
488
+ fill_opacity=1.0,
489
+ stroke_width=0,
490
+ )
491
+ inner.move_to([0, y, z0 + 0.001])
492
+ self.add(inner)
493
+
494
+ elif style == "diamond":
495
+ d = radius * 1.30
496
+ diamond = Polygon(
497
+ [0, d, z0], [ d, 0, z0],
498
+ [0, -d, z0], [-d, 0, z0],
499
+ fill_color=mo, fill_opacity=1.0, stroke_width=0,
500
+ )
501
+ diamond.move_to([0, y, z0])
502
+ self.add(diamond)
503
+ inner_d = Polygon(
504
+ [0, d*0.55, z0+0.001], [ d*0.55, 0, z0+0.001],
505
+ [0, -d*0.55, z0+0.001], [-d*0.55, 0, z0+0.001],
506
+ fill_color=mi, fill_opacity=1.0, stroke_width=0,
507
+ )
508
+ inner_d.move_to([0, y, z0 + 0.001])
509
+ self.add(inner_d)
510
+
511
+ elif style == "cross":
512
+ sw = radius * 0.40
513
+ for ang in [0, PI / 2]:
514
+ arm = Line(
515
+ start=[-radius * np.cos(ang), -radius * np.sin(ang) + y, z0],
516
+ end =[ radius * np.cos(ang), radius * np.sin(ang) + y, z0],
517
+ stroke_color=mo,
518
+ stroke_width=sw * 18,
519
+ )
520
+ self.add(arm)
521
+
522
+ # Specular highlight
523
+ spec = Circle(
524
+ radius=radius * 0.22,
525
+ fill_color=ms,
526
+ fill_opacity=0.75,
527
+ stroke_width=0,
528
+ )
529
+ spec.move_to([-radius * 0.25, y + radius * 0.26, z0 + 0.003])
530
+ self.add(spec)
531
+
532
+ # Label
533
+ if label is not None:
534
+ try:
535
+ lbl = MathTex(label, font_size=radius * 80,
536
+ color=WHITE)
537
+ except Exception:
538
+ lbl = Text(label, font_size=radius * 60,
539
+ color=WHITE)
540
+ lbl.move_to([0, y, z0 + 0.005])
541
+ self.add(lbl)
542
+
543
+
544
+ class _CIBadge(VGroup):
545
+ """
546
+ Floating badge showing "95% CI" or custom text, with a rounded-rect
547
+ background and a leader line connecting to the CI bar.
548
+
549
+ Parameters
550
+ ----------
551
+ text : str — badge content, e.g. "95% CI"
552
+ bar_y : float — y position of the CI bar
553
+ badge_y : float — y position of the badge (above bar)
554
+ x_offset : float — horizontal offset of badge centre from 0
555
+ theme : dict
556
+ """
557
+
558
+ def __init__(
559
+ self,
560
+ text: str,
561
+ bar_y: float,
562
+ badge_y: float,
563
+ x_offset: float = 0.0,
564
+ theme: dict = None,
565
+ **kwargs,
566
+ ):
567
+ super().__init__(**kwargs)
568
+ if theme is None:
569
+ theme = CI_THEMES["blue"]
570
+ z0 = 0.010
571
+
572
+ # Text
573
+ lbl = Text(
574
+ text,
575
+ font_size=20,
576
+ color=theme["badge_fg"],
577
+ font="sans-serif",
578
+ )
579
+ lbl.move_to([x_offset, badge_y, z0 + 0.002])
580
+
581
+ # Background pill
582
+ pad_x, pad_y = 0.18, 0.10
583
+ bg = RoundedRectangle(
584
+ width=lbl.width + pad_x * 2,
585
+ height=lbl.height + pad_y * 2,
586
+ corner_radius=0.08,
587
+ fill_color=theme["badge_bg"],
588
+ fill_opacity=0.90,
589
+ stroke_width=0,
590
+ )
591
+ bg.move_to([x_offset, badge_y, z0])
592
+
593
+ # Leader line
594
+ leader = Line(
595
+ start=[x_offset, badge_y - lbl.height / 2 - pad_y, z0],
596
+ end =[x_offset, bar_y + 0.06, z0],
597
+ stroke_color=theme["badge_bg"],
598
+ stroke_width=1.2,
599
+ stroke_opacity=0.70,
600
+ )
601
+
602
+ self.add(leader, bg, lbl)
603
+
604
+
605
+ class _TrueParamLine(VGroup):
606
+ """
607
+ Dashed vertical line marking the true population parameter μ.
608
+ Colour reflects capture status.
609
+
610
+ Parameters
611
+ ----------
612
+ x : float — x position in Manim units
613
+ y_bottom : float — bottom of the line
614
+ y_top : float — top of the line
615
+ status : "unknown" | "captured" | "missed"
616
+ label : str | None — e.g. "μ₀"
617
+ """
618
+
619
+ def __init__(
620
+ self,
621
+ x: float,
622
+ y_bottom: float,
623
+ y_top: float,
624
+ status: Literal["unknown", "captured", "missed"] = "unknown",
625
+ label: Optional[str] = None,
626
+ **kwargs,
627
+ ):
628
+ super().__init__(**kwargs)
629
+ self._status = status
630
+ col = TRUE_PARAM_COLORS[status]
631
+ z0 = 0.006
632
+
633
+ # Dashed line
634
+ dline = DashedLine(
635
+ start=[x, y_bottom, z0],
636
+ end =[x, y_top, z0],
637
+ stroke_color=col,
638
+ stroke_width=2.2,
639
+ dash_length=0.12,
640
+ dashed_ratio=0.55,
641
+ )
642
+ self.add(dline)
643
+
644
+ # Label
645
+ if label is not None:
646
+ try:
647
+ lbl = MathTex(label, font_size=22, color=col)
648
+ except Exception:
649
+ lbl = Text(label, font_size=18, color=col)
650
+ lbl.move_to([x, y_top + 0.20, z0])
651
+ self.add(lbl)
652
+
653
+ self._x = x
654
+ self._y_top = y_top
655
+ self._col = col
656
+
657
+ def set_status(
658
+ self,
659
+ status: Literal["unknown", "captured", "missed"],
660
+ ):
661
+ """Re-colour to reflect capture result (call before animating)."""
662
+ col = TRUE_PARAM_COLORS[status]
663
+ for mob in self.submobjects:
664
+ mob.set_stroke(col)
665
+ mob.set_color(col)
666
+ self._status = status
667
+
668
+
669
+ class _NumberLineAxis(VGroup):
670
+ """
671
+ A clean number line to host CI objects.
672
+
673
+ Features:
674
+ * Arrow tips at both ends
675
+ * Major ticks with numeric labels
676
+ * Minor ticks (no labels)
677
+ * Axis label (e.g. "x" or "μ")
678
+ """
679
+
680
+ def __init__(
681
+ self,
682
+ x_range: tuple[float, float, float], # (min, max, step)
683
+ length: float = 8.0,
684
+ minor_ticks: int = 4,
685
+ theme: dict = None,
686
+ axis_label: str = "",
687
+ **kwargs,
688
+ ):
689
+ super().__init__(**kwargs)
690
+ if theme is None:
691
+ theme = CI_THEMES["blue"]
692
+
693
+ x_min, x_max, x_step = x_range
694
+ self._x_min = x_min
695
+ self._x_max = x_max
696
+ self._length = length
697
+ self._unit_px = length / (x_max - x_min)
698
+
699
+ # ── Main axis line ────────────────────────────────────────────
700
+ ax_line = Arrow(
701
+ start=[-length / 2 - 0.3, 0, 0],
702
+ end =[ length / 2 + 0.3, 0, 0],
703
+ stroke_color=theme["axis"],
704
+ stroke_width=2.0,
705
+ tip_length=0.20,
706
+ buff=0,
707
+ )
708
+ self.add(ax_line)
709
+
710
+ # ── Major ticks and labels ────────────────────────────────────
711
+ ticks_grp = VGroup()
712
+ val = x_min
713
+ while val <= x_max + 1e-9:
714
+ px = self.to_px(val)
715
+ tk = Line(
716
+ start=[px, -0.15, 0.001],
717
+ end =[px, 0.15, 0.001],
718
+ stroke_color=theme["axis"],
719
+ stroke_width=1.8,
720
+ )
721
+ ticks_grp.add(tk)
722
+ # Minor ticks between major
723
+ if minor_ticks > 0 and val + x_step <= x_max + 1e-9:
724
+ for mi in range(1, minor_ticks + 1):
725
+ m_val = val + mi * x_step / (minor_ticks + 1)
726
+ mpx = self.to_px(m_val)
727
+ mtk = Line(
728
+ start=[mpx, -0.07, 0.001],
729
+ end =[mpx, 0.07, 0.001],
730
+ stroke_color=theme["axis"],
731
+ stroke_width=0.9,
732
+ )
733
+ ticks_grp.add(mtk)
734
+ # Label
735
+ lbl_str = (f"{val:.0f}" if x_step >= 1
736
+ else f"{val:.2f}")
737
+ lbl = Text(
738
+ lbl_str,
739
+ font_size=16,
740
+ color=theme["axis_label"],
741
+ )
742
+ lbl.move_to([px, -0.38, 0])
743
+ ticks_grp.add(lbl)
744
+ val = round(val + x_step, 10)
745
+ self.add(ticks_grp)
746
+
747
+ # ── Axis label ────────────────────────────────────────────────
748
+ if axis_label:
749
+ try:
750
+ ax_lbl = MathTex(axis_label, font_size=26,
751
+ color=theme["axis_label"])
752
+ except Exception:
753
+ ax_lbl = Text(axis_label, font_size=22,
754
+ color=theme["axis_label"])
755
+ ax_lbl.move_to([length / 2 + 0.55, -0.38, 0])
756
+ self.add(ax_lbl)
757
+
758
+ def to_px(self, value: float) -> float:
759
+ """Convert an axis value to a Manim x-coordinate."""
760
+ return (value - self._x_min) / (
761
+ self._x_max - self._x_min
762
+ ) * self._length - self._length / 2
763
+
764
+
765
+ # ──────────────────────────────────────────────────────────────────────────────
766
+ # ConfidenceInterval3D ── the main export
767
+ # ──────────────────────────────────────────────────────────────────────────────
768
+
769
+ class ConfidenceInterval3D(VGroup):
770
+ """
771
+ A detailed confidence interval visualisation object.
772
+
773
+ Parameters
774
+ ----------
775
+ center : float
776
+ Point estimate (sample mean x̄ or MLE).
777
+ half_width : float
778
+ CI half-width in axis units. E.g. for 95% Z-interval:
779
+ ``half_width = 1.96 * std_err``.
780
+ Alternatively supply ``std_err`` and ``confidence``; then
781
+ ``half_width`` is computed automatically.
782
+ true_param : float | None
783
+ True population parameter μ. If supplied, a dashed vertical
784
+ line is drawn and capture status is tracked.
785
+ confidence : float
786
+ Nominal confidence level (0–1), e.g. ``0.95``. Used for
787
+ badge label and auto-computing half_width.
788
+ std_err : float | None
789
+ Standard error. If provided (and half_width not), half_width
790
+ is computed from the confidence level.
791
+ df : int | None
792
+ Degrees of freedom. If provided, a t-interval is used
793
+ instead of a Z-interval.
794
+ axis : _NumberLineAxis | None
795
+ Axis object to anchor the CI to. If None, a default axis
796
+ is created.
797
+ x_range : tuple
798
+ (min, max, step) for the auto-created axis.
799
+ axis_length : float
800
+ Length of the auto-created axis (Manim units). Default 9.0.
801
+ y_offset : float
802
+ Vertical shift of the CI bar above the axis. Default 0.0.
803
+ bar_height : float
804
+ Thickness of the CI bar (Manim units). Default 0.22.
805
+ theme : str
806
+ Named colour theme. Default ``"blue"``.
807
+ custom_theme : dict | None
808
+ Override individual theme keys.
809
+ marker_style : "circle" | "diamond" | "cross"
810
+ Point estimate marker shape. Default ``"circle"``.
811
+ marker_label : str | None
812
+ LaTeX label on the point estimate marker (e.g. ``r"\bar{x}"``).
813
+ show_badge : bool
814
+ Show the floating CI badge. Default ``True``.
815
+ show_true_param : bool
816
+ Show the true parameter line if ``true_param`` is provided.
817
+ badge_text : str | None
818
+ Override badge text (auto: "95% CI").
819
+ badge_y_offset : float
820
+ Upward shift of the badge from the CI bar. Default 0.55.
821
+
822
+ Attributes
823
+ ----------
824
+ center : float
825
+ lower : float
826
+ upper : float
827
+ half_width : float
828
+ captures : bool | None — True/False/None (not yet revealed)
829
+ ci_bar : _CIBar
830
+ left_cap : _EndCap
831
+ right_cap : _EndCap
832
+ marker : _PointEstimateMarker
833
+ true_line : _TrueParamLine | None
834
+ badge : _CIBadge | None
835
+ axis : _NumberLineAxis
836
+ unit_scale : float — Manim units per axis unit
837
+ """
838
+
839
+ def __init__(
840
+ self,
841
+ center: float,
842
+ half_width: Optional[float] = None,
843
+ true_param: Optional[float] = None,
844
+ confidence: float = 0.95,
845
+ std_err: Optional[float] = None,
846
+ df: Optional[int] = None,
847
+ axis: Optional[_NumberLineAxis] = None,
848
+ x_range: tuple = (60.0, 100.0, 5.0),
849
+ axis_length: float = 9.0,
850
+ y_offset: float = 0.0,
851
+ bar_height: float = 0.22,
852
+ theme: str = "blue",
853
+ custom_theme: Optional[dict] = None,
854
+ marker_style: Literal["circle", "diamond", "cross"] = "circle",
855
+ marker_label: Optional[str] = None,
856
+ show_badge: bool = True,
857
+ show_true_param: bool = True,
858
+ badge_text: Optional[str] = None,
859
+ badge_y_offset: float = 0.55,
860
+ **kwargs,
861
+ ):
862
+ super().__init__(**kwargs)
863
+
864
+ # ── Resolve palette ───────────────────────────────────────────
865
+ th = dict(CI_THEMES.get(theme, CI_THEMES["blue"]))
866
+ if custom_theme:
867
+ th.update(custom_theme)
868
+
869
+ # ── Compute half-width ────────────────────────────────────────
870
+ if half_width is None:
871
+ if std_err is None:
872
+ raise ValueError(
873
+ "Provide either half_width or std_err."
874
+ )
875
+ if df is not None:
876
+ half_width = _t_half_width(std_err, df, confidence)
877
+ else:
878
+ half_width = _z_half_width(std_err, confidence)
879
+
880
+ self._center = center
881
+ self._half_width = half_width
882
+ self._lower = center - half_width
883
+ self._upper = center + half_width
884
+ self._confidence = confidence
885
+ self._true_param = true_param
886
+ self._captures = (
887
+ _captures(self._lower, self._upper, true_param)
888
+ if true_param is not None else None
889
+ )
890
+ self._y_offset = y_offset
891
+ self._bar_height = bar_height
892
+
893
+ # ── Axis ──────────────────────────────────────────────────────
894
+ if axis is None:
895
+ axis = _NumberLineAxis(
896
+ x_range=x_range,
897
+ length=axis_length,
898
+ theme=th,
899
+ )
900
+ self.axis = axis
901
+ self._unit_scale = axis._unit_px
902
+ self.add(axis)
903
+
904
+ # ── Convert CI bounds to Manim coords ─────────────────────────
905
+ cx_px = axis.to_px(center)
906
+ hw_px = half_width * self._unit_scale
907
+
908
+ # ── CI Bar ────────────────────────────────────────────────────
909
+ self.ci_bar = _CIBar(
910
+ half_width=half_width,
911
+ bar_height=bar_height,
912
+ unit_scale=self._unit_scale,
913
+ theme=th,
914
+ y=y_offset,
915
+ )
916
+ self.ci_bar.move_to([cx_px, y_offset, 0])
917
+ self.add(self.ci_bar)
918
+
919
+ # ── End caps ──────────────────────────────────────────────────
920
+ self.left_cap = _EndCap(
921
+ side=-1, bar_h=bar_height, theme=th, y=y_offset
922
+ )
923
+ self.left_cap.move_to([cx_px - hw_px, y_offset, 0])
924
+ self.add(self.left_cap)
925
+
926
+ self.right_cap = _EndCap(
927
+ side=+1, bar_h=bar_height, theme=th, y=y_offset
928
+ )
929
+ self.right_cap.move_to([cx_px + hw_px, y_offset, 0])
930
+ self.add(self.right_cap)
931
+
932
+ # ── Point estimate marker ─────────────────────────────────────
933
+ self.marker = _PointEstimateMarker(
934
+ style=marker_style,
935
+ radius=bar_height * 0.70,
936
+ theme=th,
937
+ label=marker_label,
938
+ y=y_offset,
939
+ )
940
+ self.marker.move_to([cx_px, y_offset, 0])
941
+ self.add(self.marker)
942
+
943
+ # ── True parameter line ───────────────────────────────────────
944
+ self.true_line = None
945
+ if true_param is not None and show_true_param:
946
+ tp_px = axis.to_px(true_param)
947
+ self.true_line = _TrueParamLine(
948
+ x=tp_px,
949
+ y_bottom=y_offset - bar_height * 3.5,
950
+ y_top=y_offset + bar_height * 4.0,
951
+ status="unknown",
952
+ label=r"\mu_0",
953
+ )
954
+ self.add(self.true_line)
955
+
956
+ # ── Badge ─────────────────────────────────────────────────────
957
+ self.badge = None
958
+ if show_badge:
959
+ if badge_text is None:
960
+ badge_text = f"{int(confidence * 100)}% CI"
961
+ self.badge = _CIBadge(
962
+ text=badge_text,
963
+ bar_y=y_offset + bar_height / 2,
964
+ badge_y=y_offset + badge_y_offset,
965
+ x_offset=cx_px,
966
+ theme=th,
967
+ )
968
+ self.add(self.badge)
969
+
970
+ self._theme = th
971
+ self._cx_px = cx_px
972
+ self._hw_px = hw_px
973
+
974
+ # ──────────────────────────────────────────────────────────────────
975
+ # Properties
976
+ # ──────────────────────────────────────────────────────────────────
977
+
978
+ @property
979
+ def center(self) -> float:
980
+ return self._center
981
+
982
+ @property
983
+ def lower(self) -> float:
984
+ return self._lower
985
+
986
+ @property
987
+ def upper(self) -> float:
988
+ return self._upper
989
+
990
+ @property
991
+ def half_width(self) -> float:
992
+ return self._half_width
993
+
994
+ @property
995
+ def captures(self) -> Optional[bool]:
996
+ return self._captures
997
+
998
+ @property
999
+ def unit_scale(self) -> float:
1000
+ return self._unit_scale
1001
+
1002
+ def reveal_capture_status(self):
1003
+ """
1004
+ Update the true-parameter line colour based on capture result.
1005
+ Call this before ``RevealCapture`` animation.
1006
+ """
1007
+ if self.true_line is None or self._captures is None:
1008
+ return
1009
+ status = "captured" if self._captures else "missed"
1010
+ self.true_line.set_status(status)
1011
+
1012
+ def get_capture_color(self) -> str:
1013
+ if self._captures is True:
1014
+ return TRUE_PARAM_COLORS["captured"]
1015
+ elif self._captures is False:
1016
+ return TRUE_PARAM_COLORS["missed"]
1017
+ return TRUE_PARAM_COLORS["unknown"]
1018
+
1019
+ def rescale_to_axis(self, new_axis: _NumberLineAxis):
1020
+ """Re-position all components after replacing the axis."""
1021
+ self.axis = new_axis
1022
+ self._unit_scale = new_axis._unit_px
1023
+ # (Full rebuild; subclasses can override)
1024
+
1025
+
1026
+ # ──────────────────────────────────────────────────────────────────────────────
1027
+ # CIStack ── repeated-sampling coverage demonstration
1028
+ # ──────────────────────────────────────────────────────────────────────────────
1029
+
1030
+ class CIStack(VGroup):
1031
+ """
1032
+ A vertical stack of confidence intervals from repeated samples,
1033
+ demonstrating the frequentist coverage interpretation.
1034
+
1035
+ Parameters
1036
+ ----------
1037
+ true_param : float — the fixed population parameter μ
1038
+ ci_list : list of (center, half_width) tuples
1039
+ confidence : float — nominal coverage (for badge / label)
1040
+ x_range : tuple — (min, max, step) for the shared axis
1041
+ axis_length : float
1042
+ row_spacing : float — vertical gap between CI rows
1043
+ bar_height : float
1044
+ theme_captured : str — theme for capturing CIs
1045
+ theme_missed : str — theme for missing CIs
1046
+ show_counter : bool — show live "k/N captured" badge
1047
+ show_true_col : bool — show full-height true-param column
1048
+
1049
+ Attributes
1050
+ ----------
1051
+ cis : list[ConfidenceInterval3D]
1052
+ n_captured : int
1053
+ n_total : int
1054
+ coverage_rate : float
1055
+ counter_badge : VGroup
1056
+ """
1057
+
1058
+ def __init__(
1059
+ self,
1060
+ true_param: float,
1061
+ ci_list: list[tuple[float, float]],
1062
+ confidence: float = 0.95,
1063
+ x_range: tuple = (60.0, 100.0, 5.0),
1064
+ axis_length: float = 9.0,
1065
+ row_spacing: float = 0.42,
1066
+ bar_height: float = 0.18,
1067
+ theme_captured: str = "captured",
1068
+ theme_missed: str = "missed",
1069
+ show_counter: bool = True,
1070
+ show_true_col: bool = True,
1071
+ **kwargs,
1072
+ ):
1073
+ super().__init__(**kwargs)
1074
+
1075
+ self._true_param = true_param
1076
+ self._confidence = confidence
1077
+ self._row_spacing = row_spacing
1078
+ self._bar_height = bar_height
1079
+ self.cis: list[ConfidenceInterval3D] = []
1080
+
1081
+ # ── Shared axis (drawn once at the top) ───────────────────────
1082
+ th_base = CI_THEMES["blue"]
1083
+ self.shared_axis = _NumberLineAxis(
1084
+ x_range=x_range,
1085
+ length=axis_length,
1086
+ theme=th_base,
1087
+ )
1088
+ self.add(self.shared_axis)
1089
+
1090
+ # Extract unit scale for subsequent CIs
1091
+ us = self.shared_axis._unit_px
1092
+
1093
+ # ── True-parameter column (full height) ───────────────────────
1094
+ self.true_col = None
1095
+ self._tp_px = self.shared_axis.to_px(true_param)
1096
+ if show_true_col:
1097
+ n_rows = len(ci_list)
1098
+ col_h = n_rows * (bar_height + row_spacing) + 0.5
1099
+ self.true_col = DashedLine(
1100
+ start=[self._tp_px, 0.3, 0.002],
1101
+ end =[self._tp_px, -col_h, 0.002],
1102
+ stroke_color=TRUE_PARAM_COLORS["unknown"],
1103
+ stroke_width=2.0,
1104
+ dash_length=0.10,
1105
+ dashed_ratio=0.5,
1106
+ )
1107
+ self.add(self.true_col)
1108
+
1109
+ # ── Populate CI rows ──────────────────────────────────────────
1110
+ n_cap = 0
1111
+ for i, (ctr, hw) in enumerate(ci_list):
1112
+ y_row = -(i + 1) * (bar_height + row_spacing)
1113
+ cap = _captures(ctr - hw, ctr + hw, true_param)
1114
+ n_cap += int(cap)
1115
+ th_name = theme_captured if cap else theme_missed
1116
+ th = CI_THEMES.get(th_name, CI_THEMES["blue"])
1117
+
1118
+ # Bar
1119
+ bar = _CIBar(
1120
+ half_width=hw,
1121
+ bar_height=bar_height,
1122
+ unit_scale=us,
1123
+ theme=th,
1124
+ y=y_row,
1125
+ )
1126
+ bar.move_to([self.shared_axis.to_px(ctr), y_row, 0])
1127
+
1128
+ # End caps
1129
+ cx_px = self.shared_axis.to_px(ctr)
1130
+ hw_px = hw * us
1131
+ lcap = _EndCap(side=-1, bar_h=bar_height,
1132
+ theme=th, y=y_row)
1133
+ lcap.move_to([cx_px - hw_px, y_row, 0])
1134
+ rcap = _EndCap(side=+1, bar_h=bar_height,
1135
+ theme=th, y=y_row)
1136
+ rcap.move_to([cx_px + hw_px, y_row, 0])
1137
+
1138
+ # Marker
1139
+ mk = _PointEstimateMarker(
1140
+ style="circle",
1141
+ radius=bar_height * 0.60,
1142
+ theme=th,
1143
+ y=y_row,
1144
+ )
1145
+ mk.move_to([cx_px, y_row, 0])
1146
+
1147
+ row_grp = VGroup(bar, lcap, rcap, mk)
1148
+ self.add(row_grp)
1149
+
1150
+ # Store as minimal CI record
1151
+ self.cis.append((ctr - hw, ctr + hw, cap))
1152
+
1153
+ self.n_captured = n_cap
1154
+ self.n_total = len(ci_list)
1155
+ self.coverage_rate = n_cap / max(self.n_total, 1)
1156
+
1157
+ # ── Coverage counter badge ────────────────────────────────────
1158
+ self.counter_badge = None
1159
+ if show_counter and len(ci_list) > 0:
1160
+ self.counter_badge = self._make_counter_badge(
1161
+ n_cap, len(ci_list), confidence, th_base
1162
+ )
1163
+ self.add(self.counter_badge)
1164
+
1165
+ @staticmethod
1166
+ def _make_counter_badge(
1167
+ n_cap: int,
1168
+ n_total: int,
1169
+ confidence: float,
1170
+ theme: dict,
1171
+ ) -> VGroup:
1172
+ """Build the "k / N captured (p%)" badge."""
1173
+ pct = n_cap / n_total * 100
1174
+ nom_pct = confidence * 100
1175
+ diff = pct - nom_pct
1176
+ diff_str = f"+{diff:.1f}%" if diff >= 0 else f"{diff:.1f}%"
1177
+
1178
+ txt = Text(
1179
+ f"{n_cap}/{n_total} captured ({pct:.1f}% nominal {nom_pct:.0f}% {diff_str})",
1180
+ font_size=18,
1181
+ color=WHITE,
1182
+ )
1183
+ bg = RoundedRectangle(
1184
+ width=txt.width + 0.32,
1185
+ height=txt.height + 0.18,
1186
+ corner_radius=0.07,
1187
+ fill_color="#1A1A2E",
1188
+ fill_opacity=0.88,
1189
+ stroke_color=theme.get("axis", GREY_B),
1190
+ stroke_width=0.8,
1191
+ )
1192
+ bg.move_to([0, 0.85, 0])
1193
+ txt.move_to([0, 0.85, 0.001])
1194
+ return VGroup(bg, txt)
1195
+
1196
+ @classmethod
1197
+ def from_simulation(
1198
+ cls,
1199
+ true_param: float,
1200
+ n_samples: int,
1201
+ sample_size: int,
1202
+ population_std: float,
1203
+ confidence: float = 0.95,
1204
+ seed: int = 42,
1205
+ **kwargs,
1206
+ ) -> "CIStack":
1207
+ """
1208
+ Build a CIStack by simulating ``n_samples`` draws of size
1209
+ ``sample_size`` from N(true_param, population_std²).
1210
+
1211
+ Parameters
1212
+ ----------
1213
+ true_param : population mean μ
1214
+ n_samples : number of CI rows
1215
+ sample_size : n per sample
1216
+ population_std : σ (assumed known → Z-interval)
1217
+ confidence : nominal level
1218
+ seed : RNG seed
1219
+
1220
+ Returns
1221
+ -------
1222
+ CIStack ready for ``StackCIs`` animation.
1223
+ """
1224
+ rng = np.random.default_rng(seed)
1225
+ se = population_std / np.sqrt(sample_size)
1226
+ hw = _z_half_width(se, confidence)
1227
+
1228
+ ci_list = []
1229
+ for _ in range(n_samples):
1230
+ sample_mean = rng.normal(true_param, se)
1231
+ ci_list.append((sample_mean, hw))
1232
+
1233
+ return cls(
1234
+ true_param=true_param,
1235
+ ci_list=ci_list,
1236
+ confidence=confidence,
1237
+ **kwargs,
1238
+ )
1239
+
1240
+
1241
+ # ──────────────────────────────────────────────────────────────────────────────
1242
+ # Animations
1243
+ # ──────────────────────────────────────────────────────────────────────────────
1244
+
1245
+ class BuildCI(Animation):
1246
+ """
1247
+ The CI bar grows symmetrically outward from the point estimate.
1248
+
1249
+ Sequence:
1250
+ α ∈ [0.00, 0.60] — bar expands from 0 width to full width
1251
+ α ∈ [0.45, 0.75] — end caps materialise (fade in)
1252
+ α ∈ [0.70, 1.00] — badge fades in
1253
+
1254
+ Parameters
1255
+ ----------
1256
+ ci : ConfidenceInterval3D
1257
+ run_time : float
1258
+ """
1259
+
1260
+ def __init__(
1261
+ self,
1262
+ ci: ConfidenceInterval3D,
1263
+ **kwargs,
1264
+ ):
1265
+ self.ci = ci
1266
+ self._cx_px = ci._cx_px
1267
+ self._hw_px = ci._hw_px
1268
+ kwargs.setdefault("run_time", 1.8)
1269
+ kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
1270
+ super().__init__(ci, **kwargs)
1271
+
1272
+ def interpolate_mobject(self, alpha: float):
1273
+ self.ci.become(self.starting_mobject.copy())
1274
+
1275
+ # Phase 1: bar width expansion [0 → 0.60]
1276
+ bar_alpha = min(1.0, alpha / 0.60)
1277
+ scale_x = bar_alpha
1278
+ self.ci.ci_bar.scale(
1279
+ [scale_x if scale_x > 0 else 1e-6, 1, 1],
1280
+ about_point=[self._cx_px, self.ci._y_offset, 0],
1281
+ )
1282
+
1283
+ # Phase 2: end caps opacity [0.45 → 0.75]
1284
+ cap_alpha = np.clip((alpha - 0.45) / 0.30, 0, 1)
1285
+ self.ci.left_cap.set_opacity(cap_alpha)
1286
+ self.ci.right_cap.set_opacity(cap_alpha)
1287
+ self.ci.marker.set_opacity(cap_alpha)
1288
+
1289
+ # Phase 3: badge opacity [0.70 → 1.00]
1290
+ badge_alpha = np.clip((alpha - 0.70) / 0.30, 0, 1)
1291
+ if self.ci.badge is not None:
1292
+ self.ci.badge.set_opacity(badge_alpha)
1293
+ if self.ci.true_line is not None:
1294
+ self.ci.true_line.set_opacity(badge_alpha)
1295
+
1296
+
1297
+ class RevealCapture(Succession):
1298
+ """
1299
+ Drop the true-parameter line into view and flash the CI
1300
+ green (captured) or red (missed).
1301
+
1302
+ Sequence:
1303
+ 1. True-param line drops from above (FadeIn with UP shift)
1304
+ 2. Line re-colours to capture/miss colour
1305
+ 3. CI bar flashes (Indicate) in the capture colour
1306
+ 4. Badge text fades to update status
1307
+
1308
+ Parameters
1309
+ ----------
1310
+ ci : ConfidenceInterval3D
1311
+ run_time : float
1312
+ """
1313
+
1314
+ def __init__(
1315
+ self,
1316
+ ci: ConfidenceInterval3D,
1317
+ **kwargs,
1318
+ ):
1319
+ ci.reveal_capture_status()
1320
+ cap_col = ci.get_capture_color()
1321
+
1322
+ anims = []
1323
+
1324
+ if ci.true_line is not None:
1325
+ anims.append(
1326
+ FadeIn(ci.true_line, shift=DOWN * 0.5, run_time=0.6)
1327
+ )
1328
+
1329
+ # Flash the CI bar
1330
+ anims.append(
1331
+ Indicate(
1332
+ ci.ci_bar,
1333
+ color=cap_col,
1334
+ scale_factor=1.04,
1335
+ run_time=0.7,
1336
+ )
1337
+ )
1338
+
1339
+ # Flash the end caps
1340
+ anims.append(
1341
+ AnimationGroup(
1342
+ Indicate(ci.left_cap, color=cap_col,
1343
+ scale_factor=1.06, run_time=0.5),
1344
+ Indicate(ci.right_cap, color=cap_col,
1345
+ scale_factor=1.06, run_time=0.5),
1346
+ )
1347
+ )
1348
+
1349
+ kwargs.setdefault("run_time",
1350
+ sum(getattr(a, "run_time", 0.7) for a in anims))
1351
+ super().__init__(*anims, **kwargs)
1352
+
1353
+
1354
+ class SweepCI(Animation):
1355
+ """
1356
+ Slide the CI bar horizontally to a new center value, keeping
1357
+ the true-param line and axis stationary.
1358
+
1359
+ Parameters
1360
+ ----------
1361
+ ci : ConfidenceInterval3D
1362
+ new_center : float — new center value in axis units
1363
+ run_time : float
1364
+ """
1365
+
1366
+ def __init__(
1367
+ self,
1368
+ ci: ConfidenceInterval3D,
1369
+ new_center: float,
1370
+ **kwargs,
1371
+ ):
1372
+ self.ci = ci
1373
+ self.old_cx_px = ci._cx_px
1374
+ self.new_cx_px = ci.axis.to_px(new_center)
1375
+ self._new_center = new_center
1376
+ kwargs.setdefault("run_time", 1.2)
1377
+ kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
1378
+ # Animate only the mobile components (not axis, not true_line)
1379
+ grp = VGroup(
1380
+ ci.ci_bar, ci.left_cap, ci.right_cap,
1381
+ ci.marker,
1382
+ *([ci.badge] if ci.badge else []),
1383
+ )
1384
+ super().__init__(grp, **kwargs)
1385
+
1386
+ def interpolate_mobject(self, alpha: float):
1387
+ dx = (self.new_cx_px - self.old_cx_px) * alpha
1388
+ self.mobject.become(self.starting_mobject.copy())
1389
+ self.mobject.shift([dx, 0, 0])
1390
+ if alpha >= 1.0:
1391
+ self.ci._cx_px = self.new_cx_px
1392
+ self.ci._center = self._new_center
1393
+ self.ci._lower = self._new_center - self.ci._half_width
1394
+ self.ci._upper = self._new_center + self.ci._half_width
1395
+ if self.ci._true_param is not None:
1396
+ self.ci._captures = _captures(
1397
+ self.ci._lower, self.ci._upper, self.ci._true_param
1398
+ )
1399
+
1400
+
1401
+ class NarrowCI(Animation):
1402
+ """
1403
+ Shrink the CI to a new (narrower or wider) half_width.
1404
+ Simulates increasing sample size n or changing confidence level.
1405
+
1406
+ Parameters
1407
+ ----------
1408
+ ci : ConfidenceInterval3D
1409
+ new_half_width: float — new half-width in axis units
1410
+ run_time : float
1411
+ """
1412
+
1413
+ def __init__(
1414
+ self,
1415
+ ci: ConfidenceInterval3D,
1416
+ new_half_width: float,
1417
+ **kwargs,
1418
+ ):
1419
+ self.ci = ci
1420
+ self.old_hw_px = ci._hw_px
1421
+ self.new_hw_px = new_half_width * ci._unit_scale
1422
+ self._new_half_width = new_half_width
1423
+ kwargs.setdefault("run_time", 1.4)
1424
+ kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
1425
+ grp = VGroup(
1426
+ ci.ci_bar, ci.left_cap, ci.right_cap,
1427
+ *([ci.badge] if ci.badge else []),
1428
+ )
1429
+ super().__init__(grp, **kwargs)
1430
+
1431
+ def interpolate_mobject(self, alpha: float):
1432
+ hw_now = self.old_hw_px + (self.new_hw_px - self.old_hw_px) * alpha
1433
+ scale = hw_now / max(self.old_hw_px, 1e-6)
1434
+
1435
+ self.mobject.become(self.starting_mobject.copy())
1436
+ cx = self.ci._cx_px
1437
+ self.ci.ci_bar.scale(
1438
+ [scale, 1, 1],
1439
+ about_point=[cx, self.ci._y_offset, 0],
1440
+ )
1441
+ # Shift end caps
1442
+ old_l = cx - self.old_hw_px
1443
+ old_r = cx + self.old_hw_px
1444
+ new_l = cx - hw_now
1445
+ new_r = cx + hw_now
1446
+ self.ci.left_cap.shift( [new_l - old_l, 0, 0])
1447
+ self.ci.right_cap.shift([new_r - old_r, 0, 0])
1448
+
1449
+ if alpha >= 1.0:
1450
+ self.ci._half_width = self._new_half_width
1451
+ self.ci._hw_px = self.new_hw_px
1452
+ self.ci._lower = self.ci._center - self._new_half_width
1453
+ self.ci._upper = self.ci._center + self._new_half_width
1454
+
1455
+
1456
+ class StackCIs(Succession):
1457
+ """
1458
+ Animate N CI rows being added to a CIStack one by one,
1459
+ with the coverage counter badge updating after each addition.
1460
+
1461
+ The CIStack should be created empty or with ``ci_list=[]``;
1462
+ this animation populates it in real time.
1463
+
1464
+ Since fully dynamic CIStack building is complex, this animation
1465
+ works with a pre-built CIStack and reveals each row sequentially
1466
+ using FadeIn with a downward shift.
1467
+
1468
+ Parameters
1469
+ ----------
1470
+ stack : CIStack — fully built stack (all rows present but hidden)
1471
+ run_time : float — total animation time
1472
+ per_ci_rt : float — time per CI row
1473
+ stagger : float — pause between rows
1474
+ """
1475
+
1476
+ def __init__(
1477
+ self,
1478
+ stack: CIStack,
1479
+ per_ci_rt: float = 0.15,
1480
+ stagger: float = 0.05,
1481
+ **kwargs,
1482
+ ):
1483
+ # Hide all CI rows initially
1484
+ ci_rows = [
1485
+ mob for mob in stack.submobjects
1486
+ if mob not in (stack.shared_axis, stack.true_col,
1487
+ stack.counter_badge)
1488
+ and mob is not None
1489
+ ]
1490
+ for row in ci_rows:
1491
+ row.set_opacity(0)
1492
+
1493
+ # Animate rows appearing one by one
1494
+ anims = []
1495
+ for i, row in enumerate(ci_rows):
1496
+ anims.append(
1497
+ FadeIn(row, shift=RIGHT * 0.15, run_time=per_ci_rt)
1498
+ )
1499
+
1500
+ # Reveal counter badge at the end
1501
+ if stack.counter_badge is not None:
1502
+ stack.counter_badge.set_opacity(0)
1503
+ anims.append(
1504
+ FadeIn(stack.counter_badge, run_time=0.5)
1505
+ )
1506
+
1507
+ kwargs.setdefault(
1508
+ "run_time",
1509
+ len(anims) * (per_ci_rt + stagger),
1510
+ )
1511
+ super().__init__(*anims, **kwargs)
1512
+
1513
+
1514
+ # ──────────────────────────────────────────────────────────────────────────────
1515
+ # Convenience factories
1516
+ # ──────────────────────────────────────────────────────────────────────────────
1517
+
1518
+ def make_ci_comparison(
1519
+ centers: list[float],
1520
+ half_widths: list[float],
1521
+ confidence_levels: list[float],
1522
+ true_param: Optional[float] = None,
1523
+ x_range: tuple = (60.0, 100.0, 5.0),
1524
+ axis_length: float = 9.0,
1525
+ y_spacing: float = 0.9,
1526
+ themes: Optional[list[str]] = None,
1527
+ ) -> VGroup:
1528
+ """
1529
+ Stack multiple CIs for side-by-side comparison — e.g. 90/95/99%
1530
+ intervals from the same sample, or same level from different samples.
1531
+
1532
+ Parameters
1533
+ ----------
1534
+ centers, half_widths, confidence_levels : parallel lists
1535
+ true_param : optional true parameter (shared)
1536
+ y_spacing : vertical gap between CIs
1537
+ themes : one theme name per CI; cycles if short
1538
+
1539
+ Returns
1540
+ -------
1541
+ VGroup containing a shared axis + N ConfidenceInterval3D objects.
1542
+ """
1543
+ if themes is None:
1544
+ themes = ["blue", "gold", "dark"]
1545
+ n = len(centers)
1546
+
1547
+ # Shared axis at y=0
1548
+ th_base = CI_THEMES["blue"]
1549
+ ax = _NumberLineAxis(
1550
+ x_range=x_range,
1551
+ length=axis_length,
1552
+ theme=th_base,
1553
+ )
1554
+ group = VGroup(ax)
1555
+
1556
+ for i in range(n):
1557
+ y_off = -(i + 1) * y_spacing
1558
+ ci = ConfidenceInterval3D(
1559
+ center=centers[i],
1560
+ half_width=half_widths[i],
1561
+ true_param=true_param,
1562
+ confidence=confidence_levels[i],
1563
+ axis=ax,
1564
+ y_offset=y_off,
1565
+ bar_height=0.20,
1566
+ theme=themes[i % len(themes)],
1567
+ show_true_param=(i == n - 1), # only bottom CI shows true line
1568
+ badge_y_offset=0.42,
1569
+ )
1570
+ group.add(ci)
1571
+
1572
+ return group
1573
+
1574
+
1575
+ def make_clt_ci_stack(
1576
+ true_mean: float = 80.0,
1577
+ true_std: float = 10.0,
1578
+ sample_size: int = 30,
1579
+ n_samples: int = 20,
1580
+ confidence: float = 0.95,
1581
+ x_range: tuple = (60.0, 100.0, 5.0),
1582
+ seed: int = 42,
1583
+ **stack_kwargs,
1584
+ ) -> CIStack:
1585
+ """
1586
+ Convenience wrapper: simulate ``n_samples`` of size ``sample_size``
1587
+ from N(true_mean, true_std²) and build a CIStack.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ true_mean, true_std : population parameters
1592
+ sample_size : n per draw
1593
+ n_samples : number of CI rows
1594
+ confidence : nominal level
1595
+ seed : RNG seed
1596
+
1597
+ Returns
1598
+ -------
1599
+ CIStack ready for StackCIs animation.
1600
+ """
1601
+ return CIStack.from_simulation(
1602
+ true_param=true_mean,
1603
+ n_samples=n_samples,
1604
+ sample_size=sample_size,
1605
+ population_std=true_std,
1606
+ confidence=confidence,
1607
+ x_range=x_range,
1608
+ seed=seed,
1609
+ **stack_kwargs,
1610
+ )
1611
+
1612
+
1613
+ # ──────────────────────────────────────────────────────────────────────────────
1614
+ # Demo Scene (run with: manim -pql confidence_interval.py CIDemo)
1615
+ # ──────────────────────────────────────────────────────────────────────────────
1616
+
1617
+ try:
1618
+ from manim import ThreeDScene, Scene, DEGREES, Wait
1619
+
1620
+ class CIDemo(Scene):
1621
+ """Showcase scene for ConfidenceInterval3D, CIStack, and animations."""
1622
+
1623
+ def construct(self):
1624
+
1625
+ # ── Single 95% Z-interval ─────────────────────────────────
1626
+ ci = ConfidenceInterval3D(
1627
+ center=80.0,
1628
+ std_err=3.2,
1629
+ confidence=0.95,
1630
+ true_param=82.0,
1631
+ x_range=(60.0, 100.0, 5.0),
1632
+ axis_length=9.0,
1633
+ theme="blue",
1634
+ marker_label=r"\bar{x}",
1635
+ badge_y_offset=0.60,
1636
+ )
1637
+ self.play(BuildCI(ci, run_time=2.0))
1638
+ self.wait(0.4)
1639
+ self.play(RevealCapture(ci))
1640
+ self.wait(0.5)
1641
+
1642
+ # ── Sweep to a new sample ─────────────────────────────────
1643
+ self.play(SweepCI(ci, new_center=76.5, run_time=1.3))
1644
+ self.wait(0.3)
1645
+ ci.reveal_capture_status()
1646
+ self.play(RevealCapture(ci))
1647
+ self.wait(0.5)
1648
+
1649
+ # ── Narrow the CI (larger n) ──────────────────────────────
1650
+ self.play(NarrowCI(ci, new_half_width=3.5, run_time=1.4))
1651
+ self.wait(0.5)
1652
+
1653
+ self.play(FadeOut(ci))
1654
+ self.wait(0.3)
1655
+
1656
+ # ── 90 / 95 / 99 % comparison ────────────────────────────
1657
+ comparison = make_ci_comparison(
1658
+ centers=[80.0, 80.0, 80.0],
1659
+ half_widths=[
1660
+ _z_half_width(3.2, 0.90),
1661
+ _z_half_width(3.2, 0.95),
1662
+ _z_half_width(3.2, 0.99),
1663
+ ],
1664
+ confidence_levels=[0.90, 0.95, 0.99],
1665
+ true_param=82.0,
1666
+ x_range=(60.0, 100.0, 5.0),
1667
+ y_spacing=0.85,
1668
+ themes=["blue", "gold", "dark"],
1669
+ )
1670
+ comparison.scale(0.80).center()
1671
+ for mob in comparison.submobjects[1:]:
1672
+ self.play(BuildCI(mob, run_time=0.9))
1673
+ self.wait(1.0)
1674
+ self.play(FadeOut(comparison))
1675
+
1676
+ # ── CIStack coverage demonstration ────────────────────────
1677
+ stack = make_clt_ci_stack(
1678
+ true_mean=80.0,
1679
+ true_std=10.0,
1680
+ sample_size=30,
1681
+ n_samples=15,
1682
+ confidence=0.95,
1683
+ x_range=(60.0, 100.0, 5.0),
1684
+ row_spacing=0.35,
1685
+ bar_height=0.16,
1686
+ )
1687
+ stack.scale(0.85).center()
1688
+ self.play(FadeIn(stack.shared_axis), run_time=0.5)
1689
+ self.play(StackCIs(stack, per_ci_rt=0.18, stagger=0.06))
1690
+ self.wait(2.0)
1691
+
1692
+ except ImportError:
1693
+ pass