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,1825 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/inference/error_types.py
|
|
3
|
+
=====================================
|
|
4
|
+
TypeITypeII — Highly detailed, statistically rigorous visualisation of
|
|
5
|
+
Type I error (α), Type II error (β), and Power (1−β) for Manim
|
|
6
|
+
statistics animations.
|
|
7
|
+
|
|
8
|
+
Primary use cases
|
|
9
|
+
-----------------
|
|
10
|
+
Hypothesis testing foundations — visual definition of α and β
|
|
11
|
+
Power analysis — how n, δ, σ, α trade off
|
|
12
|
+
Effect size demonstrations — shifting H₁ changes β
|
|
13
|
+
Two-tailed tests — symmetric critical regions
|
|
14
|
+
Neyman–Pearson framework — decision rules and error types
|
|
15
|
+
|
|
16
|
+
Design goals
|
|
17
|
+
------------
|
|
18
|
+
Distribution curves
|
|
19
|
+
* Two filled normal curves: H₀ (null, blue family) and H₁ (alternative,
|
|
20
|
+
red/orange family), each rendered with three layers:
|
|
21
|
+
– base fill polygon — the full curve area
|
|
22
|
+
– bright ridge spine — thin bright line along the curve peak
|
|
23
|
+
– tail AO darkening — darker gradient strips at far tails
|
|
24
|
+
* Both curves share the same x-axis and are drawn at the same scale.
|
|
25
|
+
* Curve width (σ_eff = σ/√n) is controlled by a ValueTracker for n,
|
|
26
|
+
enabling live NarrowCurves animation.
|
|
27
|
+
|
|
28
|
+
Critical region
|
|
29
|
+
* Vertical dashed line at the critical value xₒ.
|
|
30
|
+
* Hatched rejection region: parallel diagonal lines clipped to the
|
|
31
|
+
right tail of H₀ (or both tails for two-tailed), giving a "forbidden
|
|
32
|
+
zone" feel distinct from the error shading.
|
|
33
|
+
* Critical value badge: rounded-rect label at the base of the line.
|
|
34
|
+
|
|
35
|
+
Error / power regions (all with distinct hatch + fill)
|
|
36
|
+
* α region — area under H₀ in the rejection zone.
|
|
37
|
+
Bright red fill + dark red diagonal hatch (↗).
|
|
38
|
+
* β region — area under H₁ in the acceptance zone.
|
|
39
|
+
Gold/orange fill + orange hatch (↘).
|
|
40
|
+
* 1−β (Power) region — area under H₁ in the rejection zone.
|
|
41
|
+
Green fill + green hatch (↗), same direction as α.
|
|
42
|
+
* 1−α region — area under H₀ in the acceptance zone.
|
|
43
|
+
Blue fill + blue hatch (↘).
|
|
44
|
+
|
|
45
|
+
Annotation system
|
|
46
|
+
* Each region has:
|
|
47
|
+
– region_label (e.g. "α = 0.050") floating above the region
|
|
48
|
+
– bracket line with a fine leader arrow pointing into the region
|
|
49
|
+
– formula badge (e.g. "P(reject H₀ | H₀ true)")
|
|
50
|
+
|
|
51
|
+
Effect size arrow
|
|
52
|
+
* DoubleArrow between the two distribution means (μ₀ → μ₁).
|
|
53
|
+
* Label "δ" above the arrow, and computed value below.
|
|
54
|
+
|
|
55
|
+
Decision table panel
|
|
56
|
+
* 2×2 grid floating to the right:
|
|
57
|
+
Rows = Reality (H₀ true / H₁ true)
|
|
58
|
+
Cols = Decision (Fail to Reject / Reject H₀)
|
|
59
|
+
Cells = 1−α, α, β, 1−β with live numeric values.
|
|
60
|
+
|
|
61
|
+
Two-tailed support
|
|
62
|
+
* Symmetric critical regions, two α/2 annotations, correct β.
|
|
63
|
+
|
|
64
|
+
Animations
|
|
65
|
+
----------
|
|
66
|
+
BuildDistributions — curves grow from flat line upward (both together)
|
|
67
|
+
RevealAlpha — α region fills and label appears
|
|
68
|
+
RevealBeta — β region fills and label appears
|
|
69
|
+
RevealPower — 1−β region fills and label appears
|
|
70
|
+
RevealAll — orchestrated sequence of all four reveals
|
|
71
|
+
ShiftH1 — moves the H₁ distribution (changes δ), β shrinks/grows
|
|
72
|
+
NarrowCurves — increases n, both curves narrow, β shrinks
|
|
73
|
+
SweepAlpha — moves the critical value, α grows/shrinks, β inversely
|
|
74
|
+
FlashDecision — highlights one cell of the decision table
|
|
75
|
+
BuildDecisionTable — animates the 2×2 table appearing
|
|
76
|
+
|
|
77
|
+
Dependencies
|
|
78
|
+
------------
|
|
79
|
+
manim (CE or GL), numpy, scipy
|
|
80
|
+
|
|
81
|
+
Usage
|
|
82
|
+
-----
|
|
83
|
+
from statanim.inference.error_types import (
|
|
84
|
+
TypeITypeII, BuildDistributions, RevealAll, NarrowCurves
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
class PowerScene(Scene):
|
|
88
|
+
def construct(self):
|
|
89
|
+
viz = TypeITypeII(
|
|
90
|
+
mu0=0.0, mu1=2.0, sigma=1.0, n=1,
|
|
91
|
+
alpha=0.05, two_tailed=False,
|
|
92
|
+
)
|
|
93
|
+
self.play(BuildDistributions(viz))
|
|
94
|
+
self.play(RevealAll(viz))
|
|
95
|
+
self.play(NarrowCurves(viz, new_n=16, run_time=3.0))
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
from __future__ import annotations
|
|
99
|
+
|
|
100
|
+
import numpy as np
|
|
101
|
+
from typing import Optional, Literal, List, Tuple
|
|
102
|
+
|
|
103
|
+
from manim import (
|
|
104
|
+
VGroup,
|
|
105
|
+
Rectangle, RoundedRectangle, Square,
|
|
106
|
+
Circle, Annulus, Polygon, Line, DashedLine, Arrow, DoubleArrow,
|
|
107
|
+
Text, MathTex, Tex,
|
|
108
|
+
Animation, Succession, AnimationGroup,
|
|
109
|
+
ApplyMethod, FadeIn, FadeOut, GrowFromCenter,
|
|
110
|
+
Create, Write, Uncreate,
|
|
111
|
+
Indicate, Flash,
|
|
112
|
+
ValueTracker,
|
|
113
|
+
interpolate_color, color_to_rgb,
|
|
114
|
+
always_redraw,
|
|
115
|
+
WHITE, BLACK,
|
|
116
|
+
GREY, GREY_A, GREY_B, GREY_C, GREY_D,
|
|
117
|
+
RED, RED_A, RED_B, RED_C, RED_D, RED_E,
|
|
118
|
+
GREEN, GREEN_A, GREEN_B, GREEN_C, GREEN_D, GREEN_E,
|
|
119
|
+
BLUE, BLUE_A, BLUE_B, BLUE_C, BLUE_D, BLUE_E,
|
|
120
|
+
YELLOW, YELLOW_A, YELLOW_B, YELLOW_E,
|
|
121
|
+
ORANGE, TEAL, TEAL_A, TEAL_B,
|
|
122
|
+
GOLD, GOLD_A, GOLD_B, GOLD_C, GOLD_D,
|
|
123
|
+
MAROON, PURPLE_A, PURPLE_B, PINK,
|
|
124
|
+
UP, DOWN, LEFT, RIGHT, OUT, IN, ORIGIN,
|
|
125
|
+
PI, TAU,
|
|
126
|
+
rate_functions,
|
|
127
|
+
ManimColor,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
131
|
+
# scipy — graceful fallback
|
|
132
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
133
|
+
try:
|
|
134
|
+
from scipy.stats import norm as _norm
|
|
135
|
+
def _norm_pdf(x: np.ndarray, mu: float, sigma: float) -> np.ndarray:
|
|
136
|
+
return _norm.pdf(x, loc=mu, scale=sigma)
|
|
137
|
+
def _norm_cdf(x: float, mu: float, sigma: float) -> float:
|
|
138
|
+
return float(_norm.cdf(x, loc=mu, scale=sigma))
|
|
139
|
+
def _norm_ppf(p: float, mu: float, sigma: float) -> float:
|
|
140
|
+
return float(_norm.ppf(p, loc=mu, scale=sigma))
|
|
141
|
+
except ImportError:
|
|
142
|
+
def _norm_pdf(x, mu, sigma):
|
|
143
|
+
return (np.exp(-0.5 * ((x - mu) / sigma) ** 2)
|
|
144
|
+
/ (sigma * np.sqrt(2 * PI)))
|
|
145
|
+
def _norm_cdf(x, mu, sigma):
|
|
146
|
+
return float(0.5 * (1 + np.vectorize(
|
|
147
|
+
lambda t: 2 / np.sqrt(PI) * sum(
|
|
148
|
+
(-1)**k * t**(2*k+1) / (np.math.factorial(k) * (2*k+1))
|
|
149
|
+
for k in range(50)
|
|
150
|
+
)
|
|
151
|
+
)((x - mu) / (sigma * np.sqrt(2)))))
|
|
152
|
+
def _norm_ppf(p, mu, sigma):
|
|
153
|
+
# rough inverse via Newton–Raphson
|
|
154
|
+
x = mu
|
|
155
|
+
for _ in range(50):
|
|
156
|
+
x -= (_norm_cdf(x, mu, sigma) - p) / (_norm_pdf(np.array([x]), mu, sigma)[0] + 1e-12)
|
|
157
|
+
return x
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
161
|
+
# Colour palette
|
|
162
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
163
|
+
|
|
164
|
+
PALETTE = {
|
|
165
|
+
# H₀ distribution
|
|
166
|
+
"h0_fill": "#1B4F8A",
|
|
167
|
+
"h0_fill_lite": "#4A90D9",
|
|
168
|
+
"h0_ridge": "#90C8F8",
|
|
169
|
+
"h0_tail_ao": "#0D2040",
|
|
170
|
+
|
|
171
|
+
# H₁ distribution
|
|
172
|
+
"h1_fill": "#8A2B1B",
|
|
173
|
+
"h1_fill_lite": "#D9604A",
|
|
174
|
+
"h1_ridge": "#F8B090",
|
|
175
|
+
"h1_tail_ao": "#401008",
|
|
176
|
+
|
|
177
|
+
# Region fills
|
|
178
|
+
"alpha_fill": "#CC2222", # α: Type I — vivid red
|
|
179
|
+
"alpha_hatch": "#8A0808",
|
|
180
|
+
"beta_fill": "#C87820", # β: Type II — gold/amber
|
|
181
|
+
"beta_hatch": "#7A4A08",
|
|
182
|
+
"power_fill": "#1A9A50", # 1−β: Power — green
|
|
183
|
+
"power_hatch": "#0A5828",
|
|
184
|
+
"correct_fill": "#1B4F8A", # 1−α: correct rejection — blue
|
|
185
|
+
"correct_hatch":"#0D2040",
|
|
186
|
+
|
|
187
|
+
# Critical line
|
|
188
|
+
"crit_line": "#F0E8C0",
|
|
189
|
+
"crit_badge_bg":"#2A2010",
|
|
190
|
+
"crit_badge_fg":"#F0E8C0",
|
|
191
|
+
|
|
192
|
+
# Effect arrow
|
|
193
|
+
"delta_arrow": "#D4AF37",
|
|
194
|
+
"delta_label": "#F0E8C0",
|
|
195
|
+
|
|
196
|
+
# Annotations
|
|
197
|
+
"label_alpha": "#FF6060",
|
|
198
|
+
"label_beta": "#F0A030",
|
|
199
|
+
"label_power": "#40CC80",
|
|
200
|
+
"label_correct":"#70B0F0",
|
|
201
|
+
|
|
202
|
+
# Axis / general
|
|
203
|
+
"axis": "#A0A8B0",
|
|
204
|
+
"axis_label": "#C8D0D8",
|
|
205
|
+
"bg_panel": "#0E1420",
|
|
206
|
+
"table_border": "#3A4050",
|
|
207
|
+
"table_header": "#1E2840",
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
212
|
+
# Geometry helpers
|
|
213
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
214
|
+
|
|
215
|
+
def _curve_polygon_verts(
|
|
216
|
+
x_vals: np.ndarray,
|
|
217
|
+
y_vals: np.ndarray,
|
|
218
|
+
baseline_y: float = 0.0,
|
|
219
|
+
) -> list[list[float]]:
|
|
220
|
+
"""
|
|
221
|
+
Vertices for a filled curve polygon:
|
|
222
|
+
left baseline → curve top → right baseline → close.
|
|
223
|
+
"""
|
|
224
|
+
top = [[float(x), float(y), 0] for x, y in zip(x_vals, y_vals)]
|
|
225
|
+
left = [[float(x_vals[0]), baseline_y, 0]]
|
|
226
|
+
right = [[float(x_vals[-1]), baseline_y, 0]]
|
|
227
|
+
return left + top + right
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _clipped_area_verts(
|
|
231
|
+
x_vals: np.ndarray,
|
|
232
|
+
y_vals: np.ndarray,
|
|
233
|
+
x_lo: float,
|
|
234
|
+
x_hi: float,
|
|
235
|
+
baseline_y: float = 0.0,
|
|
236
|
+
) -> list[list[float]]:
|
|
237
|
+
"""
|
|
238
|
+
Vertices for the area under a curve between x_lo and x_hi.
|
|
239
|
+
Returns empty list if region is negligibly small.
|
|
240
|
+
"""
|
|
241
|
+
mask = (x_vals >= x_lo) & (x_vals <= x_hi)
|
|
242
|
+
xs = x_vals[mask]
|
|
243
|
+
ys = y_vals[mask]
|
|
244
|
+
if len(xs) < 2:
|
|
245
|
+
return []
|
|
246
|
+
|
|
247
|
+
# Interpolate boundary points precisely
|
|
248
|
+
def _interp_y(x_target: float) -> float:
|
|
249
|
+
idx = np.searchsorted(x_vals, x_target)
|
|
250
|
+
idx = np.clip(idx, 1, len(x_vals) - 1)
|
|
251
|
+
x0, x1 = x_vals[idx-1], x_vals[idx]
|
|
252
|
+
y0, y1 = y_vals[idx-1], y_vals[idx]
|
|
253
|
+
t = (x_target - x0) / (x1 - x0 + 1e-12)
|
|
254
|
+
return float(y0 + t * (y1 - y0))
|
|
255
|
+
|
|
256
|
+
xs = np.concatenate([[x_lo], xs, [x_hi]])
|
|
257
|
+
ys = np.concatenate(
|
|
258
|
+
[[_interp_y(x_lo)], ys, [_interp_y(x_hi)]]
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
top = [[float(x), float(y), 0] for x, y in zip(xs, ys)]
|
|
262
|
+
left = [[float(x_lo), baseline_y, 0]]
|
|
263
|
+
right = [[float(x_hi), baseline_y, 0]]
|
|
264
|
+
return left + top + right
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _hatch_lines(
|
|
268
|
+
x_lo: float, x_hi: float,
|
|
269
|
+
y_lo: float, y_hi: float,
|
|
270
|
+
angle: float = PI / 4,
|
|
271
|
+
spacing: float = 0.12,
|
|
272
|
+
stroke_color: str = WHITE,
|
|
273
|
+
stroke_width: float = 0.8,
|
|
274
|
+
stroke_opacity: float = 0.55,
|
|
275
|
+
z: float = 0.004,
|
|
276
|
+
) -> VGroup:
|
|
277
|
+
"""
|
|
278
|
+
Diagonal hatch lines inside an axis-aligned bounding box,
|
|
279
|
+
clipped to [x_lo, x_hi] × [y_lo, y_hi].
|
|
280
|
+
|
|
281
|
+
Each line is drawn at `angle` to horizontal, spaced `spacing` apart
|
|
282
|
+
(measured perpendicular to the lines).
|
|
283
|
+
"""
|
|
284
|
+
grp = VGroup()
|
|
285
|
+
cos_a = np.cos(angle)
|
|
286
|
+
sin_a = np.sin(angle)
|
|
287
|
+
# Perpendicular direction
|
|
288
|
+
perp = np.array([-sin_a, cos_a])
|
|
289
|
+
# Project bounding box corners onto perp axis
|
|
290
|
+
corners = np.array([
|
|
291
|
+
[x_lo, y_lo], [x_hi, y_lo],
|
|
292
|
+
[x_hi, y_hi], [x_lo, y_hi],
|
|
293
|
+
])
|
|
294
|
+
projs = corners @ perp
|
|
295
|
+
p_min, p_max = projs.min(), projs.max()
|
|
296
|
+
|
|
297
|
+
t = p_min
|
|
298
|
+
while t <= p_max + spacing:
|
|
299
|
+
# Line origin (point on the perpendicular axis)
|
|
300
|
+
ox = perp[0] * t
|
|
301
|
+
oy = perp[1] * t
|
|
302
|
+
# Extend along the line direction far enough to cross the box
|
|
303
|
+
diag = np.sqrt((x_hi - x_lo)**2 + (y_hi - y_lo)**2) * 1.5
|
|
304
|
+
sx = ox - cos_a * diag
|
|
305
|
+
sy = oy - sin_a * diag
|
|
306
|
+
ex = ox + cos_a * diag
|
|
307
|
+
ey = oy + sin_a * diag
|
|
308
|
+
# Clip to bounding box using Cohen–Sutherland (simplified)
|
|
309
|
+
pts = _clip_line_to_box(sx, sy, ex, ey, x_lo, x_hi, y_lo, y_hi)
|
|
310
|
+
if pts is not None:
|
|
311
|
+
(cx0, cy0), (cx1, cy1) = pts
|
|
312
|
+
if abs(cx1 - cx0) > 1e-4 or abs(cy1 - cy0) > 1e-4:
|
|
313
|
+
grp.add(Line(
|
|
314
|
+
start=[cx0, cy0, z],
|
|
315
|
+
end =[cx1, cy1, z],
|
|
316
|
+
stroke_color=stroke_color,
|
|
317
|
+
stroke_width=stroke_width,
|
|
318
|
+
stroke_opacity=stroke_opacity,
|
|
319
|
+
))
|
|
320
|
+
t += spacing
|
|
321
|
+
return grp
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _clip_line_to_box(
|
|
325
|
+
x0: float, y0: float,
|
|
326
|
+
x1: float, y1: float,
|
|
327
|
+
xmin: float, xmax: float,
|
|
328
|
+
ymin: float, ymax: float,
|
|
329
|
+
) -> Optional[tuple]:
|
|
330
|
+
"""Liang–Barsky line clipping. Returns ((x0,y0),(x1,y1)) or None."""
|
|
331
|
+
dx, dy = x1 - x0, y1 - y0
|
|
332
|
+
p = [-dx, dx, -dy, dy]
|
|
333
|
+
q = [x0 - xmin, xmax - x0, y0 - ymin, ymax - y0]
|
|
334
|
+
t0, t1 = 0.0, 1.0
|
|
335
|
+
for pi, qi in zip(p, q):
|
|
336
|
+
if abs(pi) < 1e-10:
|
|
337
|
+
if qi < 0:
|
|
338
|
+
return None
|
|
339
|
+
else:
|
|
340
|
+
t = qi / pi
|
|
341
|
+
if pi < 0:
|
|
342
|
+
t0 = max(t0, t)
|
|
343
|
+
else:
|
|
344
|
+
t1 = min(t1, t)
|
|
345
|
+
if t0 > t1:
|
|
346
|
+
return None
|
|
347
|
+
return (
|
|
348
|
+
(x0 + t0 * dx, y0 + t0 * dy),
|
|
349
|
+
(x0 + t1 * dx, y0 + t1 * dy),
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _world_to_px(val: float, x_center: float, unit: float) -> float:
|
|
354
|
+
"""Convert an x-axis value to Manim world x-coordinate."""
|
|
355
|
+
return (val - x_center) * unit
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
359
|
+
# Sub-components
|
|
360
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
361
|
+
|
|
362
|
+
class _NormalCurve(VGroup):
|
|
363
|
+
"""
|
|
364
|
+
A single filled normal distribution curve.
|
|
365
|
+
|
|
366
|
+
Layers (back → front):
|
|
367
|
+
1. base_poly — full curve fill polygon
|
|
368
|
+
2. ao_left — dark AO strip at the left tail
|
|
369
|
+
3. ao_right — dark AO strip at the right tail
|
|
370
|
+
4. ridge_spine — bright 1px line along the curve top
|
|
371
|
+
5. peak_cap — small bright circle at the distribution peak
|
|
372
|
+
|
|
373
|
+
Parameters
|
|
374
|
+
----------
|
|
375
|
+
mu, sigma : distribution parameters
|
|
376
|
+
x_vals : pre-computed x array (Manim world units)
|
|
377
|
+
raw_x : raw axis values corresponding to x_vals
|
|
378
|
+
scale_y : vertical scaling factor (curves are normalised to 1)
|
|
379
|
+
fill_color, fill_lite, ridge_color, ao_color : colours
|
|
380
|
+
baseline_y : y of the axis
|
|
381
|
+
z_base : base z-layer for this curve
|
|
382
|
+
"""
|
|
383
|
+
|
|
384
|
+
def __init__(
|
|
385
|
+
self,
|
|
386
|
+
mu: float,
|
|
387
|
+
sigma: float,
|
|
388
|
+
x_vals: np.ndarray,
|
|
389
|
+
raw_x: np.ndarray,
|
|
390
|
+
scale_y: float,
|
|
391
|
+
fill_color: str,
|
|
392
|
+
fill_lite: str,
|
|
393
|
+
ridge_color: str,
|
|
394
|
+
ao_color: str,
|
|
395
|
+
baseline_y: float = 0.0,
|
|
396
|
+
z_base: float = 0.0,
|
|
397
|
+
opacity: float = 0.82,
|
|
398
|
+
**kwargs,
|
|
399
|
+
):
|
|
400
|
+
super().__init__(**kwargs)
|
|
401
|
+
self._mu = mu
|
|
402
|
+
self._sigma = sigma
|
|
403
|
+
self._scale_y = scale_y
|
|
404
|
+
|
|
405
|
+
y_raw = _norm_pdf(raw_x, mu, sigma)
|
|
406
|
+
y_vals = y_raw * scale_y
|
|
407
|
+
|
|
408
|
+
# ── 1. Base fill polygon ──────────────────────────────────────
|
|
409
|
+
verts = _curve_polygon_verts(x_vals, y_vals, baseline_y)
|
|
410
|
+
if len(verts) >= 3:
|
|
411
|
+
base = Polygon(
|
|
412
|
+
*verts,
|
|
413
|
+
fill_color=fill_color,
|
|
414
|
+
fill_opacity=opacity,
|
|
415
|
+
stroke_width=0,
|
|
416
|
+
)
|
|
417
|
+
base.move_to(base.get_center() + np.array([0, 0, z_base]))
|
|
418
|
+
self.add(base)
|
|
419
|
+
|
|
420
|
+
# ── 2 & 3. AO darkening at tails ─────────────────────────────
|
|
421
|
+
ao_w = (raw_x[-1] - raw_x[0]) * 0.12
|
|
422
|
+
for side in [-1, 1]:
|
|
423
|
+
x_lim = raw_x[0] if side < 0 else raw_x[-1]
|
|
424
|
+
x_mid = x_lim + side * ao_w * (-1 if side < 0 else 1) * (-1)
|
|
425
|
+
# ao region: from tail edge to ao_w inward
|
|
426
|
+
if side < 0:
|
|
427
|
+
x_lo, x_hi = raw_x[0], raw_x[0] + ao_w
|
|
428
|
+
else:
|
|
429
|
+
x_lo, x_hi = raw_x[-1] - ao_w, raw_x[-1]
|
|
430
|
+
|
|
431
|
+
# Map to world coords
|
|
432
|
+
mask = (raw_x >= x_lo) & (raw_x <= x_hi)
|
|
433
|
+
if mask.sum() < 2:
|
|
434
|
+
continue
|
|
435
|
+
ao_verts = _clipped_area_verts(
|
|
436
|
+
x_vals, y_vals, x_vals[mask][0], x_vals[mask][-1], baseline_y
|
|
437
|
+
)
|
|
438
|
+
if len(ao_verts) >= 3:
|
|
439
|
+
ao = Polygon(
|
|
440
|
+
*ao_verts,
|
|
441
|
+
fill_color=ao_color,
|
|
442
|
+
fill_opacity=0.38,
|
|
443
|
+
stroke_width=0,
|
|
444
|
+
)
|
|
445
|
+
ao.move_to(ao.get_center() + np.array([0, 0, z_base + 0.001]))
|
|
446
|
+
self.add(ao)
|
|
447
|
+
|
|
448
|
+
# ── 4. Ridge spine (bright outline along the curve top) ───────
|
|
449
|
+
spine_pts = [
|
|
450
|
+
[float(x_vals[i]), float(y_vals[i]), z_base + 0.003]
|
|
451
|
+
for i in range(0, len(x_vals), max(1, len(x_vals)//80))
|
|
452
|
+
if y_vals[i] > 0.003
|
|
453
|
+
]
|
|
454
|
+
if len(spine_pts) >= 2:
|
|
455
|
+
from manim import VMobject
|
|
456
|
+
spine = VMobject(stroke_color=ridge_color,
|
|
457
|
+
stroke_width=1.5, stroke_opacity=0.70)
|
|
458
|
+
spine.set_points_smoothly([np.array(p) for p in spine_pts])
|
|
459
|
+
self.add(spine)
|
|
460
|
+
|
|
461
|
+
# ── 5. Peak cap ───────────────────────────────────────────────
|
|
462
|
+
peak_x_raw = mu
|
|
463
|
+
peak_x_px = x_vals[np.argmin(np.abs(raw_x - peak_x_raw))]
|
|
464
|
+
peak_y_px = float(y_vals[np.argmin(np.abs(raw_x - peak_x_raw))])
|
|
465
|
+
peak_cap = Circle(
|
|
466
|
+
radius=0.045,
|
|
467
|
+
fill_color=ridge_color,
|
|
468
|
+
fill_opacity=0.85,
|
|
469
|
+
stroke_width=0,
|
|
470
|
+
)
|
|
471
|
+
peak_cap.move_to([peak_x_px, peak_y_px + 0.01, z_base + 0.004])
|
|
472
|
+
self.add(peak_cap)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
class _ErrorRegion(VGroup):
|
|
476
|
+
"""
|
|
477
|
+
A shaded + hatched region under a normal curve between x_lo and x_hi.
|
|
478
|
+
|
|
479
|
+
Layers:
|
|
480
|
+
1. fill_polygon — filled area
|
|
481
|
+
2. hatch_lines — diagonal hatch (direction and colour per region type)
|
|
482
|
+
3. region_label — e.g. "α = 0.050"
|
|
483
|
+
4. formula_badge — e.g. "P(reject H₀ | H₀ true)"
|
|
484
|
+
5. leader_arrow — arrow from label into region
|
|
485
|
+
|
|
486
|
+
Parameters
|
|
487
|
+
----------
|
|
488
|
+
x_vals, raw_x, y_vals : arrays for the parent distribution
|
|
489
|
+
x_lo_raw, x_hi_raw : raw axis bounds for this region
|
|
490
|
+
fill_color, hatch_color : colours
|
|
491
|
+
hatch_angle : diagonal direction (PI/4 = ↗, -PI/4 = ↘)
|
|
492
|
+
label_text : e.g. "α = 0.050"
|
|
493
|
+
formula_text : e.g. "P(reject H₀ | H₀ true)"
|
|
494
|
+
label_side : "above" | "below" | "left" | "right"
|
|
495
|
+
baseline_y : y of x-axis
|
|
496
|
+
z_base : z-layer
|
|
497
|
+
"""
|
|
498
|
+
|
|
499
|
+
def __init__(
|
|
500
|
+
self,
|
|
501
|
+
x_vals: np.ndarray,
|
|
502
|
+
raw_x: np.ndarray,
|
|
503
|
+
y_vals: np.ndarray,
|
|
504
|
+
x_lo_raw: float,
|
|
505
|
+
x_hi_raw: float,
|
|
506
|
+
fill_color: str,
|
|
507
|
+
hatch_color: str,
|
|
508
|
+
hatch_angle: float = PI / 4,
|
|
509
|
+
label_text: str = "",
|
|
510
|
+
formula_text: str = "",
|
|
511
|
+
label_color: str = WHITE,
|
|
512
|
+
label_side: Literal["above","below","left","right"] = "above",
|
|
513
|
+
baseline_y: float = 0.0,
|
|
514
|
+
z_base: float = 0.001,
|
|
515
|
+
fill_opacity: float = 0.50,
|
|
516
|
+
**kwargs,
|
|
517
|
+
):
|
|
518
|
+
super().__init__(**kwargs)
|
|
519
|
+
|
|
520
|
+
# Map raw bounds to world pixel bounds
|
|
521
|
+
# (raw_x and x_vals are in 1-to-1 correspondence)
|
|
522
|
+
def raw_to_px(rv: float) -> float:
|
|
523
|
+
idx = np.argmin(np.abs(raw_x - rv))
|
|
524
|
+
return float(x_vals[idx])
|
|
525
|
+
|
|
526
|
+
x_lo_px = raw_to_px(x_lo_raw)
|
|
527
|
+
x_hi_px = raw_to_px(x_hi_raw)
|
|
528
|
+
|
|
529
|
+
# ── 1. Fill polygon ───────────────────────────────────────────
|
|
530
|
+
verts = _clipped_area_verts(
|
|
531
|
+
x_vals, y_vals, x_lo_px, x_hi_px, baseline_y
|
|
532
|
+
)
|
|
533
|
+
if len(verts) >= 3:
|
|
534
|
+
fill = Polygon(
|
|
535
|
+
*verts,
|
|
536
|
+
fill_color=fill_color,
|
|
537
|
+
fill_opacity=fill_opacity,
|
|
538
|
+
stroke_width=0,
|
|
539
|
+
)
|
|
540
|
+
fill.move_to(fill.get_center() + np.array([0, 0, z_base]))
|
|
541
|
+
self.add(fill)
|
|
542
|
+
|
|
543
|
+
# ── 2. Hatch lines ─────────────────────────────────────────────
|
|
544
|
+
# Find y extent of the region
|
|
545
|
+
mask = (raw_x >= x_lo_raw) & (raw_x <= x_hi_raw)
|
|
546
|
+
y_max = float(y_vals[mask].max()) if mask.sum() > 0 else 0.05
|
|
547
|
+
hatch = _hatch_lines(
|
|
548
|
+
x_lo=x_lo_px, x_hi=x_hi_px,
|
|
549
|
+
y_lo=baseline_y, y_hi=y_max * 1.02,
|
|
550
|
+
angle=hatch_angle,
|
|
551
|
+
spacing=0.10,
|
|
552
|
+
stroke_color=hatch_color,
|
|
553
|
+
stroke_width=0.9,
|
|
554
|
+
stroke_opacity=0.50,
|
|
555
|
+
z=z_base + 0.002,
|
|
556
|
+
)
|
|
557
|
+
self.add(hatch)
|
|
558
|
+
|
|
559
|
+
# ── 3. Region label ───────────────────────────────────────────
|
|
560
|
+
# Centroid x of the region, positioned above or below
|
|
561
|
+
mid_x_px = (x_lo_px + x_hi_px) / 2
|
|
562
|
+
mask2 = (raw_x >= x_lo_raw) & (raw_x <= x_hi_raw)
|
|
563
|
+
region_h = float(y_vals[mask2].mean()) if mask2.sum() > 0 else 0.05
|
|
564
|
+
|
|
565
|
+
if label_text:
|
|
566
|
+
lbl = Text(
|
|
567
|
+
label_text,
|
|
568
|
+
font_size=20,
|
|
569
|
+
color=label_color,
|
|
570
|
+
font="sans-serif",
|
|
571
|
+
)
|
|
572
|
+
if label_side == "above":
|
|
573
|
+
lbl_y = region_h * 0.55 + 0.30
|
|
574
|
+
elif label_side == "below":
|
|
575
|
+
lbl_y = baseline_y - 0.38
|
|
576
|
+
elif label_side == "left":
|
|
577
|
+
lbl_y = region_h * 0.40
|
|
578
|
+
else:
|
|
579
|
+
lbl_y = region_h * 0.40
|
|
580
|
+
|
|
581
|
+
lbl.move_to([mid_x_px, lbl_y, z_base + 0.010])
|
|
582
|
+
self.add(lbl)
|
|
583
|
+
self._label_pos = np.array([mid_x_px, lbl_y, z_base + 0.010])
|
|
584
|
+
|
|
585
|
+
# Leader arrow from label down into region
|
|
586
|
+
arrow_tip_y = region_h * 0.28 + baseline_y
|
|
587
|
+
if abs(lbl_y - arrow_tip_y) > 0.08:
|
|
588
|
+
leader = Arrow(
|
|
589
|
+
start=[mid_x_px, lbl_y - lbl.height / 2 - 0.04,
|
|
590
|
+
z_base + 0.009],
|
|
591
|
+
end =[mid_x_px, arrow_tip_y + 0.04,
|
|
592
|
+
z_base + 0.009],
|
|
593
|
+
stroke_color=interpolate_color(label_color, BLACK, 0.30),
|
|
594
|
+
stroke_width=1.4,
|
|
595
|
+
tip_length=0.12,
|
|
596
|
+
buff=0,
|
|
597
|
+
)
|
|
598
|
+
self.add(leader)
|
|
599
|
+
|
|
600
|
+
# ── 4. Formula badge ─────────────────────────────────────────
|
|
601
|
+
if formula_text:
|
|
602
|
+
try:
|
|
603
|
+
formula = MathTex(
|
|
604
|
+
formula_text, font_size=16,
|
|
605
|
+
color=interpolate_color(label_color, WHITE, 0.25)
|
|
606
|
+
)
|
|
607
|
+
except Exception:
|
|
608
|
+
formula = Text(
|
|
609
|
+
formula_text, font_size=14,
|
|
610
|
+
color=interpolate_color(label_color, WHITE, 0.25)
|
|
611
|
+
)
|
|
612
|
+
f_bg = RoundedRectangle(
|
|
613
|
+
width=formula.width + 0.20,
|
|
614
|
+
height=formula.height + 0.12,
|
|
615
|
+
corner_radius=0.05,
|
|
616
|
+
fill_color=PALETTE["bg_panel"],
|
|
617
|
+
fill_opacity=0.80,
|
|
618
|
+
stroke_color=label_color,
|
|
619
|
+
stroke_width=0.6,
|
|
620
|
+
stroke_opacity=0.55,
|
|
621
|
+
)
|
|
622
|
+
if label_text:
|
|
623
|
+
f_y = self._label_pos[1] + 0.32
|
|
624
|
+
else:
|
|
625
|
+
f_y = region_h * 0.55 + 0.30
|
|
626
|
+
formula.move_to([mid_x_px, f_y, z_base + 0.011])
|
|
627
|
+
f_bg.move_to([mid_x_px, f_y, z_base + 0.010])
|
|
628
|
+
self.add(f_bg, formula)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
class _CriticalLine(VGroup):
|
|
632
|
+
"""
|
|
633
|
+
Vertical dashed critical-value line with a label badge.
|
|
634
|
+
|
|
635
|
+
Layers:
|
|
636
|
+
1. dashed_line — full-height dashed vertical
|
|
637
|
+
2. upper_arrow — small upward-pointing arrow at the top
|
|
638
|
+
3. badge — rounded-rect label at the axis
|
|
639
|
+
4. xc_label — "xₒ = {value:.3f}" text in badge
|
|
640
|
+
|
|
641
|
+
Parameters
|
|
642
|
+
----------
|
|
643
|
+
x_px : Manim world x-coordinate
|
|
644
|
+
y_bottom : y of axis baseline
|
|
645
|
+
y_top : y of curve apex area
|
|
646
|
+
x_raw : raw axis value (for badge label)
|
|
647
|
+
side : "right" | "left" (which side is rejection)
|
|
648
|
+
"""
|
|
649
|
+
|
|
650
|
+
def __init__(
|
|
651
|
+
self,
|
|
652
|
+
x_px: float,
|
|
653
|
+
y_bottom: float,
|
|
654
|
+
y_top: float,
|
|
655
|
+
x_raw: float,
|
|
656
|
+
side: Literal["right","left"] = "right",
|
|
657
|
+
**kwargs,
|
|
658
|
+
):
|
|
659
|
+
super().__init__(**kwargs)
|
|
660
|
+
z0 = 0.015
|
|
661
|
+
|
|
662
|
+
# ── Dashed line ───────────────────────────────────────────────
|
|
663
|
+
dline = DashedLine(
|
|
664
|
+
start=[x_px, y_bottom - 0.12, z0],
|
|
665
|
+
end =[x_px, y_top + 0.18, z0],
|
|
666
|
+
stroke_color=PALETTE["crit_line"],
|
|
667
|
+
stroke_width=2.2,
|
|
668
|
+
dash_length=0.14,
|
|
669
|
+
dashed_ratio=0.55,
|
|
670
|
+
)
|
|
671
|
+
self.add(dline)
|
|
672
|
+
|
|
673
|
+
# ── Arrow tip at top ──────────────────────────────────────────
|
|
674
|
+
tip = Arrow(
|
|
675
|
+
start=[x_px, y_top + 0.05, z0],
|
|
676
|
+
end =[x_px, y_top + 0.30, z0],
|
|
677
|
+
stroke_color=PALETTE["crit_line"],
|
|
678
|
+
stroke_width=1.6,
|
|
679
|
+
tip_length=0.12,
|
|
680
|
+
buff=0,
|
|
681
|
+
)
|
|
682
|
+
self.add(tip)
|
|
683
|
+
|
|
684
|
+
# ── Badge at axis ─────────────────────────────────────────────
|
|
685
|
+
sign_str = "≥" if side == "right" else "≤"
|
|
686
|
+
badge_str = f"$x_c = {x_raw:.3f}$"
|
|
687
|
+
try:
|
|
688
|
+
badge_lbl = MathTex(
|
|
689
|
+
badge_str.replace("$",""),
|
|
690
|
+
font_size=18,
|
|
691
|
+
color=PALETTE["crit_badge_fg"],
|
|
692
|
+
)
|
|
693
|
+
except Exception:
|
|
694
|
+
badge_lbl = Text(
|
|
695
|
+
f"xc = {x_raw:.3f}",
|
|
696
|
+
font_size=16,
|
|
697
|
+
color=PALETTE["crit_badge_fg"],
|
|
698
|
+
)
|
|
699
|
+
badge_bg = RoundedRectangle(
|
|
700
|
+
width=badge_lbl.width + 0.22,
|
|
701
|
+
height=badge_lbl.height + 0.14,
|
|
702
|
+
corner_radius=0.06,
|
|
703
|
+
fill_color=PALETTE["crit_badge_bg"],
|
|
704
|
+
fill_opacity=0.92,
|
|
705
|
+
stroke_color=PALETTE["crit_line"],
|
|
706
|
+
stroke_width=0.8,
|
|
707
|
+
)
|
|
708
|
+
badge_y = y_bottom - 0.42
|
|
709
|
+
badge_bg.move_to([x_px, badge_y, z0 + 0.001])
|
|
710
|
+
badge_lbl.move_to([x_px, badge_y, z0 + 0.002])
|
|
711
|
+
self.add(badge_bg, badge_lbl)
|
|
712
|
+
|
|
713
|
+
# ── Rejection-side annotation arrow ───────────────────────────
|
|
714
|
+
arr_dir = RIGHT if side == "right" else LEFT
|
|
715
|
+
rej_lbl = Text(
|
|
716
|
+
"Rejection\nregion" if side == "right" else "Rejection\nregion",
|
|
717
|
+
font_size=14,
|
|
718
|
+
color=PALETTE["crit_line"],
|
|
719
|
+
)
|
|
720
|
+
rej_lbl.move_to(
|
|
721
|
+
[x_px + arr_dir[0] * 0.9, y_top + 0.05, z0 + 0.002]
|
|
722
|
+
)
|
|
723
|
+
self.add(rej_lbl)
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
class _EffectArrow(VGroup):
|
|
727
|
+
"""
|
|
728
|
+
Double-headed arrow between μ₀ and μ₁, labelled δ.
|
|
729
|
+
|
|
730
|
+
Layers:
|
|
731
|
+
1. double_arrow — DoubleArrow from μ₀_px to μ₁_px
|
|
732
|
+
2. delta_label — "δ" above the arrow
|
|
733
|
+
3. value_label — "= μ₁ − μ₀ = {value:.2f}" below
|
|
734
|
+
|
|
735
|
+
Parameters
|
|
736
|
+
----------
|
|
737
|
+
mu0_px, mu1_px : Manim world x-coords of the two means
|
|
738
|
+
y : vertical position of the arrow
|
|
739
|
+
delta : μ₁ − μ₀ (raw units)
|
|
740
|
+
"""
|
|
741
|
+
|
|
742
|
+
def __init__(
|
|
743
|
+
self,
|
|
744
|
+
mu0_px: float,
|
|
745
|
+
mu1_px: float,
|
|
746
|
+
y: float,
|
|
747
|
+
delta: float,
|
|
748
|
+
**kwargs,
|
|
749
|
+
):
|
|
750
|
+
super().__init__(**kwargs)
|
|
751
|
+
z0 = 0.018
|
|
752
|
+
|
|
753
|
+
arr = DoubleArrow(
|
|
754
|
+
start=[mu0_px, y, z0],
|
|
755
|
+
end =[mu1_px, y, z0],
|
|
756
|
+
stroke_color=PALETTE["delta_arrow"],
|
|
757
|
+
stroke_width=2.0,
|
|
758
|
+
tip_length=0.15,
|
|
759
|
+
buff=0,
|
|
760
|
+
)
|
|
761
|
+
self.add(arr)
|
|
762
|
+
|
|
763
|
+
mid_px = (mu0_px + mu1_px) / 2
|
|
764
|
+
|
|
765
|
+
try:
|
|
766
|
+
d_lbl = MathTex(r"\delta", font_size=28,
|
|
767
|
+
color=PALETTE["delta_label"])
|
|
768
|
+
except Exception:
|
|
769
|
+
d_lbl = Text("δ", font_size=24,
|
|
770
|
+
color=PALETTE["delta_label"])
|
|
771
|
+
d_lbl.move_to([mid_px, y + 0.28, z0 + 0.001])
|
|
772
|
+
self.add(d_lbl)
|
|
773
|
+
|
|
774
|
+
val_lbl = Text(
|
|
775
|
+
f"= μ₁ − μ₀ = {delta:.2f}",
|
|
776
|
+
font_size=15,
|
|
777
|
+
color=PALETTE["delta_label"],
|
|
778
|
+
)
|
|
779
|
+
val_lbl.move_to([mid_px, y - 0.22, z0 + 0.001])
|
|
780
|
+
self.add(val_lbl)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
class _DecisionTable(VGroup):
|
|
784
|
+
"""
|
|
785
|
+
2×2 decision table: Reality (rows) × Decision (columns).
|
|
786
|
+
|
|
787
|
+
Structure:
|
|
788
|
+
┌───────────────┬──────────────┬──────────────┐
|
|
789
|
+
│ │ Fail Reject │ Reject H₀ │
|
|
790
|
+
├───────────────┼──────────────┼──────────────┤
|
|
791
|
+
│ H₀ True │ 1−α (TN) │ α (FP) │
|
|
792
|
+
├───────────────┼──────────────┼──────────────┤
|
|
793
|
+
│ H₁ True │ β (FN) │ 1−β (TP) │
|
|
794
|
+
└───────────────┴──────────────┴──────────────┘
|
|
795
|
+
|
|
796
|
+
Each cell shows: symbol, name, and computed numeric value.
|
|
797
|
+
|
|
798
|
+
Parameters
|
|
799
|
+
----------
|
|
800
|
+
alpha, beta : computed Type I / II error rates
|
|
801
|
+
cell_w, cell_h : cell dimensions (Manim units)
|
|
802
|
+
"""
|
|
803
|
+
|
|
804
|
+
def __init__(
|
|
805
|
+
self,
|
|
806
|
+
alpha: float,
|
|
807
|
+
beta: float,
|
|
808
|
+
cell_w: float = 1.60,
|
|
809
|
+
cell_h: float = 0.75,
|
|
810
|
+
**kwargs,
|
|
811
|
+
):
|
|
812
|
+
super().__init__(**kwargs)
|
|
813
|
+
z0 = 0.001
|
|
814
|
+
|
|
815
|
+
power = 1 - beta
|
|
816
|
+
correct = 1 - alpha
|
|
817
|
+
|
|
818
|
+
# Cell data: (symbol, name, value, fill_color, text_color)
|
|
819
|
+
cells = [
|
|
820
|
+
# Row 0: H₀ True
|
|
821
|
+
("1−α", "Correct\nReject", correct, PALETTE["correct_fill"],
|
|
822
|
+
PALETTE["label_correct"]),
|
|
823
|
+
("α", "Type I\nError", alpha, PALETTE["alpha_fill"],
|
|
824
|
+
PALETTE["label_alpha"]),
|
|
825
|
+
# Row 1: H₁ True
|
|
826
|
+
("β", "Type II\nError", beta, PALETTE["beta_fill"],
|
|
827
|
+
PALETTE["label_beta"]),
|
|
828
|
+
("1−β", "Power", power, PALETTE["power_fill"],
|
|
829
|
+
PALETTE["label_power"]),
|
|
830
|
+
]
|
|
831
|
+
|
|
832
|
+
row_labels = ["H₀ True", "H₁ True"]
|
|
833
|
+
col_labels = ["Fail to\nReject H₀", "Reject H₀"]
|
|
834
|
+
row_header_w = cell_w * 0.80
|
|
835
|
+
|
|
836
|
+
total_w = row_header_w + 2 * cell_w
|
|
837
|
+
total_h = cell_h * 3 # header + 2 data rows
|
|
838
|
+
|
|
839
|
+
# ── Background panel ──────────────────────────────────────────
|
|
840
|
+
bg = RoundedRectangle(
|
|
841
|
+
width=total_w + 0.22,
|
|
842
|
+
height=total_h + 0.22,
|
|
843
|
+
corner_radius=0.10,
|
|
844
|
+
fill_color=PALETTE["bg_panel"],
|
|
845
|
+
fill_opacity=0.92,
|
|
846
|
+
stroke_color=PALETTE["table_border"],
|
|
847
|
+
stroke_width=1.2,
|
|
848
|
+
)
|
|
849
|
+
bg.move_to([0, 0, z0])
|
|
850
|
+
self.add(bg)
|
|
851
|
+
|
|
852
|
+
# ── Column headers ────────────────────────────────────────────
|
|
853
|
+
x_cols = [
|
|
854
|
+
row_header_w / 2, # row-label column
|
|
855
|
+
row_header_w + cell_w / 2, # col 0
|
|
856
|
+
row_header_w + cell_w * 3 / 2, # col 1
|
|
857
|
+
]
|
|
858
|
+
y_header = total_h / 2 - cell_h / 2
|
|
859
|
+
|
|
860
|
+
# Empty top-left cell
|
|
861
|
+
_draw_cell(self, x_cols[0] - total_w/2, y_header,
|
|
862
|
+
row_header_w, cell_h, PALETTE["table_header"],
|
|
863
|
+
"", z0)
|
|
864
|
+
# Top-centre label
|
|
865
|
+
_draw_label(self, x_cols[0] - total_w/2, y_header,
|
|
866
|
+
"Decision", 16, PALETTE["axis_label"], z0 + 0.002)
|
|
867
|
+
|
|
868
|
+
for ci, col_lbl in enumerate(col_labels):
|
|
869
|
+
xc = x_cols[ci + 1] - total_w / 2
|
|
870
|
+
_draw_cell(self, xc, y_header,
|
|
871
|
+
cell_w, cell_h, PALETTE["table_header"], "", z0)
|
|
872
|
+
_draw_label(self, xc, y_header,
|
|
873
|
+
col_lbl, 15, PALETTE["axis_label"], z0 + 0.002)
|
|
874
|
+
|
|
875
|
+
# ── Row headers + data cells ──────────────────────────────────
|
|
876
|
+
for ri in range(2):
|
|
877
|
+
yc = total_h / 2 - cell_h * (ri + 1.5)
|
|
878
|
+
# Row header
|
|
879
|
+
_draw_cell(self, x_cols[0] - total_w/2, yc,
|
|
880
|
+
row_header_w, cell_h, PALETTE["table_header"], "", z0)
|
|
881
|
+
_draw_label(self, x_cols[0] - total_w/2, yc,
|
|
882
|
+
row_labels[ri], 15, PALETTE["axis_label"], z0+0.002)
|
|
883
|
+
|
|
884
|
+
for ci in range(2):
|
|
885
|
+
sym, name, val, fc, tc = cells[ri * 2 + ci]
|
|
886
|
+
xc = x_cols[ci + 1] - total_w / 2
|
|
887
|
+
_draw_cell(self, xc, yc, cell_w, cell_h,
|
|
888
|
+
interpolate_color(fc, BLACK, 0.55), "", z0)
|
|
889
|
+
# Symbol
|
|
890
|
+
try:
|
|
891
|
+
sym_mob = MathTex(sym, font_size=22, color=tc)
|
|
892
|
+
except Exception:
|
|
893
|
+
sym_mob = Text(sym, font_size=18, color=tc)
|
|
894
|
+
sym_mob.move_to([xc, yc + 0.14, z0 + 0.003])
|
|
895
|
+
self.add(sym_mob)
|
|
896
|
+
# Name
|
|
897
|
+
name_mob = Text(name, font_size=11,
|
|
898
|
+
color=interpolate_color(tc, WHITE, 0.25))
|
|
899
|
+
name_mob.move_to([xc, yc - 0.05, z0 + 0.003])
|
|
900
|
+
self.add(name_mob)
|
|
901
|
+
# Value
|
|
902
|
+
val_mob = Text(
|
|
903
|
+
f"{val:.3f}",
|
|
904
|
+
font_size=13,
|
|
905
|
+
color=tc,
|
|
906
|
+
font="monospace",
|
|
907
|
+
)
|
|
908
|
+
val_mob.move_to([xc, yc - 0.28, z0 + 0.003])
|
|
909
|
+
self.add(val_mob)
|
|
910
|
+
|
|
911
|
+
# ── Grid lines ────────────────────────────────────────────────
|
|
912
|
+
for xi in [row_header_w, row_header_w + cell_w]:
|
|
913
|
+
xpx = xi - total_w / 2
|
|
914
|
+
self.add(Line(
|
|
915
|
+
start=[xpx, -total_h / 2, z0 + 0.001],
|
|
916
|
+
end =[xpx, total_h / 2, z0 + 0.001],
|
|
917
|
+
stroke_color=PALETTE["table_border"],
|
|
918
|
+
stroke_width=0.8,
|
|
919
|
+
))
|
|
920
|
+
for yi in [total_h / 2 - cell_h, total_h / 2 - 2 * cell_h]:
|
|
921
|
+
self.add(Line(
|
|
922
|
+
start=[-total_w / 2, yi, z0 + 0.001],
|
|
923
|
+
end =[ total_w / 2, yi, z0 + 0.001],
|
|
924
|
+
stroke_color=PALETTE["table_border"],
|
|
925
|
+
stroke_width=0.8,
|
|
926
|
+
))
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def _draw_cell(
|
|
930
|
+
parent: VGroup, x: float, y: float,
|
|
931
|
+
w: float, h: float, color: str, text: str, z: float,
|
|
932
|
+
):
|
|
933
|
+
rect = Rectangle(
|
|
934
|
+
width=w, height=h,
|
|
935
|
+
fill_color=color, fill_opacity=1.0,
|
|
936
|
+
stroke_color=PALETTE["table_border"],
|
|
937
|
+
stroke_width=0.6,
|
|
938
|
+
)
|
|
939
|
+
rect.move_to([x, y, z])
|
|
940
|
+
parent.add(rect)
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def _draw_label(
|
|
944
|
+
parent: VGroup, x: float, y: float,
|
|
945
|
+
text: str, fs: int, color: str, z: float,
|
|
946
|
+
):
|
|
947
|
+
lbl = Text(text, font_size=fs, color=color)
|
|
948
|
+
lbl.move_to([x, y, z])
|
|
949
|
+
parent.add(lbl)
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
953
|
+
# TypeITypeII ── the main export
|
|
954
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
955
|
+
|
|
956
|
+
class TypeITypeII(VGroup):
|
|
957
|
+
"""
|
|
958
|
+
Full Type I / Type II error visualisation.
|
|
959
|
+
|
|
960
|
+
Parameters
|
|
961
|
+
----------
|
|
962
|
+
mu0 : float
|
|
963
|
+
Null hypothesis mean.
|
|
964
|
+
mu1 : float
|
|
965
|
+
Alternative hypothesis mean.
|
|
966
|
+
sigma : float
|
|
967
|
+
Common population standard deviation.
|
|
968
|
+
n : int
|
|
969
|
+
Sample size. Effective SE = sigma / sqrt(n).
|
|
970
|
+
alpha : float
|
|
971
|
+
Significance level (Type I error rate). Default 0.05.
|
|
972
|
+
two_tailed : bool
|
|
973
|
+
If True, use symmetric two-tailed critical region.
|
|
974
|
+
plot_width : float
|
|
975
|
+
Total width of the plot in Manim units. Default 10.0.
|
|
976
|
+
plot_height : float
|
|
977
|
+
Maximum curve height. Default 3.0.
|
|
978
|
+
x_sigma_range : float
|
|
979
|
+
How many σ_eff to show on each side of the midpoint. Default 3.8.
|
|
980
|
+
show_table : bool
|
|
981
|
+
Show the decision table to the right. Default True.
|
|
982
|
+
show_effect_arrow : bool
|
|
983
|
+
Show the δ arrow between means. Default True.
|
|
984
|
+
show_all_regions : bool
|
|
985
|
+
Show α, β, 1−β, 1−α simultaneously from construction.
|
|
986
|
+
baseline_y : float
|
|
987
|
+
y-position of the x-axis baseline. Default 0.0.
|
|
988
|
+
|
|
989
|
+
Attributes
|
|
990
|
+
----------
|
|
991
|
+
h0_curve, h1_curve : _NormalCurve
|
|
992
|
+
crit_line : _CriticalLine (or VGroup of two for two-tailed)
|
|
993
|
+
alpha_region : _ErrorRegion
|
|
994
|
+
beta_region : _ErrorRegion
|
|
995
|
+
power_region : _ErrorRegion
|
|
996
|
+
correct_region : _ErrorRegion
|
|
997
|
+
effect_arrow : _EffectArrow | None
|
|
998
|
+
decision_table : _DecisionTable | None
|
|
999
|
+
n_tracker : ValueTracker — track current n
|
|
1000
|
+
alpha_tracker : ValueTracker — track current alpha
|
|
1001
|
+
xc_raw : float — critical value in raw units
|
|
1002
|
+
computed_alpha : float
|
|
1003
|
+
computed_beta : float
|
|
1004
|
+
computed_power : float
|
|
1005
|
+
sigma_eff : float
|
|
1006
|
+
|
|
1007
|
+
Class methods
|
|
1008
|
+
-------------
|
|
1009
|
+
TypeITypeII.z_test(mu0, mu1, sigma, n, alpha, **kw)
|
|
1010
|
+
TypeITypeII.t_test(mu0, mu1, sigma, n, alpha, **kw)
|
|
1011
|
+
"""
|
|
1012
|
+
|
|
1013
|
+
def __init__(
|
|
1014
|
+
self,
|
|
1015
|
+
mu0: float = 0.0,
|
|
1016
|
+
mu1: float = 2.0,
|
|
1017
|
+
sigma: float = 1.0,
|
|
1018
|
+
n: int = 1,
|
|
1019
|
+
alpha: float = 0.05,
|
|
1020
|
+
two_tailed: bool = False,
|
|
1021
|
+
plot_width: float = 10.0,
|
|
1022
|
+
plot_height: float = 3.0,
|
|
1023
|
+
x_sigma_range: float = 3.8,
|
|
1024
|
+
show_table: bool = True,
|
|
1025
|
+
show_effect_arrow: bool = True,
|
|
1026
|
+
show_all_regions: bool = False,
|
|
1027
|
+
baseline_y: float = 0.0,
|
|
1028
|
+
**kwargs,
|
|
1029
|
+
):
|
|
1030
|
+
super().__init__(**kwargs)
|
|
1031
|
+
|
|
1032
|
+
self._mu0 = mu0
|
|
1033
|
+
self._mu1 = mu1
|
|
1034
|
+
self._sigma = sigma
|
|
1035
|
+
self._n = n
|
|
1036
|
+
self._alpha = alpha
|
|
1037
|
+
self._two_tailed = two_tailed
|
|
1038
|
+
self._plot_width = plot_width
|
|
1039
|
+
self._plot_height = plot_height
|
|
1040
|
+
self._baseline_y = baseline_y
|
|
1041
|
+
|
|
1042
|
+
# Value trackers for live updates
|
|
1043
|
+
self.n_tracker = ValueTracker(float(n))
|
|
1044
|
+
self.alpha_tracker = ValueTracker(alpha)
|
|
1045
|
+
|
|
1046
|
+
self._build(show_table, show_effect_arrow, show_all_regions)
|
|
1047
|
+
|
|
1048
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1049
|
+
# Core build
|
|
1050
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1051
|
+
|
|
1052
|
+
def _build(
|
|
1053
|
+
self,
|
|
1054
|
+
show_table: bool,
|
|
1055
|
+
show_effect_arrow: bool,
|
|
1056
|
+
show_all_regions: bool,
|
|
1057
|
+
):
|
|
1058
|
+
"""Construct all visual components from current parameters."""
|
|
1059
|
+
mu0 = self._mu0
|
|
1060
|
+
mu1 = self._mu1
|
|
1061
|
+
sigma = self._sigma
|
|
1062
|
+
n = self._n
|
|
1063
|
+
alpha = self._alpha
|
|
1064
|
+
two_tailed = self._two_tailed
|
|
1065
|
+
baseline_y = self._baseline_y
|
|
1066
|
+
plot_width = self._plot_width
|
|
1067
|
+
plot_height = self._plot_height
|
|
1068
|
+
|
|
1069
|
+
# ── Derived quantities ────────────────────────────────────────
|
|
1070
|
+
sigma_eff = sigma / np.sqrt(n)
|
|
1071
|
+
self.sigma_eff = sigma_eff
|
|
1072
|
+
|
|
1073
|
+
# Critical value(s)
|
|
1074
|
+
if two_tailed:
|
|
1075
|
+
xc_hi = _norm_ppf(1 - alpha / 2, mu0, sigma_eff)
|
|
1076
|
+
xc_lo = _norm_ppf( alpha / 2, mu0, sigma_eff)
|
|
1077
|
+
else:
|
|
1078
|
+
xc_hi = _norm_ppf(1 - alpha, mu0, sigma_eff)
|
|
1079
|
+
xc_lo = -np.inf
|
|
1080
|
+
self.xc_raw = xc_hi
|
|
1081
|
+
|
|
1082
|
+
# Compute true α, β, power
|
|
1083
|
+
if two_tailed:
|
|
1084
|
+
self.computed_alpha = (
|
|
1085
|
+
_norm_cdf(xc_lo, mu0, sigma_eff)
|
|
1086
|
+
+ (1 - _norm_cdf(xc_hi, mu0, sigma_eff))
|
|
1087
|
+
)
|
|
1088
|
+
self.computed_beta = (
|
|
1089
|
+
_norm_cdf(xc_hi, mu1, sigma_eff)
|
|
1090
|
+
- _norm_cdf(xc_lo, mu1, sigma_eff)
|
|
1091
|
+
)
|
|
1092
|
+
else:
|
|
1093
|
+
self.computed_alpha = 1 - _norm_cdf(xc_hi, mu0, sigma_eff)
|
|
1094
|
+
self.computed_beta = _norm_cdf(xc_hi, mu1, sigma_eff)
|
|
1095
|
+
self.computed_power = 1 - self.computed_beta
|
|
1096
|
+
|
|
1097
|
+
# ── x-axis setup ──────────────────────────────────────────────
|
|
1098
|
+
x_mid = (mu0 + mu1) / 2
|
|
1099
|
+
x_range = self._plot_width / 2 + sigma_eff * 0.5
|
|
1100
|
+
# We span from the leftmost to rightmost relevant point
|
|
1101
|
+
x_lo_raw = min(mu0, mu1) - 3.8 * sigma_eff
|
|
1102
|
+
x_hi_raw = max(mu0, mu1) + 3.8 * sigma_eff
|
|
1103
|
+
raw_x = np.linspace(x_lo_raw, x_hi_raw, 600)
|
|
1104
|
+
|
|
1105
|
+
# Unit: Manim units per raw axis unit
|
|
1106
|
+
unit = plot_width / (x_hi_raw - x_lo_raw)
|
|
1107
|
+
self._unit = unit
|
|
1108
|
+
self._raw_x = raw_x
|
|
1109
|
+
|
|
1110
|
+
def to_px(rv: float) -> float:
|
|
1111
|
+
return (rv - x_lo_raw) * unit - plot_width / 2
|
|
1112
|
+
|
|
1113
|
+
self._to_px = to_px
|
|
1114
|
+
x_vals = (raw_x - x_lo_raw) * unit - plot_width / 2
|
|
1115
|
+
|
|
1116
|
+
# y scaling: normalise curves so peak = plot_height
|
|
1117
|
+
peak_pdf = float(_norm_pdf(np.array([mu0]), mu0, sigma_eff)[0])
|
|
1118
|
+
scale_y = plot_height / peak_pdf
|
|
1119
|
+
|
|
1120
|
+
y0_vals = _norm_pdf(raw_x, mu0, sigma_eff) * scale_y
|
|
1121
|
+
y1_vals = _norm_pdf(raw_x, mu1, sigma_eff) * scale_y
|
|
1122
|
+
|
|
1123
|
+
# ── Axis line ─────────────────────────────────────────────────
|
|
1124
|
+
axis_line = Line(
|
|
1125
|
+
start=[-plot_width / 2 - 0.3, baseline_y, 0],
|
|
1126
|
+
end =[ plot_width / 2 + 0.3, baseline_y, 0],
|
|
1127
|
+
stroke_color=PALETTE["axis"],
|
|
1128
|
+
stroke_width=1.8,
|
|
1129
|
+
)
|
|
1130
|
+
self.add(axis_line)
|
|
1131
|
+
|
|
1132
|
+
# ── Mean tick marks ───────────────────────────────────────────
|
|
1133
|
+
for mu, lbl_str in [(mu0, r"\mu_0"), (mu1, r"\mu_1")]:
|
|
1134
|
+
px = to_px(mu)
|
|
1135
|
+
tk = Line(
|
|
1136
|
+
start=[px, baseline_y - 0.10, 0.001],
|
|
1137
|
+
end =[px, baseline_y + 0.10, 0.001],
|
|
1138
|
+
stroke_color=PALETTE["axis"],
|
|
1139
|
+
stroke_width=1.5,
|
|
1140
|
+
)
|
|
1141
|
+
self.add(tk)
|
|
1142
|
+
try:
|
|
1143
|
+
ml = MathTex(lbl_str, font_size=20,
|
|
1144
|
+
color=PALETTE["axis_label"])
|
|
1145
|
+
except Exception:
|
|
1146
|
+
ml = Text(lbl_str.replace("\\","").replace("{","").replace("}",""),
|
|
1147
|
+
font_size=17, color=PALETTE["axis_label"])
|
|
1148
|
+
ml.move_to([px, baseline_y - 0.38, 0.001])
|
|
1149
|
+
self.add(ml)
|
|
1150
|
+
|
|
1151
|
+
# ── H₀ curve ──────────────────────────────────────────────────
|
|
1152
|
+
self.h0_curve = _NormalCurve(
|
|
1153
|
+
mu=to_px(mu0), sigma=sigma_eff * unit,
|
|
1154
|
+
x_vals=x_vals, raw_x=raw_x,
|
|
1155
|
+
scale_y=scale_y,
|
|
1156
|
+
fill_color=PALETTE["h0_fill"],
|
|
1157
|
+
fill_lite=PALETTE["h0_fill_lite"],
|
|
1158
|
+
ridge_color=PALETTE["h0_ridge"],
|
|
1159
|
+
ao_color=PALETTE["h0_tail_ao"],
|
|
1160
|
+
baseline_y=baseline_y,
|
|
1161
|
+
z_base=0.002,
|
|
1162
|
+
opacity=0.75,
|
|
1163
|
+
)
|
|
1164
|
+
self.add(self.h0_curve)
|
|
1165
|
+
|
|
1166
|
+
# ── H₁ curve ──────────────────────────────────────────────────
|
|
1167
|
+
self.h1_curve = _NormalCurve(
|
|
1168
|
+
mu=to_px(mu1), sigma=sigma_eff * unit,
|
|
1169
|
+
x_vals=x_vals, raw_x=raw_x,
|
|
1170
|
+
scale_y=scale_y,
|
|
1171
|
+
fill_color=PALETTE["h1_fill"],
|
|
1172
|
+
fill_lite=PALETTE["h1_fill_lite"],
|
|
1173
|
+
ridge_color=PALETTE["h1_ridge"],
|
|
1174
|
+
ao_color=PALETTE["h1_tail_ao"],
|
|
1175
|
+
baseline_y=baseline_y,
|
|
1176
|
+
z_base=0.003,
|
|
1177
|
+
opacity=0.75,
|
|
1178
|
+
)
|
|
1179
|
+
self.add(self.h1_curve)
|
|
1180
|
+
|
|
1181
|
+
# ── Curve labels ──────────────────────────────────────────────
|
|
1182
|
+
for mu, label_str, ridge_col in [
|
|
1183
|
+
(mu0, r"H_0", PALETTE["h0_ridge"]),
|
|
1184
|
+
(mu1, r"H_1", PALETTE["h1_ridge"]),
|
|
1185
|
+
]:
|
|
1186
|
+
px = to_px(mu)
|
|
1187
|
+
py = float(y0_vals[np.argmin(np.abs(raw_x - mu))]) if mu == mu0 \
|
|
1188
|
+
else float(y1_vals[np.argmin(np.abs(raw_x - mu))])
|
|
1189
|
+
try:
|
|
1190
|
+
cl = MathTex(label_str, font_size=28, color=ridge_col)
|
|
1191
|
+
except Exception:
|
|
1192
|
+
cl = Text(label_str, font_size=24, color=ridge_col)
|
|
1193
|
+
cl.move_to([px, py + 0.30, 0.020])
|
|
1194
|
+
self.add(cl)
|
|
1195
|
+
|
|
1196
|
+
# ── Critical line(s) ──────────────────────────────────────────
|
|
1197
|
+
y_top = plot_height * 0.88
|
|
1198
|
+
self.crit_lines = VGroup()
|
|
1199
|
+
self.crit_line = _CriticalLine(
|
|
1200
|
+
x_px=to_px(xc_hi),
|
|
1201
|
+
y_bottom=baseline_y,
|
|
1202
|
+
y_top=y_top,
|
|
1203
|
+
x_raw=xc_hi,
|
|
1204
|
+
side="right",
|
|
1205
|
+
)
|
|
1206
|
+
self.crit_lines.add(self.crit_line)
|
|
1207
|
+
if two_tailed:
|
|
1208
|
+
crit_lo = _CriticalLine(
|
|
1209
|
+
x_px=to_px(xc_lo),
|
|
1210
|
+
y_bottom=baseline_y,
|
|
1211
|
+
y_top=y_top,
|
|
1212
|
+
x_raw=xc_lo,
|
|
1213
|
+
side="left",
|
|
1214
|
+
)
|
|
1215
|
+
self.crit_lines.add(crit_lo)
|
|
1216
|
+
self.add(self.crit_lines)
|
|
1217
|
+
|
|
1218
|
+
# ── Error regions ─────────────────────────────────────────────
|
|
1219
|
+
# α: under H₀ in rejection zone (right of xc, or both tails)
|
|
1220
|
+
self.alpha_region = _ErrorRegion(
|
|
1221
|
+
x_vals=x_vals, raw_x=raw_x, y_vals=y0_vals,
|
|
1222
|
+
x_lo_raw=xc_hi, x_hi_raw=x_hi_raw,
|
|
1223
|
+
fill_color=PALETTE["alpha_fill"],
|
|
1224
|
+
hatch_color=PALETTE["alpha_hatch"],
|
|
1225
|
+
hatch_angle=PI / 4,
|
|
1226
|
+
label_text=f"α = {self.computed_alpha:.3f}",
|
|
1227
|
+
formula_text=r"P(\text{reject }H_0 | H_0)",
|
|
1228
|
+
label_color=PALETTE["label_alpha"],
|
|
1229
|
+
label_side="above",
|
|
1230
|
+
baseline_y=baseline_y,
|
|
1231
|
+
z_base=0.006,
|
|
1232
|
+
fill_opacity=0.55,
|
|
1233
|
+
)
|
|
1234
|
+
|
|
1235
|
+
# β: under H₁ in acceptance zone (left of xc)
|
|
1236
|
+
self.beta_region = _ErrorRegion(
|
|
1237
|
+
x_vals=x_vals, raw_x=raw_x, y_vals=y1_vals,
|
|
1238
|
+
x_lo_raw=x_lo_raw, x_hi_raw=xc_hi,
|
|
1239
|
+
fill_color=PALETTE["beta_fill"],
|
|
1240
|
+
hatch_color=PALETTE["beta_hatch"],
|
|
1241
|
+
hatch_angle=-PI / 4,
|
|
1242
|
+
label_text=f"β = {self.computed_beta:.3f}",
|
|
1243
|
+
formula_text=r"P(\text{fail reject}|H_1)",
|
|
1244
|
+
label_color=PALETTE["label_beta"],
|
|
1245
|
+
label_side="above",
|
|
1246
|
+
baseline_y=baseline_y,
|
|
1247
|
+
z_base=0.006,
|
|
1248
|
+
fill_opacity=0.55,
|
|
1249
|
+
)
|
|
1250
|
+
|
|
1251
|
+
# 1−β (Power): under H₁ in rejection zone (right of xc)
|
|
1252
|
+
self.power_region = _ErrorRegion(
|
|
1253
|
+
x_vals=x_vals, raw_x=raw_x, y_vals=y1_vals,
|
|
1254
|
+
x_lo_raw=xc_hi, x_hi_raw=x_hi_raw,
|
|
1255
|
+
fill_color=PALETTE["power_fill"],
|
|
1256
|
+
hatch_color=PALETTE["power_hatch"],
|
|
1257
|
+
hatch_angle=PI / 4,
|
|
1258
|
+
label_text=f"1−β = {self.computed_power:.3f}",
|
|
1259
|
+
formula_text=r"P(\text{reject }H_0 | H_1)",
|
|
1260
|
+
label_color=PALETTE["label_power"],
|
|
1261
|
+
label_side="above",
|
|
1262
|
+
baseline_y=baseline_y,
|
|
1263
|
+
z_base=0.006,
|
|
1264
|
+
fill_opacity=0.55,
|
|
1265
|
+
)
|
|
1266
|
+
|
|
1267
|
+
# 1−α (Correct non-rejection): under H₀ in acceptance zone
|
|
1268
|
+
self.correct_region = _ErrorRegion(
|
|
1269
|
+
x_vals=x_vals, raw_x=raw_x, y_vals=y0_vals,
|
|
1270
|
+
x_lo_raw=x_lo_raw, x_hi_raw=xc_hi,
|
|
1271
|
+
fill_color=PALETTE["correct_fill"],
|
|
1272
|
+
hatch_color=PALETTE["correct_hatch"],
|
|
1273
|
+
hatch_angle=-PI / 4,
|
|
1274
|
+
label_text=f"1−α = {1-self.computed_alpha:.3f}",
|
|
1275
|
+
formula_text=r"P(\text{fail reject}|H_0)",
|
|
1276
|
+
label_color=PALETTE["label_correct"],
|
|
1277
|
+
label_side="below",
|
|
1278
|
+
baseline_y=baseline_y,
|
|
1279
|
+
z_base=0.005,
|
|
1280
|
+
fill_opacity=0.38,
|
|
1281
|
+
)
|
|
1282
|
+
|
|
1283
|
+
if show_all_regions:
|
|
1284
|
+
self.add(self.correct_region, self.beta_region,
|
|
1285
|
+
self.alpha_region, self.power_region)
|
|
1286
|
+
else:
|
|
1287
|
+
# Regions start hidden; animations reveal them
|
|
1288
|
+
for r in [self.alpha_region, self.beta_region,
|
|
1289
|
+
self.power_region, self.correct_region]:
|
|
1290
|
+
r.set_opacity(0)
|
|
1291
|
+
self.add(r)
|
|
1292
|
+
|
|
1293
|
+
# ── Effect size arrow ─────────────────────────────────────────
|
|
1294
|
+
self.effect_arrow = None
|
|
1295
|
+
if show_effect_arrow and mu0 != mu1:
|
|
1296
|
+
arrow_y = plot_height * 0.30
|
|
1297
|
+
self.effect_arrow = _EffectArrow(
|
|
1298
|
+
mu0_px=to_px(mu0),
|
|
1299
|
+
mu1_px=to_px(mu1),
|
|
1300
|
+
y=baseline_y + arrow_y,
|
|
1301
|
+
delta=mu1 - mu0,
|
|
1302
|
+
)
|
|
1303
|
+
self.add(self.effect_arrow)
|
|
1304
|
+
|
|
1305
|
+
# ── Decision table ────────────────────────────────────────────
|
|
1306
|
+
self.decision_table = None
|
|
1307
|
+
if show_table:
|
|
1308
|
+
self.decision_table = _DecisionTable(
|
|
1309
|
+
alpha=self.computed_alpha,
|
|
1310
|
+
beta=self.computed_beta,
|
|
1311
|
+
cell_w=1.55,
|
|
1312
|
+
cell_h=0.72,
|
|
1313
|
+
)
|
|
1314
|
+
self.decision_table.scale(0.88)
|
|
1315
|
+
self.decision_table.move_to(
|
|
1316
|
+
[plot_width / 2 + 2.80, baseline_y + plot_height * 0.30, 0]
|
|
1317
|
+
)
|
|
1318
|
+
self.add(self.decision_table)
|
|
1319
|
+
|
|
1320
|
+
# Store for re-build
|
|
1321
|
+
self._x_vals = x_vals
|
|
1322
|
+
self._y0_vals = y0_vals
|
|
1323
|
+
self._y1_vals = y1_vals
|
|
1324
|
+
self._x_lo_raw = x_lo_raw
|
|
1325
|
+
self._x_hi_raw = x_hi_raw
|
|
1326
|
+
|
|
1327
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1328
|
+
# Rebuild with new parameters
|
|
1329
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1330
|
+
|
|
1331
|
+
def rebuild(
|
|
1332
|
+
self,
|
|
1333
|
+
n: Optional[int] = None,
|
|
1334
|
+
alpha: Optional[float] = None,
|
|
1335
|
+
mu1: Optional[float] = None,
|
|
1336
|
+
sigma: Optional[float] = None,
|
|
1337
|
+
) -> "TypeITypeII":
|
|
1338
|
+
"""
|
|
1339
|
+
Return a fresh TypeITypeII with updated parameters.
|
|
1340
|
+
Used internally by NarrowCurves and SweepAlpha.
|
|
1341
|
+
"""
|
|
1342
|
+
return TypeITypeII(
|
|
1343
|
+
mu0=self._mu0,
|
|
1344
|
+
mu1=mu1 if mu1 is not None else self._mu1,
|
|
1345
|
+
sigma=sigma if sigma is not None else self._sigma,
|
|
1346
|
+
n=n if n is not None else self._n,
|
|
1347
|
+
alpha=alpha if alpha is not None else self._alpha,
|
|
1348
|
+
two_tailed=self._two_tailed,
|
|
1349
|
+
plot_width=self._plot_width,
|
|
1350
|
+
plot_height=self._plot_height,
|
|
1351
|
+
baseline_y=self._baseline_y,
|
|
1352
|
+
show_table=self.decision_table is not None,
|
|
1353
|
+
show_effect_arrow=self.effect_arrow is not None,
|
|
1354
|
+
show_all_regions=True,
|
|
1355
|
+
)
|
|
1356
|
+
|
|
1357
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1358
|
+
# Class-method constructors
|
|
1359
|
+
# ─────────────────────────────────────────────────────────────────
|
|
1360
|
+
|
|
1361
|
+
@classmethod
|
|
1362
|
+
def z_test(
|
|
1363
|
+
cls,
|
|
1364
|
+
mu0: float, mu1: float,
|
|
1365
|
+
sigma: float, n: int,
|
|
1366
|
+
alpha: float = 0.05,
|
|
1367
|
+
**kwargs,
|
|
1368
|
+
) -> "TypeITypeII":
|
|
1369
|
+
"""One-sided Z-test visualisation (σ known)."""
|
|
1370
|
+
return cls(mu0=mu0, mu1=mu1, sigma=sigma, n=n,
|
|
1371
|
+
alpha=alpha, two_tailed=False, **kwargs)
|
|
1372
|
+
|
|
1373
|
+
@classmethod
|
|
1374
|
+
def t_test(
|
|
1375
|
+
cls,
|
|
1376
|
+
mu0: float, mu1: float,
|
|
1377
|
+
sigma: float, n: int,
|
|
1378
|
+
alpha: float = 0.05,
|
|
1379
|
+
**kwargs,
|
|
1380
|
+
) -> "TypeITypeII":
|
|
1381
|
+
"""One-sided t-test visualisation (uses t critical value)."""
|
|
1382
|
+
# For visual purposes use normal (large-n approx) or scipy t
|
|
1383
|
+
try:
|
|
1384
|
+
from scipy.stats import t as tdist
|
|
1385
|
+
xc = float(tdist.ppf(1 - alpha, df=n-1)) * sigma / np.sqrt(n) + mu0
|
|
1386
|
+
except ImportError:
|
|
1387
|
+
xc = _norm_ppf(1 - alpha, mu0, sigma / np.sqrt(n))
|
|
1388
|
+
return cls(mu0=mu0, mu1=mu1, sigma=sigma, n=n,
|
|
1389
|
+
alpha=alpha, two_tailed=False, **kwargs)
|
|
1390
|
+
|
|
1391
|
+
|
|
1392
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1393
|
+
# Animations
|
|
1394
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1395
|
+
|
|
1396
|
+
class BuildDistributions(Animation):
|
|
1397
|
+
"""
|
|
1398
|
+
Both distribution curves grow upward from the baseline simultaneously.
|
|
1399
|
+
The critical line materialises at the end.
|
|
1400
|
+
|
|
1401
|
+
Parameters
|
|
1402
|
+
----------
|
|
1403
|
+
viz : TypeITypeII
|
|
1404
|
+
run_time : float
|
|
1405
|
+
"""
|
|
1406
|
+
|
|
1407
|
+
def __init__(self, viz: TypeITypeII, **kwargs):
|
|
1408
|
+
self.viz = viz
|
|
1409
|
+
kwargs.setdefault("run_time", 2.2)
|
|
1410
|
+
kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
|
|
1411
|
+
grp = VGroup(viz.h0_curve, viz.h1_curve)
|
|
1412
|
+
super().__init__(grp, **kwargs)
|
|
1413
|
+
|
|
1414
|
+
def interpolate_mobject(self, alpha: float):
|
|
1415
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1416
|
+
# Scale y from 0 → 1 (curves grow upward from baseline)
|
|
1417
|
+
baseline = self.viz._baseline_y
|
|
1418
|
+
self.mobject.scale(
|
|
1419
|
+
[1, alpha if alpha > 1e-4 else 1e-4, 1],
|
|
1420
|
+
about_point=[
|
|
1421
|
+
self.mobject.get_center()[0],
|
|
1422
|
+
baseline,
|
|
1423
|
+
0,
|
|
1424
|
+
],
|
|
1425
|
+
)
|
|
1426
|
+
# Critical lines fade in during last 30%
|
|
1427
|
+
crit_alpha = max(0.0, (alpha - 0.70) / 0.30)
|
|
1428
|
+
self.viz.crit_lines.set_opacity(crit_alpha)
|
|
1429
|
+
|
|
1430
|
+
|
|
1431
|
+
class RevealAlpha(Animation):
|
|
1432
|
+
"""Fade in the α (Type I error) region."""
|
|
1433
|
+
|
|
1434
|
+
def __init__(self, viz: TypeITypeII, **kwargs):
|
|
1435
|
+
self.viz = viz
|
|
1436
|
+
kwargs.setdefault("run_time", 1.0)
|
|
1437
|
+
kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
|
|
1438
|
+
super().__init__(viz.alpha_region, **kwargs)
|
|
1439
|
+
|
|
1440
|
+
def interpolate_mobject(self, alpha: float):
|
|
1441
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1442
|
+
self.mobject.set_opacity(alpha)
|
|
1443
|
+
|
|
1444
|
+
|
|
1445
|
+
class RevealBeta(Animation):
|
|
1446
|
+
"""Fade in the β (Type II error) region."""
|
|
1447
|
+
|
|
1448
|
+
def __init__(self, viz: TypeITypeII, **kwargs):
|
|
1449
|
+
self.viz = viz
|
|
1450
|
+
kwargs.setdefault("run_time", 1.0)
|
|
1451
|
+
kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
|
|
1452
|
+
super().__init__(viz.beta_region, **kwargs)
|
|
1453
|
+
|
|
1454
|
+
def interpolate_mobject(self, alpha: float):
|
|
1455
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1456
|
+
self.mobject.set_opacity(alpha)
|
|
1457
|
+
|
|
1458
|
+
|
|
1459
|
+
class RevealPower(Animation):
|
|
1460
|
+
"""Fade in the 1−β (Power) region."""
|
|
1461
|
+
|
|
1462
|
+
def __init__(self, viz: TypeITypeII, **kwargs):
|
|
1463
|
+
self.viz = viz
|
|
1464
|
+
kwargs.setdefault("run_time", 1.0)
|
|
1465
|
+
kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
|
|
1466
|
+
super().__init__(viz.power_region, **kwargs)
|
|
1467
|
+
|
|
1468
|
+
def interpolate_mobject(self, alpha: float):
|
|
1469
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1470
|
+
self.mobject.set_opacity(alpha)
|
|
1471
|
+
|
|
1472
|
+
|
|
1473
|
+
class RevealAll(Succession):
|
|
1474
|
+
"""
|
|
1475
|
+
Orchestrated sequence: curves → α → 1−α → β → 1−β → table.
|
|
1476
|
+
|
|
1477
|
+
Parameters
|
|
1478
|
+
----------
|
|
1479
|
+
viz : TypeITypeII
|
|
1480
|
+
run_time : float — total (distributes across sub-animations)
|
|
1481
|
+
"""
|
|
1482
|
+
|
|
1483
|
+
def __init__(self, viz: TypeITypeII, **kwargs):
|
|
1484
|
+
anims = [
|
|
1485
|
+
BuildDistributions(viz, run_time=2.0),
|
|
1486
|
+
FadeIn(viz.correct_region, run_time=0.8),
|
|
1487
|
+
RevealAlpha(viz, run_time=0.9),
|
|
1488
|
+
FadeIn(viz.beta_region, run_time=0.9),
|
|
1489
|
+
RevealPower(viz, run_time=0.9),
|
|
1490
|
+
]
|
|
1491
|
+
if viz.effect_arrow is not None:
|
|
1492
|
+
anims.append(FadeIn(viz.effect_arrow, run_time=0.7))
|
|
1493
|
+
if viz.decision_table is not None:
|
|
1494
|
+
anims.append(FadeIn(viz.decision_table, shift=RIGHT * 0.3,
|
|
1495
|
+
run_time=0.8))
|
|
1496
|
+
kwargs.setdefault(
|
|
1497
|
+
"run_time", sum(a.run_time for a in anims)
|
|
1498
|
+
)
|
|
1499
|
+
super().__init__(*anims, **kwargs)
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
class ShiftH1(Animation):
|
|
1503
|
+
"""
|
|
1504
|
+
Smoothly move the H₁ distribution to a new mean ``new_mu1``,
|
|
1505
|
+
morphing the β and power regions accordingly.
|
|
1506
|
+
|
|
1507
|
+
Implementation: interpolates between the current viz and a freshly
|
|
1508
|
+
rebuilt one using ``become()``.
|
|
1509
|
+
|
|
1510
|
+
Parameters
|
|
1511
|
+
----------
|
|
1512
|
+
viz : TypeITypeII
|
|
1513
|
+
new_mu1 : float
|
|
1514
|
+
run_time: float
|
|
1515
|
+
"""
|
|
1516
|
+
|
|
1517
|
+
def __init__(
|
|
1518
|
+
self,
|
|
1519
|
+
viz: TypeITypeII,
|
|
1520
|
+
new_mu1: float,
|
|
1521
|
+
**kwargs,
|
|
1522
|
+
):
|
|
1523
|
+
self.viz = viz
|
|
1524
|
+
self.new_mu1 = new_mu1
|
|
1525
|
+
self.target = viz.rebuild(mu1=new_mu1)
|
|
1526
|
+
self.target.move_to(viz.get_center())
|
|
1527
|
+
kwargs.setdefault("run_time", 2.0)
|
|
1528
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
|
|
1529
|
+
super().__init__(viz, **kwargs)
|
|
1530
|
+
|
|
1531
|
+
def interpolate_mobject(self, alpha: float):
|
|
1532
|
+
self.mobject.become(
|
|
1533
|
+
self.starting_mobject.copy()
|
|
1534
|
+
if alpha < 0.5
|
|
1535
|
+
else self.target.copy()
|
|
1536
|
+
)
|
|
1537
|
+
# Smooth cross-fade
|
|
1538
|
+
self.starting_mobject.set_opacity(1 - alpha)
|
|
1539
|
+
self.target.set_opacity(alpha)
|
|
1540
|
+
if alpha >= 1.0:
|
|
1541
|
+
self.viz._mu1 = self.new_mu1
|
|
1542
|
+
|
|
1543
|
+
|
|
1544
|
+
class NarrowCurves(Animation):
|
|
1545
|
+
"""
|
|
1546
|
+
Increase sample size n → both curves narrow, β shrinks, power grows.
|
|
1547
|
+
Morphs the entire visualisation into a rebuilt one.
|
|
1548
|
+
|
|
1549
|
+
Parameters
|
|
1550
|
+
----------
|
|
1551
|
+
viz : TypeITypeII
|
|
1552
|
+
new_n : int — new sample size
|
|
1553
|
+
run_time: float
|
|
1554
|
+
"""
|
|
1555
|
+
|
|
1556
|
+
def __init__(
|
|
1557
|
+
self,
|
|
1558
|
+
viz: TypeITypeII,
|
|
1559
|
+
new_n: int,
|
|
1560
|
+
**kwargs,
|
|
1561
|
+
):
|
|
1562
|
+
self.viz = viz
|
|
1563
|
+
self.new_n = new_n
|
|
1564
|
+
self.target = viz.rebuild(n=new_n)
|
|
1565
|
+
self.target.move_to(viz.get_center())
|
|
1566
|
+
kwargs.setdefault("run_time", 2.5)
|
|
1567
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_cubic)
|
|
1568
|
+
super().__init__(viz, **kwargs)
|
|
1569
|
+
|
|
1570
|
+
def interpolate_mobject(self, alpha: float):
|
|
1571
|
+
# Cross-fade between old and new
|
|
1572
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1573
|
+
self.mobject.set_opacity(1 - alpha)
|
|
1574
|
+
self.target.set_opacity(alpha)
|
|
1575
|
+
|
|
1576
|
+
if alpha >= 1.0:
|
|
1577
|
+
self.mobject.become(self.target)
|
|
1578
|
+
self.viz._n = self.new_n
|
|
1579
|
+
self.viz.n_tracker.set_value(float(self.new_n))
|
|
1580
|
+
|
|
1581
|
+
|
|
1582
|
+
class SweepAlpha(Animation):
|
|
1583
|
+
"""
|
|
1584
|
+
Move the critical value to correspond to a new significance level,
|
|
1585
|
+
morphing α, β, and power regions.
|
|
1586
|
+
|
|
1587
|
+
Parameters
|
|
1588
|
+
----------
|
|
1589
|
+
viz : TypeITypeII
|
|
1590
|
+
new_alpha : float — new significance level
|
|
1591
|
+
run_time : float
|
|
1592
|
+
"""
|
|
1593
|
+
|
|
1594
|
+
def __init__(
|
|
1595
|
+
self,
|
|
1596
|
+
viz: TypeITypeII,
|
|
1597
|
+
new_alpha: float,
|
|
1598
|
+
**kwargs,
|
|
1599
|
+
):
|
|
1600
|
+
self.viz = viz
|
|
1601
|
+
self.new_alpha = new_alpha
|
|
1602
|
+
self.target = viz.rebuild(alpha=new_alpha)
|
|
1603
|
+
self.target.move_to(viz.get_center())
|
|
1604
|
+
kwargs.setdefault("run_time", 2.0)
|
|
1605
|
+
kwargs.setdefault("rate_func", rate_functions.ease_in_out_sine)
|
|
1606
|
+
super().__init__(viz, **kwargs)
|
|
1607
|
+
|
|
1608
|
+
def interpolate_mobject(self, alpha_t: float):
|
|
1609
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1610
|
+
self.mobject.set_opacity(1 - alpha_t)
|
|
1611
|
+
self.target.set_opacity(alpha_t)
|
|
1612
|
+
|
|
1613
|
+
if alpha_t >= 1.0:
|
|
1614
|
+
self.mobject.become(self.target)
|
|
1615
|
+
self.viz._alpha = self.new_alpha
|
|
1616
|
+
self.viz.alpha_tracker.set_value(self.new_alpha)
|
|
1617
|
+
|
|
1618
|
+
|
|
1619
|
+
class FlashDecision(AnimationGroup):
|
|
1620
|
+
"""
|
|
1621
|
+
Highlight one cell of the decision table with a bright flash.
|
|
1622
|
+
|
|
1623
|
+
Parameters
|
|
1624
|
+
----------
|
|
1625
|
+
viz : TypeITypeII
|
|
1626
|
+
cell : "alpha" | "beta" | "power" | "correct"
|
|
1627
|
+
run_time : float
|
|
1628
|
+
"""
|
|
1629
|
+
|
|
1630
|
+
_CELL_MAP = {
|
|
1631
|
+
"alpha": PALETTE["label_alpha"],
|
|
1632
|
+
"beta": PALETTE["label_beta"],
|
|
1633
|
+
"power": PALETTE["label_power"],
|
|
1634
|
+
"correct": PALETTE["label_correct"],
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
def __init__(
|
|
1638
|
+
self,
|
|
1639
|
+
viz: TypeITypeII,
|
|
1640
|
+
cell: Literal["alpha","beta","power","correct"] = "alpha",
|
|
1641
|
+
**kwargs,
|
|
1642
|
+
):
|
|
1643
|
+
col = self._CELL_MAP.get(cell, WHITE)
|
|
1644
|
+
region_map = {
|
|
1645
|
+
"alpha": viz.alpha_region,
|
|
1646
|
+
"beta": viz.beta_region,
|
|
1647
|
+
"power": viz.power_region,
|
|
1648
|
+
"correct": viz.correct_region,
|
|
1649
|
+
}
|
|
1650
|
+
region = region_map.get(cell, viz.alpha_region)
|
|
1651
|
+
|
|
1652
|
+
anims = [
|
|
1653
|
+
Indicate(region, color=col, scale_factor=1.03, run_time=0.8),
|
|
1654
|
+
]
|
|
1655
|
+
if viz.decision_table is not None:
|
|
1656
|
+
anims.append(
|
|
1657
|
+
Flash(
|
|
1658
|
+
viz.decision_table.get_center()
|
|
1659
|
+
+ np.array([0.5, 0, 0]),
|
|
1660
|
+
color=col,
|
|
1661
|
+
line_length=0.15,
|
|
1662
|
+
num_lines=8,
|
|
1663
|
+
run_time=0.8,
|
|
1664
|
+
)
|
|
1665
|
+
)
|
|
1666
|
+
kwargs.setdefault("run_time", 0.8)
|
|
1667
|
+
super().__init__(*anims, **kwargs)
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
class BuildDecisionTable(Animation):
|
|
1671
|
+
"""
|
|
1672
|
+
Animate the 2×2 decision table growing from the centre outward.
|
|
1673
|
+
|
|
1674
|
+
Parameters
|
|
1675
|
+
----------
|
|
1676
|
+
viz : TypeITypeII
|
|
1677
|
+
run_time : float
|
|
1678
|
+
"""
|
|
1679
|
+
|
|
1680
|
+
def __init__(self, viz: TypeITypeII, **kwargs):
|
|
1681
|
+
self.viz = viz
|
|
1682
|
+
kwargs.setdefault("run_time", 1.2)
|
|
1683
|
+
kwargs.setdefault("rate_func", rate_functions.ease_out_cubic)
|
|
1684
|
+
tbl = viz.decision_table if viz.decision_table is not None else VGroup()
|
|
1685
|
+
super().__init__(tbl, **kwargs)
|
|
1686
|
+
|
|
1687
|
+
def interpolate_mobject(self, alpha: float):
|
|
1688
|
+
self.mobject.become(self.starting_mobject.copy())
|
|
1689
|
+
self.mobject.scale(
|
|
1690
|
+
alpha if alpha > 1e-4 else 1e-4,
|
|
1691
|
+
about_point=self.mobject.get_center(),
|
|
1692
|
+
)
|
|
1693
|
+
self.mobject.set_opacity(alpha)
|
|
1694
|
+
|
|
1695
|
+
|
|
1696
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1697
|
+
# Convenience factories
|
|
1698
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1699
|
+
|
|
1700
|
+
def make_power_analysis_grid(
|
|
1701
|
+
mu0: float = 0.0,
|
|
1702
|
+
mu1_values: list[float] = None,
|
|
1703
|
+
n_values: list[int] = None,
|
|
1704
|
+
sigma: float = 1.0,
|
|
1705
|
+
alpha: float = 0.05,
|
|
1706
|
+
cell_scale: float = 0.38,
|
|
1707
|
+
) -> VGroup:
|
|
1708
|
+
"""
|
|
1709
|
+
Grid of TypeITypeII visualisations varying δ (columns) and n (rows),
|
|
1710
|
+
for a compact power analysis overview.
|
|
1711
|
+
|
|
1712
|
+
Parameters
|
|
1713
|
+
----------
|
|
1714
|
+
mu0 : null mean
|
|
1715
|
+
mu1_values: list of alternative means (grid columns)
|
|
1716
|
+
n_values : list of sample sizes (grid rows)
|
|
1717
|
+
sigma, alpha : fixed
|
|
1718
|
+
cell_scale : scale factor per cell
|
|
1719
|
+
|
|
1720
|
+
Returns
|
|
1721
|
+
-------
|
|
1722
|
+
VGroup — rows × columns grid of TypeITypeII objects.
|
|
1723
|
+
"""
|
|
1724
|
+
if mu1_values is None:
|
|
1725
|
+
mu1_values = [1.0, 2.0, 3.0]
|
|
1726
|
+
if n_values is None:
|
|
1727
|
+
n_values = [1, 4, 16]
|
|
1728
|
+
|
|
1729
|
+
grid = VGroup()
|
|
1730
|
+
col_w = 5.0
|
|
1731
|
+
row_h = 3.5
|
|
1732
|
+
|
|
1733
|
+
for ri, n in enumerate(n_values):
|
|
1734
|
+
for ci, mu1 in enumerate(mu1_values):
|
|
1735
|
+
viz = TypeITypeII(
|
|
1736
|
+
mu0=mu0, mu1=mu1,
|
|
1737
|
+
sigma=sigma, n=n,
|
|
1738
|
+
alpha=alpha,
|
|
1739
|
+
two_tailed=False,
|
|
1740
|
+
plot_width=4.0,
|
|
1741
|
+
plot_height=2.0,
|
|
1742
|
+
show_table=False,
|
|
1743
|
+
show_effect_arrow=False,
|
|
1744
|
+
show_all_regions=True,
|
|
1745
|
+
)
|
|
1746
|
+
viz.scale(cell_scale)
|
|
1747
|
+
viz.move_to([ci * col_w * cell_scale,
|
|
1748
|
+
-ri * row_h * cell_scale, 0])
|
|
1749
|
+
grid.add(viz)
|
|
1750
|
+
|
|
1751
|
+
grid.center()
|
|
1752
|
+
return grid
|
|
1753
|
+
|
|
1754
|
+
|
|
1755
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1756
|
+
# Demo Scene (run with: manim -pql error_types.py ErrorTypesDemo)
|
|
1757
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
1758
|
+
|
|
1759
|
+
try:
|
|
1760
|
+
from manim import Scene, DEGREES
|
|
1761
|
+
|
|
1762
|
+
class ErrorTypesDemo(Scene):
|
|
1763
|
+
"""Full showcase of TypeITypeII visualisation and animations."""
|
|
1764
|
+
|
|
1765
|
+
def construct(self):
|
|
1766
|
+
|
|
1767
|
+
# ── Base visualisation ────────────────────────────────────
|
|
1768
|
+
viz = TypeITypeII(
|
|
1769
|
+
mu0=0.0, mu1=2.5,
|
|
1770
|
+
sigma=1.0, n=1,
|
|
1771
|
+
alpha=0.05,
|
|
1772
|
+
two_tailed=False,
|
|
1773
|
+
plot_width=9.0,
|
|
1774
|
+
plot_height=3.2,
|
|
1775
|
+
show_table=True,
|
|
1776
|
+
show_effect_arrow=True,
|
|
1777
|
+
show_all_regions=False,
|
|
1778
|
+
baseline_y=-1.5,
|
|
1779
|
+
)
|
|
1780
|
+
viz.center()
|
|
1781
|
+
self.add(viz)
|
|
1782
|
+
|
|
1783
|
+
# ── Reveal all regions in sequence ────────────────────────
|
|
1784
|
+
self.play(RevealAll(viz))
|
|
1785
|
+
self.wait(0.8)
|
|
1786
|
+
|
|
1787
|
+
# ── Flash the α cell ──────────────────────────────────────
|
|
1788
|
+
self.play(FlashDecision(viz, cell="alpha"))
|
|
1789
|
+
self.wait(0.4)
|
|
1790
|
+
self.play(FlashDecision(viz, cell="beta"))
|
|
1791
|
+
self.wait(0.4)
|
|
1792
|
+
self.play(FlashDecision(viz, cell="power"))
|
|
1793
|
+
self.wait(0.6)
|
|
1794
|
+
|
|
1795
|
+
# ── Increase n: watch β shrink ────────────────────────────
|
|
1796
|
+
self.play(NarrowCurves(viz, new_n=9, run_time=2.8))
|
|
1797
|
+
self.wait(0.6)
|
|
1798
|
+
self.play(NarrowCurves(viz, new_n=25, run_time=2.5))
|
|
1799
|
+
self.wait(0.8)
|
|
1800
|
+
|
|
1801
|
+
# ── Sweep α: trade-off ────────────────────────────────────
|
|
1802
|
+
self.play(SweepAlpha(viz, new_alpha=0.01, run_time=2.0))
|
|
1803
|
+
self.wait(0.5)
|
|
1804
|
+
self.play(SweepAlpha(viz, new_alpha=0.10, run_time=2.0))
|
|
1805
|
+
self.wait(0.8)
|
|
1806
|
+
|
|
1807
|
+
# ── Shift H₁ closer (harder test) ────────────────────────
|
|
1808
|
+
self.play(ShiftH1(viz, new_mu1=1.5, run_time=2.0))
|
|
1809
|
+
self.wait(0.5)
|
|
1810
|
+
|
|
1811
|
+
# ── Power analysis grid ───────────────────────────────────
|
|
1812
|
+
self.play(FadeOut(viz))
|
|
1813
|
+
grid = make_power_analysis_grid(
|
|
1814
|
+
mu0=0.0,
|
|
1815
|
+
mu1_values=[1.0, 2.0, 3.0],
|
|
1816
|
+
n_values=[1, 4, 16],
|
|
1817
|
+
sigma=1.0, alpha=0.05,
|
|
1818
|
+
cell_scale=0.36,
|
|
1819
|
+
)
|
|
1820
|
+
grid.center()
|
|
1821
|
+
self.play(FadeIn(grid, shift=UP * 0.3), run_time=1.0)
|
|
1822
|
+
self.wait(2.5)
|
|
1823
|
+
|
|
1824
|
+
except ImportError:
|
|
1825
|
+
pass
|