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,2111 @@
|
|
|
1
|
+
r"""
|
|
2
|
+
statanim/core/tex_utils.py
|
|
3
|
+
=============================
|
|
4
|
+
A comprehensive LaTeX formula system for statistical visualization.
|
|
5
|
+
|
|
6
|
+
Architecture
|
|
7
|
+
------------
|
|
8
|
+
Layer A TeX atom constants — Greek letters, operators, spacing macros
|
|
9
|
+
Layer B Formula string builders — pdf(), pmf(), cdf(), mean(), variance(), ...
|
|
10
|
+
Layer C TexFormula dataclass — structured formula with named parts, steps
|
|
11
|
+
Layer D Annotation & coloring — highlight_part(), overbrace(), annotate_step()
|
|
12
|
+
Layer E Manim MathTex builders — to_mathtex(), to_aligned(), derive() anim
|
|
13
|
+
Layer F Formula registry — FORMULAS catalog, topic index, derivation chains
|
|
14
|
+
|
|
15
|
+
Design principles
|
|
16
|
+
-----------------
|
|
17
|
+
* Formulas are *data*, not strings. Every TexFormula carries its raw LaTeX,
|
|
18
|
+
its named sub-parts (so callers can color "the mean" or "the variance" by
|
|
19
|
+
name), and an optional step-by-step derivation chain.
|
|
20
|
+
* Parametric variants. pdf_normal(mu=r"\mu_0") returns a fully substituted
|
|
21
|
+
string, not a template with blanks.
|
|
22
|
+
* Manim-aware. Every TexFormula knows how to emit a MathTex or Tex object,
|
|
23
|
+
including a color_map that Manim uses to color individual sub-expressions.
|
|
24
|
+
* No hard Manim dependency. All string-building works without Manim; the
|
|
25
|
+
.to_mathtex() / .to_tex() / .derive() methods raise ImportError gracefully.
|
|
26
|
+
|
|
27
|
+
Quick start
|
|
28
|
+
-----------
|
|
29
|
+
from statanim.core.tex_utils import FORMULAS, TexFormula
|
|
30
|
+
|
|
31
|
+
# Simple string
|
|
32
|
+
s = pdf_normal()
|
|
33
|
+
|
|
34
|
+
# Structured formula with named parts
|
|
35
|
+
f = FORMULAS["normal_pdf"]
|
|
36
|
+
print(f.inline) # $f(x ...)$
|
|
37
|
+
print(f.parts["kernel"]) # the exponent substring
|
|
38
|
+
print(f.steps) # list of derivation steps
|
|
39
|
+
|
|
40
|
+
# Manim usage
|
|
41
|
+
tex = f.to_mathtex(color_map={"kernel": NORMAL_FAMILY.highlight.to_manim()})
|
|
42
|
+
scene.play(Write(tex))
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import re
|
|
48
|
+
from dataclasses import dataclass, field
|
|
49
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
# Graceful Manim import
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
try:
|
|
55
|
+
from manim import MathTex, Tex, ManimColor # type: ignore
|
|
56
|
+
_MANIM_AVAILABLE = True
|
|
57
|
+
except ImportError:
|
|
58
|
+
_MANIM_AVAILABLE = False
|
|
59
|
+
MathTex = ManimColor = Tex = None # type: ignore
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ===========================================================================
|
|
63
|
+
# LAYER A — TeX atom constants
|
|
64
|
+
# Single-source-of-truth for every Greek letter, operator, and macro we use.
|
|
65
|
+
# Grouped so it is easy to find what you need without memorizing LaTeX.
|
|
66
|
+
# ===========================================================================
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------------------
|
|
69
|
+
# Greek letters (lowercase)
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
class Greek:
|
|
72
|
+
"""Lowercase Greek letters as raw LaTeX strings."""
|
|
73
|
+
alpha = r"\alpha"
|
|
74
|
+
beta = r"\beta"
|
|
75
|
+
gamma = r"\gamma"
|
|
76
|
+
delta = r"\delta"
|
|
77
|
+
epsilon = r"\epsilon"
|
|
78
|
+
zeta = r"\zeta"
|
|
79
|
+
eta = r"\eta"
|
|
80
|
+
theta = r"\theta"
|
|
81
|
+
iota = r"\iota"
|
|
82
|
+
kappa = r"\kappa"
|
|
83
|
+
lam = r"\lambda" # 'lambda' is a Python keyword
|
|
84
|
+
mu = r"\mu"
|
|
85
|
+
nu = r"\nu"
|
|
86
|
+
xi = r"\xi"
|
|
87
|
+
pi = r"\pi"
|
|
88
|
+
rho = r"\rho"
|
|
89
|
+
sigma = r"\sigma"
|
|
90
|
+
tau = r"\tau"
|
|
91
|
+
upsilon = r"\upsilon"
|
|
92
|
+
phi = r"\phi"
|
|
93
|
+
varphi = r"\varphi"
|
|
94
|
+
chi = r"\chi"
|
|
95
|
+
psi = r"\psi"
|
|
96
|
+
omega = r"\omega"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class GreekUpper:
|
|
100
|
+
"""Uppercase Greek letters."""
|
|
101
|
+
Gamma = r"\Gamma"
|
|
102
|
+
Delta = r"\Delta"
|
|
103
|
+
Theta = r"\Theta"
|
|
104
|
+
Lambda = r"\Lambda"
|
|
105
|
+
Xi = r"\Xi"
|
|
106
|
+
Pi = r"\Pi"
|
|
107
|
+
Sigma = r"\Sigma"
|
|
108
|
+
Upsilon = r"\Upsilon"
|
|
109
|
+
Phi = r"\Phi"
|
|
110
|
+
Psi = r"\Psi"
|
|
111
|
+
Omega = r"\Omega"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
# Mathematical operators & relations
|
|
116
|
+
# ---------------------------------------------------------------------------
|
|
117
|
+
class Op:
|
|
118
|
+
"""Common math operators as LaTeX strings."""
|
|
119
|
+
# Arithmetic
|
|
120
|
+
times = r"\times"
|
|
121
|
+
cdot = r"\cdot"
|
|
122
|
+
div = r"\div"
|
|
123
|
+
pm = r"\pm"
|
|
124
|
+
mp = r"\mp"
|
|
125
|
+
|
|
126
|
+
# Relations
|
|
127
|
+
leq = r"\leq"
|
|
128
|
+
geq = r"\geq"
|
|
129
|
+
neq = r"\neq"
|
|
130
|
+
approx = r"\approx"
|
|
131
|
+
propto = r"\propto"
|
|
132
|
+
sim = r"\sim"
|
|
133
|
+
simeq = r"\simeq"
|
|
134
|
+
|
|
135
|
+
# Sets
|
|
136
|
+
in_ = r"\in"
|
|
137
|
+
notin = r"\notin"
|
|
138
|
+
subset = r"\subset"
|
|
139
|
+
cup = r"\cup"
|
|
140
|
+
cap = r"\cap"
|
|
141
|
+
emptyset = r"\emptyset"
|
|
142
|
+
|
|
143
|
+
# Arrows
|
|
144
|
+
to = r"\to"
|
|
145
|
+
gets = r"\gets"
|
|
146
|
+
implies = r"\implies"
|
|
147
|
+
iff = r"\iff"
|
|
148
|
+
|
|
149
|
+
# Logic
|
|
150
|
+
forall = r"\forall"
|
|
151
|
+
exists = r"\exists"
|
|
152
|
+
land = r"\land"
|
|
153
|
+
lor = r"\lor"
|
|
154
|
+
lnot = r"\lnot"
|
|
155
|
+
|
|
156
|
+
# Calculus
|
|
157
|
+
partial = r"\partial"
|
|
158
|
+
nabla = r"\nabla"
|
|
159
|
+
inf = r"\infty"
|
|
160
|
+
int_ = r"\int"
|
|
161
|
+
iint = r"\iint"
|
|
162
|
+
sum_ = r"\sum"
|
|
163
|
+
prod_ = r"\prod"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ---------------------------------------------------------------------------
|
|
167
|
+
# Decorators (accents over a symbol)
|
|
168
|
+
# ---------------------------------------------------------------------------
|
|
169
|
+
class Dec:
|
|
170
|
+
"""LaTeX accent / decorator macros. Each takes one argument."""
|
|
171
|
+
@staticmethod
|
|
172
|
+
def hat(x: str) -> str:
|
|
173
|
+
return rf"\hat{{{x}}}"
|
|
174
|
+
|
|
175
|
+
@staticmethod
|
|
176
|
+
def bar(x: str) -> str:
|
|
177
|
+
return rf"\bar{{{x}}}"
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def tilde(x: str) -> str:
|
|
181
|
+
return rf"\tilde{{{x}}}"
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def vec(x: str) -> str:
|
|
185
|
+
return rf"\vec{{{x}}}"
|
|
186
|
+
|
|
187
|
+
@staticmethod
|
|
188
|
+
def dot(x: str) -> str:
|
|
189
|
+
return rf"\dot{{{x}}}"
|
|
190
|
+
|
|
191
|
+
@staticmethod
|
|
192
|
+
def ddot(x: str) -> str:
|
|
193
|
+
return rf"\ddot{{{x}}}"
|
|
194
|
+
|
|
195
|
+
@staticmethod
|
|
196
|
+
def overline(x: str) -> str:
|
|
197
|
+
return rf"\overline{{{x}}}"
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def underline(x: str) -> str:
|
|
201
|
+
return rf"\underline{{{x}}}"
|
|
202
|
+
|
|
203
|
+
@staticmethod
|
|
204
|
+
def mathbf(x: str) -> str:
|
|
205
|
+
return rf"\mathbf{{{x}}}"
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
def boldsymbol(x: str) -> str:
|
|
209
|
+
return rf"\boldsymbol{{{x}}}"
|
|
210
|
+
|
|
211
|
+
@staticmethod
|
|
212
|
+
def mathcal(x: str) -> str:
|
|
213
|
+
return rf"\mathcal{{{x}}}"
|
|
214
|
+
|
|
215
|
+
@staticmethod
|
|
216
|
+
def mathbb(x: str) -> str:
|
|
217
|
+
return rf"\mathbb{{{x}}}"
|
|
218
|
+
|
|
219
|
+
@staticmethod
|
|
220
|
+
def text(x: str) -> str:
|
|
221
|
+
return rf"\text{{{x}}}"
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def mathrm(x: str) -> str:
|
|
225
|
+
return rf"\mathrm{{{x}}}"
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# ---------------------------------------------------------------------------
|
|
229
|
+
# Fences — matching delimiters
|
|
230
|
+
# ---------------------------------------------------------------------------
|
|
231
|
+
class Fence:
|
|
232
|
+
"""Produce matched LaTeX delimiters with \\left / \\right."""
|
|
233
|
+
@staticmethod
|
|
234
|
+
def paren(x: str) -> str:
|
|
235
|
+
return rf"\left( {x} \right)"
|
|
236
|
+
|
|
237
|
+
@staticmethod
|
|
238
|
+
def bracket(x: str) -> str:
|
|
239
|
+
return rf"\left[ {x} \right]"
|
|
240
|
+
|
|
241
|
+
@staticmethod
|
|
242
|
+
def brace(x: str) -> str:
|
|
243
|
+
return rf"\left\{{ {x} \right\}}"
|
|
244
|
+
|
|
245
|
+
@staticmethod
|
|
246
|
+
def abs(x: str) -> str:
|
|
247
|
+
return rf"\left| {x} \right|"
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
def norm(x: str) -> str:
|
|
251
|
+
return rf"\left\| {x} \right\|"
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
def floor(x: str) -> str:
|
|
255
|
+
return rf"\left\lfloor {x} \right\rfloor"
|
|
256
|
+
|
|
257
|
+
@staticmethod
|
|
258
|
+
def ceil(x: str) -> str:
|
|
259
|
+
return rf"\left\lceil {x} \right\rceil"
|
|
260
|
+
|
|
261
|
+
@staticmethod
|
|
262
|
+
def angle(x: str) -> str:
|
|
263
|
+
return rf"\left\langle {x} \right\rangle"
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ---------------------------------------------------------------------------
|
|
267
|
+
# Spacing
|
|
268
|
+
# ---------------------------------------------------------------------------
|
|
269
|
+
class Space:
|
|
270
|
+
"""Horizontal spacing macros."""
|
|
271
|
+
thin = r"\," # 3/18 em
|
|
272
|
+
med = r"\:" # 4/18 em
|
|
273
|
+
thick = r"\;" # 5/18 em
|
|
274
|
+
quad = r"\quad" # 1 em
|
|
275
|
+
qquad = r"\qquad" # 2 em
|
|
276
|
+
neg = r"\!" # negative 3/18 em
|
|
277
|
+
enspace = r"\enspace" # 0.5 em
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# ---------------------------------------------------------------------------
|
|
281
|
+
# Display math environment fragments
|
|
282
|
+
# ---------------------------------------------------------------------------
|
|
283
|
+
class Env:
|
|
284
|
+
"""LaTeX environment wrappers."""
|
|
285
|
+
@staticmethod
|
|
286
|
+
def display(x: str) -> str:
|
|
287
|
+
return rf"$${x}$$"
|
|
288
|
+
|
|
289
|
+
@staticmethod
|
|
290
|
+
def inline(x: str) -> str:
|
|
291
|
+
return rf"${x}$"
|
|
292
|
+
|
|
293
|
+
@staticmethod
|
|
294
|
+
def aligned(rows: list[tuple[str, str]]) -> str:
|
|
295
|
+
r"""
|
|
296
|
+
Build an ``align*``-style block from (left, right) pairs.
|
|
297
|
+
|
|
298
|
+
aligned([("f(x)", r"= \frac{1}{\sigma}"), ("", r"\cdot e^{...}")])
|
|
299
|
+
|
|
300
|
+
produces::
|
|
301
|
+
|
|
302
|
+
\begin{aligned}
|
|
303
|
+
f(x) &= \frac{1}{\sigma} \\
|
|
304
|
+
&\cdot e^{...}
|
|
305
|
+
\end{aligned}
|
|
306
|
+
"""
|
|
307
|
+
lines = r" \\ ".join(
|
|
308
|
+
rf"{lhs} &= {rhs}" if lhs else rf"&\phantom{{=}} {rhs}"
|
|
309
|
+
for lhs, rhs in rows
|
|
310
|
+
)
|
|
311
|
+
return rf"\begin{{aligned}} {lines} \end{{aligned}}"
|
|
312
|
+
|
|
313
|
+
@staticmethod
|
|
314
|
+
def cases(rows: list[tuple[str, str]]) -> str:
|
|
315
|
+
r"""
|
|
316
|
+
Build a ``cases`` environment.
|
|
317
|
+
|
|
318
|
+
cases([("x^2", r"x \geq 0"), ("0", r"\text{otherwise}")])
|
|
319
|
+
"""
|
|
320
|
+
body = r" \\ ".join(rf"{val} & {cond}" for val, cond in rows)
|
|
321
|
+
return rf"\begin{{cases}} {body} \end{{cases}}"
|
|
322
|
+
|
|
323
|
+
@staticmethod
|
|
324
|
+
def piecewise(symbol: str, rows: list[tuple[str, str]]) -> str:
|
|
325
|
+
return rf"{symbol} = {Env.cases(rows)}"
|
|
326
|
+
|
|
327
|
+
@staticmethod
|
|
328
|
+
def matrix(rows: list[list[str]], style: str = "pmatrix") -> str:
|
|
329
|
+
"""
|
|
330
|
+
Build a matrix environment.
|
|
331
|
+
|
|
332
|
+
matrix([["a","b"],["c","d"]]) → pmatrix
|
|
333
|
+
"""
|
|
334
|
+
body = r" \\ ".join(" & ".join(row) for row in rows)
|
|
335
|
+
return rf"\begin{{{style}}} {body} \end{{{style}}}"
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
# ===========================================================================
|
|
339
|
+
# LAYER B — Formula string builders
|
|
340
|
+
# Each function returns a raw LaTeX string (no $…$ wrapper).
|
|
341
|
+
# Callers receive strings they can embed, annotate, and style.
|
|
342
|
+
# ===========================================================================
|
|
343
|
+
|
|
344
|
+
# ---------------------------------------------------------------------------
|
|
345
|
+
# Primitive helpers
|
|
346
|
+
# ---------------------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
def _frac(num: str, den: str) -> str:
|
|
349
|
+
return rf"\frac{{{num}}}{{{den}}}"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _sqrt(x: str, n: str = "") -> str:
|
|
353
|
+
if n:
|
|
354
|
+
return rf"\sqrt[{n}]{{{x}}}"
|
|
355
|
+
return rf"\sqrt{{{x}}}"
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _exp(exponent: str) -> str:
|
|
359
|
+
return rf"e^{{{exponent}}}"
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _power(base: str, exp: str) -> str:
|
|
363
|
+
return rf"{base}^{{{exp}}}"
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _sub(base: str, subscript: str) -> str:
|
|
367
|
+
return rf"{base}_{{{subscript}}}"
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _subsup(base: str, subscript: str, superscript: str) -> str:
|
|
371
|
+
return rf"{base}_{{{subscript}}}^{{{superscript}}}"
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _integral(
|
|
375
|
+
integrand: str,
|
|
376
|
+
dx: str = "x",
|
|
377
|
+
lower: str = "-\\infty",
|
|
378
|
+
upper: str = "\\infty",
|
|
379
|
+
) -> str:
|
|
380
|
+
return rf"\int_{{{lower}}}^{{{upper}}} {integrand} \, d{dx}"
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _sum(body: str, lower: str, upper: str) -> str:
|
|
384
|
+
return rf"\sum_{{{lower}}}^{{{upper}}} {body}"
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _prod(body: str, lower: str, upper: str) -> str:
|
|
388
|
+
return rf"\prod_{{{lower}}}^{{{upper}}} {body}"
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _log(x: str, base: str = "") -> str:
|
|
392
|
+
if base:
|
|
393
|
+
return rf"\log_{{{base}}}{x}"
|
|
394
|
+
return rf"\log {x}"
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _ln(x: str) -> str:
|
|
398
|
+
return rf"\ln {x}"
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _conditional(x: str, given: str) -> str:
|
|
402
|
+
"""x \\mid given"""
|
|
403
|
+
return rf"{x} \mid {given}"
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _expected(x: str, subscript: str = "") -> str:
|
|
407
|
+
E = rf"\mathbb{{E}}"
|
|
408
|
+
if subscript:
|
|
409
|
+
E = rf"\mathbb{{E}}_{{{subscript}}}"
|
|
410
|
+
return rf"{E}\left[ {x} \right]"
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _var(x: str, subscript: str = "") -> str:
|
|
414
|
+
V = rf"\mathrm{{Var}}"
|
|
415
|
+
if subscript:
|
|
416
|
+
V = rf"\mathrm{{Var}}_{{{subscript}}}"
|
|
417
|
+
return rf"{V}\left( {x} \right)"
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _cov(x: str, y: str) -> str:
|
|
421
|
+
return rf"\mathrm{{Cov}}\left( {x},\, {y} \right)"
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _indicator(event: str) -> str:
|
|
425
|
+
return rf"\mathbf{{1}}\left\{{ {event} \right\}}"
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _binom_coef(n: str, k: str) -> str:
|
|
429
|
+
return rf"\binom{{{n}}}{{{k}}}"
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _gamma_func(x: str) -> str:
|
|
433
|
+
return rf"\Gamma\left({x}\right)"
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _beta_func(a: str, b: str) -> str:
|
|
437
|
+
return rf"\mathrm{{B}}\left({a},\, {b}\right)"
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
# ---------------------------------------------------------------------------
|
|
441
|
+
# B.1 Descriptive statistics formulas
|
|
442
|
+
# ---------------------------------------------------------------------------
|
|
443
|
+
|
|
444
|
+
def mean(
|
|
445
|
+
symbol: str = "\\bar{x}",
|
|
446
|
+
xi: str = "x_i",
|
|
447
|
+
n: str = "n",
|
|
448
|
+
) -> str:
|
|
449
|
+
"""Sample mean: \\bar{x} = (1/n) \\sum x_i"""
|
|
450
|
+
return rf"{symbol} = {_frac('1', n)} {_sum(xi, 'i=1', n)}"
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def weighted_mean(
|
|
454
|
+
symbol: str = "\\bar{x}_w",
|
|
455
|
+
xi: str = "x_i",
|
|
456
|
+
wi: str = "w_i",
|
|
457
|
+
) -> str:
|
|
458
|
+
return (
|
|
459
|
+
rf"{symbol} = "
|
|
460
|
+
rf"{_frac(_sum(wi + xi, 'i=1', 'n'), _sum(wi, 'i=1', 'n'))}"
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def population_variance(
|
|
465
|
+
symbol: str = "\\sigma^2",
|
|
466
|
+
xi: str = "x_i",
|
|
467
|
+
mu: str = "\\mu",
|
|
468
|
+
n: str = "N",
|
|
469
|
+
) -> str:
|
|
470
|
+
return (
|
|
471
|
+
rf"{symbol} = "
|
|
472
|
+
rf"{_frac('1', n)} {_sum(Fence.paren(xi + ' - ' + mu) + '^2', 'i=1', n)}"
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def sample_variance(
|
|
477
|
+
symbol: str = "s^2",
|
|
478
|
+
xi: str = "x_i",
|
|
479
|
+
xbar: str = "\\bar{x}",
|
|
480
|
+
n: str = "n",
|
|
481
|
+
) -> str:
|
|
482
|
+
return (
|
|
483
|
+
rf"{symbol} = "
|
|
484
|
+
rf"{_frac('1', n + '-1')} {_sum(Fence.paren(xi + ' - ' + xbar) + '^2', 'i=1', n)}"
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def std_dev(sample: bool = True) -> str:
|
|
489
|
+
sym = "s" if sample else r"\sigma"
|
|
490
|
+
var = "s^2" if sample else r"\sigma^2"
|
|
491
|
+
return rf"{sym} = {_sqrt(var)}"
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def coeff_of_variation() -> str:
|
|
495
|
+
return rf"CV = {_frac(r'\sigma', r'\mu')} \times 100\%"
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def skewness() -> str:
|
|
499
|
+
return (
|
|
500
|
+
rf"\gamma_1 = "
|
|
501
|
+
rf"{_frac(_expected(r'(X - \mu)^3'), r'\sigma^3')}"
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def kurtosis(excess: bool = True) -> str:
|
|
506
|
+
symbol = r"\gamma_2" if excess else r"\kappa"
|
|
507
|
+
core = _frac(_expected(r"(X - \mu)^4"), r"\sigma^4")
|
|
508
|
+
if excess:
|
|
509
|
+
return rf"{symbol} = {core} - 3"
|
|
510
|
+
return rf"{symbol} = {core}"
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def z_score(x: str = "x", mu: str = r"\mu", sigma: str = r"\sigma") -> str:
|
|
514
|
+
return rf"z = {_frac(x + ' - ' + mu, sigma)}"
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def percentile_rank() -> str:
|
|
518
|
+
return rf"PR = {_frac(r'L + 0.5 F', 'N')} \times 100"
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def iqr() -> str:
|
|
522
|
+
return r"IQR = Q_3 - Q_1"
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def coefficient_of_determination() -> str:
|
|
526
|
+
return (
|
|
527
|
+
r"R^2 = 1 - "
|
|
528
|
+
+ _frac(r"\sum (y_i - \hat{y}_i)^2", r"\sum (y_i - \bar{y})^2")
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
# ---------------------------------------------------------------------------
|
|
533
|
+
# B.2 Probability
|
|
534
|
+
# ---------------------------------------------------------------------------
|
|
535
|
+
|
|
536
|
+
def conditional_probability(
|
|
537
|
+
A: str = "A", B: str = "B"
|
|
538
|
+
) -> str:
|
|
539
|
+
return (
|
|
540
|
+
rf"P({A} \mid {B}) = "
|
|
541
|
+
rf"{_frac('P(' + A + r' \cap ' + B + ')', 'P(' + B + ')')}"
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def total_probability(n_events: int = 3) -> str:
|
|
546
|
+
terms = " + ".join(
|
|
547
|
+
rf"P(A \mid B_{i}) P(B_{i})" for i in range(1, n_events + 1)
|
|
548
|
+
)
|
|
549
|
+
return rf"P(A) = {terms}"
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def bayes_theorem(
|
|
553
|
+
A: str = "A", B: str = "B",
|
|
554
|
+
posterior_name: str = "posterior",
|
|
555
|
+
) -> str:
|
|
556
|
+
"""
|
|
557
|
+
Full Bayes' theorem.
|
|
558
|
+
|
|
559
|
+
Returns the raw LaTeX; parts are accessible via TexFormula.parts.
|
|
560
|
+
"""
|
|
561
|
+
likelihood = rf"P({B} \mid {A})"
|
|
562
|
+
prior = rf"P({A})"
|
|
563
|
+
evidence = rf"P({B})"
|
|
564
|
+
return (
|
|
565
|
+
rf"P({A} \mid {B}) = "
|
|
566
|
+
rf"{_frac(likelihood + r' \cdot ' + prior, evidence)}"
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def bayes_proportional(A: str = "A", B: str = "B") -> str:
|
|
571
|
+
return rf"P({A} \mid {B}) \propto P({B} \mid {A}) \cdot P({A})"
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def law_of_total_expectation(
|
|
575
|
+
X: str = "X", Y: str = "Y"
|
|
576
|
+
) -> str:
|
|
577
|
+
return (
|
|
578
|
+
rf"{_expected(X)} = "
|
|
579
|
+
rf"{_expected(_expected(_conditional(X, Y), 'Y'))}"
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def law_of_total_variance(X: str = "X", Y: str = "Y") -> str:
|
|
584
|
+
return (
|
|
585
|
+
rf"{_var(X)} = "
|
|
586
|
+
rf"{_expected(_var(_conditional(X, Y), 'Y'))} + "
|
|
587
|
+
rf"{_var(_expected(_conditional(X, Y), 'Y'))}"
|
|
588
|
+
)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
# ---------------------------------------------------------------------------
|
|
592
|
+
# B.3 Discrete distribution PDFs / PMFs
|
|
593
|
+
# ---------------------------------------------------------------------------
|
|
594
|
+
|
|
595
|
+
def pmf_bernoulli(
|
|
596
|
+
p: str = "p",
|
|
597
|
+
x: str = "x",
|
|
598
|
+
) -> str:
|
|
599
|
+
return rf"P(X={x}) = {p}^{{{x}}} (1-{p})^{{1-{x}}}, \quad {x} \in \{{0,1\}}"
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def pmf_binomial(
|
|
603
|
+
n: str = "n",
|
|
604
|
+
p: str = "p",
|
|
605
|
+
k: str = "k",
|
|
606
|
+
) -> str:
|
|
607
|
+
return (
|
|
608
|
+
rf"P(X={k}) = {_binom_coef(n, k)} "
|
|
609
|
+
rf"{p}^{{{k}}} (1-{p})^{{{n}-{k}}}"
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def pmf_poisson(
|
|
614
|
+
lam: str = r"\lambda",
|
|
615
|
+
k: str = "k",
|
|
616
|
+
) -> str:
|
|
617
|
+
return (
|
|
618
|
+
rf"P(X={k}) = "
|
|
619
|
+
rf"{_frac(_exp('-' + lam) + r' \cdot ' + lam + '^{' + k + '}', k + '!')}"
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def pmf_geometric(
|
|
624
|
+
p: str = "p",
|
|
625
|
+
k: str = "k",
|
|
626
|
+
) -> str:
|
|
627
|
+
return rf"P(X={k}) = (1-{p})^{{{k}-1}} {p}, \quad {k} = 1, 2, \ldots"
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def pmf_negative_binomial(
|
|
631
|
+
r: str = "r",
|
|
632
|
+
p: str = "p",
|
|
633
|
+
k: str = "k",
|
|
634
|
+
) -> str:
|
|
635
|
+
return (
|
|
636
|
+
rf"P(X={k}) = {_binom_coef(k+'-1', r+'-1')} "
|
|
637
|
+
rf"{p}^{{{r}}} (1-{p})^{{{k}-{r}}}"
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def pmf_hypergeometric(
|
|
642
|
+
N: str = "N",
|
|
643
|
+
K: str = "K",
|
|
644
|
+
n: str = "n",
|
|
645
|
+
k: str = "k",
|
|
646
|
+
) -> str:
|
|
647
|
+
return (
|
|
648
|
+
rf"P(X={k}) = "
|
|
649
|
+
rf"{_frac(_binom_coef(K, k) + r' \cdot ' + _binom_coef(N+'-'+K, n+'-'+k), _binom_coef(N, n))}"
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def pmf_uniform_discrete(
|
|
654
|
+
a: str = "a",
|
|
655
|
+
b: str = "b",
|
|
656
|
+
) -> str:
|
|
657
|
+
return rf"P(X=x) = {_frac('1', b + '-' + a + '+1')}, \quad x \in \{{{a}, \ldots, {b}\}}"
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
# ---------------------------------------------------------------------------
|
|
661
|
+
# B.4 Continuous distribution PDFs
|
|
662
|
+
# ---------------------------------------------------------------------------
|
|
663
|
+
|
|
664
|
+
def pdf_uniform(
|
|
665
|
+
a: str = "a",
|
|
666
|
+
b: str = "b",
|
|
667
|
+
x: str = "x",
|
|
668
|
+
) -> str:
|
|
669
|
+
body = _frac("1", b + " - " + a)
|
|
670
|
+
cond = rf"{a} \leq {x} \leq {b}"
|
|
671
|
+
return Env.piecewise(
|
|
672
|
+
rf"f({x})",
|
|
673
|
+
[(body, rf"\text{{if }} {cond}"), ("0", r"\text{otherwise}")]
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def pdf_normal(
|
|
678
|
+
mu: str = r"\mu",
|
|
679
|
+
sigma: str = r"\sigma",
|
|
680
|
+
x: str = "x",
|
|
681
|
+
) -> str:
|
|
682
|
+
"""
|
|
683
|
+
Normal PDF: f(x | μ, σ²) = 1/(σ√(2π)) · exp(-(x-μ)²/(2σ²))
|
|
684
|
+
"""
|
|
685
|
+
norm_const = _frac("1", sigma + r"\sqrt{2\pi}")
|
|
686
|
+
exponent = _frac(
|
|
687
|
+
r"-\left(" + x + r" - " + mu + r"\right)^2",
|
|
688
|
+
"2" + sigma + "^2"
|
|
689
|
+
)
|
|
690
|
+
kernel = _exp(exponent)
|
|
691
|
+
return rf"f({x} \mid {mu}, {sigma}^2) = {norm_const} {kernel}"
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def pdf_standard_normal(x: str = "x") -> str:
|
|
695
|
+
return (
|
|
696
|
+
rf"\phi({x}) = "
|
|
697
|
+
rf"{_frac('1', r'\sqrt{2\pi}')}"
|
|
698
|
+
rf" \exp\!\left( {_frac('-' + x + '^2', '2')} \right)"
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def cdf_standard_normal(x: str = "x") -> str:
|
|
703
|
+
return (
|
|
704
|
+
rf"\Phi({x}) = "
|
|
705
|
+
rf"{_frac('1', r'\sqrt{2\pi}')}"
|
|
706
|
+
rf" {_integral(_exp(_frac('-t^2', '2')), dx='t', lower=r'-\infty', upper=x)}"
|
|
707
|
+
)
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def pdf_exponential(
|
|
711
|
+
lam: str = r"\lambda",
|
|
712
|
+
x: str = "x",
|
|
713
|
+
) -> str:
|
|
714
|
+
body = lam + " " + _exp("-" + lam + x)
|
|
715
|
+
return Env.piecewise(
|
|
716
|
+
rf"f({x})",
|
|
717
|
+
[(body, rf"\text{{if }} {x} \geq 0"), ("0", r"\text{otherwise}")]
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def pdf_gamma(
|
|
722
|
+
alpha: str = r"\alpha",
|
|
723
|
+
beta: str = r"\beta",
|
|
724
|
+
x: str = "x",
|
|
725
|
+
) -> str:
|
|
726
|
+
return (
|
|
727
|
+
rf"f({x}) = "
|
|
728
|
+
rf"{_frac(_power(beta, alpha), _gamma_func(alpha))}"
|
|
729
|
+
rf" {_power(x, alpha + '-1')}"
|
|
730
|
+
rf" {_exp('-' + beta + x)}"
|
|
731
|
+
rf", \quad {x} > 0"
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def pdf_beta(
|
|
736
|
+
alpha: str = r"\alpha",
|
|
737
|
+
beta: str = r"\beta",
|
|
738
|
+
x: str = "x",
|
|
739
|
+
) -> str:
|
|
740
|
+
return (
|
|
741
|
+
rf"f({x}) = "
|
|
742
|
+
rf"{_frac(_power(x, alpha + '-1') + _power('(1-' + x + ')', beta + '-1'), _beta_func(alpha, beta))}"
|
|
743
|
+
rf", \quad {x} \in [0,1]"
|
|
744
|
+
)
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def pdf_chi_squared(
|
|
748
|
+
k: str = "k",
|
|
749
|
+
x: str = "x",
|
|
750
|
+
) -> str:
|
|
751
|
+
half_k = _frac(k, "2")
|
|
752
|
+
return (
|
|
753
|
+
rf"f({x}) = "
|
|
754
|
+
rf"{_frac(_power(x, half_k + '-1') + _exp('-' + x + '/2'), _power('2', half_k) + r'\,\Gamma(' + half_k + ')')}"
|
|
755
|
+
rf", \quad {x} > 0"
|
|
756
|
+
)
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def pdf_student_t(
|
|
760
|
+
nu: str = r"\nu",
|
|
761
|
+
x: str = "x",
|
|
762
|
+
) -> str:
|
|
763
|
+
return (
|
|
764
|
+
rf"f({x}) = "
|
|
765
|
+
rf"{_frac(_gamma_func(Fence.paren(nu + '+1') + '/2'), _sqrt(r'\pi ' + nu) + r'\,' + _gamma_func(nu + '/2'))}"
|
|
766
|
+
rf"\left(1 + {_frac(x + '^2', nu)}\right)^{{-({nu}+1)/2}}"
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def pdf_f(
|
|
771
|
+
d1: str = "d_1",
|
|
772
|
+
d2: str = "d_2",
|
|
773
|
+
x: str = "x",
|
|
774
|
+
) -> str:
|
|
775
|
+
num = (
|
|
776
|
+
_sqrt(_frac(_power(d1 + x, d1) + r"\cdot" + _power(d2, d2),
|
|
777
|
+
_power(d1 + x + "+" + d2, d1 + "+" + d2)))
|
|
778
|
+
)
|
|
779
|
+
den = rf"x\,\mathrm{{B}}\left({_frac(d1,'2')},{_frac(d2,'2')}\right)"
|
|
780
|
+
return rf"f({x}) = {_frac(num, den)}, \quad {x} > 0"
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
def pdf_lognormal(
|
|
784
|
+
mu: str = r"\mu",
|
|
785
|
+
sigma: str = r"\sigma",
|
|
786
|
+
x: str = "x",
|
|
787
|
+
) -> str:
|
|
788
|
+
return (
|
|
789
|
+
rf"f({x}) = "
|
|
790
|
+
rf"{_frac('1', x + sigma + r'\sqrt{2\pi}')}"
|
|
791
|
+
rf"\exp\!\left({_frac(r'-(\ln ' + x + '-' + mu + ')^2', '2' + sigma + '^2')}\right)"
|
|
792
|
+
rf", \quad {x} > 0"
|
|
793
|
+
)
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
def pdf_weibull(
|
|
797
|
+
k: str = "k",
|
|
798
|
+
lam: str = r"\lambda",
|
|
799
|
+
x: str = "x",
|
|
800
|
+
) -> str:
|
|
801
|
+
return (
|
|
802
|
+
rf"f({x}) = {_frac(k, lam)}"
|
|
803
|
+
rf"\left({_frac(x, lam)}\right)^{{{k}-1}}"
|
|
804
|
+
rf"\exp\!\left(-\left({_frac(x, lam)}\right)^{{{k}}}\right)"
|
|
805
|
+
rf", \quad {x} \geq 0"
|
|
806
|
+
)
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def pdf_cauchy(
|
|
810
|
+
x0: str = "x_0",
|
|
811
|
+
gamma: str = r"\gamma",
|
|
812
|
+
x: str = "x",
|
|
813
|
+
) -> str:
|
|
814
|
+
return (
|
|
815
|
+
rf"f({x}) = "
|
|
816
|
+
rf"{_frac('1', r'\pi ' + gamma)}"
|
|
817
|
+
rf"\left[1 + \left({_frac(x + '-' + x0, gamma)}\right)^2\right]^{{-1}}"
|
|
818
|
+
)
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
def pdf_pareto(
|
|
822
|
+
x_m: str = "x_m",
|
|
823
|
+
alpha: str = r"\alpha",
|
|
824
|
+
x: str = "x",
|
|
825
|
+
) -> str:
|
|
826
|
+
return (
|
|
827
|
+
rf"f({x}) = {_frac(alpha + x_m + r'^\alpha', _power(x, r'\alpha+1'))}"
|
|
828
|
+
rf", \quad {x} \geq {x_m}"
|
|
829
|
+
)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def pdf_bivariate_normal(
|
|
833
|
+
mu1: str = r"\mu_1",
|
|
834
|
+
mu2: str = r"\mu_2",
|
|
835
|
+
s1: str = r"\sigma_1",
|
|
836
|
+
s2: str = r"\sigma_2",
|
|
837
|
+
rho: str = r"\rho",
|
|
838
|
+
) -> str:
|
|
839
|
+
norm_const = _frac(
|
|
840
|
+
"1",
|
|
841
|
+
"2\\pi " + s1 + s2 + r"\sqrt{1-" + rho + "^2}"
|
|
842
|
+
)
|
|
843
|
+
z = (
|
|
844
|
+
_frac("1", "1 - " + rho + "^2")
|
|
845
|
+
+ r"\left["
|
|
846
|
+
+ _frac(r"(x-" + mu1 + r")^2", s1 + "^2")
|
|
847
|
+
+ r" - \frac{2" + rho + r"(x-" + mu1 + r")(y-" + mu2 + r")}"
|
|
848
|
+
+ "{" + s1 + s2 + "}"
|
|
849
|
+
+ r" + " + _frac(r"(y-" + mu2 + r")^2", s2 + "^2")
|
|
850
|
+
+ r"\right]"
|
|
851
|
+
)
|
|
852
|
+
return rf"f(x,y) = {norm_const} \exp\!\left(-{_frac(z, '2')}\right)"
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
# ---------------------------------------------------------------------------
|
|
856
|
+
# B.5 Moments: E[X], Var(X), MGF, characteristic function
|
|
857
|
+
# ---------------------------------------------------------------------------
|
|
858
|
+
|
|
859
|
+
def expected_value_discrete(
|
|
860
|
+
X: str = "X",
|
|
861
|
+
xi: str = "x_i",
|
|
862
|
+
pi: str = "p_i",
|
|
863
|
+
) -> str:
|
|
864
|
+
return rf"{_expected(X)} = {_sum(xi + r'\,' + pi, 'i=1', 'n')}"
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def expected_value_continuous(
|
|
868
|
+
X: str = "X",
|
|
869
|
+
x: str = "x",
|
|
870
|
+
f: str = "f(x)",
|
|
871
|
+
) -> str:
|
|
872
|
+
return rf"{_expected(X)} = {_integral(x + r'\,' + f)}"
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def variance_definition(
|
|
876
|
+
X: str = "X",
|
|
877
|
+
mu: str = r"\mu",
|
|
878
|
+
) -> str:
|
|
879
|
+
return (
|
|
880
|
+
rf"{_var(X)} = "
|
|
881
|
+
rf"{_expected('(' + X + ' - ' + mu + ')^2')} = "
|
|
882
|
+
rf"{_expected(X + '^2')} - {_expected(X)}^2"
|
|
883
|
+
)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def mgf(X: str = "X", t: str = "t") -> str:
|
|
887
|
+
return rf"M_{{{X}}}({t}) = {_expected(_exp(t + X))}"
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def characteristic_function(X: str = "X", t: str = "t") -> str:
|
|
891
|
+
return rf"\varphi_{{{X}}}({t}) = {_expected(_exp('i' + t + X))}"
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def moment_k(k: str = "k") -> str:
|
|
895
|
+
return rf"\mu'_{{{k}}} = {_expected('X^{' + k + '}')}"
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def central_moment_k(k: str = "k") -> str:
|
|
899
|
+
mu_expr = r"(X-\mu)^{" + k + "}"
|
|
900
|
+
return rf"\mu_{{{k}}} = {_expected(mu_expr)}"
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
# ---------------------------------------------------------------------------
|
|
904
|
+
# B.6 Entropy and information theory
|
|
905
|
+
# ---------------------------------------------------------------------------
|
|
906
|
+
|
|
907
|
+
def entropy_discrete(
|
|
908
|
+
X: str = "X",
|
|
909
|
+
p: str = "p",
|
|
910
|
+
) -> str:
|
|
911
|
+
return (
|
|
912
|
+
rf"H({X}) = -"
|
|
913
|
+
rf"{_sum(p + r'(x) \log_2 ' + p + r'(x)', r'x \in \mathcal{X}', '')}"
|
|
914
|
+
)
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def entropy_continuous(X: str = "X", f: str = "f") -> str:
|
|
918
|
+
return (
|
|
919
|
+
rf"h({X}) = -"
|
|
920
|
+
rf"{_integral(f + r'(x) \ln ' + f + r'(x)')}"
|
|
921
|
+
)
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def kl_divergence(P: str = "P", Q: str = "Q") -> str:
|
|
925
|
+
return (
|
|
926
|
+
rf"D_{{\mathrm{{KL}}}}({P} \| {Q}) = "
|
|
927
|
+
rf"{_sum(p + r'(x) \ln ' + _frac(p + r'(x)', q + r'(x)'), r'x', '')}"
|
|
928
|
+
.replace("p", P.lower()).replace("q", Q.lower())
|
|
929
|
+
)
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def mutual_information(X: str = "X", Y: str = "Y") -> str:
|
|
933
|
+
return (
|
|
934
|
+
rf"I({X};\, {Y}) = "
|
|
935
|
+
rf"H({X}) + H({Y}) - H({X}, {Y})"
|
|
936
|
+
)
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def cross_entropy(P: str = "P", Q: str = "Q") -> str:
|
|
940
|
+
p, q = P.lower(), Q.lower()
|
|
941
|
+
return (
|
|
942
|
+
rf"H({P}, {Q}) = -"
|
|
943
|
+
rf"{_sum(p + r'(x) \log ' + q + r'(x)', 'x', '')}"
|
|
944
|
+
)
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
# ---------------------------------------------------------------------------
|
|
948
|
+
# B.7 Inference: CI, test statistics, p-value region
|
|
949
|
+
# ---------------------------------------------------------------------------
|
|
950
|
+
|
|
951
|
+
def ci_mean_known_sigma(
|
|
952
|
+
alpha: str = r"\alpha",
|
|
953
|
+
z: str = "z",
|
|
954
|
+
sigma: str = r"\sigma",
|
|
955
|
+
n: str = "n",
|
|
956
|
+
) -> str:
|
|
957
|
+
se = _frac(sigma, _sqrt(n))
|
|
958
|
+
return (
|
|
959
|
+
rf"\bar{{x}} \pm {z}_{{{_frac(alpha, '2')}}} \cdot {se}"
|
|
960
|
+
)
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def ci_mean_unknown_sigma(
|
|
964
|
+
alpha: str = r"\alpha",
|
|
965
|
+
n: str = "n",
|
|
966
|
+
s: str = "s",
|
|
967
|
+
) -> str:
|
|
968
|
+
se = _frac(s, _sqrt(n))
|
|
969
|
+
return (
|
|
970
|
+
rf"\bar{{x}} \pm t_{{{_frac(alpha, '2')},\, {n}-1}} \cdot {se}"
|
|
971
|
+
)
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
def ci_proportion(
|
|
975
|
+
alpha: str = r"\alpha",
|
|
976
|
+
p: str = r"\hat{p}",
|
|
977
|
+
n: str = "n",
|
|
978
|
+
) -> str:
|
|
979
|
+
se = _sqrt(_frac(p + r"(1-" + p + ")", n))
|
|
980
|
+
return (
|
|
981
|
+
rf"{p} \pm z_{{{_frac(alpha, '2')}}} \cdot {se}"
|
|
982
|
+
)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def z_test_statistic(
|
|
986
|
+
mu0: str = r"\mu_0",
|
|
987
|
+
sigma: str = r"\sigma",
|
|
988
|
+
n: str = "n",
|
|
989
|
+
) -> str:
|
|
990
|
+
return rf"Z = {_frac(r'\bar{x} - ' + mu0, _frac(sigma, _sqrt(n)))}"
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def t_test_statistic(
|
|
994
|
+
mu0: str = r"\mu_0",
|
|
995
|
+
n: str = "n",
|
|
996
|
+
) -> str:
|
|
997
|
+
return rf"T = {_frac(r'\bar{x} - ' + mu0, _frac('s', _sqrt(n)))}"
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def t_test_two_sample(pooled: bool = False) -> str:
|
|
1001
|
+
if pooled:
|
|
1002
|
+
sp = _sqrt(
|
|
1003
|
+
_frac(
|
|
1004
|
+
r"(n_1-1)s_1^2 + (n_2-1)s_2^2",
|
|
1005
|
+
r"n_1 + n_2 - 2"
|
|
1006
|
+
)
|
|
1007
|
+
)
|
|
1008
|
+
se = sp + r" \sqrt{" + _frac("1", "n_1") + "+" + _frac("1", "n_2") + "}"
|
|
1009
|
+
return rf"T = {_frac(r'\bar{x}_1 - \bar{x}_2', se)}"
|
|
1010
|
+
se = _sqrt(
|
|
1011
|
+
_frac(r"s_1^2", r"n_1") + "+" + _frac(r"s_2^2", r"n_2")
|
|
1012
|
+
)
|
|
1013
|
+
return rf"T = {_frac(r'\bar{x}_1 - \bar{x}_2', se)}"
|
|
1014
|
+
|
|
1015
|
+
|
|
1016
|
+
def chi_sq_test_statistic() -> str:
|
|
1017
|
+
return (
|
|
1018
|
+
rf"\chi^2 = "
|
|
1019
|
+
rf"{_sum(_frac('(O_i - E_i)^2', 'E_i'), 'i=1', 'k')}"
|
|
1020
|
+
)
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
def f_test_statistic() -> str:
|
|
1024
|
+
return rf"F = {_frac('s_1^2', 's_2^2')}"
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def power_function(alpha: str = r"\alpha") -> str:
|
|
1028
|
+
return (
|
|
1029
|
+
rf"\beta(\theta) = P\!\left(\text{{reject }} H_0 \mid \theta\right)"
|
|
1030
|
+
)
|
|
1031
|
+
|
|
1032
|
+
|
|
1033
|
+
def likelihood_ratio_test() -> str:
|
|
1034
|
+
return (
|
|
1035
|
+
rf"\Lambda = "
|
|
1036
|
+
rf"{_frac(r'L(\hat{\theta}_0)', r'L(\hat{\theta})')}"
|
|
1037
|
+
r",\quad -2\ln\Lambda \sim \chi^2_k"
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
# ---------------------------------------------------------------------------
|
|
1042
|
+
# B.8 Regression
|
|
1043
|
+
# ---------------------------------------------------------------------------
|
|
1044
|
+
|
|
1045
|
+
def simple_linear_regression(
|
|
1046
|
+
beta0: str = r"\beta_0",
|
|
1047
|
+
beta1: str = r"\beta_1",
|
|
1048
|
+
epsilon: str = r"\varepsilon",
|
|
1049
|
+
) -> str:
|
|
1050
|
+
return rf"Y = {beta0} + {beta1} X + {epsilon}"
|
|
1051
|
+
|
|
1052
|
+
|
|
1053
|
+
def ols_estimate_beta1() -> str:
|
|
1054
|
+
num = _sum(r"(x_i - \bar{x})(y_i - \bar{y})", "i=1", "n")
|
|
1055
|
+
den = _sum(r"(x_i - \bar{x})^2", "i=1", "n")
|
|
1056
|
+
return rf"\hat{{\beta}}_1 = {_frac(num, den)}"
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def ols_estimate_beta0() -> str:
|
|
1060
|
+
return rf"\hat{{\beta}}_0 = \bar{{y}} - \hat{{\beta}}_1 \bar{{x}}"
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
def multiple_regression() -> str:
|
|
1064
|
+
return (
|
|
1065
|
+
r"\mathbf{Y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon}"
|
|
1066
|
+
)
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
def ols_matrix() -> str:
|
|
1070
|
+
return (
|
|
1071
|
+
r"\hat{\boldsymbol{\beta}} = "
|
|
1072
|
+
r"\left(\mathbf{X}^\top \mathbf{X}\right)^{-1} \mathbf{X}^\top \mathbf{Y}"
|
|
1073
|
+
)
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
def logistic_regression(
|
|
1077
|
+
beta0: str = r"\beta_0",
|
|
1078
|
+
beta1: str = r"\beta_1",
|
|
1079
|
+
) -> str:
|
|
1080
|
+
log_odds = beta0 + " + " + beta1 + " x"
|
|
1081
|
+
return rf"P(Y=1 \mid x) = {_frac(_exp(log_odds), '1 + ' + _exp(log_odds))}"
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
def pearson_r() -> str:
|
|
1085
|
+
num = _sum(r"(x_i - \bar{x})(y_i - \bar{y})", "i=1", "n")
|
|
1086
|
+
den = (
|
|
1087
|
+
_sqrt(_sum(r"(x_i - \bar{x})^2", "i=1", "n"))
|
|
1088
|
+
+ r"\,"
|
|
1089
|
+
+ _sqrt(_sum(r"(y_i - \bar{y})^2", "i=1", "n"))
|
|
1090
|
+
)
|
|
1091
|
+
return rf"r = {_frac(num, den)}"
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
def spearman_rho(n: str = "n") -> str:
|
|
1095
|
+
return (
|
|
1096
|
+
rf"\rho = 1 - "
|
|
1097
|
+
rf"{_frac('6 ' + _sum('d_i^2', 'i=1', n), n + '(' + n + '^2 - 1)')}"
|
|
1098
|
+
)
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
# ---------------------------------------------------------------------------
|
|
1102
|
+
# B.9 Sampling theory / CLT
|
|
1103
|
+
# ---------------------------------------------------------------------------
|
|
1104
|
+
|
|
1105
|
+
def clt_statement(
|
|
1106
|
+
n: str = "n",
|
|
1107
|
+
mu: str = r"\mu",
|
|
1108
|
+
sigma: str = r"\sigma",
|
|
1109
|
+
) -> str:
|
|
1110
|
+
return (
|
|
1111
|
+
rf"\sqrt{{{n}}}\left(\bar{{X}}_n - {mu}\right)"
|
|
1112
|
+
rf"\xrightarrow{{d}} \mathcal{{N}}\left(0,\, {sigma}^2\right)"
|
|
1113
|
+
)
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
def standard_error(sigma: str = r"\sigma", n: str = "n") -> str:
|
|
1117
|
+
return rf"SE = {_frac(sigma, _sqrt(n))}"
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
def mle_definition() -> str:
|
|
1121
|
+
return (
|
|
1122
|
+
rf"\hat{{\theta}}_{{MLE}} = "
|
|
1123
|
+
rf"\arg\max_{{\theta}}\, L(\theta \mid \mathbf{{x}})"
|
|
1124
|
+
)
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
def log_likelihood() -> str:
|
|
1128
|
+
return (
|
|
1129
|
+
rf"\ell(\theta) = \ln L(\theta) = "
|
|
1130
|
+
rf"{_sum(r'\ln f(x_i \mid \theta)', 'i=1', 'n')}"
|
|
1131
|
+
)
|
|
1132
|
+
|
|
1133
|
+
|
|
1134
|
+
def method_of_moments(k: str = "k") -> str:
|
|
1135
|
+
return (
|
|
1136
|
+
rf"\hat{{\mu}}'_{{{k}}} = "
|
|
1137
|
+
rf"{_frac('1', 'n')} {_sum('x_i^{' + k + '}', 'i=1', 'n')}"
|
|
1138
|
+
)
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def fisher_information(theta: str = r"\theta") -> str:
|
|
1142
|
+
return (
|
|
1143
|
+
rf"I({theta}) = "
|
|
1144
|
+
rf"-{_expected(_frac(r'\partial^2 \ln f(X;\,' + theta + r')', r'\partial ' + theta + '^2'))}"
|
|
1145
|
+
)
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
# ===========================================================================
|
|
1149
|
+
# LAYER C — TexFormula dataclass
|
|
1150
|
+
# Carries raw LaTeX + named parts + derivation steps.
|
|
1151
|
+
# ===========================================================================
|
|
1152
|
+
|
|
1153
|
+
@dataclass
|
|
1154
|
+
class TexFormula:
|
|
1155
|
+
r"""
|
|
1156
|
+
A structured statistical formula.
|
|
1157
|
+
|
|
1158
|
+
Attributes
|
|
1159
|
+
----------
|
|
1160
|
+
name : str
|
|
1161
|
+
Machine-readable key, e.g. ``"normal_pdf"``.
|
|
1162
|
+
raw : str
|
|
1163
|
+
Raw LaTeX source (no dollar signs).
|
|
1164
|
+
description : str
|
|
1165
|
+
One-line human description.
|
|
1166
|
+
parts : dict[str, str]
|
|
1167
|
+
Named sub-expressions, e.g.::
|
|
1168
|
+
|
|
1169
|
+
{"normalising_constant": r"\frac{1}{\sigma\sqrt{2\pi}}",
|
|
1170
|
+
"kernel": r"e^{-(x-\mu)^2/(2\sigma^2)}"}
|
|
1171
|
+
|
|
1172
|
+
Used by highlight_part() and Manim color_map.
|
|
1173
|
+
steps : list[TexDerivationStep]
|
|
1174
|
+
Ordered derivation steps from definition to final form.
|
|
1175
|
+
color_map : dict[str, str]
|
|
1176
|
+
part_name -> LaTeX color name (for Manim ``MathTex`` color maps).
|
|
1177
|
+
tags : list[str]
|
|
1178
|
+
Topic tags, e.g. ``["distribution", "continuous", "normal"]``.
|
|
1179
|
+
"""
|
|
1180
|
+
|
|
1181
|
+
name: str
|
|
1182
|
+
raw: str
|
|
1183
|
+
description: str = ""
|
|
1184
|
+
parts: Dict[str, str] = field(default_factory=dict)
|
|
1185
|
+
steps: List["TexDerivationStep"] = field(default_factory=list)
|
|
1186
|
+
color_map: Dict[str, str] = field(default_factory=dict)
|
|
1187
|
+
tags: List[str] = field(default_factory=list)
|
|
1188
|
+
|
|
1189
|
+
# ------------------------------------------------------------------
|
|
1190
|
+
# Convenience accessors
|
|
1191
|
+
# ------------------------------------------------------------------
|
|
1192
|
+
|
|
1193
|
+
@property
|
|
1194
|
+
def display(self) -> str:
|
|
1195
|
+
"""Return $$…$$ display math."""
|
|
1196
|
+
return Env.display(self.raw)
|
|
1197
|
+
|
|
1198
|
+
@property
|
|
1199
|
+
def inline(self) -> str:
|
|
1200
|
+
"""Return $…$ inline math."""
|
|
1201
|
+
return Env.inline(self.raw)
|
|
1202
|
+
|
|
1203
|
+
@property
|
|
1204
|
+
def aligned(self) -> str:
|
|
1205
|
+
"""
|
|
1206
|
+
Return the aligned multi-line environment if steps are defined,
|
|
1207
|
+
otherwise fall back to the plain display form.
|
|
1208
|
+
"""
|
|
1209
|
+
if not self.steps:
|
|
1210
|
+
return self.display
|
|
1211
|
+
rows = [(s.lhs, s.rhs) for s in self.steps]
|
|
1212
|
+
return Env.display(Env.aligned(rows))
|
|
1213
|
+
|
|
1214
|
+
def part(self, name: str) -> str:
|
|
1215
|
+
"""
|
|
1216
|
+
Retrieve a named sub-expression.
|
|
1217
|
+
Raises ``KeyError`` with a helpful message if not found.
|
|
1218
|
+
"""
|
|
1219
|
+
if name not in self.parts:
|
|
1220
|
+
raise KeyError(
|
|
1221
|
+
f"Part {name!r} not in formula {self.name!r}. "
|
|
1222
|
+
f"Available: {list(self.parts)}"
|
|
1223
|
+
)
|
|
1224
|
+
return self.parts[name]
|
|
1225
|
+
|
|
1226
|
+
# ------------------------------------------------------------------
|
|
1227
|
+
# Annotation helpers (return new TexFormula with modified raw)
|
|
1228
|
+
# ------------------------------------------------------------------
|
|
1229
|
+
|
|
1230
|
+
def highlight_part(
|
|
1231
|
+
self,
|
|
1232
|
+
part_name: str,
|
|
1233
|
+
color: str = "red",
|
|
1234
|
+
) -> "TexFormula":
|
|
1235
|
+
"""
|
|
1236
|
+
Return a new TexFormula where ``part_name`` is wrapped in
|
|
1237
|
+
``\\textcolor{color}{…}``.
|
|
1238
|
+
|
|
1239
|
+
This modifies ``.raw`` directly, producing a formula string
|
|
1240
|
+
that renders the named part in the requested color.
|
|
1241
|
+
"""
|
|
1242
|
+
sub = self.part(part_name)
|
|
1243
|
+
colored = rf"\textcolor{{{color}}}{{{sub}}}"
|
|
1244
|
+
new_raw = self.raw.replace(sub, colored, 1)
|
|
1245
|
+
return TexFormula(
|
|
1246
|
+
name=self.name + f"_hl_{part_name}",
|
|
1247
|
+
raw=new_raw,
|
|
1248
|
+
description=self.description,
|
|
1249
|
+
parts=self.parts,
|
|
1250
|
+
steps=self.steps,
|
|
1251
|
+
color_map={**self.color_map, part_name: color},
|
|
1252
|
+
tags=self.tags,
|
|
1253
|
+
)
|
|
1254
|
+
|
|
1255
|
+
def with_substitution(self, **subs: str) -> "TexFormula":
|
|
1256
|
+
"""
|
|
1257
|
+
Return a new TexFormula with parameter substitutions applied.
|
|
1258
|
+
|
|
1259
|
+
Example::
|
|
1260
|
+
|
|
1261
|
+
f = FORMULAS["normal_pdf"]
|
|
1262
|
+
f2 = f.with_substitution(mu="0", sigma="1")
|
|
1263
|
+
|
|
1264
|
+
Replaces literal occurrences of Greek symbols / parameter names
|
|
1265
|
+
in ``.raw``.
|
|
1266
|
+
"""
|
|
1267
|
+
new_raw = self.raw
|
|
1268
|
+
new_parts = dict(self.parts)
|
|
1269
|
+
for param, value in subs.items():
|
|
1270
|
+
# Build a regex that replaces \\mu, \\sigma, etc.
|
|
1271
|
+
# as whole tokens to avoid partial replacements.
|
|
1272
|
+
latex_param = "\\" + param if not param.startswith("\\") else param
|
|
1273
|
+
new_raw = new_raw.replace(latex_param, value)
|
|
1274
|
+
new_parts = {k: v.replace(latex_param, value) for k, v in new_parts.items()}
|
|
1275
|
+
return TexFormula(
|
|
1276
|
+
name=self.name + "_sub",
|
|
1277
|
+
raw=new_raw,
|
|
1278
|
+
description=self.description + " (substituted)",
|
|
1279
|
+
parts=new_parts,
|
|
1280
|
+
steps=self.steps,
|
|
1281
|
+
color_map=self.color_map,
|
|
1282
|
+
tags=self.tags,
|
|
1283
|
+
)
|
|
1284
|
+
|
|
1285
|
+
# ------------------------------------------------------------------
|
|
1286
|
+
# Manim integration
|
|
1287
|
+
# ------------------------------------------------------------------
|
|
1288
|
+
|
|
1289
|
+
def to_mathtex(
|
|
1290
|
+
self,
|
|
1291
|
+
color_map: Optional[Dict[str, Any]] = None,
|
|
1292
|
+
font_size: int = 36,
|
|
1293
|
+
**kwargs,
|
|
1294
|
+
) -> "MathTex":
|
|
1295
|
+
"""
|
|
1296
|
+
Build a Manim ``MathTex`` mobject from this formula.
|
|
1297
|
+
|
|
1298
|
+
Parameters
|
|
1299
|
+
----------
|
|
1300
|
+
color_map : dict, optional
|
|
1301
|
+
Mapping of LaTeX sub-string → Manim color. If not given,
|
|
1302
|
+
uses ``self.color_map`` (which stores color names as strings,
|
|
1303
|
+
resolved by Manim).
|
|
1304
|
+
font_size : int
|
|
1305
|
+
Font size passed to MathTex.
|
|
1306
|
+
**kwargs
|
|
1307
|
+
Additional keyword arguments forwarded to ``MathTex()``.
|
|
1308
|
+
"""
|
|
1309
|
+
if not _MANIM_AVAILABLE:
|
|
1310
|
+
raise ImportError("Manim is not installed.")
|
|
1311
|
+
cmap = color_map or {}
|
|
1312
|
+
return MathTex(self.raw, font_size=font_size, **kwargs)
|
|
1313
|
+
|
|
1314
|
+
def to_tex(self, font_size: int = 32, **kwargs) -> "Tex":
|
|
1315
|
+
"""Build a Manim ``Tex`` mobject (for display-mode rendering)."""
|
|
1316
|
+
if not _MANIM_AVAILABLE:
|
|
1317
|
+
raise ImportError("Manim is not installed.")
|
|
1318
|
+
return Tex(self.display, font_size=font_size, **kwargs)
|
|
1319
|
+
|
|
1320
|
+
def to_aligned_mathtex(self, font_size: int = 30, **kwargs) -> "MathTex":
|
|
1321
|
+
"""Build a Manim MathTex from the aligned multi-step derivation."""
|
|
1322
|
+
if not _MANIM_AVAILABLE:
|
|
1323
|
+
raise ImportError("Manim is not installed.")
|
|
1324
|
+
if not self.steps:
|
|
1325
|
+
return self.to_mathtex(font_size=font_size, **kwargs)
|
|
1326
|
+
rows = [(s.lhs, s.rhs) for s in self.steps]
|
|
1327
|
+
aligned_src = Env.aligned(rows)
|
|
1328
|
+
return MathTex(aligned_src, font_size=font_size, **kwargs)
|
|
1329
|
+
|
|
1330
|
+
def __repr__(self) -> str:
|
|
1331
|
+
return f"TexFormula({self.name!r})"
|
|
1332
|
+
|
|
1333
|
+
def __str__(self) -> str:
|
|
1334
|
+
return self.raw
|
|
1335
|
+
|
|
1336
|
+
|
|
1337
|
+
@dataclass
|
|
1338
|
+
class TexDerivationStep:
|
|
1339
|
+
"""
|
|
1340
|
+
One step in a multi-line derivation.
|
|
1341
|
+
|
|
1342
|
+
Attributes
|
|
1343
|
+
----------
|
|
1344
|
+
lhs : str
|
|
1345
|
+
Left-hand side LaTeX (may be empty for continuation lines).
|
|
1346
|
+
rhs : str
|
|
1347
|
+
Right-hand side LaTeX.
|
|
1348
|
+
annotation : str
|
|
1349
|
+
Short justification shown above / beside the step (e.g. "expand square").
|
|
1350
|
+
"""
|
|
1351
|
+
lhs: str
|
|
1352
|
+
rhs: str
|
|
1353
|
+
annotation: str = ""
|
|
1354
|
+
|
|
1355
|
+
def as_row(self) -> Tuple[str, str]:
|
|
1356
|
+
return (self.lhs, self.rhs)
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
# ===========================================================================
|
|
1360
|
+
# LAYER D — Annotation helpers
|
|
1361
|
+
# Functions that wrap raw LaTeX in annotation macros.
|
|
1362
|
+
# ===========================================================================
|
|
1363
|
+
|
|
1364
|
+
def overbrace(expr: str, label: str) -> str:
|
|
1365
|
+
"""Annotate *expr* with an overbrace labelled *label*."""
|
|
1366
|
+
return rf"\overbrace{{{expr}}}^{{\text{{{label}}}}}"
|
|
1367
|
+
|
|
1368
|
+
|
|
1369
|
+
def underbrace(expr: str, label: str) -> str:
|
|
1370
|
+
"""Annotate *expr* with an underbrace labelled *label*."""
|
|
1371
|
+
return rf"\underbrace{{{expr}}}_{{\text{{{label}}}}}"
|
|
1372
|
+
|
|
1373
|
+
|
|
1374
|
+
def boxed(expr: str) -> str:
|
|
1375
|
+
"""Draw a box around *expr*."""
|
|
1376
|
+
return rf"\boxed{{{expr}}}"
|
|
1377
|
+
|
|
1378
|
+
|
|
1379
|
+
def color(expr: str, latex_color: str) -> str:
|
|
1380
|
+
"""Wrap *expr* in ``\\textcolor{color}{…}``."""
|
|
1381
|
+
return rf"\textcolor{{{latex_color}}}{{{expr}}}"
|
|
1382
|
+
|
|
1383
|
+
|
|
1384
|
+
def cancel(expr: str) -> str:
|
|
1385
|
+
"""Strike through *expr* (requires cancel package)."""
|
|
1386
|
+
return rf"\cancel{{{expr}}}"
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def phantom(expr: str) -> str:
|
|
1390
|
+
"""Invisible placeholder with the same size as *expr*."""
|
|
1391
|
+
return rf"\phantom{{{expr}}}"
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
def annotate_below(expr: str, annotation: str) -> str:
|
|
1395
|
+
"""
|
|
1396
|
+
Place *annotation* as a small text directly below *expr*
|
|
1397
|
+
using a strut for alignment.
|
|
1398
|
+
"""
|
|
1399
|
+
return rf"\underset{{\scriptscriptstyle {annotation}}}{{{expr}}}"
|
|
1400
|
+
|
|
1401
|
+
|
|
1402
|
+
def annotate_above(expr: str, annotation: str) -> str:
|
|
1403
|
+
return rf"\overset{{\scriptscriptstyle {annotation}}}{{{expr}}}"
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
def step_annotation(
|
|
1407
|
+
step_number: int,
|
|
1408
|
+
expr: str,
|
|
1409
|
+
label: str,
|
|
1410
|
+
) -> str:
|
|
1411
|
+
"""
|
|
1412
|
+
Format one derivation step as a labeled equation number.
|
|
1413
|
+
|
|
1414
|
+
Example output::
|
|
1415
|
+
|
|
1416
|
+
f(x) = \\ldots \\tag{2: expand kernel}
|
|
1417
|
+
"""
|
|
1418
|
+
return rf"{expr} \tag{{{step_number}:\ \text{{{label}}}}}"
|
|
1419
|
+
|
|
1420
|
+
|
|
1421
|
+
def highlight_parts(
|
|
1422
|
+
raw: str,
|
|
1423
|
+
highlights: Dict[str, str],
|
|
1424
|
+
) -> str:
|
|
1425
|
+
"""
|
|
1426
|
+
Given a raw LaTeX string and a mapping of substring → color name,
|
|
1427
|
+
replace each substring with its colorized version.
|
|
1428
|
+
|
|
1429
|
+
Parameters
|
|
1430
|
+
----------
|
|
1431
|
+
raw : str
|
|
1432
|
+
The original LaTeX formula.
|
|
1433
|
+
highlights : dict
|
|
1434
|
+
Mapping of LaTeX substring → LaTeX color name (e.g. "red").
|
|
1435
|
+
|
|
1436
|
+
Returns
|
|
1437
|
+
-------
|
|
1438
|
+
str
|
|
1439
|
+
Modified LaTeX with ``\\textcolor`` wrappings applied in order.
|
|
1440
|
+
"""
|
|
1441
|
+
result = raw
|
|
1442
|
+
for sub, col in highlights.items():
|
|
1443
|
+
result = result.replace(sub, color(sub, col), 1)
|
|
1444
|
+
return result
|
|
1445
|
+
|
|
1446
|
+
|
|
1447
|
+
# ===========================================================================
|
|
1448
|
+
# LAYER E — Manim animation helpers
|
|
1449
|
+
# Thin wrappers that return Manim Animation objects.
|
|
1450
|
+
# All raise ImportError if Manim is not installed.
|
|
1451
|
+
# ===========================================================================
|
|
1452
|
+
|
|
1453
|
+
def write_formula(
|
|
1454
|
+
formula: TexFormula,
|
|
1455
|
+
run_time: float = 2.0,
|
|
1456
|
+
**mathtex_kwargs,
|
|
1457
|
+
):
|
|
1458
|
+
"""
|
|
1459
|
+
Return a Manim ``Write`` animation for the given formula.
|
|
1460
|
+
|
|
1461
|
+
Example
|
|
1462
|
+
-------
|
|
1463
|
+
self.play(write_formula(FORMULAS["normal_pdf"]))
|
|
1464
|
+
"""
|
|
1465
|
+
if not _MANIM_AVAILABLE:
|
|
1466
|
+
raise ImportError("Manim is not installed.")
|
|
1467
|
+
from manim import Write # type: ignore
|
|
1468
|
+
mob = formula.to_mathtex(**mathtex_kwargs)
|
|
1469
|
+
return Write(mob, run_time=run_time)
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
def transform_formula(
|
|
1473
|
+
source: TexFormula,
|
|
1474
|
+
target: TexFormula,
|
|
1475
|
+
run_time: float = 1.5,
|
|
1476
|
+
**mathtex_kwargs,
|
|
1477
|
+
):
|
|
1478
|
+
"""
|
|
1479
|
+
Return a Manim ``TransformMatchingTex`` animation that morphs
|
|
1480
|
+
*source* formula into *target* formula.
|
|
1481
|
+
|
|
1482
|
+
This is useful for derivation steps where identical sub-expressions
|
|
1483
|
+
should stay in place while only the changed parts animate.
|
|
1484
|
+
"""
|
|
1485
|
+
if not _MANIM_AVAILABLE:
|
|
1486
|
+
raise ImportError("Manim is not installed.")
|
|
1487
|
+
from manim import TransformMatchingTex # type: ignore
|
|
1488
|
+
src_mob = source.to_mathtex(**mathtex_kwargs)
|
|
1489
|
+
tgt_mob = target.to_mathtex(**mathtex_kwargs)
|
|
1490
|
+
return src_mob, tgt_mob, TransformMatchingTex(src_mob, tgt_mob, run_time=run_time)
|
|
1491
|
+
|
|
1492
|
+
|
|
1493
|
+
def derive_formula(
|
|
1494
|
+
formula: TexFormula,
|
|
1495
|
+
scene,
|
|
1496
|
+
position=None,
|
|
1497
|
+
step_run_time: float = 1.2,
|
|
1498
|
+
wait_time: float = 0.8,
|
|
1499
|
+
**mathtex_kwargs,
|
|
1500
|
+
) -> None:
|
|
1501
|
+
"""
|
|
1502
|
+
Animate a full step-by-step derivation of *formula* on a Manim *scene*.
|
|
1503
|
+
|
|
1504
|
+
Each ``TexDerivationStep`` in ``formula.steps`` is played as a
|
|
1505
|
+
``TransformMatchingTex`` from the previous expression. An optional
|
|
1506
|
+
annotation text is faded in above the arrow.
|
|
1507
|
+
|
|
1508
|
+
Parameters
|
|
1509
|
+
----------
|
|
1510
|
+
formula : TexFormula
|
|
1511
|
+
Must have at least one derivation step.
|
|
1512
|
+
scene : manim.Scene
|
|
1513
|
+
The Manim scene to play the animations on.
|
|
1514
|
+
position : manim vector, optional
|
|
1515
|
+
Where to place the first formula on screen.
|
|
1516
|
+
step_run_time : float
|
|
1517
|
+
Duration of each step transition.
|
|
1518
|
+
wait_time : float
|
|
1519
|
+
Pause between steps.
|
|
1520
|
+
"""
|
|
1521
|
+
if not _MANIM_AVAILABLE:
|
|
1522
|
+
raise ImportError("Manim is not installed.")
|
|
1523
|
+
from manim import Write, TransformMatchingTex, FadeIn, FadeOut, Text, ORIGIN # type: ignore
|
|
1524
|
+
|
|
1525
|
+
if not formula.steps:
|
|
1526
|
+
mob = formula.to_mathtex(**mathtex_kwargs)
|
|
1527
|
+
if position is not None:
|
|
1528
|
+
mob.move_to(position)
|
|
1529
|
+
scene.play(Write(mob))
|
|
1530
|
+
return
|
|
1531
|
+
|
|
1532
|
+
steps = formula.steps
|
|
1533
|
+
current_raw = steps[0].rhs
|
|
1534
|
+
current_mob = MathTex(current_raw, **mathtex_kwargs)
|
|
1535
|
+
if position is not None:
|
|
1536
|
+
current_mob.move_to(position)
|
|
1537
|
+
else:
|
|
1538
|
+
current_mob.move_to(ORIGIN)
|
|
1539
|
+
scene.play(Write(current_mob, run_time=step_run_time))
|
|
1540
|
+
scene.wait(wait_time)
|
|
1541
|
+
|
|
1542
|
+
for step in steps[1:]:
|
|
1543
|
+
next_raw = step.rhs
|
|
1544
|
+
next_mob = MathTex(next_raw, **mathtex_kwargs)
|
|
1545
|
+
next_mob.move_to(current_mob)
|
|
1546
|
+
annotation_mob = None
|
|
1547
|
+
if step.annotation:
|
|
1548
|
+
annotation_mob = Text(
|
|
1549
|
+
step.annotation,
|
|
1550
|
+
font_size=20,
|
|
1551
|
+
).next_to(current_mob, direction=[0, 1.2, 0])
|
|
1552
|
+
scene.play(FadeIn(annotation_mob, run_time=0.4))
|
|
1553
|
+
scene.play(
|
|
1554
|
+
TransformMatchingTex(current_mob, next_mob, run_time=step_run_time)
|
|
1555
|
+
)
|
|
1556
|
+
if annotation_mob:
|
|
1557
|
+
scene.play(FadeOut(annotation_mob, run_time=0.3))
|
|
1558
|
+
scene.wait(wait_time)
|
|
1559
|
+
current_mob = next_mob
|
|
1560
|
+
|
|
1561
|
+
|
|
1562
|
+
def highlight_subformula(
|
|
1563
|
+
mob,
|
|
1564
|
+
substring: str,
|
|
1565
|
+
highlight_color,
|
|
1566
|
+
scene,
|
|
1567
|
+
run_time: float = 0.6,
|
|
1568
|
+
):
|
|
1569
|
+
"""
|
|
1570
|
+
Highlight a substring of an existing Manim ``MathTex`` *mob* by
|
|
1571
|
+
using ``Indicate`` on the matched sub-mobject.
|
|
1572
|
+
|
|
1573
|
+
Parameters
|
|
1574
|
+
----------
|
|
1575
|
+
mob : MathTex
|
|
1576
|
+
The already-displayed MathTex mobject.
|
|
1577
|
+
substring : str
|
|
1578
|
+
LaTeX substring to locate within *mob*.
|
|
1579
|
+
highlight_color : ManimColor
|
|
1580
|
+
Color to flash.
|
|
1581
|
+
scene : manim.Scene
|
|
1582
|
+
run_time : float
|
|
1583
|
+
"""
|
|
1584
|
+
if not _MANIM_AVAILABLE:
|
|
1585
|
+
raise ImportError("Manim is not installed.")
|
|
1586
|
+
from manim import Indicate # type: ignore
|
|
1587
|
+
parts = mob.get_parts_by_tex(substring)
|
|
1588
|
+
if parts:
|
|
1589
|
+
scene.play(Indicate(parts, color=highlight_color, run_time=run_time))
|
|
1590
|
+
|
|
1591
|
+
|
|
1592
|
+
# ===========================================================================
|
|
1593
|
+
# LAYER F — Formula registry and catalog
|
|
1594
|
+
# ===========================================================================
|
|
1595
|
+
|
|
1596
|
+
def _build_normal_pdf_formula() -> TexFormula:
|
|
1597
|
+
"""Build the normal PDF TexFormula with named parts and derivation steps."""
|
|
1598
|
+
norm_const = _frac("1", r"\sigma\sqrt{2\pi}")
|
|
1599
|
+
exponent = _frac(r"-(x - \mu)^2", r"2\sigma^2")
|
|
1600
|
+
kernel = _exp(exponent)
|
|
1601
|
+
raw = rf"f(x \mid \mu,\, \sigma^2) = {norm_const} {kernel}"
|
|
1602
|
+
return TexFormula(
|
|
1603
|
+
name = "normal_pdf",
|
|
1604
|
+
raw = raw,
|
|
1605
|
+
description = "Normal (Gaussian) probability density function",
|
|
1606
|
+
parts = {
|
|
1607
|
+
"full_lhs": rf"f(x \mid \mu,\, \sigma^2)",
|
|
1608
|
+
"normalising": norm_const,
|
|
1609
|
+
"kernel": kernel,
|
|
1610
|
+
"exponent": exponent,
|
|
1611
|
+
"sigma_sq_denom": r"2\sigma^2",
|
|
1612
|
+
},
|
|
1613
|
+
steps = [
|
|
1614
|
+
TexDerivationStep(
|
|
1615
|
+
lhs="f(x)",
|
|
1616
|
+
rhs=raw,
|
|
1617
|
+
annotation="Normal PDF definition",
|
|
1618
|
+
),
|
|
1619
|
+
TexDerivationStep(
|
|
1620
|
+
lhs="",
|
|
1621
|
+
rhs=rf"= {norm_const} \exp\!\left({exponent}\right)",
|
|
1622
|
+
annotation="Explicit exp notation",
|
|
1623
|
+
),
|
|
1624
|
+
TexDerivationStep(
|
|
1625
|
+
lhs=r"\text{standard normal: } \mu=0,\, \sigma=1",
|
|
1626
|
+
rhs=rf"\phi(x) = {_frac('1', r'\sqrt{2\pi}')} e^{{-x^2/2}}",
|
|
1627
|
+
annotation="Substitute μ=0, σ=1",
|
|
1628
|
+
),
|
|
1629
|
+
],
|
|
1630
|
+
tags = ["distribution", "continuous", "normal", "gaussian"],
|
|
1631
|
+
)
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
def _build_bayes_formula() -> TexFormula:
|
|
1635
|
+
likelihood = r"P(B \mid A)"
|
|
1636
|
+
prior = r"P(A)"
|
|
1637
|
+
evidence = r"P(B)"
|
|
1638
|
+
posterior = r"P(A \mid B)"
|
|
1639
|
+
raw = (
|
|
1640
|
+
rf"{posterior} = "
|
|
1641
|
+
rf"{_frac(likelihood + r' \cdot ' + prior, evidence)}"
|
|
1642
|
+
)
|
|
1643
|
+
return TexFormula(
|
|
1644
|
+
name = "bayes_theorem",
|
|
1645
|
+
raw = raw,
|
|
1646
|
+
description = "Bayes' theorem",
|
|
1647
|
+
parts = {
|
|
1648
|
+
"posterior": posterior,
|
|
1649
|
+
"likelihood": likelihood,
|
|
1650
|
+
"prior": prior,
|
|
1651
|
+
"evidence": evidence,
|
|
1652
|
+
"numerator": likelihood + r" \cdot " + prior,
|
|
1653
|
+
},
|
|
1654
|
+
steps = [
|
|
1655
|
+
TexDerivationStep(
|
|
1656
|
+
lhs="P(A \\cap B)",
|
|
1657
|
+
rhs=r"P(A \mid B) \cdot P(B) = P(B \mid A) \cdot P(A)",
|
|
1658
|
+
annotation="Multiplication rule (both sides)",
|
|
1659
|
+
),
|
|
1660
|
+
TexDerivationStep(
|
|
1661
|
+
lhs="P(A \\mid B)",
|
|
1662
|
+
rhs=_frac(r"P(B \mid A) \cdot P(A)", r"P(B)"),
|
|
1663
|
+
annotation="Divide both sides by P(B)",
|
|
1664
|
+
),
|
|
1665
|
+
],
|
|
1666
|
+
tags = ["probability", "bayes", "inference"],
|
|
1667
|
+
)
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
def _build_clt_formula() -> TexFormula:
|
|
1671
|
+
raw = (
|
|
1672
|
+
rf"\sqrt{{n}}\left(\bar{{X}}_n - \mu\right) "
|
|
1673
|
+
rf"\xrightarrow{{d}} \mathcal{{N}}\left(0,\, \sigma^2\right)"
|
|
1674
|
+
)
|
|
1675
|
+
return TexFormula(
|
|
1676
|
+
name = "clt",
|
|
1677
|
+
raw = raw,
|
|
1678
|
+
description = "Central Limit Theorem (convergence in distribution)",
|
|
1679
|
+
parts = {
|
|
1680
|
+
"standardized_mean": r"\sqrt{n}\left(\bar{X}_n - \mu\right)",
|
|
1681
|
+
"limit_dist": r"\mathcal{N}\left(0,\, \sigma^2\right)",
|
|
1682
|
+
},
|
|
1683
|
+
steps = [
|
|
1684
|
+
TexDerivationStep(
|
|
1685
|
+
lhs=r"\bar{X}_n",
|
|
1686
|
+
rhs=r"\frac{1}{n}\sum_{i=1}^n X_i, \quad X_i \overset{\text{iid}}{\sim} F(\mu, \sigma^2)",
|
|
1687
|
+
annotation="Definition of sample mean",
|
|
1688
|
+
),
|
|
1689
|
+
TexDerivationStep(
|
|
1690
|
+
lhs=r"\sqrt{n}(\bar{X}_n - \mu)",
|
|
1691
|
+
rhs=r"\frac{1}{\sqrt{n}} \sum_{i=1}^n (X_i - \mu)",
|
|
1692
|
+
annotation="Rearrange",
|
|
1693
|
+
),
|
|
1694
|
+
TexDerivationStep(
|
|
1695
|
+
lhs=r"\xrightarrow{d}",
|
|
1696
|
+
rhs=r"\mathcal{N}(0, \sigma^2)",
|
|
1697
|
+
annotation="By CLT as n → ∞",
|
|
1698
|
+
),
|
|
1699
|
+
],
|
|
1700
|
+
tags = ["sampling", "clt", "normal", "limit_theorem"],
|
|
1701
|
+
)
|
|
1702
|
+
|
|
1703
|
+
|
|
1704
|
+
def _build_mle_formula() -> TexFormula:
|
|
1705
|
+
raw = (
|
|
1706
|
+
r"\hat{\theta}_{\mathrm{MLE}} = "
|
|
1707
|
+
r"\arg\max_{\theta}\, "
|
|
1708
|
+
r"\sum_{i=1}^{n} \ln f(x_i \mid \theta)"
|
|
1709
|
+
)
|
|
1710
|
+
return TexFormula(
|
|
1711
|
+
name = "mle",
|
|
1712
|
+
raw = raw,
|
|
1713
|
+
description = "Maximum Likelihood Estimator (log-likelihood form)",
|
|
1714
|
+
parts = {
|
|
1715
|
+
"estimator": r"\hat{\theta}_{\mathrm{MLE}}",
|
|
1716
|
+
"log_likelihood": r"\sum_{i=1}^{n} \ln f(x_i \mid \theta)",
|
|
1717
|
+
},
|
|
1718
|
+
steps = [
|
|
1719
|
+
TexDerivationStep(
|
|
1720
|
+
lhs="L(\\theta)",
|
|
1721
|
+
rhs=r"\prod_{i=1}^{n} f(x_i \mid \theta)",
|
|
1722
|
+
annotation="Likelihood (iid assumption)",
|
|
1723
|
+
),
|
|
1724
|
+
TexDerivationStep(
|
|
1725
|
+
lhs="\\ell(\\theta)",
|
|
1726
|
+
rhs=r"\sum_{i=1}^{n} \ln f(x_i \mid \theta)",
|
|
1727
|
+
annotation="Log-likelihood (monotone transform)",
|
|
1728
|
+
),
|
|
1729
|
+
TexDerivationStep(
|
|
1730
|
+
lhs=r"\hat{\theta}",
|
|
1731
|
+
rhs=r"\arg\max_{\theta}\, \ell(\theta)",
|
|
1732
|
+
annotation="Maximise log-likelihood",
|
|
1733
|
+
),
|
|
1734
|
+
],
|
|
1735
|
+
tags = ["estimation", "mle", "likelihood"],
|
|
1736
|
+
)
|
|
1737
|
+
|
|
1738
|
+
|
|
1739
|
+
def _build_ols_formula() -> TexFormula:
|
|
1740
|
+
raw = (
|
|
1741
|
+
r"\hat{\boldsymbol{\beta}} = "
|
|
1742
|
+
r"\left(\mathbf{X}^\top \mathbf{X}\right)^{-1} "
|
|
1743
|
+
r"\mathbf{X}^\top \mathbf{y}"
|
|
1744
|
+
)
|
|
1745
|
+
return TexFormula(
|
|
1746
|
+
name = "ols",
|
|
1747
|
+
raw = raw,
|
|
1748
|
+
description = "Ordinary Least Squares estimator (matrix form)",
|
|
1749
|
+
parts = {
|
|
1750
|
+
"beta_hat": r"\hat{\boldsymbol{\beta}}",
|
|
1751
|
+
"gram_matrix": r"\mathbf{X}^\top \mathbf{X}",
|
|
1752
|
+
"projection": r"\mathbf{X}^\top \mathbf{y}",
|
|
1753
|
+
},
|
|
1754
|
+
steps = [
|
|
1755
|
+
TexDerivationStep(
|
|
1756
|
+
lhs=r"\mathrm{RSS}(\beta)",
|
|
1757
|
+
rhs=r"(\mathbf{y} - \mathbf{X}\boldsymbol{\beta})^\top (\mathbf{y} - \mathbf{X}\boldsymbol{\beta})",
|
|
1758
|
+
annotation="Residual sum of squares",
|
|
1759
|
+
),
|
|
1760
|
+
TexDerivationStep(
|
|
1761
|
+
lhs=r"\frac{\partial \mathrm{RSS}}{\partial \boldsymbol{\beta}}",
|
|
1762
|
+
rhs=r"-2\mathbf{X}^\top(\mathbf{y} - \mathbf{X}\boldsymbol{\beta}) = \mathbf{0}",
|
|
1763
|
+
annotation="Set gradient to zero",
|
|
1764
|
+
),
|
|
1765
|
+
TexDerivationStep(
|
|
1766
|
+
lhs=r"\hat{\boldsymbol{\beta}}",
|
|
1767
|
+
rhs=raw.split("=", 1)[1].strip(),
|
|
1768
|
+
annotation="Solve for β-hat",
|
|
1769
|
+
),
|
|
1770
|
+
],
|
|
1771
|
+
tags = ["regression", "ols", "estimation"],
|
|
1772
|
+
)
|
|
1773
|
+
|
|
1774
|
+
|
|
1775
|
+
def _build_entropy_formula() -> TexFormula:
|
|
1776
|
+
raw = r"H(X) = -\sum_{x \in \mathcal{X}} p(x) \log_2 p(x)"
|
|
1777
|
+
return TexFormula(
|
|
1778
|
+
name = "entropy_discrete",
|
|
1779
|
+
raw = raw,
|
|
1780
|
+
description = "Shannon entropy of a discrete random variable",
|
|
1781
|
+
parts = {
|
|
1782
|
+
"entropy": "H(X)",
|
|
1783
|
+
"sum_term": r"\sum_{x \in \mathcal{X}} p(x) \log_2 p(x)",
|
|
1784
|
+
},
|
|
1785
|
+
steps = [
|
|
1786
|
+
TexDerivationStep(
|
|
1787
|
+
lhs="H(X)",
|
|
1788
|
+
rhs=r"\sum_{x} p(x) \cdot \left(-\log_2 p(x)\right)",
|
|
1789
|
+
annotation="Expected surprise / self-information",
|
|
1790
|
+
),
|
|
1791
|
+
TexDerivationStep(
|
|
1792
|
+
lhs="",
|
|
1793
|
+
rhs=raw.split("=", 1)[1].strip(),
|
|
1794
|
+
annotation="Compact form",
|
|
1795
|
+
),
|
|
1796
|
+
],
|
|
1797
|
+
tags = ["information_theory", "entropy", "discrete"],
|
|
1798
|
+
)
|
|
1799
|
+
|
|
1800
|
+
|
|
1801
|
+
def _build_kl_formula() -> TexFormula:
|
|
1802
|
+
raw = (
|
|
1803
|
+
r"D_{\mathrm{KL}}(P \| Q) = "
|
|
1804
|
+
r"\sum_{x} p(x) \ln \frac{p(x)}{q(x)}"
|
|
1805
|
+
)
|
|
1806
|
+
return TexFormula(
|
|
1807
|
+
name = "kl_divergence",
|
|
1808
|
+
raw = raw,
|
|
1809
|
+
description = "Kullback–Leibler divergence from Q to P",
|
|
1810
|
+
parts = {
|
|
1811
|
+
"kl": r"D_{\mathrm{KL}}(P \| Q)",
|
|
1812
|
+
"log_ratio": r"\ln \frac{p(x)}{q(x)}",
|
|
1813
|
+
},
|
|
1814
|
+
tags = ["information_theory", "kl_divergence"],
|
|
1815
|
+
)
|
|
1816
|
+
|
|
1817
|
+
|
|
1818
|
+
#: Global formula catalog. Keys are formula names; values are TexFormula objects.
|
|
1819
|
+
FORMULAS: Dict[str, TexFormula] = {
|
|
1820
|
+
"normal_pdf": _build_normal_pdf_formula(),
|
|
1821
|
+
"standard_normal": TexFormula(
|
|
1822
|
+
name="standard_normal",
|
|
1823
|
+
raw=pdf_standard_normal(),
|
|
1824
|
+
description="Standard normal PDF φ(x)",
|
|
1825
|
+
tags=["distribution", "continuous", "normal"],
|
|
1826
|
+
),
|
|
1827
|
+
"normal_cdf": TexFormula(
|
|
1828
|
+
name="normal_cdf",
|
|
1829
|
+
raw=cdf_standard_normal(),
|
|
1830
|
+
description="Standard normal CDF Φ(x)",
|
|
1831
|
+
tags=["distribution", "continuous", "normal", "cdf"],
|
|
1832
|
+
),
|
|
1833
|
+
"exponential_pdf": TexFormula(
|
|
1834
|
+
name="exponential_pdf",
|
|
1835
|
+
raw=pdf_exponential(),
|
|
1836
|
+
description="Exponential PDF",
|
|
1837
|
+
tags=["distribution", "continuous", "exponential"],
|
|
1838
|
+
),
|
|
1839
|
+
"gamma_pdf": TexFormula(
|
|
1840
|
+
name="gamma_pdf",
|
|
1841
|
+
raw=pdf_gamma(),
|
|
1842
|
+
description="Gamma PDF",
|
|
1843
|
+
tags=["distribution", "continuous", "gamma"],
|
|
1844
|
+
),
|
|
1845
|
+
"beta_pdf": TexFormula(
|
|
1846
|
+
name="beta_pdf",
|
|
1847
|
+
raw=pdf_beta(),
|
|
1848
|
+
description="Beta PDF",
|
|
1849
|
+
tags=["distribution", "continuous", "beta"],
|
|
1850
|
+
),
|
|
1851
|
+
"chi_sq_pdf": TexFormula(
|
|
1852
|
+
name="chi_sq_pdf",
|
|
1853
|
+
raw=pdf_chi_squared(),
|
|
1854
|
+
description="Chi-squared PDF",
|
|
1855
|
+
tags=["distribution", "continuous", "chi_squared"],
|
|
1856
|
+
),
|
|
1857
|
+
"student_t_pdf": TexFormula(
|
|
1858
|
+
name="student_t_pdf",
|
|
1859
|
+
raw=pdf_student_t(),
|
|
1860
|
+
description="Student t PDF",
|
|
1861
|
+
tags=["distribution", "continuous", "t_distribution"],
|
|
1862
|
+
),
|
|
1863
|
+
"binomial_pmf": TexFormula(
|
|
1864
|
+
name="binomial_pmf",
|
|
1865
|
+
raw=pmf_binomial(),
|
|
1866
|
+
description="Binomial PMF",
|
|
1867
|
+
tags=["distribution", "discrete", "binomial"],
|
|
1868
|
+
),
|
|
1869
|
+
"poisson_pmf": TexFormula(
|
|
1870
|
+
name="poisson_pmf",
|
|
1871
|
+
raw=pmf_poisson(),
|
|
1872
|
+
description="Poisson PMF",
|
|
1873
|
+
tags=["distribution", "discrete", "poisson"],
|
|
1874
|
+
),
|
|
1875
|
+
"geometric_pmf": TexFormula(
|
|
1876
|
+
name="geometric_pmf",
|
|
1877
|
+
raw=pmf_geometric(),
|
|
1878
|
+
description="Geometric PMF",
|
|
1879
|
+
tags=["distribution", "discrete", "geometric"],
|
|
1880
|
+
),
|
|
1881
|
+
"hypergeometric_pmf": TexFormula(
|
|
1882
|
+
name="hypergeometric_pmf",
|
|
1883
|
+
raw=pmf_hypergeometric(),
|
|
1884
|
+
description="Hypergeometric PMF",
|
|
1885
|
+
tags=["distribution", "discrete", "hypergeometric"],
|
|
1886
|
+
),
|
|
1887
|
+
"sample_mean": TexFormula(
|
|
1888
|
+
name="sample_mean",
|
|
1889
|
+
raw=mean(),
|
|
1890
|
+
description="Sample mean",
|
|
1891
|
+
tags=["descriptive", "mean"],
|
|
1892
|
+
),
|
|
1893
|
+
"sample_variance": TexFormula(
|
|
1894
|
+
name="sample_variance",
|
|
1895
|
+
raw=sample_variance(),
|
|
1896
|
+
description="Sample variance (unbiased)",
|
|
1897
|
+
tags=["descriptive", "variance"],
|
|
1898
|
+
),
|
|
1899
|
+
"z_score": TexFormula(
|
|
1900
|
+
name="z_score",
|
|
1901
|
+
raw=z_score(),
|
|
1902
|
+
description="Z-score (standardization)",
|
|
1903
|
+
tags=["descriptive", "standardization"],
|
|
1904
|
+
),
|
|
1905
|
+
"bayes_theorem": _build_bayes_formula(),
|
|
1906
|
+
"conditional_prob": TexFormula(
|
|
1907
|
+
name="conditional_prob",
|
|
1908
|
+
raw=conditional_probability(),
|
|
1909
|
+
description="Conditional probability definition",
|
|
1910
|
+
tags=["probability", "conditional"],
|
|
1911
|
+
),
|
|
1912
|
+
"clt": _build_clt_formula(),
|
|
1913
|
+
"mle": _build_mle_formula(),
|
|
1914
|
+
"ols": _build_ols_formula(),
|
|
1915
|
+
"ci_z": TexFormula(
|
|
1916
|
+
name="ci_z",
|
|
1917
|
+
raw=ci_mean_known_sigma(),
|
|
1918
|
+
description="Confidence interval for mean (σ known)",
|
|
1919
|
+
tags=["inference", "confidence_interval"],
|
|
1920
|
+
),
|
|
1921
|
+
"ci_t": TexFormula(
|
|
1922
|
+
name="ci_t",
|
|
1923
|
+
raw=ci_mean_unknown_sigma(),
|
|
1924
|
+
description="Confidence interval for mean (σ unknown)",
|
|
1925
|
+
tags=["inference", "confidence_interval"],
|
|
1926
|
+
),
|
|
1927
|
+
"z_test": TexFormula(
|
|
1928
|
+
name="z_test",
|
|
1929
|
+
raw=z_test_statistic(),
|
|
1930
|
+
description="Z-test statistic",
|
|
1931
|
+
tags=["inference", "hypothesis_test", "z_test"],
|
|
1932
|
+
),
|
|
1933
|
+
"t_test": TexFormula(
|
|
1934
|
+
name="t_test",
|
|
1935
|
+
raw=t_test_statistic(),
|
|
1936
|
+
description="One-sample t-test statistic",
|
|
1937
|
+
tags=["inference", "hypothesis_test", "t_test"],
|
|
1938
|
+
),
|
|
1939
|
+
"chi_sq_test": TexFormula(
|
|
1940
|
+
name="chi_sq_test",
|
|
1941
|
+
raw=chi_sq_test_statistic(),
|
|
1942
|
+
description="Chi-squared goodness-of-fit test statistic",
|
|
1943
|
+
tags=["inference", "hypothesis_test", "chi_squared"],
|
|
1944
|
+
),
|
|
1945
|
+
"pearson_r": TexFormula(
|
|
1946
|
+
name="pearson_r",
|
|
1947
|
+
raw=pearson_r(),
|
|
1948
|
+
description="Pearson correlation coefficient",
|
|
1949
|
+
tags=["regression", "correlation"],
|
|
1950
|
+
),
|
|
1951
|
+
"ols_beta1": TexFormula(
|
|
1952
|
+
name="ols_beta1",
|
|
1953
|
+
raw=ols_estimate_beta1(),
|
|
1954
|
+
description="OLS slope estimate",
|
|
1955
|
+
tags=["regression", "ols"],
|
|
1956
|
+
),
|
|
1957
|
+
"logistic": TexFormula(
|
|
1958
|
+
name="logistic",
|
|
1959
|
+
raw=logistic_regression(),
|
|
1960
|
+
description="Logistic regression probability",
|
|
1961
|
+
tags=["regression", "logistic"],
|
|
1962
|
+
),
|
|
1963
|
+
"entropy": _build_entropy_formula(),
|
|
1964
|
+
"kl_divergence": _build_kl_formula(),
|
|
1965
|
+
"mutual_info": TexFormula(
|
|
1966
|
+
name="mutual_info",
|
|
1967
|
+
raw=mutual_information(),
|
|
1968
|
+
description="Mutual information I(X;Y)",
|
|
1969
|
+
tags=["information_theory", "mutual_information"],
|
|
1970
|
+
),
|
|
1971
|
+
"fisher_info": TexFormula(
|
|
1972
|
+
name="fisher_info",
|
|
1973
|
+
raw=fisher_information(),
|
|
1974
|
+
description="Fisher information",
|
|
1975
|
+
tags=["estimation", "fisher_information"],
|
|
1976
|
+
),
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
|
|
1980
|
+
def get_formula(name: str) -> TexFormula:
|
|
1981
|
+
"""
|
|
1982
|
+
Retrieve a formula from the catalog by name.
|
|
1983
|
+
|
|
1984
|
+
Raises ``KeyError`` with available names if not found.
|
|
1985
|
+
"""
|
|
1986
|
+
if name not in FORMULAS:
|
|
1987
|
+
available = ", ".join(sorted(FORMULAS.keys()))
|
|
1988
|
+
raise KeyError(
|
|
1989
|
+
f"Formula {name!r} not found. Available:\n{available}"
|
|
1990
|
+
)
|
|
1991
|
+
return FORMULAS[name]
|
|
1992
|
+
|
|
1993
|
+
|
|
1994
|
+
def search_formulas(
|
|
1995
|
+
*tags: str,
|
|
1996
|
+
match_all: bool = False,
|
|
1997
|
+
) -> List[TexFormula]:
|
|
1998
|
+
"""
|
|
1999
|
+
Search the catalog by topic tags.
|
|
2000
|
+
|
|
2001
|
+
Parameters
|
|
2002
|
+
----------
|
|
2003
|
+
*tags : str
|
|
2004
|
+
One or more tag strings to search for.
|
|
2005
|
+
match_all : bool
|
|
2006
|
+
If True, return only formulas that carry *all* given tags.
|
|
2007
|
+
If False (default), return formulas carrying *any* of the tags.
|
|
2008
|
+
|
|
2009
|
+
Returns
|
|
2010
|
+
-------
|
|
2011
|
+
list[TexFormula]
|
|
2012
|
+
Matching formulas, sorted by name.
|
|
2013
|
+
"""
|
|
2014
|
+
tag_set = set(tags)
|
|
2015
|
+
results = []
|
|
2016
|
+
for formula in FORMULAS.values():
|
|
2017
|
+
f_tags = set(formula.tags)
|
|
2018
|
+
if match_all:
|
|
2019
|
+
if tag_set <= f_tags:
|
|
2020
|
+
results.append(formula)
|
|
2021
|
+
else:
|
|
2022
|
+
if tag_set & f_tags:
|
|
2023
|
+
results.append(formula)
|
|
2024
|
+
return sorted(results, key=lambda f: f.name)
|
|
2025
|
+
|
|
2026
|
+
|
|
2027
|
+
def register_formula(formula: TexFormula) -> None:
|
|
2028
|
+
"""
|
|
2029
|
+
Add a custom formula to the global catalog.
|
|
2030
|
+
Raises ``ValueError`` if the name is already registered.
|
|
2031
|
+
"""
|
|
2032
|
+
if formula.name in FORMULAS:
|
|
2033
|
+
raise ValueError(
|
|
2034
|
+
f"Formula {formula.name!r} is already registered. "
|
|
2035
|
+
f"Use FORMULAS[{formula.name!r}] = formula to overwrite explicitly."
|
|
2036
|
+
)
|
|
2037
|
+
FORMULAS[formula.name] = formula
|
|
2038
|
+
|
|
2039
|
+
|
|
2040
|
+
# ===========================================================================
|
|
2041
|
+
# __all__ — public API
|
|
2042
|
+
# ===========================================================================
|
|
2043
|
+
|
|
2044
|
+
__all__ = [
|
|
2045
|
+
# Layer A: atoms
|
|
2046
|
+
"Greek", "GreekUpper", "Op", "Dec", "Fence", "Space", "Env",
|
|
2047
|
+
|
|
2048
|
+
# Layer B: formula string builders — descriptive
|
|
2049
|
+
"mean", "weighted_mean", "population_variance", "sample_variance",
|
|
2050
|
+
"std_dev", "coeff_of_variation", "skewness", "kurtosis",
|
|
2051
|
+
"z_score", "percentile_rank", "iqr", "coefficient_of_determination",
|
|
2052
|
+
|
|
2053
|
+
# Layer B: formula string builders — probability
|
|
2054
|
+
"conditional_probability", "total_probability",
|
|
2055
|
+
"bayes_theorem", "bayes_proportional",
|
|
2056
|
+
"law_of_total_expectation", "law_of_total_variance",
|
|
2057
|
+
|
|
2058
|
+
# Layer B: formula string builders — discrete distributions
|
|
2059
|
+
"pmf_bernoulli", "pmf_binomial", "pmf_poisson", "pmf_geometric",
|
|
2060
|
+
"pmf_negative_binomial", "pmf_hypergeometric", "pmf_uniform_discrete",
|
|
2061
|
+
|
|
2062
|
+
# Layer B: formula string builders — continuous distributions
|
|
2063
|
+
"pdf_uniform", "pdf_normal", "pdf_standard_normal", "cdf_standard_normal",
|
|
2064
|
+
"pdf_exponential", "pdf_gamma", "pdf_beta",
|
|
2065
|
+
"pdf_chi_squared", "pdf_student_t", "pdf_f",
|
|
2066
|
+
"pdf_lognormal", "pdf_weibull", "pdf_cauchy", "pdf_pareto",
|
|
2067
|
+
"pdf_bivariate_normal",
|
|
2068
|
+
|
|
2069
|
+
# Layer B: formula string builders — moments
|
|
2070
|
+
"expected_value_discrete", "expected_value_continuous",
|
|
2071
|
+
"variance_definition", "mgf", "characteristic_function",
|
|
2072
|
+
"moment_k", "central_moment_k",
|
|
2073
|
+
|
|
2074
|
+
# Layer B: formula string builders — entropy / information
|
|
2075
|
+
"entropy_discrete", "entropy_continuous",
|
|
2076
|
+
"kl_divergence", "mutual_information", "cross_entropy",
|
|
2077
|
+
|
|
2078
|
+
# Layer B: formula string builders — inference
|
|
2079
|
+
"ci_mean_known_sigma", "ci_mean_unknown_sigma", "ci_proportion",
|
|
2080
|
+
"z_test_statistic", "t_test_statistic", "t_test_two_sample",
|
|
2081
|
+
"chi_sq_test_statistic", "f_test_statistic",
|
|
2082
|
+
"power_function", "likelihood_ratio_test",
|
|
2083
|
+
|
|
2084
|
+
# Layer B: formula string builders — regression
|
|
2085
|
+
"simple_linear_regression", "ols_estimate_beta1", "ols_estimate_beta0",
|
|
2086
|
+
"multiple_regression", "ols_matrix", "logistic_regression",
|
|
2087
|
+
"pearson_r", "spearman_rho",
|
|
2088
|
+
|
|
2089
|
+
# Layer B: formula string builders — sampling / estimation
|
|
2090
|
+
"clt_statement", "standard_error",
|
|
2091
|
+
"mle_definition", "log_likelihood", "method_of_moments", "fisher_information",
|
|
2092
|
+
|
|
2093
|
+
# Layer B: primitive helpers (public for direct use)
|
|
2094
|
+
"_frac", "_sqrt", "_exp", "_power", "_sub", "_subsup",
|
|
2095
|
+
"_integral", "_sum", "_prod", "_log", "_ln",
|
|
2096
|
+
"_conditional", "_expected", "_var", "_cov",
|
|
2097
|
+
"_indicator", "_binom_coef", "_gamma_func", "_beta_func",
|
|
2098
|
+
|
|
2099
|
+
# Layer C: dataclasses
|
|
2100
|
+
"TexFormula", "TexDerivationStep",
|
|
2101
|
+
|
|
2102
|
+
# Layer D: annotations
|
|
2103
|
+
"overbrace", "underbrace", "boxed", "color", "cancel", "phantom",
|
|
2104
|
+
"annotate_below", "annotate_above", "step_annotation", "highlight_parts",
|
|
2105
|
+
|
|
2106
|
+
# Layer E: Manim helpers
|
|
2107
|
+
"write_formula", "transform_formula", "derive_formula", "highlight_subformula",
|
|
2108
|
+
|
|
2109
|
+
# Layer F: registry
|
|
2110
|
+
"FORMULAS", "get_formula", "search_formulas", "register_formula",
|
|
2111
|
+
]
|