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.
- statanim/__init__.py +0 -0
- statanim/animations/__init__.py +0 -0
- statanim/animations/clt_demo.py +1852 -0
- statanim/animations/flip_roll.py +1851 -0
- statanim/animations/sampling.py +2291 -0
- statanim/animations/transitions.py +1857 -0
- statanim/axes/__init__.py +0 -0
- statanim/axes/axes3d.py +1989 -0
- statanim/axes/grid3d.py +1127 -0
- statanim/axes/number_plane3d.py +1526 -0
- statanim/charts/__init__.py +0 -0
- statanim/charts/bar_chart3d.py +1572 -0
- statanim/charts/box_plot3d.py +1977 -0
- statanim/charts/heat_map3d.py +1639 -0
- statanim/charts/histogram3d.py +1019 -0
- statanim/charts/line_plot3d.py +1891 -0
- statanim/charts/scatter_plot3d.py +1469 -0
- statanim/charts/violin_plot3d.py +1567 -0
- statanim/core/__init__.py +0 -0
- statanim/core/base.py +1585 -0
- statanim/core/colors.py +1373 -0
- statanim/core/math_utils.py +2081 -0
- statanim/core/tex_utils.py +2111 -0
- statanim/distributions/__init__.py +0 -0
- statanim/distributions/base_dist.py +1936 -0
- statanim/distributions/cdf_viz.py +1773 -0
- statanim/distributions/continuous_dists.py +1769 -0
- statanim/distributions/discrete_dists.py +1734 -0
- statanim/distributions/normal3d.py +1877 -0
- statanim/distributions/pdf_viz.py +2247 -0
- statanim/distributions/pmf_viz.py +1936 -0
- statanim/inference/__init__.py +0 -0
- statanim/inference/confidence_interval.py +1693 -0
- statanim/inference/error_types.py +1825 -0
- statanim/inference/hypothesis.py +1821 -0
- statanim/inference/sampling_dist.py +1933 -0
- statanim/probability/__init__.py +0 -0
- statanim/probability/bayes.py +1682 -0
- statanim/probability/prob_tree.py +1478 -0
- statanim/probability/sample_space.py +1642 -0
- statanim/probability/venn3d.py +1857 -0
- statanim/props/__init__.py +0 -0
- statanim/props/card.py +2259 -0
- statanim/props/coin.py +1011 -0
- statanim/props/die.py +1391 -0
- statanim/props/spinner.py +1591 -0
- statanim/props/urn.py +1531 -0
- statanim/regression/__init__.py +0 -0
- statanim/regression/correlation.py +2805 -0
- statanim/regression/regression_plane.py +2286 -0
- statanim/regression/residuals.py +2599 -0
- statanim/scenes/__init__.py +0 -0
- statanim/scenes/demo_bayes.py +2056 -0
- statanim/scenes/demo_clt.py +1756 -0
- statanim/scenes/demo_distributions.py +1905 -0
- statanim/scenes/demo_hypothesis.py +1791 -0
- statanim/ui/__init__.py +0 -0
- statanim/ui/labels.py +1844 -0
- statanim/ui/panels.py +1937 -0
- statanim/ui/table3d.py +1745 -0
- statanim/ui/ticker.py +2007 -0
- statanim-0.1.0.dist-info/METADATA +463 -0
- statanim-0.1.0.dist-info/RECORD +66 -0
- statanim-0.1.0.dist-info/WHEEL +5 -0
- statanim-0.1.0.dist-info/licenses/LICENSE +21 -0
- statanim-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1857 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/probability/venn3d.py
|
|
3
|
+
===================================
|
|
4
|
+
Production-quality 3D Venn diagram visualizations for Manim.
|
|
5
|
+
|
|
6
|
+
This is the definitive standalone Venn implementation. While
|
|
7
|
+
``sample_space.py`` includes Venn zones as one feature among many,
|
|
8
|
+
this module focuses entirely on Venn geometry with full analytical
|
|
9
|
+
precision, rich per-zone surfaces, and a comprehensive animation API.
|
|
10
|
+
|
|
11
|
+
Architecture
|
|
12
|
+
------------
|
|
13
|
+
|
|
14
|
+
Geometry engine
|
|
15
|
+
``_CircleArcGeometry``
|
|
16
|
+
Computes the two intersection points of two circles analytically
|
|
17
|
+
and determines which angular arc segments belong to each zone.
|
|
18
|
+
All circle geometry uses these results so zone boundaries are
|
|
19
|
+
mathematically exact, not approximated.
|
|
20
|
+
|
|
21
|
+
``_ZonePatch``
|
|
22
|
+
For a given atomic zone (e.g. A∩Bᶜ or A∩B∩Cᶜ), parametrises
|
|
23
|
+
the boundary as a sequence of circular arc segments and renders
|
|
24
|
+
the enclosed region as a ``Surface``. Side walls are
|
|
25
|
+
extruded downward from the boundary curve to y=0, giving each
|
|
26
|
+
zone a proper 3D profile. Zone height is tiered by membership
|
|
27
|
+
level: single-set at h₁, two-set overlap at h₂, triple at h₃.
|
|
28
|
+
|
|
29
|
+
Data containers
|
|
30
|
+
``VennData2``
|
|
31
|
+
Holds P(A), P(B), P(A∩B) for a 2-set diagram. Validates all
|
|
32
|
+
consistency constraints and computes the three derived zone probs
|
|
33
|
+
(A only, B only, A∩B) plus the "neither" zone.
|
|
34
|
+
|
|
35
|
+
``VennData3``
|
|
36
|
+
Holds the 7 input probabilities for a 3-set diagram. Validates
|
|
37
|
+
and computes all 8 atomic zone probabilities (including neither).
|
|
38
|
+
|
|
39
|
+
Visual objects
|
|
40
|
+
``_VennCircleOutline``
|
|
41
|
+
The full circle ring drawn as a ``ParametricFunction`` floating
|
|
42
|
+
just above the zone surfaces. Provides the classic "overlapping
|
|
43
|
+
circles" visual as a thin colored curve.
|
|
44
|
+
|
|
45
|
+
``_ZoneSurface``
|
|
46
|
+
A single atomic zone: ``Surface`` top + extruded side
|
|
47
|
+
wall + floating MathTex labels (set-notation + probability + optional
|
|
48
|
+
count).
|
|
49
|
+
|
|
50
|
+
``_InclusionExclusionBracket``
|
|
51
|
+
A bracket annotation system showing
|
|
52
|
+
P(A∪B) = P(A) + P(B) − P(A∩B) with color-coded terms.
|
|
53
|
+
|
|
54
|
+
``_IndependenceAnnotation``
|
|
55
|
+
Shows P(A∩B) vs P(A)·P(B) side by side with a
|
|
56
|
+
``≈`` or ``≠`` indicator colored green/red.
|
|
57
|
+
|
|
58
|
+
Main class
|
|
59
|
+
``VennDiagram3D``
|
|
60
|
+
Composes all components. Supports 2-set and 3-set diagrams,
|
|
61
|
+
four layout modes ("standard", "linear", "nested", "euler"),
|
|
62
|
+
and a full animation API.
|
|
63
|
+
|
|
64
|
+
Factory classmethods:
|
|
65
|
+
``two_set(data, …)`` – 2-set Venn from VennData2
|
|
66
|
+
``three_set(data, …)`` – 3-set Venn from VennData3
|
|
67
|
+
``from_counts(n_a, …)`` – build from natural frequency counts
|
|
68
|
+
``disjoint(p_a, p_b, …)`` – disjoint events (Euler diagram)
|
|
69
|
+
``subset(p_a, p_b, …)`` – A ⊆ B nested layout
|
|
70
|
+
``independent(p_a, p_b, …)`` – P(A∩B) = P(A)·P(B) case
|
|
71
|
+
|
|
72
|
+
Animation suite:
|
|
73
|
+
``animate_grow_circles()`` – outlines draw one by one
|
|
74
|
+
``animate_fill_zones()`` – platforms rise level by level
|
|
75
|
+
``animate_highlight_zone(name)`` – flash one zone, dim others
|
|
76
|
+
``animate_inclusion_exclusion()`` – step through P(A∪B) formula
|
|
77
|
+
``animate_condition_on(name)`` – dim outside-A zones, show P(B|A)
|
|
78
|
+
``animate_independence_test()`` – show P(A∩B) vs P(A)·P(B)
|
|
79
|
+
``animate_morph_to(new_data)`` – morph zone sizes to new probs
|
|
80
|
+
``animate_add_set_c(data3)`` – grow 2-set into 3-set
|
|
81
|
+
``animate_restore()`` – restore all opacities
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
from __future__ import annotations
|
|
85
|
+
|
|
86
|
+
from dataclasses import dataclass, field
|
|
87
|
+
from typing import Callable, Sequence
|
|
88
|
+
import warnings
|
|
89
|
+
|
|
90
|
+
import numpy as np
|
|
91
|
+
|
|
92
|
+
from manim import (
|
|
93
|
+
WHITE, BLACK, GRAY, GRAY_A, GRAY_B, GRAY_C, GRAY_D, GRAY_E,
|
|
94
|
+
BLUE, BLUE_E, RED, RED_E, GREEN, GREEN_E, YELLOW, ORANGE, PURPLE,
|
|
95
|
+
UP, DOWN, LEFT, RIGHT,
|
|
96
|
+
PI, TAU,
|
|
97
|
+
VGroup, VMobject,
|
|
98
|
+
Line3D, Polygon, Sphere, Dot3D, Arrow3D,
|
|
99
|
+
Surface, ParametricFunction,
|
|
100
|
+
Text, MathTex,
|
|
101
|
+
FadeIn, FadeOut, GrowFromCenter, GrowFromPoint, Transform,
|
|
102
|
+
Create, Write, AnimationGroup, Succession, LaggedStart,
|
|
103
|
+
interpolate_color,
|
|
104
|
+
ManimColor,
|
|
105
|
+
DEGREES,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
# Semantic palette
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
SET_A_COLOR = ManimColor("#1565C0") # blue
|
|
114
|
+
SET_B_COLOR = ManimColor("#B71C1C") # red
|
|
115
|
+
SET_C_COLOR = ManimColor("#2E7D32") # green
|
|
116
|
+
|
|
117
|
+
ZONE_A_ONLY = ManimColor("#1E88E5") # lighter blue
|
|
118
|
+
ZONE_B_ONLY = ManimColor("#E53935") # lighter red
|
|
119
|
+
ZONE_C_ONLY = ManimColor("#43A047") # lighter green
|
|
120
|
+
ZONE_AB = ManimColor("#7B1FA2") # purple (A∩B)
|
|
121
|
+
ZONE_AC = ManimColor("#00838F") # teal (A∩C)
|
|
122
|
+
ZONE_BC = ManimColor("#E65100") # orange (B∩C)
|
|
123
|
+
ZONE_ABC = ManimColor("#F9A825") # amber (A∩B∩C)
|
|
124
|
+
ZONE_NEITHER = ManimColor("#1C2A30") # near-black
|
|
125
|
+
|
|
126
|
+
OUTLINE_OPACITY = 0.90
|
|
127
|
+
ZONE_DIM_OPACITY = 0.10
|
|
128
|
+
LABEL_COLOR = ManimColor("#ECEFF1")
|
|
129
|
+
|
|
130
|
+
FACE_DARKEN = 0.40
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _dk(c: ManimColor, f: float) -> ManimColor:
|
|
134
|
+
return interpolate_color(c, BLACK, f)
|
|
135
|
+
|
|
136
|
+
def _lt(c: ManimColor, f: float) -> ManimColor:
|
|
137
|
+
return interpolate_color(c, WHITE, f)
|
|
138
|
+
|
|
139
|
+
def _clamp(v: float, lo: float = 0.0, hi: float = 1.0) -> float:
|
|
140
|
+
return float(np.clip(v, lo, hi))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ---------------------------------------------------------------------------
|
|
144
|
+
# VennData containers (validation + derived zone probabilities)
|
|
145
|
+
# ---------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
@dataclass
|
|
148
|
+
class VennData2:
|
|
149
|
+
"""Probability specification for a 2-set Venn diagram.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
p_a : float
|
|
154
|
+
P(A)
|
|
155
|
+
p_b : float
|
|
156
|
+
P(B)
|
|
157
|
+
p_ab : float
|
|
158
|
+
P(A ∩ B). Must satisfy: p_ab ≤ min(p_a, p_b) and p_ab ≥ 0.
|
|
159
|
+
label_a, label_b : str
|
|
160
|
+
Display names for the two sets.
|
|
161
|
+
|
|
162
|
+
Derived zone probabilities (read-only properties):
|
|
163
|
+
p_a_only = P(A) − P(A∩B)
|
|
164
|
+
p_b_only = P(B) − P(A∩B)
|
|
165
|
+
p_aub = P(A) + P(B) − P(A∩B)
|
|
166
|
+
p_neither = 1 − P(A∪B)
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
p_a: float
|
|
170
|
+
p_b: float
|
|
171
|
+
p_ab: float
|
|
172
|
+
label_a: str = "A"
|
|
173
|
+
label_b: str = "B"
|
|
174
|
+
|
|
175
|
+
def __post_init__(self):
|
|
176
|
+
self.p_a = _clamp(self.p_a)
|
|
177
|
+
self.p_b = _clamp(self.p_b)
|
|
178
|
+
self.p_ab = _clamp(self.p_ab)
|
|
179
|
+
self._validate()
|
|
180
|
+
|
|
181
|
+
def _validate(self) -> None:
|
|
182
|
+
msgs = []
|
|
183
|
+
if self.p_ab > self.p_a + 1e-9:
|
|
184
|
+
msgs.append(f"P(A∩B)={self.p_ab:.4f} > P(A)={self.p_a:.4f}")
|
|
185
|
+
if self.p_ab > self.p_b + 1e-9:
|
|
186
|
+
msgs.append(f"P(A∩B)={self.p_ab:.4f} > P(B)={self.p_b:.4f}")
|
|
187
|
+
if self.p_a + self.p_b - self.p_ab > 1.0 + 1e-9:
|
|
188
|
+
msgs.append(f"P(A∪B)={self.p_a+self.p_b-self.p_ab:.4f} > 1")
|
|
189
|
+
if msgs:
|
|
190
|
+
warnings.warn("VennData2 inconsistency: " + "; ".join(msgs))
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def p_a_only(self) -> float:
|
|
194
|
+
return max(0.0, self.p_a - self.p_ab)
|
|
195
|
+
|
|
196
|
+
@property
|
|
197
|
+
def p_b_only(self) -> float:
|
|
198
|
+
return max(0.0, self.p_b - self.p_ab)
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def p_aub(self) -> float:
|
|
202
|
+
return _clamp(self.p_a + self.p_b - self.p_ab)
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def p_neither(self) -> float:
|
|
206
|
+
return max(0.0, 1.0 - self.p_aub)
|
|
207
|
+
|
|
208
|
+
def zone_probs(self) -> dict[str, float]:
|
|
209
|
+
return {
|
|
210
|
+
"a_only": self.p_a_only,
|
|
211
|
+
"b_only": self.p_b_only,
|
|
212
|
+
"ab": self.p_ab,
|
|
213
|
+
"neither": self.p_neither,
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
def is_independent(self, tol: float = 0.005) -> bool:
|
|
217
|
+
return abs(self.p_ab - self.p_a * self.p_b) < tol
|
|
218
|
+
|
|
219
|
+
def is_disjoint(self, tol: float = 0.005) -> bool:
|
|
220
|
+
return self.p_ab < tol
|
|
221
|
+
|
|
222
|
+
def p_b_given_a(self) -> float:
|
|
223
|
+
return self.p_ab / self.p_a if self.p_a > 1e-9 else 0.0
|
|
224
|
+
|
|
225
|
+
def p_a_given_b(self) -> float:
|
|
226
|
+
return self.p_ab / self.p_b if self.p_b > 1e-9 else 0.0
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@dataclass
|
|
230
|
+
class VennData3:
|
|
231
|
+
"""Probability specification for a 3-set Venn diagram.
|
|
232
|
+
|
|
233
|
+
Parameters
|
|
234
|
+
----------
|
|
235
|
+
p_a, p_b, p_c : float
|
|
236
|
+
Marginal probabilities.
|
|
237
|
+
p_ab, p_ac, p_bc : float
|
|
238
|
+
Pairwise joint probabilities.
|
|
239
|
+
p_abc : float
|
|
240
|
+
Triple intersection P(A ∩ B ∩ C).
|
|
241
|
+
label_a, label_b, label_c : str
|
|
242
|
+
Display names for the three sets.
|
|
243
|
+
|
|
244
|
+
All 8 atomic zone probabilities are derived as properties.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
p_a: float
|
|
248
|
+
p_b: float
|
|
249
|
+
p_c: float
|
|
250
|
+
p_ab: float
|
|
251
|
+
p_ac: float
|
|
252
|
+
p_bc: float
|
|
253
|
+
p_abc: float
|
|
254
|
+
label_a: str = "A"
|
|
255
|
+
label_b: str = "B"
|
|
256
|
+
label_c: str = "C"
|
|
257
|
+
|
|
258
|
+
def __post_init__(self):
|
|
259
|
+
for attr in ("p_a","p_b","p_c","p_ab","p_ac","p_bc","p_abc"):
|
|
260
|
+
setattr(self, attr, _clamp(getattr(self, attr)))
|
|
261
|
+
self._validate()
|
|
262
|
+
|
|
263
|
+
def _validate(self) -> None:
|
|
264
|
+
msgs = []
|
|
265
|
+
if self.p_abc > min(self.p_ab, self.p_ac, self.p_bc) + 1e-9:
|
|
266
|
+
msgs.append("P(A∩B∩C) > min pairwise intersection")
|
|
267
|
+
for name, mv, mv_name in [
|
|
268
|
+
("p_ab", self.p_a, "p_a"), ("p_ab", self.p_b, "p_b"),
|
|
269
|
+
("p_ac", self.p_a, "p_a"), ("p_ac", self.p_c, "p_c"),
|
|
270
|
+
("p_bc", self.p_b, "p_b"), ("p_bc", self.p_c, "p_c"),
|
|
271
|
+
]:
|
|
272
|
+
if getattr(self, name) > mv + 1e-9:
|
|
273
|
+
msgs.append(f"P({name[2:].upper()})>{mv_name}")
|
|
274
|
+
if msgs:
|
|
275
|
+
warnings.warn("VennData3 inconsistency: " + "; ".join(msgs))
|
|
276
|
+
|
|
277
|
+
# Atomic zone probabilities (inclusion-exclusion decomposition)
|
|
278
|
+
@property
|
|
279
|
+
def p_a_only(self) -> float:
|
|
280
|
+
return max(0.0, self.p_a - self.p_ab - self.p_ac + self.p_abc)
|
|
281
|
+
|
|
282
|
+
@property
|
|
283
|
+
def p_b_only(self) -> float:
|
|
284
|
+
return max(0.0, self.p_b - self.p_ab - self.p_bc + self.p_abc)
|
|
285
|
+
|
|
286
|
+
@property
|
|
287
|
+
def p_c_only(self) -> float:
|
|
288
|
+
return max(0.0, self.p_c - self.p_ac - self.p_bc + self.p_abc)
|
|
289
|
+
|
|
290
|
+
@property
|
|
291
|
+
def p_ab_only(self) -> float:
|
|
292
|
+
return max(0.0, self.p_ab - self.p_abc)
|
|
293
|
+
|
|
294
|
+
@property
|
|
295
|
+
def p_ac_only(self) -> float:
|
|
296
|
+
return max(0.0, self.p_ac - self.p_abc)
|
|
297
|
+
|
|
298
|
+
@property
|
|
299
|
+
def p_bc_only(self) -> float:
|
|
300
|
+
return max(0.0, self.p_bc - self.p_abc)
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def p_abc_zone(self) -> float:
|
|
304
|
+
return max(0.0, self.p_abc)
|
|
305
|
+
|
|
306
|
+
@property
|
|
307
|
+
def p_aub_uc(self) -> float:
|
|
308
|
+
return _clamp(
|
|
309
|
+
self.p_a + self.p_b + self.p_c
|
|
310
|
+
- self.p_ab - self.p_ac - self.p_bc
|
|
311
|
+
+ self.p_abc
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
@property
|
|
315
|
+
def p_neither(self) -> float:
|
|
316
|
+
return max(0.0, 1.0 - self.p_aub_uc)
|
|
317
|
+
|
|
318
|
+
def zone_probs(self) -> dict[str, float]:
|
|
319
|
+
return {
|
|
320
|
+
"a_only": self.p_a_only,
|
|
321
|
+
"b_only": self.p_b_only,
|
|
322
|
+
"c_only": self.p_c_only,
|
|
323
|
+
"ab_only": self.p_ab_only,
|
|
324
|
+
"ac_only": self.p_ac_only,
|
|
325
|
+
"bc_only": self.p_bc_only,
|
|
326
|
+
"abc": self.p_abc_zone,
|
|
327
|
+
"neither": self.p_neither,
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# ---------------------------------------------------------------------------
|
|
332
|
+
# _CircleArcGeometry — analytical circle-circle intersection
|
|
333
|
+
# ---------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
class _CircleArcGeometry:
|
|
336
|
+
"""Compute intersection points and arc parameters for two circles.
|
|
337
|
+
|
|
338
|
+
Given circle C₁ = (cx₁, cz₁, r₁) and C₂ = (cx₂, cz₂, r₂),
|
|
339
|
+
computes (if they intersect) the two intersection points and the
|
|
340
|
+
angular positions of these points as seen from each circle center.
|
|
341
|
+
|
|
342
|
+
These are used to determine which arc segment of each circle forms
|
|
343
|
+
the boundary of each Venn zone.
|
|
344
|
+
|
|
345
|
+
All coordinates are in the XZ plane (y=0 flat).
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
def __init__(
|
|
349
|
+
self,
|
|
350
|
+
cx1: float, cz1: float, r1: float,
|
|
351
|
+
cx2: float, cz2: float, r2: float,
|
|
352
|
+
):
|
|
353
|
+
self.c1 = np.array([cx1, cz1])
|
|
354
|
+
self.c2 = np.array([cx2, cz2])
|
|
355
|
+
self.r1 = r1
|
|
356
|
+
self.r2 = r2
|
|
357
|
+
self._compute()
|
|
358
|
+
|
|
359
|
+
def _compute(self) -> None:
|
|
360
|
+
d = np.linalg.norm(self.c2 - self.c1)
|
|
361
|
+
self.d = d
|
|
362
|
+
|
|
363
|
+
if d < 1e-10 or d > self.r1 + self.r2 + 1e-9 or d < abs(self.r1 - self.r2) - 1e-9:
|
|
364
|
+
self.intersects = False
|
|
365
|
+
self.p1 = self.p2 = None
|
|
366
|
+
self.ang1_p1 = self.ang1_p2 = None
|
|
367
|
+
self.ang2_p1 = self.ang2_p2 = None
|
|
368
|
+
return
|
|
369
|
+
|
|
370
|
+
self.intersects = True
|
|
371
|
+
# Distance along c1→c2 axis to the radical line
|
|
372
|
+
a = (self.r1**2 - self.r2**2 + d**2) / (2 * d)
|
|
373
|
+
# Height of intersection triangle
|
|
374
|
+
h_sq = self.r1**2 - a**2
|
|
375
|
+
h = np.sqrt(max(h_sq, 0.0))
|
|
376
|
+
|
|
377
|
+
# Unit vectors
|
|
378
|
+
u = (self.c2 - self.c1) / d # along axis
|
|
379
|
+
v = np.array([-u[1], u[0]]) # perpendicular
|
|
380
|
+
|
|
381
|
+
# The two intersection points
|
|
382
|
+
mid = self.c1 + a * u
|
|
383
|
+
self.p1 = mid + h * v
|
|
384
|
+
self.p2 = mid - h * v
|
|
385
|
+
|
|
386
|
+
# Angles of intersection points as seen from each center
|
|
387
|
+
def _ang(center, point):
|
|
388
|
+
d = point - center
|
|
389
|
+
return float(np.arctan2(d[1], d[0]))
|
|
390
|
+
|
|
391
|
+
self.ang1_p1 = _ang(self.c1, self.p1)
|
|
392
|
+
self.ang1_p2 = _ang(self.c1, self.p2)
|
|
393
|
+
self.ang2_p1 = _ang(self.c2, self.p1)
|
|
394
|
+
self.ang2_p2 = _ang(self.c2, self.p2)
|
|
395
|
+
|
|
396
|
+
def arc_for_zone(
|
|
397
|
+
self,
|
|
398
|
+
circle_index: int, # 1 or 2
|
|
399
|
+
inside: bool, # True = arc that is INSIDE the other circle
|
|
400
|
+
) -> tuple[float, float]:
|
|
401
|
+
"""Return (theta_start, theta_end) for the relevant arc segment.
|
|
402
|
+
|
|
403
|
+
Parameters
|
|
404
|
+
----------
|
|
405
|
+
circle_index : 1 or 2
|
|
406
|
+
Which circle's arc we want.
|
|
407
|
+
inside : bool
|
|
408
|
+
True → the arc that lies inside the other circle (the "lens" arc)
|
|
409
|
+
False → the arc that lies outside the other circle
|
|
410
|
+
"""
|
|
411
|
+
if not self.intersects:
|
|
412
|
+
# Full circle or no arc
|
|
413
|
+
return (0.0, TAU)
|
|
414
|
+
|
|
415
|
+
if circle_index == 1:
|
|
416
|
+
a1, a2 = self.ang1_p1, self.ang1_p2
|
|
417
|
+
# The "inside" arc is the one that points toward c2
|
|
418
|
+
c_dir = float(np.arctan2(self.c2[1] - self.c1[1],
|
|
419
|
+
self.c2[0] - self.c1[0]))
|
|
420
|
+
else:
|
|
421
|
+
a1, a2 = self.ang2_p1, self.ang2_p2
|
|
422
|
+
c_dir = float(np.arctan2(self.c1[1] - self.c2[1],
|
|
423
|
+
self.c1[0] - self.c2[0]))
|
|
424
|
+
|
|
425
|
+
# Normalise angles to [0, TAU)
|
|
426
|
+
a1 = a1 % TAU
|
|
427
|
+
a2 = a2 % TAU
|
|
428
|
+
c_dir = c_dir % TAU
|
|
429
|
+
|
|
430
|
+
# Determine which arc contains c_dir
|
|
431
|
+
def _arc_contains(start, end, angle):
|
|
432
|
+
angle = angle % TAU
|
|
433
|
+
if start <= end:
|
|
434
|
+
return start <= angle <= end
|
|
435
|
+
else:
|
|
436
|
+
return angle >= start or angle <= end
|
|
437
|
+
|
|
438
|
+
# Arc from a1 → a2 (CCW)
|
|
439
|
+
if _arc_contains(a1, a2, c_dir):
|
|
440
|
+
toward_arc = (a1, a2)
|
|
441
|
+
away_arc = (a2, a1)
|
|
442
|
+
else:
|
|
443
|
+
toward_arc = (a2, a1)
|
|
444
|
+
away_arc = (a1, a2)
|
|
445
|
+
|
|
446
|
+
return toward_arc if inside else away_arc
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
# ---------------------------------------------------------------------------
|
|
450
|
+
# _ZoneSurface — one atomic zone rendered as Surface
|
|
451
|
+
# ---------------------------------------------------------------------------
|
|
452
|
+
|
|
453
|
+
class _ZoneSurface(VGroup):
|
|
454
|
+
"""3D platform for one atomic zone of a Venn diagram.
|
|
455
|
+
|
|
456
|
+
The top surface is a flat disc/patch at height ``y_level``.
|
|
457
|
+
The side wall is a thin extruded ring from y=0 to y=y_level.
|
|
458
|
+
Both are built from Surface using circular arc parametrisation.
|
|
459
|
+
|
|
460
|
+
For zones defined by a single circle arc (single-set zones and the
|
|
461
|
+
lens-shaped intersection), the boundary is one or more arc segments.
|
|
462
|
+
|
|
463
|
+
Parameters
|
|
464
|
+
----------
|
|
465
|
+
arc_def : list[dict]
|
|
466
|
+
Each dict describes one arc segment of the zone boundary:
|
|
467
|
+
{"cx": float, "cz": float, "r": float,
|
|
468
|
+
"t_start": float, "t_end": float, "ccw": bool}
|
|
469
|
+
Arc segments are concatenated to form the closed boundary.
|
|
470
|
+
centroid : np.ndarray
|
|
471
|
+
(x, z) centroid of the zone, used for label placement and
|
|
472
|
+
for building the "fan" parametrisation of the top surface.
|
|
473
|
+
y_level : float
|
|
474
|
+
Height of the top face.
|
|
475
|
+
color : ManimColor
|
|
476
|
+
cfg : VennConfig
|
|
477
|
+
label_tex : str
|
|
478
|
+
Set-notation label (e.g. r"A \cap B^c").
|
|
479
|
+
prob : float
|
|
480
|
+
count : int | None
|
|
481
|
+
Natural frequency count to display (if not None).
|
|
482
|
+
resolution : int
|
|
483
|
+
Number of angular segments per arc.
|
|
484
|
+
"""
|
|
485
|
+
|
|
486
|
+
def __init__(
|
|
487
|
+
self,
|
|
488
|
+
arc_def: list[dict],
|
|
489
|
+
centroid: np.ndarray,
|
|
490
|
+
y_level: float,
|
|
491
|
+
color: ManimColor,
|
|
492
|
+
cfg: "VennConfig",
|
|
493
|
+
label_tex: str = "",
|
|
494
|
+
prob: float = 0.0,
|
|
495
|
+
count: int | None = None,
|
|
496
|
+
resolution: int = 60,
|
|
497
|
+
):
|
|
498
|
+
super().__init__()
|
|
499
|
+
self._color = color
|
|
500
|
+
self._y_level = y_level
|
|
501
|
+
self._centroid = centroid
|
|
502
|
+
self._cfg = cfg
|
|
503
|
+
|
|
504
|
+
# ------ Build the boundary polygon points -----
|
|
505
|
+
# We sample all arc segments at `resolution` points each
|
|
506
|
+
# to get the flat polygon, then build a "fan" surface from centroid.
|
|
507
|
+
bnd_pts: list[np.ndarray] = []
|
|
508
|
+
for seg in arc_def:
|
|
509
|
+
cx, cz = seg["cx"], seg["cz"]
|
|
510
|
+
r = seg["r"]
|
|
511
|
+
t0, t1 = seg["t_start"], seg["t_end"]
|
|
512
|
+
ccw = seg.get("ccw", True)
|
|
513
|
+
n_seg = max(4, int(resolution * abs(t1 - t0) / TAU))
|
|
514
|
+
|
|
515
|
+
if ccw:
|
|
516
|
+
thetas = np.linspace(t0, t1, n_seg, endpoint=False)
|
|
517
|
+
else:
|
|
518
|
+
# Clockwise: go from t0 down to t1 (wrapping if needed)
|
|
519
|
+
if t1 < t0:
|
|
520
|
+
thetas = np.linspace(t0, t1, n_seg, endpoint=False)
|
|
521
|
+
else:
|
|
522
|
+
thetas = np.linspace(t0, t1 - TAU, n_seg, endpoint=False)
|
|
523
|
+
|
|
524
|
+
for theta in thetas:
|
|
525
|
+
bnd_pts.append(np.array([
|
|
526
|
+
cx + r * np.cos(theta),
|
|
527
|
+
cz + r * np.sin(theta),
|
|
528
|
+
]))
|
|
529
|
+
|
|
530
|
+
if len(bnd_pts) < 3:
|
|
531
|
+
return # degenerate zone — skip
|
|
532
|
+
|
|
533
|
+
bnd = np.array(bnd_pts) # (N, 2)
|
|
534
|
+
N = len(bnd)
|
|
535
|
+
|
|
536
|
+
top_color = color
|
|
537
|
+
side_color = _dk(color, FACE_DARKEN)
|
|
538
|
+
opacity = cfg.zone_opacity
|
|
539
|
+
|
|
540
|
+
# ------ Top surface: "fan" triangles from centroid ------
|
|
541
|
+
# Build as a Surface mapping (u, v) → world:
|
|
542
|
+
# u ∈ [0,1) = fraction around the boundary polygon
|
|
543
|
+
# v ∈ [0,1] = radial interpolation centroid → boundary
|
|
544
|
+
cx_xz, cz_xz = centroid[0], centroid[1]
|
|
545
|
+
|
|
546
|
+
def top_fn(u: float, v: float) -> np.ndarray:
|
|
547
|
+
idx_f = u * N
|
|
548
|
+
idx_lo = int(idx_f) % N
|
|
549
|
+
idx_hi = (idx_lo + 1) % N
|
|
550
|
+
alpha = idx_f - int(idx_f)
|
|
551
|
+
bnd_pt = (1 - alpha) * bnd[idx_lo] + alpha * bnd[idx_hi]
|
|
552
|
+
xv = cx_xz + v * (bnd_pt[0] - cx_xz)
|
|
553
|
+
zv = cz_xz + v * (bnd_pt[1] - cz_xz)
|
|
554
|
+
return np.array([xv, y_level, zv])
|
|
555
|
+
|
|
556
|
+
top_surf = Surface(
|
|
557
|
+
top_fn,
|
|
558
|
+
u_range=[0.0, 1.0],
|
|
559
|
+
v_range=[0.0, 1.0],
|
|
560
|
+
resolution=(resolution, max(2, cfg.zone_depth_resolution)),
|
|
561
|
+
)
|
|
562
|
+
top_surf.set_style(
|
|
563
|
+
fill_color=top_color,
|
|
564
|
+
fill_opacity=opacity,
|
|
565
|
+
stroke_color=_dk(top_color, 0.45),
|
|
566
|
+
stroke_width=cfg.zone_stroke_width,
|
|
567
|
+
stroke_opacity=opacity * 0.60,
|
|
568
|
+
)
|
|
569
|
+
self.top_surface = top_surf
|
|
570
|
+
self.add(top_surf)
|
|
571
|
+
|
|
572
|
+
# ------ Side wall: extruded boundary from y=0 to y_level ------
|
|
573
|
+
if y_level > 1e-4 and cfg.show_zone_walls:
|
|
574
|
+
def wall_fn(u: float, v: float) -> np.ndarray:
|
|
575
|
+
idx_f = u * N
|
|
576
|
+
idx_lo = int(idx_f) % N
|
|
577
|
+
idx_hi = (idx_lo + 1) % N
|
|
578
|
+
alpha = idx_f - int(idx_f)
|
|
579
|
+
bnd_pt = (1 - alpha) * bnd[idx_lo] + alpha * bnd[idx_hi]
|
|
580
|
+
yv = v * y_level
|
|
581
|
+
return np.array([bnd_pt[0], yv, bnd_pt[1]])
|
|
582
|
+
|
|
583
|
+
wall = Surface(
|
|
584
|
+
wall_fn,
|
|
585
|
+
u_range=[0.0, 1.0],
|
|
586
|
+
v_range=[0.0, 1.0],
|
|
587
|
+
resolution=(resolution, 3),
|
|
588
|
+
)
|
|
589
|
+
wall.set_style(
|
|
590
|
+
fill_color=side_color,
|
|
591
|
+
fill_opacity=opacity * 0.80,
|
|
592
|
+
stroke_width=0,
|
|
593
|
+
)
|
|
594
|
+
self.add(wall)
|
|
595
|
+
|
|
596
|
+
# ------ Labels ------
|
|
597
|
+
self._label_group = VGroup()
|
|
598
|
+
lbl_x = float(centroid[0])
|
|
599
|
+
lbl_z = float(centroid[1])
|
|
600
|
+
lbl_y = y_level + cfg.label_lift
|
|
601
|
+
|
|
602
|
+
if cfg.show_zone_labels and label_tex:
|
|
603
|
+
set_lbl = MathTex(label_tex,
|
|
604
|
+
color=_lt(color, 0.25),
|
|
605
|
+
font_size=cfg.zone_label_font_size)
|
|
606
|
+
set_lbl.move_to(np.array([lbl_x, lbl_y, lbl_z]))
|
|
607
|
+
self._label_group.add(set_lbl)
|
|
608
|
+
self.set_label = set_lbl
|
|
609
|
+
|
|
610
|
+
if cfg.show_prob_labels and prob > 1e-6:
|
|
611
|
+
prob_lbl = MathTex(
|
|
612
|
+
rf"{prob:.3f}",
|
|
613
|
+
color=_lt(color, 0.15),
|
|
614
|
+
font_size=cfg.prob_label_font_size,
|
|
615
|
+
)
|
|
616
|
+
prob_lbl.move_to(np.array([lbl_x, lbl_y + 0.30, lbl_z]))
|
|
617
|
+
self._label_group.add(prob_lbl)
|
|
618
|
+
self.prob_label = prob_lbl
|
|
619
|
+
|
|
620
|
+
if count is not None and cfg.show_count_labels:
|
|
621
|
+
cnt_lbl = Text(
|
|
622
|
+
f"n={count}",
|
|
623
|
+
color=_lt(color, 0.20),
|
|
624
|
+
font_size=cfg.count_label_font_size,
|
|
625
|
+
)
|
|
626
|
+
cnt_lbl.move_to(np.array([lbl_x, lbl_y + 0.55, lbl_z]))
|
|
627
|
+
self._label_group.add(cnt_lbl)
|
|
628
|
+
|
|
629
|
+
self.add(self._label_group)
|
|
630
|
+
|
|
631
|
+
# Centre point for animation origins
|
|
632
|
+
self._floor_center = np.array([lbl_x, 0.0, lbl_z])
|
|
633
|
+
|
|
634
|
+
@property
|
|
635
|
+
def floor_center(self) -> np.ndarray:
|
|
636
|
+
return self._floor_center.copy()
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
# ---------------------------------------------------------------------------
|
|
640
|
+
# _VennCircleOutline — the classic circle ring floating above zones
|
|
641
|
+
# ---------------------------------------------------------------------------
|
|
642
|
+
|
|
643
|
+
class _VennCircleOutline(VGroup):
|
|
644
|
+
"""Full-circle ParametricFunction ring drawn above the zone surfaces.
|
|
645
|
+
|
|
646
|
+
Provides the "overlapping circles" visual that makes Venn diagrams
|
|
647
|
+
instantly recognisable, layered on top of the 3D zone geometry.
|
|
648
|
+
"""
|
|
649
|
+
|
|
650
|
+
def __init__(
|
|
651
|
+
self,
|
|
652
|
+
cx: float,
|
|
653
|
+
cz: float,
|
|
654
|
+
r: float,
|
|
655
|
+
y: float,
|
|
656
|
+
color: ManimColor,
|
|
657
|
+
stroke_width: float = 2.8,
|
|
658
|
+
opacity: float = OUTLINE_OPACITY,
|
|
659
|
+
):
|
|
660
|
+
super().__init__()
|
|
661
|
+
curve = ParametricFunction(
|
|
662
|
+
lambda t: np.array([cx + r * np.cos(t * TAU),
|
|
663
|
+
y,
|
|
664
|
+
cz + r * np.sin(t * TAU)]),
|
|
665
|
+
t_range=[0, 1, 1 / 120],
|
|
666
|
+
color=color,
|
|
667
|
+
stroke_width=stroke_width,
|
|
668
|
+
)
|
|
669
|
+
curve.set_opacity(opacity)
|
|
670
|
+
self.add(curve)
|
|
671
|
+
self.curve = curve
|
|
672
|
+
self._cx, self._cz, self._r = cx, cz, r
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
# ---------------------------------------------------------------------------
|
|
676
|
+
# _InclusionExclusionBracket — P(A∪B) annotation
|
|
677
|
+
# ---------------------------------------------------------------------------
|
|
678
|
+
|
|
679
|
+
class _InclusionExclusionBracket(VGroup):
|
|
680
|
+
"""Color-coded MathTex showing P(A∪B) = P(A) + P(B) − P(A∩B).
|
|
681
|
+
|
|
682
|
+
Each term is colored to match the corresponding zone color.
|
|
683
|
+
"""
|
|
684
|
+
|
|
685
|
+
def __init__(
|
|
686
|
+
self,
|
|
687
|
+
data: VennData2,
|
|
688
|
+
pos: np.ndarray,
|
|
689
|
+
font_size: int = 28,
|
|
690
|
+
):
|
|
691
|
+
super().__init__()
|
|
692
|
+
# Build multi-color formula using separate MathTex objects
|
|
693
|
+
terms = [
|
|
694
|
+
(rf"P({data.label_a} \cup {data.label_b})",
|
|
695
|
+
_lt(ZONE_AB, 0.20), 0.0),
|
|
696
|
+
(r"=", LABEL_COLOR, 0.0),
|
|
697
|
+
(rf"P({data.label_a})",
|
|
698
|
+
_lt(ZONE_A_ONLY, 0.20), 0.0),
|
|
699
|
+
(r"+", LABEL_COLOR, 0.0),
|
|
700
|
+
(rf"P({data.label_b})",
|
|
701
|
+
_lt(ZONE_B_ONLY, 0.20), 0.0),
|
|
702
|
+
(r"-", LABEL_COLOR, 0.0),
|
|
703
|
+
(rf"P({data.label_a} \cap {data.label_b})",
|
|
704
|
+
_lt(ZONE_AB, 0.20), 0.0),
|
|
705
|
+
]
|
|
706
|
+
values = [
|
|
707
|
+
(rf"= {data.p_aub:.3f}", _lt(ZONE_AB, 0.10), 0.35),
|
|
708
|
+
("", LABEL_COLOR, 0.0),
|
|
709
|
+
(rf"= {data.p_a:.3f}", _lt(ZONE_A_ONLY, 0.10), 0.35),
|
|
710
|
+
("", LABEL_COLOR, 0.0),
|
|
711
|
+
(rf"= {data.p_b:.3f}", _lt(ZONE_B_ONLY, 0.10), 0.35),
|
|
712
|
+
("", LABEL_COLOR, 0.0),
|
|
713
|
+
(rf"= {data.p_ab:.3f}", _lt(ZONE_AB, 0.10), 0.35),
|
|
714
|
+
]
|
|
715
|
+
|
|
716
|
+
self.term_objects: list[VGroup] = []
|
|
717
|
+
x_cursor = pos[0] - 3.5
|
|
718
|
+
for (tex, color, _), (val, vcol, vshift) in zip(terms, values):
|
|
719
|
+
grp = VGroup()
|
|
720
|
+
lbl = MathTex(tex, color=color, font_size=font_size)
|
|
721
|
+
lbl.move_to(np.array([x_cursor, pos[1], pos[2]]))
|
|
722
|
+
grp.add(lbl)
|
|
723
|
+
x_cursor += lbl.width + 0.18
|
|
724
|
+
if val:
|
|
725
|
+
vlbl = MathTex(val, color=vcol, font_size=font_size - 6)
|
|
726
|
+
vlbl.move_to(np.array([x_cursor - lbl.width / 2,
|
|
727
|
+
pos[1] - vshift, pos[2]]))
|
|
728
|
+
grp.add(vlbl)
|
|
729
|
+
self.term_objects.append(grp)
|
|
730
|
+
self.add(grp)
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
# ---------------------------------------------------------------------------
|
|
734
|
+
# _IndependenceAnnotation — P(A∩B) vs P(A)·P(B)
|
|
735
|
+
# ---------------------------------------------------------------------------
|
|
736
|
+
|
|
737
|
+
class _IndependenceAnnotation(VGroup):
|
|
738
|
+
"""Show P(A∩B) and P(A)·P(B) side by side with a verdict symbol."""
|
|
739
|
+
|
|
740
|
+
def __init__(
|
|
741
|
+
self,
|
|
742
|
+
data: VennData2,
|
|
743
|
+
pos: np.ndarray,
|
|
744
|
+
font_size: int = 26,
|
|
745
|
+
tol: float = 0.005,
|
|
746
|
+
):
|
|
747
|
+
super().__init__()
|
|
748
|
+
product = data.p_a * data.p_b
|
|
749
|
+
is_ind = abs(data.p_ab - product) < tol
|
|
750
|
+
|
|
751
|
+
color = ManimColor("#00E676") if is_ind else ManimColor("#FF5252")
|
|
752
|
+
symbol = r"\approx" if is_ind else r"\neq"
|
|
753
|
+
verdict = "Independent" if is_ind else "Dependent"
|
|
754
|
+
|
|
755
|
+
lhs = MathTex(
|
|
756
|
+
rf"P({data.label_a} \cap {data.label_b}) = {data.p_ab:.4f}",
|
|
757
|
+
color=_lt(ZONE_AB, 0.20),
|
|
758
|
+
font_size=font_size,
|
|
759
|
+
)
|
|
760
|
+
sym = MathTex(symbol, color=color, font_size=font_size)
|
|
761
|
+
rhs = MathTex(
|
|
762
|
+
rf"P({data.label_a}) \cdot P({data.label_b}) = {product:.4f}",
|
|
763
|
+
color=LABEL_COLOR,
|
|
764
|
+
font_size=font_size,
|
|
765
|
+
)
|
|
766
|
+
ver = Text(verdict, color=color, font_size=font_size - 4,
|
|
767
|
+
weight="BOLD")
|
|
768
|
+
|
|
769
|
+
lhs.move_to(pos + np.array([-2.8, 0, 0]))
|
|
770
|
+
sym.move_to(pos)
|
|
771
|
+
rhs.move_to(pos + np.array([ 2.8, 0, 0]))
|
|
772
|
+
ver.move_to(pos + np.array([0, -0.45, 0]))
|
|
773
|
+
|
|
774
|
+
self.add(lhs, sym, rhs, ver)
|
|
775
|
+
self.lhs = lhs
|
|
776
|
+
self.sym = sym
|
|
777
|
+
self.rhs = rhs
|
|
778
|
+
self.verdict = ver
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
# ---------------------------------------------------------------------------
|
|
782
|
+
# VennConfig
|
|
783
|
+
# ---------------------------------------------------------------------------
|
|
784
|
+
|
|
785
|
+
@dataclass
|
|
786
|
+
class VennConfig:
|
|
787
|
+
"""All visual parameters for VennDiagram3D.
|
|
788
|
+
|
|
789
|
+
Circle geometry
|
|
790
|
+
---------------
|
|
791
|
+
circle_radius : float
|
|
792
|
+
Radius of each Venn circle (Manim units).
|
|
793
|
+
circle_separation : float
|
|
794
|
+
Centre-to-centre distance between adjacent circles as a
|
|
795
|
+
fraction of circle_radius. 0.8 → heavy overlap; 1.4 → light.
|
|
796
|
+
layout : str
|
|
797
|
+
``"standard"`` – classic side-by-side (2-set) or triangle (3-set)
|
|
798
|
+
``"linear"`` – all circles on the x-axis
|
|
799
|
+
``"nested"`` – A inside B (use only when A ⊆ B)
|
|
800
|
+
``"euler"`` – disjoint circles (no overlap)
|
|
801
|
+
|
|
802
|
+
Zone surfaces
|
|
803
|
+
-------------
|
|
804
|
+
zone_opacity : float
|
|
805
|
+
Fill opacity of zone top surfaces.
|
|
806
|
+
zone_stroke_width : float
|
|
807
|
+
Mesh line width on zone surfaces.
|
|
808
|
+
show_zone_walls : bool
|
|
809
|
+
Extrude side walls from each zone boundary.
|
|
810
|
+
zone_depth_resolution : int
|
|
811
|
+
Number of v-slices in the side wall extrusion (2–4 is enough).
|
|
812
|
+
height_single : float
|
|
813
|
+
Platform height for single-set zones (A only, B only, C only).
|
|
814
|
+
height_double : float
|
|
815
|
+
Platform height for two-set intersection zones.
|
|
816
|
+
height_triple : float
|
|
817
|
+
Platform height for the triple intersection zone.
|
|
818
|
+
height_neither : float
|
|
819
|
+
Platform height for the "neither" background zone (usually 0).
|
|
820
|
+
|
|
821
|
+
Circle outlines
|
|
822
|
+
---------------
|
|
823
|
+
show_outlines : bool
|
|
824
|
+
Render the floating circle outlines above the zones.
|
|
825
|
+
outline_stroke_width : float
|
|
826
|
+
Stroke width of circle outline curves.
|
|
827
|
+
outline_y_lift : float
|
|
828
|
+
How high above the tallest zone the outline floats.
|
|
829
|
+
|
|
830
|
+
Labels
|
|
831
|
+
------
|
|
832
|
+
show_set_labels : bool
|
|
833
|
+
Show A/B/C labels at the far end of each circle.
|
|
834
|
+
show_zone_labels : bool
|
|
835
|
+
Show set-notation labels (A∩Bᶜ, etc.) inside each zone.
|
|
836
|
+
show_prob_labels : bool
|
|
837
|
+
Show probability values inside each zone.
|
|
838
|
+
show_count_labels : bool
|
|
839
|
+
Show natural frequency counts inside zones (requires total N).
|
|
840
|
+
label_lift : float
|
|
841
|
+
Y offset above the zone top for floating labels.
|
|
842
|
+
set_label_font_size : int
|
|
843
|
+
zone_label_font_size : int
|
|
844
|
+
prob_label_font_size : int
|
|
845
|
+
count_label_font_size : int
|
|
846
|
+
|
|
847
|
+
Annotations
|
|
848
|
+
-----------
|
|
849
|
+
show_inclusion_exclusion : bool
|
|
850
|
+
Show the P(A∪B) formula annotation below the diagram.
|
|
851
|
+
show_independence_test : bool
|
|
852
|
+
Show the P(A∩B) vs P(A)·P(B) annotation.
|
|
853
|
+
annotation_y_offset : float
|
|
854
|
+
How far below the diagram the formula annotations sit.
|
|
855
|
+
annotation_font_size : int
|
|
856
|
+
|
|
857
|
+
Ω box
|
|
858
|
+
-----
|
|
859
|
+
show_omega_box : bool
|
|
860
|
+
Draw a bounding rectangle indicating the sample space.
|
|
861
|
+
omega_box_padding : float
|
|
862
|
+
Extra clearance around the circles for the Ω box.
|
|
863
|
+
omega_stroke_width : float
|
|
864
|
+
omega_font_size : int
|
|
865
|
+
"""
|
|
866
|
+
|
|
867
|
+
# ---- circle geometry ----
|
|
868
|
+
circle_radius: float = 1.80
|
|
869
|
+
circle_separation: float = 1.05 # fraction of radius
|
|
870
|
+
layout: str = "standard"
|
|
871
|
+
|
|
872
|
+
# ---- zone surfaces ----
|
|
873
|
+
zone_opacity: float = 0.68
|
|
874
|
+
zone_stroke_width: float = 0.25
|
|
875
|
+
show_zone_walls: bool = True
|
|
876
|
+
zone_depth_resolution: int = 3
|
|
877
|
+
height_single: float = 0.16
|
|
878
|
+
height_double: float = 0.30
|
|
879
|
+
height_triple: float = 0.44
|
|
880
|
+
height_neither: float = 0.00
|
|
881
|
+
|
|
882
|
+
# ---- circle outlines ----
|
|
883
|
+
show_outlines: bool = True
|
|
884
|
+
outline_stroke_width: float = 2.80
|
|
885
|
+
outline_y_lift: float = 0.08
|
|
886
|
+
|
|
887
|
+
# ---- labels ----
|
|
888
|
+
show_set_labels: bool = True
|
|
889
|
+
show_zone_labels: bool = True
|
|
890
|
+
show_prob_labels: bool = True
|
|
891
|
+
show_count_labels: bool = False
|
|
892
|
+
label_lift: float = 0.22
|
|
893
|
+
set_label_font_size: int = 36
|
|
894
|
+
zone_label_font_size: int = 20
|
|
895
|
+
prob_label_font_size: int = 18
|
|
896
|
+
count_label_font_size: int = 16
|
|
897
|
+
|
|
898
|
+
# ---- annotations ----
|
|
899
|
+
show_inclusion_exclusion: bool = False
|
|
900
|
+
show_independence_test: bool = False
|
|
901
|
+
annotation_y_offset: float = -1.40
|
|
902
|
+
annotation_font_size: int = 26
|
|
903
|
+
|
|
904
|
+
# ---- Ω box ----
|
|
905
|
+
show_omega_box: bool = True
|
|
906
|
+
omega_box_padding: float = 0.55
|
|
907
|
+
omega_stroke_width: float = 1.50
|
|
908
|
+
omega_font_size: int = 32
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
# ---------------------------------------------------------------------------
|
|
912
|
+
# _CircleLayout — compute circle centre positions from config
|
|
913
|
+
# ---------------------------------------------------------------------------
|
|
914
|
+
|
|
915
|
+
def _circle_centres_2(cfg: VennConfig) -> tuple[np.ndarray, np.ndarray]:
|
|
916
|
+
"""Return (c1, c2) in XZ plane for a 2-set layout."""
|
|
917
|
+
r = cfg.circle_radius
|
|
918
|
+
s = cfg.circle_separation
|
|
919
|
+
d = r * s # centre-to-centre half distance
|
|
920
|
+
|
|
921
|
+
if cfg.layout in ("standard", "linear"):
|
|
922
|
+
return np.array([-d, 0.0]), np.array([d, 0.0])
|
|
923
|
+
elif cfg.layout == "nested":
|
|
924
|
+
# A inside B: place both at origin, B has larger radius (handled externally)
|
|
925
|
+
return np.array([0.0, 0.0]), np.array([0.0, 0.0])
|
|
926
|
+
elif cfg.layout == "euler":
|
|
927
|
+
# Disjoint: circles do not overlap
|
|
928
|
+
gap = r * 0.20
|
|
929
|
+
return np.array([-r - gap, 0.0]), np.array([r + gap, 0.0])
|
|
930
|
+
else:
|
|
931
|
+
return np.array([-d, 0.0]), np.array([d, 0.0])
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def _circle_centres_3(cfg: VennConfig) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
935
|
+
"""Return (c_a, c_b, c_c) in XZ plane for a 3-set layout."""
|
|
936
|
+
r = cfg.circle_radius
|
|
937
|
+
s = cfg.circle_separation
|
|
938
|
+
d = r * s
|
|
939
|
+
|
|
940
|
+
if cfg.layout in ("standard", "linear"):
|
|
941
|
+
# Equilateral triangle
|
|
942
|
+
cx_a = -d
|
|
943
|
+
cx_b = d
|
|
944
|
+
cx_c = 0.0
|
|
945
|
+
cz_a = d * 0.55
|
|
946
|
+
cz_b = d * 0.55
|
|
947
|
+
cz_c = -d * 0.90
|
|
948
|
+
return (np.array([cx_a, cz_a]),
|
|
949
|
+
np.array([cx_b, cz_b]),
|
|
950
|
+
np.array([cx_c, cz_c]))
|
|
951
|
+
else:
|
|
952
|
+
return (np.array([-d, 0.0]),
|
|
953
|
+
np.array([d, 0.0]),
|
|
954
|
+
np.array([0.0, -d * 1.2]))
|
|
955
|
+
|
|
956
|
+
|
|
957
|
+
# ---------------------------------------------------------------------------
|
|
958
|
+
# Zone arc definitions — compute arc_def lists for each zone
|
|
959
|
+
# ---------------------------------------------------------------------------
|
|
960
|
+
|
|
961
|
+
def _zone_arcs_2(
|
|
962
|
+
c1: np.ndarray, r1: float,
|
|
963
|
+
c2: np.ndarray, r2: float,
|
|
964
|
+
geo: _CircleArcGeometry,
|
|
965
|
+
) -> dict[str, tuple[list[dict], np.ndarray]]:
|
|
966
|
+
"""Return arc_def and centroid for each of the 3 zones of a 2-set Venn.
|
|
967
|
+
|
|
968
|
+
Returns dict with keys "a_only", "b_only", "ab".
|
|
969
|
+
Value is (arc_def_list, centroid_xz).
|
|
970
|
+
"""
|
|
971
|
+
if not geo.intersects:
|
|
972
|
+
# Return full-circle zones for disjoint / subset cases
|
|
973
|
+
def _full(cx, cz, r, toward=None):
|
|
974
|
+
return [{"cx": cx, "cz": cz, "r": r,
|
|
975
|
+
"t_start": 0.0, "t_end": TAU, "ccw": True}]
|
|
976
|
+
return {
|
|
977
|
+
"a_only": (_full(c1[0], c1[1], r1), c1.copy()),
|
|
978
|
+
"b_only": (_full(c2[0], c2[1], r2), c2.copy()),
|
|
979
|
+
"ab": ([], np.array([0.0, 0.0])),
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
# Arc of circle 1 that is OUTSIDE circle 2 = a_only boundary
|
|
983
|
+
ta1_out = geo.arc_for_zone(1, inside=False)
|
|
984
|
+
# Arc of circle 1 INSIDE circle 2 = ab boundary (circle-1 side)
|
|
985
|
+
ta1_in = geo.arc_for_zone(1, inside=True)
|
|
986
|
+
# Arc of circle 2 OUTSIDE circle 1 = b_only boundary
|
|
987
|
+
ta2_out = geo.arc_for_zone(2, inside=False)
|
|
988
|
+
# Arc of circle 2 INSIDE circle 1 = ab boundary (circle-2 side)
|
|
989
|
+
ta2_in = geo.arc_for_zone(2, inside=True)
|
|
990
|
+
|
|
991
|
+
# a_only: outer arc of circle 1
|
|
992
|
+
a_only_arcs = [
|
|
993
|
+
{"cx": c1[0], "cz": c1[1], "r": r1,
|
|
994
|
+
"t_start": ta1_out[0], "t_end": ta1_out[1], "ccw": True},
|
|
995
|
+
]
|
|
996
|
+
a_only_centroid = c1 - np.array([(c2[0]-c1[0])*0.40, (c2[1]-c1[1])*0.40])
|
|
997
|
+
|
|
998
|
+
# b_only: outer arc of circle 2
|
|
999
|
+
b_only_arcs = [
|
|
1000
|
+
{"cx": c2[0], "cz": c2[1], "r": r2,
|
|
1001
|
+
"t_start": ta2_out[0], "t_end": ta2_out[1], "ccw": True},
|
|
1002
|
+
]
|
|
1003
|
+
b_only_centroid = c2 - np.array([(c1[0]-c2[0])*0.40, (c1[1]-c2[1])*0.40])
|
|
1004
|
+
|
|
1005
|
+
# ab (lens): inner arc of circle 1 then inner arc of circle 2 (reversed)
|
|
1006
|
+
ab_arcs = [
|
|
1007
|
+
{"cx": c1[0], "cz": c1[1], "r": r1,
|
|
1008
|
+
"t_start": ta1_in[0], "t_end": ta1_in[1], "ccw": True},
|
|
1009
|
+
{"cx": c2[0], "cz": c2[1], "r": r2,
|
|
1010
|
+
"t_start": ta2_in[1], "t_end": ta2_in[0], "ccw": False},
|
|
1011
|
+
]
|
|
1012
|
+
ab_centroid = (c1 + c2) / 2
|
|
1013
|
+
|
|
1014
|
+
return {
|
|
1015
|
+
"a_only": (a_only_arcs, a_only_centroid),
|
|
1016
|
+
"b_only": (b_only_arcs, b_only_centroid),
|
|
1017
|
+
"ab": (ab_arcs, ab_centroid),
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
# ---------------------------------------------------------------------------
|
|
1022
|
+
# Main VennDiagram3D class
|
|
1023
|
+
# ---------------------------------------------------------------------------
|
|
1024
|
+
|
|
1025
|
+
class VennDiagram3D(VGroup):
|
|
1026
|
+
"""A detailed 3D Venn diagram for Manim probability animations.
|
|
1027
|
+
|
|
1028
|
+
Supports 2-set and 3-set Venn diagrams with analytically computed
|
|
1029
|
+
zone boundaries, height-tiered platforms, floating circle outlines,
|
|
1030
|
+
and a comprehensive animation API.
|
|
1031
|
+
|
|
1032
|
+
Basic 2-set usage
|
|
1033
|
+
-----------------
|
|
1034
|
+
>>> from manim import *
|
|
1035
|
+
>>> from statanim.probability.venn3d import (
|
|
1036
|
+
... VennDiagram3D, VennData2, VennConfig
|
|
1037
|
+
... )
|
|
1038
|
+
>>>
|
|
1039
|
+
>>> class MyScene(ThreeDScene):
|
|
1040
|
+
... def construct(self):
|
|
1041
|
+
... data = VennData2(p_a=0.40, p_b=0.35, p_ab=0.15)
|
|
1042
|
+
... cfg = VennConfig(show_prob_labels=True)
|
|
1043
|
+
... venn = VennDiagram3D.two_set(data, config=cfg)
|
|
1044
|
+
... self.set_camera_orientation(phi=60*DEGREES, theta=-45*DEGREES)
|
|
1045
|
+
... self.play(venn.animate_grow_circles())
|
|
1046
|
+
... self.play(venn.animate_fill_zones())
|
|
1047
|
+
... self.play(venn.animate_inclusion_exclusion())
|
|
1048
|
+
|
|
1049
|
+
Parameters
|
|
1050
|
+
----------
|
|
1051
|
+
config : VennConfig, optional
|
|
1052
|
+
"""
|
|
1053
|
+
|
|
1054
|
+
def __init__(self, config: VennConfig | None = None):
|
|
1055
|
+
super().__init__()
|
|
1056
|
+
self.cfg = config or VennConfig()
|
|
1057
|
+
|
|
1058
|
+
# Populated by build methods
|
|
1059
|
+
self._zones: dict[str, _ZoneSurface] = {}
|
|
1060
|
+
self._outlines: list[_VennCircleOutline] = []
|
|
1061
|
+
self._set_labels: list[MathTex] = []
|
|
1062
|
+
self._data2: VennData2 | None = None
|
|
1063
|
+
self._data3: VennData3 | None = None
|
|
1064
|
+
self._omega_box: VGroup | None = None
|
|
1065
|
+
self._annots: VGroup = VGroup()
|
|
1066
|
+
self.add(self._annots)
|
|
1067
|
+
|
|
1068
|
+
# ------------------------------------------------------------------
|
|
1069
|
+
# Internal builders
|
|
1070
|
+
# ------------------------------------------------------------------
|
|
1071
|
+
|
|
1072
|
+
def _build_omega_box(
|
|
1073
|
+
self,
|
|
1074
|
+
x_min: float, x_max: float,
|
|
1075
|
+
z_min: float, z_max: float,
|
|
1076
|
+
y: float,
|
|
1077
|
+
) -> None:
|
|
1078
|
+
"""Draw the Ω bounding rectangle."""
|
|
1079
|
+
cfg = self.cfg
|
|
1080
|
+
p = cfg.omega_box_padding
|
|
1081
|
+
x0, x1 = x_min - p, x_max + p
|
|
1082
|
+
z0, z1 = z_min - p, z_max + p
|
|
1083
|
+
|
|
1084
|
+
corners = [
|
|
1085
|
+
np.array([x0, y, z0]),
|
|
1086
|
+
np.array([x1, y, z0]),
|
|
1087
|
+
np.array([x1, y, z1]),
|
|
1088
|
+
np.array([x0, y, z1]),
|
|
1089
|
+
]
|
|
1090
|
+
edges = [(0,1),(1,2),(2,3),(3,0)]
|
|
1091
|
+
grp = VGroup()
|
|
1092
|
+
for i, j in edges:
|
|
1093
|
+
line = Line3D(
|
|
1094
|
+
start=corners[i], end=corners[j],
|
|
1095
|
+
color=GRAY_C,
|
|
1096
|
+
stroke_width=cfg.omega_stroke_width,
|
|
1097
|
+
)
|
|
1098
|
+
line.set_opacity(0.65)
|
|
1099
|
+
grp.add(line)
|
|
1100
|
+
|
|
1101
|
+
omega_lbl = MathTex(r"\Omega", color=GRAY_C,
|
|
1102
|
+
font_size=cfg.omega_font_size)
|
|
1103
|
+
omega_lbl.move_to(np.array([x1 + 0.25, y + 0.22, z0]))
|
|
1104
|
+
grp.add(omega_lbl)
|
|
1105
|
+
|
|
1106
|
+
self._omega_box = grp
|
|
1107
|
+
self.add(grp)
|
|
1108
|
+
|
|
1109
|
+
def _add_zone(
|
|
1110
|
+
self,
|
|
1111
|
+
name: str,
|
|
1112
|
+
arc_def: list[dict],
|
|
1113
|
+
centroid: np.ndarray,
|
|
1114
|
+
y_level: float,
|
|
1115
|
+
color: ManimColor,
|
|
1116
|
+
label_tex: str,
|
|
1117
|
+
prob: float,
|
|
1118
|
+
count: int | None = None,
|
|
1119
|
+
) -> _ZoneSurface:
|
|
1120
|
+
zone = _ZoneSurface(
|
|
1121
|
+
arc_def=arc_def,
|
|
1122
|
+
centroid=centroid,
|
|
1123
|
+
y_level=y_level,
|
|
1124
|
+
color=color,
|
|
1125
|
+
cfg=self.cfg,
|
|
1126
|
+
label_tex=label_tex,
|
|
1127
|
+
prob=prob,
|
|
1128
|
+
count=count,
|
|
1129
|
+
)
|
|
1130
|
+
self._zones[name] = zone
|
|
1131
|
+
self.add(zone)
|
|
1132
|
+
return zone
|
|
1133
|
+
|
|
1134
|
+
def _build_2set(
|
|
1135
|
+
self,
|
|
1136
|
+
data: VennData2,
|
|
1137
|
+
circles: tuple[np.ndarray, np.ndarray],
|
|
1138
|
+
radii: tuple[float, float] = (None, None),
|
|
1139
|
+
total_n: int | None = None,
|
|
1140
|
+
) -> None:
|
|
1141
|
+
cfg = self.cfg
|
|
1142
|
+
c1, c2 = circles
|
|
1143
|
+
r1 = radii[0] or cfg.circle_radius
|
|
1144
|
+
r2 = radii[1] or cfg.circle_radius
|
|
1145
|
+
|
|
1146
|
+
geo = _CircleArcGeometry(c1[0], c1[1], r1, c2[0], c2[1], r2)
|
|
1147
|
+
zones = _zone_arcs_2(c1, r1, c2, r2, geo)
|
|
1148
|
+
zp = data.zone_probs()
|
|
1149
|
+
|
|
1150
|
+
def _cnt(p): return round(total_n * p) if total_n else None
|
|
1151
|
+
|
|
1152
|
+
la, lb = data.label_a, data.label_b
|
|
1153
|
+
|
|
1154
|
+
self._add_zone(
|
|
1155
|
+
"a_only",
|
|
1156
|
+
*zones["a_only"],
|
|
1157
|
+
y_level=cfg.height_single,
|
|
1158
|
+
color=ZONE_A_ONLY,
|
|
1159
|
+
label_tex=rf"{la} \cap {lb}^c",
|
|
1160
|
+
prob=zp["a_only"],
|
|
1161
|
+
count=_cnt(zp["a_only"]),
|
|
1162
|
+
)
|
|
1163
|
+
self._add_zone(
|
|
1164
|
+
"b_only",
|
|
1165
|
+
*zones["b_only"],
|
|
1166
|
+
y_level=cfg.height_single,
|
|
1167
|
+
color=ZONE_B_ONLY,
|
|
1168
|
+
label_tex=rf"{la}^c \cap {lb}",
|
|
1169
|
+
prob=zp["b_only"],
|
|
1170
|
+
count=_cnt(zp["b_only"]),
|
|
1171
|
+
)
|
|
1172
|
+
if geo.intersects and zp["ab"] > 1e-5:
|
|
1173
|
+
self._add_zone(
|
|
1174
|
+
"ab",
|
|
1175
|
+
*zones["ab"],
|
|
1176
|
+
y_level=cfg.height_double,
|
|
1177
|
+
color=ZONE_AB,
|
|
1178
|
+
label_tex=rf"{la} \cap {lb}",
|
|
1179
|
+
prob=zp["ab"],
|
|
1180
|
+
count=_cnt(zp["ab"]),
|
|
1181
|
+
)
|
|
1182
|
+
|
|
1183
|
+
# Circle outlines
|
|
1184
|
+
if cfg.show_outlines:
|
|
1185
|
+
y_out = cfg.height_double + cfg.outline_y_lift
|
|
1186
|
+
for cx_arr, r, col in [(c1, r1, SET_A_COLOR), (c2, r2, SET_B_COLOR)]:
|
|
1187
|
+
out = _VennCircleOutline(
|
|
1188
|
+
cx=cx_arr[0], cz=cx_arr[1], r=r,
|
|
1189
|
+
y=y_out, color=col,
|
|
1190
|
+
stroke_width=cfg.outline_stroke_width,
|
|
1191
|
+
)
|
|
1192
|
+
self._outlines.append(out)
|
|
1193
|
+
self.add(out)
|
|
1194
|
+
|
|
1195
|
+
# Set name labels
|
|
1196
|
+
if cfg.show_set_labels:
|
|
1197
|
+
y_lbl = cfg.height_single + 0.38
|
|
1198
|
+
for cx_arr, r, col, label in [
|
|
1199
|
+
(c1, r1, SET_A_COLOR, la),
|
|
1200
|
+
(c2, r2, SET_B_COLOR, lb),
|
|
1201
|
+
]:
|
|
1202
|
+
# Place label at the far end of the circle (away from the other)
|
|
1203
|
+
direction = cx_arr - (c1 + c2) / 2
|
|
1204
|
+
norm = np.linalg.norm(direction)
|
|
1205
|
+
if norm > 1e-4:
|
|
1206
|
+
direction = direction / norm
|
|
1207
|
+
else:
|
|
1208
|
+
direction = np.array([1.0, 0.0])
|
|
1209
|
+
pos = np.array([
|
|
1210
|
+
cx_arr[0] + direction[0] * r * 0.72,
|
|
1211
|
+
y_lbl,
|
|
1212
|
+
cx_arr[1] + direction[1] * r * 0.72,
|
|
1213
|
+
])
|
|
1214
|
+
slbl = MathTex(label, color=col,
|
|
1215
|
+
font_size=cfg.set_label_font_size)
|
|
1216
|
+
slbl.move_to(pos)
|
|
1217
|
+
self._set_labels.append(slbl)
|
|
1218
|
+
self.add(slbl)
|
|
1219
|
+
|
|
1220
|
+
# Omega box
|
|
1221
|
+
if cfg.show_omega_box:
|
|
1222
|
+
all_x = [c1[0] - r1, c1[0] + r1, c2[0] - r2, c2[0] + r2]
|
|
1223
|
+
all_z = [c1[1] - r1, c1[1] + r1, c2[1] - r2, c2[1] + r2]
|
|
1224
|
+
self._build_omega_box(
|
|
1225
|
+
min(all_x), max(all_x), min(all_z), max(all_z),
|
|
1226
|
+
y=0.0,
|
|
1227
|
+
)
|
|
1228
|
+
|
|
1229
|
+
# Annotations
|
|
1230
|
+
ann_y = cfg.annotation_y_offset
|
|
1231
|
+
ann_z = (c1[1] + c2[1]) / 2
|
|
1232
|
+
|
|
1233
|
+
if cfg.show_inclusion_exclusion:
|
|
1234
|
+
ie = _InclusionExclusionBracket(
|
|
1235
|
+
data=data,
|
|
1236
|
+
pos=np.array([0.0, ann_y, ann_z]),
|
|
1237
|
+
font_size=cfg.annotation_font_size,
|
|
1238
|
+
)
|
|
1239
|
+
self._annots.add(ie)
|
|
1240
|
+
self.ie_banner = ie
|
|
1241
|
+
|
|
1242
|
+
if cfg.show_independence_test:
|
|
1243
|
+
ind = _IndependenceAnnotation(
|
|
1244
|
+
data=data,
|
|
1245
|
+
pos=np.array([0.0, ann_y - 0.55, ann_z]),
|
|
1246
|
+
font_size=cfg.annotation_font_size,
|
|
1247
|
+
)
|
|
1248
|
+
self._annots.add(ind)
|
|
1249
|
+
self.independence_banner = ind
|
|
1250
|
+
|
|
1251
|
+
def _build_3set(
|
|
1252
|
+
self,
|
|
1253
|
+
data: VennData3,
|
|
1254
|
+
circles: tuple[np.ndarray, np.ndarray, np.ndarray],
|
|
1255
|
+
total_n: int | None = None,
|
|
1256
|
+
) -> None:
|
|
1257
|
+
cfg = self.cfg
|
|
1258
|
+
c1, c2, c3 = circles
|
|
1259
|
+
r = cfg.circle_radius
|
|
1260
|
+
zp = data.zone_probs()
|
|
1261
|
+
|
|
1262
|
+
def _cnt(p): return round(total_n * p) if total_n else None
|
|
1263
|
+
|
|
1264
|
+
la, lb, lc = data.label_a, data.label_b, data.label_c
|
|
1265
|
+
|
|
1266
|
+
geo12 = _CircleArcGeometry(c1[0],c1[1],r, c2[0],c2[1],r)
|
|
1267
|
+
geo13 = _CircleArcGeometry(c1[0],c1[1],r, c3[0],c3[1],r)
|
|
1268
|
+
geo23 = _CircleArcGeometry(c2[0],c2[1],r, c3[0],c3[1],r)
|
|
1269
|
+
|
|
1270
|
+
# ---- Single zones (approximated as circle sectors with other circles cut out)
|
|
1271
|
+
# We approximate each single zone as the outer arc of its circle
|
|
1272
|
+
# minus both pairwise overlaps. For visual rendering we use the
|
|
1273
|
+
# full outer arc (partial circle patch) as a simple approximation.
|
|
1274
|
+
single_specs = [
|
|
1275
|
+
("a_only", c1, r, SET_A_COLOR, ZONE_A_ONLY,
|
|
1276
|
+
rf"{la} \cap {lb}^c \cap {lc}^c", zp["a_only"]),
|
|
1277
|
+
("b_only", c2, r, SET_B_COLOR, ZONE_B_ONLY,
|
|
1278
|
+
rf"{la}^c \cap {lb} \cap {lc}^c", zp["b_only"]),
|
|
1279
|
+
("c_only", c3, r, SET_C_COLOR, ZONE_C_ONLY,
|
|
1280
|
+
rf"{la}^c \cap {lb}^c \cap {lc}", zp["c_only"]),
|
|
1281
|
+
]
|
|
1282
|
+
for name, c, rad, _, color, label_tex, prob in single_specs:
|
|
1283
|
+
if prob < 1e-5:
|
|
1284
|
+
continue
|
|
1285
|
+
# Build outer arc (the non-overlapping lune)
|
|
1286
|
+
# Approximate: use full circle arcs and rely on opacity layering
|
|
1287
|
+
full_arc = [{"cx": float(c[0]), "cz": float(c[1]), "r": rad,
|
|
1288
|
+
"t_start": 0.0, "t_end": TAU, "ccw": True}]
|
|
1289
|
+
# Centroid pushed away from centre
|
|
1290
|
+
others = [cc for cc in [c1, c2, c3] if not np.allclose(cc, c)]
|
|
1291
|
+
push = c - np.mean(others, axis=0)
|
|
1292
|
+
pnorm = np.linalg.norm(push)
|
|
1293
|
+
if pnorm > 1e-4:
|
|
1294
|
+
centroid = c + push / pnorm * rad * 0.55
|
|
1295
|
+
else:
|
|
1296
|
+
centroid = c.copy()
|
|
1297
|
+
self._add_zone(name, full_arc, centroid,
|
|
1298
|
+
cfg.height_single, color, label_tex, prob,
|
|
1299
|
+
count=_cnt(prob))
|
|
1300
|
+
|
|
1301
|
+
# ---- Pairwise zones
|
|
1302
|
+
pair_specs = [
|
|
1303
|
+
("ab_only", c1, c2, r, r, geo12, ZONE_AB,
|
|
1304
|
+
rf"{la} \cap {lb} \cap {lc}^c", zp["ab_only"]),
|
|
1305
|
+
("ac_only", c1, c3, r, r, geo13, ZONE_AC,
|
|
1306
|
+
rf"{la} \cap {lb}^c \cap {lc}", zp["ac_only"]),
|
|
1307
|
+
("bc_only", c2, c3, r, r, geo23, ZONE_BC,
|
|
1308
|
+
rf"{la}^c \cap {lb} \cap {lc}", zp["bc_only"]),
|
|
1309
|
+
]
|
|
1310
|
+
for name, ca, cb, ra, rb, geo, color, label_tex, prob in pair_specs:
|
|
1311
|
+
if prob < 1e-5 or not geo.intersects:
|
|
1312
|
+
continue
|
|
1313
|
+
arcs_dict = _zone_arcs_2(ca, ra, cb, rb, geo)
|
|
1314
|
+
self._add_zone(name, *arcs_dict["ab"],
|
|
1315
|
+
cfg.height_double, color, label_tex, prob,
|
|
1316
|
+
count=_cnt(prob))
|
|
1317
|
+
|
|
1318
|
+
# ---- Triple intersection (centroid of all three)
|
|
1319
|
+
if zp["abc"] > 1e-5:
|
|
1320
|
+
triple_centroid = np.mean([c1, c2, c3], axis=0)
|
|
1321
|
+
# Use geo12 lens arc as approximation for innermost zone
|
|
1322
|
+
if geo12.intersects:
|
|
1323
|
+
arcs_dict12 = _zone_arcs_2(c1, r, c2, r, geo12)
|
|
1324
|
+
abc_arcs = arcs_dict12["ab"][0]
|
|
1325
|
+
else:
|
|
1326
|
+
abc_arcs = [{"cx": float(triple_centroid[0]),
|
|
1327
|
+
"cz": float(triple_centroid[1]),
|
|
1328
|
+
"r": r * 0.25,
|
|
1329
|
+
"t_start": 0.0, "t_end": TAU, "ccw": True}]
|
|
1330
|
+
self._add_zone(
|
|
1331
|
+
"abc", abc_arcs, triple_centroid,
|
|
1332
|
+
cfg.height_triple, ZONE_ABC,
|
|
1333
|
+
rf"{la} \cap {lb} \cap {lc}", zp["abc"],
|
|
1334
|
+
count=_cnt(zp["abc"]),
|
|
1335
|
+
)
|
|
1336
|
+
|
|
1337
|
+
# Circle outlines
|
|
1338
|
+
if cfg.show_outlines:
|
|
1339
|
+
y_out = cfg.height_double + cfg.outline_y_lift
|
|
1340
|
+
for c_arr, col in [(c1, SET_A_COLOR), (c2, SET_B_COLOR), (c3, SET_C_COLOR)]:
|
|
1341
|
+
out = _VennCircleOutline(
|
|
1342
|
+
cx=float(c_arr[0]), cz=float(c_arr[1]), r=r,
|
|
1343
|
+
y=y_out, color=col,
|
|
1344
|
+
stroke_width=cfg.outline_stroke_width,
|
|
1345
|
+
)
|
|
1346
|
+
self._outlines.append(out)
|
|
1347
|
+
self.add(out)
|
|
1348
|
+
|
|
1349
|
+
# Set labels
|
|
1350
|
+
if cfg.show_set_labels:
|
|
1351
|
+
for c_arr, col, label, others in [
|
|
1352
|
+
(c1, SET_A_COLOR, la, [c2, c3]),
|
|
1353
|
+
(c2, SET_B_COLOR, lb, [c1, c3]),
|
|
1354
|
+
(c3, SET_C_COLOR, lc, [c1, c2]),
|
|
1355
|
+
]:
|
|
1356
|
+
push = c_arr - np.mean(others, axis=0)
|
|
1357
|
+
pnorm = np.linalg.norm(push)
|
|
1358
|
+
if pnorm > 1e-4:
|
|
1359
|
+
push = push / pnorm
|
|
1360
|
+
else:
|
|
1361
|
+
push = np.array([0.0, -1.0])
|
|
1362
|
+
pos = np.array([
|
|
1363
|
+
c_arr[0] + push[0] * r * 0.88,
|
|
1364
|
+
cfg.height_double + 0.38,
|
|
1365
|
+
c_arr[1] + push[1] * r * 0.88,
|
|
1366
|
+
])
|
|
1367
|
+
slbl = MathTex(label, color=col,
|
|
1368
|
+
font_size=cfg.set_label_font_size)
|
|
1369
|
+
slbl.move_to(pos)
|
|
1370
|
+
self._set_labels.append(slbl)
|
|
1371
|
+
self.add(slbl)
|
|
1372
|
+
|
|
1373
|
+
# Omega box
|
|
1374
|
+
if cfg.show_omega_box:
|
|
1375
|
+
all_x = [c[0] - r for c in [c1,c2,c3]] + [c[0] + r for c in [c1,c2,c3]]
|
|
1376
|
+
all_z = [c[1] - r for c in [c1,c2,c3]] + [c[1] + r for c in [c1,c2,c3]]
|
|
1377
|
+
self._build_omega_box(
|
|
1378
|
+
min(all_x), max(all_x), min(all_z), max(all_z), y=0.0
|
|
1379
|
+
)
|
|
1380
|
+
|
|
1381
|
+
# ------------------------------------------------------------------
|
|
1382
|
+
# Animation API
|
|
1383
|
+
# ------------------------------------------------------------------
|
|
1384
|
+
|
|
1385
|
+
def animate_grow_circles(
|
|
1386
|
+
self,
|
|
1387
|
+
lag_ratio: float = 0.35,
|
|
1388
|
+
run_time: float = 2.5,
|
|
1389
|
+
) -> LaggedStart:
|
|
1390
|
+
"""Draw circle outlines one by one, each tracing its full ring.
|
|
1391
|
+
|
|
1392
|
+
The outlines are drawn in the order they were added (A, B, C)::
|
|
1393
|
+
|
|
1394
|
+
self.play(venn.animate_grow_circles())
|
|
1395
|
+
"""
|
|
1396
|
+
if not self._outlines:
|
|
1397
|
+
return LaggedStart(FadeIn(VGroup()), lag_ratio=0, run_time=0.1)
|
|
1398
|
+
return LaggedStart(
|
|
1399
|
+
*[Create(out.curve, run_time=run_time * 0.65)
|
|
1400
|
+
for out in self._outlines],
|
|
1401
|
+
lag_ratio=lag_ratio,
|
|
1402
|
+
run_time=run_time,
|
|
1403
|
+
)
|
|
1404
|
+
|
|
1405
|
+
def animate_fill_zones(
|
|
1406
|
+
self,
|
|
1407
|
+
lag_ratio: float = 0.12,
|
|
1408
|
+
run_time: float = 3.0,
|
|
1409
|
+
) -> Succession:
|
|
1410
|
+
"""Zones rise level by level: single → double → triple.
|
|
1411
|
+
|
|
1412
|
+
This ordering reinforces the inclusion-exclusion structure:
|
|
1413
|
+
individual sets first, then their interactions.
|
|
1414
|
+
"""
|
|
1415
|
+
single_names = {"a_only", "b_only", "c_only"}
|
|
1416
|
+
double_names = {"ab_only", "ac_only", "bc_only", "ab"}
|
|
1417
|
+
triple_names = {"abc"}
|
|
1418
|
+
|
|
1419
|
+
def _level_anim(names, rt):
|
|
1420
|
+
zones = [self._zones[n] for n in names if n in self._zones]
|
|
1421
|
+
if not zones:
|
|
1422
|
+
return FadeIn(VGroup(), run_time=0.01)
|
|
1423
|
+
return LaggedStart(
|
|
1424
|
+
*[GrowFromPoint(z, z.floor_center, run_time=rt * 0.65)
|
|
1425
|
+
for z in zones],
|
|
1426
|
+
lag_ratio=lag_ratio,
|
|
1427
|
+
run_time=rt,
|
|
1428
|
+
)
|
|
1429
|
+
|
|
1430
|
+
return Succession(
|
|
1431
|
+
_level_anim(single_names, run_time * 0.45),
|
|
1432
|
+
_level_anim(double_names, run_time * 0.35),
|
|
1433
|
+
_level_anim(triple_names, run_time * 0.20),
|
|
1434
|
+
)
|
|
1435
|
+
|
|
1436
|
+
def animate_highlight_zone(
|
|
1437
|
+
self,
|
|
1438
|
+
zone_name: str,
|
|
1439
|
+
highlight_color: ManimColor | None = None,
|
|
1440
|
+
scale_factor: float = 1.12,
|
|
1441
|
+
run_time: float = 0.60,
|
|
1442
|
+
) -> Succession:
|
|
1443
|
+
"""Flash-scale one zone and dim all others.
|
|
1444
|
+
|
|
1445
|
+
Parameters
|
|
1446
|
+
----------
|
|
1447
|
+
zone_name : str
|
|
1448
|
+
One of: ``"a_only"``, ``"b_only"``, ``"c_only"``,
|
|
1449
|
+
``"ab"``, ``"ab_only"``, ``"ac_only"``, ``"bc_only"``, ``"abc"``.
|
|
1450
|
+
"""
|
|
1451
|
+
if zone_name not in self._zones:
|
|
1452
|
+
return Succession(FadeIn(VGroup(), run_time=0.1))
|
|
1453
|
+
|
|
1454
|
+
target = self._zones[zone_name]
|
|
1455
|
+
others = [z for k, z in self._zones.items() if k != zone_name]
|
|
1456
|
+
h_color = highlight_color or self.cfg.highlight_color \
|
|
1457
|
+
if hasattr(self.cfg, "highlight_color") else YELLOW
|
|
1458
|
+
|
|
1459
|
+
dim = AnimationGroup(*[
|
|
1460
|
+
z.animate(run_time=run_time / 2).set_opacity(ZONE_DIM_OPACITY)
|
|
1461
|
+
for z in others
|
|
1462
|
+
])
|
|
1463
|
+
scale = target.animate(run_time=run_time / 2).scale(scale_factor)
|
|
1464
|
+
restore = AnimationGroup(
|
|
1465
|
+
*[z.animate(run_time=run_time / 2).set_opacity(self.cfg.zone_opacity)
|
|
1466
|
+
for z in others],
|
|
1467
|
+
target.animate(run_time=run_time / 2).scale(1 / scale_factor),
|
|
1468
|
+
)
|
|
1469
|
+
return Succession(AnimationGroup(dim, scale), restore)
|
|
1470
|
+
|
|
1471
|
+
def animate_inclusion_exclusion(
|
|
1472
|
+
self,
|
|
1473
|
+
run_time_each: float = 1.0,
|
|
1474
|
+
) -> Succession:
|
|
1475
|
+
"""Step through P(A∪B) = P(A) + P(B) − P(A∩B) visually.
|
|
1476
|
+
|
|
1477
|
+
Step 1: Highlight A (A_only + AB zones).
|
|
1478
|
+
Step 2: Highlight B (B_only + AB zones).
|
|
1479
|
+
Step 3: Dim the AB zone (show we counted it twice).
|
|
1480
|
+
Step 4: Re-brighten AB at normal opacity (correct once).
|
|
1481
|
+
Step 5: Reveal the inclusion-exclusion annotation.
|
|
1482
|
+
"""
|
|
1483
|
+
def _set_zone_opacity(names, opacity, rt):
|
|
1484
|
+
zones = [self._zones[n] for n in names if n in self._zones]
|
|
1485
|
+
if not zones:
|
|
1486
|
+
return FadeIn(VGroup(), run_time=0.01)
|
|
1487
|
+
return AnimationGroup(*[
|
|
1488
|
+
z.animate(run_time=rt).set_opacity(opacity)
|
|
1489
|
+
for z in zones
|
|
1490
|
+
])
|
|
1491
|
+
|
|
1492
|
+
full = self.cfg.zone_opacity
|
|
1493
|
+
dim = ZONE_DIM_OPACITY
|
|
1494
|
+
rt = run_time_each
|
|
1495
|
+
|
|
1496
|
+
# Step 1: show A
|
|
1497
|
+
s1 = _set_zone_opacity(
|
|
1498
|
+
["b_only","c_only","ab_only","ac_only","bc_only","abc"], dim, rt
|
|
1499
|
+
)
|
|
1500
|
+
# Step 2: show B (re-brighten b_only, keep ab bright)
|
|
1501
|
+
s2 = _set_zone_opacity(["b_only"], full, rt * 0.6)
|
|
1502
|
+
# Step 3: double-count AB — flash AB to bright red
|
|
1503
|
+
s3 = AnimationGroup(
|
|
1504
|
+
*[self._zones[n].animate(run_time=rt * 0.4)
|
|
1505
|
+
.set_color(ManimColor("#FF5252"))
|
|
1506
|
+
for n in ["ab", "ab_only"] if n in self._zones]
|
|
1507
|
+
) if any(n in self._zones for n in ["ab","ab_only"]) else FadeIn(VGroup())
|
|
1508
|
+
# Step 4: restore AB
|
|
1509
|
+
s4 = _set_zone_opacity(["ab","ab_only"], full, rt * 0.5)
|
|
1510
|
+
# Step 5: restore all + show annotation
|
|
1511
|
+
s5 = _set_zone_opacity(
|
|
1512
|
+
list(self._zones.keys()), full, rt * 0.6
|
|
1513
|
+
)
|
|
1514
|
+
s6 = FadeIn(self._annots, run_time=rt) \
|
|
1515
|
+
if len(self._annots) > 0 else FadeIn(VGroup(), run_time=0.1)
|
|
1516
|
+
|
|
1517
|
+
return Succession(s1, s2, s3, s4, s5, s6)
|
|
1518
|
+
|
|
1519
|
+
def animate_condition_on(
|
|
1520
|
+
self,
|
|
1521
|
+
set_name: str,
|
|
1522
|
+
run_time: float = 1.5,
|
|
1523
|
+
) -> Succession:
|
|
1524
|
+
"""Dim all zones outside set_name; show the P(B|A) annotation.
|
|
1525
|
+
|
|
1526
|
+
For a 2-set diagram, ``set_name = "a"`` dims "b_only" and
|
|
1527
|
+
"neither", leaving "a_only" and "ab" fully lit. A MathTex
|
|
1528
|
+
annotation P(B|A) = P(A∩B)/P(A) is revealed above the AB zone.
|
|
1529
|
+
|
|
1530
|
+
Parameters
|
|
1531
|
+
----------
|
|
1532
|
+
set_name : str
|
|
1533
|
+
``"a"`` or ``"b"`` (or ``"c"`` for 3-set).
|
|
1534
|
+
"""
|
|
1535
|
+
set_name = set_name.lower()
|
|
1536
|
+
|
|
1537
|
+
# Zones that belong to the conditioned set
|
|
1538
|
+
in_set: dict[str, set[str]] = {
|
|
1539
|
+
"a": {"a_only", "ab", "ab_only", "ac_only", "abc"},
|
|
1540
|
+
"b": {"b_only", "ab", "ab_only", "bc_only", "abc"},
|
|
1541
|
+
"c": {"c_only", "ac_only", "bc_only", "abc"},
|
|
1542
|
+
}
|
|
1543
|
+
inside = in_set.get(set_name, set())
|
|
1544
|
+
outside = set(self._zones.keys()) - inside
|
|
1545
|
+
|
|
1546
|
+
dim_out = AnimationGroup(*[
|
|
1547
|
+
self._zones[n].animate(run_time=run_time * 0.55)
|
|
1548
|
+
.set_opacity(ZONE_DIM_OPACITY)
|
|
1549
|
+
for n in outside if n in self._zones
|
|
1550
|
+
])
|
|
1551
|
+
|
|
1552
|
+
# Conditional probability annotation
|
|
1553
|
+
ann_zone = None
|
|
1554
|
+
ann_tex = ""
|
|
1555
|
+
if self._data2 is not None:
|
|
1556
|
+
d = self._data2
|
|
1557
|
+
if set_name == "a":
|
|
1558
|
+
val = d.p_b_given_a()
|
|
1559
|
+
ann_tex = (rf"P({d.label_b}|{d.label_a}) = "
|
|
1560
|
+
rf"\frac{{{d.p_ab:.3f}}}{{{d.p_a:.3f}}} = {val:.3f}")
|
|
1561
|
+
ann_zone = "ab" if "ab" in self._zones else None
|
|
1562
|
+
elif set_name == "b":
|
|
1563
|
+
val = d.p_a_given_b()
|
|
1564
|
+
ann_tex = (rf"P({d.label_a}|{d.label_b}) = "
|
|
1565
|
+
rf"\frac{{{d.p_ab:.3f}}}{{{d.p_b:.3f}}} = {val:.3f}")
|
|
1566
|
+
ann_zone = "ab" if "ab" in self._zones else None
|
|
1567
|
+
|
|
1568
|
+
cond_lbl = None
|
|
1569
|
+
if ann_tex and ann_zone and ann_zone in self._zones:
|
|
1570
|
+
z = self._zones[ann_zone]
|
|
1571
|
+
lbl = MathTex(ann_tex, color=YELLOW,
|
|
1572
|
+
font_size=self.cfg.annotation_font_size)
|
|
1573
|
+
tc = z.floor_center
|
|
1574
|
+
lbl.move_to(np.array([tc[0], self.cfg.height_double + 0.70, tc[2]]))
|
|
1575
|
+
self.add(lbl)
|
|
1576
|
+
cond_lbl = FadeIn(lbl, run_time=run_time * 0.45)
|
|
1577
|
+
|
|
1578
|
+
return Succession(
|
|
1579
|
+
dim_out,
|
|
1580
|
+
cond_lbl if cond_lbl else FadeIn(VGroup(), run_time=0.1),
|
|
1581
|
+
)
|
|
1582
|
+
|
|
1583
|
+
def animate_restore(
|
|
1584
|
+
self,
|
|
1585
|
+
run_time: float = 0.8,
|
|
1586
|
+
) -> AnimationGroup:
|
|
1587
|
+
"""Restore all zones to full opacity and original color."""
|
|
1588
|
+
return AnimationGroup(*[
|
|
1589
|
+
z.animate(run_time=run_time).set_opacity(self.cfg.zone_opacity)
|
|
1590
|
+
for z in self._zones.values()
|
|
1591
|
+
])
|
|
1592
|
+
|
|
1593
|
+
def animate_independence_test(
|
|
1594
|
+
self,
|
|
1595
|
+
run_time: float = 1.5,
|
|
1596
|
+
) -> Succession:
|
|
1597
|
+
"""Show P(A∩B) vs P(A)·P(B) with a verdict badge.
|
|
1598
|
+
|
|
1599
|
+
Highlights the AB zone, then reveals the independence annotation.
|
|
1600
|
+
"""
|
|
1601
|
+
if self._data2 is None:
|
|
1602
|
+
return Succession(FadeIn(VGroup(), run_time=0.1))
|
|
1603
|
+
|
|
1604
|
+
highlight = self.animate_highlight_zone("ab", run_time=run_time * 0.55)
|
|
1605
|
+
if hasattr(self, "independence_banner"):
|
|
1606
|
+
show_ann = FadeIn(self.independence_banner, run_time=run_time * 0.45)
|
|
1607
|
+
else:
|
|
1608
|
+
d = self._data2
|
|
1609
|
+
ind = _IndependenceAnnotation(
|
|
1610
|
+
data=d,
|
|
1611
|
+
pos=np.array([0.0, self.cfg.annotation_y_offset, 0.0]),
|
|
1612
|
+
font_size=self.cfg.annotation_font_size,
|
|
1613
|
+
)
|
|
1614
|
+
self.add(ind)
|
|
1615
|
+
show_ann = FadeIn(ind, run_time=run_time * 0.45)
|
|
1616
|
+
|
|
1617
|
+
return Succession(highlight, show_ann)
|
|
1618
|
+
|
|
1619
|
+
def animate_morph_to(
|
|
1620
|
+
self,
|
|
1621
|
+
new_data: VennData2,
|
|
1622
|
+
run_time: float = 2.0,
|
|
1623
|
+
) -> AnimationGroup:
|
|
1624
|
+
"""Morph all zone surfaces to reflect new probability values.
|
|
1625
|
+
|
|
1626
|
+
A new ``VennDiagram3D`` is built internally and each zone
|
|
1627
|
+
transforms into its counterpart. The circle outlines also
|
|
1628
|
+
rescale if radii change.
|
|
1629
|
+
|
|
1630
|
+
Parameters
|
|
1631
|
+
----------
|
|
1632
|
+
new_data : VennData2
|
|
1633
|
+
Updated probabilities. Only 2-set supported currently.
|
|
1634
|
+
"""
|
|
1635
|
+
new_venn = VennDiagram3D.two_set(new_data, config=self.cfg)
|
|
1636
|
+
anims = []
|
|
1637
|
+
for name, zone in self._zones.items():
|
|
1638
|
+
if name in new_venn._zones:
|
|
1639
|
+
anims.append(Transform(zone, new_venn._zones[name],
|
|
1640
|
+
run_time=run_time))
|
|
1641
|
+
return AnimationGroup(*anims)
|
|
1642
|
+
|
|
1643
|
+
def animate_add_set_c(
|
|
1644
|
+
self,
|
|
1645
|
+
data3: VennData3,
|
|
1646
|
+
run_time: float = 2.5,
|
|
1647
|
+
) -> Succession:
|
|
1648
|
+
"""Grow the C circle into an existing 2-set diagram.
|
|
1649
|
+
|
|
1650
|
+
The new circle outline traces in, then the C-containing zones
|
|
1651
|
+
rise: c_only, ac_only, bc_only, abc — in that order.
|
|
1652
|
+
"""
|
|
1653
|
+
cfg = self.cfg
|
|
1654
|
+
circles = _circle_centres_3(cfg)
|
|
1655
|
+
_, _, c3 = circles
|
|
1656
|
+
r = cfg.circle_radius
|
|
1657
|
+
|
|
1658
|
+
c3_out = _VennCircleOutline(
|
|
1659
|
+
cx=float(c3[0]), cz=float(c3[1]), r=r,
|
|
1660
|
+
y=cfg.height_double + cfg.outline_y_lift,
|
|
1661
|
+
color=SET_C_COLOR,
|
|
1662
|
+
stroke_width=cfg.outline_stroke_width,
|
|
1663
|
+
)
|
|
1664
|
+
self.add(c3_out)
|
|
1665
|
+
|
|
1666
|
+
new_zone_names = ["c_only", "ac_only", "bc_only", "abc"]
|
|
1667
|
+
# Build a full 3-set venn internally, extract the new zones
|
|
1668
|
+
full3 = VennDiagram3D.three_set(data3, config=cfg)
|
|
1669
|
+
new_zones = {n: full3._zones[n] for n in new_zone_names
|
|
1670
|
+
if n in full3._zones}
|
|
1671
|
+
for zone in new_zones.values():
|
|
1672
|
+
self.add(zone)
|
|
1673
|
+
self._zones[list(new_zones.keys())[
|
|
1674
|
+
list(new_zones.values()).index(zone)
|
|
1675
|
+
]] = zone
|
|
1676
|
+
|
|
1677
|
+
draw_c = Create(c3_out.curve, run_time=run_time * 0.35)
|
|
1678
|
+
grow = LaggedStart(
|
|
1679
|
+
*[GrowFromPoint(z, z.floor_center, run_time=run_time * 0.45)
|
|
1680
|
+
for z in new_zones.values()],
|
|
1681
|
+
lag_ratio=0.15,
|
|
1682
|
+
run_time=run_time * 0.65,
|
|
1683
|
+
)
|
|
1684
|
+
return Succession(draw_c, grow)
|
|
1685
|
+
|
|
1686
|
+
# ------------------------------------------------------------------
|
|
1687
|
+
# Factory classmethods
|
|
1688
|
+
# ------------------------------------------------------------------
|
|
1689
|
+
|
|
1690
|
+
@classmethod
|
|
1691
|
+
def two_set(
|
|
1692
|
+
cls,
|
|
1693
|
+
data: VennData2,
|
|
1694
|
+
config: VennConfig | None = None,
|
|
1695
|
+
total_n: int | None = None,
|
|
1696
|
+
) -> "VennDiagram3D":
|
|
1697
|
+
"""Build a 2-set Venn diagram.
|
|
1698
|
+
|
|
1699
|
+
Parameters
|
|
1700
|
+
----------
|
|
1701
|
+
data : VennData2
|
|
1702
|
+
config : VennConfig, optional
|
|
1703
|
+
total_n : int, optional
|
|
1704
|
+
If set, natural frequency counts are shown inside zones.
|
|
1705
|
+
|
|
1706
|
+
Example
|
|
1707
|
+
-------
|
|
1708
|
+
>>> data = VennData2(p_a=0.40, p_b=0.35, p_ab=0.15)
|
|
1709
|
+
>>> venn = VennDiagram3D.two_set(data)
|
|
1710
|
+
"""
|
|
1711
|
+
cfg = config or VennConfig()
|
|
1712
|
+
venn = cls(config=cfg)
|
|
1713
|
+
venn._data2 = data
|
|
1714
|
+
circles = _circle_centres_2(cfg)
|
|
1715
|
+
venn._build_2set(data, circles, total_n=total_n)
|
|
1716
|
+
return venn
|
|
1717
|
+
|
|
1718
|
+
@classmethod
|
|
1719
|
+
def three_set(
|
|
1720
|
+
cls,
|
|
1721
|
+
data: VennData3,
|
|
1722
|
+
config: VennConfig | None = None,
|
|
1723
|
+
total_n: int | None = None,
|
|
1724
|
+
) -> "VennDiagram3D":
|
|
1725
|
+
"""Build a 3-set Venn diagram.
|
|
1726
|
+
|
|
1727
|
+
Parameters
|
|
1728
|
+
----------
|
|
1729
|
+
data : VennData3
|
|
1730
|
+
config : VennConfig, optional
|
|
1731
|
+
total_n : int, optional
|
|
1732
|
+
|
|
1733
|
+
Example
|
|
1734
|
+
-------
|
|
1735
|
+
>>> data = VennData3(
|
|
1736
|
+
... p_a=0.50, p_b=0.40, p_c=0.35,
|
|
1737
|
+
... p_ab=0.20, p_ac=0.15, p_bc=0.12,
|
|
1738
|
+
... p_abc=0.06,
|
|
1739
|
+
... )
|
|
1740
|
+
>>> venn = VennDiagram3D.three_set(data)
|
|
1741
|
+
"""
|
|
1742
|
+
cfg = config or VennConfig()
|
|
1743
|
+
venn = cls(config=cfg)
|
|
1744
|
+
venn._data3 = data
|
|
1745
|
+
circles = _circle_centres_3(cfg)
|
|
1746
|
+
venn._build_3set(data, circles, total_n=total_n)
|
|
1747
|
+
return venn
|
|
1748
|
+
|
|
1749
|
+
@classmethod
|
|
1750
|
+
def from_counts(
|
|
1751
|
+
cls,
|
|
1752
|
+
n_a: int,
|
|
1753
|
+
n_b: int,
|
|
1754
|
+
n_ab: int,
|
|
1755
|
+
n_total: int,
|
|
1756
|
+
config: VennConfig | None = None,
|
|
1757
|
+
label_a: str = "A",
|
|
1758
|
+
label_b: str = "B",
|
|
1759
|
+
) -> "VennDiagram3D":
|
|
1760
|
+
"""Build a 2-set Venn from natural frequency counts.
|
|
1761
|
+
|
|
1762
|
+
Parameters
|
|
1763
|
+
----------
|
|
1764
|
+
n_a, n_b, n_ab : int
|
|
1765
|
+
Counts of outcomes in A, B, and A∩B.
|
|
1766
|
+
n_total : int
|
|
1767
|
+
Total sample size (denominator for all probabilities).
|
|
1768
|
+
|
|
1769
|
+
Example
|
|
1770
|
+
-------
|
|
1771
|
+
>>> # 200 people: 80 own a cat, 70 own a dog, 30 own both
|
|
1772
|
+
>>> venn = VennDiagram3D.from_counts(80, 70, 30, 200)
|
|
1773
|
+
"""
|
|
1774
|
+
data = VennData2(
|
|
1775
|
+
p_a = n_a / n_total,
|
|
1776
|
+
p_b = n_b / n_total,
|
|
1777
|
+
p_ab = n_ab / n_total,
|
|
1778
|
+
label_a=label_a,
|
|
1779
|
+
label_b=label_b,
|
|
1780
|
+
)
|
|
1781
|
+
cfg = config or VennConfig()
|
|
1782
|
+
cfg.show_count_labels = True
|
|
1783
|
+
return cls.two_set(data, config=cfg, total_n=n_total)
|
|
1784
|
+
|
|
1785
|
+
@classmethod
|
|
1786
|
+
def disjoint(
|
|
1787
|
+
cls,
|
|
1788
|
+
p_a: float,
|
|
1789
|
+
p_b: float,
|
|
1790
|
+
config: VennConfig | None = None,
|
|
1791
|
+
label_a: str = "A",
|
|
1792
|
+
label_b: str = "B",
|
|
1793
|
+
) -> "VennDiagram3D":
|
|
1794
|
+
"""Euler diagram for two disjoint events (P(A∩B) = 0).
|
|
1795
|
+
|
|
1796
|
+
The circles are placed far enough apart that they don't overlap,
|
|
1797
|
+
making the mutual exclusivity visually obvious.
|
|
1798
|
+
"""
|
|
1799
|
+
cfg = config or VennConfig()
|
|
1800
|
+
cfg.layout = "euler"
|
|
1801
|
+
data = VennData2(p_a=p_a, p_b=p_b, p_ab=0.0,
|
|
1802
|
+
label_a=label_a, label_b=label_b)
|
|
1803
|
+
return cls.two_set(data, config=cfg)
|
|
1804
|
+
|
|
1805
|
+
@classmethod
|
|
1806
|
+
def subset(
|
|
1807
|
+
cls,
|
|
1808
|
+
p_a: float,
|
|
1809
|
+
p_b: float,
|
|
1810
|
+
config: VennConfig | None = None,
|
|
1811
|
+
label_a: str = "A",
|
|
1812
|
+
label_b: str = "B",
|
|
1813
|
+
) -> "VennDiagram3D":
|
|
1814
|
+
"""Nested diagram for A ⊆ B (every outcome in A is also in B).
|
|
1815
|
+
|
|
1816
|
+
The A circle sits entirely inside the B circle.
|
|
1817
|
+
P(A∩B) = P(A) since A ⊆ B.
|
|
1818
|
+
"""
|
|
1819
|
+
cfg = config or VennConfig()
|
|
1820
|
+
cfg.layout = "nested"
|
|
1821
|
+
data = VennData2(p_a=p_a, p_b=p_b, p_ab=p_a,
|
|
1822
|
+
label_a=label_a, label_b=label_b)
|
|
1823
|
+
r_a = cfg.circle_radius * np.sqrt(p_a / max(p_b, 1e-9))
|
|
1824
|
+
r_b = cfg.circle_radius
|
|
1825
|
+
venn = cls(config=cfg)
|
|
1826
|
+
venn._data2 = data
|
|
1827
|
+
c_b = np.array([0.0, 0.0])
|
|
1828
|
+
offset = r_b * 0.30
|
|
1829
|
+
c_a = np.array([-offset, 0.0])
|
|
1830
|
+
venn._build_2set(data, (c_a, c_b),
|
|
1831
|
+
radii=(r_a, r_b))
|
|
1832
|
+
return venn
|
|
1833
|
+
|
|
1834
|
+
@classmethod
|
|
1835
|
+
def independent(
|
|
1836
|
+
cls,
|
|
1837
|
+
p_a: float,
|
|
1838
|
+
p_b: float,
|
|
1839
|
+
config: VennConfig | None = None,
|
|
1840
|
+
label_a: str = "A",
|
|
1841
|
+
label_b: str = "B",
|
|
1842
|
+
) -> "VennDiagram3D":
|
|
1843
|
+
"""2-set diagram where A and B are independent: P(A∩B) = P(A)·P(B).
|
|
1844
|
+
|
|
1845
|
+
The independence annotation is automatically shown.
|
|
1846
|
+
"""
|
|
1847
|
+
cfg = config or VennConfig()
|
|
1848
|
+
cfg.show_independence_test = True
|
|
1849
|
+
cfg.show_inclusion_exclusion = False
|
|
1850
|
+
data = VennData2(
|
|
1851
|
+
p_a = p_a,
|
|
1852
|
+
p_b = p_b,
|
|
1853
|
+
p_ab = p_a * p_b,
|
|
1854
|
+
label_a=label_a,
|
|
1855
|
+
label_b=label_b,
|
|
1856
|
+
)
|
|
1857
|
+
return cls.two_set(data, config=cfg)
|