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,1682 @@
1
+ """
2
+ statanim/probability/bayes.py
3
+ ==================================
4
+ Production-quality Bayesian reasoning visualizations for Manim.
5
+
6
+ Objects
7
+ -------
8
+
9
+ BayesBox3D
10
+ The classic 2×2 Bayes table rendered as a 3D mosaic of prisms.
11
+ Cell footprint area (width × depth) encodes joint probability P(H∩E).
12
+ Cell height encodes the likelihood ratio for that cell.
13
+ Four labeled partitions: TP, FP, FN, TN — each a shaded prism.
14
+ Axes labeled with P(H)/P(¬H) and P(E|H)/P(E|¬H).
15
+ Posterior P(H|E) displayed as an annotated bracket along one edge.
16
+
17
+ PriorPosteriorBar3D
18
+ A vertical probability bar split into two color bands (H vs ¬H).
19
+ Displays the prior split, then morphs to the posterior after evidence
20
+ via animate_update(). The "squeeze/expand" motion makes the
21
+ Bayesian shift viscerally visible.
22
+
23
+ LikelihoodPanel3D
24
+ Side-by-side pair of bars: P(E|H) and P(E|¬H).
25
+ A ratio bracket above them shows LR = P(E|H) / P(E|¬H) with color
26
+ coding — green for LR > 1 (evidence supports H), red for LR < 1.
27
+
28
+ NaturalFrequencyTree3D
29
+ Tree where each branch is a 3D prism whose cross-sectional area
30
+ encodes the absolute count of people/items in that branch.
31
+ Root: population N. Level 1: N·P(H) with H vs ¬H branches.
32
+ Level 2: further splits by P(E|H) and P(E|¬H).
33
+ Leaf nodes show icon-array style dot grids.
34
+
35
+ SequentialBayesUpdater3D
36
+ A horizontal probability axis [0, 1] with a marker at the current
37
+ prior. Each piece of evidence shifts the marker left or right via
38
+ animate_add_evidence(). A trail of ghost markers records the history.
39
+ The Bayes factor for each update is displayed above the axis.
40
+
41
+ BayesFormulaBanner
42
+ Floating MathTex rendering of Bayes' theorem with each term in a
43
+ distinct color matching the visual objects in the scene.
44
+ animate_highlight_term() pulses one term at a time.
45
+
46
+ BayesConfig
47
+ Dataclass controlling all visual parameters.
48
+
49
+ Animation suite
50
+ ---------------
51
+ All objects expose named animate_* methods returning Manim Animations
52
+ suitable for self.play(...). Key animations:
53
+
54
+ BayesBox3D
55
+ .animate_build_box() – cells rise from floor one by one
56
+ .animate_highlight_cell() – flash one partition prism
57
+ .animate_reveal_posterior() – bracket and label slide into place
58
+ .animate_sweep_evidence() – color-wave across the E+ column
59
+
60
+ PriorPosteriorBar3D
61
+ .animate_build() – bar grows upward from floor
62
+ .animate_update(p_h, evidence) – morph split to posterior
63
+
64
+ LikelihoodPanel3D
65
+ .animate_build() – both bars grow simultaneously
66
+ .animate_highlight_lr() – pulse the LR bracket
67
+
68
+ NaturalFrequencyTree3D
69
+ .animate_grow_tree() – branches extend level by level
70
+ .animate_drop_icons() – icon dots rain into leaf nodes
71
+
72
+ SequentialBayesUpdater3D
73
+ .animate_axis() – axis and prior marker appear
74
+ .animate_add_evidence(lr) – update marker with Bayes factor
75
+
76
+ BayesFormulaBanner
77
+ .animate_appear() – formula writes itself
78
+ .animate_highlight_term(t) – pulse term t (0–4)
79
+ """
80
+
81
+ from __future__ import annotations
82
+
83
+ from dataclasses import dataclass, field
84
+ from typing import Sequence
85
+
86
+ import numpy as np
87
+ from scipy import stats as scipy_stats
88
+
89
+ from manim import (
90
+ WHITE, BLACK, GRAY, GRAY_A, GRAY_B, GRAY_C, GRAY_D, GRAY_E,
91
+ BLUE, BLUE_E, RED, RED_E, GREEN, GREEN_E, YELLOW, ORANGE, PURPLE,
92
+ UP, DOWN, LEFT, RIGHT,
93
+ PI, TAU,
94
+ VGroup, VMobject,
95
+ Line3D, Polygon, Sphere, Dot3D, Arrow3D,
96
+ Text, MathTex,
97
+ FadeIn, FadeOut, GrowFromPoint, GrowFromCenter, Transform,
98
+ Create, Write, AnimationGroup, Succession, LaggedStart,
99
+ interpolate_color,
100
+ ManimColor,
101
+ DEGREES,
102
+ )
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Color semantics for Bayesian reasoning
107
+ # ---------------------------------------------------------------------------
108
+
109
+ # Hypothesis colors
110
+ H_TRUE_COLOR = ManimColor("#1565C0") # blue – H is true
111
+ H_FALSE_COLOR = ManimColor("#B71C1C") # red – H is false
112
+
113
+ # Evidence colors
114
+ E_POS_COLOR = ManimColor("#2E7D32") # green – E is present / test +
115
+ E_NEG_COLOR = ManimColor("#4E342E") # brown – E is absent / test −
116
+
117
+ # Cell (joint probability) colors — one per quadrant
118
+ TP_COLOR = ManimColor("#1976D2") # blue – H true & E+ (true positive)
119
+ FP_COLOR = ManimColor("#EF5350") # red – H false & E+ (false positive)
120
+ FN_COLOR = ManimColor("#64B5F6") # lt blue – H true & E− (false negative)
121
+ TN_COLOR = ManimColor("#EF9A9A") # lt red – H false & E− (true negative)
122
+
123
+ # Likelihood ratio
124
+ LR_POS_COLOR = ManimColor("#00E676") # green – LR > 1 (evidence supports H)
125
+ LR_NEG_COLOR = ManimColor("#FF5252") # red – LR < 1 (evidence against H)
126
+ LR_NULL_COLOR = GRAY_C # grey – LR ≈ 1 (no information)
127
+
128
+ # Posterior update
129
+ PRIOR_COLOR = ManimColor("#78909C") # slate
130
+ POSTERIOR_COLOR = ManimColor("#FFD600") # yellow
131
+
132
+ # Formula term colors (matching visual objects)
133
+ TERM_COLORS = [
134
+ ManimColor("#FFD600"), # P(H|E) – posterior
135
+ ManimColor("#1976D2"), # P(E|H) – likelihood
136
+ ManimColor("#1565C0"), # P(H) – prior
137
+ ManimColor("#FF5252"), # P(E|¬H) – false positive rate
138
+ ManimColor("#B71C1C"), # P(¬H) – complement prior
139
+ ]
140
+
141
+ FACE_DARKEN_SIDE = 0.38
142
+ FACE_DARKEN_RIGHT = 0.55
143
+
144
+
145
+ def _dk(c: ManimColor, f: float) -> ManimColor:
146
+ return interpolate_color(c, BLACK, f)
147
+
148
+ def _lt(c: ManimColor, f: float) -> ManimColor:
149
+ return interpolate_color(c, WHITE, f)
150
+
151
+ def _clamp(v: float, lo: float = 0.0, hi: float = 1.0) -> float:
152
+ return float(np.clip(v, lo, hi))
153
+
154
+
155
+ # ---------------------------------------------------------------------------
156
+ # Core Bayesian math helpers
157
+ # ---------------------------------------------------------------------------
158
+
159
+ def bayes_update(prior: float, lr: float) -> float:
160
+ """Bayesian update via likelihood ratio on probability (not odds).
161
+
162
+ posterior = (prior * lr) / (prior * lr + (1 − prior))
163
+
164
+ Parameters
165
+ ----------
166
+ prior : float
167
+ P(H) before evidence.
168
+ lr : float
169
+ Likelihood ratio P(E|H) / P(E|¬H).
170
+
171
+ Returns
172
+ -------
173
+ float
174
+ Posterior P(H|E).
175
+ """
176
+ prior = _clamp(prior, 1e-9, 1 - 1e-9)
177
+ odds_pre = prior / (1 - prior)
178
+ odds_post = odds_pre * lr
179
+ return odds_post / (1 + odds_post)
180
+
181
+
182
+ def compute_joint_probs(
183
+ p_h: float,
184
+ p_e_h: float,
185
+ p_e_nh: float,
186
+ ) -> dict[str, float]:
187
+ """Compute the four joint probabilities for a 2×2 Bayes table.
188
+
189
+ Returns
190
+ -------
191
+ dict with keys "tp", "fp", "fn", "tn" and "p_e", "posterior"
192
+ """
193
+ p_nh = 1 - p_h
194
+ tp = p_h * p_e_h # P(H ∩ E+)
195
+ fn = p_h * (1 - p_e_h) # P(H ∩ E−)
196
+ fp = p_nh * p_e_nh # P(¬H ∩ E+)
197
+ tn = p_nh * (1 - p_e_nh) # P(¬H ∩ E−)
198
+ p_e = tp + fp # P(E+) = total positive rate
199
+ post = tp / p_e if p_e > 1e-12 else 0.0
200
+ return dict(tp=tp, fp=fp, fn=fn, tn=tn,
201
+ p_e=p_e, posterior=post,
202
+ p_h=p_h, p_nh=p_nh,
203
+ p_e_h=p_e_h, p_e_nh=p_e_nh,
204
+ lr=p_e_h / p_e_nh if p_e_nh > 1e-12 else float("inf"))
205
+
206
+
207
+ # ---------------------------------------------------------------------------
208
+ # Configuration
209
+ # ---------------------------------------------------------------------------
210
+
211
+ @dataclass
212
+ class BayesConfig:
213
+ """Visual configuration for all Bayesian objects in this module.
214
+
215
+ BayesBox3D
216
+ ----------
217
+ box_scale_x : float
218
+ Total width of the Bayes box (maps P(H) axis) in Manim units.
219
+ box_scale_z : float
220
+ Total depth of the Bayes box (maps P(E|·) axis) in Manim units.
221
+ box_max_height : float
222
+ Maximum prism height (cell with largest LR gets this height).
223
+ Set to 0 for a flat mosaic (no height encoding).
224
+ box_gap : float
225
+ Gap between adjacent prisms (visual separation).
226
+ show_cell_labels : bool
227
+ Render probability annotations inside each cell.
228
+ show_axis_labels : bool
229
+ Render P(H)/P(¬H) and P(E|H)/P(E|¬H) axis labels.
230
+ show_posterior_bracket : bool
231
+ Render the posterior bracket + annotation on the E+ row.
232
+ cell_label_font_size : int
233
+ Font size for cell value annotations.
234
+ axis_label_font_size : int
235
+ Font size for axis labels.
236
+
237
+ PriorPosteriorBar3D
238
+ -------------------
239
+ bar_width : float
240
+ Width of the prior/posterior bar prism.
241
+ bar_depth : float
242
+ Depth (Z) of the bar prism.
243
+ bar_max_height : float
244
+ Full height of the bar (represents probability = 1).
245
+ show_probability_labels : bool
246
+ Show floating P(H) / P(¬H) labels on each band.
247
+
248
+ LikelihoodPanel3D
249
+ -----------------
250
+ lr_bar_width : float
251
+ Width of each likelihood bar.
252
+ lr_bar_spacing : float
253
+ Gap between the two likelihood bars.
254
+ lr_max_height : float
255
+ Height corresponding to probability = 1.
256
+ show_lr_bracket : bool
257
+ Render the LR ratio bracket above the two bars.
258
+
259
+ NaturalFrequencyTree3D
260
+ ----------------------
261
+ tree_population : int
262
+ Total population N at the root.
263
+ tree_level_spacing : float
264
+ Vertical distance between tree levels.
265
+ tree_branch_gap : float
266
+ Gap between sibling branches at the same level.
267
+ tree_max_width : float
268
+ Maximum width of the root node.
269
+ show_icon_arrays : bool
270
+ Draw dot grids in leaf nodes.
271
+ icon_radius : float
272
+ Radius of each icon dot.
273
+
274
+ SequentialBayesUpdater3D
275
+ ------------------------
276
+ axis_length : float
277
+ Length of the [0, 1] probability axis.
278
+ marker_radius : float
279
+ Radius of the prior/posterior marker sphere.
280
+ ghost_opacity : float
281
+ Opacity of historical ghost markers.
282
+ show_bayes_factor : bool
283
+ Display the LR above the axis at each update.
284
+
285
+ Shared
286
+ ------
287
+ show_formula_banner : bool
288
+ Show the BayesFormulaBanner floating above the main object.
289
+ font_size : int
290
+ Default font size for labels.
291
+ axes_color : ManimColor
292
+ Color for axis lines and ticks.
293
+ """
294
+
295
+ # ---- BayesBox3D ----
296
+ box_scale_x: float = 6.0
297
+ box_scale_z: float = 4.0
298
+ box_max_height: float = 1.20
299
+ box_gap: float = 0.06
300
+ show_cell_labels: bool = True
301
+ show_axis_labels: bool = True
302
+ show_posterior_bracket: bool = True
303
+ cell_label_font_size: int = 20
304
+ axis_label_font_size: int = 22
305
+
306
+ # ---- PriorPosteriorBar3D ----
307
+ bar_width: float = 0.80
308
+ bar_depth: float = 0.40
309
+ bar_max_height: float = 4.50
310
+ show_probability_labels: bool = True
311
+
312
+ # ---- LikelihoodPanel3D ----
313
+ lr_bar_width: float = 0.70
314
+ lr_bar_spacing: float = 0.55
315
+ lr_max_height: float = 3.50
316
+ show_lr_bracket: bool = True
317
+
318
+ # ---- NaturalFrequencyTree3D ----
319
+ tree_population: int = 1000
320
+ tree_level_spacing: float = 2.20
321
+ tree_branch_gap: float = 0.30
322
+ tree_max_width: float = 5.00
323
+ show_icon_arrays: bool = True
324
+ icon_radius: float = 0.045
325
+
326
+ # ---- SequentialBayesUpdater3D ----
327
+ axis_length: float = 7.00
328
+ marker_radius: float = 0.14
329
+ ghost_opacity: float = 0.28
330
+ show_bayes_factor: bool = True
331
+
332
+ # ---- Shared ----
333
+ show_formula_banner: bool = True
334
+ font_size: int = 22
335
+ axes_color: ManimColor = GRAY_B
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # _ShadeBox — shared 3-face shaded prism (reused across all objects)
340
+ # ---------------------------------------------------------------------------
341
+
342
+ class _ShadeBox(VGroup):
343
+ """A 3D prism with physically-shaded top / front / right faces.
344
+
345
+ Coordinate layout:
346
+ x : [x0, x0 + width]
347
+ y : [0, height ]
348
+ z : [z0, z0 + depth]
349
+ """
350
+
351
+ def __init__(
352
+ self,
353
+ x0: float,
354
+ z0: float,
355
+ width: float,
356
+ depth: float,
357
+ height: float,
358
+ top_color: ManimColor,
359
+ opacity: float = 0.90,
360
+ edge_w: float = 0.6,
361
+ edge_op: float = 0.40,
362
+ ):
363
+ super().__init__()
364
+ h = max(height, 0.004)
365
+ s_w, s_d = width, depth
366
+
367
+ front_color = _dk(top_color, FACE_DARKEN_SIDE)
368
+ right_color = _dk(top_color, FACE_DARKEN_RIGHT)
369
+
370
+ # 8 corners
371
+ AFL = np.array([x0, 0, z0 ])
372
+ AFR = np.array([x0 + s_w, 0, z0 ])
373
+ ABL = np.array([x0, 0, z0 + s_d ])
374
+ ABR = np.array([x0 + s_w, 0, z0 + s_d ])
375
+ TFL = np.array([x0, h, z0 ])
376
+ TFR = np.array([x0 + s_w, h, z0 ])
377
+ TBL = np.array([x0, h, z0 + s_d ])
378
+ TBR = np.array([x0 + s_w, h, z0 + s_d ])
379
+
380
+ def _face(pts, color):
381
+ p = Polygon(*pts, color=color)
382
+ p.set_fill(color=color, opacity=opacity)
383
+ p.set_stroke(color=_dk(color, 0.50), width=edge_w, opacity=edge_op)
384
+ return p
385
+
386
+ self.top_face = _face([TFL, TFR, TBR, TBL], top_color)
387
+ self.front_face = _face([AFL, AFR, TFR, TFL], front_color)
388
+ self.right_face = _face([AFR, ABR, TBR, TFR], right_color)
389
+ self.add(self.front_face, self.right_face, self.top_face)
390
+
391
+ self._top_center = np.array([
392
+ x0 + width / 2,
393
+ h,
394
+ z0 + depth / 2,
395
+ ])
396
+
397
+ @property
398
+ def top_center(self) -> np.ndarray:
399
+ return self._top_center.copy()
400
+
401
+ @property
402
+ def floor_center(self) -> np.ndarray:
403
+ c = self._top_center.copy()
404
+ c[1] = 0.0
405
+ return c
406
+
407
+
408
+ # ---------------------------------------------------------------------------
409
+ # _PosteriorBracket — annotated bracket on the E+ edge of the Bayes box
410
+ # ---------------------------------------------------------------------------
411
+
412
+ class _PosteriorBracket(VGroup):
413
+ """A vertical bracket along the front edge of the E+ column,
414
+ labeled with the posterior probability P(H|E+)."""
415
+
416
+ def __init__(
417
+ self,
418
+ x0: float, # start of the TP cell
419
+ x1: float, # end of the TP cell (= start of FP cell at x1)
420
+ x2: float, # full width (x0 + total box width)
421
+ y_height: float, # height to draw the bracket
422
+ z_pos: float,
423
+ posterior: float,
424
+ font_size: int,
425
+ ):
426
+ super().__init__()
427
+
428
+ # Vertical ticks at x0, x1, x2
429
+ for xv, label, color in [
430
+ (x0, "", POSTERIOR_COLOR),
431
+ (x1, f"P(H|E⁺)\n= {posterior:.3f}", POSTERIOR_COLOR),
432
+ ]:
433
+ tick = Line3D(
434
+ start=np.array([xv, y_height, z_pos]),
435
+ end =np.array([xv, y_height + 0.20, z_pos]),
436
+ color=color, stroke_width=1.8,
437
+ )
438
+ self.add(tick)
439
+
440
+ # Horizontal bar from x0 → x1
441
+ horiz = Line3D(
442
+ start=np.array([x0, y_height + 0.20, z_pos]),
443
+ end =np.array([x1, y_height + 0.20, z_pos]),
444
+ color=POSTERIOR_COLOR, stroke_width=1.8,
445
+ )
446
+ self.add(horiz)
447
+
448
+ # Label
449
+ lbl = MathTex(
450
+ rf"P(H|E^+) = {posterior:.3f}",
451
+ color=POSTERIOR_COLOR,
452
+ font_size=font_size,
453
+ )
454
+ lbl.move_to(np.array([(x0 + x1) / 2, y_height + 0.55, z_pos]))
455
+ self.add(lbl)
456
+
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # BayesBox3D
460
+ # ---------------------------------------------------------------------------
461
+
462
+ class BayesBox3D(VGroup):
463
+ """2×2 Bayesian mosaic rendered as shaded 3D prisms.
464
+
465
+ The footprint of each prism encodes the joint probability
466
+ (width = P(H) or P(¬H), depth = P(E|H) or P(E|¬H)).
467
+ Height encodes the likelihood ratio of that cell, giving a 3D
468
+ "landscape" where tall peaks show the most diagnostic quadrants.
469
+
470
+ Layout (viewed from above):
471
+ ┌───────────────┬────────────────┐ ← E+ row (front, z=0)
472
+ │ TP P(H∩E+) │ FP P(¬H∩E+) │
473
+ ├───────────────┼────────────────┤ ← E− row (back)
474
+ │ FN P(H∩E−) │ TN P(¬H∩E−) │
475
+ └───────────────┴────────────────┘
476
+ H column ¬H column
477
+
478
+ Parameters
479
+ ----------
480
+ p_h : float
481
+ Prior P(H).
482
+ p_e_h : float
483
+ Sensitivity P(E+|H).
484
+ p_e_nh : float
485
+ False positive rate P(E+|¬H).
486
+ config : BayesConfig, optional
487
+ """
488
+
489
+ def __init__(
490
+ self,
491
+ p_h: float,
492
+ p_e_h: float,
493
+ p_e_nh: float,
494
+ config: BayesConfig | None = None,
495
+ ):
496
+ super().__init__()
497
+ self.cfg = config or BayesConfig()
498
+ self.stats = compute_joint_probs(
499
+ _clamp(p_h, 1e-4, 1 - 1e-4),
500
+ _clamp(p_e_h, 1e-4, 1 - 1e-4),
501
+ _clamp(p_e_nh, 1e-4, 1 - 1e-4),
502
+ )
503
+ self._build()
504
+
505
+ # ------------------------------------------------------------------
506
+
507
+ def _build(self) -> None:
508
+ cfg = self.cfg
509
+ s = self.stats
510
+ sx = cfg.box_scale_x
511
+ sz = cfg.box_scale_z
512
+ g = cfg.box_gap / 2
513
+
514
+ # Column widths (x axis = H vs ¬H)
515
+ w_h = s["p_h"] * sx
516
+ w_nh = s["p_nh"] * sx
517
+
518
+ # Row depths (z axis = E+ vs E−)
519
+ d_ep = s["p_e_h"] * sz # depth of E+ row for H column
520
+ d_en = (1 - s["p_e_h"]) * sz
521
+
522
+ d_fp = s["p_e_nh"] * sz # depth of E+ row for ¬H column
523
+ d_fn = (1 - s["p_e_nh"])* sz
524
+
525
+ # Cell heights (encode likelihood ratio of each cell)
526
+ # TP height = max_height (it is the most diagnostic)
527
+ # We scale by joint prob so larger cells don't dominate
528
+ max_h = cfg.box_max_height
529
+ lr = s["lr"]
530
+ cell_heights = {
531
+ "tp": max_h,
532
+ "fn": max_h * (1 / max(lr, 1.0)),
533
+ "fp": max_h * (1 / max(lr, 1.0)),
534
+ "tn": max_h * 0.30,
535
+ }
536
+
537
+ # ---- Four prisms --------------------------------------------
538
+ # TP: x ∈ [0, w_h], z ∈ [0, d_ep]
539
+ # FP: x ∈ [w_h+g, sx], z ∈ [0, d_fp]
540
+ # FN: x ∈ [0, w_h], z ∈ [d_ep+g, sz]
541
+ # TN: x ∈ [w_h+g, sx], z ∈ [d_fp+g, sz]
542
+
543
+ self.tp_cell = _ShadeBox(
544
+ x0=0, z0=0,
545
+ width=w_h - g, depth=d_ep - g,
546
+ height=cell_heights["tp"], top_color=TP_COLOR,
547
+ )
548
+ self.fp_cell = _ShadeBox(
549
+ x0=w_h + g, z0=0,
550
+ width=w_nh - g, depth=d_fp - g,
551
+ height=cell_heights["fp"], top_color=FP_COLOR,
552
+ )
553
+ self.fn_cell = _ShadeBox(
554
+ x0=0, z0=d_ep + g,
555
+ width=w_h - g, depth=d_en - g,
556
+ height=cell_heights["fn"], top_color=FN_COLOR,
557
+ )
558
+ self.tn_cell = _ShadeBox(
559
+ x0=w_h + g, z0=d_fp + g,
560
+ width=w_nh - g, depth=d_fn - g,
561
+ height=cell_heights["tn"], top_color=TN_COLOR,
562
+ )
563
+ self._cells = [self.tp_cell, self.fp_cell,
564
+ self.fn_cell, self.tn_cell]
565
+ for cell in self._cells:
566
+ self.add(cell)
567
+
568
+ # ---- Cell labels --------------------------------------------
569
+ self._cell_labels = VGroup()
570
+ if cfg.show_cell_labels:
571
+ cell_data = [
572
+ (self.tp_cell, "TP", s["tp"], WHITE),
573
+ (self.fp_cell, "FP", s["fp"], WHITE),
574
+ (self.fn_cell, "FN", s["fn"], WHITE),
575
+ (self.tn_cell, "TN", s["tn"], WHITE),
576
+ ]
577
+ for cell, name, prob, color in cell_data:
578
+ tc = cell.top_center
579
+ # Name tag
580
+ tag = Text(name, color=color, font_size=cfg.cell_label_font_size + 4,
581
+ weight="BOLD")
582
+ tag.move_to(tc + np.array([0, 0.22, 0]))
583
+ # Probability value
584
+ val = MathTex(
585
+ rf"{prob:.4f}",
586
+ color=_lt(color, 0.30),
587
+ font_size=cfg.cell_label_font_size,
588
+ )
589
+ val.move_to(tc + np.array([0, 0.50, 0]))
590
+ self._cell_labels.add(tag, val)
591
+ self.add(self._cell_labels)
592
+
593
+ # ---- Axis dimension labels ----------------------------------
594
+ self._axis_labels = VGroup()
595
+ if cfg.show_axis_labels:
596
+ # H / ¬H labels on x axis (at z = sz + 0.3)
597
+ h_lbl = MathTex(
598
+ rf"P(H) = {s['p_h']:.2f}",
599
+ color=H_TRUE_COLOR,
600
+ font_size=cfg.axis_label_font_size,
601
+ )
602
+ h_lbl.move_to(np.array([w_h / 2, -0.15, sz + 0.45]))
603
+
604
+ nh_lbl = MathTex(
605
+ rf"P(\neg H) = {s['p_nh']:.2f}",
606
+ color=H_FALSE_COLOR,
607
+ font_size=cfg.axis_label_font_size,
608
+ )
609
+ nh_lbl.move_to(np.array([w_h + w_nh / 2, -0.15, sz + 0.45]))
610
+
611
+ # P(E+|H) / P(E+|¬H) labels on z axis (at x = -0.3)
612
+ ep_h_lbl = MathTex(
613
+ rf"P(E^+|H) = {s['p_e_h']:.2f}",
614
+ color=E_POS_COLOR,
615
+ font_size=cfg.axis_label_font_size,
616
+ )
617
+ ep_h_lbl.move_to(np.array([-1.10, -0.10, d_ep / 2]))
618
+
619
+ ep_nh_lbl = MathTex(
620
+ rf"P(E^+|\neg H) = {s['p_e_nh']:.2f}",
621
+ color=FP_COLOR,
622
+ font_size=cfg.axis_label_font_size,
623
+ )
624
+ ep_nh_lbl.move_to(np.array([-1.30, -0.10, d_fp / 2]))
625
+
626
+ # LR badge
627
+ lr_color = LR_POS_COLOR if s["lr"] > 1 else (
628
+ LR_NEG_COLOR if s["lr"] < 1 else LR_NULL_COLOR
629
+ )
630
+ lr_lbl = MathTex(
631
+ rf"LR = {s['lr']:.2f}",
632
+ color=lr_color,
633
+ font_size=cfg.axis_label_font_size + 4,
634
+ )
635
+ lr_lbl.move_to(np.array([sx / 2, cfg.box_max_height + 0.55, sz / 2]))
636
+
637
+ self._axis_labels.add(h_lbl, nh_lbl, ep_h_lbl, ep_nh_lbl, lr_lbl)
638
+ self.add(self._axis_labels)
639
+
640
+ # ---- Posterior bracket --------------------------------------
641
+ self._posterior_bracket: _PosteriorBracket | None = None
642
+ if cfg.show_posterior_bracket:
643
+ self._posterior_bracket = _PosteriorBracket(
644
+ x0=0,
645
+ x1=w_h,
646
+ x2=sx,
647
+ y_height=cell_heights["tp"] + 0.05,
648
+ z_pos=0.0,
649
+ posterior=s["posterior"],
650
+ font_size=cfg.axis_label_font_size,
651
+ )
652
+ self.add(self._posterior_bracket)
653
+
654
+ # Store metrics for animations
655
+ self._w_h = w_h
656
+ self._sx = sx
657
+ self._sz = sz
658
+ self._d_ep = d_ep
659
+
660
+ # ------------------------------------------------------------------
661
+ # Animations
662
+ # ------------------------------------------------------------------
663
+
664
+ def animate_build_box(
665
+ self,
666
+ lag_ratio: float = 0.20,
667
+ run_time: float = 2.5,
668
+ ) -> LaggedStart:
669
+ """Cells rise from the floor one by one: TP → FP → FN → TN.
670
+
671
+ The build order conveys the structure: first the diagnostic
672
+ cells (high evidence value), then the irrelevant ones.
673
+ """
674
+ order = [self.tp_cell, self.fp_cell, self.fn_cell, self.tn_cell]
675
+ return LaggedStart(
676
+ *[GrowFromPoint(cell, point=cell.floor_center, run_time=run_time * 0.6)
677
+ for cell in order],
678
+ lag_ratio=lag_ratio,
679
+ run_time=run_time,
680
+ )
681
+
682
+ def animate_highlight_cell(
683
+ self,
684
+ cell_name: str,
685
+ highlight_color: ManimColor = YELLOW,
686
+ scale_factor: float = 1.10,
687
+ run_time: float = 0.55,
688
+ ) -> Succession:
689
+ """Flash and scale one cell.
690
+
691
+ Parameters
692
+ ----------
693
+ cell_name : str
694
+ One of ``"tp"``, ``"fp"``, ``"fn"``, ``"tn"``.
695
+ """
696
+ cell_map = {"tp": self.tp_cell, "fp": self.fp_cell,
697
+ "fn": self.fn_cell, "tn": self.tn_cell}
698
+ cell = cell_map[cell_name.lower()]
699
+ orig_top = cell.top_face.get_fill_color()
700
+ orig_front = cell.front_face.get_fill_color()
701
+ orig_right = cell.right_face.get_fill_color()
702
+
703
+ flash = AnimationGroup(
704
+ cell.animate(run_time=run_time / 2).scale(scale_factor),
705
+ cell.top_face.animate(run_time=run_time / 2)
706
+ .set_fill(color=highlight_color),
707
+ )
708
+ restore = AnimationGroup(
709
+ cell.animate(run_time=run_time / 2).scale(1 / scale_factor),
710
+ cell.top_face.animate(run_time=run_time / 2)
711
+ .set_fill(color=orig_top),
712
+ )
713
+ return Succession(flash, restore)
714
+
715
+ def animate_reveal_posterior(
716
+ self,
717
+ run_time: float = 1.0,
718
+ ) -> FadeIn:
719
+ """Fade the posterior bracket annotation into view."""
720
+ if self._posterior_bracket is None:
721
+ return FadeIn(VGroup(), run_time=0.1)
722
+ return FadeIn(self._posterior_bracket, run_time=run_time)
723
+
724
+ def animate_sweep_evidence(
725
+ self,
726
+ run_time: float = 1.2,
727
+ lag_ratio: float = 0.30,
728
+ ) -> LaggedStart:
729
+ """Color-wave sweep across the E+ column (TP + FP) then dim E−.
730
+
731
+ Visually "selects" the positive-evidence partition to show
732
+ how only the E+ column contributes to the posterior.
733
+ """
734
+ return LaggedStart(
735
+ self.tp_cell.animate(run_time=run_time * 0.5)
736
+ .set_fill(color=E_POS_COLOR),
737
+ self.fp_cell.animate(run_time=run_time * 0.5)
738
+ .set_fill(color=_lt(E_POS_COLOR, 0.45)),
739
+ AnimationGroup(
740
+ self.fn_cell.animate(run_time=run_time * 0.4)
741
+ .set_opacity(0.25),
742
+ self.tn_cell.animate(run_time=run_time * 0.4)
743
+ .set_opacity(0.25),
744
+ ),
745
+ lag_ratio=lag_ratio,
746
+ run_time=run_time,
747
+ )
748
+
749
+
750
+ # ---------------------------------------------------------------------------
751
+ # PriorPosteriorBar3D
752
+ # ---------------------------------------------------------------------------
753
+
754
+ class PriorPosteriorBar3D(VGroup):
755
+ """A vertical probability bar split into H (bottom) and ¬H (top) bands.
756
+
757
+ The bar height represents the full probability space [0, 1].
758
+ The split point encodes P(H). After calling animate_update(),
759
+ the split morphs to the posterior P(H|E).
760
+
761
+ Parameters
762
+ ----------
763
+ p_h : float
764
+ Initial prior P(H) — height of the blue (H) band.
765
+ x_pos : float
766
+ World X position of the bar center.
767
+ config : BayesConfig, optional
768
+ """
769
+
770
+ def __init__(
771
+ self,
772
+ p_h: float,
773
+ x_pos: float = 0.0,
774
+ config: BayesConfig | None = None,
775
+ ):
776
+ super().__init__()
777
+ self.cfg = config or BayesConfig()
778
+ self._p_h = _clamp(p_h)
779
+ self._x_pos = x_pos
780
+ self._build(p_h=p_h, animate=False)
781
+
782
+ def _build(self, p_h: float, animate: bool = False) -> None:
783
+ cfg = self.cfg
784
+ p_h = _clamp(p_h)
785
+ p_nh = 1 - p_h
786
+ w = cfg.bar_width
787
+ d = cfg.bar_depth
788
+ H = cfg.bar_max_height
789
+ xc = self._x_pos - w / 2
790
+ zc = -d / 2
791
+
792
+ h_h = H * p_h
793
+ h_nh = H * p_nh
794
+
795
+ self.h_band = _ShadeBox(
796
+ x0=xc, z0=zc,
797
+ width=w, depth=d,
798
+ height=h_h,
799
+ top_color=H_TRUE_COLOR,
800
+ )
801
+ self.nh_band = _ShadeBox(
802
+ x0=xc, z0=zc,
803
+ width=w, depth=d,
804
+ height=h_nh,
805
+ top_color=H_FALSE_COLOR,
806
+ )
807
+ # ¬H sits on top of H
808
+ self.nh_band.shift(np.array([0, h_h, 0]))
809
+
810
+ self.add(self.h_band, self.nh_band)
811
+
812
+ # Dividing line at the split
813
+ self._split_line = Line3D(
814
+ start=np.array([xc, h_h, zc ]),
815
+ end =np.array([xc + w, h_h, zc + d]),
816
+ color=WHITE, stroke_width=1.8,
817
+ )
818
+ self.add(self._split_line)
819
+
820
+ # Probability labels
821
+ self._bar_labels = VGroup()
822
+ if cfg.show_probability_labels:
823
+ lbl_h = MathTex(
824
+ rf"P(H) = {p_h:.3f}",
825
+ color=_lt(H_TRUE_COLOR, 0.30),
826
+ font_size=cfg.font_size,
827
+ )
828
+ lbl_h.move_to(np.array([xc + w + 0.55, h_h / 2, 0]))
829
+
830
+ lbl_nh = MathTex(
831
+ rf"P(\neg H) = {p_nh:.3f}",
832
+ color=_lt(H_FALSE_COLOR, 0.30),
833
+ font_size=cfg.font_size,
834
+ )
835
+ lbl_nh.move_to(np.array([xc + w + 0.65, h_h + h_nh / 2, 0]))
836
+
837
+ self._bar_labels.add(lbl_h, lbl_nh)
838
+ self.add(self._bar_labels)
839
+
840
+ # Y axis tick marks at 0, 0.25, 0.5, 0.75, 1.0
841
+ self._ticks = VGroup()
842
+ ax_x = xc - 0.12
843
+ for frac in [0.0, 0.25, 0.50, 0.75, 1.0]:
844
+ yw = frac * H
845
+ tick = Line3D(
846
+ start=np.array([ax_x, yw, 0]),
847
+ end =np.array([ax_x - 0.12, yw, 0]),
848
+ color=cfg.axes_color, stroke_width=0.8,
849
+ )
850
+ lbl = Text(f"{frac:.2f}", color=cfg.axes_color,
851
+ font_size=cfg.font_size - 4)
852
+ lbl.move_to(np.array([ax_x - 0.38, yw, 0]))
853
+ self._ticks.add(tick, lbl)
854
+ self.add(self._ticks)
855
+
856
+ self._h_h = h_h
857
+ self._h_nh = h_nh
858
+
859
+ # ------------------------------------------------------------------
860
+
861
+ def animate_build(self, run_time: float = 1.5) -> LaggedStart:
862
+ """Grow the bar from the floor upward: H band first, then ¬H."""
863
+ return LaggedStart(
864
+ GrowFromPoint(self.h_band, point=self.h_band.floor_center,
865
+ run_time=run_time * 0.55),
866
+ GrowFromPoint(self.nh_band, point=self.h_band.top_center,
867
+ run_time=run_time * 0.45),
868
+ lag_ratio=0.40,
869
+ run_time=run_time,
870
+ )
871
+
872
+ def animate_update(
873
+ self,
874
+ p_h_new: float,
875
+ run_time: float = 1.5,
876
+ ) -> AnimationGroup:
877
+ """Morph the bar split from the current prior to a new probability.
878
+
879
+ Typically called with the posterior after seeing evidence::
880
+
881
+ post = bayes_update(prior=0.01, lr=10.0)
882
+ self.play(bar.animate_update(p_h_new=post))
883
+ """
884
+ cfg = self.cfg
885
+ p_h_new = _clamp(p_h_new)
886
+ H = cfg.bar_max_height
887
+ xc = self._x_pos - cfg.bar_width / 2
888
+ zc = -cfg.bar_depth / 2
889
+
890
+ # Build target geometry objects
891
+ target_h = _ShadeBox(
892
+ x0=xc, z0=zc,
893
+ width=cfg.bar_width, depth=cfg.bar_depth,
894
+ height=H * p_h_new,
895
+ top_color=H_TRUE_COLOR,
896
+ )
897
+ target_nh = _ShadeBox(
898
+ x0=xc, z0=zc,
899
+ width=cfg.bar_width, depth=cfg.bar_depth,
900
+ height=H * (1 - p_h_new),
901
+ top_color=H_FALSE_COLOR,
902
+ )
903
+ target_nh.shift(np.array([0, H * p_h_new, 0]))
904
+
905
+ new_split = Line3D(
906
+ start=np.array([xc, H * p_h_new, zc ]),
907
+ end =np.array([xc + cfg.bar_width, H * p_h_new, zc + cfg.bar_depth]),
908
+ color=POSTERIOR_COLOR, stroke_width=2.2,
909
+ )
910
+
911
+ return AnimationGroup(
912
+ Transform(self.h_band, target_h, run_time=run_time),
913
+ Transform(self.nh_band, target_nh, run_time=run_time),
914
+ Transform(self._split_line, new_split, run_time=run_time),
915
+ )
916
+
917
+
918
+ # ---------------------------------------------------------------------------
919
+ # LikelihoodPanel3D
920
+ # ---------------------------------------------------------------------------
921
+
922
+ class LikelihoodPanel3D(VGroup):
923
+ """Side-by-side bars for P(E|H) and P(E|¬H) with an LR bracket.
924
+
925
+ Parameters
926
+ ----------
927
+ p_e_h : float
928
+ P(E+|H) — sensitivity.
929
+ p_e_nh : float
930
+ P(E+|¬H) — false positive rate.
931
+ x_pos : float
932
+ World X of the panel centre.
933
+ config : BayesConfig, optional
934
+ """
935
+
936
+ def __init__(
937
+ self,
938
+ p_e_h: float,
939
+ p_e_nh: float,
940
+ x_pos: float = 0.0,
941
+ config: BayesConfig | None = None,
942
+ ):
943
+ super().__init__()
944
+ self.cfg = config or BayesConfig()
945
+ self.p_e_h = _clamp(p_e_h)
946
+ self.p_e_nh = _clamp(p_e_nh)
947
+ self._x_pos = x_pos
948
+ self._build()
949
+
950
+ def _build(self) -> None:
951
+ cfg = self.cfg
952
+ H = cfg.lr_max_height
953
+ w = cfg.lr_bar_width
954
+ sp = cfg.lr_bar_spacing
955
+ d = 0.30
956
+ xc = self._x_pos - (w + sp / 2)
957
+
958
+ # P(E|H) bar
959
+ self.h_bar = _ShadeBox(
960
+ x0=xc, z0=-d / 2,
961
+ width=w, depth=d,
962
+ height=H * self.p_e_h,
963
+ top_color=E_POS_COLOR,
964
+ )
965
+ # P(E|¬H) bar
966
+ self.nh_bar = _ShadeBox(
967
+ x0=xc + w + sp, z0=-d / 2,
968
+ width=w, depth=d,
969
+ height=H * self.p_e_nh,
970
+ top_color=FP_COLOR,
971
+ )
972
+ self.add(self.h_bar, self.nh_bar)
973
+
974
+ # Bar labels underneath
975
+ for bar, text, color in [
976
+ (self.h_bar, rf"P(E^+|H)\n= {self.p_e_h:.3f}", E_POS_COLOR),
977
+ (self.nh_bar, rf"P(E^+|\neg H)\n= {self.p_e_nh:.3f}", FP_COLOR),
978
+ ]:
979
+ fc = bar.floor_center
980
+ lbl = MathTex(text, color=color, font_size=cfg.font_size - 2)
981
+ lbl.move_to(fc + np.array([0, -0.35, 0]))
982
+ self.add(lbl)
983
+
984
+ # LR bracket + value
985
+ self._lr_bracket = VGroup()
986
+ if cfg.show_lr_bracket:
987
+ lr = self.p_e_h / max(self.p_e_nh, 1e-9)
988
+ y_tp = H * self.p_e_h + 0.12
989
+ y_fp = H * self.p_e_nh + 0.12
990
+ y_brk = max(y_tp, y_fp) + 0.20
991
+
992
+ lr_color = LR_POS_COLOR if lr > 1 else (
993
+ LR_NEG_COLOR if lr < 1 else LR_NULL_COLOR
994
+ )
995
+ x_left = xc + w / 2
996
+ x_right = xc + w + sp + w / 2
997
+
998
+ for xv in [x_left, x_right]:
999
+ tick = Line3D(
1000
+ start=np.array([xv, y_brk - 0.12, 0]),
1001
+ end =np.array([xv, y_brk, 0]),
1002
+ color=lr_color, stroke_width=1.6,
1003
+ )
1004
+ self._lr_bracket.add(tick)
1005
+
1006
+ horiz = Line3D(
1007
+ start=np.array([x_left, y_brk, 0]),
1008
+ end =np.array([x_right, y_brk, 0]),
1009
+ color=lr_color, stroke_width=1.6,
1010
+ )
1011
+ self._lr_bracket.add(horiz)
1012
+
1013
+ lr_lbl = MathTex(
1014
+ rf"LR = \frac{{P(E^+|H)}}{{P(E^+|\neg H)}} = {lr:.2f}",
1015
+ color=lr_color,
1016
+ font_size=cfg.font_size,
1017
+ )
1018
+ lr_lbl.move_to(np.array([(x_left + x_right) / 2, y_brk + 0.45, 0]))
1019
+ self._lr_bracket.add(lr_lbl)
1020
+ self.add(self._lr_bracket)
1021
+
1022
+ # ------------------------------------------------------------------
1023
+
1024
+ def animate_build(self, run_time: float = 1.5) -> AnimationGroup:
1025
+ """Both bars grow simultaneously from the floor."""
1026
+ return AnimationGroup(
1027
+ GrowFromPoint(self.h_bar, self.h_bar.floor_center, run_time=run_time),
1028
+ GrowFromPoint(self.nh_bar, self.nh_bar.floor_center, run_time=run_time),
1029
+ )
1030
+
1031
+ def animate_highlight_lr(
1032
+ self,
1033
+ run_time: float = 0.8,
1034
+ ) -> Succession:
1035
+ """Pulse the LR bracket to draw attention to the ratio."""
1036
+ bright = self._lr_bracket.animate(run_time=run_time / 2).scale(1.12)
1037
+ dim = self._lr_bracket.animate(run_time=run_time / 2).scale(1 / 1.12)
1038
+ return Succession(bright, dim)
1039
+
1040
+
1041
+ # ---------------------------------------------------------------------------
1042
+ # NaturalFrequencyTree3D
1043
+ # ---------------------------------------------------------------------------
1044
+
1045
+ class NaturalFrequencyTree3D(VGroup):
1046
+ """A tree of prisms where branch area encodes absolute count.
1047
+
1048
+ Structure
1049
+ ---------
1050
+ Level 0 (root) : N people total
1051
+ Level 1 (H/¬H) : N·P(H) with H | N·P(¬H) without H
1052
+ Level 2 (E/¬E) : each level-1 branch splits by P(E|·)
1053
+
1054
+ Leaf nodes (level 2) show icon-array dot grids if
1055
+ ``config.show_icon_arrays = True``.
1056
+
1057
+ Parameters
1058
+ ----------
1059
+ p_h : float
1060
+ p_e_h : float
1061
+ p_e_nh : float
1062
+ config : BayesConfig, optional
1063
+ """
1064
+
1065
+ def __init__(
1066
+ self,
1067
+ p_h: float,
1068
+ p_e_h: float,
1069
+ p_e_nh: float,
1070
+ config: BayesConfig | None = None,
1071
+ ):
1072
+ super().__init__()
1073
+ self.cfg = config or BayesConfig()
1074
+ self.stats = compute_joint_probs(
1075
+ _clamp(p_h, 1e-4, 1 - 1e-4),
1076
+ _clamp(p_e_h, 1e-4, 1 - 1e-4),
1077
+ _clamp(p_e_nh, 1e-4, 1 - 1e-4),
1078
+ )
1079
+ self._build()
1080
+
1081
+ def _build(self) -> None:
1082
+ cfg = self.cfg
1083
+ s = self.stats
1084
+ N = cfg.tree_population
1085
+ ls = cfg.tree_level_spacing
1086
+ mw = cfg.tree_max_width
1087
+ g = cfg.tree_branch_gap
1088
+ d = 0.28 # uniform prism depth
1089
+
1090
+ # Counts at each node
1091
+ n_h = round(N * s["p_h"])
1092
+ n_nh = N - n_h
1093
+ n_tp = round(n_h * s["p_e_h"])
1094
+ n_fn = n_h - n_tp
1095
+ n_fp = round(n_nh * s["p_e_nh"])
1096
+ n_tn = n_nh - n_fp
1097
+
1098
+ # Width proportional to count / N
1099
+ def _w(n): return mw * (n / N)
1100
+
1101
+ # ---- Level 0: root ------------------------------------------
1102
+ root_w = mw
1103
+ root_x0 = -root_w / 2
1104
+ self.root_bar = _ShadeBox(
1105
+ x0=root_x0, z0=-d / 2,
1106
+ width=root_w, depth=d,
1107
+ height=0.30,
1108
+ top_color=GRAY_C,
1109
+ )
1110
+ self.add(self.root_bar)
1111
+ self._add_count_label(self.root_bar, N, GRAY_B, cfg.font_size)
1112
+
1113
+ # ---- Connector line from root to level 1 --------------------
1114
+ root_top_x = 0.0
1115
+ y_root_top = 0.30
1116
+
1117
+ # ---- Level 1: H and ¬H --------------------------------------
1118
+ w_h = _w(n_h)
1119
+ w_nh = _w(n_nh)
1120
+ total_l1_w = w_h + g + w_nh
1121
+ x0_h = -total_l1_w / 2
1122
+ x0_nh = x0_h + w_h + g
1123
+ y1 = -(ls)
1124
+
1125
+ self.h_bar = _ShadeBox(
1126
+ x0=x0_h, z0=-d / 2,
1127
+ width=w_h, depth=d, height=0.30,
1128
+ top_color=H_TRUE_COLOR,
1129
+ )
1130
+ self.nh_bar = _ShadeBox(
1131
+ x0=x0_nh, z0=-d / 2,
1132
+ width=w_nh, depth=d, height=0.30,
1133
+ top_color=H_FALSE_COLOR,
1134
+ )
1135
+ for bar in [self.h_bar, self.nh_bar]:
1136
+ bar.shift(np.array([0, y1, 0]))
1137
+ self.add(self.h_bar, self.nh_bar)
1138
+ self._add_count_label(self.h_bar, n_h, H_TRUE_COLOR, cfg.font_size)
1139
+ self._add_count_label(self.nh_bar, n_nh, H_FALSE_COLOR, cfg.font_size)
1140
+
1141
+ # Connectors: root → h_bar centre, root → nh_bar centre
1142
+ for bar, name in [(self.h_bar, "H"), (self.nh_bar, "¬H")]:
1143
+ fc = bar.floor_center
1144
+ conn = Line3D(
1145
+ start=np.array([0, y_root_top, 0]),
1146
+ end =np.array([fc[0], y1 + 0.30, 0]),
1147
+ color=GRAY_C, stroke_width=1.2,
1148
+ )
1149
+ self.add(conn)
1150
+ mid = (np.array([0, y_root_top, 0]) + fc) / 2
1151
+ lbl = Text(name,
1152
+ color=H_TRUE_COLOR if name == "H" else H_FALSE_COLOR,
1153
+ font_size=cfg.font_size - 2)
1154
+ lbl.move_to(mid + np.array([0.22, 0, 0]))
1155
+ self.add(lbl)
1156
+
1157
+ # ---- Level 2: four leaf nodes (TP, FN, FP, TN) --------------
1158
+ y2 = y1 - ls
1159
+ gap2 = g * 0.7
1160
+
1161
+ nodes_l2 = [
1162
+ (n_tp, TP_COLOR, x0_h, "TP", "E+|H", s["tp"]),
1163
+ (n_fn, FN_COLOR, x0_h + _w(n_tp) + gap2, "FN", "E−|H", s["fn"]),
1164
+ (n_fp, FP_COLOR, x0_nh, "FP", "E+|¬H", s["fp"]),
1165
+ (n_tn, TN_COLOR, x0_nh + _w(n_fp) + gap2, "TN", "E−|¬H", s["tn"]),
1166
+ ]
1167
+ self.leaf_bars = []
1168
+ for count, color, xstart, name, branch_lbl, prob in nodes_l2:
1169
+ if count == 0:
1170
+ continue
1171
+ w_leaf = _w(count)
1172
+ bar = _ShadeBox(
1173
+ x0=xstart, z0=-d / 2,
1174
+ width=w_leaf, depth=d, height=0.30,
1175
+ top_color=color,
1176
+ )
1177
+ bar.shift(np.array([0, y2, 0]))
1178
+ self.add(bar)
1179
+ self.leaf_bars.append(bar)
1180
+ self._add_count_label(bar, count, WHITE, cfg.font_size - 2)
1181
+
1182
+ # Branch label
1183
+ branch_lbl_obj = Text(
1184
+ f"{branch_lbl}\n{prob:.4f}",
1185
+ color=color, font_size=cfg.font_size - 4,
1186
+ )
1187
+ branch_lbl_obj.move_to(
1188
+ bar.floor_center + np.array([0, -0.50, 0])
1189
+ )
1190
+ self.add(branch_lbl_obj)
1191
+
1192
+ # Connector from parent level-1 bar
1193
+ parent_bar = self.h_bar if name in ("TP", "FN") else self.nh_bar
1194
+ conn = Line3D(
1195
+ start=parent_bar.floor_center + np.array([0, y1, 0]),
1196
+ end =bar.floor_center + np.array([0, 0.30, 0]),
1197
+ color=GRAY_C, stroke_width=1.0,
1198
+ )
1199
+ self.add(conn)
1200
+
1201
+ # Icon array in leaf
1202
+ if cfg.show_icon_arrays and count > 0:
1203
+ self._build_icon_array(bar, count, N, color)
1204
+
1205
+ # Posterior annotation
1206
+ if n_tp + n_fp > 0:
1207
+ post_pct = n_tp / (n_tp + n_fp)
1208
+ post_lbl = MathTex(
1209
+ rf"P(H|E^+) = \frac{{{n_tp}}}{{{n_tp + n_fp}}} = {post_pct:.3f}",
1210
+ color=POSTERIOR_COLOR,
1211
+ font_size=cfg.font_size,
1212
+ )
1213
+ post_lbl.move_to(np.array([0, y2 - 0.70, 0]))
1214
+ self.add(post_lbl)
1215
+
1216
+ def _add_count_label(
1217
+ self,
1218
+ bar: _ShadeBox,
1219
+ count: int,
1220
+ color: ManimColor,
1221
+ font_size: int,
1222
+ ) -> None:
1223
+ lbl = Text(f"n = {count}", color=color, font_size=font_size)
1224
+ lbl.move_to(bar.top_center + np.array([0, 0.22, 0]))
1225
+ self.add(lbl)
1226
+
1227
+ def _build_icon_array(
1228
+ self,
1229
+ bar: _ShadeBox,
1230
+ count: int,
1231
+ total: int,
1232
+ color: ManimColor,
1233
+ ) -> None:
1234
+ """Draw a small grid of dots inside the leaf bar footprint."""
1235
+ cfg = self.cfg
1236
+ max_dots = 25 # cap for visual clarity
1237
+ n_dots = min(count, max_dots)
1238
+ radius = cfg.icon_radius
1239
+ tc = bar.top_center
1240
+ cols = min(n_dots, 5)
1241
+ rows = (n_dots + cols - 1) // cols
1242
+ spacing = radius * 2.8
1243
+ x_start = tc[0] - (cols - 1) * spacing / 2
1244
+ z_pos = tc[2]
1245
+
1246
+ for k in range(n_dots):
1247
+ row_k = k // cols
1248
+ col_k = k % cols
1249
+ dot = Dot3D(
1250
+ point=np.array([
1251
+ x_start + col_k * spacing,
1252
+ tc[1] + 0.12 + row_k * spacing,
1253
+ z_pos,
1254
+ ]),
1255
+ radius=radius,
1256
+ color=color,
1257
+ )
1258
+ dot.set_opacity(0.85)
1259
+ self.add(dot)
1260
+
1261
+ # ------------------------------------------------------------------
1262
+
1263
+ def animate_grow_tree(
1264
+ self,
1265
+ run_time: float = 3.0,
1266
+ ) -> Succession:
1267
+ """Extend branches level by level: root → L1 → L2."""
1268
+ root_anim = GrowFromPoint(
1269
+ self.root_bar, self.root_bar.floor_center,
1270
+ run_time=run_time * 0.25,
1271
+ )
1272
+ l1_anim = AnimationGroup(
1273
+ GrowFromPoint(self.h_bar, self.h_bar.floor_center,
1274
+ run_time=run_time * 0.35),
1275
+ GrowFromPoint(self.nh_bar, self.nh_bar.floor_center,
1276
+ run_time=run_time * 0.35),
1277
+ )
1278
+ l2_anim = LaggedStart(
1279
+ *[GrowFromPoint(bar, bar.floor_center, run_time=run_time * 0.30)
1280
+ for bar in self.leaf_bars],
1281
+ lag_ratio=0.20,
1282
+ run_time=run_time * 0.40,
1283
+ )
1284
+ return Succession(root_anim, l1_anim, l2_anim)
1285
+
1286
+
1287
+ # ---------------------------------------------------------------------------
1288
+ # SequentialBayesUpdater3D
1289
+ # ---------------------------------------------------------------------------
1290
+
1291
+ class SequentialBayesUpdater3D(VGroup):
1292
+ """A probability axis with a marker that updates with each evidence.
1293
+
1294
+ Maintains a running prior. Each call to animate_add_evidence()
1295
+ returns an animation that moves the marker and records a ghost.
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ prior : float
1300
+ Starting prior P(H).
1301
+ x_center : float
1302
+ World X of the axis center.
1303
+ y_pos : float
1304
+ World Y of the axis.
1305
+ config : BayesConfig, optional
1306
+ """
1307
+
1308
+ def __init__(
1309
+ self,
1310
+ prior: float,
1311
+ x_center: float = 0.0,
1312
+ y_pos: float = 0.0,
1313
+ config: BayesConfig | None = None,
1314
+ ):
1315
+ super().__init__()
1316
+ self.cfg = config or BayesConfig()
1317
+ self._prior = _clamp(prior)
1318
+ self._x_center = x_center
1319
+ self._y = y_pos
1320
+ self._history: list[float] = [self._prior]
1321
+ self._build()
1322
+
1323
+ def _build(self) -> None:
1324
+ cfg = self.cfg
1325
+ L = cfg.axis_length
1326
+ x0 = self._x_center - L / 2
1327
+ x1 = self._x_center + L / 2
1328
+ y = self._y
1329
+
1330
+ # Axis line
1331
+ axis = Line3D(
1332
+ start=np.array([x0, y, 0]),
1333
+ end =np.array([x1, y, 0]),
1334
+ color=cfg.axes_color, stroke_width=1.5,
1335
+ )
1336
+ self.add(axis)
1337
+
1338
+ # Tick marks and labels at 0, 0.1, ..., 1.0
1339
+ for k in range(11):
1340
+ t = k / 10
1341
+ xv = x0 + t * L
1342
+ tick = Line3D(
1343
+ start=np.array([xv, y, 0]),
1344
+ end =np.array([xv, y - 0.10, 0]),
1345
+ color=cfg.axes_color, stroke_width=0.8,
1346
+ )
1347
+ lbl = Text(f"{t:.1f}", color=cfg.axes_color,
1348
+ font_size=cfg.font_size - 6)
1349
+ lbl.move_to(np.array([xv, y - 0.28, 0]))
1350
+ self.add(tick, lbl)
1351
+
1352
+ # Axis label
1353
+ axis_lbl = MathTex(r"P(H)", color=cfg.axes_color,
1354
+ font_size=cfg.font_size)
1355
+ axis_lbl.move_to(np.array([x1 + 0.50, y, 0]))
1356
+ self.add(axis_lbl)
1357
+
1358
+ # Prior marker
1359
+ self._marker = self._make_marker(
1360
+ self._prior, POSTERIOR_COLOR, cfg.marker_radius
1361
+ )
1362
+ self.add(self._marker)
1363
+
1364
+ # Ghosts group
1365
+ self._ghosts = VGroup()
1366
+ self.add(self._ghosts)
1367
+
1368
+ # BF label group
1369
+ self._bf_labels = VGroup()
1370
+ self.add(self._bf_labels)
1371
+
1372
+ self._x0 = x0
1373
+ self._L = L
1374
+
1375
+ def _prob_to_x(self, p: float) -> float:
1376
+ return self._x0 + _clamp(p) * self._L
1377
+
1378
+ def _make_marker(
1379
+ self,
1380
+ p: float,
1381
+ color: ManimColor,
1382
+ radius: float,
1383
+ ) -> Sphere:
1384
+ m = Sphere(radius=radius, resolution=(10, 10))
1385
+ m.set_color(color)
1386
+ m.set_opacity(0.95)
1387
+ m.move_to(np.array([self._prob_to_x(p), self._y, 0]))
1388
+ return m
1389
+
1390
+ # ------------------------------------------------------------------
1391
+
1392
+ def animate_axis(self, run_time: float = 1.0) -> FadeIn:
1393
+ """Fade the axis and prior marker into view."""
1394
+ return FadeIn(self, run_time=run_time)
1395
+
1396
+ def animate_add_evidence(
1397
+ self,
1398
+ lr: float,
1399
+ label: str = "",
1400
+ run_time: float = 1.2,
1401
+ ) -> Succession:
1402
+ """Apply one Bayesian update and animate the marker shift.
1403
+
1404
+ A ghost marker is left at the old position.
1405
+ A Bayes factor annotation appears above the axis.
1406
+
1407
+ Parameters
1408
+ ----------
1409
+ lr : float
1410
+ Likelihood ratio P(E|H) / P(E|¬H) for this piece of evidence.
1411
+ label : str
1412
+ Optional label for this evidence item (e.g. "Test +").
1413
+
1414
+ Returns a ``Succession`` animation::
1415
+
1416
+ for lr in [10.0, 5.0, 0.2]:
1417
+ self.play(updater.animate_add_evidence(lr))
1418
+ """
1419
+ cfg = self.cfg
1420
+ old_p = self._prior
1421
+ new_p = bayes_update(old_p, lr)
1422
+ self._prior = new_p
1423
+ self._history.append(new_p)
1424
+
1425
+ # Ghost at old position
1426
+ ghost = self._make_marker(old_p, PRIOR_COLOR, cfg.marker_radius * 0.75)
1427
+ ghost.set_opacity(cfg.ghost_opacity)
1428
+ self._ghosts.add(ghost)
1429
+
1430
+ # Connecting trail line old → new
1431
+ old_x = self._prob_to_x(old_p)
1432
+ new_x = self._prob_to_x(new_p)
1433
+ trail = Line3D(
1434
+ start=np.array([old_x, self._y, 0]),
1435
+ end =np.array([new_x, self._y, 0]),
1436
+ color=POSTERIOR_COLOR, stroke_width=1.8,
1437
+ )
1438
+
1439
+ # Bayes factor label above the midpoint
1440
+ bf_color = LR_POS_COLOR if lr > 1 else (
1441
+ LR_NEG_COLOR if lr < 1 else LR_NULL_COLOR
1442
+ )
1443
+ bf_text = f"LR = {lr:.2f}"
1444
+ if label:
1445
+ bf_text = f"{label}: {bf_text}"
1446
+ bf_lbl = Text(bf_text, color=bf_color, font_size=cfg.font_size - 4)
1447
+ mid_x = (old_x + new_x) / 2
1448
+ bf_lbl.move_to(np.array([mid_x, self._y + 0.45, 0]))
1449
+ self._bf_labels.add(bf_lbl)
1450
+
1451
+ # Target marker at new position
1452
+ new_marker = self._make_marker(new_p, POSTERIOR_COLOR, cfg.marker_radius)
1453
+
1454
+ build_ghost = FadeIn(ghost, run_time=run_time * 0.15)
1455
+ draw_trail = Create(trail, run_time=run_time * 0.40)
1456
+ move_marker = Transform(self._marker, new_marker, run_time=run_time * 0.45)
1457
+ show_bf = FadeIn(bf_lbl, run_time=run_time * 0.20)
1458
+
1459
+ self.add(trail)
1460
+
1461
+ return Succession(
1462
+ build_ghost,
1463
+ AnimationGroup(draw_trail, show_bf),
1464
+ move_marker,
1465
+ )
1466
+
1467
+ def animate_reset(
1468
+ self,
1469
+ new_prior: float,
1470
+ run_time: float = 0.8,
1471
+ ) -> AnimationGroup:
1472
+ """Jump the marker back to a new prior, clearing all ghosts."""
1473
+ self._prior = _clamp(new_prior)
1474
+ self._history = [self._prior]
1475
+ target = self._make_marker(new_prior, POSTERIOR_COLOR,
1476
+ self.cfg.marker_radius)
1477
+ return AnimationGroup(
1478
+ Transform(self._marker, target, run_time=run_time),
1479
+ FadeOut(self._ghosts, run_time=run_time * 0.5),
1480
+ FadeOut(self._bf_labels, run_time=run_time * 0.5),
1481
+ )
1482
+
1483
+
1484
+ # ---------------------------------------------------------------------------
1485
+ # BayesFormulaBanner
1486
+ # ---------------------------------------------------------------------------
1487
+
1488
+ class BayesFormulaBanner(VGroup):
1489
+ """Floating MathTex rendering of Bayes' theorem with color-coded terms.
1490
+
1491
+ The five terms are colored to match the visual objects in the scene:
1492
+ P(H|E) ← posterior [gold]
1493
+ P(E|H) ← likelihood [blue]
1494
+ P(H) ← prior [blue]
1495
+ P(E|¬H) ← FP rate [red]
1496
+ P(¬H) ← comp. prior [red]
1497
+
1498
+ Parameters
1499
+ ----------
1500
+ pos : np.ndarray
1501
+ World position of the banner center.
1502
+ font_size : int
1503
+ show_numerical : bool
1504
+ If True (and stats are provided), show the numerical substitution
1505
+ below the symbolic formula.
1506
+ stats : dict | None
1507
+ Output of ``compute_joint_probs()`` for numerical display.
1508
+ """
1509
+
1510
+ def __init__(
1511
+ self,
1512
+ pos: np.ndarray = np.array([0.0, 2.5, 0.0]),
1513
+ font_size: int = 36,
1514
+ show_numerical: bool = False,
1515
+ stats: dict | None = None,
1516
+ ):
1517
+ super().__init__()
1518
+
1519
+ # Symbolic formula
1520
+ self.formula = MathTex(
1521
+ r"P(H|E)",
1522
+ r"=",
1523
+ r"\frac{",
1524
+ r"P(E|H)",
1525
+ r"\cdot",
1526
+ r"P(H)",
1527
+ r"}{",
1528
+ r"P(E|H)",
1529
+ r"\cdot",
1530
+ r"P(H)",
1531
+ r"+",
1532
+ r"P(E|\neg H)",
1533
+ r"\cdot",
1534
+ r"P(\neg H)",
1535
+ r"}",
1536
+ font_size=font_size,
1537
+ )
1538
+
1539
+ # Color individual terms
1540
+ # Index mapping (rough — depends on MathTex split):
1541
+ color_map = {
1542
+ 0: TERM_COLORS[0], # P(H|E)
1543
+ 3: TERM_COLORS[1], # P(E|H) numerator
1544
+ 5: TERM_COLORS[2], # P(H) numerator
1545
+ 7: TERM_COLORS[1], # P(E|H) denominator
1546
+ 9: TERM_COLORS[2], # P(H) denominator
1547
+ 11: TERM_COLORS[3], # P(E|¬H)
1548
+ 13: TERM_COLORS[4], # P(¬H)
1549
+ }
1550
+ for idx, color in color_map.items():
1551
+ if idx < len(self.formula):
1552
+ self.formula[idx].set_color(color)
1553
+
1554
+ self.formula.move_to(pos)
1555
+ self.add(self.formula)
1556
+
1557
+ # Numerical substitution row
1558
+ if show_numerical and stats:
1559
+ s = stats
1560
+ num = MathTex(
1561
+ rf"= \frac{{{s['p_e_h']:.3f} \times {s['p_h']:.3f}}}"
1562
+ rf"{{{s['p_e_h']:.3f} \times {s['p_h']:.3f} + "
1563
+ rf"{s['p_e_nh']:.3f} \times {s['p_nh']:.3f}}}"
1564
+ rf"= {s['posterior']:.4f}",
1565
+ font_size=font_size - 6,
1566
+ color=GRAY_B,
1567
+ )
1568
+ num.next_to(self.formula, DOWN, buff=0.30)
1569
+ self.add(num)
1570
+ self.numerical = num
1571
+
1572
+ # ------------------------------------------------------------------
1573
+
1574
+ def animate_appear(self, run_time: float = 2.0) -> Write:
1575
+ """Write the formula with the Manim Write animation."""
1576
+ return Write(self.formula, run_time=run_time)
1577
+
1578
+ def animate_highlight_term(
1579
+ self,
1580
+ term_index: int,
1581
+ run_time: float = 0.5,
1582
+ scale_factor: float = 1.20,
1583
+ ) -> Succession:
1584
+ """Pulse-scale one term of the formula to draw attention.
1585
+
1586
+ Parameters
1587
+ ----------
1588
+ term_index : int
1589
+ 0 = P(H|E) / posterior
1590
+ 1 = P(E|H) / likelihood
1591
+ 2 = P(H) / prior
1592
+ 3 = P(E|¬H)/ FP rate
1593
+ 4 = P(¬H) / complement prior
1594
+ """
1595
+ # Map logical term index to MathTex sub-object indices
1596
+ term_subobject_map = {0: [0], 1: [3, 7], 2: [5, 9], 3: [11], 4: [13]}
1597
+ indices = term_subobject_map.get(term_index, [0])
1598
+
1599
+ pulse_in = AnimationGroup(*[
1600
+ self.formula[i].animate(run_time=run_time / 2).scale(scale_factor)
1601
+ for i in indices if i < len(self.formula)
1602
+ ])
1603
+ pulse_out = AnimationGroup(*[
1604
+ self.formula[i].animate(run_time=run_time / 2).scale(1 / scale_factor)
1605
+ for i in indices if i < len(self.formula)
1606
+ ])
1607
+ return Succession(pulse_in, pulse_out)
1608
+
1609
+ def animate_highlight_all_terms(
1610
+ self,
1611
+ run_time_each: float = 0.45,
1612
+ ) -> Succession:
1613
+ """Sequentially pulse each of the 5 logical terms in order:
1614
+ posterior → likelihood → prior → FP rate → complement prior.
1615
+
1616
+ Useful as a "walking tour" of the formula before the main
1617
+ Bayesian scene begins.
1618
+ """
1619
+ return Succession(*[
1620
+ self.animate_highlight_term(i, run_time=run_time_each)
1621
+ for i in range(5)
1622
+ ])
1623
+
1624
+
1625
+ # ---------------------------------------------------------------------------
1626
+ # Convenience factory: full Bayes scene bundle
1627
+ # ---------------------------------------------------------------------------
1628
+
1629
+ def build_bayes_scene(
1630
+ p_h: float,
1631
+ p_e_h: float,
1632
+ p_e_nh: float,
1633
+ config: BayesConfig | None = None,
1634
+ ) -> dict:
1635
+ """Instantiate and position all five Bayesian objects for a scene.
1636
+
1637
+ Returns a dict with keys:
1638
+ "box" – BayesBox3D (centred at origin)
1639
+ "prior_bar" – PriorPosteriorBar3D (left of box)
1640
+ "lr_panel" – LikelihoodPanel3D (right of box)
1641
+ "tree" – NaturalFrequencyTree3D (below box)
1642
+ "updater" – SequentialBayesUpdater3D (above box)
1643
+ "formula" – BayesFormulaBanner (top)
1644
+ "stats" – dict from compute_joint_probs()
1645
+
1646
+ Typical use::
1647
+
1648
+ bundle = build_bayes_scene(p_h=0.01, p_e_h=0.90, p_e_nh=0.05)
1649
+ self.play(bundle["box"].animate_build_box())
1650
+ self.play(bundle["formula"].animate_appear())
1651
+ """
1652
+ cfg = config or BayesConfig()
1653
+ stats = compute_joint_probs(
1654
+ _clamp(p_h, 1e-4, 1 - 1e-4),
1655
+ _clamp(p_e_h, 1e-4, 1 - 1e-4),
1656
+ _clamp(p_e_nh, 1e-4, 1 - 1e-4),
1657
+ )
1658
+
1659
+ box = BayesBox3D(p_h, p_e_h, p_e_nh, config=cfg)
1660
+ bar = PriorPosteriorBar3D(p_h, x_pos=-(cfg.box_scale_x / 2 + 1.60),
1661
+ config=cfg)
1662
+ lr = LikelihoodPanel3D(p_e_h, p_e_nh,
1663
+ x_pos=cfg.box_scale_x / 2 + 1.50, config=cfg)
1664
+ tree = NaturalFrequencyTree3D(p_h, p_e_h, p_e_nh, config=cfg)
1665
+ tree.shift(np.array([cfg.box_scale_x / 2, 0, cfg.box_scale_z + 1.5]))
1666
+
1667
+ updater = SequentialBayesUpdater3D(
1668
+ prior=p_h,
1669
+ y_pos=cfg.box_max_height + 1.20,
1670
+ config=cfg,
1671
+ )
1672
+ formula = BayesFormulaBanner(
1673
+ pos=np.array([cfg.box_scale_x / 2, cfg.box_max_height + 2.50, 0]),
1674
+ show_numerical=True,
1675
+ stats=stats,
1676
+ )
1677
+
1678
+ return dict(
1679
+ box=box, prior_bar=bar, lr_panel=lr,
1680
+ tree=tree, updater=updater, formula=formula,
1681
+ stats=stats,
1682
+ )