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,2247 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statanim/distributions/pdf_viz.py
|
|
3
|
+
======================================
|
|
4
|
+
Production-quality probability density function visualizer.
|
|
5
|
+
|
|
6
|
+
Design philosophy
|
|
7
|
+
-----------------
|
|
8
|
+
A PDF visualizer in a statistics course must do far more than draw a
|
|
9
|
+
curve. Every annotatable feature of a distribution — its moments,
|
|
10
|
+
tails, specific probability regions, percentiles, comparison to data —
|
|
11
|
+
must be expressible as an independent visual layer that can be added,
|
|
12
|
+
removed, and animated independently.
|
|
13
|
+
|
|
14
|
+
``PDFVisualizer3D`` is built from these independent layers:
|
|
15
|
+
|
|
16
|
+
Curve layer – stroke + glow halo (Catmull-Rom smoothed).
|
|
17
|
+
Fill layer – gradient area fill under the full curve.
|
|
18
|
+
Moment layer – μ, σ markers with bracket annotations.
|
|
19
|
+
Region layer – arbitrary [a, b] probability regions with P(·) labels.
|
|
20
|
+
Percentile layer– vertical markers at specified quantiles.
|
|
21
|
+
KDE layer – empirical density from observed data.
|
|
22
|
+
Overlay layer – second (or third) PDF curve for comparison.
|
|
23
|
+
Divergence layer– shaded region between two overlapping curves.
|
|
24
|
+
|
|
25
|
+
Each layer is an independently animated VGroup, so a teacher can
|
|
26
|
+
``Create`` the curve first, then ``FadeIn`` the moment annotations,
|
|
27
|
+
then shade a tail region — all as separate ``scene.play`` calls.
|
|
28
|
+
|
|
29
|
+
Distribution support
|
|
30
|
+
--------------------
|
|
31
|
+
All distributions are self-contained (no scipy dependency). Supported
|
|
32
|
+
families with their parameterisations:
|
|
33
|
+
|
|
34
|
+
Normal(μ, σ)
|
|
35
|
+
StudentT(df)
|
|
36
|
+
ChiSquared(df)
|
|
37
|
+
Gamma(shape=k, rate=λ) mean = k/λ
|
|
38
|
+
Beta(α, β) support [0, 1]
|
|
39
|
+
Exponential(rate=λ) mean = 1/λ
|
|
40
|
+
Cauchy(x0, γ) heavy-tailed
|
|
41
|
+
Laplace(μ, b) double-exponential
|
|
42
|
+
LogNormal(μ_log, σ_log)
|
|
43
|
+
Weibull(shape=k, scale=λ)
|
|
44
|
+
Uniform(a, b)
|
|
45
|
+
|
|
46
|
+
Classes
|
|
47
|
+
-------
|
|
48
|
+
PDFConfig
|
|
49
|
+
PDFVisualizer3D
|
|
50
|
+
MultiplePDFComparison3D
|
|
51
|
+
PDFDistribution (base)
|
|
52
|
+
|
|
53
|
+
Distribution helpers
|
|
54
|
+
--------------------
|
|
55
|
+
NormalDist
|
|
56
|
+
StudentTDist
|
|
57
|
+
ChiSquaredDist
|
|
58
|
+
GammaDist
|
|
59
|
+
BetaDist
|
|
60
|
+
ExponentialDist
|
|
61
|
+
CauchyDist
|
|
62
|
+
LaplaceDist
|
|
63
|
+
LogNormalDist
|
|
64
|
+
WeibullDist
|
|
65
|
+
UniformDist
|
|
66
|
+
|
|
67
|
+
Ready-to-render scenes
|
|
68
|
+
----------------------
|
|
69
|
+
NormalPDFScene
|
|
70
|
+
TDistScene
|
|
71
|
+
GammaPDFScene
|
|
72
|
+
PDFComparisonScene
|
|
73
|
+
PDFParameterSweepScene
|
|
74
|
+
|
|
75
|
+
Usage
|
|
76
|
+
-----
|
|
77
|
+
from manim import *
|
|
78
|
+
from statanim.distributions.pdf_viz import PDFVisualizer3D, NormalDist
|
|
79
|
+
|
|
80
|
+
class MyScene(ThreeDScene):
|
|
81
|
+
def construct(self):
|
|
82
|
+
self.set_camera_orientation(phi=65*DEGREES, theta=-45*DEGREES)
|
|
83
|
+
|
|
84
|
+
viz = PDFVisualizer3D(NormalDist(mu=0, sigma=1),
|
|
85
|
+
x_range=(-4, 4, 0.04))
|
|
86
|
+
self.play(viz.animate_curve())
|
|
87
|
+
self.play(viz.animate_fill())
|
|
88
|
+
self.play(viz.animate_moments())
|
|
89
|
+
viz.shade_tail_right(z_crit=1.645, label="5%")
|
|
90
|
+
self.play(FadeIn(viz.regions))
|
|
91
|
+
self.wait()
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
from __future__ import annotations
|
|
95
|
+
|
|
96
|
+
from dataclasses import dataclass, field
|
|
97
|
+
from typing import List, Tuple, Optional, Callable, Union, Dict
|
|
98
|
+
from abc import ABC, abstractmethod
|
|
99
|
+
import numpy as np
|
|
100
|
+
|
|
101
|
+
from manim import (
|
|
102
|
+
VGroup, VMobject, Polygon, Line, DashedLine, Dot3D,
|
|
103
|
+
Text, MathTex, Arrow, Brace,
|
|
104
|
+
ThreeDScene,
|
|
105
|
+
AnimationGroup, LaggedStart, Succession,
|
|
106
|
+
Create, FadeIn, FadeOut, Transform,
|
|
107
|
+
UpdateFromAlphaFunc, Flash, Write,
|
|
108
|
+
DEGREES, PI, TAU,
|
|
109
|
+
RIGHT, LEFT, UP, DOWN, OUT, IN, ORIGIN,
|
|
110
|
+
X_AXIS, Y_AXIS, Z_AXIS,
|
|
111
|
+
WHITE, BLACK, GRAY, BLUE, GREEN, RED, YELLOW,
|
|
112
|
+
ManimColor, color_to_rgb, rgba_to_color, color_to_rgba,
|
|
113
|
+
rate_functions, smooth,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# ---------------------------------------------------------------------------
|
|
117
|
+
# Shared colour helpers
|
|
118
|
+
# ---------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def _with_opacity(color: ManimColor, opacity: float) -> ManimColor:
|
|
121
|
+
r, g, b = color_to_rgb(color)
|
|
122
|
+
return rgba_to_color([r, g, b, max(0.0, min(1.0, opacity))])
|
|
123
|
+
|
|
124
|
+
def _darken(color: ManimColor, factor: float = 0.65) -> ManimColor:
|
|
125
|
+
r, g, b = color_to_rgb(color)
|
|
126
|
+
return ManimColor([r * factor, g * factor, b * factor])
|
|
127
|
+
|
|
128
|
+
def _lighten(color: ManimColor, factor: float = 1.35) -> ManimColor:
|
|
129
|
+
r, g, b = color_to_rgb(color)
|
|
130
|
+
return ManimColor([min(r * factor, 1.0), min(g * factor, 1.0), min(b * factor, 1.0)])
|
|
131
|
+
|
|
132
|
+
def _lerp_color(a: ManimColor, b: ManimColor, t: float) -> ManimColor:
|
|
133
|
+
ra, ga, ba = color_to_rgb(a)
|
|
134
|
+
rb, gb, bb = color_to_rgb(b)
|
|
135
|
+
return ManimColor([ra + (rb - ra) * t, ga + (gb - ga) * t, ba + (bb - ba) * t])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ---------------------------------------------------------------------------
|
|
139
|
+
# Internal geometry helpers
|
|
140
|
+
# ---------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
def _catmull_rom(points: np.ndarray, resolution: int = 20) -> np.ndarray:
|
|
143
|
+
"""Catmull-Rom spline through *points*, returning smoothed path."""
|
|
144
|
+
n = len(points)
|
|
145
|
+
if n < 2:
|
|
146
|
+
return points.copy()
|
|
147
|
+
p = np.vstack([2 * points[0] - points[1],
|
|
148
|
+
points,
|
|
149
|
+
2 * points[-1] - points[-2]])
|
|
150
|
+
out = []
|
|
151
|
+
for i in range(1, len(p) - 2):
|
|
152
|
+
p0, p1, p2, p3 = p[i-1], p[i], p[i+1], p[i+2]
|
|
153
|
+
for j in range(resolution):
|
|
154
|
+
t = j / resolution
|
|
155
|
+
t2, t3 = t*t, t*t*t
|
|
156
|
+
pt = 0.5 * ((-t3+2*t2-t)*p0 + (3*t3-5*t2+2)*p1
|
|
157
|
+
+ (-3*t3+4*t2+t)*p2 + (t3-t2)*p3)
|
|
158
|
+
out.append(pt)
|
|
159
|
+
out.append(points[-1].copy())
|
|
160
|
+
return np.array(out)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _build_fill_polygon(
|
|
164
|
+
curve_pts: np.ndarray,
|
|
165
|
+
floor_z: float,
|
|
166
|
+
y_pos: float,
|
|
167
|
+
n_gradient_strips: int = 10,
|
|
168
|
+
color: ManimColor = ManimColor("#4A90D9"),
|
|
169
|
+
opacity: float = 0.22,
|
|
170
|
+
gradient: bool = True,
|
|
171
|
+
) -> VGroup:
|
|
172
|
+
"""Build a gradient area fill polygon below *curve_pts*.
|
|
173
|
+
|
|
174
|
+
Returns a VGroup of thin horizontal strips (gradient mode) or a
|
|
175
|
+
single Polygon (flat mode).
|
|
176
|
+
"""
|
|
177
|
+
floor_pts = np.array([[p[0], y_pos, floor_z] for p in curve_pts])
|
|
178
|
+
grp = VGroup()
|
|
179
|
+
|
|
180
|
+
if not gradient or n_gradient_strips <= 1:
|
|
181
|
+
poly_pts = list(curve_pts) + list(reversed(floor_pts))
|
|
182
|
+
grp.add(Polygon(
|
|
183
|
+
*poly_pts,
|
|
184
|
+
fill_color=_with_opacity(color, opacity),
|
|
185
|
+
fill_opacity=1.0, stroke_width=0,
|
|
186
|
+
))
|
|
187
|
+
return grp
|
|
188
|
+
|
|
189
|
+
for s in range(n_gradient_strips):
|
|
190
|
+
t_lo = s / n_gradient_strips
|
|
191
|
+
t_hi = (s + 1) / n_gradient_strips
|
|
192
|
+
strip_op = opacity * (1.0 - 0.60 * t_lo)
|
|
193
|
+
upper_lo = curve_pts * (1 - t_lo) + floor_pts * t_lo
|
|
194
|
+
upper_hi = curve_pts * (1 - t_hi) + floor_pts * t_hi
|
|
195
|
+
strip_pts = list(upper_lo) + list(reversed(upper_hi))
|
|
196
|
+
grp.add(Polygon(
|
|
197
|
+
*strip_pts,
|
|
198
|
+
fill_color=_with_opacity(color, strip_op),
|
|
199
|
+
fill_opacity=1.0, stroke_width=0,
|
|
200
|
+
))
|
|
201
|
+
return grp
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ===========================================================================
|
|
205
|
+
# Distribution hierarchy
|
|
206
|
+
# ===========================================================================
|
|
207
|
+
|
|
208
|
+
class PDFDistribution(ABC):
|
|
209
|
+
"""Abstract base class for all continuous distributions.
|
|
210
|
+
|
|
211
|
+
Subclasses implement ``pdf(x)``, ``cdf(x)``, ``ppf(p)``, and
|
|
212
|
+
provide ``default_x_range``, ``mean``, ``variance``, and ``name``.
|
|
213
|
+
|
|
214
|
+
No scipy is used. All calculations are implemented analytically or
|
|
215
|
+
via numerical integration where needed.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
@abstractmethod
|
|
219
|
+
def pdf(self, x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
|
|
220
|
+
"""Probability density at *x*."""
|
|
221
|
+
|
|
222
|
+
@abstractmethod
|
|
223
|
+
def cdf(self, x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
|
|
224
|
+
"""Cumulative distribution function at *x*."""
|
|
225
|
+
|
|
226
|
+
def ppf(self, p: float) -> float:
|
|
227
|
+
"""Percent-point function (quantile) via bisection."""
|
|
228
|
+
lo, hi = self.default_x_range[0], self.default_x_range[1]
|
|
229
|
+
for _ in range(64):
|
|
230
|
+
mid = (lo + hi) / 2
|
|
231
|
+
if self.cdf(mid) < p:
|
|
232
|
+
lo = mid
|
|
233
|
+
else:
|
|
234
|
+
hi = mid
|
|
235
|
+
return (lo + hi) / 2
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
@abstractmethod
|
|
239
|
+
def name(self) -> str: ...
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
@abstractmethod
|
|
243
|
+
def param_string(self) -> str:
|
|
244
|
+
"""Short parameter description, e.g. 'μ=0, σ=1'."""
|
|
245
|
+
|
|
246
|
+
@property
|
|
247
|
+
@abstractmethod
|
|
248
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
249
|
+
"""Sensible (x_min, x_max) for plotting."""
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
@abstractmethod
|
|
253
|
+
def mean(self) -> Optional[float]: ...
|
|
254
|
+
|
|
255
|
+
@property
|
|
256
|
+
@abstractmethod
|
|
257
|
+
def variance(self) -> Optional[float]: ...
|
|
258
|
+
|
|
259
|
+
@property
|
|
260
|
+
def std(self) -> Optional[float]:
|
|
261
|
+
v = self.variance
|
|
262
|
+
return float(np.sqrt(v)) if v is not None else None
|
|
263
|
+
|
|
264
|
+
def pdf_array(self, x_range: Tuple[float, float], n: int = 400) -> Tuple[np.ndarray, np.ndarray]:
|
|
265
|
+
"""Return (xs, ys) evaluated over *x_range* at *n* points."""
|
|
266
|
+
xs = np.linspace(x_range[0], x_range[1], n)
|
|
267
|
+
ys = np.array([max(float(self.pdf(x)), 0.0) for x in xs])
|
|
268
|
+
return xs, ys
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# ---------------------------------------------------------------------------
|
|
272
|
+
# Normal
|
|
273
|
+
# ---------------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
class NormalDist(PDFDistribution):
|
|
276
|
+
"""Normal (Gaussian) distribution N(μ, σ).
|
|
277
|
+
|
|
278
|
+
Parameters
|
|
279
|
+
----------
|
|
280
|
+
mu : float
|
|
281
|
+
Mean.
|
|
282
|
+
sigma : float
|
|
283
|
+
Standard deviation (> 0).
|
|
284
|
+
"""
|
|
285
|
+
|
|
286
|
+
def __init__(self, mu: float = 0.0, sigma: float = 1.0):
|
|
287
|
+
if sigma <= 0:
|
|
288
|
+
raise ValueError("sigma must be positive")
|
|
289
|
+
self.mu = float(mu)
|
|
290
|
+
self.sigma = float(sigma)
|
|
291
|
+
|
|
292
|
+
def pdf(self, x):
|
|
293
|
+
z = (np.asarray(x, dtype=float) - self.mu) / self.sigma
|
|
294
|
+
return np.exp(-0.5 * z**2) / (self.sigma * np.sqrt(TAU))
|
|
295
|
+
|
|
296
|
+
def cdf(self, x):
|
|
297
|
+
z = (float(x) - self.mu) / (self.sigma * np.sqrt(2))
|
|
298
|
+
return 0.5 * (1 + _erf(z))
|
|
299
|
+
|
|
300
|
+
@property
|
|
301
|
+
def name(self) -> str:
|
|
302
|
+
return "Normal"
|
|
303
|
+
|
|
304
|
+
@property
|
|
305
|
+
def param_string(self) -> str:
|
|
306
|
+
return f"μ = {self.mu:.3g}, σ = {self.sigma:.3g}"
|
|
307
|
+
|
|
308
|
+
@property
|
|
309
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
310
|
+
return (self.mu - 4 * self.sigma, self.mu + 4 * self.sigma)
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def mean(self) -> float:
|
|
314
|
+
return self.mu
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def variance(self) -> float:
|
|
318
|
+
return self.sigma**2
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
# ---------------------------------------------------------------------------
|
|
322
|
+
# Student-t
|
|
323
|
+
# ---------------------------------------------------------------------------
|
|
324
|
+
|
|
325
|
+
class StudentTDist(PDFDistribution):
|
|
326
|
+
"""Student's t-distribution with *df* degrees of freedom.
|
|
327
|
+
|
|
328
|
+
Parameters
|
|
329
|
+
----------
|
|
330
|
+
df : float
|
|
331
|
+
Degrees of freedom (> 0).
|
|
332
|
+
mu : float
|
|
333
|
+
Location parameter.
|
|
334
|
+
sigma : float
|
|
335
|
+
Scale parameter.
|
|
336
|
+
"""
|
|
337
|
+
|
|
338
|
+
def __init__(self, df: float = 5.0, mu: float = 0.0, sigma: float = 1.0):
|
|
339
|
+
self.df = float(df)
|
|
340
|
+
self.mu = float(mu)
|
|
341
|
+
self.sigma = float(sigma)
|
|
342
|
+
self._log_norm = _lgamma((df + 1) / 2) - _lgamma(df / 2) - 0.5 * np.log(df * PI)
|
|
343
|
+
|
|
344
|
+
def pdf(self, x):
|
|
345
|
+
x = np.asarray(x, dtype=float)
|
|
346
|
+
z = (x - self.mu) / self.sigma
|
|
347
|
+
nu = self.df
|
|
348
|
+
return (np.exp(self._log_norm)
|
|
349
|
+
* (1 + z**2 / nu) ** (-(nu + 1) / 2)
|
|
350
|
+
/ self.sigma)
|
|
351
|
+
|
|
352
|
+
def cdf(self, x):
|
|
353
|
+
# Regularised incomplete beta: use numerical integration
|
|
354
|
+
z = (float(x) - self.mu) / self.sigma
|
|
355
|
+
nu = self.df
|
|
356
|
+
if z == 0:
|
|
357
|
+
return 0.5
|
|
358
|
+
x_b = nu / (nu + z**2)
|
|
359
|
+
ib = _reg_inc_beta(nu / 2, 0.5, x_b)
|
|
360
|
+
return 0.5 * ib if z < 0 else 1 - 0.5 * ib
|
|
361
|
+
|
|
362
|
+
@property
|
|
363
|
+
def name(self) -> str:
|
|
364
|
+
return "Student's t"
|
|
365
|
+
|
|
366
|
+
@property
|
|
367
|
+
def param_string(self) -> str:
|
|
368
|
+
return f"df = {self.df:.3g}"
|
|
369
|
+
|
|
370
|
+
@property
|
|
371
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
372
|
+
return (-5.0 * self.sigma + self.mu, 5.0 * self.sigma + self.mu)
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def mean(self) -> Optional[float]:
|
|
376
|
+
return self.mu if self.df > 1 else None
|
|
377
|
+
|
|
378
|
+
@property
|
|
379
|
+
def variance(self) -> Optional[float]:
|
|
380
|
+
if self.df > 2:
|
|
381
|
+
return self.sigma**2 * self.df / (self.df - 2)
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
# ---------------------------------------------------------------------------
|
|
386
|
+
# Chi-squared
|
|
387
|
+
# ---------------------------------------------------------------------------
|
|
388
|
+
|
|
389
|
+
class ChiSquaredDist(PDFDistribution):
|
|
390
|
+
"""Chi-squared distribution χ²(df).
|
|
391
|
+
|
|
392
|
+
Parameters
|
|
393
|
+
----------
|
|
394
|
+
df : int or float
|
|
395
|
+
Degrees of freedom (> 0).
|
|
396
|
+
"""
|
|
397
|
+
|
|
398
|
+
def __init__(self, df: float = 5.0):
|
|
399
|
+
if df <= 0:
|
|
400
|
+
raise ValueError("df must be positive")
|
|
401
|
+
self.df = float(df)
|
|
402
|
+
self._k2 = df / 2
|
|
403
|
+
self._log_norm = self._k2 * np.log(2) + _lgamma(self._k2)
|
|
404
|
+
|
|
405
|
+
def pdf(self, x):
|
|
406
|
+
x = np.asarray(x, dtype=float)
|
|
407
|
+
out = np.where(
|
|
408
|
+
x > 0,
|
|
409
|
+
np.exp((self._k2 - 1) * np.log(np.where(x > 0, x, 1))
|
|
410
|
+
- x / 2 - self._log_norm),
|
|
411
|
+
0.0,
|
|
412
|
+
)
|
|
413
|
+
return out
|
|
414
|
+
|
|
415
|
+
def cdf(self, x):
|
|
416
|
+
x = float(x)
|
|
417
|
+
if x <= 0:
|
|
418
|
+
return 0.0
|
|
419
|
+
return _reg_lower_gamma(self._k2, x / 2)
|
|
420
|
+
|
|
421
|
+
@property
|
|
422
|
+
def name(self) -> str:
|
|
423
|
+
return "Chi-squared"
|
|
424
|
+
|
|
425
|
+
@property
|
|
426
|
+
def param_string(self) -> str:
|
|
427
|
+
return f"df = {self.df:.3g}"
|
|
428
|
+
|
|
429
|
+
@property
|
|
430
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
431
|
+
hi = max(self.df + 5 * np.sqrt(2 * self.df), 3.0)
|
|
432
|
+
return (0.0, hi)
|
|
433
|
+
|
|
434
|
+
@property
|
|
435
|
+
def mean(self) -> float:
|
|
436
|
+
return self.df
|
|
437
|
+
|
|
438
|
+
@property
|
|
439
|
+
def variance(self) -> float:
|
|
440
|
+
return 2 * self.df
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
# ---------------------------------------------------------------------------
|
|
444
|
+
# Gamma
|
|
445
|
+
# ---------------------------------------------------------------------------
|
|
446
|
+
|
|
447
|
+
class GammaDist(PDFDistribution):
|
|
448
|
+
"""Gamma distribution Gamma(shape=k, rate=λ). Mean = k/λ.
|
|
449
|
+
|
|
450
|
+
Parameters
|
|
451
|
+
----------
|
|
452
|
+
shape : float
|
|
453
|
+
Shape parameter k (> 0).
|
|
454
|
+
rate : float
|
|
455
|
+
Rate parameter λ (> 0). Scale = 1/rate.
|
|
456
|
+
"""
|
|
457
|
+
|
|
458
|
+
def __init__(self, shape: float = 2.0, rate: float = 1.0):
|
|
459
|
+
self.k = float(shape)
|
|
460
|
+
self.lam = float(rate)
|
|
461
|
+
self._log_norm = _lgamma(self.k) - self.k * np.log(self.lam)
|
|
462
|
+
|
|
463
|
+
def pdf(self, x):
|
|
464
|
+
x = np.asarray(x, dtype=float)
|
|
465
|
+
out = np.where(
|
|
466
|
+
x > 0,
|
|
467
|
+
np.exp((self.k - 1) * np.log(np.where(x > 0, x, 1))
|
|
468
|
+
- self.lam * x - self._log_norm),
|
|
469
|
+
0.0,
|
|
470
|
+
)
|
|
471
|
+
return out
|
|
472
|
+
|
|
473
|
+
def cdf(self, x):
|
|
474
|
+
x = float(x)
|
|
475
|
+
if x <= 0:
|
|
476
|
+
return 0.0
|
|
477
|
+
return _reg_lower_gamma(self.k, self.lam * x)
|
|
478
|
+
|
|
479
|
+
@property
|
|
480
|
+
def name(self) -> str:
|
|
481
|
+
return "Gamma"
|
|
482
|
+
|
|
483
|
+
@property
|
|
484
|
+
def param_string(self) -> str:
|
|
485
|
+
return f"k = {self.k:.3g}, λ = {self.lam:.3g}"
|
|
486
|
+
|
|
487
|
+
@property
|
|
488
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
489
|
+
mu = self.k / self.lam
|
|
490
|
+
sig = np.sqrt(self.k) / self.lam
|
|
491
|
+
return (0.0, mu + 5 * sig)
|
|
492
|
+
|
|
493
|
+
@property
|
|
494
|
+
def mean(self) -> float:
|
|
495
|
+
return self.k / self.lam
|
|
496
|
+
|
|
497
|
+
@property
|
|
498
|
+
def variance(self) -> float:
|
|
499
|
+
return self.k / self.lam**2
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
# ---------------------------------------------------------------------------
|
|
503
|
+
# Beta
|
|
504
|
+
# ---------------------------------------------------------------------------
|
|
505
|
+
|
|
506
|
+
class BetaDist(PDFDistribution):
|
|
507
|
+
"""Beta distribution Beta(α, β). Support [0, 1].
|
|
508
|
+
|
|
509
|
+
Parameters
|
|
510
|
+
----------
|
|
511
|
+
alpha, beta : float
|
|
512
|
+
Shape parameters (> 0).
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
def __init__(self, alpha: float = 2.0, beta: float = 3.0):
|
|
516
|
+
self.alpha = float(alpha)
|
|
517
|
+
self.beta = float(beta)
|
|
518
|
+
self._log_norm = _lgamma(alpha) + _lgamma(beta) - _lgamma(alpha + beta)
|
|
519
|
+
|
|
520
|
+
def pdf(self, x):
|
|
521
|
+
x = np.asarray(x, dtype=float)
|
|
522
|
+
a, b = self.alpha, self.beta
|
|
523
|
+
out = np.where(
|
|
524
|
+
(x > 0) & (x < 1),
|
|
525
|
+
np.exp(
|
|
526
|
+
(a - 1) * np.log(np.where(x > 0, x, 1e-300))
|
|
527
|
+
+ (b - 1) * np.log(np.where(x < 1, 1 - x, 1e-300))
|
|
528
|
+
- self._log_norm
|
|
529
|
+
),
|
|
530
|
+
0.0,
|
|
531
|
+
)
|
|
532
|
+
return out
|
|
533
|
+
|
|
534
|
+
def cdf(self, x):
|
|
535
|
+
x = float(x)
|
|
536
|
+
if x <= 0:
|
|
537
|
+
return 0.0
|
|
538
|
+
if x >= 1:
|
|
539
|
+
return 1.0
|
|
540
|
+
return _reg_inc_beta(self.alpha, self.beta, x)
|
|
541
|
+
|
|
542
|
+
@property
|
|
543
|
+
def name(self) -> str:
|
|
544
|
+
return "Beta"
|
|
545
|
+
|
|
546
|
+
@property
|
|
547
|
+
def param_string(self) -> str:
|
|
548
|
+
return f"α = {self.alpha:.3g}, β = {self.beta:.3g}"
|
|
549
|
+
|
|
550
|
+
@property
|
|
551
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
552
|
+
return (0.0, 1.0)
|
|
553
|
+
|
|
554
|
+
@property
|
|
555
|
+
def mean(self) -> float:
|
|
556
|
+
return self.alpha / (self.alpha + self.beta)
|
|
557
|
+
|
|
558
|
+
@property
|
|
559
|
+
def variance(self) -> float:
|
|
560
|
+
a, b = self.alpha, self.beta
|
|
561
|
+
return a * b / ((a + b)**2 * (a + b + 1))
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
# ---------------------------------------------------------------------------
|
|
565
|
+
# Exponential
|
|
566
|
+
# ---------------------------------------------------------------------------
|
|
567
|
+
|
|
568
|
+
class ExponentialDist(PDFDistribution):
|
|
569
|
+
"""Exponential distribution Exp(rate=λ). Mean = 1/λ.
|
|
570
|
+
|
|
571
|
+
Parameters
|
|
572
|
+
----------
|
|
573
|
+
rate : float
|
|
574
|
+
Rate parameter λ (> 0).
|
|
575
|
+
"""
|
|
576
|
+
|
|
577
|
+
def __init__(self, rate: float = 1.0):
|
|
578
|
+
self.lam = float(rate)
|
|
579
|
+
|
|
580
|
+
def pdf(self, x):
|
|
581
|
+
x = np.asarray(x, dtype=float)
|
|
582
|
+
return np.where(x >= 0, self.lam * np.exp(-self.lam * x), 0.0)
|
|
583
|
+
|
|
584
|
+
def cdf(self, x):
|
|
585
|
+
x = float(x)
|
|
586
|
+
return max(0.0, 1.0 - np.exp(-self.lam * x))
|
|
587
|
+
|
|
588
|
+
@property
|
|
589
|
+
def name(self) -> str:
|
|
590
|
+
return "Exponential"
|
|
591
|
+
|
|
592
|
+
@property
|
|
593
|
+
def param_string(self) -> str:
|
|
594
|
+
return f"λ = {self.lam:.3g}"
|
|
595
|
+
|
|
596
|
+
@property
|
|
597
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
598
|
+
return (0.0, 5.0 / self.lam)
|
|
599
|
+
|
|
600
|
+
@property
|
|
601
|
+
def mean(self) -> float:
|
|
602
|
+
return 1.0 / self.lam
|
|
603
|
+
|
|
604
|
+
@property
|
|
605
|
+
def variance(self) -> float:
|
|
606
|
+
return 1.0 / self.lam**2
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
# ---------------------------------------------------------------------------
|
|
610
|
+
# Cauchy
|
|
611
|
+
# ---------------------------------------------------------------------------
|
|
612
|
+
|
|
613
|
+
class CauchyDist(PDFDistribution):
|
|
614
|
+
"""Cauchy distribution Cauchy(x₀, γ). Heavy-tailed.
|
|
615
|
+
|
|
616
|
+
Parameters
|
|
617
|
+
----------
|
|
618
|
+
x0 : float
|
|
619
|
+
Location parameter.
|
|
620
|
+
gamma : float
|
|
621
|
+
Scale parameter (half-width at half-maximum).
|
|
622
|
+
"""
|
|
623
|
+
|
|
624
|
+
def __init__(self, x0: float = 0.0, gamma: float = 1.0):
|
|
625
|
+
self.x0 = float(x0)
|
|
626
|
+
self.gamma = float(gamma)
|
|
627
|
+
|
|
628
|
+
def pdf(self, x):
|
|
629
|
+
x = np.asarray(x, dtype=float)
|
|
630
|
+
return 1.0 / (PI * self.gamma * (1 + ((x - self.x0) / self.gamma)**2))
|
|
631
|
+
|
|
632
|
+
def cdf(self, x):
|
|
633
|
+
return 0.5 + np.arctan((float(x) - self.x0) / self.gamma) / PI
|
|
634
|
+
|
|
635
|
+
@property
|
|
636
|
+
def name(self) -> str:
|
|
637
|
+
return "Cauchy"
|
|
638
|
+
|
|
639
|
+
@property
|
|
640
|
+
def param_string(self) -> str:
|
|
641
|
+
return f"x₀ = {self.x0:.3g}, γ = {self.gamma:.3g}"
|
|
642
|
+
|
|
643
|
+
@property
|
|
644
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
645
|
+
return (self.x0 - 6 * self.gamma, self.x0 + 6 * self.gamma)
|
|
646
|
+
|
|
647
|
+
@property
|
|
648
|
+
def mean(self) -> Optional[float]:
|
|
649
|
+
return None # undefined
|
|
650
|
+
|
|
651
|
+
@property
|
|
652
|
+
def variance(self) -> Optional[float]:
|
|
653
|
+
return None # undefined
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
# ---------------------------------------------------------------------------
|
|
657
|
+
# Laplace
|
|
658
|
+
# ---------------------------------------------------------------------------
|
|
659
|
+
|
|
660
|
+
class LaplaceDist(PDFDistribution):
|
|
661
|
+
"""Laplace (double-exponential) distribution Laplace(μ, b).
|
|
662
|
+
|
|
663
|
+
Parameters
|
|
664
|
+
----------
|
|
665
|
+
mu : float
|
|
666
|
+
Location (mean).
|
|
667
|
+
b : float
|
|
668
|
+
Scale (diversity); std = b√2.
|
|
669
|
+
"""
|
|
670
|
+
|
|
671
|
+
def __init__(self, mu: float = 0.0, b: float = 1.0):
|
|
672
|
+
self.mu = float(mu)
|
|
673
|
+
self.b = float(b)
|
|
674
|
+
|
|
675
|
+
def pdf(self, x):
|
|
676
|
+
x = np.asarray(x, dtype=float)
|
|
677
|
+
return np.exp(-np.abs(x - self.mu) / self.b) / (2 * self.b)
|
|
678
|
+
|
|
679
|
+
def cdf(self, x):
|
|
680
|
+
z = (float(x) - self.mu) / self.b
|
|
681
|
+
return 0.5 * (1 + np.sign(z) * (1 - np.exp(-abs(z))))
|
|
682
|
+
|
|
683
|
+
@property
|
|
684
|
+
def name(self) -> str:
|
|
685
|
+
return "Laplace"
|
|
686
|
+
|
|
687
|
+
@property
|
|
688
|
+
def param_string(self) -> str:
|
|
689
|
+
return f"μ = {self.mu:.3g}, b = {self.b:.3g}"
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
693
|
+
return (self.mu - 6 * self.b, self.mu + 6 * self.b)
|
|
694
|
+
|
|
695
|
+
@property
|
|
696
|
+
def mean(self) -> float:
|
|
697
|
+
return self.mu
|
|
698
|
+
|
|
699
|
+
@property
|
|
700
|
+
def variance(self) -> float:
|
|
701
|
+
return 2 * self.b**2
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
# ---------------------------------------------------------------------------
|
|
705
|
+
# LogNormal
|
|
706
|
+
# ---------------------------------------------------------------------------
|
|
707
|
+
|
|
708
|
+
class LogNormalDist(PDFDistribution):
|
|
709
|
+
"""Log-normal distribution LN(μ_log, σ_log).
|
|
710
|
+
|
|
711
|
+
X = exp(Y) where Y ~ N(μ_log, σ_log).
|
|
712
|
+
|
|
713
|
+
Parameters
|
|
714
|
+
----------
|
|
715
|
+
mu_log : float
|
|
716
|
+
Mean of the underlying normal (log-space).
|
|
717
|
+
sigma_log : float
|
|
718
|
+
Std of the underlying normal (log-space).
|
|
719
|
+
"""
|
|
720
|
+
|
|
721
|
+
def __init__(self, mu_log: float = 0.0, sigma_log: float = 0.5):
|
|
722
|
+
self.mu_log = float(mu_log)
|
|
723
|
+
self.sigma_log = float(sigma_log)
|
|
724
|
+
|
|
725
|
+
def pdf(self, x):
|
|
726
|
+
x = np.asarray(x, dtype=float)
|
|
727
|
+
out = np.where(
|
|
728
|
+
x > 0,
|
|
729
|
+
np.exp(-0.5 * ((np.log(np.where(x > 0, x, 1)) - self.mu_log)
|
|
730
|
+
/ self.sigma_log)**2)
|
|
731
|
+
/ (np.where(x > 0, x, 1) * self.sigma_log * np.sqrt(TAU)),
|
|
732
|
+
0.0,
|
|
733
|
+
)
|
|
734
|
+
return out
|
|
735
|
+
|
|
736
|
+
def cdf(self, x):
|
|
737
|
+
x = float(x)
|
|
738
|
+
if x <= 0:
|
|
739
|
+
return 0.0
|
|
740
|
+
z = (np.log(x) - self.mu_log) / (self.sigma_log * np.sqrt(2))
|
|
741
|
+
return 0.5 * (1 + _erf(z))
|
|
742
|
+
|
|
743
|
+
@property
|
|
744
|
+
def name(self) -> str:
|
|
745
|
+
return "Log-Normal"
|
|
746
|
+
|
|
747
|
+
@property
|
|
748
|
+
def param_string(self) -> str:
|
|
749
|
+
return f"μ_log = {self.mu_log:.3g}, σ_log = {self.sigma_log:.3g}"
|
|
750
|
+
|
|
751
|
+
@property
|
|
752
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
753
|
+
hi = np.exp(self.mu_log + 4 * self.sigma_log)
|
|
754
|
+
return (0.0, hi)
|
|
755
|
+
|
|
756
|
+
@property
|
|
757
|
+
def mean(self) -> float:
|
|
758
|
+
return np.exp(self.mu_log + 0.5 * self.sigma_log**2)
|
|
759
|
+
|
|
760
|
+
@property
|
|
761
|
+
def variance(self) -> float:
|
|
762
|
+
return (np.exp(self.sigma_log**2) - 1) * np.exp(2*self.mu_log + self.sigma_log**2)
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
# ---------------------------------------------------------------------------
|
|
766
|
+
# Weibull
|
|
767
|
+
# ---------------------------------------------------------------------------
|
|
768
|
+
|
|
769
|
+
class WeibullDist(PDFDistribution):
|
|
770
|
+
"""Weibull distribution Weibull(shape=k, scale=λ).
|
|
771
|
+
|
|
772
|
+
Parameters
|
|
773
|
+
----------
|
|
774
|
+
shape : float
|
|
775
|
+
Shape parameter k (> 0). k < 1 = decreasing; k = 1 = Exp.
|
|
776
|
+
scale : float
|
|
777
|
+
Scale parameter λ (> 0). Characteristic life.
|
|
778
|
+
"""
|
|
779
|
+
|
|
780
|
+
def __init__(self, shape: float = 2.0, scale: float = 1.0):
|
|
781
|
+
self.k = float(shape)
|
|
782
|
+
self.lam = float(scale)
|
|
783
|
+
|
|
784
|
+
def pdf(self, x):
|
|
785
|
+
x = np.asarray(x, dtype=float)
|
|
786
|
+
k, lam = self.k, self.lam
|
|
787
|
+
return np.where(
|
|
788
|
+
x >= 0,
|
|
789
|
+
(k / lam) * (x / lam) ** (k - 1) * np.exp(-(x / lam) ** k),
|
|
790
|
+
0.0,
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
def cdf(self, x):
|
|
794
|
+
x = float(x)
|
|
795
|
+
if x < 0:
|
|
796
|
+
return 0.0
|
|
797
|
+
return 1.0 - np.exp(-(x / self.lam)**self.k)
|
|
798
|
+
|
|
799
|
+
@property
|
|
800
|
+
def name(self) -> str:
|
|
801
|
+
return "Weibull"
|
|
802
|
+
|
|
803
|
+
@property
|
|
804
|
+
def param_string(self) -> str:
|
|
805
|
+
return f"k = {self.k:.3g}, λ = {self.lam:.3g}"
|
|
806
|
+
|
|
807
|
+
@property
|
|
808
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
809
|
+
hi = self.lam * (-np.log(0.001)) ** (1 / self.k)
|
|
810
|
+
return (0.0, hi)
|
|
811
|
+
|
|
812
|
+
@property
|
|
813
|
+
def mean(self) -> float:
|
|
814
|
+
return self.lam * np.exp(_lgamma(1 + 1 / self.k))
|
|
815
|
+
|
|
816
|
+
@property
|
|
817
|
+
def variance(self) -> float:
|
|
818
|
+
g1 = np.exp(_lgamma(1 + 1 / self.k))
|
|
819
|
+
g2 = np.exp(_lgamma(1 + 2 / self.k))
|
|
820
|
+
return self.lam**2 * (g2 - g1**2)
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
# ---------------------------------------------------------------------------
|
|
824
|
+
# Uniform (continuous)
|
|
825
|
+
# ---------------------------------------------------------------------------
|
|
826
|
+
|
|
827
|
+
class UniformDist(PDFDistribution):
|
|
828
|
+
"""Continuous Uniform distribution U(a, b).
|
|
829
|
+
|
|
830
|
+
Parameters
|
|
831
|
+
----------
|
|
832
|
+
a, b : float
|
|
833
|
+
Support endpoints.
|
|
834
|
+
"""
|
|
835
|
+
|
|
836
|
+
def __init__(self, a: float = 0.0, b: float = 1.0):
|
|
837
|
+
if b <= a:
|
|
838
|
+
raise ValueError("b must be > a")
|
|
839
|
+
self.a = float(a)
|
|
840
|
+
self.b = float(b)
|
|
841
|
+
self._height = 1.0 / (b - a)
|
|
842
|
+
|
|
843
|
+
def pdf(self, x):
|
|
844
|
+
x = np.asarray(x, dtype=float)
|
|
845
|
+
return np.where((x >= self.a) & (x <= self.b), self._height, 0.0)
|
|
846
|
+
|
|
847
|
+
def cdf(self, x):
|
|
848
|
+
x = float(x)
|
|
849
|
+
if x < self.a:
|
|
850
|
+
return 0.0
|
|
851
|
+
if x > self.b:
|
|
852
|
+
return 1.0
|
|
853
|
+
return (x - self.a) / (self.b - self.a)
|
|
854
|
+
|
|
855
|
+
@property
|
|
856
|
+
def name(self) -> str:
|
|
857
|
+
return "Uniform"
|
|
858
|
+
|
|
859
|
+
@property
|
|
860
|
+
def param_string(self) -> str:
|
|
861
|
+
return f"a = {self.a:.3g}, b = {self.b:.3g}"
|
|
862
|
+
|
|
863
|
+
@property
|
|
864
|
+
def default_x_range(self) -> Tuple[float, float]:
|
|
865
|
+
pad = (self.b - self.a) * 0.15
|
|
866
|
+
return (self.a - pad, self.b + pad)
|
|
867
|
+
|
|
868
|
+
@property
|
|
869
|
+
def mean(self) -> float:
|
|
870
|
+
return (self.a + self.b) / 2
|
|
871
|
+
|
|
872
|
+
@property
|
|
873
|
+
def variance(self) -> float:
|
|
874
|
+
return (self.b - self.a)**2 / 12
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
# ---------------------------------------------------------------------------
|
|
878
|
+
# Special function implementations (no scipy)
|
|
879
|
+
# ---------------------------------------------------------------------------
|
|
880
|
+
|
|
881
|
+
def _erf(z: float) -> float:
|
|
882
|
+
"""Error function via Horner-form polynomial approximation (max err < 1.5e-7)."""
|
|
883
|
+
t = 1.0 / (1.0 + 0.3275911 * abs(z))
|
|
884
|
+
poly = t * (0.254829592 + t * (-0.284496736
|
|
885
|
+
+ t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))))
|
|
886
|
+
val = 1.0 - poly * np.exp(-z * z)
|
|
887
|
+
return val if z >= 0 else -val
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def _lgamma(x: float) -> float:
|
|
891
|
+
"""Natural log of the gamma function via Lanczos approximation."""
|
|
892
|
+
g = 7
|
|
893
|
+
c = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
|
|
894
|
+
771.32342877765313, -176.61502916214059, 12.507343278686905,
|
|
895
|
+
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]
|
|
896
|
+
if x < 0.5:
|
|
897
|
+
return np.log(PI / np.sin(PI * x)) - _lgamma(1 - x)
|
|
898
|
+
x -= 1
|
|
899
|
+
a = c[0]
|
|
900
|
+
t = x + g + 0.5
|
|
901
|
+
for i in range(1, g + 2):
|
|
902
|
+
a += c[i] / (x + i)
|
|
903
|
+
return 0.5 * np.log(TAU) + (x + 0.5) * np.log(t) - t + np.log(a)
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def _reg_lower_gamma(a: float, x: float, n_terms: int = 150) -> float:
|
|
907
|
+
"""Regularised lower incomplete gamma P(a, x) via series expansion."""
|
|
908
|
+
if x < 0:
|
|
909
|
+
return 0.0
|
|
910
|
+
if x == 0:
|
|
911
|
+
return 0.0
|
|
912
|
+
log_x = np.log(x)
|
|
913
|
+
term = np.exp(a * log_x - x - _lgamma(a)) / a
|
|
914
|
+
total = term
|
|
915
|
+
for k in range(1, n_terms):
|
|
916
|
+
term *= x / (a + k)
|
|
917
|
+
total += term
|
|
918
|
+
if abs(term) < 1e-14 * abs(total):
|
|
919
|
+
break
|
|
920
|
+
return min(1.0, max(0.0, total))
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def _reg_inc_beta(a: float, b: float, x: float, n_terms: int = 200) -> float:
|
|
924
|
+
"""Regularised incomplete beta I_x(a, b) via continued fraction (Lentz)."""
|
|
925
|
+
if x <= 0:
|
|
926
|
+
return 0.0
|
|
927
|
+
if x >= 1:
|
|
928
|
+
return 1.0
|
|
929
|
+
log_norm = _lgamma(a + b) - _lgamma(a) - _lgamma(b)
|
|
930
|
+
log_factor = log_norm + a * np.log(x) + b * np.log(1 - x)
|
|
931
|
+
|
|
932
|
+
# Use symmetry for faster convergence
|
|
933
|
+
if x > (a + 1) / (a + b + 2):
|
|
934
|
+
return 1.0 - _reg_inc_beta(b, a, 1.0 - x)
|
|
935
|
+
|
|
936
|
+
# Continued fraction via Lentz's method
|
|
937
|
+
def beta_cf(aa, bb, xx):
|
|
938
|
+
fpmin = 1e-300
|
|
939
|
+
qab = aa + bb
|
|
940
|
+
qap = aa + 1
|
|
941
|
+
qam = aa - 1
|
|
942
|
+
c = 1.0
|
|
943
|
+
d = 1.0 - qab * xx / qap
|
|
944
|
+
d = fpmin if abs(d) < fpmin else d
|
|
945
|
+
d = 1.0 / d
|
|
946
|
+
h = d
|
|
947
|
+
for m in range(1, n_terms + 1):
|
|
948
|
+
m2 = 2 * m
|
|
949
|
+
aa_m = m * (bb - m) * xx / ((qam + m2) * (aa + m2))
|
|
950
|
+
d = 1.0 + aa_m * d
|
|
951
|
+
c = 1.0 + aa_m / c
|
|
952
|
+
d = fpmin if abs(d) < fpmin else d
|
|
953
|
+
c = fpmin if abs(c) < fpmin else c
|
|
954
|
+
d = 1.0 / d
|
|
955
|
+
h *= d * c
|
|
956
|
+
aa_m = -(aa + m) * (qab + m) * xx / ((aa + m2) * (qap + m2))
|
|
957
|
+
d = 1.0 + aa_m * d
|
|
958
|
+
c = 1.0 + aa_m / c
|
|
959
|
+
d = fpmin if abs(d) < fpmin else d
|
|
960
|
+
c = fpmin if abs(c) < fpmin else c
|
|
961
|
+
d = 1.0 / d
|
|
962
|
+
delta = d * c
|
|
963
|
+
h *= delta
|
|
964
|
+
if abs(delta - 1.0) < 1e-14:
|
|
965
|
+
break
|
|
966
|
+
return h
|
|
967
|
+
|
|
968
|
+
cf = beta_cf(a, b, x)
|
|
969
|
+
return np.exp(log_factor) * cf / a
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
# ===========================================================================
|
|
973
|
+
# PDFConfig
|
|
974
|
+
# ===========================================================================
|
|
975
|
+
|
|
976
|
+
@dataclass
|
|
977
|
+
class PDFConfig:
|
|
978
|
+
"""Complete visual configuration for a single ``PDFVisualizer3D``.
|
|
979
|
+
|
|
980
|
+
Curve layers
|
|
981
|
+
~~~~~~~~~~~~
|
|
982
|
+
``curve_color`` : main stroke colour.
|
|
983
|
+
``curve_stroke_width`` : stroke width.
|
|
984
|
+
``curve_opacity`` : stroke opacity.
|
|
985
|
+
``glow_width`` : wider halo behind the stroke (0 = off).
|
|
986
|
+
``glow_opacity`` : opacity of glow halo.
|
|
987
|
+
``smooth_resolution`` : Catmull-Rom points per segment.
|
|
988
|
+
|
|
989
|
+
Fill layers
|
|
990
|
+
~~~~~~~~~~~
|
|
991
|
+
``fill_color`` : area fill colour (defaults to curve_color).
|
|
992
|
+
``fill_opacity`` : area fill opacity.
|
|
993
|
+
``fill_gradient`` : True = darker near floor, lighter near curve.
|
|
994
|
+
``n_gradient_strips`` : number of gradient strips.
|
|
995
|
+
``floor_z`` : z-coordinate of the density baseline.
|
|
996
|
+
|
|
997
|
+
Moment layer
|
|
998
|
+
~~~~~~~~~~~~
|
|
999
|
+
``show_mean_line`` : vertical line at μ.
|
|
1000
|
+
``show_sigma_brackets``: horizontal bracket ±1σ, ±2σ around μ.
|
|
1001
|
+
``mean_color`` : colour of mean line and annotation.
|
|
1002
|
+
``sigma_color`` : colour of σ bracket.
|
|
1003
|
+
``moment_stroke_width``: stroke width of moment markers.
|
|
1004
|
+
|
|
1005
|
+
Region layer
|
|
1006
|
+
~~~~~~~~~~~~
|
|
1007
|
+
``region_colors`` : cycle of colours for successive shade regions.
|
|
1008
|
+
``region_opacity`` : opacity of shaded regions.
|
|
1009
|
+
``region_label_font`` : font size for P(·) probability labels.
|
|
1010
|
+
``region_label_decimals`` : decimal places in P(·) labels.
|
|
1011
|
+
|
|
1012
|
+
Percentile layer
|
|
1013
|
+
~~~~~~~~~~~~~~~~
|
|
1014
|
+
``percentile_color`` : colour of percentile marker lines.
|
|
1015
|
+
``percentile_font`` : font size of percentile labels.
|
|
1016
|
+
|
|
1017
|
+
Annotation
|
|
1018
|
+
~~~~~~~~~~
|
|
1019
|
+
``show_title`` : show distribution name above the curve.
|
|
1020
|
+
``title_font`` : font size of title.
|
|
1021
|
+
``show_param_label`` : show parameter string beneath the title.
|
|
1022
|
+
``param_label_font`` : font size of parameter label.
|
|
1023
|
+
|
|
1024
|
+
Layout
|
|
1025
|
+
~~~~~~
|
|
1026
|
+
``x_pos`` : x offset of the entire visualiser in scene.
|
|
1027
|
+
``y_pos`` : y (depth) position.
|
|
1028
|
+
``z_scale`` : vertical (z) scale factor for the PDF.
|
|
1029
|
+
"""
|
|
1030
|
+
|
|
1031
|
+
curve_color: ManimColor = ManimColor("#4A90D9")
|
|
1032
|
+
curve_stroke_width: float = 3.0
|
|
1033
|
+
curve_opacity: float = 1.0
|
|
1034
|
+
glow_width: float = 9.0
|
|
1035
|
+
glow_opacity: float = 0.14
|
|
1036
|
+
smooth_resolution: int = 20
|
|
1037
|
+
|
|
1038
|
+
fill_color: Optional[ManimColor] = None # None → inherit curve_color
|
|
1039
|
+
fill_opacity: float = 0.26
|
|
1040
|
+
fill_gradient: bool = True
|
|
1041
|
+
n_gradient_strips: int = 12
|
|
1042
|
+
floor_z: float = 0.0
|
|
1043
|
+
|
|
1044
|
+
show_mean_line: bool = True
|
|
1045
|
+
show_sigma_brackets: bool = True
|
|
1046
|
+
mean_color: ManimColor = ManimColor("#E0AA40")
|
|
1047
|
+
sigma_color: ManimColor = ManimColor("#E0AA40")
|
|
1048
|
+
moment_stroke_width: float = 1.8
|
|
1049
|
+
|
|
1050
|
+
region_colors: List[ManimColor] = field(default_factory=lambda: [
|
|
1051
|
+
ManimColor("#E8593C"), # red — tails / rejection
|
|
1052
|
+
ManimColor("#2DAA6E"), # green — acceptance
|
|
1053
|
+
ManimColor("#9B59B6"), # purple — third region
|
|
1054
|
+
ManimColor("#1ABC9C"), # teal — fourth
|
|
1055
|
+
])
|
|
1056
|
+
region_opacity: float = 0.32
|
|
1057
|
+
region_label_font: int = 20
|
|
1058
|
+
region_label_decimals: int = 4
|
|
1059
|
+
|
|
1060
|
+
percentile_color: ManimColor = ManimColor("#9B59B6")
|
|
1061
|
+
percentile_font: int = 17
|
|
1062
|
+
|
|
1063
|
+
show_title: bool = True
|
|
1064
|
+
title_font: int = 22
|
|
1065
|
+
show_param_label: bool = True
|
|
1066
|
+
param_label_font: int = 18
|
|
1067
|
+
|
|
1068
|
+
x_pos: float = 0.0
|
|
1069
|
+
y_pos: float = 0.0
|
|
1070
|
+
z_scale: float = 3.5
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
# ── Presets ──────────────────────────────────────────────────────────────
|
|
1074
|
+
|
|
1075
|
+
MINIMAL_PDF = PDFConfig(
|
|
1076
|
+
glow_opacity=0.0,
|
|
1077
|
+
fill_gradient=False,
|
|
1078
|
+
fill_opacity=0.18,
|
|
1079
|
+
show_mean_line=False,
|
|
1080
|
+
show_sigma_brackets=False,
|
|
1081
|
+
show_title=False,
|
|
1082
|
+
show_param_label=False,
|
|
1083
|
+
)
|
|
1084
|
+
|
|
1085
|
+
TEACHING_PDF = PDFConfig(
|
|
1086
|
+
glow_opacity=0.16,
|
|
1087
|
+
fill_gradient=True,
|
|
1088
|
+
fill_opacity=0.28,
|
|
1089
|
+
show_mean_line=True,
|
|
1090
|
+
show_sigma_brackets=True,
|
|
1091
|
+
show_title=True,
|
|
1092
|
+
show_param_label=True,
|
|
1093
|
+
smooth_resolution=24,
|
|
1094
|
+
)
|
|
1095
|
+
|
|
1096
|
+
COMPARISON_PDF = PDFConfig(
|
|
1097
|
+
fill_opacity=0.14,
|
|
1098
|
+
fill_gradient=True,
|
|
1099
|
+
glow_opacity=0.10,
|
|
1100
|
+
show_mean_line=False,
|
|
1101
|
+
show_sigma_brackets=False,
|
|
1102
|
+
show_title=False,
|
|
1103
|
+
show_param_label=False,
|
|
1104
|
+
)
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
# ===========================================================================
|
|
1108
|
+
# PDFVisualizer3D
|
|
1109
|
+
# ===========================================================================
|
|
1110
|
+
|
|
1111
|
+
class PDFVisualizer3D(VGroup):
|
|
1112
|
+
"""Full-featured 3D PDF visualizer for a single distribution.
|
|
1113
|
+
|
|
1114
|
+
Visual layers (all public VGroup attributes):
|
|
1115
|
+
- ``curve_group`` : glow + stroke VMobject.
|
|
1116
|
+
- ``fill_group`` : gradient area fill strips.
|
|
1117
|
+
- ``moments_group`` : mean line + σ bracket annotations.
|
|
1118
|
+
- ``regions`` : all shaded probability regions + labels.
|
|
1119
|
+
- ``percentiles`` : all percentile marker lines + labels.
|
|
1120
|
+
- ``kde_group`` : empirical KDE curve (if added).
|
|
1121
|
+
- ``title_group`` : distribution name + parameter label.
|
|
1122
|
+
|
|
1123
|
+
Parameters
|
|
1124
|
+
----------
|
|
1125
|
+
distribution : PDFDistribution
|
|
1126
|
+
The distribution to visualize.
|
|
1127
|
+
x_range : (float, float, float) or None
|
|
1128
|
+
``(x_min, x_max, x_step)`` for curve sampling. If None, uses
|
|
1129
|
+
``distribution.default_x_range`` with a step of
|
|
1130
|
+
``(x_max - x_min) / 200``.
|
|
1131
|
+
config : PDFConfig
|
|
1132
|
+
scene : ThreeDScene or None
|
|
1133
|
+
"""
|
|
1134
|
+
|
|
1135
|
+
def __init__(
|
|
1136
|
+
self,
|
|
1137
|
+
distribution: PDFDistribution,
|
|
1138
|
+
x_range: Optional[Tuple[float, float, float]] = None,
|
|
1139
|
+
config: Optional[PDFConfig] = None,
|
|
1140
|
+
scene: Optional[ThreeDScene] = None,
|
|
1141
|
+
**kwargs,
|
|
1142
|
+
):
|
|
1143
|
+
super().__init__(**kwargs)
|
|
1144
|
+
|
|
1145
|
+
self.dist = distribution
|
|
1146
|
+
self.cfg = config if config is not None else PDFConfig()
|
|
1147
|
+
self._scene = scene
|
|
1148
|
+
|
|
1149
|
+
# Resolve x_range
|
|
1150
|
+
if x_range is not None:
|
|
1151
|
+
self._x_min, self._x_max, self._x_step = x_range
|
|
1152
|
+
else:
|
|
1153
|
+
lo, hi = distribution.default_x_range
|
|
1154
|
+
step = (hi - lo) / 200
|
|
1155
|
+
self._x_min, self._x_max, self._x_step = lo, hi, step
|
|
1156
|
+
|
|
1157
|
+
# Sample the PDF
|
|
1158
|
+
xs = np.arange(self._x_min, self._x_max + self._x_step * 0.5, self._x_step)
|
|
1159
|
+
ys_raw = np.array([max(float(distribution.pdf(x)), 0.0) for x in xs])
|
|
1160
|
+
y_max = ys_raw.max() if ys_raw.max() > 0 else 1.0
|
|
1161
|
+
# Scale so peak reaches z_scale
|
|
1162
|
+
self._y_max_raw = y_max
|
|
1163
|
+
ys = ys_raw / y_max * self.cfg.z_scale
|
|
1164
|
+
|
|
1165
|
+
self._xs = xs
|
|
1166
|
+
self._ys = ys
|
|
1167
|
+
self._ys_raw = ys_raw
|
|
1168
|
+
|
|
1169
|
+
# Convert to 3D scene coordinates
|
|
1170
|
+
cfg = self.cfg
|
|
1171
|
+
self._curve_pts: np.ndarray = np.column_stack([
|
|
1172
|
+
xs + cfg.x_pos,
|
|
1173
|
+
np.full(len(xs), cfg.y_pos),
|
|
1174
|
+
ys,
|
|
1175
|
+
])
|
|
1176
|
+
self._smoothed_pts: np.ndarray = _catmull_rom(
|
|
1177
|
+
self._curve_pts, resolution=cfg.smooth_resolution
|
|
1178
|
+
)
|
|
1179
|
+
|
|
1180
|
+
# Public VGroup layers
|
|
1181
|
+
self.curve_group = VGroup()
|
|
1182
|
+
self.fill_group = VGroup()
|
|
1183
|
+
self.moments_group = VGroup()
|
|
1184
|
+
self.regions = VGroup()
|
|
1185
|
+
self.percentiles = VGroup()
|
|
1186
|
+
self.kde_group = VGroup()
|
|
1187
|
+
self.title_group = VGroup()
|
|
1188
|
+
|
|
1189
|
+
# Internal state
|
|
1190
|
+
self._region_count: int = 0
|
|
1191
|
+
self._percentile_count: int = 0
|
|
1192
|
+
|
|
1193
|
+
# Build all layers
|
|
1194
|
+
self._build_curve()
|
|
1195
|
+
self._build_fill()
|
|
1196
|
+
if cfg.show_mean_line or cfg.show_sigma_brackets:
|
|
1197
|
+
self._build_moments(scene)
|
|
1198
|
+
if cfg.show_title:
|
|
1199
|
+
self._build_title(scene)
|
|
1200
|
+
|
|
1201
|
+
self.add(
|
|
1202
|
+
self.fill_group, self.curve_group,
|
|
1203
|
+
self.moments_group, self.regions,
|
|
1204
|
+
self.percentiles, self.kde_group, self.title_group,
|
|
1205
|
+
)
|
|
1206
|
+
|
|
1207
|
+
# ------------------------------------------------------------------
|
|
1208
|
+
# Internal builders
|
|
1209
|
+
# ------------------------------------------------------------------
|
|
1210
|
+
|
|
1211
|
+
def _build_curve(self) -> None:
|
|
1212
|
+
cfg = self.cfg
|
|
1213
|
+
col = _with_opacity(cfg.curve_color, cfg.curve_opacity)
|
|
1214
|
+
|
|
1215
|
+
stroke = VMobject()
|
|
1216
|
+
stroke.set_points_as_corners(self._smoothed_pts)
|
|
1217
|
+
stroke.set_stroke(color=col, width=cfg.curve_stroke_width)
|
|
1218
|
+
stroke.set_fill(opacity=0)
|
|
1219
|
+
self.stroke = stroke
|
|
1220
|
+
|
|
1221
|
+
if cfg.glow_width > 0 and cfg.glow_opacity > 0:
|
|
1222
|
+
glow = VMobject()
|
|
1223
|
+
glow.set_points_as_corners(self._smoothed_pts)
|
|
1224
|
+
glow.set_stroke(
|
|
1225
|
+
color=_with_opacity(cfg.curve_color, cfg.glow_opacity),
|
|
1226
|
+
width=cfg.glow_width,
|
|
1227
|
+
)
|
|
1228
|
+
glow.set_fill(opacity=0)
|
|
1229
|
+
self.glow = glow
|
|
1230
|
+
self.curve_group.add(glow)
|
|
1231
|
+
|
|
1232
|
+
self.curve_group.add(stroke)
|
|
1233
|
+
|
|
1234
|
+
def _build_fill(self) -> None:
|
|
1235
|
+
cfg = self.cfg
|
|
1236
|
+
fill_col = cfg.fill_color if cfg.fill_color is not None else cfg.curve_color
|
|
1237
|
+
fill_grp = _build_fill_polygon(
|
|
1238
|
+
self._smoothed_pts,
|
|
1239
|
+
floor_z=cfg.floor_z,
|
|
1240
|
+
y_pos=cfg.y_pos,
|
|
1241
|
+
n_gradient_strips=cfg.n_gradient_strips,
|
|
1242
|
+
color=fill_col,
|
|
1243
|
+
opacity=cfg.fill_opacity,
|
|
1244
|
+
gradient=cfg.fill_gradient,
|
|
1245
|
+
)
|
|
1246
|
+
self.fill_group.add(fill_grp)
|
|
1247
|
+
|
|
1248
|
+
def _build_moments(self, scene: Optional[ThreeDScene]) -> None:
|
|
1249
|
+
cfg = self.cfg
|
|
1250
|
+
mu = self.dist.mean
|
|
1251
|
+
sig = self.dist.std
|
|
1252
|
+
y = cfg.y_pos
|
|
1253
|
+
floor_z = cfg.floor_z
|
|
1254
|
+
|
|
1255
|
+
if mu is None:
|
|
1256
|
+
return
|
|
1257
|
+
|
|
1258
|
+
x_mu = mu + cfg.x_pos
|
|
1259
|
+
z_mu_pdf = float(self.dist.pdf(mu)) / self._y_max_raw * cfg.z_scale
|
|
1260
|
+
|
|
1261
|
+
# Mean line — dashed vertical from floor to PDF height
|
|
1262
|
+
mean_col = _with_opacity(cfg.mean_color, 0.85)
|
|
1263
|
+
mean_line = DashedLine(
|
|
1264
|
+
np.array([x_mu, y, floor_z]),
|
|
1265
|
+
np.array([x_mu, y, z_mu_pdf * 1.05]),
|
|
1266
|
+
dash_length=0.07, dashed_ratio=0.45,
|
|
1267
|
+
color=mean_col, stroke_width=cfg.moment_stroke_width,
|
|
1268
|
+
)
|
|
1269
|
+
mean_dot = Dot3D(
|
|
1270
|
+
point=np.array([x_mu, y, floor_z]),
|
|
1271
|
+
radius=0.06, color=mean_col,
|
|
1272
|
+
)
|
|
1273
|
+
|
|
1274
|
+
mu_lbl = Text(f"μ = {mu:.3g}", font_size=17, color=cfg.mean_color)
|
|
1275
|
+
mu_lbl.move_to(np.array([x_mu + 0.12, y, z_mu_pdf + 0.28]))
|
|
1276
|
+
if scene is not None:
|
|
1277
|
+
scene.add_fixed_orientation_mobjects(mu_lbl)
|
|
1278
|
+
|
|
1279
|
+
self.mean_line = mean_line
|
|
1280
|
+
self.mean_dot = mean_dot
|
|
1281
|
+
self.mean_label = VGroup(mu_lbl)
|
|
1282
|
+
self.moments_group.add(mean_line, mean_dot, mu_lbl)
|
|
1283
|
+
|
|
1284
|
+
# Sigma brackets (±1σ and ±2σ)
|
|
1285
|
+
if cfg.show_sigma_brackets and sig is not None:
|
|
1286
|
+
sig_col = _with_opacity(cfg.sigma_color, 0.70)
|
|
1287
|
+
for n_sig, label_text in [(1, "±1σ"), (2, "±2σ")]:
|
|
1288
|
+
lo_x = (mu - n_sig * sig) + cfg.x_pos
|
|
1289
|
+
hi_x = (mu + n_sig * sig) + cfg.x_pos
|
|
1290
|
+
z_bracket = floor_z - 0.12 * n_sig
|
|
1291
|
+
|
|
1292
|
+
bracket = VGroup(
|
|
1293
|
+
Line(np.array([lo_x, y, z_bracket]),
|
|
1294
|
+
np.array([hi_x, y, z_bracket]),
|
|
1295
|
+
color=sig_col,
|
|
1296
|
+
stroke_width=cfg.moment_stroke_width * 0.8),
|
|
1297
|
+
Line(np.array([lo_x, y, z_bracket]),
|
|
1298
|
+
np.array([lo_x, y, z_bracket + 0.08]),
|
|
1299
|
+
color=sig_col,
|
|
1300
|
+
stroke_width=cfg.moment_stroke_width * 0.8),
|
|
1301
|
+
Line(np.array([hi_x, y, z_bracket]),
|
|
1302
|
+
np.array([hi_x, y, z_bracket + 0.08]),
|
|
1303
|
+
color=sig_col,
|
|
1304
|
+
stroke_width=cfg.moment_stroke_width * 0.8),
|
|
1305
|
+
)
|
|
1306
|
+
lbl = Text(label_text, font_size=14, color=cfg.sigma_color)
|
|
1307
|
+
lbl.move_to(np.array([(lo_x + hi_x) / 2, y, z_bracket - 0.22]))
|
|
1308
|
+
if scene is not None:
|
|
1309
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1310
|
+
self.moments_group.add(bracket, lbl)
|
|
1311
|
+
|
|
1312
|
+
def _build_title(self, scene: Optional[ThreeDScene]) -> None:
|
|
1313
|
+
cfg = self.cfg
|
|
1314
|
+
x_cen = (self._x_min + self._x_max) / 2 + cfg.x_pos
|
|
1315
|
+
z_top = cfg.z_scale * 1.12
|
|
1316
|
+
|
|
1317
|
+
title_lbl = Text(
|
|
1318
|
+
self.dist.name,
|
|
1319
|
+
font_size=cfg.title_font,
|
|
1320
|
+
color=_with_opacity(cfg.curve_color, 0.88),
|
|
1321
|
+
)
|
|
1322
|
+
title_lbl.move_to(np.array([x_cen, cfg.y_pos, z_top]))
|
|
1323
|
+
self.title_group.add(title_lbl)
|
|
1324
|
+
|
|
1325
|
+
if cfg.show_param_label:
|
|
1326
|
+
param_lbl = Text(
|
|
1327
|
+
self.dist.param_string,
|
|
1328
|
+
font_size=cfg.param_label_font,
|
|
1329
|
+
color=_with_opacity(cfg.curve_color, 0.60),
|
|
1330
|
+
)
|
|
1331
|
+
param_lbl.move_to(np.array([x_cen, cfg.y_pos, z_top - 0.38]))
|
|
1332
|
+
self.title_group.add(param_lbl)
|
|
1333
|
+
|
|
1334
|
+
for mob in self.title_group:
|
|
1335
|
+
if scene is not None:
|
|
1336
|
+
scene.add_fixed_orientation_mobjects(mob)
|
|
1337
|
+
|
|
1338
|
+
# ------------------------------------------------------------------
|
|
1339
|
+
# Public layer API
|
|
1340
|
+
# ------------------------------------------------------------------
|
|
1341
|
+
|
|
1342
|
+
def shade_region(
|
|
1343
|
+
self,
|
|
1344
|
+
x_lo: float,
|
|
1345
|
+
x_hi: float,
|
|
1346
|
+
color: Optional[ManimColor] = None,
|
|
1347
|
+
label: bool = True,
|
|
1348
|
+
label_fmt: str = "P = {p:.{d}f}",
|
|
1349
|
+
scene: Optional[ThreeDScene] = None,
|
|
1350
|
+
) -> VGroup:
|
|
1351
|
+
"""Shade the PDF region between *x_lo* and *x_hi*.
|
|
1352
|
+
|
|
1353
|
+
Computes P(x_lo ≤ X ≤ x_hi) by numerical integration and adds
|
|
1354
|
+
an optional probability label above the shaded region.
|
|
1355
|
+
|
|
1356
|
+
Parameters
|
|
1357
|
+
----------
|
|
1358
|
+
x_lo, x_hi : float
|
|
1359
|
+
Region boundaries in data coordinates.
|
|
1360
|
+
color : ManimColor or None
|
|
1361
|
+
Uses next colour from ``cfg.region_colors`` if None.
|
|
1362
|
+
label : bool
|
|
1363
|
+
Whether to add a probability annotation.
|
|
1364
|
+
label_fmt : str
|
|
1365
|
+
Format string with ``{p}`` (probability) and ``{d}`` (decimals).
|
|
1366
|
+
scene : ThreeDScene or None
|
|
1367
|
+
|
|
1368
|
+
Returns
|
|
1369
|
+
-------
|
|
1370
|
+
VGroup — the region fill + label (added to ``self.regions``).
|
|
1371
|
+
"""
|
|
1372
|
+
cfg = self.cfg
|
|
1373
|
+
col = (color if color is not None
|
|
1374
|
+
else cfg.region_colors[self._region_count % len(cfg.region_colors)])
|
|
1375
|
+
self._region_count += 1
|
|
1376
|
+
|
|
1377
|
+
# Clip to visible x range
|
|
1378
|
+
lo = max(x_lo, self._x_min)
|
|
1379
|
+
hi = min(x_hi, self._x_max)
|
|
1380
|
+
|
|
1381
|
+
# Find curve points within [lo, hi]
|
|
1382
|
+
mask = (self._xs >= lo) & (self._xs <= hi)
|
|
1383
|
+
xs_r = self._xs[mask] + cfg.x_pos
|
|
1384
|
+
ys_r = self._ys[mask]
|
|
1385
|
+
|
|
1386
|
+
# Add boundary interpolations
|
|
1387
|
+
y_lo = float(self.dist.pdf(lo)) / self._y_max_raw * cfg.z_scale
|
|
1388
|
+
y_hi = float(self.dist.pdf(hi)) / self._y_max_raw * cfg.z_scale
|
|
1389
|
+
xs_full = np.concatenate([[lo + cfg.x_pos], xs_r, [hi + cfg.x_pos]])
|
|
1390
|
+
ys_full = np.concatenate([[y_lo], ys_r, [y_hi]])
|
|
1391
|
+
|
|
1392
|
+
region_curve_pts = np.column_stack([
|
|
1393
|
+
xs_full, np.full(len(xs_full), cfg.y_pos), ys_full
|
|
1394
|
+
])
|
|
1395
|
+
|
|
1396
|
+
fill = _build_fill_polygon(
|
|
1397
|
+
region_curve_pts,
|
|
1398
|
+
floor_z=cfg.floor_z,
|
|
1399
|
+
y_pos=cfg.y_pos,
|
|
1400
|
+
n_gradient_strips=1,
|
|
1401
|
+
color=col,
|
|
1402
|
+
opacity=cfg.region_opacity,
|
|
1403
|
+
gradient=False,
|
|
1404
|
+
)
|
|
1405
|
+
|
|
1406
|
+
grp = VGroup(fill)
|
|
1407
|
+
|
|
1408
|
+
# Probability label
|
|
1409
|
+
if label:
|
|
1410
|
+
p = self.dist.cdf(hi) - self.dist.cdf(lo)
|
|
1411
|
+
lbl_text = label_fmt.format(p=p, d=cfg.region_label_decimals)
|
|
1412
|
+
lbl = Text(lbl_text, font_size=cfg.region_label_font, color=col)
|
|
1413
|
+
x_mid = (lo + hi) / 2 + cfg.x_pos
|
|
1414
|
+
z_mid = float(self.dist.pdf((lo + hi) / 2)) / self._y_max_raw * cfg.z_scale
|
|
1415
|
+
lbl.move_to(np.array([x_mid, cfg.y_pos, z_mid + 0.38]))
|
|
1416
|
+
grp.add(lbl)
|
|
1417
|
+
if scene is not None:
|
|
1418
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1419
|
+
|
|
1420
|
+
self.regions.add(grp)
|
|
1421
|
+
return grp
|
|
1422
|
+
|
|
1423
|
+
def shade_tail_left(
|
|
1424
|
+
self,
|
|
1425
|
+
x_crit: float,
|
|
1426
|
+
label: bool = True,
|
|
1427
|
+
color: Optional[ManimColor] = None,
|
|
1428
|
+
scene: Optional[ThreeDScene] = None,
|
|
1429
|
+
) -> VGroup:
|
|
1430
|
+
"""Shade P(X ≤ x_crit) — the left tail."""
|
|
1431
|
+
return self.shade_region(
|
|
1432
|
+
self._x_min, x_crit,
|
|
1433
|
+
color=color, label=label, scene=scene,
|
|
1434
|
+
)
|
|
1435
|
+
|
|
1436
|
+
def shade_tail_right(
|
|
1437
|
+
self,
|
|
1438
|
+
x_crit: float,
|
|
1439
|
+
label: bool = True,
|
|
1440
|
+
color: Optional[ManimColor] = None,
|
|
1441
|
+
scene: Optional[ThreeDScene] = None,
|
|
1442
|
+
) -> VGroup:
|
|
1443
|
+
"""Shade P(X ≥ x_crit) — the right tail."""
|
|
1444
|
+
return self.shade_region(
|
|
1445
|
+
x_crit, self._x_max,
|
|
1446
|
+
color=color, label=label, scene=scene,
|
|
1447
|
+
)
|
|
1448
|
+
|
|
1449
|
+
def shade_two_tails(
|
|
1450
|
+
self,
|
|
1451
|
+
alpha: float = 0.05,
|
|
1452
|
+
label: bool = True,
|
|
1453
|
+
color: Optional[ManimColor] = None,
|
|
1454
|
+
scene: Optional[ThreeDScene] = None,
|
|
1455
|
+
) -> VGroup:
|
|
1456
|
+
"""Shade both tails for a two-sided test at level *alpha*.
|
|
1457
|
+
|
|
1458
|
+
Returns a VGroup containing both tail fills.
|
|
1459
|
+
"""
|
|
1460
|
+
x_lo = self.dist.ppf(alpha / 2)
|
|
1461
|
+
x_hi = self.dist.ppf(1 - alpha / 2)
|
|
1462
|
+
g_left = self.shade_tail_left(x_lo, label=label, color=color, scene=scene)
|
|
1463
|
+
g_right = self.shade_tail_right(x_hi, label=label, color=color, scene=scene)
|
|
1464
|
+
return VGroup(g_left, g_right)
|
|
1465
|
+
|
|
1466
|
+
def shade_between_sigmas(
|
|
1467
|
+
self,
|
|
1468
|
+
n_sigma: float = 1.0,
|
|
1469
|
+
label: bool = True,
|
|
1470
|
+
color: Optional[ManimColor] = None,
|
|
1471
|
+
scene: Optional[ThreeDScene] = None,
|
|
1472
|
+
) -> VGroup:
|
|
1473
|
+
"""Shade the region μ ± n_sigma·σ.
|
|
1474
|
+
|
|
1475
|
+
Useful for showing the 68–95–99.7 rule.
|
|
1476
|
+
"""
|
|
1477
|
+
mu = self.dist.mean
|
|
1478
|
+
sig = self.dist.std
|
|
1479
|
+
if mu is None or sig is None:
|
|
1480
|
+
return VGroup()
|
|
1481
|
+
return self.shade_region(
|
|
1482
|
+
mu - n_sigma * sig, mu + n_sigma * sig,
|
|
1483
|
+
color=color, label=label,
|
|
1484
|
+
label_fmt=f"P(μ ± {n_sigma:.0f}σ) = {{p:.{self.cfg.region_label_decimals}f}}",
|
|
1485
|
+
scene=scene,
|
|
1486
|
+
)
|
|
1487
|
+
|
|
1488
|
+
def add_percentile_marker(
|
|
1489
|
+
self,
|
|
1490
|
+
p: float,
|
|
1491
|
+
label: bool = True,
|
|
1492
|
+
color: Optional[ManimColor] = None,
|
|
1493
|
+
scene: Optional[ThreeDScene] = None,
|
|
1494
|
+
) -> VGroup:
|
|
1495
|
+
"""Add a vertical marker line at the *p*-th percentile.
|
|
1496
|
+
|
|
1497
|
+
Parameters
|
|
1498
|
+
----------
|
|
1499
|
+
p : float
|
|
1500
|
+
Probability in (0, 1).
|
|
1501
|
+
label : bool
|
|
1502
|
+
If True, show a "{100p}th percentile" label.
|
|
1503
|
+
|
|
1504
|
+
Returns
|
|
1505
|
+
-------
|
|
1506
|
+
VGroup — the marker line + label (added to ``self.percentiles``).
|
|
1507
|
+
"""
|
|
1508
|
+
cfg = self.cfg
|
|
1509
|
+
col = color if color is not None else cfg.percentile_color
|
|
1510
|
+
x_p = self.dist.ppf(p) + cfg.x_pos
|
|
1511
|
+
z_top = float(self.dist.pdf(x_p - cfg.x_pos)) / self._y_max_raw * cfg.z_scale
|
|
1512
|
+
|
|
1513
|
+
marker = DashedLine(
|
|
1514
|
+
np.array([x_p, cfg.y_pos, cfg.floor_z]),
|
|
1515
|
+
np.array([x_p, cfg.y_pos, z_top * 1.05]),
|
|
1516
|
+
dash_length=0.07, dashed_ratio=0.5,
|
|
1517
|
+
color=_with_opacity(col, 0.80),
|
|
1518
|
+
stroke_width=1.8,
|
|
1519
|
+
)
|
|
1520
|
+
dot = Dot3D(
|
|
1521
|
+
point=np.array([x_p, cfg.y_pos, cfg.floor_z]),
|
|
1522
|
+
radius=0.06, color=_with_opacity(col, 0.90),
|
|
1523
|
+
)
|
|
1524
|
+
grp = VGroup(marker, dot)
|
|
1525
|
+
|
|
1526
|
+
if label:
|
|
1527
|
+
pct = int(round(p * 100))
|
|
1528
|
+
suffix = {1: "st", 2: "nd", 3: "rd"}.get(pct % 10 if pct % 100 not in (11, 12, 13) else 0, "th")
|
|
1529
|
+
lbl = Text(
|
|
1530
|
+
f"{pct}{suffix}",
|
|
1531
|
+
font_size=cfg.percentile_font,
|
|
1532
|
+
color=col,
|
|
1533
|
+
)
|
|
1534
|
+
lbl.move_to(np.array([x_p, cfg.y_pos, -0.28]))
|
|
1535
|
+
grp.add(lbl)
|
|
1536
|
+
if scene is not None:
|
|
1537
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1538
|
+
|
|
1539
|
+
self.percentiles.add(grp)
|
|
1540
|
+
self._percentile_count += 1
|
|
1541
|
+
return grp
|
|
1542
|
+
|
|
1543
|
+
def add_percentile_markers(
|
|
1544
|
+
self,
|
|
1545
|
+
ps: List[float],
|
|
1546
|
+
scene: Optional[ThreeDScene] = None,
|
|
1547
|
+
) -> VGroup:
|
|
1548
|
+
"""Add multiple percentile markers at once.
|
|
1549
|
+
|
|
1550
|
+
Returns a VGroup of all added marker VGroups.
|
|
1551
|
+
"""
|
|
1552
|
+
all_grps = VGroup()
|
|
1553
|
+
for p in ps:
|
|
1554
|
+
all_grps.add(self.add_percentile_marker(p, scene=scene))
|
|
1555
|
+
return all_grps
|
|
1556
|
+
|
|
1557
|
+
def add_kde_overlay(
|
|
1558
|
+
self,
|
|
1559
|
+
data: np.ndarray,
|
|
1560
|
+
bandwidth: Optional[float] = None,
|
|
1561
|
+
color: Optional[ManimColor] = None,
|
|
1562
|
+
stroke_width: float = 2.2,
|
|
1563
|
+
scene: Optional[ThreeDScene] = None,
|
|
1564
|
+
) -> VMobject:
|
|
1565
|
+
"""Draw an empirical KDE curve over the theoretical PDF.
|
|
1566
|
+
|
|
1567
|
+
Uses Silverman's rule-of-thumb bandwidth if *bandwidth* is None.
|
|
1568
|
+
The KDE is scaled to match the theoretical PDF's peak height.
|
|
1569
|
+
|
|
1570
|
+
Parameters
|
|
1571
|
+
----------
|
|
1572
|
+
data : np.ndarray
|
|
1573
|
+
Observed data values.
|
|
1574
|
+
bandwidth : float or None
|
|
1575
|
+
color : ManimColor or None
|
|
1576
|
+
Defaults to a lighter version of the curve colour.
|
|
1577
|
+
|
|
1578
|
+
Returns
|
|
1579
|
+
-------
|
|
1580
|
+
VMobject — the KDE stroke (added to ``self.kde_group``).
|
|
1581
|
+
"""
|
|
1582
|
+
cfg = self.cfg
|
|
1583
|
+
n = len(data)
|
|
1584
|
+
std = float(np.std(data))
|
|
1585
|
+
bw = bandwidth if bandwidth is not None else max(1.06 * std * n**(-0.2), 1e-3)
|
|
1586
|
+
col = color if color is not None else _lighten(cfg.curve_color, 1.45)
|
|
1587
|
+
|
|
1588
|
+
xs = np.linspace(self._x_min, self._x_max, 300)
|
|
1589
|
+
zs = np.array([
|
|
1590
|
+
float(np.mean(
|
|
1591
|
+
np.exp(-0.5 * ((x - data) / bw)**2) / (bw * np.sqrt(TAU))
|
|
1592
|
+
))
|
|
1593
|
+
for x in xs
|
|
1594
|
+
])
|
|
1595
|
+
z_max_kde = zs.max() if zs.max() > 0 else 1.0
|
|
1596
|
+
zs_scaled = zs / z_max_kde * cfg.z_scale
|
|
1597
|
+
|
|
1598
|
+
pts = np.column_stack([xs + cfg.x_pos, np.full(len(xs), cfg.y_pos), zs_scaled])
|
|
1599
|
+
smoothed = _catmull_rom(pts, resolution=12)
|
|
1600
|
+
|
|
1601
|
+
kde_stroke = VMobject()
|
|
1602
|
+
kde_stroke.set_points_as_corners(smoothed)
|
|
1603
|
+
kde_stroke.set_stroke(color=_with_opacity(col, 0.80), width=stroke_width)
|
|
1604
|
+
kde_stroke.set_fill(opacity=0)
|
|
1605
|
+
|
|
1606
|
+
# KDE glow
|
|
1607
|
+
kde_glow = VMobject()
|
|
1608
|
+
kde_glow.set_points_as_corners(smoothed)
|
|
1609
|
+
kde_glow.set_stroke(color=_with_opacity(col, 0.12), width=stroke_width * 2.5)
|
|
1610
|
+
kde_glow.set_fill(opacity=0)
|
|
1611
|
+
|
|
1612
|
+
self.kde_group.add(kde_glow, kde_stroke)
|
|
1613
|
+
return kde_stroke
|
|
1614
|
+
|
|
1615
|
+
def add_critical_value(
|
|
1616
|
+
self,
|
|
1617
|
+
x_crit: float,
|
|
1618
|
+
label: str = "",
|
|
1619
|
+
color: ManimColor = ManimColor("#E8593C"),
|
|
1620
|
+
scene: Optional[ThreeDScene] = None,
|
|
1621
|
+
) -> VGroup:
|
|
1622
|
+
"""Add a critical-value annotation line at *x_crit*.
|
|
1623
|
+
|
|
1624
|
+
Combines a dashed vertical line from the floor to above the curve
|
|
1625
|
+
with an optional text label. Returns the VGroup for animation.
|
|
1626
|
+
"""
|
|
1627
|
+
cfg = self.cfg
|
|
1628
|
+
sc = x_crit + cfg.x_pos
|
|
1629
|
+
z_pdf = float(self.dist.pdf(x_crit)) / self._y_max_raw * cfg.z_scale
|
|
1630
|
+
col = _with_opacity(color, 0.82)
|
|
1631
|
+
|
|
1632
|
+
ln = DashedLine(
|
|
1633
|
+
np.array([sc, cfg.y_pos, cfg.floor_z]),
|
|
1634
|
+
np.array([sc, cfg.y_pos, cfg.z_scale * 1.08]),
|
|
1635
|
+
dash_length=0.08, dashed_ratio=0.45,
|
|
1636
|
+
color=col, stroke_width=2.0,
|
|
1637
|
+
)
|
|
1638
|
+
dot = Dot3D(
|
|
1639
|
+
point=np.array([sc, cfg.y_pos, z_pdf]),
|
|
1640
|
+
radius=0.08, color=color,
|
|
1641
|
+
)
|
|
1642
|
+
grp = VGroup(ln, dot)
|
|
1643
|
+
|
|
1644
|
+
if label:
|
|
1645
|
+
lbl = Text(label, font_size=19, color=color)
|
|
1646
|
+
lbl.move_to(np.array([sc, cfg.y_pos, cfg.z_scale * 1.18]))
|
|
1647
|
+
grp.add(lbl)
|
|
1648
|
+
if scene is not None:
|
|
1649
|
+
scene.add_fixed_orientation_mobjects(lbl)
|
|
1650
|
+
|
|
1651
|
+
self.add(grp)
|
|
1652
|
+
return grp
|
|
1653
|
+
|
|
1654
|
+
# ------------------------------------------------------------------
|
|
1655
|
+
# Parameter morphing
|
|
1656
|
+
# ------------------------------------------------------------------
|
|
1657
|
+
|
|
1658
|
+
def morph_to_distribution(
|
|
1659
|
+
self,
|
|
1660
|
+
new_dist: PDFDistribution,
|
|
1661
|
+
run_time: float = 1.5,
|
|
1662
|
+
update_title: bool = True,
|
|
1663
|
+
scene: Optional[ThreeDScene] = None,
|
|
1664
|
+
) -> AnimationGroup:
|
|
1665
|
+
"""Return an animation that morphs this visualiser to *new_dist*.
|
|
1666
|
+
|
|
1667
|
+
Updates the stroke, glow, and fill to the new distribution's shape.
|
|
1668
|
+
Rebuilds the title annotation if *update_title* is True.
|
|
1669
|
+
|
|
1670
|
+
Parameters
|
|
1671
|
+
----------
|
|
1672
|
+
new_dist : PDFDistribution
|
|
1673
|
+
Target distribution.
|
|
1674
|
+
run_time : float
|
|
1675
|
+
update_title : bool
|
|
1676
|
+
If True, also transform the title and parameter labels.
|
|
1677
|
+
|
|
1678
|
+
Returns
|
|
1679
|
+
-------
|
|
1680
|
+
AnimationGroup — play with ``scene.play(viz.morph_to_distribution(...))``.
|
|
1681
|
+
"""
|
|
1682
|
+
cfg = self.cfg
|
|
1683
|
+
|
|
1684
|
+
# Compute new curve points
|
|
1685
|
+
xs = np.arange(self._x_min, self._x_max + self._x_step * 0.5, self._x_step)
|
|
1686
|
+
ys_raw = np.array([max(float(new_dist.pdf(x)), 0.0) for x in xs])
|
|
1687
|
+
y_max_new = ys_raw.max() if ys_raw.max() > 0 else 1.0
|
|
1688
|
+
ys_new = ys_raw / y_max_new * cfg.z_scale
|
|
1689
|
+
|
|
1690
|
+
new_curve_pts = np.column_stack([
|
|
1691
|
+
xs + cfg.x_pos,
|
|
1692
|
+
np.full(len(xs), cfg.y_pos),
|
|
1693
|
+
ys_new,
|
|
1694
|
+
])
|
|
1695
|
+
new_smoothed = _catmull_rom(new_curve_pts, resolution=cfg.smooth_resolution)
|
|
1696
|
+
|
|
1697
|
+
old_stroke_pts = np.array(self.stroke.get_all_points())
|
|
1698
|
+
if len(old_stroke_pts) == 0:
|
|
1699
|
+
old_stroke_pts = self._smoothed_pts
|
|
1700
|
+
|
|
1701
|
+
# Resample both to the same length for clean interpolation
|
|
1702
|
+
n_interp = max(len(new_smoothed), len(old_stroke_pts))
|
|
1703
|
+
from_pts = _resample_equal(old_stroke_pts, n_interp)
|
|
1704
|
+
to_pts = _resample_equal(new_smoothed, n_interp)
|
|
1705
|
+
|
|
1706
|
+
def stroke_updater(mob: VMobject, alpha: float) -> None:
|
|
1707
|
+
t = rate_functions.ease_in_out_cubic(alpha)
|
|
1708
|
+
mob.set_points_as_corners(from_pts + (to_pts - from_pts) * t)
|
|
1709
|
+
|
|
1710
|
+
anims: List = [UpdateFromAlphaFunc(self.stroke, stroke_updater, run_time=run_time)]
|
|
1711
|
+
|
|
1712
|
+
if hasattr(self, "glow"):
|
|
1713
|
+
glow_from = _resample_equal(old_stroke_pts, n_interp)
|
|
1714
|
+
|
|
1715
|
+
def glow_updater(mob: VMobject, alpha: float) -> None:
|
|
1716
|
+
t = rate_functions.ease_in_out_cubic(alpha)
|
|
1717
|
+
mob.set_points_as_corners(glow_from + (to_pts - glow_from) * t)
|
|
1718
|
+
|
|
1719
|
+
anims.append(UpdateFromAlphaFunc(self.glow, glow_updater, run_time=run_time))
|
|
1720
|
+
|
|
1721
|
+
# Update fill (rebuild and cross-fade)
|
|
1722
|
+
new_fill_grp = _build_fill_polygon(
|
|
1723
|
+
new_smoothed,
|
|
1724
|
+
floor_z=cfg.floor_z,
|
|
1725
|
+
y_pos=cfg.y_pos,
|
|
1726
|
+
n_gradient_strips=cfg.n_gradient_strips,
|
|
1727
|
+
color=cfg.fill_color or cfg.curve_color,
|
|
1728
|
+
opacity=cfg.fill_opacity,
|
|
1729
|
+
gradient=cfg.fill_gradient,
|
|
1730
|
+
)
|
|
1731
|
+
anims.append(FadeOut(self.fill_group, run_time=run_time * 0.4))
|
|
1732
|
+
anims.append(FadeIn(new_fill_grp, run_time=run_time * 0.6))
|
|
1733
|
+
|
|
1734
|
+
# Update stored state
|
|
1735
|
+
self._smoothed_pts = new_smoothed
|
|
1736
|
+
self.dist = new_dist
|
|
1737
|
+
self._y_max_raw = y_max_new
|
|
1738
|
+
self._ys = ys_new
|
|
1739
|
+
self._ys_raw = ys_raw
|
|
1740
|
+
|
|
1741
|
+
return AnimationGroup(*anims)
|
|
1742
|
+
|
|
1743
|
+
# ------------------------------------------------------------------
|
|
1744
|
+
# Animation helpers (layer-by-layer)
|
|
1745
|
+
# ------------------------------------------------------------------
|
|
1746
|
+
|
|
1747
|
+
def animate_curve(self, run_time: float = 1.5) -> AnimationGroup:
|
|
1748
|
+
"""Trace the PDF curve left-to-right."""
|
|
1749
|
+
anims = [Create(self.stroke, run_time=run_time)]
|
|
1750
|
+
if hasattr(self, "glow"):
|
|
1751
|
+
anims.append(FadeIn(self.glow, run_time=run_time * 0.3))
|
|
1752
|
+
return AnimationGroup(*anims, lag_ratio=0.0)
|
|
1753
|
+
|
|
1754
|
+
def animate_fill(self, run_time: float = 1.0) -> UpdateFromAlphaFunc:
|
|
1755
|
+
"""Grow the area fill upward from the floor."""
|
|
1756
|
+
cfg = self.cfg
|
|
1757
|
+
full_fill = self.fill_group
|
|
1758
|
+
smoothed = self._smoothed_pts
|
|
1759
|
+
floor_z = cfg.floor_z
|
|
1760
|
+
y_pos = cfg.y_pos
|
|
1761
|
+
fill_col = cfg.fill_color or cfg.curve_color
|
|
1762
|
+
|
|
1763
|
+
def updater(mob: VGroup, alpha: float) -> None:
|
|
1764
|
+
t = smooth(alpha)
|
|
1765
|
+
interp_pts = np.column_stack([
|
|
1766
|
+
smoothed[:, 0],
|
|
1767
|
+
smoothed[:, 1],
|
|
1768
|
+
floor_z + (smoothed[:, 2] - floor_z) * t,
|
|
1769
|
+
])
|
|
1770
|
+
mob.become(
|
|
1771
|
+
_build_fill_polygon(
|
|
1772
|
+
interp_pts, floor_z=floor_z, y_pos=y_pos,
|
|
1773
|
+
n_gradient_strips=cfg.n_gradient_strips,
|
|
1774
|
+
color=fill_col, opacity=cfg.fill_opacity,
|
|
1775
|
+
gradient=cfg.fill_gradient,
|
|
1776
|
+
)
|
|
1777
|
+
)
|
|
1778
|
+
|
|
1779
|
+
return UpdateFromAlphaFunc(full_fill, updater, run_time=run_time)
|
|
1780
|
+
|
|
1781
|
+
def animate_moments(self, run_time: float = 0.8) -> AnimationGroup:
|
|
1782
|
+
"""Fade in all moment annotations."""
|
|
1783
|
+
return FadeIn(self.moments_group, run_time=run_time)
|
|
1784
|
+
|
|
1785
|
+
def animate_title(self, run_time: float = 0.6) -> FadeIn:
|
|
1786
|
+
return FadeIn(self.title_group, run_time=run_time)
|
|
1787
|
+
|
|
1788
|
+
def animate_percentiles(
|
|
1789
|
+
self,
|
|
1790
|
+
lag: float = 0.12,
|
|
1791
|
+
run_time_per: float = 0.4,
|
|
1792
|
+
) -> LaggedStart:
|
|
1793
|
+
"""Reveal percentile markers one by one."""
|
|
1794
|
+
return LaggedStart(
|
|
1795
|
+
*[Create(m, run_time=run_time_per) for m in self.percentiles],
|
|
1796
|
+
lag_ratio=lag,
|
|
1797
|
+
)
|
|
1798
|
+
|
|
1799
|
+
def animate_regions(
|
|
1800
|
+
self,
|
|
1801
|
+
lag: float = 0.10,
|
|
1802
|
+
run_time_per: float = 0.45,
|
|
1803
|
+
) -> LaggedStart:
|
|
1804
|
+
"""Fade in probability regions one by one."""
|
|
1805
|
+
return LaggedStart(
|
|
1806
|
+
*[FadeIn(r, run_time=run_time_per) for r in self.regions],
|
|
1807
|
+
lag_ratio=lag,
|
|
1808
|
+
)
|
|
1809
|
+
|
|
1810
|
+
def full_reveal(
|
|
1811
|
+
self,
|
|
1812
|
+
scene: ThreeDScene,
|
|
1813
|
+
curve_rt: float = 1.5,
|
|
1814
|
+
fill_rt: float = 1.0,
|
|
1815
|
+
moments_rt: float = 0.8,
|
|
1816
|
+
title_rt: float = 0.6,
|
|
1817
|
+
) -> None:
|
|
1818
|
+
"""Play the complete layer-by-layer reveal directly on *scene*."""
|
|
1819
|
+
scene.play(self.animate_curve(run_time=curve_rt))
|
|
1820
|
+
scene.play(self.animate_fill(run_time=fill_rt))
|
|
1821
|
+
if len(self.moments_group) > 0:
|
|
1822
|
+
scene.play(self.animate_moments(run_time=moments_rt))
|
|
1823
|
+
if len(self.title_group) > 0:
|
|
1824
|
+
scene.play(self.animate_title(run_time=title_rt))
|
|
1825
|
+
|
|
1826
|
+
|
|
1827
|
+
def _resample_equal(pts: np.ndarray, n: int) -> np.ndarray:
|
|
1828
|
+
"""Resample *pts* to *n* points via arc-length parameterisation."""
|
|
1829
|
+
if len(pts) == n:
|
|
1830
|
+
return pts.copy()
|
|
1831
|
+
if len(pts) < 2:
|
|
1832
|
+
return np.tile(pts[0] if len(pts) > 0 else np.zeros(3), (n, 1))
|
|
1833
|
+
deltas = np.linalg.norm(np.diff(pts, axis=0), axis=1)
|
|
1834
|
+
cum = np.concatenate([[0.0], np.cumsum(deltas)])
|
|
1835
|
+
total = cum[-1]
|
|
1836
|
+
if total < 1e-9:
|
|
1837
|
+
return np.tile(pts[0], (n, 1))
|
|
1838
|
+
ts = np.linspace(0.0, total, n)
|
|
1839
|
+
out = np.zeros((n, 3))
|
|
1840
|
+
for i, t in enumerate(ts):
|
|
1841
|
+
idx = int(np.searchsorted(cum, t, side="right")) - 1
|
|
1842
|
+
idx = max(0, min(idx, len(pts) - 2))
|
|
1843
|
+
seg = deltas[idx] if deltas[idx] > 1e-12 else 1e-12
|
|
1844
|
+
frac = (t - cum[idx]) / seg
|
|
1845
|
+
out[i] = pts[idx] + frac * (pts[idx + 1] - pts[idx])
|
|
1846
|
+
return out
|
|
1847
|
+
|
|
1848
|
+
|
|
1849
|
+
# ===========================================================================
|
|
1850
|
+
# MultiplePDFComparison3D
|
|
1851
|
+
# ===========================================================================
|
|
1852
|
+
|
|
1853
|
+
class MultiplePDFComparison3D(VGroup):
|
|
1854
|
+
"""Overlay multiple PDFVisualizer3D curves on the same axes.
|
|
1855
|
+
|
|
1856
|
+
Manages a list of ``PDFVisualizer3D`` objects with compatible x-ranges,
|
|
1857
|
+
staggering their fills and rendering them at different y-depths
|
|
1858
|
+
(``depth_stagger > 0``) or overlaid at the same depth.
|
|
1859
|
+
|
|
1860
|
+
Parameters
|
|
1861
|
+
----------
|
|
1862
|
+
distributions : list of PDFDistribution
|
|
1863
|
+
Distributions to compare.
|
|
1864
|
+
x_range : (float, float, float) or None
|
|
1865
|
+
Shared x-range. If None each distribution uses its own default.
|
|
1866
|
+
colors : list of ManimColor or None
|
|
1867
|
+
configs : list of PDFConfig or None
|
|
1868
|
+
Per-distribution configs. If None, ``COMPARISON_PDF`` is used
|
|
1869
|
+
with the corresponding colour.
|
|
1870
|
+
depth_stagger : float
|
|
1871
|
+
Y-offset between successive curves (0 = all overlaid).
|
|
1872
|
+
show_divergence : bool
|
|
1873
|
+
If True and there are exactly two distributions, shade the
|
|
1874
|
+
region between the two curves.
|
|
1875
|
+
show_legend : bool
|
|
1876
|
+
Whether to add a floating legend.
|
|
1877
|
+
scene : ThreeDScene or None
|
|
1878
|
+
|
|
1879
|
+
Attributes
|
|
1880
|
+
----------
|
|
1881
|
+
visualizers : list of PDFVisualizer3D
|
|
1882
|
+
divergence_group : VGroup
|
|
1883
|
+
Shaded region between two overlaid PDFs (if ``show_divergence``).
|
|
1884
|
+
legend : VGroup
|
|
1885
|
+
"""
|
|
1886
|
+
|
|
1887
|
+
_DEFAULT_COLORS: List[ManimColor] = [
|
|
1888
|
+
ManimColor("#4A90D9"),
|
|
1889
|
+
ManimColor("#E8593C"),
|
|
1890
|
+
ManimColor("#2DAA6E"),
|
|
1891
|
+
ManimColor("#E0AA40"),
|
|
1892
|
+
ManimColor("#9B59B6"),
|
|
1893
|
+
ManimColor("#1ABC9C"),
|
|
1894
|
+
]
|
|
1895
|
+
|
|
1896
|
+
def __init__(
|
|
1897
|
+
self,
|
|
1898
|
+
distributions: List[PDFDistribution],
|
|
1899
|
+
x_range: Optional[Tuple[float, float, float]] = None,
|
|
1900
|
+
colors: Optional[List[ManimColor]] = None,
|
|
1901
|
+
configs: Optional[List[PDFConfig]] = None,
|
|
1902
|
+
depth_stagger: float = 0.0,
|
|
1903
|
+
show_divergence: bool = False,
|
|
1904
|
+
show_legend: bool = True,
|
|
1905
|
+
x_center: float = 0.0,
|
|
1906
|
+
scene: Optional[ThreeDScene] = None,
|
|
1907
|
+
**kwargs,
|
|
1908
|
+
):
|
|
1909
|
+
super().__init__(**kwargs)
|
|
1910
|
+
|
|
1911
|
+
n = len(distributions)
|
|
1912
|
+
self._colors = colors or [self._DEFAULT_COLORS[i % len(self._DEFAULT_COLORS)] for i in range(n)]
|
|
1913
|
+
|
|
1914
|
+
# Resolve shared x_range
|
|
1915
|
+
if x_range is None:
|
|
1916
|
+
all_lo = [d.default_x_range[0] for d in distributions]
|
|
1917
|
+
all_hi = [d.default_x_range[1] for d in distributions]
|
|
1918
|
+
lo = min(all_lo)
|
|
1919
|
+
hi = max(all_hi)
|
|
1920
|
+
step = (hi - lo) / 200
|
|
1921
|
+
x_range = (lo, hi, step)
|
|
1922
|
+
|
|
1923
|
+
self.visualizers: List[PDFVisualizer3D] = []
|
|
1924
|
+
|
|
1925
|
+
for i, (dist, col) in enumerate(zip(distributions, self._colors)):
|
|
1926
|
+
if configs is not None and i < len(configs):
|
|
1927
|
+
cfg = configs[i]
|
|
1928
|
+
else:
|
|
1929
|
+
cfg = PDFConfig(**COMPARISON_PDF.__dict__)
|
|
1930
|
+
cfg.curve_color = col
|
|
1931
|
+
cfg.fill_color = col
|
|
1932
|
+
|
|
1933
|
+
cfg.y_pos = i * depth_stagger
|
|
1934
|
+
cfg.x_pos = x_center
|
|
1935
|
+
|
|
1936
|
+
viz = PDFVisualizer3D(
|
|
1937
|
+
dist,
|
|
1938
|
+
x_range=x_range,
|
|
1939
|
+
config=cfg,
|
|
1940
|
+
scene=scene,
|
|
1941
|
+
)
|
|
1942
|
+
self.visualizers.append(viz)
|
|
1943
|
+
self.add(viz)
|
|
1944
|
+
|
|
1945
|
+
# Divergence shading (two curves only)
|
|
1946
|
+
self.divergence_group = VGroup()
|
|
1947
|
+
if show_divergence and len(distributions) == 2:
|
|
1948
|
+
self._build_divergence(x_range)
|
|
1949
|
+
self.add(self.divergence_group)
|
|
1950
|
+
|
|
1951
|
+
# Legend
|
|
1952
|
+
self.legend = VGroup()
|
|
1953
|
+
if show_legend:
|
|
1954
|
+
self._build_legend(distributions, scene)
|
|
1955
|
+
self.add(self.legend)
|
|
1956
|
+
|
|
1957
|
+
# ------------------------------------------------------------------
|
|
1958
|
+
|
|
1959
|
+
def _build_divergence(self, x_range: Tuple[float, float, float]) -> None:
|
|
1960
|
+
"""Shade the area between two PDFs (KL-divergence visualization)."""
|
|
1961
|
+
v0, v1 = self.visualizers[0], self.visualizers[1]
|
|
1962
|
+
cfg0, cfg1 = v0.cfg, v1.cfg
|
|
1963
|
+
xs = np.linspace(x_range[0], x_range[1], 400)
|
|
1964
|
+
|
|
1965
|
+
z0 = np.array([max(float(v0.dist.pdf(x)), 0.0) / v0._y_max_raw * cfg0.z_scale for x in xs])
|
|
1966
|
+
z1 = np.array([max(float(v1.dist.pdf(x)), 0.0) / v1._y_max_raw * cfg1.z_scale for x in xs])
|
|
1967
|
+
|
|
1968
|
+
# Upper envelope minus lower: two regions (dist0 > dist1, dist0 < dist1)
|
|
1969
|
+
for (upper_z, lower_z, col) in [
|
|
1970
|
+
(np.maximum(z0, z1), np.minimum(z0, z1), ManimColor("#AAAAAA")),
|
|
1971
|
+
]:
|
|
1972
|
+
# Build alternating strips based on which curve is higher
|
|
1973
|
+
for i in range(len(xs) - 1):
|
|
1974
|
+
z_u = (upper_z[i] + upper_z[i+1]) / 2
|
|
1975
|
+
z_l = (lower_z[i] + lower_z[i+1]) / 2
|
|
1976
|
+
if abs(z_u - z_l) < 0.01:
|
|
1977
|
+
continue
|
|
1978
|
+
x_l, x_r = xs[i] + cfg0.x_pos, xs[i+1] + cfg0.x_pos
|
|
1979
|
+
y = (cfg0.y_pos + cfg1.y_pos) / 2
|
|
1980
|
+
strip_col = self._colors[0] if z0[i] > z1[i] else self._colors[1]
|
|
1981
|
+
strip = Polygon(
|
|
1982
|
+
np.array([x_l, y, z_l]),
|
|
1983
|
+
np.array([x_r, y, z_l]),
|
|
1984
|
+
np.array([x_r, y, z_u]),
|
|
1985
|
+
np.array([x_l, y, z_u]),
|
|
1986
|
+
fill_color=_with_opacity(strip_col, 0.14),
|
|
1987
|
+
fill_opacity=1.0, stroke_width=0,
|
|
1988
|
+
)
|
|
1989
|
+
self.divergence_group.add(strip)
|
|
1990
|
+
|
|
1991
|
+
def _build_legend(
|
|
1992
|
+
self,
|
|
1993
|
+
distributions: List[PDFDistribution],
|
|
1994
|
+
scene: Optional[ThreeDScene],
|
|
1995
|
+
) -> None:
|
|
1996
|
+
"""Build a floating legend listing distribution names and colours."""
|
|
1997
|
+
for i, (dist, col) in enumerate(zip(distributions, self._colors)):
|
|
1998
|
+
swatch = Line(
|
|
1999
|
+
ORIGIN, RIGHT * 0.38,
|
|
2000
|
+
color=_with_opacity(col, 0.90),
|
|
2001
|
+
stroke_width=3.0,
|
|
2002
|
+
)
|
|
2003
|
+
lbl = Text(
|
|
2004
|
+
f"{dist.name} ({dist.param_string})",
|
|
2005
|
+
font_size=16,
|
|
2006
|
+
color=col,
|
|
2007
|
+
)
|
|
2008
|
+
row = VGroup(swatch, lbl)
|
|
2009
|
+
row.arrange(RIGHT, buff=0.12)
|
|
2010
|
+
row.move_to(np.array([5.5, 0, 3.5 - i * 0.35]))
|
|
2011
|
+
self.legend.add(row)
|
|
2012
|
+
if scene is not None:
|
|
2013
|
+
scene.add_fixed_orientation_mobjects(row)
|
|
2014
|
+
|
|
2015
|
+
# ------------------------------------------------------------------
|
|
2016
|
+
|
|
2017
|
+
def animate_reveal(
|
|
2018
|
+
self,
|
|
2019
|
+
stagger: float = 0.3,
|
|
2020
|
+
run_time_per: float = 1.2,
|
|
2021
|
+
) -> LaggedStart:
|
|
2022
|
+
"""Reveal all curves with a staggered draw animation."""
|
|
2023
|
+
return LaggedStart(
|
|
2024
|
+
*[viz.animate_curve(run_time=run_time_per) for viz in self.visualizers],
|
|
2025
|
+
lag_ratio=stagger / run_time_per,
|
|
2026
|
+
)
|
|
2027
|
+
|
|
2028
|
+
def animate_fills(
|
|
2029
|
+
self,
|
|
2030
|
+
stagger: float = 0.15,
|
|
2031
|
+
run_time_per: float = 0.9,
|
|
2032
|
+
) -> LaggedStart:
|
|
2033
|
+
"""Grow all fills with a stagger."""
|
|
2034
|
+
return LaggedStart(
|
|
2035
|
+
*[viz.animate_fill(run_time=run_time_per) for viz in self.visualizers],
|
|
2036
|
+
lag_ratio=stagger / run_time_per,
|
|
2037
|
+
)
|
|
2038
|
+
|
|
2039
|
+
def highlight_distribution(
|
|
2040
|
+
self,
|
|
2041
|
+
index: int,
|
|
2042
|
+
dim_others: bool = True,
|
|
2043
|
+
dim_opacity: float = 0.20,
|
|
2044
|
+
) -> AnimationGroup:
|
|
2045
|
+
"""Emphasise one distribution, dimming the others."""
|
|
2046
|
+
anims = []
|
|
2047
|
+
for i, viz in enumerate(self.visualizers):
|
|
2048
|
+
if i == index:
|
|
2049
|
+
anims.append(viz.stroke.animate.set_stroke(
|
|
2050
|
+
width=viz.cfg.curve_stroke_width * 1.8
|
|
2051
|
+
))
|
|
2052
|
+
elif dim_others:
|
|
2053
|
+
anims.append(viz.animate.set_opacity(dim_opacity))
|
|
2054
|
+
return AnimationGroup(*anims, run_time=0.5)
|
|
2055
|
+
|
|
2056
|
+
def morph_parameter(
|
|
2057
|
+
self,
|
|
2058
|
+
dist_index: int,
|
|
2059
|
+
new_distribution: PDFDistribution,
|
|
2060
|
+
run_time: float = 1.5,
|
|
2061
|
+
scene: Optional[ThreeDScene] = None,
|
|
2062
|
+
) -> AnimationGroup:
|
|
2063
|
+
"""Morph one distribution in the comparison to *new_distribution*."""
|
|
2064
|
+
return self.visualizers[dist_index].morph_to_distribution(
|
|
2065
|
+
new_distribution, run_time=run_time, scene=scene
|
|
2066
|
+
)
|
|
2067
|
+
|
|
2068
|
+
|
|
2069
|
+
# ===========================================================================
|
|
2070
|
+
# Ready-to-render ThreeDScene subclasses
|
|
2071
|
+
# ===========================================================================
|
|
2072
|
+
|
|
2073
|
+
class NormalPDFScene(ThreeDScene):
|
|
2074
|
+
"""Normal PDF with σ-brackets, 68–95–99.7 rule, and z-score annotations.
|
|
2075
|
+
|
|
2076
|
+
Render: manim -pql pdf_viz.py NormalPDFScene
|
|
2077
|
+
"""
|
|
2078
|
+
|
|
2079
|
+
def construct(self):
|
|
2080
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
2081
|
+
self.begin_ambient_camera_rotation(rate=0.025)
|
|
2082
|
+
|
|
2083
|
+
dist = NormalDist(mu=0.0, sigma=1.0)
|
|
2084
|
+
viz = PDFVisualizer3D(
|
|
2085
|
+
dist,
|
|
2086
|
+
x_range=(-4.0, 4.0, 0.04),
|
|
2087
|
+
config=TEACHING_PDF,
|
|
2088
|
+
scene=self,
|
|
2089
|
+
)
|
|
2090
|
+
self.add(viz)
|
|
2091
|
+
|
|
2092
|
+
viz.full_reveal(self)
|
|
2093
|
+
self.wait(0.5)
|
|
2094
|
+
|
|
2095
|
+
# Shade 68-95-99.7
|
|
2096
|
+
for n_sig, col in [
|
|
2097
|
+
(1, ManimColor("#2DAA6E")),
|
|
2098
|
+
(2, ManimColor("#E0AA40")),
|
|
2099
|
+
(3, ManimColor("#E8593C")),
|
|
2100
|
+
]:
|
|
2101
|
+
region = viz.shade_between_sigmas(n_sig, color=col, scene=self)
|
|
2102
|
+
self.play(FadeIn(region, run_time=0.55))
|
|
2103
|
+
self.wait(0.4)
|
|
2104
|
+
|
|
2105
|
+
self.wait(2)
|
|
2106
|
+
|
|
2107
|
+
|
|
2108
|
+
class TDistScene(ThreeDScene):
|
|
2109
|
+
"""t-distribution for df = 1, 3, 10, 30 compared to Normal.
|
|
2110
|
+
|
|
2111
|
+
Render: manim -pql pdf_viz.py TDistScene
|
|
2112
|
+
"""
|
|
2113
|
+
|
|
2114
|
+
def construct(self):
|
|
2115
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
2116
|
+
self.begin_ambient_camera_rotation(rate=0.02)
|
|
2117
|
+
|
|
2118
|
+
normal = NormalDist(0, 1)
|
|
2119
|
+
dists = [StudentTDist(df=df) for df in [1, 3, 10, 30]]
|
|
2120
|
+
colors = [
|
|
2121
|
+
ManimColor("#E8593C"),
|
|
2122
|
+
ManimColor("#E0AA40"),
|
|
2123
|
+
ManimColor("#2DAA6E"),
|
|
2124
|
+
ManimColor("#9B59B6"),
|
|
2125
|
+
]
|
|
2126
|
+
|
|
2127
|
+
comp = MultiplePDFComparison3D(
|
|
2128
|
+
distributions=[normal] + dists,
|
|
2129
|
+
x_range=(-5.0, 5.0, 0.05),
|
|
2130
|
+
colors=[ManimColor("#4A90D9")] + colors,
|
|
2131
|
+
depth_stagger=0.0,
|
|
2132
|
+
show_divergence=False,
|
|
2133
|
+
show_legend=True,
|
|
2134
|
+
scene=self,
|
|
2135
|
+
)
|
|
2136
|
+
self.add(comp)
|
|
2137
|
+
self.play(comp.animate_reveal(stagger=0.35, run_time_per=1.2))
|
|
2138
|
+
self.play(comp.animate_fills(stagger=0.12, run_time_per=0.8))
|
|
2139
|
+
self.wait(3)
|
|
2140
|
+
|
|
2141
|
+
|
|
2142
|
+
class GammaPDFScene(ThreeDScene):
|
|
2143
|
+
"""Gamma distribution sweeping shape k from 1 → 5, rate λ = 1.
|
|
2144
|
+
|
|
2145
|
+
Render: manim -pql pdf_viz.py GammaPDFScene
|
|
2146
|
+
"""
|
|
2147
|
+
|
|
2148
|
+
def construct(self):
|
|
2149
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
2150
|
+
|
|
2151
|
+
dist = GammaDist(shape=1.0, rate=1.0)
|
|
2152
|
+
cfg = PDFConfig(**TEACHING_PDF.__dict__)
|
|
2153
|
+
cfg.curve_color = ManimColor("#E8593C")
|
|
2154
|
+
cfg.fill_color = ManimColor("#E8593C")
|
|
2155
|
+
cfg.show_sigma_brackets = False
|
|
2156
|
+
|
|
2157
|
+
viz = PDFVisualizer3D(dist, x_range=(0.0, 12.0, 0.06), config=cfg, scene=self)
|
|
2158
|
+
self.add(viz)
|
|
2159
|
+
viz.full_reveal(self, curve_rt=1.2, fill_rt=0.9, moments_rt=0.5, title_rt=0.4)
|
|
2160
|
+
self.wait(0.5)
|
|
2161
|
+
|
|
2162
|
+
for k in [2.0, 3.0, 4.0, 5.0]:
|
|
2163
|
+
new_dist = GammaDist(shape=k, rate=1.0)
|
|
2164
|
+
self.play(
|
|
2165
|
+
viz.morph_to_distribution(new_dist, run_time=1.0, scene=self),
|
|
2166
|
+
run_time=1.0,
|
|
2167
|
+
)
|
|
2168
|
+
self.wait(0.4)
|
|
2169
|
+
|
|
2170
|
+
self.wait(2)
|
|
2171
|
+
|
|
2172
|
+
|
|
2173
|
+
class PDFComparisonScene(ThreeDScene):
|
|
2174
|
+
"""Side-by-side PDFs: Normal, t(5), Laplace, Cauchy.
|
|
2175
|
+
|
|
2176
|
+
All zero-centred, similar scale, depth-staggered for depth cues.
|
|
2177
|
+
|
|
2178
|
+
Render: manim -pql pdf_viz.py PDFComparisonScene
|
|
2179
|
+
"""
|
|
2180
|
+
|
|
2181
|
+
def construct(self):
|
|
2182
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
2183
|
+
self.begin_ambient_camera_rotation(rate=0.025)
|
|
2184
|
+
|
|
2185
|
+
dists = [
|
|
2186
|
+
NormalDist(0, 1),
|
|
2187
|
+
StudentTDist(df=5),
|
|
2188
|
+
LaplaceDist(mu=0, b=0.707), # same variance as N(0,1)
|
|
2189
|
+
CauchyDist(x0=0, gamma=0.5),
|
|
2190
|
+
]
|
|
2191
|
+
comp = MultiplePDFComparison3D(
|
|
2192
|
+
distributions=dists,
|
|
2193
|
+
x_range=(-5.0, 5.0, 0.05),
|
|
2194
|
+
depth_stagger=0.6,
|
|
2195
|
+
show_legend=True,
|
|
2196
|
+
scene=self,
|
|
2197
|
+
)
|
|
2198
|
+
self.add(comp)
|
|
2199
|
+
self.play(comp.animate_reveal(stagger=0.30, run_time_per=1.2))
|
|
2200
|
+
self.play(comp.animate_fills(stagger=0.12, run_time_per=0.8))
|
|
2201
|
+
self.wait(0.5)
|
|
2202
|
+
|
|
2203
|
+
# Highlight heavy-tailed distributions
|
|
2204
|
+
self.play(comp.highlight_distribution(3, dim_others=True))
|
|
2205
|
+
self.wait(2)
|
|
2206
|
+
self.play(AnimationGroup(*[
|
|
2207
|
+
v.animate.set_opacity(1.0) for v in comp.visualizers
|
|
2208
|
+
]))
|
|
2209
|
+
self.wait(2)
|
|
2210
|
+
|
|
2211
|
+
|
|
2212
|
+
class PDFParameterSweepScene(ThreeDScene):
|
|
2213
|
+
"""Beta(α, β) PDF: sweep α from 0.5 → 5 while β = 2 stays fixed.
|
|
2214
|
+
|
|
2215
|
+
Render: manim -pql pdf_viz.py PDFParameterSweepScene
|
|
2216
|
+
"""
|
|
2217
|
+
|
|
2218
|
+
def construct(self):
|
|
2219
|
+
self.set_camera_orientation(phi=65 * DEGREES, theta=-50 * DEGREES)
|
|
2220
|
+
self.begin_ambient_camera_rotation(rate=0.03)
|
|
2221
|
+
|
|
2222
|
+
dist = BetaDist(alpha=0.5, beta=2.0)
|
|
2223
|
+
cfg = PDFConfig(**TEACHING_PDF.__dict__)
|
|
2224
|
+
cfg.curve_color = ManimColor("#9B59B6")
|
|
2225
|
+
cfg.fill_color = ManimColor("#9B59B6")
|
|
2226
|
+
cfg.show_sigma_brackets = False
|
|
2227
|
+
|
|
2228
|
+
viz = PDFVisualizer3D(dist, config=cfg, scene=self)
|
|
2229
|
+
self.add(viz)
|
|
2230
|
+
viz.full_reveal(self, curve_rt=1.0, fill_rt=0.8, moments_rt=0.4, title_rt=0.3)
|
|
2231
|
+
self.wait(0.5)
|
|
2232
|
+
|
|
2233
|
+
alpha_values = np.arange(1.0, 5.5, 0.5)
|
|
2234
|
+
for alpha in alpha_values:
|
|
2235
|
+
new_dist = BetaDist(alpha=alpha, beta=2.0)
|
|
2236
|
+
self.play(
|
|
2237
|
+
viz.morph_to_distribution(new_dist, run_time=0.65, scene=self),
|
|
2238
|
+
)
|
|
2239
|
+
self.wait(0.2)
|
|
2240
|
+
|
|
2241
|
+
self.wait(1)
|
|
2242
|
+
|
|
2243
|
+
# Shade the mode region
|
|
2244
|
+
mode = (dist.alpha - 1) / (dist.alpha + dist.beta - 2) if dist.alpha > 1 else 0.0
|
|
2245
|
+
viz.add_critical_value(mode, label="mode", scene=self)
|
|
2246
|
+
self.play(FadeIn(viz[-1], run_time=0.5))
|
|
2247
|
+
self.wait(2)
|