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,1642 @@
1
+ """
2
+ statanim/probability/sample_space.py
3
+ =========================================
4
+ Production-quality 3D sample space and event visualization for Manim.
5
+
6
+ Objects
7
+ -------
8
+
9
+ SampleSpaceConfig (dataclass)
10
+ Every visual and layout parameter in one place.
11
+
12
+ _SampleSpaceBox (VGroup)
13
+ The Ω boundary rendered as a 3D transparent box: 12 visible edges
14
+ built from Line3D, semi-transparent face panels (front + top only,
15
+ so the interior stays visible), 8 corner dot markers, and a floating
16
+ MathTex Ω label. The interior floor has a faint grid.
17
+
18
+ _EventRegion3D (VGroup)
19
+ An event A ⊆ Ω rendered as a raised 3D prism platform.
20
+ Supports three footprint shapes:
21
+ "rect" — rectangular prism, placed by (x0, z0, width, depth)
22
+ "ellipse" — Surface of revolution (smooth elliptical top)
23
+ "poly" — arbitrary polygon footprint from a vertex list
24
+ All variants share the same shaded-face treatment (top / front /
25
+ right) from the module's standard _ShadeBox idiom.
26
+ Carries: event label (MathTex above), P(A) annotation, optional
27
+ fill pattern (solid / hatched / gradient).
28
+
29
+ _IntersectionRegion (VGroup)
30
+ Visual overlay showing A ∩ B: a raised platform colored distinctly,
31
+ sitting slightly higher than both parent regions, labeled P(A ∩ B).
32
+
33
+ _ComplementRegion (VGroup)
34
+ Ω \ A — the space outside an event region, rendered as a floor-level
35
+ shaded panel filling the box minus the event footprint, with a
36
+ hatched diagonal pattern to distinguish it from the event.
37
+
38
+ _ProbabilityAxis (VGroup)
39
+ A decorated [0, 1] number line on the floor plane with tick marks
40
+ at 0, 1/6, 1/4, 1/3, 1/2, 2/3, 3/4, 5/6, 1 and floating labels.
41
+ Event probability markers (colored vertical lines + labels) can be
42
+ added for P(A), P(B), P(A∪B), P(A∩B).
43
+
44
+ _OutcomeGrid (VGroup)
45
+ A rectangular grid of Sphere glyphs, one per outcome in a discrete
46
+ sample space. Outcomes can be colored by event membership:
47
+ no event → grey, A only → blue, B only → red,
48
+ A∩B → purple, neither → dark grey.
49
+ Supports card deck (4×13), dice (1×6), gene pairs, custom grids.
50
+
51
+ _VennZone (VGroup)
52
+ One of the 7 atomic regions of a 3-circle Venn diagram, rendered as
53
+ a Surface patch with its own color, opacity, and label.
54
+
55
+ SampleSpace3D (VGroup)
56
+ Main class. Composes the box, event regions, optional Venn layout,
57
+ optional discrete outcome grid, and probability axis.
58
+
59
+ Factory classmethods:
60
+ two_event_venn(p_a, p_b, p_ab) – 2-circle Venn inside Ω box
61
+ three_event_venn(p_a,…) – 3-circle with all 7 zones
62
+ from_dice(event_A, event_B) – discrete Ω={1…6} grid
63
+ from_cards(event_A, event_B) – 52-card layout grid
64
+ conditional_highlight(p_a,p_b,p_ab)– P(B|A) conditional visual
65
+
66
+ Animation suite:
67
+ animate_build_space() – box boundary grows edge by edge
68
+ animate_add_event(event) – event platform rises from floor
69
+ animate_intersection(a, b, inter) – intersection region materializes
70
+ animate_complement(event, comp) – complement shading sweeps in
71
+ animate_show_union(a, b, union) – union region builds from A + B
72
+ animate_sweep_probability(p) – vertical plane sweeps to P=p
73
+ animate_highlight_outcome(i, j) – flash one discrete outcome
74
+ animate_venn_build() – circles grow then labels appear
75
+ animate_conditional(a, b, inter) – dim Ω minus A then show B∩A fraction
76
+ animate_show_operation(op) – morph between ∩ / ∪ / complement
77
+ """
78
+
79
+ from __future__ import annotations
80
+
81
+ from dataclasses import dataclass, field
82
+ from typing import Sequence
83
+
84
+ import numpy as np
85
+
86
+ from manim import (
87
+ WHITE, BLACK, GRAY, GRAY_A, GRAY_B, GRAY_C, GRAY_D, GRAY_E,
88
+ BLUE, BLUE_E, RED, RED_E, GREEN, GREEN_E, YELLOW, ORANGE, PURPLE,
89
+ UP, DOWN, LEFT, RIGHT,
90
+ PI, TAU,
91
+ VGroup, VMobject,
92
+ Line3D, Polygon, Sphere, Dot3D, Arrow3D,
93
+ Surface,
94
+ Text, MathTex,
95
+ FadeIn, FadeOut, GrowFromCenter, GrowFromPoint, Transform,
96
+ Create, Write, AnimationGroup, Succession, LaggedStart,
97
+ interpolate_color,
98
+ ManimColor,
99
+ DEGREES,
100
+ )
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Semantic palette
105
+ # ---------------------------------------------------------------------------
106
+
107
+ OMEGA_COLOR = ManimColor("#37474F") # dark slate – Ω boundary
108
+ OMEGA_FACE = ManimColor("#1C2A30") # near-black – box face fill
109
+ GRID_COLOR = ManimColor("#455A64") # blue-grey – floor grid
110
+ CORNER_COLOR = ManimColor("#546E7A") # lighter slate – corner dots
111
+
112
+ EVENT_A_COLOR = ManimColor("#1565C0") # blue – event A
113
+ EVENT_B_COLOR = ManimColor("#B71C1C") # red – event B
114
+ EVENT_C_COLOR = ManimColor("#2E7D32") # green – event C
115
+ INTER_AB_COLOR = ManimColor("#7B1FA2") # purple – A ∩ B
116
+ INTER_ABC_COLOR= ManimColor("#E65100") # orange – A ∩ B ∩ C
117
+ UNION_COLOR = ManimColor("#00838F") # teal – A ∪ B
118
+ COMP_COLOR = ManimColor("#263238") # very dark – complement
119
+ NEITHER_COLOR = ManimColor("#212121") # near-black – neither region
120
+
121
+ OUTCOME_NONE = ManimColor("#546E7A") # grey – no event
122
+ OUTCOME_A = ManimColor("#1E88E5") # blue – in A
123
+ OUTCOME_B = ManimColor("#E53935") # red – in B
124
+ OUTCOME_AB = ManimColor("#8E24AA") # purple – in A ∩ B
125
+
126
+ AXIS_COLOR = GRAY_C
127
+ LABEL_COLOR = ManimColor("#ECEFF1")
128
+
129
+ FACE_DARKEN_SIDE = 0.38
130
+ FACE_DARKEN_RIGHT = 0.55
131
+ FACE_DARKEN_BACK = 0.65
132
+
133
+
134
+ def _dk(c: ManimColor, f: float) -> ManimColor:
135
+ return interpolate_color(c, BLACK, f)
136
+
137
+ def _lt(c: ManimColor, f: float) -> ManimColor:
138
+ return interpolate_color(c, WHITE, f)
139
+
140
+
141
+ # ---------------------------------------------------------------------------
142
+ # SampleSpaceConfig
143
+ # ---------------------------------------------------------------------------
144
+
145
+ @dataclass
146
+ class SampleSpaceConfig:
147
+ """All visual and layout parameters for SampleSpace3D.
148
+
149
+ Box geometry
150
+ ------------
151
+ box_width : float
152
+ X extent of the Ω box.
153
+ box_depth : float
154
+ Z extent of the Ω box.
155
+ box_height : float
156
+ Y extent (visual height of the bounding box walls).
157
+ box_edge_width : float
158
+ Stroke width of the 12 box edges.
159
+ box_face_opacity : float
160
+ Opacity of the two visible box face panels (front + top).
161
+ show_corner_dots : bool
162
+ Place small Dot3D markers at each of the 8 box corners.
163
+ show_floor_grid : bool
164
+ Render a faint grid on the floor (y=0) inside the box.
165
+ floor_grid_n : int
166
+ Number of grid lines in each direction.
167
+ omega_label_font_size : int
168
+ Font size of the floating Ω label.
169
+
170
+ Event regions
171
+ -------------
172
+ event_height : float
173
+ Default height of a rectangular event prism.
174
+ event_opacity : float
175
+ Fill opacity of event platform faces.
176
+ event_edge_width : float
177
+ Stroke width of event prism edges.
178
+ ellipse_resolution : int
179
+ Mesh resolution for elliptical event surfaces.
180
+ show_event_labels : bool
181
+ Show event name labels above each region.
182
+ show_prob_labels : bool
183
+ Show P(A) annotations above event regions.
184
+ label_font_size : int
185
+ Font size for event labels.
186
+ prob_label_font_size : int
187
+ Font size for P(A) labels.
188
+
189
+ Intersection / union / complement
190
+ ----------------------------------
191
+ inter_height_boost : float
192
+ How much higher the intersection prism sits above the event height.
193
+ inter_opacity : float
194
+ Fill opacity of intersection / union overlays.
195
+ comp_hatch_n : int
196
+ Number of diagonal hatch lines in the complement region.
197
+ comp_opacity : float
198
+ Fill opacity of the complement shaded panel.
199
+
200
+ Probability axis
201
+ ----------------
202
+ show_prob_axis : bool
203
+ Render the [0,1] probability number line on the floor.
204
+ axis_length : float
205
+ Length of the probability axis in Manim units.
206
+ axis_y_offset : float
207
+ Y offset (should be 0 for floor placement).
208
+ axis_z_offset : float
209
+ Z position of the axis (typically at the front of the box).
210
+
211
+ Discrete outcome grid
212
+ ---------------------
213
+ outcome_radius : float
214
+ Radius of Sphere / Dot3D glyphs in the outcome grid.
215
+ outcome_spacing : float
216
+ Centre-to-centre spacing between outcomes.
217
+ outcome_opacity : float
218
+ Opacity of outcome glyphs.
219
+
220
+ Venn diagram
221
+ ------------
222
+ venn_circle_radius : float
223
+ Radius of each Venn circle (used for 2- and 3-set layouts).
224
+ venn_overlap : float
225
+ Horizontal overlap between adjacent circles as a fraction of radius.
226
+ venn_height : float
227
+ Height of the Venn platform prisms.
228
+ venn_label_font_size : int
229
+ Font size of Venn zone probability labels.
230
+
231
+ Layout
232
+ ------
233
+ origin : np.ndarray
234
+ World position of the front-left-bottom corner of the Ω box.
235
+ """
236
+
237
+ # ---- box ----
238
+ box_width: float = 7.00
239
+ box_depth: float = 5.00
240
+ box_height: float = 0.08
241
+ box_edge_width: float = 1.80
242
+ box_face_opacity: float = 0.10
243
+ show_corner_dots: bool = True
244
+ show_floor_grid: bool = True
245
+ floor_grid_n: int = 8
246
+ omega_label_font_size: int = 36
247
+
248
+ # ---- event regions ----
249
+ event_height: float = 0.22
250
+ event_opacity: float = 0.62
251
+ event_edge_width: float = 0.70
252
+ ellipse_resolution: int = 28
253
+ show_event_labels: bool = True
254
+ show_prob_labels: bool = True
255
+ label_font_size: int = 26
256
+ prob_label_font_size: int = 22
257
+
258
+ # ---- set operations ----
259
+ inter_height_boost: float = 0.12
260
+ inter_opacity: float = 0.80
261
+ comp_hatch_n: int = 14
262
+ comp_opacity: float = 0.28
263
+
264
+ # ---- probability axis ----
265
+ show_prob_axis: bool = False
266
+ axis_length: float = 6.50
267
+ axis_y_offset: float = 0.00
268
+ axis_z_offset: float = 0.00
269
+
270
+ # ---- discrete grid ----
271
+ outcome_radius: float = 0.13
272
+ outcome_spacing: float = 0.44
273
+ outcome_opacity: float = 0.90
274
+
275
+ # ---- Venn ----
276
+ venn_circle_radius: float = 1.60
277
+ venn_overlap: float = 0.50
278
+ venn_height: float = 0.18
279
+ venn_label_font_size: int = 20
280
+
281
+ # ---- layout ----
282
+ origin: np.ndarray = field(
283
+ default_factory=lambda: np.array([-3.5, 0.0, -2.5])
284
+ )
285
+
286
+
287
+ # ---------------------------------------------------------------------------
288
+ # _SampleSpaceBox — the Ω boundary
289
+ # ---------------------------------------------------------------------------
290
+
291
+ class _SampleSpaceBox(VGroup):
292
+ """3D bounding box for the sample space Ω.
293
+
294
+ Rendered as 12 Line3D edges + two semi-transparent face panels
295
+ (front face and top face) so the interior remains fully visible.
296
+ Eight Dot3D corner markers and a floating Ω label complete the
297
+ visual cue that "everything inside is the sample space."
298
+ """
299
+
300
+ def __init__(self, cfg: SampleSpaceConfig):
301
+ super().__init__()
302
+ ox, oy, oz = cfg.origin
303
+ w, h, d = cfg.box_width, cfg.box_height, cfg.box_depth
304
+ ew = cfg.box_edge_width
305
+
306
+ # 8 corners
307
+ corners = {
308
+ "FBL": np.array([ox, oy, oz ]),
309
+ "FBR": np.array([ox + w, oy, oz ]),
310
+ "FTL": np.array([ox, oy + h, oz ]),
311
+ "FTR": np.array([ox + w, oy + h, oz ]),
312
+ "BBL": np.array([ox, oy, oz + d]),
313
+ "BBR": np.array([ox + w, oy, oz + d]),
314
+ "BTL": np.array([ox, oy + h, oz + d]),
315
+ "BTR": np.array([ox + w, oy + h, oz + d]),
316
+ }
317
+ self._corners = corners
318
+
319
+ # 12 edges
320
+ edges = [
321
+ ("FBL","FBR"), ("FBL","FTL"), ("FBR","FTR"), ("FTL","FTR"),
322
+ ("BBL","BBR"), ("BBL","BTL"), ("BBR","BTR"), ("BTL","BTR"),
323
+ ("FBL","BBL"), ("FBR","BBR"), ("FTL","BTL"), ("FTR","BTR"),
324
+ ]
325
+ self.edges: list[Line3D] = []
326
+ for a, b in edges:
327
+ line = Line3D(
328
+ start=corners[a], end=corners[b],
329
+ color=OMEGA_COLOR, stroke_width=ew,
330
+ )
331
+ line.set_opacity(0.90)
332
+ self.add(line)
333
+ self.edges.append(line)
334
+
335
+ # Front face panel (semi-transparent)
336
+ front = Polygon(
337
+ corners["FBL"], corners["FBR"],
338
+ corners["FTR"], corners["FTL"],
339
+ color=OMEGA_FACE,
340
+ )
341
+ front.set_fill(color=OMEGA_FACE, opacity=cfg.box_face_opacity)
342
+ front.set_stroke(width=0)
343
+ self.add(front)
344
+
345
+ # Top face panel
346
+ top = Polygon(
347
+ corners["FTL"], corners["FTR"],
348
+ corners["BTR"], corners["BTL"],
349
+ color=OMEGA_FACE,
350
+ )
351
+ top.set_fill(color=OMEGA_FACE, opacity=cfg.box_face_opacity * 0.6)
352
+ top.set_stroke(width=0)
353
+ self.add(top)
354
+
355
+ # Corner dots
356
+ if cfg.show_corner_dots:
357
+ for pt in corners.values():
358
+ dot = Dot3D(point=pt, radius=0.035, color=CORNER_COLOR)
359
+ dot.set_opacity(0.70)
360
+ self.add(dot)
361
+
362
+ # Floor grid
363
+ if cfg.show_floor_grid:
364
+ n = cfg.floor_grid_n
365
+ for i in range(n + 1):
366
+ t = i / n
367
+ xv = ox + t * w
368
+ zv = oz + t * d
369
+ self.add(Line3D(
370
+ start=np.array([xv, oy, oz ]),
371
+ end =np.array([xv, oy, oz + d]),
372
+ color=GRID_COLOR, stroke_width=0.4,
373
+ ).set_opacity(0.25))
374
+ self.add(Line3D(
375
+ start=np.array([ox, oy, zv]),
376
+ end =np.array([ox + w, oy, zv]),
377
+ color=GRID_COLOR, stroke_width=0.4,
378
+ ).set_opacity(0.25))
379
+
380
+ # Ω label — top-right corner of the front-top edge
381
+ omega = MathTex(r"\Omega", color=OMEGA_COLOR,
382
+ font_size=cfg.omega_label_font_size)
383
+ omega.move_to(corners["FTR"] + np.array([0.35, 0.20, 0]))
384
+ self.add(omega)
385
+ self.omega_label = omega
386
+
387
+ # Store geometry for use by children
388
+ self._ox, self._oy, self._oz = ox, oy, oz
389
+ self._w, self._h, self._d = w, h, d
390
+
391
+
392
+ # ---------------------------------------------------------------------------
393
+ # _EventRegion3D — a single event platform
394
+ # ---------------------------------------------------------------------------
395
+
396
+ class _EventRegion3D(VGroup):
397
+ """A raised prism platform representing one event A ⊆ Ω.
398
+
399
+ Shape variants
400
+ --------------
401
+ ``"rect"``
402
+ Rectangular footprint. Requires ``x0``, ``z0``, ``width``, ``depth``.
403
+ ``"ellipse"``
404
+ Elliptical footprint built as a Surface of revolution.
405
+ Requires ``cx``, ``cz``, ``rx`` (x-radius), ``rz`` (z-radius).
406
+ ``"poly"``
407
+ Arbitrary polygon footprint. Requires ``vertices`` — a list of
408
+ (x, z) pairs in world space.
409
+
410
+ All variants sit at y = floor_y + height for their top face.
411
+ """
412
+
413
+ def __init__(
414
+ self,
415
+ shape: str,
416
+ color: ManimColor,
417
+ cfg: SampleSpaceConfig,
418
+ floor_y: float = 0.0,
419
+ height: float | None = None,
420
+ label: str = "",
421
+ prob: float | None = None,
422
+ # rect params
423
+ x0: float = 0.0,
424
+ z0: float = 0.0,
425
+ width: float = 1.0,
426
+ depth: float = 1.0,
427
+ # ellipse params
428
+ cx: float = 0.0,
429
+ cz: float = 0.0,
430
+ rx: float = 1.0,
431
+ rz: float = 1.0,
432
+ # poly params
433
+ vertices: list[tuple[float, float]] | None = None,
434
+ ):
435
+ super().__init__()
436
+ self._cfg = cfg
437
+ self._color = color
438
+ self._shape = shape
439
+ self._label = label
440
+ self._prob = prob
441
+
442
+ h = height if height is not None else cfg.event_height
443
+ fy = floor_y
444
+
445
+ top_color = color
446
+ front_color = _dk(color, FACE_DARKEN_SIDE)
447
+ right_color = _dk(color, FACE_DARKEN_RIGHT)
448
+
449
+ def _face(pts: list[np.ndarray],
450
+ col: ManimColor,
451
+ opac: float) -> Polygon:
452
+ p = Polygon(*pts, color=col)
453
+ p.set_fill(color=col, opacity=opac)
454
+ p.set_stroke(color=_dk(col, 0.50),
455
+ width=cfg.event_edge_width,
456
+ opacity=0.55)
457
+ return p
458
+
459
+ # ---- rectangular prism ----
460
+ if shape == "rect":
461
+ x1, z1 = x0 + width, z0 + depth
462
+ TFL = np.array([x0, fy + h, z0])
463
+ TFR = np.array([x1, fy + h, z0])
464
+ TBL = np.array([x0, fy + h, z1])
465
+ TBR = np.array([x1, fy + h, z1])
466
+ AFL = np.array([x0, fy, z0])
467
+ AFR = np.array([x1, fy, z0])
468
+ ABL = np.array([x0, fy, z1])
469
+ ABR = np.array([x1, fy, z1])
470
+
471
+ self.top_face = _face([TFL, TFR, TBR, TBL], top_color, cfg.event_opacity)
472
+ self.front_face = _face([AFL, AFR, TFR, TFL], front_color, cfg.event_opacity)
473
+ self.right_face = _face([AFR, ABR, TBR, TFR], right_color, cfg.event_opacity)
474
+ self.add(self.front_face, self.right_face, self.top_face)
475
+
476
+ self._top_center = np.array([
477
+ x0 + width / 2, fy + h, z0 + depth / 2
478
+ ])
479
+
480
+ # ---- elliptical surface ----
481
+ elif shape == "ellipse":
482
+ def top_surf(u: float, v: float) -> np.ndarray:
483
+ theta = u * TAU
484
+ r_u = v # v ∈ [0,1] = radial fraction
485
+ return np.array([
486
+ cx + rx * r_u * np.cos(theta),
487
+ fy + h,
488
+ cz + rz * r_u * np.sin(theta),
489
+ ])
490
+
491
+ surf = Surface(
492
+ top_surf,
493
+ u_range=[0, 1],
494
+ v_range=[0, 1],
495
+ resolution=(cfg.ellipse_resolution, cfg.ellipse_resolution // 2),
496
+ )
497
+ surf.set_style(
498
+ fill_color=top_color,
499
+ fill_opacity=cfg.event_opacity,
500
+ stroke_color=_dk(top_color, 0.45),
501
+ stroke_width=cfg.event_edge_width * 0.6,
502
+ stroke_opacity=0.50,
503
+ )
504
+ self.top_face = surf
505
+ self.add(surf)
506
+
507
+ # Side wall: thin elliptical ring cylinder
508
+ def side_wall(u: float, v: float) -> np.ndarray:
509
+ theta = u * TAU
510
+ y_v = fy + v * h
511
+ return np.array([
512
+ cx + rx * np.cos(theta),
513
+ y_v,
514
+ cz + rz * np.sin(theta),
515
+ ])
516
+
517
+ wall = Surface(
518
+ side_wall,
519
+ u_range=[0, 1],
520
+ v_range=[0, 1],
521
+ resolution=(cfg.ellipse_resolution, 4),
522
+ )
523
+ wall.set_style(
524
+ fill_color=front_color,
525
+ fill_opacity=cfg.event_opacity * 0.75,
526
+ stroke_width=0,
527
+ )
528
+ self.add(wall)
529
+
530
+ self._top_center = np.array([cx, fy + h, cz])
531
+
532
+ # ---- polygon footprint ----
533
+ elif shape == "poly":
534
+ if not vertices:
535
+ vertices = [(0, 0), (1, 0), (1, 1), (0, 1)]
536
+
537
+ top_pts = [np.array([vx, fy + h, vz]) for vx, vz in vertices]
538
+ bot_pts = [np.array([vx, fy, vz]) for vx, vz in vertices]
539
+
540
+ self.top_face = _face(top_pts, top_color, cfg.event_opacity)
541
+ self.add(self.top_face)
542
+
543
+ # Side faces: one per edge of the polygon
544
+ n = len(vertices)
545
+ for i in range(n):
546
+ j = (i + 1) % n
547
+ side = _face(
548
+ [bot_pts[i], bot_pts[j], top_pts[j], top_pts[i]],
549
+ front_color if i == 0 else right_color,
550
+ cfg.event_opacity * 0.75,
551
+ )
552
+ self.add(side)
553
+
554
+ cx_avg = np.mean([vx for vx, _ in vertices])
555
+ cz_avg = np.mean([vz for _, vz in vertices])
556
+ self._top_center = np.array([cx_avg, fy + h, cz_avg])
557
+
558
+ else:
559
+ raise ValueError(f"Unknown event shape: '{shape}'")
560
+
561
+ # ---- event label ----
562
+ self._label_group = VGroup()
563
+ if cfg.show_event_labels and label:
564
+ evt_lbl = MathTex(label, color=_lt(color, 0.28),
565
+ font_size=cfg.label_font_size)
566
+ evt_lbl.move_to(self._top_center + np.array([0, 0.32, 0]))
567
+ self._label_group.add(evt_lbl)
568
+ self.event_label = evt_lbl
569
+
570
+ if cfg.show_prob_labels and prob is not None:
571
+ p_lbl = MathTex(
572
+ rf"P = {prob:.3f}",
573
+ color=_lt(color, 0.15),
574
+ font_size=cfg.prob_label_font_size,
575
+ )
576
+ p_lbl.move_to(self._top_center + np.array([0, 0.60, 0]))
577
+ self._label_group.add(p_lbl)
578
+ self.prob_label = p_lbl
579
+
580
+ self.add(self._label_group)
581
+
582
+ @property
583
+ def top_center(self) -> np.ndarray:
584
+ return self._top_center.copy()
585
+
586
+ @property
587
+ def floor_center(self) -> np.ndarray:
588
+ c = self._top_center.copy()
589
+ c[1] = 0.0
590
+ return c
591
+
592
+
593
+ # ---------------------------------------------------------------------------
594
+ # _IntersectionRegion — A ∩ B overlay
595
+ # ---------------------------------------------------------------------------
596
+
597
+ class _IntersectionRegion(_EventRegion3D):
598
+ """A ∩ B rendered as a raised platform above both parent regions.
599
+
600
+ Inherits _EventRegion3D and adds a MathTex A∩B label + P(A∩B).
601
+ The height is the parent event_height + inter_height_boost so it
602
+ visually "pops" above both A and B.
603
+ """
604
+
605
+ def __init__(
606
+ self,
607
+ cfg: SampleSpaceConfig,
608
+ floor_y: float = 0.0,
609
+ prob: float | None = None,
610
+ label_a: str = "A",
611
+ label_b: str = "B",
612
+ **region_kwargs,
613
+ ):
614
+ lbl = rf"{label_a} \cap {label_b}"
615
+ super().__init__(
616
+ color = INTER_AB_COLOR,
617
+ cfg = cfg,
618
+ floor_y = floor_y,
619
+ height = cfg.event_height + cfg.inter_height_boost,
620
+ label = lbl,
621
+ prob = prob,
622
+ **region_kwargs,
623
+ )
624
+
625
+
626
+ # ---------------------------------------------------------------------------
627
+ # _ComplementRegion — Ω \ A
628
+ # ---------------------------------------------------------------------------
629
+
630
+ class _ComplementRegion(VGroup):
631
+ """The complement of event A: fills Omega minus A on the floor plane.
632
+
633
+ Rendered as a floor-level shaded panel spanning the full Ω footprint,
634
+ overlaid with diagonal hatch lines. The event region itself is left
635
+ uncovered so the two regions are visually distinct.
636
+ """
637
+
638
+ def __init__(
639
+ self,
640
+ box: _SampleSpaceBox,
641
+ cfg: SampleSpaceConfig,
642
+ label: str = r"A^c",
643
+ prob: float | None = None,
644
+ ):
645
+ super().__init__()
646
+ ox, oy, oz = box._ox, box._oy, box._oz
647
+ w, h, d = box._w, box._h, box._d
648
+ y = oy + 0.001 # just above the floor
649
+
650
+ # Full Ω footprint quad
651
+ panel = Polygon(
652
+ np.array([ox, y, oz ]),
653
+ np.array([ox + w, y, oz ]),
654
+ np.array([ox + w, y, oz + d]),
655
+ np.array([ox, y, oz + d]),
656
+ color=COMP_COLOR,
657
+ )
658
+ panel.set_fill(color=COMP_COLOR, opacity=cfg.comp_opacity)
659
+ panel.set_stroke(width=0)
660
+ self.add(panel)
661
+
662
+ # Diagonal hatch lines
663
+ n = cfg.comp_hatch_n
664
+ span = w + d
665
+ for k in range(n):
666
+ t = (k + 0.5) / n
667
+ # Lines run from (ox + t*w, oz) → (ox, oz + t*d) direction
668
+ xstart = ox + t * span
669
+ zstart = oz
670
+ xend = ox
671
+ zend = oz + t * span
672
+ # Clamp to box bounds
673
+ x0c = np.clip(xstart, ox, ox + w)
674
+ z0c = oz if xstart <= ox + w else oz + (xstart - ox - w)
675
+ x1c = np.clip(xend, ox, ox + w)
676
+ z1c = np.clip(zend, oz, oz + d)
677
+ if abs(x0c - x1c) < 1e-4 and abs(z0c - z1c) < 1e-4:
678
+ continue
679
+ line = Line3D(
680
+ start=np.array([x0c, y + 0.001, z0c]),
681
+ end =np.array([x1c, y + 0.001, z1c]),
682
+ color=_lt(COMP_COLOR, 0.25),
683
+ stroke_width=0.45,
684
+ )
685
+ line.set_opacity(cfg.comp_opacity * 1.3)
686
+ self.add(line)
687
+
688
+ # Label
689
+ if cfg.show_event_labels:
690
+ lbl = MathTex(label, color=_lt(COMP_COLOR, 0.50),
691
+ font_size=cfg.label_font_size)
692
+ lbl.move_to(np.array([ox + w * 0.85, y + 0.28, oz + d * 0.15]))
693
+ self.add(lbl)
694
+ if prob is not None and cfg.show_prob_labels:
695
+ p_lbl = MathTex(rf"P = {prob:.3f}",
696
+ color=_lt(COMP_COLOR, 0.40),
697
+ font_size=cfg.prob_label_font_size)
698
+ p_lbl.move_to(np.array([ox + w * 0.85, y + 0.52, oz + d * 0.15]))
699
+ self.add(p_lbl)
700
+
701
+
702
+ # ---------------------------------------------------------------------------
703
+ # _ProbabilityAxis — decorated [0,1] number line
704
+ # ---------------------------------------------------------------------------
705
+
706
+ class _ProbabilityAxis(VGroup):
707
+ """A [0, 1] probability axis with labelled ticks and event markers.
708
+
709
+ Notable tick positions: 0, 1/6, 1/4, 1/3, 1/2, 2/3, 3/4, 5/6, 1.
710
+ Event probability markers are vertical line + MathTex label above.
711
+ """
712
+
713
+ NOTABLE_TICKS = [
714
+ (0.0, "0"),
715
+ (1/6, r"\tfrac{1}{6}"),
716
+ (1/4, r"\tfrac{1}{4}"),
717
+ (1/3, r"\tfrac{1}{3}"),
718
+ (1/2, r"\tfrac{1}{2}"),
719
+ (2/3, r"\tfrac{2}{3}"),
720
+ (3/4, r"\tfrac{3}{4}"),
721
+ (5/6, r"\tfrac{5}{6}"),
722
+ (1.0, "1"),
723
+ ]
724
+
725
+ def __init__(
726
+ self,
727
+ x_center: float,
728
+ y_pos: float,
729
+ z_pos: float,
730
+ length: float,
731
+ cfg: SampleSpaceConfig,
732
+ ):
733
+ super().__init__()
734
+ x0 = x_center - length / 2
735
+ x1 = x_center + length / 2
736
+
737
+ # Main axis line
738
+ axis = Arrow3D(
739
+ start=np.array([x0 - 0.15, y_pos, z_pos]),
740
+ end =np.array([x1 + 0.15, y_pos, z_pos]),
741
+ color=AXIS_COLOR, stroke_width=1.5,
742
+ )
743
+ self.add(axis)
744
+
745
+ # Axis label
746
+ ax_lbl = MathTex(r"P(\cdot)", color=AXIS_COLOR, font_size=22)
747
+ ax_lbl.move_to(np.array([x1 + 0.55, y_pos, z_pos]))
748
+ self.add(ax_lbl)
749
+
750
+ # Notable ticks
751
+ for val, tex in self.NOTABLE_TICKS:
752
+ xv = x0 + val * length
753
+ tick = Line3D(
754
+ start=np.array([xv, y_pos, z_pos]),
755
+ end =np.array([xv, y_pos - 0.10, z_pos]),
756
+ color=AXIS_COLOR, stroke_width=0.8,
757
+ )
758
+ self.add(tick)
759
+ lbl = MathTex(tex, color=AXIS_COLOR, font_size=16)
760
+ lbl.move_to(np.array([xv, y_pos - 0.28, z_pos]))
761
+ self.add(lbl)
762
+
763
+ self._x0 = x0
764
+ self._length = length
765
+ self._y = y_pos
766
+ self._z = z_pos
767
+
768
+ # Event marker group (populated by add_event_marker)
769
+ self._markers = VGroup()
770
+ self.add(self._markers)
771
+
772
+ def add_event_marker(
773
+ self,
774
+ prob: float,
775
+ label: str,
776
+ color: ManimColor,
777
+ height: float = 0.35,
778
+ ) -> Line3D:
779
+ """Add a vertical marker at P = prob and return it."""
780
+ xv = self._x0 + np.clip(prob, 0.0, 1.0) * self._length
781
+ m = Line3D(
782
+ start=np.array([xv, self._y, self._z]),
783
+ end =np.array([xv, self._y + height, self._z]),
784
+ color=color, stroke_width=2.2,
785
+ )
786
+ m.set_opacity(0.90)
787
+ lbl = MathTex(label, color=color, font_size=20)
788
+ lbl.move_to(np.array([xv, self._y + height + 0.22, self._z]))
789
+ grp = VGroup(m, lbl)
790
+ self._markers.add(grp)
791
+ return grp
792
+
793
+
794
+ # ---------------------------------------------------------------------------
795
+ # _OutcomeGrid — discrete sample space of spheres
796
+ # ---------------------------------------------------------------------------
797
+
798
+ class _OutcomeGrid(VGroup):
799
+ """A rectangular grid of spheres, one per outcome, color-coded by event.
800
+
801
+ Parameters
802
+ ----------
803
+ outcomes : list[list[str]]
804
+ 2D list of outcome labels. outcomes[row][col].
805
+ membership : list[list[str]]
806
+ Parallel 2D list. Each entry is one of:
807
+ ``""`` / ``"none"`` — not in any event
808
+ ``"A"`` — in event A only
809
+ ``"B"`` — in event B only
810
+ ``"AB"`` — in A ∩ B
811
+ center : np.ndarray
812
+ World position of the grid center.
813
+ cfg : SampleSpaceConfig
814
+ floor_y : float
815
+ show_labels : bool
816
+ Show outcome text labels beside each sphere.
817
+ """
818
+
819
+ MEMBERSHIP_COLORS = {
820
+ "": OUTCOME_NONE,
821
+ "none": OUTCOME_NONE,
822
+ "A": OUTCOME_A,
823
+ "B": OUTCOME_B,
824
+ "AB": OUTCOME_AB,
825
+ "C": EVENT_C_COLOR,
826
+ "AC": ManimColor("#1A237E"),
827
+ "BC": ManimColor("#880E4F"),
828
+ "ABC": INTER_ABC_COLOR,
829
+ }
830
+
831
+ def __init__(
832
+ self,
833
+ outcomes: list[list[str]],
834
+ membership: list[list[str]],
835
+ center: np.ndarray,
836
+ cfg: SampleSpaceConfig,
837
+ floor_y: float = 0.0,
838
+ show_labels: bool = True,
839
+ ):
840
+ super().__init__()
841
+ rows = len(outcomes)
842
+ cols = max(len(r) for r in outcomes)
843
+ sp = cfg.outcome_spacing
844
+ r = cfg.outcome_radius
845
+
846
+ # Compute grid top-left
847
+ x_start = center[0] - (cols - 1) * sp / 2
848
+ z_start = center[2] - (rows - 1) * sp / 2
849
+ y = floor_y + r + 0.01
850
+
851
+ self._glyphs: list[list[Dot3D | None]] = []
852
+
853
+ for row_i, (outcome_row, mem_row) in enumerate(
854
+ zip(outcomes, membership)
855
+ ):
856
+ glyph_row = []
857
+ for col_j, (label, mem) in enumerate(
858
+ zip(outcome_row, mem_row)
859
+ ):
860
+ color = self.MEMBERSHIP_COLORS.get(mem, OUTCOME_NONE)
861
+ pos = np.array([
862
+ x_start + col_j * sp,
863
+ y,
864
+ z_start + row_i * sp,
865
+ ])
866
+ dot = Dot3D(point=pos, radius=r, color=color)
867
+ dot.set_opacity(cfg.outcome_opacity)
868
+ self.add(dot)
869
+ glyph_row.append(dot)
870
+
871
+ if show_labels and label:
872
+ lbl = Text(label, color=_lt(color, 0.35), font_size=12)
873
+ lbl.move_to(pos + np.array([0, r + 0.10, 0]))
874
+ self.add(lbl)
875
+
876
+ self._glyphs.append(glyph_row)
877
+
878
+ def get_glyph(self, row: int, col: int) -> Dot3D | None:
879
+ """Return the glyph at grid position (row, col)."""
880
+ if 0 <= row < len(self._glyphs) and 0 <= col < len(self._glyphs[row]):
881
+ return self._glyphs[row][col]
882
+ return None
883
+
884
+
885
+ # ---------------------------------------------------------------------------
886
+ # _VennZone — one atomic region of a Venn diagram
887
+ # ---------------------------------------------------------------------------
888
+
889
+ class _VennZone(_EventRegion3D):
890
+ """One of the atomic regions of a Venn diagram (A only, B only, A∩B, etc.).
891
+
892
+ Thin platform prism with a label. Inherits _EventRegion3D.
893
+ """
894
+
895
+ def __init__(
896
+ self,
897
+ shape_kwargs: dict,
898
+ color: ManimColor,
899
+ cfg: SampleSpaceConfig,
900
+ label: str = "",
901
+ prob: float | None = None,
902
+ floor_y: float = 0.0,
903
+ ):
904
+ super().__init__(
905
+ color = color,
906
+ cfg = cfg,
907
+ floor_y = floor_y,
908
+ height = cfg.venn_height,
909
+ label = label,
910
+ prob = prob,
911
+ **shape_kwargs,
912
+ )
913
+
914
+
915
+ # ---------------------------------------------------------------------------
916
+ # Main SampleSpace3D
917
+ # ---------------------------------------------------------------------------
918
+
919
+ class SampleSpace3D(VGroup):
920
+ """A detailed 3D sample space for Manim probability animations.
921
+
922
+ Composes the Ω bounding box, event platforms, set operation overlays,
923
+ optional discrete outcome grid, and probability axis.
924
+
925
+ Basic usage (continuous events)
926
+ --------------------------------
927
+ >>> from manim import *
928
+ >>> from statanim.probability.sample_space import (
929
+ ... SampleSpace3D, SampleSpaceConfig
930
+ ... )
931
+ >>>
932
+ >>> class MyScene(ThreeDScene):
933
+ ... def construct(self):
934
+ ... cfg = SampleSpaceConfig()
935
+ ... ss = SampleSpace3D.two_event_venn(
936
+ ... p_a=0.40, p_b=0.35, p_ab=0.15, config=cfg)
937
+ ... self.set_camera_orientation(phi=55*DEGREES, theta=-45*DEGREES)
938
+ ... self.play(ss.animate_build_space())
939
+ ... self.play(ss.animate_venn_build())
940
+
941
+ Parameters
942
+ ----------
943
+ config : SampleSpaceConfig, optional
944
+ """
945
+
946
+ def __init__(self, config: SampleSpaceConfig | None = None):
947
+ super().__init__()
948
+ self.cfg = config or SampleSpaceConfig()
949
+ self._box = _SampleSpaceBox(self.cfg)
950
+ self.add(self._box)
951
+
952
+ # Public sub-group references (populated by add_* methods)
953
+ self.event_regions: list[_EventRegion3D] = []
954
+ self._event_group = VGroup()
955
+ self._overlay_group = VGroup()
956
+ self._grid_group = VGroup()
957
+ self._axis_group = VGroup()
958
+ self.add(self._event_group, self._overlay_group,
959
+ self._grid_group, self._axis_group)
960
+
961
+ # ------------------------------------------------------------------
962
+ # Builder methods (add objects incrementally)
963
+ # ------------------------------------------------------------------
964
+
965
+ def add_rect_event(
966
+ self,
967
+ x0: float,
968
+ z0: float,
969
+ width: float,
970
+ depth: float,
971
+ color: ManimColor = EVENT_A_COLOR,
972
+ label: str = "A",
973
+ prob: float | None = None,
974
+ ) -> _EventRegion3D:
975
+ """Add a rectangular event region and return it."""
976
+ ev = _EventRegion3D(
977
+ shape="rect", color=color, cfg=self.cfg,
978
+ floor_y=self.cfg.origin[1],
979
+ label=label, prob=prob,
980
+ x0=x0, z0=z0, width=width, depth=depth,
981
+ )
982
+ self.event_regions.append(ev)
983
+ self._event_group.add(ev)
984
+ return ev
985
+
986
+ def add_ellipse_event(
987
+ self,
988
+ cx: float,
989
+ cz: float,
990
+ rx: float,
991
+ rz: float,
992
+ color: ManimColor = EVENT_A_COLOR,
993
+ label: str = "A",
994
+ prob: float | None = None,
995
+ ) -> _EventRegion3D:
996
+ """Add an elliptical event region and return it."""
997
+ ev = _EventRegion3D(
998
+ shape="ellipse", color=color, cfg=self.cfg,
999
+ floor_y=self.cfg.origin[1],
1000
+ label=label, prob=prob,
1001
+ cx=cx, cz=cz, rx=rx, rz=rz,
1002
+ )
1003
+ self.event_regions.append(ev)
1004
+ self._event_group.add(ev)
1005
+ return ev
1006
+
1007
+ def add_intersection(
1008
+ self,
1009
+ shape_kwargs: dict,
1010
+ prob: float | None = None,
1011
+ label_a: str = "A",
1012
+ label_b: str = "B",
1013
+ ) -> _IntersectionRegion:
1014
+ """Add an intersection overlay and return it."""
1015
+ inter = _IntersectionRegion(
1016
+ cfg=self.cfg,
1017
+ floor_y=self.cfg.origin[1],
1018
+ prob=prob,
1019
+ label_a=label_a,
1020
+ label_b=label_b,
1021
+ **shape_kwargs,
1022
+ )
1023
+ self._overlay_group.add(inter)
1024
+ return inter
1025
+
1026
+ def add_complement(
1027
+ self,
1028
+ label: str = r"A^c",
1029
+ prob: float | None = None,
1030
+ ) -> _ComplementRegion:
1031
+ """Add a complement (Omega minus A) overlay and return it."""
1032
+ comp = _ComplementRegion(
1033
+ box=self._box, cfg=self.cfg,
1034
+ label=label, prob=prob,
1035
+ )
1036
+ self._overlay_group.add(comp)
1037
+ return comp
1038
+
1039
+ def add_outcome_grid(
1040
+ self,
1041
+ outcomes: list[list[str]],
1042
+ membership: list[list[str]],
1043
+ center: np.ndarray | None = None,
1044
+ show_labels: bool = True,
1045
+ ) -> _OutcomeGrid:
1046
+ """Add a discrete outcome grid and return it."""
1047
+ if center is None:
1048
+ ox, oy, oz = self.cfg.origin
1049
+ center = np.array([
1050
+ ox + self.cfg.box_width / 2,
1051
+ oy,
1052
+ oz + self.cfg.box_depth / 2,
1053
+ ])
1054
+ grid = _OutcomeGrid(
1055
+ outcomes=outcomes,
1056
+ membership=membership,
1057
+ center=center,
1058
+ cfg=self.cfg,
1059
+ floor_y=self.cfg.origin[1],
1060
+ show_labels=show_labels,
1061
+ )
1062
+ self._grid_group.add(grid)
1063
+ return grid
1064
+
1065
+ def add_probability_axis(self) -> _ProbabilityAxis:
1066
+ """Add the [0,1] probability axis along the front edge and return it."""
1067
+ ox, oy, oz = self.cfg.origin
1068
+ axis = _ProbabilityAxis(
1069
+ x_center=ox + self.cfg.box_width / 2,
1070
+ y_pos =oy + self.cfg.axis_y_offset,
1071
+ z_pos =oz + self.cfg.axis_z_offset - 0.50,
1072
+ length =self.cfg.axis_length,
1073
+ cfg =self.cfg,
1074
+ )
1075
+ self._axis_group.add(axis)
1076
+ self.prob_axis = axis
1077
+ return axis
1078
+
1079
+ # ------------------------------------------------------------------
1080
+ # Animation API
1081
+ # ------------------------------------------------------------------
1082
+
1083
+ def animate_build_space(
1084
+ self,
1085
+ lag_ratio: float = 0.06,
1086
+ run_time: float = 2.0,
1087
+ ) -> LaggedStart:
1088
+ """Grow the Ω box boundary edge by edge from the front-left corner.
1089
+
1090
+ The 12 edges trace out in a logical order: bottom square →
1091
+ top square → vertical pillars, giving a satisfying "box
1092
+ materialising" effect::
1093
+
1094
+ self.play(ss.animate_build_space())
1095
+ """
1096
+ return LaggedStart(
1097
+ *[Create(edge, run_time=run_time * 0.45)
1098
+ for edge in self._box.edges],
1099
+ lag_ratio=lag_ratio,
1100
+ run_time=run_time,
1101
+ )
1102
+
1103
+ def animate_add_event(
1104
+ self,
1105
+ event: _EventRegion3D,
1106
+ run_time: float = 1.2,
1107
+ ) -> GrowFromPoint:
1108
+ """Raise an event platform from the floor.
1109
+
1110
+ The platform rises upward from its floor footprint centre.
1111
+ """
1112
+ return GrowFromPoint(
1113
+ event,
1114
+ point=event.floor_center,
1115
+ run_time=run_time,
1116
+ )
1117
+
1118
+ def animate_intersection(
1119
+ self,
1120
+ inter: _IntersectionRegion,
1121
+ run_time: float = 1.0,
1122
+ ) -> GrowFromPoint:
1123
+ """Materialise the intersection region above the parent events."""
1124
+ return GrowFromPoint(
1125
+ inter,
1126
+ point=inter.floor_center,
1127
+ run_time=run_time,
1128
+ )
1129
+
1130
+ def animate_complement(
1131
+ self,
1132
+ comp: _ComplementRegion,
1133
+ run_time: float = 1.2,
1134
+ ) -> FadeIn:
1135
+ """Sweep the complement shading across Omega minus A."""
1136
+ return FadeIn(comp, run_time=run_time)
1137
+
1138
+ def animate_show_union(
1139
+ self,
1140
+ event_a: _EventRegion3D,
1141
+ event_b: _EventRegion3D,
1142
+ union: _EventRegion3D,
1143
+ run_time: float = 1.4,
1144
+ ) -> Succession:
1145
+ """Build the union region: briefly highlight A and B then fade in union."""
1146
+ pulse_a = event_a.animate(run_time=run_time * 0.20).scale(1.04)
1147
+ pulse_b = event_b.animate(run_time=run_time * 0.20).scale(1.04)
1148
+ restore = AnimationGroup(
1149
+ event_a.animate(run_time=run_time * 0.15).scale(1 / 1.04),
1150
+ event_b.animate(run_time=run_time * 0.15).scale(1 / 1.04),
1151
+ )
1152
+ show = FadeIn(union, run_time=run_time * 0.45)
1153
+ return Succession(
1154
+ AnimationGroup(pulse_a, pulse_b),
1155
+ restore,
1156
+ show,
1157
+ )
1158
+
1159
+ def animate_sweep_probability(
1160
+ self,
1161
+ p: float,
1162
+ run_time: float = 1.8,
1163
+ ) -> Create:
1164
+ """Sweep a translucent vertical plane from x=0 to x=P·box_width.
1165
+
1166
+ Visualises the "probability as area fraction" interpretation.
1167
+ The plane is created here and added to the scene.
1168
+ """
1169
+ ox, oy, oz = self.cfg.origin
1170
+ target_x = ox + np.clip(p, 0.0, 1.0) * self.cfg.box_width
1171
+ h = self.cfg.box_height
1172
+ d = self.cfg.box_depth
1173
+
1174
+ sweep_plane = Polygon(
1175
+ np.array([target_x, oy, oz ]),
1176
+ np.array([target_x, oy + h, oz ]),
1177
+ np.array([target_x, oy + h, oz + d]),
1178
+ np.array([target_x, oy, oz + d]),
1179
+ color=YELLOW,
1180
+ )
1181
+ sweep_plane.set_fill(color=YELLOW, opacity=0.12)
1182
+ sweep_plane.set_stroke(color=YELLOW, width=1.5, opacity=0.70)
1183
+ self.add(sweep_plane)
1184
+
1185
+ lbl = MathTex(rf"P = {p:.3f}", color=YELLOW, font_size=22)
1186
+ lbl.move_to(np.array([target_x, oy + h + 0.30, oz + d / 2]))
1187
+ self.add(lbl)
1188
+
1189
+ return Create(sweep_plane, run_time=run_time)
1190
+
1191
+ def animate_highlight_outcome(
1192
+ self,
1193
+ grid: _OutcomeGrid,
1194
+ row: int,
1195
+ col: int,
1196
+ highlight_color: ManimColor = YELLOW,
1197
+ scale_factor: float = 2.0,
1198
+ run_time: float = 0.5,
1199
+ ) -> Succession:
1200
+ """Flash and scale one outcome sphere in a discrete grid."""
1201
+ glyph = grid.get_glyph(row, col)
1202
+ if glyph is None:
1203
+ return Succession(FadeIn(VGroup(), run_time=0.1))
1204
+ orig_color = glyph.get_color()
1205
+ return Succession(
1206
+ AnimationGroup(
1207
+ glyph.animate(run_time=run_time / 2)
1208
+ .scale(scale_factor)
1209
+ .set_color(highlight_color),
1210
+ ),
1211
+ AnimationGroup(
1212
+ glyph.animate(run_time=run_time / 2)
1213
+ .scale(1 / scale_factor)
1214
+ .set_color(orig_color),
1215
+ ),
1216
+ )
1217
+
1218
+ def animate_venn_build(
1219
+ self,
1220
+ lag_ratio: float = 0.25,
1221
+ run_time: float = 3.0,
1222
+ ) -> LaggedStart:
1223
+ """Grow event regions then labels: platforms rise, labels fade in.
1224
+
1225
+ Designed for use with the Venn factory classmethods where
1226
+ multiple _EventRegion3D objects have been added.
1227
+ """
1228
+ region_anims = [
1229
+ GrowFromPoint(ev, point=ev.floor_center,
1230
+ run_time=run_time * 0.55)
1231
+ for ev in self.event_regions
1232
+ ]
1233
+ label_anims = [
1234
+ FadeIn(ev._label_group, run_time=run_time * 0.30)
1235
+ for ev in self.event_regions
1236
+ ]
1237
+ return LaggedStart(
1238
+ *region_anims,
1239
+ *label_anims,
1240
+ lag_ratio=lag_ratio,
1241
+ run_time=run_time,
1242
+ )
1243
+
1244
+ def animate_conditional(
1245
+ self,
1246
+ event_a: _EventRegion3D,
1247
+ event_b: _EventRegion3D,
1248
+ inter: _IntersectionRegion,
1249
+ run_time: float = 2.5,
1250
+ ) -> Succession:
1251
+ """Visualise P(B|A): dim Ω minus A, then highlight B∩A fraction.
1252
+
1253
+ Step 1 — dim everything outside A (set opacity of B and box to low)
1254
+ Step 2 — grow the intersection region above A
1255
+ Step 3 — show a P(B|A) annotation above the intersection
1256
+
1257
+ Parameters
1258
+ ----------
1259
+ event_a, event_b : _EventRegion3D
1260
+ inter : _IntersectionRegion
1261
+ The A ∩ B overlay.
1262
+ """
1263
+ dim_outside = AnimationGroup(
1264
+ self._box.animate(run_time=run_time * 0.30)
1265
+ .set_opacity(0.18),
1266
+ event_b.animate(run_time=run_time * 0.30)
1267
+ .set_opacity(0.15),
1268
+ )
1269
+ grow_inter = GrowFromPoint(
1270
+ inter, point=inter.floor_center, run_time=run_time * 0.40
1271
+ )
1272
+ if inter._prob is not None:
1273
+ p_ab = inter._prob
1274
+ p_a = event_a._prob or 1e-9
1275
+ cond = p_ab / p_a
1276
+ cond_lbl = MathTex(
1277
+ rf"P(B|A) = \frac{{P(A \cap B)}}{{P(A)}} = "
1278
+ rf"\frac{{{p_ab:.3f}}}{{{p_a:.3f}}} = {cond:.3f}",
1279
+ color=INTER_AB_COLOR,
1280
+ font_size=self.cfg.label_font_size,
1281
+ )
1282
+ cond_lbl.move_to(inter.top_center + np.array([0, 0.55, 0]))
1283
+ self.add(cond_lbl)
1284
+ show_label = FadeIn(cond_lbl, run_time=run_time * 0.30)
1285
+ else:
1286
+ show_label = FadeIn(VGroup(), run_time=0.1)
1287
+
1288
+ return Succession(dim_outside, grow_inter, show_label)
1289
+
1290
+ def animate_show_operation(
1291
+ self,
1292
+ operation: str,
1293
+ event_a: _EventRegion3D,
1294
+ event_b: _EventRegion3D | None = None,
1295
+ result_region: _EventRegion3D | None = None,
1296
+ run_time: float = 1.5,
1297
+ ) -> AnimationGroup | Succession:
1298
+ """Morph the scene to highlight a set operation.
1299
+
1300
+ Parameters
1301
+ ----------
1302
+ operation : str
1303
+ One of ``"intersection"``, ``"union"``, ``"complement"``,
1304
+ ``"difference"`` (A \\ B).
1305
+ event_a, event_b : _EventRegion3D
1306
+ result_region : _EventRegion3D | None
1307
+ Pre-built result region to reveal; if None, just dims.
1308
+ """
1309
+ anims = []
1310
+
1311
+ if operation == "complement":
1312
+ # Dim A, brighten everything else
1313
+ anims.append(event_a.animate(run_time=run_time)
1314
+ .set_opacity(0.15))
1315
+ if result_region:
1316
+ anims.append(FadeIn(result_region, run_time=run_time))
1317
+
1318
+ elif operation == "intersection":
1319
+ # Dim non-overlapping parts
1320
+ if event_b:
1321
+ anims.append(
1322
+ AnimationGroup(
1323
+ event_a.animate(run_time=run_time * 0.5)
1324
+ .set_opacity(0.25),
1325
+ event_b.animate(run_time=run_time * 0.5)
1326
+ .set_opacity(0.25),
1327
+ )
1328
+ )
1329
+ if result_region:
1330
+ anims.append(
1331
+ GrowFromPoint(result_region,
1332
+ point=result_region.floor_center,
1333
+ run_time=run_time * 0.5)
1334
+ )
1335
+
1336
+ elif operation == "union":
1337
+ if result_region:
1338
+ anims.append(FadeIn(result_region, run_time=run_time))
1339
+
1340
+ elif operation == "difference":
1341
+ # A \ B: dim B portion
1342
+ if event_b:
1343
+ anims.append(event_b.animate(run_time=run_time).set_opacity(0.12))
1344
+
1345
+ return AnimationGroup(*anims) if len(anims) != 1 else anims[0]
1346
+
1347
+ # ------------------------------------------------------------------
1348
+ # Factory classmethods
1349
+ # ------------------------------------------------------------------
1350
+
1351
+ @classmethod
1352
+ def two_event_venn(
1353
+ cls,
1354
+ p_a: float,
1355
+ p_b: float,
1356
+ p_ab: float,
1357
+ config: SampleSpaceConfig | None = None,
1358
+ label_a: str = "A",
1359
+ label_b: str = "B",
1360
+ ) -> "SampleSpace3D":
1361
+ """Classic 2-circle Venn diagram inside the Ω box.
1362
+
1363
+ Lays out three event regions:
1364
+ - A only (left ellipse, minus overlap)
1365
+ - B only (right ellipse, minus overlap)
1366
+ - A ∩ B (central overlap, raised higher)
1367
+
1368
+ The "A only" and "B only" regions use rectangular footprints
1369
+ for simplicity; the intersection uses the same footprint
1370
+ centred between them.
1371
+
1372
+ Parameters
1373
+ ----------
1374
+ p_a, p_b : float
1375
+ Marginal probabilities P(A) and P(B).
1376
+ p_ab : float
1377
+ Joint probability P(A ∩ B). Must satisfy p_ab ≤ min(p_a, p_b).
1378
+ """
1379
+ cfg = config or SampleSpaceConfig()
1380
+ ss = cls(config=cfg)
1381
+ ox, oy, oz = cfg.origin
1382
+ w, d = cfg.box_width, cfg.box_depth
1383
+ r = cfg.venn_circle_radius
1384
+
1385
+ cx_a = ox + w * 0.35
1386
+ cx_b = ox + w * 0.65
1387
+ cz = oz + d * 0.50
1388
+
1389
+ # A-only ellipse (left)
1390
+ ev_a = ss.add_ellipse_event(
1391
+ cx=cx_a, cz=cz, rx=r, rz=r * 0.85,
1392
+ color=EVENT_A_COLOR,
1393
+ label=label_a, prob=p_a,
1394
+ )
1395
+ # B-only ellipse (right)
1396
+ ev_b = ss.add_ellipse_event(
1397
+ cx=cx_b, cz=cz, rx=r, rz=r * 0.85,
1398
+ color=EVENT_B_COLOR,
1399
+ label=label_b, prob=p_b,
1400
+ )
1401
+ # A ∩ B intersection — centred between A and B
1402
+ cx_ab = (cx_a + cx_b) / 2
1403
+ inter = ss.add_intersection(
1404
+ shape_kwargs=dict(
1405
+ shape="ellipse",
1406
+ cx=cx_ab, cz=cz,
1407
+ rx=(cx_b - cx_a) * 0.28,
1408
+ rz=r * 0.55,
1409
+ ),
1410
+ prob=p_ab,
1411
+ label_a=label_a,
1412
+ label_b=label_b,
1413
+ )
1414
+ ss._inter_ab = inter
1415
+
1416
+ # Probability axis
1417
+ if cfg.show_prob_axis:
1418
+ axis = ss.add_probability_axis()
1419
+ axis.add_event_marker(p_a, rf"P({label_a})", EVENT_A_COLOR)
1420
+ axis.add_event_marker(p_b, rf"P({label_b})", EVENT_B_COLOR)
1421
+ axis.add_event_marker(p_ab, rf"P({label_a}\cap{label_b})", INTER_AB_COLOR)
1422
+ p_aub = p_a + p_b - p_ab
1423
+ axis.add_event_marker(p_aub, rf"P({label_a}\cup{label_b})", UNION_COLOR)
1424
+
1425
+ return ss
1426
+
1427
+ @classmethod
1428
+ def three_event_venn(
1429
+ cls,
1430
+ p_a: float,
1431
+ p_b: float,
1432
+ p_c: float,
1433
+ p_ab: float,
1434
+ p_ac: float,
1435
+ p_bc: float,
1436
+ p_abc: float,
1437
+ config: SampleSpaceConfig | None = None,
1438
+ ) -> "SampleSpace3D":
1439
+ """3-circle Venn diagram with all 7 atomic zones.
1440
+
1441
+ Zones rendered as elliptical platforms at their approximate
1442
+ geometric centroid positions. Heights are stacked:
1443
+ single-event → event_height
1444
+ two-event inter → event_height + inter_height_boost
1445
+ triple inter → event_height + 2×inter_height_boost
1446
+
1447
+ Parameters
1448
+ ----------
1449
+ p_a, p_b, p_c : float
1450
+ Marginal probabilities.
1451
+ p_ab, p_ac, p_bc : float
1452
+ Pairwise joint probabilities.
1453
+ p_abc : float
1454
+ Triple joint probability P(A ∩ B ∩ C).
1455
+ """
1456
+ cfg = config or SampleSpaceConfig()
1457
+ ss = cls(config=cfg)
1458
+ ox, oy, oz = cfg.origin
1459
+ w, d = cfg.box_width, cfg.box_depth
1460
+ r = cfg.venn_circle_radius * 0.85
1461
+
1462
+ # Centres of the three circles (equilateral triangle)
1463
+ tri_r = r * 0.75
1464
+ angles = [90, 90 + 120, 90 + 240]
1465
+ cx_mid = ox + w / 2
1466
+ cz_mid = oz + d / 2
1467
+
1468
+ centres = [
1469
+ np.array([
1470
+ cx_mid + tri_r * np.cos(np.radians(a)),
1471
+ oy,
1472
+ cz_mid - tri_r * np.sin(np.radians(a)),
1473
+ ])
1474
+ for a in angles
1475
+ ]
1476
+
1477
+ colors = [EVENT_A_COLOR, EVENT_B_COLOR, EVENT_C_COLOR]
1478
+ labels = ["A", "B", "C"]
1479
+ probs = [p_a, p_b, p_c]
1480
+
1481
+ for i, (center, color, label, prob) in enumerate(
1482
+ zip(centres, colors, labels, probs)
1483
+ ):
1484
+ ev = ss.add_ellipse_event(
1485
+ cx=center[0], cz=center[2],
1486
+ rx=r, rz=r * 0.90,
1487
+ color=color, label=label, prob=prob,
1488
+ )
1489
+
1490
+ # Pairwise intersections — midpoints between circle centres
1491
+ inter_pairs = [
1492
+ (0, 1, INTER_AB_COLOR, "A∩B", p_ab),
1493
+ (0, 2, ManimColor("#00695C"), "A∩C", p_ac),
1494
+ (1, 2, ManimColor("#880E4F"), "B∩C", p_bc),
1495
+ ]
1496
+ h_boost = cfg.inter_height_boost
1497
+
1498
+ for i, j, color, lbl, prob in inter_pairs:
1499
+ mid = (centres[i] + centres[j]) / 2
1500
+ ss.add_intersection(
1501
+ shape_kwargs=dict(
1502
+ shape="ellipse",
1503
+ cx=mid[0], cz=mid[2],
1504
+ rx=r * 0.35, rz=r * 0.30,
1505
+ ),
1506
+ prob=prob,
1507
+ label_a=labels[i],
1508
+ label_b=labels[j],
1509
+ )
1510
+
1511
+ # Triple intersection at centroid
1512
+ triple_centre = np.mean(centres, axis=0)
1513
+ triple = _EventRegion3D(
1514
+ shape="ellipse",
1515
+ color=INTER_ABC_COLOR,
1516
+ cfg=cfg,
1517
+ floor_y=oy,
1518
+ height=cfg.event_height + 2 * h_boost,
1519
+ label=r"A\cap B\cap C",
1520
+ prob=p_abc,
1521
+ cx=triple_centre[0],
1522
+ cz=triple_centre[2],
1523
+ rx=r * 0.20,
1524
+ rz=r * 0.18,
1525
+ )
1526
+ ss._overlay_group.add(triple)
1527
+
1528
+ return ss
1529
+
1530
+ @classmethod
1531
+ def from_dice(
1532
+ cls,
1533
+ event_a: set[int] | None = None,
1534
+ event_b: set[int] | None = None,
1535
+ config: SampleSpaceConfig | None = None,
1536
+ ) -> "SampleSpace3D":
1537
+ """Discrete sample space Ω = {1, 2, 3, 4, 5, 6}.
1538
+
1539
+ Outcomes are arranged in a 1×6 grid of spheres, color-coded
1540
+ by event membership.
1541
+
1542
+ Parameters
1543
+ ----------
1544
+ event_a : set[int], optional
1545
+ Dice outcomes in event A. E.g. ``{2, 4, 6}`` for even numbers.
1546
+ event_b : set[int], optional
1547
+ Dice outcomes in event B. E.g. ``{1, 2, 3}`` for ≤ 3.
1548
+ """
1549
+ cfg = config or SampleSpaceConfig()
1550
+ ss = cls(config=cfg)
1551
+ event_a = event_a or set()
1552
+ event_b = event_b or set()
1553
+
1554
+ outcomes = [[str(k) for k in range(1, 7)]]
1555
+ membership = [[
1556
+ "AB" if k in event_a and k in event_b else
1557
+ "A" if k in event_a else
1558
+ "B" if k in event_b else
1559
+ ""
1560
+ for k in range(1, 7)
1561
+ ]]
1562
+
1563
+ ox, oy, oz = cfg.origin
1564
+ centre = np.array([ox + cfg.box_width / 2, oy, oz + cfg.box_depth / 2])
1565
+ ss.add_outcome_grid(outcomes, membership, center=centre)
1566
+
1567
+ # Probability annotations
1568
+ n = 6
1569
+ p_a = len(event_a) / n
1570
+ p_b = len(event_b) / n
1571
+ p_ab = len(event_a & event_b) / n
1572
+ if cfg.show_prob_axis:
1573
+ axis = ss.add_probability_axis()
1574
+ if p_a > 0: axis.add_event_marker(p_a, "P(A)", EVENT_A_COLOR)
1575
+ if p_b > 0: axis.add_event_marker(p_b, "P(B)", EVENT_B_COLOR)
1576
+ if p_ab > 0: axis.add_event_marker(p_ab, r"P(A\cap B)", INTER_AB_COLOR)
1577
+
1578
+ return ss
1579
+
1580
+ @classmethod
1581
+ def from_cards(
1582
+ cls,
1583
+ event_a: set[str] | None = None,
1584
+ event_b: set[str] | None = None,
1585
+ config: SampleSpaceConfig | None = None,
1586
+ ) -> "SampleSpace3D":
1587
+ """Discrete sample space: full 52-card deck in a 4×13 grid.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ event_a : set[str], optional
1592
+ Card identifiers in event A. Format: "A♠", "K♥", "2♣", etc.
1593
+ event_b : set[str], optional
1594
+ Card identifiers in event B.
1595
+ """
1596
+ cfg = config or SampleSpaceConfig()
1597
+ ss = cls(config=cfg)
1598
+ event_a = event_a or set()
1599
+ event_b = event_b or set()
1600
+
1601
+ suits = ["♠", "♥", "♦", "♣"]
1602
+ values = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
1603
+
1604
+ outcomes = [[f"{v}{s}" for v in values] for s in suits]
1605
+ membership = [[
1606
+ "AB" if f"{v}{s}" in event_a and f"{v}{s}" in event_b else
1607
+ "A" if f"{v}{s}" in event_a else
1608
+ "B" if f"{v}{s}" in event_b else
1609
+ ""
1610
+ for v in values
1611
+ ] for s in suits]
1612
+
1613
+ ox, oy, oz = cfg.origin
1614
+ centre = np.array([ox + cfg.box_width / 2, oy, oz + cfg.box_depth / 2])
1615
+ ss.add_outcome_grid(outcomes, membership, center=centre, show_labels=False)
1616
+
1617
+ return ss
1618
+
1619
+ @classmethod
1620
+ def conditional_highlight(
1621
+ cls,
1622
+ p_a: float,
1623
+ p_b: float,
1624
+ p_ab: float,
1625
+ config: SampleSpaceConfig | None = None,
1626
+ ) -> "SampleSpace3D":
1627
+ """Pre-built scene for visualising P(B|A).
1628
+
1629
+ Lays out a 2-event Venn with A and B, ready for
1630
+ ``animate_conditional()`` to be called::
1631
+
1632
+ ss = SampleSpace3D.conditional_highlight(0.4, 0.35, 0.15)
1633
+ self.play(ss.animate_build_space())
1634
+ self.play(ss.animate_venn_build())
1635
+ self.play(ss.animate_conditional(
1636
+ ss.event_regions[0],
1637
+ ss.event_regions[1],
1638
+ ss._inter_ab,
1639
+ ))
1640
+ """
1641
+ base = cls.two_event_venn(p_a, p_b, p_ab, config=config)
1642
+ return base